ÿØÿà JFIF      ÿÛ „ 	 ( %!1!%*+...983,7(-.-

# NEWS for Ruby 3.0.0

This document is a list of user visible feature changes
since the **2.7.0** release, except for bug fixes.

Note that each entry is kept so brief that no reason behind or reference
information is supplied with.  For a full list of changes with all
sufficient information, see the ChangeLog file or Redmine
(e.g. `https://bugs.ruby-lang.org/issues/$FEATURE_OR_BUG_NUMBER`).

## Language changes

* Keyword arguments are now separated from positional arguments.
  Code that resulted in deprecation warnings in Ruby 2.7 will now
  result in ArgumentError or different behavior. [[Feature #14183]]

* Procs accepting a single rest argument and keywords are no longer
  subject to autosplatting.  This now matches the behavior of Procs
  accepting a single rest argument and no keywords.
  [[Feature #16166]]

    ```ruby
    pr = proc{|*a, **kw| [a, kw]}

    pr.call([1])
    # 2.7 => [[1], {}]
    # 3.0 => [[[1]], {}]

    pr.call([1, {a: 1}])
    # 2.7 => [[1], {:a=>1}] # and deprecation warning
    # 3.0 => [[[1, {:a=>1}]], {}]
    ```

* Arguments forwarding (`...`) now supports leading arguments.
  [[Feature #16378]]

    ```ruby
    def method_missing(meth, ...)
      send(:"do_#{meth}", ...)
    end
    ```

* Pattern matching (`case/in`) is no longer experimental. [[Feature #17260]]

* One-line pattern matching is redesigned.  [EXPERIMENTAL]

    * `=>` is added. It can be used like a rightward assignment.
      [[Feature #17260]]

        ```ruby
        0 => a
        p a #=> 0

        {b: 0, c: 1} => {b:}
        p b #=> 0
        ```

    * `in` is changed to return `true` or `false`. [[Feature #17371]]

        ```ruby
        # version 3.0
        0 in 1 #=> false

        # version 2.7
        0 in 1 #=> raise NoMatchingPatternError
        ```

* Find-pattern is added.  [EXPERIMENTAL]
  [[Feature #16828]]

    ```ruby
    case ["a", 1, "b", "c", 2, "d", "e", "f", 3]
    in [*pre, String => x, String => y, *post]
      p pre  #=> ["a", 1]
      p x    #=> "b"
      p y    #=> "c"
      p post #=> [2, "d", "e", "f", 3]
    end
    ```

* Endless method definition is added.  [EXPERIMENTAL]
  [[Feature #16746]]

    ```ruby
    def square(x) = x * x
    ```

* Interpolated String literals are no longer frozen when
  `# frozen-string-literal: true` is used. [[Feature #17104]]

* Magic comment `shareable_constant_value` added to freeze constants.
  See {Magic Comments}[rdoc-ref:doc/syntax/comments.rdoc@Magic+Comments] for more details.
  [[Feature #17273]]

* A {static analysis}[rdoc-label:label-Static+analysis] foundation is
  introduced.
    * {RBS}[rdoc-label:label-RBS] is introduced. It is a type definition
      language for Ruby programs.
    * {TypeProf}[rdoc-label:label-TypeProf] is experimentally bundled. It is a
      type analysis tool for Ruby programs.

* Deprecation warnings are no longer shown by default (since Ruby 2.7.2).
  Turn them on with `-W:deprecated` (or with `-w` to show other warnings too).
  [[Feature #16345]]

* $SAFE and $KCODE are now normal global variables with no special behavior.
  C-API methods related to $SAFE have been removed.
  [[Feature #16131]] [[Feature #17136]]

* yield in singleton class definitions in methods is now a SyntaxError
  instead of a warning. yield in a class definition outside of a method
  is now a SyntaxError instead of a LocalJumpError.  [[Feature #15575]]

* When a class variable is overtaken by the same definition in an
  ancestor class/module, a RuntimeError is now raised (previously,
  it only issued a warning in verbose mode).  Additionally, accessing a
  class variable from the toplevel scope is now a RuntimeError.
  [[Bug #14541]]

* Assigning to a numbered parameter is now a SyntaxError instead of
  a warning.

## Command line options

### `--help` option

When the environment variable `RUBY_PAGER` or `PAGER` is present and has
a non-empty value, and the standard input and output are tty, the `--help`
option shows the help message via the pager designated by the value.
[[Feature #16754]]

### `--backtrace-limit` option

The `--backtrace-limit` option limits the maximum length of a backtrace.
[[Feature #8661]]

## Core classes updates

Outstanding ones only.

* Array

    * The following methods now return Array instances instead of
      subclass instances when called on subclass instances:
      [[Bug #6087]]

        * Array#drop
        * Array#drop_while
        * Array#flatten
        * Array#slice!
        * Array#slice / Array#[]
        * Array#take
        * Array#take_while
        * Array#uniq
        * Array#*

    * Can be sliced with Enumerator::ArithmeticSequence

        ```ruby
        dirty_data = ['--', 'data1', '--', 'data2', '--', 'data3']
        dirty_data[(1..).step(2)] # take each second element
        # => ["data1", "data2", "data3"]
        ```

* Binding

    * Binding#eval when called with one argument will use "(eval)"
      for `__FILE__` and 1 for `__LINE__` in the evaluated code.
      [[Bug #4352]] [[Bug #17419]]

* ConditionVariable

    * ConditionVariable#wait may now invoke the `block`/`unblock` scheduler
      hooks in a non-blocking context. [[Feature #16786]]

* Dir

    * Dir.glob and Dir.[] now sort the results by default, and
      accept the `sort:` keyword option.  [[Feature #8709]]

* ENV

    * ENV.except has been added, which returns a hash excluding the
      given keys and their values.  [[Feature #15822]]

    * Windows: Read ENV names and values as UTF-8 encoded Strings
      [[Feature #12650]]

* Encoding

    * Added new encoding IBM720.  [[Feature #16233]]

    * Changed default for Encoding.default_external to UTF-8 on Windows
      [[Feature #16604]]

* Fiber

    * Fiber.new(blocking: true/false) allows you to create non-blocking
      execution contexts. [[Feature #16786]]

    * Fiber#blocking? tells whether the fiber is non-blocking. [[Feature #16786]]

    * Fiber#backtrace and Fiber#backtrace_locations provide per-fiber backtrace.
      [[Feature #16815]]

    * The limitation of Fiber#transfer is relaxed. [[Bug #17221]]

* GC

    * GC.auto_compact= and GC.auto_compact have been added to control
      when compaction runs.  Setting `auto_compact=` to true will cause
      compaction to occur during major collections.  At the moment,
      compaction adds significant overhead to major collections, so please
      test first!  [[Feature #17176]]

* Hash

    * Hash#transform_keys and Hash#transform_keys! now accept a hash that maps
      keys to new keys.  [[Feature #16274]]

    * Hash#except has been added, which returns a hash excluding the
      given keys and their values.  [[Feature #15822]]

* IO

    * IO#nonblock? now defaults to `true`. [[Feature #16786]]

    * IO#wait_readable, IO#wait_writable, IO#read, IO#write and other
      related methods (e.g. IO#puts, IO#gets) may invoke the scheduler hook
      `#io_wait(io, events, timeout)` in a non-blocking execution context.
      [[Feature #16786]]

* Kernel

    * Kernel#clone when called with the `freeze: false` keyword will call
      `#initialize_clone` with the `freeze: false` keyword.
      [[Bug #14266]]

    * Kernel#clone when called with the `freeze: true` keyword will call
      `#initialize_clone` with the `freeze: true` keyword, and will
      return a frozen copy even if the receiver is unfrozen.
      [[Feature #16175]]

    * Kernel#eval when called with two arguments will use "(eval)"
      for `__FILE__` and 1 for `__LINE__` in the evaluated code.
      [[Bug #4352]]

    * Kernel#lambda now warns if called without a literal block.
      [[Feature #15973]]

    * Kernel.sleep invokes the scheduler hook `#kernel_sleep(...)` in a
      non-blocking execution context. [[Feature #16786]]

* Module

    * Module#include and Module#prepend now affect classes and modules
      that have already included or prepended the receiver, mirroring the
      behavior if the arguments were included in the receiver before
      the other modules and classes included or prepended the receiver.
      [[Feature #9573]]

        ```ruby
        class C; end
        module M1; end
        module M2; end
        C.include M1
        M1.include M2
        p C.ancestors #=> [C, M1, M2, Object, Kernel, BasicObject]
        ```

    * Module#public, Module#protected, Module#private, Module#public_class_method,
      Module#private_class_method, toplevel "private" and "public" methods
      now accept single array argument with a list of method names. [[Feature #17314]]

    * Module#attr_accessor, Module#attr_reader, Module#attr_writer and Module#attr
      methods now return an array of defined method names as symbols.
      [[Feature #17314]]

    * Module#alias_method now returns the defined alias as a symbol.
      [[Feature #17314]]

* Mutex

    * `Mutex` is now acquired per-`Fiber` instead of per-`Thread`. This change
      should be compatible for essentially all usages and avoids blocking when
      using a scheduler. [[Feature #16792]]

* Proc

    * Proc#== and Proc#eql? are now defined and will return true for
      separate Proc instances if the procs were created from the same block.
      [[Feature #14267]]

* Queue / SizedQueue

    * Queue#pop, SizedQueue#push and related methods may now invoke the
      `block`/`unblock` scheduler hooks in a non-blocking context.
      [[Feature #16786]]

* Ractor

    * New class added to enable parallel execution. See rdoc-ref:ractor.md for
      more details.

* Random

    * `Random::DEFAULT` now refers to the `Random` class instead of being a `Random` instance,
      so it can work with `Ractor`.
      [[Feature #17322]]

    * `Random::DEFAULT` is deprecated since its value is now confusing and it is no longer global,
      use `Kernel.rand`/`Random.rand` directly, or create a `Random` instance with `Random.new` instead.
      [[Feature #17351]]


* String

    * The following methods now return or yield String instances
      instead of subclass instances when called on subclass instances:
      [[Bug #10845]]

        * String#*
        * String#capitalize
        * String#center
        * String#chomp
        * String#chop
        * String#delete
        * String#delete_prefix
        * String#delete_suffix
        * String#downcase
        * String#dump
        * String#each_char
        * String#each_grapheme_cluster
        * String#each_line
        * String#gsub
        * String#ljust
        * String#lstrip
        * String#partition
        * String#reverse
        * String#rjust
        * String#rpartition
        * String#rstrip
        * String#scrub
        * String#slice!
        * String#slice / String#[]
        * String#split
        * String#squeeze
        * String#strip
        * String#sub
        * String#succ / String#next
        * String#swapcase
        * String#tr
        * String#tr_s
        * String#upcase

* Symbol

    * Symbol#to_proc now returns a lambda Proc.  [[Feature #16260]]

    * Symbol#name has been added, which returns the name of the symbol
      if it is named.  The returned string is frozen.  [[Feature #16150]]

* Fiber

    * Introduce Fiber.set_scheduler for intercepting blocking operations and
      Fiber.scheduler for accessing the current scheduler. See
      rdoc-ref:fiber.md for more details about what operations are supported and
      how to implement the scheduler hooks. [[Feature #16786]]

    * Fiber.blocking? tells whether the current execution context is
      blocking. [[Feature #16786]]

    * Thread#join invokes the scheduler hooks `block`/`unblock` in a
      non-blocking execution context. [[Feature #16786]]

* Thread

    * Thread.ignore_deadlock accessor has been added for disabling the
      default deadlock detection, allowing the use of signal handlers to
      break deadlock. [[Bug #13768]]

* Warning

    * Warning#warn now supports a category keyword argument.
      [[Feature #17122]]

## Stdlib updates

Outstanding ones only.

* BigDecimal

    * Update to BigDecimal 3.0.0

    * This version is Ractor compatible.

* Bundler

    * Update to Bundler 2.2.3

* CGI

    * Update to 0.2.0

    * This version is Ractor compatible.

* CSV

    * Update to CSV 3.1.9

* Date

    * Update to Date 3.1.1

    * This version is Ractor compatible.

* Digest

    * Update to Digest 3.0.0

    * This version is Ractor compatible.

* Etc

    * Update to Etc 1.2.0

    * This version is Ractor compatible.

* Fiddle

    * Update to Fiddle 1.0.5

* IRB

    * Update to IRB 1.2.6

* JSON

    * Update to JSON 2.5.0

    * This version is Ractor compatible.

* Set

    * Update to set 1.0.0

    * SortedSet has been removed for dependency and performance reasons.

    * Set#join is added as a shorthand for `.to_a.join`.

    * Set#<=> is added.

* Socket

    * Add :connect_timeout to TCPSocket.new [[Feature #17187]]

* Net::HTTP

    * Net::HTTP#verify_hostname= and Net::HTTP#verify_hostname have been
      added to skip hostname verification.  [[Feature #16555]]

    * Net::HTTP.get, Net::HTTP.get_response, and Net::HTTP.get_print
      can take the request headers as a Hash in the second argument when the
      first argument is a URI.  [[Feature #16686]]

* Net::SMTP

    * Add SNI support.

    * Net::SMTP.start arguments are keyword arguments.

    * TLS should not check the host name by default.

* OpenStruct

    * Initialization is no longer lazy. [[Bug #12136]]

    * Builtin methods can now be overridden safely. [[Bug #15409]]

    * Implementation uses only methods ending with `!`.

    * Ractor compatible.

    * Improved support for YAML. [[Bug #8382]]

    * Use officially discouraged. Read OpenStruct@Caveats section.

* Pathname

    * Ractor compatible.

* Psych

    * Update to Psych 3.3.0

    * This version is Ractor compatible.

* Reline

    * Update to Reline 0.1.5

* RubyGems

    * Update to RubyGems 3.2.3

* StringIO

    * Update to StringIO 3.0.0

    * This version is Ractor compatible.

* StringScanner

    * Update to StringScanner 3.0.0

    * This version is Ractor compatible.

## Compatibility issues

Excluding feature bug fixes.

* Regexp literals and all Range objects are frozen. [[Feature #8948]] [[Feature #16377]] [[Feature #15504]]

    ```ruby
    /foo/.frozen? #=> true
    (42...).frozen? # => true
    ```

* EXPERIMENTAL: Hash#each consistently yields a 2-element array. [[Bug #12706]]

    * Now `{ a: 1 }.each(&->(k, v) { })` raises an ArgumentError
      due to lambda's arity check.

* When writing to STDOUT redirected to a closed pipe, no broken pipe
  error message will be shown now.  [[Feature #14413]]

* `TRUE`/`FALSE`/`NIL` constants are no longer defined.

* Integer#zero? overrides Numeric#zero? for optimization.  [[Misc #16961]]

* Enumerable#grep and Enumerable#grep_v when passed a Regexp and no block no longer modify
  Regexp.last_match. [[Bug #17030]]

* Requiring 'open-uri' no longer redefines `Kernel#open`.
  Call `URI.open` directly or `use URI#open` instead. [[Misc #15893]]

* SortedSet has been removed for dependency and performance reasons.

## Stdlib compatibility issues

* Default gems

    * The following libraries are promoted to default gems from stdlib.

        * English
        * abbrev
        * base64
        * drb
        * debug
        * erb
        * find
        * net-ftp
        * net-http
        * net-imap
        * net-protocol
        * open-uri
        * optparse
        * pp
        * prettyprint
        * resolv-replace
        * resolv
        * rinda
        * set
        * securerandom
        * shellwords
        * tempfile
        * tmpdir
        * time
        * tsort
        * un
        * weakref

    * The following extensions are promoted to default gems from stdlib.

        * digest
        * io-nonblock
        * io-wait
        * nkf
        * pathname
        * syslog
        * win32ole

* Bundled gems

    * net-telnet and xmlrpc have been removed from the bundled gems.
      If you are interested in maintaining them, please comment on
      your plan to https://github.com/ruby/xmlrpc
      or https://github.com/ruby/net-telnet.

* SDBM has been removed from the Ruby standard library. [[Bug #8446]]

    * The issues of sdbm will be handled at https://github.com/ruby/sdbm

* WEBrick has been removed from the Ruby standard library. [[Feature #17303]]

    * The issues of WEBrick will be handled at https://github.com/ruby/webrick

## C API updates

* C API functions related to $SAFE have been removed.
  [[Feature #16131]]

* C API header file `ruby/ruby.h` was split. [[GH-2991]]

    This should have no impact on extension libraries,
    but users might experience slow compilations.

* Memory view interface [EXPERIMENTAL]

    * The memory view interface is a C-API set to exchange a raw memory area,
      such as a numeric array or a bitmap image, between extension libraries.
      The extension libraries can share also the metadata of the memory area
      that consists of the shape, the element format, and so on.
      Using these kinds of metadata, the extension libraries can share even
      a multidimensional array appropriately.
      This feature is designed by referring to Python's buffer protocol.
      [[Feature #13767]] [[Feature #14722]]

* Ractor related C APIs are introduced (experimental) in "include/ruby/ractor.h".

## Implementation improvements

* New method cache mechanism for Ractor. [[Feature #16614]]

    * Inline method caches pointed from ISeq can be accessed by multiple Ractors
      in parallel and synchronization is needed even for method caches. However,
      such synchronization can be overhead so introducing new inline method cache
      mechanisms, (1) Disposable inline method cache (2) per-Class method cache
      and (3) new invalidation mechanism. (1) can avoid per-method call
      synchronization because it only uses atomic operations.
      See the ticket for more details.

* The number of hashes allocated when using a keyword splat in
  a method call has been reduced to a maximum of 1, and passing
  a keyword splat to a method that accepts specific keywords
  does not allocate a hash.

* `super` is optimized when the same type of method is called in the previous call
  if it's not refinements or an attr reader or writer.

### JIT

* Performance improvements of JIT-ed code

    * Microarchitectural optimizations

        * Native functions shared by multiple methods are deduplicated on JIT compaction.

        * Decrease code size of hot paths by some optimizations and partitioning cold paths.

    * Instance variables

        * Eliminate some redundant checks.

        * Skip checking a class and a object multiple times in a method when possible.

        * Optimize accesses in some core classes like Hash and their subclasses.

    * Method inlining support for some C methods

        * `Kernel`: `#class`, `#frozen?`

        * `Integer`: `#-@`, `#~`, `#abs`, `#bit_length`, `#even?`, `#integer?`, `#magnitude`,
          `#odd?`, `#ord`, `#to_i`, `#to_int`, `#zero?`

        * `Struct`: reader methods for 10th or later members

    * Constant references are inlined.

    * Always generate appropriate code for `==`, `nil?`, and `!` calls depending on
      a receiver class.

    * Reduce the number of PC accesses on branches and method returns.

    * Optimize C method calls a little.

* Compilation process improvements

    * It does not keep temporary files in /tmp anymore.

    * Throttle GC and compaction of JIT-ed code.

    * Avoid GC-ing JIT-ed code when not necessary.

    * GC-ing JIT-ed code is executed in a background thread.

    * Reduce the number of locks between Ruby and JIT threads.

## Static analysis

### RBS

* RBS is a new language for type definition of Ruby programs.
  It allows writing types of classes and modules with advanced
  types including union types, overloading, generics, and
  _interface types_ for duck typing.

* Ruby ships with type definitions for core/stdlib classes.

* `rbs` gem is bundled to load and process RBS files.

### TypeProf

* TypeProf is a type analysis tool for Ruby code based on abstract interpretation.

    * It reads non-annotated Ruby code, tries inferring its type signature, and prints
      the analysis result in RBS format.

    * Though it supports only a subset of the Ruby language yet, we will continuously
      improve the coverage of language features, analysis performance, and usability.

```ruby
# test.rb
def foo(x)
  if x > 10
    x.to_s
  else
    nil
  end
end

foo(42)
```

```
$ typeprof test.rb
# Classes
class Object
  def foo : (Integer) -> String?
end
```

## Miscellaneous changes

* Methods using `ruby2_keywords` will no longer keep empty keyword
  splats, those are now removed just as they are for methods not
  using `ruby2_keywords`.

* When an exception is caught in the default handler, the error
  message and backtrace are printed in order from the innermost.
  [[Feature #8661]]

* Accessing an uninitialized instance variable no longer emits a
  warning in verbose mode. [[Feature #17055]]

[Bug #4352]:      https://bugs.ruby-lang.org/issues/4352
[Bug #6087]:      https://bugs.ruby-lang.org/issues/6087
[Bug #8382]:      https://bugs.ruby-lang.org/issues/8382
[Bug #8446]:      https://bugs.ruby-lang.org/issues/8446
[Feature #8661]:  https://bugs.ruby-lang.org/issues/8661
[Feature #8709]:  https://bugs.ruby-lang.org/issues/8709
[Feature #8948]:  https://bugs.ruby-lang.org/issues/8948
[Feature #9573]:  https://bugs.ruby-lang.org/issues/9573
[Bug #10845]:     https://bugs.ruby-lang.org/issues/10845
[Bug #12136]:     https://bugs.ruby-lang.org/issues/12136
[Feature #12650]: https://bugs.ruby-lang.org/issues/12650
[Bug #12706]:     https://bugs.ruby-lang.org/issues/12706
[Feature #13767]: https://bugs.ruby-lang.org/issues/13767
[Bug #13768]:     https://bugs.ruby-lang.org/issues/13768
[Feature #14183]: https://bugs.ruby-lang.org/issues/14183
[Bug #14266]:     https://bugs.ruby-lang.org/issues/14266
[Feature #14267]: https://bugs.ruby-lang.org/issues/14267
[Feature #14413]: https://bugs.ruby-lang.org/issues/14413
[Bug #14541]:     https://bugs.ruby-lang.org/issues/14541
[Feature #14722]: https://bugs.ruby-lang.org/issues/14722
[Bug #15409]:     https://bugs.ruby-lang.org/issues/15409
[Feature #15504]: https://bugs.ruby-lang.org/issues/15504
[Feature #15575]: https://bugs.ruby-lang.org/issues/15575
[Feature #15822]: https://bugs.ruby-lang.org/issues/15822
[Misc #15893]:    https://bugs.ruby-lang.org/issues/15893
[Feature #15921]: https://bugs.ruby-lang.org/issues/15921
[Feature #15973]: https://bugs.ruby-lang.org/issues/15973
[Feature #16131]: https://bugs.ruby-lang.org/issues/16131
[Feature #16150]: https://bugs.ruby-lang.org/issues/16150
[Feature #16166]: https://bugs.ruby-lang.org/issues/16166
[Feature #16175]: https://bugs.ruby-lang.org/issues/16175
[Feature #16233]: https://bugs.ruby-lang.org/issues/16233
[Feature #16260]: https://bugs.ruby-lang.org/issues/16260
[Feature #16274]: https://bugs.ruby-lang.org/issues/16274
[Feature #16345]: https://bugs.ruby-lang.org/issues/16345
[Feature #16377]: https://bugs.ruby-lang.org/issues/16377
[Feature #16378]: https://bugs.ruby-lang.org/issues/16378
[Feature #16555]: https://bugs.ruby-lang.org/issues/16555
[Feature #16604]: https://bugs.ruby-lang.org/issues/16604
[Feature #16614]: https://bugs.ruby-lang.org/issues/16614
[Feature #16686]: https://bugs.ruby-lang.org/issues/16686
[Feature #16746]: https://bugs.ruby-lang.org/issues/16746
[Feature #16754]: https://bugs.ruby-lang.org/issues/16754
[Feature #16786]: https://bugs.ruby-lang.org/issues/16786
[Feature #16792]: https://bugs.ruby-lang.org/issues/16792
[Feature #16815]: https://bugs.ruby-lang.org/issues/16815
[Feature #16828]: https://bugs.ruby-lang.org/issues/16828
[Misc #16961]:    https://bugs.ruby-lang.org/issues/16961
[Bug #17030]:     https://bugs.ruby-lang.org/issues/17030
[Feature #17055]: https://bugs.ruby-lang.org/issues/17055
[Feature #17104]: https://bugs.ruby-lang.org/issues/17104
[Feature #17122]: https://bugs.ruby-lang.org/issues/17122
[Feature #17136]: https://bugs.ruby-lang.org/issues/17136
[Feature #17176]: https://bugs.ruby-lang.org/issues/17176
[Feature #17187]: https://bugs.ruby-lang.org/issues/17187
[Bug #17221]:     https://bugs.ruby-lang.org/issues/17221
[Feature #17260]: https://bugs.ruby-lang.org/issues/17260
[Feature #17273]: https://bugs.ruby-lang.org/issues/17273
[Feature #17303]: https://bugs.ruby-lang.org/issues/17303
[Feature #17314]: https://bugs.ruby-lang.org/issues/17314
[Feature #17322]: https://bugs.ruby-lang.org/issues/17322
[Feature #17351]: https://bugs.ruby-lang.org/issues/17351
[Feature #17371]: https://bugs.ruby-lang.org/issues/17371
[Bug #17419]:     https://bugs.ruby-lang.org/issues/17419
[GH-2991]:        https://github.com/ruby/ruby/pull/2991
[![Build Status](https://travis-ci.org/ruby/ruby.svg?branch=master)](https://travis-ci.org/ruby/ruby)
[![Build status](https://ci.appveyor.com/api/projects/status/0sy8rrxut4o0k960/branch/master?svg=true)](https://ci.appveyor.com/project/ruby/ruby/branch/master)
[![Actions Status](https://github.com/ruby/ruby/workflows/macOS/badge.svg)](https://github.com/ruby/ruby/actions?query=workflow%3A"macOS")
[![Actions Status](https://github.com/ruby/ruby/workflows/MinGW/badge.svg)](https://github.com/ruby/ruby/actions?query=workflow%3A"MinGW")
[![Actions Status](https://github.com/ruby/ruby/workflows/MJIT/badge.svg)](https://github.com/ruby/ruby/actions?query=workflow%3A"MJIT")
[![Actions Status](https://github.com/ruby/ruby/workflows/Ubuntu/badge.svg)](https://github.com/ruby/ruby/actions?query=workflow%3A"Ubuntu")
[![Actions Status](https://github.com/ruby/ruby/workflows/Windows/badge.svg)](https://github.com/ruby/ruby/actions?query=workflow%3A"Windows")

# What's Ruby

Ruby is an interpreted object-oriented programming language often
used for web development. It also offers many scripting features
to process plain text and serialized files, or manage system tasks.
It is simple, straightforward, and extensible.

## Features of Ruby

*   Simple Syntax
*   **Normal** Object-oriented Features (e.g. class, method calls)
*   **Advanced** Object-oriented Features (e.g. mix-in, singleton-method)
*   Operator Overloading
*   Exception Handling
*   Iterators and Closures
*   Garbage Collection
*   Dynamic Loading of Object Files (on some architectures)
*   Highly Portable (works on many Unix-like/POSIX compatible platforms as
    well as Windows, macOS, etc.) cf.
    https://github.com/ruby/ruby/blob/master/doc/contributing.rdoc#label-Platform+Maintainers


## How to get Ruby

For a complete list of ways to install Ruby, including using third-party tools
like rvm, see:

https://www.ruby-lang.org/en/downloads/

### Git

The mirror of the Ruby source tree can be checked out with the following command:

    $ git clone https://github.com/ruby/ruby.git

There are some other branches under development. Try the following command
to see the list of branches:

    $ git ls-remote https://github.com/ruby/ruby.git

You may also want to use https://git.ruby-lang.org/ruby.git (actual master of Ruby source)
if you are a committer.

### Subversion

Stable branches for older Ruby versions can be checked out with also the
following command:

    $ svn co https://svn.ruby-lang.org/repos/ruby/branches/ruby_2_6/ ruby

Try the following command to see the list of branches:

    $ svn ls https://svn.ruby-lang.org/repos/ruby/branches/


## Ruby home page

https://www.ruby-lang.org/

## Mailing list

There is a mailing list to discuss Ruby. To subscribe to this list, please
send the following phrase:

    subscribe

in the mail body (not subject) to the address [ruby-talk-request@ruby-lang.org].

[ruby-talk-request@ruby-lang.org]: mailto:ruby-talk-request@ruby-lang.org?subject=Join%20Ruby%20Mailing%20List&body=subscribe

## How to compile and install

1.  If you want to use Microsoft Visual C++ to compile Ruby, read
    [win32/README.win32](win32/README.win32) instead of this document.

2.  Run `./autogen.sh` to generate configure, when you build the source checked
    out from the Git repository.

3.  Run `./configure`, which will generate `config.h` and `Makefile`.

    Some C compiler flags may be added by default depending on your
    environment. Specify `optflags=..` and `warnflags=..` as necessary to
    override them.

4.  Edit `include/ruby/defines.h` if you need. Usually this step will not be needed.

5.  Remove comment mark(`#`) before the module names from `ext/Setup` (or add
    module names if not present), if you want to link modules statically.

    If you don't want to compile non static extension modules (probably on
    architectures which do not allow dynamic loading), remove comment mark
    from the line "`#option nodynamic`" in `ext/Setup`.

    Usually this step will not be needed.

6.  Run `make`.

    * On Mac, set RUBY\_CODESIGN environment variable with a signing identity.
      It uses the identity to sign `ruby` binary. See also codesign(1).

7.  Optionally, run '`make check`' to check whether the compiled Ruby
    interpreter works well. If you see the message "`check succeeded`", your
    Ruby works as it should (hopefully).

8.  Run '`make install`'.

    This command will create the following directories and install files into
    them.

    *   `${DESTDIR}${prefix}/bin`
    *   `${DESTDIR}${prefix}/include/ruby-${MAJOR}.${MINOR}.${TEENY}`
    *   `${DESTDIR}${prefix}/include/ruby-${MAJOR}.${MINOR}.${TEENY}/${PLATFORM}`
    *   `${DESTDIR}${prefix}/lib`
    *   `${DESTDIR}${prefix}/lib/ruby`
    *   `${DESTDIR}${prefix}/lib/ruby/${MAJOR}.${MINOR}.${TEENY}`
    *   `${DESTDIR}${prefix}/lib/ruby/${MAJOR}.${MINOR}.${TEENY}/${PLATFORM}`
    *   `${DESTDIR}${prefix}/lib/ruby/site_ruby`
    *   `${DESTDIR}${prefix}/lib/ruby/site_ruby/${MAJOR}.${MINOR}.${TEENY}`
    *   `${DESTDIR}${prefix}/lib/ruby/site_ruby/${MAJOR}.${MINOR}.${TEENY}/${PLATFORM}`
    *   `${DESTDIR}${prefix}/lib/ruby/vendor_ruby`
    *   `${DESTDIR}${prefix}/lib/ruby/vendor_ruby/${MAJOR}.${MINOR}.${TEENY}`
    *   `${DESTDIR}${prefix}/lib/ruby/vendor_ruby/${MAJOR}.${MINOR}.${TEENY}/${PLATFORM}`
    *   `${DESTDIR}${prefix}/lib/ruby/gems/${MAJOR}.${MINOR}.${TEENY}`
    *   `${DESTDIR}${prefix}/share/man/man1`
    *   `${DESTDIR}${prefix}/share/ri/${MAJOR}.${MINOR}.${TEENY}/system`


    If Ruby's API version is '*x.y.z*', the `${MAJOR}` is '*x*', the
    `${MINOR}` is '*y*', and the `${TEENY}` is '*z*'.

    **NOTE**: teeny of the API version may be different from one of Ruby's
    program version

    You may have to be a super user to install Ruby.

If you fail to compile Ruby, please send the detailed error report with the
error log and machine/OS type, to help others.

Some extension libraries may not get compiled because of lack of necessary
external libraries and/or headers, then you will need to run '`make distclean-ext`'
to remove old configuration after installing them in such case.

## Copying

See the file [COPYING](COPYING).

## Feedback

Questions about the Ruby language can be asked on the Ruby-Talk mailing list
(https://www.ruby-lang.org/en/community/mailing-lists) or on websites like
(https://stackoverflow.com).

Bugs should be reported at https://bugs.ruby-lang.org. Read [HowToReport] for more information.

[HowToReport]: https://bugs.ruby-lang.org/projects/ruby/wiki/HowToReport

## Contributing

See the file [CONTRIBUTING.md](CONTRIBUTING.md)

## The Author

Ruby was originally designed and developed by Yukihiro Matsumoto (Matz) in 1995.

<matz@ruby-lang.org>
metadata.gz                                                                                         0000444 0000000 0000000 00000002304 14442217575 013450  0                                                                                                    ustar 00wheel                           wheel                           0000000 0000000                                                                                                                                                                         }dX[OF~%-!meQ	Y$B>=ݹsaYo,] 9gfss>1b7(]v
2ˮ(q"E%dr݂(&ԩ"B6F/Y]HDԻZE19ZKnTPi{n 
7Q	eM9n˯_ĳo⯏l?1h@1P%17kDy)CADrS^=xYڄdn -5U*,<=߂`XǕ9aٹW#4 ƾ	0߆%|Gf`K
@+AYrT6IyAhh!p,h	=VP4qmK5YTy{ssMʶCXZ\6ȊIxx3[ǅ˳M,AjanV,9zVgHnȗ:.p^`UpZch,HaHL"`nO"ҷl;*`hhn. y7O$'o/NO7Wg9h%5OM|~v2$~HIL)"EKk6}Vl
jy9`ڱӤܣUZGP̽c0l㥸[6
CImIGY{6j)]U}4ҳpwppWB(kTп*#dh38:D-a'hhVe"+9Q	OYt^lJ.GAOTzPXn<@noH|"1]05r#y{|*(;a`o*\5~+7NE0ᜭ
ip	гSZAΏ45{ل30荐
qFGrZBC+$sҴE6$T0#GX8U:L߿SʭD2|S&EM8T5t=iGF:j]93Z{SB^jO#8,
֪kC̢v.l`a,=kȾksar̶AT $m
"6~Y^)$<Yd(^Jj98cLbSp_u:(                                                                                                                                                                                                                                                                                                                              data.tar.gz                                                                                         0000444 0000000 0000000 00000312574 14442217575 013403  0                                                                                                    ustar 00wheel                           wheel                           0000000 0000000                                                                                                                                                                         }dvٕ6QT-2ML)DIY_"@ $GHAUV?{ܫ=Iz7'%]]UL"7^nO+t#t[[{{~gkoAyfqMiQp4Q4IGd$i&QHb,KEpS^|%E4DI^2L4	4,z<p08M&QGA,JQ(nE167oK7t3J6ڝvgsh<z|ܡ?`촶6mxG"Y8(ig8An0oēnpNQ?>=wQy'l>lF3hEt&ҢvG;nO{;?i<.%x(Â8y-u8Ωu=9:]^a2o~}O"wE.g`شk]E43ky5<5nP|[mt>'I9t>)bZqq][\N)mVo`[Eb־?vkwwo?'INk3ERߝ:\/IEuoQD?쥾۟t{r{ ۠䲸7'I,9.o+U7Mx<{N"}eiF~DE؁PGϳppBKMo ,D&R< G!`^:N[|:)AlWVL<G룳wWﮮ~<?*{}K?lI}^RoiQE>m`ǟfo#Bq[Zp< D@x *s`*M_=tfOԧ^6=>|x#D8}κ<'pLҤ5fYAWtHMQyN;9JЎ}_ݨ_g~yy<\'q`7=lQ$D O DG{XuDX2!rk_E>&w<s,ƄZ(b^:іwx4;+19!g՝Wo$MoЛMs~ۮB$ 3+:*>dlӌ`hF=π0]&AHCfЍ}bXYXW.z϶v϶Vbbyʻpc^v*5ݕ<?>Rv)gZو5!t8-<`{qI
`WA)1z]4ml^<p{e
8q4syA99G	ٛt9 `y*EE3?=S=#|2 ҂<tBۧ__9f>E[;{]Ԯo\Wf3:-ք?0KDIo%IR D#9WC:t	ķ@.4OdZƸEכh3iNQJj^o߱uC({iIvO͘T)1fA	5Ƹ>(͉SX`#%dؠL~1	֣^^x1aixr$wEq:B9$&,m<ށa]v4X#m8oKn6j}ܛ:"> ^]m׍oQw>qOl\$u넋n(4a	//~w|q}~qvuvtvSRׯIxH.:Lܾƈ;/B=6dHO}&p:pN3\iס:D.IdѾu批cW概Y2-i: ~? oyQM7b+_FP{8ply@KJv^QHP%(T^M1
MFn[OL-l<c^A?0qy0 W8	tҔe#}tJ;#\9immxzI;8<zsÛӓ+,B( [ OcQhqĮ}M:atGB&XDWһ°j8K<"D=H1,
F%,F|vrg	
Ne%SV֭;}TRHL=N㾌2ZP(7ElX)"X?p5#(J"ä1Ĥ(k1%4(`~]Fݎ~8i`NT
Y	&=s]Xy"ˎ_"^e8N`(hRG	[0Pū`{9tG,'eȭ>Q}?{zÐ0u bCCeLd&ΕՖ=Sŷo[Ӯ(Cz).<guUw"a<"_Q$gѱȻ_c<meo$2+ّfO;Uxy#a=/	8f_(p}Jt/a00DS{4w
/GD'0
Ao`y|<3BBQn?Qn/2Wqh=æv<݋	mCL$rf⽚1<U%=YHЮx'^Gl<.owP9ae	O>lԎN&ڎ~ƬK+hF({y)qkK4zƇ$ȏME TD Բ\A(0KNl4/T5JHu3ZˠI1 dGX xu^~lWĉ>*l2*Y:6+%a,<IÁ|5@`Y^t`S Y]xU Vv$VQG#qQ/	-3?<na-U@'=1"z-[}XELf`J!Z.elؑdΩ2( nZD.~3֛<w$BZf@"~О +WvppfG9>Vzq;~;]4rQtel9Ecz+aDC;hoxbxL[ӡS;-Kqcc1և1w
%3"W,f<55>QS\&gh"$ϋޱ8
 ֝gAwivG@3ľ!Lϸ~S[ͩb'l](#@r6jzU{2bg.0})Z0T,qzU|j=k1i0VQsRԮu?bf"YDm#!~^	v; v$p2՛.Ia}9,a*=<  SΉaNՎ2.P_ugPSB1I5PaEn,!7F0r!Ō;C	}ݧ	|vE4N[FbSBl?zh%h< &ÔE=jFЈz݃uV#E>8T)gG7aln:?ugۀԙvpu@JRp'}9]&k7Yz#ֳiڨ݆ȏTmS=K%Mh`TZwjY
}UKѡjs0OkEcIg!4 YcnZ \D5{p"gxRVa)t=^~zDl_;3je'¦{SU;M7avO](xGOᒱx5{+cq@g~7E9!4ل"ΚO0֞̸Fb&LIo(H@/<Yg7g6SCnCwy8w&]_{]7?N\ W"L~0G-yMJ^K/unuv:¹'{n"1v|P,@\UeuCDHod==LNy<ߎlc7Aߟu#8"7xN5.u'bUcp$7Bͽu:֭efNn_MxnsMf'J >3bQ>>Ў7yxsЌA&<#nĬ6$2zt;vg	
Ɖ`ՓLia&S1݊BCg{0k9XÐnb$@]P7Ě	 |"Һ6O=XXqƆFY.GPM8gO>m|r<&[_/YNR/̖0 UHgNģRmo+߯;>w17Jg*M|TԹ佁K^;$y @n?ºP+U*,ɉS%i={qreJ'SVn#>M,P}{;|{4]\i͙xe>} :x_aʺR50e(Ɯ@}*оKY6b&o)wğ!]u3{|V7tYaWSGDe5oO=h0mD OOhhAbU6u^/e6Fi$
sUʚ8 ro։QAa/gEx4G0*kƗ@W^
bՒo ;V}	ѷX)㍾S1۰}{׬]C1
yX5,KUHK-f)mʊ1c<X8:V`*cw%k:U&X=MOP|9;h9MxYtث.xDwp1Wd/uT 3iR&K4ɰd[ 藷PŐ&c5TN|Q-ͻoQϖX	Dt(dOj+z7h(^ŮGB4R<%yr&#ף*_?8ovqƗq	^j% qUmòӯ*NҾD48(ˉ"*n=XDݧge
TX5n#PsApbxICh|Fyy^JrrK*B߳U^	JL@	2-Ebܢ2ޘlc|jJ_P໳u%#*TK̓meRݥk9
nO0t-UIVQKlY]dsSchuIwQ/O9o>Tqn}>;iT:Q:x,2͇Z!kzDxWt旄*@ kK̈9"g_	rJZ{m˒K&oY^4.QTRb_l!k@|Ì7Ǔۧ`F	5O-<TBHٖH'G<)~vv6th((n6RV7uZ8E_@u~_Z`JᘨG(V.\zPœp9<;4ZˍizP.tGnwꇗ郃wNޝ\d~~ww;L0%W
;o;Jn!Ur \DڈqF"1FliDX&faMD4t6|_fZ>)(LPrveg,<G[w'*bE5{R8|wI[Re1@E&G_Xf/	M᥎&i2ZtsFUeUn!دY1,LT1*[(,:iߋ6KHJOE4;+#5SM+OUgVyfW2]gMnxU87a(_٨aqsa "tcu+&,e42
,>1/d
3;z!ZSX.m5M/QJ>XE!a_"ć#*y!t-#`3PQCaφr?x vM<'q:W9^UnU(a0fct`kߋ4eè6 J@ރܤXԅ\S"R:!2ßb=$i{{OOˣѺ/dp(^qzwlTFFbe8JZ%F}C^+aǠ͒
ϵ~i%9N	A( ~5z/4F}yyzgr4k(m4!A$a-++$.7gF_Y3p&W]%8Vi:<4GQ+ONeGI"% 0OyXo>ȩʄItOk|Ϛ!\}HwcY/]/5 ud4(qYSuT>mh=ُH:uqɻןӁ(V;|rNy՘<#3X`"dya`vIL-ð!K5d"G6^\d~px:Xo(f>Y(|O-E);v/q/(ψ?A9"&덡X`nTr9,_3h&ƞ/' aPH=q]TȖC/ib1 ۨ2@,2gMLuF"}:ƭ/La~,[gk$Cp3LLRlwa/jW'zEbNņW{
f'7.3Q΄Ţ>$>,|8|˝9%\VD+qg;P8b2K7;#&4!wVh-QiVHon\SΊ	.z}|G!]~/)~x-=UAx4-Zlne)LK84m bM>0Xnooz+s㽪Y>+$4?_$}$u[8&.1@X]aE_kZߖY[6mAUxpw+c!֨Eo=)7/q!t..Z'-c22<l\2ꅲfaȬfp1A~=QsNqC,<Ji!MGHd7Y$,`L	}IoJQޱ[H7ßLС	`jF`b$(zGHIPbzUqF%ϋU7Xi=?kOar$ؤ^^/rA6կ8{tD"~7(s=%Wع	{0₄ޢ^r	u>B[7]08[\Sޱ3&a.Q|W\}"N7$y:i/3*?^#*Sb&uYݕ4|xzz4\|!".7ܳwtչ'XrODoq
|XZ*Kj;_|J3xj-I
zd%5np^s-mսF9QB+$:!}MQr#66s6i[8{ͫrh֯ˑBl}-I	(!'3xvq迢pcC_JZEdjYjue|Mu[6cVZ冷bFf-[ƎJ }>WS(	JQ}c
HߊDCxs
iny8ו=s7C:[o贊/j\[@3\|4IZ]9<[̤LdH
}Yg8v==EKKW"E9~ 9(RA8A%+B^'ɉSE5{㞉?[zOm?8t*@+"(fjDN^rJ&ҵYY>YJVª2pz?{OtE:~#vX+mTBtt=pBxnS|2bx`DXl +<:GF;^^7U	ZNWX-2&Ǵ8Ze/UFka1\$fA#OqbI:,*jH8opOD٠DUt	_õ̰YEZ/i4h=-:c1rnhXtN[	gCǈ>uyj>ɉ˪K7{nQm,=>tF NB|LhHC3yZ2͎"~d YDOjwjZ;[Kc?MB`&
SP2pB?le,nEc*; $)%B̗h121K8<&nһ(p7RPj\毹=NA6i:jJ*P
}^MBHp2xjH])%|ّQZ8Ұ,Pq7ƒo#Ē/?fHV/.Lu?Q>iä"H|s87zD`9U\ȶ sf$Iж!"ͅZd|U1p֦EL!͢DM6"jz{Z	 ^8fɆK4R%rWY=$JE$,=6dgdzܜy4o$}*Zf-20lwj
cj{H[4
&dv˨T߽?=r8_^.fSXHlUoV'1vms"B$+zy뛸;%=Og8D_F|};lPiio04@3`+Q4a<M4%ߧk|·+|/pVpdx##VE˨ѤtEX.Hu'ї<R)ԦuAqȖ@I>tz@K1k\ֈfz0tES!zj2To/ޭ`8\&IaƣMe,6EwypF""M"0%{7Ń& Sx1Qur|nZbLZdMIz5\jJ|+dip2= ErO5~at806f:lc[SA
1$rk3pX_7XN:-zwCy<]0M78)&93M@?o(NRM.GzMLsøM5thu8Tܫ0ETĒENSxRG^b/~0b04?hc*x=>	oaBP#@mK NJH<U}B$奱DlA'0/RLۓ6xH-D4rqsdZw*wDi'w8*iU8pҝ)Z+ɪ^w$+ş9YPKI`j{E:ϪqAWqH:ϏĴҤt<\b]9-{0pa4wTGEEawz)rA194ʡq8wyda'*"1ۈI/"|5Wts2xy|~q|txu^B~ !>m?3G㶲OvY`6%
ϑ^{w&	eMH)H
]~'lba]ġ^cTezt&&cYkk4-
aoVE=bNK(*JQˇ`v-Hi@^-61ջĞ_٫'Nz o^.8Ðk]J.^&`<sޯ'El|ٟ7-'!gD=*dfp&E8kȆ2ߴm=/ݪ(u$1gK E#m! ~jܽ\pH 0΍_b˸Ꭱˀ5~yxs?<#z
7~0c~G3>Ua1.AJqX{FS"$u_]on.=0uck;oc#4	aڥ$Ϝ+˥Cɵ3瑘ljOVpb3GZN#kᖠ}Ko+42R؍\pB+ȗs$dRh
Ns=e?B{+Nr^6~_Es&=W)Hp<0D4`4JdG~=#!_W-}d$3}#W$Ig;P.wG2l.d#bԕ5k{Y}_dN!x݉~S[ҊǝG32SZauǽ瑠°jfM,Ȯ@g7ӄ{2)2iB`ϋ]
	~iJpǋã߾?:9?>=y{r!|v-c1)K~owo#xA?
5$U{8Ϻa,0'*f}3;H6R}2IKAA̠EXXhA*\~HL4t9Vg"uxtt|NCcsdMo30OZF L4rl*Oڣt k4\zj3c-͌%:o?ݒks>݅}^4Gsv^!<yms%oJsjHXOk?&k뛨L6?4H^IO	i@xKgv	30=Ay	xҙTn3./N/%a%旰ñ4.M⅖SDT;vלtSy{XR򰌐C#พE~u2o#&)>IL\nggRXQ(4:]4aOA&Wo2\e2N#WiyRw/n;`1a[9%V@=9]tHQ D!Q9p_λI~:EgeFjm+<%Q0#f c<-%+AUDE{5;>I[2ꪂ3-W&1*0IwРAq-
J<QPh7!kE*l,h2#oWAaG?'r<ưD	l{[?U7N-"b&^8py	k&O3R	\"^A4-u3}O{H#Ǫתq3.tztq.vPYG\d0yܩWվ#ϧ1;;nK*BMhMU͍"S"8 P/EBnK*JMZv&j4P(X]w~F$_QN&{-fRc2Le)֍#$qB{25|f[BdٰyAQʾX@*+.@gq[gDD?wO(vI{Qk
;+P}kQdYvxꏗGÃ~1XFy\)"|·]Z؉" ydX$JI?<!!KbD&BBuu\:Y'ͽ>*-恄VӕlaslL8OM&Ŏ@%^bү֔k Rv<ȑ:Q:jBb=yƴWu8 z2bWZƙNgDʉ	.,vvV8NәsڤD??SroN&;
.q"E
@G޶
/ٔחeRsVX7yu80uBj2s(Eih9Sޠ*9I'>=Z.i L{,]U5j{/>[f+p҆O8h<8T,H>yvHVM|}@	nzth8E~q㍟Jm=kj;Q1+J g1;D1[2h|a-쑗s64yRm)y_^Z\.zR9Ѱkw.iQ`W2İ똑A1"[8F+Jrdb@@"~^`ё
籍 a=UXO:۬VbPDrjW]z&4脮C6bjbU\BrLLPC0ۚG]W9)}֊uw;{u:	#vvy]..2 J&7Ǉ/7IWyEV+qE&#M+azzqx	iUMY@',).$%fޟbdi>x)|!pI޽`e,YsKI$$Q:÷k]ZȔYY!%fW٭h9u2	 ˮ`f.jDtxVeRΥ7bj,E
vNJd*3#KAd/S-)6MX3=o\=qJs]}8͛DM)xN8'x\ڀY)1s:ѓ8ĆKZ6眓# iI3pDPU|K jQ_EiL"kŊ@#\m'!{DR0T׏R^]蝼Q<yc_EwWgnOL>uNFhQ%ׯ.>^y['PMud$eh ^<Ӽygqi0lnݵ>INMneMCt:;mc+$\rz) fğh%77Vik8=Nk˙P`Znqfp*D&yGic$v!_p
tW'+{G8%f@K]ˤ2zMA
!jc-w³DzK
Fb ߃uۤ#'1 {;fmVF[m(S!/0Yܐ{acaůBDq.0s(m3UctNiۜҾJYRzYAq\{nyQ[<쯿mr^#Ӌ!ke65	53oc>R;dB&c_e9(]/rܢMGQV+]:aUt@Y]Έw"ByC2e)O./rR{E1n
$jǳ84.Pʾ0$Xr^\hշ!vZZ}rv #H.%{n?0ĤT&94Txivu
[I>g-;a!%|R Nάcaֶ6F[lDg9]a"$@Lо(s1OMAc>9u\د7$(Mfm{zs] ɼv<(:bC+Of?]`e4fδ?G>h?d|BphL*-ߣW:q4V-3gط<hÎ>7prk}w'*gcY`FYN6ív+A|֞69%f*q(\Epl_f ,XMֈVҞF-eG5Q8ZpF t`N+[q^iTNn\{!N-DVa]S=q}K	{Kbw9p)mGĵ	x/g(9yz0l{mi.Qt)$ČhSPkDB$Y!syB%eWVU bS˺W.ReX#An~暹> A8Hv:+|[/D=~*IBH*= OqL=֐05xKsb6yb~Ü*P_QR#&V!)J$4oRᓶi0$4ȵ ʒ1SEQqnS6lڹ:RaY9#:|M_L\mHߪhՑ<[u4"Rk;%>_8!2ޥ8a=3,rć |ͳuy-LJMlPa3.Did
7hf!%<'2|X0"vHnS3s"@h;B!iwLËt)IQ͎n5eW 2H%є=٬\n@|kĳi	ma}،<RѦ1fU8LKKU49;CNAp
=l\M}ڷ߮y.`LR!toU0S:`qO=UQ<  {U{؂;Vճ~ǭfS{:#KQpH3cDSA0!*<b."pYJNOu)D{_<%O*R>)jT)b3LqUK^)N#ʔ.4ڛ\Fs\##2Ѯή}Vhds ;wc+|Z^iBϞ,+꛱H&dDN%%	+7]վW5~S3.@ԊWcM6,ʱ>9+(}h+բIc3;5ڛ2Le8rutyEy[2j(jM5lC^h&zT^r#WsEQNkŧrJF^Py8EZjgr)q\ Fc/Xבgjd-U*!B`XցN}`Cіɨ53U,dBYOTʸYQ4GG8exG$0ZBydRx@Δ0g!0fC܀/7-
7yD3?u,Ml)+a4EQo9fDtPbӚ$pXi
tZ4;De\1pJ,H(wt,]EC<-/ФOz^Oj!]ArFub(!*EcCgkecW-x,1Z X"'eICv6L=N+vZ@hV"z﬋Hۧn5u%z۞>(?!vvUTFVͧG4XSIjJ;ltjOMV)t`qhOj˜n/}X+WΘ7'!LbBkr^`ON"kvxg!wm¤~ְPB^L1Zj~*u*st:?mbkwww{{koo"-`Z
v_^1JܤPk4'ι
IRHr /}%]@U;7t8YyCyQza=m	"5Ys0;g6Wޟ#;|e4i!Xv,ez81ķX2Xr7Tɰ$D4Sm7<A¤QѺ%? F_Դ<bDFH>oa< V(U:#[ƍSq!zYH[,+L;3H%wYC`p.%/vg۰ڒ>^٩D\xu4F֗"D=~J3Ͳ[C\+Oѓգ.h&P1{vmCma	- %dxVm<V),WW5678y+HCks(MC>NZׇH,h`|$yJO\јM~FtQ+j6U|d>7&Ѭ]K-{	N}-ʌONe5IYǇ/ZUtV.6IGL/- iݯHZD/D&p6G"	zFkd%9Tͽ~ ?Va<9zqQa$4;pIflu ;ռۜ5jSv(5JZ߃T<Cj.C&)%2F)&^Q?cZbde-˰G=搲HM2߀
lN.&=!?H r04v(%dB3)j7#<p$VSZ_#)LMs,'a$ij-Hy{X	Y1D+ɼ+˅lRWh:"mEYY7(iJ*;9
E
ݡv}	 쬍gHlX,,pDQ+GrE7a~D=4X38bz#_qPGChoBV78?Z9840e5%9'o(;h5p5[S;?*8=j<o{k{"m?F#$a<?6#N2֏6DմMF8xocZAn؟9a3zHEM  jhy:,ǺH'^Gkcm4fe23b]ċfS|^&nل>om&RǜSp9F{14Bl$~8Bkn8oY;a<Y8d1i6MF!`iEAM+s߽S?Pwj[(syUﹼMCWo˳WW/Gw'/_kZ3prU@-.]
pe38epv8y{~zrL;:}S_PwgHBJ^P:9`o/l_89=xurc: YLOޟ^/.i4컓w.h4+./.Ǵ2*m3xy5rQn&	>9O
~bVџMŕ^\b.hx&'ݱSJOMcǇ4%67n]_+縟o?%JnmO*o"/g:k1RLnSWUADCǃ/[.Cr!Ɖv-ytS-FR,+H«xt3rQ4
M՚04-k[D$pҔa&xfP=Q؄Vlu~2b?-1܄(9O``"P>De`ĉIXzT!8l,-#?gĚ5ZȗlMl;)Sb(s2n6IU}gGԊ6D''3A%61?ڴ{|$>?_ZpCk=WErFI.+4:e^r2(h3qavK[b,^eEh5HRJ.W!ɦ8t<

]Wx,hVs<a()8k3,t5OiS*1ӀxiG`?k3X4fڧOhRtn ]X"9z Аgt6=?[Xu톷h{b%H4)Iέ^eG[R7QZ_8Oloo3h*WTl96DDyU;PS7`8W_<E17i߽>y}!,xr"IH,03'\ΐ]g祪ŀ'y=q*K#݊0{&"6ޞy**6E|}m.-v6>i	Q	~DvMXچS:p $GvX˧uWW<([Zph}lIZ	%mDbRbpbLo"'69KR%/ϙK(KZT!7ϔ0-F``~gj*)cNľS0e_\n3oy}Rŋ/SD
aSR
,B]VTowo$ƮzK^aɠ"UkfF5ː&aHQm|U]pMޏe}8|1ޅyo+6.E,xENv^_У3JCl6'y$/-P|tM|"/dE'gл"&C^H^"48r>$zF-I F"]uGz|"wV4B,dM`Qontv%rũLjP둊-Hb*`Ai8f"DCH4-EcЉ~Vo֞,	PzyLVG4vy^P]gS!Mlqԕtr';	Df%t,{N3mpaND.Mo]X>tNĦwiz%Z^}<m*r'?zMtCu]+`ꤙ'EͽK}M3kRyEڗ__-Vp2}!nuXgm,E(Ϛ`"9P4HLFlpPiR7irPyTN+%F:~t8MElCHhGsx`xdM	-Si,N
X<8*Q'I  qX5$Pp`>'dAP,@GWM.(Oy}/b6=s+z3-Ӕ!@#,GP<38f-nӲeh4jE MͥhvN^,Fy=fzvAp46_}ȸ\m͆-91YjRiIKJ{NZN5)ư"}5<uː0t[gTb] 7ժֆ~e-CD<T3@+q/g"4'{)ih%ʙj	rdUHB&I8n!6겎eF`)o9-+G{0ജVrob" ˄[ޡf'2iMQP}$k{YB`rp,uѰNK)dYVxbwprfpۖMK-2%PyK״\<e(2^{pk_J%/cWTDSMfxc\_i(LwKEw|\d(h2g.e.6R\).vuk	X}cwz+b}gwq]\7i	BAXgRU,{uMзwbZnFglk)0rIMnVQ*\^ [[Q0ǒFab2ˌ |Tpe"f ֆz:L˅=: 墮NNk$f44ԺBe<͐ۭ+ihƪrw%("??&'.;N34A(>jooï,_e4ήOK	:#o%]Lru+ aWHdXl
h0nBgHmқ_>!4<\ͶqbJ6opm+#3nt4Iٙ_i$/(|lUSתImJR l]Y:0+L	L<_J5zJ	8I#[7W!gq.J@rHO!ϗ.TxzIE(vNvi71>;|1#kP^,j0xQklq)MDqK6>o^]8Y6{0fX-0ԖJqTph6~VܯϦ*y8.0ۅ!Mkt%>9hkFO?095pǄx#V cĿp-wL2|߃@0O[" \8\sFr8Op N!P?`A?,= ?:V}?m035r֯yǘQwHrHQA~Gǔ[G0NWu|D܇\0l~3\G)Ѩ%Fdc>3]3A5ѥ	Ag>f7	RUeA)WFf]J٫&O!JY
|*1	bz%Jӕ(NXG9_?9;LJ^I>!$W 7򉴞DF0B{/!?ߨu!sSD3[4[Bee^X?ZѩIN9BG+c	6v"tiIEӫ~K;Oh}	ī?i3x%7qpE{"Hܯ3ǥ~;^J'I?HZx1u"d9y*G|Lc.v桻~KD<\ҡlvrjAV!GOi148#271/bѬ	Fq9:T\:L8ъilRRL#TJC45%t̹p)AcBCu1b_QMVp$sVG|d۠a%-_gt=SCIq2.F"g$搄)~ē@#E(w43ʒbѪhی%s3R^85&MSBTmۤ+DTf/4kTu4UKU_QdNTroìO~dKJ`5!f@ ъ#h]構3
խZo P5 6`{ 䢠w	}?7+p0]p9"PqU%HO^hĤZPh[OǞR62cPV~qkdKIbf:k${C2(uY:+ZdHٱ8,<,bSnXv8\A(Im,yUMʇ.Oڍ8s5T16O[MC%a~LT6>HHik@IO47pƱY=ŝOs{`9J>,rq"V&mBǎln/)Iٟ)Jѭt>Kο~N,o8hSա6jRl`Tlɣ#k7-__˫Wo^~I?A>ZipIp|p8Ef)?IVM9Τ9\',^𥉽l_>΃5aY?Snu+dYCI%h*dU58ϣ9xx{Ǻ9m)mtUoeiZ܅D)ć]?@(	-zﱸCDWZ zŵkʁTo+Y2Z]~q(@땔n$!%=qӤ z!$WM+ ](@yVm?1m¢M{FAY0k){j|{P-RQ27ޯP"8gTx%a6WJ ,pG`+j$H\t8UY-+Ϛ@~eI.h&]	({<
0ںs7aK{6=}GU72\`qa6ൔrqvuvtvjcxDͥ>tfeHxr;3@OS= K[4=ƥB؃e:<}vnz/A|J,p`P-ϭц|r	+W̬N4}az[IQ1d)T6a}i5s	ŪSPY:``礒lr42	?ijC};VG_]3L753$E|Wݥ>'5	ؖl 0,jVRe\Ț*]s3vUd[rKjMJ&[nxe})rf&	|0=Iڞ8Q@no
D_x+D-牵mIY3t$aHYz&Z4Aݰ_=ߨjF6ø}1Bba{'Q\\nlX⁦%!e@|W&ϰtRDdWo>zxsTxkEo>$,7'<j{0,SubBe\><cnΓtW߆1,pټ] S Z[..G$.*7%X}vͮGm82ukNGQQ'gt% )8}gr#kVS7%Fp`5&R	Ɩ`w&V86Hֲs#d%hM@IA%,eǑ#-mk"Ġl=U҉M,<	N:X`hfPJKi(M$RĘiGemCJ` Ly$!/k32UAY'zS>ā]/Gc吲g(Mݎ,	82ڔ"p:3ha!<Nq3,&c!7bŭDÉSvVZ20
bNh7x	*{}F@h'*6>*zPz8d%&(NJf^:vL/HG''(RhnzV5fxy	&XyČ7p5;^8^Ww9RgzQ;cɩ_8`B}"שbNw2 ՙ?c0q~5-x֎O&8>V/Fs0fIjM݂E	S;<[UUZҘh<Q]#<rXzBhhQ 7HIЌKmtdhxs
!e\p-RF7Xt0HLbIm몃J(5mJY$fqTOl8[	aVjQSy#@YsE޲~h၀='ԣ(	NMRRR7*2>+/7QH*"5t\mZ$9Vt+r5(e5uno%*;ZTi/o
r>I.'µ>[i,KJהijEL%@s|GE]Io:G<4G>ӆzt(4{h $ѩFZwAgî8=J%pzlDSQSKPr$*zS{dI[V3-υd>D䬞
[C0П]:hV<S㚝ٽ(VmYZgd&$8Hk!PTc321?A#S!G
OlbA+KfshvYV_fb6t̸J%g)XY@~"<e\uf1pH3/FΐGE=ʍmg9*(YK$c*ZY7hIܭKPu T
fNkl_Ͳ~KD<f.dIynVzU!\jR4i.e)^`68rڔ@^wQ1tΗ6U<-J]b#Q?q-}qy.ybRN%9lmz@woCੴ'_+npHJXܝu_[X痗̢
^2z"m}M%a]rN;dNI8jywiqМQ6< ls'ē">qj ѱi3<SJXbCk0,4=.O焰M"9%o!)[.hz[nA+^pwR20[4*9<_A xv-&Ͽ>v}W1^@W$`8X-ҨbY.R*T-<;Yk彚w)rDE
w0,MI(UsiS@eGDsdvi!
WkE+jx7P@bűQ~գv`OIþKIHNG }
`" 捊˗Pfmj<%IM(l9(͡jMet<6NJk'_LXmE2#ƻ]cIH*QvkJ)/-U	d`ƛ]mV'otD[V֤oGmamYN`X0n/1K̓_}ݯ?|]_,(wTUaoq5G:N+
hMt]70K&?&5
~+ђ9r)!vg%n͔"}}RirFuڠ~Z /y1LeugXX$;vF@	!PNj֐b$u<K7^O "|FtZID>Ag ,?*NVzax<2\lۭr{a2 [1
3"1eTZ
Fem@""*AmQ֛ٳ:g.a*L0砤uGt	aϱI/E ն ˻}̩$e%udcA1Ne֖TW:˩ָZ_7IoJ"րEIpVM7gGroXSr.ڀ۬ӎ@2e$TR%򄰼Ve3aܡR5}D7|HG\RP'v,dJR#+Ir砬ak-f-g%u=lS5^;Tʏ~hc?Q`BJKe@˲ș#0NFm65$r^uInj2[oApD%
\%|RȥyANvòdKGkHJ]ʍV4Nع?ĎFP);'9ǓxWd9L D⛥8a˂ړP  >aJޔ=#Xi蠤pXqH.Uc҉kl3i&lbڳ)C֙eiU:ްJniL2eZzɺ kʜ"<%!gNM5omnDki$Me!Yӓ3K ؃KXMi1ʫE,B 6MtV60ESϾ m0Iγp$WZ4flM$M	yhi ܏ɳ/&HpQtBPھVtM)Lmٲb@9sgxc!Ajw8y\}іA35eBs?/W8{jϪ]M?Qm]Ki䀣P}@%GGI"t2 -q.6Qؔ#d ,Wx)ߤh"ڧRs)LRfQr̸KLz Ot!يcaYd#Y8/R2YBm4ĭFbK#xɏ-+1ޑXMN˂n%}Mє?n4dK&ÌYnpfdfO\+!<K?/l+z_5Oi֗?+m}?m#Vx]lCZr.zK]re_K-\!;'-7KL+*{6,QtSq$Qe;1Ӷ LJI*BQI37~V$'g:@ծ_k{=@ՙzRdmfViT2i̥zn+IU*6~_q+f!OfnL?lm>4owvE3F`"&5>$97w`oO
b~RuEfI+o>&1QJTL[FvI@/;kr Vs6`yM)nF-cNNFku,K=,MuDW)h̪!5?DLJ.[TeǘfTf;]tP퍽UGo-S>=Xe T0_}?\{t-&9_EZ>N>K,(pOypdq8uX	_h<u
n\.)- 96#>i@y' (1\\C%$췸_X0b ;C46Qj<@`IPǟ͋FU7;BmW&UͲ=*6jpczdRۋ`&ݍ?х5:S/ߊC?Zٸ0WfQ
TBZGz_@Ť'O[SC=ET頿8p`G9Pd(>7am:NTv;UFV2=5@oc(w!fJFk~ȢswhX@Ͼvޛ_ۿU)$yrNc{c!?p|Fi³(O);FpStk^.'i竛fGxkBk࣍[J$۲yG^ ?
tE, z2K84䋨
b5RV~⊑$hE_%n
G$Yl&HЖގxX~ҷ(]wgma>	bD!扺jPWuzywޯԃ0-,9[|;)pf3!NV~Vi77GWa?F1Dr捗]íwD}aVz`kKydQ^C6/Uu1XZ,܋hKzQcx̓"e#_gmf +Gw-ưyl S`8ZN@9Xʜjy@+X-R[VM*Rv!=eeT@?|_%#@)J+I
 x;V W/2,g6f	dM*R+\ps3@/YvԱALAx!)k(6_\JfX=N8 ؀`opi9)UB]21W<W"M\HBuՁ̏*צϛ`T`X*q8XşEkv8,SZ-wl86{0hNMmvlmM=x~\;u{wc}c߲fe!IB{2tZEOĳ}vB-#L)& >֏88
 	#kP#ӳ+j;Z^yf?}ՠɅQxMlW+u͌,傓8=̀B7Kjۭ?W*8^7sZ8"@"yC`qIJ`C
ڪ!6}	@x=BoCEa(ر@I>l-^P2Po`y0
)7-;M5ɔ}%FVAF\G5޿-ocduo#}ydͥ)۝ݟv켒 Ic'A,b``$)$&g;QOiQ(	@Ar8;fEQ 
(ϪSvaZlЈ8ݮeWA`-DT4qŭ<0@`GӬהp7B-5FaײvhJ R:_؛9esۑ0v~%t@kXzep?C~\<84g&CzVPDԂ6\ǷPiJ1FmT\o)MI^Dp,_\&0epysN_R 0-<pBjId;.gw;Zj.)Nl8WnG\1FagK."2UpnuoL^ ف)tD=-]4Z\lJT*IP%}S:'롋TS,g;.0'i̯5U+ut<B|=7֬tA{oaTUZt֨Vp}Zl<tmF@ 7MӘ~Y?L]hRHB{)珙ƌe]xm-9ڥC{*GUa#`8MfQ<*&S6)^@Kد"sD/`y!"E>P("4uu)pX<94n;U
	Z/ t{v1~G/Q`㗨ptgUP#"ǿWSXm,4@W= jVȜsN8=_{8RϿxj$v;ڝi3_8gee|OWhP#	揾ûwSοqwwsWοIl<ZοCb@9د|`,URT6pL+N`_N[R\,69)q-IrLIA\T
K0
UlO9KN0JCagRT^Sx׏-]=
N"ez`{0BL.08jیvM<NPՎ˪ cPSN-4۞^
30%d&-"ͱ#.^FE̙/8D-tn	a7>M&҇f#sТw&k[Y_:TYlm+L]5R-		yȴ.d#;o%^k|bQ3=&Wȳ𬄝etf~k,i^&ݫ5"SL厢[l۾$ssھ?"mucw7pVͳlؖdv~6UN`O'iԞsm!t?4\Fy4JUi3XhD3.Dp8+,ffgJonqM'lqfc\ GlgE5-R][Ay^#%vJ+C&ǃۏ%~4]dgiGսV_eѺov3OF3Wq/M"CǤ	DK&.0wIpSka"EJpnK9K.&GӃT	~@Ź򪩫Vea`C&eH4ֿ~yyer?Z/w%˓ˀ\HEΏ{чnwRUCE|ҸL4VǊ0T,#G!y4F*
KNC5EBn(٬qWD 9
q_׍ȪC. 9N'.TWanqP<Iת^Vb3d	ƒ>GG]'Y4J;n-hxeeE5>DE\#aI	,;@|rZ:DJ<L@M.zn	?Qf}2!Uqg}&ʞ	qd<#\Hyc\WdPl|5؁!bUѽźhY֢á:.TiUlZJlZ"WHj^.ZB14	r&}i0R@B=H!W%H c^tow:@X2.m"N~ϔ cS+O\ .S>_pƦ־dr.+{w..\+[U73L};i@'M(wp	cE|Po(+'5E kzrmp LC[;>>xvL"!~>x9}Uyz!^IqF1B++_鮓FxIB6r~XbnhXW|G`+ubs5_AgGp޾jo~h3\UZ
m\RNVZLuH7k|5jW
p%$`po!Qݤ340S)ukb.\QR=hkL*Y XleI̢*SODi*#E(Q< =QJb_K&Jib"WՄe2{>E	)z$l+  6OXXc"8 
czyFl}Vq$e *
_^,u햺M	zh4q-zW/PSrj]VzE+ꆫfy,QdxJ'ZA5Jʢj̶\&*P\AbJRqeM_XD_	\h?+6ՔQjO(cYXXB!Wu5pQ:딫&Tt(hAK[M<J$1ݰ533/XaDMgHtcs>Y9T:9)3X ͧ.Lѭ6SJTU)6wYE4)u=[>m*үϬ1<xis:)=j4TS0,>EʇhΗq4wh<Ż8&l(z(ʀ쑓a)<7d"̤^3w߹{cϟ-ú>#;]_#AXZ7h#^G`w㓴N."D`*/Ea8XX{fp*o(2RϵQ6-F񵄕J&R=.FVK3Lؤl!<9?OqיU'm]BWKozXx}UV_pC	q8rnen-MnseT-%KiSL4isBdkFHSrUY4JFrq1=u5	[p_mPF_$1FVyB:zZ钙ƒ9g :.a.MJj7*25ښeKHmsZaXMD:*9"7=[	io'Gq(9j0:[7Sq{:~@#R_>g"
څ&THpJEtkg_Uzo޵N]aHDM[%]~&C%ğ(:<9T4bܕL)?4}N5
ws}.mI\	5̊a2rcJ	TR[RF3i<T='XJYm&Sl;?Xb1I6ϊJHqE^wr1Iؾa
;P`OE52ۀ<j?4B.w?R+a"G)q4PSRo-V|w_ߤWy7&%|B$;DyH<dK}	unJace/A-15H2Al2O-IQVK`RqVcv )հ$dig
Ue%([x_ݣ(([=գG_v)ܺ	r:}THp<Gy|Ʃic8BO#Y83&he*Yh瑂[8xGT>wmD;odeOҨCL/;b-4!L7
J^Oi)-fRF~׭vX|v6Hh
=][hE^.7%4' T3G7Fjhs;2G?UoC4oj["mz{G7𩽻Boς,#)Oؤ" \.!;-*K&%+=ab=#ǭǚ2զO23&k0|<h\D`9L$&+")
{8$7F}atsi%60nBynb=#'$X~M<ŹIȚ51%$FZAL~ξ;Td_qf%Vaˍ1Ș1+·Y$.@jk]XW
7[Ji-\ksW_N)&p|ƣ|]7`Zéu\1.o% RG0;jQƬ i^+M
;%CjW z)|B d%@Yj$FH]d:j@_1qU8 cfh8tĬ"?y5(Xgd=(NU)t[&رelbeQeˮ!ZKyOVCq#צk]##B<b&O<@ͨE}Y`.F+wY/z|j9k谽CIz
,^뛊I~0Vv\sWcSX\ݐW7hIBA9ڹ\qro[SD sXn  q^	Ss_ajgn^[8w]G 䐾Pa湏:
s/l<Ӂ^TIC}ԓv|9K..S$gd`˘H1nk*#ҤR(=:wyoq&zETPL^72Ue97@w}諒cf{UQL?IbDᮔ}Ձ@̾;F)7K!I@#
6mbÂ_nn+TwjQ>5TD?ش/B`RiγD0>q>ujn5\Ptb]_tD;&Pvs5\	jɐLfBOW¿T<&'lkCT1+k4ǳ!)UU;TU_U+9!AV~StPΆv%NƆ{q|.PgLw)\.VzhsϠ|a+J%|[{vpޫcnểϻ/;o:7t~{KHaxD]p1)ګ_7:ys~ljOm0TVjV_hةYku[ԇ.Rp?-,i
(2jfWra?d+zĖYEĳDYE)nt>%^j[0qB7Gj6G?YND|_بRSib n{xBt
nݽ
8H	h,<nLNpk뭇߷Vւ啍S0hrV++ gr?T}~xyAFZlIAtxo7tOb׳61!혫}wvnWv.7/*Q.2mciKE,D0/_Q2m{p%%+݉p4EKTAk	YMŀkn].wG&:1^)6XUal3pgYt3-BK<2}΁h!uuP""OV=l2jC[(n50ǉ>pZךA6En=n/	e&ڡpԢcۉTϔK2ݍaׯ$@-$V[qCAWu,x	l{LG?-vKe3D/gvK%HEjˠdWU`\u7>Xm+J:={<H9\FA/20#s하v䆠ǲ>JnbhdQivvDߑ^C3p|Rc
X&SY_ƪnb>!Bkz*_Z_n?V;b̿j8{࿣+ı *TL_OγbDh%׏+$<.3xa6NM>Q6u~x$?g?TiKM+Um-w	U(dĺC77U.4W.}⇒	o~1q|Q
b	FR%OcY	=fA(x8ǨEVJwN%<̈́;"9FR.C7J%iuV/lv	
_]ӛ;X'zQõ;TwBc~<D'%MyPFewr<L92><%mFzI 8!=bH1+qtӉmӃP
Zu}y"$uFq6lo'
xfW6P`	^؍{d
^*%pCG!XTˢmZti/	3pL>(qy?ЉK^-Ń௃$;K0kSO;)¤K/`9|n6:уe˸EDVW?/$I񎴛wό΢Z5̄RdUBy}×{Ϗm*/e{yB@"K؅?ζYG.[Azlqf g7c^j5ZG<:Yϵ0{/b'k;{'[/Dň4e=RLhGtaHlqElRvv_tiw@|Ҳ!ٮs#E55睃7U2|l褷ښΪ7=?|ѕ''r_	zYh]]%6wemiWcecf|$oS䖭 i:B4ӓ-d%
DiTQ
á	,{S0_^(Ț#>h|fǦ"(πn"m|8XK`8$uXUO
ٍVD!L;O%a#JKɷ,OՐ8A
{Ȋ+xwn!J`>UYAB1[j),bz@`\%m!W}3܄hz.(wYh׷XG|B21<n39s4`q3ssO+z~!	f[&Slu UjrP=ϝY_
l}Y$`V_p&Ͽ0QoY_jfaUxoU'<WZ[m]nj@CldFCl_98Ī >y6,,k;Vd~|_y<{LOc{yQ:>\Yr,fx(I4B 7ez_owK	ՠ9tJ?`	yb리
Ɋg6]\TI	d0QO;~t}R#3BW6=_i;
WW|pw>_7+>z#UfWaϔN5x&$ht % 9sjU}v~дEuylf'#W{?ޟWoM*^L<r YGmB.o>>oSOg饘p^nU α$ &A'}/_o1sΒfm~~?o?{6lγW?Ž	 Xj ߽:}<oOq؝Yw
(<yvK	ǝtX9x=x~^683;chw:M :8;.:^fC@)vY HVl tsfC`J_<aS@0zn1} Q8<07
f[4>oww}J8=B(飗hrĿ:K!
3`GI1,n$5=P$^8g4p̰:I>r8Pl2ÊyBNv8+ 9䦹#\:׾k_t_3tU@#룕G3G4+lI49FAJC/&);':hQ~4]ڂrDl*bZ?vz[c9L
h/9:\67G)qF1e~Ag-:wo Q*O%[)V܎Ϩ
;dETYޤD򵨐|\whjE=N'ϸrT~d&s҃B~e8FWC 攲&hl$K=!JJ(c\1=uQ5Z\p}u.V90,BڏU?8`a/	1jpzYv#D]RN\(YABnV^M5h;nnZ)'DH;rZFEG*VP8<0K5'V5,~U8Z!0ieB Q.7?У'յ6; [6&NWů:'V\FүaS<l~߂Eemfd_$QhPd!ؚ֪jt OfyV9Lu:<LP,90]%`Jҋ3?12,S4#AFgJUcHxS8yBVKxY,G*x*[nX8l>6epwn[.I<howEeƩQ' L7ucUYx tŰGvWy)uC6nÐ>2>sbV+6ߕFEUFD+dyDi4ھ
|10Gkl79!E#@pjLՓHq_Aqgv禎=w%ףQQƳ\)ZTrkn5zJIֹO+~=ёg^kЮ2]tSNM2Wqr
g\͑\_r:`p:7P	fe2c/ 0{hVUpLG^%ՃCd,AuHl}jgemP<5y7c?|P/\~Kusp;BAh1z![ުdƔm:KCwb2+9R3=_MO{Rzb1!iW'(J>əxҙd<V))=Am~tr0aiĨ3E;U( ]񐂎$/mÈ^`Z v\ov;#Nuԯ9G\4/
^2Ȭ9ў:  hC>kpOL?PL'c'}e`W PW''T5t@{jݫsS-bQ0R)1HKF'
_*Ҹi0?i*Il:jiyKN3[$Frf5QRx]-SB2>plRDKnnel}RҶr+`LaOP	NM]hp'd,\.ReܻwgQ֡ut3M/5q^8S%Hn=Ek-[S|ȫ&CH]Mو)A~\`W,,m	q99)w)ȼrJ.c߷d"]zVEϩsq/G{p;ePnjm,t@ޡT={)os);{.{R*Sl'&0@(a?$l$cbA!+]\ҝfl'JePt<\/7cQ~Qo9=VM0'Qp6Of3zMRd8	ݪ8;?;EއQmn.ヅM\'mO&pOao<Gd\&Ap+[/mό@,ǈd|}%hl|$m//>?>k%?B\(x-Ar?ɘ^4d&#̝JmCC]D?0&fb9l~#&kwo࿰g׼׼'SZvfPIlTCo{{7ejNM&%Bu9BE(\d'0iS$ϰiᑊ	@[{ok-."2WU>trv^yZf!q֋..	I5պWܰ:98E[O}΀U:ؓ_i}Mf:<30)^@j&NQHq?|QBdmZdN`Ѩ뷚MfJ UyD#e	a;+TşpRIQ۝G۳Q*X""|;Ŵ"tE[QPpϫa8/,@_dM;1a tX苼UmYtKx4B0SGus5	.jA	%8"=#/+7h(U81lArsDBs,(XHp}i 
ì*9{\eйZ5ɛai3D|$HI;{:ݨߑtdz0nC>G=	t!sSFנ'-v{dwJIɓ*#'n< 3;w|ڔP Є&p 99oSazF1RHә֕ORB T8S7:36x

[w1jjCٍb5!)4۵jΞ{f< Lj69H: !
9Y8%kc Ƶ873!/4H]HFNblF>8vƦ0ߚJzay;E#pЊҟ2gs`c|v)8ʭqyA$eZąd$%U/?X]77OŏX]7Ѡ~TFTAyQ0kL5.jgH?_Ӕa kgLa'W2[᪘o,)rP(X+2H Gpr"[Mps*&	)p)Ѳ{!$"Kh4L[=FCjoK'<K33	bn\2-a&.-'847Y{m@D"B5mϵ.?uCJ<g&Z{+7㌾f)bK8Ʒr+V#4y$[)]Hz?\=96Uv+DIY߼Vo7UoV՛c54MΣawT8dMa2b7Sʖ2!3rUX r|4%,lV[_+ʝE37}[~r
k3;֪_%,һ;1M&6UGn ppbݼ:jUEr"&2۲fGe1GO	^yvrbΕdnf7b6tBbƗ)
qR1Z*/Ӓ5Oqa8uiϴ1QrɄdDUt3yP7a*_㴨GxpM7(&<hb0bxLR(h|Fw;nv9*HZZ-),ߪQQޣ?6f ʩ8҄F	pK?%9xɿtWN.Ak?7In*yfFw pӝOp}"͉ s{0w fv`5+I1@w^z	ݕcF(4<\0s;kªl=U4sh)-<?o$^\[i
o6I;kuF.;o3˜^1hw<M?wыGD=2:E\AnArzu3K9+6ũf1;VߋnD;Gr`V1I0#YW#k(DH=vC"]GioCj8"j'Hq4dަI 3& \
y*l\G4nAkd{g 
3l"8.U.T+?Pkxƒ.LFxl'dDr]ZAGwU>D2sY|rǰ
*_àO&QH8˸K*YWkݞO(ҡ*E0a{`s3жdc.|2M%a{ۄj&õ%GpL0GqL(M1KTece2Zsco1ۢ6mwrݫXddr
E
I`E+RCL.?*̮=bv)]JO2F_1H*ܔ&iClЎ7R$+5=/7#{ZcHU3xݒLBݕ$B6zaЩVi	oگBtڷm2r!gk uc"̠/#UQrz<*Y_ь4[.G
pjdy_k@Z3o(bqWƼ_*Ului>2 f|D}Fn!U=1{ĝNQ4pĕ*-UI-iVԄKYcTn15,oGqjdw-C"$.#}FCuhfHьQ;8`Wl00=z5cZx	P;H>o+H*(wZ'y-uj:PJG3ˋ
Z(LS3?RsQrP}~
k5~
9!?"ZsG)-%hَNg6чXy
j@v&ÙuIBT9!8<p3M]fvաS;cbSS8 >u27qښ=
<Ү j2}B[`ݗLISd~T0w|Jzh~eRԹ}m(wF>gIO	hI_
ZW6rL	~őhTLl)bl}Y!$zZiw3;w?1柙r76nܝ0/̩J2 p<Ds.x~y N=cuNt{rB7ǃA_!QFf$hpf_Z{RIU?KzD8iBX5I_K8%KÄ9W~n?
?bYGXݱih"8$s12eo{/˰IRՔk[*.L/P.IswY+ĥE\L˿^o^&4	1)C1\Ndy{FC8!~o|]m,ϖjΒJeVɠT^'3cz2WQv(Vzz0nP4u]f:ObywCAOuW~FCHlwߩ:UQlc;`XPu6_Rp(+cSQ#"&B)2,FJ!cph}cK?y[`ވck%@jI,ETKTӺKt@*_9xcPB1OG9]du6bt0)LabY*Ļ/:pY@8=Hz%1h"WO<O(sqa[Lp3[oLϽ@yǣ^Mt?\<t[(k?oUh۬okK'Xn!q`9e)`؜sh8*@;	m,3dZEX>kTJ>NCPN
MeVuFy@V>=4[=[^:[3ڒ&G+sYG!e',UP5o	+GLP}x^lGI?FYKn)5k_[@*'	9S*:Dm!OmG.0o&iͣČShV$%y`ZrٔXܑK[%
-cScN䅩
zmk)Uxeԭp#s`MuLvD4NƦDKdok)9 x|wz7/+h:zD"Yd>&M69s1e맏b4 &Y`5!lEe1ay_,y6aΗr{BɼL]DӋcAnxJb֘CؾA'ES<TȆ~ XnH:r|Xh$IOS;~/kI E,v8-oq@^zW@=6 2gz}X$u'oD p:FÊJ|ښ7VL\wA>w:Խ}*}̩ztʍc%Q'KrNψA"SчX}GFc|L"FQ(VtWy&{FwpsʣP#eD?#y@Sz)/cn9INŽ:{E9E˳T'Cs#g[ sS쿫+;7ijZ(EfQ	h5*$p_r0+{7UGݩN61ÏG|>8n{Nqf%
B;WPA-1_Bɧgrʿr"M6@R2eI.9_ebMNR~c(!hH+	%m?#@5|q2 GTfѱ>G̬[+Yea2z)Mw.&M2N£3KNҹޖ%P7~H6X{sM_*j\/r5-UJyGѕ;q`GeΦw;@]0g[V@";KNlJ81\SUEEgS+w&G:c}"z[/n_5k{x댆'8ƄV;51F<0/}ٸPLXC-8>p) * T7#jVK)/t?9|4qg* tf7*-pp)њ?\w|C.rEnLUτc?zecMH_h7jhşx͂w\Ol\5|Jr;QL
hs5@^A"Az[J6Rg;(n:ߠP7J{Aן?}9t\+)lͯ͚c4mDrA
aF6]vu躠$=TƣˮTqbēɚtq1P9zx7v3y:{kBG
aey`,=0P&ȣKlZSZăiY抱؃M|<
7L`lgg:cU_tڞp|{wٟ\JheXrE!W!gہi-wZ`8{aNl_F#rz}IjUҾ]GN^!C}\fѮyr u,fu@k^˒9s3؟W4λ×{`v9"Q4l/<)(:Eg${PpU
8^BJK0@Ŵᱯs3ndJ&&6 9bjXc%e$s<kk<:I^c! AI~6x 1M"TĞ !c!'-83c0A8Myu^\֋O@dT5܏ѢNzYBfg)̩RA?~]H}y8#|R쵣A?s%<avJ5];n+[ǢSw~ /T籘p;JD/[SjY)[r԰c)pG |򄳔<uJF<pQ MJNWS{r6%<kgw:X⵩|2?FVF6`GS5>űӭB<2FN$E,#=5T+oalss#o*n+a{䇩Q!1`DsRCEHA6~\{vKql6%DX])Klkb> #?Z;ns4\7EKu#Lyii@2DͫȏzLJBh~̯,+u[*M?̡LBYBU
(@QqAE.jP@)peI<̥U`%ģf Y5 !̆e
Sf1_vF0BQ8z%xa{o4٣*-<r4{ieݸ#/dR*bΚʴN@~+%ku0"/}g}kQ?й߶7Gc͋"/g0LG
h"s&Rur$d		:as<~&<jhn3CT*BrfQS*o+P45c>0"Ldi9D'VD{PnN9~Wd4JsCTr=e`/
	j1㞵3sP{Y2 o+W)a~guuK{_ٳ&A;.!~64ʼipeLv<0f>73*-gl)gZ&+p4RdԹ&Ӛ	8^We QrV!	%	/ƨb
Kd$F,]m|ڕhx盾Uu^w) zy7EdR(Hf7dE+b<'_%e\Ɣ9a~Qs.R$UdSr/q;_H=}?T3p({i<ZB^JyI&\d&!y <л&>3@&9h;{JXV9yR!>S!yAN:k?Bzc#9Vv҃9x^\XҕՒ0<Kyǁa*f&^'fNX/(8PO]{8fB3!/͜@0*5\A<'/!VO+s#\W7b8MYzhistoeGAiIRU2=t)E4?'S;ҝ/~rX7<Vt`	Wa	7~˖˼lM1C'BUӦwHs^JD+Sgv sk41Kx.O'~BqE{:upSǆ2}:9FQdKpLe<Lw;}]Z[ǜ	;4!+,^Y%0vffᣬKU9V~&ѲgqѭP	 ]3kA؜XHz.-@
}~v
)PW)D;dhT ݊eFPNu^G&x h-X̎8Jy41{d_6}ˇt	'_qOŁ/8gVuxj%9)ƕ|m3f'w&5l{qdٓ4 2n#Ϻ6ms
)GaW{?ޟR1U>ji;5YF@6!/%Njs h_6	LsOؗ̀t20E/}&AnMtzKy;@`)D,.A S*JG
q*:6=F$+ɻ/,n_UT|]e\VBej J;|_`|-k|sꤏ:&RކVQZJe6dnXwvcAFB"m[ܤqp,K ҹƗ(TPVH> jHYDlQ/{u(@<׻ۯ߾}yv-'ׅHio1}д[Z!N4pSK%N47*~[a8^$ucs|γwh4r+*VK\[ҳpTja	]Fw +1fԵV<hH>٘WAC4>L'"N?4e@pC,:Q'X'{Q/=0TR)=[`̎Mҹ~z2a<2sƄKK(IEƗc`,0Ly*3ZV)&QW\zYWiv{>kQN-I\z
^z쉏!g)\W i&ch*ÍПhnHD"	]YD s]K7cϗ̶'c8}Ί<֋`~뢚kMHo<#ul+x:v=aW+{h%W+s*w"8h)ZXE!W-z|o_ۙaCVXRQ%gpr/OpvDp{u7[sVJV5Ʋ{ygGpyL_C~eƣ,Z_/B$׹2XpxׇՆ~.z_)Fq0 "Y^뢸ʉӪS,ZJX< ZJjg[y-e{Pu)	fWxٮ,:r[~oh:Pe'hO''N/{Jx6ߴ+d~UdYbמ5A=X(oB2"܀9p>o
:\K\_ulQ-@6:lvXۦfU
~ӗmv~gT؛]Jgl .bgٗ
r}l9N?vay|sG˿{W}Y>^z[s*xb(nar~1I
}Xi\Q{4n"JZKa}_Rw3 |o?F4]JtYʕX<>,lZs_)g"A!wTcBGZa]P5,^hbb<;4b9 2udyz8aR]YUìWؑh}IZ"U uӬM$ôTjgҕيwK(ee㾥oT8*:j8]nB&N c_]HN9(eYL-*gaE,[A$wZR&9O!O4DXX;9C@hdrZ.UЗ^:G#D mR"0*ECZ(+aEk!-bN3lv>xyfe&26&K=|Qr6Y:Szy~~"\I$AٖseOBFr(jAC5s6.v:9p&ĔzR
C눝ERP1W<q|U3cM>]b5'd]FeD5:gwHgH%xM?o@'K،u*Ŋ+͎C@=HEU^eg	Ŗ@.%v	<jaF6Xs^]G~+r+x`l[5Û"EXXi(L07w(i5c%') snFF*Pg0LKC{:c^j \V{<f0J"<]+[htEl&1a?cb]6\qf.s ݽE|깴펱FRY7{g=d^Sd%vQ8ƧaJjO(߁qTr6$QlV#C9sKⵆ\4(C!@9ǂ#*L4XcwHW!`5/,td1;JwE/FW)%Q{:kyߥ(EeL%s~f>\BH,9i6)`"B'<9}!tGƙ߮zN2ὯL)V4\e_7p+kBcfjjh,z*(\ܜuA]T|
fWG+yD1E8Z )(mqmJ\|/HRuKX/_5:H$<eTg<"Sn[o[|,mqxGq\^8}w[朔ŒM\='l`r^bd0q[C'5C*_&WxyeOΧ)iӼ`"jU@pj`]yޒb{Np{Gv|Lݑ((0[Ot&2ӱP`7M32[5cQe;#D#]#??vq9c¥cnDThp*۫܎RTq%>l2S0%:v7P8J*Có!GԇeJζɰ7,Xy5)[#$W2M?*CtIguQ.:{&Lq+  n:>#+I$tŗZxdb m/U!2}`.v[uuka#'Þ
C0c49p{&6'8ҭ"@iΊcwv6XgZؒ׵rKqwgEucUL0A]Qـt+ QXhL8'  dªQDI
Kt°Rn嗖ϑ!.)oU|DYr)Y7jɸq ϒ$k|P,ӐM"㊾~(E"&)eXu.I5˝\wK{K&)NV(KsWx.vJ.88eN,Ccm{dvLL}"Qe{Nf]][R i"4,sFUNTah@,!L٩&PcЖW@U.ِ(XҌN.łCd&M0مr:.$*;sA!\AFZKŁ94hPQ
chE"v"1}j4Ch'RW/W*&K S|7"b(<"٧,E3{@wIIx@>TrTziǟ`I^[]ƑtQ=+`+<B(%bV}'謼.9a.UϹD^KހԕEL@',+oἇQXl&$N	)Ov[6Y{FpfaLE͵DbxW牾4u+Qw)`rH;[dAb7 \2TfZ]r	|h4LϡS,6߂o+I)7eW ctRVA㣓eUrϬ(8y˓ոtCe2IcdI:(,18yq5Eq^S`ng-1}TF/S_SKD~HmHR?PɐXCH<wiiEx?48nCخ0P{A30WdDH*K %7b
1 q(~ޝoe]O|wH^ÕZld&-вYR,R}A~{ǣA9ce WEurHק|C6e 2p#7s,PLDýݘB{M}fAe`aC~Y+xc\]h>wPu;خ20XoToMfSVL^7e͑0MzR؃y\+7KJMfeee=48nC\֔ùYI屌<ȍ[/v#Ww=:,%:ذSÅA?+H݋kƚT\lwt~=|yi9=_V8$3MvjZ'dH25BD1DfK,o2~D)Uw Ug|p>
a͟R"EƝ[x&P9x\6=-vJn9
<x@:&'dHM*rc̣K8ȏ1\[4llKvi?tb,Vx)}#T׳.rZ[8ҙ'H[MVYv̳_H1VX(ͱp9K:G.$Yc>
D+x{8$I؅"y[TO:u)OX4p{)7|!,0P-O.A(N?KOmUV!79s*N ?]BB/G`0P"0YuXȚNF ˑTK9]pOІއzHq3+_Y/kHZe}wrL]BG'rWtаMrh$e~I;8V^m޲/|)F!zy5zE .gTv>!2B螥`=Yɓ\16Vw4\vD?[ӟfvٯnOb*#'tڒW:}ajJCvpρ kRtNq%鈪kYMlV*%Ha^)Aݲ#۝@kԥC[K8fvsw	cᛞ[Bm,.Fi"wy7UT^RG:Pxp0$%d[x|<@^C|%6Dh_a֦sA	:
̂Vy0dmb9Tˆ`B&]EwW{0U
΂ L{02(c0eDAnypc#v/(\7&O"u˕)BQurZHmLy!~cvNpni4='q(,|5rʷϼ%vTAZ]p]XoJ)}V)N)V^?:DF*jؕ]Yմ\6a04X`v8mVs*ޢhBSgG0ĕSU$zs9s,qSEHQdFCgaiK0"ɂAMx*[WC 5K-)ʄX~GDQ8@;(s"`+?Gd;a-7_B=.5]Naynhl]	u7|NdnH	msGEKV(X$/kGق՜XwT'P?]$y8્ xG 50bƭaw@FP<l\s9su+(Na笜u4e ǵHsظB6QqTODWr$9(WVG"fD"67ˏ7ߥ)fOyGzY9IHG?A*|z~KHh{!uYdM&%+jt>``aTcu)xv2ׅguiigRH1EdV/ýr%{EƅCN>=C.~C*#(ѢXt$FT*0e[A3k0~řYԯ.ZVM-Zt;tuNq
z8܉?@Ib"[m>X#f1zu8U;lzj]E~N$[\N?dAz&qW~J5(c`}}=7x{#?]AhVgW{\WLً"/3=/ 1g/̎?ix1>W1]߷ot(6U8}<\]y?V766V?WV7ug,O&,SzO_ߢvXC.]bYP>[Uua~̱+@%TzȘJh/;ǟA&ӊ Q3{*qs5읍a:8'.-BMn{5D6Hzo/8D\sVtRA-%L-xsxįi]EzQ~)l\bvӺ%b0s	Z܋|;mʣG>zGT=E7`Vp!`&E`UΥ*"uZ	rK	 .D6l(׻KU#l+*DnPu=.,xRYEM`?ID_8kxpb5!DSp' iIe2yc́m2A }{ysx}1s
e1c5MT2@ʩ"唁Z49W6@30Ӱ$K% 4n^ddxk2>Y?AZF{h$CΕ@3a3ƄuefqEZ#`㸥HrdRt,kNzkVY[Em hZV
?бa] ՜]oku8.jߵՋt+޾['ɂH5l辤 Esx,@~`v25l4!>hhnbU1iBSd	l: 9* ֓JpZj`8l^^P|{\%ͬRU4Q_U:i0!;w2xխ*>uENTq>HAjq
xo'~ZJ(?{6$
g
<Ӗn%nǝ(?YۙYۣP%1-$uqo
 	 %gһ}>g'Q(
BUAڲ0 ػ\dktmS%@RXu??=C$i\M8F4! pң@;7]\;g%oߝ^{7g̳֫7޽?;{N^'m7FplwT	?z7f]ڨcd})L|˂xS;ٱeSjY-cOo^/_鯳y?B'f@)#Yªӡل[~
zAY<,G2eU5Q3{IV)H{۟FUF+Xbm;
Pczv_H 7q!#+1~KϨa[Dp<n,O5>q3tܔ漥9Er?ƛlՐ;yq78t.k
_o#.?;;`џ?<zqMLz	RS`SS\l-Bc>a2/X>^[=-|h<2 M"ySy3dP7#EYVirgJw3J77a[颭R3OudYQc7N9ʶ%E`mG:̲Ւxv%λlK-
v	M@(5EWwcC'>≙:Ms!6(D,+4ZזSE:Bpf=P@&XND{R|HQHKj/7S绠J8rOo3}K!  qfK`ӏ`fr(ch ^gOJDu%K&-6*=ex,x%Q^BF/A3!{Lg0 Qϭq *mG95.yxF"uu:kK鋶9!Pt(`Tcb<),lqM&wMlDCo_l$fa6cbp>Hq倅 ʞ}yBJ.s,0Scxo~:4e*AW|N{woY?lc&*^g?5Q7JGPe/ޟ$;zOe6+	tᄣ8aJrmXzT5ms8FH ǍkkF^4Ix*$2tUHg
Xi#cjXx+MJA^@,ئ2h}s҇N~8YMTVRQ<;cmJq ʴGK"Nzf~,W]׍lf(h+`6*OCt> E
'iF!ȡr홺1N)`Reŏ̀͆)xB5\Jn:+Qp1Pq0ݫ8}tfGNzI*ݘ%f0~&?J Q- {ŏ-kdܧJ
SiQ+Cl@I~^#P^A]5` a>ɊóOåtTh0IjOn#׺vo#ĔVD0FKj 37JEi<7K[yMd4eǏ4g&e:B6XA9M]_!iR V5ޔ*<ʆzrAod|/Mgt
> O*ܠZ#MwvCf /(@ăIFjxYv:[:0HPcp	u+s*(Ԋ1("
SF2)Kd@UԊ7.^${8KAb<S,{[Q8VQde$\0UqcWJ93C=r]
Rï稉:Ia'8KL8VBTQe"IU*IzZEM*WJKSdb.Cn'Z,*'sC\3e%י,:H;GäzX`$ѨVAFFUM%JAM܁XkJT;;Ú 0Y8Ry#Uy:ɔ90/s5ȇL5ց;2Q02
k,'HHTaFlqgbL^#{wOTwFݲ˞a~*7Gt^8A(dwVΰ|Q; ЌJMH'j/(Lt#l[Ljg㌲S/;X,e!KUa
¹2´1+0^ߚ˺h0 >kx0Ť!,Y+
eyQ6OpE-שp
\cуwvڬ37qbʣPV姇P\%p*vn(ț'ZYKVݱb^)fag=5L`:/J}$d<qOf,nWloeY֞*8
3v-W+HMka>"	!nZ+OA'*IHK]C[w<^ZSmQsBQCҚ)3n?TFF'7=jzpNQ:u9j`(c;O2*Ǹ'huĒu䇵ێ}	}ldU6GJToK+@:d枊h*ec˒8P蕇ad)Id=D~!w)PU`W.WUc]35j'q<dDϕ~JɧO7F+fa?v8s0IhvБco̰@s;IPڙBg2YO5:'A(<akeYѲdAh3QoxZOS㊑;c;BjJI@{A|L{lB6&Y..e*aY,|Rd
Bd{d^3O'n^MWM6t@}̾
@ٙ%jA`ٙ*b>0=GǙ*I>6!.  O2'ui!7ZU)j>U>>7͆&a]uv84+{}
RrA浆'p@uF*#Oy^ŒջAqDm: ( JD>(J,אFAB.ݓ\Ù%`-Lzw:6vGa>2I+GHޛ\SGH7pq!|SN Ou?/HWBݲ%*WěL}⠪fzOč[Ѷ&xi⢗w7׫^2>tT8[|նt@ T،"f}pj2;l;f2Pg+NLMB?Gјhu*ҌLl\!v˞Q0V	ʺ!~@JYgtLaBPQy$[i` Rq܁[p1]{7c(DWsbENMVc4;ԖЭmQrJ;S*{S%r^;P4rv*ie,F+[..<NY< 1x7`c3p||yEJ\n\>u$7}FY4}>|Xhr0hR n|l\c1Y徇|6^`R%`oHoWu_īT-؟`
 Xy8eAA@1 eSN6u1Q*^CL5cΒ %c°xu"s՚]zDU7\wk#IJk
KAeH%
h)ѰjmܲScAɧz_(sqEx#{꘼X	S贈Xu0k
%"pC@RT@`YDװavzm1Pтj	ƼV#sG{AH^81F(OAxSGA*Ad`xgoLT@mO'^I*"1U6~4L[IXua=I.JJj9T_Ugb4AF.{<]KO±oyR5\c6JxDNs⛕^T:GGNRqêB`LH~uS.uBTܴl>>U`;ΤPkb@|a(.q47KyZɂ*s(:P܂e\k)I\6
|Arڲv_]kWe=f~Bמc	vzGZ2aͅ^fC+D65A4kͅ;
J"T>&ݐ+zrnVu 0\UqZU :)!&*E{J+ҵ*
Gv3,kE臗tkQOC&w!3
H1pK.nD􎈘MwӉFh`&:\A4:rM\d^ R;*znv+	׌k)،m뮱(`O5	4V}1bw+F,ΓIb;0CG(ݝ0aք|$ŏЏTQ'PQNKa+LINb'm3Wqp|TLQ:/6_qW
&/\,H)KdJ.+kwǕ
l~'h=	kbbn
Dن.|Os ,`_{uQC\_FU(j&61)<0KNBgNN?\CG(θ~$H`;,ŝRvs!a}5}T֓TfeOax[Tgyi'\pD,3W^։LY6_ƱUGF^X7ĸ`XHq=R#8a3AOѢv7[ͼ=m|Q;oGjdԲ$qWTuɉAX-"|U\L/N>X@5lqFiE@"VjݩG }<B
H24W~E-~`vd*#L=@;f
$v߹YV+k+lrHzCv!@7+AwlH55ƲGUv3r|*rnhJA'Ǚ\]R4j	vs@+nS0Ph89hFdPCzsWz3Uĳ0g	0uT+KPɨyKRDYR`\q20~=*|b+99v0pZ7\ Q5jG&H9)U$AP|zØ<)].QY|lg	'"5U'_Ut7kMLs|eWiXu=843(ٝ*u?V`;G8\9%F>tKVY:*%ՆDqqL9o8Ռl}j&ߴ>TBA.ik7#zHp`:\ pjRN+N]M;Oj	uábeI*y;R{[5S5'6@Y}*RV·nP@
zB
t21ȭnP;2G@LulK3
P`\+lMoFID	^Jv?ӵ TkRuo
R
uA5NʯjHEI#HNorW1fg*\>"HqI#j:ңPTb#V]İk N㵙y<YY&wx JA]ʰq-oյJ̸,/-j
NiE/Iԓȹ6G̥\ViH^d!WOob7IY"g3yUᠸcNDX?*83HclG}7}-آ&uB:gv\gA9qE]ȜZS2 |S}z^WgFMn{HS36B3*QhkԀ
J6g(gD5=5SSaǛ;ɖ>jf!LK5bD-k%ވ`jW,q\5sEf$B+!KV SjH9Plq6=
&˕Y5#2w8@G*ZVoaܜ͖H:39[f+g<ˋ0>B;7ʠlb<
2`v4DFf/,9kX\;>J(滋08HשÑo>vCpC(J͸K|X{A0WiQRs
-0O1BtyvWq~!f,)V)&NB5rd2ghiM;ܺ(QM'f2l-̏>d)s2}5UqA)>*0G	&0_PPNդ)EPk,C"GdvP}qrMHKA+iw
5VUSjS5b勦zPr[kԃzwUW2*hZQ!ˤ69tR[|$ #(iY^#u=M|1L]z駰?`:1=#ҩ
@9uߴ3Z^4.KuSgyYO TmqǡɕݰaT_Ro'ӎǣ:=y9ɸKU^J"C^E.U|rdx+J޹멶e
m@鲾_m&QEu~O뺘yo5(`Y˫_TF;lh˨Ű˒>vB_E axle/V8OQ8rCXu'q)B>CLT'WXيO;W\8DLQ7*2qʗ~M1'V;ֆy+)?2uGJ6HgRc9y?l'z;v2=ywv=> `g?	 {te߯[U6q}r~%^8$ߵJ7^ѵ,段t[_ߘݽkomoŀh!@9t}0.S A87n5@2Z-OhҺf	Y`-l27;Oom,£1BQwj˱8[Ʊޝ"d(d;eLmc$n6K*޲!ڳ|:4лQjA;FL*hfUyS5I[ݛ̘OEV6e*L'Ys6ٵ3ZH:v|k\rRYMu$c's|`Ԏ?$!)\"L])%\d8H%d>hȮX`b
6 	dmIB!u:1L (MnՑ;`is6>Р#ghh?K"'sԍ?8z{wNsIieq|b-NOON om	6{>MXV1	OHp^nZk$_{ŀ;m֙Zۄ-ն8Kq-6	VR&,ۓ#M}]@z]x`V?	|I8:#C/> z><{!:(uewa::j@쫨!Nޞ9n n`i'')g'-	˿νc sAaգOXykH$x^vy/-;v`6LsStJفL\ˇj	\t]ܙ1=0|*EO]
g*C.$,BY&scnõ '5hTk쑱r;%X_L٥_ }L=|eZHN
=¥B:amO_<z(qIR/ A>/<`rd<D(\/_d8*CSTrʈDTZ/z$*	Ŷ4p|_lLdDXOoӶԊA',~}(I#-|3	k\HóEMnH"D||2S7P,s́zߞ<;yâRAyߋy~N'OӦ mÚ?عHb=Ri?{/O_f5ateZo;=,y^H\1¡S]`GXw=9=WbR	z M7~ܩ@)]&+%U8gͯWRǴ'WBzP!B?{!1	xveA-3V?m45@|Z̍D45 я@%i<SNC-Y/GXlCU@hbr42O9>-nA6m/;MV	l_%=d$ej}_ƾHb yH\Snyyo{lFLY,۠3K|T9jHHxS8\yb6eC	8nc	"ȫޛ__6tEh=ɦ?kkSiX1C̛HOoN{-ҍ[{ye1a0W/ 'ѹaYA@,>;խܔRRՀ\j}Qhti8=	Jm'7H<-y~mN֗E_vH%E*'J9bYP7`%ޟ(pmsk  4syD;fsf/Wp
rlmnp+7f.F
v=rAe\9T,-}»+>H'OHY;='.,%%S闓eI?V	s˦8U{E5S@0-]J;sW$NRar`|F:ciL9Q
LZX.f@MymL9~',W>Pu%l1t;#E<fqKeG>2hjB#
*"{6բ|ț֋uq78GW]vX^wL2#+dMq-Fl-J%#7bH#[hL{}Vn	`Z}g#[o55:e۶lpt}軆UH]l."s	$$7"p:cnAQ+S!m[{;΃+lQvCDA|cKG+ǉ7n!wWQPeRis43"1wVVGI4K[Œ}M,;&5f2lH5/[a3='	ض`Z=8h3o|/(hIF`yqlaNҔȰEZ0V*Qk#RQ8^X_T` HZB U`مQp5vUشxLFTGYZʠI,* [Bچ/8@CoQ]i7/	~,F.k[lCz>ǣжZjFpZުxcƇgفhbǜoº_1ٓ^wOɢg -lxҔʳs7w^??|h(ufá `lgpTu|Q[NO&yd5
[x
Zދ3mEټzQi)(vqL  : vEV!/>s-Ոu8Z1ukf77F-gUQr<~U?邋wzh5׌w/^NgSw&Y89}+{Q[2v>XV"MҰ9;bܴW
X(|e;H_9dn4-s"$[U:UjROؖO?}~+I`Cpyb|%VdYxRc0(~*x o}y@%c%[{j00 `Pըװȷ_9=_Pu1L0)0ss/ u8;pbҎEWT|n"8ACfv_`	P7sZԋx;]_1[*Wz7웑*+.edoiC(6:'N21\lArbv%'W#pYR!26'-CYf_,Ha
JbEYDMӥX
u'J{ʁl=.nVkG] rUcC%7ӺUXHmY3F"ha$|>.ۋvDRۍf5=^\[-WU^!ulD5]}$&nmQP[c(@%q.=Jcl46<N^lT0d3HJ)kI>].4¿\lYC!_P|6p E6e(so<h@&ʽAnX/?bѶg6{<&[O%k<֣4zQg#Xy2|pt ͓?AnZLxMRuƖzgl{n@O^6!<twC'Qqb6efNFxm ;y' I	|<*}/wl6/uxܾ߂_Bf&<?[܆´zsqq}yqyuxpuy~|LvK2Pߏ^aFq~WuE2Կ.k3o־\s3amqMr jZanê1U_+ޛJe\q`X_5l܊<Fcd`*wt~~z˻^ˣSZ.;;rhj)[?|[zunm~VU>=pybXޯ^aG{<ECu#=5`n[2bLˊFQ{z9%D7=},o֎^G;N4Q)ʅt/eޖ/X+G(Uң҂)r\ˁFT	a4 *!1j|lo} E@΃?<zKΡWGǸuyz'ɩwtU
_4F[&"i
lΦfr@jANhy|"[zpX^$R@g	zX;,+쌚2'eXui9Ɵ~Jt#˰ pǬ{bкr݅DOKpuU,\YB(1Xdn2Wn"qHȅ1gQS58	g]D7lBj[C3jcrDpjx!C!Qk<V	6?%bUnjj[W-%G,q[ݘeY\DQO	WyGsSZ(flt;`7\<Dz.N?ZgDGkys.z<?ڱS/f1Y'A+8_cћОg.`/|*ޓEĵ4҆w+an5ܐr6Nkef=XEz	-w;"߇5H/pQo$%Hft')NͮJ]ݺϳK1|I.
I1נzé@;1u6 ixVKugkQ9f!:Op+0o.#h1(jc":ĠY%4I	]MNryDPc%,g;%YK˥yX3Yo~cAQ<L/@彼n@>T>絺
qa+l]ݥm)hY7n~[K؛2X3i<^ՒTjW5MyJj厹V/n7W1犸*y9? Kw}!;a=U&KԋxaF/|ehF}@9/̎d$Զ̚D|^X3V&2w̼ծnQViAvݭX?P-nJtQ2b뮚wfw	qGhzeyp*
lbUV7t*52Q[98vwž1,/
ՄYeMRSeu^2|`bں\IWa<U6#J1wPVQIdŘ_1Kc!Ʒ/~>DavjDݲ	G 2hynɭAUɇ//NN;:}.m]`z:6I?O>fKal<LDGT yPsdCˣ޴bIlEY1խimdm݄sEH+CӁEư$k[G#~L13ȬY/A`V&O"MTtQE7Jֺta^z@y2,^]7g^tcƀQ UvCPs!bJU_NjI)֞ax~򦷆22I0c[TDvׇ;p,"N;l:dΤp)|j!gOUؠOYYv ;o 1\l5c<E7G}.'EnPWzޜ.*i0/~x賆)HfKkWTˮ%(q;uٴ[mqyPaUab["ɺ|9:,dkd@bHC'Kx~
۲~L#S2uiPױBߴ#7'b~,qBvy*!2
NbF.C-@#N/Xʐk׍-LhC΄EGK=	p`bK.Hq.zo,p@YL7btd.<'\y^p0B:s=r}o>ڈ~8㌒UJO#7rUft(; m뎔X/q~\Wڥ-@m
ZR\.!{_ѝz՗2pb*2SliaXZD%yŀ6k<*YW'%6%H Pr-i0=5[stREm԰jM2}MIlii+Ўŭ!/̮,mKsϊ:V5őYr	Z%#~6]k<&;C\nSQlOUC9BMjmg(ҭNw2+Eb;2A6.	-iPT2ګ܉͝pqDoY7l঵r6:lo~ڸբCA-CQIj7,,o[{Ёڋ^"خnWJ3k-ugOӅ4N>ᣀ<Ч$$uguԄ1JbWL[#d3#<qJ'T1nҥ_+I"&pӛ`@c15aq,]]wD4m՗|{\(_$i/eC/i6{'PɏTPҐFUPBd5[3CFE2r%eJJ)
NS8yl3}pYjc#m]iV~[/6mk_;v[ A_U/ebt1Wۍ
_ߖr~*Mӆa~l>[$1A_J/氙[R`q0tUGw0ˋ]^6M^w`rweJ|(ǀ`d:i*>tr=롫xJR7k2N!lH !n}NLbgvUqJz|VE6;llgt@(dWܲJHs>,9)"6ðlSߩF=P5ª̼܆bz(uۚ>S  ŊTwk۝+!q#f hosoGJNeFk#=&%L(A#+k֤fv}YqXe7,B%E45YLP2<|0U@=9O	\r/{J<,Lp!HaI^U$tZVv?V06@bG*\AT(	n]-9R^UcfU8*}gz9"7%j=Iam^]8HR#[ʨK-쪝].WI&{ѢHP Q|Cm7يAȧS͢k,KR/܃}JjorѐTAαsҸܶ5s{<u.k[_-kS-*ZSuϊ|G7_/'Zχyj>; "2ʇ@=LgO|u믽+&I{R͉fDo}f@ )m=Pzm=YxF53ph=ʃůJ4$Y	T]#]_O#'s3>FL}ī{ΩiL4韖j{s>*wl@ì7g4:ne7m񜆠hΌÓ' h;硷_q@ã_;ϟH%^ŁH8R&nY\|eyׯOVqؾxL m_C#lb+Y² Agt@ТRʱ[j5٣fX~"E*	ƾG1dEHm5޹'V蘹5"	n2ry¡+'[%Qu5Z1'{] 7!͹O(ʤj[8)FN<Yv,꧱3;0ֈ'}ޒalD\ܠ<xB:|"yl\q?0n
	Ƅ
j[o}|%A2f^QX*y`+\oz:xtZhLF'E~֮AqG÷:pXʰimtiRwd(ǟT)T@Ypie{^ÈAaliӯ9tt`; "PzXb[[e3;r\mvdk8.lE:b.G9l87-[{V-ubBpH
z(,K5k~ќ{\7ѡ'쮵hj'E^>ؾ3euC[zp).x%;qbwMyʥ,)R5GT(9y0t^gZ@X:zUuk֕k'@2wFŇ%Ѽm9+YG`H34;@q茄zN;1q'G0'܅mYIeIv2)V"c'k4&, Oc=x9B
ж
a:L[iS#UϒLGI/E\+DڶvZ_E&w(- RC%7˂^K$j!<M[*GCa(0&		x%r͜@Mt<"lA=B4ϡ6k4u<ir|\|m*i] yc@<ՕvRkT&[
!T1ӟMHw&V(hn)$
`+ҝ0`#vCr3J?;yd܅5q:EQTJz5.lNܺ vR]Fײ$LPH(\^/D]Y) x44y_Uśngt衡fL?^*9]\I^_l,5!q{U6<Ϛ庢g>̭za52yUԑbdʫtj$6yDg 6+$
3\c]+VBBR5|AW'#6.|yǕ(GuyE`6.۷(*8֋WDy*Q]qUr}EzHbԶoX-F	,zbpLL-Y񱆭/goF-v+b5	1dyquqse51b[C-I|^wػbIڔ<>^NQ$A/m΃+.}n\p23C#3SSye҇7`|O9lu0HJi!"u_>5+6u9[f	nŊҲttx[+g\>hN93*CT+<ՉR	>r_ҊGz-6oh
1D4>l*4ϒVH4.C@Oc=K!@l(O+@W[> ZהL8SI;.+)gJxj]+zO/bIxh!WPfInDg6ޝ#8JFnXЅyE(mG[*)IJܜvqTSgܛm(sM=!U[/Q O%{.̐Ol#}51yNMlV#㾳aS'vY,ViˢߐUp}فsThbSeh[-p<6i,;
G/UĳGq<:Ob06o"91M]LcJ60XFVn
f껉fHB7%	R>NW6{fa:޷_ܡ#TfI|6Mل%y	=caSf*wƮBXE	#:r8!8VqGņ̟F,,mE	~Or$͡gZ2vXSMmտypӁ|9b͋sfuviHjr<	ѐ7ٔӆ^m9S:xa	z{dTOKo1T]V潔owG;&KtBF342\$IFȐR2>&,y'C4 |qnn0T*aarEr"Q͍܍I'**@{pntQR($i1vD~zWcb_.yqrc}FwOz%+=0]ٹQ?KޞvR?jUޕnO1,j3Ï@ۆK%ZErE( 1`XoJHnLBP04bI*Og[tRpPk¶' 7 ,]2'<sGG
OaY{=;=~{N8]M&nh{@^{DōQ& yPj  ܶX\ͦܰ'E<dWD2Ip"/BQp!o!Ah6I<$ty<'*$8ʍVU9:;<y~W7D&W7$3Րύގ߼}wp,.hG/9K&^[%={)MY$Jkg-kogkO׷^ÓO'0
~(gFa3qAuj] f7>zU]63ץWzozxN,N&Fd/ROytmIEFiT90>|,Ad,%rɒ?<vX7*BC)ZhB!g8.18D AUuyܰjr%?pY=FC%L c &`V =*̝RpyVpW͇^3Nhp$,ɨIT>Y`I`E5<_؈877C?ON`эf}Ai\tQ\0wNm\;& !m+oڄPX;mLΆ9۝BpS>0g%$7ħd# إ2ѿbE%GAj)^7F{3@<'ۚM;JN!vz@ w[5Z`z#R"`o z$_Dܘ&=-	wEOQa+u.?QcM	zP8jC:w;",ei؏F5Vv4E@D]sCrTl3ؔt]aGxgIoo	I5W ೛0s;',q@^|ɀXNn[IF6:9Ga_ߝήY}ܐE}޲xmEg"*Yۗv3fhn%	'Jo<Tyٻr&8Ʊ"SҖshZD_AfӪ]EO;Ֆq&.yEcy:][ AQ}E^iZz<@|6	xA*=MG)5bniFd,Pܐ_'[1lj9+n-nH!bLn5 
e~Dh畆>JApx6XUIE/T/"i|fi<zIL<쟊WNR[F!?R.#YCjņU]u7'ϏOg^n;G 3ڟ\ݝ?|r!OW.ܑQ=.<Cip2u%ug>I֑F}~܇C)MY;7()TB2ǣ{4-z+rە
γC7Oo-CJ6
U_BSd/J(BnҤ{5hDO;h\ts]_"-?FeQ>oϢf8^#j6E=a .zpI@=職§)-|T	(8xg|~2d+>.\$gBtId,Һ;)YuX6G %4@10,f@ybf(MF?!yX$3wpe~:VDK-uFW2E0mK"'0 pv(hYBrsuWExM]ravgMZ}Axbe{>믲KPX1MG&W1:#rlIKLO)@	J*Uc±(hkl*p
S_}ٽ:?
`Z*6pw$(Q3}yh}|]}iQEc?~;`%l_@ghݭGVsA-/+7Nmk+HEd#wv,۶ƣX$|vI^<c+2'Z5cg>wlߵ~Oj'hqᏵOnل-uj<B|\[rCQh	#ɋWN~=ngᯋ&݌ )fq⺟\[P>SvU18ǘjy51.%{&S ]!SRYPL9%y5l.n#̕`w-x	{i<<	%ihDocAJ6$z;!5]l]d0Z`iͽgRLbSK$v%xM+4cy>;wpɭ2|iQLa}jXsXࠩczMS X/`x,fB҅g3CpF 篢(NsoFm޿qXH\*kX['xug[0{.K䕓C>fF#Z`{8c7)/e- ʻX4kS]֖8w;'[kW}o*3>qFvRhUBCw{{X؋}et;>vRwfIIPt(sEהj*m|->>U
KtQuUןz92we%h&\㣏Mr,"&G~t{eg2%6퐫%Y:<?`ۃx@חUDy'vr]ߛxr	Neѓm?s8}qrP)$eCXgOhhS*țj4W3̊8uYC lnTO,[|WXLf$	Ì=>kLUD#SkˊbYެ!iC9H~gr^MfR~"[ri	^$4m!'<湉j蔮ON11UT#d,Һ9"Yit-7yTYX[j]E!s"_oL[1m,v4Tq_Z{{zr~blJԾ>s3P rKΖ'LspXni<{eóW[򩂏K=UIB(t[mqHU?ֱI~-z.i,I%J[&l}`<ܻkzrlk Q`Zs\AjuPܳ[kt%fWFA)UUWMXo[7Vke)!Z`$}uq	wgѯǭezk&*W<NV-E%2| G85Q5Y(p,ʐmai+k(kz?y+Q]IVtb894#ʶ6hIVнa;={z罒p~Ҷ!0oއ_{窡1&; $=-+( R'8A?ʝߺMfN^x]5;LK?XSC;t>x)^1	{L;!CC΁,aV~.{,X.j)Y	uFAs[Q%qei6.F.ԺgUiV]F(U[Rr]yz~Lc/d/衭0%"?=7]_h
Ǉh Cϭ`I8$m3͞'{2ӠluԪdv0I.R#/ KQ0L:mIJK|AUH2wS"j;`Q_R6RRfSpi汍궻nu9/4|%YwYG*U@yNutYr`oǽˣ-#,13oS%ZRso]QᠴqeFN\Sly8M-2R)Oi/kH+4IɵG4rvxr9MM༟ߎ_67K٨:#SC>իFiE`O#Z
Ci[v90_[ыTeCL+p
x+/䏍x1P9(V%8TPjstsUۑ0z@ȟ3GV9HHF(. Ֆ")sϟ8`!&#N?Μ@V$'makO¹WMnEj9{{ґ]"X9jHTx_Ĝ]gFʒH XKq,%u*;9k)'*Дs,Q-- h*Y
,W>l}{Q2ʂCjobl\# 1 P=zUa=M%5){f%*3̬ݩIا
rj~IӼkT@_1C /J[ִh.WJZ
->ώ"M*b).2ϏjrU"Ƨ'[RL
\}1EiSoQoK` UBXX~|dY<"Fd4C	LQgu.wVg"ALfOۤZ<'@c}_Q`m	X(t~)&HJ^d:jc*1o>>3M\ޓAo2q/]G'D.Kvb7-oe0%M6lHBRʊ'rDiERHDX+l!y/}0Ɲ1jPe@ADQ7L0J1}@}|ۏ$Vk?ax?7eeJI,;R%JCߖKDKPDj5bVmK^ˤ/tZ$iƈKX&*}=)?[[%9lޭ<	:zb	x!Pzɞ:AڛjH&qro`ti|"Eu_J73ey
!l{
iA]߼{8XD9"z_Z:>;?uvmъW4]='Yn³4<o*,BMgxɧ;1׼+>#`"3sLWKa_މGi`L#RTIY{%QKWè  y]'qJsU=c,Mh%wzz?9=ѫjOn2~D2J(,Ҁ6+y](v-b-&r&X	m?2Qna @6. [u=- q.0UJ

OQ+nGRRMZn!l#P^}jkޮ_ۖZ[
2U5gIYJ>Gc|K[}UKJum?LIot0Ayxݧbjq<1s1% >AkWIVy@_[n"m̦f1	Ն6VeN	.<JC,TѢxՙ]kҪeڒ!~哮^EJʷa&5Ss$GImcC}-I9sNYG%9K$9¹3r"oMnma6<&%ӤRVN1{wn+xqh#]޿.pݥ<hJlDQ]0{LWtΉA<CV&Zi:^938R4Ӧ89OGfHK %e{9P)n,0rYZo/_uϷk+&X0ˬ۹zmCI
&1@QrgM-eU)xhZiL+3.QD𔻆20`g	E3p)#,&$察XhرZz9zVCb#J<Ө@T^b.M)Iw:3ўgMd/_vG2VX롋(dlE\߈I,:h1ƁL<o52Ԗ3l͓qWRƮQn;t5{Pr ALtԖx /_Lxwʝ7>%ؔ;1H7Cœ+@]O%	e8Ӭc$;ۚ00 &uYys

-N8&-:z뻣_{-Y@n(Gޘ,O$*
S%JSxu19eE|n^\Ɛ ,ܸX:8[$=G3֛+<p2FiT✮vi5%W4zR_qi6OinfdJ[`/̜V-yI*O̊A	zRc-]D(l>11+g_J~^5شzskE.j+!uX?fżro+D¯scEtFaw'fXpq&/)![dAY%n)uN@ML9E/7K#dWj=I;n\IGD8gap*(5IMq߸W!T*JN+R<"nx*._wÖ>0.fۖ֙	ta#3O]{Gs/p"+ؾ<xмW[JQe6ި']H#൮VIG$ċv9KO_<d\)|Ybㅏ k;n96
BBthc 1imU!`Ryn.16*+ Im+mW/6HQz6D} ]p2/d|tmȐy$xVpY^JlW!CZvu^Pn#Tx{ٮ.RZZVWݡު__^]ŋEϽqGAYnW^t'WU8~\k{r5UHK)ųw/ONy:sG}<V.^axN"ϞKkZgbrYV]^@\y3֥&8$ ̅,8w҃z-גo?Qqqѝ5^}ſ./.{S_MX'ےH&$ξHmu/ZoN$7-11vwP,7"Y/-~Y*>课GQۨvQ'2I_mhȄy#2`1wJ)g,Vikޮݪ5mYjdcg視/Z(iMrM3*s=\n>ՉZѢR栒p.Xի
7exGIy'8Mzc}?-㻚foQ\Y%j	kJuȈDWnc f(We"]dllZ0F!vo	.`ޒ￠l_vkz[{0Rn
y*:oŐO.?C3Vn:{)B1Fg;XR6ݖC0;E[$#$ؑ1?IaE;HZjF1|9#&NtW_u ѼJ8[n
=D
UJNiy
?㎸7`}HJ>L.V<fCԡdحST2
YԞ(f"?,cj"VEIwNLKTkh)+d1lVLН7
EdËyI%=:>pDQc?x]uev&ÜG]R.  J^Y
[si jqDŔec}>vTm͌bTD}|Xy3Ɯ&ZQ4
ʒHOc7q(+R4L'R>Kp>xZd{zPb&)d{XvIqIK~=U\WDbiNS?+0Nԏ@'
/9;^ RVlRK+xY ٚ*.2YTfJڀaV-ijƁJ
KYmW$*p|- xCÏ`	(%S%b^{HEWP縂C4e~i
?1t8?M
nazT_dj0cE&KQԢyFmɊ% JH)<kJiu]tgɱYRc
U{٪ADIӪ1XE36cz#{9u6NfEzRّ34G2THM#X@35sWͻ[v@>l_a˾s3-
8ig^FrFcѶAȱ]K#'}땢r|
k%gk* j]|+Dwz|@Zr>:-xK|7k[0D݃Vj@~[E	9ya6Ajdv	
]!0QY"p{k*ȸ p˱4uIcZ	gip %BEBJ)-|]/gN$/R%Kܹoz͊erLR殘ICTu} L)~:)i?I(|ӕ-ێ!p4WȳLf\G'ch<3ۙ*a"
77{OlckϩyR/ڥE&C|Fp:{R!*ȏ/uހs20W7ø^-C͊t"
ƒ;l3S/ԲfgBure2Pǻ]^Lk!XXfxtmzdUf'(\#zM(sPH<GX/ ~:ioP`
 :$͔q,I|۞ϑ#PǶ
ZLߧ-5q#@U7}4*^I_tͤ_zp7ʓ0M׏箖Mi)X?艍vyI +? MUXaf@Y*9móV
I2'^
ȡȀ23֕Bz`OAzߓF$%x@:6YP6B@4 HDď  Hkݩ?H<Bzݓ"ʆ>;+)!=xBz7@F6'_')?UlHF:"QmH	p8S~ixꃱ@aۃ!.T@܍w=ſ[<O5J@B)3^;T3Շc)3^@\BVlo#ƀuC+2`V)M$q2O	?y`,IƱgt&Z{r.zov8co|(K.`d@l_$XƐ%DJUn~.6ǟʐkã]C!Mr4'AIfZj%,h0[36pԚ:vu'H5ۡ? tΛ"X'VHSe3`+9_47<\{fdzr(N8??rtM* }Us5ڻ|w{zQ|=2P{S6Tk
rE'{P<I2~Hb&iQqΊNsPIZAޗԇ_PCD+8ݨH{ߊ5iW4/9jz pa@Una׳Y>:lT˭l]ۻCk얓hkjŊ^zv8^v(ha͒v1w<]6i9lRJ;)8Дtns(\r(|	p:
#H~EY/i0١@ eD@q 'iks-*'(+(.gzZ,nВZif[gTa{X,5Td{t.1Hc*>-V-̳^+40+2l6cMfr\]Nt_:-kJxPaW3_шBq|w{t#c?c|J(an҃MÃ,k3!b(FImq(h2鍱4O%Ǡ:0G~ːkQ/&簛x^IGE<FM3M |bCvoCI(sCnd%=AųpIyb+ʙ|2M̯X؅Hp#"gTDo5g7~E	EX ^IM;	=LxBw,Z,<3d)6e،LXCzU6	ĉZ3,¹qn]4v\zJƘs͠&\[Oq̊~CS9hQac@gtŲAz #dɈest(꧈Fɐ> x!.#`MKx*EtڄF%	[P\d4I9Hr^58\NE)xF8x,S6}q'۵/ܬ>*`'稃.htQcG2!˗v`}+;J1P$&k$b9{%Mt5AR0O)&$4h(Z+TleaHfEW$cnci@asI+#jT $j}aWpBk;bj~}cI` ~kY(܃)PALVFXÚpȫcuO(K@X1U;(^x:UxΉN{u]<Y>S3 1F5ԃA>*`{[elB)){H| my&ƽ+d=z~Y<?U$ qn7[_/?.&}ΓI{mw](q$*MJ3^Gt,x.IՠNZJ#G:pxaz6Jg$62ukk|gn7EB	\qlyK2лcϹoYOQ<䓚cbkLo3Z{yXʋ\QBs3fU(B*~ksL*@Oʠ)U+3l ,Ax}cN/Bsri@?O謵+S_/@-stا<K1ѐ3Eȱx("OfM^$9,!K<Aꑲh^]8;G'!
wXqԪrGȬ$m4gh>m<㆝(ƀLGr_t	+sDpj(5Q01kaQ"NK]'!%;znZbT8Ȟ̅1єfEإ5^V(Վ#ԁI̂*/z=FG8a@(`Ob1	"бd(abV !~LreI%>Ehd70oIgMh *}Zրp.!+jaإtbc=}8|Se/n<g[9wG̓@`I#2UZԱV8Iꚝ6Y 8:;k zhB[v
sj:E\P~_K&o:]ܖh@//Ξ[Tv	8I>	`jy{(NzМ|Av(0cf/.,EPU+Г+WBBc@g׆uڭ[rDQ	laԉ_E?/6K"Tʤ1&K*x]w"GBy@pZ0 1o
bJ',7	7 ( N~~a:ؐzq7qwi!@{VZOa.4$IZI@z:Ke:ooH
(o67V,k]=YC<T[ӂr$Yg`
J9fE9Xs`o*Y.:􅤷3t5k0*+L-j{ەFǎ<Xw605)ļMŅd٫gWxg	 XHD
x
(Hc՛֫xtţ۝x"-p+gl\tXe(}99ԶJ*;;A1-] 쑡5	k`s:ÔA`k/V[*o}h=CZj&qdy0SNYd{YTLA0Mс@b(\"B6d,:6& Ē)vBVI*[L|[SDϑ3NDARxy&4*4TPF)YWb񕡛2HDzhP?u5=5ƢϪ]+4e,;¯A&
Cd[e132*dkBI,
-e6	1yPGn;FIvc.-7DF(LVU:SG=Y5A}t)lt/vRٽ,J٧{Ԡ[Qvu&k\5="Cb@gx욂cg쥱%O={9*%L$$xD{IQ:]N߆^ŗͬ}"%j,d-C)B^:g1,DҎщIpV@N,2{{UseڂWi'QLpC49ܚH-H٩k%?4aw$~~o	$KAFiLXu02E'TWZ6. @+=ê>aBLͯy?
Ehgmmm#xt=(U&孻4N -۲Y]Ou)˗}D4LH)X2JʜW,,HאQirE&h8(G
MڔypJ`YR2vQbE>i<E(OSRL#1Gp<-35(-	X72cFפ!ƾyDNw{!]uX")ta4LBP/+}6'Ō$޶x([Bha9ÒI^.izMP/LYeC8U&*g5cL7
1W%Vd$bߙjW=~0'g$יG%(]w8.ooNݨJuZ2"e{o)&6ܺBB{ҵMƮ8UI,6dugYiJ<]Ey?aT ?̞N,PU}S	NStϑf@s&!H;P<AS,q+QX~ z}USM`<&j
j[;ʔu/@w+ʟo0g(DhJ:F54"fU=ުwk߰#*N-;mtr_`߬h(%߬>y9 t=sH@Њ^28@7vۑtC0׋ E5$Y^ēiQ!c$3yPPJ["< erGd䝎!_UpШ,\=S%ewh5[ӷ\G
tF<.Y¦##PQ.]tVP$HuY#S$ُcjbr4i|ֆuU(>KIKՋٲ"i^`Bc3~Y|HKj8WG:NDGFgZּ~xs,k({=8wo,9nK&`mjU'|`8-,*ގ4[Z_u3?JBjWX<>$ve5$F騢2n1YUzdݜ KAsěeBojS>S\/0vڛggBC֫8M,Ý7{ua:^l~ۻC|D'/6[\TOқ1DdGIRS\<hȥ\Lvu	c촧b*,+Y	h3	fYg(}JuM4t;tcFhVHͫ8@κ)
x
,
%S$8$goSYwycc-閺`"{dJRm]|3-{s51\PLWpδBktӵ^nQsZ5RbT7]RPkVsx,gda!a5NA"˾7S׭`<`6O9Z<7=";"p|ӝQ90"y&*W(
[^7*U"-u><14喻dwMz?|AfG|5tl&HZD*Cr$]L&D	%q7kzwz^	.lis8%0IEI06/ar=ܔ-c܃VTzinvSvZØ
pg9Ca}ggÒtث e($%ka/d(-ij>^ve	 x<.,Օ@Wngy1W޼Lq3pkD:0?Q6kL_	 |l6/,hq%=rC15WG1Eny
(]ЉFr-(%sgk5L+ŴfI<Jq^>w5ʉaox fpfId{o-ָ|lڗa%9]H Mpv͎s|Az&Z;F.3P(?5Wo9lFM` es@Ce A!՘PgFAf+CUh}yݬLLg?/!)5#PrU)Pѓ>Lf!*?6+mƇTJ_?&Xq[Y|z	8<c:8nZSqFxC9ӳW$?/(䈼vbMUk#|a#]~o:O.4zQ{wKE-4BmTAakff4
`6s9	o&%5"鬺+!ƃ8BNײJt33p8  +X᪥8Wz2rkVYoF5vDE3Q0r({Bl*Eɪn!dn`""(y9*#v'+ab\E~Z?i5KٔĤ(w.\k'3I0IzS;0j6_, Zײ%}$cRM^EWCyy*~*[f_ɭZSL`4_79UHLgq3xpޏI8g41},&J#ݨsoXc7S.$iAJmq&`͑5s
2`~"(za'P=̢[PK֢|2х5^*8|鋋Yp֫,9i"g_yfˇ{iq:9T=$
KYew⛭}ݮonw&5"U\B:|ooR"E}$2gqK Wd	
T^d{jtu(7l^|YEUYB:y۴ߖѤWqW:ؤq'ŗu,ݘ^M5RC}PWzWVMvdz}W:x\(-=t	4ydyeK!^<O^$'4#x3i!ljlXkz >ZG|`w,ۑ+sdHc+O,&9	ȇOG.,sg8JlL]z;+0`Q.m]b</LHfL.X.5$S=Vpiqq[O(IQ*|TR̐-\{*@
dv>4gcrOݜ؏	OonVȗcW#:/$
֕r-D|(nOT8Რ򜂰+>mS[Q\68UJ:݁Z:xZqJ#/F?f|4WMgb[$F~RP#AI߅`էrWM|c/rubU%j&(
Z-THٯ~lcw{??tr񟟮=g= Rz	?PuNO,pO F*T',㡹=ICl	ӉJ049L߈\JypY Yn92[Bt
QD2ǀ>4LgĔY_7ޡ;R,=sOTd>L&{xe0dY+CAG/i-{eA8fOSŐ2:kN15CF5P.{6ZPuٵћo8={k|M~G꟥|!gZ..yHʱ=:f	},9wՏ+CR8(!=
M/<în-mn=闸(t_eK=[TdRH{^>Gאk+{k]G/\Ztw-v.*1B?RCѺu*9W[{X>
|Bz,/tKĎ5@gHRszY~]L@+kMu.1!CֆF(o_XvҐ+4xq
Yt]ِښ[nRƇ÷NxXӒiŝ:KƂbUiiF	`~om_YtXb?"׽_>}o<0/0	'AQL,	_i"K1Oqpo)
c	,]
A
,4#ByAyX_FZ`,$g`ђm#!h*.]e@h.〿)E896>~K~ȥveS ;'d^I0
}Bw)eHU10׻Nu<\Ul.lN*tozl@ Q:tJ$g
^%jyuDvӲc#\28+	/r:[1L<p@S̷
Gu?\s~pY8[=*$h(kftpr`5osErOaWoFz[(`6]@tg|JX]}"9Fx#FBoJ)lP.`gA]"`QϝB,˝xdS܇~ 򆾈C(aSۀ' wv}39;Zre9Cj]&l*+1|)|J~^ru[\dD=zm5ԐދX%ۺ,B9F?Aɟj{UI=ߩd7ODgSr	Px\зV|]j~izvW*}\/ S/LD̓f6hČA]xvHt	ED,0!nBLNΑP\3C\6AR"<7("Q%(@aj2~8!̤tCET^-|	wD2=I8<g'FɤuYp8º,v(u%	aEBZxThsz:TUFDJɜ{80ouZ}ZUH YDfq4c@eCLӫjJD~ <>Mj:|"iƁs6kx)fT̍c3
q?yWKN!ve*M"/'>ߕ+`EPOe 0vgeொGA/S+>돚5+U|gΫpMFF!k3"l=lq>2耋,S:o|vH7,);;ov;<x+n͊Յ)EDg5'/qzgISYv4VN `\ Q 5mU1,eʜiⳭ?a=fUaʻ4kqKjʏn$nyhenAڶ}g"pdAB+5﷏_(ŝO;Rmby[ܑ]|ۯۡ.ah렳^pP+z[OӖG9EZ.PLJVzZepiU|⭷p:*7NZxfm /#dQi߅CE:)-y1Zd*+eYV)o$cXxIޖ.AhiW|Pea_e_`왜-|(m&%[NP7[mMAqnˁcHb53[/W4kg=C̱jX&xڡfltS0btȆHeGl,`[!)wlh3jakF^X>CK(PPqN̉,;\Wx.InC|b!p	:ȤJu	rcJB/Pwws voIo}(2blnb|:)LL<9mn.!IkQ`"06|:۳VrщםUՈiW#ځa>''uZJHKegZwl-SnWȶ$vϱ|x{,n?&dh~VJLIQ;*R]1ιH!į{VK[2Ua<+HGG@($G3'e!MZU{%	AH\~w.(J>J4MYjeqp2@RklX(ނ֨V`H)`BGU:Xa.Ђa5-\
cyRx$7zk9+u+דPPLHB,E,QO-nP2t`LH~c^.%T_DHUyd_0c	u w(}M=;Ac%47V	sT'd,^j'p]2[N⌽cZ▬$9q*"{O^mHk|eAMW[nl}	 UrdNHĝ7I	\/gk
o]bK4_X#5Ň;!zԔKT)ئ\ĢbC7GIb8=tBDZB@3$ ȱ?Lj 8jeU_w&)+8]>+-37K}n>xsOEſ3[SLi#Z¢~ ].P`(7uVYf?),Ia;GaU'+9=" *HTA>DuG5s6GT  ѐ1`o	hT*,FvIX&Si#R760sV
k~fÙ&d>
{+ܤ㷆8FK8.WZF.g@x!J<Ɯr:'|!ǈ5/;FK6 $%< <QC;*VR>*VU+<cACK)x3{ y9]ДL`oo^$ߓZ57uic\zp>(rQ?)I_f0E/Y]yTPTݍ5%_8B:*4d?WظƯ5)N/3`K:@潏QaޏoL,4'nU1ºLq
iyN	jǃ'xݻ[pso;tu5	Iqk$ܢ`|&ɺH$ f28S\#S`ya)I1Us%r'^yB,<?'7<$<e:8T*	n],m̝,`>Y*4Ft8w~c
A^8+uTH՚N u=/jLG0vUgE~ iӑS;跫mQ`#0 pRݾLtM.toQ^gp!\oH} ,za=~,>̀GA HB$8
GA+g-.ra8uvbF@=h,<ϴ+ꨀ7uR '1Y7bBd$p,7z(h=.<[`R789':V ŪStY V1$ĩ+EB##CU	 @=VZ/eHR'u8OD4e{k}nGÞئ$Lvc	kG7SFJl9xU\ ΍Mw*N(yiѸ𞹻*ۃFxvqʠ.Y}VsDfԯ${z07/5A4V&#y ;V8,MTaw75@dizZ1VRؑLXd7Y|ӟh0M}d
Dn`4((_!`A/H|׼N!1&`ɓޚG^ם?9Yl"  ZKyd5?Y$q<ŶƗ㦊+ gKY(}_ܿ!SGL^C)h`6S<2#-'x>Rfr&X6KV 뾸+$RL|Z?eR3*UJJvR}VCM	۹~Cײ-4.n]䨶f?W`^?͏tg24tрI>\*Xu2e8
CŎZ~َAJj4TuߒKc8nZUIGķ4KCsfGG:^O	_z#Roi!*Xm)ӷɞkb|"-+,ԠpJNyN)BNW|$sL6考>i0,#ίVWMpv7%P-uk7KRsNgqmlNUlZ`o:(DL5YKڴ@f:*Ɨs(./+`[Km9:\Ldmd^ՍpTgl6 `bghjݐH̬sdN4Lg\̱/'nJ11hXJ(,:r*̀@-ug&;o$VW[P@-âfOKj~O%wKX{V]mkպx,v]V3D}\{~w Tp;2}^i8^/Urzy]T5;X[|xש}cC10+cJ׺,vYc ڌa" k&0$'+,1^)1!]c9]@FijU+#0p9vS)0'IC8&`Vab*ex6f%E HZ;MBzMqGNWl邊"ZA}nI2Yu3Jtd
kXꗹ<b0D亃!G~J䯬%^p7߾EpyRmJVд62U홛md@ˊZa1rԬTh6+BE̦~B^eByZIX4_~*X9ʋ_93cՍ'XII(I'_(o0&l3#;F'd">d +d)'3qW'7WtrCk/,҆Vz/*4<mW&ͽp]B`8L1ǭh4Jݺ?iᨈ<{U"@"<@>)S,<{:rTr#f:
*.²%DdZ͚!%Az!]߷5 Ƀ <!BG%Bb4<ʃip<NŲ"<_Rdpss4!<-9pN.KjdUXZD\\{)!B|`}63SqI#;Ŭ7zx^qS$U;c6}jrVN8Ŀ!Q/hZ2$x[aL^A^ARfQjYwNF8Kт%MFW$$Eb [+x@Xe 'vMKJT3Gx۫i̴'^cx@$i̖hi"N$W!ej[הf"B$AzF(RZdrUPvf~~VPIe QF[ 	W7F"f
ɳA!S 2j\iXtAR턚=t]AKADŌ "D ?Sp>7dXN!Y9$H緧S8I`!ּ<\>?˚ܿHe $|0 (Uzowh6.C~E0zd](|pD2ؽW}+F:%n*'jAf=ԫگJYI4%AI/+ލLtyL}8NszPؿ okV"ڸ I!$U
L\SIQ$!F39-+APY)d3s5UXWJ=^$ygvd[RiPu72l?CD|ߩLԣβal=SL=hy4YN9\%X3hH1r-G[Hк Qe+3KgW~pϢ夵D*:0*P+oQn|_!|Lvd_pD}[uF_0]77E^ ;5.pTrW(`9}"yP
!\3&'[ޢ4>^A?0vOu] OuE
>jpD7Kӈٺb~61P0q[YC,a%-1m/;yv/~xw4Ԭ7	f,YjNh٫.i]oôZXHSn}Қ_&ja<R&Ұjw_BJ1+Ny_9b$OCDNw<z}qtR4h͋v16=YiMą2pa(Cݣ	E~#0klpiRKaDbLdЅ-N~n=4ݷ5#K#ǚkd38jXllu6YAbxtVNɊa)@/WŬ':,,ӯhS%~G[0*@U2Nj8"&]9@9̰}iQS4A6Ռ?V\<?~,;毳XkO^ۙvxzB4Jګ9Z*<ҞMG)(pTvTv
Δ2jjG!~)nYG;isߛV#P{Xڔd~v^7qr@{WR[.Zf2shb#kږm똚{'edD7]gָ4f\fܿC
⋞Ko|!'́7Tbs6\>Yv4zj4yz1`1y%1wG:1T^.&q\uݮ1_Lda2QNи2S"'Hi.;77w<'BRW$qz+J-[9chfuCR}!qR1w8#]gzɬqZ'!)9 ix;fCAL־70'NO4A|mO\IѺ;Ԍ)%(U|Ĕܝo>&:#TLP	^7JN|Dq=]ԛ$Eh.cmo,e9b-6JGam9 ]7SdBj
H]`l^3fs!FB87bfx)̍ m-SGMkU#'B%E^y($T^ZS3)H@?
N}*=syH$mq5C!5@Neũ'{C'cC@#O6v;+)GeZP]"\Α2%ҔJ
'H.b`&gED?~j *|Ba]bd	F3м=eH
/9K?#pIowRF@9=ʿ)h=a@2?Q!ȤhSLt$h ~	UxN4=iQ:{NoĦ4;0R5,Ԍ0Uqyިm=qcCznKAiñUY1(էFռt<:>p49x{d9Btm2%A?t!
hY2ҧMOkiןOwmUy7á;~5	qSj^U(tqNПZ)}HMηm}|Ɲ<a V;Lfޯ	zv.f* Ƌ/7V	8?gYC2Y_Yyv[_x3lZExztED|n}9o
3	C(Qv59?S`"bfu9q*솮87Sao-:
H6$j2[xn_=ux~ -_uf&6>ñSfMM859cX%x0}-ޑxI[}@w
O"Kp**s~awW6	F VWe햮aq<XnV
 y8D
/<ɯznUX_8X'xM&E+D+uos đD=Ā6G}TGo=L]q c}S4kv	DPXBȺD\ %!C(QjOb)ʁnHhݹݯgo)GJ(h}u4
G)RLr?c)ѫQ-';,*!ʸ9OT0SCVRKҠ]o(|?{??x#ߝjdx^/0>@ԩ{FaZ;A~]sQ Xeo(.P	OWɑ1mV[QTAgw6u-FoK/ҫ{@ሼ =		F 
kgզ2BG
+KYM!hvPO8'Y_BVLlLB(ʫ_AȘ?ڭ!9Tv%(%`#
^2UＪ↼)ٮlpUF܁`n
t`*J]u44afW``+?>|lW"j饨Q9n\_Z^c|t#_Pr?޵:͟66`|%J"үI`D{+*_,-/q]m	t$v.U_B_&+h컽&GL ZlvogwhuJfLlP'd=JVhs2
q.g1p˲Jbɦ>q/,3G	<oMy,fA.0+iLUueUgB6G:֣J@EҲ`NC=\9Қj@EV]YzTpo<y:ZAe_a-}Ŗ\YzeGyA>wn浽gla`2 t:!DibԔh럯~?    Ke B                                                                                                                                     checksums.yaml.gz                                                                                   0000444 0000000 0000000 00000000450 14442217575 014616  0                                                                                                    ustar 00wheel                           wheel                           0000000 0000000                                                                                                                                                                         }de;r@D=^`Μs}H(GCH@Oz?^~y{-yxrLN5"1vNy}>O| 2QSL
cqD\vY 9- 3ٟ>i>tMo8[x͉]'?Ղ)<Iu%KdFGn6UQanh2u;ZA4hAp(݃ ͉si̫mRb;M|oKVvJ4h]Xs3魄#ԫnis'ޅ1e                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          metadata.gz                                                                                         0000444 0000000 0000000 00000001271 14364637605 013455  0                                                                                                    ustar 00wheel                           wheel                           0000000 0000000                                                                                                                                                                         ?cW]o0}0{S>,1		@eC Pt&fclB۹ڮe+K+%>>>(拤?aBY,Ldc;([<bGC2iOYa8MPm'=!С^s0l~nCriJ;+ЅAR>1ӣ(DG<ME߳-M!|{ϖj,4k觫bJH:$ɓ>K	K|kM	R(+{!|C}`_O(P5Bw'k"8GرeȀ>*GSRM*ZBd{ߍ#o4^+sK􅓶.m\;qoMWJ
dll&mC^ĕ _gc*ګ+<)*ӲqUNFvRC[(/H&uIPٓNEՍF9z$uEQFzM_|4<4>RFY?%M?ä,o/2]snٴUn[;gD=|;Ŷ	2T9.U1?t'Nɑ{&jlǬ[3^t~                                                                                                                                                                                                                                                                                                                                         data.tar.gz                                                                                         0000444 0000000 0000000 00000026114 14364637605 013376  0                                                                                                    ustar 00wheel                           wheel                           0000000 0000000                                                                                                                                                                         ?c}v7`.2!Pԇ/6%mIԐGM;jv9߾9o>}$[U qL4K( P*Tlwͷ⛯oOƃo6?zxu۸7l?'
BT.g;T?ʽ(F{h,}0}=:v}iЏxl}X}YXs\GR~7}_pK#y[YāG_nmo=zy_+n|"w}8;؁=n -}6ls}ss_g%[;85ҥ廬VKcPDBҧGH+7NKMu͚Ts%NJwaFOÇ[wܒ/Vpe/:Wwo*RGw,wB݅ P؞[K>yf])g9Z[aKM<=w27jvN4Sl#v_uZ1TD,sfI l(bȭΗbQ{ k~yD尙̠8[X+r4=6>|[f%meLa>_ș,1zPl@)L"h#H@aCyO+@2&]I7,bb\ijkrvHxmwK(	3VuM-'
GT8<7sUO*:9%Jnlvwcӝ|_@8Jھqk+sz>ohGW4F0k :7ɞE*	/#$ Y⛴P$Il/0&DϚDmUc1@f:;h`C=N$o*~} ]]Ds'I֘TcᓰҚܐ56wAނ~2²k$Efg ǖ[ˏ̋,e J; 	1&Gh׋Pld5d=ƞѓ
Rg2 2ٔ\RU7$Ԭ4`d[xKl̵eMUK~Жc:Ͳk°Hl"gVpD>d+1nv(Ê0hd>@ѻs)'GsmK:
&&rPAǐD*+l[n j3&YX1)MsmPpv8B]6.G6jRN9E!~3m煂n;'\@3Ō/=~UW_X~R2Y ^)vGz9'vO&O1V.`F7,Yk;itZ}f_/ Vyc]cRU^RM6/sm
ADV+%e?y_oz{_˱yR@Mc҆\.*`mVg/L ѿ6F0ݠf	i;P`p<GA`\!O+4Eeک%PfVmD	lUM=stvހ㮧ڽ^7ga[< uF!yu rƞ,A5_Ɏ^3I׷އaBK	`  [}	6qF h	@#
mԮPVM7 ރI*.<zYʮWuVMf.l/
`OQinBPY]hͰgEEE2Tp:LӕWE7ƮJٿR*pD1W[	F+ꈛ=ciNsvFO<C֥gWri~:}Sw?K`K־ -%GU4(:J^9b[o^)S4QbBA8/~^{lE&pqU2CUo <μ zz3mu`38[ݵdmꤹcd[^@}PT5{BU^[?=?z:1Hv MG)H%'AIS7\~Y̕ԘS/<3k:)cK;OT,`>·t<Ӽ,:/,Ǟ%vޠU~fʨ{#Ԅspu粪 ZYWg˸.=>5G}u"2B<@ڋi67ih})!_ݨڮ0<, Z@c)^ Љyc P(ڕBg϶-EH$ĐZ %}#tη%Hxh'Y䞛
-ӪP3 OFTH"ϸ)ΌJ`l%u={(i.&`hi	^H6n.5=VN|&6oyh/,?1mҌ.0JۜhnEIBdH071AbP["0iPfR`PօukA^dj҃ãIzGᷰYr
*F%z3YGY83"CĭoY2OI+"tݟҩͧ/nw+!@XiGx.;81fZL!dloXĂJT(yvO-"kܮvnm숕JX	x:sWN c+
'"TfqΗuXtZ䇸SRX xiw())Ƃ/6zϫd4*b ف/=tZ1_)NET9D!XeO`
j~l0**o@TCyk	~:YhYWBo9tQBˢřVNMABjwGO:q,o>PYR2.;T3$̽*(7vs,WԖMy	XCV<2pE)"&>CZx4}vEB}(5@TT+0
NeWgId}{9n_|qwfOnq'2}-dv%/؂Ōq`{BŁXJʆ/JGY*'ȵ fNؔA{2v{lt<u5^og/_O'._owwG?O[?𧋳'?X޿_޽\7{[G\~<\gazj錬7qX<8\t5y8Ïu`a{qonevAYhD(U-Ͽ/NO^s@Lj`^%	Rxk<uE9Nܘ1!JOslaoY}xƄ$3LV0t
֦daX!Q4C?cۋ{Or=Ӆ%
PܞWya]Y*'zVVf^0T]`,/;?0OH;ˑuO6 ߃dCXrkp geWuէ*	mKR  Þ<A_+050>_'b3Ӱԅhh_FVMGpAR+_b -jP_ˮD`Г׭l6Cȱo"J?*ͽ:oc|O,yh	_zvA*+Wnͩ]-I4ڷ8QA{8rMֽnUͼ!PCk /8a&,b;nW@+#6#juGMd	5cTw7o>JN"\X>+B	2v(潏ͅswvWHP(Ҍh3P3߅|@AY/U~]A\-#2&0L[O^\Ԑ9SW\^	a1=-7B1\(3dB|=G4GN˥t̬MBu4ZA tutU'rA稍!B؛r-̓.l=>hkw:G{``؃@¨%D쪔D`9x-O3Vŗw޾k5D5|xRK)+]=@9.gطaqXֽxqtʐnJn?uDGGNtKAGn#V[K0{t0 ?3sTcDetZS
reIˣY6\c9Z:̧=#rg&>Eekѿ-kYΥH@nlm`^l<%85yהKc z [VgWT\QA2Q%O B:ZIahYExF*b!X`#ÿQWE]m 7w]'ZoۧX׵=K` Ju$A&*`e`}~V5
B'p	e\4^[ttJ6X\g{S)>"%<?^)ru/0^^jarN+Coܞ<-zv|%~1aK3<sM<ä udVFEm!Aؒkm2SQCHKv'
jB;{6@-]&K{lǾ!%r=3~uFk-_Ɣc.mNB8ܸy##k1Z Bl;=~`0o)(D;eynP4\KR찻GxKeu\Zyp2Z/' 	x=v	n_UK,]1)Wk`E"J~p=}nNwvCv3br?x(Bڋ[i?bpoto\

UiƘ|YY[vz^JՆ0q׬t0L@yCY+Fhi񢒆,V)'yȩ<.̟$qVi) oѧuFOt 0
u.b:Sv`,웉pUHe<hfre
ɉ%Qɤx0ܓpDMKnߪ~Aղv7k]o̭p<{^ե[a6{PT	HC:ZW Lg"I@7Ӧ2c]LobmN")Ĕ2EL77aX_NUSM"y/[z~9UW>gLq퀖c媆;ܟͥZȬrq>:"0S*}(e<ª5D`{Iz+[ƄN!(G[K)ʚ?VE=DdXE?R$[esT7kbUsUE2[eɸΒ9V1DM匯\U=u7
E+ӭg*@"V7rE߮Pr؏\
잎.=ߙTN48u?%J'Kj/#B?&ur6Z"C1$̄b	ҕ%sBxZaC賦bV<ex%^ 諑K^?JXH}ɝV:%-7F2SN4"`4h"1Te4l4Pk'+s{tX>Iq
F3H[jS_lUjQBx@n:3}u"3;3-,om z..зqjp  撒$6y0uHK5aA!ŵ{EMR8MA:k0$=VhljX8[uibp:UA
aqlIٶp"ȴ?vv֖Z_o14iZS@:SkK@yF*p搓gO[+ix!}c@V֪*
<d/6Afk\:t
GC!^ѩJP^ڨToW/mDd"ݓ<*qm6Z-?z">.Jlu!gBBs]kxv1v GIְvP5yQ-i|F-4Ed&={PʹiZj:`Zd;H
2X?SJ1ȋt*Pѵ~ITpUje}4Ѥ{Οԛի*,jc0~8Wɽ\$<53Nu_?]oλZ	]O$QI;Mɤ,MXk5Y9=CB/-P<κ @OkeMhq" Tu
1quuk{آV&ҦsrᄚiXM׷մ$hGaZKk0^_NŞͭLxcdɘ9PSQc=[} enOAX+a*9֞$#ȟu9̕D^J*3k-%a%(!h+(Q8Zc]*f4~*d3Zr+5ܛHt-beHE,2^h^-|b^F(0J	CrQ+1V2SLD܊R녶T&ƳCcaUNz7^1N۳DDY CR7yAK:#R`T.@ >6UjZ,6"u'	
PFnUt~LraJONUD@n?UYsb_3ClhUQﮐgٌ:K7[--sL_8anMa@3L&AG1PO|ў_6 5d K5jia,y14RBBr^?:W)5n55	yd8!+9dnn5gؓH 3͌r	ÑB
kݻyI+ԧQL/lAJ5{|AΣ閠֖P3gCt%0
B]*%iQ L#֌D^a{ >*FB9ka\!b+tp_aؼ4y=m8ՋGnN(KhddZ>Օ9=r)a>t
kfMؓ\Nխa&Uŧok"	.JW*cDrzq}dGKЉ"4sfu(Lw^CҖ<Bmj(u%w䑂AC[>^IW̠W}.j[%~n{=u>;^[YZ*뻦Q\n+xw>|85QHHs]hӓ*Е<{nB$*gAX)HS$>6[/e&[#f@jE)`Sɭ~gpL4ĆҽQnt!ʋ8_մD`w3x'ОZ$:U
6٠`Pe[Sc0Bޣ[zGh t@>:;(f5VY}OΤq[#۵%3x8AQG`Fv8ԖTU Pr8Q/^LP.mCyK2	jk9_U槉Zy* *+R<:m0g<G8CL!I??*E*ԛ3bd'a`':9b
& 8"H_6Zd%}gثU-2S6~A2Ŧɖ|=S:k(ꋿe+nKFgЁ%7XX$\ 'uDܛ1/U(ƥL\j q1ԛƺrŕ.g9(s`F4I;`>y&	=&-1iFߠ;Z08(zXƑ+kw_JI
9˾ad?&Hv!vSIUż*J~ZֿsrNE$,zqV1Q#p#^N/lW>7.Dko*dYtU@ԔdbkI+RiT%54J\[uqSKFxSG<L5@L-h6w:Gއww`a&vbvH
pA3#\%(ad$ړ@0,lc
93[a5?z9sS
	"h`r XP&z1O`ܩ(ES.eЅTɁhUM)`F'{NdbjVB#}/u9%%)Jb]NSQu6B[Hk.<[{x`H	v~W9x!zja\%oo%(c,}M<skKy1u>JPJ0Y9S0tkeW<wDpBT,u}/
WϋµT73l.ݩO{vo\`R^C|h\5ii%a恧0I=),NW٠T _eƶ/qЊs|]iM"n}'3^'&aЯmЬ}&Nnr1A".d-Y4{0䵹%ƒsw	5p$D<>YOW9}/אD2N+E<T)W12M'
q쒆+qt(K,5ʫDH2SZfH{	I)}g6"#64raEx3wbSͽ-s97뛛[-(;]t0fc^8yO^7ͭ)Gͥ돀ן/pkƎxtnw`ءW[}[m,t)@ƺhY.۱B]gg_qƣX;"^0,vy>&{cl u r#>z9`8֚y`e{{HlAW"Y~v<?T7é]Z~4'#{yNra	t}"OA/Q#&򽉕R߭5EA`^ |~{9/koc^Z@gs,u؛^;`  DgAnΛL
xq@Ȳ_´ܺE @5)AHgoʖKbL^E{օ=aܱYS.xoE凍߀'?b<saLͽ0,</rN LA zE@d!8!bfs?)zc}ۇvrHh^<X!U{gE0@KؾudE䉾p
zZBo
l[\jg ܴ wZ~o>" <,uPX̑
Hl1ޙB1Or 3D'2<Ä~[+HMKq72$	IY/kkurJ2*8H#VՇ	.{ 7= (Au u*ӰDӬ&66=0#Qxfh է-؀75N`@/$h(ID7/gJSlQ%]S6\!hJe	*PdVeQ0KU!8!KO%-_Pj`g۬}9xYu{swݷdMh?>JNuvbo5w@wF]ʦ:>6vcks|^vGnq7=hq߆٣KR6Wx0jup]ZovzWL}Z;mj9aUju^	v~_a-owf9?ӃGLyUw:k+=PK@hI͌|~ov cen|<]&ol}a\8L'6(> 1*l_$ZUqsDɽ$7-JnP}M|OEcv`m ;ȚFpqVEn\=˗VVXmD!`?oSn?,:Rf0a} r}odF҅yϜ4қJ:|\cX˅MHBߤyH>6i@*^+]oNWeC!+Jo16aP\Ĉ@X#̀P*͗.\pk}l h*T(YҚL@ e
V߂Q0Sچ<%!yLqԪ(OǑ_q6 ߗ+{ `n	Nk72:)    ZC                                                                                                                                                                                                                                                                                                                                                                                                                                                       checksums.yaml.gz                                                                                   0000444 0000000 0000000 00000000450 14364637605 014621  0                                                                                                    ustar 00wheel                           wheel                           0000000 0000000                                                                                                                                                                         ?ce=V@"o[ ZRyz7)cfne^ׯǊ{|^c$A+42a0hn)rmV{|?y3=}kMG^ThLFW]f)|"DeYKljZu-iPGdu3q/jRF3m.4цaBZoN+9p-^r.qTm2KuBYN35GS?`R὎[I[@8 As*u_~                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          metadata.gz                                                                                         0000444 0000000 0000000 00000001056 15172366541 013452  0                                                                                                    ustar 00wheel                           wheel                           0000000 0000000                                                                                                                                                                         aiTMo0W^vH *Q!$HErI2vVv$3~32Ygn[wz-*fGP6x9"	Fu"Ӽ8 ^/Wldhs"&[+
Bo@CQyY?&tĀht7SPD+kd ĺ\gleY'/we`0
a1$7=zNL90xVz2.|?`j~Ν3i훁>"/@MAR҃"\JY殎'k-8^]^x1#94"Ø`XO=tڼ?vX1:js4mGA?@Bͭ%RR8q1.{au@Xv͏t/؀^T$l>4>aOXܦfıOwF$OL`M[ׯh+^+WSWsM73h:IgǞ3?i-A.}(c/                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    data.tar.gz                                                                                         0000444 0000000 0000000 00000135205 15172366541 013374  0                                                                                                    ustar 00wheel                           wheel                           0000000 0000000                                                                                                                                                                         ai{_Ȳ(=fM3+C| 6X\-NlK!oU/2Ya&`jZ/?1w_lGEg/_xކOY *w7A0-),4!"E J8"8!}mO;;-S$$|;"8׎ҿ3e:.n>	 GQγ?M@fq`2	Gaeο'YLiFYLQ@sf8ܓxIxA c) $N01+B:$?aO!	m4
yOp5%oooc װ	E<%j?(v7~Fn;
(n$fH[?	i@⑦ (XODk#8"$gp?#E4u	PCQZoq=~P,Oa!~ݤ'N,c8'a{9QG  cuU|EQ6E{x
Mpά%Wk$] }B:~8M8L~6qV%nXisMry/{{$gl1#AC36C)t8O{m&|o5c|ǐ䊧R^ ]?d`M JV$ O;2);%Xi{>Z ((n^q.N>YOmN0~,6ER^O%\`Lq)	QWE˫A3@AV:>|Ԇ Ph<'>2J,0u,ٹ۞YΡY0ųt1Is~wf.$Nx62n@[v 1)E0
μo$Q{F8@WըՌ0YOkO
qΤ{Mqu6DD)q:YVvVPTP ,&3
M}+IÚ2:-!Ώ`;zkM\9F77ڲBW~26/D;9A8xX	T"f8qka66LӮ[+V-P
$.LX*lwZΆJYBp1 ~7(DuޘAI
FIVx^quuj>X>>͂p&Tdx$<	&AxWO71[EUihu4kN4PmA0 r9|BN|(84*u8M>g.6J7,B'cՌ52T?ƀs1KQd)T[.Ţ\,2e4Ť12uʇe2=E2)rQӘUf[>:dv::zE

eC+ZYKr2D*p%г&@3#g>$0upy9Y0a,RGE2<X?8SeANow9L`q
DEĒPM-LcTaTuE˝@}/NH$NTX(9jIq]tTe:VmG%wלP428#Z+>*xt?a**91u"&G+3MI`r ['9:`{߆55N-
Fl)m;N.E*ƣ8mިI^UkЈ570F?#ՆR,AFWV491r-lE}jBK.t%DB!C (:D c"Q"09iZͽc^o&jᘣG*gOcad8*aY7H\mNlTB8H$mq2	|HX|YtY6"<""`gTZ&/`Q9A
#69>|'FYSI퐡<?gƵP U-ZZV +eշ~t';9vSvh(HFAdUFS*0j>AW{+IAv[vd[z2=}OkTcz	vGku\}[/^[g/v/e3~{Hil*vk5n-o<.,6a>ZkAC)ǐlּ >c'Ur@PbRuQ)gʺUg[f:tW[/E_Q{f'![{;^촷[~O~A+Nsͦ؄%N'Z3j{6ֽ&}_oϐwiN^<I:;	-~/9}k?r>&Ok0@]}6²['7mqNx1HAWc#7JET_̓w~Fd=Hus2 oa}.==h3DN@jn[_:o-o?{vΆ=nc|'ڙN	EmhaWԉAw#HS@=:1M#ÑσdfhcvNmD㐞Mb,^1<WJѡO&~Yբ8\`SѓFGS?GhP!@zIEhu\8#aǣbvb
2$;BGVV:#x6]?E-a&<2P+v8j&O# Hٱ1wHm!n8FmfIvXi<	>;''	[8/Mij÷>_uțm_GZ7@59twr'w= a;hQI  9;N{zC(6<oFjΛiom7<öN\\/]:O;wݣmhZ$ݟgC2x9={Y;G.7]r9bCG~p? fmp=E0ݿ_B!$GwZ}	E}(or%'G΃nawGNXnvvh (Gi;vˋ!( _AU(qA/t!P}}'TI0 bpXHκ'as/AC`mڼ]!j°M:wL:G?m^~lBIv{Sվ'xtw=z )#
Gk؏V/ݾ900UƛO)k/_tɌtϵ`,ft:݋!nIyltjvQ_ߞ{D3U=e|iݳ<^W+=H.w=}F9|S;A׎A x]53<||?;@`U. n~)Z_ ~?d/9
Þv08?;ϕcV(7 ޛz iQVnV ?Y '3o2q)d﹏{#	0sL*m-w7vQ^J)0!g?Ɨ/"x'Hz=5LG`M`Q9?M L7ݓ:o\vBuހJ`Qv;
+x?sASJ=w4xa^Z0x?Px&+??t9sͿiG($f/^<{(w9;/$p(u?4~4Ay-\Ənμ A-Mkamf(^]gd si(X"b.Ʉ|	lˠ\xDE,zT[_gAÌwX	TLzp(ӴF=()g(F6Y|/-l[dx2(dM|kh(sqx$L"lq9h61LXQ@lX%	T9m8{\-Ѭ}8%sܡ^{w0Iܴ lmkӐy֮I.fXE٥6֑:ݐ?dϜ6[ K6&b<;QV:QX⡣+GA@X#(Mej7	ҹjIIW@jt\lv\9y`13	=Z^]~ix=S^k9][;꾹<e*U/_VῬVaaFyx:EzR$Q'Al'MC驞ާ;EX[:i6FLc+O4܈ٸ*ٸSO	;ة5HD{=:	;6E('s<$$,hM<qMj7ksFO~#ig^Gc0OF6F'AfpSYt#|D<w.(381t..N$zxh,]*dfAƾ?^&hwG/Gާ{xuHH)~WE8`F0zK^{QՋZ=|zMHmgpo,4"cPu8}&;5mȋx mDƟ~z5`|-`I

SQȢ6ew8uϲA\w%ޜV`1%49o:?/i8~syz`۵L=j6~KP4v靥Gv;=ȼ'7p<A/G1lk6<LOt: zO/]),A9Va?!Js,,(o0+.9/\!vfڽ0yRcyH'gy%ڵ>`jQc-jԛҒrUcgK=wj
%j(usoJ9dͽqpf:gJ!яMJ`e7McFJDȃ%~Fdz[K^0pF]-{>Ek9rʟz#PhݠAl~+3: *Jz!ဣmY(!18sJ+@wã,0#B/^ivhZu=qKjNdlϼ0ERg򐏞C {:(8!»Nh*g6Ez7ԉG+L1d|(L`8o(+'=
N&MX5di\yzr	ȝP"($91jE`(Z>FEţ(:)wZ"A	YםCNDꮢWsW ÅEbڃ.r!).4kIv[W/.{doG#ƻ׃ywwu~4PY#>m4yxj7cF]/@!K,D_RiAtݰR0?ӋĿ"f3. \8	[λHMQs0M)tG vhfbY?ՙ2Eq	l,H9&~Brڛ<i,eʗ^;	D~Gz2gǱ$ eJ\ƣF?*|C@(֚ks~v>1ӘJJC9ߣB32°冭.u)nM2.s{{V2RSu	aێw5hHUj}<ZQ=	.ܫy3=y4,'c6[X[nqAol.a55qWr҈^ΛMp|z>~JrLl3mg3> oO0	Mz.a_EoE"˅H`d )$xGnE޾Nŝ/FAzPPsdν0p&z_)׬<:Lutg'5c-puwTѫ?l&am|&$8.(E7o-ΏsبQ̄Lŋ?ϡѸN?P%"Yi 9zs"Fԋc(/MDE(eXx?{ }F|`HF> f1ou͟& (]X&'u>mH^դ@
ތ=1|ꢽVL0P 14?&9iau|	%>a2 .-V ɘ& ,Y(-[@lddi`;;!ְ%#fw/wf	rS
F>MyimC̀]~[3BwcJ)ژF.Va{ Fcs:G(jKm,][VKjއR<İIC%y*{u4z)_+E E|6ET`P !{xMDtdADѱv `6a;Q_gf~QYX".g&DT:Ѐ=8Qn7h:
5rw<aYx%sh'.4Ф\O 
W,AmpLi$Y
Y@u<Ahs`$"FUID t-rƠ"~8C>ut)(N MU;??Y|VL1>yWiCO<k=廋||)d9iZv~;ov7=4H6[5r) s"qFPS"///ޭyJ-7SEW&#p[	oݢګpm<7>/Z(6v婼R_0^tۏly@󢩒F!{NwER%	i(Nl\AŬNᬓs_9=?IŰLЛ&;P$zs ",8V<i F@9Tdi:i[DMdYz0X_\4MR]=`s
6Ffʺq<(;e)X{Nu5;GG殞^=ǕxMlt㥋+hm$avL7^j^͂Sy[BI=37ISQf$ÉUAGul0φ;̢9ئWN".Gj7b~TP$ڴ,
 l֛(ȥ6· t2iksMm2m2[x>4iqJt~Nb՘W0O`jVy`~Gka|h\z>CS58`t\@)$uJL:k Yc}=L}mYjƺEGP45/uDAQ`ȩEkP9X٘.i[0z'w1C7gĲaꞳ&/gg?X)RX:>.B'<l;o' $k,zPfWtGbtzgj# 
yMU ]ِb˔ZBN
sTr" =|6Ғl0	V|&[ֲe3U<	(ϒw{4_N
bLgUjzݠ53RMZ~BY"|s\EKoRUZ{6 Ax	O&i1Ěה&z`F̉ƿp9k wH',:0
J
`P]ノW-K\`J׀\)ĳlYsUb^V),PgY8prx1Cgn1vXNDu;JZۨ&pKSCOp kdzݴQq&y	z؋XE\YUP*HBn/Er*]IM
%H7EQlD?6o5,P"E/@;M(#>
9 r}P"
_M.7deN苖lc [4I"QkB!0T1"IT<S\)l͸@kb 5ˎHEݞ*B,·^]n
 eL)?,{Ɯ޹h昪l-㍜GP[Ժ?+`#/	Ru'f.7?7v*]Fݸ:l4uIԩOh	/NMѕM@M':3pGt`SpD+s\iX%oU3^_#Eڮf$oU)[@^tFvb55$)J/W6=4Js%(#q(ETאZϜ5Rwk	+ܖyL:\*	E=D/W6\1ԭ|ܙ%A'Kh!*,*-P*-ZʫkYieE_˚aJLU C׮h{0-Â5Bg
e1,PrY[(V0YM#1VF8Rݶ;܌s)OTT4~#[rT,1(	u"}./|V(˒83zw9*LBiw;Q&y)?k2ݧ(dfѪSo3]KQ+IIZ+$Ɯ]quz¸.KvwC1{&LEk	ކ\?w  ٘=VIx 캳νe!y&ÚW`LE.? Q	X:sH=GS%.$#HFqШOkxKުӔb mP{YkHSOӻ1Zf>}2EKNm/xrzsyE
0v8m$:4ˬ[|WG?UzVr0Zc5Њq/j}z(PY @&@|~+S^O^(BLTRPsYAX>g 46=#L2vY%a
9T-$XT3EUyQ)8UhQ
4sM5zk?ws|qkD" 6'm&<{-5[A@2bBUnC'^(])^ˈS~=9$	MLJ~Q9ABꆟ!KEËi"$U|٨,j&9Gg&il>־oԚȋa1MhW	,};X^7{bJ9ݦ-,3ϳ48KHb^$
?>o!yIUo8~=ۢp5x#$}oURߌ|ct:w8#v]fe0ǙZLvJa3V
i-'I[Oä]ݔn=ƒ䢐	+[m&.;PX7y.ԛⱠ?nKOϜʵ2
Eљ:1y"sjT,m0wO1	}riwp$Ǽ¨ѷ2Do0~'4V$0z~Ka"敄AL@zE^j9+J\י8+)4'''Gy;%oN{^wxs4<bYۭkjw 3^cx=O/Z?>KN1/饐=at0;kB9}Pr5 ÛW)z)h6?	d!&4 ʗmF,ΧKhmPXS#O1lA5)@)Y\QIh0LA>+~MM1pRpX΋cY*I]fbZgS[^_g9dg'c'r11oi8N@Xe&O{3K.(4 AHq6m0iFE0M6Iͥ1U_b;^ ʳ&g5Do	4!13ඨ
/4MߙWS;bt,dIUۄwͼYk0"8:@r1u,bH8M۔вuw^nJ; 貴fZd='[^gy܀R޸m/[[ŚhҒK9G;-8{hՊdt ՗NCfǦz|xY;RwlwsuX'wco
ïʖ!D^2lI%}r`SrP/ zEG[&tGT>y<h 7vsKD6Ye2'2n)7rgbVNl䚎3$Y#4i^\Z	Pɢ<FIV%ЏV@vFmϵJ	X[B̪we}+/?"N*'MVEzl-Ґ?In͜i	x)LvERD9ǑV⛰"+y>#_d7~Nty2D@e~IUzDԋd6~1>^§3}^&Jglu^0h/(f=]Yg[$W6z]F͑x8Xu#ܓhdh01^]1`\i:pVdY4vq*o<T*|,ՏuWR#Kzy8@W	ٳ|L"b&_KU@`iXޘ#7x$a7b2b[+]'"
)SZA ""H!	l΁_il~2{I`y}~[$4$J^>y{z]aWv`l)7a]cJ0&@.a֖K_}\\=p$7G^(R7*xM$/J?)K
l`nF0tSĥ5U)ˮFNl4Y+$*7qYǔHcJ_~(uՄR5( hѐUBT1rXòH[2+Mn$a+4P֭(%!Kru0O0UaޙPȵQu%Ӣ#)(oj1JÓźO`t]ʒWW]{鏹w|g~iW,N:"g>7;{UJ؞^۷Bl;bwV\HDPADvIm̦-ΜzhZ9G{ۯlb]_/P죏bLUg fY\#d
^=ZeIAWJDv &iSoҴ~5iՊoe%Ϊ1.oȨP%*Jk%oyЧvk^F;iǒF|Giu|lχc ZWi-%i.r?]'n}aARnRnesq,E6HC͟_w.v}|/YɌn+Vm]v͠EIìxrXR7ܾ>1_ qR:~f[mG5LSY=N*>+$^>&vZZ힛<0]bV+tө_{ӜT/pr]$R1ZL",G	e7/9!z秧O੭OgGMMnEPy]ayDoAw%d\ s1`uCd5;5*LfB&ò`v#IKQzO2G9e侺1bj9_~2SAl)gV^Bw%/A\S+C:B8H˻]ԅ'Ԯ~낋Dny}lLfUdk3ʨQFg$4t$yik!2``,6w~=P?ШH#G>Ǥ6X{C;+Na%6,B2X&+YN2T,u_1ӌZ`f3c=(֕>ri%۴;hzv&֛@<Zրqۗ\L1qq^Z2o'3zuêąX+Xak@?Z:d!2ud>:]-h[tdbdenٍ<ڤE$`c](yۊ{«&䋚6ЧX]YP	>;P<p
E4J"Y1R{oSP1o}6msT`UsIlz;-qhFL>wrѻ]enY62P?Hf%띜5ԗ9H,$GufU
/dc~/jz^DjhbQ{Pf{:>׶DA>(rSZ*\?h){J8QxfݠK	z4"iQj!?G	,C$(@K	Υ+xҩ:>ԪpದH.7g+<	]a P<je4]9fsQ㽳(+\2rxX4ԏGX]XvŶJIG?CXH#o.A]#	2.j]w6E]푡{cgHp9i,7T:Cd,@+iVETA1 (k;v'ZLk,|/}0Jh(EoldWl 6 S[~cՙ5DQ8 ¨: 20@]nL,ȾR|,'S-UmZǰ֥7L$cfCyzL4" Ė'|΄*2nWGu#}AlJ,eqčg+=Uru7+}Y̥jL<cN7@g۬8ۿ=Iml;1 Kuab}.d=
z7<h坝uO;U.s(U3QgL >]:縹-	mnx$]v\zm,_iu0$[;[a_U9f'tI-|O!U]{hQ5zkR^q~QyUPLղEIE]֝4^^A b\-ǖg./]~"JP9tJ}9%7@Yպ+
#D)S,aVW~yvT\տd]{~|e/jMo1-Q禣N
/WR)BcKh*xә'/:AcͥU\lЗιVt"L!F[JcsBSx,tm{^׸Z,炵Hi"guRβ&QYF>O&uRמ-o\ρ4l..	m54$UP {*rkUAt,lF,o豍;V.lϺ"t;lR,g ˨~*_%Oq_eܢeqo9bpҾh/<-e?M^4Q ([f"MZg
qZbeD5φ| jA1I:^$s"%f{j;$F!858_,"2[	=;dlʌ("ƣ>ln6zFAIiyf~ɻP}w L6
D~gPJ9~&uyUh{"afh4b_"뜔_λ%lhSnV>YE,A{!0ƭܟbG2X0NOKYMRP==zɡ|Z;ј קt?!iC7WXא(TtZŨV4X@6o->g>FXߞ0<1@T^]583Sovi<_7Xe!rby%/r)Ԓ>l1^@
&L<Sټ)G1bbGr]X
^
침X,(DAG#,O(C)LeS-UX-Re
D{T<v%z"-c=t{;ù"k5EaLXA#q)tgzfe;ƱJ&DN/%FeUץ7hcٖzg0vА&9Y.6	/W("r~wҹ	1Ggaw,b~[n	G--T[!*mZK+:Î06S+sv
_A`g&Cݿґ^z0_C-?b[/~݁_ dQnǘW_k&3"CeWUGL[.7g:b솸:/"Ry j J5|RPUaEtݷڞ0$ˮ"]Z~Ȅy/jXʮq;D{b!EC2ojCyeK
xք*Us?ꅈqK'PyԄ
ُ]=+s>:ÎCbi,?~uvWo	9P;Q\QGܺőO|XLtcD?c_YhNpÀ?^xgH;*بHR
k#kN˹re>c
jr"⫀r	S<0ny6]D0Db}#:}sE)hRT<"|:
EΉ%NnqH祥TQ28W*y|mχpsS/ŔRYUeo I\Fv~>"_դu*PaQSS$ܨ*OY% -r?#xrO\#3,".Ղ֒GZ'tm{0$ҍd_U5b&xBO
~F}q3gf	X.uKj֌|[VJ
|s&.%AxP-5nڷ2f$X@P6f ]G{~,o$G#"?t9-zBw@']\'v>?lЌ0W\)4̟b=µ9oԕo$r{g}t՗u'\`ج9'p__cPI_twu}!^~FyM{(Gk); C@/"=ͼk튳ls3^ΎeП~SfFӮ*{đ2W;Am}v)7qI^tRi;\8`c6W:/|1[AC%wdC_A7~5O^jZ;Q*/4M4ʰ<B}YE<c^<<qК՞'b|K{۬}Ã:o?~mzZ54*9z(9ժ)xO+i萏&ʢs΍tCp.oZvyVbju"Dx+1[H}D@0:pYDQa+{:VA#ڍ:Z8nb>jQ:|Q)k>z(\`]:i﫝%'Uz[&}Xҧ#JI^އ
a@2X3/8V6vuŌ?µꂶ]N~cB!'e@xkooI^諝u+FAWTց7/t.ҏ4XAy8=q?m6/vQXcz<($8ym-%g'u^klD,+kWycpzɭL7[?OAM褟\tDZqBFmHkcE{M3E{\+P^pjnƢd-YYaUV){|RtA)*rU|y(pcq="!2W|ٲ1uOMM=8M9={F|hOK5CK{^Q{)jbԾB竤09mxFto4u&bRt(47yWo:uL1>ai'S?k#sh&F1ѴRNDoE$](jR98UOE/%n$TE|%Xj0򟴦KǇ%x`Z#i`d!$~e/)OgeҫlɣY`"DWemcIIoZd]!B#6C	!N]ƐtGj0Rxlq:_A򥻾fQ*x5>I\g|n1lMZ 5o)կгK6QUf}U]C*Y>&S9r/ɛ0Gpe:~+P$amy@咾OV+bC'~2BӃX_峪yZ
Y\ZoYoJo ^r}6ooo$+.@pWBR9M\UL!Wr"/ܲ[թPѰwcv[GX>,[V_uՄ>WR<P=vlK"L)`v̭pN3p~YCdcEmZ[#lrB3#~kZ[h`4l"\=U_uD%&2Қ-I:ʁ޲YyNWp!nOӚ{Oy+<x'vIB9Te7EٞӽU1ۚ[#A WzPL`sxL( W Xu	%B9cQ.Q?jeW[W"͗ГA'UKiQ+տ^NzLo "Rh:vd>։ĔE |cJ&_1,HA;OAV(3jțQR9z%9E1T+StV4^TEYו@.	hFid:lsg](r4&bZ&cToZ1bq<hy`){B#|Uk46XW_??{>Y<֐ݶ۫04ޖgaYc)~[@pP'cdYA48d,^g5[x纩` a.wB&*}fhG!u$7czcA'8tAĺr4$TA70/{t};es[l=yO̹)(юk)
=Iv:~i'xA1(MS{3LG87zV-e3(6#"
0ګWkXIAۖDvb7&kr@>B_MShZ(:g5J#"?QOv*ӛ8֬
Ḝ_`P^&C0t&9̛:Pd"~A7Oܹ
q_Mst"bPApG+,m&~)58Q8[5f.ѯ^8BHh{VV8:]1,!jiB5b#C٥q9eQpY<1мj)L,_Q9 h oX)/YI|ux[T^ќCp⧜ڤ8:%
3ͭ[rmhTjc-riN}xX9oG5
ZFk +&Ki00>7Dj8AP8[Z"	`c*T?|A='jH~ߙsH 7<%th8
~cv8Bq௙7h
ekL*?FaO+`]I:z/ǨʢOOTtélYNmeP?y-*[ʞj:ohh̨ծ.b]R, xZҬ.%M*9^EFQ$d.6g|܂?!]&+&/_[ $ÄV:LSX)&uop]m]tN!L
m02"*`ZKJ#+R7YPLpv^w7+".CCgVyua5^J2ƠO`d#v""J1+3=ޱv"s`D4E/cъIXXG7A t!Z^@^]<QTyM4y>qF{Xa0̡B$;;?v~sv9Y,s~13);[~{*#EqN*ow* pOe8V"9JńJYi!b~i1hRŴe!Lܩki
a:͙cUWӸis~d4/Zv/m5\DLw\os쨴;V+9C,ê㼹eYPD|B_gQ@WXa&P9DΝ+(dhqZ{TgzR,y~$" gA`P2AFו`[P"@Q23d0|eu64ǝ~;3zggaȮ"6tp5'aaʾXR,󿜝휝|lvWHv|Χd_zǃY{T$W10R^ƿwP9'ѿG.j5Y2}k{ӳڂ]
ZsـٰNdYrf7HW1BJ>)=gJѻ]b hrlSЩk _ò8Z\{anu\64'
z)N㲅قV^&ԾKG;X㊟RlcO5ʪu
Z$-sMZuUNM^)Wbe}d/]\YNpqkGRm\_=`fKcVps(gkk.M*
Vԓ+i---uuev9B4=#mi5Jd8Wi.u٦;2_8vrCVil0Lh~Zk+Vo ^4sCP^SZo4l(=m//ްwsv~qQjxKwzZe$c,NRdÜ9i,WVjg5~kӍ	+o_ +#k~j_PFcCJ5G,w=GoS *u\~Q@E2ZufhҝvLc_e3fgj\װZ^PΎٽ4$YD/Mr; LI|06kIC$/,2M08oT ]YdqPӰZ9bh2f#g3(@g0eO4;Ď\`G
 hclc]3<89ch@̊
V+|"Ye`H~_)hg	뛌 ӭrW]toYNzF>lqe֚KlpY>͂PE)y&OaVׇ{eCc嘭4(x^Y|}q6gVaDfp>4	ʜuGVpOO6RE_j(bU[<N-1ACɪѤ	bOyN.vp@nrwys@Zp_0c1âM½\@UH&׃Phj(t1#vX'ޓa(6+[?KՒZ{'"kE2Y䧞$Q8TKePܨ,ifO-\C4Wu	~*<XFN nVYbn*8* = v÷Quv"IIWڽȏWiTXoXL	Y6L]+F=aXKlσb}=ǏȹX遌U 98]ٱ=|5[7n\c~ ܲKk/o~OUg,
	x2M1H1]UUfKfR64uv\IF}%<x>a[N渓">o2BHJ1Md67L 7z{34	c!3p'&j̀Q-NW6tKV3tnIETT7.pGTzxDՏ)t>}6 b,Hf?!OC]̄zکJ`.bHkv7ӌ˒h&j8."[ʠŋLïqL?Iq^{,]<AXv`lop_+7<!fN*zCZ9QF==jbYu9}GOQK>{GoD d1 1"sUhÝMT5d!(rVw6leؒ
CZUVVg*UZa\Z{F);yI{8ot%[p}]vps._72жsV"<-ph: JjAǅL.a jmU5(\zK\)DowW8.uTAy$05F=xGu)hu#{L|1=i d~K^p1ܸtuJ>e!sjLGcukvvQ_U,gVo4Z{Eq_e@!l;qeOJ*1q/ˑL<e}Krgۑ<o Hx[[6DɊ }LagZ\%>h[GfsS}qJG~Cc[`^҈RM-Gs(ј>{Ƹ,aC[h`։E#+t-h0vբV >ܥBɩ\3Bf-ew&l'ҙQD.mS
:3YGe/jq[
hX9K֡𧦨.7Kr"6p;q5GNk[\q:@suk510E]g&W_\gЮ'M41܅9Hkq\K1.|{Q9p̳'`Ŧ},WѺ薴EǺ*kK}C}3y>8_>@S\ԏ e	m9,S2mp0vVXL6dzJ]+8T6`+i<\m6o'>լiCkA%!>q8oYP9JUn4qVu(M:m*i*'vV,]BnTR7 Ղq8BP8\z驼|ʆ3vP~X,q].GFwn^rAܹsQڹykkZdQ.3Ye_<\_D]ݗWr
nUcI3xKYTe\5MsdiNQuOI*`webHtEgIrw{[1B:ۜiW㔩t]gvW;Bغ' 	ao
T;[ӶA9K7z

ۃZ%jW.?FMWWWTj9K׵oS/ӣw
cn*ht^gry9A[-(jԬTmnVhHg%U,_rv-&EZCfF l |sc)=9>|;E//mWPk:+8}+
<+;*;*S<Tу`o^zy/.rn±v(7.e}/-63ėiG{thGtiA!ldkDٝZ}2ZP\<W)U6\!a~kƞ:7d7j?b=:wz=d=Rĝ6ve5Z#½\&MS􁸃l9|]tmX8FIGjÑOܲ],Z=9ynT>/y7<uwgqjE;U芓.}쪚ӆܫEI
NSD6ْX͗zEnYKZMܠR,AKyR%hxm+kQ }\:hV 
r[K@Cy  `ߒŀ?6']O~iNKo[ƍMVvpK~ryJ̧zmc}]YAKjGuD,XTQ.?ݐZX=J2nXY]蚼L]_E.WX<EWh5ǊgVZJ_*RHg겻]0Wt_|ePeVBolk\c{iAh0ʄY$qxPttOcZa++ߟ+UtVjC	}_˷9V[ĝ--qN؜QX*m*<ß;&;)JybW9B]QTqMXytWj/b澉D9J"8kTz3#ЌOoH͡,1,'Ӎm3
BGy+!DNPw =rtߞ}i|{Jfژ^ePԚAO&8أzkM[YuVnF3p \\v-"zx^E߅h(<9A71,_ At&q$
T&YHF>nxgZVoy&ڊ_:xfI4XIؠBy6o/<YmZ0U ~B]SU}jziN,~MҪ67eů_SOӻ1	~}1.CO=QS%=X`^x=\˞Wvj!-㈶2)Й.Z`y'cya;lׁJ5	>*wK&|r(V{Њ-V=YQSlӢq}E!^{-9՚]󻭃ؽ2X'NTX^B"Ng̃iPe^s?bm`Mywr1Ji<ŋR ==LoՀ>{ˀ!ɧ;O]$n\XwK8<K0K!Dl{i>1fN뾇2&T\=6%hBsÜsڹ?k cgݳЃF|u!1v`v@/BINM)j:YLBwꉵD{N#_#,.!*aIZ/?WC=?f?;^;>|x7^-,5@%A5/,	{5JһMn33ɖ!qĦ&*xjQZPo*7z2vxݤ*5MzIRr}Po/wsesXzѭ?-!XhTKΙS2Ќw@K`;dRU\GGu|R=wz~e }_?)`[B?G@^:Gw
ac`\~pwDUj-iԲCGnm84mq1R
ۅ>#1/G|;?-kSej"^f8?4p[ 0<E~Pr7oԵB+80ߩVi:/ylK#?^VQT]M}ܼaecmY#^U;5>vjyH7axފqЁ2znYyP&^2MΪ4LkA<x"ߤoj%о)(D$;7-(!-n؛PMHYy. V_q"(Ps=SW A}2?G_
/>"0ԣZuwTnast3زCjtG4.x޻4ϡ$`6%^m%}"Nܛo/wk-6嬚qr;"RP!?{[ޙR)p/"-j=vQ4?xݺH[ZC%!nI9l"[MD8hj]je.&M<g $y"i`كf<IW:qkIBE3]8/7Ai
nj~iRI rknQj9jQtqp<0Y}l\-&hjo3gg{g+݄)1>/K0˦r?vOkxiZ>4/Z1GeD
˃XW%X~%ճk#B~hKEPV[49*(䙘O*om!ad!`0BblۄF
YGc=aqfsAPb4φΏ2Nx}QsW&Q|0>ICiuO/xbY?dnؿoF.ۏWx4	g,z/|fayx9c$M9AS
0*MAvhO1'hA(l$kl
2?&;v$F1QZ?βtjU(ey`g8G$ܳM7ȡ$d3wHٛF@ІX~ʂm/ǷaҳY~6SAjG=I{do@}k(p61^ߋ4"%`5!_TRi֕#'dxlӛ#q`f,Y|iTeׁYWƥJKhR!$kEXKZeaΖLyc < ^>BLsi7e`/4}}|vs"qI0CzeHmew%|k1W}zz!x3}dB?3m u,.X0lw7[0Iq[R`8U&*ע9riva]b1N.!Kh`jjL{Z|8(kAdӏ-XE?	HF %w=!<?X=V6r
MMɢ/LЉY[$x#id+HF8췪=#!ɹ{o_jK* ǟF 91L֫{X܊aQ{ṰZ!0	.4x"C(A8RU$7	17}
9= i*X M	-WZAD/И>͎%Qԋo.nڰ($V䘞'絍﮼iWFܷLsv)'&u 䃜."V )4AAB"o?~60f`@*(ݡnp2H<Qp}s)
Z;8 \cn@vWnOիzßF5?Ao7| 漌$`3~.W9(9k5z(Dg@}A5}CQt䉷^_fEyȵHކ<a`ψa+?s/^Lʆwp#6Q̔4݊9I+@J9aRn
~۽9Ev`"Ȯ^~[O>].~u"QC8z[Sbb3mzF3	v۝-uGyF]kFZꮑbSjg&onlSVm=۔tGZ)F[vvzVoo#L&6;Z9E<;ש&HbZho]vzi	m%QgSke7'% ܪͭ:e%Ħ%H[ݨv7{hl5!\[&%8xn^u4MI UתLSTol66׳IׂslN9Qn/6'1Rw}}4'Ijog;۔Ďkxw2%9Gz𨺙iNbA_d`b[[j(۔~$=zCmԵDiI`og{TTs4JO[G-GJ25[g%^SG 762MJݾ(ۤqlt$n'~ڮfΣv4)Ɏ|V&%mfI	[٩pod`@LStl:Oy׷LJ[[rRv4QT#%FHJz!:ع>tMJu^9IGLӯvGR2RolMJH;^-ۤw~9IBnTMJʲzm#6NgdۛN=ۤ:u__6)y{۽zmRb#9g_7:C>tuЋ)ϒIfo=kLl:*\LרN"%Ob)l42U[Qrufa$a.ƕuB!g];tWZVbooooYۮߨAX@<S *-+O_e5wNn˫EIz`IX+^ax9"{;z\4tЙ=p>~0ƧE%p>ˍ
\,i``60&Ӏ^PeIp8QK\a(rlH9&!+L1B~" DKn thݘ{1`,@H㭐!Y5ÒDrAC$;zU`)G
+.zQopd	t	C%N#uJ_$pdк O(Ϯhtޠ NƜ򢈦kn_N~{zsE{^7W[ы;8~_[Z'gS{;9e7o~zpj6Jy|xeI+GPuRAKqz~<o5[i14wNwoOyvxt|xQaD^ٳ̝r8E)v<x~h/FuJ&h\NߗDgS:8b/`-Z;mAgw{ur|8y8cG'gwgRA. SP?w$5[wo[͓",/  TF'S~y݀杻O0v2xVNϑ7^5_5Xz<kagXIØhʸD U4Dɚ/KdB(;|-]Zu{A1n~|~V'Wd8MN]U cr싲Wq<x-hYG}|b~*fPxB΃LlSpg}kZQ0>AwvO%},{rlļє$`,I]C>}pN
ꠋO{d,iH2r@4|>遼1o^fQt^Tm-.R[>J5IFf]u-)WХW9OUid|kgj]*wEspOH6`Cf;9$odڲAc	-V$ڬ"k0-l\f xgM  U:jnq^%*	;Lf/`oYcZadsoz,-u2#Xjl/s
`ՁmKŻɴX|'o^wR4o%LWtXu@ɹ/_?1ܠQao;Z\j]bs~azD-XVs-ݥbw:y~WyI.31ujώFuTzE*<m2pjv"VG2Y;Wd|PVU8튒>+SLն/MB'8^`P?t }&uQ$v1\[ŰE#r6v	YtI TP?31FG `GKe!2T6eFHe@7vwWw.0%:8UDwIGXe2+/r9e@FZe=k:U"
=# oֳB;}R/%ο-gQ?s<҉g3T`zdS-0K	cY:1K $>ās% ,nPȉKz	.]@ߘ	}5#4M+U<[Le$nd;cf䔜~_X/6&osO58
D>b,<x $~l"u~ksc;p_5!9u#bW,S3o^&؁Eӧ;.&ޝTȬN
p!k`C"ѓ	}Np컓$K`8n@N%J߰Q6m_&y{yɓ=m-eCe:L/qy\<q3;'L{$1%&)e`~ mI-Bb@uo
EHDb%&f|Eu\vi,\KdI19oW[=s&ˢٰ*u^JJ#BChYtHV%uեehKQ8Q'ev\Dxl63^6=LRqXcZ RD%w4҈SQyg9y& m~9Ԁ1=c{Ȉ&\5٪/Ԇ%!|IDM" `)ĸI5#):vw{q˔l/S֯Q{ߞiNz.ɜ2jDB_(;,7*OO4i{/RU$0ۤ{!nNDC8Ľ%fz|m룷mhkݥGVjrUs:C>n1J/^Oi5(#֨@G=}VYO1Vqzzr56j6[VZ#=ky1!ު/1іT|*֗Uq֩uT~|aᩮK"п.rHwv̲-vܟye@0.YQEVU?_c:ܔbz=ǟϰVfXw߷n5Oۇ'/9Nn>;N0^$頱=%sZRhG])UcYw3\5i6h~b_c8{ɚ	EL|*N,e^99]%0Y<ɢVq^q*pJ|ppqڀiW*Lfie|]:ŭY@M%06kdJ<hOmW13^\rժvc)	1Def5jth<mk(gs"`gQǛEƉ&Œ7,Zu=FϭZ#SC,=i/dGX*JITCрėKĿRhXCEvKD]3QzgU
W7RQ?`HHOU*S -"I2)qA-*CUt|!נh}=QSsD-=O<ޫT*e8vw<[ߝ]Χx=u/Q>zE*QZ!wyH-VR/v/EAqb/[r:u#śC6ŒY<*cV,`(&ZV5Ixh˓~WqNey+R1Wp@-']Q֞`\RaYR_~5~(Ø/{2+VLIcJ'.|O($0tXx7[^Vd"ZEX{a7]}=ߎ_a#;66WZS7'&f~u`~܋A}K  Ҥۓ)Nz.&3W^,si!=?5Wd[kL"C9Upw&wotT}M+DZSjwSLKG$L0bǸZ*9<%٣<Bj5K\t]@4)R+M )rJpxgp61%|%Ĉjwgho3 	Ti0p!E#I6#	nZĬ =?vH<	4Tpc?<{=O)12\ILgt<Pf634i?9"֘Þ")Ɓ\¥]O%-
oѓW`gf&H|RTT>V8V_fNX1fnoPmBTW@*F	i$`\x䉕=]4`6GSq+wd0<45,
8j+U˭i&dMocOSiT.d0|OhΧFX34ᏏKKƲzLܸf֨_Xĕ%)h
~cY3"2臃yr|Y،w~.%(.x]*&1W\j6ED<jicZ0"D7^nCт3XKȥdF:ִtPbEGl$1AٔZ8Kc"JkWVu~i#@q[&2kY+#t9"&d4]`ޫ%$q#)If1.j@6:FuCUV9~5lP%xMg]]v-MS?|}u(	i*ǭ6$W%Ltn:m '/57tL%>j2oAtlDM~:I~9jC DT޿mp=ofLxί ċ}knTε35 2]1Lyn`%uC썢ȱ'@_s8&7թl!qG3Ȕf]T^z.fc߇qy=LvhыI5M2d';d@.ivw%VW|.LLIzw ]m<g(s*Q1Ss4{f76 v$z=`%y!YڞGT*[\Z>V:mq~&S.Զ关50-	8"$3ʾny\0$!$<MJԽtܘ-O1X{bf0"ߡ	9f6焆̡$+Sk0l4@:c)Ԟx*dY>oݶF?Yww/05lPtƸvd$ScL^L$8&.={Aʊ.Gݔb&(TփcOnKo=ϠX9gIqT=8mo%ƅN]vn6D=PN @+#iXKch^R^v_T/9TEgji+Pڭ^Kar pf7X9KI0	l>
yWǄs/RM>@sE{t#%1
Q</%-OW+2Z#U*]=b>pƢf =c6@Y/ӡiNQgҔhdƝc'2*9Z>FmB_o,.!0ÖFguFȰTf04)&	ʇ&aaIw
Lwq))xړpW:^9٧#1V@y^J~㴥p_݂  -_@kgW>z+G#ʙzT~AGCa~vq8j9 6B' K	;vڲoh{a|^"n[!z^)Ӣ!jf0T+{,
vQfnk0pL'5{8O"ڧ+fQ>}y\US%>>|y<j+^bLwEDlL[=.a34p,0HH_4iWG$JK|#]7Dv;1{WXg<C*)qbSVe*<4~X r=3JeXd,Y6ht!Ŀ(ͻ}=:Y1"Έp@Pr_.S{T7μߧIM<t?`k؎x@D|U߫o
8dB]9o'8_^V tI8@_XXM8܌j"2Im-󩓔fȿf鄏kQ@0oMژ*>^g"uF%ihˠ
&AI< k/hPYW(x$ -ȹJ)e$׸O98bӘP2et A@&ųK7f
5~2vĖ 9	U`976Luv{\M^<ĩ&ʅ~c\I%ch'}œ$bnC0IK|<GL0\DnpAhWT㑡;i%t´ZW@ת0uٍd>HJn#	M6:{Kw0mDHָӠ`«kFǝbneY  %t'u	iolԌ>;H/i:Q$D53LךߍC^JQ6ƶ%pm_dMg2=! L52@$ϲGj]Ţc:[VH6+c=Wo.D>GӢiѓz0YtJOXZ}BݴNѸ[zY P=nȊ9iH#A0i#;!˯ltIBl:2M3^>""6Ioxf涀vyI	_1&rK&kKjޜZho6Qa62-1O5_b~R9ydlޮi":)h]9POF;ޟXU~_1^ wW~fi|[$s5umYd0<΅0xyO)_2h\.bx)hPq9ՠMXEvHKFip?Ybz$؟*K'5i~gS|ПEM"C_FbR2Æ%t~J΃'%R$`,-jo޾l5UHՋ4>oWL5mL}BΞф*my;o%61%D	OFϋ0, )#/!IzƃY\1[_.ʼL=p3=M"ל)E6*KRҞ$ui8oϏ?=ΩFFe+ZDM(2^YZm0SfӃßڧ''e\N{tPixby^5{a8MEӑB]AGEh$o2y^QT<x8HJ
b~t~4<"G9(}SPimAi9C.ip|nz!LMwGʬl
B~Z[5^o7M9_6P4RBgfVCŸGq/hvu:phO+C?ʗjLՌS~q{>
鴩qлd_pܶ92il|Go3/]˷n{O]Sq6`0vWYW?47"PՊ~eiFhdub-cݰ|2zXY&GҔNU+-\jH昑Sܗ[.hbLHˑCn7OcNƣ,@5~5_.Ӽ^peI4Xz6JRWFҡv^F~!TxbӬ~fi՞~C3Ԇi6?6׭/J,&ɚ$+78:^j%G,TbT:eliˡF|pL>Fir`djC)iԸ4>iUHLb"CkxJhY5?B2HF9W@\CEWp9JRplƥa"݁D>;iP	.dkBSrR-* oU22{4V^n*RKf,ex'}ҎʔVp/#ֈ`nDDkGfy+OzLԮWkZkBh-K
gzCGKdc̮0Q 6_^|h>.~>N9^		>s8䧨<붭{5 Xs-/6>q;GX *dmfnr}}]NԮ89eCc;:Wp =Х/ޠ#|Gg]Agʹc c@ҙ/~T/}]We\r| ݔ<k~%EDS`q?Et>ês()-Vl5N
UNg{8e|SX6v9u[1sܯ̣ievam\1[=zRmBm>WAew9l!	glRxx61ˊ!-wz<:Ú}v51OapEd<#K )̪((ghf ݻ?0Ll\UjV~ZwU"wV0ͳ55(J U F`92w2ד{/T"iZ5/@tVʉC"{yc&IY:.1O}}D/=_Jr-L`V8v.	SbL	- Qǽ @_ɬuȼ9mO	SLpk7.ɆH} Y獢ߣ_eam?`H/,_4q	d<&#ˇ1ߢ3xDÒjQ`^΄f{=䁜"<'pŹrߓx$=EDI8/xt`baއJyiCe;=bz~PC9-h
q M!=a7B F9o0EN˓yg8]vy,w	WRE]\l̚gԄ~'躃1ľ+Gt o':?f5oZu)?rjƼna*k?ӐT7ix9G(R(ϮiP
9<oYI|пblĦw
{9wۣ;S* !{yѠI-T\as9qUh#A9^e;'Et+tO`Fy5@7I7$'Oi)K8X$X)9GC EU8O'<ge*N|iA	ŏbM[9I^GOib3CI5C@_3ԀT^ϸ.
.AQPbi`![
t:Ŷ`]{u8B&I7O=*8_jR@:wGq/-"Ԏ⢠7k-_g'=?yܝGa3z%Ѳ

3f966#C)TK ջXr=jL (JO-bʦ:T|j(B_3~
L>֡Ɇ
&Hde_ט9GP4ž-`짞W 8^_c`}x~texEq(Cf|yo|29.˛(4:V@UБ)<c:`bo
/fUG$0\qAi4p#΁f&d|Z_EL{*ig T"FcTZ(*7+vX ?<Y+k%|UoaW)f4f^eRbuÄ&uWSIN&	nupCqʙ#>rC_?ZIt7$/;NF65;A4venc!E4N`%5Љ)ŏn]hh%SFQeHب$IAT3HGz _H+0-\ <XO(hGpQ䝍_CsJT\(ƪe 2JTl+_h2%=yT8R_ڔ=a"0ˤ寬A`C^6ݽ:OH3OE:m%zN,?4tVv@lK@liV6ƧJUI*F4ѐ=j00.\AZ^FRZATeh\* *$uuB|1ni1$oǷ`0Ã0Qyt/>]`ip|=gg̥xyY4M1SiІO0[@ 00|*kkhkx߯;ݰKxf^!(mv0m.ZsQ96Ia  Qf=Z
ZVXgvB!hk,^~aO4
X__n_BV!/bL@QLTaTj3{׸<bbˮ}_҂| BI`Qvmlu,9V!&Ҕ+`ŝ\ J&\ĕ~ff.B=P&
Ss{@(̈Ԡ-hL68+E"U(ɦղ]ӠGVF,Z>24#ƍn"6ja7ack**uerA*߁"u #7;J52|-7!#	jN Z{mIɡo2Xɝ޻piGXX1\0]F#-n0ƔGpTYO8!+Slb(r z"#3.UƨQɡNJZ$goU4.2@l[˖<%rȀ'c!|@20<z<#QeҬz*RN̑_X%onBufFl0дtkj+*220Y"JdR.oRFȆ7d1mJs-.Ʒ#`Pyp8簜­kf]-[XO3#&qZrK&5tpSuS0\^יvbU8ġ8Wxr*a%EYJf-䱉ZxuEZJaK	2	͹R3pP |ƳTC.x	365|8X[VĈ_ۢtw+O?VyQ/?ߵlgt_y1}aX<b/PyPJ{pl~^xqDvUzli*۩(gtCߔ/w{a'bd1#wg2\ş?.gU`:P/[1FH JхF#r×`8@
QT/=!#	JMRT1BdO$]*/Q?I}1X"
KҍcYN@L?B*oY'\)6sDЁ1
c
YĔt1`s5<<k3BIC˕"5m@9"-Z>gm#b	.;\kcM&Ú	ͦAi8J27Ui7<ٚՌ]37,i[Lg($/BZ2r'w0xYX=bn>Q\Js3)le_b$aד!8ꖘi$UǃaIQKQ8بL)JKiӖ܈/΢-k`5(њ`h :Ihh39H7j=K."tAOgQ	L
rPXRɲOtFO.(0eJJapKTٷ\ (Ysjm=E,L@뉖hG-]>mjU⃖5==lVUm;ukIcYs0%y$fiCAu!0֚N1lMS9ƒW1%jm.Q,7Y:@aŭTrG>b.W%@0PK,@ZdG۸/|tኸok^{LŪ\C3)~\zt]ڹp1\+R?86{O3d p$g609D84{0 @".4Dєg%ʘq27yC
pHc[Q9'2;R>)ԞxLSQxu@)r	`TƸ,Oc	WmX 80QPox#JBfaWe	r$U]`
c~Du_bnΫH7PrŏjПTC<j[>[j%B!bFH	Y"RFlgLGlٖpڂQ^q.wzŐ31sK~t3DնپcҬԅ\Bʇq-љ1
.ԧqyƸ<	BZ*V uG%;&$ZyDVXKkʱhkdI /VҵHnB̳MOcz%d0q4$7>	M$G'	7}0'[`@jV#,G焎흀N<F]Jߚ]u ^qXs* DUsc 1Ql͙:ߘdVui_6<dLh@u,1>!g3&pZJ>4.:=@6A5cپ1bȬ'm%67znlaoD)G>;FDz&I'c\b`oaWma8󊷕zX	~ȶ|"Hd+r.%3IY.iz|)Dp
AP0x]h7Cke-cPaabȱEXP?.+Tȋ+_ב?|􊛠Y(\V/4YODɖ"eT Y}$)p.QE|E/ޝ-:cUɓ{[ysp|8k	EF| dS	{P?q/&+_Hd0p/)Đ/4[@ceV.ß;pri̊zQ:=l̀φe^<G_`Hhng8
C9K>~gZ*.CQ
X&&]<keQ+&b&\Y+|̻ŋ`̸*QHm%{Omkb?۫Ԙ,80LL@oo	h9b ֞ZqQh?.Y	9Jǀ{g!Ƹ.SRr<EM1;7b%c<a[ 1:	en*Y8_WaQJGIBOh-$S$wRdtV	_h%K&
"$2DWdcAm
03[d*4FCcw$\ZcV4)4~Aky2YϤ#{*[hgD{nCDA	 S1#-4ٟJ%S|
.;HOV#Q>F7IVHYq;T%&>Z5+RaZ(.Bxp#IElL!.e~#y#ƘKl dX #kQV*X]NXߓWzJRҍl
\Q+Us%cnS#X,ҒOdc0aL6ԆI>Nm=`m-MFFB'EX+(VXQzD_>೛]4?W FMsިO{v-	j>rJ9{J<6a@JmW[E't;F_pZe@QP~[z3y$K-J1.}]=6&2kC6!3/lbV![/cB7Ae1#bs\]XnMFH,VI
kF_[V̒$[itM.jLPu+)9Y{Nk$8Zy0c(8=FF2Ys,AJ])rƺWB[Hi-4
+_B>E8̕uj,p5_tw"a+gIې)@j(@Y&󃄞^XPDh8/գXxRY\|.nz/4ւ9bqx;I#0wg]_/Ec:NC?0Ol+(<np!xmm<	VauDu3Fq$_F䫲+N1(OJ5	ҔfE2@>8.@x52D|]d#yՒduQЏy >6bRICKBeXyr1=paFD|}}
}bpr+1Wܤ @n?B+zZ'}zp֊@(n&ohzi[*=(s4&[>9+
wdB
/al/@ŗqaЏI>{si=C	Ѩxk"b쇵F(LޢI7'cA($%?OveAh4oZ߼lɧ͢$p%X3lQc-ꛫ$[N\rsvCk{uf?DKH"ҷq]	$g(2
5*]OýͬtӘ(_jY(1E
eEW(g-=U\@Ň2^q^0< h)SGR2#p9vaH75(O[a8&eyD68Q7B*K-c<F[}(Hv
*k>t^oaP1$BVf"UŏO%24R;k=3LecŎGVxMyEeeahWUFͱO˄ocJQF9|߰Ȗ	pbvMwVyqЙ
BDtIGCh'm3#ݱTk<:,Ć2qg$FǤOʁ؝'-f(xAD@#3^}K<:z5
	"CY~*W9>'
K!K4MX f/IJMio/a:t2\P4Vuv#zj	aE$әVZUY@ysfcKboW!hfu',+\#RuHرawBN8NS(tuH@v. ]jMEK.DJ7%bY=FIuiulcŔ!sJA'݂^o0wh[`&jڿT`r9im<;ߚG:9Un<tHZK--WөKy@u3ۺ
˧otwPWiZRh/>HxR<O%P₋.ps:\iBίK 7[:U"KG H.1`ICqNi0<xů"t33eT-'P8gR0"	[D+~d^<$O\۵Jb!z8U0T
@m۸M\e}2"Ւ.qd2'5aToYoO! 5Y	B=qX[WςNKq%Et%+FQ[Rv>mٳM=]XhXkK%&{;I..K./c^&r*?˛Z2EkPx{=ŤPa)\S$Jw]*3s^95g2n` d,JFb@Q"L&Ք5AԌVа<cWwҒjˍ7䎏,Z˝׊yGa7q628ЬѠ+2͉7/_ׄ!%'W`	ҨOu%Z1QHO;FGtҡɵNz\Hbt.щi97E2Tf&D:y\^IBg%e3nʰ^F2grC2(݀D2RV%E9V3S	)\qSKƷJl|Ĝ<bo>23t="Wiz%PX["eKTYğ<jnsPB!2WUbZL*HmɯǠ^8C R)vYt괕IEVuP(؎TƭN%	F#p%(=-K2L^_LĖQ5kl>%اbYv&b߀V&(-o
*P\'2zsvlaK=
{Ǜ.|U<J@mK'd|sqe82*Pg%D@H;Dlmo lG|w[o9^+Tᇊ)*	p_[-߰2{@L1ml\R\W9<d4b2;aR"c{]. 7UV`dzR=q)֧n|lύY:HFFq%0"wB=iV˅/ܲ2Nn& D	H6EZW*q8hh?jNP4@OWM8G[Xo߄
q{d0leaaxY^e%kH5Xv~/S0 ~b~Yy(2Az:%\W}'+ 'jCHɏh$EA "l*'[!,-YTЀrrIB1"%	Ű<OJ/
 `:蟷Yƫ?tf2O,?+Ê?W&72>|X<ݽjz޽`_ēIsYE{=Iѥ@zΣ0H>7\.JNc2D'v!FI4CI_b]2x^N;hiqh<	#ɢ[7ZZ;`w`>O.h]4j }?dJ^渒RT)BŞRªHEU*shrUY\קKM']K,{ៅs̇ߕO®=~bbǕv`pπIlI˓a!V<\TxZުRT `̈̐Ef,2Yaq0 /ڕU֡HSa7b<&`GQt%F(c,.:5|>m'B&Xln?a+ʫO|[M{iT#y~	1Ѡa:2Z{֎=d,rHEP7^Pu+ދyGbr&Rnmm	}x	"3^8g?YȎCYzO(3TseKBRKБ#@.YaeUݦB=NjyVU%BrXσ^X"Ca
MeqAB{D;Џ~o;]h;8*26]휉V$;ͥǢ7ƺGrI+2,5A   ` D                                                                                                                                                                                                                                                                                                                                                                                            checksums.yaml.gz                                                                                   0000444 0000000 0000000 00000000452 15172366541 014617  0                                                                                                    ustar 00wheel                           wheel                           0000000 0000000                                                                                                                                                                         aie9@E^Eo=@1?33w#WoC!xx^߾y/?~<r"r>!R\P`L蝶`s)޼ϬẉЮ&'TsG4XF'q2vMߠބ/ )T Kph˽b'\"1 aF4@O:;3+h_Ĺ:qsF<Zk_-kR*bZ栴" z(2mXmA'<VS!5\s?btpqI4&e[Lcpۣ}^UY                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        #!/opt/alt/ruby30/bin/ruby

require 'lsapi'

$count = 0;

while LSAPI.accept != nil
	print "HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\nHello World! \##{$count}<br>\r\n"
	ENV.each_pair {|key, value| print "#{key} is #{value}<br>\r\n" }
	$count = $count + 1
end
#!/opt/alt/ruby30/bin/ruby

require 'lsapi'
require 'cgi'


while LSAPI.accept != nil
    cgi = CGI.new
    name = cgi['name']
    puts cgi.header
    puts "Hello #{name}! <br> " if name
    puts "You are from #{cgi.remote_addr}<br>"

end
#
# setup.rb
#
# Copyright (c) 2000-2005 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.
#

unless Enumerable.method_defined?(:map)   # Ruby 1.4.6
  module Enumerable
    alias map collect
  end
end

unless File.respond_to?(:read)   # Ruby 1.6
  def File.read(fname)
    open(fname) {|f|
      return f.read
    }
  end
end

unless Errno.const_defined?(:ENOTEMPTY)   # Windows?
  module Errno
    class ENOTEMPTY
      # We do not raise this exception, implementation is not needed.
    end
  end
end

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


class ConfigTable

  include Enumerable

  def initialize(rbconfig)
    @rbconfig = rbconfig
    @items = []
    @table = {}
    # options
    @install_prefix = nil
    @config_opt = nil
    @verbose = true
    @no_harm = false
  end

  attr_accessor :install_prefix
  attr_accessor :config_opt

  attr_writer :verbose

  def verbose?
    @verbose
  end

  attr_writer :no_harm

  def no_harm?
    @no_harm
  end

  def [](key)
    lookup(key).resolve(self)
  end

  def []=(key, val)
    lookup(key).set val
  end

  def names
    @items.map {|i| i.name }
  end

  def each(&block)
    @items.each(&block)
  end

  def key?(name)
    @table.key?(name)
  end

  def lookup(name)
    @table[name] or setup_rb_error "no such config item: #{name}"
  end

  def add(item)
    @items.push item
    @table[item.name] = item
  end

  def remove(name)
    item = lookup(name)
    @items.delete_if {|i| i.name == name }
    @table.delete_if {|name, i| i.name == name }
    item
  end

  def load_script(path, inst = nil)
    if File.file?(path)
      MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path
    end
  end

  def savefile
    '.config'
  end

  def load_savefile
    begin
      File.foreach(savefile()) do |line|
        k, v = *line.split(/=/, 2)
        self[k] = v.strip
      end
    rescue Errno::ENOENT
      setup_rb_error $!.message + "\n#{File.basename($0)} config first"
    end
  end

  def save
    @items.each {|i| i.value }
    File.open(savefile(), 'w') {|f|
      @items.each do |i|
        f.printf "%s=%s\n", i.name, i.value if i.value? and i.value
      end
    }
  end

  def load_standard_entries
    standard_entries(@rbconfig).each do |ent|
      add ent
    end
  end

  def standard_entries(rbconfig)
    c = rbconfig

    rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT'])

    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)))))

    if c['rubylibdir']
      # V > 1.6.3
      libruby         = "#{c['prefix']}/lib/ruby"
      librubyver      = c['rubylibdir']
      librubyverarch  = c['archdir']
      siteruby        = c['sitedir']
      siterubyver     = c['sitelibdir']
      siterubyverarch = c['sitearchdir']
    elsif newpath_p
      # 1.4.4 <= V <= 1.6.3
      libruby         = "#{c['prefix']}/lib/ruby"
      librubyver      = "#{c['prefix']}/lib/ruby/#{version}"
      librubyverarch  = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}"
      siteruby        = c['sitedir']
      siterubyver     = "$siteruby/#{version}"
      siterubyverarch = "$siterubyver/#{c['arch']}"
    else
      # V < 1.4.4
      libruby         = "#{c['prefix']}/lib/ruby"
      librubyver      = "#{c['prefix']}/lib/ruby/#{version}"
      librubyverarch  = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}"
      siteruby        = "#{c['prefix']}/lib/ruby/#{version}/site_ruby"
      siterubyver     = siteruby
      siterubyverarch = "$siterubyver/#{c['arch']}"
    end
    parameterize = lambda {|path|
      path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix')
    }

    if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg }
      makeprog = arg.sub(/'/, '').split(/=/, 2)[1]
    else
      makeprog = 'make'
    end

    [
      ExecItem.new('installdirs', 'std/site/home',
                   'std: install under libruby; site: install under site_ruby; home: install under $HOME')\
          {|val, table|
            case val
            when 'std'
              table['rbdir'] = '$librubyver'
              table['sodir'] = '$librubyverarch'
            when 'site'
              table['rbdir'] = '$siterubyver'
              table['sodir'] = '$siterubyverarch'
            when 'home'
              setup_rb_error '$HOME was not set' unless ENV['HOME']
              table['prefix'] = ENV['HOME']
              table['rbdir'] = '$libdir/ruby'
              table['sodir'] = '$libdir/ruby'
            end
          },
      PathItem.new('prefix', 'path', c['prefix'],
                   'path prefix of target environment'),
      PathItem.new('bindir', 'path', parameterize.call(c['bindir']),
                   'the directory for commands'),
      PathItem.new('libdir', 'path', parameterize.call(c['libdir']),
                   'the directory for libraries'),
      PathItem.new('datadir', 'path', parameterize.call(c['datadir']),
                   'the directory for shared data'),
      PathItem.new('mandir', 'path', parameterize.call(c['mandir']),
                   'the directory for man pages'),
      PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']),
                   'the directory for system configuration files'),
      PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']),
                   'the directory for local state data'),
      PathItem.new('libruby', 'path', libruby,
                   'the directory for ruby libraries'),
      PathItem.new('librubyver', 'path', librubyver,
                   'the directory for standard ruby libraries'),
      PathItem.new('librubyverarch', 'path', librubyverarch,
                   'the directory for standard ruby extensions'),
      PathItem.new('siteruby', 'path', siteruby,
          'the directory for version-independent aux ruby libraries'),
      PathItem.new('siterubyver', 'path', siterubyver,
                   'the directory for aux ruby libraries'),
      PathItem.new('siterubyverarch', 'path', siterubyverarch,
                   'the directory for aux ruby binaries'),
      PathItem.new('rbdir', 'path', '$siterubyver',
                   'the directory for ruby scripts'),
      PathItem.new('sodir', 'path', '$siterubyverarch',
                   'the directory for ruby extentions'),
      PathItem.new('rubypath', 'path', rubypath,
                   'the path to set to #! line'),
      ProgramItem.new('rubyprog', 'name', rubypath,
                      'the ruby program using for installation'),
      ProgramItem.new('makeprog', 'name', makeprog,
                      'the make program to compile ruby extentions'),
      SelectItem.new('shebang', 'all/ruby/never', 'ruby',
                     'shebang line (#!) editing mode'),
      BoolItem.new('without-ext', 'yes/no', 'no',
                   'does not compile/install ruby extentions')
    ]
  end
  private :standard_entries

  def load_multipackage_entries
    multipackage_entries().each do |ent|
      add ent
    end
  end

  def multipackage_entries
    [
      PackageSelectionItem.new('with', 'name,name...', '', 'ALL',
                               'package names that you want to install'),
      PackageSelectionItem.new('without', 'name,name...', '', 'NONE',
                               'package names that you do not want to install')
    ]
  end
  private :multipackage_entries

  ALIASES = {
    'std-ruby'         => 'librubyver',
    'stdruby'          => 'librubyver',
    'rubylibdir'       => 'librubyver',
    'archdir'          => 'librubyverarch',
    'site-ruby-common' => 'siteruby',     # For backward compatibility
    'site-ruby'        => 'siterubyver',  # For backward compatibility
    'bin-dir'          => 'bindir',
    'bin-dir'          => 'bindir',
    'rb-dir'           => 'rbdir',
    'so-dir'           => 'sodir',
    'data-dir'         => 'datadir',
    'ruby-path'        => 'rubypath',
    'ruby-prog'        => 'rubyprog',
    'ruby'             => 'rubyprog',
    'make-prog'        => 'makeprog',
    'make'             => 'makeprog'
  }

  def fixup
    ALIASES.each do |ali, name|
      @table[ali] = @table[name]
    end
    @items.freeze
    @table.freeze
    @options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/
  end

  def parse_opt(opt)
    m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}"
    m.to_a[1,2]
  end

  def dllext
    @rbconfig['DLEXT']
  end

  def value_config?(name)
    lookup(name).value?
  end

  class Item
    def initialize(name, template, default, desc)
      @name = name.freeze
      @template = template
      @value = default
      @default = default
      @description = desc
    end

    attr_reader :name
    attr_reader :description

    attr_accessor :default
    alias help_default default

    def help_opt
      "--#{@name}=#{@template}"
    end

    def value?
      true
    end

    def value
      @value
    end

    def resolve(table)
      @value.gsub(%r<\$([^/]+)>) { table[$1] }
    end

    def set(val)
      @value = check(val)
    end

    private

    def check(val)
      setup_rb_error "config: --#{name} requires argument" unless val
      val
    end
  end

  class BoolItem < Item
    def config_type
      'bool'
    end

    def help_opt
      "--#{@name}"
    end

    private

    def check(val)
      return 'yes' unless val
      case val
      when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes'
      when /\An(o)?\z/i, /\Af(alse)\z/i  then 'no'
      else
        setup_rb_error "config: --#{@name} accepts only yes/no for argument"
      end
    end
  end

  class PathItem < Item
    def config_type
      'path'
    end

    private

    def check(path)
      setup_rb_error "config: --#{@name} requires argument"  unless path
      path[0,1] == '$' ? path : File.expand_path(path)
    end
  end

  class ProgramItem < Item
    def config_type
      'program'
    end
  end

  class SelectItem < Item
    def initialize(name, selection, default, desc)
      super
      @ok = selection.split('/')
    end

    def config_type
      'select'
    end

    private

    def check(val)
      unless @ok.include?(val.strip)
        setup_rb_error "config: use --#{@name}=#{@template} (#{val})"
      end
      val.strip
    end
  end

  class ExecItem < Item
    def initialize(name, selection, desc, &block)
      super name, selection, nil, desc
      @ok = selection.split('/')
      @action = block
    end

    def config_type
      'exec'
    end

    def value?
      false
    end

    def resolve(table)
      setup_rb_error "$#{name()} wrongly used as option value"
    end

    undef set

    def evaluate(val, table)
      v = val.strip.downcase
      unless @ok.include?(v)
        setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})"
      end
      @action.call v, table
    end
  end

  class PackageSelectionItem < Item
    def initialize(name, template, default, help_default, desc)
      super name, template, default, desc
      @help_default = help_default
    end

    attr_reader :help_default

    def config_type
      'package'
    end

    private

    def check(val)
      unless File.dir?("packages/#{val}")
        setup_rb_error "config: no such package: #{val}"
      end
      val
    end
  end

  class MetaConfigEnvironment
    def initialize(config, installer)
      @config = config
      @installer = installer
    end

    def config_names
      @config.names
    end

    def config?(name)
      @config.key?(name)
    end

    def bool_config?(name)
      @config.lookup(name).config_type == 'bool'
    end

    def path_config?(name)
      @config.lookup(name).config_type == 'path'
    end

    def value_config?(name)
      @config.lookup(name).config_type != 'exec'
    end

    def add_config(item)
      @config.add item
    end

    def add_bool_config(name, default, desc)
      @config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc)
    end

    def add_path_config(name, default, desc)
      @config.add PathItem.new(name, 'path', default, desc)
    end

    def set_config_default(name, default)
      @config.lookup(name).default = default
    end

    def remove_config(name)
      @config.remove(name)
    end

    # For only multipackage
    def packages
      raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer
      @installer.packages
    end

    # For only multipackage
    def declare_packages(list)
      raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer
      @installer.packages = list
    end
  end

end   # class ConfigTable


# This module requires: #verbose?, #no_harm?
module FileOperations

  def mkdir_p(dirname, prefix = nil)
    dirname = prefix + File.expand_path(dirname) if prefix
    $stderr.puts "mkdir -p #{dirname}" if verbose?
    return if no_harm?

    # Does not check '/', it's too abnormal.
    dirs = File.expand_path(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(path)
    $stderr.puts "rm -f #{path}" if verbose?
    return if no_harm?
    force_remove_file path
  end

  def rm_rf(path)
    $stderr.puts "rm -rf #{path}" if verbose?
    return if no_harm?
    remove_tree path
  end

  def remove_tree(path)
    if File.symlink?(path)
      remove_file path
    elsif File.dir?(path)
      remove_tree0 path
    else
      force_remove_file path
    end
  end

  def remove_tree0(path)
    Dir.foreach(path) do |ent|
      next if ent == '.'
      next if ent == '..'
      entpath = "#{path}/#{ent}"
      if File.symlink?(entpath)
        remove_file entpath
      elsif File.dir?(entpath)
        remove_tree0 entpath
      else
        force_remove_file entpath
      end
    end
    begin
      Dir.rmdir path
    rescue Errno::ENOTEMPTY
      # directory may not be empty
    end
  end

  def move_file(src, dest)
    force_remove_file 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 force_remove_file(path)
    begin
      remove_file path
    rescue
    end
  end

  def remove_file(path)
    File.chmod 0777, path
    File.unlink path
  end

  def install(from, dest, mode, prefix = nil)
    $stderr.puts "install #{from} #{dest}" if verbose?
    return if no_harm?

    realdest = prefix ? prefix + File.expand_path(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(*args)
    $stderr.puts args.join(' ') if verbose?
    system(*args) or raise RuntimeError,
        "system(#{args.map{|a| a.inspect }.join(' ')}) failed"
  end

  def ruby(*args)
    command config('rubyprog'), *args
  end
  
  def make(task = nil)
    command(*[config('makeprog'), task].compact)
  end

  def extdir?(dir)
    File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb")
  end

  def files_of(dir)
    Dir.open(dir) {|d|
      return d.select {|ent| File.file?("#{dir}/#{ent}") }
    }
  end

  DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn )

  def directories_of(dir)
    Dir.open(dir) {|d|
      return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT
    }
  end

end


# This module requires: #srcdir_root, #objdir_root, #relpath
module HookScriptAPI

  def get_config(key)
    @config[key]
  end

  alias config get_config

  # obsolete: use metaconfig to change configuration
  def set_config(key, val)
    @config[key] = val
  end

  #
  # srcdir/objdir (works only in the package directory)
  #

  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.4.1'
  Copyright = 'Copyright (c) 2000-2005 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' ],
    [ 'test',     'run all tests in test/' ],
    [ 'clean',    "does `make clean' for each extention" ],
    [ 'distclean',"does `make distclean' for each extention" ]
  ]

  def ToplevelInstaller.invoke
    config = ConfigTable.new(load_rbconfig())
    config.load_standard_entries
    config.load_multipackage_entries if multipackage?
    config.fixup
    klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller)
    klass.new(File.dirname($0), config).invoke
  end

  def ToplevelInstaller.multipackage?
    File.dir?(File.dirname($0) + '/packages')
  end

  def ToplevelInstaller.load_rbconfig
    if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg }
      ARGV.delete(arg)
      load File.expand_path(arg.split(/=/, 2)[1])
      $".push 'rbconfig.rb'
    else
      require 'rbconfig'
    end
    ::Config::CONFIG
  end

  def initialize(ardir_root, config)
    @ardir = File.expand_path(ardir_root)
    @config = config
    # cache
    @valid_task_re = nil
  end

  def config(key)
    @config[key]
  end

  def inspect
    "#<#{self.class} #{__id__()}>"
  end

  def invoke
    run_metaconfigs
    case task = parsearg_global()
    when nil, 'all'
      parsearg_config
      init_installers
      exec_config
      exec_setup
      exec_install
    else
      case task
      when 'config', 'test'
        ;
      when 'clean', 'distclean'
        @config.load_savefile if File.exist?(@config.savefile)
      else
        @config.load_savefile
      end
      __send__ "parsearg_#{task}"
      init_installers
      __send__ "exec_#{task}"
    end
  end
  
  def run_metaconfigs
    @config.load_script "#{@ardir}/metaconfig"
  end

  def init_installers
    @installer = Installer.new(@config, @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
    while arg = ARGV.shift
      case arg
      when /\A\w+\z/
        setup_rb_error "invalid task: #{arg}" unless valid_task?(arg)
        return arg
      when '-q', '--quiet'
        @config.verbose = false
      when '--verbose'
        @config.verbose = true
      when '--help'
        print_usage $stdout
        exit 0
      when '--version'
        puts "#{File.basename($0)} version #{Version}"
        exit 0
      when '--copyright'
        puts Copyright
        exit 0
      else
        setup_rb_error "unknown global option '#{arg}'"
      end
    end
    nil
  end

  def valid_task?(t)
    valid_task_re() =~ t
  end

  def valid_task_re
    @valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/
  end

  def parsearg_no_options
    unless ARGV.empty?
      task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1)
      setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}"
    end
  end

  alias parsearg_show       parsearg_no_options
  alias parsearg_setup      parsearg_no_options
  alias parsearg_test       parsearg_no_options
  alias parsearg_clean      parsearg_no_options
  alias parsearg_distclean  parsearg_no_options

  def parsearg_config
    evalopt = []
    set = []
    @config.config_opt = []
    while i = ARGV.shift
      if /\A--?\z/ =~ i
        @config.config_opt = ARGV.dup
        break
      end
      name, value = *@config.parse_opt(i)
      if @config.value_config?(name)
        @config[name] = value
      else
        evalopt.push [name, value]
      end
      set.push name
    end
    evalopt.each do |name, value|
      @config.lookup(name).evaluate value, @config
    end
    # Check if configuration is valid
    set.each do |n|
      @config[n] if @config.value_config?(n)
    end
  end

  def parsearg_install
    @config.no_harm = false
    @config.install_prefix = ''
    while a = ARGV.shift
      case a
      when '--no-harm'
        @config.no_harm = true
      when /\A--prefix=/
        path = a.split(/=/, 2)[1]
        path = File.expand_path(path) unless path[0,1] == '/'
        @config.install_prefix = path
      else
        setup_rb_error "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} <global option>"
    out.puts "  ruby #{File.basename $0} [<global options>] <task> [<task options>]"

    fmt = "  %-24s %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, '   --help',    'print this message'
    out.printf fmt, '   --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 fmt, name, desc
    end

    fmt = "  %-24s %s [%s]\n"
    out.puts
    out.puts 'Options for CONFIG or ALL:'
    @config.each do |item|
      out.printf fmt, item.help_opt, item.description, item.help_default
    end
    out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's"
    out.puts
    out.puts 'Options for INSTALL:'
    out.printf fmt, '--no-harm', 'only display what to do if given', 'off'
    out.printf fmt, '--prefix=path',  'install path 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_test
    @installer.exec_test
  end

  def exec_show
    @config.each do |i|
      printf "%-20s %s\n", i.name, i.value if i.value?
    end
  end

  def exec_clean
    @installer.exec_clean
  end

  def exec_distclean
    @installer.exec_distclean
  end

end   # class ToplevelInstaller


class ToplevelInstallerMulti < ToplevelInstaller

  include FileOperations

  def initialize(ardir_root, config)
    super
    @packages = directories_of("#{@ardir}/packages")
    raise 'no package exists' if @packages.empty?
    @root_installer = Installer.new(@config, @ardir, File.expand_path('.'))
  end

  def run_metaconfigs
    @config.load_script "#{@ardir}/metaconfig", self
    @packages.each do |name|
      @config.load_script "#{@ardir}/packages/#{name}/metaconfig"
    end
  end

  attr_reader :packages

  def 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

  def init_installers
    @installers = {}
    @packages.each do |pack|
      @installers[pack] = Installer.new(@config,
                                       "#{@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|
      setup_rb_error "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

  #
  # 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_test
    run_hook 'pre-test'
    each_selected_installers {|inst| inst.exec_test }
    run_hook 'post-test'
  end

  def exec_clean
    rm_f @config.savefile
    run_hook 'pre-clean'
    each_selected_installers {|inst| inst.exec_clean }
    run_hook 'post-clean'
  end

  def exec_distclean
    rm_f @config.savefile
    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 verbose?
      Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}")
      Dir.chdir "packages/#{pack}"
      yield @installers[pack]
      Dir.chdir '../..'
    end
  end

  def run_hook(id)
    @root_installer.run_hook id
  end

  # module FileOperations requires this
  def verbose?
    @config.verbose?
  end

  # module FileOperations requires this
  def no_harm?
    @config.no_harm?
  end

end   # class ToplevelInstallerMulti


class Installer

  FILETYPES = %w( bin lib ext data conf man )

  include FileOperations
  include HookScriptAPI

  def initialize(config, srcroot, objroot)
    @config = config
    @srcdir = File.expand_path(srcroot)
    @objdir = File.expand_path(objroot)
    @currdir = '.'
  end

  def inspect
    "#<#{self.class} #{File.basename(@srcdir)}>"
  end

  def noop(rel)
  end

  #
  # Hook Script API base methods
  #

  def srcdir_root
    @srcdir
  end

  def objdir_root
    @objdir
  end

  def relpath
    @currdir
  end

  #
  # Config Access
  #

  # module FileOperations requires this
  def verbose?
    @config.verbose?
  end

  # module FileOperations requires this
  def no_harm?
    @config.no_harm?
  end

  def verbose_off
    begin
      save, @config.verbose = @config.verbose?, false
      yield
    ensure
      @config.verbose = save
    end
  end

  #
  # TASK config
  #

  def exec_config
    exec_task_traverse 'config'
  end

  alias config_dir_bin noop
  alias config_dir_lib noop

  def config_dir_ext(rel)
    extconf if extdir?(curr_srcdir())
  end

  alias config_dir_data noop
  alias config_dir_conf noop
  alias config_dir_man noop

  def extconf
    ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt
  end

  #
  # TASK setup
  #

  def exec_setup
    exec_task_traverse 'setup'
  end

  def setup_dir_bin(rel)
    files_of(curr_srcdir()).each do |fname|
      update_shebang_line "#{curr_srcdir()}/#{fname}"
    end
  end

  alias setup_dir_lib noop

  def setup_dir_ext(rel)
    make if extdir?(curr_srcdir())
  end

  alias setup_dir_data noop
  alias setup_dir_conf noop
  alias setup_dir_man noop

  def update_shebang_line(path)
    return if no_harm?
    return if config('shebang') == 'never'
    old = Shebang.load(path)
    if old
      $stderr.puts "warning: #{path}: Shebang line includes too many args.  It is not portable and your program may not work." if old.args.size > 1
      new = new_shebang(old)
      return if new.to_s == old.to_s
    else
      return unless config('shebang') == 'all'
      new = Shebang.new(config('rubypath'))
    end
    $stderr.puts "updating shebang: #{File.basename(path)}" if verbose?
    open_atomic_writer(path) {|output|
      File.open(path, 'rb') {|f|
        f.gets if old   # discard
        output.puts new.to_s
        output.print f.read
      }
    }
  end

  def new_shebang(old)
    if /\Aruby/ =~ File.basename(old.cmd)
      Shebang.new(config('rubypath'), old.args)
    elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby'
      Shebang.new(config('rubypath'), old.args[1..-1])
    else
      return old unless config('shebang') == 'all'
      Shebang.new(config('rubypath'))
    end
  end

  def open_atomic_writer(path, &block)
    tmpfile = File.basename(path) + '.tmp'
    begin
      File.open(tmpfile, 'wb', &block)
      File.rename tmpfile, File.basename(path)
    ensure
      File.unlink tmpfile if File.exist?(tmpfile)
    end
  end

  class Shebang
    def Shebang.load(path)
      line = nil
      File.open(path) {|f|
        line = f.gets
      }
      return nil unless /\A#!/ =~ line
      parse(line)
    end

    def Shebang.parse(line)
      cmd, *args = *line.strip.sub(/\A\#!/, '').split(' ')
      new(cmd, args)
    end

    def initialize(cmd, args = [])
      @cmd = cmd
      @args = args
    end

    attr_reader :cmd
    attr_reader :args

    def to_s
      "#! #{@cmd}" + (@args.empty? ? '' : " #{@args.join(' ')}")
    end
  end

  #
  # TASK install
  #

  def exec_install
    rm_f 'InstalledFiles'
    exec_task_traverse 'install'
  end

  def install_dir_bin(rel)
    install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755
  end

  def install_dir_lib(rel)
    install_files libfiles(), "#{config('rbdir')}/#{rel}", 0644
  end

  def install_dir_ext(rel)
    return unless extdir?(curr_srcdir())
    install_files rubyextentions('.'),
                  "#{config('sodir')}/#{File.dirname(rel)}",
                  0555
  end

  def install_dir_data(rel)
    install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644
  end

  def install_dir_conf(rel)
    # FIXME: should not remove current config files
    # (rename previous file to .old/.org)
    install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644
  end

  def install_dir_man(rel)
    install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644
  end

  def install_files(list, dest, mode)
    mkdir_p dest, @config.install_prefix
    list.each do |fname|
      install fname, dest, mode, @config.install_prefix
    end
  end

  def libfiles
    glob_reject(%w(*.y *.output), targetfiles())
  end

  def rubyextentions(dir)
    ents = glob_select("*.#{@config.dllext}", targetfiles())
    if ents.empty?
      setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first"
    end
    ents
  end

  def targetfiles
    mapdir(existfiles() - hookfiles())
  end

  def mapdir(ents)
    ents.map {|ent|
      if File.exist?(ent)
      then ent                         # objdir
      else "#{curr_srcdir()}/#{ent}"   # srcdir
      end
    }
  end

  # picked up many entries from cvs-1.11.1/src/ignore.c
  JUNK_FILES = %w( 
    core RCSLOG tags TAGS .make.state
    .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb
    *~ *.old *.bak *.BAK *.orig *.rej _$* *$

    *.org *.in .*
  )

  def existfiles
    glob_reject(JUNK_FILES, (files_of(curr_srcdir()) | files_of('.')))
  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 glob_select(pat, ents)
    re = globs2re([pat])
    ents.select {|ent| re =~ ent }
  end

  def glob_reject(pats, ents)
    re = globs2re(pats)
    ents.reject {|ent| re =~ ent }
  end

  GLOB2REGEX = {
    '.' => '\.',
    '$' => '\$',
    '#' => '\#',
    '*' => '.*'
  }

  def globs2re(pats)
    /\A(?:#{
      pats.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| GLOB2REGEX[ch] } }.join('|')
    })\z/
  end

  #
  # TASK test
  #

  TESTDIR = 'test'

  def exec_test
    unless File.directory?('test')
      $stderr.puts 'no test in this package' if verbose?
      return
    end
    $stderr.puts 'Running tests...' if verbose?
    begin
      require 'test/unit'
    rescue LoadError
      setup_rb_error 'test/unit cannot loaded.  You need Ruby 1.8 or later to invoke this task.'
    end
    runner = Test::Unit::AutoRunner.new(true)
    runner.to_run << TESTDIR
    runner.run
  end

  #
  # TASK clean
  #

  def exec_clean
    exec_task_traverse 'clean'
    rm_f @config.savefile
    rm_f 'InstalledFiles'
  end

  alias clean_dir_bin noop
  alias clean_dir_lib noop
  alias clean_dir_data noop
  alias clean_dir_conf noop
  alias clean_dir_man noop

  def clean_dir_ext(rel)
    return unless extdir?(curr_srcdir())
    make 'clean' if File.file?('Makefile')
  end

  #
  # TASK distclean
  #

  def exec_distclean
    exec_task_traverse 'distclean'
    rm_f @config.savefile
    rm_f 'InstalledFiles'
  end

  alias distclean_dir_bin noop
  alias distclean_dir_lib noop

  def distclean_dir_ext(rel)
    return unless extdir?(curr_srcdir())
    make 'distclean' if File.file?('Makefile')
  end

  alias distclean_dir_data noop
  alias distclean_dir_conf noop
  alias distclean_dir_man noop

  #
  # Traversing
  #

  def exec_task_traverse(task)
    run_hook "pre-#{task}"
    FILETYPES.each do |type|
      if type == 'ext' and config('without-ext') == 'yes'
        $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)], '')
      directories_of(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

  def run_hook(id)
    path = [ "#{curr_srcdir()}/#{id}",
             "#{curr_srcdir()}/#{id}.rb" ].detect {|cand| File.file?(cand) }
    return unless path
    begin
      instance_eval File.read(path), path, 1
    rescue
      raise if $DEBUG
      setup_rb_error "hook #{path} failed:\n" + $!.message
    end
  end

end   # class Installer


class SetupError < StandardError; end

def setup_rb_error(msg)
  raise SetupError, msg
end

if $0 == __FILE__
  begin
    ToplevelInstaller.invoke
  rescue SetupError
    raise if $DEBUG
    $stderr.puts $!.message
    $stderr.puts "Try 'ruby #{$0} --help' for detailed usage."
    exit 1
  end
end
Gem::Specification.new do |s|
  s.name = %q{ruby-lsapi}
  s.version = "5.6"
  s.date = %q{2024-01-22}
  s.description = "This is a ruby extension for fast communication with LiteSpeed Web Server."
  s.summary = %q{A ruby extension for fast communication with LiteSpeed Web Server.}
  s.has_rdoc = false
  s.authors = ["LiteSpeed Technologies Inc."]
  s.email = "info@litespeedtech.com"
  s.homepage = "http://www.litespeedtech.com/"
  s.rubyforge_project = "ruby-lsapi"
  s.files = ["lsapi.gemspec", "README", "examples", "examples/testlsapi.rb", "examples/lsapi_with_cgi.rb", "ext", "ext/lsapi", "ext/lsapi/extconf.rb", "ext/lsapi/lsapidef.h", "ext/lsapi/lsapilib.c", "ext/lsapi/lsapilib.h", "ext/lsapi/lsruby.c", "rails", "rails/dispatch.lsapi", "scripts", "scripts/lsruby_runner.rb", "setup.rb"]
  s.extra_rdoc_files = ["README"]
  s.extensions << "ext/lsapi/extconf.rb"
  s.require_paths << "lib"
end
#!/opt/alt/ruby30/bin/ruby

require 'lsapi'

class CodeCache
    def [](filename)
		mtime = File.mtime( filename )		
		
		entry = @cache[filename];
		if entry != nil 
			return entry
						
		end
		code = compile(filename)
		#entry = CodeEntry.new( filename, mtime, code )
		@cache[filename] = code
		return code
    end

    private

    def initialize
      @cache = {}
    end

    def compile(filename)
		open(filename) do |f|
			s = f.read
			s.untaint
			binding = eval_string_wrap("binding")
			return eval(format("Proc.new {\n%s\n}", s), binding, filename, 0)
		end
    end
end


$count = 0;

$cache = CodeCache.new


while true
	$req = LSAPI.accept 
	break if $req == nil 
	
	filename = ENV['SCRIPT_FILENAME']
	filename.untaint

	filename =~ %r{^(\/.*?)\/*([^\/]+)$}
	path   = $1
	Dir.chdir( path )
	#load( filename, true )	
    code = $cache[filename]
    code.call
	
end

class CodeEntry
	public :path, :name, :mtime, :opcode 
	
	def initizlize( filename, mtime, opcode )
		filename =~ %r{^(\/.*?)\/*([^\/]+)$}
		@path   = $1
		@name   = $2
		@mtime  = mtime
		@opcode = opcode
	end

end


/*
Copyright (c) 2002-2018, Lite Speed Technologies Inc.
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 Lite Speed Technologies Inc 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  _LSAPILIB_H_
#define  _LSAPILIB_H_

#if defined (c_plusplus) || defined (__cplusplus)
extern "C" {
#endif

#include "lsapidef.h"

#include <stddef.h>
#include <sys/time.h>
#include <sys/types.h>

struct LSAPI_key_value_pair
{
    char * pKey;
    char * pValue;
    int    keyLen;
    int    valLen;
};

struct lsapi_child_status;
#define LSAPI_MAX_RESP_HEADERS  1000

typedef struct lsapi_request
{
    int               m_fdListen;
    int               m_fd;

    long              m_lLastActive;
    long              m_lReqBegin;

    char            * m_pReqBuf;
    int               m_reqBufSize;

    char            * m_pRespBuf;
    char            * m_pRespBufEnd;
    char            * m_pRespBufPos;

    char            * m_pRespHeaderBuf;
    char            * m_pRespHeaderBufEnd;
    char            * m_pRespHeaderBufPos;
    struct lsapi_child_status * child_status;


    struct iovec    * m_pIovec;
    struct iovec    * m_pIovecEnd;
    struct iovec    * m_pIovecCur;
    struct iovec    * m_pIovecToWrite;

    struct lsapi_packet_header      * m_respPktHeaderEnd;

    struct lsapi_req_header         * m_pHeader;
    struct LSAPI_key_value_pair     * m_pEnvList;
    struct LSAPI_key_value_pair     * m_pSpecialEnvList;
    int                               m_envListSize;
    int                               m_specialEnvListSize;

    struct lsapi_http_header_index  * m_pHeaderIndex;
    struct lsapi_header_offset      * m_pUnknownHeader;

    char            * m_pScriptFile;
    char            * m_pScriptName;
    char            * m_pQueryString;
    char            * m_pHttpHeader;
    char            * m_pRequestMethod;
    int               m_totalLen;
    int               m_reqState;
    off_t             m_reqBodyLen;
    off_t             m_reqBodyRead;
    int               m_bufProcessed;
    int               m_bufRead;

    struct lsapi_packet_header        m_respPktHeader[5];

    struct lsapi_resp_header          m_respHeader;
    short                             m_respHeaderLen[LSAPI_MAX_RESP_HEADERS];
    void            * m_pAppData;

}LSAPI_Request;

extern LSAPI_Request g_req;


/* return: >0 continue, ==0 stop, -1 failed  */
typedef int (*LSAPI_CB_EnvHandler )( const char * pKey, int keyLen,
                const char * pValue, int valLen, void * arg );


int LSAPI_Init(void);

void LSAPI_Stop(void);

int LSAPI_Is_Listen_r( LSAPI_Request * pReq);

int LSAPI_InitRequest( LSAPI_Request * pReq, int fd );

int LSAPI_Accept_r( LSAPI_Request * pReq );

void LSAPI_Reset_r( LSAPI_Request * pReq );

int LSAPI_Finish_r( LSAPI_Request * pReq );

int LSAPI_Release_r( LSAPI_Request * pReq );

char * LSAPI_GetHeader_r( LSAPI_Request * pReq, int headerIndex );

int LSAPI_ForeachHeader_r( LSAPI_Request * pReq,
            LSAPI_CB_EnvHandler fn, void * arg );

int LSAPI_ForeachOrgHeader_r( LSAPI_Request * pReq,
            LSAPI_CB_EnvHandler fn, void * arg );

int LSAPI_ForeachEnv_r( LSAPI_Request * pReq,
            LSAPI_CB_EnvHandler fn, void * arg );

int LSAPI_ForeachSpecialEnv_r( LSAPI_Request * pReq,
            LSAPI_CB_EnvHandler fn, void * arg );

char * LSAPI_GetEnv_r( LSAPI_Request * pReq, const char * name );

ssize_t LSAPI_ReadReqBody_r( LSAPI_Request * pReq, char * pBuf, size_t len );

int LSAPI_ReqBodyGetChar_r( LSAPI_Request * pReq );

int LSAPI_ReqBodyGetLine_r( LSAPI_Request * pReq, char * pBuf, size_t bufLen, int *getLF );


int LSAPI_FinalizeRespHeaders_r( LSAPI_Request * pReq );

ssize_t LSAPI_Write_r( LSAPI_Request * pReq, const char * pBuf, size_t len );

ssize_t LSAPI_sendfile_r( LSAPI_Request * pReq, int fdIn, off_t* off, size_t size );

ssize_t LSAPI_Write_Stderr_r( LSAPI_Request * pReq, const char * pBuf, size_t len );

int LSAPI_Flush_r( LSAPI_Request * pReq );

int LSAPI_AppendRespHeader_r( LSAPI_Request * pReq, const char * pBuf, int len );

int LSAPI_AppendRespHeader2_r( LSAPI_Request * pReq, const char * pHeaderName,
                              const char * pHeaderValue );

int LSAPI_ErrResponse_r( LSAPI_Request * pReq, int code, const char ** pRespHeaders,
                         const char * pBody, int bodyLen );

static inline int LSAPI_SetRespStatus_r( LSAPI_Request * pReq, int code )
{
    if ( !pReq )
        return -1;
    pReq->m_respHeader.m_respInfo.m_status = code;
    return 0;
}

static inline int LSAPI_SetAppData_r( LSAPI_Request * pReq, void * data )
{
    if ( !pReq )
        return -1;
    pReq->m_pAppData = data;
    return 0;
}

static inline void * LSAPI_GetAppData_r( LSAPI_Request * pReq )
{
    if ( !pReq )
        return NULL;
    return pReq->m_pAppData;
}

static inline char * LSAPI_GetQueryString_r( LSAPI_Request * pReq )
{
    if ( pReq )
        return pReq->m_pQueryString;
    return NULL;
}


static inline char * LSAPI_GetScriptFileName_r( LSAPI_Request * pReq )
{
    if ( pReq )
        return pReq->m_pScriptFile;
    return NULL;
}


static inline char * LSAPI_GetScriptName_r( LSAPI_Request * pReq )
{
    if ( pReq )
        return pReq->m_pScriptName;
    return NULL;
}


static inline char * LSAPI_GetRequestMethod_r( LSAPI_Request * pReq)
{
    if ( pReq )
        return pReq->m_pRequestMethod;
    return NULL;
}



static inline off_t LSAPI_GetReqBodyLen_r( LSAPI_Request * pReq )
{
    if ( pReq )
        return pReq->m_reqBodyLen;
    return -1;
}

static inline off_t LSAPI_GetReqBodyRemain_r( LSAPI_Request * pReq )
{
    if ( pReq )
        return pReq->m_reqBodyLen - pReq->m_reqBodyRead;
    return -1;
}


int LSAPI_End_Response_r(LSAPI_Request * pReq);



int LSAPI_Is_Listen(void);

static inline int LSAPI_Accept( void )
{   return LSAPI_Accept_r( &g_req );                        }

static inline int LSAPI_Finish(void)
{   return LSAPI_Finish_r( &g_req );                        }

static inline char * LSAPI_GetHeader( int headerIndex )
{   return LSAPI_GetHeader_r( &g_req, headerIndex );        }

static inline int LSAPI_ForeachHeader( LSAPI_CB_EnvHandler fn, void * arg )
{   return LSAPI_ForeachHeader_r( &g_req, fn, arg );        }

static inline int LSAPI_ForeachOrgHeader(
            LSAPI_CB_EnvHandler fn, void * arg )
{   return LSAPI_ForeachOrgHeader_r( &g_req, fn, arg );     }

static inline int LSAPI_ForeachEnv( LSAPI_CB_EnvHandler fn, void * arg )
{   return LSAPI_ForeachEnv_r( &g_req, fn, arg );           }

static inline int LSAPI_ForeachSpecialEnv( LSAPI_CB_EnvHandler fn, void * arg )
{   return LSAPI_ForeachSpecialEnv_r( &g_req, fn, arg );    }

static inline char * LSAPI_GetEnv( const char * name )
{   return LSAPI_GetEnv_r( &g_req, name );                  }

static inline char * LSAPI_GetQueryString(void)
{   return LSAPI_GetQueryString_r( &g_req );                }

static inline char * LSAPI_GetScriptFileName(void)
{   return LSAPI_GetScriptFileName_r( &g_req );             }

static inline char * LSAPI_GetScriptName(void)
{    return LSAPI_GetScriptName_r( &g_req );                }

static inline char * LSAPI_GetRequestMethod(void)
{   return LSAPI_GetRequestMethod_r( &g_req );              }

static inline off_t LSAPI_GetReqBodyLen(void)
{   return LSAPI_GetReqBodyLen_r( &g_req );                 }

static inline off_t LSAPI_GetReqBodyRemain(void)
{   return LSAPI_GetReqBodyRemain_r( &g_req );                 }

static inline ssize_t LSAPI_ReadReqBody( char * pBuf, size_t len )
{   return LSAPI_ReadReqBody_r( &g_req, pBuf, len );        }

static inline int LSAPI_ReqBodyGetChar(void)
{   return LSAPI_ReqBodyGetChar_r( &g_req );        }

static inline int LSAPI_ReqBodyGetLine( char * pBuf, int len, int *getLF )
{   return LSAPI_ReqBodyGetLine_r( &g_req, pBuf, len, getLF );        }



static inline int LSAPI_FinalizeRespHeaders(void)
{   return LSAPI_FinalizeRespHeaders_r( &g_req );           }

static inline ssize_t LSAPI_Write( const char * pBuf, ssize_t len )
{   return LSAPI_Write_r( &g_req, pBuf, len );              }

static inline ssize_t LSAPI_sendfile( int fdIn, off_t* off, size_t size )
{
    return LSAPI_sendfile_r(&g_req, fdIn, off, size );
}

static inline ssize_t LSAPI_Write_Stderr( const char * pBuf, ssize_t len )
{   return LSAPI_Write_Stderr_r( &g_req, pBuf, len );       }

static inline int LSAPI_Flush(void)
{   return LSAPI_Flush_r( &g_req );                         }

static inline int LSAPI_AppendRespHeader( char * pBuf, int len )
{   return LSAPI_AppendRespHeader_r( &g_req, pBuf, len );   }

static inline int LSAPI_SetRespStatus( int code )
{   return LSAPI_SetRespStatus_r( &g_req, code );           }

static inline int LSAPI_ErrResponse( int code, const char ** pRespHeaders, const char * pBody, int bodyLen )
{   return LSAPI_ErrResponse_r( &g_req, code, pRespHeaders, pBody, bodyLen );   }

static inline int LSAPI_End_Response(void)
{   return LSAPI_End_Response_r( &g_req );                         }

int LSAPI_IsRunning(void);

int LSAPI_CreateListenSock( const char * pBind, int backlog );

typedef int (*fn_select_t)( int, fd_set *, fd_set *, fd_set *, struct timeval * );

int LSAPI_Init_Prefork_Server( int max_children, fn_select_t fp, int avoidFork );

void LSAPI_Set_Server_fd( int fd );

int LSAPI_Prefork_Accept_r( LSAPI_Request * pReq );

void LSAPI_No_Check_ppid(void);

void LSAPI_Set_Max_Reqs( int reqs );

void LSAPI_Set_Max_Idle( int secs );

void LSAPI_Set_Max_Children( int maxChildren );

void LSAPI_Set_Max_Idle_Children( int maxIdleChld );

void LSAPI_Set_Server_Max_Idle_Secs( int serverMaxIdle );

void LSAPI_Set_Max_Process_Time( int secs );

int LSAPI_Init_Env_Parameters( fn_select_t fp );

void LSAPI_Set_Slow_Req_Msecs( int msecs );

int  LSAPI_Get_Slow_Req_Msecs(void);

int LSAPI_is_suEXEC_Daemon(void);

int LSAPI_Set_Restored_Parent_Pid(int pid);

typedef void (*LSAPI_On_Timer_pf)(int *forked_child_pid);
void LSAPI_Register_Pgrp_Timer_Callback(LSAPI_On_Timer_pf);

int LSAPI_Inc_Req_Processed(int cnt);

int LSAPI_Accept_Before_Fork(LSAPI_Request * pReq);

int LSAPI_Postfork_Child(LSAPI_Request * pReq);

int LSAPI_Postfork_Parent(LSAPI_Request * pReq);

#define LSAPI_LOG_LEVEL_BITS    0xff
#define LSAPI_LOG_FLAG_NONE     0
#define LSAPI_LOG_FLAG_DEBUG    1
#define LSAPI_LOG_FLAG_INFO     2
#define LSAPI_LOG_FLAG_NOTICE   3
#define LSAPI_LOG_FLAG_WARN     4
#define LSAPI_LOG_FLAG_ERROR    5
#define LSAPI_LOG_FLAG_CRIT     6
#define LSAPI_LOG_FLAG_FATAL    7

#define LSAPI_LOG_TIMESTAMP_BITS (0xff00)
#define LSAPI_LOG_TIMESTAMP_FULL (0x100)
#define LSAPI_LOG_TIMESTAMP_HMS  (0x200)
#define LSAPI_LOG_TIMESTAMP_STDERR  (0x400)

#define LSAPI_LOG_PID            (0x10000)

void LSAPI_Log(int flag, const char * fmt, ...)
#if __GNUC__
        __attribute__((format(printf, 2, 3)))
#endif
;


#if defined (c_plusplus) || defined (__cplusplus)
}
#endif


#endif







ELF          >                             @     @ ; :           
                   .   0                      1                -   2                ,   3              fD          Hff.      H    H   H+       H   HOD  H     1f     1f     ATIHUSHc    HcLH    H=    HH    [   ]A\ff.      H     HH=           HfHH=        Hc5    ;5    H=    |6    H        H               HfD      f     ?    IH=     H   H+   9M1~+HHcHc5    H5        ~    Hfff.     @ HH=        tHHHD     Hff.      HH=        H    HHH=        H    HHH=           tH    HH SHH\$Ht$H    H    1H    H[ff.     fAWAVAUAATIUSHH<Q  ~v<R   <Su"   H=    H   @ McLL    HcHI    H=    LH    H   []A\A]A^A_fD  <Pu
   H=    H uƀULcu   H=    H t?   H    IH  HAL)A)McHLHL$    	   H=    H$    H$H=    H    HL$LH       H=    H$    H$H=    H    1A??LIL       H=    I    H=    LH    fD     H=    H r: i@ A   L%    QfD  O<4LE1=    t1@ H    H   =       tUSH;=       H=        HH    Ń   H    H    Hc    H       E1A      H1    H    H       1H[]f.     Hc       H    HuH=           @         1 H=               fD      8    Hپ   H    IH    H81    H       NH=               1fAU1ATUHSHV      -    +    HcD%        IŅt"D)A    DID9uD   HL[]A\A]ÐD)Hc5    HH5    Hc        HL[]A\A]@ H} @u&    xU-        )9OT     ؐD9Hc5    LDNH5    Ic    D%    U@ HA   [L]A\A]ff.     AWAVL5    AUATUSHf     D9-    ~N   }D-    M&   H    Hc=    D)ILHcH    HtL)D)XHcH    Ią~Hc5    HH5    H        HL[]A\A]A^A_f     H1atH#    HfD      SH        2fH        9    }1uٿ   fH[ff.     AUATUHSHdH%(   HD$1   HE1IG@ HI9}HH    H   uj tUHCJHL   IH$    H uHCI9|HL$dH3%(      uVH[]A\A]@ HC f.     H    H    H=        HH   H$        @ 1f     UHSHHdH%(   HD$1uHtHHHtCH       D$@uEHt<HE Hu/H}u;&f      ukHS  tD$@t   H    fD  HE Ht$   H8PHHHDHL$dH3%(   u7H[]fD  H{ BHSHu            y    SHdH%(   HD$1H    H$H    Hu%H    D     H    H    HtH=    H   H    HD$dH3%(   uH[    ff.     fAUATUHSHH      H    fD  HLc H@tOH    Ml$H t\HhHXH   HHI<$AHH[]HD A\A]f.     HtHU HHуHuMl$ uHHhHfD  HHHH8H{@( H    H       H    H81    Fff.     @ SHH[ff.      SH    HH   [ÐUSHH=           tyH=    Ht    H        H                9    uI1H    H-    H;HHu     Hu H;H    H    HH[]D      H    Hu'H           H    H    Ht11Hƿ       hf     H9    tH    ATUHS    L     H5    H=    H            L H    Hu%L%    D     L    H    HtH=    HH[]A\        AWAVAUATUHSHS     GHL-    Ldtf     H   HubfD      HIHI    M~M   IFA|
tH    HH0NHL9t[H;@tHufD  H=           Hf.     Hu5HHHH=4    L9uH   []A\A]A^A_fD  t.fD  M~HHH    L   H    H81    I fH    HH0nff.     AVAUATUHSHdH%(   HD$1      IH6A   L5    H     H   Hu4HA9~NH    H0HtHIt H@tHu@    L    HHA9H    H0Hu;HL$dH3%(      uPH[]A\A]A^ÐHHta    HPfD      IA   HH$    f     AUATUSH    H=    H        H                Ht8
   1HH    HŅ~M   H    H  -    H=        HHtH    HH=  `  X   fo    f    )    H=    1    Ht1
   H1    @H=            H=            H  H      H    HHH    HH    H    Hu L%       L    H    HtL%    HI<$    H5    H    Hu4L-    f.        L    HH    HtH    11H    H=    H           H=           H=    I    H=    LH       H5H=        I4$H=        1H6H5    HH          H=    1HH5        H=       HH5        H=       HZH5        H=    HH5        H=    HlH5        H=    HH5        H=       HH5        H=    1HH5        H=    1HH5        H=    1H:H5        H=    HH5        H=    1HH5        H=    1HH5        H=    1HgH5        H=    1HKH5        H=    1HH5        H=    1HCH5        H=    1H7H5        H=    1HH5        H=    1HH5        H=       HH5        H=    HH5        L%    H=       HL    H-    H    H=    HP H    HJH*H    H    HH    H    H=    L   H    H    H=    HP H    HJH*H        H(    H        H    1H5    H=        H3H=            H(H[]A\A]D  HP   HH=        HwH    H.XXXXXX H(Ht+   H=     ub    H=    1H8H5        H=    1HH5        H=    1HH5            H=        R    H=        H6BfD  m   H    H^K   H    Ht
-    Gk   H    Hu-    *                                                   GA$3p1113                            GA$running gcc 8.5.0 20210514            GA$annobin gcc 8.5.0 20210514            GA$plugin name: gcc-annobin              GA*GOW *            GA*             GA+stack_clash            GA*cf_protection             GA*FORTIFY               GA+GLIBCXX_ASSERTIONS             GA*             GA!              GA+omit_frame_pointer             GA*             GA!stack_realign            GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                            GA$3p1113                            GA$running gcc 8.5.0 20210514            GA$annobin gcc 8.5.0 20210514            GA$plugin name: gcc-annobin              GA*GOW *            GA*             GA+stack_clash            GA*cf_protection             GA*FORTIFY               GA+GLIBCXX_ASSERTIONS             GA*             GA!              GA+omit_frame_pointer             GA*             GA!stack_realign             GA$3p1113                            GA$running gcc 8.5.0 20210514            GA$annobin gcc 8.5.0 20210514            GA$plugin name: gcc-annobin              GA*GOW *            GA*             GA+stack_clash            GA*cf_protection             GA*FORTIFY               GA+GLIBCXX_ASSERTIONS             GA*             GA!              GA+omit_frame_pointer             GA*             GA!stack_realign             GA$3p1113                            GA$running gcc 8.5.0 20210514            GA$annobin gcc 8.5.0 20210514            GA$plugin name: gcc-annobin              GA*GOW *            GA*             GA+stack_clash            GA*cf_protection             GA*FORTIFY               GA+GLIBCXX_ASSERTIONS             GA*             GA!              GA+omit_frame_pointer             GA*             GA!stack_realign             GA$3p1113                            GA$running gcc 8.5.0 20210514            GA$annobin gcc 8.5.0 20210514            GA$plugin name: gcc-annobin              GA*GOW *            GA*             GA+stack_clash            GA*cf_protection             GA*FORTIFY               GA+GLIBCXX_ASSERTIONS             GA*             GA!              GA+omit_frame_pointer             GA*             GA!stack_realign    / QUERY_STRING REQUEST_URI PATH_INFO REQUEST_PATH SCRIPT_NAME %s: %s
 ftruncate() failed. 
 File mapping failed. 
 Memory calloc error 
 [...] %s
 replace srand STDERR reopen nil LSAPI_MAX_BODYBUF_LENGTH LSAPI_TEMPFILE XXXXXX LSAPI_CHILDREN RACK_ROOT chdir() ENV to_hash CGI/1.2 eval_string_wrap LSAPI accept accept_new_connection postfork_child postfork_parent process putc write print printf puts << flush getc gets read rewind each eof eof? close binmode isatty tty? sync sync= RACK_ENV   RSTRING_PTR is returning NULL!! SIGSEGV is highly expected to follow immediately. If you could reproduce, attach your debugger here, and look at the passed string.     GATEWAY_Irewindable_input.rbNTERFACE H    H       H    H81    %                         /tmp/lsapi.XXXXX`       `                                )       a    )                   %J           'Q       (   bint        )5                                                        )        1      3        6	       7	       8	       9	        :	   (    ;	   0    <	   8    =	   @    @	   H    A	   P    B	   X    D  `    F  h    H   p    I   t    J   x    MQ       NX       O      Q      Y       [      \      ]      ^	<       _
>       `       b         c    +"             )       "      "           )               ?       M       !    !      !      !           [  Q P      [             [      a       ~             d        _       r          6         6    !      $       2       7       ;           6          W  )        G                    G                6            4       6	         7	            !&)     eID !')   .    5   KJ                   4                         .    5   "+c       =    "/      "0       "1   .    5   nG                                           	    
                                                                     .    5   	`       .       	v                @    `    #     #     #     #     #     #     #     #      #     @#                                                      @                                                          @f    x#     @#      .    5   ;  #                     .    5   D           7O  ,    P   ,    Q   IL	  /len M    /ptr N   /aux R   7K6  ,    S  Rary T6      F  )    =    (Io  B    Jc   /as U   .    5   H  #                    .    5   R           7\  ,    ]   ,    c   IZ		  /len [    /aux d  /ptr e	     7Y5	  ,    f  Rary gE	     E	  )    5	  =    (Ws	  B    Xc   /as h	       A	  	  g	  0<    =    (C	  B    Dc       Es	      Fs	      G<         M  .    5   #0	             D$
  	      HF_
      G       O_
      P
  0    Q<   8    S  @ I(H
      Is	       Js	      K
      Ls	      M
    J>   
  0   
  <   
  )     
  =    (V  B    Wc       X
      Y      Z<         $"      $#      $$      $%      $&      $'      $(      $)      $*      $+      $-      $/      $0      $1      $2      $3      $4      $5      $6      $7      $8      $9      $:      $;      $<      $=      $>      $?      $@      $A      $B      $C      $D      $E      $F      $G      $H      $I      $J      $K      $L      $M      $N      $P      $Q      $R      $S      $T      $U      $V      $W      $X      $Y      $Z      $[      $\      $]      $^      $_      $`      $a      $b      $c      $d      $e      $f      $g      $h      $i      $j      $k      $l      $m      $o      $p      $q      $r      $t      $v      $v      $v(          %      %      %       %!      %"      &     D  )    4      '0D     `  Q U      '1`      '2`      '3`      '4       '5`      '6`      '7`  h5   (,^                                           	    
                                                         7(q  ,    (s  ,    (t        (k      (m        (n       (o       (p       (u^       ,(_      (        (      (      (      (      (      (      (       (  $    (  (     (      (       (  4     )        )        (      (       (      (      (       (      (       (       (9      ("       ("       /{      1        2       3       4    i    	:      <        =       ?       @       B       C        E   (    F   0    G   8    I   @    J   H    K   P    L!  X    O  `    P  h    Q  p    R  x    T'      V'      W'      X'      Y'       Z'       \'      ]'      _       `       a       b       c       d       e       f      g      h       i   C    k'   C    m'  (C    n'  8C    o<   	 "          )      )<        )>          9  _        )    k     S)        q{      s  ,  J   O  0  0   0  0   0<        *-       *.       +Q       ,      ,g       ,
   s       )    s    "          "          "          "              -Q      -g       -      -      -       V  j    -  >    -g   >    -  >    -  >    -d  >    -   a  a    "          "          "          "          "        $  "    /  /  9    D    O    Z    e    p  Q  {                  
        4        -      -      -!        -{  7-4  ,    -
4  ,    -D  ,    -T     D  )      T  )      d  )        -      -	    d      -      -  J     )        )   @   6    .  6    .  8    "  8    #      $  	            (  	            *  	            ,  	            .   	            9  /req ;   /env <      =     J	    0  0  0>          >a      @  	            B  	            C	  	              E  	        8    F	      G  	            I      K        L       M       N        OG      Q  	             S)        R  	            &  k      	        l    4        S      &  %    6          4p 7           %    8	           ?        ,       	  D    Z*  	        (4H                  ,       Z*QH          EH          dH              SuH              H          
        5]  U| T3     E      %    [           @    [&  %    [           E      D    [  	        94H              [QH          EH          dH              SuH              H          
        5]  U} T7     
        A]  Q0R0  E    H  %              
        M]  THQ	        R|   E      %              
        M]  THQ	        R|   T&              :'              <      #'          .'          M              "  M          
        Y]  Us T0Q:          e]  A  U	                 r]  _  Us TM         r]  }  Us Tm         r]    Us TK 
        r]  Us Tk   &              =      	'          M              (F  M          M          
        ]  U	        Ts QvR
   :mM                         *	  M          ~M                   e]    U	         
        ]  Us    M              @  M          
        Y]  T0Q:          ]          e]  (   U	                 ]          ]          e]  a   U	                 ]          ]          ]     U	                 ^     U	        T7         ^     U	        TA         ^     Q}          '!  U	        T	        Q1         ^  F!  U	                 s!  T	        Q	        R0         !  T	        Q	        R0         !  T	        Q	        R1         !  T	        Q	        R1         ("  T	        Q	        R	         V"  T	        Q	        R	         "  T	        Q	        R	         "  T	        Q	        R1         "  T	        Q	        R0         #  T	        Q	        R0         8#  T	        Q	        R0         f#  T	        Q	        R	         #  T	        Q	        R0         #  T	        Q	        R0         #  T	        Q	        R0         $  T	        Q	        R0         G$  T	        Q	        R0         t$  T	        Q	        R0         $  T	        Q	        R0         $  T	        Q	        R0         $  T	        Q	        R0         (%  T	        Q	        R1         V%  T	        Q	        R	         ]  u%  U	                 ]  %  U	                 &^          &^          2^          C          >^  %  U	                 >^  &  U	                 &^          @&  T	        Q	        R0         m&  T	        Q	        R0         &  T	        Q	        R0         J^  &  U	         
        e]  U	            &  m&   &      n    -U    "'  )p $   U    :'  )n 	   )p    ;      '  *        *    -	  *    9  @      VD    	*  	                         g       (  !               K-                         	        W^          c^          o^                         ^(  A    "  UA    -  T o      }(  *       ;      (  *    !                         (  A    "  U                +       +)  A      U(G                         $G                   U       I*  !              4str           :I*                   
       )  [*           T>-              -,              ;*  ?,              L,  Y,          f,  q,                  Q  ,*  W?,  s          Z-            |^   ;      i*  *    !        y          4      -,  !    y           !    y*	          !    y6          4str {          4n |	           %    }	           %    ~	           L               +  *L              4L          1M                          [+  $M                   ^          ^            Z-          ^  +  Us  $ &         },  +  U|          ^  ,  U} Qs  $ & 
        ^  U} Q|  $ &  ;    J  },  *    J   )str L  @    M   )n N	   )p O         5           a       >-  !    5"           p    7     %    8           %    9	           %    :	           @    ;	   G              ;0-  $G           ^   L    0   L    +   X       y-  )fd 	    X       -  )fd 	   )sfn     L                      2       .  !               4ch 	           K              .  L          AL              RL              \L          fL          pL          zL          L                     ^                         .  !    !                  W^                         N/  5out !          5str ,          
        2  Us TT  ;      /  *       *    *	  2out 6  )i 	   @       ;    l  /  2ary l#  2out l.  *    l7   )tmp n  )i o
         c                 0  !    c           !    c,	          5out c8                  ^  t0  UUTT 
        2  Us        ?          7      2  !    ?           !    ?,	          5out ?8          4i A	           D    B  @G              Tb1  G              	H          
        ^  U~ T3   K              Qa2  K          L              2  L          1OM                          %1  `M           L                          L            K                         K          -               K                     2  y2  Uv          2  2  Uv          2  2  Uv          2  2  Uv          ^          ^        3          !      8  !    3!          5str 3-          %    5	          4len 6	           H              7W5  H          J              J          J              FJ          FJ          K              K	5  'K          K          93K          
     PK          DK          L              4  L          1L                          4  L           OM                          %`M            (K          !               K          -               K              :H                          Q;5  H           
        ^  Us T<    K              9	#6  K          L              5  L          L                         L            K                         K          -               K             J              ;;6  $J  &J              $7J  zJ              	6  J          $J  9J              	J          $J    MCJ      DJ  RJ              $cJ      oJ               I               ;)7  $I      I          &J              O7  $7J  MCJ      DJ    I          	        )       $I  -        )       I  M                  )       	GM  
        M          
        ^  T1Q	        R	              K              <8  L          AL              RL              \L          fL          pL          zL          L                     
_  8  Uv  q        Tv Qs   r    '      ?  !    '          5c '+          sch )
   W%    *	          I              )b=  I          K              4	:  'K          K          (3K                          PK          DK          :L                         K:  L          1L                          :  L           OM                          %`M            (K                  	       K          -        	       K              L              7.;  *L              4L          1M                          [;  $M                   ^  ;  Us          ^    J          	    4)R<  J          &J              7J          zJ              	;  J          J          (J                          	J          J            NCJ                  DJ  RJ                          cJ          -                oJ               tI      5I              I          u&J      <  7J          NCJ                 DJ    vI          $       I          -        $       I  M                  $       	GM  
        M          
        ^  T1Q	        R	               H              +Z?  H          J              J          J              FJ          FJ          K              K	
?  'K          K          93K          	     PK          DK          L              >  L          L              >  L           OM                          %`M            (K                         K          -               K              :H                          Q>?  H           
        ^  Uv T<            s?  TWQ1         ^                  
       ?  A    #  U                3       E@  !    +          5str 7                  _  @  Us          "_  1@  Us  
        ._  T0  <                      @  &    ,                  :_   <                      @  &    +                  G_   <              -       A  &    ,                  T_   <                     B  &    $          Ypid 	           ?        I       kB  H        8    &  H        ?        3       MB        	        4H                  3       QH          EH          dH              SuH              H          
        5]  Us T5     
        A]  U8Q0R0  B               	B   C                  C          a_  B  Qs  
        m_  Qs           y_          o^          ]   w    C  +    )	   x                   HD  ?        S       :D  H           XD  `H       ?        1        D        	        4H                  1       QH          EH          dH              SuH              H          
        5]  Us T7     
        A]  Q1Rw           ^     XD  )     HD  <               B       BE  &    )          &    3           &    H          &    T           Zarg #<                   _  	E  UQT	R $ &         _  -E  U| Ts  $ & 
        ^  Qv   <    k                 pG  &    k(          &    k2           &    kG          &    kS           Zarg l"<           Yp n           ylen o	            _  F  U| T~          _  )F  Us Tv  $ &         ^  AF  Q|          _  _F  U| T?         _  F  U| T         ^  F  U	        T9         ^  F  Qw          _  F  U| T         ^   G  U	        T<         ^  G  Qw          _  7G  U T}          ^  [G  U	        T< 
        ^  Q}   z    a               G  &    a&	          {        _         G  +    ?         G  +    <       
  H  str 
!  'len 

        
   4H  str 
       P  ^H  ptr P^H  str P*         G  H  str G  'len I>          H  obj        <   H  obj        	  H  ary   'tmp        	  I  a        	  ,I  a $         JI  ary           fI  a        v   I  ary v  'f {         I  x   +      +    C        2   I  x 2          J  str   'ptr            &J  str        {F  RJ  str {  V8    F        h   zJ  str h  'f m   [    	   J  2obj 	   *    	         	  J  obj 	  +    	!   |    IK  2v I  2t I*  \    ^\    [ [      3K  2obj   2t +         [K  obj !  t ;         yK  obj          K  obj          K  obj          K  obj          K  obj   'ret          L  v         T   AL  x T  'ret V
        R  L  i R   'j X0   'k Y0   'l Z   'm [   'n \         L  obj          L  obj          L  obj          M  obj   8             1M  obj          OM  obj        m  mM  obj m   O       M  +       +       O    \   M  +    \   +    \   }    i   M  *    i   O    d   N  +    d'  +    d<  ~ 3I*                 /N  G[*  U 3}(                 RN  G(  U 3Z-                Q  l-  :G                         N  $G   K-                          Z-              P      l-          y-              P      -          -          M               	O  M          M          
        ^  T1Q	        Rs           _  O  U	                 _  O  Us          _  O  Us          o^  O  Us          _          _  
        o^  Us            _  6P  Uv Ts          _  hP  U0Ts Q3R1Xv Y0         `  P  Uv          J^  P  U	                 `  P  Uv          J^  P  U	         
        `  Uv            `  Q  T1 
        J^  U	          3-,                 R  L,          Y,  f,          q,          ?,          KL-                          _        },  Q  U
          `  Q  U|  "Tv Q	        R1         ^  Q  Uv  
        ^  U| Qv   3-,          *       zR  ?,          L,  Y,   f,  q,           Z-  ]        Q  W?,  U  3/                 V  /          /          /          ^/  @/          JI              wS  [I          1fI                         JS  wI          -               I            zJ              	J          J          (J                         	J          J             H              yU  H              H          1I                         RT  I          I          I          
        a`  Us   H              I          ,I              	U  =I          zJ          	    J          J          (J                         	J          J             I              U  !I          zJ              	J          J          (J                          	J          J             
        m`  Us     /              lV  /          /          /              ^/  @/  G              saV  G              	H          
        ^  U	        T5   
        y`  U1Tw Qv            y`  V  U1Tw Qv          ^   3:'                 UX  L'          Y'          f'          s'  9:'               f'          Y'          L'              s'          '          1       W  (4H                  1       	*QH          EH          dH              SuH              H          
        5]  U| T6             &^          &^          >^  )X  U	                 &^  ]        A]  QURT    3N/                5]  `/          m/          z/          /  /  N/       ]  $z/  $m/  $`/      /          /          I              GZ  I              I          I              Y  I              I  M              	M          M          
        ^  T1Q	        R}     &J              7J          zJ              	5Z  J          J          (J                         	J          J            MCJ      DJ      K               F[  K          L              Z  L          1OM                          %Z  `M           L                          L            K                         K          -               K             J              $_\  J          &J              7J          zJ          
    	[  J          J          9J              	J          J            NCJ                 DJ  RJ                         cJ          -               oJ               G              \  G              	H          
        ^  U	        T3           
_          2  \  Uv T~          2  \  Uv  
        `  U	        Qv    
        2  Uv   	        9	        / 	        L	                w_        0 P/tmp/lsapi.XXXXXX _        0 P
.XXXXXX         1	        {        n        t        	        2?	        3'	        
J	        4*	        5	        6B	        4#	        75        	        	        8L        3	        9%	        7	        8	        
=	        
j	        		        	        :	        ;8        	        	        Z	        
V	        Z	        [	        /                        }	        	                ^	        
0	        1	        <'	        =%                9	        *%        1        	        89        a                1qP64/opt/alt/ruby30/include/ruby/internal/core/rarray.h 	        	        o	        %0	        >6  B   1B   :;9I8  4 :;9I?<  (   1   I  4 1B  	. ?<n:;9  
1   1   :;9I  1RBUXYW  7 I  & I  U     :;9I  I  .:;9'I 4  (   1RBUXYW  ! I/  4 1  . ?<n:;9  :;9  1RBUXYW  1RBXYW  .:;9'I   $ >  4 :;9I   .:;9'I@B  ! :;9IB  " <  #(   $ 1  %4 :;9IB  & :;9IB  '4 :;9I  (1RBXYW  )4 :;9I  * :;9I  + :;9I  , :;9I  -  .>I:;9  / :;9I8  0 I  11RBXYW  2 :;9I  3.1@B  44 :;9IB  5 :;9IB  64 :;9I?<  7:;9  84 :;9I  91RBUXYW  :1RBXYW  ;.:;9'I   <.:;9'I@B  =:;9  > :;9I8  ?  @4 :;9I  A :;9I  B :;9I8  C :;9I8  D4 :;9I  EU  F
 1  G 1  H4 :;9I  I:;9  J'I  K 1RBXYW  L. :;9I   M1U  N1  O.?:;9'I 4  P6   Q!   R :;9I  S! I/  T 1RBUXYW  U.:;9   V  W 1B  X.:;9I   Y4 :;9IB  Z :;9IB  [.:;9'I 4  \
 :;9  ]B1  ^4 1  _. ?<n:;  `%U  a   b$ >  c :;9  d&   e :;9I  f(   g'  h>I:;9  i:;9  j:;9  k4 :;9I?  l.?:;9@B  m! I/  n. :;9   o.:;9'I  p4 :;9I  q  r.:;9'IU@B  s4 :;9I  t1UXYW  u1UXYW  v1XYW  w.:;9'   x.:;9@B  y4 :;9I  z.:;9'@B  { B1  |.:;9' 4  }.?:;9'I   ~   4 1  4 1  4 1  1  1UXYW  . ?<n                        V                 p                                        P                 P                 P                                          0                 V                 0                 V                 0                                
                                         
                                          
                                           3                                    0                 0                                    0                 0                                
                                         
                                          
                                           7                                   P                                   P                                   P                                       P                 S                 S                                    P                 S                                         P                 S                                       S                 S                                                         S                                  
                         
                                                                                 
                                            P                                     U                 U                                       U                 S                 P                                   U                                       U                 S                 P                                    S                 S                                    
                  
                                     0                 0                                                   U                 S                 U                 S                 U                 S                 U                 S                 U                                                   T                 V                 T                 V                 T                 V                 T                 V                 T                                     Q                 Q                                             P                 ]                 P                 ]                 P                 ]                                        S                 S                 P                 \                                         v |                  v |  $0 $+(                  v  $0 $+(                  v  $0 $+(                  v  $0 $+(                                      P                 P                                     U                 U                                    P                 P                                 U                                       U                 u@                 U                                             $ &        "                          $ &        "                                   P                                     Q                 Q                                     U                 U                                     P                 P                                  P                                   	 p  $ &                 P                                   	 p  $ &                 P                                  P                                  P                                  P                                  P                                     U                 U                                       U                 S                 P                                     T                 T                                     U                 U                                     T                 T                                       Q                 S                 Q                                     U                 U                 1                                         T                 ]                 T                 T                 W                                             Q                 V                 Q                 V                 Q                 V                                     0                 S                 S                 0                                 
                                           3                                     s $ &3$} "                 s $ &3$} "                 s $ &3$} "                                    s $ &3$} "                 s $ &3$} "                                  s $ &3$} "                                 s $ &3$} "                                 s $ &3$} "                                 t O                                               U                 S                 U                 S                 U                 S                 U                                         T                 V                 V                 T                                       \                 \                 \                                   P                                      U                 S                 S                                    <                 <                                      U                 S                 S                                    <                 <                                      U                 S                 S                
                    <                 <                
                      U                 S                 S                                      U                 S                 S                                 U                                  S                                 S                                 s O                                 S                                     P                 V                 V                                      P                 V                 V                                 P                                 V                                  q O                
                 
                   
                  
                 
                   
                                    Q                
                     V                 V                 V                                     p                  U                                 P                                	 p  $ &                                	 p  $ &                                 p  $ &1$#                	                    p  $ &1$#                 P                
                    p  $ &1$#                 P                                    p  $ &1$#                 P                                                     U                 V                 U                 V                 U                 U                 V                 U                 U                 V                                           T                 S                 T                 S                 S                                   P                                            T                 S                 S                 S                 S                 S                                  5                                    T                 S                                  5                                    T                 S                                    T                 S                                 T                                  S                                 S                                  p O                                   S                 S                                    P                 P                                 S                                   S                 S                                  S                 S                                 
                                   S                                 
                                   S                	                 S                	                 P                 p O>$                 p >%O                                      S                 S                 S                                         Q                 Q                 Q                 s                                   S                                  S                                     p                  U                                   V                 V                                   <                 <                                   V                 V                                   <                 <                                   V                 V                	 	                  <                 <                	 	                  V                 V                                   V                 V                                 V                 V                                  V                                 V                                 v O                                 V                                     U                 U                                   T                                     U                 U                                     U                 U                                     U                 U                                     U                 U                                       P                 P                	                                         
                                         
                                          
                                           5                                   S                                
                                         
                                          
                                           7                                       U                 \                 U                                       T                 S                 T                                     Q                 Q                                     R                 R                                     X                 X                                           U                 S                 S                 S                 S                                                   T                 V                 T                 T                 V                 T                 V                 T                 V                                             Q                 \                 Q                 \                 Q                 \                                                     R                 ]                 R                 ]                 R                 ]                 ^                 R                 ]                 ^                                             X                 X                 X                 X                 X                 X                                         P                 _                 P                 _                                     U                 U                                       V                 V                 	                 V                                            	                 P                 V                 V                 P                 V                                       P                 S                 S                                  
                                              p                  U                                       P                 \                 P                                   S                                     P                 P                                  ?,                                       U                 U                                             U                 S                 U                 S                 U                 U                                             T                 V                 T                 V                 T                 V                                         Q                 Q                 Q                 Q                                       ]                 }                 ]                 ]                                    S                 S                                  S                                    P                 p H<$                 p ?%3                 s ?%3                                  
                                    S                                  
                                    S                                    S                 S                                   S                 S                                                                                                                                                   S                                    S                 S                                  S                	                  @E$                	                  S                                  @E$                                  S                                    S                 S                	                 
                  	                 S                	                 
                  	                 S                                    U                 U                                    Q                 Q                                     T                 V                                 
                                           5                                         U                 S                 Q                 U                                         T                 V                 R                 T                                     Q                 Q                                    Q                 Q                                       V                 R                 T                                       S                 Q                 U                                   \                                
                                         
                                          
                                           6                                         U                 U                 U                 U                                         T                 T                 T                 T                                             Q                 V                 Q                 V                 Q                 V                                   0                                           U                 P                 ^                 P                 ^                                    ^                 ^                 ^                                    _                 _                                  ^                                 
                                              p                  U                                   ^                 ^                                  
                                    ^                                  
                                    ^                                       U                 U                 U                                    U                 U                                  U                                 U                                  U                                  u O                                     ^                 ^                 ^                                     ^                 ^                 ^                
                  
                   
                  
                  ^                 ^                
                  
                   
                  
                  ^                 ^                                 ^                                   P                 p O>$                 P                                 
                                           3                <                                   .                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       b   l        /opt/alt/ruby30/include/ruby/internal/arithmetic /usr/include/bits /opt/alt/ruby30/include/ruby/internal /opt/alt/ruby30/include/ruby/internal/core /opt/alt/ruby30/include/ruby/internal/intern /usr/include /usr/lib/gcc/x86_64-redhat-linux/8/include /usr/include/bits/types /usr/include/sys /opt/alt/ruby30/include/ruby /usr/include/netinet  lsruby.c    lsapilib.h    int.h   long.h   stdio2.h   special_consts.h   rarray.h   rgengc.h   fl_type.h   string.h   char.h   value_type.h   rdata.h   rtypeddata.h   rstring.h   symbol.h   stdlib.h   string_fortified.h   stddef.h   types.h   struct_FILE.h   FILE.h   stdio.h   sys_errlist.h   types.h 	  stdint-intn.h   stdint-uintn.h   unistd.h   getopt_core.h   math.h   time.h   time.h 	  value.h   rbasic.h   robject.h   globals.h   io.h   ruby.h   version.h 
  lsapidef.h    struct_iovec.h   errno.h   sockaddr.h   socket.h   in.h   signal.h   eval.h   <built-in>    string.h   variable.h   gc.h   hash.h   module.h   error.h   variable.h   mman.h 	  iterator.h   sprintf.h   parse.h   gc.h   util.h 
  thread.h     	        JK?K|	#t>iK>KK{KY;./<X KJOOtYKKtY}t	jp	2]T	w~.}<t	g}	#}.-MsJ)u<ttY	KitKt
JtYZ}	.|JYHZ~.KKtYvKKtYtK	Kt	[u 		Jw		XwX		X<Z ~.K<%XXt<.X<hI,JX.X^f)  X  .% X=(3<(J3<f88g;gc9X.X "fp K;<f//	RX}	t		0Yfq\:>X.	t" ut/u* uZ^	%gfu	Z3	X
|t	|<
tXXu Kt	.t.	X	f.	f*8ut		X			o.@5<	t-<	tiJJ	[X{J
.P	j[		L( ff	{X<9=t;K1tQJ/f J	L2	
=t<UMtUX&<<
`	0<f@	L5	t-<	tj<TKt	Jt X K
b y<
~
	
U~
		tZ J}	?~nJ<	Z~ \	 h<Pxf	 h	YJ	K#L	K"U  ~  	    h    < 	\"J _Jf	~		
~zXtX		KY.	J~	X
u 	<. <
 = ff	~
.Q;	X
K~R	X
u 	f <
  tf
<~ ~i	h	]c	%J t<
K~R	X
u 	f.~JJ 	~t%	 J	D[XX 	        XtxX		t	s\ g (K~R	X
u <fX~<J~uJ 	f	~i	h	YJ~Jb	j	~	~J.~.X.~ <X	dK<fh~Xi	h	]cJiJg	b	j	e	R <
  f
<~.~	
ttX<K =YJK =Xf~.K
ht	\tY	Z		Y	d	.btZY	vyg~txX		t	s\Kp	X	=Z	vZX	>*ztxX		t	s\  *X 	        }K
}f <
		Y;	=}b	h<	J	eJj J	Z~<u 	f

}z<	~df	_\sX	g}e		Kbi	h	cJ=	X	
t<X bi	h<	<Y.	>~
~XT <
Xt	Z~"h	~u 	f

~zwX
~k	~d	f jY:g<	KXKYsbXtv
SY|X	|X<	L/$eX<
z
<
zt	yt5Y|X|.Xz	Zrh	Y		*ytxX		tt	s\y.tuyxX		t	sqwZ7v-uY"u{wtJvI;tZvpJuI==[X=XvXuv0X>f~z
t	gz
t	 d(v#G< Y(%[$  	        	
t.<.X 
 rb_mWaitWritable _sys_errlist m_pScriptFile RUBY_Qnil rb_eNoMemError _unused2 wrap_struct_name _fileno rb_cMethod rb_obj_wb_unprotect rb_eSyntaxError m_cntUnknownHeaders H_AUTHORIZATION sockaddr_iso blockSize m_pIovecEnd strcpy m_pRespBufPos RUBY_FL_EXIVAR __uint8_t dmark _Bool RUBY_DATA_FUNC m_pktHeader rb_eIOError m_bytes RARRAY_EMBED_LEN m_pHeader RSTRING_LEN rb_data_object_get _shortbuf sockaddr_in rb_cFile rb_eSignal unlink lsapi_data RUBY_T_ARRAY rb_eKeyError add_env_rails __environ lsapi_addstr rbimpl_rtypeddata_p ruby_robject_consts sa_data uint16_t m_totalLen sin_zero RUBY_FL_UNTRUSTED rb_eZeroDivError in_port_t _flags lsapi_gets calloc m_respPktHeader __off_t createTempFile dfree RUBY_T_IMEMO rb_global_variable _lock ROBJECT_EMBED_LEN_MAX RUBY_T_UNDEF /builddir/build/BUILD/opt/alt/ruby30/share/gems/gems/ruby-lsapi-5.6/ext/lsapi rb_cString rb_eEOFError atoi m_pHttpHeader LSAPI_GetReqBodyRemain_r m_pScriptName rb_mKernel m_pEnvList rb_output_fs int32_t __fmt sa_family m_specialEnvListSize mask rb_cModule sockaddr_ns __u6_addr8 RUBY_T_FALSE rb_cInteger RUBY_T_FILE _IO_write_end m_iLen sockaddr rb_cTrueClass s_addr RUBY_FL_USER0 RUBY_FL_USER1 RUBY_FL_USER2 RUBY_FL_USER3 RUBY_FL_USER4 RUBY_FL_USER5 RUBY_FL_USER6 RUBY_FL_USER7 RUBY_FL_USER8 RUBY_FL_USER9 nameLen LSAPI_Postfork_Child free rb_fs m_requestMethodOff RUBY_T_COMPLEX __tzname data_struct_obj rb_eEncCompatError ruby_special_consts rb_intern_const valLen RSTRING_EMBED_LEN_SHIFT __stack_chk_fail ruby_rarray_flags ruby_description sin_family RString m_fdListen MAX_BODYBUF_LENGTH rb_data_type_t m_status m_reqBodyLen rb_eNameError optarg needRead rb_eRegexpError rb_cBasicObject RUBY_T_STRUCT rb_cRational rb_cFloat type rb_cStat sys_errlist RSTRING_EMBED_LEN in_addr_t basic RUBY_Qtrue daylight LSAPI_ReqBodyGetChar_r pKey __uint16_t sin_port RUBY_T_STRING rb_cFalseClass m_flag RARRAY_EMBED_LEN_SHIFT readMaxBodyBufLength Check_Type m_pQueryString _chain RUBY_T_MODULE rb_eArgError rb_eInterrupt recur rb_funcallv rbimpl_intern_const RUBY_FL_SINGLETON sockaddr_un unsigned char capa nRead m_cntSpecialEnv _IO_lock_t RUBY_T_ZOMBIE float LSAPI_key_value_pair LSAPI_ForeachHeader_r rb_stderr lsapi_each m_cntHeaders rb_str_cat bodyBuf RARRAY_EMBED_LEN_MAX RB_TEST RUBY_T_FIXNUM rb_eSecurityError isEofBodyBuf lsapi_process lsapi_flush RARRAY_EMBED_FLAG off_t child_status RUBY_SYMBOL_FLAG rb_mComparable H_X_FORWARDED_FOR __fprintf_chk m_queryStringOff H_TRANSFER_ENCODING RUBY_FLONUM_FLAG rb_stdout ruby_rstring_flags H_CONTENT_LENGTH rb_cTime ruby_engine _IO_write_ptr rb_output_rs lsapi_packet_header LSAPI_ReadReqBody_r rb_eFatal lsapi_http_header_index rb_funcall_argc sTempFile rb_funcall_args strcat close shared lsapi_printf RUBY_T_OBJECT FILE H_COOKIE s_fn_add_env munmap RSTRING_EMBED_LEN_MAX bodyCurrentLen LSAPI_Accept_Before_Fork rb_cNumeric s_req_stderr rb_cHash size_t rb_array_const_ptr H_CONNECTION getdate_err rb_rs uint8_t H_CONTENT_TYPE RArray lsapi_mark m_headerLen RUBY_ELTS_SHARED rb_data_type_struct perror lsapi_env ruby_release_date rb_cDir setup_cgi_env _IO_save_base iovec lsapi_eof rb_array_const_ptr_transient environ lsapi_child_status readTempFileTemplate rb_str_new sockaddr_x25 rb_eLoadError sin6_flowinfo fastpath m_pIovecToWrite orig_stderr m_respHeaderLen _wide_data H_IF_MATCH RUBY_FL_PROMOTED0 RUBY_FL_PROMOTED1 __in6_u H_ACC_CHARSET ruby_version orig_stdout __stream signgam ruby_copyright m_reqBufSize rb_eException rb_yield add_env_no_fix RUBY_T_FLOAT RUBY_T_CLASS ftruncate ruby_fl_type lsapi_request strerror rb_cComplex fprintf rb_check_type RUBY_T_HASH sync RUBY_T_NODE chdir reserved __ssize_t __src rb_mErrno lsapi_close H_IF_RANGE nameOff ruby_api_version RB_TYPE_P sa_family_t m_packetLen readMore RUBY_FL_WB_PROTECTED in6_addr isBodyWriteToFile slowpath __timezone line sin6_addr RB_SYMBOL_P rb_mWaitReadable lsapi_setsync m_respPktHeaderEnd ruby_fl_ushift RUBY_FL_TAINT LSAPI_Postfork_Parent fn_add_env lsapi_body rb_int2num_inline lsapi_print rb_eSystemCallError RB_STATIC_SYM_P dcompact rb_intern2 stderr m_pHeaderIndex RB_FL_TEST_RAW program_invocation_short_name RARRAY_PTR rb_cUnboundMethod rb_f_sprintf RB_FL_ANY_RAW _IO_save_end rb_const_get __nptr LSAPI_Init LSAPI_Request rb_eScriptError fn_write lsapi_sync m_bufProcessed RB_FLOAT_TYPE_P stdout readBodyBuf optopt lsapi_reopen RB_DYNAMIC_SYM_P rb_mGC rb_eIndexError m_httpHeaderLen curPos H_IF_NO_MATCH lsapi_s_accept prefork RUBY_T_DATA buff ssizetype keyLen __builtin_strchr LSAPI_Flush_r short unsigned int signed char rb_array_len filename lsruby.c lsapi_header_offset RARRAY_TRANSIENT_P __off64_t sockaddr_eon _IO_read_base _offset m_pIovec rb_string_value_ptr rb_eFloatDomainError _IO_buf_end m_respInfo opterr lsapi_puts_ary _mode blkSize rbimpl_RB_TYPE_P_fastpath _IO_write_base valueLen function Init_lsapi rb_eStandardError tz_dsttime rb_argv0 H_CACHE_CTRL H_COOKIE2 __dest rb_cMatch rb_cEncoding lsapi_isatty H_USERAGENT RARRAY_EMBED_LEN_MASK LSAPI_ForeachEnv_r long int RUBY_T_NONE rb_mProcess rb_mFileTest remain _IO_marker rb_cEnumerator m_pRespBufEnd RB_BUILTIN_TYPE __builtin___memcpy_chk rb_io_puts lsapi_s_postfork_child rb_define_global_const rb_obj_as_string m_bufRead in_addr uint32_t sockaddr_in6 __pid_t _IO_codecvt rb_funcall_nargs H_RANGE RData strtol g_req long double rb_cRange RB_SPECIAL_CONST_P iov_len lsapi_resp_info rb_cObject long unsigned int lsapi_req_header rb_cSymbol RVALUE_EMBED_LEN_MAX rb_gc_mark initBodyBuf ruby_strdup m_headerOff rb_eNotImpError rbimpl_id RSTRING_PTR __errno_location lsapi_s_postfork_parent rbimpl_strlen char RB_INT2FIX sockaddr_inarp m_pSpecialEnvList sin6_scope_id rb_cIO stdin sin_addr RUBY_FL_SHAREABLE RUBY_T_BIGNUM _IO_buf_base RSTRING_NOEMBED RUBY_T_RATIONAL RB_FLONUM_P RUBY_FL_PROMOTED s_body rb_eTypeError RBasic rb_eNoMethodError _IO_read_end RUBY_T_ICLASS rb_num2int cLSAPI RUBY_SPECIAL_SHIFT _IO_FILE H_IF_UNMOD_SINCE m_fd RUBY_T_SYMBOL H_HOST rb_num2char_inline _IO_wide_data ruby_rstring_consts strlen tzname __u6_addr16 s_pid self rb_eSystemExit isAllBodyRead m_respHeader rb_cThread RUBY_FL_SEEN_OBJ_ID m_envListSize m_pAppData RB_NIL_P ruby_platform sockaddr_ax25 RSTRING_FSTR rb_eThreadError __pad5 rb_str_new_static shared_root __u6_addr32 rb_cNilClass m_type _markers rb_stdin rb_eStopIteration m_scriptFileOff RUBY_FL_USHIFT klass rb_define_class H_VIA _codecvt m_pRespHeaderBufEnd H_PRAGMA RTypedData RUBY_FL_FINALIZE rb_cRandom double mkstemp lsapi_putc argc ssize_t RB_IMMEDIATE_P lsapi_write lsapi_puts orig_stdin RUBY_FIXNUM_FLAG argv rb_eRuntimeError m_pRespHeaderBuf rb_cClass __int32_t rb_cProc __uint32_t RUBY_IMMEDIATE_MASK rb_hash_aset data __daylight H_REFERER rb_cStruct LSAPI_Prefork_Accept_r RB_FIXNUM_P heap _sys_siglist RARRAY_TRANSIENT_FLAG m_pUnknownHeader rb_type m_reqState RUBY_T_NIL RUBY_T_MOVED rb_eSysStackError rbimpl_rstring_getmem GNU C17 8.5.0 20210514 (Red Hat 8.5.0-28) -mtune=generic -m64 -march=x86-64 -g -O2 -fPIC -fexceptions -fstack-protector-strong -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection=full -fplugin=gcc-annobin m_pRespBuf rb_num2int_inline program_invocation_name rb_cArray rb_eEncodingError rb_ruby_verbose_ptr rb_cBinding dsize H_IF_MODIFIED_SINCE rb_ary_detransient RUBY_FL_USER10 RUBY_FL_USER11 RUBY_FL_USER12 RUBY_FL_USER13 RUBY_FL_USER14 RUBY_FL_USER15 RUBY_FL_USER16 RUBY_FL_USER17 RUBY_FL_USER18 RUBY_FL_USER19 _freeres_buf RUBY_T_MATCH long long unsigned int parent pid_t _cur_column lsapi_rewind s_req rb_eRangeError m_pRespHeaderBufPos s_stderr_data rb_eval_string_wrap getpid typed_flag m_cntEnv ruby_rarray_consts RUBY_T_MASK rb_lastline_get createBodyBuf _IO_backup_base H_KEEP_ALIVE __memcpy_chk _IO_read_ptr rb_eMathDomainError rb_fix2int LSAPI_GetReqBodyLen_r rb_gc_writebarrier_unprotect rb_exec_recursive getenv _freeres_list rb_eLocalJumpError _sys_nerr lsapi_read timezone pReq lsapi_getc rb_hash_new clear_env rb_cRegexp lsapi_binmode _old_offset strchr m_pReqBuf rb_cNameErrorMesg retval valueOff optind H_ACC_LANG long long int in6addr_loopback _flags2 VALUE rb_mMath RUBY_T_TRUE memmem sin6_family sockaddr_at ruby_value_type m_scriptNameOff H_ACCEPT m_lLastActive rb_eNoMatchingPatternError lsapi_resp_header sys_nerr in6addr_any m_pRequestMethod s_req_data iov_base m_lReqBegin ruby_rvalue_flags m_versionB0 m_versionB1 rb_str_buf_new RUBY_FLONUM_MASK ruby_patchlevel RUBY_T_REGEXP m_pIovecCur LSAPI_Init_Env_Parameters orig_env m_reqBodyRead RUBY_Qundef lsapi_s_accept_new_conn rb_eFrozenError sockaddr_dl RSTRING_EMBED_LEN_MASK RUBY_FL_FREEZE unsigned int bodyLen sockaddr_ipx rb_default_rs short int rb_string_value _vtable_offset pValue env_copy mmap orig_verbose rbimpl_str_new_cstr rb_data_object_zalloc rb_mEnumerable RUBY_Qfalse flags tz_minuteswest sys_siglist H_ACC_ENCODING sin6_port lsapi_eval_string_wrap  GCC: (GNU) 8.5.0 20210514 (Red Hat 8.5.0-28)                 GNU                    zR x            
          0                 D       +          X                 l                               (          B    FGA kFB                                  HU           g    HQ
G          a    yd           2    HW
II      @           HW    X           HW    p      -    Hd          3    ED hA H            FBB E(D0C8GPm
8F0A(B BBBG 4            oAD 
AAKpP  \   ,      4   FDA D(F0`
(D ABBBj
(D ABBEl(G DBB   D             BBI B(A0A8D@8D0A(B BBB         *    HP
HI            U    KI  8             FBA D(D@
(A ABBE    L             (   `         EDG0
AAG        zR x0           .                     AD w
AA 8         !   FBA D(G0d
(C AGBK              EL      8          EY   (   T          EAD 
DAF ,             ZAD rAB   H            FBB B(A0D8D@
8F0A(B BBBG @         7   FBB A(D0D@
0A(A BBBB 8   @      S   FBA A(D0
(A ABBF                        
                                                                     	                                           
                     /                                       )                                           ?    0                                       Y                                           t    1                                                                                      2                                                                                      3                                          
               5            
       C    
               _    "               y                     	 @                 "                   [                   0       +           [                   h                   `                  h               )    w               C    p              P    w               m                                                                                      B          	 p                                                                     &                   A                  Z                  f                      w                        g                             w                                          a                             "              +          2       6    "              ]    P                  0                                    P                  p                  P                  p              (                  M    p      -       e                                              3                                                                                                   )                  D                 R   	 @              \                  v                            4                                                                                                         *       (                  B    	              Z          U       e    	                  
                   	                 
                  '
                   
                 '
                  O                                        0
            (            .       :    O              S                  j    P             t   	 x             }   	                                                              !                            "              	                 	    "              ,	    O              F	    0             S	    O              q	    G              	    P             	   	 X             	   	 `             	   	               	    G              	                  	    P              
                   
   	              
   	               )
                  C
    t              [
                f
    t              
                  
          7      
                  
                  
   	                
   	               
   	                 	 h                                                                                    !                      "                      $                      &                      (                      *                      0                      1                      2                      3                      4                      5                                            /                      6                      2                                                            %                                   !                     &     s               +     F               0     >               5     \               :                    @                    F                    L                     R                    X                    ^                    d                    j                    p                    v                    |                                                                                                                                                                  (                   .                   j                   r                   w                   }                                                                                                                                                                                                                                                                                         $                   *                   0                   6                    <     5              B     K              H     Z              N                    T                   Z                     f                     v                                                                    +                      ,                      -                      .                                                                                                                                                                                                                                                                                                       	                                          4                     J                     _                     x                                                                                                                                                                                                                                                                                                                                                                     )                     8                     C                     N                     Y                     `                     i                                                                                                                                                                                                                                                          #                     9                     L                     `                     w                                                                                                                   S                                                                                                                                                                                                   (                     5                     H                     X                     n                     |                                                                                                                                                                            .annobin_lsruby.c .annobin_lsruby.c_end .annobin_lsruby.c.hot .annobin_lsruby.c_end.hot .annobin_lsruby.c.unlikely .annobin_lsruby.c_end.unlikely .annobin_lsruby.c.startup .annobin_lsruby.c_end.startup .annobin_lsruby.c.exit .annobin_lsruby.c_end.exit .annobin_lsapi_process.start .annobin_lsapi_process.end lsapi_process .annobin_lsapi_rewind.start .annobin_lsapi_rewind.end lsapi_rewind s_body .annobin_lsapi_eof.start .annobin_lsapi_eof.end lsapi_eof .annobin_lsapi_binmode.start .annobin_lsapi_binmode.end lsapi_binmode .annobin_lsapi_isatty.start .annobin_lsapi_isatty.end lsapi_isatty .annobin_lsapi_setsync.start .annobin_lsapi_setsync.end lsapi_setsync .annobin_add_env_no_fix.start .annobin_add_env_no_fix.end add_env_no_fix lsapi_env .annobin_lsapi_mark.start .annobin_lsapi_mark.end lsapi_mark .annobin_lsapi_flush.start .annobin_lsapi_flush.end lsapi_flush .annobin_lsapi_close.start .annobin_lsapi_close.end lsapi_close MAX_BODYBUF_LENGTH .annobin_readBodyBuf.start .annobin_readBodyBuf.end readBodyBuf .annobin_lsapi_getc.start .annobin_lsapi_getc.end lsapi_getc .annobin_lsapi_s_postfork_parent.start .annobin_lsapi_s_postfork_parent.end lsapi_s_postfork_parent s_req .annobin_lsapi_s_postfork_child.start .annobin_lsapi_s_postfork_child.end lsapi_s_postfork_child .annobin_lsapi_s_accept_new_conn.start .annobin_lsapi_s_accept_new_conn.end lsapi_s_accept_new_conn .annobin_lsapi_eval_string_wrap.start .annobin_lsapi_eval_string_wrap.end lsapi_eval_string_wrap .annobin_add_env_rails.start .annobin_add_env_rails.end add_env_rails .annobin_createBodyBuf.start .annobin_createBodyBuf.end createBodyBuf sTempFile .annobin_lsapi_read.start .annobin_lsapi_read.end lsapi_read .annobin_lsapi_gets.part.1.start .annobin_lsapi_gets.part.1.end lsapi_gets.part.1 .annobin_lsapi_gets.start .annobin_lsapi_gets.end lsapi_gets .annobin_lsapi_each.start .annobin_lsapi_each.end lsapi_each .annobin_lsapi_puts_ary.start .annobin_lsapi_puts_ary.end lsapi_puts_ary .annobin_lsapi_sync.start .annobin_lsapi_sync.end lsapi_sync .annobin_lsapi_putc.start .annobin_lsapi_putc.end lsapi_putc lsapi_putc.cold.9 .annobin_clear_env.start .annobin_clear_env.end clear_env env_copy rbimpl_id.16058 .annobin_lsapi_write.start .annobin_lsapi_write.end lsapi_write .annobin_lsapi_addstr.start .annobin_lsapi_addstr.end lsapi_addstr .annobin_lsapi_printf.start .annobin_lsapi_printf.end lsapi_printf .annobin_lsapi_s_accept.start .annobin_lsapi_s_accept.end lsapi_s_accept s_pid s_req_data rbimpl_id.16071 .annobin_lsapi_reopen.start .annobin_lsapi_reopen.end lsapi_reopen s_req_stderr orig_stderr rbimpl_id.16235 .annobin_lsapi_puts.start .annobin_lsapi_puts.end lsapi_puts .annobin_lsapi_print.start .annobin_lsapi_print.end lsapi_print .annobin_Init_lsapi.start .annobin_Init_lsapi.end rbimpl_id.16251 rbimpl_id.16256 orig_env cLSAPI .LC5 .LC3 .LC2 .LC4 .LC1 .LC0 .LC9 .LC7 .LC6 .LC8 .LC10 .LC11 .LC15 .LC12 .LC13 .LC16 .LC17 .LC18 .LC19 .LC20 .LC21 .LC58 .LC23 .LC24 .LC26 .LC27 .LC28 .LC29 .LC30 .LC31 .LC32 .LC36 .LC37 .LC38 .LC39 .LC40 .LC41 .LC42 .LC43 .LC44 .LC45 .LC46 .LC47 .LC48 .LC49 .LC50 .LC51 .LC52 .LC53 .LC54 .LC55 .LC56 .LC22 .LC33 .LC34 .LC35 .LC25 .LC57 .text.group .text.hot.group .text.unlikely.group .text.startup.group .text.exit.group _GLOBAL_OFFSET_TABLE_ g_req rb_str_new rb_hash_aset rb_gc_mark LSAPI_Flush_r munmap free LSAPI_ReadReqBody_r LSAPI_ReqBodyGetChar_r LSAPI_Postfork_Parent LSAPI_Postfork_Child LSAPI_Accept_Before_Fork rb_string_value rb_string_value_ptr rb_eval_string_wrap strchr rb_str_new_static ruby_strdup mkstemp unlink ftruncate mmap calloc perror __errno_location strerror __fprintf_chk rb_str_buf_new rb_str_cat rb_num2int rb_fix2int memmem rb_yield rb_gc_writebarrier_unprotect rb_io_puts rb_ary_detransient __stack_chk_fail rb_check_type rb_intern2 rb_funcallv rb_obj_as_string rb_f_sprintf LSAPI_Prefork_Accept_r getpid s_fn_add_env LSAPI_ForeachHeader_r LSAPI_ForeachEnv_r rb_ruby_verbose_ptr rb_define_global_const rb_default_rs rb_exec_recursive rb_output_fs rb_output_rs rb_lastline_get Init_lsapi LSAPI_Init getenv strtol strlen select LSAPI_Init_Env_Parameters chdir rb_stderr rb_cObject rb_const_get rb_global_variable rb_define_class rb_data_object_zalloc LSAPI_Write_r rb_stdout rb_stdin LSAPI_Write_Stderr_r rb_hash_new __memcpy_chk rb_define_method rb_define_global_function rb_define_singleton_method                   H      7       *                                             l                          *                         *                   '            D      -                   4            <      ;            B            8      R            D      ]            H      q                  *                  H                  <                              H            *                   ;      *      @            G                   [      *      `            g                   {      *                                                                                     B            P            W            l      b                                                                                                l      $            4            @            I            T            l      \            s                                                l                                                      C            *                   D      6                   C            <       H            S            f            n            u            D                                         <                                        <                                         @                                        1           8           G            Q      *     [           c            t            y                                  D                  L                  H               	              L                   <      (         
  .            L      S           ]            L      c            D      y                       L                  <               
              L                  <                  D                  H                              L      2           K         	  Y            L      c            <      k         
  q            L                  D                  H                             D                  L      h	           	           	           	            	            
           
           z
           
           A           K           h            t      s                                                           l                                       %                 *                                        9           ]      *      b           s            <      }                        8                  D                  H                             T                  \            *                                                          T                                     !           (                   >           W            r           z                                                                                                                                                          I                 *                                         3      *     B            L           c      *                       *   !  )            @      *   "           #                      %                          8                  D                  H               &           '  '            9                   @            E         &  U         (  q            x            L                   <                            &           '        *   )           *                                     T               &           +        *           *   ,  	                                                 )           0                   <      *   -  H         .  O                   V            |      b            y                                          |                             t                  t               /                                                              t                                       9                       0              '            d      ,         :  ;            d      K            P         8  W            d      j            o         8  v            d                           8              d                           8              d                           8              d                           8              d                  
         8              d      !            &         8  -            d      =            B         8  I            d      Y            ^         8  e            d      x            }         8              d                           8              d                           8              d                           8              d                           8              d                  	         8              d                   %         8  ,            d      <            A         8  H            d      X            ]         8  d            d      t            y         8              d                           8              d                           8        *                  d               1        *            *   2                                                    \            *   3        *   4            /  '            d      ;         1  B      *   5  I            T            c         /  h           p           |         6              l                  l                                                                           <                7              <                   +            d      ;            @         :  G            d      W            \         :  c            d      s            x         :                                              &                                                         
                                5                                                                                                  
       $                    ,            
       P            
       X            "                   
                   "                   "                   [                   "                   [                   [                   h       D            [       L            h       p            h       x            w                   h                   w                   w                                      w                          0                   8                   d                   l                                                                                                                                    $                   ,                  P                  X            w                                    w                  w                                    w                                                      "      D                  L            "      p            "      x            P                  "                  P                  P                  p                  P                  p      0            p      8                  d            p      l                                                                                                                              $                  ,                  P                  X                                                                                                                              	                  	                  D	                  L	                  p	                  x	                  	                  	                  	                  	            	      
                  
            	      0
            	      8
            
      d
            	      l
            
      
            
      
            '
      
            
      
            '
      
            '
      
            O      $            '
      ,            O      P            O      X                              O                                                                                                                              "      D                  L            "      p            "      x            O                  "                  O                  O                  G                  O                  G      0            G      8                  d            G      l                                                t                                    t                  t                        $            t      ,                  P                  X                                                                                                                                                                                                                                         *     
                                                                   
                     
                   
                   
                   
      0      %       
              ,       
            8       
      K!      ?       
      -      M       
            T       
            [       
            `       
            n       
      {!      s       
                   
                   
                   
      i             
                   
                   
      _             
                   
                  
                  
      u             
            -      
            :      
            G      
            T      
      	      a      
      @      n      
      /      {      
      K            
                  
                  
      ?            
      ^            
                  
      _             
      T            
                  
                  
      !      
      
                  
            $      
            1      
            >      
            K      
      f      X      
            e      
            r      
      x            
      E             
      
            
      ,            
                  
      g            
      .            
      !	      
      
      )            
             -      
            9      
            E      
            a      
            m      
            y      
                   
                  
                  
                  
      5            
                  
      f            
      +            
      I            
                  
      4            
      P      	      
      #            
      b      !      
            /      
      E      6      
      
      ;      
      ?      X      
      I      d      
            p      
            |      
      W            
                  
                  
      T            
                  
      "            
                  
      \            
      u            
      !            
                  
      ,              
             &      
            ,      
      b      2      
      y       8      
      	      >      
      4	      D      
            K      
      @       ]      
            d      
            r      
      "            
                  
                  
      r            
      
            
                  
                  
                  
      %            
                   
                  
                  
                  
      !            
      4            
      F            
                  
      :            
      L            
      w            
      k            
                  
                  
                  
            #      
            )      
            /      
            5      
      7      ;      
            A      
            H      
      %      Z      
            a      
            s      
            y      
                  
                  
      h            
                  
      4            
                  
      H            
                  
                   
      <!            
      s            
                  
                  
                  
                  
                  
                  
                  
                  
                  
      4            
      C            
      R      (      
      a      1      
      p      :      
            C      
            L      
            U      
            ^      
            h      
            o      
            w      
      	            
      <            
      %!            
                  
      <            
                  
      
            
                  
      
            
      +      G      
            U      
            p      
                  
      	            
      @            
      =            
                  
      I            
                  
                  
      2      	      
      +      K	      
      }      Y	      
            t	      
            	      
            	      
            	      
            	      
            	      
            	      
            	      
            	      
             
      
            
      
            
      
      N       +
      
            8
      
            E
      
            R
      
      "      i
      
            v
      
            
      
            
      
            
      
            
      
            
      
            
      
            
      
      s            
                  
            &      
      E	      2      
      !      >      
      /      J      
            V      
            b      
      b      n      
      ~      z      
                  
                    
      p            
                  
                  
                  
                  
                  
                  
      3            
                  
            
      
                  
      $      "      
            .      
      (      :      
            F      
      g       R      
            ^      
            j      
      J      v      
                  
                  
                  
                  
                  
                  
                  
      R            
                  
                  
                  
      	            
      ^            
                  
      c      *      
            6      
      u      B      
            N      
            Z      
      0
      f      
            r      
      ]      ~      
                  
      p            
                  
      '            
      2            
      x            
      	!            
                  
                  
      	            
                  
      Z            
      ]            
      6       &      
            2      
      6      >      
      t      J      
            V      
      `      b      
            n      
      b      z      
                  
      y            
      B            
                   
      |            
                  
      g            
      	            
      v            
                  
      !            
                  
      `            
      m!            
      	      )      
            J      
      X      f      
            r      
            ~      
                  
                   
                  
      G            
      	            
                  
                  
      ,"            
      *            
                   
      G            
      n            
      	            
      
            
                  
            
      
                  
                  
      4            
            "      
            (      
            .      
      !      4      
      E      :      
            @      
            F      
            L      
      T	      R      
            X      
      	      h      
      N      t      
      >            
      
            
      R             
      ^             
      W            
      B            
                  
                  
      &            
      
            
      5            
                  
                  
      t	      +      
      '      8      
             E      
      ~      R      
            `      
      :
      m      
            z      
      Q            
                  
      P            
                  
                  
                  
                  
                  
      ,            
                  
      &      ,      
      W      :      
      K      G      
            T      
      !      a      
      a      n      
            |      
                  
                  
                  
                  
      4             
                  
      V            
                  
                  
                   
                  
                  
      6      &      
      '	      3      
            @      
             M      
             Z      
            g      
            t      
      W            
                  
                  
                  
                  
                  
      S            
                   
                  
                  
      o            
                   
      4            
      l      *      
      5      7      
             D      
            Q      
      7      ^      
            l      
            z      
                  
                  
      <            
                  
      +             
                  
      k            
            P      
            \      
            h      
      s      t      
      U            
                  
      #            
                  
                  
      !            
                  
                  
            *      
            7      
            D      
      ?      b      
      R      p      
      ~      ~      
      ;"            
                  
                  
                  
                  
      `!            
                   
                  
            0      
      o            
                  
      A            
      l            
      k            
                  
      ^      (      
      >      e      
            r      
                  
                   
      C            
      0            
       "            
      W            
      *            
                              
      
                                      
      !      -            x      6      
            C            p      L      
      
      Y                   b      
                  
                  
                  
                        h            
      !                               
                          `            
                                &      
      J      2      
      j      ?            X      H      
      c      U      
            b      
      X!      o      
      
      |      
                  
      c            
      y                  @            
      b
                  @             
      X            
      
                               
                                    
      !             
             $      
              3      
      A       7      
      ;       <      
      >      H      
             L      
             Q                  f      
      m      t                                                              
                  
                  
      6            
      4                               
                   
      d            
      b            
                   
                  
                        -      
      
      0            
      R
            
            #      
            (      
      l
      5      
      s      A      
            E      
            J      
      `      S      
      m      a                   n            Z      w      
      `            
      0            
      .            
      ^            
      \                  p            
                  
                  
                  
                  
                  
                        }                              
                  
      R            
                  
            "                  8                   I      
             R      
      R      ^      
            b      
            g            ?      }                                           
                                    
                  
                  
      *            
      (            
      S            
      M                              
      0            
                  
                              #                   8         N          B            +      `                  ~                                                =            
      `            
      `            
                  
                        h            
                  
      X            
      T            
                  
                              )            @       K                  T                  q      
            u      
            ~      
                  
      	                  I               N                      Y                              
                  
      9            
      7                                          
                             N          )                   6                   C                   X          N          b                   o             L      |                                x                                   N                                      h                                                !         N         !                  (!                  =!         N   (      G!            0      X!         N   .      e!            P      t!            T      !         N   j      !                    !            s      !         N   r      !            0
      !                  !         N   w      !                  !                  "         N   }      "                  )"                  :"         N         G"            0      W"                  h"         N         u"                  "                  "         N         "                  "            *      "         N         "                   "            F      "         N         "                  #            b      #         N         *#                  9#                  J#         N         W#                  g#                  x#         N         #                   #                  #         N         #                  #                  #         N         #            0       #                  #         N         $            0       $                  ,$         N         9$                  H$            )      Y$         N         f$            `       u$            E      $         N         $            p       $            a      $         N         $            p       $            }      $         N         $             
      $                  %         N         %                   )%                  :%         N          G%            P      W%            $      l%                   v%            g      %                    %            l      %            t      %                  %                  %                  %         N         %                  %         N          &                  &            D      %&         N   5      2&            p      A&            `      R&         N   K      _&            P      n&            |      &         N   Z      &            0      &                  &         N          &                  &         N         &      
      W      &      
      9      &      
      O      '      
      `      ;'      
            M'      
      $      Z'      
      s      g'      
      p      t'      
      !      '      
      m      '                   '      
      9      '                  '      
      p      '      
      `      '      
      \      '            $      '            $      '            $      (            ?      (            u      (      
            )(                   @(      
      p      O(      
            _(      
            p(      
      p      ~(      
      '      (      
      p      (      
            (            `       (      
      p      (      
            (            0       (      
      p      )            4       )            4       ,)      
            8)                  O)      
      p      [)      
            _)      
            p)      
            t)      
            })                  )                  )      
            )      
            )                  )      
      @      )                  )      
      p      )      
      `      )      
      \      )      
      p      )      
            )      
            
*      
            *      
            *                  -*            	      <*                  J*      
            \*      
      p      j*      
            v*                  *      
      $      *      
      $      *      
            *      
      s      *      
            *      
            *      
      p      *      
            *      
            *      
      	      *      
      	      *      
      	      *      
      	      *      
      W       +      
      	      +      
      	      	+      
            +      
      
      +      
      
      "+            L      ++      
            <+      
      
      @+      
      
      E+      
            N+      
      4      R+      
      0      [+            L      d+            L      +      
      l      +      
      j      +            W      +            }      +                  +                  +                  +            ,      ,                  .,      
      |      @,      
      p      Z,      
      ~      ~,      
            ,                  ,      
      W      ,      
            ,      
            ,      
             ,      
      R      ,      
            ,      
            ,      
            ,      
      X      ,      
      V      ,      
            ,      
            ,      
      {      -      
            -                  -      
              1-                  ?-      
            M-      
            [-      
            z-      
            -      
            -      
            -                  -      
      p      -      
            -      
            -      
            -      
            .            	      .      
      @       .      
      .      ".      
      ,      +.            	      4.      
      P       @.      
      U      D.      
      Q      I.      
      P       R.      
            V.      
            _.      
            c.      
            l.      
            p.      
            y.      
      !      }.      
            .      
      F      .      
      D      .                  .      
      	      .                   .      
      p      .      
      m      .      
      i      .                  .      
            .                  /      
            /      
            */      
            ./      
            3/                  O/      
      L      a/      
      $      n/      
      s      /      
            /      
      i      /      
            /      
      
      /            0      0      
      $      "0      
      6      &0      
      2      +0      
      s      70      
      s      ;0      
      o      L0      
            P0      
            U0            =      u0            H      0      
            0                  0      
      $      0      
            0      
            0      
      s      0      
      X      0      
      N      0      
            0      
            0      
      c      0      
      [      0      
            1                   1      
            -1      
            11      
            61      
            ?1      
            C1      
            H1            -      g1                  p1      
      P      1      
            1      
            1                  1      
            1      
            1      
            1                  1                  1      
            1      
            1                  1                  2      
            2      
            2            p       2            p      82      
      >      <2      
      <      A2            p      V2      
      o      Z2      
      m      b2                  z2                  2            8      2                  2                  2                  2      
      @      2                   3      
      p      3      
            3      
            !3      
      K      %3      
      C      *3      
            63      
            :3      
            K3      
            O3      
            X3                  a3      
            r3      
      !      v3      
            3                  3      
            3      
      n      3      
      j      3      
            3      
            3      
            3                  3                  3                  3      
      @      3      
            3      
            3      
      7      3      
      1      4                  
4      
      P      4      
            4      
            $4      
            (4      
            14                  :4      
            K4      
            O4      
            X4                  a4                  }4      
      \      4      
      Z      4                  4                  4      
            4      
            4                  4                  4      
            4      
            4                  4      
            4      
            5                  5                  25      
            65      
            <5            
      \5                  e5      
            v5      
            z5      
            5                  5      
       	      5      
      m      5      
      g      5                  5                  5      
            5      
            5            u      5            u      5      
            5      
            6            u      6      
            6      
             (6            1      16      
      0	      G6            1      P6      
      	      a6            1      j6      
      
      z6      
      -      ~6      
      )      6            1      6      
      `
      6      
      m      6      
      i      6      
      
      6                  6      
      
      6      
      
      6      
            6      
            6            >      6      
      
      7      
      
      7      
            7      
            &7            >      /7      
      P      D7      
            T7                  ]7                  v7                  7                  7                  7         N          7      
      !      7      
            7                  7         N          7         h            8            T      	8      
            8      
      Z      8      
      X      '8            T      08      
             <8      
            @8      
      }      E8      
             N8      
            R8      
            [8      
            _8      
            h8      
            l8      
            u8      
      R      y8      
      N      8      
            8      
            8            )      8            T      8      
            8      
            8      
      p      8      
            8      
            8      
            8      
            9      
            9      
      =      9      
      ;      $9            P
      -9      
            >9      
      l      B9      
      `      K9            P
      T9      
            d9      
            h9      
            q9      
            u9      
            ~9            P
      9            P
      9      
      P      9      
      N      9      
      x      9      
      t      9            P
      9            P
      9      
            9      
            9            P
      9            P
      :      
            :      
             :            U
      ):            U
      A:      
            E:      
            P:            ^
      Y:            ^
      r:      
      4      v:      
      2      {:            ^
      :      
      Y      :      
      W      :            m
      :      
            :      
            :      
            :      
            :      
            :      
            :            m
      :            m
      :      
            ;      
            ;            ~
       ;            E      3;            
      <;      
            L;      
             P;      
             Y;            
      b;      
             n;      
      W       r;      
      S       {;            
      ;      
      @      ;      
             ;      
             ;      
             ;      
             ;            
      ;            
      ;      
             ;      
             ;      
      !      ;      
      !      ;            
      <            
      <            
      '<      
      )!      +<      
      '!      0<            
      E<      
      R!      I<      
      L!      W<      
      p      c<      
      !      g<      
      !      l<      
      p      u<      
      !      y<      
      !      <      
            <      
      ]"      <      
      ["      <            
      <                    <      
      "      <      
      "      <                    <                    <                    =         N          '=      
      "      +=      
      "      0=            $       F=         N          S=         h           g=            
      p=      
            =      
      "      =      
      "      =            
      =      
      @      =      
      #      =      
      #      =      
      Z#      =      
      V#      =      
      @      =            
      =            
      =            
      =      
            =      
      #      =      
      #      >      
      #      >      
      #      >            
      >      
            &>      
      
$      *>      
      $      3>      
      F$      7>      
      B$      @>            
      I>      
            Z>      
      $      ^>      
      |$      g>            
      p>      
      @      >      
      $      >      
      $      >            
      >            
      >      
      $      >      
      $      >            
      >            
      >      
      %      >      
      %      >            
      >      
      <%      ?      
      :%      ?            
      ?            
      5?      
      f%      9?      
      d%      ??            
      [?            
      t?            O      ?      
            ?                    ?      
      p      ?      
      E"      ?                  ?      
      p      ?      
      %      ?      
      %      ?      
      %      ?      
      %      @                  @                  2@                  F@      
            Q@            0      h@      
      p      s@      
      %      w@      
      %      |@            D      @      
            @            P      @      
      p      @      
      ,&      @      
      (&      @            d      @      
             @            p      @      
      p      @      
      i&      @      
      e&      A                  A      
      /      A            P      4A      
      p      ?A      
      &      CA      
      &      SA      
      &      WA      
      &      \A                  qA      
      R
      ~A      
      l
      A      
      s      A                  A      
      m      A                   A                  A                  A      
      8'      A      
      6'      A      
      f'      A      
      d'      B                  
B      
            B      
      '      B      
      '      B      
            (B      
      '      ,B      
      '      1B            %      NB            B      pB                  yB      
      `      B      
      '      B      
      '      B                  B                  B                  B            f      B                  B                  B      
            C      
            C      
            C            P      ,C            e      AC      
      R
      NC      
      l
      ]C      
      s      jC            p      C      
      m      C                    C            p      C            p      C      
      (      C      
      (      C      
      ;(      C      
      9(      C                  C      
      p      C      
      i(      C      
      g(      C      
      p      C      
      (      C      
      (      D                  !D                  ;D                  ^D      
      z      iD                   D      
            D      
      (      D      
      (      D      
      a      D      
      )      D      
      )      D      
      !      D      
      c)      D      
      _)      D      
            D      
      )      D      
      )      D      
      )      D      
      )      D                   
E                   .E                   CE      
            NE                  eE      
            pE      
       *      tE      
      *      yE      
      a      E      
      *      E      
      *      E      
      !      E      
      k+      E      
      _+      E      
            E      
      ,      E      
      +      E      
      ,      E      
      ,      E      
      n-      E      
      f-      E            F      F            T      *F            f      BF                  `F                   F                  F         N          F            (      F            8      F            M      F         N   %       G            `      G            w      8G                  MG         N          \G                  qG      
            xG                   G      
            G      
      -      G      
      -      G                   G      
      }      G      
            G      
            G      
            G      
      !      H      
            5H      
            eH      
            H      
            H      
      m      H      
            H      
      4      I      
            -I      
            KI      
            gI      
      F      I      
      r       I      
            I      
            I      
            I      
      w      	J      
      a      'J      
            EJ      
            SJ      
            {J      
      1      J      
      "      J      
            J      
      "      J      
      u      J      
            J      
            	K      
      i      4K      
            \K      
            zK      
            K      
            K      
      d      K      
            K      
      n      L      
            BL      
            L      
            L      
      1      L      
      \      L      
            M      
            M      
            2M      
            PM      
            nM      
      |
      M      
      	      M      
      )      M      
             M      
      	      M      
      )      M      
      j      M      
      Y      M      
            M      
      6      M      
            N                   4N            p       WN                   xN                  N                  N            .      N            .      N            @      N      
             N      
             N      
      .      N      
      .      N            @      N      
             O      
             O      
      y.      O      
      m.      O      
      /      "O      
      .      +O            N      4O      
             EO      
      N/      IO      
      L/      RO      
      ~/      VO      
      z/      [O            _      qO         N   >       O            L      O            @       O            W      O            j      O            r      O            5      O            <      P            g      P                  7P                  iP                  P                  P         N   F       P            #      P            }      P         N   \       P                  P                  Q                  Q         N   s       $Q                  ?Q      
      /      CQ      
      /      QQ      
      0      UQ      
      0      ^Q      
      -0      bQ      
      )0      kQ      
      e0      oQ      
      c0      xQ                  Q                  Q                  Q            6      Q         N          Q            O      Q            o      R                  4R      
      0      8R      
      0      VR                  cR                  R             	      R      
      0      R      
      0      R      
      j1      R      
      ^1      R      
      1      R      
      1      R      
      a2      R      
      Y2      R            	      R      
            R      
      2      R      
      2      R            X	      S            X	      "S      
      2      &S      
      2      +S            X	      @S      
      &3      DS      
      3      OS            	      XS      
            dS      
      3      hS      
      3      qS      
      3      uS      
      3      ~S            	      S            	      S      
      3      S      
      3      S      
      4      S      
      
4      S            d	      S      
            S      
      34      S      
      /4      S      
            S      
      m4      S      
      i4      S            d	      S            d	      T      
      4      T      
      4      (T      
      4      ,T      
      4      5T      
      '5      9T      
      %5      >T            l	      WT            l	      `T      
      p      lT      
      N5      pT      
      J5      yT            l	      T      
            T      
      5      T      
      5      T            l	      T      
            T      
      5      T      
      5      T      
      5      T      
      5      T            l	      T            l	      T      
      5      T      
      5      T      
       6      U      
      6      U            v	      U      
            &U      
      G6      *U      
      C6      3U            v	      <U      
      P      HU      
      6      LU      
      }6      UU      
      6      YU      
      6      bU            v	      kU            v	      U      
      6      U      
      6      U      
      6      U      
      6      U            	      U            	      U      
            U      
      7      U      
      7      U      
      X7      U      
      T7      U      
      7      U      
      7      U      
            V            	      V      
            %V      
      7      )V      
      7      .V      
            7V      
      7      ;V      
      7      @V            
      QV         N          bV            
      V            	      V            
      V            P      V      
      '8      V      
      8      V      
      8      V      
      8      V      
      8      V      
      8      V            q      W      
            W      
      .9      W      
      *9      "W      
      m9      &W      
      g9      /W      
      9      3W      
      9      8W      
            AW      
      :      EW      
      :      OW                  hW                  qW                  W      
      2:      W      
      0:      W      
      `:      W      
      ^:      W                  W      
            W      
      :      W      
      :      W      
            W      
      :      W      
      :      W                  W            v      W            ~      X                   X         N          *X                  7X                  ZX                  uX      
      :      yX      
      :      X      
      R;      X      
      J;      X      
      ;      X      
      ;      X      
             X      
             X      
      G<      X      
      E<      X      
      u<      X      
      k<      X            [      X      
             Y      
      <      Y      
      <      	Y      
            Y      
      7=      Y      
      3=      Y            0      (Y      
      0      8Y      
      o=      <Y      
      m=      AY      
      0      OY            0      XY      
      0      dY      
      =      hY      
      =      qY      
      =      uY      
      =      zY            P      Y         N          Y            [      Y      
      `      Y      
      =      Y      
      =      Y            [      Y      
            Y      
      7>      Y      
      5>      Y      
      _>      Y      
      ]>      Y            [      Z            [      Z      
      >      "Z      
      >      +Z      
      >      /Z      
      >      :Z      
            LZ                  UZ      
            fZ      
      >      jZ      
      >      sZ                  |Z      
      P      Z      
      "?      Z      
      ?      Z            0      Z            0      Z      
      Z?      Z      
      X?      Z                  Z                  Z      
      ?      Z      
      }?      Z                  [                  [      
      ?      ![      
      ?      &[                  ;[      
      ?      ?[      
      ?      K[            $      T[      
            e[      
      ?      i[      
      ?      r[            $      {[      
             [      
      F@      [      
      @@      [            $      [      
      `      [      
      @      [      
      @      [      
      @      [      
      @      [            $      [      
            [      
      A      [      
      	A      [      
      MA      [      
      IA      [            $      \            $      \            $      4\      
      A      8\      
      A      =\            $      R\      
      A      V\      
      A      d\                  m\      
            ~\      
      A      \      
      A      \      
            \      
      -B      \      
      +B      \                  \         N          \            M      \            [      \                  \                  ]             	      !]            r      6]      
            :]      
            B]      
            F]      
            N]      
      !      R]      
      !      Z]      
            ^]      
            f]      
      _      j]      
      _      s]      
            w]      
      h      ]      
            ]      
            ]      
      P      ]      
      P      ]      
      `      ]      
      `      ]      
             ]      
             ]      
      l      ]      
      l      ]      
            ]      
            ]      
      L      ]      
      L      ]      
            ]      
            ^      
             ^      
             ^      
            ^      
            ^      
            ^      
            '^      
            +^      
            3^      
            7^      
            ?^      
            C^      
            K^      
            O^      
            X^      
      y      \^      
      y      d^      
      
      h^      
      
      p^      
            t^      
            }^      
      q      ^      
      q      ^      
            ^      
            ^      
            ^      
            ^      
      j       ^      
      j       ^      
            ^      
            ^      
      
      ^      
      
      ^      
            ^      
            ^      
      $      ^      
      $      ^      
            ^      
            ^      
            ^      
            ^      
            ^      
            ^      
      f	      _      
      f	      _      
      &      _      
      &      _      
      !      _      
      !      #_      
      "      '_      
      "      /_      
      X      3_      
      X      ;_      
      B      ?_      
      B      H_      
            L_      
            U_      
      
      Y_      
      
      b_      
      `      f_      
      `      n_      
      V      r_      
      V      z_      
            ~_      
            _      
      d      _      
      d      _      
            _      
            _      
      .      _      
      .      _      
      E      _      
      E      _      
            _      
            _      
            _      
            _      
            _      
            _      
            _      
            _      
            _      
            _      
      !      _      
      !      `      
      
      `      
      
      `      
            `      
            `      
      w      !`      
      w      b`      
      0      f`      
      0      n`      
      !      r`      
      !      z`      
            ~`      
            `      
      M      `      
      M                   o                                                               A                   I                   T                   \                   g                   o                                                                                                                               !                   !                                                                                             9               N         6                  >            9      I                    d                   l            -      w         N                                        -                  Z                                    !                                    Z                        
            !                        0            Z      8                  C         N         ^            Z      f                  q                               p                                 N                     p                                                      #                  ?                  f      *                  2            *      S                   [                  f                  n            =      y                                                                                                                        L                  X                  X                  h                  h                              
      }]                        &                  1                   9            !      X            h      `            |      k      
      }]      p                  x                              h                  |                  @                                                       @                                                  
      ]                                                       @       9                  A                  `                  h                  s                  {            w                                                                        	                  	                  	                                                                              &                  .            	      9            	      A            	      `                  h                  s                  {            	                                                                        	                                                                        	      $                  ,                  7                  ?                  J                  R            D      `            D      h            g      s            g      {            u                  u                                                                                                                                                                                                            #                  +            D      9            D      A            a      L            a      T            u      b            u      j                  u                  }                                                                                                                                                                  	                  	                   	                  (	                  3	                  ;	            +      F	            +      N	            C      Y	            C      a	            D      l	                  t	                  	                  	                  	                  	                  	            W      	            u      	                  	                  	                  
                  
                  
                  =
                  E
                  b
                  j
            ?      
                  
                  
                  
                  
                  
                  
            L                  V                  u                  |      4            W      <            W      G            }      O                  l            L      t            L                                                                                                                                                                  L                  @                                          *            L      ;            @      X                  `                                                                                                                                                            "                                          	                                    .            	      6                  U            	      ]                  p                  x                              	                                                                                                                                    !                  )                  F                  N                  m                   u                                                                                                                          !                  !                  "                                                                        "      6            0      >            <      I            <      Q            O      s            0      {            <                  <                  O                  0                  <                  <                  N                  N                  O                                                                              *                  2                  X                  `                  k                  s                  ~                                                                                                                                                                              h                  h                  o                  o                        %                  -                  8                  @                  c                  k                  w                                                8                  =                                                                        -               N                                        =                        #                  :                  B                  Y            o      a            o                                                                                                                                                      >            o      F            o      o            o      w            o                                                                        >                  >                  f                  f                                                            
                                                      %                  K                  S                  ^                  f            )      q            f      y                                                                                    c                  f                                                                        T                   a      !                  )                  4                  <                  G                  O                  n                  v            
                                                                                                            
                                                                                                                  7                  ?                  J                  R                  ]                  e                                                                                                                                                                                                                                          $                  ,                  7                  ?                  \                  d                                                                                                                                                                                    &                  1                  9            !      D            f      L            y      m                  u                                                !                  f                  u                                                      u                  y                  y      
            y      -            1      5            1      C                  K                  m            1      u            1                                                                                          >                  \                                                                              !                  )                  5                  =                  Z            T      b            T                  T                  T                  T                  T                  T                  T                  T                  a      +            a      3            f      R            T      Z            a      q            a      y            f                  T                  a                  a                  f                  0
                  p
                  p
      	            
                  
                  
      '            
      /                  :                  B                  P                  X            9      c            9      k            O      v            O      ~            O                                                                            .                   0
                  S
                  S
                                                                                          O                                       .       =            
      E            
      l            P
      t            S
                  S
                  ~
                  
                  
                                    J                  O                  O                                      .                   P
                  m
                  P
                   S
      +            S
      3            m
      P            P
      X            m
      x            P
                  S
                  S
                  m
                  P
                  S
                  S
                  ^
                  P
                  P
                  U
                  U
      4            ^
      <            a
      Y            a
      a            a
                  m
                  
                  9                  E                  ~
                  
                  E                  E                  m
                  m
                   
      %             
      0                   8                   W             
      _             
      j                   r                                
                   
                   
                   
                   
                   
      !            
      !            
      )!            
      1!            
      R!            
      Z!            
      e!            
      m!            
      ~!            
      !            
      !            +      !            9      !            O      !            O      !                    !            $       !            /      "            9      "            O      "            O      $"                    ,"                   7"                   ?"            #       ]"            +      e"            /      "                    "            .       "                   "                   "                   "            #       "            
      "            
      "            
      "            
      #            
      &#            
      2#            
      :#            
      Z#            
      b#            
      m#            
      u#            
      #            
      #            
      #            
      #            
      #            
      #            
      #            
      #            
      
$            
      $            
      $            
      &$            
      F$            
      N$            
      Y$            
      a$            
      $            
      $            
      $            
      $            
      $            
      $            
      $            
      $            
      $            
      $            
      %            
      %            
      <%            
      D%            
      f%            
      n%            
      %                  %                  %                  %                  %                  %                  %            0      %            ?      &            ?      
&            P      ,&            P      4&            _      ?&            _      G&            p      i&            p      q&                  |&                  &                  &            P      &            a      &            a      &            G      &                  &                  &                   '                  '                  '                  '            X      8'                  @'            1      K'         N          f'                  n'            1      y'                   '                  '            %      '         N          '                  '            %      '                  '                  (            p      (                   (         N          ;(            p      C(                  N(                    i(                  q(                  |(         N          (                  (                  (                   (                   (                   (                   (                   (                   )                   )                   &)                   .)                   9)                   A)                   c)                   k)                   v)                   ~)                   )                   )                   )                   )                   )                   )                   )                   )                    *                  (*            "      3*            "      ;*            '      F*            z      N*                  Y*                  a*                  l*                  t*                  *                  *            %      *            %      *            q      *            q      *            z      *            z      *                  *                  *                  +                  +                  +                  +                  )+                  1+                  <+                  D+                  k+                  s+            ;      ~+            ;      +            O      +            z      +                  +                  +                  +                  +                  +                  +                  ,                  	,                  ,                  ,            ;      ',            z      /,                  :,                  B,                  M,                  U,                  `,                  h,                  s,                  {,                  ,                  ,                  ,                  ,                  ,                  ,                  ,                  ,            ;      ,            ;      ,            z      -            z      -                  -                  -                  --                  5-                  @-                  H-                  n-                  v-                  -                  -                  -                  -                  -                  -                  -                   -                   -                   -                   .            r      .                  ".                  *.            *      5.            g      =.            q      J.            q      R.                  y.            @      .            Y      .            Y      .            i      .            i      .                  .                  .            *      .            *      .            4      .            4      .                  /            R      /            V      /            V      /            y      )/            *      1/            q      N/            N      V/            q      a/         N   >       ~/            U      /            Z      /            Z      /            ^      /            R      /            n      /            n      /                  /                  /                  0            D      0            }      -0                  50                  @0            6      H0            >      e0                  m0                  0                  0                  0                  0                  0             	      0            T	      0            T	      0            	      0            	      1            	      1            	      1            	      %1            	      -1            	      81            	      @1            
      j1             	      r1            T	      }1            T	      1            	      1            	      1            	      1            	      1            	      1            	      1            	      1            	      1            
      1             	      1            T	      
2            T	      2            	       2            	      (2             
      32             
      ;2            
      a2            T	      i2            	      t2            	      |2            	      2            	      2            	      2            	      2            	      2            T	      2            _	      2            	      2            	      2            T	      3            _	      &3            T	      .3            T	      93            T	      A3            T	      R3            T	      Z3            \	      k3            \	      s3            _	      3            	      3            	      3            	      3            	      3            	      3            	      4            	      4            	      34            d	      ;4            	      F4            	      N4            	      m4            l	      u4            	      4            	      4            	      4            d	      4            	      4      
      )`      4            	      4            	      4      
      )`      4            d	      4            	       5            	      5            	      '5            d	      /5            l	      N5            l	      V5            	      a5            	      i5            	      5            l	      5            o	      5            l	      5            o	      5            l	      5            o	      5            l	       6            o	       6            l	      (6            o	      G6            v	      O6            	      Z6            	      b6            	      6            v	      6            v	      6            v	      6            v	      6            v	      6            v	      6            v	      6            v	      7            	      #7            	      .7            	      67            
      X7            	      `7             
      k7             
      s7            
      7            	      7            	      7            	      7            
      7            	      7            
      7         N          7            	      8            
      '8            P      /8            u      :8            u      B8                  M8                  U8                  `8                  h8                  8            P      8            u      8            u      8                  8                  8                  8                  8                  8            P      8            u      9            u      9                  .9            q      69            u      A9            u      I9                  m9            q      u9                  9                  9                  9                  9                  9            q      9                  9                  9                  9                  9                  :            y      :                  2:                  ::                  E:         N          `:                  h:                  s:                   :                  :                  :         N          :                  :                  :                  :            '      :            '      ;            ^      ;            ^      ;            j      $;            j      ,;            t      R;                  Z;            '      e;            '      m;            ^      {;            ^      ;            m      ;            m      ;            t      ;                  ;            '      ;            '      ;                  ;                  ;            
      ;            
      <            ^      <            ^      <            q      "<            q      *<            t      G<                  O<            '      u<            B      }<            L      <            S      <            Z      <            Z      <                  <                  <                  <                  <            ^      <            [      <            t      <                  =            $      =            0      =            P      7=            k      ?=                  J=            $      R=            ^      o=            0      w=            ^      =            0      =            ^      =         N          =            7      =            K      =            K      =            O      =            [      >            k      >                  >            $      7>            [      ?>            ^      _>            [      g>            ^      >            [      >            ^      >            [      >            ^      >            '      >            B      >                  >                  >                  ?                  "?            '      *?            =      5?                  =?                  Z?            '      b?            '      ?                  ?                  ?                  ?                  ?                  ?                  ?            t      ?            x      
@            $      @            0      @            P      %@            ^      F@            t      N@            x      Y@            $      a@            0      l@            P      t@            ^      @            $      @            $      @            P      @            S      @            $      @            $      @            P      @            S      A            $      A            $      #A            P      +A            S      MA            $      UA            $      `A            P      hA            S      A            $      A            +      A            $      A            $      A            $      A            (      A            +      A            +      A                  B                  B         N          -B                  5B                         
                                                                                                                                                          (                   @             	      H             	      P             	      X                   `                   h                                @                                                                            @                   r                   0                   g                   <                   K                   N                   _                  L                  W                   x      (                  @                  H                  P                  X                  p                  x                                                	                  X	                  _	                  	                  	                  	                  	                  	                  	                  	                  	                  d	                  l	                   l	      (            l	      0            l	      8            v	      @            v	      H            	      P            	      X            	      p            l	      x            l	                  l	                  l	                  l	                  v	                  v	                  	                  	                  	                  l	                  l	                  l	                  l	                  l	                  o	                  v	                  v	                   v	      (            	      0            	      8            	      P            v	      X            v	      `            v	      h            v	                  	                  	                  	                  
                  	                  	                  	                  
                  0
                  O                                      .                   P
                  P
                   P
      (            ~
      0            
      8            
      @            
      H            
      P            
      X            
      `                   h            J      p                    x            .                   P
                  P
                  P
                  m
                  m
                  ~
                  @                  J                  
                  
                   
                  
                  
                  
                          (                   @            
      H            
      P            
      X            
      p            
      x            
                  
                  
                  +                  @                                      $                   
                  
                  +                  /                  
                  
                   
                  
                  
                  
                   
      (            
      @            
      H            
      P            
      X            
      `            
      h            
      p            
      x            
                  
                  
                  
                  
                  
                  
                  
                  
                  
                  
                  
                  
                  
                  
                   
      (            
      @            
      H            
      P            
      X            
      p            |      x                                                                                                                                                                                                                                                                                                                                      (                  @                  H                  P                  X                  `                  h                  p                  x                                                                                                                                                            !                  p                         	                  	            !      	            p      	            u      0	            1      8	            1      @	            1      H	            1      P	            1      X	            6      `	                  h	                  p	                  x	                  	                  	                  	                  	                  	            1      	            1      	            1      	            6      	                  	                  	                  	                  	                  	                  
            1      
            1       
            1      (
            1      0
                  8
                  @
                  H
                  `
            1      h
            1      p
                  x
                  
                  
                  
                  
                  
            6      
            :      
            >      
            >      
            >      
            G      
                  
                                                                                                              (                  0                  8                  P            6      X            :      `            >      h            >      p            >      x            >                                                                                                                                                                                                                                                                              T                  T                   T      (            T      0            X      8            Z      @            \      H            a      `                  h                  p                  x                              
                                                      %                  q                                                                                                                                                        (            [      0            [      8                  @                  H                  P                  X                   `                   h            $      p            $      x            $                  $                  P                  P                  P                  P                  `                                    0                  [                  [                  [                  t                                                                            $                  0                  P      0                  8            0      @            0      H            P      `            [      h            [      p            [      x            k                                                                           $                  [                  [                  [                  ^                                                                           $                  0                  H                         (                  0                  8                  P            0      X            =      `                  h                              t                  x                  $                  $                  $                  $                  $                  0                  P                  P                  P                  P                  P                  `                   t                  x                  $                  $                   $      (            0      0            P      8            P      @            P      H            `      `            $      h            $      p            $      x            $                  P                  P                  P                  S                  $                  $                  P                  S                                                                                                                                      (                   0                   8            -      P                  X                  `                  h                   p            p      x            v                                                                                                                                                                                                                         =                                          0                  8                  @                  H                  `            =      h                  p                  x            (                  h                  |                  |                                                                                                                                                                                                         -      0            L      8            S      @            Z      H                  `            L      h            S      p            Z      x                              _                  p                  p                                                                                                                                                 $                  ?                  M                  Q      0                    8                  @                    H            .       {                                P                        (                                          4                    H             0       \             `       p             p                                                                                                                            $                  D            0      \            P      t            p                                                             0                                                                                     	      P             
      d            0
                                      P                                           <            0      X            P                  P                                           D                   .symtab .strtab .shstrtab .rela.text .data .bss .rela.gnu.build.attributes .text.hot .rela.gnu.build.attributes.hot .rela.gnu.build.attributes.unlikely .text.startup .rela.gnu.build.attributes.startup .text.exit .rela.gnu.build.attributes.exit .rodata.str1.1 .rodata.str1.8 .rela.text.unlikely .rela.data.rel.local .rodata.cst16 .rela.debug_info .debug_abbrev .rela.debug_loc .rela.debug_aranges .rela.debug_ranges .rela.debug_line .debug_str .comment .text.hot.zzz .text.unlikely.zzz .text.startup.zzz .text.exit.zzz .note.GNU-stack .note.gnu.property .rela.eh_frame .group                                                                 9                     @              8                    9                     T              8                    9                     l              8                    9                                   8                    9                                   8                                                                                   @              xe     #      8                    &                                                         ,                                                          6                                                         1      @                         8   
                 L                    (                                     [                     (                                   V      @              x     0       8                                       h*                                     z                     h*                                   u      @                   0       8                                        <,                                                          <,                                         @              ؕ     0       8                                        .                                                          .                                         @                   0       8                          2               /                                       2               1                                                      2      .                                   @              8     `       8                    ,                    2                                    '     @                           8                    <                    2                                   O                     2      `                             J     @                    p      8                    [                                                        n                     h      QB                             i     @                M     hm      8   "                 ~                           @                              y     @                    H       8   $                                            `                                  @               к      .      8   &                                      Y      f                                  @                    `       8   (                      0                    \"                                 0               1     .                                                 I1                                                        I1                                    L                    I1                                                          I1                                                       I1                                                       I1                                                       I1                                                       I1                                                         I1                                                        P1                                    /                    p1     x                             *     @               P     H      8   6                                       6           9                    	                      pT                                                             @                             
SHELL = /bin/sh

# V=0 quiet, V=1 verbose.  other values don't work.
V = 1
Q1 = $(V:1=)
Q = $(Q1:0=@)
ECHO1 = $(V:1=@ :)
ECHO = $(ECHO1:0=@ echo)
NULLCMD = :

#### Start of system configuration section. ####

srcdir = .
topdir = /opt/alt/ruby30/include
hdrdir = $(topdir)
arch_hdrdir = /opt/alt/ruby30/include
PATH_SEPARATOR = :
VPATH = $(srcdir):$(arch_hdrdir)/ruby:$(hdrdir)/ruby
prefix = $(DESTDIR)/opt/alt/ruby30
rubysitearchprefix = $(sitearchlibdir)/$(RUBY_BASE_NAME)
rubyarchprefix = $(DESTDIR)/opt/alt/ruby30/lib64/ruby
rubylibprefix = $(exec_prefix)/share/ruby
exec_prefix = $(DESTDIR)/opt/alt/ruby30
vendorarchhdrdir = $(vendorhdrdir)/$(arch)
sitearchhdrdir = $(sitehdrdir)/$(arch)
rubyarchhdrdir = $(DESTDIR)/opt/alt/ruby30/include
vendorhdrdir = $(rubyhdrdir)/vendor_ruby
sitehdrdir = $(rubyhdrdir)/site_ruby
rubyhdrdir = $(DESTDIR)/opt/alt/ruby30/include
rubygemsdir = $(DESTDIR)/opt/alt/ruby30/share/rubygems
vendorarchdir = $(DESTDIR)/opt/alt/ruby30/lib64/ruby/vendor_ruby
vendorlibdir = $(vendordir)
vendordir = $(DESTDIR)/opt/alt/ruby30/share/ruby/vendor_ruby
sitearchdir = $(DESTDIR)./.gem.20260423-2958356-umky45
sitelibdir = $(DESTDIR)./.gem.20260423-2958356-umky45
sitedir = $(DESTDIR)/opt/alt/ruby30/share/ruby/site_ruby
rubyarchdir = $(rubyarchprefix)
rubylibdir = $(rubylibprefix)
sitearchincludedir = $(includedir)/$(sitearch)
archincludedir = $(includedir)/$(arch)
sitearchlibdir = $(libdir)/$(sitearch)
archlibdir = $(DESTDIR)/opt/alt/ruby30/lib64
ridir = $(datarootdir)/$(RI_BASE_NAME)
mandir = $(DESTDIR)/opt/alt/ruby30/share/man
localedir = $(datarootdir)/locale
libdir = $(exec_prefix)/lib64
psdir = $(docdir)
pdfdir = $(docdir)
dvidir = $(docdir)
htmldir = $(docdir)
infodir = $(DESTDIR)/opt/alt/ruby30/share/info
docdir = $(datarootdir)/doc/$(PACKAGE)
oldincludedir = $(DESTDIR)/usr/include
includedir = $(DESTDIR)/opt/alt/ruby30/include
localstatedir = $(DESTDIR)/var
sharedstatedir = $(DESTDIR)/var/lib
sysconfdir = $(DESTDIR)/etc
datadir = $(DESTDIR)/opt/alt/ruby30/share
datarootdir = $(prefix)/share
libexecdir = $(DESTDIR)/opt/alt/ruby30/libexec
sbindir = $(DESTDIR)/opt/alt/ruby30/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 = -Wl,-rpath,$(archlibdir) -L$(archlibdir) -l$(RUBY_SO_NAME)
LIBRUBYARG_STATIC = -Wl,-rpath,$(archlibdir) -L$(archlibdir) -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) -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection $(ARCH_FLAG)
INCFLAGS = -I. -I$(arch_hdrdir) -I$(hdrdir)/ruby/backward -I$(hdrdir) -I$(srcdir)
DEFS     = 
CPPFLAGS =   $(DEFS) $(cppflags)
CXXFLAGS = $(CCDLFLAGS) -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection $(ARCH_FLAG)
ldflags  = -L. -Wl,-z,relro  -Wl,-z,now -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -fstack-protector-strong -rdynamic -Wl,-export-dynamic -Wl,--no-as-needed
dldflags = -Wl,-z,relro  -Wl,-z,now -specs=/usr/lib/rpm/redhat/redhat-hardened-ld 
ARCH_FLAG = -m64
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_dir_name)
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)
BUILTRUBY = $(bindir)/$(RUBY_BASE_NAME)
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 = . $(archlibdir)
LIBPATH =  -L. -L$(archlibdir) -Wl,-rpath,$(archlibdir)
DEFFILE = 

CLEANFILES = mkmf.log
DISTCLEANFILES = 
DISTCLEANDIRS = 

extout = 
extout_prefix = 
target_prefix = 
LOCAL_LIBS = 
LIBS = $(LIBRUBYARG_SHARED)  -lm   -lc
ORIG_SRCS = lsapilib.c lsruby.c
SRCS = $(ORIG_SRCS) 
OBJS = lsapilib.o lsruby.o
HDRS = $(srcdir)/lsapidef.h $(srcdir)/lsapilib.h
LOCAL_HDRS = 
TARGET = lsapi
TARGET_NAME = lsapi
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)
/*
Copyright (c) 2002-2018, Lite Speed Technologies Inc.
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 Lite Speed Technologies Inc 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  _LSAPIDEF_H_
#define  _LSAPIDEF_H_

#include <inttypes.h>

#if defined (c_plusplus) || defined (__cplusplus)
extern "C" {
#endif

enum
{
    H_ACCEPT = 0,
    H_ACC_CHARSET,
    H_ACC_ENCODING,
    H_ACC_LANG,
    H_AUTHORIZATION,
    H_CONNECTION,
    H_CONTENT_TYPE,
    H_CONTENT_LENGTH,
    H_COOKIE,
    H_COOKIE2,
    H_HOST,
    H_PRAGMA,
    H_REFERER,
    H_USERAGENT,
    H_CACHE_CTRL,
    H_IF_MODIFIED_SINCE,
    H_IF_MATCH,
    H_IF_NO_MATCH,
    H_IF_RANGE,
    H_IF_UNMOD_SINCE,
    H_KEEP_ALIVE,
    H_RANGE,
    H_X_FORWARDED_FOR,
    H_VIA,
    H_TRANSFER_ENCODING

};
#define LSAPI_SOCK_FILENO           0

#define LSAPI_VERSION_B0            'L'
#define LSAPI_VERSION_B1            'S'

/* Values for m_flag in lsapi_packet_header */
#define LSAPI_ENDIAN_LITTLE         0
#define LSAPI_ENDIAN_BIG            1
#define LSAPI_ENDIAN_BIT            1

#if defined(__i386__)||defined( __x86_64 )||defined( __x86_64__ )
#define LSAPI_ENDIAN                LSAPI_ENDIAN_LITTLE
#else
#define LSAPI_ENDIAN                LSAPI_ENDIAN_BIG
#endif

/* Values for m_type in lsapi_packet_header */
#define LSAPI_BEGIN_REQUEST         1
#define LSAPI_ABORT_REQUEST         2
#define LSAPI_RESP_HEADER           3
#define LSAPI_RESP_STREAM           4
#define LSAPI_RESP_END              5
#define LSAPI_STDERR_STREAM         6
#define LSAPI_REQ_RECEIVED          7
#define LSAPI_CONN_CLOSE            8
#define LSAPI_INTERNAL_ERROR        9


#define LSAPI_MAX_HEADER_LEN        65535
#define LSAPI_MAX_DATA_PACKET_LEN   16384

#define LSAPI_RESP_HTTP_HEADER_MAX  32768
#define LSAPI_PACKET_HEADER_LEN     8


struct lsapi_packet_header
{
    char    m_versionB0;      /* LSAPI protocol version */
    char    m_versionB1;
    char    m_type;
    char    m_flag;
    union
    {
        int32_t m_iLen;       /* include this header */
        char    m_bytes[4];
    }m_packetLen;
};

/*
    LSAPI request header packet

    1. struct lsapi_req_header
    2. struct lsapi_http_header_index
    3. lsapi_header_offset * unknownHeaders
    4. org http request header
    5. request body if available
*/

struct lsapi_req_header
{
    struct lsapi_packet_header m_pktHeader;

    int32_t m_httpHeaderLen;
    int32_t m_reqBodyLen;
    int32_t m_scriptFileOff;   /* path to the script file. */
    int32_t m_scriptNameOff;   /* decrypted URI, without pathinfo, */
    int32_t m_queryStringOff;  /* Query string inside env */
    int32_t m_requestMethodOff;
    int32_t m_cntUnknownHeaders;
    int32_t m_cntEnv;
    int32_t m_cntSpecialEnv;
} ;


struct lsapi_http_header_index
{
    uint16_t m_headerLen[H_TRANSFER_ENCODING+1];
    int32_t m_headerOff[H_TRANSFER_ENCODING+1];
} ;

struct lsapi_header_offset
{
    int32_t nameOff;
    int32_t nameLen;
    int32_t valueOff;
    int32_t valueLen;
} ;

struct lsapi_resp_info
{
    int32_t m_cntHeaders;
    int32_t m_status;
};

struct lsapi_resp_header
{
    struct  lsapi_packet_header  m_pktHeader;
    struct  lsapi_resp_info      m_respInfo;
};

#if defined (c_plusplus) || defined (__cplusplus)
}
#endif


#endif

ELF          >                             @     @ = <           
                   0   2                /   3                .   4                -   5               ff.             ÐHGH+F HcAVIH@AUATL$USHtQHHtIHIL9r0HI9v'KHSMsH;Յ[]A\A]A^     [D]A\A]A^øff.     f=    D         ÐOAWDD_AVAUATUSD6^nAxj׋G3GD!3GV\$ЋW^$DD1\$!3WAʋNFp $EL$A1A1DD^!D1G;νD\$DEDVDT$A!A1EE|A
1AD!E1DD*ƇGD1D!A1A1DDNDL$E	F0D!DnA1D1DGFEDf Dd$D^(A!A1EEؘiA
1AD!1DDDʋ^0D1D!A1DE[D1!D1DDN,A1DL$G\EA!Df8A1ED"kA
1AD!1DDN4EqDD1!1DECyD1!D1DDV<1G!I!1DDD$
E b%1!1DDD$E@@1!1DDD$	EQZ^&1!1DE6Ƕ1!1DD]/։1!1DESD1!1DE
؉	1!1DDD$E01!1DDD$E !1!1DE7É1!1DDD$	E1!1DDD$A0ZEAA1A!A1AA㩉AAD1!1t$DD1!AogD1	1D!FL*1DD$Ή1AA!B9A1DD$AAD1D$qDD11D$0"amD1G81Ɖ11DDD$	ED꾤11DDD$AKAA1A5`KA1AЉApA1AD1D1D1A	~(D	1G'111DDD$A0AA1A1AЋT$A2A1D1֋T$	
9ىDD11D11C|AA1A1AD$A0eVĉA1D1AD")Dt$	D	D1A*CDG#	1
	1DD9Ή	1DDY[e\$	1DEDt$	щ1DE3}D\$
	1DDD$E ]	1DEO~oAAD	1DE
,DT$	A1ADE6CDt$
AN	1A~SADEAA	A1A5:ADAAD	1Љ3*\$D	D1DFӆ[
]A\A]A^	1։	1DƉA4A_OWGOW    ATI1USH   dH%(   H$   1HH    H<$ t)H$   dH3%(   u<HĠ   []A\f.     H{    1HމǄ$       L$$        D  H    HA(HQ8H9s;8ufD  98tH0H9w1ÅtHP0H;Q0vHQ0D  fH@$    @@@,     D  UHcSHHHH@    Ht#HSPHH+S@HC@HHSPHCH1H[]øf     U1҉1S   H    tt/H1[]fD  tH߾   [1]    fff.     SH   dH%(   H$   1HT$Ht$D$   D$       Ãtf|$t'H$   dH3%(   u0HĠ   [f     HL$A      Ǿ           ff.     f       HcHvLHL9   HH)H   SNf.     E      LI؃HLGLECHDGwI9thHH)H~SHpH2HpD H2HpDXH2pAEL@LIcApDHcLML9i[f0uH[H1øËuHH1f     AVAUE1ATUH-    SH}( t[D]A\A]A^ EEA!   Lc@   D
     DIE11A McL    HHt]L1H    KvH](HH]0HH]8HCH    H    HCHH    H        [D]A\A]A^H=    A    1     H   H   H+   HcpG )   H   HxsH9AVHNAUATUISHwHDwH    LHD    IHu!    8u
    uD[]A\A]A^ÐH~   []A\A]A^øfD  USHtMH    u    8u
    uH    E Ht(H    Ht@ H[]ff.     @ AWAVAUATUSH       t8AAIAfI7D    Å-tx    uDD)H[]A\A]A^A_    A)E~ڋ    tIf     H)I~HPHcH9vHIH)Hx          tsE)EAOr1k S    t-=    t+1    u    [8    1[@     9[ÐAVAUATUHSHHP  dH%(   H$H  1    H
fD  HHDB uLd$@   HL    D$@Ƅ$?   </tc<[      :   LfE     H    |$@*HXz  H5    L    Aƅ;  E  M      H}l   fu L    1H$H  dH3%(   Q  HP  []A\A]A^D  
   Ml$]   fM L    H    |$A*HXA      1;:
   1HH    HÍ@=     Euf1f]YD  E f1HT$)D$HL$LD$H      )D$ )D$0HD$    upLd$HAT$It$    L    LE1M    EA<     E    E1M"::  AD$ MfA$
        AUIATUSH(  H$  H$  L$  L$  t@)$  )$  )$  )$  )$  )$  )$   )$  dH%(   H$h  1   t=    M  Ld$`L@@u         L9   H    H;HL$HL   H$P  D$H   HD$PH$p  D$L0   HD$X    H$h  dH3%(     H(  []A\A] H    HL    HL¾d   1       HHÁ   K-        HHߺ   UAL    d   H1    HHXZL9HH    M1L)H       H;    fH1Ld$`H    Ht$H       uI   D$   L   L       PD$PDL$(1    Y^HcLLHD$L       L      PD$PD$$PD$0PD$<PD$HPD$TDl  1    H0HcL    ff.     @ AWAVAUATUSH(dH%(   HD$1H=     .  D$   Hl$L5    L-    L%    @    H    Aǅ   T$Ѓ<~$ML     DME1    D;=    tD;=    tUDHHtHH1@1@Ɖ@   H    Ht(H        hK     9H5    HN0HV(H9s*DAHAEtD  H08u.HH9rHF0HD$dH3%(   uH([]A\A]A^A_ HN0    D$@1D$XH    HDCff.     AWAVAUATUHSHH(  =    dH%(   H$  1t1    thHC(IID3L+cI)HC D{H)    D$    HEEATH5      AU1UL$,    H         t)H$  dH3%(   ulH(  []A\A]A^A_@ DH\$H   H߹      AQL        XHZ    t1    fD  H=            D  AWAVAUATUSHL    IZ(Mj0L9  H|$E1E1E1@ BveCAl$   ABD)A;B  E9r
      ~ HSHL$HH)H9   fD  CAfA H0I9wARD)1)ȃ  H[]A\A]A^A_fD  HC Ht$H)IcBH9   Cigf  f)f9u       Cf~pH5      1    ;	       tpCAL    AfC5fD  CfC     A     H5      1    ;       u    8u    L    HEED[H5    ]  A\1A]A^A_    fD  Ht$H@ E1E1E1zf.     UHSH    HHI[H5      1]    f         1u1=              Ð    D  H=    @ ATUSH   dH%(   H$   1H}  H    HH1HǇ 	      HىHH)   	  HH{`    IH0  HCxHS`Lc`    LH)HCxHCpLH)HCpI$   HCh    HC8HC(H   H    I   HHC0H(  LcxLcpH   l   twHT$Ht$D$       t
    8kt01kH$   dH3%(   uiHĠ   []A\fD  +   CC1    1       H=    1    1    _fD      ff.     S    t	1ۉ[     H5L            eH5>
   T                    H=    1    tI              H=            HcH5    H    H    [ÉD 1? H=        HW(Hw`HǇ       HHǇ0      H   HWHVHWHWHWHWH)8  1H    SHHHt    H   Ht    H   Ht    H{@Ht    1[fD  HtGwBL   HcAT4t/HcApH   HH: t
 H   H    1ff.     fHtPtJSHc   H;   }HSHH      [ ~	Hc   и[Ã AWAVAUATUSHZHHHD$H:  G   H%  H      IH   I   IILfD  A   )HcH   L9HcIOIvI
   HL    HtML)HLHXHH    A   I   A$   D)E  H[]A\A]A^A_    LHHH    A   L|$I   I)A   M?D  LLHcH~A   -H1|v@ AVAUATUSH   I   HH   HH   H   H+   E1H   H9Hc   HO؋   )HH~)H9HwHHNHHI    E   LL)Ht6Eu@ HHD    Hu4    8u
    uMt-M   [L]A\A]A^     H~IHH)uID  HO(HW8H   Ǉ   LS    H)ʍB     HGpH0HpH@   Hwp~HcHHH HPHO8HGp    AWAVAUATUSHH   HT$H   HH<$   IH=        HcB$H   H@H,H9rZf.     HH9vGH3L    uHCH[]A\A]A^A_HD$L9  IM9   f.     1H[]A\A]A^A_    H$1L=    L   @ Al4tI4L       HHuHD$HcP 1~H$HL   Mt M9sH   H$ID$HD$@ IcMIcm H,$L| L9)A\$)    H8HD$'-t	_HHI9tHU :t 8 IcUIcEH$H:      H$HcHcAVH   H: @ AVAUATUSL$ H   H$ L9uHdH%(   H$@  1H  HH  H   H  HE1L    L    f     H   HcHcT4t7qH   M
 HIcAHLEHTDTtHHuH   HcP    H   HLL9   IcIHLfHH I9   HcHHc0AH    LcPIHcHH   B DBHJHH2JA   u   H        L    $D  IH    Ic    L    EtaE1@ AI E9~CAMIUIAuI} ӅH$@  dH3%(   u6H@  []A\A]A^    D 1@ IcU    ff.     AWAVAUATUSHX  Ht$ HT$dH%(   H$H  1H  IH  1E1L-    HL%    HH   HcHcT4t/HH   AAt I<H LD$Aׅ4  HHuH   Dt$<HcB   L   HLHD$0I9   H\$(Lt$@fD  HD$(Al$Ic$AHTTPH      AF_L<HD$   OHcŉl$8IHD$I9   Mn IIoI_   @-t    H AEL9uHD$IDt$8LD$  LIcD$IcT$HT$ HD$ AL$Ѕ~"IL9d$0-Hl$(H   B D$<H$H  dH3<%(   u'HX  []A\A]A^A_D  IFv    ff.     Ht7Ht2H   D@$1E    H   HHD f.     Ht7Ht2H   D@(1E    H   HHDS f.     H   HO`Htz   ЃtrLG@      HWPL9vHwpL)LHHVHwpHc0  HTHQ   ,  H(  Ǉ(  LS H1HOxøf.     H   HGpH+GxH   G   SH      HC(H9C8tH    HSpH+Sx1H~J       u${Hsx9   ~H{ǃ       HS`HSxHSp[fHG(H9G8c1        lǇ       HW(HW8HW`HWxHWpøf     AWAVAUATUSHXHt$dH%(   HD$H1H.  H=        GI   ;   HG(H9G8tH$    H$HD$L|$Ld$H$Hl$ I     HL)H   H @   @  L|$0HOLd$ D$LS BLjHT$8I׋    D$DHD$(   Hl$uA~H4$D   HI9~I~HL)HLH+D$    Ht$       HL$HdH3%(   uHX[]A\A]A^A_H    @ AWAVAUATUSH   H$ HdH%(   H$  1HII    H8    HIH    HD    A    AW   HSA   1AVL       AU       H H=   OHcMt7L    1H$  dH3%(   u&H  []A\A]A^A_                ff.     @ AT~   fAUHSH  dH%(   H$  1H|$H)$HHH    xH$  dH3%(   u?H  []A\ÉID  H5    1    1H5    Hi    ff.     fATUSH   H$ H   H$ HdH%(   H$   1      ?/HH     H    Hb  HߋH!%t¹     DHWHD@ HH)</)HcHcH1H    HJ  L$     HL    H      H=    L      A  H1    Ń   uRH=    H9t
Ht    H1    H    H$   dH34%(      H   []A\fD                       @      4+    HH5    1rrD  H߹    SfD                  HH5    1     Htv   t]SHtCuWHC(H9C8tH    HCpH    HHHH@      HCp    H    1[@         뢸ff.     H      uu1fSHtRubHC(H9C8tH    HCpH    HHHH@      HCp    H{:      1[    1HO@H9OPv    닸    AWAVAUATUSHH  H|     I֨,  a  HHt$H>  L{8I   HC0L)H9>  Lt$L+{(L   A @  LLfIM)M   KH @     σLS LCpN   IHD   I0HI@   HKpM~HC(MxIH E1I@HC8H   L1HMLIHHKpH9eH    thILM)MUI9tH    tDL+t$HL[]A\A]A^A_D  M@   @  M)(        I    Ht$HL    Hk8f.     H         AVL   AUIATIUS   Hu\H߉       AD${Lǃ   LS          Hu0{L[L]A\A]A^                 [H]A\A]A^Hff.     AWAVAUATUSHHH  H     D$  0    x  IHIH    Lc\  C  HcTt
u(HD  Lc  LH
ttL    Å~6HcATt
u#H@ Å~ALH
ttE<AG=      I|$PHHTI9T$Hs7H   I+t$@L2%  ))   I|$PLHHcA    Mt$PHLIFID$PA:I|$P    MD$PII@ID$PA  Ic$0  fET8  HЃA$0  D$H[]A\A]A^A_D$ff.     H
  H  B=           0       AUATUSHcHfDA<
t<uH؅uH[]A\A] IHPHHDI9D$Hs3H   I+t$@L2%  ))tQI|$PHHA    I\$PHCID$P Ic$0  fET8  HЃA$0  H1[]A\A]øSD  AUATAUHSH?dH%(   HD$1D$   f   f
t1f   HL$dH3%(      H[]A\A]ÐA   1Ҿ       ÃtŉǺ      1    HL$A   ߺ          u#DH    uD    o    ߻D H    De OA   kD  H}An       } N     Htff.     USH   dH%(   H$   1HH    u/H    H$   dH3%(   uHĘ   []         @ 1H=     t       AUATA'  USH    '  DNuD    H@      A    HH    H   HtH-                Ɖǉ        U       Dk H    DcEu<DSuGC   H,    HC    1H[]A\A]@ A|$C    {˸كÉSff.     @ H    Ht8ff.     fH    B    HB(HR8H9s     H0H9wH    Ht	     H    Ht	     fD  H    HH;       wHHH;    ff.     @ ATUSHH dH%(   HD$1H    D`    HSX    HkXH-        H                        H    H        HtH    11H-    EH    Ht {1F    uH    HtAD9 ~           ut;u]HLS    [HH$    D$       H߉D$        1HL$dH3%(   u)H []A\D           t    H    SH@HX t1    HSXHBHB{    C1[AWAVAUATUSHH  H    H|$H$   LedH%(   H$8  1HLǄ$(      H$       H    H       c  HLǄ$(      H$       H    H         H    H         H    H
         H    H         HD$1E1Ld$         L|$ǀ       D$    H    Ht	H=    1    IL9t71   LPCtS  D$    fD  V       H       LH1HHc;    ;MLHD$   HD$    ?)Ѻ   H1H	T 1    Ń          8   1H5           1ҿ   H5        1ҿ   H5        1ҿ   H5        1ҿ
   H5        H$8  dH3%(   k  HH  []A\A]A^A_fD  H    HudDCSK
D9   H    AHtD  H5    1             M fD  D0DCE~E~      D      Au D$t$9/D  ;)AHD$DpAuc    0kbH=    D    jf.     H=        H=        11H\$HCX         =    f=    D  H    Htxff.     H    Htxx     H    Ht~x     H    Ht~x     H    Htxff.     =    D      D          Ð    D  AUATUHH=    SH8  dH%(   H$(  1    HtH H=       H=        HE  1
   H      H=        Ht
   1H        H=        HHt
   1H    IAąW  E1H=        Ht
   1H        H=        HtHǺ
   1        H=        H         H=        HtHǺ
   1              H=        H  1
   H    O  H=        HtHǺ
   1        H=        HtHǺ
   1        H=        HtHǺ
   1        H=        HtHǺ
   1        H=        Ht    H=        Ht
   1H        _  H=        Ht
   1H        D                    E  H=        H  =    u	P    5      H=        H  
   1H        t      H    H H   HH   D    L    L    L    C 
   HL t@Hֹ   L D	t%HtAHHt9   HL uHfD  HJHHJHuHHu1ۉH$(  dH3%(     H8  []A\A]fD         H    D<G~   A<MEDA sDHH    _     @ H=        HfD  H=        HfD  Af@    #f    fD  1EH    H    8       H=        HH    H  H5    H    HH        H  -    H5    H    H5    HIH        H5    H    H5    HH        ~H5    H    H    H=    H~  AԅLH=        H=        H        $@ H   H$    HD$        D  HH$      $          t    1҃8k     H=        Ht1
   H    ~    H=        Ht1
   H    ~    H=        HHi  HǺ  11    Ã  HT$ƿ         D$(?     H5        H       H    Htxc@d   x  @  D    E9D    E)Zf     H=            HK]    u
    '          '               )f     ՅtbH    H-D  HH5      1        AHc    L%    HH    a    Åt=            u
        5        `HH5    uHH5      1        HH5    Fff.     AVIAUEATIUHSHt4  Hu!(fD  HH    HL    H] HuMtEL    [1]A\A]A^ÐIcLL    H#EgHG    HHܺvT2HG     AWAVAAUIATUHoSH1HGO@ƉWDW?t;AĉDHH| @   D)A9rhAGt4LL    HL9A?vWEfAIIIH޺@   HH@    HLL9uA?DLHH[]A\A]A^A_    I    ATLfUHSFH?LHz?   )w=t1 9rLHfCAD$AD$ ID$0    7   1)    HCHLHCP?oH{1HM H    HCP    H)KXH[]A\ff.     fAWAVAUATUSH   dH%(   H$   1Ht^   I  A      f     Mcg IoA_@ LH    HuM    8u
=    uٽH$   dH3%(   
  HĨ   []A\A]A^A_f     ~A   A   uI   AǇ      f8LS|  xr  @tPHf@HPXN    	  Mg  A;G Z  A   9~u    Eo)HHcI     HLD    Hu$    85    u    A   MgA   9ID$,HD$HcII   DhA  h(A9   }A    /  HcI   H4@H    H  A   I   I   h$A9   }A      HcI   H4@H    H  A   I   I   Hl$p(I   LH  I   I   Lp$h  M   Ic@o  9g  IcP[  9S  IcpG  9?  IcH3  9+  IHHHHI   HT$I   Ic@ H)I   HHI   HHH   I   HI   IcHI   HHHD$I9  E  1D  L4t9d<B9ZHHuIcP k  I   HHH9r*R   P9!P9P9HH9-  9~H5      1    H5      1    >fH        H IGAG     I   PHf@	f@HHPPHHPPHHPPHHPPHHPPf@f@f@HH#PP H H'P#P$H$H+P'P(f@f@!f@%H(P+f@)I   1fD  I   HcȋL4t#fBI   HT4
rfB@2JHHuM   IcP    I   HHH9       pH@ppHH@ppHH@ppHH@ppHH@ppHH@ppHH@ppHH@pHH9wM   ApI   bIc@I   H0      AǇ      t`    
    A          1       LHc    IHIGAo I   uI   D%    D-    B(AA1  IcH4II   LI
9   HqH=           IJDB(9 x  HqH=        X  IJB($AD$IK  AzHL$;  Mbfo    Lt$ LAoL$AT$Ml$)$           LL    HL$   LH    LL    H$   ID$H$   I3L$H1H	  D$$Dl$E  DDl$    H=    IH  ID      M  H=     t"LDLŃP  |$      Et$A9u  Ht$         D    Ń  5    $  A?D5    t    AH5    L    HtHH        f)    #A   H5    1    H@H5      1       L    H
   1H    I   H5      1    H5      1    D%        DD$    H=    IHtZEW7    E1111       H=        H5      1    E|$       M2;     |$       E1H5    LuI}     Ń1H5    LKfD  =    -        ED$A    IF  H5      1    HH)H5      H1    1H5    L    1H5    LA#    LH    H        1H5    Laff.     AVAUATUSH   dH%(   H$   1D$   H  H    	  ;1Ll$Ld$Lt$Hkl       {ul;   LLD$       C   H    Ht@H    Ht {1f|$   =     u|H4tH舴H        d1H$   dH3%(   u}HĠ   []A\A]A^D            {   H5        Hfы{L      A       ;    ff.     AWAVAUATUSH  D=    dH%(   H$  1Ex  H    H-    H  }       ;    D  H-    Ht1    HED    E  H$   L|$PDcA:  E1A   f     D    E   D    EtH    Ht@f   LH1HIc    DHD$P   HD$X    A?)Ѻ   HH	   D9#  11A|$MH    D9#    H    Ht@ D9#      AD91葳f     H$  dH34%(   '	  H  []A\A]A^A_KL$  HǄ$h      Ml$H$  L    H$   L   HHD$@    A  HLǄ$h      H$      H$  L   HHD$0    P  H$  L   HHD$8    +  H$`  L
   HHD$(      H$   L   HHD$H    Aǅ  HD$PE1Ll$`HD$H$   HD$H$`  HD$fD%    E   H    Ht	H=    1    IL9t<1ձ   L5E  DuE  ME1    V       H       LH1HHc}     } LD$LHD$P   HD$X    ?)Ѻ   H1H	T`1          8Ht$(1ҿ
       x =       _5    tH    Ht@f,D9#
  DC  H    Ht@H    Ht Dc1DN      =     {   H5        HH    Ht*H    HB (@ H    Ht@H    H @     8B-D  AD9M =        =    H    
   HtDH    Ht
A9H    HtD҉T$$DE~:E~5      T$$A    A    AuDEUM
D9vH    AHtDH5      1             D$    0H=        T$fD  } 蠩C   1mH|$I    H|$       HT$Ht$1    6        1  EMtAMgMg{E1    CHt$1ҿ       H=        f;    >fD  D$$    0dT$$WH=    T$    T$fD  D#AfD      RD    EBH    H29    {   H5        H{wH=            H=    0    MA    H
  H{H         H=            Ht$1ҿ         H                    L=        H            H        HtH    11L=    AGH    Ht {1蝦D-    EuH    Ht!E9~              ;t    Ht$@1ҿ   L$      Ht$01ҿ       Ht$H1ҿ       Ht$81ҿ       Ht$(1ҿ
       kHLS    H$      $         L$              H=        %    ,H=        QH    Ht*fC  1CD$CC    T$HC(HC         fD  =        ff.     @ H                ,          LS    LS    LS    LS                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         GA$3p1113                            GA$running gcc 8.5.0 20210514            GA$annobin gcc 8.5.0 20210514            GA$plugin name: gcc-annobin              GA*GOW *            GA*             GA+stack_clash            GA*cf_protection             GA*FORTIFY               GA+GLIBCXX_ASSERTIONS             GA*             GA!              GA+omit_frame_pointer             GA*             GA!stack_realign            GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                           GA*FORTIFY                             GA+GLIBCXX_ASSERTIONS                            GA$3p1113                            GA$running gcc 8.5.0 20210514            GA$annobin gcc 8.5.0 20210514            GA$plugin name: gcc-annobin              GA*GOW *            GA*             GA+stack_clash            GA*cf_protection             GA*FORTIFY               GA+GLIBCXX_ASSERTIONS             GA*             GA!              GA+omit_frame_pointer             GA*             GA!stack_realign             GA$3p1113                            GA$running gcc 8.5.0 20210514            GA$annobin gcc 8.5.0 20210514            GA$plugin name: gcc-annobin              GA*GOW *            GA*             GA+stack_clash            GA*cf_protection             GA*FORTIFY               GA+GLIBCXX_ASSERTIONS             GA*             GA!              GA+omit_frame_pointer             GA*             GA!stack_realign             GA$3p1113                            GA$running gcc 8.5.0 20210514            GA$annobin gcc 8.5.0 20210514            GA$plugin name: gcc-annobin              GA*GOW *            GA*             GA+stack_clash            GA*cf_protection             GA*FORTIFY               GA+GLIBCXX_ASSERTIONS             GA*             GA!              GA+omit_frame_pointer             GA*             GA!stack_realign             GA$3p1113                            GA$running gcc 8.5.0 20210514            GA$annobin gcc 8.5.0 20210514            GA$plugin name: gcc-annobin              GA*GOW *            GA*             GA+stack_clash            GA*cf_protection             GA*FORTIFY               GA+GLIBCXX_ASSERTIONS             GA*             GA!              GA+omit_frame_pointer             GA*             GA!stack_realign    Anonymous mmap() failed localhost %02d:%02d:%02d  [%s]  [UID:%d][%d]  %.*s yes no system() %s, errno: %d (%s)
 /dev/null libpthread.so pthread_atfork HTTP_  [UID:%d][%d] %s:%s: %s
 LSAPI: jail() failure. /etc/ Can't set signals accept() failed LSAPI_STDERR_LOG PHP_LSAPI_MAX_REQUESTS LSAPI_MAX_REQS LSAPI_KEEP_LISTEN LSAPI_AVOID_FORK LSAPI_ACCEPT_NOTIFY LSAPI_SLOW_REQ_MSECS LSAPI_ALLOW_CORE_DUMP LSAPI_MAX_IDLE PHP_LSAPI_CHILDREN LSAPI_CHILDREN LSAPI_EXTRA_CHILDREN LSAPI_MAX_IDLE_CHILDREN LSAPI_PGRP_MAX_IDLE LSAPI_MAX_PROCESS_TIME LSAPI_PPID_NO_CHECK LSAPI_MAX_BUSY_WORKER LSAPI_DUMP_DEBUG_INFO nobody LSAPI_DEFAULT_UID LSAPI_DEFAULT_GID LSAPI_SECRET LSAPI_LVE_ENABLE LVE_ENABLE liblve.so.0 lve_is_available lve_instance_init lve_destroy lve_enter lve_leave jail LSAPI_ PHP_LSAPI_ PHPRC= packetLen < 0
 packetLen > %d
 Bad request header - ERROR#1
 ParseRequest error
 SUEXEC_AUTH SUEXEC_UGID LSAPI: setgid() LSAPI: initgroups() LSAPI: setgroups() LSAPI: setuid() Bad request header - ERROR#2
 lsapi_accept() error Pragma: no-cache Retry-After: 60 Content-Type: text/html DEBUG INFO NOTICE WARN ERROR CRIT FATAL Accept Accept-Charset Accept-Encoding Accept-Language Authorization Connection Content-Type Content-Length Cookie Cookie2 Host Pragma Referer User-Agent Cache-Control If-Modified-Since If-Match If-None-Match If-Range If-Unmodified-Since Keep-Alive Range X-Forwarded-For Via Transfer-Encoding HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING HTTP_ACCEPT_LANGUAGE HTTP_AUTHORIZATION HTTP_CONNECTION CONTENT_TYPE CONTENT_LENGTH HTTP_COOKIE HTTP_COOKIE2 HTTP_HOST HTTP_PRAGMA HTTP_REFERER HTTP_USER_AGENT HTTP_CACHE_CONTROL HTTP_IF_MODIFIED_SINCE HTTP_IF_MATCH HTTP_IF_NONE_MATCH HTTP_IF_RANGE HTTP_IF_UNMODIFIED_SINCE HTTP_KEEP_ALIVE HTTP_RANGE HTTP_X_FORWARDED_FOR HTTP_VIA HTTP_TRANSFER_ENCODING       %04d-%02d-%02d %02d:%02d:%02d.%06d      Child process with pid: %d was killed by signal: %d, core dumped: %s
   Possible runaway process, UID: %d, PPID: %d, PID: %d, reqCount: %d, process time: %ld, checkpoint time: %ld, start time: %ld
   gdb --batch -ex "attach %d" -ex "set height 0" -ex "bt" >&2;PATH=$PATH:/usr/sbin lsof -p %d >&2 Force killing runaway process PID: %d with SIGKILL
     Killing runaway process PID: %d with SIGTERM
   Children tracking is wrong: Cur Children: %d, count: %d, idle: %d, dying: %d
   LSAPI: LVE jail(%d) result: %d, error: %s !
    Invalid custom stderr log path  Failed to open custom stderr log        Can't set signal handler for SIGCHILD   Reached max children process limit: %d, extra: %d, current: %d, busy: %d, please increase LSAPI_CHILDREN.
      LSAPI: failed to open secret file: %s!
 LSAPI: failed to check state of file: %s!
      LSAPI: file permission check failure: %s
       LSAPI: failed to read secret from secret file: %s
      LSAPI: Unable to initialize LVE Request header does match total size, total: %d, real: %ld
     LSAPI: missing SUEXEC_UGID env, use default user!
      LSAPI: SUEXEC_AUTH authentication failed, use default user!
    LSAPI: lve_enter() failure, reached resource limit.     prctl: Failed to set dumpable, core dump may not be available!  sigprocmask(SIG_BLOCK) to block SIGCHLD sigprocmask( SIG_SETMASK ) to restore SIGMASK in child  fork() failed, please increase process limit    sigprocmask( SIG_SETMASK ) to restore SIGMASK   Cache-Control: private, no-cache, no-store, must-revalidate, max-age=0                   PID                            <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<HTML><HEAD>
<TITLE>508 Resource Limit Is Reached</TITLE>
</HEAD><BODY>
<H1>Resource Limit Is Reached</H1>
The website is temporarily unable to service your request as it exceeded resource limit.
Please try again later.
<HR>
</BODY></HTML>
                                            
                        
                     
                                                                         	                                 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       ^                    d          /    4-   /    /    /    /        %-   /    Ga       '9       (   _int G       )@   /    G       G       @       @       G       @       G                                   G                 `<E                           !     <|  /    4  G      @   B@   +/  0     0     0     0     0     0      0     @0                        4  <      G       8   "    	S      -       p   "    .$      0        5       =       >       @       A        C	   $    E   (    J   0    NL  8    PX  @    [+  H    \+  X    ]+  h    j$  x p  4  G        -      	-       	N   1	o      o    G     G        X        a      &       &    	E         18      :	       ;    1?      A
        B
       C   1GO      I	       J       K   1 O      Q	       R       S
       T      U   1a      cE       dE   C^  &    e  &    g    1 Y      [E       ]a       h
   1l5      n        o
    1tf      vE       w
       x@    Cp3  &    5  &    <  &    D  b_rt L  &    VO  &    i  &    p  &    y5        G    1$	+      &	        (	       *	       0	       {	f       |      HC  I  RT       Cv  &    "7  &    $	   R          E   +  v  "          &T       .      1	       4   c  	    G   @ 4  H      H      /    /      -  G        ld      y   "    m      
-       9       1   1;	      C    m    G        Fy    <  d    (  e          G     f       I     @    I     @   I     E  I     E   "    1	      3        6	|      7	|      8	|      9	|       :	|  (    ;	|  0    <	|  8    =	|  @    @	|  H    A	|  P    B	|  X    D	  `    F	  h    H   p    I   t    J   x    M9       NN       O	      Q	      Y       [	      \	      ]	      ^	E      _
      `       b	         g    +J    	      	  G     	  J    	  J    	    
  G        4  '    
  	  <
  '    
  '    
  '        	  T
  h 4I
  '     T
  X    @   !
                                       	            
                                 !!  "    !      !
       !
   "    "F      "E       "       #!  X    @   $                              
i       0          %9   "    #      #       #
   4      G      "    &4      &6	        &7	      <  |  "    0'1      '3	|       '4	|      '6       '7       '8	|      '9	|       ':	|  ( jtm 8(,      (	        (
       (       (       (       (       (       (       (        (   (    (  0 |  <  G    '    ),  '    )   '    )   '    ),  '    )   '    )   H    *!  B@   ,H                                           	    
                                                                                             !    "    #    $    %    &    '    (    )    *    +    ,    -    .    /    0    1    2    3    4    5    6    7    8    9    :    ;    <    <    =    >    ?    @    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    {    |    }    ~                                                                                                                                                                                                                                                                                                                                                             '    -$|  '    -2   '    -7   '    -;       .U       .m       .   4      /  "    /*      /!    B@   /)                                               !    )    .    /    2    3    \    ^    b    g    l                    0    0         /{  C/  &    /
  &    /-  &    /=     -  G      =  G      M  G    "    /h      /	    4M  '    /h  '    /h  "    /      /       /      /      /   -     G    K    /,      /       /      /      /M      /   K    005      07        08       09       0:       0;F      0<      0=	|       0>  (   ,  "    n1      1       1 
       G   k B@   2,                                           	    
                                                         C2q  &    2s9  &    2t   "    2k      2m       2n      2o      2p      2u   "    ,2      2        29      29      29      29      29      29      29       29  $    29  ( "    2      2       2  4     G    9    G    "    2      29       29      29      29   "    2G      29       29   "    2o      2"       2"   /    "    
/      
1|       
2|      
3       
4    k    	
:      
<        
=       
?       
@       
B|      
C        
E|  (    
F|  0    
G|  8    
I|  @    
J|  H    
K|  P    
L!V  X    
O  `    
P  h    
Q  p    
R  x    
T'\      
V'b      
W'h      
X'h      
Y'       
Z'       
\'n      
]'t      
_|      
`|      
a|      
b|      
c|      
d       
e       
f      
g      
h       
i   L    
k'z   L    
m'G  (L    
n'  8L    
oE  	 "    0pV      r        s       uh       v      w      x       z       {        |   (       v          G    a     =G        
q  '    
s      
w    9                    E   M    
X    9                   $     E  M    
x7  =  RH   H      "    XO  Ybuf P=       Q  Yin R       G    -     G   ?     ]!N  B@   j                    ~        	                 	               	               	               	               	               	               	               	               	               	               	        9                     	              H  	            H  	            H  	               	            |  	               	               	              	              	              	          l  	          "  G          	            *  	          ^  G        N  	             G        t  	            N  	            t  	            G          	        M    >C      Q   	            L  	            L  	            @  	               	        J           	        l       E  	        m          	           9                  	           	       9   #!          9   9   #!         	@!  	         !  9   Z!       #!   	    
g!  F!  9   !   !   |   '      !  	        m!        	        	      	            	            #  	            #  	          *"  G        &%"  	        K     "                                  
  	        K    @
V#      
	        
	       
	       
	       
	       
	       
	       
	       
	        
  (    
  0    
  8 M    
"      
z#  	        V#      @   	               	               	              	            #  	            -  	              	              	        H    !                        x$  2cnt !   U                       $  2pid '   U    	            :            Y      O%  2buf '#!  U#in <O%          a           b           c           d              (    d               y'      d#y'          #ctx dH'              f@           p gy'          `                          w	&            }          q           `                          |	d&            }          q           
`               	&            }          q                    T0  
               &                                 
`               @'            }          q                   $  ^'  Uu T|          $  Uu T|   -   N  (    3               )  #ctx 3/'          #buf 3I)          #len 3W@           t 5          ;    (  p Cy'          S                 G?(  $  $  $   
                J	(                                          U| v "TTQ           $  U} Tv   
               S	*)                                          Uv Ts@Q@  
               \z)                                n                   $  Uu Tv   4   (    $        (       )  2ctx $-'  U 7    )  !buf (y'      6@   t                          5+      *5+              4               H;+              '              2           
v               *                                 *  Us          [  *  U| Ts          zq  +  U|          j  U| T~ Q}  $ &      o    k           	      9  #fp k,          p m          ch n
          n o	               p	           5               ,      
  }          U4Tw                             T,                      T0Q:  
               ,                      T0Q:                            ,                      Us T0Q:                            5-                      T0Q:                            -                      T0Q:                            -                      T0Q:                            .                      T0Q:                            i.                      T0Q:                            .                      T0Q:                            /                      T0Q:                            P/                      T0Q:                            /                      T0Q:                            !/                      T0Q:  
:               B3      :          :          N:      %3  :                                    0                      T0Q:                             0                      T0Q:  
#               2  5              B  }N          H                          M}1  e          Y                  '  Uv T0Q
                            S
1  4          '                  3  U1Ts Q}  ʊ                          g
T2                      ۊ                  @  Us T	        Q@          L  l2  Us            2  U           L  2  Us            U  T	        Qv            Y  2  U	                 Y  	3  U	                 Y  U	                  f  U	           
{               	5      {          Ռ                          3                      T0Q:  
z               	4  >          >       74                    r            "4  Ts            Us             ]4  U	        T
           4  Us T	                    
[               5      m                    4  Us T	                   5  Us T	                   ,5  Us T	                   Q5  Us T	                   v5  Us T	                   5  U	                           ʳ            Y  5  U	                 Y  U	           ;                          W6  %               ;          O";                 #;             Y                   2       x6  k          %        2       w  ~  }        ׳  6  U2T~Qw                      Y   7  U	                 9          Y  ,7  U	                 Y  K7  U	                 Y  j7  U	                 Y  7  U	                 Y  7  U	                 ;          Y  7  U	                 Y  7  U	                 <          yt          Y  ,8  U	                 Y  K8  U	                 G<          Y  w8  U	                 ;          Y  8  U	                 ;          Y  8  U	                 <          Y  8  U	                 Q;          Y  '9  U	                 Y  F9  U	                   ^9  Us          <          Y  9  U	                 Y  9  U	                 Q;          {X  9  Tv Q
|  $0.         MX                 ]   ":  !p ],  	    _
":     3:  =G        E   `:      E-  	    G	        %   :  !p %)      %2|      %=   	    '
:  len (	   end )|     :  =G            ;  i 	   pw !  )p     7    2;  env !  )del !    D                      T                   D                      (                   ;  *    $   U (                   ;  *    *   U (                   <  *    '   U (                   G<  *    &   U (                   v<  *    $   U (                   <  *    "   U (                   <  *       U (                   	=                                 
      H      -5+          fd            ret                                 ~    E  t;    =  	       	        5               
>  __d                      U|  $ &  5        8       5>      8!            
O               E  O          O          O              O  wP  yP  z%P  {2P  |?P  ~LP          YP          fP          sP          P          P          P  tP  tP  uP  vNP      <?  P  P   >P          	       p?  P                     >Q          T       ?  Q                    ?  U
                      
y                @  y              !y  
               9C@                                                           7@  Ä                                                 *  Uv T| Q@           T          7  @  U}          C  
A  UAT| Qt         7  "A  U}          C  GA  U?T| Qt         C  lA  U2T| Qt         C  A  U:T| Qt         C  A  U3T| Qt 3        A  U	                 O  A  U0                   KQ  B  U|          [  %B  UV 3        KB  T} Q0R0Xt                   C  |B  U:TtQ0           B  U  T	                   B  U          [W          V  B  Uu          7  B  Ut         h  C  UtTA         t  DC  U0TtQt                   L          t  C  U2TtQ            C  U	                             C  U	                   C  U	                             D  U	                   8D  U	                           t  iD  U2TtQ0                     3        D  U0T0Q	                   D  T0         L          C  D  UATtQ0         C  E  U?TtQ0         C  8E  U3TtQ0         C  \E  U2TtQ0         C  E  U:TtQ0           E  U	                 Q            U	           
?y               j"F  Qy          -?y               +Qy          +y          	         #       /y          +y                   #       y          y                  *  T	        Q8     ly                          9G  ~y          +y                          y          y                  *  T	        Q8           zq  QG  Us          O  hG  U0 3        G  U|Tv Q0R0X                    [W  G  U|            G  U| T0                   Q                      H  U	                 L            GH  Us?Ã  s          x  _H  Us            H  Us?Ã  s          qp  H  Us          O  H  U0                M                 M      M.5+              O4              P4              Q  }    RE  }    S           ret T               Vz#          Eact X  ~;    I  	    	   	    	    5               I  __d 	                      ;    1J                           #J  U
                    T          7  VJ  U|          C  J  UATv Q	                 7  J  U|          C  J  U?Tv Q	                 C  J  U2Tv Q	                 C  K  U:Tv Q	                 C  @K  U3Tv Q	         3        [K  U	                 O  rK  U0                   KQ  K  U}          [  K  UV 3        K  T| Q0R0X                    C  	L  UAT	        Q0         C  2L  U?T	        Q0         C  [L  U3T	        Q0         C  L  U2T	        Q0         C  L  U:T	        Q0           L  U  T	                   L  U          [W                      )M  U	                   HM  U	                   gM  U	                 V  M  Uu                 >           @       N      >+5+          5               N      C4                  O  U0          L                  p      O      *5+              	           
y                6GO  y              !y  @
               7N  Ä                               
               9O                                                   *  Us Tw Q@                                 3        O  U0T0Q	                   O  T0         L          Q                 :   Q      :@z#      ;95+  act =  	    =  	    =%  	    =/  	    >  	    >  	    ?  	    @   ret A   pid B   	    C4  	    D4  	    E  	    FE  	    H  	    I  FP  	    	   	    	    FQ  __d 	    )	         D    /           1       T    +               :            6      R      ,               	               	               	               	                                                 %R  U  T	                   <R  T9           dR  U  T	                   {R  T?           Z          R  U  T	                 R  Us T  :            +      T      3              A               
T  wi                    )       	S                      z                    Us T
 Q1R
 X	                    S  T0                   r            T  U  T	        RwX~ Y                      =T  Us          ˴  TT  U0           sT  U	                      T  =G    6                      U      |              	               	           `                          cU            }          q                    Us T} Q|           ش  U  U} T| Q3R!X	Y}                      U	          7    C:V      C!   	    E	   pid E   	    F
  	    G
  	    H  )	    T   	    V    (    .        Z       V      4              5           6              k       ,W  2pid 4   U                            +`                          !          }          q            :                   [W  *       U 6    
                  =X      
           fd 
               
   ~Elen 
F  ~    
=X  ~          X  UUT~Q~           /X  Us T6Q1R~X4              MX  G    (    
               {X  2fd 
   U 8    
   X      
$   !fp 
>      
F        
           l       Y      
*              
5               

=X  ~ret 
	           pfd 
	           Y  SY  UUTs          Z  qY  Us Tv             8    8
   Z      8
'      8
@  	    :

Z  p ;
|  	    <
|  res =
  	    =
,  	    >

   	    ?
	      Z  G        
           -      [      
6[              
G           ret 

	           fd 
	               
	   D    
	                     Z  T1Q0           Z  Us T2Q1           [  Us T1Q2RDX4           ?[  Us Tv Q}             ][  Us T|                    L          ,  [  Uv              8    	   [      	/5+      	B  !len 	L   F[  ch 	   )	    	         	                 ^      	05+              	C              	,              		               	           len 	           ;    \  ch 	           ;    \  ch 	           5        7       ]      	                     U|   
               	x]                                          TTQ~   
               	]                                          T} Qv             ]  Uv            U}       	                  t^  *    	25+  U-               	Ä                                    	           F       ^      	05+          #fn 	!          #arg 	,E          @        p_  QTRQ      t	           F       p_      t	)5+          #fn u	!          #arg u	,E          @        p_  QTRQ  6    a	           s       `      a	6h          #n b	           #fn b	(          #arg b	3E              d	#h          ret e		           q        X}       	                 b      	,5+          #fn 	!          #arg 	,E          i  		           len !		               "	|          ret #		               $		           ;    Zb      7	Z  }p 8	|              9	|              :	|              ;	               <	&t              <	-t          5        (       a  ch K	          %                   O	           Fa  __c O	            9    
̋               F	1b                      ݋           r        }U~ T}#X|  3        b  Uv 3$| "T	v 2$} "X|                           $      _d      /5+          #fn !          #arg ,E          i 	           len 	               |          ret 	               	               _d  ~5               c      |                             &t              -t                   E  d  Uw Q R	                 E  =d  Uw T|  $ &Q R	         3        Qd  Xv             A"  pd  =G                          d  2v1 '  U2v2 7  T     |                'f      (5+              ;              #h          	    #h  ['f      f  $Ff  $9f      Sf          ^f          Nkf      e  lf          wf          f          f          f          f          Uf      f          Uf      f                  9             R  U| Ts 3$ "           R  U|       q|  f      q-5+      q@  i s	   	    t|  )p   	    |  	    |  	       	    &t  	    -t  )ch   )	       )__c         8    <	-  g      </5+      <B  !len <O  	    >   	    ?  p @  	    A-  	    B-  ret C	   iov Dg  	    E     g  G                          h      $5+          ret 	           n 	           
                .ph  6          $)                          C  P          ]          q  Ts            h  h  Us            h  Us?Ã  s          ^   (            i       Ni  *    '5+  U    "\              	           -                Ä                                    	-                 j      +5+              5           #off Bj              N              "\          
               j  Ä                                       g  5j  Us          *  Rj  T~ Q8 Z        ^  yj  TTQQRR         ^     8    	-   k      (5+      ;  !len H  	    "\  	       p !  	    "-  	    #-  	    $-  	    %	        	-                l      .5+              ;|              H          len -                        
               	l            $                      Uv Q|   -o                	                                            ʊ                          l                      ۊ                  @  U~ Tv Qs                               l      n      -5+              :|              G              TH          len -              -              |              |              |          p |          
               	>n                                          #n  T Qs            T Qs   mo                          n  o          %               o  o                    U~            j  U T:Qs                  ]       mo      -5+          +mo                          o          %               o  o                    Us            o      .5+  	      len -       |          S       p  *    +5+  U    5           off 	                y           J       qp      y&5+                                                   (    n        Y       p      n%5+          -`               t          }          $q        K                  zq      K*5+                  h  -q  Us          g  Eq  Us            eq  Us?Ã  s          ^  Us       -                  r      -%5+                  h  q  Us          g  q  Us          qp  q  Us          ^                        Ft      %5+              =X  ~Elen F  ~       ~
?y               Ps  Qy          -?y               +Qy          +y                           /y          +y          	                 y          y                  *  T	        Q8             zq  hs  Us            s  T0           s  T| Q}            s  T0         x  s  Us            s  Uv ?Ã  s          qp  t  Us                      8t  T6Q1R~ X4                                  yt  *    (5+  U                       t  @        Ft  U	                               %w      (5+          #fd 2               	           
`               Tu            }          $q   
               
u                                            v  T
    Y                   '       
>v  k          %        '       w  ~  ~        ׳  /v  Uv T~Q~             
H               v  e          Y                  '  U	        T2          ʳ  v  U
             v  Us T
            v  Uv T1            w  U0           w  T0            (                   Sw  2cb ;*  U D                      T                                         x          E                            ۄ  w  U=T	                 ۄ  x  U:T	                   ;x  UIT1           Wx  U2T1         t  {x  U	        T0                     x  U	        T1           T	               A   y      A%5+  len C	   	    D	        4   /y  !fd 4)   	    6
/y     ?y  G        +   ^y  !fd +,    s               y  !fd 5        	   y  !fd 	7           y  !fd .   !pkt N\          *z      *5+      4   	    	   	    |  	    |          Wz      65+  	           D   z      D.5+  uid F	   gid G	   	    H  	    I  	    J#h  	    K#h  i L	        1   >{      1.5+      2|  !len 2       2+|      26   	    4  	    5>{   -   N{  G           {      '5+  !uid 3L  !gid >@      P  rv 	   pw !          {  	       6                      |      +5+          #uid 7L          #pw L!          ret 	               T  w3        o|  UQTs            |  U  T	        Q| Xs          }  |  Uv T	        Q0                   $}      ,5+  !uid 8L  )	      ret             r}      -5+      r}  	            }  	           }  G      }  =G   # 4}  6    {                        {,5+              {?              {R              }
":  _n ~	           
i                ~~                      $z            Uv T
 Q1R
 X	                                                r          f  ~  U| Tv          *  ~  U2            D    r                      J   [      J%  st LS  fd M	        )   z  rc +	             )uid                   -5+  	    	   i 	   )	    &t  	    -t    7    O      35+  i 	   F2  b   p |   )	    &t  	    -t    7    v      /5+  p b   7          )H  p |  b    6    t                 Y      t4h              tB           *    u!  Q    u#|              w#h              x               x                h     !fd h   	    j=X  len kF       R   ف      R<ف      SH      S+   	    U#h   h      >         >>\      >L  )b F    6    2           G             235+              2=           p 4|                  v  Tv       $   Ă      $+5+  !n $5   p &                05+      :   	    |          i  !fd        2i      <       G   ret 	   	    	   n 	          -    !fd '       2E  !len ?  ret -   7    у      35+            !fd    ret 	    6               U         #fd #               +           val 	                       Us T3Q0 @          UUT4  7    wф      wJ\      x&  !len x0    t    R:    A                     A               A2          Esa C  ~        C  W  Uv T0Qs          7  o  Us         C    Uv Ts Q0            :    8               υ  2sig 8!   U :    3                 2sig 3    U u       (            7                            .                     m  Us  @          U  T	        QURT  v                  v  w               xfmt '          PVbuf 
T  vyp |          z    	           Eap 
  u5                 Vtv E  uVtm   u{i               և                      z                    U| T
 Q1R
 X	          \i                   /       X                      z                    U| T
 Q1R
 X	                  õ  u  Us T0         ϵ  Us Tu  
                 +                                      ۵  T1Q} Ru  \i                   -                             z                    Us TdQ1R	X	        Yv 3$        "  
i                                       z                    Us TdQ1R	X	          
>               	[  [          O                    T1Q	        X|           r             W    
         
:5+      
D    .    |  ʊ      |         .    "-         "       "E      "%   .    k|  6      k      k      k   .    \|  `      \      \   .    >E        >E      >       >   .    'E  ̋      'E      '      '   .    E        G               .       8       
            18     .    d   i      d 
      d<  P .    A     ]__s A  ]__n A      A  P .    %|  Ռ      %      %  |sz '
   8    n         n   8    i         i   8    	   B      	       	B   S  .    )   s      )      )   P W    1         1    W    "m         "m    ,mo                   o          o          o          -o                                                            ʊ                                                ۊ                  @  U~ Tv Q|                ,          a       q  $Ã  Sу                  G  $  %                                  L  8  Us              +                           $Ã    ,                                       )          6          C          P          ]              Uv Q|             ,          O       t  
               O                       f  T0            ,Y          Y        Y          Y          Y  }Y          Y          Y  }Y  }Y          Y                                     G
g  )                                        U| Ts Q  
                N
	ʑ  )                                        UvT| Ql  
               
                      Us T0Q:  
`               
	T            }          q           
̋                
	                      ݋                  
  Uv   
6               \
  S          G                             )    U| T:         5  1  U| T	                 )  O  U} T]         A  z  U} T0Q}R}         N    U|          [    U}             ,U                  U          U  U  QU  QV  V  [U      Cה  $U      U  U          U          V          V          NV        V          +V                    U  T| Q           g    U	Tv Q3         V  Uu               ,f          l      E  f          g          g          g  ,g  9g  Dg  Qg  ^g  kg  xg  f                          <	  g          g          f          %               g  ,g          9g          Dg          Qg          ^g          kg  xg  
               e  6          )                                  C  P          ]                  q  Tw Q2R}    
               Z	  Ä                                       g    U~            U~?Ã  ~            *  7  U2T~            ,9          =        	:          :  п
`:               b	  :          }:          r:              :  _:          :          
               ,2                              s  Uw T
                             9	                      %               Ɍ                    Us T| Q
             ј  Tv Q0                                 
3:               g6  E:              R:          H                          G  e          Y                  '  Us T
AQ
                        Us            ڙ  Uv T2         L    Uv              U2T1         }  U0T	        Qs    9                           ]  	:          %                :          }  U0T	        QU              ,j                  j          j          j          j  j  j  j  j  k  Qk   
j               	  j          j          j              j          j          j          j          j          k          k  
               S	  $Ä                                                 ?	c                                          U TQv           g  {  Us          g  Us            ^   ,[                  [          [          [          }[      	[          $[  $[  >[                 ,  [           >[          3       g  [                    U|   -               	                                        Tv Qs     ,Y                 8  Y          Y          Y  Y  Y  Y  Y  QY   Y  @        t  UUTT  ,{X          !      #  X          X          X          -{X               
X          X          X                    ՞  U@T1                                       [    UU             ,x                  x          x          x  
o                O/                                              ʊ                                                 ۊ                  @  Us Tv Q|               
x               Ah  x              x          x          ߁                   1       V۠                      O                             o                    @       iš                                %        8                 ʊ                                                ۊ                  @  U} T| Qv               
y               n
  y          y              z          z  ~z                             A                                       %        A       ˁ  +                   5       R                              %        5       ˁ                  v  Tv  $ &33$                        A                                       %        A       ˁ  +                   5       R                              %        5       ˁ                  v  Tv  $ &33$     
               	w                                    O          D                              O                          	X  ]          %               j          
v                                                     
v               [                                      
v                                                     
v                                                     
v               6                                      
v                                                     
v               Ȧ                                      
v                                                     -v                                                     S                 	K  $  %                         >          #       )            &          +v                                     %                                      O2                 3          @          
v                                                     
v               ڨ  $                    
v                 $                    -v               $                       *z                   1       	ԩ  <z          %        1       Iz                  o    U T7           T0Q:               Qq R|            
  R|            2  U  T	                   Z  U  T	                   U  T	        Qs    Ă                    +       d            ւ          %        +                         v  U| Tv  $ &   
Wz               x  iz              vz          z          z          z          z          z          z          
z               j¬  z          {          	{          z          z              #{  ~0{  
               9E                                         )  ]  U~          '    U~ T| Q          '    U~ T~Q8         U%  U} T~    
N{               
2  {          z{          m{          `{              {          {          
|               M  $|  |          U}      }  ~}          $}                   !         6}          %        !               )  U T
Q	        R	        X
#   3        %  T| Q	R	Xv          }  U T	        Q0   ф                   -       ,	          Ƕ    U4Q0R0X0           U	                  Ӷ  ή  U|          {    U T| Q}          ߶              U1T~           5  U|          Ӷ  M  U|          ߶          ߶          }    U T	        Q0                   }  ȯ  U T	        Q0         Ӷ    Uv          }  
  U T	        Q0         }  U T	        Q0           L          d  d  U T	                 9              U  T	                   U  T	           `                          z	            }          q           
?y                 Qy          -?y          	     +Qy          +y                   &       /y          +y                   &       y          y                  *  T	        Q8                 U  T	                   ;  U  T	                   U  T	        Q
   Ă                   /       I޲            ւ          %        /                         v  T
                A         A                 3        4E                        	                *a        w        't        *        *        58        5@        5R                3                6        7%~                8        *        9D        *t        *n                        )K        *k                        *        *        *w        pA                         f        :9        6        6        6f                6p        6        *9        +S        ;        3        ;!        3[        %dup dup *        *        *        X        3        &D        )        ]        Z        <4A         A         ::         +O#        3        =t        0        0        >"        ?o                        36        3A                 *                @        'n        *        A        *        A  B   1B  (   1   :;9I8  4 1B   1  1  	4 :;9I  
1RBUXYW   :;9IB  4 :;9IB   :;9I   I   :;9I  4 :;9I  1RBXYW  . ?<n:;9  4 :;9I  4 :;9IB  I  4 1  U  .:;9'I    :;9I  ! I/  .?:;9'I@B  4 :;9I  4 1   :;9I8  . ?<n:;9    I  ! :;9I  ":;9  # :;9IB  $ 1  %  & :;9I  '4 :;9I?<  (.?:;9'@B  )  * :;9I  +1RBXYW  ,.1@B  -1RBUXYW  ..?:;9'I 4  /$ >  0(   1:;9  2 :;9I  3  4& I  5  6.:;9'I@B  7.:;9'   8.?:;9'I   9'I  :.:;9'@B  ;U  <7 I  =! I/  >1  ? 1B  @B1  A. ?<n:;  B>I:;9  C:;9  D. ?:;9'I@B  E4 :;9I  F  G5 I  H4 :;9I?<  I :;I8  J <  K:;9  L :;9I8  M :;9I  N1U  O1  P   Q4 1  R'  S1XYW  T. ?:;9'@B  U1U  V4 :;9I  W.:;9'I   X>I:;9  Y :;9I8  ZB1  [1UXYW  \1RBXYW  ] :;9I  ^%  _$ >  `   a:;9  b :;9I  c '  d&   e I  f:;  g :;9  h!   i(   j:;9  k:;9  l4 G:;9  m 'I  n B1  o.?:;9'I@B  p4 :;9I  q  rB  s. :;9'I   t. :;9'   u. :;9I   v.?:;9'@B  w :;9IB  x :;9IB  y4 :;9IB  z4 :;9IB  {1RBUXYW  |4 :;9I  }1UXYW  ~. ?<n  . ?<n:;9  6     dd      qd      	                                           T      )       T                                                                          u                P             P             P(             P             P      s       P             P      K       P[             P      "       R+             R             R      J       Q^             Q      5       Q5      <       v  <             Q             {               P             T             t                                                                            _             X      ~       X             X      [       Ti             T      2       TA             X             X      [       P[      a       Qx             T      4       T@             P             P      {       P{             t               X             R             r               t ;# $%!r "             p ;# $%!r "                                                                        u       ?       [g             R      S       Rb             R      H       RQ             R             R       {       R             T      K       Ti             Q             X%      v       Xv      z       r               T      i       T             T             Q             q               R                                                                      u.             Q      2       QH             Q      +       Q4             Q             Q      o       Q             Q      ;       QQ             X             P      i       R~             R             v        F       RF      W       {  _             R             z               Q                       K      $K       U$K      K       VK      K       U                         K      IK       TIK      K       SK      K       |hK      K       T                        K      .K       P.K      PK       QpK      uK       QuK      }K       ?p                        K      $K       Q$K      LK       UpK      }K       U                 3K      FK      	 q                  3K      FK       0                 3K      FK       U                 QK      pK       8                 QK      pK       0                 QK      pK       \                   pK      yK       7p yK      }K       Q                 pK      ~K       0                 pK      }K       U                 K      K       @                   K      K       UK      K       S                 K      K       V                 K      K       X                 K      K       0                   K      K       SK      K       |h                            J      lJ       UlJ      J       ]J      J       UJ      J       ]J      J       UJ      J       U                              J      0J       T0J      J       SJ      J       TJ      J       TJ      J       SJ      J       TJ      J       s@J      J       SJ      J       S                          J      J       QJ      J       ^J      J       QJ      J       QJ      J       ^J      J       ^                          7J      TJ       PWJ      ZJ       p ?ZJ      aJ       PaJ      tJ       \tJ      J       PJ      J       _                   lJ      J       UJ      J       | v "                  |J      J       _                      |J      J       SJ      J       TJ      J       T                    |J      J       UJ      J       | v "                 J      J       @                     J      J       SJ      J       TJ      J       s@                 J      J       }                   J      J      	 ~ J      J       Q                 J      J       \                 J      J       u                        `I      I       UI      I       \I      I       UI      I       \                    `I      I       TI      I       T                        `I      I       QI      I       VI      I       vxI      I       VI      I       V                        `I      I       RI      I       ^I      I       RI      I       ^                        `I      I       XI      I       ]I      I       XI      I       ]                dI      I       T                dI      I       U                                  P@      c@       Uc@      C       VC      rD       UrD      E       VE      .E       U.E      eE       VeE      lF       UlF      ;G       V;G      TI       U                                                            @      @       P@      @       P@      @       P@      A       PA      0A       S0A      CA       PVA      iA       P}A      A       PA      A       PA      A       PA      B       P$B      7B       PKB      ^B       PrB      B       PB      B       PB      B       PrD      D       SD      D       PD      E       PE      E       PE      E       SlF      F       P                    D      D       s p "1D      D       P                                     @      @       P@      @       PjA      pA       PA      A       PA      A       0A      A       PB      B       PD      D       PD      D       0.E      4E       P:E      QE       P                                           ~@      A       0A      !A       P$A      C       \rD      D       PD      D       \D      D       0D      D       \D      E       0E      E       \lF      F       \F      F       0F      H       \H      @I       \EI      TI       \                 @      @       P                 @      @       P                   A      A       PA      A       S                 5A      CA       P                 [A      iA       P                 A      A       P                 A      A       P                 B      B       P                 )B      7B       P                 PB      ^B       P                 wB      B       P                 B      B       P                 B      B       P                    F      G       P"G      ,G       P                      'C      QC       PE      #E       P H      QH       P                                   F      F       PG      !G       P;G      PG       PPG      TG       UTG      G       VH      H       VH      H       QH      H       VI      ;I       VEI      TI       V                 F      F       P                 G      !G       P                               DG      PG       PPG      TG       UTG      G       VH      H       VH      H       QH      H       VI      ;I       VEI      TI       V                              WG      pG       PpG      G       SH      H       SI      %I       S%I      6I       P6I      @I       SEI      TI       S                 DG      WG       0                     DG      PG       PPG      TG       UTG      WG       V                     `G      eG       }eG      pG       QpG      qG       }                   `G      pG       PpG      qG       S                 G      G       @                 G      G      
                          G      G       S                       ]C      tC       P{C      }C       0G      H       PH       H       P                 fC      tC       P                    H      H       PH      I       S                    <F      OF       PH      H       P                      C      D       PD      D       pD      KD       P                    0D      8D       Q8D      <D       qx<D      DD       Q                 F      F       2                    P?      W?       UW?      ^?       u                          `Y      Y       UY      [       S[      @[       U@[      d       Sd      Zd       U                               Z      [       \]      ^       \^      __       \_      2`       \`      a       \a      -b       \d      Ud       \                          Z      Z       P]      ]       Pp^      ^       P^      ^       Pa      a       P                               Z      [       ^]      ^       ^^      __       ^_      2`       ^`      a       ^a      -b       ^d      Ud       ^                                 aZ      dZ      	 |  $ &dZ      hZ       UhZ      [      	 |  $ &]      (^      	 |  $ &p^      ^      	 |  $ &^      __      	 |  $ &_      2`      	 |  $ &a      -b      	 |  $ &d      Ud      	 |  $ &                   (_      A_       :A_      __       P                             @[      ]       S^      ^       S__      _       S2`      `       Sa      Ba       Sa      a       S-b      d       S                               @[      ]       V^      ^       V__      _       V2`      `       Va      9a       Va      a       V-b      <b       VFb      c       Vc      c       Vc      d       V                          [`      _`       P_`      `       _a      a       _Fb      b       _d      d       _                                @[      ~\       0~\      ]       _^      ^       ___      _       _2`      L`       _L`      `       0a      9a       _a      a       0-b      <b       0Fb      c       0c      c       0c      d       0                         @[      ~\       0b]      x]       P__      g_       P-b      Fb       0c      c       0                      `      `       Pa      a       PFb      Jb       P                                     @[      ~\       0~\      \       ^\      \       P\      \       \\      ]       ^^      ^       \__      _       ^2`      `       ^a      9a       ^a      a       ^-b      <b       0Fb      c       ^c      c       0c      d       ^                	                      @[      ~\       0\      \       P\      ]       \^      ^       \__      _       \_      _       \2`      `       \a      9a       \a      a       \-b      <b       0Fb      Bc       \c      c       0c      d       \                   ]      ]       v  $ &]      ]       U                           __      p_       0p_      _       Q_      _       t_      _       t1_      _       |_      _       |~_      _       |_      _       |~_      _       |_      _       0                  c      c       V                 c      c       4                 c      c      
                          c      c                        c      c       @                 c      c       6                 c      c       \                 M^      `^       s                 M^      `^       s                 M^      `^       s                 M^      p^      
                          M^      `^       s                 a      a       s                 a      a      
                          a      a       s                    0;      t;       Ut;      H?       }                          p;      u<       0u<      <       ^<      <       P<      =       ]=      >       ]>      ,?       0,?      C?       ]                          p;      u<       0<      <       P<      =       ]=      >       ]>      ,?       0,?      C?       ]                             p;      u<       0u<      `=       }=      >       }>      >       T>      >       }>      ,?       0,?      ,?       },?      C?       0                                 p;      u<       0u<      @=       V@=      V=       PV=      =       V=      =       P=      >       V>      >       V>      ,?       0,?      0?       V>?      C?       0                   p;      `=       S=      :?       S                   <      <       s  $ &<      <       U                         =       >       0Z>      c>       0c>      {>       ^{>      >       ~>      >       ~~>      >       ~                      :      ;       U;      /;       S/;      0;       U                  ;      ;       P                          9      9       U9      :       S:      :       U:      :       S:      :       U                  9      S:       \                  :      :       S                 :      :       @                 :      :       6                 :      :       W                 :      :       4                 :      :      
                          :      :       H                                     4       U4                          U                   
       U
      $       $      6       U                                4       04             ^             ^
      $       ^$      6       0                       4             0      0       00      T       9r             0             ?
      $       0                                  4       04             _      \       _\      m       m             _
      $       _$      6       0                                    4       04      K       \K             V             \             V             \
      $       V$      6       0                                   S             S
      6       S                                   ]             ]
      6       ]                                         U             S             U             S             U             S                                   T      .       V.             T                              
                                        
                                  w             S                                       P      '       S'      W       v(d      r       Pr      x       S                                      
              
              p `#             p `# 
 <$      c       ~ `# 
 <$d      x       ~ `# 
 <$                                   
 vv"             P      c       ^d      x       ^                              \                              0                                P             S                  8      9       P                  8      :9       Q                                 P      +	       P                                   Q             Q	      +	       Q                 	      #	       0                 	      #	       0                 	      #	       P                    	      
       U
      s
       U                            
      )
       P)
      >
       S>
      k
       Pk
      n
       Sn
      r
       Pr
      s
       S                     7      L7       UL7      7       U                         7      H7       TH7      w7       Vw7      x7       Tx7      7       V                    M7      Z7       Px7      7       P                              5      5       U5      6       V6      ?6       U?6      6       V6      6       U6      6       V6      6       U                                5      6       T6      ?6       T?6      F6       TF6      6       \6      6       T6      6       T6      6       \6      6       T                      6      6       P6      6       P6      6       \                      T6      g6       Pg6      6       S6      6       U                   F6      6       ]6      6       n                    2      (3       U(3      4       \4      4       U                        2      23       T23      (4       V(4      04       T04      4       T                    2      23       Q23      4       ]4      4       Q                        63      Y3       PY3      c3       pc3      t3       Pt3      ~3       ^                      3      3       p3      3       P3      3       S                     3      4       P4      ,4       ,4      h4                           L3      p3       Qp3      ~3       R                    3      3       Q3      3       R                      3      
4       T
4      4       t p 4      4       T                 4      14       ^                     4      (4       V(4      04       T04      14       T                 4      04       |                    I4      R4       QR4      S4       V                   I4      R4       TR4      S4       ]                 I4      R4       |                   _(      l(       Pl(      v(       u                _(      v(       3                  _(      l(       ul(      v(       P                      '      '       U'      '       U'      '       U                        '      '       T'      '       Q'      '       T'      '       T                        '      '       Q'      '       R'      '       Q'      '       Q                      P'      '       U'      '       U'      '       U                        P'      '       T'      '       Q'      '       T'      '       T                        P'      '       Q'      '       R'      '       Q'      '       Q                        0       `        U`               S               S               U                        0       `        T`               ^               T               T                            0       `        Q`               V               Q               V               Q               Q                            0       `        R`               ]               R               ]               R               R                              D               \               ~ 1$~ "3$U"               T $ &33$U"               \               ~ 1$~ "3$U"               T $ &33$U"               \                    `       i        P{               P                              0%      %       U%      &       S&      &       }&      +'       U+'      9'       }9'      @'       U@'      E'       U                          0%      %       T%      &       _&      9'       }9'      @'       T@'      E'       }                        0%      %       Q%      9'       |9'      @'       Q@'      E'       |                  %      %       V%      %       v                     b%      %       0%      %       p 
9'      @'       0                   %      %       Q&      &       Q                    %      %       P&      &       P                           b%      %       0%      %       ^%      %       ~%      &       ^&      '       }+'      9'       }9'      @'       0                         c&      u&       }u&      &       ]&      &       }&      &       }&      &       ]+'      9'       }                    K&      &       _+'      9'       _                    c&      &       S+'      9'       S                           K&      X&       V_&      u&       Vu&      &       }&      &       t&      &       T&      &       }#+'      9'       V                    %      '       \+'      9'       \                      &      &       P&      '       }+'      9'       }                  &      &       V                    &      &       v 8$8&2$p "&      &       v 8$8&2$p "                c&      c&       5                c&      c&      
                         c&      c&       ^                             #      |$       U|$      $       U$      $       U$      %       U%      %       U%      $%       U                             #      w#       Tw#      $       S$      $       T$      %       S%      %       T%      $%       T                                 #      w#       Qw#      $       V$      $       Q$      %       V%      %       Q%      %       V%      %       Q%      $%       Q                          #      #       P#      #       p$      $       0$      $       0$      $       ^$      %       ^                      <#      w#       0#      #       r 
#      #       t 
%      %       0                          #      #       Q$      $       q$      !$       qpI$      Y$       RY$      m$       q%      %       qp                      $      $       P$      $       P$      %       P                             <#      w#       0w#      #       \#      #       |#      ,$       \,$      _$       |_$      $       \$      %       \%      %       \%      %       0                        $      !$       T3$      m$       T%      %       T%      %       q`                        $      !$       X>$      B$       RB$      $       X%      %       X                    #      $       P%      %       P                    #      $       Y%      %       Y                                         !       U!      7!       S7!      p!       w p!      {!       {!      !       U!      !       S!      *"       w *"      "       U"      "       w                          !       T                                  uF!      q!       S                    !      !       S!      !       s"      "       S                    "      "       P"      "       P                     {!      !       |I"      o"       |o"      "       P                      {!      !       VD"      "       V"      "       v"      "       V                    {!      !       _I"      "       _                   {!      !       }D"      d"       }                    {!      !       ]"      "       ]                    {!      !       ^"      "       ^                    o"      "       q 2$u ""      "       q 2$u "                     o"      "       v 8$8&2$u ""      "       v8$8&2$u ""      "       v 8$8&2$u "                            (      (       U(      =)       S=)      >)       U>)      Q)       UQ)      b)       Sb)      )       U                        (      )       0)       )       P!)      &)       	&)      <)       P>)      )       0                       (      (       u u @(      )       Q>)      Q)       u u @b)      |)       u u @                  (      )       P                      (      	)       s 	)      )       T)      )       s                   (      )       s                 (      )       P                       t               u               T               p                p #               p`#               tp#                                Q                                 P                                 4                                 T                                 2      D2       UD2      2       S2      2       ~~2      2       U2      2       S2      2       ~~2      2       U2      2       U                                 2      D2       TD2      2       V2      2       T2      2       T2      2       T2      2       V2      2       T2      2       T                                 2      D2       QD2      2       ]2      2       Q2      2       Q2      2       Q2      2       ]2      2       Q2      2       Q                                 2      D2       RD2      2       \2      2       R2      2       R2      2       R2      2       \2      2       R2      2       R                           2      )2       u)2      2       ^2      2       U#2      2       ^2      2       U#2      2       u                   U2      Z2       |Z2      u2       P                 U2      u2       4                 U2      u2       ^                        `             U      <        ]<       H        UH       b        ]b       k        U                     `             T      <        VH       b        V                        `             Q      5        SH       [        S[       ^        s p ^       b        S                                        P             }q  $ &             }} $ &             P             \H       b        P                                P             0      <        \H       b        \                                P             \                              V                          0        SH       H        S                          0        VH       H        V                          0        ^H       H        ^                                    PH       b        P                                S                                V                                ^                                Z       UZ             ^             U      H       ^H      \       U                                Q       TQ             ]             T      H       ]H      \       T                            Z       QZ      H       QH      \       Q                                Z       RZ             \             R      H       \H      \       R                   l             S      H       S                       ?      Z       SZ             _      H       _H      R       S                                 P      \                                           Q       TQ      Z       ]Z             V             U             V             V             U      H       VH      \       T                                   T             _             _                                 P             P                               S             S                               _             _                                 U             V             U                 (      4       ^                   (      3      	 p  $ &3      7      	 s  $ &                                         U             S             U             S             U             U                              S                              ss $ &                    0      y       Ty             T                      M      Y       QY      n      	 t 2$x "#4n      y       R                                   U      )       S)      *       U                                   U             P             U                                                            0                          /      /       U/      0       S0      	0       U	0      #0       S#0      )0       U                            .      /       U/      [/       S[/      \/       U\/      a/       Ua/      o/       So/      u/       U                              W      W       UW      X       SX      X       UX      Y       SY      Y       UY      PY       SPY      UY       U                 Y      #Y       s                 Y      #Y       s                 Y      #Y       s                 Y      0Y      
                          Y      #Y       s                                	       U	             S      "       U"      r       Sr             U                                  '       T'             V"      ]       V]      _       P_      r       Vr             T                  d      l       P                       3       
	                       3       0                3      }       @                3      }       S                   ?      L       PL      }       \                             V                 ]      d       2                 ]      d      
                           3      J       P                         ,      2,       U2,      h,       Vh,      k,       Uk,      ,       V                         ,      <,       T<,      j,       \j,      k,       Tk,      ,       \                     ,      G,       QG,      ,       Q                       -,      H,       0H,      L,       Pk,      ,       P,      ,       R                         +      :+       U:+      +       \+      +       U+      +       \                         +      :+       T:+      +       ^+      +       T+      +       ^                       +      :+       Q:+      V+       SV+      +       Q                  +      +       P+      +       p  $
  $-(                   q+      +      
                           q+      +       
                     
      
       U
      
       uh
             U                    
      
       T
             T                        
      q       Rq      w       Rw      y       Ry             R                    
      q       Zw             Z                           
      
       0
             [             p       *       X-      q       [q             0                                  
      
       0
      
       T
      
       t
             u|#-      4       T4      7       pD      W       T^      b       tb      q       u|#q             0                        0	      C	       UC	      n	       Sn	      p	       Up	      w	       S                      0	      G	       TG	      o	       Vo	      w	       T                      H	      _	       P_	      i	       s p	      u	       P                              	      	       U	      	       S	      	       U	      	       S	      	       U	      	       U	      	       S                            	      	       T	      	       V	      	       T	      	       V	      	       T	      	       V                      	      	       P	      	       P	      	       P                        0      _       U_             V             U             V                        0      7       T7             \             T             \                        @      J       UJ      r       Vr      v       Qv      w       U                        @      U       TU      c       Sc      v       Rv      w       T                              @             U             V      }       U}             V      .       U.             V             U                            @             T      |       ]|      }       T}      .       ].      5       T5             ]                                                v             \             S}             S             R.      :       v:             \             S             \             S                            	       P}             P             v                              
                                       
                               \                 c            
                          c             
                  c             \                   S      W       RW      X       u                   S      W       QW      X       ]                 S      W       s                  }            
                          }             d                 }             S                              
                                        d                                 U             S                       .      
                                 (       s                                          U             S             U             S      $       U$      *       U                                Q$      *       Q                                 P      )       P)      *       u t  $ &                                 P             \             \                                 T             V             V                               ^             ^                                   P             ]      $       P                              \                              V                              ^                  G      P       P                                       U             V      	       U	             V             U                                       T             _      	       T	             _             T                                       Q             \      	       Q	             \             Q                                         R             ^      	       R	      z       ^z             R             R                                         P             S	      %       P%      X       SX      d       Pd             S                                    R             ]	             ]             R                                     U             S             S      (       S                                     T             V             T      9       V                           4       }4             ]             }      *       \                          k             P             S      (       P(      Q       S      *       S                                  04             ^             0                      Q      T       PT      h       Ss             S                 '      <                        '      <       S                   '      ,       },      <       \                              l                              \                                U             v                 F      Q       S                 s             0                 s             0                   s             }             Q                                 |             Q                               |                               V                                                                 \                          d       Ud             U                                }             P             _             U             _      /       0/      L       PL      n       _             _             U                            d             S             P      n       S             S             P             S                            d                   n                                              P                                                P             Q             Q                               R                               X                            )      )       U)      *       ^*      *       U*      *       U*      *       U*      *       U                            )      )       T)      *       ~*      *       T*      *       ~*      *       T*      *       ~                              )      )       Q)      )       w )      *       Q*      *       Q*      *       Q*      *       Q*      *       Q                      )      )       Q)      )       w )      *       Q                    )      )       T)      *       ~                    )      )       U)      *       ^                  *      *       S                     )      *       ~*      `*       _`*      v*       v*      *       _                        &*      f*       Qf*      *       *      *       }x*      *       Q                 j*      *       ]                  *      *       P                   {*      *       P*      *       ]                 {*      *       2                 {*      *       w                  {*      *       ~                   {*      *       P*      *       ]                 {*      *       2                   D*      T*       qT*      j*       P                 D*      j*       6                 D*      j*       \                                      ,      -       U-      -       V-      T.       UT.      .       V.      .       Q.      .       U.      .       U.      .       V.      .       U.      .       V.      .       U                       ,      -       
 T.      q.       
 .      .       
 .      .       
 .      .       
                          ,      -       W-      -       ST.      q.       S.      .       S.      .       S.      .       S                           ,      -       U-      {-       V{-      -       ST.      q.       S.      .       U.      .       V.      .       S.      .       V                     ,      V-       0V-      h-       U.      .       0                    r-      -       P.      .       P                  -      -       
                   -      -       W                   {-      -       _-      -       \                 {-      -       S                 {-      -       
                    -      .       S*.      T.       S.      .       S                            -      -       P-      -       V*.      ;.       P;.      T.       V.      .       P.      .       V                 -      -       
A                 -      -       S                     q.      .       V.      .       Q.      .       U                            00      0       U0      1       S1      1       U1      1       S1      1       U1      1       S                                00      0       T0      1       1      1       T1      1       1      1       T1      1       1      1       T1      1                                     00      0       Q0      0       V0      1       Q1      1       Q1      1       V1      1       Q1      1       V                        0      0       V0      1       Q1      1       Q1      1       V                      0      1       1      1       1      1                             0      1       S1      1       S1      1       S                          0      0       ]0      1       T1      1       x 1      b1       Tn1      1       T1      1       T                    0      1       V1      1       V                       0      0       0      F1       ^F1      R1       rpR1      1       ^1      1       ^                     0      -1       _-1      51       x51      1       _1      1       _                        0      b1       Yq1      1       Y1      1       Y1      1       Y                    0      0       R1      1       R1      1       
 @                 0      0       4                 0      0       T                 1      1       V                 1      1                        1      1       _                              4      5       U5      %5       U%5      /5       U/5      5       \5      5       U5      5       \5      5       U                              4      5       T5      %5       T%5      F5       TF5      5       V5      5       T5      5       V5      5       T                          4      5       Q5      %5       Q%5      P5       QP5      5       Q5      5       Q                         5      5       S5      5       s5      5       }%5      5       S5      5       }5      5       S                         5      5       P5      5       s t "%5      75       P75      F5       s t "1F5      f5       v s "1                      K5      `5       T`5      b5       t p b5      f5       T                 q5      5       S                 q5      5       V                 q5      5       |                        7      7       U7      7       U7      7       U                       7      7       T7      7       T7      7       T                        7      7       U7      8       U8      8       U8      8       U                            7      7       T7      8       V8      8       T8      8       V8      8       T8      8       V                            7      7       Q7      8       ]8      8       Q8      8       ]8      8       Q8      8       ]                          7      7       Q7      8       ]8      8       Q8      8       ]8      8       ]                          7      7       T7      8       V8      8       T8      8       V8      8       V                      7      7       U7      ^8       \8      8       \                                K      	L       U	L      WL       _WL      L       UL      P       _P      $P       U$P      OW       _OW      TW       UTW      W       _                 L      L       P                   ,L      WL       \L      L       \                   ,L      WL       VL      L       V                   ,L      WL       SL      L       S                    =L      GL       PL      L       P                 ,L      =L       \                 ,L      =L       V                 ,L      =L       S                      L      P       _OP      OW       _TW      W       _                 qM      M       P                        L      P       SOP      DU       S\U      OW       STW      W       S                 L      L       1                 L      L       P                 L      L       Q                 8M      qM       V                 8M      qM       \                 .M      qM       ]                    NM      XM       PqM      M       P                 8M      NM       V                 8M      NM       \                 8M      NM       ]                      M      P       SOP      ,R       S\U      U       SV      0V       SW      /W       S                      M      P       _OP      ,R       _\U      U       _V      0V       _W      /W       _                    M      M      
 p1OP      Q      
 p1                       M      P       \OP      ,R       \\U      U       \V      0V       \W      /W       \                 M      N       V                 M      N                        M      N                        M      N       V                 M      N                        M      N                        M      N       P                 N      ON       V                 N      ON                        N      ON                        !N      ON       V                 !N      ON                        !N      ON                        8N      ON       P                             yO      O       _R      iR       _R      DU       _\U      V       _5V      V       _4W      OW       _TW      W       _                     yO      O       #R      ,R       #\U      hU       #                   yO      {O       0{O      O       PO      O       p                  O      O       P                  O      O       R                 OP      Q       _                 OP      Q       P                OP      kP       p                 OP      Q       p                 SP      kP       Q                kP      yP       p                 kP      Q       p                 oP      yP       Q                 yP      P       p                 yP      Q       p                  }P      P       QP      P       p                 P      P       p                 P      Q       p                	 P      P       p                 P      P       p                 P      Q       p                	 P      P       p                 P      P       p                 P      Q       p                 P      P       QP      P       p                 P      P       p                  P      Q       p                 	 P      P       p!                 P      P       p$                 P      Q       p$                	 P      P       p%                 P      P       p(                 P      Q       p(                 P      P       QP      P       p)                  Q      EQ       PEQ      IQ       p                 "Q      'Q       p 1$q "                 "Q      .Q       p 1$q "                 3Q      EQ       Q                3Q      EQ       Q                 6Q      EQ       R                    iQ      Q       PQ      Q       ppQ      R       P                  pQ      R       Q                   Q      Q       PQ      Q       pp                   Q      Q       PQ      R       pp                  Q      Q       R                  Q      Q       R                  Q      Q       R                  Q      Q       R                 \U      U       _                  iU      U       P                 vR      R       V                 vR      R       _                 R      R       P                         R      U       _U      V       _5V      V       _4W      OW       _TW      W       _                        R      DS       \DS      GS       PGS      S       w S       T       \U      U       \U      U       0U      U       \                       R      KS       ]KS      S       PS      S       ~S       T       ]U      U       ]                  T      U       P                         R      U       0U      V       05V      V       04W      OW       0TW      W       0                    R      S       ZS      S       zhU      U       zhU      U       0                   S      S       ZU      U       Z                      R      R       pR      S       XU      U       X                _S      S       _                 _S      S       z|                   _S      S       RS      S       ~                  _S      S       z                      _S      S       zS      S       \S      S       }p                S      S       @                S      S      
                         S      S       ]                        T      T       0U      V       05V      V       0V      V       04W      JW       0TW      W       0W      W       0                    T      T       ~U      U       P                    8V      XV       \V      V       V                         T      T       _U      V       _5V      V       _V      V       _4W      JW       _TW      W       _W      W       _                                            ^T      pT       PyT      T       PT      T       PT      T       PU      U       PU      V       VAV      XV       PiV      V       PV      V       PV      V       PV      V       VV      V       P4W      IW       PW      W       PW      W       V                                  T      2T       P2T      T       ]U      U       P5V      @V       P@V      XV       ]XV      zV       0V      V       ]V      V       ]V      V       PTW      W       ]                         T      T       _U      U       _XV      zV       _V      V       _TW      W       _                      T      3T       	3T      ;T       PTW      gW       P                hW      W       _                 U      U       H                 U      U       0                 U      U      
                          U      4U                        U      4U                        U      4U                        U      DU      
                          U      4U                       P      JP       
                    P      $P       U$P      JP       _                 .P      JP       P                ,                     d                                                                                                                                                                                      9      >      A      C      F      Q                      x      x      |                                                                                                               *                            )      S      X                                                                                            0                      5      :                                                          @      n                                  O      h                                                    "      '      3                      "      '      3      T      Y      }                      O      [      ]      d                            R      V      ]                                                                                                                                                                                                                 0       P       P                              0       P       P                                                                                 {!      !      !       "      "      "                      {!      !      "      "                      `"      h"      p"      "      "      "                      `"      h"      "      "                      %      '      0'      9'                      .&      5&      B&      G&      c&      c&                      _(      e(      l(      v(                      (      (      (      )      	)      )                      )      *      *      *      `*      f*      {*      *                      D*      D*      I*      Q*                      ;+      >+      c+      n+      q+      +                      ,      ,      ,      -      X.      x.      .      .      .      .                      ,      ,       -      -                      -      .      0.      X.      .      .                      0      1      1      1      1      1                      0      0      0      0                      U2      U2      `2      j2                      D3      c3      k3      ~3                      3      3      3      3                      4      %4      ,4      14                      64      <4      I4      S4                       5      5      +5      5      5      5                      q5      w5      {5      5                      7      7      7      8      8      8      8      8      8      8                      s:      }:      :      :                      s:      }:      :      :      :      :                      :      :      :      :                      O<      T<      <      <      <      <                      =       >      `>      >                      @      @      @      @                      B      QC       E      0E      F       H       H      XH      H      H      I      ;I      EI      TI                      F      G      H      H      I      ;I      EI      TI                      DG      G      H      H      I      ;I      EI      TI                      QC      C      hE      pF       H       H      XH      H      H      I                      hE      E      XH      H      H      I                      E      pF      H      H                      dI      dI      xI      I                      _J      J      J      J                      |J      |J      J      J      J      J                      J      J      J      J                      J      J      J      J      J      J                      pK      pK      uK      wK      yK      ~K                      K      K      K      K                      K      K      K      K                      ,L      WL      L      L                      0L      WL      L      L                      WL      \L      L       P      OP      iS      iS      U      U      U      U      OW      TW      W                      M      P      OP      ,R      \U      U      V      5V      W      4W                      yO      yO      O      O                      OP      \P      aP      dP      hP      kP                      \P      aP      dP      hP      kP      rP      vP      yP                      rP      vP      yP      P      P      P      P      P                      P      P      P      P      P      P      P      P                      P      P      P      P      P      P      P      P                      P      P      P      P      P      P      P      P      P      P                      P      P      P      P      P      P      P      P                      P      P      P      P      P      P      P      P                      P      P      P      P      P      Q                      Q      Q      Q      Q      Q      Q                      Q      Q      Q      Q      Q      Q                      Q      Q      Q      Q      Q      Q                      Q      Q      Q      Q                      R      iS      iS      U      U      V      5V      V      4W      @W      EW      OW      TW      `W      cW      W                      US      eS      iS      iS      iS      S      S      S                      US      _S      _S      eS      iS      iS      iS      S      S      S                      iS      qS      S      S      S      S                       T      T      U      V      8V      V      4W      @W      EW      OW      TW      `W      cW      W                       T      T      T      T      U      U      U      V      8V      V      4W      @W      EW      OW      TW      `W      cW      W                       T      ;T      U      U      TW      `W      cW      W                       T      ;T      TW      `W      cW      W                      U      U      U      U      U      DU                      Y      Y      Y      Y      Y      0Y                      Y      Y      Z       Z      UZ      aZ                      Z      Z      @[      ]      ^       _      `_      `      8`      `      a      Ha      a      a      0b      <b      Fb      c      c      d                      Z\      _\      ]      	]      ]      ]                      :c      Bc      c      c                      :c      Bc      c      c                      M^      M^      M^      M^      M^      p^                      R           /usr/include/bits /usr/include /usr/include/sys /usr/lib/gcc/x86_64-redhat-linux/8/include /usr/include/bits/types /usr/include/netinet /usr/include/arpa  lsapilib.c    string_fortified.h   unistd.h   byteswap.h   stdlib.h   stdio2.h   fcntl2.h   stdlib.h   stat.h   lsapilib.h    types.h   stddef.h   fcntl.h   struct_timespec.h   stat.h   time_t.h   __sigset_t.h   sigset_t.h   __sigval_t.h   siginfo_t.h   signal.h   sigaction.h   types.h   stdint-intn.h   struct_timeval.h   select.h   stdarg.h   <built-in>    struct_FILE.h   FILE.h   stdio.h   sys_errlist.h   resource.h   struct_iovec.h   socket.h   socket_type.h   sockaddr.h   time.h   pwd.h   struct_tm.h   time.h   unistd.h   ctype.h   confname.h   getopt_core.h   stdint-uintn.h   in.h   netdb.h   un.h   lsapidef.h    string.h   resource.h   dlfcn.h   socket.h   errno.h   select2.h   sched.h   mman.h   sendfile.h   uio.h   strings.h   inet.h   wait.h   prctl.h   grp.h     	        KK.K5J/I#KK1
0	z
zJ	Z	"OJJ= ...v <KgfJ.T2KxJ.n=@<YDw<<=:/;<;/u;=IK=H</փ-K-=>:X-=;=0:/;=I<//sf=H</[G-K-=18=;=0:X;=-/I=;/?Gf-K-=I<-=;=-/e=-/t0//-</-</-</-<///-<///-J=t=Y-</ȑ-</J>Xtu-=ttu;/K-=-/X-/t;/gK-=Y-=;=J;=/K-=-/X;/u-=ttu-=K;</f;=;/fu-=t.V>,>t;=/.K-=-/t-=-//-/-X.I</t.W=-/0,0,<.W=-/t/t;=;/<t.W=-/0:0:<.W=/.:==:</=;J=uI=-=.Yx =5 x./yJ.K0+=0+/.Z1Mz.?/=:===`[+/{.	r		KZ.4tKK
	Z		J
sJX/t OJg8j
 n!;K;KJYZC%t!K%K:K%K/X X~!-/-!WgY	LXf  	ztZ@F2yt</
	
X/	ZJv 0X 	        n	<JK
	<<x			=	=#	=E	K#>H	>#	K#	=
l	Z<<	h	u$I$K="IY<IJ	=$J$<=;"<J	=vXF.LL=/d f.Lu/O7@p$tik<=<><V=
Wuki
I)HKI,IKI,<K*Iu*u,1K,uY	r u	;YvVvVM,U	i+h]q<.qJXq<3 q3Jv<v	|
	fX.X	< X	vJ		Yh x`uth.s		uXX.X	
	su	YyJ	t	Yt'X
	w
			/J
iX<%<`t=XI/7L*J<_C=&<KX._<t
eX$.~	"fN	f	KtxX	`x t.eX/g.J.X	
I
Jwl
XV	Y	K	Y	?U	Lj k<Lt	
lX	Kl
	 .	Z	K		>V	La$f	mX	Xm<	.>m<XN1+	pk"
kJJ
k.XX"~K
k		[X	O(kX
	<
kX	b>=E<>:<Y<;=vk<qR<!l

l< lz/	fX<	Kffkv
~*~
X$	rJ~
#.?f	h
~~<
.<1	~)	<
~t)X
~<<t	
~XX	~
/.<<zf~
~X.
~t.J<<X< 
W=ڬq		K	ffL4z>=jtt				Z-JJXft
XL!sgf
fF
JY	Y
:"foXXXJlt0
hd/	L.XN6g	J	yi<
X$		Z4tKK
	;:|".<ZIY6t(f+K"JMX"X<mJ<	&
AJ X0J
XXXV$J)I!4f<9 X!Jh.$r.XX`KJJt5<uY"Jq<%3$x.`X YB W[$g		F	x	\	*2.	F^	\t;:j KK-uYIX 	        Ki+ JJK2KKu\/
u
 u
(tX
|
x(9?JL6J9xX<u1tu6,XJK,@g
L,K /sJK u
XQyXKEW	\	gx.	<	%	/s	uZ	ptt	/t.X	o tK
!fJ/	kt	Zs	gY	Z	Y	g	Y#!xwJ KxJKK!JK
sJ
s< !KJ9J!JK!s
fK =J	YYt	YYt	YYJ	YY<xK	t<YL	,<W	ue	[A<v v.K Xe#!CJ;CgK	EdX` x DNK$JGMY  <, "g
< 		=	&>	t	uX	Y
r<f	Kr
<
r<X		v	v[L	qXr

r<X	ltXrl.<	v
hK1<
z'K , M;!?qL	/	Z(>
rJ<J(
r<<<	r
X		u	=
>	huJL	|
	fX.X
]u	u<
Z==
y<kJK,&J"Irt&s=r<!rff	"yJD!IK	L%;	K%H	K	KKK.7
.XB#I1u#J
Q	
F	ZKNJ U	X
hJ.$.Xhr	/XL*~Jf-S.	LKI	u	YZ.HJKY)%fX80JJ)X%<XX$%4HJL<0YBL=;B=Vv< )/Mt	z0<6u 	zt/L4K"vI4H="@"F%#K%WYzQ* u  Jf		uJ	KmJJ.I
<vJuMF=0Ju)Y%#K,K"9=&=X	YsJY	FX : J J	Z	LN*<xX<JX>tJ	e
<	7/tL4KxH4=K* v  JfJ		uJ	Y.W
mJt
mXKtKm\x JYKW i    X  <  J JzNS=;0WXY)?KLeJf<Ki*_8tK)^	~tf<_Kz.`	ztf<	XK  JZfv*=gJ	ZAK=%,	=%H	KM,tY,Lho!(fot(=-Kl X|K<x <	o.K	MsfsftJt		Z	93JJM  _< .	jy	93JJ	Kw ' K"  f/ 	s	XMXXmXL

f		yrrX'=PYr<f'	Kz<		Yr	.Z
j
fX	]XX$XZ&v/8
yX<t
yy<
	;	Y3 4   JJ	/<0/Y;K;=R.	z XZw /J8fC
b<	hb
X	<	=	K<Xha
	X+^aX^	t	Y=-Xu	g+uJit#	YE<7	]X	gv.X	g.XmLZfF&	t0N)Jx)8=)HuK	Z/ XpytKh/a<'	t0Q)Jx)8=)HuKY	/ lm.ttKw	"g;L	p<>J:h6tYGu	uf>=
.
f		K	^tj!tJ<		jF	%	=%H	KZ7)KLK)8K!K	2%o	=K%:	K2	GK_X#<
]<
<&	YZX[f<Ȃ	_Xy	q
		KK& ,N>:hZs"	[sf	"Ui	XigY ..-	sX ... K fh00<=
	h+<	Yu<
		YJz
.	L+<	g/.
	L	gJ	JK*X.X	v6=	Y;	u/Xl
f?
lJXY
lf"Kl
"K8G8=P.4XK%  		
J.Jp<J*<X	v6=	Y;.	/Xl
f
lJXY"=8G8=I/..c<<jBz<	sX&`"
f
[Z	M	LY0	U==YK^f	4I	gYK  $/fY	L	y^/K-%]	K+/X>0XX<uj	YvXgYIgZ$Hv&L<X(.=	/.u.Z.fJOwX(WuO=.ft"<*w <K	t	Y /?N&tuKK
	h	g
G]	t	Y	t	YtM   t	YIgYJvYYg	r	Y
>v	t	YK ,	<Y	._ho<x
}<Ju


ZL
Xw	vY-)Xf\Ks =K	v.	Y+J	K'Ju<$RxtXp/Zu:Y	<u:Y	<	 - ;	-;	-;bX)	 <]X&ZX
_	##tY		Z.X<L		y}	Af<X1d		9	+Y	X)////0A1t[J	.<%<;   < 3 
l
z<)>KYWJtbXK X	9	
ft"u;	<u	WY	rXu	WY X"0", XXLXJ<f?JfjK
t	Y*=K	t	,=K	t	0=K	t	.=K
t	Y,=KgjKK2K	zt/	Y	Z		c			Zc	
cf		Zc
<<		a,<		Zci		Zc	x				Zc	w
X		c			Yc	v	Yc	v	Zc	w	Yc	vZ	[	Zc g		Yb
	f}r			g	{
	g1J}	
<1-u-).K.X
UJ.<	Z.)JKIKXx<X/-X</ift 		<<JJ<X_!	hX~<u	 	uX	f~<uYuY	Yvt=			XJeu\TKEW	~	ZdK	h	ZdK	h	hyX.	}
Xy
.t	tZg2u4w
ifX	ho.Jt.	 u	f	=^uL23fK& 	 mYX	fXK
a
a<Z,g<=<IXJ^J...	*Kz}>K+zz< O=>;g<0:><	Y62
_< <	Z		\_< 
_X< 
_<X	 K		0f	/_
 
_JX	 B		9X
J_ 
_<f XX
_JX K		.wJ]7A<@.=
J?w	Z_
.	 		 <<[_
	 _	 
_X	 .
_.X	 McMY	 _
!JJ_fJ _
  ..i/Zl	h+JJxJL	|
	fX.X	,X	x4	Ltot$ry5	h	K)MU	=)	= <Jf

t	T.TJ=..7<x<	|
	fX.	Z	t
Q~%#<=u7<{z+h	s	ut0<{z+h	s	ut

t	K	K	K	K#/K;?;;*x/Su$	*zJ/:<v3O/xJuBJ=su;uIu<<Y{	{t/JL5KK-)EJ
fJ		uJ	K"<K<#K<LyJ.J	/	;YtXyJ		K		uX{oK
M=
K=	nK
=
K=
mK
=
K=
Ku:
Ku:
NXl
Xk
Xj
=
K=
Ku:
Ku:
NXi
Xh
Xg
=
=
XtX	{t/<ZtWX=
MU=
=*JftJ		uJ	=M=
2J
NJK
H=K
K
N<+LK
K
H=K
K
N<,KK
K
H=K
K
N<-JK
K
H=K
K
<.z)JudPw	j	u	`yf		K	K	uX}	rtu	u=t	h(t	<!J&;HK%J*;(IgY<RL4fNJw

wfwYK
#&K	]X:
~
Zr>	@	/	 
J			

f :v	ZYw	Yu
	
Zv

.X	 t 	tXI//			u
~ft
Zr>	ZJ	z		X/X<
zX
	tX	/`ggWK>X	u	~X~	}XYX|X|<Y^	X	 ./
XR	XUJ
Y	h.eX>	tYvtYK		M
U-/](tq $~Zv
<Qyt/Z
t	
t	Z*(t
N	bXJ|<	y! #J<X=K	tZ2K'eK,tX~+|ZsW	u:Y		/	/	/+X	 <\.X
	#tY		Z.X<		y}	AfJX?		9	+Y	X ?%  t'YJ" =tYwtYLLmZv
<tYKtttYvt)X|.K6 2 X!s Y!Y+! t!Y+K f|tY1+IKvvWJgWJ~J	.<%<;[(Jt" 	|	=vV>YZ+KZ)=1K-M< <Yv.u.}JtZY<
gJf" < 		/np
<}2NX)		
~	|X}Y"Xg![qg!p'Y>tYK&CXK%.ZY&i
fYp<x u


Zv
X w	~9}5Xlt.Z7j.+"<g7/W5K/IMu_Kg\K _SC_THREAD_SPORADIC_SERVER pthread_atfork_func total LSAPI_Set_Max_Process_Time lsapi_parent_dead __fxstat parseContentLenFromHeader ugidLen _SC_2_SW_DEV m_pScriptFile LSAPI_Stop si_addr_lsb _unused2 _SC_TIMERS m_iReqCounter _fileno _SC_SHELL _SC_MEMORY_PROTECTION _SC_SCHAR_MAX __path tm_sec H_AUTHORIZATION _SC_THREAD_SAFE_FUNCTIONS _SC_UCHAR_MAX max_len freeaddrinfo gid_t verifyHeader _SC_C_LANG_SUPPORT m_pIovecEnd strcpy __uint8_t IPPROTO_TP pw_uid waitpid HTTP_HEADER_LEN _SC_TTY_NAME_MAX _SC_PASS_MAX LSAPI_ErrResponse_r si_uid m_bytes _SC_2_PBS_TRACK fp_lve_destroy m_pHeader _IO_buf_end __RLIM_NLIMITS _SC_SELECT _shortbuf rlimit sockaddr_in sa_family_t SOCK_DCCP _SC_BC_STRING_MAX _ISpunct is_enough_free_mem inet_addr _SC_TRACE_INHERIT init_lve_ex newSize m_tmStart liblve setgroups _SC_SEMAPHORES _SC_EQUIV_CLASS_MAX read __environ _sigpoll sa_data uint16_t __builtin_memmove ai_protocol _value m_pChildrenStatusCur IPPROTO_UDP overflow_arg_area time_t sin_zero _SC_DEVICE_SPECIFIC in_port_t _flags achMD5 _SC_THREAD_THREADS_MAX error_msg _SC_LEVEL3_CACHE_SIZE _SC_TRACE reg_save_area calloc _arch m_respPktHeader g_running __off_t _addr_bnd lsapi_cleanup achHeaderName st_size _SC_THREAD_PROCESS_SHARED allocateBuf _SC_JOB_CONTROL getppid tm_isdst swapIntEndian lsapi_check_child_status signal _lock s_max_idle_secs lsapi_set_nblock environ s_schedule_notify setUID_LVE _SC_NL_NMAX __RLIMIT_NPROC /builddir/build/BUILD/opt/alt/ruby30/share/gems/gems/ruby-lsapi-5.6/ext/lsapi RLIMIT_DATA pServer atol uint32_t initgroups _SC_POLL m_pHttpHeader _SC_V6_ILP32_OFF32 _SC_TRACE_SYS_MAX m_pScriptName __builtin_va_list st_blksize RLIMIT_NOFILE m_pEnvList _SC_BASE _sigchld LSAPI_Set_Max_Idle_Children int32_t _SC_LONG_BIT fixEndian LSAPI_GetEnv_r _upper __fmt sa_family m_specialEnvListSize pw_passwd _SC_CLOCK_SELECTION mask lsapi_resp_info sigaction __RLIMIT_RTTIME _SC_V7_LPBIG_OFFBIG bodyLeft fcntl lastTime _SC_AIO_LISTIO_MAX LSAPI_Init_Prefork_Server pErr1 pErr2 st_gid m_cntHeaders s_notify_scheduled m_envListSize accepting gettimeofday pBuf ai_addr m_iAvoidFork s_secret _timer lsapi_MD5Context __syscall_slong_t __builtin_memset _SC_FILE_SYSTEM sa_restorer m_pChildrenStatusEnd _IO_write_end type _SC_SCHAR_MIN _SC_LINE_MAX LSAPI_SetRespStatus_r lsapi_MD5_CTX __res st_nlink s_addr _SC_TZNAME_MAX __va_list_tag _syscall st_ctim nameLen __builtin___snprintf_chk LSAPI_Postfork_Child _SC_2_VERSION free _SC_2_PBS_CHECKPOINT IPPROTO_MPLS __sigset_t m_requestMethodOff m_tmWaitBegin readSecret readReq __tzname atoi g_inited getaddrinfo valLen s_ack lsapi_jailLVE __d0 _SC_LEVEL4_CACHE_ASSOC lsapi_MD5Final _SC_NL_LANGMAX doAddrInfo __stack_chk_fail memcpy _kill curSize RLIMIT_STACK IPPROTO_IPIP dlopen backlog sin_family _SC_LEVEL1_ICACHE_ASSOC pIov rlim_max m_iKillSent m_fdListen _SC_AIO_PRIO_DELTA_MAX validateHeaders st_atim m_status m_reqBodyLen sig_num optarg SOCK_RAW snprintf old_int _SC_2_C_BIND s_enable_lve __clock_t parseRequest IPPROTO_RAW strdup bufLen _SC_PRIORITY_SCHEDULING _SC_SS_REPL_MAX sys_errlist sival_ptr pStderrLog setpgid __uid_t daylight si_stime optopt LSAPI_ReqBodyGetChar_r pKey sun_family __uint16_t _SC_FSYNC sin_port getpeername LSAPI_is_suEXEC_Daemon LSAPI_Is_Listen_r LSAPI_End_Response_r _SC_FILE_ATTRIBUTES setreuid serverAddr _SC_NZERO m_pQueryString __gnuc_va_list _SC_2_C_DEV _chain pContentLen _call_addr EnvForeach newfd m_iServerMaxIdle SOCK_NONBLOCK usleep SOCK_RDM _SC_SYMLOOP_MAX sockaddr_un _ISblank unsigned char IPPROTO_MAX _SC_MQ_OPEN_MAX SOCK_DGRAM m_tmReqBegin __fd_mask __blkcnt_t lsapi_enterLVE __builtin_calloc _IO_lock_t LSAPI_Is_Listen IPPROTO_COMP LSAPI_key_value_pair lsapi_check_path LSAPI_ForeachHeader_r pHeaderName _SC_SEM_NSEMS_MAX _SC_USHRT_MAX LSAPI_FinalizeRespHeaders_r __read_alias __fdelt_chk shouldFixEndian pBody _SC_STREAM_MAX _SC_ASYNCHRONOUS_IO serverMaxIdle __open_alias _SC_READER_WRITER_LOCKS _SC_CPUTIME __getcwd_alias _SC_2_PBS_LOCATE _SC_DEVICE_IO sa_flags pVec geteuid _SC_SIGNALS __ctype_b_loc _SC_V7_ILP32_OFFBIG status off_t child_status s_notified_pid s_max_reqs H_X_FORWARDED_FOR s_pid_dump_debug_info _ISalpha __fprintf_chk tm_zone __mode_t m_queryStringOff _SC_V7_LP64_OFF64 _SC_NPROCESSORS_CONF __RLIMIT_SIGPENDING fdIn lsapi_changeUGid tv_usec _SC_XOPEN_XCU_VERSION old_child old_term LSAPI_sendfile_r lsapi_lve_error accept _SC_MEMLOCK allocateRespHeaderBuf _ISprint sched_yield pMessage s_liblve pValue H_CONTENT_LENGTH m_tmLastCheckPoint __vfprintf_chk _ISalnum _SC_SEM_VALUE_MAX s_req_processed strtoll open _SC_XOPEN_XPG2 _SC_XOPEN_XPG3 _SC_XOPEN_XPG4 LSAPI_STATE_CONNECTED _IO_write_ptr _SC_REALTIME_SIGNALS system lsapi_packet_header IPPROTO_ENCAP _ISspace lsapi_suexec_auth getLF g_prefork_server va_list __suseconds_t reqs exit LSAPI_CreateListenSock2 __rlim_t s_ignore_pid __RLIMIT_MEMLOCK pCur pHeaderValue __size size s_slow_req_msecs lsapi_init_children_status getuid FILE H_COOKIE LSAPI_ParseSockAddr dlsym pthread_lib _SC_PII_INTERNET_DGRAM _SC_SINGLE_PROCESS byteReverse dump_debug_info LSAPI_Accept_Before_Fork _SC_SHRT_MAX _ISxdigit _SC_RAW_SOCKETS fp_lve_enter LSAPI_AppendRespHeader_r size_t H_CONNECTION LSAPI_GetHeader_r _SC_MULTI_PROCESS s_stderr_log_path m_state fp_lve_instance_init _SC_BC_BASE_MAX H_CONTENT_TYPE LSAPI_STATE_ACCEPTING _SC_RTSIG_MAX _SC_NETWORKING achCmd H_ACCEPT _SC_GETGR_R_SIZE_MAX perror compareValueLocation _SC_THREAD_ATTR_STACKADDR _SC_LEVEL2_CACHE_ASSOC _SC_IOV_MAX _SC_TRACE_EVENT_NAME_MAX _SC_PII_INTERNET IPPROTO_IGMP pServerAddr lsapi_accept lsapi_initLVE _IO_save_base LSAPI_Release_r iovec old_usr1 maxIdleChld socklen_t m_iMaxChildren _SC_2_UPE ai_canonname IPPROTO_IPV6 _SC_DELAYTIMER_MAX pw_dir sa_mask __sigval_t LSAPI_Set_Extra_Children s_restored_ppid sin6_flowinfo totalLen m_pid _SC_SYSTEM_DATABASE lsapi_prefork_server_accept m_pIovecToWrite code m_respHeaderLen _wide_data H_IF_MATCH ai_family __nlink_t si_addr st_ino st_mode LSAPI_IsRunning _SC_T_IOV_MAX CGI_HEADER_LEN IPPROTO_DCCP __in6_u sysconf GetHeaderVar H_ACC_CHARSET __stream _SC_XOPEN_STREAMS m_iMaxIdleChildren sendfile _IScntrl m_reqBufSize lsapi_child_status prctl allocateEnvList _ISupper pStatus err_no sival_int si_code m_pReqBuf wait_time strcasecmp H_IF_UNMOD_SINCE pw_name _SC_TRACE_USER_EVENT_MAX __socklen_t send_notification_pkt lsapi_request pKeyEnd curTime fprintf lsapi_writev __ssize_t __src lsapi_close pChroot H_IF_RANGE timespec nameOff __u6_addr8 strerror __RLIMIT_RSS avoidFork m_packetLen LSAPI_ReadReqBody_r IPPROTO_MPTCP _SC_2_FORT_RUN bind fp_lve_leave __val in6_addr _SC_ADVISORY_INFO packetLen __timezone __ctype_toupper_loc sin6_addr _SC_TIMER_MAX pBufCur _SC_THREADS unset_lsapi_envs __sighandler_t _SC_USER_GROUPS_R LSAPI_Set_Server_fd LSAPI_CreateListenSock __RLIMIT_LOCKS m_respPktHeaderEnd LSAPI_On_Timer_pf LSAPI_Set_Max_Reqs _SC_UINT_MAX st_uid s_conn_close_pkt LSAPI_Postfork_Parent pEnd pktType lsapilib.c set_skip_write _SC_TRACE_NAME_MAX _lower s_busy_workers _SC_THREAD_DESTRUCTOR_ITERATIONS m_flag memset level stderr m_pHeaderIndex name idle _SC_CHILD_MAX lsapi_reopen_stderr2 _IO_save_end tm_min __nptr LSAPI_Init LSAPI_Request _SC_V6_LP64_OFF64 flag _SC_NGROUPS_MAX m_bufProcessed fixHeaderIndexEndian stdout fp_offset lsapi_MD5Transform LSAPI_Write_Stderr_r __time_t _SC_THREAD_ROBUST_PRIO_INHERIT gp_offset _pad LSAPI_ForeachOrgHeader_r sigaddset LSAPI_Inc_Req_Processed m_httpHeaderLen dying realpath tm_yday _SC_SSIZE_MAX _SC_PII_OSI_CLTS _SC_SYSTEM_DATABASE_R msecs pAuth _SC_LEVEL1_DCACHE_SIZE keyLen extraChildren LSAPI_Flush_r short unsigned int rlim_cur signed char LSAPI_Reset_r s_lve old_ppid LSAPI_CB_EnvHandler _valueLen __blksize_t _SC_STREAMS SOCK_STREAM digest pBufEnd _SC_PAGESIZE _SC_THREAD_PRIORITY_SCHEDULING count si_pid IPPROTO_MTP s_stop _SC_CHARCLASS_NAME_MAX lsapi_header_offset strchr vfprintf setgid _bounds tm_wday __off64_t __fd __len achBuf _sigsys _IO_read_base _SC_XBS5_ILP32_OFFBIG send_req_received_notification _offset IPPROTO_EGP LSAPI_reset_server_state sockaddr sigset_t s_defaultGid s_keep_listener secs m_cntUnknownHeaders readfds ai_addrlen longs opterr _SC_DEVICE_SPECIFIC_R LSAPI_Set_Restored_Parent_Pid pw_gecos _mode m_iExtraChildren LSAPI_No_Check_ppid _SC_PIPE _IO_write_base _SC_XOPEN_CRYPT valueLen m_respInfo tz_dsttime _SC_PHYS_PAGES lsapi_enable_core_dump H_CACHE_CTRL H_COOKIE2 _SC_ATEXIT_MAX __dest tm_mon close _SC_SHRT_MIN _SC_FIFO bits time H_USERAGENT s_min_avail_pages _SC_USER_GROUPS m_lLastActive LSAPI_ForeachEnv_r long int SOCK_PACKET sa_sigaction notify_req_received _SC_XBS5_ILP32_OFF32 dump s_worker_status _IO_marker __builtin_strncpy s_ppid tm_year limit max_children _SC_2_PBS_MESSAGE m_pRespBufEnd timeval orig_mask tmCur _SC_XOPEN_REALTIME_THREADS fp_lve_is_available pAddr s_defaultUid m_pChildrenStatus __fds_bits _SC_SPIN_LOCKS LSAPI_Set_Server_Max_Idle_Secs write m_bufRead _SC_SPORADIC_SERVER lsapi_close_connection uint8_t _SC_LEVEL1_DCACHE_LINESIZE __sigaction_handler lsapi_signal _SC_PRIORITIZED_IO in_addr SOCK_SEQPACKET __pid_t _IO_codecvt _SC_GETPW_R_SIZE_MAX pUgid headers hints _SC_XOPEN_VERSION H_RANGE _SC_BC_SCALE_MAX _SC_2_C_VERSION dup2 strtol g_req long double parseEnv ai_socktype _SC_THREAD_KEYS_MAX iov_len _SC_LEVEL4_CACHE_LINESIZE fd_set lsapi_MD5Init _SC_NL_TEXTMAX nonblock long unsigned int lsapi_req_header _SC_LOGIN_NAME_MAX find_child_status IPPROTO_PIM _SC_XBS5_LP64_OFF64 _SC_SPAWN maxChildren newlen si_status sigemptyset _pkey m_headerOff __RLIMIT_OFILE HTTP_HEADERS _SC_2_PBS s_proc_group_timer_cb pw_gid __errno_location _SC_XBS5_LPBIG_OFFBIG _SC_WORD_BIT char _SC_2_PBS_ACCOUNTING m_pSpecialEnvList sin6_scope_id stdin _SC_AIO_MAX __oflag _SC_2_CHAR_TERM resolved_path _SC_LEVEL1_ICACHE_LINESIZE _IO_buf_base ai_flags realloc _SC_XOPEN_SHM __dev_t _SC_XOPEN_ENH_I18N old_quit RLIMIT_CPU __glibc_reserved _IO_read_end _SC_ULONG_MAX _SC_TYPED_MEMORY_OBJECTS _SC_TIMEOUTS _SC_LEVEL2_CACHE_SIZE final _SC_XOPEN_UNIX m_pRespBufPos _IO_FILE in_addr_t m_fd H_HOST _IO_wide_data cookie strlen tzname _sifields _SC_LEVEL2_CACHE_LINESIZE __u6_addr16 s_pid IPPROTO_AH LSAPI_ReqBodyGetLine_r tm_hour setsid Flush_RespBuf_r _SC_THREAD_STACK_MIN isPipe _SC_PII_OSI_M m_respHeader s_global_counter RLIMIT_AS _SC_NL_MSGMAX si_signo m_pAppData __RLIMIT_MSGQUEUE achAddr m_inProcess _SC_THREAD_ROBUST_PRIO_PROTECT _ISgraph _lsapi_prefork_server tm_mday pInteger lsapi_siguser1 __pad0 _SC_BC_DIM_MAX __pad5 _SC_LEVEL1_DCACHE_ASSOC malloc s_dump_debug_info s_avail_pages __u6_addr32 _headerInfo m_type si_errno finish_close listen signo _SC_XOPEN_REALTIME _markers LSAPI_InitRequest _SC_SAVED_IDS pBind m_scriptFileOff _SC_INT_MAX si_band s_log_level_names s_skip_write H_VIA memccpy _codecvt fork IPPROTO_ESP m_pRespHeaderBufEnd _SC_TRACE_LOG getpwnam timeout _SC_THREAD_PRIO_PROTECT g_fnSelect RLIMIT_FSIZE __builtin_memcpy st_rdev lsapi_http_header_index pEnv _SC_OPEN_MAX st_dev ssize_t dlerror headerIndex _SC_UIO_MAXIOV LSAPI_Log m_pRespHeaderBuf __int32_t H_PRAGMA __uint32_t qsort pSecretFile __RLIMIT_NLIMITS __daylight IPPROTO_RSVP strncpy H_REFERER IPPROTO_UDPLITE SOCK_CLOEXEC LSAPI_Set_Slow_Req_Msecs LSAPI_Prefork_Accept_r _sys_siglist handler _SC_CHAR_MAX LSAPI_Get_ppid _ISlower pEnvEnd sigprocmask m_pUnknownHeader getpwuid m_reqState _SC_PII_XTI pRespHeaders left kill GNU C17 8.5.0 20210514 (Red Hat 8.5.0-28) -mtune=generic -m64 -march=x86-64 -g -O2 -fPIC -fexceptions -fstack-protector-strong -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection=full -fplugin=gcc-annobin m_pRespBuf m_iCurChildren socket LSAPI_Write_r _SC_PII_OSI_COTS m_totalLen passwd m_pIovec s_stderr_is_pipe fstat __snprintf_chk _SC_PII_SOCKET __gid_t lsapi_sigpipe _SC_V6_LPBIG_OFFBIG _SC_MQ_PRIO_MAX getcwd H_TRANSFER_ENCODING H_IF_MODIFIED_SINCE __bsx ai_next s_enable_core_dump _SC_TRACE_EVENT_FILTER nodelay sin6_family __resolved _freeres_buf _sigfault m_iChildrenMaxIdleTime _SC_THREAD_CPUTIME si_utime tv_sec _SC_VERSION m_cntSpecialEnv _SC_C_LANG_SUPPORT_R long long unsigned int memmove sa_handler sin_addr _cur_column lsapi_load_lve_lib toWrite uid_t _SC_PII si_fd _SC_MAPPED_FILES _SC_LEVEL4_CACHE_SIZE IPPROTO_BEETPH fp_lve_jail _SC_2_FORT_DEV IPPROTO_IP m_pRespHeaderBufPos st_blocks lsapi_initSuEXEC __bswap_16 getpid __buf _SC_2_LOCALEDEF m_cntEnv localtime_r _SC_LEVEL1_ICACHE_SIZE readBodyToReqBuf tm_gmtoff IPPROTO_PUP _name sigval _IO_backup_base H_KEEP_ALIVE _IO_read_ptr _SC_CHAR_BIT LSAPI_Register_Pgrp_Timer_Callback md5ctx __socket_type __nbytes _nameLen getenv _freeres_list __ap s_max_busy_workers IPPROTO_ETHERNET H_IF_NO_MATCH pEnvList rlim_t lsapi_read sun_path timezone CGI_HEADERS si_overrun __bswap_32 pReq _SC_INT_MIN lsapi_MD5Update _SC_RE_DUP_MAX _SC_PII_INTERNET_STREAM achBody achPeer header _SC_THREAD_ATTR_STACKSIZE full_path _old_offset _SC_SIGQUEUE_MAX siginfo_t _SC_FD_MGMT expect_connected _SC_SYNCHRONIZED_IO LSAPI_STATE_IDLE valueOff sighandler_t _SC_V7_ILP32_OFF32 skip unlink send_conn_close_notification optind s_accept_notify writev H_ACC_LANG _SC_EXPR_NEST_MAX _SC_LEVEL3_CACHE_LINESIZE long long int m_pktHeader in6addr_loopback port s_accepting_workers IPPROTO_IDP _flags2 lsapi_prefork_server allocateIovec _SC_MESSAGE_PASSING __ch _SC_REGEX_VERSION m_iLen LSAPI_Set_Max_Children __d1 setuid tv_nsec m_scriptNameOff lsapi_perror _SC_FILE_LOCKING _SC_AVPHYS_PAGES _SC_MB_LEN_MAX pHeader _ISdigit sockaddr_in6 IPPROTO_SCTP _SC_PII_OSI _SC_ARG_MAX __ino_t setsockopt _SC_MEMLOCK_RANGE LSAPI_Finish_r _SC_SHARED_MEMORY_OBJECTS lsapi_resp_header sys_nerr in6addr_any m_pRequestMethod achError _SC_CHAR_MIN __realpath_chk iov_base m_lReqBegin s_uid s_total_pages pw_shell __name m_versionB0 m_versionB1 IPPROTO_GRE _SC_XOPEN_LEGACY _SC_NL_ARGMAX RLIMIT_CORE si_tid tobekilled _SC_THREAD_PRIO_INHERIT _SC_LEVEL3_CACHE_ASSOC _SC_NPROCESSORS_ONLN m_headerLen expect_accepting m_pIovecCur fdListen LSAPI_Init_Env_Parameters addr_len _SC_HOST_NAME_MAX IPPROTO_TCP LSAPI_AppendRespHeader2_r _SC_COLL_WEIGHTS_MAX _SC_MONOTONIC_CLOCK __rlimit_resource m_reqBodyRead LSAPI_Set_Max_Idle _SC_CLK_TCK LSAPI_ForeachSpecialEnv_r lsapi_buildPacketHeader LSAPI_perror_r _SC_NL_SETMAX unsigned int _SC_BARRIERS bodyLen pBegin LSAPI_Accept_r wait_secs lsapi_reopen_stderr strcmp st_mtim __statbuf __RLIMIT_NICE fn_select_t short int lsapi_notify_pid si_sigval setrlimit _vtable_offset addrinfo _SC_IPV6 mmap IPPROTO_ICMP lsapi_sigchild _SC_REGEXP lsapi_schedule_notify LSAPI_Get_Slow_Req_Msecs _SC_V6_ILP32_OFFBIG stat memchr tz_minuteswest sys_siglist H_ACC_ENCODING sin6_port m_iMaxReqProcessTime __RLIMIT_RTPRIO  GCC: (GNU) 8.5.0 20210514 (Red Hat 8.5.0-28)             GNU                    zR x                      0                 D              L   X       s    EIB E(A0z
(A BBBIA
(D BBBA                                    @          Y   GJB B(A0A80F(B DBb 0             BFC G
 AABK    H      k       (   \      G    ADJ n
AAA  4         U    AGK R
CAGL
JCG                AG]
AJ             t
CKF  L             BBE A(H0H
(D BBBD
(D BBBA P   X          vFB A(D0D
(A BBBBL(A BBBA  $         a    AAD XAAH             BBB B(A0A8D@N
8C0A(B BBBH $          O    Af
QC
EH   @   H      Y   BBB A(D0J
0A(A BBBFx            FEA C(G
 
(A ABBDM
I
c
A

E
M
A
k
E
E
E
E
HV
 H            FBB B(A0A8D``
8A0A(B BBBDl   T      +   BBB B(A0D8JYHPC	Mi
8A0A(B BBBELTMDd         6   BBB B(A0A8DP
8A0A(B BBBG
8J0H(G DBBK   $   ,      7    EFF IIO    T                h                |                             4            FAA G>
 AABG                 EO
D
A                                     (      Y          <      J    ED     X      S           l      ]    Ph
HXA   H         l   FBB B(A0A8LP
8A0A(B BBBH <            FBB A(A0
(D BBBI            i       `   0         FBB B(A0A8DP~
8A0A(B BBBAk
8A0A(B BBBH L         $   FBB A(A0HQD
0A(A BBBH L            FBB B(A0A8G
8A0A(B BBBF      4      F          H      F          \             $   p          nCXJ   L         l   FBB B(A0A8DA
8A0A(B BBBA   `             BBB B(A0A8G I K I L N N w
8A0A(B BBBI0   L	          BMD GL
 AABA<   	      =   BAA G L@I@U
 AABG   $   	          TWEHG       	          ag
HS   H   
         FBB B(A0A8DPS
8D0A(B BBBFT   X
          bIE D(C0P
(F BBBMQ(H BBBA H   
         FBB B(A0A8DP
8A0A(B BBBAT   
         CBA A(G0`
(A ABBD
(C ABBAJ   8   T      -   FBD D(D@T
(A ABBB                 (         l    ECGF
AAIL         !   cBG A(D0
(A ABBEXD0                       4      Z          H      1       0   \      p   FAA G@7
 AABF         @    Ls   L            FBB B(A0A8G
8A0A(B BBBG                                      $                8                L                `                t                                                                             <         	   FBA K(G 
(A ABBG   <             FEE D(D0M
(C BBBB      X      (       H   l          FBH E(A0E8I@
8A0A(B BBBE (             FED AB  H            BBB B(A0A8G
8A0A(B BBBJD   0         FBB A(A0G
0A(A BBBF   L   x      
   FBB B(A0A8G
8A0A(B BBBA                                                               
                                                                     	                                           
                     1                                       -                                           E    2                                       a                                           ~    3                                                                                      4                                                                                      5                                     .                   I                   W                   u                                         l	                                    -                   -               
                   "    0       s       -                   J                   e                  s   	              z                                         	                                     )                         Y          )              2                  L    0             Y                  z    +	                        k          	                   +	                  w	                  0	      G           w	              :    	              X    	      U       i    	                  s
                  	                 s
                                    
                                  x                                    5                 P   	              _   	              s    (                  0                  x                  *                                   *              #                  N    0      a       l   	              |                                                                                                   O       &   	              -   	              =                  h    9                        Y          9                                                         	                          @           	                                $                  @                O   	              e    `	             r                                    U          +                            6                         6      	                   %	   	              7	    6              S	    w              m	    w              	                  	   	 l             	   	              	                  	                  	                  
                  4
                  f
                  
   	 x             
                  
                  
                      ]                 	              '   	              ;    ]              \    m              {    m                                                                                          *              +    *              L                  k                                                          \                  \              "    k               C    k               b                                          "                                    "                  $%                  @                   `      d       0    $%              U    E'              x          d           E'                  '                  '                  '                  '              D    (              m    (                  )                  )                  *                 	                  *                  +              7     +             F    +              c    ,              ~     ,                	 0                 ,                  .                  ,      =          .                  u/              *                  7    u/              [    )0              }    )0                  1                  1                  2                  2                  4              C    4              k    5                  5                  6                  6                   7              !    7              G    7              k    7                  8                  d	                                    X	                 8              
    8              +    8              S    :9              y    :9                  q9                  P	                 q9                  :                                       	              #    h	             3   	 (             B    :              g    0;                  0;                  H?                 	                   	                 	 @                	                  	                  H?              '    ^?              G                  R    ^?              t    k?                  k?                  ?                  ?                  ?              ,    ?              V    ?              ~    ?                  ?                  ?                   @              ,    @              T    @              z   	                  @                  +@                  +@                  ?@                  ?@              ;    K@              W    K@                  TI                 	 )                	 p                	 h                	 d                	 `                	 P                	 H                	 @             #   	 8             0   	 X             6    TI              Y    I              z    I                  J                  J                  J                  J                  K              (    K              ?    W              T    K            \    (              b            $      o            (       |    W                  UY                  UY                  Zd                                      Zd              >    qd              i    qd                  d                                                                                     !                      #                      $                      &                      (                      )                      +                      2                      3                      4                      5                      6                      7                      1                      8                                                               2                    8                    F                    "                                         K                    O                    (                    p                                        R                    P                                                         [                    o                    y                                   #                    )                    /                    5                   ;                    A                    G     8              M     X              S                   Y                    _                    e                   k                    q                   w     +              }     =                   N                   b                   w                                                                                                                                                        *                   @                   V                                                                                                                                                                                                                                                                                        %     ]              +     o              1                   7                   =                   C     p              I                   O     @              U                   [     T              a     h              g     t              m                   s     8              y     p                                      6                                                         &                                                                                                                                     (                                      P                                                                                                                            ,                      -                      .                      /                      0                                                                                                                               )                   >                  M                     c                     m                     y                                                                                                                                                                                                                                        1                                                                                                                                                                                                                                          "                      /                      9     @                                 C                      R                      a                      h                      v                                                                                                                                         @      7                                                                                                     !                 !                     '!                     	#                     S!                     3!                     8!                 C!                     R                     K!    @       	      Q!                     X!                     ^!    `             p!    p             !          Y       !          J       !                     !    0      S       !          ]       !          l      !                     !                     !    `            "    p       i       "                 %"                     ,"                     @"     #      $      Y"                     _"    0%            u"    P'      F       "    '      F       "    '             "    (             "    )      l                           "                     "                     "                     "                     #                     #    .             #    /             1#    00            ?#     2             P#                     Y#    2            s#                     z#    4            #    5      -      #                     #                     #                     #                     #     7             #     7      l       #    7      !      
$                     $                     $                     !$    8             5$    8      Z       N$    @9      1       a$    9      p      v$    :      @       $                     $    0;            $                     $                     $                     $    P?             $    `?             $    p?             %    ?             %    ?             :%    ?             V%    ?             u%    @             %     @             %    0@             %    @@             %    P@      	      %                     %                     %                     %                     &                     &                     &                      &    `I             4&    I      (       B&    J             R&     K             a&                     j&                     q&                     {&                     &                     &                     &                     &    W            &    `Y      
      &                     &                     &    `d             &    d             '                      .annobin_lsapilib.c .annobin_lsapilib.c_end .annobin_lsapilib.c.hot .annobin_lsapilib.c_end.hot .annobin_lsapilib.c.unlikely .annobin_lsapilib.c_end.unlikely .annobin_lsapilib.c.startup .annobin_lsapilib.c_end.startup .annobin_lsapilib.c.exit .annobin_lsapilib.c_end.exit .annobin_lsapi_sigpipe.start .annobin_lsapi_sigpipe.end lsapi_sigpipe .annobin_lsapi_siguser1.start .annobin_lsapi_siguser1.end lsapi_siguser1 g_running .annobin_compareValueLocation.start .annobin_compareValueLocation.end .annobin_EnvForeach.start .annobin_EnvForeach.end EnvForeach .annobin_lsapi_cleanup.start .annobin_lsapi_cleanup.end lsapi_cleanup s_stop .annobin_set_skip_write.start .annobin_set_skip_write.end s_skip_write .annobin_lsapi_MD5Transform.start .annobin_lsapi_MD5Transform.end lsapi_MD5Transform .annobin_lsapi_signal.start .annobin_lsapi_signal.end lsapi_signal .annobin_find_child_status.start .annobin_find_child_status.end find_child_status g_prefork_server .annobin_allocateRespHeaderBuf.start .annobin_allocateRespHeaderBuf.end allocateRespHeaderBuf .annobin_lsapi_set_nblock.start .annobin_lsapi_set_nblock.end lsapi_set_nblock .annobin_lsapi_accept.start .annobin_lsapi_accept.end lsapi_accept .annobin_parseEnv.start .annobin_parseEnv.end parseEnv .annobin_lsapi_init_children_status.start .annobin_lsapi_init_children_status.end lsapi_init_children_status s_busy_workers s_accepting_workers s_avail_pages s_global_counter .annobin_readBodyToReqBuf.part.2.start .annobin_readBodyToReqBuf.part.2.end readBodyToReqBuf.part.2 .annobin_lsapi_close_connection.isra.4.start .annobin_lsapi_close_connection.isra.4.end lsapi_close_connection.isra.4 s_worker_status .annobin_lsapi_writev.part.6.start .annobin_lsapi_writev.part.6.end lsapi_writev.part.6 .annobin_lsapi_parent_dead.start .annobin_lsapi_parent_dead.end lsapi_parent_dead s_ppid s_restored_ppid .annobin_LSAPI_ParseSockAddr.part.13.start .annobin_LSAPI_ParseSockAddr.part.13.end LSAPI_ParseSockAddr.part.13 .annobin_LSAPI_Log.start .annobin_LSAPI_Log.end s_stderr_is_pipe s_log_level_names s_pid .annobin_lsapi_sigchild.start .annobin_lsapi_sigchild.end lsapi_sigchild s_pid_dump_debug_info s_ignore_pid .annobin_dump_debug_info.start .annobin_dump_debug_info.end .annobin_lsapi_check_child_status.start .annobin_lsapi_check_child_status.end lsapi_check_child_status s_max_idle_secs s_dump_debug_info .annobin_lsapi_perror.start .annobin_lsapi_perror.end .annobin_LSAPI_is_suEXEC_Daemon.start .annobin_LSAPI_is_suEXEC_Daemon.end s_uid s_secret .annobin_LSAPI_Stop.start .annobin_LSAPI_Stop.end .annobin_LSAPI_IsRunning.start .annobin_LSAPI_IsRunning.end .annobin_LSAPI_Register_Pgrp_Timer_Callback.start .annobin_LSAPI_Register_Pgrp_Timer_Callback.end s_proc_group_timer_cb .annobin_LSAPI_InitRequest.start .annobin_LSAPI_InitRequest.end .annobin_LSAPI_Init.start .annobin_LSAPI_Init.end g_inited pthread_atfork_func .annobin_LSAPI_Is_Listen_r.start .annobin_LSAPI_Is_Listen_r.end .annobin_LSAPI_Is_Listen.start .annobin_LSAPI_Is_Listen.end .annobin_LSAPI_Reset_r.start .annobin_LSAPI_Reset_r.end .annobin_LSAPI_Release_r.start .annobin_LSAPI_Release_r.end .annobin_LSAPI_GetHeader_r.start .annobin_LSAPI_GetHeader_r.end .annobin_LSAPI_ReqBodyGetChar_r.start .annobin_LSAPI_ReqBodyGetChar_r.end .annobin_LSAPI_ReqBodyGetLine_r.start .annobin_LSAPI_ReqBodyGetLine_r.end .annobin_LSAPI_ReadReqBody_r.start .annobin_LSAPI_ReadReqBody_r.end .annobin_Flush_RespBuf_r.start .annobin_Flush_RespBuf_r.end .annobin_LSAPI_GetEnv_r.start .annobin_LSAPI_GetEnv_r.end CGI_HEADERS .annobin_LSAPI_ForeachOrgHeader_r.start .annobin_LSAPI_ForeachOrgHeader_r.end HTTP_HEADERS HTTP_HEADER_LEN .annobin_LSAPI_ForeachHeader_r.start .annobin_LSAPI_ForeachHeader_r.end CGI_HEADER_LEN .annobin_LSAPI_ForeachEnv_r.start .annobin_LSAPI_ForeachEnv_r.end .annobin_LSAPI_ForeachSpecialEnv_r.start .annobin_LSAPI_ForeachSpecialEnv_r.end .annobin_LSAPI_FinalizeRespHeaders_r.start .annobin_LSAPI_FinalizeRespHeaders_r.end .annobin_LSAPI_Flush_r.start .annobin_LSAPI_Flush_r.end .annobin_LSAPI_Write_Stderr_r.start .annobin_LSAPI_Write_Stderr_r.end s_stderr_log_path .annobin_LSAPI_perror_r.start .annobin_LSAPI_perror_r.end LSAPI_perror_r .annobin_lsapi_jailLVE.start .annobin_lsapi_jailLVE.end lsapi_jailLVE fp_lve_jail .annobin_lsapi_reopen_stderr.start .annobin_lsapi_reopen_stderr.end lsapi_reopen_stderr .annobin_LSAPI_Finish_r.start .annobin_LSAPI_Finish_r.end finish_close .annobin_LSAPI_End_Response_r.start .annobin_LSAPI_End_Response_r.end .annobin_LSAPI_Write_r.start .annobin_LSAPI_Write_r.end .annobin_LSAPI_sendfile_r.start .annobin_LSAPI_sendfile_r.end .annobin_LSAPI_AppendRespHeader2_r.start .annobin_LSAPI_AppendRespHeader2_r.end .annobin_LSAPI_AppendRespHeader_r.start .annobin_LSAPI_AppendRespHeader_r.end .annobin_LSAPI_CreateListenSock2.start .annobin_LSAPI_CreateListenSock2.end .annobin_LSAPI_ParseSockAddr.start .annobin_LSAPI_ParseSockAddr.end .annobin_LSAPI_CreateListenSock.start .annobin_LSAPI_CreateListenSock.end .annobin_LSAPI_Init_Prefork_Server.start .annobin_LSAPI_Init_Prefork_Server.end s_max_busy_workers g_fnSelect s_total_pages .annobin_LSAPI_Set_Server_fd.start .annobin_LSAPI_Set_Server_fd.end .annobin_LSAPI_reset_server_state.start .annobin_LSAPI_reset_server_state.end .annobin_is_enough_free_mem.start .annobin_is_enough_free_mem.end s_min_avail_pages .annobin_LSAPI_Postfork_Child.start .annobin_LSAPI_Postfork_Child.end s_req_processed s_keep_listener s_notified_pid .annobin_LSAPI_Postfork_Parent.start .annobin_LSAPI_Postfork_Parent.end .annobin_LSAPI_Accept_Before_Fork.start .annobin_LSAPI_Accept_Before_Fork.end old_child old_term old_int old_usr1 old_quit .annobin_LSAPI_Set_Max_Reqs.start .annobin_LSAPI_Set_Max_Reqs.end s_max_reqs .annobin_LSAPI_Set_Max_Idle.start .annobin_LSAPI_Set_Max_Idle.end .annobin_LSAPI_Set_Max_Children.start .annobin_LSAPI_Set_Max_Children.end .annobin_LSAPI_Set_Extra_Children.start .annobin_LSAPI_Set_Extra_Children.end .annobin_LSAPI_Set_Max_Process_Time.start .annobin_LSAPI_Set_Max_Process_Time.end .annobin_LSAPI_Set_Max_Idle_Children.start .annobin_LSAPI_Set_Max_Idle_Children.end .annobin_LSAPI_Set_Server_Max_Idle_Secs.start .annobin_LSAPI_Set_Server_Max_Idle_Secs.end .annobin_LSAPI_Set_Slow_Req_Msecs.start .annobin_LSAPI_Set_Slow_Req_Msecs.end s_slow_req_msecs .annobin_LSAPI_Get_Slow_Req_Msecs.start .annobin_LSAPI_Get_Slow_Req_Msecs.end .annobin_LSAPI_No_Check_ppid.start .annobin_LSAPI_No_Check_ppid.end .annobin_LSAPI_Get_ppid.start .annobin_LSAPI_Get_ppid.end .annobin_LSAPI_Init_Env_Parameters.start .annobin_LSAPI_Init_Env_Parameters.end s_accept_notify s_enable_core_dump s_defaultUid s_defaultGid s_enable_lve s_liblve fp_lve_is_available fp_lve_instance_init fp_lve_enter s_lve .annobin_LSAPI_ErrResponse_r.start .annobin_LSAPI_ErrResponse_r.end .annobin_lsapi_MD5Init.start .annobin_lsapi_MD5Init.end .annobin_lsapi_MD5Update.start .annobin_lsapi_MD5Update.end .annobin_lsapi_MD5Final.start .annobin_lsapi_MD5Final.end .annobin_readReq.start .annobin_readReq.end readReq s_ack achBody.7025 headers.7024 .annobin_LSAPI_Accept_r.start .annobin_LSAPI_Accept_r.end .annobin_LSAPI_Prefork_Accept_r.start .annobin_LSAPI_Prefork_Accept_r.end s_conn_close_pkt .annobin_LSAPI_Set_Restored_Parent_Pid.start .annobin_LSAPI_Set_Restored_Parent_Pid.end .annobin_LSAPI_Inc_Req_Processed.start .annobin_LSAPI_Inc_Req_Processed.end .LC0 .LC1 .LC4 .LC5 .LC6 .LC3 .LC2 .LC7 .LC8 .LC9 .LC10 .LC11 .LC12 .LC13 .LC14 .LC15 .LC16 .LC17 .LC18 .LC19 .LC20 .LC21 .LC22 .LC23 .LC24 .LC25 .LC26 .LC27 .LC31 .LC32 .LC30 .LC29 .LC33 .LC34 .LC36 .LC37 .LC38 .LC39 .LC40 .LC41 .LC42 .LC44 .LC45 .LC46 .LC47 .LC48 .LC49 .LC50 .LC51 .LC59 .LC69 .LC70 .LC71 .LC43 .LC35 .LC61 .LC62 .LC63 .LC64 .LC65 .LC66 .LC67 .LC68 .LC52 .LC53 .LC54 .LC60 .LC58 .LC57 .LC55 .LC56 .LC87 .LC76 .LC77 .LC78 .LC72 .LC79 .LC80 .LC86 .LC74 .LC84 .LC83 .LC73 .LC75 .LC82 .LC81 .LC85 .LC92 .LC91 .LC88 .LC90 .LC89 .text.group .text.hot.group .text.unlikely.group .text.startup.group .text.exit.group compareValueLocation set_skip_write _GLOBAL_OFFSET_TABLE_ sigaction sigemptyset __stack_chk_fail realloc fcntl setsockopt mmap memset setsid read __errno_location writev kill getppid __ctype_b_loc strncpy strchr strcasecmp strtol getaddrinfo memcpy freeaddrinfo inet_addr LSAPI_Log __vfprintf_chk __snprintf_chk getuid __fprintf_chk gettimeofday localtime_r waitpid fork system lsapi_perror strerror LSAPI_is_suEXEC_Daemon LSAPI_Stop LSAPI_IsRunning LSAPI_Register_Pgrp_Timer_Callback LSAPI_InitRequest malloc getpeername dup2 LSAPI_Init geteuid g_req dlopen dlsym LSAPI_Is_Listen_r LSAPI_Is_Listen LSAPI_Reset_r LSAPI_Release_r free LSAPI_GetHeader_r LSAPI_ReqBodyGetChar_r LSAPI_ReqBodyGetLine_r memchr memmove LSAPI_ReadReqBody_r Flush_RespBuf_r LSAPI_GetEnv_r strcmp __ctype_toupper_loc LSAPI_ForeachOrgHeader_r qsort LSAPI_ForeachHeader_r LSAPI_ForeachEnv_r LSAPI_ForeachSpecialEnv_r LSAPI_FinalizeRespHeaders_r LSAPI_Flush_r LSAPI_Write_Stderr_r getpid getcwd memccpy __realpath_chk strdup LSAPI_Finish_r LSAPI_End_Response_r LSAPI_Write_r LSAPI_sendfile_r sendfile LSAPI_AppendRespHeader2_r strlen LSAPI_AppendRespHeader_r LSAPI_CreateListenSock2 socket bind listen unlink LSAPI_ParseSockAddr LSAPI_CreateListenSock LSAPI_Init_Prefork_Server calloc setpgid sysconf LSAPI_Set_Server_fd LSAPI_reset_server_state is_enough_free_mem LSAPI_Postfork_Child LSAPI_Postfork_Parent time LSAPI_Accept_Before_Fork __fdelt_chk usleep sched_yield LSAPI_Set_Max_Reqs LSAPI_Set_Max_Idle LSAPI_Set_Max_Children LSAPI_Set_Extra_Children LSAPI_Set_Max_Process_Time LSAPI_Set_Max_Idle_Children LSAPI_Set_Server_Max_Idle_Secs LSAPI_Set_Slow_Req_Msecs LSAPI_Get_Slow_Req_Msecs LSAPI_No_Check_ppid LSAPI_Get_ppid LSAPI_Init_Env_Parameters getenv getpwnam environ dlerror setrlimit __fxstat setreuid LSAPI_ErrResponse_r lsapi_MD5Init lsapi_MD5Update lsapi_MD5Final getpwuid setgid setgroups setuid strtoll prctl initgroups LSAPI_Accept_r LSAPI_Prefork_Accept_r sigaddset sigprocmask LSAPI_Set_Restored_Parent_Pid LSAPI_Inc_Req_Processed select                  d	                                            \                                                              D	           	           
           h
           o
                                                   2                  9                  H           $       O           ,       T           g         -  o                                             h	      C           M           X            h	      c                  z                              h	                             h	                  h	      a                                                                                	           8           g                    .                                   J                                                       5                                   *     T                               /                                                   0             	      *              1  %           >           K           w         2                      3                        5                  R         4  Y         5  `         6  v                                                    \	                        
                  "            X	      3                                                                            /           8           M         7  `           i           o                           8                                            9                                          p                              3         :  ?           K           _                           ;                                                              <  R           f         =              h                  {                  d	                  h	                  t      8           ~                                 K           W         >  `           i                                                               {                  h                                  *                                             $         ?  *                  /           ?         @  G           N                  w      *                                      "                                                                               (             h	      !         A  `!           !                 !           a"           j#           <       q#            \      p$      *     }$           $      *     $            %           %                  %                 &           A'           (           (                  Y)           )                  )           b*                  *           *           7+           A+           N+         B  W+           _+           }+         C  +           +           +           +           D,            ,      {,         D  ,           ,         E  ,           ,            h      	-           n-           -           -         F  -           -                  -           -           .                  8.           ?.           N.           Y.           ~.         G  .           .           .         H  .           /           */                   L/           T/           i/           /           /                   /           0           _1           1           1           1           Q2           v2           2           /3           3           -4           O4           |5           N6           h6           6           6           6           6           6           6           6           I7           W7           7           7                  7            `	      7            `	      7            7                  8           8           8                  #8           -8                  28           <8           G8            T	      {8           8                  8                  9                  '9                  G9           $       Q9            L	      f9            T	      9                  9           9                  9                  9           9                  9           9                  9                  9                  9            p      :      *     :                  #:                  <:            d	      G:                  Z:            `	      d:            h      :            :           :           :            #      :           :           :           :                  ;           !;           H;                  ;           ;            ;           ;           ;            |      ;           ;            <      <           <                   <           ,<                  9<           V<                  x<            t      <            \	      <           <           <           $       <         
  :=           S=           e=            o=           }=            |      =           =                  =           =            <      =           =                   =           =                  >                  />         I  6>           @>           F>                  w>           >           >           >         J  >           ?         K  ?           ?         L  #?           D?           Y?                    f?            w?                  ?                  ?                  ?                  ?                  @                  &@                  6@                  F@                  _@         M  @           @                  @         N  @           @           @         O  @           @           @            d	      @         P  @           A           'A         Q  ,A           @A           FA            %      MA         R  RA           fA           mA           tA         S  yA           A            h      A         T  A           A           A           A           A         U  A           A           A         V  A           B           B           B         W   B           4B           ;B           BB         X  GB           [B           bB           iB         Y  nB           B           B           B         Z  B           B           B         [  B           B           B            `	      B         \  B           B           B                  B            h       C            `      
C            \      C         ]  #C           2C            d      ?C            d      EC            `      TC         ^  YC           qC           wC            \      C            h      C      *     C            h      C         _  C         `  C         a  zD            `	      D           D            L	      D           D         b  D           D         c   E           %E            `      1E           NE           UE      *     \E           pE         d  uE           E            L      E         e  E           E            D      E           E            \      E         f  E           E         g  E            <      E           E         h  E           E         i  F            4      
F           F         j  F           %F            ,      ,F            T      GF         k  LF           SF            T      XF           _F            P      F           F           F           F                  F         l  F           F           F            d      G         m  
G           G           (G            `      /G         n  4G           QG           mG           G            |      G           G           G                  G            d      G            `      H         o  H           H            \      "H            d      ,H            `      6H            `      DH            \      ZH            X      yH            L      H         p  H           H           H           H            <      H            T      H           H            h      H           H            D      H            X      I            h      I           I         q  +I         r  7I           AI           KI         s  I           I           I           I           J           J           zK           9L           DL           OL            h	      JM           UM           dM            h	      M           4N           O         t  O           P         u  P           *P           .R            h      DR            %      JR            $      ]R            #      }R           R            d      R            `      R         v  S         w  mS            |      S         !  S         "  S         "  S         #  	T         $  T            T      /T            4      GT            +      uT         %  T         &  T         '  T            l      T            h      T           T         M  T           U                  U            |      *U            $       1U           GU         x  SU           eU           }U         (  U         y  U           U         z  U           U            d      U            `      U         $  U            T      U         )  V         {  V            V         |  ,V           =V         %  eV         %  V         }  V         *  V         ~  V            [      V            d      V            `      V         $  V           W           W           +W           9W           PW           YW           yW                   W           W            W           W           X            h	      BX           UX                  hX                  X            $      X           X            h	      X           Y            $        Y           GY           QY           xY                  Y           Y                  Y                  Y                    Y                  Y           Y            h	      #Z            h	      3Z                  ?Z                  eZ         
  Z           Z                  Z            p[           [           [           [           [           \           C\           \                  \            t      \            \	      \           \           \           $       ]         
  ^]           u]           ]           ]                  ]                  ^                  ^                  4^            d	      B^            $      X^            $       ]^           s^                  ^                  ^                  ^                  ^           _            d	      _           _            c	      +_                  D_                  c_                  _           _           _           _                  _         I  _           _           `            `           %`           \`           k`         -  |`         .  `           `           `         .  `           `           `           a           ,a         J  5a           ba                  qa            `	      a                  a            `	      a                   a           a           a           a           a           a           b           b            h	      3b         K  8b           Gb           Xb         .  gb                  pb           vb                  {b           b                  b                  b                  b                  b            p      b      *     b                  b                  b            d	      b                  c            `	      c            h      $c           Cc           Tc           ec           vc           c           c            c           c           c            #      c                  c         L  c           c           d           
d           d                  9d           Kd                  Vd           fd                  ld                  d           ,       	                      s           |           2           J                                           +                                                 $                    ,                   P                   X                                                                                        -                                      -                   -                          D            -       L                   p                   x                                                                                                                                     0                   8            )      d                   l            )                  )                                    )                                                      +	      $                  ,            +	      P            +	      X            w	                  +	                  w	                  w	                  	                  w	                  	                  	                  s
      D            	      L            s
      p            s
      x                              s
                                                      x                                    x      0            x      8            *      d            x      l            *                  *                                    *                                                            $                  ,                  P                  X                                                                                    9                                    9      	            9      	                  D	            9      L	                  p	                  x	                  	                  	                  	                  	                  
                  
                  0
                  8
            6      d
                  l
            6      
            6      
            w      
            6      
            w      
            w      
                  $            w      ,                  P                  X                                                                                                                                                                  D                  L                  p                  x                                                                                    ]                                    ]      0            ]      8            m      d            ]      l            m                  m                                    m                                                            $                  ,                  P                  X            *                                    *                  *                                    *                                                            D                  L                  p                  x            \                                    \                  \                  k                   \                  k       0            k       8                   d            k       l                                                  "                                     "                  "                  $%      $            "      ,            $%      P            $%      X            E'                  $%                  E'                  E'                  '                  E'                  '                  '                  '      D            '      L            '      p            '      x            (                  '                  (                  (                  )                  (                  )      0            )      8            *      d            )      l            *                  *                  +                  *                  +                  +                  ,      $            +      ,            ,      P            ,      X            .                  ,                  .                  .                  u/                  .                  u/                  u/                  )0      D            u/      L            )0      p            )0      x            1                  )0                  1                  1                  2                  1                  2      0            2      8            4      d            2      l            4                  4                  5                  4                  5                  5                  6      $            5      ,            6      P            6      X            7                  6                  7                  7                  7                  7                  7                  7                  8      D            7      L            8      p            8      x            8                  8                  8                  8                  :9                  8                  :9      0            :9      8            q9      d            :9      l            q9                  q9                  :                  q9                  :                  :                  0;      $            :      ,            0;      P            0;      X            H?                  0;                  H?                  H?                  ^?                  H?                  ^?                  ^?                  k?      D            ^?      L            k?      p            k?      x            ?                  k?                  ?                  ?                  ?                  ?                  ?      0            ?      8            ?      d            ?      l            ?                  ?                  ?                  ?                  ?                  ?                  @      $            ?      ,            @      P            @      X            @                  @                  @                  @                  +@                  @                  +@                  +@                  ?@      D            +@      L            ?@      p            ?@      x            K@                  ?@                  K@                  K@                  TI                  K@                  TI      0            TI      8            I      d            TI      l            I                  I                  J                  I                  J                  J                  J      $             J      ,             J      P             J      X             K                   J                   K                   K                   W                   K                   W      !            W      !            UY      D!            W      L!            UY      p!            UY      x!            Zd      !            UY      !            Zd      !            Zd      !            qd      "            Zd      "            qd      0"            qd      8"            d      d"            qd      l"            d                                      %                                          &                                          '                                          (                     ]                   C                   C                   C         (             X	      0                              1                     C                    C   3                C   9                C   >                 C   E      (          C   J      0          C   P      8          C   U      @          C   [      H          C   b      P          C   q      X          C         `          C         h          C         p          C         x          C                   C                   C                   C                   C                   C                   C                   C                   C                   C                   C                   C   +                C   4                C   H                C   S                C   Y                C   i                C   m                C         (         C         0         C         8         C         @         C         H         C         P         C         X         C         `         C         h         C         p         C   !      x         C   +               C   7               C   D               C   T               C   g               C   ~               C                  C                  C                  C                  C                  C                  C                  C                
                    
   $  +             
   $               
   $                             )       
   #          0       
   $        <       
   $  Y      C       
   $  7      J       
   $  "$      Q       
   $  u      V       
   $        d       
   $  7      n       
   $  ?      z       
   $  *             
   $  *             
   $  !             
   $  %             
   $               
   $  e-             
   $  @4             
   $  '             
   $               
   $  q             
   $        
      
   $  #            
   $  u      "      
   $        .      
   $  E      :      
   $  o      M      
   $        Y      
   $        e      
   $        q      
   $  ?            
   $  F%            
   $  a            
   $              
   $  +            
   $              
   $  4            
   $              
   $  5            
   $              
   $  +(            
   $  }            
   $              
   $              
   $  n            
   $               
   $        ,      
   $        9      
   $  o.      F      
   $  3      T      
   $  U8      a      
   $  [*      n      
   $        {      
   $              
   $              
   $              
   $              
   $  j(            
   $  )*            
   $              
   $  Z            
   $  /            
   $              
   $  j7      
      
   $  !	            
   $  .&      5      
   $        A      
   $  r      M      
   $  /      b      
   $  p            
   $  	            
   $  *            
   $  !0            
   $              
   $              
   $  $            
   $  !            
   $              
   $  s5            
   $  .1            
   $  7      (      
   $  !      5      
   $        B      
   $  7      Y      
   $  !      f      
   $        s      
   $  $            
   $  f.            
   $              
   $              
   $              
   $  y            
   $  $            
   $              
   $               
   $  }            
   $  f)      (      
   $  /      ?      
   $        L      
   $  	      Y      
   $  Q      p      
   $  w      |      
   $  n
            
   $  '            
   $              
   $  2.            
   $  M            
   $              
   $  '            
   $  (            
   $              
   $  j(            
   $  &      ,      
   $  1      8      
   $        ^      
   $  .      j      
   $  !            
   $  9            
   $  "            
   $              
   $  h            
   $  r            
   $  `+            
   $  p8            
   $  2            
   $  .      .      
   $  b*      :      
   $        F      
   $  !      S      
   $  o.      `      
   $        n      
   $              
   $  2"            
   $  #            
   $              
   $  H            
   $  
	            
   $  m            
   $              
   $              
   $  <            
   $  &      (      
   $        5      
   $  E0      B      
   $  ?&      O      
   $        \      
   $        i      
   $        v      
   $              
   $  %            
   $  I            
   $              
   $  (0            
   $              
   $  )            
   $              
   $               
   $  '3            
   $  1      	      
   $  .      	      
   $  7      	      
   $  o      ,	      
   $        9	      
   $        F	      
   $  )      S	      
   $        `	      
   $  0      m	      
   $  %.      z	      
   $  (      	      
   $        	      
   $         	      
   $        	      
   $        	      
   $  g!      	      
   $  #      	      
   $  &      
      
   $  g      
      
   $  %      &
      
   $        2
      
   $  J      >
      
   $  4      Z
      
   $        f
      
   $  6      x
      
   $  #&      ~
      
   $  *      
      
   $        
      
   $  |
      
      
   $  g5      
      
   $  
      
      
   $  e      
      
   $  $      
      
   $  '      
      
   $  t      
      
   $        
      
   $  C      
      
   $  h      
      
   $  '      
      
   $  |7      
      
   $  8      
      
   $  C      
      
   $  *      
      
   $  U      
      
   $  0      
      
   $  y            
   $  l            
   $  
            
   $        ,      
   $  4      9      
   $  #      G      
   $        S      
   $  0      e      
   $        k      
   $        q      
   $  A      w      
   $  X      }      
   $  #            
   $              
   $  !            
   $  #+            
   $  C            
   $              
   $  !            
   $              
   $  V            
   $  1            
   $  a8      	      
   $  -       (      
   $   -      5      
   $  @      B      
   $        O      
   $        \      
   $  %      i      
   $        v      
   $              
   $  5            
   $              
   $              
   $  S'            
   $  J(            
   $               
   $  !            
   $              
   $              
   $              
   $  0            
   $        =      
   $  	      I      
   $  *      U      
   $        a      
   $  &      m      
   $        y      
   $  1            
   $  C            
   $  44            
   $  j            
   $  6            
   $              
   $  N*            
   $              
   $              
   $              
   $  6)            
   $              
   $              
   $               
   $              
   $  "            
   $  2            
   $  J             
   $  /            
   $              
   $  S4            
   $               
   $  R3            
   $        $      
   $  t4      *      
   $        0      
   $  %      6      
   $  
      <      
   $        B      
   $        H      
   $  -      N      
   $  v.      T      
   $        Z      
   $        `      
   $  m      f      
   $  w      l      
   $  1      r      
   $        x      
   $  ^      ~      
   $  q(            
   $  k#            
   $              
   $  V6            
   $  *            
   $  2            
   $              
   $  e1            
   $  ;            
   $  _	            
   $  [            
   $              
   $  W/            
   $  O            
   $               
   $  /            
   $  /            
   $  +            
   $  V-            
   $  G            
   $  (4            
   $              
   $  d            
   $  ~*            
   $  "            
   $  t1            
   $  K             
   $  -      &      
   $        ,      
   $  '      2      
   $        8      
   $        >      
   $  5      D      
   $        J      
   $  (#      P      
   $  E$      V      
   $        \      
   $        b      
   $  #      h      
   $  r'      n      
   $        t      
   $        z      
   $  1            
   $              
   $  5            
   $  )            
   $              
   $  S            
   $  5            
   $  8             
   $  3            
   $  u             
   $              
   $  Q#            
   $              
   $  &            
   $  	             
   $  &            
   $  %            
   $  %            
   $  |#            
   $              
   $              
   $              
   $              
   $  R0      
      
   $  u+            
   $  4            
   $  Z)            
   $  I1      "      
   $        (      
   $  9%      .      
   $  3      4      
   $        :      
   $        @      
   $  	      F      
   $        L      
   $        R      
   $         X      
   $  O      ^      
   $        d      
   $  L&      j      
   $        p      
   $  Y5      v      
   $  <
      |      
   $  '            
   $  h            
   $  6            
   $  
$            
   $  =!            
   $              
   $  v$            
   $  #%            
   $  H5            
   $  )            
   $  !            
   $              
   $  7            
   $  ~            
   $              
   $  .            
   $              
   $  .            
   $  S.            
   $  Z            
   $              
   $               
   $  1            
   $               
   $              
   $              
   $  3            
   $  b      $      
   $  k6      *      
   $        0      
   $  b      6      
   $        <      
   $        B      
   $  ="      H      
   $  8      N      
   $  k3      T      
   $         Z      
   $  ~      `      
   $  $      f      
   $  {"      l      
   $          r      
   $  u      x      
   $        ~      
   $  s&            
   $  Z&            
   $               
   $              
   $  $            
   $  K%            
   $  I            
   $  !            
   $               
   $  a            
   $              
   $  r	            
   $              
   $  A8            
   $              
   $  {-            
   $  6            
   $  2            
   $  -            
   $              
   $  )            
   $  /            
   $  
            
   $  %            
   $              
   $  (            
   $  "             
   $  &      &      
   $        ,      
   $  '      2      
   $        8      
   $  5      >      
   $  2      D      
   $  &/      J      
   $  
      P      
   $  #      V      
   $  7      \      
   $        b      
   $  F2      h      
   $        n      
   $  A      t      
   $  S      z      
   $              
   $  .            
   $              
   $  (            
   $  H            
   $  y            
   $  N            
   $  (            
   $  :            
   $  2            
   $              
   $              
   $  "            
   $  ^            
   $              
   $  &            
   $  "            
   $        9      
   $  f/      ?      
   $  7      E      
   $  X      K      
   $  
      Q      
   $  06      W      
   $        ]      
   $  0      c      
   $        i      
   $  3      o      
   $        u      
   $  8      {      
   $              
   $  *            
   $  <5            
   $  )            
   $  1'            
   $  (            
   $  </            
   $  '            
   $  j$            
   $              
   $  4            
   $  +            
   $  	            
   $  0            
   $              
   $  A            
   $              
   $              
   $              
   $  '            
   $  (      N      
   $  v      [      
   $  E      n      
   $  4      z      
   $  2            
   $              
   $  
            
   $  T            
   $  .            
   $              
   $  4            
   $  .            
   $  8            
   $  X            
   $              
   $  r%      -      
   $  7      ;      
   $  %      I      
   $        W      
   $  #      e      
   $  y      s      
   $  q            
   $  	            
   $              
   $  -            
   $  q            
   $  4            
   $  1            
   $              
   $  b      
      
   $  |8            
   $  2            
   $  %            
   $        "      
   $  n      (      
   $  ;      .      
   $        4      
   $  k       :      
   $  &      @      
   $  *      F      
   $  	+      L      
   $         R      
   $  ^       X      
   $  -      ^      
   $        d      
   $  0      j      
   $        p      
   $  /      v      
   $  80      |      
   $  c#            
   $              
   $  )            
   $  -            
   $  }3            
   $              
   $              
   $  $5            
   $  05            
   $  (            
   $  6            
   $  !            
   $  4$            
   $  2             
   $        -      
   $  %      :      
   $  J)      G      
   $  3      T      
   $  0      a      
   $  	      n      
   $  U      {      
   $  /            
   $  .            
   $  1*            
   $  5            
   $  $            
   $  R            
   $              
   $  )	            
   $  02            
   $                
   $  )      -      
   $        :      
   $        H      
   $  4      U      
   $  2      b      
   $  "       r      
   $  #      w      
   $  %            
   $  /            
   $  4            
   $  6            
   $  	            
   $              
   $  
            
   $  &            
   $               
   $  4            
   $              
   $              
   $  ,      "      
   $  !      /      
   $  &      <      
   $  *      I      
   $  )      V      
   $  q/      c      
   $        p      
   $  '-      }      
   $              
   $  5            
   $              
   $  R            
   $  ?            
   $  s            
   $  `%            
   $              
   $              
   $  Q            
   $  +            
   $               
   $  :      &      
   $        3      
   $        @      
   $  4      M      
   $  -      Z      
   $  +      g      
   $  %      t      
   $  6            
   $              
   $  q"            
   $  W            
   $  '            
   $              
   $  '            
   $              
   $  o            
   $               
   $  
            
   $   (            
   $  A      "      
   $         /      
   $  	      <      
   $        I      
   $  L            
   $              
   $  #            
   $              
   $  7      +      
   $  e      O      
   $  .      i      
   $               
   $              
   $  2            
   $              
   $  }            
   $              
   $  W!                              
   $  	                              
   $  g                  l	      $      
   $  !      1                  :      
   $  H      G                  P      
   $  +'      ]                  f      
   $        s                  |      
   $  @                  h	            
   $  (                              
   $                                
   $                                
   $  )                              
   $                                 
   $        ,                  5      
   $  3      B                  K      
   $  '      X           0       a      
   $  0      n            d	      w      
   $  /                              
   $  0-                              
   $                    `	            
   $  5                  X	            
   $                     P	            
   $  (                 (       
                   #      
   $        0                  9      
   $  $      F            x      _      
   $  "1      l                        
   $  )                              
   $  $                 @             
   $                    `            
   $  n)                               
   $  92            
   $  -                   p             
   $   5                   l      (       
   $  "      6             h      ?       
   $  3      M             d      V       
   $  h      d             `      m       
   $  
      r       
   $                     X             
   $  +                   P             
   $  !                   H             
   $  I                   @             
   $  0      *!      
   $        8!            8      [!      
   $  c      !      
   $  K/      !            0      !      
   $  2      !            )      !      
   $  K      !      
   $        !      
   $        !            (      !      
   $  	      !            (       "      
   $        "                    +"      
   $  (      9"                   B"      
   $  (      P"      
   $  0      ^"      
   $  0      l"      
   $        z"      
   $        "      
   $   *      "                   "      
   $  4(      "      
   $  &      "      
   $        "      
   $        "      
   $  ,      "      
   $        "      
   $  2      #      
   $  <.      #      
   $  8      #      
   $        ,#      
   $   "      :#      
   $        H#      
   $  ~      W#      
   $  /3      d#      
   $  V      r#                   #      
   $        #                   #      
   $  "      #                    #      
   $  4      #                  #      
   $        #                  #      
   $  &      #                  #      
   $  S      $            @      $      
   $        $                   "$      
   $        0$                    9$      
   $  C      F$      
   $        R$            d      y$      
   $        $            `d      $      
   $        $      
             $      
              $      
   $        $                   $      
      1       $      
      -       %      
             %      
      j        %      
      ~      $%      
      R      3%      
            7%      
      p      F%      
      h      J%      
      @      V%      
   $  -
      ^%             K      u%      
   $        %      
            %      
            %      
      X      %      
      P      %      
   $        %      
            %      
            %      
      (	      %      
      "	      %            3K      %            3K      %      
      s	      %      
      q	      %      
      	      &      
      	      &      
      	      &      
      	      &            QK      $&            QK      A&      
      	      E&      
      	      N&      
      
      R&      
      
      [&      
      8
      _&      
      6
      i&            pK      s&      
   "         &      
      _
      &      
      [
      &      
      
      &      
      
      &      
      
      &      
      
      &            ~K      &            K      &      
   "  `      &      
      
      &      
      
      &      
            &      
            &      
      M      &      
      K      '            K      '      
   "        '      
      r      !'      
      p      *'      
            .'      
            7'      
            ;'      
            A'            QK      _'            K      '      
   $  U1      '            J      '      
            '      
            '      
            '      
            '      
      h      '      
      \      '      
            '      
            '      
   "  @      
(      
            (      
            (            dJ      D(            |J      N(      
   "  p      _(      
            c(      
            l(      
            p(      
            y(      
      @      }(      
      <      (            J      (            J      (            J      (      
   "        (      
            (      
            (      
            (      
            )      
            )      
            
)            J      /)            J      9)      
   "        J)      
      $      N)      
             W)      
      d      [)      
      b      d)      
            h)      
            m)            J      {)            J      )      
   $  #      )            I      )      
   $  u      )      
   $  |      )      
   $        *            `I      "*      
   $  D1      .*      
            2*      
            7*      
   $        C*      
            G*      
            L*      
   $  +      X*      
      \      \*      
      R      a*      
   $        m*      
            q*      
            v*      
   $  '7      *      
      <      *      
      4      *            dI      *      
   "        *      
            *      
            *      
            *      
            *            I      *            I      *            I      +            I      B+      
   $  5      N+            P@      p+      
            t+      
            +      
            +      
            +      
            +      
            +      
            +      
            +      
   $        +      
            +      
            +            pF      +      
   $  !      +            F      ,            @      ,            @      3,      
            7,      
            <,            @      Y,            @      c,      
   "        t,      
      6      x,      
      4      },            @      ,            A      ,            A      ,      
      ]      ,      
      Y      ,            A      ,            5A      ,            5A      -      
            -      
            -            DA      :-            [A      D-            [A      a-      
            e-      
            j-            jA      -            A      -            A      -      
            -      
            -            A      -            A      -            A      -      
            -      
            .            A      !.            B      +.            B      H.      
      )      L.      
      '      Q.            B      n.            )B      x.            )B      .      
      N      .      
      L      .            8B      .            PB      .            PB      .      
      s      .      
      q      .            _B      /            wB      /            wB      //      
            3/      
            8/            B      U/            B      _/            B      |/      
            /      
            /            B      /            B      /            B      /      
            /      
            /            B      /            B      /      
   "         0      
   "         0      
      	      0      
            0      
      E       0      
      ?      )0      
   "        60      
            :0      
            C0            F      M0            F      j0      
      r      n0      
      p      s0            F      0            G      0            G      0      
            0      
            0            "G      0            DG      0      
   "        0      
            0      
            1      
   "        1      
            1      
      r       1            DG      *1            DG      G1      
            K1      
            T1      
      A      X1      
      ;      ]1            UG      1            `G      1            `G      1      
            1      
            1      
            1      
            1            qG      1            G      1            G      2      
            2      
            2      
      A      2      
      ?      %2      
      o      )2      
      m      .2            G      E2                  U2            G      m2            H      2            H      2            ;I      2         ]         2            F      2         C   ]      2            G       3         C   o      
3            8G      3         C         &3            'C      73         C   V      G3            QC      Q3      
   "  @      ^3      
   "  @      g3      
            k3      
            t3            fC      ~3            fC      3      
            3      
            3            uC      3            hE      3      
   "        3            H      3      
             3      
            3            H      4            H      #4            I      84            yE      M4         C         ^4            E      y4         C         4            E      4            E      4      
   "        4      
   "        4      
      Z      4      
      V      4            E      4         C         4            E      4         C         5            E      #5         C         -5            F      H5         C         R5            "F      m5         C         w5            PF      5         ]         5            \F      5            H      5            ]C      5         C         5            H      5         C         5            C      5            C      6            C      *6      
            .6      
            76            0D      L6      
            P6      
            \6            F      f6            F      6      
      4       6      
      2       6            F      6            F      6            F      6            @      6         C          7            @      7            @      #7         C         -7            @      B7         C   +      L7            @      a7         C   =      k7            0A      7         C   N      7            VA      7         C   b      7            qA      7            }A      7         C   w      7            A      7         C         7            A      8            A      8            A      #8         C         -8            A      B8         C         L8            B      Y8            $B      n8         C         x8            ?B      8            KB      8         C         8            fB      8            rB      8         C         8            B      8            B      8         C         8            B      	9            B      9         C   *      (9            B      =9         C   @      G9            D      _9            D      l9            D      9         C         9            E      9         C         9            5E      9            RE      9            `E      9            EI      9      
   $  O7      :      
   $  1      4:      
   $  x      F:      
   $  1      S:      
   $  ,      a:      
   $  :      ~:      
   $  &      :      
   $  ]      :      
   $  %      :      
   $  /      ;      
   $        3;      
   $  +      ?;            @@      R;      
   $        Z;            0@      m;      
   $  (8      y;             @      ;      
   $  0+      ;            @      ;      
   $        ;      
   $  L"      ;            ?      ;      
   $        ;      
   $        ;            ?      	<      
   $        <      
   $  5       !<            ?      8<      
   $  P      H<      
   $  /      P<            ?      g<      
   $  =      w<      
   $  3      <            p?      <      
   $  $      <      
   $  6      <            `?      <      
   $  P      <      
   $  w      <            P?      <      
   $  }       =      
      \       =      
      X       
=      
   $  I+      =            `Y      -=      
   $  D1      9=      
             ==      
             M=      
      !!      Q=      
      !      b=      
      !      f=      
      !      k=      
   $  E7      w=      
      ="      {=      
      /"      =      
   $  i      =      
   $  )      =      
   "        =      
   $  
      =      
   $  3      =            aZ      =      
      "      =      
      "      =            iZ      >            (_       >      
   $        ,>      
      #      0>      
      #      :>            @[      D>      
   "        U>      
      ($      Y>      
      $      b>      
      ($      f>      
      $      o>      
      $      s>      
      $      x>      
   "        >      
      %      >      
      %      >      
      0&      >      
      &      >      
      5'      >      
      +'      >      
      '      >      
      '      >      
      (      >      
      '      >      
      I)      >      
      /)      )?      
   "        A?            ]      Z?      
      W*      ^?      
      S*      c?            ]      u?            `_      ?      
      *      ?      
      *      ?            _      ?            _      ?            _      ?            c      ?      
   "        ?      
      +      ?      
      +      ?      
   "        @            c      @      
   "         @      
      +      $@      
      +      -@      
      +      1@      
      +      :@      
      	,      >@      
      ,      H@            c      R@            c      o@      
      1,      s@      
      /,      |@      
      W,      @      
      U,      @      
      },      @      
      {,      @            c      @            c      @            E[      @            t[      @            [      A            [      #A            [      HA            [      mA            "\      A            G\      A            \      A            `	      A            \      A            \      A            \      B            \      &B            b]      LB            y]      YB            ]      }B            _      B         ]         B            _      B            @`      B            S`      B            ``      B            o`      C            `      EC            `      RC            `      _C            `      C            `      C         ]         C            a      C            9a      C         C          C            a      C         ]   (      C            a      C            a      D         ]         D            <b      /D         C          9D            Kb      FD            \b      jD            tb      wD            b      D            b      D                   D            b      D            (c      D            Gc      D            Xc      E            ic      9E            zc      ]E            c      E            c      E         ]         E            c      E            d      E         ]   P      E            M^      E      
   "         E      
      ,      E      
      ,      E            M^       F      
   "  0      F      
      ,      F      
      ,      F            M^      $F            M^      =F      
      ,      AF      
      ,      JF            M^      TF            M^      mF      
      -      qF      
      -      zF      
      B-      ~F      
      @-      F            a^      F            (       F            a      F            a      F      
      h-      F      
      f-      F            a      F            a      G      
      -      G      
      -      G      
      -      G      
      -      G            a      )G                    :G            Y      RG            Y      iG            Z      G            Z      G            ]      G            2^      G            ^      G            _      G            	`      G            )`      H         C         H            `      (H            a      HH            a      `H            b      H            b      H            =d      H            Zd      H      
   $        H            0;      H      
   $  D1      H      
      -      H      
      -      H      
   $  v      I      
      *.      I      
      .      
I      
   $        I      
      .      I      
      .      I      
   $  i      0I      
   $  )      AI      
   $  E7      MI      
      a/      QI      
      Q/      bI      
      (0      fI      
      0      kI      
   $        wI      
      0      {I      
      0      I      
   "        I      
   $  
      I      
   $  3      I            <      I      
      71      I      
      31      I            <      I      
   "        I      
   $        J      
      1      J      
      w1      J            {>      $J            >      2J            u;      ?J            ;      WJ            ;      wJ                    J            ;      J            ;      J                  J            <      J            @      J            !<      K                   K            =<      7K                  AK            <      RK            `	      \K            <      sK            <      K            <      K            <      K            >=      K            W=      K            s=      K                    
L            =      $L                  3L            =      ML                  \L            =      vL            @      L            =      L                   L            :>      L         ]         L            D>      L            >      L            >      M            >       M         C          *M            ?      ?M         C          IM            '?      ^M         ]         hM            5?      M            H?      M      
   $        M            :      M      
   $  D1      M      
      2      M      
      2      M            
;      M      
   $        M      
      a2      M      
      _2      M            ;      N            %;      N      
   $  J	      N            9      5N      
   $  D1      AN      
      2      EN      
      2      JN      
   $  !      VN      
      3      ZN      
      3      cN            :      mN      
   "  
      ~N      
      *3      N      
      (3      N      
   "  
      N            :      N      
   "        N      
      O3      N      
      M3      N      
      u3      N      
      s3      N      
      3      N      
      3      N            :      N      
   "  P      N      
      3      N      
      3      O      
      3      O      
      3      O      
      4      O      
      4      O            :      'O            :      HO            9      UO            9      bO            9      oO            :      O                   O            ::      O            :      O            :      O            :      O      
   $        O      
   $        O      
   $  D1      P      
   $        P      
   $  &      &P      
   $  S      3P      
   $        @P      
   $        MP      
   $        ZP      
   $  E7      P      
   $  v      P      
   $        P      
   $  i      P      
   $  )      P      
   $  $      P      
   $  !      P      
   $  
      P      
   $  3      Q      
   $        Q      
   $        Q            @9      1Q      
   $        9Q                   LQ      
   $        TQ                   kQ      
   $  !      wQ      
      G4      {Q      
      94      Q      
   $  e      Q      
      4      Q      
      4      Q      
   $  z5      Q      
      o5      Q      
      c5      Q      
   $        Q      
      6      Q      
      5      Q      
   $        Q      
      6      Q      
      6      Q      
   $        Q      
      ^7      Q      
      X7      Q      
   $        Q      
      7      Q      
      7      Q            C      R         ]   P      &R            O      =R                  [R         ]         eR                  |R                  R            
      R         ]         R                  R      
   $        R                  R      
   $        R      
      8      R      
      7      S      
   $  !      S      
      8      S      
      8      S      
   $        ,S                  6S                  SS      
      8      WS      
      8      `S      
      9      dS      
      
9      mS      
      69      qS      
      29      vS                  S         ]          S                  S            3      S            <      S            d      S         ]   p       T            m      &T                  >T                  UT                  jT         C   R       tT                  T      
   $        T                  T      
   $        T      
      y9      T      
      o9      T      
   $        T      
      9      T      
      9      T      
   $  !      T      
      :      T      
      :      T                  U                   U      
      ;      $U      
      ;      -U      
      B;      1U      
      @;      :U      
      j;      >U      
      f;      CU                  dU                  U            X      U            s      U         C           U      
   $  7      U      
   $        U      
   $        U      
   $  1      V      
   $  5      V      
   $        V      
   $  2      ,V      
   $  R!      ;V      
   $        CV            8      ZV      
   $        fV      
      ;      jV      
      ;      oV      
   $        {V      
      ;      V      
      ;      V      
   $  X$      V                  V      
   $        V      
      ;      V      
      ;      V      
   $        V      
      *<      V      
      $<      V            	      V            	      W      
      u<      W      
      s<      W      
      <      W      
      <      "W      
      <      &W      
      <      -W      
   $        5W                   LW      
   $        \W      
   $  q      hW            	      W      
   $  5      W      
      <      W      
      <      W      
      .=      W      
      "=      W      
   $  .      W      
   $  1      W            
      X            l
      0X            s
      NX      
   $        VX            8      |X      
   $        X      
   $  !      X      
   $        X      
   $  ,      X             7      X      
   $  D)      X      
      =      X      
      =      X      
   $  
      X      
      =      X      
      =      Y      
   $        Y      
      X>      #Y      
      T>      5Y            M7      TY            [7      rY            7      Y      
   $  %      Y      
   $  D)      Y      
   $  "      Y      
   $  '      Y      
   $        Y      
   $  K#      Y      
   $  K
      Y      
   $  3      Z      
   $        "Z            5      9Z      
   $  e      EZ      
      >      IZ      
      >      NZ      
   $  
      ZZ      
      J?      ^Z      
      :?      oZ      
      @      sZ      
      ?      Z      
      P@      Z      
      J@      Z      
   $        Z      
   $  6      Z      
      @      Z      
      @      Z            R6      Z            l6      Z            6      [            6      @[            6      ^[            6      k[            6      x[            6      [            6      [      
   $        [      
   $  D1      [      
   $        [      
   $  $      [      
   $  <6      \            2      "\      
   $  D1      .\      
      @      2\      
      @      7\      
   $  a      C\      
      /A      G\      
      'A      L\      
   $        X\      
      A      \\      
      A      a\      
   $  )	      m\      
      A      q\      
      A      v\      
   $  	      \      
      LB      \      
      FB      \      
      B      \      
      B      \      
   "  P	      \      
      B      \      
      B      \      
   "  	      \      
      (C      \      
      $C      \            3      \      
   $  $      \      
      dC      ]      
      ^C      ]            4      ]            4      )]      
   "  	      :]      
      C      >]      
      C      G]      
      C      K]      
      C      T]      
      +D      X]      
      )D      ]]            14      }]            I4      ]      
   "  	      ]      
      TD      ]      
      PD      ]      
      D      ]      
      D      ]      
      D      ]      
      D      ]            S4      ]            33      ]            3      ^      
   $        ^            '      &^      
   $  D1      9^            _(      C^      
   "        P^      
      D      T^      
      D      ]^      
      )E      a^      
      'E      j^      
      QE      n^      
      ME      u^      
   $  6      ^            '      ^      
   $  D1      ^      
      E      ^      
      E      ^      
      E      ^      
      E      ^      
      KF      ^      
      CF      ^            '      ^      
   $         ^            P'      _      
   $  D1      "_      
      F      &_      
      F      6_      
      G      :_      
      F      K_      
      kG      O_      
      cG      T_            '      q_      
   $  !      }_            0       _      
   $  I*      _      
      G      _      
      G      _      
      6H      _      
      .H      _      
      H      _      
      H      _      
      5I      _      
      )I      _      
   $        _      
      I      _      
      I      `      
      J      
`      
      J      `            {        `      
   $  K      ,`            0%      C`      
   $  D1      O`      
      J      S`      
      J      c`      
      K      g`      
      K      x`      
      L      |`      
       L      `      
      lL      `      
      hL      `      
      L      `      
      L      `      
   $  4      `      
      L      `      
      L      `      
      9M      `      
      5M      `      
   $        `      
      }M      `      
      oM      `      
   "  @      `      
   $        a      
      &N      a      
      N      a      
   $  /      !a      
      N      %a      
      N      *a      
   $        6a      
      N      :a      
      N      ?a      
   $  6      Ka      
      4O      Oa      
      &O      Ta      
   $        `a      
      O      da      
      O      ia      
   $        ua      
      P      ya      
      P      ~a            x&      a      
      cP      a      
      aP      a            &      a      
   $        a      
      P      a      
      P      a            &      a            c&      a      
   "  p      b      
      P      b      
      P      b      
      Q      b      
      P      (b      
      /Q      ,b      
      -Q      2b            &      [b            %      b            E'      b      
   $  |      b             #      b      
   $  D1      b      
      ^Q      b      
      RQ      b      
      Q      b      
      Q      b      
      R      b      
      }R      c      
      JS      c      
      >S      c      
      S      c      
      S      !c      
   $  4      -c      
      NT      1c      
      BT      Bc      
      T      Fc      
      T      Kc      
   $        Wc      
      5U      [c      
      #U      `c      
   $  C#      rc            #      c      
   $  /      c      
      U      c      
      U      c      
   $  6      c      
      cV      c      
      [V      c      
   $        c      
      V      c      
      V      c      
   $        c      
      V      c      
      V      c            $      c                   d            $      4d                   >d            $      Rd            $%      qd      
   $        }d                    d      
   $        d                   d      
   $  D1      d      
      EW      d      
      3W      d      
   $  `      d      
      X      d      
      X      d      
   $  /7      
e      
      4X      e      
      0X      e      
   $        $e      
   "  `      ;e      
   "  `      De      
      rX      He      
      lX      Qe      
      X      Ue      
      X      ^e      
   "        ke      
      X      oe      
      X      xe      
      RY      |e      
      JY      e      
      Y      e      
      Y      e      
      Y      e      
      Y      e      
      *Z      e      
      &Z      e      
      dZ      e      
      `Z      e      
   "        e      
      Z      e      
      Z      e      
   "        e      
      Z      e      
      Z      e            e"      e            !      f            d!      (f      
   $  U      :f      
   $  D1      Gf      
   $  `      _f      
   $  4      xf      
   $  /      f      
   $        f      
   $  6      f      
   $        f      
   $        f      
   $        f      
   $  0      f      
   $  D1      g      
   $         g      
   $  1      -g      
   $        Eg      
   $        Rg      
   $  f      yg      
   $  
      g      
   $  K      g            (      g      
   $  D1      g      
      e[      g      
      Y[      g      
      [      g      
      [      g      
      o\      g      
      g\      g            (      h      
   "        h      
      \      h      
      \      (h      
      ]      ,h      
      ]      5h      
      h]      9h      
      f]      >h      
   "        Lh      
      ]      Ph      
      ]      Zh            )      qh            (      h            !)      h            ])      h      
   $  b'      h            p       h      
   $  D1      h      
   $  3      h      
      ]      h      
      ]      h      
   $        i      
      T^      
i      
      R^      i                   i      
   "         *i      
      y^      .i      
      w^      7i      
      ^      ;i      
      ^      Di      
      ^      Hi      
      ^      Oi      
   $        [i             2      ri      
   $  D1      ~i      
      ^      i      
      ^      i      
   $  |      i      
      _      i      
      _      i      
      y`      i      
      i`      i      
   $        i      
      7a      i      
      'a      i      
   $  3      i      
      a      i      
      a      i            U2      i      
   "   	      i      
      b      i      
      b      j      
      b      j      
      b      j      
      b      j      
      b      j            U2      6j            z2      Sj            2      zj            2      j      
   $  ,      j      
   $  D1      j      
   $        j      
   $  3      j      
   $        j      
   $        j      
   $  .      k      
   $        k      
   $  Y2      !k      
   $  -      -k            `      Dk      
   $  D1      Pk      
      c      Tk      
      c      Yk      
   $        ek      
      c      ik      
      c      nk      
   $        zk      
      c      ~k      
      c      k      
      dd      k      
      Xd      k      
   $  /       k      
      e      k      
      e      k                  k      
   "        k      
      ne      k      
      je      k      
      e      k      
      e      k                  l                   l      
   "        l      
      e      !l      
      e      *l      
      f      .l      
      f      7l      
      Af      ;l      
      =f      @l      
   "        Il      
      {f      Ml      
      wf      Vl                   `l                   }l      
      f      l      
      f      l      
      f      l      
      f      l      
      f      l      
      f      l                   l            !       l      
   $  <'      l                  l      
   $  D1       m      
      *g      m      
       g      	m      
   $        m      
      g      m      
      g      m      
   $        *m      
      h      .m      
      h      3m      
   $  P      ?m      
      th      Cm      
      jh      Tm      
      h      Xm      
      h      ]m      
   $  +      im      
      (i      mm      
       i      rm      
   $        ~m      
      i      m      
      i      m      
   $        m      
      i      m      
      i      m      
   $        m      
      j      m      
      j      m      
      j      m      
      j      m                  m      
   "         m      
      k      m      
      k      m      
      Tk      m      
      Pk      m      
      k      n      
      k      n                  $n                  Cn            (      Mn            (      jn      
      k      nn      
      k      sn            (      n      
      l      n      
      k      n            4      n                  n      
   $        n                  n      
   $  D1      n      
      Tl      n      
      Hl      o                  o                  +o      
      l      /o      
      l      4o                  No      
      m      Ro      
      m      Wo                  no      
   $  /      o      
   $  D1      o      
   $  g      o      
   $        o            0      o      
   $  D1      o      
   $  r*      o      
      ;m      o      
      7m      o      
      zm      o      
      tm      p      
   $        p                  (p      
   $  D1      4p      
      m      8p      
      m      =p                  Jp                  Wp                  dp            &      rp      
   $        zp                  p      
   $  D1      p      
      #n      p      
      n      p                  p      
   "        p      
      qn      p      
      on      p      
      n      p      
      n      p      
   $        p            /      q      
   $  D1      q      
      n      q      
      n      q            /      .q            /      Fq            /      fq            !0      {q      
   $  e4      q            .      q      
   $  D1      q      
      Do      q      
      8o      q            #/      q            P/      q            X/      q            m/      	r      
   $  67      r            W      ,r      
   $  D1      8r      
      o      <r      
      o      Ar      
   $  1      cr      
   $  .      xr            Y      r      
   "  P      r      
      wp      r      
      up      r            Y      r      
   "  `      r      
      p      r      
      p      r            Y      r            Y      r      
      p      r      
      p      r            Y      r            Y      s      
      p      s      
      p      $s      
      q      (s      
      q      -s            $Y      >s            (       Qs            W      is            X      s            FX      s            X      s            X      s            X      s            X      t            X      t            KY      9t            UY      Gt      
   $        St            `      jt      
   $  D1      zt      
   $        t            p      t                  t                   t      
   $  $)      t                  t      
   $  D1      t      
      Eq      t      
      ;q      t      
      q       u      
      q      u      
   $  ,      u      
      Mr      u      
      Kr      u                  (u      
   "         9u      
      rr      =u      
      pr      Fu      
      r      Ju      
      r      Yu            3      cu      
   "  @      tu      
      r      xu      
      r      u      
      r      u      
      r      u      
   "  @      u      
      s      u      
      	s      u            <      u                  u                  u      
      Es      u      
      Cs      u                  
v                  0v                  Cv            ]      Mv      
   "        ^v      
      js      bv      
      hs      kv      
      s      ov      
      s      tv            d      v         C   o       v                  v                  v            =      v            O      w            m      w                  &w      
   $  _0      .w                  Tw      
   $        `w                  sw      
   $         {w                  w      
   $        w                  w      
   "        w      
   $  ?      w      
      s      w      
      s      w                  w                  w                    w                  x                    x                  <x                  Xx                  mx                   |x                  x            3      x         C   y       x            K      x         C          x      
   $  	      x      
   $  D1      x      
   $        y      
   $  7      "y      
   $        @y      
   $  )!      _y      
   $  8      my      
   $  e2      y      
   $        y      
   $  m      y      
   $        y      
   $  D1      y      
   $  f      z      
   $        z      
   $  /7      z      
   $        +z      
   $  k       =z      
   $  D1      Jz      
   $  
      Xz      
   $        jz      
   $  D1      z      
   $        z      
   $        z      
   $  I*      z      
   $        z      
   $  >      z      
   $  D1      z      
   $        
{      
   $  =#      {      
   $         ${      
   $  0      1{      
   $        O{      
   $  ]      a{      
   $  D1      {      
   $        {      
   $  ~      {      
   $  I*      {      
   $  
      {             ,      {      
   $  D1      {      
      s      |      
      s      |      
      Pt      |      
      Ht      &|      
      t      *|      
      t      ;|      
      t      ?|      
      t      D|      
   $        U|            H,      p|            ,      |         ]         |            ,      |         C          |            ,      |      
   $        |      
   $  D1      	}      
   $  &      %}      
   $        7}      
   $  D1      D}      
   $  C#      R}                   [}      
   $  1      i}                    }      
   $  6      }             +      }      
   $  D1      }      
      Yu      }      
      Qu      }      
   $        }      
      u      }      
      u      }      
   $        }      
      %v      }      
      v      }      
   $  4      ~      
      uv      ~      
      qv      #~            q+      -~      
   "        >~      
      v      B~      
      v      K~      
      v      O~      
      v      Y~            +      ~         C          ~            ;+      ~            E+      ~            [+      ~            c+      ~            +      ~            +      ~            +            
   $  i                        $      
   $  	      6      
   $  *      \      
   $        {      
   $  .            
   $              
   $  D1            
   $  f            
   $              
   $              
   $              
   $  D1      4      
   $        A      
   $        P      
   $        ^      
   $  D1      w      
   $              
   $  R(            
   $  #                  
      ̀      
   $  0      ؀      
      w      ܀      
      w            
   $              
      jw            
      fw            
   $  /7            
   $              
      w            
      w            
   $  +      &      
      x      *      
      x      /      
   $  6      ;      
      Sx      ?      
      Gx      D      
   $  	      P      
      x      T      
      x      Z      
   $  '      x      
   $  1            
   $              
   $  0            
   $  t
            
   $        ́      
   $              
   $  x            
   $  3            
   $              
   $        &            0	      =      
   $  D1      I      
      y      M      
      y      R      
   $        ^      
      Fz      b      
      @z      q      
      z      u      
      z      z            H	            
   $  D3            
   $  D1      ł      
   $        ׂ      
   $  D1            
   $              
   $              
   $              
   $  q      *      
   $        7      
   $  f      Q      
   $  +      p      
   $  1            
   $              
   $  "      ă      
   $  D1      ҃      
   $              
   $  2      
            	      ,      
      z      0      
      z      5      
   $  $      A      
      {      E      
      {      V      
      &|      Z      
       |      _            	                  	            
   $  6            
   $  3            
   $        ҄      
   $  G       ܄      
   $  "                  0            
   $  )            
      w|            
      o|            
   $  m+            
      |             
      |      5            `      X                  p                                          
   $  [(                         Ѕ      
   $  m-      ؅                          
   $  P             
   $  3                  @      ,      
   $  "      8      
      E}      <      
      =}      A      
   $        M      
      }      Q      
      }      V            V      n            w               C   [             
   $  *                  @            
   $        ʆ      
      ~      Ά      
      ~      ކ      
      ~            
      ~            
      \            
      H      
      
   $  D            
      6            
      0      .            0      e                  o      
   "  P            
                  
                  
                  
                  
      ܀            
      ڀ                        ̇         ]           ۇ            c                  c            
                  
                  
      /            
      -            
      W            
      U      $                  N         C   "       Y            B      v            O                  S            
   "              
      ~            
      z            
                  
            ˈ      
            ψ      
            Ԉ            X                                                
            #      
            ,      
      G      0      
      E      9      
      n      =      
      l      B                  j         C   2       ~                                           
   "              
                  
                  
                  
            ĉ      
            ȉ      
            ͉                           C   8                               
   "              
      "      #      
             ,      
      P      0      
      N      5            )      K         C   F       \                  i                  w      
   $              
   $  D1            
   $              
   $  -            
   $  /            
   $        ˊ      
   $  >      ܊      
   $              
   $  /            
   $  0            
   $  +            
   $               
   $        *      
   $        7      
   $        H      
   $         T      
   $        a      
   $  =      r      
   $         ~      
   $  f3            
   $              
   $  .            
   $               
   $              
   $        ͋      
   $  g
      ދ      
   $               
   $              
   $              
   $  m            
   $  p             
   $        ,      
   $  0      ?      
   $        P      
   $  p      \      
   $        j      
   $  J            
   $              
   $              
   $  5            
   $  .      ֌      
   $              
   $              
   $  	            
   $              
   $  A-      (      
   $        5      
   $  r7      I      
   $        Z      
   $        f      
   $  %      t      
   $  91            
   $  -            
   $  /            
   $  -                        ύ      
            Ӎ      
      t      ܍      
                  
                  
      H            
      B                               
   "                
                  
                  
                  
            '      
      @      +      
      <      0      
   "  0       9      
      |      =      
      v      F                  P                  m      
      ǅ      q      
      Ņ      z      
            ~      
                  
                  
                                                Ŏ            0                  @                  @            
      6            
      4      !            G      9            Q      L            w      V            w      v                        
      c            
      Y            
      ߆            
      Ն            
      [            
      Q            
      ه            
      ͇      ŏ      
      m      ɏ      
      a      ҏ      
            ֏      
                                          e                        +                  5      
   "  `       B                  P                  g                  y                        
      [            
      S            
                  
                  
      &            
            Đ      
            Ȑ      
                  
                  
                  
      X            
      R                  '                  '      $      
            (      
            1      
      ʋ      5      
      ȋ      >      
            B      
            G            <      l                  v      
   "               
      ,            
      *            
      S            
      Q            
      z            
      v                        ϑ            F      ّ      
   "               
                  
                        N                  x             
   "         1      
      ٌ      5      
      ׌      >      
             B      
            K      
      (      O      
      $      Y                  c      
   "  P      t      
      e      x      
      a            
                  
                  
      ͍            
      ˍ                                                
   "        ˒      
            ϒ      
            ؒ      
            ܒ      
                                          k                        (         C          2                  P                  {                                                9                        ؓ      
      C      ܓ      
      ?             
   "              
   "        $      
            (      
      |      1      
      V      5      
      J      >      
            B      
      ؏      K      
      v      O      
      p      X      
   "        e      
            i      
            r      
            v      
            {                              z                        ؔ                              )            
            	      
      	            
                  
                  
      ?      #      
      1      T            )      ^            )      {      
                  
      ޒ            
      5            
      1            
      q            
      m                  )            
                  
            ɕ      
      ԓ      ͕      
      ̓      ֕      
      <      ڕ      
      4            
                  
                  
      Ô            
                        {*            
   "         *      
            .      
            7      
      "      ;      
             D      
      H      H      
      F      Q      
      n      U      
      l      Z      
   "         h      
            l      
            u      
      Ε      y      
      ̕      ~            *                  D*            
   "  p            
            Ö      
            ̖      
      0      Ж      
      .      ٖ      
      V      ݖ      
      T                  )                  *                  *      8            *      J            ,      e      
            i      
      y      |            ,            
   "              
                  
      y            
                  
                  
                  
                  
   "        ̗      
      M      З      
      G      ٗ      
            ݗ      
                         -            
   "  @            
      ԙ            
      ҙ            
                  
                        -      7            {-      A            {-      ^      
      #      b      
            k      
      ^      o      
      \      t            {-            
                  
                        -                  r-      Ҙ            ].      ߘ            .                  .                  -      	      
   "  p            
                  
            #      
   "  p      ,      
            0      
            9            -      C            -      `      
            d      
            m      
            q      
            v            -                  -                  -                  <.      ۙ            C.                  R.                  .      %         ]   X      ;            x.      E            x.      b      
      ٛ      f      
      ӛ      k            x.                  .               ]   8                  .                  00      ך      
      1      ۚ      
      %            
      ɜ            
                  
                  
            "            0      ,      
   "        =      
      0      A      
      (      J      
            N      
            W      
            [      
            `      
   "        i      
      B      m      
      6      v      
      ɟ      z      
      ş            
      	            
                  
                  
      {            
                  
                  
      J            
      D                  0      ƛ      
   "        ܛ      
                  
                  
                  
                        1                  1            
            "      
            +      
            /      
            8      
      /      <      
      -      A            1      d            c1      |            1                  1                  4            
      `      Ü      
      R      ̜      
      	      М      
            ٜ      
            ݜ      
                  
   "  
            
      /            
      #      
             5      #      
            '      
            1            >5      J      
      F      N      
      @      S            g5      l            q5      v      
   "  P
            
                  
                  
                  
                  
                  
      ޥ                  5      ǝ             7            
                  
                  
      ]            
      W                  7      =            7      X      
            \      
            e      
            i      
            r      
            v      
                        7            
   "  
            
      ?            
      5            
                  
                  
      3            
      -                  7      ֞            8                  '8                  68                  @8                  8      (            K      C      
            G      
      |      P      
      <      T      
      :      b            ,L      l      
   "        }      
      c            
      _            
                  
                  
      ת            
      Ӫ            
   "              
                  
                        0L                  0L      ݟ      
      I            
      G            
      n            
      l            
                  
                         =L      !            HL      4            L      >      
   "         O      
            S      
            X      
   "         a      
            e      
            n      
      2      r      
      *      {            L                  L            
                  
                  
                  
                        L      Ѡ      
      ۬      ՠ      
      ٬                  8M                  8M            
                   
                  
      %            
      #      !      
      J      %      
      H      *            @M      ?      
      q      C      
      m      L            @M      V            @M      s      
            w      
                  
      έ            
      ̭            
                  
                        NM                  YM      ʡ            M      ԡ      
   "              
                   
                  
                  
                  
   "              
                  
                  
      ^            
      T      '            M      1            M      N      
      ϯ      R      
      ͯ      [      
            _      
            h      
            l      
            q            M                  M                  M            
      D            
      B            
      i            
      g      Ȣ      
            ̢      
            Ѣ            M            
                  
                        M                  N                  N      <      
      ް      @      
      ܰ      I      
            M      
            V      
      +      Z      
      )      _            N      y            !N                  !N            
      S            
      Q            
      x            
      v            
                  
                        !N      ԣ      
      ȱ      أ      
      Ʊ      ݣ            8N                  yO            
   "               
            "      
            '      
   "         0      
            4      
            =      
            A      
            J            O      _      
      @      c      
      >      l      
      e      p      
      c      |            OP                  OP            
                  
                        OP            
            Ť      
            Τ            OP      ؤ      
   "  0            
      Գ            
      ҳ            
   "  0            
                  
                  
      "            
                         kP      !      
   "  p      2      
      G      6      
      E      ;      
   "  p      D      
      n      H      
      l      Q      
            U      
            `            yP      j      
   "        {      
                  
                  
   "              
                  
      ߴ            
      
            
                        P            
   "        ĥ      
      C      ȥ      
      A      ͥ      
   "        ֥      
      j      ڥ      
      h            
                  
                        P            
   "  `            
                  
                  
   "  `            
      ޵      #      
      ܵ      ,      
            0      
            ;            P      E      
   "        V      
      +      Z      
      )      _      
   "        h      
      R      l      
      P      u      
      {      y      
      w                  P            
   "              
                  
                  
   "              
      ۶            
      ٶ            
            ¦      
             ͦ            P      צ      
   "  `            
      (            
      &            
   "  `            
      O            
      M            
      v            
      t                  P             
   "        -      
            1      
            6      
   "        ?      
      ÷      C      
            L      
            P      
            ]            Q      {            Q            
      '            
      #                  "Q            
      a            
      _      ç      
            ǧ      
            Ч            3Q      ڧ            3Q            
                  
                        3Q            
      ݸ            
      ۸            
            "      
             .            bQ      C      
      +      G      
      %      P      
      x      T      
      v      ]            Q      g      
   "        x      
            |      
                  
   "              
      ۹            
      ׹            
                  
                        Q            
   "  0      ¨      
   "  0      Ш      
      :      Ԩ      
      8      ߨ            Q            
   "  p            
   "  p      	      
      _            
      ]                  Q      "      
   "        0      
   "        >      
            B      
            P            \U      Z            \U      w      
            {      
                        \U            
      κ            
      ̺                  iU                  U      թ            pN                  N                  P      )         C         3            0V      Q         C   6      [            /W      u         ]                     vR                  vR            
                  
                  
            ê      
            Ȫ            vR      ݪ      
      =            
      ;                  R                  R            
   "        '      
      j      +      
      `      0      
   "        9      
            =      
      ٻ      F      
            J      
      ~      S      
            W      
            `      
      (      d      
            m      
            q      
            z      
      	      ~      
                  
      E            
      ?                  _S            
   "  p            
                  
                  
                  
            ɫ      
      ߾      ͫ      
      ۾      ֫      
            ګ      
                  
      C            
      =            
   "                    S            
   "         "      
            &      
            /      
            3      
            <      
            @      
            F            S      ^            S                  S                  S      Ǭ            T      Ѭ      
   "  `            
                  
                  
                  
                  
                   
            	      
      6            
      (            
   "              
                  
            (      
      *      ,      
            5            U      ?      
   "        U      
            Y      
            b      
   "        t      
      x      x      
      r                  hW                  hW            
                  
                        hW      ­            W                                                          3T      &            hW      =         ]         R            U      \            U      u            V                  V               ]                     T      Ϯ            \T                  yT                   T                  T      6            U      N            AV      [            iV      h            V               C                     V                  V               C         ɯ            V                  JW               C                     W      "         C         3            T      @            T      [         C          e            U      r            U               ]   8                  U               ]   p      İ            U      ΰ            U            
                  
                  
                  
                  
      6      	      
      4                  U            
   "        .      
      d      2      
      b      ;            U      E      
   "         R      
            V      
            _            U      i            U            
                  
                        U                  U            
                  
                  
            ñ      
            ȱ            5U      ٱ            (                   P      
         C   T                  WU      2         C         <            
W      V         C   &      m             P      w             P            
      *            
      (            
      T            
      P                   P            
            ò      
            Ȳ            .P      ߲            TW            
   $  =            
   $  Q            
   $  .            
   $  g            
   $  &            
   $  &            
   $  7            
   $  7            
   $  #             
   $  #      (      
   $        ,      
   $  	      4      
   $  b       8      
   $  b       A      
   $  >      E      
   $        M      
   $         Q      
   $         Z      
   $  0      ^      
   $  0      g      
   $  )      k      
   $  )      s      
   $        w      
   $              
   $              
   $              
   $  
            
   $  
            
   $  9            
   $  9            
   $  j*            
   $  j*            
   $              
   $              
   $  m	      ³      
   $  m	      ˳      
   $  (      ϳ      
   $  (      س      
   $  ]      ܳ      
   $  ]            
   $  %            
   $  %            
   $  V
            
   $  V
            
   $              
   $              
   $  Q      	      
   $  Q            
   $              
   $              
   $  /      "      
   $  /      +      
   $  k"      /      
   $  k"      8      
   $  $      <      
   $  $      D      
   $  9      H      
   $  9      P      
   $         T      
   $         \      
   $  M      `      
   $  M      i      
   $        m      
   $        u      
   $  +      y      
   $  +            
   $  )            
   $  )            
   $  ['            
   $  ['            
   $              
   $              
   $  +            
   $  +            
   $  G-            
   $  1	            
   $        ô      
   $        ̴      
   $        д      
   $        ٴ      
   $  7      ݴ      
   $  7            
   $              
   $              
   $  H4            
   $  H4            
   $  ,            
   $  ,      	      
   $  p            
   $  p            
   $  ^            
   $  ^      !      
   $  (      %      
   $  (      -      
   $  ^2      1      
   $  ^2      :      
   $        >      
   $        F      
   $  *      J      
   $  *      S      
   $  c7      W      
   $  c7      _      
   $        c      
   $        k      
   $  Z8      o      
   $  Z8      w      
   $  %      {      
   $  %            
   $  #            
   $  #            
   $  v            
   $  v            
   $              
   $              
   $              
   $        ĵ      
   $        ȵ      
   $        е      
   $  /      Ե      
   $  /      ܵ      
   $  _            
   $  _            
   $              
   $              
   $  2            
   $  2             
   $  +            
   $  r!            
   $  g
            
   $  *            
   $        "      
   $        *      
   $  f      .      
   $  f      6      
   $  $      :      
   $  $      B      
   $  	      F      
   $  	      O      
   $  e      S      
   $  e      \      
   $        `      
   $        h      
   $        l      
   $        t      
   $  -      x      
   $  :            
   $  4            
   $  4            
   $  )            
   $  )            
   $              
   $              
   $  J            
   $              
   $              
   $              
   $              
   $        ȶ      
   $        ̶      
   $        Զ      
   $  +      ض      
   $  +            
   $  v            
   $  v            
   $              
   $              
   $  3            
   $  3            
   $        
      
   $                           T                  +                    '-            (       -                    3                    8         ]          Q         C          p            (       s         C   o       v         C                   ]                    C   "       ,         C   2                C   8       5         C   F             
           ʿ                  I                              (              
                                                                  
                                              4                    H                     \             0                                                                               0      L                  `            0	                  	                  	                  
                        \                              0                        $                  L                              @                        X                                     0            @      X                  l                                                                                                      `                  p      ,                  @                  \            0      p                                                `                   p       4                                #                  0%      8            P'      L            '      `            '      t            (                  )                   +      P	             ,      	            ,      	            .      	            /      
            00      \
             2      
            2                   4      X            5                   7                   7                  7      $            8      8            8      L            @9      `            9                  :                  0;                   P?                  `?      (            p?      <            ?      P            ?      d            ?      x            ?                  @                   @                  0@                  @@                  P@                  `I      \            I      p            J                   K                  K      4            W      |            `Y                  `d                  d       .symtab .strtab .shstrtab .rela.text .data .bss .rela.gnu.build.attributes .text.hot .rela.gnu.build.attributes.hot .text.unlikely .rela.gnu.build.attributes.unlikely .text.startup .rela.gnu.build.attributes.startup .text.exit .rela.gnu.build.attributes.exit .rodata.str1.1 .rodata.str1.8 .rodata .rela.data.rel.local .rela.data.rel .rela.data.rel.ro.local .rela.debug_info .debug_abbrev .rela.debug_loc .rela.debug_aranges .debug_ranges .rela.debug_line .debug_str .comment .text.hot.zzz .text.unlikely.zzz .text.startup.zzz .text.exit.zzz .note.GNU-stack .note.gnu.property .rela.eh_frame .group                                                                  P                     @              :                   P                     T              :                   P                     l              :                   P                                   :                   P                                   :                                               d                                   @              @A     @G      :                    &                     `e      p	                              ,                     n                                    6                     n      t"                             1      @                          :   
                 L                    T                                     [                     T                                   V      @              P     0       :                    u                    (                                                          (                                         @                   0       :                                                                                                                                           @                   0       :                                        Ж                                                          Ж                                         @                   0       :                         2                                                      2                     /                            "                           D                              /                    `      8                               *     @                           :                    D                                                        ?     @                           :                    S                                                        N     @                    p      :                    k                                                        f     @               (     \     :   !                 w                     a                                                       -i                                       @                          :   $                                      /     0                                   @                    0       :   &                                      0     `                                                  lJ     R                                  @                    H       :   )                      0               }     8                                 0               7     .                                                 e                                                        e                                    u                    e                                    L                    e                                                          e                                                       e                                                       e                                                       e                                                       e                                                         e                                    .                    h                                    F                                                      A     @               (     (      :   8                                       x     4      ;                   	                      (     '                                                   P     W                             
#include "ruby.h"

#if defined( RUBY_VERSION_CODE ) && RUBY_VERSION_CODE < 180
#include "util.h"
#else
#include <ruby/util.h>
#include <ruby/version.h>
#endif

#include "lsapilib.h"
#include <errno.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>


#ifndef RUBY_API_VERSION_CODE
#define RUBY_API_VERSION_CODE (RUBY_API_VERSION_MAJOR*10000+RUBY_API_VERSION_MINOR*100+RUBY_API_VERSION_TEENY)
#endif

/* RUBY_EXTERN VALUE ruby_errinfo; */
RUBY_EXTERN VALUE rb_stdin;
RUBY_EXTERN VALUE rb_stdout;
#if defined( RUBY_VERSION_CODE ) && RUBY_VERSION_CODE < 180
RUBY_EXTERN VALUE rb_defout;
#endif

static VALUE orig_stdin;
static VALUE orig_stdout;
static VALUE orig_stderr;
#if defined( RUBY_VERSION_CODE ) && RUBY_VERSION_CODE < 180
static VALUE orig_defout;
#endif
static VALUE orig_env;

static VALUE env_copy;

static VALUE lsapi_env;

static int MAX_BODYBUF_LENGTH = (10 * 1024 * 1024);

#if RUBY_API_VERSION_CODE >= 20700
# if defined rb_tainted_str_new
#  undef rb_tainted_str_new
# endif
# define rb_tainted_str_new(p,l)  rb_str_new((p),(l))
#endif

/* static VALUE lsapi_objrefs; */

typedef struct lsapi_data
{
    LSAPI_Request * req;
    VALUE           env;
    ssize_t      (* fn_write)( LSAPI_Request *, const char * , size_t );
}lsapi_data;

static VALUE cLSAPI;

static VALUE s_req = Qnil;
static lsapi_data * s_req_data;

static VALUE s_req_stderr = Qnil;
static lsapi_data * s_stderr_data;
static pid_t s_pid = 0;

typedef struct lsapi_body
{
    char        *bodyBuf;  //we put small one into memory, otherwise, into a memory mapping file, and we still use the bodyBuf to access this mapping
    int	        bodyLen;	//expected length got form content-length
    int	        bodyCurrentLen;	//current length by read() readBodyToReqBuf
    int	        curPos;
}lsapi_body;

static lsapi_body	s_body;
static char sTempFile[1024] = {0};

/*
 * static void lsapi_ruby_setenv(const char *name, const char *value)
 * {
 *    if (!name) return;
 * 
 *    if (value && *value)
 *	    ruby_setenv(name, value);
 *    else
 *        ruby_unsetenv(name);
 } *        *
 */


static void lsapi_mark( lsapi_data * data )
{
    rb_gc_mark( data->env );
}
/*
 * static void lsapi_free_data( lsapi_data * data )
 * {
 *   free( data );
 } *        *
 */
static int add_env_rails( const char * pKey, int keyLen, const char * pValue, int valLen,
                          void * arg )
{
    char * p;
    int len;
    /* Fixup some environment variables for rails */
    switch( *pKey )
    {
        case 'Q':
            if ( strcmp( pKey, "QUERY_STRING" ) == 0 )
            {
                if ( !*pValue )
                    return 1;
            }
            break;
        case 'R':
            if (( *(pKey+8) == 'U' )&&( strcmp( pKey, "REQUEST_URI" ) == 0 ))
            {
                p = strchr( pValue, '?' );
                if ( p )
                {
                    len = valLen - ( p - pValue ) - 1;
                    /* 
                     *                valLen = p - pValue;
                     *p++ = 0;
                     */
                }
                else
                {
                    p = (char *)pValue + valLen;
                    len = 0;
                }
                rb_hash_aset( lsapi_env,rb_tainted_str_new("PATH_INFO", 9),
                              rb_tainted_str_new(pValue, p - pValue));
                rb_hash_aset( lsapi_env,rb_tainted_str_new("REQUEST_PATH", 12),
                              rb_tainted_str_new(pValue, p - pValue));
                if ( *p == '?' )
                    ++p;
                rb_hash_aset( lsapi_env,rb_tainted_str_new("QUERY_STRING", 12),
                rb_tainted_str_new(p, len));
            }
            break;
        case 'S':
            if ( strcmp( pKey, "SCRIPT_NAME" ) == 0 )
            {
                pValue = "/";
                valLen = 1;
            }
            break;
        case 'P':
            if ( strcmp( pKey, "PATH_INFO" ) == 0 )
                return 1;
        default:
            break;
    }
    
    /* lsapi_ruby_setenv(pKey, pValue ); */
    
    rb_hash_aset( lsapi_env,rb_tainted_str_new(pKey, keyLen),
                  rb_tainted_str_new(pValue, valLen));
    return 1;
}

static int add_env_no_fix( const char * pKey, int keyLen, const char * pValue, int valLen,
                           void * arg )
{
    rb_hash_aset( lsapi_env,rb_tainted_str_new(pKey, keyLen),
                  rb_tainted_str_new(pValue, valLen));
    return 1;
}

typedef int (*fn_add_env)( const char * pKey, int keyLen, const char * pValue, int valLen,
                           void * arg );

fn_add_env s_fn_add_env = add_env_no_fix;

static void clear_env()
{
    /* rb_funcall( lsapi_env, rb_intern( "clear" ), 0 ); */
    rb_funcall( lsapi_env, rb_intern( "replace" ), 1, env_copy );
}

static void setup_cgi_env( lsapi_data * data )
{
    clear_env();
    
    LSAPI_ForeachHeader_r( data->req, s_fn_add_env, data );
    LSAPI_ForeachEnv_r( data->req, s_fn_add_env, data );
}

static VALUE lsapi_s_accept( VALUE self )
{
    int pid;
    if ( LSAPI_Prefork_Accept_r( &g_req ) == -1 )
        return Qnil;
    else
    {
        if (s_body.bodyBuf != NULL)
            free (s_body.bodyBuf);
        
        s_body.bodyBuf = NULL;
        s_body.bodyLen = -1;
        s_body.bodyCurrentLen = 0;
        s_body.curPos = 0;    
        
        pid = getpid();
        if ( pid != s_pid )
        {
            s_pid = pid;
            rb_funcall( Qnil, rb_intern( "srand" ), 0 );
        }
        
        setup_cgi_env( s_req_data );
        return s_req;
    }
}


static VALUE lsapi_s_accept_new_conn(VALUE self)
{
    if (LSAPI_Accept_Before_Fork(&g_req) == -1 )
        return Qnil;
    else
        return s_req;
}


static VALUE lsapi_s_postfork_child(VALUE self)
{
    LSAPI_Postfork_Child(&g_req);
    return s_req;
}


static VALUE lsapi_s_postfork_parent(VALUE self)
{
    LSAPI_Postfork_Parent(&g_req);
    return s_req;
}


/*
 * static int chdir_file( const char * pFile )
 * {
 *    char * p = strrchr( pFile, '/' );
 *    int ret;
 *    if ( !p )
 *        return -1;
 *p = 0;
 ret = chdir( pFile );
 *p = '/';
 return ret;
 }
 */

static VALUE lsapi_eval_string_wrap(VALUE self, VALUE str)
{
#if RUBY_API_VERSION_CODE < 20700
    if (rb_safe_level() >= 4)
    {
        Check_Type(str, T_STRING);
    }
    else
#endif
    {
        SafeStringValue(str);
    }
    return rb_eval_string_wrap(StringValuePtr(str), NULL);
}

static VALUE lsapi_process( VALUE self )
{
/*    lsapi_data *data;
    const char * pScriptPath;
    Data_Get_Struct(self,lsapi_data, data);
    pScriptPath = LSAPI_GetScriptFileName_r( data->req );
*/
    /*
     *   if ( chdir_file( pScriptPath ) == -1 )
     *   {
     *       lsapi_send_error( 404 );
     *   }
     *   rb_load_file( pScriptPath );
     */
    return Qnil;
}


static VALUE lsapi_putc(VALUE self, VALUE c)
{
    char ch = NUM2CHR(c);
    lsapi_data *data;
    Data_Get_Struct(self,lsapi_data, data);
    if ( (*data->fn_write)( data->req, &ch, 1 ) == 1 )
        return c;
    else
        return INT2NUM( EOF );
}


static VALUE lsapi_write( VALUE self, VALUE str )
{
    lsapi_data *data;
    int len;
    Data_Get_Struct(self,lsapi_data, data);
    /*    len = LSAPI_Write_r( data->req, RSTRING_PTR(str), RSTRING_LEN(str) ); */
    if (TYPE(str) != T_STRING)
        str = rb_obj_as_string(str);
    len = (*data->fn_write)( data->req, RSTRING_PTR(str), RSTRING_LEN(str) );
    return INT2NUM( len );
}

static VALUE lsapi_print( int argc, VALUE *argv, VALUE out )
{
    int i;
    VALUE line;
    
    /* if no argument given, print `$_' */
    if (argc == 0)
    {
        argc = 1;
        line = rb_lastline_get();
        argv = &line;
    }
    for (i = 0; i<argc; i++)
    {
        if (!NIL_P(rb_output_fs) && i>0)
        {
            lsapi_write(out, rb_output_fs);
        }
        switch (TYPE(argv[i]))
        {
            case T_NIL:
                lsapi_write(out, rb_str_new2("nil"));
                break;
            default:
                lsapi_write(out, argv[i]);
                break;
        }
    }
    if (!NIL_P(rb_output_rs))
    {
        lsapi_write(out, rb_output_rs);
    }
    
    return Qnil;
}

static VALUE lsapi_printf(int argc, VALUE *argv, VALUE out)
{
    lsapi_write(out, rb_f_sprintf(argc, argv));
    return Qnil;
}

static VALUE lsapi_puts _((int, VALUE*, VALUE));

#if RUBY_API_VERSION_CODE >= 10900
static VALUE lsapi_puts_ary(VALUE ary, VALUE out, int recur )
{
    VALUE tmp;
    long i;
    
    if (recur)
    {
        tmp = rb_str_new2("[...]");
        rb_io_puts(1, &tmp, out);
        return Qnil;
    }
    for (i=0; i<RARRAY_LEN(ary); i++) 
    {
        tmp = RARRAY_PTR(ary)[i];
        rb_io_puts(1, &tmp, out);
    }
    return Qnil;
    
}
#else
static VALUE lsapi_puts_ary(VALUE ary, VALUE out)
{
    VALUE tmp;
    int i;
    
    for (i=0; i<RARRAY_LEN(ary); i++)
    {
        tmp = RARRAY_PTR(ary)[i];
        if (rb_inspecting_p(tmp))
        {
            tmp = rb_str_new2("[...]");
        }
        lsapi_puts(1, &tmp, out);
    }
    return Qnil;
}
#endif

static VALUE lsapi_puts(int argc, VALUE *argv, VALUE out)
{
    int i;
    VALUE line;
    
    /* if no argument given, print newline. */
    if (argc == 0)
    {
        lsapi_write(out, rb_default_rs);
        return Qnil;
    }
    for (i=0; i<argc; i++)
    {
        switch (TYPE(argv[i]))
        {
            case T_NIL:
                line = rb_str_new2("nil");
                break;
            case T_ARRAY:
#if RUBY_API_VERSION_CODE >= 10900
                rb_exec_recursive(lsapi_puts_ary, argv[i], out);
#else
                rb_protect_inspect(lsapi_puts_ary, argv[i], out);
#endif
                continue;
            default:
                line = argv[i];
                break;
        }
        line = rb_obj_as_string(line);
        lsapi_write(out, line);
        if (*( RSTRING_PTR(line) + RSTRING_LEN(line) - 1 ) != '\n')
        {
            lsapi_write(out, rb_default_rs);
        }
    }
    
    return Qnil;
}


static VALUE lsapi_addstr(VALUE out, VALUE str)
{
    lsapi_write(out, str);
    return out;
}

static VALUE lsapi_flush( VALUE self )
{
    /*
     *    lsapi_data *data;
     *    Data_Get_Struct(self,lsapi_data, data);
     */
    LSAPI_Flush_r( &g_req ); 
    return Qnil;
}

static VALUE lsapi_getc( VALUE self )
{
    int ch;
    /*
     *    lsapi_data *data;
     *    Data_Get_Struct(self,lsapi_data, data);
     */
#if RUBY_API_VERSION_CODE < 20700
    if (rb_safe_level() >= 4 && !OBJ_TAINTED(self))
    {
        rb_raise(rb_eSecurityError, "Insecure: operation on untainted IO");
    }
#endif
    ch = LSAPI_ReqBodyGetChar_r( &g_req );
    if ( ch == EOF )
        return Qnil;
    return INT2NUM( ch );
}

static inline int isBodyWriteToFile()
{
    return ((s_body.bodyLen >= MAX_BODYBUF_LENGTH)? (1): (0));
}

//create a temp file and open it, if failed, fd = -1
static inline int createTempFile()
{
    int fd = -1;
    char *sfn = strdup(sTempFile);
    
    if ((fd = mkstemp(sfn)) == -1)
    {
        fprintf(stderr, "%s: %s\n", sfn, strerror(errno));
    }
    else
        unlink(sfn);
    
    free(sfn);
    return fd;
}

//return 1 if error occured!
//if already created, always OK (0)
static int createBodyBuf()
{
    int fd = -1;
    if (s_body.bodyLen == -1)
    {
        s_body.bodyLen = LSAPI_GetReqBodyLen_r(&g_req);
        //Error if get a zeor length, should not happen 
        if (s_body.bodyLen < 0)
        {
            //Wrong bode length will be treated as 0
            s_body.bodyLen = 0;
        }
        
        if (s_body.bodyLen > 0) 
        {
            if (isBodyWriteToFile())
            {
                //create file mapping
                fd = createTempFile();
                if (fd == -1)
                {
                    return 1;
                }
                if (ftruncate(fd, s_body.bodyLen) == 0)
                {
                    perror("ftruncate() failed. \n");
                    close(fd);
                    return 1;
                }
                s_body.bodyBuf = mmap(NULL, s_body.bodyLen, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
                if (s_body.bodyBuf == MAP_FAILED)
                {
                    perror("File mapping failed. \n");
                    close(fd);
                    return 1;
                }
                close(fd);  //close since needn't it anymore
            }
            else
            {
                s_body.bodyBuf = (char *)calloc(s_body.bodyLen, sizeof(char));
                if (s_body.bodyBuf == NULL)
                {
                    perror("Memory calloc error");
                    return 1;
                }
            }
        }
    }

    return 0;   
}

static inline int isAllBodyRead()
{
    return (s_body.bodyCurrentLen < s_body.bodyLen)? 0 : 1;
}

static inline int isEofBodyBuf()
{
    return (s_body.curPos < s_body.bodyLen) ? 0 : 1;
}
//try to read length as times pagesize (such as 8KB * N)
static int readBodyBuf(const int needRead)
{
    const int blockSize = 8192;
    char *buff = s_body.bodyBuf + s_body.bodyCurrentLen;
    int nRead;
    int readMore = (needRead + blockSize -1) / blockSize * blockSize;
    int remain = LSAPI_GetReqBodyRemain_r( &g_req );
    //Only when not enough left, needReadChange will be changed!!!
    if (remain < readMore) 
        readMore = remain;

    if ( readMore <= 0 )
        return 0;
    
    nRead = LSAPI_ReadReqBody_r(&g_req, buff, readMore);
    if ( nRead > 0 )
        s_body.bodyCurrentLen += nRead;

    return nRead;
}

static VALUE lsapi_gets( VALUE self )
{
    VALUE str;
    const int blkSize = 4096;
    int n;
    char *p = NULL;
    
#if RUBY_API_VERSION_CODE < 20700
    if (rb_safe_level() >= 4 && !OBJ_TAINTED(self))
    {
        rb_raise(rb_eSecurityError, "Insecure: operation on untainted IO");
    }
#endif
    if (createBodyBuf() == 1)
    {
        return Qnil;
    }   
    
    //comment:
    while((p = memmem(s_body.bodyBuf + s_body.curPos, s_body.bodyCurrentLen - s_body.curPos, "\n", 1)) == NULL) 
    {
        if (isAllBodyRead() == 1)
            break;
        //read one page and check, then reply
        readBodyBuf(blkSize);
    }
    
    p = memmem(s_body.bodyBuf + s_body.curPos, s_body.bodyCurrentLen - s_body.curPos, "\n", 1);
    if (p != NULL)
        n = p - s_body.bodyBuf - s_body.curPos + 1;
    else
        n = s_body.bodyCurrentLen - s_body.curPos;
    
    str = rb_str_buf_new( n );
#if RUBY_API_VERSION_CODE < 20700
    OBJ_TAINT(str);
#endif
    
    if (n > 0)
    {
        rb_str_buf_cat( str, s_body.bodyBuf + s_body.curPos, n );
        s_body.curPos += n;
    }
    
    return str;
}

static VALUE lsapi_read(int argc, VALUE *argv, VALUE self)
{
    VALUE str;
    int n;
    int needRead;
    int nRead;
    
#if RUBY_API_VERSION_CODE < 20700
    if (rb_safe_level() >= 4 && !OBJ_TAINTED(self))
    {
        rb_raise(rb_eSecurityError, "Insecure: operation on untainted IO");
    }
#endif
    if (createBodyBuf() == 1)
    {
        return Qnil;
    }
    
    //we need to consider these 4 cases:
    //1, need all data since argc == 0, we may have all data 2, or not
    //3, need a length of data (argv >= 1), we may have enough data already read, 4, or not
    if (argc == 0)
        n = s_body.bodyLen - s_body.curPos;
    else
    {
        n = NUM2INT(argv[0]); //request that length from currentpos
        if (n < 0)
            return Qnil;
        if (n > s_body.bodyLen - s_body.curPos)
            n = s_body.bodyLen - s_body.curPos;            
    }
    needRead = s_body.curPos + n - s_body.bodyCurrentLen;
    if (needRead < 0)
        needRead = 0;
    
    str = rb_str_buf_new( n );
#if RUBY_API_VERSION_CODE < 20700
    OBJ_TAINT(str);
#endif
    if (n == 0)
        return str;
    
    //copy already have part first
    if (n - needRead != 0)
    {
        rb_str_buf_cat( str, s_body.bodyBuf + s_body.curPos, n - needRead);
        s_body.curPos += (n - needRead);
    }
    
    if (needRead > 0)
    {
        //try to read needRead, but may be less (changed) when read the end of the data
        nRead = readBodyBuf(needRead);
        if (nRead > 0)
        {
            n = ((nRead < needRead) ? nRead : needRead);
            rb_str_buf_cat( str, s_body.bodyBuf + s_body.curPos, n );
            s_body.curPos += n;
        }
    }
    
    return str;
}

static VALUE lsapi_rewind(VALUE self)
{  
    s_body.curPos = 0;
    return self;
}

static VALUE lsapi_each(VALUE self)
{
    VALUE str;
    lsapi_rewind(self);
   
    while(isEofBodyBuf() != 1)
    {
        str = lsapi_gets(self);
        rb_yield(str);
    }
    return self;

}

static VALUE lsapi_eof(VALUE self)
{
    return (LSAPI_GetReqBodyRemain_r( &g_req ) <= 0) ? Qtrue : Qfalse;
}

static VALUE lsapi_binmode(VALUE self)
{
    return self;
}

static VALUE lsapi_isatty(VALUE self)
{
    return Qfalse;
}

static VALUE lsapi_sync(VALUE self)
{
    return Qfalse;
}

static VALUE lsapi_setsync(VALUE self,VALUE sync)
{
    return Qfalse;
}

static VALUE lsapi_close(VALUE self)
{
    LSAPI_Flush_r( &g_req );
    if (isBodyWriteToFile())
    {
        //msync(s_body.bodyBuf, s_body.bodyLen, MS_SYNC);
        //sleep(5);
        munmap(s_body.bodyBuf, s_body.bodyLen);
    }
    else
        free(s_body.bodyBuf);
    
    s_body.bodyBuf = NULL;
    s_body.bodyLen = -1;
    s_body.bodyCurrentLen = 0;
    s_body.curPos = 0;    
    //Should the temp be deleted here?!
        
    return Qnil;
}


static VALUE lsapi_reopen( int argc, VALUE *argv, VALUE self)
{
    VALUE orig_verbose;
    if ( self == s_req_stderr )
    {
        /* constant silence hack */
        orig_verbose = (VALUE)ruby_verbose;
        ruby_verbose = Qnil;
        
        rb_define_global_const("STDERR", orig_stderr);
        
        ruby_verbose = (VALUE)orig_verbose;
        
        return rb_funcall2( orig_stderr, rb_intern( "reopen" ), argc, argv );
        
    }
    return self;
}

static void readMaxBodyBufLength()
{
    int n;
    const char *p = getenv( "LSAPI_MAX_BODYBUF_LENGTH" );
    if ( p )
    {
        n = atoi( p );
        if (n > 0)
        {
            if (strstr(p, "M") || strstr(p, "m"))
                MAX_BODYBUF_LENGTH = n * 1024 * 1024;
            else if (strstr(p, "K") || strstr(p, "k"))
                MAX_BODYBUF_LENGTH = n * 1024;
            else
                MAX_BODYBUF_LENGTH = n;
        }
    }
}

static void readTempFileTemplate()
{
    const char *p = getenv( "LSAPI_TEMPFILE" );
    if (p == NULL || strlen(p) > 1024 - 7)
         p = "/tmp/lsapi.XXXXXX";
    
    strcpy(sTempFile, p);
    if (strlen(p) <= 6 || strcmp(p + (strlen(p) - 6), "XXXXXX") != 0)
        strcat(sTempFile, ".XXXXXX");
}

static void initBodyBuf()
{
    s_body.bodyBuf = NULL;
    s_body.bodyLen = -1;
    s_body.bodyCurrentLen = 0;
    s_body.curPos = 0;    
}
void Init_lsapi()
{
    VALUE orig_verbose; 
    char * p;
    int prefork = 0;
    LSAPI_Init();
    initBodyBuf();
    
    readMaxBodyBufLength();
    readTempFileTemplate();
    
    p = getenv("LSAPI_CHILDREN");
    if (p && atoi(p) > 1)
        prefork = 1;

#ifdef rb_thread_select
    LSAPI_Init_Env_Parameters( rb_thread_select );
#else
    LSAPI_Init_Env_Parameters( select );
#endif
    
    s_pid = getpid();
    
    p = getenv( "RACK_ROOT" );
    if ( p )
    {
        if ( chdir( p ) == -1 )
            perror( "chdir()" );
    }
    if ( p || getenv( "RACK_ENV" ) )
        s_fn_add_env = add_env_rails;
    
    orig_stdin = rb_stdin;
    orig_stdout = rb_stdout;
    orig_stderr = rb_stderr;
#if defined( RUBY_VERSION_CODE ) && RUBY_VERSION_CODE < 180
    orig_defout = rb_defout;
#endif
    orig_env = rb_const_get( rb_cObject, rb_intern("ENV") );
    env_copy = rb_funcall( orig_env, rb_intern( "to_hash" ), 0 );
    
    /* tell the garbage collector it is a global variable, do not recycle it. */
    rb_global_variable(&env_copy);
    
    rb_hash_aset( env_copy,rb_tainted_str_new("GATEWAY_Irewindable_input.rbNTERFACE", 17),
                                              rb_tainted_str_new("CGI/1.2", 7));
        
    rb_define_global_function("eval_string_wrap", lsapi_eval_string_wrap, 1);
    
    cLSAPI = rb_define_class("LSAPI", rb_cObject);
    rb_define_singleton_method(cLSAPI, "accept", lsapi_s_accept, 0);
    if (prefork)
    {
        rb_define_singleton_method(cLSAPI, "accept_new_connection", lsapi_s_accept_new_conn, 0);
        rb_define_singleton_method(cLSAPI, "postfork_child", lsapi_s_postfork_child, 0);
        rb_define_singleton_method(cLSAPI, "postfork_parent", lsapi_s_postfork_parent, 0);
    }

    rb_define_method(cLSAPI, "process", lsapi_process, 0 );
    /* rb_define_method(cLSAPI, "initialize", lsapi_initialize, 0); */
    rb_define_method(cLSAPI, "putc", lsapi_putc, 1);
    rb_define_method(cLSAPI, "write", lsapi_write, 1);
    rb_define_method(cLSAPI, "print", lsapi_print, -1);
    rb_define_method(cLSAPI, "printf", lsapi_printf, -1);
    rb_define_method(cLSAPI, "puts", lsapi_puts, -1);
    rb_define_method(cLSAPI, "<<", lsapi_addstr, 1);
    rb_define_method(cLSAPI, "flush", lsapi_flush, 0);
    rb_define_method(cLSAPI, "getc", lsapi_getc, 0);
    /* rb_define_method(cLSAPI, "ungetc", lsapi_ungetc, 1); */
    rb_define_method(cLSAPI, "gets", lsapi_gets, 0);
    
    //TEST: adding readline function to make irb happy?
    /*rb_define_method(cLSAPI, "readline", lsapi_gets, 0); */
    
    rb_define_method(cLSAPI, "read", lsapi_read, -1);
    rb_define_method(cLSAPI, "rewind", lsapi_rewind, 0);
    rb_define_method(cLSAPI, "each", lsapi_each, 0);
    
    rb_define_method(cLSAPI, "eof", lsapi_eof, 0);
    rb_define_method(cLSAPI, "eof?", lsapi_eof, 0);
    rb_define_method(cLSAPI, "close", lsapi_close, 0);
    /* rb_define_method(cLSAPI, "closed?", lsapi_closed, 0); */
    rb_define_method(cLSAPI, "binmode", lsapi_binmode, 0);
    rb_define_method(cLSAPI, "isatty", lsapi_isatty, 0);
    rb_define_method(cLSAPI, "tty?", lsapi_isatty, 0);
    rb_define_method(cLSAPI, "sync", lsapi_sync, 0);
    rb_define_method(cLSAPI, "sync=", lsapi_setsync, 1);
    rb_define_method(cLSAPI, "reopen", lsapi_reopen, -1 );
    
    
    s_req = Data_Make_Struct( cLSAPI, lsapi_data, lsapi_mark, free, s_req_data );
    s_req_data->req = &g_req;
    s_req_data->fn_write = LSAPI_Write_r;
    rb_stdin = rb_stdout = s_req;
    
#if defined( RUBY_VERSION_CODE ) && RUBY_VERSION_CODE < 180
    rb_defout = s_req;
#endif

    rb_global_variable(&s_req );
    
    s_req_stderr = Data_Make_Struct( cLSAPI, lsapi_data, lsapi_mark, free, s_stderr_data );
    s_stderr_data->req = &g_req;
    s_stderr_data->fn_write = LSAPI_Write_Stderr_r;
    rb_stderr = s_req_stderr;
    rb_global_variable(&s_req_stderr );
    
    /* constant silence hack */
    orig_verbose = (VALUE)ruby_verbose;
    ruby_verbose = Qnil;
    
    lsapi_env = rb_hash_new();
    clear_env();
    /* redefine ENV using a hash table, should be faster than char **environment */
    rb_define_global_const("ENV", lsapi_env);
    
    rb_define_global_const("STDERR", rb_stderr);
    
    ruby_verbose = (VALUE)orig_verbose;
    
    return;
}

require 'mkmf'
dir_config( 'lsapi' )
if ( have_library( "socket" ))
    have_library( "nsl" )
end
if RUBY_VERSION =~ /1.9/ then
    $CPPFLAGS += " -DRUBY_19"
end 
if RUBY_VERSION =~ /2/ then
    $CPPFLAGS += " -DRUBY_2"
end 
create_makefile( "lsapi" )
//#define LSAPI_DEBUG
/*
Copyright (c) 2002-2018, Lite Speed Technologies Inc.
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 Lite Speed Technologies Inc 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.
*/


#include <ctype.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <sys/stat.h>
#include <sched.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <grp.h>
#include <pwd.h>
#include <time.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/un.h>

#include "lsapilib.h"

#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
#include <sys/prctl.h>
#endif

#if defined(__FreeBSD__ ) || defined(__NetBSD__) || defined(__OpenBSD__) \
    || defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
#include <sys/sysctl.h>
#endif

#include <inttypes.h>
#ifndef uint32
#define uint32 uint32_t
#endif

struct lsapi_MD5Context {
    uint32 buf[4];
    uint32 bits[2];
    unsigned char in[64];
};

void lsapi_MD5Init(struct lsapi_MD5Context *context);
void lsapi_MD5Update(struct lsapi_MD5Context *context, unsigned char const *buf,
           unsigned len);
void lsapi_MD5Final(unsigned char digest[16], struct lsapi_MD5Context *context);

/*
 * This is needed to make RSAREF happy on some MS-DOS compilers.
 */
typedef struct lsapi_MD5Context lsapi_MD5_CTX;


#define LSAPI_ST_REQ_HEADER     1
#define LSAPI_ST_REQ_BODY       2
#define LSAPI_ST_RESP_HEADER    4
#define LSAPI_ST_RESP_BODY      8
#define LSAPI_ST_BACKGROUND     16

#define LSAPI_RESP_BUF_SIZE     8192
#define LSAPI_INIT_RESP_HEADER_LEN 4096

enum
{
    LSAPI_STATE_IDLE,
    LSAPI_STATE_CONNECTED,
    LSAPI_STATE_ACCEPTING,
};

typedef struct lsapi_child_status
{
    int     m_pid;
    long    m_tmStart;

    volatile short   m_iKillSent;
    volatile char    m_inProcess;
    volatile char    m_state;
    volatile int     m_iReqCounter;

    volatile long    m_tmWaitBegin;
    volatile long    m_tmReqBegin;
    volatile long    m_tmLastCheckPoint;
}
lsapi_child_status;

static lsapi_child_status * s_worker_status = NULL;

static int g_inited = 0;
static int g_running = 1;
static int s_ppid;
static int s_restored_ppid = 0;
static int s_pid = 0;
static int s_slow_req_msecs = 0;
static int s_keep_listener = 1;
static int s_dump_debug_info = 0;
static int s_pid_dump_debug_info = 0;
static int s_req_processed = 0;
static int s_skip_write = 0;
static int (*pthread_atfork_func)(void (*prepare)(void), void (*parent)(void),
                                  void (*child)(void)) = NULL;

static int *s_busy_workers = NULL;
static int *s_accepting_workers = NULL;
static int *s_global_counter = &s_req_processed;
static int s_max_busy_workers = -1;
static char *s_stderr_log_path = NULL;
static int s_stderr_is_pipe = 0;
static int s_ignore_pid = -1;
static size_t s_total_pages = 1;
static size_t s_min_avail_pages = 256 * 1024;
static size_t *s_avail_pages = &s_total_pages;

LSAPI_Request g_req =
{ .m_fdListen = -1, .m_fd = -1 };

static char         s_secret[24];

static LSAPI_On_Timer_pf s_proc_group_timer_cb = NULL;

void Flush_RespBuf_r( LSAPI_Request * pReq );
static int lsapi_reopen_stderr(const char *p);

static const char *CGI_HEADERS[H_TRANSFER_ENCODING+1] =
{
    "HTTP_ACCEPT", "HTTP_ACCEPT_CHARSET",
    "HTTP_ACCEPT_ENCODING",
    "HTTP_ACCEPT_LANGUAGE", "HTTP_AUTHORIZATION",
    "HTTP_CONNECTION", "CONTENT_TYPE",
    "CONTENT_LENGTH", "HTTP_COOKIE", "HTTP_COOKIE2",
    "HTTP_HOST", "HTTP_PRAGMA",
    "HTTP_REFERER", "HTTP_USER_AGENT",
    "HTTP_CACHE_CONTROL",
    "HTTP_IF_MODIFIED_SINCE", "HTTP_IF_MATCH",
    "HTTP_IF_NONE_MATCH",
    "HTTP_IF_RANGE",
    "HTTP_IF_UNMODIFIED_SINCE",
    "HTTP_KEEP_ALIVE",
    "HTTP_RANGE",
    "HTTP_X_FORWARDED_FOR",
    "HTTP_VIA",
    "HTTP_TRANSFER_ENCODING"
};

static int CGI_HEADER_LEN[H_TRANSFER_ENCODING+1] =
{    11, 19, 20, 20, 18, 15, 12, 14, 11, 12, 9, 11, 12, 15, 18,
     22, 13, 18, 13, 24, 15, 10, 20, 8, 22 };


static const char *HTTP_HEADERS[H_TRANSFER_ENCODING+1] =
{
    "Accept", "Accept-Charset",
    "Accept-Encoding",
    "Accept-Language", "Authorization",
    "Connection", "Content-Type",
    "Content-Length", "Cookie", "Cookie2",
    "Host", "Pragma",
    "Referer", "User-Agent",
    "Cache-Control",
    "If-Modified-Since", "If-Match",
    "If-None-Match",
    "If-Range",
    "If-Unmodified-Since",
    "Keep-Alive",
    "Range",
    "X-Forwarded-For",
    "Via",
    "Transfer-Encoding"
};

static int HTTP_HEADER_LEN[H_TRANSFER_ENCODING+1] =
{   6, 14, 15, 15, 13, 10, 12, 14, 6, 7, 4, 6, 7, 10, //user-agent
    13,17, 8, 13, 8, 19, 10, 5, 15, 3, 17
};


static const char *s_log_level_names[8] =
{
    "", "DEBUG","INFO", "NOTICE", "WARN", "ERROR", "CRIT", "FATAL"
};


void LSAPI_Log(int flag, const char * fmt, ...)
{
    char buf[1024];
    char *p = buf;
    if ((flag & LSAPI_LOG_TIMESTAMP_BITS)
        && !(s_stderr_is_pipe))
    {
        struct timeval  tv;
        struct tm       tm;
        gettimeofday(&tv, NULL);
        localtime_r(&tv.tv_sec, &tm);
        if (flag & LSAPI_LOG_TIMESTAMP_FULL)
        {
            p += snprintf(p, 1024, "%04d-%02d-%02d %02d:%02d:%02d.%06d ",
                tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
                tm.tm_hour, tm.tm_min, tm.tm_sec, (int)tv.tv_usec);
        }
        else if (flag & LSAPI_LOG_TIMESTAMP_HMS)
        {
            p += snprintf(p, 1024, "%02d:%02d:%02d ",
                tm.tm_hour, tm.tm_min, tm.tm_sec);
        }
    }

    int level = flag & LSAPI_LOG_LEVEL_BITS;
    if (level && level <= LSAPI_LOG_FLAG_FATAL)
    {
        p += snprintf(p, 100, "[%s] ", s_log_level_names[level]);
    }

    if (flag & LSAPI_LOG_PID)
    {
        p += snprintf(p, 100, "[UID:%d][%d] ", getuid(), s_pid);
    }

    if (p > buf)
        fprintf(stderr, "%.*s", (int)(p - buf), buf);
    va_list ap;
    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
}

#ifdef LSAPI_DEBUG

#define DBGLOG_FLAG (LSAPI_LOG_TIMESTAMP_FULL|LSAPI_LOG_FLAG_DEBUG|LSAPI_LOG_PID)
#define lsapi_dbg(...)   LSAPI_Log(DBGLOG_FLAG, __VA_ARGS__)

#else

#define lsapi_dbg(...)

#endif

#define lsapi_log(...)  LSAPI_Log(LSAPI_LOG_TIMESTAMP_FULL|LSAPI_LOG_PID, __VA_ARGS__)


void lsapi_perror(const char * pMessage, int err_no)
{
    lsapi_log("%s, errno: %d (%s)\n", pMessage, err_no, strerror(err_no));
}


static int lsapi_parent_dead()
{
    // Return non-zero if the parent is dead.  0 if still alive.
    if (!s_ppid) {
        // not checking, so not dead
        return(0);
    }
    if (s_restored_ppid) {
        if (kill(s_restored_ppid,0) == -1) {
            if (errno == EPERM) {
                return(0); // no permission, but it's still there.
            }
            return(1); // Dead
        }
        return(0); // it worked, so it's not dead
    }
    return(s_ppid != getppid());
}


static void lsapi_sigpipe( int sig )
{
}


static void lsapi_siguser1( int sig )
{
    g_running = 0;
}

#ifndef sighandler_t
typedef void (*sighandler_t)(int);
#endif

static void lsapi_signal(int signo, sighandler_t handler)
{
    struct sigaction sa;

    sigaction(signo, NULL, &sa);

    if (sa.sa_handler == SIG_DFL)
    {
        sigemptyset(&sa.sa_mask);
        sa.sa_flags = 0;
        sa.sa_handler = handler;
        sigaction(signo, &sa, NULL);
    }
}


static int s_enable_core_dump = 0;
static void lsapi_enable_core_dump(void)
{
#if defined(__FreeBSD__ ) || defined(__NetBSD__) || defined(__OpenBSD__) \
    || defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
    int  mib[2];
    size_t len;

#if !defined(__OpenBSD__)
    len = 2;
    if ( sysctlnametomib("kern.sugid_coredump", mib, &len) == 0 )
    {
        len = sizeof(s_enable_core_dump);
        if (sysctl(mib, 2, NULL, 0, &s_enable_core_dump, len) == -1)
            perror( "sysctl: Failed to set 'kern.sugid_coredump', "
                    "core dump may not be available!");
    }
#else
    int set = 3;
    len = sizeof(set);
    mib[0] = CTL_KERN;
    mib[1] = KERN_NOSUIDCOREDUMP;
    if (sysctl(mib, 2, NULL, 0, &set, len) == 0) {
        s_enable_core_dump = 1;
    }
#endif


#endif

#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
    if (prctl(PR_SET_DUMPABLE, s_enable_core_dump,0,0,0) == -1)
        perror( "prctl: Failed to set dumpable, "
                    "core dump may not be available!");
#endif
}


static inline void lsapi_buildPacketHeader( struct lsapi_packet_header * pHeader,
                                char type, int len )
{
    pHeader->m_versionB0 = LSAPI_VERSION_B0;  /* LSAPI protocol version */
    pHeader->m_versionB1 = LSAPI_VERSION_B1;
    pHeader->m_type      = type;
    pHeader->m_flag      = LSAPI_ENDIAN;
    pHeader->m_packetLen.m_iLen = len;
}


static  int lsapi_set_nblock( int fd, int nonblock )
{
    int val = fcntl( fd, F_GETFL, 0 );
    if ( nonblock )
    {
        if (!( val & O_NONBLOCK ))
        {
            return fcntl( fd, F_SETFL, val | O_NONBLOCK );
        }
    }
    else
    {
        if ( val & O_NONBLOCK )
        {
            return fcntl( fd, F_SETFL, val &(~O_NONBLOCK) );
        }
    }
    return 0;
}


static int lsapi_close( int fd )
{
    int ret;
    while( 1 )
    {
        ret = close( fd );
        if (( ret == -1 )&&( errno == EINTR )&&(g_running))
            continue;
        return ret;
    }
}


static void lsapi_close_connection(LSAPI_Request *pReq)
{
    if (pReq->m_fd == -1)
        return;
    lsapi_close(pReq->m_fd);
    pReq->m_fd = -1;
    if (s_busy_workers)
        __atomic_fetch_sub(s_busy_workers, 1, __ATOMIC_SEQ_CST);
    if (s_worker_status)
        __atomic_store_n(&s_worker_status->m_state, LSAPI_STATE_IDLE,
                         __ATOMIC_SEQ_CST);
}


static inline ssize_t lsapi_read( int fd, void * pBuf, size_t len )
{
    ssize_t ret;
    while( 1 )
    {
        ret = read( fd, (char *)pBuf, len );
        if (( ret == -1 )&&( errno == EINTR )&&(g_running))
            continue;
        return ret;
    }
}


/*
static int lsapi_write( int fd, const void * pBuf, int len )
{
   int ret;
   const char * pCur;
   const char * pEnd;
   if ( len == 0 )
       return 0;
   pCur = (const char *)pBuf;
   pEnd = pCur + len;
   while( g_running && (pCur < pEnd) )
   {
       ret = write( fd, pCur, pEnd - pCur );
       if ( ret >= 0)
           pCur += ret;
       else if (( ret == -1 )&&( errno != EINTR ))
           return ret;
   }
   return pCur - (const char *)pBuf;
}
*/


static int lsapi_writev( int fd, struct iovec ** pVec, int count, int totalLen )
{
    int ret;
    int left = totalLen;
    int n = count;

    if (s_skip_write)
        return totalLen;

    while(( left > 0 )&&g_running )
    {
        ret = writev( fd, *pVec, n );
        if ( ret > 0 )
        {
            left -= ret;
            if (( left <= 0)||( !g_running ))
                return totalLen - left;
            while( ret > 0 )
            {
                if ( (*pVec)->iov_len <= (unsigned int )ret )
                {
                    ret -= (*pVec)->iov_len;
                    ++(*pVec);
                }
                else
                {
                    (*pVec)->iov_base = (char *)(*pVec)->iov_base + ret;
                    (*pVec)->iov_len -= ret;
                    break;
                }
            }
        }
        else if ( ret == -1 )
        {
            if ( errno == EAGAIN )
            {
                if ( totalLen - left > 0 )
                    return totalLen - left;
                else
                    return -1;
            }
            else if ( errno != EINTR )
                return ret;
        }
    }
    return totalLen - left;
}


/*
static int getTotalLen( struct iovec * pVec, int count )
{
   struct iovec * pEnd = pVec + count;
   int total = 0;
   while( pVec < pEnd )
   {
       total += pVec->iov_len;
       ++pVec;
   }
   return total;
}
*/


static inline int allocateBuf( LSAPI_Request * pReq, int size )
{
    char * pBuf = (char *)realloc( pReq->m_pReqBuf, size );
    if ( pBuf )
    {
        pReq->m_pReqBuf = pBuf;
        pReq->m_reqBufSize = size;
        pReq->m_pHeader = (struct lsapi_req_header *)pReq->m_pReqBuf;
        return 0;
    }
    return -1;
}


static int allocateIovec( LSAPI_Request * pReq, int n )
{
    struct iovec * p = (struct iovec *)realloc(
                pReq->m_pIovec, sizeof(struct iovec) * n );
    if ( !p )
        return -1;
    pReq->m_pIovecToWrite = p + ( pReq->m_pIovecToWrite - pReq->m_pIovec );
    pReq->m_pIovecCur = p + ( pReq->m_pIovecCur - pReq->m_pIovec );
    pReq->m_pIovec = p;
    pReq->m_pIovecEnd = p + n;
    return 0;
}


static int allocateRespHeaderBuf( LSAPI_Request * pReq, int size )
{
    char * p = (char *)realloc( pReq->m_pRespHeaderBuf, size );
    if ( !p )
        return -1;
    pReq->m_pRespHeaderBufPos   = p + ( pReq->m_pRespHeaderBufPos - pReq->m_pRespHeaderBuf );
    pReq->m_pRespHeaderBuf      = p;
    pReq->m_pRespHeaderBufEnd   = p + size;
    return 0;
}


static inline int verifyHeader( struct lsapi_packet_header * pHeader, char pktType )
{
    if (( LSAPI_VERSION_B0 != pHeader->m_versionB0 )||
        ( LSAPI_VERSION_B1 != pHeader->m_versionB1 )||
        ( pktType != pHeader->m_type ))
        return -1;
    if ( LSAPI_ENDIAN != (pHeader->m_flag & LSAPI_ENDIAN_BIT ))
    {
        register char b;
        b = pHeader->m_packetLen.m_bytes[0];
        pHeader->m_packetLen.m_bytes[0] = pHeader->m_packetLen.m_bytes[3];
        pHeader->m_packetLen.m_bytes[3] = b;
        b = pHeader->m_packetLen.m_bytes[1];
        pHeader->m_packetLen.m_bytes[1] = pHeader->m_packetLen.m_bytes[2];
        pHeader->m_packetLen.m_bytes[2] = b;
    }
    return pHeader->m_packetLen.m_iLen;
}


static int allocateEnvList( struct LSAPI_key_value_pair ** pEnvList,
                        int *curSize, int newSize )
{
    struct LSAPI_key_value_pair * pBuf;
    if ( *curSize >= newSize )
        return 0;
    if ( newSize > 8192 )
        return -1;
    pBuf = (struct LSAPI_key_value_pair *)realloc( *pEnvList, newSize *
                    sizeof(struct LSAPI_key_value_pair) );
    if ( pBuf )
    {
        *pEnvList = pBuf;
        *curSize  = newSize;
        return 0;
    }
    else
        return -1;

}


static inline int isPipe( int fd )
{
    char        achPeer[128];
    socklen_t   len = 128;
    if (( getpeername( fd, (struct sockaddr *)achPeer, &len ) != 0 )&&
        ( errno == ENOTCONN ))
        return 0;
    else
        return 1;
}


static int parseEnv( struct LSAPI_key_value_pair * pEnvList, int count,
            char **pBegin, char * pEnd )
{
    struct LSAPI_key_value_pair * pEnvEnd;
        int keyLen = 0, valLen = 0;
    if ( count > 8192 )
        return -1;
    pEnvEnd = pEnvList + count;
    while( pEnvList != pEnvEnd )
    {
        if ( pEnd - *pBegin < 4 )
            return -1;
        keyLen = *((unsigned char *)((*pBegin)++));
        keyLen = (keyLen << 8) + *((unsigned char *)((*pBegin)++));
        valLen = *((unsigned char *)((*pBegin)++));
        valLen = (valLen << 8) + *((unsigned char *)((*pBegin)++));
        if ( *pBegin + keyLen + valLen > pEnd )
            return -1;
        if (( !keyLen )||( !valLen ))
            return -1;

        pEnvList->pKey = *pBegin;
        *pBegin += keyLen;
        pEnvList->pValue = *pBegin;
        *pBegin += valLen;

        pEnvList->keyLen = keyLen - 1;
        pEnvList->valLen = valLen - 1;
        ++pEnvList;
    }
    if ( memcmp( *pBegin, "\0\0\0\0", 4 ) != 0 )
        return -1;
    *pBegin += 4;
    return 0;
}


static inline void swapIntEndian( int * pInteger )
{
    char * p = (char *)pInteger;
    register char b;
    b = p[0];
    p[0] = p[3];
    p[3] = b;
    b = p[1];
    p[1] = p[2];
    p[2] = b;

}


static inline void fixEndian( LSAPI_Request * pReq )
{
    struct lsapi_req_header *p= pReq->m_pHeader;
    swapIntEndian( &p->m_httpHeaderLen );
    swapIntEndian( &p->m_reqBodyLen );
    swapIntEndian( &p->m_scriptFileOff );
    swapIntEndian( &p->m_scriptNameOff );
    swapIntEndian( &p->m_queryStringOff );
    swapIntEndian( &p->m_requestMethodOff );
    swapIntEndian( &p->m_cntUnknownHeaders );
    swapIntEndian( &p->m_cntEnv );
    swapIntEndian( &p->m_cntSpecialEnv );
}


static void fixHeaderIndexEndian( LSAPI_Request * pReq )
{
    int i;
    for( i = 0; i < H_TRANSFER_ENCODING; ++i )
    {
        if ( pReq->m_pHeaderIndex->m_headerOff[i] )
        {
            register char b;
            char * p = (char *)(&pReq->m_pHeaderIndex->m_headerLen[i]);
            b = p[0];
            p[0] = p[1];
            p[1] = b;
            swapIntEndian( &pReq->m_pHeaderIndex->m_headerOff[i] );
        }
    }
    if ( pReq->m_pHeader->m_cntUnknownHeaders > 0 )
    {
        struct lsapi_header_offset * pCur, *pEnd;
        pCur = pReq->m_pUnknownHeader;
        pEnd = pCur + pReq->m_pHeader->m_cntUnknownHeaders;
        while( pCur < pEnd )
        {
            swapIntEndian( &pCur->nameOff );
            swapIntEndian( &pCur->nameLen );
            swapIntEndian( &pCur->valueOff );
            swapIntEndian( &pCur->valueLen );
            ++pCur;
        }
    }
}


static int validateHeaders( LSAPI_Request * pReq )
{
    int totalLen = pReq->m_pHeader->m_httpHeaderLen;
    int i;
    for(i = 0; i < H_TRANSFER_ENCODING; ++i)
    {
        if ( pReq->m_pHeaderIndex->m_headerOff[i] )
        {
            if (pReq->m_pHeaderIndex->m_headerOff[i] > totalLen
                || pReq->m_pHeaderIndex->m_headerLen[i]
                    + pReq->m_pHeaderIndex->m_headerOff[i] > totalLen)
                return -1;
        }
    }
    if (pReq->m_pHeader->m_cntUnknownHeaders > 0)
    {
        struct lsapi_header_offset * pCur, *pEnd;
        pCur = pReq->m_pUnknownHeader;
        pEnd = pCur + pReq->m_pHeader->m_cntUnknownHeaders;
        while( pCur < pEnd )
        {
            if (pCur->nameOff > totalLen
                || pCur->nameOff + pCur->nameLen > totalLen
                || pCur->valueOff > totalLen
                || pCur->valueOff + pCur->valueLen > totalLen)
                return -1;
            ++pCur;
        }
    }
    return 0;
}


static uid_t s_uid = 0;
static uid_t s_defaultUid;  //web server need set this
static gid_t s_defaultGid;

#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)

#define LSAPI_LVE_DISABLED  0
#define LSAPI_LVE_ENABLED   1
#define LSAPI_CAGEFS_ENABLED 2
#define LSAPI_CAGEFS_NO_SUEXEC 3
struct liblve;
static int s_enable_lve = LSAPI_LVE_DISABLED;
static struct liblve * s_lve = NULL;

static void *s_liblve;
static int (*fp_lve_is_available)(void) = NULL;
static int (*fp_lve_instance_init)(struct liblve *) = NULL;
static int (*fp_lve_destroy)(struct liblve *) = NULL;
static int (*fp_lve_enter)(struct liblve *, uint32_t, int32_t, int32_t, uint32_t *) = NULL;
static int (*fp_lve_leave)(struct liblve *, uint32_t *) = NULL;
static int (*fp_lve_jail)( struct passwd *, char *) = NULL;
static int lsapi_load_lve_lib(void)
{
    s_liblve = dlopen("liblve.so.0", RTLD_NOW | RTLD_GLOBAL);
    if (s_liblve)
    {
        fp_lve_is_available = dlsym(s_liblve, "lve_is_available");
        if (dlerror() == NULL)
        {
            if ( !(*fp_lve_is_available)() )
            {
                int uid = getuid();
                if ( uid )
                {
                    if (setreuid( s_uid, uid )) {};
                    if ( !(*fp_lve_is_available)() )
                        s_enable_lve = 0;
                    if (setreuid( uid, s_uid )) {};
                }
            }
        }
    }
    else
    {
        s_enable_lve = LSAPI_LVE_DISABLED;
    }
    return (s_liblve)? 0 : -1;
}


static int init_lve_ex(void)
{
    int rc;
    if ( !s_liblve )
        return -1;
    fp_lve_instance_init = dlsym(s_liblve, "lve_instance_init");
    fp_lve_destroy = dlsym(s_liblve, "lve_destroy");
    fp_lve_enter = dlsym(s_liblve, "lve_enter");
    fp_lve_leave = dlsym(s_liblve, "lve_leave");
    if ( s_enable_lve >= LSAPI_CAGEFS_ENABLED )
        fp_lve_jail = dlsym(s_liblve, "jail" );

    if ( s_lve == NULL )
    {
        rc = (*fp_lve_instance_init)(NULL);
        s_lve = malloc(rc);
    }
    rc = (*fp_lve_instance_init)(s_lve);
    if (rc != 0)
    {
        perror( "LSAPI: Unable to initialize LVE" );
        free( s_lve );
        s_lve = NULL;
        return -1;
    }
    return 0;

}

#endif



static int readSecret( const char * pSecretFile )
{
    struct stat st;
    int fd = open( pSecretFile, O_RDONLY , 0600 );
    if ( fd == -1 )
    {
        lsapi_log("LSAPI: failed to open secret file: %s!\n", pSecretFile );
        return -1;
    }
    if ( fstat( fd, &st ) == -1 )
    {
        lsapi_log("LSAPI: failed to check state of file: %s!\n", pSecretFile );
        close( fd );
        return -1;
    }
/*
    if ( st.st_uid != s_uid )
    {
        lsapi_log("LSAPI: file owner check failure: %s!\n", pSecretFile );
        close( fd );
        return -1;
    }
*/
    if ( st.st_mode & 0077 )
    {
        lsapi_log("LSAPI: file permission check failure: %s\n", pSecretFile );
        close( fd );
        return -1;
    }
    if ( read( fd, s_secret, 16 ) < 16 )
    {
        lsapi_log("LSAPI: failed to read secret from secret file: %s\n", pSecretFile );
        close( fd );
        return -1;
    }
    close( fd );
    return 0;
}


int LSAPI_is_suEXEC_Daemon(void)
{
    if (( !s_uid )&&( s_secret[0] ))
        return 1;
    else
        return 0;
}


static int LSAPI_perror_r( LSAPI_Request * pReq, const char * pErr1, const char *pErr2 )
{
    char achError[4096];
    int n = snprintf(achError, sizeof(achError), "[UID:%d][%d] %s:%s: %s\n",
                     getuid(), getpid(),
                     pErr1, (pErr2)?pErr2:"", strerror(errno));
    if (n > (int)sizeof(achError))
        n = sizeof(achError);
    if ( pReq )
        LSAPI_Write_Stderr_r( pReq, achError, n );
    else
        if (write( STDERR_FILENO, achError, n )) {};
    return 0;
}


#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
static int lsapi_lve_error( LSAPI_Request * pReq )
{
    static const char * headers[] =
    {
        "Cache-Control: private, no-cache, no-store, must-revalidate, max-age=0",
        "Pragma: no-cache",
        "Retry-After: 60",
        "Content-Type: text/html",
        NULL
    };
    static const char achBody[] =
        "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
        "<HTML><HEAD>\n<TITLE>508 Resource Limit Is Reached</TITLE>\n"
        "</HEAD><BODY>\n" "<H1>Resource Limit Is Reached</H1>\n"
        "The website is temporarily unable to service your request as it exceeded resource limit.\n"
        "Please try again later.\n"
        "<HR>\n"
        "</BODY></HTML>\n";

    LSAPI_ErrResponse_r( pReq, 508, headers, achBody, sizeof( achBody ) - 1 );
    return 0;
}

static int lsapi_enterLVE( LSAPI_Request * pReq, uid_t uid )
{
    if ( s_lve && uid ) //root user should not do that
    {
        uint32_t cookie;
        int ret = -1;
        ret = (*fp_lve_enter)(s_lve, uid, -1, -1, &cookie);
        if ( ret < 0 )
        {
            //lsapi_log("enter LVE (%d) : result: %d !\n", uid, ret );
            LSAPI_perror_r(pReq, "LSAPI: lve_enter() failure, reached resource limit.", NULL );
            lsapi_lve_error( pReq );
            return -1;
        }
    }

    return 0;
}

static int lsapi_jailLVE( LSAPI_Request * pReq, uid_t uid, struct passwd * pw )
{
    int ret = 0;
    char  error_msg[1024] = "";
    ret = (*fp_lve_jail)( pw, error_msg );
    if ( ret < 0 )
    {
        lsapi_log("LSAPI: LVE jail(%d) result: %d, error: %s !\n",
                  uid, ret, error_msg );
        LSAPI_perror_r( pReq, "LSAPI: jail() failure.", NULL );
        return -1;
    }
    return ret;
}


static int lsapi_initLVE(void)
{
    const char * pEnv;
    if ( (pEnv = getenv( "LSAPI_LVE_ENABLE" ))!= NULL )
    {
        s_enable_lve = atol( pEnv );
        pEnv = NULL;
    }
    else if ( (pEnv = getenv( "LVE_ENABLE" ))!= NULL )
    {
        s_enable_lve = atol( pEnv );
        pEnv = NULL;
    }
    if ( s_enable_lve && !s_uid )
    {
        lsapi_load_lve_lib();
        if ( s_enable_lve )
        {
            return init_lve_ex();
        }

    }
    return 0;
}
#endif


static int setUID_LVE(LSAPI_Request * pReq, uid_t uid, gid_t gid, const char * pChroot)
{
    int rv;
    struct passwd * pw;
    pw = getpwuid( uid );
#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
    if ( s_lve )
    {
        if( lsapi_enterLVE( pReq, uid ) == -1 )
            return -1;
        if ( pw && fp_lve_jail)
        {
            rv = lsapi_jailLVE( pReq, uid, pw );
            if ( rv == -1 )
                return -1;
            if (( rv == 1 )&&(s_enable_lve == LSAPI_CAGEFS_NO_SUEXEC ))    //this mode only use cageFS, does not use suEXEC
            {
                uid = s_defaultUid;
                gid = s_defaultGid;
                pw = getpwuid( uid );
            }
        }
    }
#endif
    //if ( !uid || !gid )  //do not allow root
    //{
    //    return -1;
    //}

#if defined(__FreeBSD__ ) || defined(__NetBSD__) || defined(__OpenBSD__) \
    || defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
    if ( s_enable_core_dump )
        lsapi_enable_core_dump();
#endif

    rv = setgid(gid);
    if (rv == -1)
    {
        LSAPI_perror_r(pReq, "LSAPI: setgid()", NULL);
        return -1;
    }
    if ( pw && (pw->pw_gid == gid ))
    {
        rv = initgroups( pw->pw_name, gid );
        if (rv == -1)
        {
            LSAPI_perror_r(pReq, "LSAPI: initgroups()", NULL);
            return -1;
        }
    }
    else
    {
        rv = setgroups(1, &gid);
        if (rv == -1)
        {
            LSAPI_perror_r(pReq, "LSAPI: setgroups()", NULL);
        }
    }
    if ( pChroot )
    {
        rv = chroot( pChroot );
        if ( rv == -1 )
        {
            LSAPI_perror_r(pReq, "LSAPI: chroot()", NULL);
            return -1;
        }
    }
    rv = setuid(uid);
    if (rv == -1)
    {
        LSAPI_perror_r(pReq, "LSAPI: setuid()", NULL);
        return -1;
    }
#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
    if ( s_enable_core_dump )
        lsapi_enable_core_dump();
#endif
    return 0;
}

static int lsapi_suexec_auth( LSAPI_Request *pReq,
            char * pAuth, int len, char * pUgid, int ugidLen )
{
    lsapi_MD5_CTX md5ctx;
    unsigned char achMD5[16];
    if ( len < 32 )
        return -1;
    memmove( achMD5, pAuth + 16, 16 );
    memmove( pAuth + 16, s_secret, 16 );
    lsapi_MD5Init( &md5ctx );
    lsapi_MD5Update( &md5ctx, (unsigned char *)pAuth, 32 );
    lsapi_MD5Update( &md5ctx, (unsigned char *)pUgid, 8 );
    lsapi_MD5Final( (unsigned char *)pAuth + 16, &md5ctx);
    if ( memcmp( achMD5, pAuth + 16, 16 ) == 0 )
        return 0;
    return 1;
}


static int lsapi_changeUGid( LSAPI_Request * pReq )
{
    int uid = s_defaultUid;
    int gid = s_defaultGid;
    const char *pStderrLog;
    const char *pChroot = NULL;
    struct LSAPI_key_value_pair * pEnv;
    struct LSAPI_key_value_pair * pAuth;
    int i;
    if ( s_uid )
        return 0;
    //with special ID  0x00
    //authenticate the suEXEC request;
    //first one should be MD5( nonce + lscgid secret )
    //remember to clear the secret after verification
    //it should be set at the end of special env
    i = pReq->m_pHeader->m_cntSpecialEnv - 1;
    if ( i >= 0 )
    {
        pEnv = pReq->m_pSpecialEnvList + i;
        if (( *pEnv->pKey == '\000' )&&
            ( strcmp( pEnv->pKey+1, "SUEXEC_AUTH" ) == 0 ))
        {
            --pReq->m_pHeader->m_cntSpecialEnv;
            pAuth = pEnv--;
            if (( *pEnv->pKey == '\000' )&&
                ( strcmp( pEnv->pKey+1, "SUEXEC_UGID" ) == 0 ))
            {
                --pReq->m_pHeader->m_cntSpecialEnv;
                uid = *(uint32_t *)pEnv->pValue;
                gid = *(((uint32_t *)pEnv->pValue) + 1 );
                //lsapi_log("LSAPI: SUEXEC_UGID set UID: %d, GID: %d\n", uid, gid );
            }
            else
            {
                lsapi_log("LSAPI: missing SUEXEC_UGID env, use default user!\n" );
                pEnv = NULL;
            }
            if ( pEnv&& lsapi_suexec_auth( pReq, pAuth->pValue, pAuth->valLen, pEnv->pValue, pEnv->valLen ) == 0 )
            {
                //read UID, GID from specialEnv

            }
            else
            {
                //authentication error
                lsapi_log("LSAPI: SUEXEC_AUTH authentication failed, use default user!\n" );
                uid = 0;
            }
        }
        else
        {
            //lsapi_log("LSAPI: no SUEXEC_AUTH env, use default user!\n" );
        }
    }


    if ( !uid )
    {
        uid = s_defaultUid;
        gid = s_defaultGid;
    }

    //change uid
    if ( setUID_LVE( pReq, uid, gid, pChroot ) == -1 )
    {
        return -1;
    }

    s_uid = uid;

    if ( pReq->m_fdListen != -1 )
    {
        close( pReq->m_fdListen );
        pReq->m_fdListen = -1;
    }

    pStderrLog = LSAPI_GetEnv_r( pReq, "LSAPI_STDERR_LOG");
    if (pStderrLog)
        lsapi_reopen_stderr(pStderrLog);

    return 0;

}


static int parseContentLenFromHeader(LSAPI_Request * pReq)
{
    const char * pContentLen = LSAPI_GetHeader_r( pReq, H_CONTENT_LENGTH );
    if ( pContentLen )
        pReq->m_reqBodyLen = strtoll( pContentLen, NULL, 10 );
    return 0;
}


static int parseRequest( LSAPI_Request * pReq, int totalLen )
{
    int shouldFixEndian;
    char * pBegin = pReq->m_pReqBuf + sizeof( struct lsapi_req_header );
    char * pEnd = pReq->m_pReqBuf + totalLen;
    shouldFixEndian = ( LSAPI_ENDIAN != (
                pReq->m_pHeader->m_pktHeader.m_flag & LSAPI_ENDIAN_BIT ) );
    if ( shouldFixEndian )
    {
        fixEndian( pReq );
    }
    if ( (pReq->m_specialEnvListSize < pReq->m_pHeader->m_cntSpecialEnv )&&
            allocateEnvList( &pReq->m_pSpecialEnvList,
                &pReq->m_specialEnvListSize,
                pReq->m_pHeader->m_cntSpecialEnv ) == -1 )
        return -1;
    if ( (pReq->m_envListSize < pReq->m_pHeader->m_cntEnv )&&
            allocateEnvList( &pReq->m_pEnvList, &pReq->m_envListSize,
                pReq->m_pHeader->m_cntEnv ) == -1 )
        return -1;

    if ( parseEnv( pReq->m_pSpecialEnvList,
                pReq->m_pHeader->m_cntSpecialEnv,
                &pBegin, pEnd ) == -1 )
        return -1;
    if ( parseEnv( pReq->m_pEnvList, pReq->m_pHeader->m_cntEnv,
                &pBegin, pEnd ) == -1 )
        return -1;
    if (pReq->m_pHeader->m_scriptFileOff < 0
        || pReq->m_pHeader->m_scriptFileOff >= totalLen
        || pReq->m_pHeader->m_scriptNameOff < 0
        || pReq->m_pHeader->m_scriptNameOff >= totalLen
        || pReq->m_pHeader->m_queryStringOff < 0
        || pReq->m_pHeader->m_queryStringOff >= totalLen
        || pReq->m_pHeader->m_requestMethodOff < 0
        || pReq->m_pHeader->m_requestMethodOff >= totalLen)
    {
        lsapi_log("Bad request header - ERROR#1\n");
        return -1;
    }
    pReq->m_pScriptFile     = pReq->m_pReqBuf + pReq->m_pHeader->m_scriptFileOff;
    pReq->m_pScriptName     = pReq->m_pReqBuf + pReq->m_pHeader->m_scriptNameOff;
    pReq->m_pQueryString    = pReq->m_pReqBuf + pReq->m_pHeader->m_queryStringOff;
    pReq->m_pRequestMethod  = pReq->m_pReqBuf + pReq->m_pHeader->m_requestMethodOff;

    pBegin = pReq->m_pReqBuf + (( pBegin - pReq->m_pReqBuf + 7 ) & (~0x7));
    pReq->m_pHeaderIndex = ( struct lsapi_http_header_index * )pBegin;
    pBegin += sizeof( struct lsapi_http_header_index );

    pReq->m_pUnknownHeader = (struct lsapi_header_offset *)pBegin;
    pBegin += sizeof( struct lsapi_header_offset) *
                    pReq->m_pHeader->m_cntUnknownHeaders;

    pReq->m_pHttpHeader = pBegin;
    pBegin += pReq->m_pHeader->m_httpHeaderLen;
    if ( pBegin != pEnd )
    {
        lsapi_log("Request header does match total size, total: %d, "
                 "real: %ld\n", totalLen, pBegin - pReq->m_pReqBuf );
        return -1;
    }
    if ( shouldFixEndian )
    {
        fixHeaderIndexEndian( pReq );
    }

    if (validateHeaders(pReq) == -1)
    {
        lsapi_log("Bad request header - ERROR#2\n");
        return -1;
    }

    pReq->m_reqBodyLen = pReq->m_pHeader->m_reqBodyLen;
    if ( pReq->m_reqBodyLen == -2 )
    {
        parseContentLenFromHeader(pReq);
    }

    return 0;
}


//OPTIMIZATION
static char s_accept_notify = 0;
static char s_schedule_notify = 0;
static char s_notify_scheduled = 0;
static char s_notified_pid = 0;

static struct lsapi_packet_header s_ack = {'L', 'S',
                LSAPI_REQ_RECEIVED, LSAPI_ENDIAN, {LSAPI_PACKET_HEADER_LEN} };
static struct lsapi_packet_header s_conn_close_pkt = {'L', 'S',
                LSAPI_CONN_CLOSE, LSAPI_ENDIAN, {LSAPI_PACKET_HEADER_LEN} };


static inline int send_notification_pkt( int fd, struct lsapi_packet_header *pkt )
{
    if ( write( fd, pkt, LSAPI_PACKET_HEADER_LEN ) < LSAPI_PACKET_HEADER_LEN )
        return -1;
    return 0;
}


static inline int send_req_received_notification( int fd )
{
    return send_notification_pkt(fd, &s_ack);
}


static inline int send_conn_close_notification( int fd )
{
    return send_notification_pkt(fd, &s_conn_close_pkt);
}


//static void lsapi_sigalarm( int sig )
//{
//    if ( s_notify_scheduled )
//    {
//        s_notify_scheduled = 0;
//        if ( g_req.m_fd != -1 )
//            write_req_received_notification( g_req.m_fd );
//    }
//}


static inline int lsapi_schedule_notify(void)
{
    if ( !s_notify_scheduled )
    {
        alarm( 2 );
        s_notify_scheduled = 1;
    }
    return 0;
}


static inline int notify_req_received( int fd )
{
    if ( s_schedule_notify )
        return lsapi_schedule_notify();
    return send_req_received_notification( fd );

}


static inline int lsapi_notify_pid( int fd )
{
    char achBuf[16];
    lsapi_buildPacketHeader( (struct lsapi_packet_header *)achBuf, LSAPI_STDERR_STREAM,
                        8 + LSAPI_PACKET_HEADER_LEN );
    memmove( &achBuf[8], "\0PID", 4 );
    *((int *)&achBuf[12]) = getpid();

    if ( write( fd, achBuf, 16 ) < 16 )
        return -1;
    return 0;
}

static int readReq( LSAPI_Request * pReq )
{
    int len;
    int packetLen;
    if ( !pReq )
        return -1;
    if ( pReq->m_reqBufSize < 8192 )
    {
        if ( allocateBuf( pReq, 8192 ) == -1 )
            return -1;
    }

    while ( pReq->m_bufRead < LSAPI_PACKET_HEADER_LEN )
    {
        len = lsapi_read( pReq->m_fd, pReq->m_pReqBuf, pReq->m_reqBufSize );
        if ( len <= 0 )
            return -1;
        pReq->m_bufRead += len;
    }
    pReq->m_reqState = LSAPI_ST_REQ_HEADER;

    packetLen = verifyHeader( &pReq->m_pHeader->m_pktHeader, LSAPI_BEGIN_REQUEST );
    if ( packetLen < 0 )
    {
        lsapi_log("packetLen < 0\n");
        return -1;
    }
    if ( packetLen > LSAPI_MAX_HEADER_LEN )
    {
        lsapi_log("packetLen > %d\n", LSAPI_MAX_HEADER_LEN );
        return -1;
    }

    if ( packetLen + 1024 > pReq->m_reqBufSize )
    {
        if ( allocateBuf( pReq, packetLen + 1024 ) == -1 )
            return -1;
    }
    while( packetLen > pReq->m_bufRead )
    {
        len = lsapi_read( pReq->m_fd, pReq->m_pReqBuf + pReq->m_bufRead, packetLen - pReq->m_bufRead );
        if ( len <= 0 )
            return -1;
        pReq->m_bufRead += len;
    }
    if ( parseRequest( pReq, packetLen ) < 0 )
    {
        lsapi_log("ParseRequest error\n");
        return -1;
    }

    pReq->m_reqState = LSAPI_ST_REQ_BODY | LSAPI_ST_RESP_HEADER;

    if ( !s_uid )
    {
        if ( lsapi_changeUGid( pReq ) )
            return -1;
        memset(s_secret, 0, sizeof(s_secret));
    }
    pReq->m_bufProcessed = packetLen;

    //OPTIMIZATION
    if ( !s_accept_notify && !s_notified_pid )
        return notify_req_received( pReq->m_fd );
    else
    {
        s_notified_pid = 0;
        return 0;
    }
}


int LSAPI_Init(void)
{
    if ( !g_inited )
    {
        s_uid = geteuid();
        s_secret[0] = 0;
        lsapi_signal(SIGPIPE, lsapi_sigpipe);
        lsapi_signal(SIGUSR1, lsapi_siguser1);

#if defined(SIGXFSZ) && defined(SIG_IGN)
        signal(SIGXFSZ, SIG_IGN);
#endif
        /* let STDOUT function as STDERR,
           just in case writing to STDOUT directly */
        dup2( 2, 1 );
        if ( LSAPI_InitRequest( &g_req, LSAPI_SOCK_FILENO ) == -1 )
            return -1;
        g_inited = 1;
        s_ppid = getppid();
        void *pthread_lib = dlopen("libpthread.so", RTLD_LAZY);
        if (pthread_lib)
            pthread_atfork_func = dlsym(pthread_lib, "pthread_atfork");

    }
    return 0;
}


void LSAPI_Stop(void)
{
    g_running = 0;
}


int LSAPI_IsRunning(void)
{
    return g_running;
}


void LSAPI_Register_Pgrp_Timer_Callback(LSAPI_On_Timer_pf cb)
{
    s_proc_group_timer_cb = cb;
}


int LSAPI_InitRequest( LSAPI_Request * pReq, int fd )
{
    int newfd;
    if ( !pReq )
        return -1;
    memset( pReq, 0, sizeof( LSAPI_Request ) );
    if ( allocateIovec( pReq, 16 ) == -1 )
        return -1;
    pReq->m_pRespBuf = pReq->m_pRespBufPos = (char *)malloc( LSAPI_RESP_BUF_SIZE );
    if ( !pReq->m_pRespBuf )
        return -1;
    pReq->m_pRespBufEnd = pReq->m_pRespBuf + LSAPI_RESP_BUF_SIZE;
    pReq->m_pIovecCur = pReq->m_pIovecToWrite = pReq->m_pIovec + 1;
    pReq->m_respPktHeaderEnd = &pReq->m_respPktHeader[5];
    if ( allocateRespHeaderBuf( pReq, LSAPI_INIT_RESP_HEADER_LEN ) == -1 )
        return -1;

    if ( fd == STDIN_FILENO )
    {
        fd = dup( fd );
        newfd = open( "/dev/null", O_RDWR );
        dup2( newfd, STDIN_FILENO );
    }

    if ( isPipe( fd ) )
    {
        pReq->m_fdListen = -1;
        pReq->m_fd = fd;
    }
    else
    {
        pReq->m_fdListen = fd;
        pReq->m_fd = -1;
        lsapi_set_nblock( fd, 1 );
    }
    return 0;
}


int LSAPI_Is_Listen( void )
{
    return LSAPI_Is_Listen_r( &g_req );
}


int LSAPI_Is_Listen_r( LSAPI_Request * pReq)
{
    return pReq->m_fdListen != -1;
}


int LSAPI_Accept_r( LSAPI_Request * pReq )
{
    char        achPeer[128];
    socklen_t   len;
    int         nodelay = 1;

    if ( !pReq )
        return -1;
    if ( LSAPI_Finish_r( pReq ) == -1 )
        return -1;
    lsapi_set_nblock( pReq->m_fdListen , 0 );
    while( g_running )
    {
        if ( pReq->m_fd == -1 )
        {
            if ( pReq->m_fdListen != -1)
            {
                len = sizeof( achPeer );
                pReq->m_fd = accept( pReq->m_fdListen,
                            (struct sockaddr *)&achPeer, &len );
                if ( pReq->m_fd == -1 )
                {
                    if (( errno == EINTR )||( errno == EAGAIN))
                        continue;
                    else
                        return -1;
                }
                else
                {
                    if (s_worker_status)
                        __atomic_store_n(&s_worker_status->m_state,
                                       LSAPI_STATE_CONNECTED, __ATOMIC_SEQ_CST);
                    if (s_busy_workers)
                        __atomic_fetch_add(s_busy_workers, 1, __ATOMIC_SEQ_CST);
                    lsapi_set_nblock( pReq->m_fd , 0 );
                    if (((struct sockaddr *)&achPeer)->sa_family == AF_INET )
                    {
                        setsockopt(pReq->m_fd, IPPROTO_TCP, TCP_NODELAY,
                                   (char *)&nodelay, sizeof(nodelay));
                    }
                    //init_conn_key( pReq->m_fd );
                    //OPTIMIZATION
                    if ( s_accept_notify )
                        if ( notify_req_received( pReq->m_fd ) == -1 )
                                return -1;
                }
            }
            else
                return -1;
        }
        if ( !readReq( pReq ) )
            break;
        //abort();
        lsapi_close_connection(pReq);
        LSAPI_Reset_r( pReq );
    }
    return 0;
}


static struct lsapi_packet_header   finish_close[2] =
{
    {'L', 'S', LSAPI_RESP_END, LSAPI_ENDIAN, {LSAPI_PACKET_HEADER_LEN} },
    {'L', 'S', LSAPI_CONN_CLOSE, LSAPI_ENDIAN, {LSAPI_PACKET_HEADER_LEN} }
};


int LSAPI_Finish_r( LSAPI_Request * pReq )
{
    /* finish req body */
    if ( !pReq )
        return -1;
    if (pReq->m_reqState)
    {
        if ( pReq->m_fd != -1 )
        {
            if ( pReq->m_reqState & LSAPI_ST_RESP_HEADER )
            {
                LSAPI_FinalizeRespHeaders_r( pReq );
            }
            if ( pReq->m_pRespBufPos != pReq->m_pRespBuf )
            {
                Flush_RespBuf_r( pReq );
            }

            pReq->m_pIovecCur->iov_base = (void *)finish_close;
            pReq->m_pIovecCur->iov_len  = LSAPI_PACKET_HEADER_LEN;
            pReq->m_totalLen += LSAPI_PACKET_HEADER_LEN;
            ++pReq->m_pIovecCur;
            LSAPI_Flush_r( pReq );
        }
        LSAPI_Reset_r( pReq );
    }
    return 0;
}


int LSAPI_End_Response_r(LSAPI_Request * pReq)
{
    if (!pReq)
        return -1;
    if (pReq->m_reqState & LSAPI_ST_BACKGROUND)
        return 0;
    if (pReq->m_reqState)
    {
        if ( pReq->m_fd != -1 )
        {
            if ( pReq->m_reqState & LSAPI_ST_RESP_HEADER )
            {
                if ( pReq->m_pRespHeaderBufPos <= pReq->m_pRespHeaderBuf )
                    return 0;

                LSAPI_FinalizeRespHeaders_r( pReq );
            }
            if ( pReq->m_pRespBufPos != pReq->m_pRespBuf )
            {
                Flush_RespBuf_r( pReq );
            }

            pReq->m_pIovecCur->iov_base = (void *)finish_close;
            pReq->m_pIovecCur->iov_len  = LSAPI_PACKET_HEADER_LEN << 1;
            pReq->m_totalLen += LSAPI_PACKET_HEADER_LEN << 1;
            ++pReq->m_pIovecCur;
            LSAPI_Flush_r( pReq );
            lsapi_close_connection(pReq);
        }
        pReq->m_reqState |= LSAPI_ST_BACKGROUND;
    }
    return 0;
}


void LSAPI_Reset_r( LSAPI_Request * pReq )
{
    pReq->m_pRespBufPos         = pReq->m_pRespBuf;
    pReq->m_pIovecCur           = pReq->m_pIovecToWrite = pReq->m_pIovec + 1;
    pReq->m_pRespHeaderBufPos   = pReq->m_pRespHeaderBuf;

    memset( &pReq->m_pHeaderIndex, 0,
            (char *)(pReq->m_respHeaderLen) - (char *)&pReq->m_pHeaderIndex );
}


int LSAPI_Release_r( LSAPI_Request * pReq )
{
    if ( pReq->m_pReqBuf )
        free( pReq->m_pReqBuf );
    if ( pReq->m_pSpecialEnvList )
        free( pReq->m_pSpecialEnvList );
    if ( pReq->m_pEnvList )
        free( pReq->m_pEnvList );
    if ( pReq->m_pRespHeaderBuf )
        free( pReq->m_pRespHeaderBuf );
    return 0;
}


char * LSAPI_GetHeader_r( LSAPI_Request * pReq, int headerIndex )
{
    int off;
    if ( !pReq || ((unsigned int)headerIndex > H_TRANSFER_ENCODING) )
        return NULL;
    off = pReq->m_pHeaderIndex->m_headerOff[ headerIndex ];
    if ( !off )
        return NULL;
    if ( *(pReq->m_pHttpHeader + off
        + pReq->m_pHeaderIndex->m_headerLen[ headerIndex ]) )
    {
        *( pReq->m_pHttpHeader + off
            + pReq->m_pHeaderIndex->m_headerLen[ headerIndex ]) = 0;
    }
    return pReq->m_pHttpHeader + off;
}


static int readBodyToReqBuf( LSAPI_Request * pReq )
{
    off_t bodyLeft;
    ssize_t len = pReq->m_bufRead - pReq->m_bufProcessed;
    if ( len > 0 )
        return len;
    pReq->m_bufRead = pReq->m_bufProcessed = pReq->m_pHeader->m_pktHeader.m_packetLen.m_iLen;

    bodyLeft = pReq->m_reqBodyLen - pReq->m_reqBodyRead;
    len = pReq->m_reqBufSize - pReq->m_bufRead;
    if ( len < 0 )
        return -1;
    if ( len > bodyLeft )
        len = bodyLeft;

    len = lsapi_read( pReq->m_fd, pReq->m_pReqBuf + pReq->m_bufRead, len );
    if ( len > 0 )
        pReq->m_bufRead += len;
    return len;
}


int LSAPI_ReqBodyGetChar_r( LSAPI_Request * pReq )
{
    if (!pReq || (pReq->m_fd ==-1) )
        return EOF;
    if ( pReq->m_bufProcessed >= pReq->m_bufRead )
    {
        if ( readBodyToReqBuf( pReq ) <= 0 )
            return EOF;
    }
    ++pReq->m_reqBodyRead;
    return (unsigned char)*(pReq->m_pReqBuf + pReq->m_bufProcessed++);
}


int LSAPI_ReqBodyGetLine_r( LSAPI_Request * pReq, char * pBuf, size_t bufLen, int *getLF )
{
    ssize_t len;
    ssize_t left;
    char * pBufEnd = pBuf + bufLen - 1;
    char * pBufCur = pBuf;
    char * pCur;
    char * p;
    if (!pReq || pReq->m_fd == -1 || !pBuf || !getLF)
        return -1;
    *getLF = 0;
    while( (left = pBufEnd - pBufCur ) > 0 )
    {

        len = pReq->m_bufRead - pReq->m_bufProcessed;
        if ( len <= 0 )
        {
            if ( (len = readBodyToReqBuf( pReq )) <= 0 )
            {
                *getLF = 1;
                break;
            }
        }
        if ( len > left )
            len = left;
        pCur = pReq->m_pReqBuf + pReq->m_bufProcessed;
        p = memchr( pCur, '\n', len );
        if ( p )
            len = p - pCur + 1;
        memmove( pBufCur, pCur, len );
        pBufCur += len;
        pReq->m_bufProcessed += len;

        pReq->m_reqBodyRead += len;

        if ( p )
        {
            *getLF = 1;
            break;
        }
    }
    *pBufCur = 0;

    return pBufCur - pBuf;
}


ssize_t LSAPI_ReadReqBody_r( LSAPI_Request * pReq, char * pBuf, size_t bufLen )
{
    ssize_t len;
    off_t total;
    /* char *pOldBuf = pBuf; */
    if (!pReq || pReq->m_fd == -1 || !pBuf || (ssize_t)bufLen < 0)
        return -1;

    total = pReq->m_reqBodyLen - pReq->m_reqBodyRead;

    if ( total <= 0 )
        return 0;
    if ( total < (ssize_t)bufLen )
        bufLen = total;

    total = 0;
    len = pReq->m_bufRead - pReq->m_bufProcessed;
    if ( len > 0 )
    {
        if ( len > (ssize_t)bufLen )
            len = bufLen;
        memmove( pBuf, pReq->m_pReqBuf + pReq->m_bufProcessed, len );
        pReq->m_bufProcessed += len;
        total += len;
        pBuf += len;
        bufLen -= len;
    }
    while( bufLen > 0 )
    {
        len = lsapi_read( pReq->m_fd, pBuf, bufLen );
        if ( len > 0 )
        {
            total += len;
            pBuf += len;
            bufLen -= len;
        }
        else if ( len <= 0 )
        {
            if ( !total)
                return -1;
            break;
        }
    }
    pReq->m_reqBodyRead += total;
    return total;

}


ssize_t LSAPI_Write_r( LSAPI_Request * pReq, const char * pBuf, size_t len )
{
    struct lsapi_packet_header * pHeader;
    const char * pEnd;
    const char * p;
    ssize_t bufLen;
    ssize_t toWrite;
    ssize_t packetLen;
    int skip = 0;

    if (!pReq || !pBuf)
        return -1;
    if (pReq->m_reqState & LSAPI_ST_BACKGROUND)
        return len;
    if (pReq->m_fd == -1)
        return -1;
    if ( pReq->m_reqState & LSAPI_ST_RESP_HEADER )
    {
        LSAPI_FinalizeRespHeaders_r( pReq );
/*
        if ( *pBuf == '\r' )
        {
            ++skip;
        }
        if ( *pBuf == '\n' )
        {
            ++skip;
        }
*/
    }
    pReq->m_reqState |= LSAPI_ST_RESP_BODY;

    if ( ((ssize_t)len - skip) < pReq->m_pRespBufEnd - pReq->m_pRespBufPos )
    {
        memmove( pReq->m_pRespBufPos, pBuf + skip, len - skip );
        pReq->m_pRespBufPos += len - skip;
        return len;
    }


    pHeader = pReq->m_respPktHeader;
    p       = pBuf + skip;
    pEnd    = pBuf + len;
    bufLen  = pReq->m_pRespBufPos - pReq->m_pRespBuf;

    while( ( toWrite = pEnd - p ) > 0 )
    {
        packetLen = toWrite + bufLen;
        if ( LSAPI_MAX_DATA_PACKET_LEN < packetLen)
        {
            packetLen = LSAPI_MAX_DATA_PACKET_LEN;
            toWrite = packetLen - bufLen;
        }

        lsapi_buildPacketHeader( pHeader, LSAPI_RESP_STREAM,
                            packetLen + LSAPI_PACKET_HEADER_LEN );
        pReq->m_totalLen += packetLen + LSAPI_PACKET_HEADER_LEN;

        pReq->m_pIovecCur->iov_base = (void *)pHeader;
        pReq->m_pIovecCur->iov_len  = LSAPI_PACKET_HEADER_LEN;
        ++pReq->m_pIovecCur;
        ++pHeader;
        if ( bufLen > 0 )
        {
            pReq->m_pIovecCur->iov_base = (void *)pReq->m_pRespBuf;
            pReq->m_pIovecCur->iov_len  = bufLen;
            pReq->m_pRespBufPos = pReq->m_pRespBuf;
            ++pReq->m_pIovecCur;
            bufLen = 0;
        }

        pReq->m_pIovecCur->iov_base = (void *)p;
        pReq->m_pIovecCur->iov_len  = toWrite;
        ++pReq->m_pIovecCur;
        p += toWrite;

        if ( pHeader >= pReq->m_respPktHeaderEnd - 1)
        {
            if ( LSAPI_Flush_r( pReq ) == -1 )
                return -1;
            pHeader = pReq->m_respPktHeader;
        }
    }
    if ( pHeader != pReq->m_respPktHeader )
        if ( LSAPI_Flush_r( pReq ) == -1 )
            return -1;
    return p - pBuf;
}


#if defined(__FreeBSD__ )
ssize_t gsendfile( int fdOut, int fdIn, off_t* off, size_t size )
{
    ssize_t ret;
    off_t written;
    ret = sendfile( fdIn, fdOut, *off, size, NULL, &written, 0 );
    if ( written > 0 )
    {
        ret = written;
        *off += ret;
    }
    return ret;
}
#endif

#if defined(__OpenBSD__) || defined(__NetBSD__)
ssize_t gsendfile( int fdOut, int fdIn, off_t* off, size_t size )
{
    ssize_t ret;
    off_t written = 0;
    const size_t bufsiz = 16384;
    unsigned char in[bufsiz] = {0};

    if (lseek(fdIn, *off, SEEK_SET) == -1) {
        return -1;
    }

    while (size > 0) {
        size_t tor = size > sizeof(in) ? sizeof(in) : size;
        ssize_t c = read(fdIn, in, tor);
        if (c <= 0) {
            goto end;
        }

        ssize_t w = write(fdOut, in, c);
        if (w > 0)
            written += w;

        if (w != c) {
            goto end;
        }
        size -= c;
    }

end:
    *off += written;
    return 0;
}
#endif


#if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
ssize_t gsendfile( int fdOut, int fdIn, off_t* off, size_t size )
{
    ssize_t ret;
    off_t len = size;
    ret = sendfile( fdIn, fdOut, *off, &len, NULL, 0 );
    if (( ret == 0 )&&( len > 0 ))
    {
        ret = len;
        *off += len;
    }
    return ret;
}
#endif


#if defined(sun) || defined(__sun)
#include <sys/sendfile.h>
ssize_t gsendfile( int fdOut, int fdIn, off_t *off, size_t size )
{
    int n = 0 ;
    sendfilevec_t vec[1];

    vec[n].sfv_fd   = fdIn;
    vec[n].sfv_flag = 0;
    vec[n].sfv_off  = *off;
    vec[n].sfv_len  = size;
    ++n;

    size_t written;
    ssize_t ret = sendfilev( fdOut, vec, n, &written );
    if (( !ret )||( errno == EAGAIN ))
        ret = written;
    if ( ret > 0 )
        *off += ret;
    return ret;
}
#endif


#if defined(linux) || defined(__linux) || defined(__linux__) || \
    defined(__gnu_linux__)
#include <sys/sendfile.h>
#define gsendfile sendfile
#endif


#if defined(HPUX)
ssize_t gsendfile( int fdOut, int fdIn, off_t * off, size_t size )
{
    return sendfile( fdOut, fdIn, off, size, NULL, 0 );
}
#endif


ssize_t LSAPI_sendfile_r( LSAPI_Request * pReq, int fdIn, off_t* off, size_t size )
{
    struct lsapi_packet_header * pHeader = pReq->m_respPktHeader;
    if ( !pReq || (pReq->m_fd == -1) || fdIn == -1 )
        return -1;
    if ( pReq->m_reqState & LSAPI_ST_RESP_HEADER )
    {
        LSAPI_FinalizeRespHeaders_r( pReq );
    }
    pReq->m_reqState |= LSAPI_ST_RESP_BODY;

    LSAPI_Flush_r(pReq);

    lsapi_buildPacketHeader( pHeader, LSAPI_RESP_STREAM,
                            size + LSAPI_PACKET_HEADER_LEN );


    if (write(pReq->m_fd,  (const char *) pHeader, LSAPI_PACKET_HEADER_LEN ) != LSAPI_PACKET_HEADER_LEN)
        return -1;

    return gsendfile( pReq->m_fd, fdIn, off, size );
}


void Flush_RespBuf_r( LSAPI_Request * pReq )
{
    struct lsapi_packet_header * pHeader = pReq->m_respPktHeader;
    int bufLen = pReq->m_pRespBufPos - pReq->m_pRespBuf;
    pReq->m_reqState |= LSAPI_ST_RESP_BODY;
    lsapi_buildPacketHeader( pHeader, LSAPI_RESP_STREAM,
                        bufLen + LSAPI_PACKET_HEADER_LEN );
    pReq->m_totalLen += bufLen + LSAPI_PACKET_HEADER_LEN;

    pReq->m_pIovecCur->iov_base = (void *)pHeader;
    pReq->m_pIovecCur->iov_len  = LSAPI_PACKET_HEADER_LEN;
    ++pReq->m_pIovecCur;
    ++pHeader;
    if ( bufLen > 0 )
    {
        pReq->m_pIovecCur->iov_base = (void *)pReq->m_pRespBuf;
        pReq->m_pIovecCur->iov_len  = bufLen;
        pReq->m_pRespBufPos = pReq->m_pRespBuf;
        ++pReq->m_pIovecCur;
        bufLen = 0;
    }
}


int LSAPI_Flush_r( LSAPI_Request * pReq )
{
    int ret = 0;
    int n;
    if ( !pReq )
        return -1;
    n = pReq->m_pIovecCur - pReq->m_pIovecToWrite;
    if (( 0 == n )&&( pReq->m_pRespBufPos == pReq->m_pRespBuf ))
        return 0;
    if ( pReq->m_fd == -1 )
    {
        pReq->m_pRespBufPos = pReq->m_pRespBuf;
        pReq->m_totalLen = 0;
        pReq->m_pIovecCur = pReq->m_pIovecToWrite = pReq->m_pIovec;
        return -1;
    }
    if ( pReq->m_reqState & LSAPI_ST_RESP_HEADER )
    {
        LSAPI_FinalizeRespHeaders_r( pReq );
    }
    if ( pReq->m_pRespBufPos != pReq->m_pRespBuf )
    {
        Flush_RespBuf_r( pReq );
    }

    n = pReq->m_pIovecCur - pReq->m_pIovecToWrite;
    if ( n > 0 )
    {

        ret = lsapi_writev( pReq->m_fd, &pReq->m_pIovecToWrite,
                  n, pReq->m_totalLen );
        if ( ret < pReq->m_totalLen )
        {
            lsapi_close_connection(pReq);
            ret = -1;
        }
        pReq->m_totalLen = 0;
        pReq->m_pIovecCur = pReq->m_pIovecToWrite = pReq->m_pIovec;
    }
    return ret;
}


ssize_t LSAPI_Write_Stderr_r( LSAPI_Request * pReq, const char * pBuf, size_t len )
{
    struct lsapi_packet_header header;
    const char * pEnd;
    const char * p;
    ssize_t packetLen;
    ssize_t totalLen;
    int ret;
    struct iovec iov[2];
    struct iovec *pIov;

    if ( !pReq )
        return -1;
    if (s_stderr_log_path || pReq->m_fd == -1 || pReq->m_fd == pReq->m_fdListen)
        return write( 2, pBuf, len );
    if ( pReq->m_pRespBufPos != pReq->m_pRespBuf )
    {
        LSAPI_Flush_r( pReq );
    }

    p       = pBuf;
    pEnd    = pBuf + len;

    while( ( packetLen = pEnd - p ) > 0 )
    {
        if ( LSAPI_MAX_DATA_PACKET_LEN < packetLen)
        {
            packetLen = LSAPI_MAX_DATA_PACKET_LEN;
        }

        lsapi_buildPacketHeader( &header, LSAPI_STDERR_STREAM,
                            packetLen + LSAPI_PACKET_HEADER_LEN );
        totalLen = packetLen + LSAPI_PACKET_HEADER_LEN;

        iov[0].iov_base = (void *)&header;
        iov[0].iov_len  = LSAPI_PACKET_HEADER_LEN;

        iov[1].iov_base = (void *)p;
        iov[1].iov_len  = packetLen;
        p += packetLen;
        pIov = iov;
        ret = lsapi_writev( pReq->m_fd, &pIov,
                  2, totalLen );
        if ( ret < totalLen )
        {
            lsapi_close_connection(pReq);
            ret = -1;
        }
    }
    return p - pBuf;
}


static char * GetHeaderVar( LSAPI_Request * pReq, const char * name )
{
    int i;
    char * pValue;
    for( i = 0; i < H_TRANSFER_ENCODING; ++i )
    {
        if ( pReq->m_pHeaderIndex->m_headerOff[i] )
        {
            if ( strcmp( name, CGI_HEADERS[i] ) == 0 )
            {
                pValue = pReq->m_pHttpHeader
                         + pReq->m_pHeaderIndex->m_headerOff[i];
                if ( *(pValue + pReq->m_pHeaderIndex->m_headerLen[i]) != '\0')
                {
                    *(pValue + pReq->m_pHeaderIndex->m_headerLen[i]) = '\0';
                }
                return pValue;
            }
        }
    }
    if ( pReq->m_pHeader->m_cntUnknownHeaders > 0 )
    {
        const char *p;
        char *pKey;
        char *pKeyEnd;
        int  keyLen;
        struct lsapi_header_offset * pCur, *pEnd;
        pCur = pReq->m_pUnknownHeader;
        pEnd = pCur + pReq->m_pHeader->m_cntUnknownHeaders;
        while( pCur < pEnd )
        {
            pKey = pReq->m_pHttpHeader + pCur->nameOff;
            keyLen = pCur->nameLen;
            pKeyEnd = pKey + keyLen;
            p = &name[5];

            while(( pKey < pKeyEnd )&&( *p ))
            {
                char ch = toupper( *pKey );
                if ((ch != *p )||(( *p == '_' )&&( ch != '-')))
                    break;
                ++p; ++pKey;
            }
            if (( pKey == pKeyEnd )&& (!*p ))
            {
                pValue = pReq->m_pHttpHeader + pCur->valueOff;

                if ( *(pValue + pCur->valueLen) != '\0')
                {
                    *(pValue + pCur->valueLen) = '\0';
                }
                return pValue;
            }
            ++pCur;
        }
    }
    return NULL;
}


char * LSAPI_GetEnv_r( LSAPI_Request * pReq, const char * name )
{
    struct LSAPI_key_value_pair * pBegin = pReq->m_pEnvList;
    struct LSAPI_key_value_pair * pEnd = pBegin + pReq->m_pHeader->m_cntEnv;
    if ( !pReq || !name )
        return NULL;
    if ( strncmp( name, "HTTP_", 5 ) == 0 )
    {
        return GetHeaderVar( pReq, name );
    }
    while( pBegin < pEnd )
    {
        if ( strcmp( name, pBegin->pKey ) == 0 )
            return pBegin->pValue;
        ++pBegin;
    }
    return NULL;
}


struct _headerInfo
{
    const char * _name;
    int          _nameLen;
    const char * _value;
    int          _valueLen;
};


int compareValueLocation(const void * v1, const void *v2 )
{
    return ((const struct _headerInfo *)v1)->_value -
           ((const struct _headerInfo *)v2)->_value;
}


int LSAPI_ForeachOrgHeader_r( LSAPI_Request * pReq,
            LSAPI_CB_EnvHandler fn, void * arg )
{
    int i;
    int len = 0;
    char * pValue;
    int ret;
    int count = 0;
    struct _headerInfo headers[512];

    if ( !pReq || !fn )
        return -1;

    if ( !pReq->m_pHeaderIndex )
        return 0;

    for( i = 0; i < H_TRANSFER_ENCODING; ++i )
    {
        if ( pReq->m_pHeaderIndex->m_headerOff[i] )
        {
            len = pReq->m_pHeaderIndex->m_headerLen[i];
            pValue = pReq->m_pHttpHeader + pReq->m_pHeaderIndex->m_headerOff[i];
            *(pValue + len ) = 0;
            headers[count]._name = HTTP_HEADERS[i];
            headers[count]._nameLen = HTTP_HEADER_LEN[i];
            headers[count]._value = pValue;
            headers[count]._valueLen = len;
            ++count;

            //ret = (*fn)( HTTP_HEADERS[i], HTTP_HEADER_LEN[i],
            //            pValue, len, arg );
            //if ( ret <= 0 )
            //    return ret;
        }
    }
    if ( pReq->m_pHeader->m_cntUnknownHeaders > 0 )
    {
        char *pKey;
        int  keyLen;
        struct lsapi_header_offset * pCur, *pEnd;
        pCur = pReq->m_pUnknownHeader;
        pEnd = pCur + pReq->m_pHeader->m_cntUnknownHeaders;
        while( pCur < pEnd )
        {
            pKey = pReq->m_pHttpHeader + pCur->nameOff;
            keyLen = pCur->nameLen;
            *(pKey + keyLen ) = 0;

            pValue = pReq->m_pHttpHeader + pCur->valueOff;
            *(pValue + pCur->valueLen ) = 0;
            headers[count]._name = pKey;
            headers[count]._nameLen = keyLen;
            headers[count]._value = pValue;
            headers[count]._valueLen = pCur->valueLen;
            ++count;
            if ( count == 512 )
                break;
            //ret = (*fn)( pKey, keyLen,
            //            pValue, pCur->valueLen, arg );
            //if ( ret <= 0 )
            //    return ret;
            ++pCur;
        }
    }
    qsort( headers, count, sizeof( struct _headerInfo ), compareValueLocation );
    for( i = 0; i < count; ++i )
    {
        ret = (*fn)( headers[i]._name, headers[i]._nameLen,
                    headers[i]._value, headers[i]._valueLen, arg );
        if ( ret <= 0 )
            return ret;
    }
    return count;
}


int LSAPI_ForeachHeader_r( LSAPI_Request * pReq,
            LSAPI_CB_EnvHandler fn, void * arg )
{
    int i;
    int len = 0;
    char * pValue;
    int ret;
    int count = 0;
    if ( !pReq || !fn )
        return -1;
    for( i = 0; i < H_TRANSFER_ENCODING; ++i )
    {
        if ( pReq->m_pHeaderIndex->m_headerOff[i] )
        {
            len = pReq->m_pHeaderIndex->m_headerLen[i];
            pValue = pReq->m_pHttpHeader + pReq->m_pHeaderIndex->m_headerOff[i];
            *(pValue + len ) = 0;
            ret = (*fn)( CGI_HEADERS[i], CGI_HEADER_LEN[i],
                        pValue, len, arg );
            ++count;
            if ( ret <= 0 )
                return ret;
        }
    }
    if ( pReq->m_pHeader->m_cntUnknownHeaders > 0 )
    {
        char achHeaderName[256];
        char *p;
        char *pKey;
        char *pKeyEnd ;
        int  keyLen;
        struct lsapi_header_offset * pCur, *pEnd;
        pCur = pReq->m_pUnknownHeader;
        pEnd = pCur + pReq->m_pHeader->m_cntUnknownHeaders;
        while( pCur < pEnd )
        {
            pKey = pReq->m_pHttpHeader + pCur->nameOff;
            keyLen = pCur->nameLen;
            if ( keyLen > 250 )
                keyLen = 250;
            pKeyEnd = pKey + keyLen;
            memcpy( achHeaderName, "HTTP_", 5 );
            p = &achHeaderName[5];

            while( pKey < pKeyEnd )
            {
                char ch = *pKey++;
                if ( ch == '-' )
                    *p++ = '_';
                else
                    *p++ = toupper( ch );
            }
            *p = 0;
            keyLen += 5;

            pValue = pReq->m_pHttpHeader + pCur->valueOff;
            *(pValue + pCur->valueLen ) = 0;
            ret = (*fn)( achHeaderName, keyLen,
                        pValue, pCur->valueLen, arg );
            if ( ret <= 0 )
                return ret;
            ++pCur;
        }
    }
    return count + pReq->m_pHeader->m_cntUnknownHeaders;
}


static int EnvForeach( struct LSAPI_key_value_pair * pEnv,
            int n, LSAPI_CB_EnvHandler fn, void * arg )
{
    struct LSAPI_key_value_pair * pEnd = pEnv + n;
    int ret;
    if ( !pEnv || !fn )
        return -1;
    while( pEnv < pEnd )
    {
        ret = (*fn)( pEnv->pKey, pEnv->keyLen,
                    pEnv->pValue, pEnv->valLen, arg );
        if ( ret <= 0 )
            return ret;
        ++pEnv;
    }
    return n;
}


int LSAPI_ForeachEnv_r( LSAPI_Request * pReq,
            LSAPI_CB_EnvHandler fn, void * arg )
{
    if ( !pReq || !fn )
        return -1;
    if ( pReq->m_pHeader->m_cntEnv > 0 )
    {
        return EnvForeach( pReq->m_pEnvList, pReq->m_pHeader->m_cntEnv,
                    fn, arg );
    }
    return 0;
}


int LSAPI_ForeachSpecialEnv_r( LSAPI_Request * pReq,
            LSAPI_CB_EnvHandler fn, void * arg )
{
    if ( !pReq || !fn )
        return -1;
    if ( pReq->m_pHeader->m_cntSpecialEnv > 0 )
    {
        return EnvForeach( pReq->m_pSpecialEnvList,
                pReq->m_pHeader->m_cntSpecialEnv,
                    fn, arg );
    }
    return 0;

}


int LSAPI_FinalizeRespHeaders_r( LSAPI_Request * pReq )
{
    if ( !pReq || !pReq->m_pIovec )
        return -1;
    if ( !( pReq->m_reqState & LSAPI_ST_RESP_HEADER ) )
        return 0;
    pReq->m_reqState &= ~LSAPI_ST_RESP_HEADER;
    if ( pReq->m_pRespHeaderBufPos > pReq->m_pRespHeaderBuf )
    {
        pReq->m_pIovecCur->iov_base = (void *)pReq->m_pRespHeaderBuf;
        pReq->m_pIovecCur->iov_len  = pReq->m_pRespHeaderBufPos - pReq->m_pRespHeaderBuf;
        pReq->m_totalLen += pReq->m_pIovecCur->iov_len;
        ++pReq->m_pIovecCur;
    }

    pReq->m_pIovec->iov_len  = sizeof( struct lsapi_resp_header)
            + pReq->m_respHeader.m_respInfo.m_cntHeaders * sizeof( short );
    pReq->m_totalLen += pReq->m_pIovec->iov_len;

    lsapi_buildPacketHeader( &pReq->m_respHeader.m_pktHeader,
                    LSAPI_RESP_HEADER, pReq->m_totalLen  );
    pReq->m_pIovec->iov_base = (void *)&pReq->m_respHeader;
    pReq->m_pIovecToWrite = pReq->m_pIovec;
    return 0;
}


int LSAPI_AppendRespHeader2_r( LSAPI_Request * pReq, const char * pHeaderName,
                              const char * pHeaderValue )
{
    int nameLen, valLen, len;
    if ( !pReq || !pHeaderName || !pHeaderValue )
        return -1;
    if ( pReq->m_reqState & LSAPI_ST_RESP_BODY )
        return -1;
    if ( pReq->m_respHeader.m_respInfo.m_cntHeaders >= LSAPI_MAX_RESP_HEADERS )
        return -1;
    nameLen = strlen( pHeaderName );
    valLen = strlen( pHeaderValue );
    if ( nameLen == 0 )
        return -1;
    while( nameLen > 0 )
    {
        char ch = *(pHeaderName + nameLen - 1 );
        if (( ch == '\n' )||( ch == '\r' ))
            --nameLen;
        else
            break;
    }
    if ( nameLen <= 0 )
        return 0;
    while( valLen > 0 )
    {
        char ch = *(pHeaderValue + valLen - 1 );
        if (( ch == '\n' )||( ch == '\r' ))
            --valLen;
        else
            break;
    }
    len = nameLen + valLen + 1;
    if ( len > LSAPI_RESP_HTTP_HEADER_MAX )
        return -1;

    if ( pReq->m_pRespHeaderBufPos + len + 1 > pReq->m_pRespHeaderBufEnd )
    {
        int newlen = pReq->m_pRespHeaderBufPos + len + 4096 - pReq->m_pRespHeaderBuf;
        newlen -= newlen % 4096;
        if ( allocateRespHeaderBuf( pReq, newlen ) == -1 )
            return -1;
    }
    memmove( pReq->m_pRespHeaderBufPos, pHeaderName, nameLen );
    pReq->m_pRespHeaderBufPos += nameLen;
    *pReq->m_pRespHeaderBufPos++ = ':';
    memmove( pReq->m_pRespHeaderBufPos, pHeaderValue, valLen );
    pReq->m_pRespHeaderBufPos += valLen;
    *pReq->m_pRespHeaderBufPos++ = 0;
    ++len;  /* add one byte padding for \0 */
    pReq->m_respHeaderLen[pReq->m_respHeader.m_respInfo.m_cntHeaders] = len;
    ++pReq->m_respHeader.m_respInfo.m_cntHeaders;
    return 0;
}


int LSAPI_AppendRespHeader_r( LSAPI_Request * pReq, const char * pBuf, int len )
{
    if ( !pReq || !pBuf || len <= 0 || len > LSAPI_RESP_HTTP_HEADER_MAX )
        return -1;
    if ( pReq->m_reqState & LSAPI_ST_RESP_BODY )
        return -1;
    if ( pReq->m_respHeader.m_respInfo.m_cntHeaders >= LSAPI_MAX_RESP_HEADERS )
        return -1;
    while( len > 0 )
    {
        char ch = *(pBuf + len - 1 );
        if (( ch == '\n' )||( ch == '\r' ))
            --len;
        else
            break;
    }
    if ( len <= 0 )
        return 0;
    if ( pReq->m_pRespHeaderBufPos + len + 1 > pReq->m_pRespHeaderBufEnd )
    {
        int newlen = pReq->m_pRespHeaderBufPos + len + 4096 - pReq->m_pRespHeaderBuf;
        newlen -= newlen % 4096;
        if ( allocateRespHeaderBuf( pReq, newlen ) == -1 )
            return -1;
    }
    memmove( pReq->m_pRespHeaderBufPos, pBuf, len );
    pReq->m_pRespHeaderBufPos += len;
    *pReq->m_pRespHeaderBufPos++ = 0;
    ++len;  /* add one byte padding for \0 */
    pReq->m_respHeaderLen[pReq->m_respHeader.m_respInfo.m_cntHeaders] = len;
    ++pReq->m_respHeader.m_respInfo.m_cntHeaders;
    return 0;
}


int LSAPI_CreateListenSock2( const struct sockaddr * pServerAddr, int backlog )
{
    int ret;
    int fd;
    int flag = 1;
    int addr_len;

    switch( pServerAddr->sa_family )
    {
    case AF_INET:
        addr_len = 16;
        break;
    case AF_INET6:
        addr_len = sizeof( struct sockaddr_in6 );
        break;
    case AF_UNIX:
        addr_len = sizeof( struct sockaddr_un );
        unlink( ((struct sockaddr_un *)pServerAddr)->sun_path );
        break;
    default:
        return -1;
    }

    fd = socket( pServerAddr->sa_family, SOCK_STREAM, 0 );
    if ( fd == -1 )
        return -1;

    fcntl( fd, F_SETFD, FD_CLOEXEC );

    if(setsockopt( fd, SOL_SOCKET, SO_REUSEADDR,
                (char *)( &flag ), sizeof(flag)) == 0)
    {
        ret = bind( fd, pServerAddr, addr_len );
        if ( !ret )
        {
            ret = listen( fd, backlog );
            if ( !ret )
                return fd;
        }
    }

    ret = errno;
    close(fd);
    errno = ret;
    return -1;
}


int LSAPI_ParseSockAddr( const char * pBind, struct sockaddr * pAddr )
{
    char achAddr[256];
    char * p = achAddr;
    char * pEnd;
    struct addrinfo *res, hints;
    int  doAddrInfo = 0;
    int port;

    if ( !pBind )
        return -1;

    while( isspace( *pBind ) )
        ++pBind;

    strncpy(achAddr, pBind, 255);
    achAddr[255] = 0;

    switch( *p )
    {
    case '/':
        pAddr->sa_family = AF_UNIX;
        strncpy( ((struct sockaddr_un *)pAddr)->sun_path, p,
                sizeof(((struct sockaddr_un *)pAddr)->sun_path) );
        return 0;

    case '[':
        pAddr->sa_family = AF_INET6;
        ++p;
        pEnd = strchr( p, ']' );
        if ( !pEnd )
            return -1;
        *pEnd++ = 0;

        if ( *p == '*' )
        {
            strcpy( achAddr, "::" );
            p = achAddr;
        }
        doAddrInfo = 1;
        break;

    default:
        pAddr->sa_family = AF_INET;
        pEnd = strchr( p, ':' );
        if ( !pEnd )
            return -1;
        *pEnd++ = 0;

        doAddrInfo = 0;
        if ( *p == '*' )
        {
            ((struct sockaddr_in *)pAddr)->sin_addr.s_addr = htonl(INADDR_ANY);
        }
        else if (!strcasecmp( p, "localhost" ) )
            ((struct sockaddr_in *)pAddr)->sin_addr.s_addr = htonl( INADDR_LOOPBACK );
        else
        {
#ifdef HAVE_INET_PTON
            if (!inet_pton(AF_INET, p, &((struct sockaddr_in *)pAddr)->sin_addr))
#else
            ((struct sockaddr_in *)pAddr)->sin_addr.s_addr = inet_addr( p );
            if ( ((struct sockaddr_in *)pAddr)->sin_addr.s_addr == INADDR_BROADCAST)
#endif
            {
                doAddrInfo = 1;
            }
        }
        break;
    }
    if ( *pEnd == ':' )
        ++pEnd;

    port = atoi( pEnd );
    if (( port <= 0 )||( port > 65535 ))
        return -1;
    if ( doAddrInfo )
    {

        memset(&hints, 0, sizeof(hints));

        hints.ai_family   = pAddr->sa_family;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_protocol = IPPROTO_TCP;

        if ( getaddrinfo(p, NULL, &hints, &res) )
        {
            return -1;
        }

        memcpy(pAddr, res->ai_addr, res->ai_addrlen);
        freeaddrinfo(res);
    }

    if ( pAddr->sa_family == AF_INET )
        ((struct sockaddr_in *)pAddr)->sin_port = htons( port );
    else
        ((struct sockaddr_in6 *)pAddr)->sin6_port = htons( port );
    return 0;

}


int LSAPI_CreateListenSock( const char * pBind, int backlog )
{
    char serverAddr[128];
    int ret;
    int fd = -1;
    ret = LSAPI_ParseSockAddr( pBind, (struct sockaddr *)serverAddr );
    if ( !ret )
    {
        fd = LSAPI_CreateListenSock2( (struct sockaddr *)serverAddr, backlog );
    }
    return fd;
}


static fn_select_t g_fnSelect = select;
typedef struct _lsapi_prefork_server
{
    int m_fd;
    int m_iMaxChildren;
    int m_iExtraChildren;
    int m_iCurChildren;
    int m_iMaxIdleChildren;
    int m_iServerMaxIdle;
    int m_iChildrenMaxIdleTime;
    int m_iMaxReqProcessTime;
    int m_iAvoidFork;

    lsapi_child_status * m_pChildrenStatus;
    lsapi_child_status * m_pChildrenStatusCur;
    lsapi_child_status * m_pChildrenStatusEnd;

}lsapi_prefork_server;
static lsapi_prefork_server * g_prefork_server = NULL;


int LSAPI_Init_Prefork_Server( int max_children, fn_select_t fp, int avoidFork )
{
    if ( g_prefork_server )
        return 0;
    if ( max_children <= 1 )
        return -1;
    if ( max_children >= 10000)
        max_children = 10000;

    if (s_max_busy_workers == 0)
        s_max_busy_workers = max_children / 2 + 1;

    g_prefork_server = (lsapi_prefork_server *)malloc( sizeof( lsapi_prefork_server ) );
    if ( !g_prefork_server )
        return -1;
    memset( g_prefork_server, 0, sizeof( lsapi_prefork_server ) );

    if ( fp != NULL )
        g_fnSelect = fp;

    s_ppid = getppid();
    s_pid = getpid();
    setpgid( s_pid, s_pid );
#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
    s_total_pages = sysconf(_SC_PHYS_PAGES);
#endif
    g_prefork_server->m_iAvoidFork = avoidFork;
    g_prefork_server->m_iMaxChildren = max_children;

    g_prefork_server->m_iExtraChildren = ( avoidFork ) ? 0 : (max_children / 3) ;
    g_prefork_server->m_iMaxIdleChildren = ( avoidFork ) ? (max_children + 1) : (max_children / 3);
    if ( g_prefork_server->m_iMaxIdleChildren == 0 )
        g_prefork_server->m_iMaxIdleChildren = 1;
    g_prefork_server->m_iChildrenMaxIdleTime = 300;
    g_prefork_server->m_iMaxReqProcessTime = 3600;

    setsid();

    return 0;
}


void LSAPI_Set_Server_fd( int fd )
{
    if( g_prefork_server )
        g_prefork_server->m_fd = fd;
}


static int lsapi_accept( int fdListen )
{
    int         fd;
    int         nodelay = 1;
    socklen_t   len;
    char        achPeer[128];

    len = sizeof( achPeer );
    fd = accept( fdListen, (struct sockaddr *)&achPeer, &len );
    if ( fd != -1 )
    {
        if (((struct sockaddr *)&achPeer)->sa_family == AF_INET )
        {
            setsockopt( fd, IPPROTO_TCP, TCP_NODELAY,
                    (char *)&nodelay, sizeof(nodelay));
        }

        //OPTIMIZATION
        //if ( s_accept_notify )
        //    notify_req_received( fd );
    }
    return fd;

}


static unsigned int s_max_reqs = UINT_MAX;
static int s_max_idle_secs = 300;
static int s_stop;

static void lsapi_cleanup(int signal)
{
    s_stop = signal;
}


static lsapi_child_status * find_child_status( int pid )
{
    lsapi_child_status * pStatus = g_prefork_server->m_pChildrenStatus;
    lsapi_child_status * pEnd = g_prefork_server->m_pChildrenStatusEnd;
    while( pStatus < pEnd )
    {
        if ( pStatus->m_pid == pid )
        {
            if (pid == 0)
            {
                memset(pStatus, 0, sizeof( *pStatus ) );
                pStatus->m_pid = -1;
            }
            if ( pStatus + 1 > g_prefork_server->m_pChildrenStatusCur )
                g_prefork_server->m_pChildrenStatusCur = pStatus + 1;
            return pStatus;
        }
        ++pStatus;
    }
    return NULL;
}


void LSAPI_reset_server_state( void )
{
    /*
       Reset child status
    */
    g_prefork_server->m_iCurChildren = 0;
    lsapi_child_status * pStatus = g_prefork_server->m_pChildrenStatus;
    lsapi_child_status * pEnd = g_prefork_server->m_pChildrenStatusEnd;
    while( pStatus < pEnd )
    {
        pStatus->m_pid = 0;
        ++pStatus;
    }
    if (s_busy_workers)
        __atomic_store_n(s_busy_workers, 0, __ATOMIC_SEQ_CST);
    if (s_accepting_workers)
        __atomic_store_n(s_accepting_workers, 0, __ATOMIC_SEQ_CST);

}


static void lsapi_sigchild( int signal )
{
    int status, pid;
    char expect_connected = LSAPI_STATE_CONNECTED;
    char expect_accepting = LSAPI_STATE_ACCEPTING;
    lsapi_child_status * child_status;
    if (g_prefork_server == NULL)
        return;
    while( 1 )
    {
        pid = waitpid( -1, &status, WNOHANG|WUNTRACED );
        if ( pid <= 0 )
        {
            break;
        }
        if ( WIFSIGNALED( status ))
        {
            int sig_num = WTERMSIG( status );
#ifdef WCOREDUMP
            const char * dump = WCOREDUMP( status ) ? "yes" : "no";
#else
            const char * dump = "unknown";
#endif
            lsapi_log("Child process with pid: %d was killed by signal: "
                     "%d, core dumped: %s\n", pid, sig_num, dump );
        }
        if ( pid == s_pid_dump_debug_info )
        {
            pid = 0;
            continue;
        }
        if ( pid == s_ignore_pid )
        {
            pid = 0;
            s_ignore_pid = -1;
            continue;
        }
        child_status = find_child_status( pid );
        if ( child_status )
        {
            if (__atomic_compare_exchange_n(&child_status->m_state,
                                            &expect_connected,
                                            LSAPI_STATE_IDLE, 1,
                                            __ATOMIC_SEQ_CST,
                                            __ATOMIC_SEQ_CST))
            {
                if (s_busy_workers)
                    __atomic_fetch_sub(s_busy_workers, 1, __ATOMIC_SEQ_CST);
            }
            else if (__atomic_compare_exchange_n(&child_status->m_state,
                                                 &expect_accepting,
                                                 LSAPI_STATE_IDLE, 1,
                                                 __ATOMIC_SEQ_CST,
                                                 __ATOMIC_SEQ_CST))
            {
                if (s_accepting_workers)
                    __atomic_fetch_sub(s_accepting_workers, 1, __ATOMIC_SEQ_CST);
            }
            child_status->m_pid = 0;
            --g_prefork_server->m_iCurChildren;
        }
    }
    while(( g_prefork_server->m_pChildrenStatusCur > g_prefork_server->m_pChildrenStatus )
            &&( g_prefork_server->m_pChildrenStatusCur[-1].m_pid == 0 ))
        --g_prefork_server->m_pChildrenStatusCur;

}


static int lsapi_init_children_status(void)
{
    char * pBuf;
    int size = 4096;
    int max_children;
    if (g_prefork_server->m_pChildrenStatus)
        return 0;
    max_children = g_prefork_server->m_iMaxChildren
                        + g_prefork_server->m_iExtraChildren;

    size = max_children * sizeof( lsapi_child_status ) * 2 + 3 * sizeof(int);
    size = (size + 4095) / 4096 * 4096;
    pBuf =( char*) mmap( NULL, size, PROT_READ | PROT_WRITE,
        MAP_ANON | MAP_SHARED, -1, 0 );
    if ( pBuf == MAP_FAILED )
    {
        perror( "Anonymous mmap() failed" );
        return -1;
    }
    memset( pBuf, 0, size );
    g_prefork_server->m_pChildrenStatus = (lsapi_child_status *)pBuf;
    g_prefork_server->m_pChildrenStatusCur = (lsapi_child_status *)pBuf;
    g_prefork_server->m_pChildrenStatusEnd = (lsapi_child_status *)pBuf + max_children;
    s_busy_workers = (int *)g_prefork_server->m_pChildrenStatusEnd;
    s_accepting_workers = s_busy_workers + 1;
    s_global_counter = s_accepting_workers + 1;
    s_avail_pages = (size_t *)(s_global_counter + 1);

    setsid();
    return 0;
}


static void dump_debug_info( lsapi_child_status * pStatus, long tmCur )
{
    char achCmd[1024];
    if ( s_pid_dump_debug_info )
    {
        if ( kill( s_pid_dump_debug_info, 0 ) == 0 )
            return;
    }

    lsapi_log("Possible runaway process, UID: %d, PPID: %d, PID: %d, "
             "reqCount: %d, process time: %ld, checkpoint time: %ld, start "
             "time: %ld\n", getuid(), getppid(), pStatus->m_pid,
             pStatus->m_iReqCounter, tmCur - pStatus->m_tmReqBegin,
             tmCur - pStatus->m_tmLastCheckPoint, tmCur - pStatus->m_tmStart );

    s_pid_dump_debug_info = fork();
    if (s_pid_dump_debug_info == 0)
    {
        snprintf( achCmd, 1024, "gdb --batch -ex \"attach %d\" -ex \"set height 0\" "
                "-ex \"bt\" >&2;PATH=$PATH:/usr/sbin lsof -p %d >&2",
                pStatus->m_pid, pStatus->m_pid );
        if ( system( achCmd ) == -1 )
            perror( "system()" );
        exit( 0 );
    }
}


static void lsapi_check_child_status( long tmCur )
{
    int idle = 0;
    int tobekilled;
    int dying = 0;
    int count = 0;
    lsapi_child_status * pStatus = g_prefork_server->m_pChildrenStatus;
    lsapi_child_status * pEnd = g_prefork_server->m_pChildrenStatusCur;
    while( pStatus < pEnd )
    {
        tobekilled = 0;
        if ( pStatus->m_pid != 0 && pStatus->m_pid != -1)
        {
            ++count;
            if ( !pStatus->m_inProcess )
            {
                if (g_prefork_server->m_iCurChildren - dying
                        > g_prefork_server->m_iMaxChildren
                    || idle > g_prefork_server->m_iMaxIdleChildren)
                {
                    ++pStatus->m_iKillSent;
                    //tobekilled = SIGUSR1;
                }
                else
                {
                    if (s_max_idle_secs> 0
                        && tmCur - pStatus->m_tmWaitBegin > s_max_idle_secs + 5)
                    {
                        ++pStatus->m_iKillSent;
                        //tobekilled = SIGUSR1;
                    }
                }
                if (!pStatus->m_iKillSent)
                    ++idle;
            }
            else
            {
                if (tmCur - pStatus->m_tmReqBegin >
                        g_prefork_server->m_iMaxReqProcessTime)
                {
                    if ((pStatus->m_iKillSent % 5) == 0 && s_dump_debug_info)
                        dump_debug_info( pStatus, tmCur );
                    if ( pStatus->m_iKillSent > 5 )
                    {
                        tobekilled = SIGKILL;
                        lsapi_log("Force killing runaway process PID: %d"
                                 " with SIGKILL\n", pStatus->m_pid );
                    }
                    else
                    {
                        tobekilled = SIGTERM;
                        lsapi_log("Killing runaway process PID: %d with "
                                 "SIGTERM\n", pStatus->m_pid );
                    }
                }
            }
            if ( tobekilled )
            {
                if (( kill( pStatus->m_pid, tobekilled ) == -1 ) &&
                    ( errno == ESRCH ))
                {
                    pStatus->m_pid = 0;
                    --count;
                }
                else
                {
                    ++pStatus->m_iKillSent;
                    ++dying;
                }
            }
        }
        ++pStatus;
    }
    if ( abs( g_prefork_server->m_iCurChildren - count ) > 1 )
    {
        lsapi_log("Children tracking is wrong: Cur Children: %d,"
                  " count: %d, idle: %d, dying: %d\n",
                  g_prefork_server->m_iCurChildren, count, idle, dying );
    }
}


//static int lsapi_all_children_must_die(void)
//{
//    int maxWait;
//    int sec =0;
//    g_prefork_server->m_iMaxReqProcessTime = 10;
//    g_prefork_server->m_iMaxIdleChildren = -1;
//    maxWait = 15;
//
//    while( g_prefork_server->m_iCurChildren && (sec < maxWait) )
//    {
//        lsapi_check_child_status(time(NULL));
//        sleep( 1 );
//        sec++;
//    }
//    if ( g_prefork_server->m_iCurChildren != 0 )
//        kill( -getpgrp(), SIGKILL );
//    return 0;
//}


void set_skip_write(void)
{   s_skip_write = 1;   }


int is_enough_free_mem(void)
{
#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
    //minimum 1GB or 10% available free memory
    return (*s_avail_pages > s_min_avail_pages
            || (*s_avail_pages * 10) / s_total_pages > 0);
#endif
    return 1;
}


static int lsapi_prefork_server_accept( lsapi_prefork_server * pServer,
                                        LSAPI_Request * pReq )
{
    struct sigaction act, old_term, old_quit, old_int,
                    old_usr1, old_child;
    lsapi_child_status * child_status;
    int             wait_secs = 0;
    int             ret = 0;
    int             pid;
    time_t          lastTime = 0;
    time_t          curTime = 0;
    fd_set          readfds;
    struct timeval  timeout;

    sigset_t mask;
    sigset_t orig_mask;

    lsapi_init_children_status();

    act.sa_flags = 0;
    act.sa_handler = lsapi_sigchild;
    sigemptyset(&(act.sa_mask));
    if( sigaction( SIGCHLD, &act, &old_child ) )
    {
        perror( "Can't set signal handler for SIGCHILD" );
        return -1;
    }

    /* Set up handler to kill children upon exit */
    act.sa_flags = 0;
    act.sa_handler = lsapi_cleanup;
    sigemptyset(&(act.sa_mask));
    if( sigaction( SIGTERM, &act, &old_term ) ||
        sigaction( SIGINT,  &act, &old_int  ) ||
        sigaction( SIGUSR1, &act, &old_usr1 ) ||
        sigaction( SIGQUIT, &act, &old_quit ))
    {
        perror( "Can't set signals" );
        return -1;
    }

    while( !s_stop )
    {
        if (s_proc_group_timer_cb != NULL) {
            s_proc_group_timer_cb(&s_ignore_pid);
        }

        curTime = time( NULL );
        if (curTime != lastTime )
        {
            lastTime = curTime;
            if (lsapi_parent_dead())
                break;
            lsapi_check_child_status(curTime );
            if (pServer->m_iServerMaxIdle)
            {
                if ( pServer->m_iCurChildren <= 0 )
                {
                    ++wait_secs;
                    if ( wait_secs > pServer->m_iServerMaxIdle )
                        return -1;
                }
                else
                    wait_secs = 0;
            }
        }

#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
        *s_avail_pages = sysconf(_SC_AVPHYS_PAGES);
//        lsapi_log("Memory total: %zd, free: %zd, free %%%zd\n",
//                  s_total_pages, *s_avail_pages, *s_avail_pages * 100 / s_total_pages);

#endif
        FD_ZERO( &readfds );
        FD_SET( pServer->m_fd, &readfds );
        timeout.tv_sec = 1;
        timeout.tv_usec = 0;
        ret = (*g_fnSelect)(pServer->m_fd+1, &readfds, NULL, NULL, &timeout);
        if (ret == 1 )
        {
            int accepting = 0;
            if (s_accepting_workers)
                accepting = __atomic_load_n(s_accepting_workers, __ATOMIC_SEQ_CST);

            if (pServer->m_iCurChildren > 0
                && accepting > 0)
            {
                usleep(400);
                while(accepting-- > 0)
                    sched_yield();
                continue;
            }
        }
        else if ( ret == -1 )
        {
            if ( errno == EINTR )
                continue;
            /* perror( "select()" ); */
            break;
        }
        else
        {
            continue;
        }

        if (pServer->m_iCurChildren >=
            pServer->m_iMaxChildren + pServer->m_iExtraChildren)
        {
            lsapi_log("Reached max children process limit: %d, extra: %d,"
                     " current: %d, busy: %d, please increase LSAPI_CHILDREN.\n",
                     pServer->m_iMaxChildren, pServer->m_iExtraChildren,
                     pServer->m_iCurChildren,
                     s_busy_workers ? *s_busy_workers : -1 );
            usleep( 100000 );
            continue;
        }

        pReq->m_fd = lsapi_accept( pServer->m_fd );
        if ( pReq->m_fd != -1 )
        {
            wait_secs = 0;
            child_status = find_child_status( 0 );

            sigemptyset( &mask );
            sigaddset( &mask, SIGCHLD );

            if ( sigprocmask(SIG_BLOCK, &mask, &orig_mask) < 0 )
            {
                perror( "sigprocmask(SIG_BLOCK) to block SIGCHLD" );
            }

            pid = fork();

            if ( !pid )
            {
                setsid();
                if (sigprocmask(SIG_SETMASK, &orig_mask, NULL) < 0)
                    perror( "sigprocmask( SIG_SETMASK ) to restore SIGMASK in child" );
                g_prefork_server = NULL;
                s_ppid = getppid();
                s_pid = getpid();
                s_req_processed = 0;
                s_proc_group_timer_cb = NULL;
                s_worker_status = child_status;

                if (pthread_atfork_func)
                    (*pthread_atfork_func)(NULL, NULL, set_skip_write);

                __atomic_store_n(&s_worker_status->m_state,
                                 LSAPI_STATE_CONNECTED, __ATOMIC_SEQ_CST);
                if (s_busy_workers)
                    __atomic_add_fetch(s_busy_workers, 1, __ATOMIC_SEQ_CST);
                lsapi_set_nblock( pReq->m_fd, 0 );
                //keep it open if busy_count is used.
                if (!s_keep_listener && s_busy_workers
                    && *s_busy_workers > (pServer->m_iMaxChildren >> 1))
                    s_keep_listener = 1;
                if ((s_uid == 0 || !s_keep_listener || !is_enough_free_mem())
                    && pReq->m_fdListen != -1 )
                {
                    close( pReq->m_fdListen );
                    pReq->m_fdListen = -1;
                }
                /* don't catch our signals */
                sigaction( SIGCHLD, &old_child, 0 );
                sigaction( SIGTERM, &old_term, 0 );
                sigaction( SIGQUIT, &old_quit, 0 );
                sigaction( SIGINT,  &old_int,  0 );
                sigaction( SIGUSR1, &old_usr1, 0 );
                //init_conn_key( pReq->m_fd );
                lsapi_notify_pid( pReq->m_fd );
                s_notified_pid = 1;
                //if ( s_accept_notify )
                //    return notify_req_received( pReq->m_fd );
                return 0;
            }
            else if ( pid == -1 )
            {
                lsapi_perror("fork() failed, please increase process limit", errno);
                if (child_status)
                    child_status->m_pid = 0;
            }
            else
            {
                ++pServer->m_iCurChildren;
                if ( child_status )
                {
                    child_status->m_pid = pid;
                    child_status->m_tmWaitBegin = curTime;
                    child_status->m_tmStart = curTime;
                }
            }
            close( pReq->m_fd );
            pReq->m_fd = -1;

            if (sigprocmask(SIG_SETMASK, &orig_mask, NULL) < 0)
                perror( "sigprocmask( SIG_SETMASK ) to restore SIGMASK" );

        }
        else
        {
            if (( errno == EINTR )||( errno == EAGAIN))
                continue;
            lsapi_perror("accept() failed", errno);
            return -1;
        }
    }
    sigaction( SIGUSR1, &old_usr1, 0 );
    //kill( -getpgrp(), SIGUSR1 );
    //lsapi_all_children_must_die();  /* Sorry, children ;-) */
    return -1;

}


static struct sigaction old_term, old_quit, old_int,
                    old_usr1, old_child;


int LSAPI_Postfork_Child(LSAPI_Request * pReq)
{
    int max_children = g_prefork_server->m_iMaxChildren;
    s_pid = getpid();
    __atomic_store_n(&pReq->child_status->m_pid, s_pid, __ATOMIC_SEQ_CST);
    s_worker_status = pReq->child_status;

    setsid();
    g_prefork_server = NULL;
    s_ppid = getppid();
    s_req_processed = 0;
    s_proc_group_timer_cb = NULL;

    if (pthread_atfork_func)
        (*pthread_atfork_func)(NULL, NULL, set_skip_write);

    __atomic_store_n(&s_worker_status->m_state,
                     LSAPI_STATE_CONNECTED, __ATOMIC_SEQ_CST);
    if (s_busy_workers)
        __atomic_add_fetch(s_busy_workers, 1, __ATOMIC_SEQ_CST);
    lsapi_set_nblock( pReq->m_fd, 0 );
    //keep it open if busy_count is used.
    if (!s_keep_listener && s_busy_workers
        && *s_busy_workers > (max_children >> 1))
        s_keep_listener = 1;
    if ((s_uid == 0 || !s_keep_listener || !is_enough_free_mem())
        && pReq->m_fdListen != -1 )
    {
        close(pReq->m_fdListen);
        pReq->m_fdListen = -1;
    }

    //init_conn_key( pReq->m_fd );
    lsapi_notify_pid(pReq->m_fd);
    s_notified_pid = 1;
    //if ( s_accept_notify )
    //    return notify_req_received( pReq->m_fd );
    return 0;
}


int LSAPI_Postfork_Parent(LSAPI_Request * pReq)
{
    ++g_prefork_server->m_iCurChildren;
    if (pReq->child_status)
    {
        time_t curTime = time( NULL );
        pReq->child_status->m_tmWaitBegin = curTime;
        pReq->child_status->m_tmStart = curTime;
    }
    close(pReq->m_fd);
    pReq->m_fd = -1;
    return 0;
}


int LSAPI_Accept_Before_Fork(LSAPI_Request * pReq)
{
    time_t          lastTime = 0;
    time_t          curTime = 0;
    fd_set          readfds;
    struct timeval  timeout;
    int             wait_secs = 0;
    int             ret = 0;

    lsapi_prefork_server * pServer = g_prefork_server;

    struct sigaction act;

    lsapi_init_children_status();

    act.sa_flags = 0;
    act.sa_handler = lsapi_sigchild;
    sigemptyset(&(act.sa_mask));
    if (sigaction(SIGCHLD, &act, &old_child))
    {
        perror( "Can't set signal handler for SIGCHILD" );
        return -1;
    }

    /* Set up handler to kill children upon exit */
    act.sa_flags = 0;
    act.sa_handler = lsapi_cleanup;
    sigemptyset(&(act.sa_mask));
    if (sigaction(SIGTERM, &act, &old_term) ||
        sigaction(SIGINT,  &act, &old_int ) ||
        sigaction(SIGUSR1, &act, &old_usr1) ||
        sigaction(SIGQUIT, &act, &old_quit))
    {
        perror( "Can't set signals" );
        return -1;
    }
    s_stop = 0;
    pReq->m_reqState = 0;

    while(!s_stop)
    {
        if (s_proc_group_timer_cb != NULL) {
            s_proc_group_timer_cb(&s_ignore_pid);
        }

        curTime = time(NULL);
        if (curTime != lastTime)
        {
            lastTime = curTime;
            if (lsapi_parent_dead())
                break;
            lsapi_check_child_status(curTime);
            if (pServer->m_iServerMaxIdle)
            {
                if (pServer->m_iCurChildren <= 0)
                {
                    ++wait_secs;
                    if ( wait_secs > pServer->m_iServerMaxIdle )
                        return -1;
                }
                else
                    wait_secs = 0;
            }
        }

#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
        *s_avail_pages = sysconf(_SC_AVPHYS_PAGES);
//        lsapi_log("Memory total: %zd, free: %zd, free %%%zd\n",
//                  s_total_pages, *s_avail_pages, *s_avail_pages * 100 / s_total_pages);

#endif
        FD_ZERO(&readfds);
        FD_SET(pServer->m_fd, &readfds);
        timeout.tv_sec = 1;
        timeout.tv_usec = 0;
        ret = (*g_fnSelect)(pServer->m_fd+1, &readfds, NULL, NULL, &timeout);
        if (ret == 1 )
        {
            int accepting = 0;
            if (s_accepting_workers)
                accepting = __atomic_load_n(s_accepting_workers, __ATOMIC_SEQ_CST);

            if (pServer->m_iCurChildren > 0
                && accepting > 0)
            {
                usleep( 400);
                while(accepting-- > 0)
                    sched_yield();
                continue;
            }
        }
        else if (ret == -1)
        {
            if (errno == EINTR)
                continue;
            /* perror( "select()" ); */
            break;
        }
        else
        {
            continue;
        }

        if (pServer->m_iCurChildren >=
            pServer->m_iMaxChildren + pServer->m_iExtraChildren)
        {
            lsapi_log("Reached max children process limit: %d, extra: %d,"
                     " current: %d, busy: %d, please increase LSAPI_CHILDREN.\n",
                     pServer->m_iMaxChildren, pServer->m_iExtraChildren,
                     pServer->m_iCurChildren,
                     s_busy_workers ? *s_busy_workers : -1);
            usleep(100000);
            continue;
        }

        pReq->m_fd = lsapi_accept(pServer->m_fd);
        if (pReq->m_fd != -1)
        {
            wait_secs = 0;
            pReq->child_status = find_child_status(0);

            ret = 0;
            break;
        }
        else
        {
            if ((errno == EINTR) || (errno == EAGAIN))
                continue;
            lsapi_perror("accept() failed", errno);
            ret = -1;
            break;
        }
    }

    sigaction(SIGCHLD, &old_child, 0);
    sigaction(SIGTERM, &old_term, 0);
    sigaction(SIGQUIT, &old_quit, 0);
    sigaction(SIGINT,  &old_int,  0);
    sigaction(SIGUSR1, &old_usr1, 0);

    return ret;
}


int LSAPI_Prefork_Accept_r( LSAPI_Request * pReq )
{
    int             fd;
    int             ret;
    int             wait_secs;
    fd_set          readfds;
    struct timeval  timeout;

    if (s_skip_write)
        return -1;

    LSAPI_Finish_r( pReq );

    if ( g_prefork_server )
    {
        if ( g_prefork_server->m_fd != -1 )
            if ( lsapi_prefork_server_accept( g_prefork_server, pReq ) == -1 )
                return -1;
    }
    else if (s_req_processed > 0 && s_max_busy_workers > 0 && s_busy_workers)
    {
        ret = __atomic_load_n(s_busy_workers, __ATOMIC_SEQ_CST);
        if (ret >= s_max_busy_workers)
        {
            send_conn_close_notification(pReq->m_fd);
            lsapi_close_connection(pReq);
        }
    }

    if ( (unsigned int)s_req_processed > s_max_reqs )
        return -1;

    if ( s_worker_status )
    {
        s_worker_status->m_tmWaitBegin = time( NULL );
    }


    while( g_running )
    {
        if ( pReq->m_fd != -1 )
        {
            fd = pReq->m_fd;
        }
        else if ( pReq->m_fdListen != -1 )
            fd = pReq->m_fdListen;
        else
        {
            break;
        }
        wait_secs = 0;
        while( 1 )
        {
            if ( !g_running )
                return -1;
            if (s_req_processed && s_worker_status
                && s_worker_status->m_iKillSent)
                return -1;
            FD_ZERO( &readfds );
            FD_SET( fd, &readfds );
            timeout.tv_sec = 1;
            timeout.tv_usec = 0;
            if (fd == pReq->m_fdListen)
            {
                if (s_worker_status)
                    __atomic_store_n(&s_worker_status->m_state,
                                     LSAPI_STATE_ACCEPTING, __ATOMIC_SEQ_CST);
                if (s_accepting_workers)
                    __atomic_fetch_add(s_accepting_workers, 1, __ATOMIC_SEQ_CST);
            }
            ret = (*g_fnSelect)(fd+1, &readfds, NULL, NULL, &timeout);
            if (fd == pReq->m_fdListen)
            {
                if (s_accepting_workers)
                    __atomic_fetch_sub(s_accepting_workers, 1, __ATOMIC_SEQ_CST);
                if (s_worker_status)
                    __atomic_store_n(&s_worker_status->m_state,
                                     LSAPI_STATE_IDLE, __ATOMIC_SEQ_CST);
            }

            if ( ret == 0 )
            {
                if ( s_worker_status )
                {
                    s_worker_status->m_inProcess = 0;
                    if (fd == pReq->m_fdListen)
                    {
                        if (s_keep_listener == 0 || !is_enough_free_mem())
                            return -1;
                        if (s_keep_listener == 1)
                        {
                            int wait_time = 10;
                            if (s_busy_workers)
                                wait_time += *s_busy_workers * 10;
                            if (s_accepting_workers)
                                wait_time >>= (*s_accepting_workers);
                            if (wait_secs >= wait_time)
                                return -1;
                        }
                    }
                }
                ++wait_secs;
                if (( s_max_idle_secs > 0 )&&(wait_secs >= s_max_idle_secs ))
                    return -1;
                if ( lsapi_parent_dead() )
                    return -1;
            }
            else if ( ret == -1 )
            {
                if ( errno == EINTR )
                    continue;
                else
                    return -1;
            }
            else if ( ret >= 1 )
            {
                if (s_req_processed && s_worker_status
                    && s_worker_status->m_iKillSent)
                    return -1;
                if ( fd == pReq->m_fdListen )
                {
                    pReq->m_fd = lsapi_accept( pReq->m_fdListen );
                    if ( pReq->m_fd != -1 )
                    {
                        if (s_worker_status)
                            __atomic_store_n(&s_worker_status->m_state,
                                             LSAPI_STATE_CONNECTED,
                                             __ATOMIC_SEQ_CST);
                        if (s_busy_workers)
                            __atomic_fetch_add(s_busy_workers, 1, __ATOMIC_SEQ_CST);

                        fd = pReq->m_fd;

                        lsapi_set_nblock( fd, 0 );
                        //init_conn_key( pReq->m_fd );
                        if (!s_keep_listener)
                        {
                            close( pReq->m_fdListen );
                            pReq->m_fdListen = -1;
                        }
                        if ( s_accept_notify )
                            if ( notify_req_received( pReq->m_fd ) == -1 )
                                return -1;
                    }
                    else
                    {
                        if (( errno == EINTR )||( errno == EAGAIN))
                            continue;
                        lsapi_perror( "lsapi_accept() error", errno );
                        return -1;
                    }
                }
                else
                    break;
            }
        }

        if ( !readReq( pReq ) )
        {
            if ( s_worker_status )
            {
                s_worker_status->m_iKillSent = 0;
                s_worker_status->m_inProcess = 1;
                ++s_worker_status->m_iReqCounter;
                s_worker_status->m_tmReqBegin =
                s_worker_status->m_tmLastCheckPoint = time(NULL);
            }
            ++s_req_processed;
            return 0;
        }
        lsapi_close_connection(pReq);
        LSAPI_Reset_r( pReq );
    }
    return -1;

}


void LSAPI_Set_Max_Reqs( int reqs )
{   s_max_reqs = reqs - 1;      }

void LSAPI_Set_Max_Idle( int secs )
{   s_max_idle_secs = secs;     }


void LSAPI_Set_Max_Children( int maxChildren )
{
    if ( g_prefork_server )
        g_prefork_server->m_iMaxChildren = maxChildren;
}


void LSAPI_Set_Extra_Children( int extraChildren )
{
    if (( g_prefork_server )&&( extraChildren >= 0 ))
        g_prefork_server->m_iExtraChildren = extraChildren;
}


void LSAPI_Set_Max_Process_Time( int secs )
{
    if (( g_prefork_server )&&( secs > 0 ))
        g_prefork_server->m_iMaxReqProcessTime = secs;
}


void LSAPI_Set_Max_Idle_Children( int maxIdleChld )
{
    if (( g_prefork_server )&&( maxIdleChld > 0 ))
        g_prefork_server->m_iMaxIdleChildren = maxIdleChld;
}


void LSAPI_Set_Server_Max_Idle_Secs( int serverMaxIdle )
{
    if ( g_prefork_server )
        g_prefork_server->m_iServerMaxIdle = serverMaxIdle;
}


void LSAPI_Set_Slow_Req_Msecs( int msecs )
{
    s_slow_req_msecs = msecs;
}


int  LSAPI_Get_Slow_Req_Msecs(void)
{
    return s_slow_req_msecs;
}


void LSAPI_No_Check_ppid(void)
{
    s_ppid = 0;
}


int LSAPI_Get_ppid(void)
{
    return(s_ppid);
}


#if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
#include <crt_externs.h>
#else
extern char ** environ;
#endif
static void unset_lsapi_envs(void)
{
    char **env;
#if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
    env = *_NSGetEnviron();
#else
    env = environ;
#endif
    while( env != NULL && *env != NULL )
    {
        if (!strncmp(*env, "LSAPI_", 6) || !strncmp( *env, "PHP_LSAPI_", 10 )
            || (!strncmp( *env, "PHPRC=", 6 )&&(!s_uid)))
        {
            char ** del = env;
            do
                *del = del[1];
            while( *del++ );
        }
        else
            ++env;
    }
}


static int lsapi_initSuEXEC(void)
{
    int i;
    struct passwd * pw;
    s_defaultUid = 0;
    s_defaultGid = 0;
    if ( s_uid == 0 )
    {
        const char * p = getenv( "LSAPI_DEFAULT_UID" );
        if ( p )
        {
            i = atoi( p );
            if ( i > 0 )
                s_defaultUid = i;
        }
        p = getenv( "LSAPI_DEFAULT_GID" );
        if ( p )
        {
            i = atoi( p );
            if ( i > 0 )
                s_defaultGid = i;
        }
        p = getenv( "LSAPI_SECRET" );
        if (( !p )||( readSecret(p) == -1 ))
                return -1;
        if ( g_prefork_server )
        {
            if ( g_prefork_server->m_iMaxChildren < 100 )
                g_prefork_server->m_iMaxChildren = 100;
            if ( g_prefork_server->m_iExtraChildren < 1000 )
                g_prefork_server->m_iExtraChildren = 1000;
        }
    }
    if ( !s_defaultUid || !s_defaultGid )
    {
        pw = getpwnam( "nobody" );
        if ( pw )
        {
            if ( !s_defaultUid )
                s_defaultUid = pw->pw_uid;
            if ( !s_defaultGid )
                s_defaultGid = pw->pw_gid;
        }
        else
        {
            if ( !s_defaultUid )
                s_defaultUid = 10000;
            if ( !s_defaultGid )
                s_defaultGid = 10000;
        }
    }
    return 0;
}


static int lsapi_check_path(const char *p, char *final, int max_len)
{
    char resolved_path[PATH_MAX+1];
    int len = 0;
    char *end;
    if (*p != '/')
    {
        if (getcwd(final, max_len) == NULL)
            return -1;
        len = strlen(final);
        *(final + len) = '/';
        ++len;
    }
    end = memccpy(&final[len], p, '\0', PATH_MAX - len);
    if (!end)
    {
        errno = EINVAL;
        return -1;
    }
    p = final;
    if (realpath(p, resolved_path) == NULL
        && errno != ENOENT && errno != EACCES)
        return -1;
    if (strncmp(resolved_path, "/etc/", 5) == 0)
    {
        errno = EPERM;
        return -1;
    }
    return 0;
}


static int lsapi_reopen_stderr2(const char *full_path)
{
    int newfd = open(full_path, O_WRONLY | O_CREAT | O_APPEND, 0644);
    if (newfd == -1)
    {
        LSAPI_perror_r(NULL, "Failed to open custom stderr log", full_path);
        return -1;
    }
    if (newfd != 2)
    {
        dup2(newfd, 2);
        close(newfd);
        dup2(2, 1);
    }
    if (s_stderr_log_path && full_path != s_stderr_log_path)
    {
        free(s_stderr_log_path);
        s_stderr_log_path = NULL;
    }
    s_stderr_log_path = strdup(full_path);
    return 0;
}


static int lsapi_reopen_stderr(const char *p)
{
    char full_path[PATH_MAX];
    if (s_uid == 0)
        return -1;
    if (lsapi_check_path(p, full_path, PATH_MAX) == -1)
    {
        LSAPI_perror_r(NULL, "Invalid custom stderr log path", p);
        return -1;
    }
    return lsapi_reopen_stderr2(full_path);
}


int LSAPI_Init_Env_Parameters( fn_select_t fp )
{
    const char *p;
    char ch;
    int n;
    int avoidFork = 0;

    p = getenv("LSAPI_STDERR_LOG");
    if (p)
    {
        lsapi_reopen_stderr(p);
    }
    if (!s_stderr_log_path)
        s_stderr_is_pipe = isPipe(STDERR_FILENO);

    p = getenv( "PHP_LSAPI_MAX_REQUESTS" );
    if ( !p )
        p = getenv( "LSAPI_MAX_REQS" );
    if ( p )
    {
        n = atoi( p );
        if ( n > 0 )
            LSAPI_Set_Max_Reqs( n );
    }

    p = getenv( "LSAPI_KEEP_LISTEN" );
    if ( p )
    {
        n = atoi( p );
        s_keep_listener = n;
    }

    p = getenv( "LSAPI_AVOID_FORK" );
    if ( p )
    {
        avoidFork = atoi( p );
        if (avoidFork)
        {
            s_keep_listener = 2;
            ch = *(p + strlen(p) - 1);
            if (  ch == 'G' || ch == 'g' )
                avoidFork *= 1024 * 1024 * 1024;
            else if (  ch == 'M' || ch == 'm' )
                avoidFork *= 1024 * 1024;
            if (avoidFork >= 1024 * 10240)
                s_min_avail_pages = avoidFork / 4096;
        }
    }

    p = getenv( "LSAPI_ACCEPT_NOTIFY" );
    if ( p )
    {
        s_accept_notify = atoi( p );
    }

    p = getenv( "LSAPI_SLOW_REQ_MSECS" );
    if ( p )
    {
        n = atoi( p );
        LSAPI_Set_Slow_Req_Msecs( n );
    }

#if defined( RLIMIT_CORE )
    p = getenv( "LSAPI_ALLOW_CORE_DUMP" );
    if ( !p )
    {
        struct rlimit limit = { 0, 0 };
        setrlimit( RLIMIT_CORE, &limit );
    }
    else
        s_enable_core_dump = 1;

#endif

    p = getenv( "LSAPI_MAX_IDLE" );
    if ( p )
    {
        n = atoi( p );
        LSAPI_Set_Max_Idle( n );
    }

    if ( LSAPI_Is_Listen() )
    {
        n = 0;
        p = getenv( "PHP_LSAPI_CHILDREN" );
        if ( !p )
            p = getenv( "LSAPI_CHILDREN" );
        if ( p )
            n = atoi( p );
        if ( n > 1 )
        {
            LSAPI_Init_Prefork_Server( n, fp, avoidFork != 0 );
            LSAPI_Set_Server_fd( g_req.m_fdListen );
        }

        p = getenv( "LSAPI_EXTRA_CHILDREN" );
        if ( p )
            LSAPI_Set_Extra_Children( atoi( p ) );

        p = getenv( "LSAPI_MAX_IDLE_CHILDREN" );
        if ( p )
            LSAPI_Set_Max_Idle_Children( atoi( p ) );

        p = getenv( "LSAPI_PGRP_MAX_IDLE" );
        if ( p )
        {
            LSAPI_Set_Server_Max_Idle_Secs( atoi( p ) );
        }

        p = getenv( "LSAPI_MAX_PROCESS_TIME" );
        if ( p )
            LSAPI_Set_Max_Process_Time( atoi( p ) );

        if ( getenv( "LSAPI_PPID_NO_CHECK" ) )
        {
            LSAPI_No_Check_ppid();
        }

        p = getenv("LSAPI_MAX_BUSY_WORKER");
        if (p)
        {
            n = atoi(p);
            s_max_busy_workers = n;
            if (n >= 0)
                LSAPI_No_Check_ppid();
        }


        p = getenv( "LSAPI_DUMP_DEBUG_INFO" );
        if ( p )
            s_dump_debug_info = atoi( p );

        if ( lsapi_initSuEXEC() == -1 )
            return -1;
#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
        lsapi_initLVE();
#endif
    }
    unset_lsapi_envs();
    return 0;
}


int LSAPI_ErrResponse_r( LSAPI_Request * pReq, int code, const char ** pRespHeaders,
                         const char * pBody, int bodyLen )
{
    LSAPI_SetRespStatus_r( pReq, code );
    if ( pRespHeaders )
    {
        while( *pRespHeaders )
        {
            LSAPI_AppendRespHeader_r( pReq, *pRespHeaders, strlen( *pRespHeaders ) );
            ++pRespHeaders;
        }
    }
    if ( pBody &&( bodyLen > 0 ))
    {
        LSAPI_Write_r( pReq, pBody, bodyLen );
    }
    LSAPI_Finish_r( pReq );
    return 0;
}


static void lsapi_MD5Transform(uint32 buf[4], uint32 const in[16]);

/*
 * Note: this code is harmless on little-endian machines.
 */
static void byteReverse(unsigned char *buf, unsigned longs)
{
    uint32 t;
    do {
        t = (uint32) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
            ((unsigned) buf[1] << 8 | buf[0]);
        *(uint32 *) buf = t;
        buf += 4;
    } while (--longs);
}


/*
 * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
 * initialization constants.
 */
void lsapi_MD5Init(struct lsapi_MD5Context *ctx)
{
    ctx->buf[0] = 0x67452301;
    ctx->buf[1] = 0xefcdab89;
    ctx->buf[2] = 0x98badcfe;
    ctx->buf[3] = 0x10325476;

    ctx->bits[0] = 0;
    ctx->bits[1] = 0;
}

/*
 * Update context to reflect the concatenation of another buffer full
 * of bytes.
 */
void lsapi_MD5Update(struct lsapi_MD5Context *ctx, unsigned char const *buf, unsigned len)
{
    register uint32 t;

    /* Update bitcount */

    t = ctx->bits[0];
    if ((ctx->bits[0] = t + ((uint32) len << 3)) < t)
        ctx->bits[1]++;                /* Carry from low to high */
    ctx->bits[1] += len >> 29;

    t = (t >> 3) & 0x3f;        /* Bytes already in shsInfo->data */

    /* Handle any leading odd-sized chunks */

    if (t) {
        unsigned char *p = (unsigned char *) ctx->in + t;

        t = 64 - t;
        if (len < t) {
            memmove(p, buf, len);
            return;
        }
        memmove(p, buf, t);
        byteReverse(ctx->in, 16);
        lsapi_MD5Transform(ctx->buf, (uint32 *) ctx->in);
        buf += t;
        len -= t;
    }
    /* Process data in 64-byte chunks */

    while (len >= 64) {
        memmove(ctx->in, buf, 64);
        byteReverse(ctx->in, 16);
        lsapi_MD5Transform(ctx->buf, (uint32 *) ctx->in);
        buf += 64;
        len -= 64;
    }

    /* Handle any remaining bytes of data. */

    memmove(ctx->in, buf, len);
}


/*
 * Final wrap-up - pad to 64-byte boundary with the bit pattern
 * 1 0* (64-bit count of bits processed, MSB-first)
 */
void lsapi_MD5Final(unsigned char digest[16], struct lsapi_MD5Context *ctx)
{
    unsigned int count;
    unsigned char *p;

    /* Compute number of bytes mod 64 */
    count = (ctx->bits[0] >> 3) & 0x3F;

    /* Set the first char of padding to 0x80.  This is safe since there is
       always at least one byte free */
    p = ctx->in + count;
    *p++ = 0x80;

    /* Bytes of padding needed to make 64 bytes */
    count = 64 - 1 - count;

    /* Pad out to 56 mod 64 */
    if (count < 8) {
        /* Two lots of padding:  Pad the first block to 64 bytes */
        memset(p, 0, count);
        byteReverse(ctx->in, 16);
        lsapi_MD5Transform(ctx->buf, (uint32 *) ctx->in);

        /* Now fill the next block with 56 bytes */
        memset(ctx->in, 0, 56);
    } else {
        /* Pad block to 56 bytes */
        memset(p, 0, count - 8);
    }
    byteReverse(ctx->in, 14);

    /* Append length in bits and transform */
    ((uint32 *) ctx->in)[14] = ctx->bits[0];
    ((uint32 *) ctx->in)[15] = ctx->bits[1];

    lsapi_MD5Transform(ctx->buf, (uint32 *) ctx->in);
    byteReverse((unsigned char *) ctx->buf, 4);
    memmove(digest, ctx->buf, 16);
    memset(ctx, 0, sizeof(*ctx));        /* In case it's sensitive */
}


/* The four core functions - F1 is optimized somewhat */

/* #define F1(x, y, z) (x & y | ~x & z) */
#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))

/* This is the central step in the MD5 algorithm. */
#define MD5STEP(f, w, x, y, z, data, s) \
        ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )

/*
 * The core of the MD5 algorithm, this alters an existing MD5 hash to
 * reflect the addition of 16 longwords of new data.  MD5Update blocks
 * the data and converts bytes into longwords for this routine.
 */
static void lsapi_MD5Transform(uint32 buf[4], uint32 const in[16])
{
    register uint32 a, b, c, d;

    a = buf[0];
    b = buf[1];
    c = buf[2];
    d = buf[3];

    MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
    MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
    MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
    MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
    MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
    MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
    MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
    MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
    MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
    MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
    MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
    MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
    MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
    MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
    MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
    MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);

    MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
    MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
    MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
    MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
    MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
    MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
    MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
    MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
    MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
    MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
    MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
    MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
    MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
    MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
    MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
    MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);

    MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
    MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
    MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
    MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
    MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
    MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
    MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
    MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
    MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
    MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
    MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
    MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
    MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
    MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
    MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
    MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);

    MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
    MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
    MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
    MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
    MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
    MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
    MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
    MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
    MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
    MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
    MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
    MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
    MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
    MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
    MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
    MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);

    buf[0] += a;
    buf[1] += b;
    buf[2] += c;
    buf[3] += d;
}


int LSAPI_Set_Restored_Parent_Pid(int pid)
{
    int old_ppid = s_ppid;
    s_restored_ppid = pid;
    return old_ppid;
}


int LSAPI_Inc_Req_Processed(int cnt)
{
    return __atomic_add_fetch(s_global_counter, cnt, __ATOMIC_SEQ_CST);
}


ELF          >    S      @       ('         @ 8 	 @                                                                !     !                                    !     !                              8      8      8      $       $                                                             Std                                            Ptd   p      p      p                         Qtd                                                  Rtd        !     !     0
      0
                      GNU J㋚{(zP:    C         	       H  3@( L ` qCSl P*fR                                                                                                                                                                                                                                   n}'3qѮl>&Sɶ
ܮŉSO`[is|&߱R D/y7řkՊ eY&09=By:%/=ejOzJ6'l#mNULCB1{!\$O#W23S=apbU06aD7jp#7ĴDIΊ=\4yݾCEкQuo	rSѮIo|q%h6	󝵛'
=qX                                             [                                                               u                                          	                                                                w	                     f                                                                                                            #	                     	                                                                !
                                          y                                                                  s                                           O                     f	                                                                                                         |
                     
                                                                                                           [                                                                                                                                                                         ^                     k                                          	                                           &                                                                                                                                  !                   \
                     	                     2                     Z	                     R                     T                     	                     s                                                               
                                           ?                                            +                     	                                          A	                                          >                                          n                                          	                                                                                     -                     r
                     L                     H                     	                     
  "                   .                                                                                    
  "                   
  "                   $                     7                     x                                           	                     W                     ,
                                          9
                                                               
                                                                                                         A                                           .	                     9                                                                                     4                                          ,                                                                 2                                                                                    F   "                                                             O	                                                                                    E                     
                                          
                     L
                     r                 G    0                  |      F           p             D                  
          S                
      5    t      i       ~    p                 P            z    @!     	      b                 .                 	    !                            ]    `      Z       \    e                @n                              v          1           p             Y                `    p             @                                       pr      l          y            j     @U                 p|                 P      -          r      ]           Д      	           n                  q      Y           0n                 Г             5    p             o    w      $          ~      l      !    s            U     T             E    `u                q      S           m      7            n             T    `      (                                                                               {      F           `q      J                  p          !                 }             I    @                                                         !      b    P             g                     p      @       $    "!                       l           0            6    Pn                0                                 !              __gmon_start__ _ITM_deregisterTMCloneTable _ITM_registerTMCloneTable __cxa_finalize compareValueLocation set_skip_write sigaction sigemptyset __stack_chk_fail realloc fcntl accept setsockopt mmap memset setsid read __errno_location close writev kill getppid __ctype_b_loc strncpy strchr strcasecmp strtol getaddrinfo memcpy freeaddrinfo inet_addr LSAPI_Log __vfprintf_chk __snprintf_chk getuid __fprintf_chk gettimeofday localtime_r waitpid fork system exit lsapi_perror strerror LSAPI_is_suEXEC_Daemon LSAPI_Stop LSAPI_IsRunning LSAPI_Register_Pgrp_Timer_Callback LSAPI_InitRequest malloc getpeername dup2 LSAPI_Init geteuid signal g_req dlopen dlsym LSAPI_Is_Listen_r LSAPI_Is_Listen LSAPI_Reset_r LSAPI_Release_r free LSAPI_GetHeader_r LSAPI_ReqBodyGetChar_r LSAPI_ReqBodyGetLine_r memchr memmove LSAPI_ReadReqBody_r Flush_RespBuf_r LSAPI_GetEnv_r strcmp __ctype_toupper_loc LSAPI_ForeachOrgHeader_r qsort LSAPI_ForeachHeader_r LSAPI_ForeachEnv_r LSAPI_ForeachSpecialEnv_r LSAPI_FinalizeRespHeaders_r LSAPI_Flush_r LSAPI_Write_Stderr_r getpid getcwd memccpy __realpath_chk LSAPI_Finish_r LSAPI_End_Response_r LSAPI_Write_r LSAPI_sendfile_r sendfile LSAPI_AppendRespHeader2_r strlen LSAPI_AppendRespHeader_r LSAPI_CreateListenSock2 socket bind listen unlink LSAPI_ParseSockAddr LSAPI_CreateListenSock LSAPI_Init_Prefork_Server calloc setpgid sysconf LSAPI_Set_Server_fd LSAPI_reset_server_state is_enough_free_mem LSAPI_Postfork_Child LSAPI_Postfork_Parent time LSAPI_Accept_Before_Fork __fdelt_chk usleep sched_yield LSAPI_Set_Max_Reqs LSAPI_Set_Max_Idle LSAPI_Set_Max_Children LSAPI_Set_Extra_Children LSAPI_Set_Max_Process_Time LSAPI_Set_Max_Idle_Children LSAPI_Set_Server_Max_Idle_Secs LSAPI_Set_Slow_Req_Msecs LSAPI_Get_Slow_Req_Msecs LSAPI_No_Check_ppid LSAPI_Get_ppid LSAPI_Init_Env_Parameters getenv getpwnam dlerror setrlimit __fxstat setreuid LSAPI_ErrResponse_r lsapi_MD5Init lsapi_MD5Update lsapi_MD5Final getpwuid setgid setgroups setuid strtoll prctl initgroups LSAPI_Accept_r LSAPI_Prefork_Accept_r sigaddset sigprocmask LSAPI_Set_Restored_Parent_Pid LSAPI_Inc_Req_Processed select rb_str_new rb_hash_aset rb_gc_mark munmap rb_string_value rb_string_value_ptr rb_eval_string_wrap rb_str_new_static ruby_strdup mkstemp ftruncate rb_str_buf_new rb_str_cat rb_num2int rb_fix2int memmem rb_yield rb_gc_writebarrier_unprotect rb_io_puts rb_ary_detransient rb_check_type rb_intern2 rb_funcallv rb_obj_as_string rb_f_sprintf s_fn_add_env rb_ruby_verbose_ptr rb_define_global_const rb_default_rs rb_exec_recursive rb_output_fs rb_output_rs rb_lastline_get Init_lsapi chdir rb_stderr rb_cObject rb_const_get rb_global_variable rb_define_class rb_data_object_zalloc rb_stdout rb_stdin rb_hash_new __memcpy_chk rb_define_method rb_define_global_function rb_define_singleton_method libruby.so.3.0 libm.so.6 libc.so.6 __environ _edata __bss_start _end GLIBC_2.14 GLIBC_2.15 GLIBC_2.4 GLIBC_2.3.4 GLIBC_2.2.5 GLIBC_2.3 /opt/alt/ruby30/lib64                                                                                                                                                                                                                        
            )        4     ii   ?     ti	   I     ui	   U     ii   a      !            pT      !            0T      !            !      !                  !            q      !                  !            w       !            ~      (!                  0!                  8!                  @!                  H!                  P!                  X!                  `!                  h!                  p!                  x!                  !                  !                  !                  !                  !                  !            "      !            -      !            ;      !            M      !            V      !            d      !            m      !                  !            g      !                  !                   !                   !                  (!                  0!                  8!                  @!                  H!                  P!                  X!            ,      `!            ;      h!            G      p!            T      x!            ^      !            j      !            w      !                  !                  !                  !                  !                  !                  !                  !            	      !                  !            )      !            2      !            8      !            8      !            I      !            Y      !            X!     !            !     !                  P!                   X!                   `!                   h!                   p!                   x!                   !        !           !        2           !                   !        <           !        H           !        J           !        R           !        V           !        V           !        W           !                   !                   !        m           !        {           !                   !                   
!                   
!                    
!                   (
!                   0
!                   8
!                   @
!                   H
!                   P
!                   X
!                   `
!                   h
!        	           p
!        
           x
!                   
!                   
!                   
!                   
!                   
!                   
!                   
!                   
!                   
!                   
!                   
!                   
!                   
!                   
!                   
!                   
!                    !                   !                   !                   !                    !                   (!                   0!                   8!                   @!                   H!                   P!                    X!        "           `!        #           h!                   p!        $           x!        %           !        &           !                   !        '           !        (           !                   !        )           !                   !                   !                   !        *           !        +           !        ,           !        -           !                   !                   !                    !                   !        .           !        /           !        0            !                   (!        1           0!                   8!                   @!        3           H!        4           P!        5           X!        6           `!        7           h!        8           p!        9           x!        ;           !        =           !        >           !        ?           !        @           !                   !        A           !        B           !        C           !        D           !        E           !        F           !                   !        G           !                   !        I           !        K            !        L           !        M           !        N           !        O            !                   (!        P           0!        Q           8!                   @!        S           H!                   P!        T           X!        U           `!        X           h!        Y           p!        Z           x!        [           !        \           !        ]           !        ^           !                   !        _           !        `           !                   !        a           !        b           !        c           !        d           !        e           !        f           !        g           !        h           !        i            !                   !        j           !        k           !        l            !                   (!                   0!        n           8!        o           @!        p           H!        q           P!        r           X!                   `!        s           h!        t           p!        u           x!        w           !        x           !        y           !        z           !        |           !                   !        }           !        ~           !                   !                   !                   !                   !                   !                   !                   !                   !                    !                   !                   !                   !                    !                   (!                   0!                   8!                   @!                   H!                   HH1  HtH     5z  %{   h    h   h   h   h   h   h   h   qh   ah	   Qh
   Ah   1h   !h   h   h   h   h   h   h   h   h   h   h   qh   ah   Qh   Ah   1h   !h   h   h   h    h!   h"   h#   h$   h%   h&   h'   qh(   ah)   Qh*   Ah+   1h,   !h-   h.   h/   h0   h1   h2   h3   h4   h5   h6   h7   qh8   ah9   Qh:   Ah;   1h<   !h=   h>   h?   h@   hA   hB   hC   hD   hE   hF   hG   qhH   ahI   QhJ   AhK   1hL   !hM   hN   hO   hP   hQ   hR   hS   hT   hU   hV   hW   qhX   ahY   QhZ   Ah[   1h\   !h]   h^   h_   h`   ha   hb   hc   hd   he   hf   hg   qhh   ahi   Qhj   Ahk   1hl   !hm   hn   ho   hp   hq   hr   hs   ht   hu   hv   hw   qhx   ahy   Qhz   Ah{   1h|   !h}   h~   h   h   h   h   h   h   h   h   h   qh   ah   Qh   Ah   1h   !h   h   h   h   h   h   h   h   h   h   h   qh   ah   Qh   Ah   1h   !h   h   h   h   h   h   h   h   h   h   h   q%  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %}  D  %u  D  %m  D  %e  D  %]  D  %U  D  %M  D  %E  D  %=  D  %5  D  %-  D  %%  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %ݿ  D  %տ  D  %Ϳ  D  %ſ  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %}  D  %u  D  %m  D  %e  D  %]  D  %U  D  %M  D  %E  D  %=  D  %5  D  %-  D  %%  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %ݾ  D  %վ  D  %;  D  %ž  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %}  D  %u  D  %m  D  %e  D  %]  D  %U  D  %M  D  %E  D  %=  D  %5  D  %-  D  %%  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %ݽ  D  %ս  D  %ͽ  D  %Ž  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %}  D  %u  D  %m  D  %e  D  %]  D  %U  D  %M  D  %E  D  %=  D  %5  D  %-  D  %%  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %ݼ  D  %ռ  D  %ͼ  D  %ż  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %}  D  %u  D  %m  D  %e  D  %]  D  %U  D  %M  D  %E  D  %=  D  %5  D  %-  D  %%  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  %ݻ  D  %ջ  D  %ͻ  D  %Ż  D  %  D  HY  H     Hf  H81\%    fH=  H  H9tH~  Ht	        H=  H5  H)HHH?HHtHŻ  HtfD      =   u+UH=   HtH=  id}  ]     w    ff.           ÐHGH+F HcAVIH@AUATL$USHtQHHtIHIL9r0HI9v'KHSMsH;Յ[]A\A]A^     [D]A\A]A^øff.     f=  D  r     ÐOAWDD_AVAUATUSD6^nAxj׋G3GD!3GV\$ЋW^$DD1\$!3WAʋNFp $EL$A1A1DD^!D1G;νD\$DEDVDT$A!A1EE|A
1AD!E1DD*ƇGD1D!A1A1DDNDL$E	F0D!DnA1D1DGFEDf Dd$D^(A!A1EEؘiA
1AD!1DDDʋ^0D1D!A1DE[D1!D1DDN,A1DL$G\EA!Df8A1ED"kA
1AD!1DDN4EqDD1!1DECyD1!D1DDV<1G!I!1DDD$
E b%1!1DDD$E@@1!1DDD$	EQZ^&1!1DE6Ƕ1!1DD]/։1!1DESD1!1DE
؉	1!1DDD$E01!1DDD$E !1!1DE7É1!1DDD$	E1!1DDD$A0ZEAA1A!A1AA㩉AAD1!1t$DD1!AogD1	1D!FL*1DD$Ή1AA!B9A1DD$AAD1D$qDD11D$0"amD1G81Ɖ11DDD$	ED꾤11DDD$AKAA1A5`KA1AЉApA1AD1D1D1A	~(D	1G'111DDD$A0AA1A1AЋT$A2A1D1֋T$	
9ىDD11D11C|AA1A1AD$A0eVĉA1D1AD")Dt$	D	D1A*CDG#	1
	1DD9Ή	1DDY[e\$	1DEDt$	щ1DE3}D\$
	1DDD$E ]	1DEO~oAAD	1DE
,DT$	A1ADE6CDt$
AN	1A~SADEAA	A1A5:ADAAD	1Љ3*\$D	D1DFӆ[
]A\A]A^	1։	1DƉA4A_OWGOW    ATI1USH   dH%(   H$   1HHH<$ t)H$   dH3%(   u<HĠ   []A\f.     H{w1HމǄ$       L$$luD  Hٿ  HA(HQ8H9s;8ufD  98tH0H9w1ÅtHP0H;Q0vHQ0D  fH@$    @@@,     D  UHcSHHHH@Ht#HSPHH+S@HC@HHSPHCH1H[]øf     U1҉1S   Htt/H1[]fD  tH߾   [1]rfff.     SH   dH%(   H$   1HT$Ht$D$   D$   Ãtf|$t'H$   dH3%(   u0HĠ   [f     HL$A      Ǿ   ff.     f       HcHvLHL9   HH)H   SNf.     E      LI؃HLGLECHDGwI9thHH)H~SHpH2HpD H2HpDXH2pAEL@LIcApDHcLML9i[f0uH[H1øËuHH1f     AVAUE1ATUH-  SH}( t[D]A\A]A^ EEA!   Lc@   D
     DIE11A McLbHHt]L1HlKvH](HH]0HH]8HCH  H  HCHHܸ  Hݸ  [D]A\A]A^H=uq  A1     H   H   H+   HcpG )   H   HxsH9AVHNAUATUISHwHDwH    LHDjIHu!|8u
  uD[]A\A]A^ÐH~   []A\A]A^øfD  USHtMHu8u
  uHɻ  E Ht(H  Ht@ H[]ff.     @ AWAVAUATUSH   0  t8AAIAfI7D#Å-tx  uDD)H[]A\A]A^A_    A)E~ڋζ  tIf     H)I~HPHcH9vHIH)Hx      tsE)EAOr1k Sź  t-=  t+1Du[8    1[@ 9[ÐAVAUATUHSHHP  dH%(   H$H  1H
fD  HHDB uLd$@   HLTD$@Ƅ$?   </tc<[      :   LfE 5H    |$@*HXz  H5kn  LAƅ;  E  M      H}l   fu L1H$H  dH3%(   Q  HP  []A\A]A^D  
   Ml$]   fM LH    |$A*HXA      1;:
   1HHHÍ@=     Euf1f]YD  E f1HT$)D$HL$LD$H      )D$ )D$0HD$upLd$HAT$It$LLE1MEA<     E    E1M"::  AD$ MfA$
    AUIATUSH(  H$  H$  L$  L$  t@)$  )$  )$  )$  )$  )$  )$   )$  dH%(   H$h  1   t==  M  Ld$`L@@u         L9   HW  H;HL$HL   H$P  D$H   HD$PH$p  D$L0   HD$XH$h  dH3%(     H(  []A\A] H  HLk  HL¾d   1   CHHÁ   K-  HHߺ   UAL8k  d   H1HHXZL9HHc  M1L)H
k     H;gfH1Ld$`HHt$H   uI   D$   L   Lj     PD$PDL$(1^Y^HcLLHD$L$q     L      PD$PD$$PD$0PD$<PD$HPD$TDl  1H0HcL/ff.     @ AWAVAUATUSH(dH%(   HD$1H=f   .  D$   Hl$L5i  L-i  L%p  @    HfAǅ   T$Ѓ<~$ML     DME1D;=  tD;=  tUDHHtHH1@1@Ɖ@   H2  Ht(H      hK   9H5i  HN0HV(H9s*DAHAEtD  H08u.HH9rHF0HD$dH3%(   uH([]A\A]A^A_ HN0D$@1D$XHr  HDCff.     AWAVAUATUHSHH(  =[  dH%(   H$  1t1thHC(IID3L+cI)HC D{H)-D$HEEATH5n    AU1UL$,H ղ  t)H$  dH3%(   ulH(  []A\A]A^A_@ DH\$H   H߹      AQLn  $XHZt1fD  H=Cg  5D  AWAVAUATUSHL  IZ(Mj0L9  H|$E1E1E1@ BveCAl$   ABD)A;B  E9r
    ~ HSHL$HH)H9   fD  CAfA H0I9wARD)1)ȃ  H[]A\A]A^A_fD  HC Ht$H)IcBH9   Cigf  f)f9u.     Cf~pH5m    1=;	   tpCAL=  AfC5fD  CfC     A     H5m    1;   1u8u    Lů  HEED[H5m  ]  A\1A]A^A_vfD  Ht$H@ E1E1E1zf.     UHSHHHI[H5d    1]	f     b  1u1=g    >      Ð2  D  H=-  @ ATUSH   dH%(   H$   1H}  H    HH1HǇ 	      HىHH)   	  HH{`IH0  HCxHS`Lc`    LH)HCxHCpLH)HCpI$   HChHC8HC(H   H    I   HHC0H(  LcxLcpH   l   twHT$Ht$D$   t
}8kt01kH$   dH3%(   uiHĠ   []A\fD  +   CC1    1   H=b  11#_fD  ff.     Sŭ  t	1ۉ[ H5L   @   &  eH5>
   T            H=G  1(tII     D   H=1b  .  HcH5$b  HH  [ÉD 1? H=͞  0HW(Hw`HǇ       HHǇ0      H   HWHVHWHWHWHWH)8  1H    SHHHt
H   HtH   HtH{@Ht1[fD  HtGwBL   HcAT4t/HcApH   HH: t
 H   H    1ff.     fHtPtJSHc   H;   }HSHH      [ ~	Hc   и[Ã AWAVAUATUSHZHHHD$H:  G   H%  H      IH   I   IILfD  A   )HcH   L9HcIOIvI
   HLHtML)HLHXHHA   I   A$   D)E  H[]A\A]A^A_    LHHHA   L|$I   I)A   M?D  LLHcH~A   -H1|v@ AVAUATUSH   I   HH   HH   H   H+   E1H   H9Hc   HO؋   )HH~)H9HwHHNHHIE   LL)Ht6Eu@ HHD:Hu4O8u
  uMt-M   [L]A\A]A^     H~IHH)uID  HO(HW8H   Ǉ   LS    H)ʍB     HGpH0HpH@   Hwp~HcHHH HPHO8HGp    AWAVAUATUSHH   HT$H   HH<$   IH=Y]      HcB$H   H@H,H9rZf.     HH9vGH3L<uHCH[]A\A]A^A_HD$L9  IM9   f.     1H[]A\A]A^A_    H$1L=ې  L   @ Al4tI4L   HHuHD$HcP 1~H$HL   Mt M9sH   H$ID$HD$@ IcMIcm H,$L| L9)A\$)KH8HD$'-t	_HHI9tHU :t 8 IcUIcEH$H:      H$HcHcAVH   H: @ AVAUATUSL$ H   H$ L9uHdH%(   H$@  1H  HH  H   H  HE1LR  Lh  f     H   HcHcT4t7qH   M
 HIcAHLEHTDTtHHuH   HcP    H   HLL9   IcIHLfHH I9   HcHHc0AH    LcPIHcHH   B DBHJHH2JA   u   Hܖ      L$D  IH  Ic    LnEtaE1@ AI E9~CAMIUIAuI} ӅH$@  dH3%(   u6H@  []A\A]A^    D 1@ IcUff.     AWAVAUATUSHX  Ht$ HT$dH%(   H$H  1H  IH  1E1L-]g  HL%  HH   HcHcT4t/HH   AAt I<H LD$Aׅ4  HHuH   Dt$<HcB   L   HLHD$0I9   H\$(Lt$@fD  HD$(Al$Ic$AHTTPH      AF_L<HD$   OHcŉl$8IHD$I9   Mn IIoI_   @-tH AEL9uHD$IDt$8LD$  LIcD$IcT$HT$ HD$ AL$Ѕ~"IL9d$0-Hl$(H   B D$<H$H  dH3<%(   u'HX  []A\A]A^A_D  IFvff.     Ht7Ht2H   D@$1E    H   HHD f.     Ht7Ht2H   D@(1E    H   HHDS f.     H   HO`Htz   ЃtrLG@      HWPL9vHwpL)LHHVHwpHc0  HTHQ   ,  H(  Ǉ(  LS H1HOxøf.     H   HGpH+GxH   G   SH      HC(H9C8tHHSpH+Sx1H~JH     u${Hsx9   ~H{ǃ       HS`HSxHSp[fHG(H9G8c1    lǇ       HW(HW8HW`HWxHWpøf     AWAVAUATUSHXHt$dH%(   HD$H1H.  H=X      GI   ;   HG(H9G8tH$H$HD$L|$Ld$H$Hl$ I     HL)H   H @   @  L|$0HOLd$ D$LS BLjHT$8I׋ڞ  D$DHD$(   Hl$uA~H4$D   HI9~I~HL)HLH+D$    Ht$   HL$HdH3%(   uHX[]A\A]A^A_H4@ AWAVAUATUSH   H$ HdH%(   H$  1HII5H8HIHCb  HDAAW   HSA   1AVLR     AUc   H H=   OHcMt7L/1H$  dH3%(   u&H  []A\A]A^A_        f?ff.     @ AT~   fAUHSH  dH%(   H$  1H|$H)$HHHh  xH$  dH3%(   u?H  []A\ÉID  H5YZ  11H5R  Hiff.     fATUSH   H$ H   H$ HdH%(   H$   1    ?/HH     HHb  HߋH!%t¹     DHWHD@ HH)</)HcHcH1H.HJ  L$     HLmH      H=Q  L      A  H1"Ń   uRH=;  H9t
HtH1H  H$   dH34%(      H   []A\fD     T      >@  4+    HH5X  1rrD  H߹    SfD          HH5LX  1C Htv   t]SHtCuWHC(H9C8tHHCpHb  HHHH@      HCpPH1[@     s뢸ff.     H      uu1fSHtRubHC(H9C8tH0HCpHŋ  HHHH@      HCpH{:      1[    1HO@H9OPv닸    AWAVAUATUSHH  H|     I֨,  a  HHt$H>  L{8I   HC0L)H9>  Lt$L+{(L   A @  LLfIM)M   KH @     σLS LCpN   IHD   I0HI@   HKpM~HC(MxIH E1I@HC8H   L1HMLIHHKpH9eH=thILM)MUI9tHtDL+t$HL[]A\A]A^A_D  M@   @  M)(    I    Ht$HLHk8f.     H         AVL   AUIATIUS   Hu\H߉   KAD${Lǃ   LS      Hu0{L[L]A\A]A^x     ;    [H]A\A]A^Hff.     AWAVAUATUSHHH  H     D$  0    x  IHIHLc\  C  HcTt
u(HD  Lc  LH
ttLÅ~6HcATt
u#H@ Å~ALH
ttE<AG=      I|$PHHTI9T$Hs7H   I+t$@L2%  ))   I|$PLHHcAoMt$PHLIFID$PA:I|$PMMD$PII@ID$PA  Ic$0  fET8  HЃA$0  D$H[]A\A]A^A_D$ff.     H
  H  B=           0       AUATUSHcHfDA<
t<uH؅uH[]A\A] IHPHHDI9D$Hs3H   I+t$@L2%  ))tQI|$PHHA I\$PHCID$P Ic$0  fET8  HЃA$0  H1[]A\A]øSD  AUATAUHSH?dH%(   HD$1D$   f   f
t1f   HL$dH3%(      H[]A\A]ÐA   1Ҿ   ÃtŉǺ      1ԿHL$A   ߺ      訿u#DHuDo輾߻D H*De OA   kD  H}An   葾} N3 Htff.     USH   dH%(   H$   1HHu/HUH$   dH3%(   uHĘ   []     褿@ 1H=   t       AUATA'  USH  '  DNuD  H@      AxHH  H   HtH-!  D:  9Ɖǉ#  U   Dk H  DcEu<DSuGC   H,    HC1H[]A\A]@ A|$C    {˸كÉSff.     @ HՏ  Ht8ff.     fH  B    HB(HR8H9s     H0H9wH  Ht	     H  Ht	     fD  H݋  HH;{     wHHH;n  ff.     @ ATUSHH dH%(   HD$1H  D`豼HSX  HkXH-  RHǎ      \      n  HC  H      HtH܀  11H-O  EH	  Ht {1F  uH  HtAD9 ~       ut;u]HLS    [HH$sP  D$ʻ   H߉D$觻  1HL$dH3%(   u)H []A\D   t@H  SH@HX t1HSXHBHB{˽C1[AWAVAUATUSHH  HT  H|$H$   LedH%(   H$8  1HLǄ$(      H$   yH  H   uc  HLǄ$(      H$   ;H$  H   7  HȊ  H     H  H
     H0  H     HD$1E1Ld$ :      L|$ǀ       D$    H|  Ht	H=X  1IL9t71   LPCtS  D$    fD  V   6HG     LH1HHc;ƺ;MLHD$   HD$    ?)Ѻ   H1H	T 1  Ń      8   1H5     譸1ҿ   H5  蚸1ҿ   H5̉  臸1ҿ   H5  t1ҿ
   H5f  aH$8  dH3%(   k  HH  []A\A]A^A_fD  H1  HudDCSK
D9   H  AHtD  H5EI  1F lN  M fD  D0DCE~E~  5D  諺Au D$t$9/D  ;)AHD$DpAuc袶0kbH=?  Dojf.     H=?  H=3H  ٽ11H\$HCX     ='|  f=|  D  H%  Htxff.     H  Htxx     H  Ht~x     Hň  Ht~x     H  Htxff.     =6  D  &  D        Ð  D  AUATUHH=p>  SH8  dH%(   H$(  1=HtH H=     H=?>  HE  1
   H莹  H=9>  Ht
   1Hf  H=%>  ĳHHt
   1H=IAąW  E1H=>  萳Ht
   1H_  H==  jHtHǺ
   1_H==  CH  `     H==  $HtHǺ
   1蠸)贶  H==  H  1
   HhO  H==  òHtHǺ
   1?شH==  蜲HtHǺ
   1H=u=  uHtHǺ
   1躺H=b=  NHtHǺ
   1ʷ蓲H=R=  'Ht-H=P=  Ht
   1H荷  _  H=8=  Ht
   1H_U  D        ҅      E  H==  ɶH  =  u	P  5    H==  cH  
   1H۶e  te    Hw  H H   HH   D6  L
=  L<  L=  C 
   HL t@Hֹ   L D	t%HtAHHt9   HL uHfD  HJHHJHuHHu1ۉH$(  dH3%(     H8  []A\A]fD  f     H膲D<G~   A<MEDA sDHH  _ 豲@ H=:  ܯHfD  H=9  輯HfD  Af@  #f蛳fD  1EHnHu  8   H=:  路HHM  H  H5:  HŶHH#  H  -'  H5:  H萶H5:  HIH܂  wH5:  HhH5:  HH  R~H5:  H>H  H=  H~  AԅLH=]B  谶H=  褮Hq      $@ H   H$    HD$    bD  HH$      $   ̯   t议1҃8kH   H=N9  ܭHt1
   HX~  H=69  貭Ht1
   H.~  H=9  舭HHi  HǺ  11蛵Ã  HT$ƿ     D$(?     H5o  踱H   GH  Htxc@d   x  @  D  E9D  E)Zf     H=]8  贬΀  HK]  u
  '      '       ~      )f     ՅtbHS  H-D  HH5?    1ڵCAHc~L%  HH  asÅt=    u
      5  `HH5 ?  uHH5>    1EHH5>  Fff.     AVIAUEATIUHSHt4  Hu!(fD  HHtHLGH] HuMtEL[1]A\A]A^ÐIcLLH#EgHG    HHܺvT2HG     AWAVAAUIATUHoSH1HGO@ƉWDW?t;AĉDHH| @   D)A9rhAGt4LLHL9A?vWEfAIIIH޺@   HH@ܱHLL9uA?DLHH[]A\A]A^A_鬱I    ATLfUHSFH?LHz?   )w=t1 9rLHfCAD$AD$ ID$0    7   1)HCHLHCP?oH{1HM H    HCP    H)KXH[]A\ff.     fAWAVAUATUSH   dH%(   H$   1Ht^   I  A      f     Mcg IoA_@ LHHuM(8u
=x  uٽH$   dH3%(   
  HĨ   []A\A]A^A_f     ~A   A   uI   AǇ      f8LS|  xr  @tPHf@HPXN    	  Mg  A;G Z  A   9~u    Eo)HHcI     HLDHu$85w  u    A   MgA   9ID$,HD$HcII   DhA  h(A9   }A    /  HcI   H4@H5H  A   I   I   h$A9   }A      HcI   H4@HH  A   I   I   Hl$p(I   LH  I   I   Lp$h  M   Ic@o  9g  IcP[  9S  IcpG  9?  IcH3  9+  IHHHHI   HT$I   Ic@ H)I   HHI   HHH   I   HI   IcHI   HHHD$I9  E  1D  L4t9d<B9ZHHuIcP k  I   HHH9r*R   P9!P9P9HH9-  9~H51    1}H51    1g>fH    H IGAG     I   PHf@	f@HHPPHHPPHHPPHHPPHHPPf@f@f@HH#PP H H'P#P$H$H+P'P(f@f@!f@%H(P+f@)I   1fD  I   HcȋL4t#fBI   HT4
rfB@2JHHuM   IcP    I   HHH9       pH@ppHH@ppHH@ppHH@ppHH@ppHH@ppHH@ppHH@pHH9wM   ApI   bIc@I   H0  v  AǇ      t`av  
Zv  A     Fv   1       LHc蟩IHIGAo I   uI   D%9v  D-.v  B(AA1  IcH4II   LI
9   HqH=7.         IJDB(9 x  HqH=.      X  IJB($AD$IK  AzHL$;  Mbfou  Lt$ LAoL$AT$Ml$)$   航    LLHL$   LHLLH$   ID$H$   I3L$H1H	  D$$Dl$E  DDl$âH=t  IH  IDt    M  H=dt   t"LDLŃP  |$W  Et$A9u  Ht$   n  DŃ  5,t  $  A?D5t  tAH5)  LHtHHt      f)s  #A   H5zf  1H@H5+    1)   LH
   1H_I   H5t3    1H53    1ͨD%.s  $s  DD$H=s  IHtZEW7    E1111   ͤH=3  H5*    1PE|$菦   M2;     |$g   E1H5*  LuI} wŃ1H5*  LKfD  =r  -r  r  ED$AIF  H5)    1vHH)H51    H1Q1H5*  Lܟ1H5#2  LA#    LH3  H|m  w1H5)  Laff.     AVAUATUSH   dH%(   H$   1D$   H  H	  ;1Ll$Ld$Lt$Hkll     {ul;   LLD$   C   Hq  Ht@Hp  Ht {1f|$   =p   u|H4tH舴H06l  d1H$   dH3%(   u}HĠ   []A\A]A^D  胜      {   H5b  ,Hfы{L      A   ;۝ff.     AWAVAUATUSH  D=o  dH%(   H$  1Ex  HH-n  H  }   o  ;a  D  H-o  Ht11HEDk  E  H$   L|$PDcA:  E1A   f     Dj  E   Do  EtH%o  Ht@f   LH1HIcWDHD$P   HD$X    A?)Ѻ   HH	   D9#  11A|$MH}j  D9#    Hn  Ht@ D9#  `  AD91葳f     H$  dH34%(   '	  H  []A\A]A^A_KL$  HǄ$h      Ml$H$  L蜞H$   L   HHD$@菚A  HLǄ$h      H$  UH$  L   HHD$0HP  H$  L   HHD$8#+  H$`  L
   HHD$(  H$   L   HHD$HٙAǅ  HD$PE1Ll$`HD$H$   HD$H$`  HD$fD%l  E   Hal  Ht	H==h  1dIL9t<1ձ   L5E  DuE  ME1    V   H'h     LH1HHc} 襚} LD$LHD$P   HD$X    ?)Ѻ   H1H	T`1g    8Ht$(1ҿ
   荘x =       _5}k  tHk  Ht@f,D9#
  DC  H`k  Ht@Hk  Ht Dc1DNf    =bj   {   H5L]  HHj  Ht*Hj  HB (@ Hj  Ht@Hnj  H @ 蛖8B-D  AD9M =e  }=e  Hj  
   HtDHi  Ht
A9Hi  HtD҉T$$DE~:E~5  'T$$A蛙A茙AuDEUM
D9vHgi  AHtDH5'    1薞 輞    D$g0H=!  7T$fD  } 蠩C   1mH|$I谙H|$   HT$Ht$1`6  ӝ  1  EMtAMgMg{E13CHt$1ҿ   H=)  f;>fD  D$$_0dT$$WH=  T$'T$fD  D#AfD  g  RDoc  EBHg  H29Nc  {   H5Y  蠔H{wH=3(  6蜓H=}(  0~MA    H
  H{HƘb   H=z  ĚՖHt$1ҿ   脒  H1f      f  L=f  f  Hf  f      HPf      HtH4X  11L=f  AGH`f  Ht {1蝦D-a  EuH:f  Ht!E9~a     e     ;tȕHt$@1ҿ   L$  ْHt$01ҿ   ȒHt$H1ҿ   跒Ht$81ҿ   覒Ht$(1ҿ
   蕒kHLS    H$  Z'  $  讒   L$  舒d  oe  H=o#  %蛚,H=&  QHNe  Ht*fC  1CD$CCӖT$HC(HC d  ֒fD  =d  d  ff.     @ H`  f.     f   fD  i      Hff.      HmV  H   H+       H   HOD  H     1f     1f     ATIHUSHc8HcLH*H=h  HHȔ[   ]A\ff.      H飕 HH=U     HfHH=U  ܏Hc5g  ;5_  H=g  |6aHg      Hg     g      HfD  f     ?    IH=U   H   H+   9M1~+HHcHc5ig  H5Vg  ѐ~Sg  Hfff.     @ HH=T  ̏tHHHD     Hff.      HH=iT  茕H]^  HHH=IT  蜏H=^  HHH=)T     tH^  HH SHH\$Ht$H5H]1H#H[ff.     fAWAVAUAATIUSHH<Q  ~v<R   <Su"   H=%  H   @ McLL蚕HcHI茕H=e  LH*H   []A\A]A^A_fD  <Pu
   H=-%  H uƀULcu   H=$  H t?   H,IH  HAL)A)McHLHL$	   H=$  H$KH$H=0e  HhHL$LH訔   H=$  H$H$H=d  H01A??LILi   H=!$  IՍH=d  LHfD     H=#  H r: i@ A   L%*  QfD  O<4LE1=!d  t1@ HQ  H   =d     tUSH;=v[     H=_  4HH虑Ń   HvHHcc  Hݍ   E1A      H1Htc  H   蓎1H[]f.     Hc   H<c  HuH=#  k   @ c      1 H="  D-   fD  蛊8$Hپ   H  IH{P  H81葒H   NH=~"  ̍   1fAU1ATUHSHV      -gb  +gb  HcD%Yb  (IŅt"D)A    DID9uD   HL[]A\A]ÐD)Hc5b  HH5a  HcDa  HL[]A\A]@ H} @u&xU-a  a  )9OT 裒ؐD9Hc5a  LDNH5a  IcЋD%a  U@ HA   [L]A\A]ff.     AWAVL5Ea  AUATUSHf     D9-1a  ~N   }D-"a  M&   H   Hc=a  D)ILHcH芍HtL)D)XHcH豍Ią~Hc5`  HH5`  H`  HL[]A\A]A^A_f     H1atH#    HfD  ^`  SHX`      2fH5`  97`  }1uٿ   fH[ff.     AUATUHSHdH%(   HD$1   HE1IG@ HI9}HHH   uj tUHCJHL   IH$uH uHCI9|HL$dH3%(      uVH[]A\A]@ HC f.     H踎H    H=%  _HH   H$t@ 1f     UHSHHdH%(   HD$1uHtHHHtCH   袏D$@uEHt<HE Hu/H}u;&f      ukHS  tD$@t   HfD  HE Ht$   H8PHHHDHL$dH3%(   u7H[]fD  H{ BHSHu7    yASHdH%(   HD$1H]  H$HiY  Hu%H  D     H;HDY  HtH=]  H   H(HD$dH3%(   uH[轆ff.     fAUATUHSHH      HƉfD  HLc H@tOHǅMl$H t\HhHXH   HHI<$AHH[]HD A\A]f.     HtHU HHуHuMl$ uHHhHfD  HHHH8H{@( HI  H     H  H81Fff.     @ SHH[ff.      SHsHH   [ÐUSHH=GI  ʅ   tyH=[  Ht߂H[      H[  [      9[  uI1H[  H-H  H;HHu =Hu H;HHR  HH[]D  :[  HV  Hu'H         H請HV  Ht11Hƿ   螆hf     H9ER  tH    ATUHS誂L 袂H5Z  H=  H    舆胂L HIV  Hu%L%  D     LH$V  HtH=Z  HH[]A\    AWAVAUATUHSHS     GHL-P  Ldtf     H   HubfD  裂HIHI    M~M   IFA|
tHF  HH0NHL9t[H;@tHufD  H=     蟂Hf.     Hu5HHHH=4迆L9uH   []A\A]A^A_fD  t.fD  M~HHHF  L   H	  H81蠈I fHF  HH0nff.     AVAUATUHSHdH%(   HD$1      IH6A   L5}  H     H   Hu4HA9~NHE  H0HtHIt H@tHu@    L3HHA9H4E  H0Hu;HL$dH3%(      uPH[]A\A]A^ÐHHta    HPfD  IA   HH$ـf     AUATUSH=H=h  H6W      H7W  5W       ~Ht8
   1HH虃HŅ~M   HՀH  -sN  H=  }HHtHHH=  `  X   fo  fR  )R  H=U  1}Ht1
   H1	@H=C  FH=  lV  O}H  H  H^C  HHHC  HH[V  HQ  Hu L%G     L裆HQ  HtL% C  HI<$dH5Q  HV  Hu4L-"  f.        LSHHqQ  HtHU  11HAH=U  HU  .   H=  ~   H=I  I~H=zU  LH见   H5H=  迂I4$H=  O1H6H5  HHU    H=	U  1HH5  ̂H=T     HH5  譂H=T     HZH5k  莂H=T  HH5R  oH=T  HlH59  PH=qT  HH5!  1H=RT     HH5  H=3T  1HH5  H=T  1HH5  ځH=S  1H:H5  辁H=S  HH5  蟁H=S  1HH5  胁H=S  1HH5{  gH=S  1HgH5d  KH=lS  1HKH5L  /H=PS  1HH55  H=4S  1HCH5  H=S  1H7H5  ۀH=R  1HH5  迀H=R  1HH5  裀H=R     HH5  脀H=R  HH5  eL%n?  H=R     HL}H-?  Hm?  H=I  HP HI  HJH*H5R  H?  HHD?  H輀H=R  L   H}H*?  H=SI  HP HHI  HJH*HyyH(yH    ЂHQ  1H5Q  H=  }H3H=  p}kyH(H[]A\A]D  HP   HH=EM  }HwH3M  H.XXXXXX H(Ht+   H=^   ub    H=Q  1H8H5w  ~H=P  1HH5q  ~H=P  1HH5d  ~    H=  R    H=  twH6BfD  m   H3zH^K   HzHt
-G  Gk   HyHu-G  * HH                               Anonymous mmap() failed localhost %02d:%02d:%02d  [%s]  [UID:%d][%d]  %.*s yes no system() %s, errno: %d (%s)
 /dev/null libpthread.so pthread_atfork HTTP_ [UID:%d][%d] %s:%s: %s
 LSAPI: jail() failure. /etc/ Can't set signals accept() failed LSAPI_STDERR_LOG PHP_LSAPI_MAX_REQUESTS LSAPI_MAX_REQS LSAPI_KEEP_LISTEN LSAPI_AVOID_FORK LSAPI_ACCEPT_NOTIFY LSAPI_SLOW_REQ_MSECS LSAPI_ALLOW_CORE_DUMP LSAPI_MAX_IDLE PHP_LSAPI_CHILDREN LSAPI_EXTRA_CHILDREN LSAPI_MAX_IDLE_CHILDREN LSAPI_PGRP_MAX_IDLE LSAPI_MAX_PROCESS_TIME LSAPI_PPID_NO_CHECK LSAPI_MAX_BUSY_WORKER LSAPI_DUMP_DEBUG_INFO nobody LSAPI_DEFAULT_UID LSAPI_DEFAULT_GID LSAPI_SECRET LSAPI_LVE_ENABLE liblve.so.0 lve_is_available lve_instance_init lve_destroy lve_enter lve_leave jail PHP_LSAPI_ PHPRC= packetLen < 0
 packetLen > %d
 Bad request header - ERROR#1
 ParseRequest error
 SUEXEC_AUTH SUEXEC_UGID LSAPI: setgid() LSAPI: initgroups() LSAPI: setgroups() LSAPI: setuid() Bad request header - ERROR#2
 lsapi_accept() error Pragma: no-cache Retry-After: 60 Content-Type: text/html DEBUG NOTICE WARN ERROR CRIT FATAL Accept Accept-Charset Accept-Encoding Accept-Language Authorization Connection Content-Type Content-Length Cookie Cookie2 Host Pragma Referer User-Agent Cache-Control If-Modified-Since If-Match If-None-Match If-Range If-Unmodified-Since Keep-Alive X-Forwarded-For Via Transfer-Encoding HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING HTTP_ACCEPT_LANGUAGE HTTP_AUTHORIZATION HTTP_CONNECTION CONTENT_TYPE CONTENT_LENGTH HTTP_COOKIE HTTP_COOKIE2 HTTP_HOST HTTP_PRAGMA HTTP_REFERER HTTP_USER_AGENT HTTP_CACHE_CONTROL HTTP_IF_MODIFIED_SINCE HTTP_IF_MATCH HTTP_IF_NONE_MATCH HTTP_IF_RANGE HTTP_IF_UNMODIFIED_SINCE HTTP_KEEP_ALIVE HTTP_RANGE HTTP_X_FORWARDED_FOR HTTP_VIA HTTP_TRANSFER_ENCODING        %04d-%02d-%02d %02d:%02d:%02d.%06d      Child process with pid: %d was killed by signal: %d, core dumped: %s
   Possible runaway process, UID: %d, PPID: %d, PID: %d, reqCount: %d, process time: %ld, checkpoint time: %ld, start time: %ld
   gdb --batch -ex "attach %d" -ex "set height 0" -ex "bt" >&2;PATH=$PATH:/usr/sbin lsof -p %d >&2 Force killing runaway process PID: %d with SIGKILL
     Killing runaway process PID: %d with SIGTERM
   Children tracking is wrong: Cur Children: %d, count: %d, idle: %d, dying: %d
   LSAPI: LVE jail(%d) result: %d, error: %s !
    Invalid custom stderr log path  Failed to open custom stderr log        Can't set signal handler for SIGCHILD   Reached max children process limit: %d, extra: %d, current: %d, busy: %d, please increase LSAPI_CHILDREN.
      LSAPI: failed to open secret file: %s!
 LSAPI: failed to check state of file: %s!
      LSAPI: file permission check failure: %s
       LSAPI: failed to read secret from secret file: %s
      LSAPI: Unable to initialize LVE Request header does match total size, total: %d, real: %ld
     LSAPI: missing SUEXEC_UGID env, use default user!
      LSAPI: SUEXEC_AUTH authentication failed, use default user!
    LSAPI: lve_enter() failure, reached resource limit.     prctl: Failed to set dumpable, core dump may not be available!  sigprocmask(SIG_BLOCK) to block SIGCHLD sigprocmask( SIG_SETMASK ) to restore SIGMASK in child  fork() failed, please increase process limit    sigprocmask( SIG_SETMASK ) to restore SIGMASK   Cache-Control: private, no-cache, no-store, must-revalidate, max-age=0   PID                            <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<HTML><HEAD>
<TITLE>508 Resource Limit Is Reached</TITLE>
</HEAD><BODY>
<H1>Resource Limit Is Reached</H1>
The website is temporarily unable to service your request as it exceeded resource limit.
Please try again later.
<HR>
</BODY></HTML>
                                            
                        
                     
                                                                         	                                 
            QUERY_STRING REQUEST_URI PATH_INFO REQUEST_PATH SCRIPT_NAME ftruncate() failed. 
 File mapping failed. 
 Memory calloc error [...] replace srand STDERR reopen nil LSAPI_MAX_BODYBUF_LENGTH LSAPI_TEMPFILE XXXXXX RACK_ROOT chdir() to_hash CGI/1.2 eval_string_wrap LSAPI accept accept_new_connection postfork_child postfork_parent process putc write print printf puts << flush getc gets read rewind each eof eof? close binmode isatty tty? sync sync= RACK_ENV      RSTRING_PTR is returning NULL!! SIGSEGV is highly expected to follow immediately. If you could reproduce, attach your debugger here, and look at the passed string.     GATEWAY_Irewindable_input.rbNTERFACE    /tmp/lsapi.XXXXX;  |   Z  d0   o  pH   p\  0pp  @p  p  p  p  @x@  xt  @y  y  y  z  {4  |  @}  }   ~L  ~t  P   4      PX	  	  	  	  Љ	  	  
  p,
  @
  T
  h
  @
  
   
  p  H  \    @  ``  t           x         @8      (      0    ШL  `  Pt       @  `(  p<  P  d  x          0  @  P  `  pD           \  p  p       4  H  \   p  0  @        0  $  D   \   t  P      @0    @  p    P  d          <   X       0   pD             zR x  $       V
   FJw ?:*3$"       D   h`
             \   k          p   k             k       L      ks    EIB E(A0z
(A BBBIA
(D BBBA        k             k       @     kY   GJB B(A0A80F(B DBb 0   T  r    BFC G
 AABK      Tsk       (     sG    ADJ n
AAA  4     sU    AGK R
CAGL
JCG         s    AG]
AJ    $  xt   t
CKF  L   H  du    BBE A(H0H
(D BBBD
(D BBBA P     v    vFB A(D0D
(A BBBBL(A BBBA  $     `va    AAD XAAH     v    BBB B(A0A8D@N
8C0A(B BBBH $   `  LwO    Af
QC
EH   @     twY   BBB A(D0J
0A(A BBBFx     y   FEA C(G
 
(A ABBDM
I
c
A

E
M
A
k
E
E
E
E
HV
 H   H  {   FBB B(A0A8D``
8A0A(B BBBDl     X}+   BBB B(A0D8JYHPC	Mi
8A0A(B BBBELTMDd     ~6   BBB B(A0A8DP
8A0A(B BBBG
8J0H(G DBBK   $   l  7    EFF IIO                                                 4        FAA G>
 AABG             EO
D
A    @  <          T  8          h  4Y          |  J    ED       S              ]    Ph
HXA   H     <l   FBB B(A0A8LP
8A0A(B BBBH <     `   FBB A(A0
(D BBBI      \  0i       `   p     FBB B(A0A8DP~
8A0A(B BBBAk
8A0A(B BBBH L     H$   FBB A(A0HQD
0A(A BBBH L   $  (   FBB B(A0A8G
8A0A(B BBBF      t  F            4F            p       $         nCXJ   L     Ԍl   FBB B(A0A8DA
8A0A(B BBBA   `   (	      BBB B(A0A8G I K I L N N w
8A0A(B BBBI0   	      BMD GL
 AABA<   	  =   BAA G L@I@U
 AABG   $    
      TWEHG       (
  t    ag
HS   H   L
      FBB B(A0A8DPS
8D0A(B BBBFT   
      bIE D(C0P
(F BBBMQ(H BBBA H   
     FBB B(A0A8DP
8A0A(B BBBAT   <     CBA A(G0`
(A ABBD
(C ABBAJ   8     X-   FBD D(D@T
(A ABBB      L       (     Xl    ECGF
AAIL     !   cBG A(D0
(A ABBEXD0      `  |          t  Z            Ԙ1       0      p   FAA G@7
 AABF     <@    Ls   L     `   FBB B(A0A8G
8A0A(B BBBG      <  0          P  ,          d  (          x  4            @            L            X            d            `            \            X       <     T	   FBA K(G 
(A ABBG   <   X  $    FEE D(D0M
(C BBBB        d(       H         FBH E(A0E8I@
8A0A(B BBBE (     $    FED AB  H   $  Ȩ   BBB B(A0A8G
8A0A(B BBBJD   p  \   FBB A(A0G
0A(A BBBF   L     ĵ
   FBB B(A0A8G
8A0A(B BBBA        t                          4  
          H            \  +          p                                 (     B    FGA kFB                        HU      g    HQ
G       a    yd    8  t2    HW
II      X       HW    p       HW      -    Hd      3    ED hA H        FBB E(D0C8GPm
8F0A(B BBBG 4        oAD 
AAKpP  \   D  4   FDA D(F0`
(D ABBBj
(D ABBEl(G DBB   D         BBI B(A0A8D@8D0A(B BBB     `*    HP
HI        pU    KI  8   (      FBA D(D@
(A ABBE    d  x       (   x  t   EDG0
AAG        zR x0       lW.             8    AD w
AA 8     !   FBA D(G0d
(C AGBK    4      EL      P      EY   (   l      EAD 
DAF ,     t    ZAD rAB   H        FBB B(A0D8D@
8F0A(B BBBG @     (7   FBB A(D0D@
0A(A BBBB 8   X  $S   FBA A(D0
(A ABBF                 GNU                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     pT      0T      !                                   q            w      ~                                                                                                      "      -      ;      M      V      d      m            g                                                                                          ,      ;      G      T      ^      j      w                                                	            )      2             
             
             
             k             `>             4             !                          !                   o    `                                
                                  	!                                       .             0&             p      	                             o           o    %      o           o    $      o    D                                                                                       !                     >      >      >      >      >      >      >       ?      ?       ?      0?      @?      P?      `?      p?      ?      ?      ?      ?      ?      ?      ?      ?       @      @       @      0@      @@      P@      `@      p@      @      @      @      @      @      @      @      @       A      A       A      0A      @A      PA      `A      pA      A      A      A      A      A      A      A      A       B      B       B      0B      @B      PB      `B      pB      B      B      B      B      B      B      B      B       C      C       C      0C      @C      PC      `C      pC      C      C      C      C      C      C      C      C       D      D       D      0D      @D      PD      `D      pD      D      D      D      D      D      D      D      D       E      E       E      0E      @E      PE      `E      pE      E      E      E      E      E      E      E      E       F      F       F      0F      @F      PF      `F      pF      F      F      F      F      F      F      F      F       G      G       G      0G      @G      PG      `G      pG      G      G      G      G      G      G      G      G       H      H       H      0H      @H      PH      `H      pH      H      H      H      H      H      H      H      H       I                                                                                                                                                                                      ,          LS    LS    LS    LS                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                8      8      I      Y              X!     !                                                 GA$3a1 `>      A               GA$3p1113  S                      GA*             GA$annobin gcc 8.5.0 20210514            GA$plugin name: gcc-annobin              GA$running gcc 8.5.0 20210514            GA*             GA*             GA!              GA*FORTIFY               GA+GLIBCXX_ASSERTIONS             GA*GOW *            GA*cf_protection             GA+omit_frame_pointer             GA+stack_clash            GA!stack_realign             GA$3p1113         3                GA*             GA$annobin gcc 8.5.0 20210514            GA$plugin name: gcc-annobin              GA$running gcc 8.5.0 20210514            GA*             GA*             GA!              GA*FORTIFY               GA+GLIBCXX_ASSERTIONS             GA*GOW *            GA*cf_protection             GA+omit_frame_pointer             GA+stack_clash            GA!stack_realign            GA*FORTIFY     T                     GA+GLIBCXX_ASSERTIONS           GA*FORTIFY            *               GA+GLIBCXX_ASSERTIONS   lsapi.so-5.6-3.el8.x86_64.debug 7,f$7zXZ  ִF !   t/?N] ?Eh=ڊ2N뺉>)L$;	=ֿ2,!~L$zHvK}D@&NzRLΝl;/%nA{4FmF&߾7̂#ϏIԱuJS=Pkds|X0o0ai7oscW	y6қ9|.cv?Y+][Bױ8ӈ>JOfJ	Uhژ|v\bU?QfUG\͗5ꌸ[ZNB%O2=dR,qvEAUYivHĴsҨ35,du"cPKF[X%7ѶYC;]Fdd(7T|
P L6ɂ{7f"ZY]5{-dqq(=fȍRf2AE8{u*҆l'ҝWBjinu	8pG{Prc>CnᮥD=H<_t ]4CB<h:'͑@Qe*ab&_Oq[ꘂ+`h_:/0A@ZrZ?)ͦG7(e`&[AϬ}+ s&8y]lGnUل北(S\XcrgWeWWEx]ov:6^ꄒ;C-΢V0eAձAO=Svk$չ|r&s};⿕G
yq%X頛؇7sPiYPȔwK#kd7rbW^kS1xW2;;>T<LV78|~u=PVL:Lj.\uc`3b`v1694jҊJD00L3q%VOIs
+8 L"Oy
A* nC"i7;z,5W%Vg:w.\>l}Rg{廬6hlyzCˏGsAN+`lEψ2,UyŸ8|\ymV嫤uFI9[gQ}9SאUnog\"꼙zׇ;Շ	A$מؿEGZ_=MWd9l-׿t
N~jNymǲ)!>1Tb8+@lRqw2bK:;w`ͪw~)Cn_i206OU1MnEVfuoKLWldB!n^Baf75d{nA]x6ǙSRk_Bv"LΔF-m3vW݃|F
zܢrDKjz;D?pO
JZnC͠]n|wpzfI+(uϗz2&пEAJ~dO߯~B`#EnJJ_ƹ\c?҈h}	2XŮ}>#a( Qn;6 '1=UyU48E4SjVVh8b@xv-5lYu}u:7$PTW値kˀc6nJd~U^)*`i63cJD:sO@Os{F";ܐx&${;^j`f""_<cn:&(%d/U\#
~yed㿎dOjB-9b|ͨD/摔%@%xHJ]vCBEw!N^ErϐԶŕr˄z!||'cܽ   WIg/ <  g    YZ .shstrtab .note.gnu.build-id .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rela.dyn .rela.plt .init .plt.sec .text .fini .rodata .eh_frame_hdr .eh_frame .note.gnu.property .init_array .fini_array .data.rel.ro .dynamic .got .data .bss .gnu.build.attributes .gnu_debuglink .gnu_debugdata                                                                              8      8      $                                 o       `      `      p                            (                                                   0                                                      8   o       $      $                                 E   o       %      %      p                            T             0&      0&      p                           ^      B       .      .                                h             `>      `>                                    c             >      >      
                            n             I      I      
                            w             S      S      ~                             }             4      4                                                 `      `                                                 p      p                                                `      `                                                                                                        !                                                    !                                                    !                                                     !                                                  	!     	                                                !           	                                           !                                                      "a          l                             
                     L     $                                                   p                                                         &     (                             
lsapi - LSAPI extension for Ruby
================================

INSTALL
-------

  $ ruby setup.rb config
  $ ruby setup.rb setup
  # ruby setup.rb install

USAGE
-----

General CGI scripts
^^^^^^^^^^^^^^^^^^^
The most efficient way to use LSAPI interface is to modify your CGI scripts. 
You need to add the following code to your CGI scripts:

  require 'lsapi'
  
  while LSAPI.accept != nil

     <your CGI script>
     ...

  end

There is no need to change the way that how CGI environment variables 
are being accessed in your scripts.

You can find some examples under examples/ folder.


Ruby Script Runner
^^^^^^^^^^^^^^^^^^
If you don't want to change your existing Ruby CGI code, you can use our 
Ruby script runner under scripts/ folder. You need to configure 
lsruby_runner.rb as a LSAPI application, then add a script handler 
for "rb" suffix.



Rails dispatcher
^^^^^^^^^^^^^^^^

With Ruby LSAPI, we proudly provide a optimum platform for Rails application
deployment. Ruby LSAPI has the following advantages over other solutions.

  * Easy configuration, deploy a Rails application only take a few clicks
    with our Rails easy configuration
  * Fast startup, the expensive Rails framework initialization only takes
    place once when multiple processes need to be started
  * Resource efficience, ruby processes can be started on demand, idle
    process will be stop.
    
To use LSAPI with Ruby on Rails, please check out our toturial
http://www.litespeedtech.com/support/wiki/doku.php

There are a few environment variables that can be tweaked to tune ruby 
LSAPI process.

* LSAPI_CHILDREN                (default: 0)

LSAPI_CHILDREN controls the maximum number of children processes can be
started by the first ruby process started by web server. When set to <=1,
the first ruby process will handle request by itself, without starting any
child process. When LSAPI_CHILDREN is >1, the LSAPI application is stared in
"Self Managed Mode", which will start children processes based on demand.
With Rails easy configuration, LSAPI_CHILDREN is set to the value of
"Max Connections" by web server, no need to set it explicitly.

Usually, there is no need to set value of LSAPI_CHILDREN over 100 in most
server environment.


* LSAPI_AVOID_FORK              (default: 0)

LSAPI_AVOID_FORK specifies the policy of the internal process manager in
"Self Managed Mode". When set to 0, the internal process manager will stop
and start children process on demand to save system resource. This is
preferred in a shared hosting environment. When set to 1, the internal
process manager will try to avoid freqently stopping and starting children
process. This might be preferred in a dedicate hosting environment.


* LSAPI_EXTRA_CHILDREN          (default: 1/3 of LSAPI_CHILDREN or 0)

LSAPI_EXTRA_CHILDREN controls the maximum number of extra children processes
can be started when some or all existing children processes are in
malfunctioning state. Total number of children processes will be reduced to
LSAPI_CHILDREN level as soon as service is back to normal.
When LSAPI_AVOID_FORK is set to 0, the default value is 1/3 of
LSAPI_CHIDLREN, When LSAPI_AVOID_FORK is set to 1, the default value is 0.


* LSAPI_MAX_REQS                (default value: 10000)

LSAPI_MAX_REQS specifies the maximum number of requests each child
process will handle before it exits automatically. This parameter can
help reducing memory usage when there are memory leaks in the application. 


* LSAPI_MAX_IDLE                (default value: 300 seconds)

In Self Managed Mode, LSAPI_MAX_IDLE controls how long a idle child  
process will wait for a new request before exit. This option help 
releasing system resources taken by idle processes.


* LSAPI_MAX_IDLE_CHILDREN
    (default value: 1/3 of LSAPI_CHILDREN or LSAPI_CHILDREN)

In Self Managed Mode, LSAI_MAX_IDLE_CHILDREN controls how many idle 
children processes are allowed. Excessive idle children processes
will be killed by the parent process.
When LSAPI_AVOID_FORK is set to 0, the default value is 1/3 of
LSAPI_CHIDLREN, When LSAPI_AVOID_FORK is set to 1, the default value
is LSAPI_CHILDREN.


* LSAPI_MAX_PROCESS_TIME        (default value: 300 seconds)

In Self Managed Mode, LSAPI_MAX_PROCESS_TIME controls the maximum 
processing time allowed when processing a request. If a child process
can not finish processing of a request in the given time period, it 
will be killed by the parent process. This option can help getting rid 
of dead or runaway child process.


* LSAPI_PGRP_MAX_IDLE           (default value: FOREVER )

In Self Managed Mode, LSAPI_PGRP_MAX_IDLE controls how long the parent
process will wait before exiting when there is no child process.
This option help releasing system resources taken by an idle parent 
process.


* LSAPI_PPID_NO_CHECK

By default a LSAPI application check the existence of its parent process
and exits automatically if the parent process died. This is to reduce 
orphan process when web server is restarted. However, it is desireable 
to disable this feature, such as when a LSAPI process was started 
manually from command line. LSAPI_PPID_NO_CHECK should be set when 
you want to disable the checking of existence of parent process.


License
-------

LSAPI library code is under BSD license

LSAPI ruby extension code is under Ruby license

* ((<URL:http://www.ruby-lang.org/ja/LICENSE.txt>)) (Japanese)
* ((<URL:http://www.ruby-lang.org/en/LICENSE.txt>)) (English)


Copyright
---------

Copyright (C) 2006 Lite Speed Technologies Inc.


#!/opt/alt/ruby30/bin/ruby

if GC.respond_to?(:copy_on_write_friendly=)
    GC.copy_on_write_friendly = true
end

require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT)

# If you're using RubyGems and mod_ruby, this require should be changed to an absolute path one, like:
# "/usr/local/lib/ruby/gems/1.8/gems/rails-0.8.0/lib/dispatcher" -- otherwise performance is severely impaired
require "dispatcher"
require "lsapi"

while LSAPI.accept != nil
	Dispatcher.dispatch
end
# frozen_string_literal: false
require "bigdecimal/ludcmp"
require "bigdecimal/jacobian"

#
# newton.rb
#
# Solves the nonlinear algebraic equation system f = 0 by Newton's method.
# This program is not dependent on BigDecimal.
#
# To call:
#    n = nlsolve(f,x)
#  where n is the number of iterations required,
#        x is the initial value vector
#        f is an Object which is used to compute the values of the equations to be solved.
# It must provide the following methods:
#
# f.values(x):: returns the values of all functions at x
#
# f.zero:: returns 0.0
# f.one:: returns 1.0
# f.two:: returns 2.0
# f.ten:: returns 10.0
#
# f.eps:: returns the convergence criterion (epsilon value) used to determine whether two values are considered equal. If |a-b| < epsilon, the two values are considered equal.
#
# On exit, x is the solution vector.
#
module Newton
  include LUSolve
  include Jacobian
  module_function

  def norm(fv,zero=0.0) # :nodoc:
    s = zero
    n = fv.size
    for i in 0...n do
      s += fv[i]*fv[i]
    end
    s
  end

  # See also Newton
  def nlsolve(f,x)
    nRetry = 0
    n = x.size

    f0 = f.values(x)
    zero = f.zero
    one  = f.one
    two  = f.two
    p5 = one/two
    d  = norm(f0,zero)
    minfact = f.ten*f.ten*f.ten
    minfact = one/minfact
    e = f.eps
    while d >= e do
      nRetry += 1
      # Not yet converged. => Compute Jacobian matrix
      dfdx = jacobian(f,f0,x)
      # Solve dfdx*dx = -f0 to estimate dx
      dx = lusolve(dfdx,f0,ludecomp(dfdx,n,zero,one),zero)
      fact = two
      xs = x.dup
      begin
        fact *= p5
        if fact < minfact then
          raise "Failed to reduce function values."
        end
        for i in 0...n do
          x[i] = xs[i] - dx[i]*fact
        end
        f0 = f.values(x)
        dn = norm(f0,zero)
      end while(dn>=d)
      d = dn
    end
    nRetry
  end
end
# frozen_string_literal: false

require 'bigdecimal'

# require 'bigdecimal/jacobian'
#
# Provides methods to compute the Jacobian matrix of a set of equations at a
# point x. In the methods below:
#
# f is an Object which is used to compute the Jacobian matrix of the equations.
# It must provide the following methods:
#
# f.values(x):: returns the values of all functions at x
#
# f.zero:: returns 0.0
# f.one:: returns 1.0
# f.two:: returns 2.0
# f.ten:: returns 10.0
#
# f.eps:: returns the convergence criterion (epsilon value) used to determine whether two values are considered equal. If |a-b| < epsilon, the two values are considered equal.
#
# x is the point at which to compute the Jacobian.
#
# fx is f.values(x).
#
module Jacobian
  module_function

  # Determines the equality of two numbers by comparing to zero, or using the epsilon value
  def isEqual(a,b,zero=0.0,e=1.0e-8)
    aa = a.abs
    bb = b.abs
    if aa == zero &&  bb == zero then
      true
    else
      if ((a-b)/(aa+bb)).abs < e then
        true
      else
        false
      end
    end
  end


  # Computes the derivative of f[i] at x[i].
  # fx is the value of f at x.
  def dfdxi(f,fx,x,i)
    nRetry = 0
    n = x.size
    xSave = x[i]
    ok = 0
    ratio = f.ten*f.ten*f.ten
    dx = x[i].abs/ratio
    dx = fx[i].abs/ratio if isEqual(dx,f.zero,f.zero,f.eps)
    dx = f.one/f.ten     if isEqual(dx,f.zero,f.zero,f.eps)
    until ok>0 do
      deriv = []
      nRetry += 1
      if nRetry > 100
        raise "Singular Jacobian matrix. No change at x[" + i.to_s + "]"
      end
      dx = dx*f.two
      x[i] += dx
      fxNew = f.values(x)
      for j in 0...n do
        if !isEqual(fxNew[j],fx[j],f.zero,f.eps) then
          ok += 1
          deriv <<= (fxNew[j]-fx[j])/dx
        else
          deriv <<= f.zero
        end
      end
      x[i] = xSave
    end
    deriv
  end

  # Computes the Jacobian of f at x. fx is the value of f at x.
  def jacobian(f,fx,x)
    n = x.size
    dfdx = Array.new(n*n)
    for i in 0...n do
      df = dfdxi(f,fx,x,i)
      for j in 0...n do
        dfdx[j*n+i] = df[j]
      end
    end
    dfdx
  end
end
# frozen_string_literal: false
#
#--
# bigdecimal/util extends various native classes to provide the #to_d method,
# and provides BigDecimal#to_d and BigDecimal#to_digits.
#++

require 'bigdecimal'

class Integer < Numeric
  # call-seq:
  #     int.to_d  -> bigdecimal
  #
  # Returns the value of +int+ as a BigDecimal.
  #
  #     require 'bigdecimal'
  #     require 'bigdecimal/util'
  #
  #     42.to_d   # => 0.42e2
  #
  # See also BigDecimal::new.
  #
  def to_d
    BigDecimal(self)
  end
end


class Float < Numeric
  # call-seq:
  #     float.to_d             -> bigdecimal
  #     float.to_d(precision)  -> bigdecimal
  #
  # Returns the value of +float+ as a BigDecimal.
  # The +precision+ parameter is used to determine the number of
  # significant digits for the result (the default is Float::DIG).
  #
  #     require 'bigdecimal'
  #     require 'bigdecimal/util'
  #
  #     0.5.to_d         # => 0.5e0
  #     1.234.to_d(2)    # => 0.12e1
  #
  # See also BigDecimal::new.
  #
  def to_d(precision=Float::DIG+1)
    BigDecimal(self, precision)
  end
end


class String
  # call-seq:
  #     str.to_d  -> bigdecimal
  #
  # Returns the result of interpreting leading characters in +str+
  # as a BigDecimal.
  #
  #     require 'bigdecimal'
  #     require 'bigdecimal/util'
  #
  #     "0.5".to_d             # => 0.5e0
  #     "123.45e1".to_d        # => 0.12345e4
  #     "45.67 degrees".to_d   # => 0.4567e2
  #
  # See also BigDecimal::new.
  #
  def to_d
    BigDecimal.interpret_loosely(self)
  end
end


class BigDecimal < Numeric
  # call-seq:
  #     a.to_digits -> string
  #
  # Converts a BigDecimal to a String of the form "nnnnnn.mmm".
  # This method is deprecated; use BigDecimal#to_s("F") instead.
  #
  #     require 'bigdecimal/util'
  #
  #     d = BigDecimal("3.14")
  #     d.to_digits                  # => "3.14"
  #
  def to_digits
    if self.nan? || self.infinite? || self.zero?
      self.to_s
    else
      i       = self.to_i.to_s
      _,f,_,z = self.frac.split
      i + "." + ("0"*(-z)) + f
    end
  end

  # call-seq:
  #     a.to_d -> bigdecimal
  #
  # Returns self.
  #
  #     require 'bigdecimal/util'
  #
  #     d = BigDecimal("3.14")
  #     d.to_d                       # => 0.314e1
  #
  def to_d
    self
  end
end


class Rational < Numeric
  # call-seq:
  #     rat.to_d(precision)  -> bigdecimal
  #
  # Returns the value as a BigDecimal.
  #
  # The required +precision+ parameter is used to determine the number of
  # significant digits for the result.
  #
  #     require 'bigdecimal'
  #     require 'bigdecimal/util'
  #
  #     Rational(22, 7).to_d(3)   # => 0.314e1
  #
  # See also BigDecimal::new.
  #
  def to_d(precision)
    BigDecimal(self, precision)
  end
end


class Complex < Numeric
  # call-seq:
  #     cmp.to_d             -> bigdecimal
  #     cmp.to_d(precision)  -> bigdecimal
  #
  # Returns the value as a BigDecimal.
  #
  # The +precision+ parameter is required for a rational complex number.
  # This parameter is used to determine the number of significant digits
  # for the result.
  #
  #     require 'bigdecimal'
  #     require 'bigdecimal/util'
  #
  #     Complex(0.1234567, 0).to_d(4)   # => 0.1235e0
  #     Complex(Rational(22, 7), 0).to_d(3)   # => 0.314e1
  #
  # See also BigDecimal::new.
  #
  def to_d(*args)
    BigDecimal(self) unless self.imag.zero? # to raise eerror

    if args.length == 0
      case self.real
      when Rational
        BigDecimal(self.real) # to raise error
      end
    end
    self.real.to_d(*args)
  end
end


class NilClass
  # call-seq:
  #     nil.to_d -> bigdecimal
  #
  # Returns nil represented as a BigDecimal.
  #
  #     require 'bigdecimal'
  #     require 'bigdecimal/util'
  #
  #     nil.to_d   # => 0.0
  #
  def to_d
    BigDecimal(0)
  end
end
# frozen_string_literal: false
require 'bigdecimal'

#
# Solves a*x = b for x, using LU decomposition.
#
module LUSolve
  module_function

  # Performs LU decomposition of the n by n matrix a.
  def ludecomp(a,n,zero=0,one=1)
    prec = BigDecimal.limit(nil)
    ps     = []
    scales = []
    for i in 0...n do  # pick up largest(abs. val.) element in each row.
      ps <<= i
      nrmrow  = zero
      ixn = i*n
      for j in 0...n do
        biggst = a[ixn+j].abs
        nrmrow = biggst if biggst>nrmrow
      end
      if nrmrow>zero then
        scales <<= one.div(nrmrow,prec)
      else
        raise "Singular matrix"
      end
    end
    n1          = n - 1
    for k in 0...n1 do # Gaussian elimination with partial pivoting.
      biggst  = zero;
      for i in k...n do
        size = a[ps[i]*n+k].abs*scales[ps[i]]
        if size>biggst then
          biggst = size
          pividx  = i
        end
      end
      raise "Singular matrix" if biggst<=zero
      if pividx!=k then
        j = ps[k]
        ps[k] = ps[pividx]
        ps[pividx] = j
      end
      pivot   = a[ps[k]*n+k]
      for i in (k+1)...n do
        psin = ps[i]*n
        a[psin+k] = mult = a[psin+k].div(pivot,prec)
        if mult!=zero then
          pskn = ps[k]*n
          for j in (k+1)...n do
            a[psin+j] -= mult.mult(a[pskn+j],prec)
          end
        end
      end
    end
    raise "Singular matrix" if a[ps[n1]*n+n1] == zero
    ps
  end

  # Solves a*x = b for x, using LU decomposition.
  #
  # a is a matrix, b is a constant vector, x is the solution vector.
  #
  # ps is the pivot, a vector which indicates the permutation of rows performed
  # during LU decomposition.
  def lusolve(a,b,ps,zero=0.0)
    prec = BigDecimal.limit(nil)
    n = ps.size
    x = []
    for i in 0...n do
      dot = zero
      psin = ps[i]*n
      for j in 0...i do
        dot = a[psin+j].mult(x[j],prec) + dot
      end
      x <<= b[ps[i]] - dot
    end
    (n-1).downto(0) do |i|
      dot = zero
      psin = ps[i]*n
      for j in (i+1)...n do
        dot = a[psin+j].mult(x[j],prec) + dot
      end
      x[i]  = (x[i]-dot).div(a[psin+i],prec)
    end
    x
  end
end
# frozen_string_literal: false
require 'bigdecimal'

#
#--
# Contents:
#   sqrt(x, prec)
#   sin (x, prec)
#   cos (x, prec)
#   atan(x, prec)  Note: |x|<1, x=0.9999 may not converge.
#   PI  (prec)
#   E   (prec) == exp(1.0,prec)
#
# where:
#   x    ... BigDecimal number to be computed.
#            |x| must be small enough to get convergence.
#   prec ... Number of digits to be obtained.
#++
#
# Provides mathematical functions.
#
# Example:
#
#   require "bigdecimal/math"
#
#   include BigMath
#
#   a = BigDecimal((PI(100)/2).to_s)
#   puts sin(a,100) # => 0.99999999999999999999......e0
#
module BigMath
  module_function

  # call-seq:
  #   sqrt(decimal, numeric) -> BigDecimal
  #
  # Computes the square root of +decimal+ to the specified number of digits of
  # precision, +numeric+.
  #
  #   BigMath.sqrt(BigDecimal('2'), 16).to_s
  #   #=> "0.1414213562373095048801688724e1"
  #
  def sqrt(x, prec)
    x.sqrt(prec)
  end

  # call-seq:
  #   sin(decimal, numeric) -> BigDecimal
  #
  # Computes the sine of +decimal+ to the specified number of digits of
  # precision, +numeric+.
  #
  # If +decimal+ is Infinity or NaN, returns NaN.
  #
  #   BigMath.sin(BigMath.PI(5)/4, 5).to_s
  #   #=> "0.70710678118654752440082036563292800375e0"
  #
  def sin(x, prec)
    raise ArgumentError, "Zero or negative precision for sin" if prec <= 0
    return BigDecimal("NaN") if x.infinite? || x.nan?
    n    = prec + BigDecimal.double_fig
    one  = BigDecimal("1")
    two  = BigDecimal("2")
    x = -x if neg = x < 0
    if x > (twopi = two * BigMath.PI(prec))
      if x > 30
        x %= twopi
      else
        x -= twopi while x > twopi
      end
    end
    x1   = x
    x2   = x.mult(x,n)
    sign = 1
    y    = x
    d    = y
    i    = one
    z    = one
    while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
      m = BigDecimal.double_fig if m < BigDecimal.double_fig
      sign = -sign
      x1  = x2.mult(x1,n)
      i  += two
      z  *= (i-one) * i
      d   = sign * x1.div(z,m)
      y  += d
    end
    neg ? -y : y
  end

  # call-seq:
  #   cos(decimal, numeric) -> BigDecimal
  #
  # Computes the cosine of +decimal+ to the specified number of digits of
  # precision, +numeric+.
  #
  # If +decimal+ is Infinity or NaN, returns NaN.
  #
  #   BigMath.cos(BigMath.PI(4), 16).to_s
  #   #=> "-0.999999999999999999999999999999856613163740061349e0"
  #
  def cos(x, prec)
    raise ArgumentError, "Zero or negative precision for cos" if prec <= 0
    return BigDecimal("NaN") if x.infinite? || x.nan?
    n    = prec + BigDecimal.double_fig
    one  = BigDecimal("1")
    two  = BigDecimal("2")
    x = -x if x < 0
    if x > (twopi = two * BigMath.PI(prec))
      if x > 30
        x %= twopi
      else
        x -= twopi while x > twopi
      end
    end
    x1 = one
    x2 = x.mult(x,n)
    sign = 1
    y = one
    d = y
    i = BigDecimal("0")
    z = one
    while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
      m = BigDecimal.double_fig if m < BigDecimal.double_fig
      sign = -sign
      x1  = x2.mult(x1,n)
      i  += two
      z  *= (i-one) * i
      d   = sign * x1.div(z,m)
      y  += d
    end
    y
  end

  # call-seq:
  #   atan(decimal, numeric) -> BigDecimal
  #
  # Computes the arctangent of +decimal+ to the specified number of digits of
  # precision, +numeric+.
  #
  # If +decimal+ is NaN, returns NaN.
  #
  #   BigMath.atan(BigDecimal('-1'), 16).to_s
  #   #=> "-0.785398163397448309615660845819878471907514682065e0"
  #
  def atan(x, prec)
    raise ArgumentError, "Zero or negative precision for atan" if prec <= 0
    return BigDecimal("NaN") if x.nan?
    pi = PI(prec)
    x = -x if neg = x < 0
    return pi.div(neg ? -2 : 2, prec) if x.infinite?
    return pi / (neg ? -4 : 4) if x.round(prec) == 1
    x = BigDecimal("1").div(x, prec) if inv = x > 1
    x = (-1 + sqrt(1 + x**2, prec))/x if dbl = x > 0.5
    n    = prec + BigDecimal.double_fig
    y = x
    d = y
    t = x
    r = BigDecimal("3")
    x2 = x.mult(x,n)
    while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
      m = BigDecimal.double_fig if m < BigDecimal.double_fig
      t = -t.mult(x2,n)
      d = t.div(r,m)
      y += d
      r += 2
    end
    y *= 2 if dbl
    y = pi / 2 - y if inv
    y = -y if neg
    y
  end

  # call-seq:
  #   PI(numeric) -> BigDecimal
  #
  # Computes the value of pi to the specified number of digits of precision,
  # +numeric+.
  #
  #   BigMath.PI(10).to_s
  #   #=> "0.3141592653589793238462643388813853786957412e1"
  #
  def PI(prec)
    raise ArgumentError, "Zero or negative precision for PI" if prec <= 0
    n      = prec + BigDecimal.double_fig
    zero   = BigDecimal("0")
    one    = BigDecimal("1")
    two    = BigDecimal("2")

    m25    = BigDecimal("-0.04")
    m57121 = BigDecimal("-57121")

    pi     = zero

    d = one
    k = one
    t = BigDecimal("-80")
    while d.nonzero? && ((m = n - (pi.exponent - d.exponent).abs) > 0)
      m = BigDecimal.double_fig if m < BigDecimal.double_fig
      t   = t*m25
      d   = t.div(k,m)
      k   = k+two
      pi  = pi + d
    end

    d = one
    k = one
    t = BigDecimal("956")
    while d.nonzero? && ((m = n - (pi.exponent - d.exponent).abs) > 0)
      m = BigDecimal.double_fig if m < BigDecimal.double_fig
      t   = t.div(m57121,n)
      d   = t.div(k,m)
      pi  = pi + d
      k   = k+two
    end
    pi
  end

  # call-seq:
  #   E(numeric) -> BigDecimal
  #
  # Computes e (the base of natural logarithms) to the specified number of
  # digits of precision, +numeric+.
  #
  #   BigMath.E(10).to_s
  #   #=> "0.271828182845904523536028752390026306410273e1"
  #
  def E(prec)
    raise ArgumentError, "Zero or negative precision for E" if prec <= 0
    BigMath.exp(1, prec)
  end
end
# frozen_string_literal: true

module Bundler
  class Source
    autoload :Gemspec,  File.expand_path("source/gemspec", __dir__)
    autoload :Git,      File.expand_path("source/git", __dir__)
    autoload :Metadata, File.expand_path("source/metadata", __dir__)
    autoload :Path,     File.expand_path("source/path", __dir__)
    autoload :Rubygems, File.expand_path("source/rubygems", __dir__)
    autoload :RubygemsAggregate, File.expand_path("source/rubygems_aggregate", __dir__)

    attr_accessor :dependency_names

    def unmet_deps
      specs.unmet_dependency_names
    end

    def version_message(spec)
      message = "#{spec.name} #{spec.version}"
      message += " (#{spec.platform})" if spec.platform != Gem::Platform::RUBY && !spec.platform.nil?

      if Bundler.locked_gems
        locked_spec = Bundler.locked_gems.specs.find {|s| s.name == spec.name }
        locked_spec_version = locked_spec.version if locked_spec
        if locked_spec_version && spec.version != locked_spec_version
          message += Bundler.ui.add_color(" (was #{locked_spec_version})", version_color(spec.version, locked_spec_version))
        end
      end

      message
    end

    def can_lock?(spec)
      spec.source == self
    end

    def local!; end

    def local_only!; end

    def cached!; end

    def remote!; end

    def add_dependency_names(names)
      @dependency_names = Array(dependency_names) | Array(names)
    end

    # it's possible that gems from one source depend on gems from some
    # other source, so now we download gemspecs and iterate over those
    # dependencies, looking for gems we don't have info on yet.
    def double_check_for(*); end

    def dependency_names_to_double_check
      specs.dependency_names
    end

    def spec_names
      specs.spec_names
    end

    def include?(other)
      other == self
    end

    def inspect
      "#<#{self.class}:0x#{object_id} #{self}>"
    end

    def identifier
      to_s
    end

    def path?
      instance_of?(Bundler::Source::Path)
    end

    def extension_cache_path(spec)
      return unless Bundler.feature_flag.global_gem_cache?
      return unless source_slug = extension_cache_slug(spec)
      Bundler.user_cache.join(
        "extensions", Gem::Platform.local.to_s, Bundler.ruby_scope,
        source_slug, spec.full_name
      )
    end

    private

    def version_color(spec_version, locked_spec_version)
      if Gem::Version.correct?(spec_version) && Gem::Version.correct?(locked_spec_version)
        # display yellow if there appears to be a regression
        earlier_version?(spec_version, locked_spec_version) ? :yellow : :green
      else
        # default to green if the versions cannot be directly compared
        :green
      end
    end

    def earlier_version?(spec_version, locked_spec_version)
      Gem::Version.new(spec_version) < Gem::Version.new(locked_spec_version)
    end

    def print_using_message(message)
      if !message.include?("(was ") && Bundler.feature_flag.suppress_install_using_messages?
        Bundler.ui.debug message
      else
        Bundler.ui.info message
      end
    end

    def extension_cache_slug(_)
      nil
    end
  end
end
# frozen_string_literal: true

module Bundler
  # Represents metadata from when the Bundler gem was built.
  module BuildMetadata
    # begin ivars
    @release = false
    # end ivars

    # A hash representation of the build metadata.
    def self.to_h
      {
        "Built At" => built_at,
        "Git SHA" => git_commit_sha,
        "Released Version" => release?,
      }
    end

    # A string representing the date the bundler gem was built.
    def self.built_at
      @built_at ||= Time.now.utc.strftime("%Y-%m-%d").freeze
    end

    # The SHA for the git commit the bundler gem was built from.
    def self.git_commit_sha
      return @git_commit_sha if instance_variable_defined? :@git_commit_sha

      # If Bundler has been installed without its .git directory and without a
      # commit instance variable then we can't determine its commits SHA.
      git_dir = File.join(File.expand_path("../../../..", __FILE__), ".git")
      if File.directory?(git_dir)
        return @git_commit_sha = Dir.chdir(git_dir) { `git rev-parse --short HEAD`.strip.freeze }
      end

      @git_commit_sha ||= "unknown"
    end

    # Whether this is an official release build of Bundler.
    def self.release?
      @release
    end
  end
end
# frozen_string_literal: true

require_relative "base"

module Bundler
  class Fetcher
    class Index < Base
      def specs(_gem_names)
        Bundler.rubygems.fetch_all_remote_specs(remote)
      rescue Gem::RemoteFetcher::FetchError => e
        case e.message
        when /certificate verify failed/
          raise CertificateFailureError.new(display_uri)
        when /401/
          raise BadAuthenticationError, remote_uri if remote_uri.userinfo
          raise AuthenticationRequiredError, remote_uri
        when /403/
          raise BadAuthenticationError, remote_uri if remote_uri.userinfo
          raise AuthenticationRequiredError, remote_uri
        else
          raise HTTPError, "Could not fetch specs from #{display_uri} due to underlying error <#{e.message}>"
        end
      end

      def fetch_spec(spec)
        spec -= [nil, "ruby", ""]
        spec_file_name = "#{spec.join "-"}.gemspec"

        uri = Bundler::URI.parse("#{remote_uri}#{Gem::MARSHAL_SPEC_DIR}#{spec_file_name}.rz")
        if uri.scheme == "file"
          path = Bundler.rubygems.correct_for_windows_path(uri.path)
          Bundler.load_marshal Bundler.rubygems.inflate(Gem.read_binary(path))
        elsif cached_spec_path = gemspec_cached_path(spec_file_name)
          Bundler.load_gemspec(cached_spec_path)
        else
          Bundler.load_marshal Bundler.rubygems.inflate(downloader.fetch(uri).body)
        end
      rescue MarshalError
        raise HTTPError, "Gemspec #{spec} contained invalid data.\n" \
          "Your network or your gem server is probably having issues right now."
      end

      private

      # cached gem specification path, if one exists
      def gemspec_cached_path(spec_file_name)
        paths = Bundler.rubygems.spec_cache_dirs.map {|dir| File.join(dir, spec_file_name) }
        paths.find {|path| File.file? path }
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class Fetcher
    class Base
      attr_reader :downloader
      attr_reader :display_uri
      attr_reader :remote

      def initialize(downloader, remote, display_uri)
        raise "Abstract class" if self.class == Base
        @downloader = downloader
        @remote = remote
        @display_uri = display_uri
      end

      def remote_uri
        @remote.uri
      end

      def fetch_uri
        @fetch_uri ||= begin
          if remote_uri.host == "rubygems.org"
            uri = remote_uri.dup
            uri.host = "index.rubygems.org"
            uri
          else
            remote_uri
          end
        end
      end

      def available?
        true
      end

      def api_fetcher?
        false
      end

      private

      def log_specs(debug_msg)
        if Bundler.ui.debug?
          Bundler.ui.debug debug_msg
        else
          Bundler.ui.info ".", false
        end
      end
    end
  end
end
# frozen_string_literal: true

require_relative "base"
require_relative "../worker"

module Bundler
  autoload :CompactIndexClient, File.expand_path("../compact_index_client", __dir__)

  class Fetcher
    class CompactIndex < Base
      def self.compact_index_request(method_name)
        method = instance_method(method_name)
        undef_method(method_name)
        define_method(method_name) do |*args, &blk|
          begin
            method.bind(self).call(*args, &blk)
          rescue NetworkDownError, CompactIndexClient::Updater::MisMatchedChecksumError => e
            raise HTTPError, e.message
          rescue AuthenticationRequiredError
            # Fail since we got a 401 from the server.
            raise
          rescue HTTPError => e
            Bundler.ui.trace(e)
            nil
          end
        end
      end

      def specs(gem_names)
        specs_for_names(gem_names)
      end
      compact_index_request :specs

      def specs_for_names(gem_names)
        gem_info = []
        complete_gems = []
        remaining_gems = gem_names.dup

        until remaining_gems.empty?
          log_specs "Looking up gems #{remaining_gems.inspect}"

          deps = begin
                   parallel_compact_index_client.dependencies(remaining_gems)
                 rescue TooManyRequestsError
                   @bundle_worker.stop if @bundle_worker
                   @bundle_worker = nil # reset it.  Not sure if necessary
                   serial_compact_index_client.dependencies(remaining_gems)
                 end
          next_gems = deps.map {|d| d[3].map(&:first).flatten(1) }.flatten(1).uniq
          deps.each {|dep| gem_info << dep }
          complete_gems.concat(deps.map(&:first)).uniq!
          remaining_gems = next_gems - complete_gems
        end
        @bundle_worker.stop if @bundle_worker
        @bundle_worker = nil # reset it.  Not sure if necessary

        gem_info
      end

      def fetch_spec(spec)
        spec -= [nil, "ruby", ""]
        contents = compact_index_client.spec(*spec)
        return nil if contents.nil?
        contents.unshift(spec.first)
        contents[3].map! {|d| Gem::Dependency.new(*d) }
        EndpointSpecification.new(*contents)
      end
      compact_index_request :fetch_spec

      def available?
        return nil unless SharedHelpers.md5_available?
        user_home = Bundler.user_home
        return nil unless user_home.directory? && user_home.writable?
        # Read info file checksums out of /versions, so we can know if gems are up to date
        fetch_uri.scheme != "file" && compact_index_client.update_and_parse_checksums!
      rescue CompactIndexClient::Updater::MisMatchedChecksumError => e
        Bundler.ui.debug(e.message)
        nil
      end
      compact_index_request :available?

      def api_fetcher?
        true
      end

      private

      def compact_index_client
        @compact_index_client ||=
          SharedHelpers.filesystem_access(cache_path) do
            CompactIndexClient.new(cache_path, client_fetcher)
          end
      end

      def parallel_compact_index_client
        compact_index_client.execution_mode = lambda do |inputs, &blk|
          func = lambda {|object, _index| blk.call(object) }
          worker = bundle_worker(func)
          inputs.each {|input| worker.enq(input) }
          inputs.map { worker.deq }
        end

        compact_index_client
      end

      def serial_compact_index_client
        compact_index_client.sequential_execution_mode!
        compact_index_client
      end

      def bundle_worker(func = nil)
        @bundle_worker ||= begin
          worker_name = "Compact Index (#{display_uri.host})"
          Bundler::Worker.new(Bundler.settings.processor_count, worker_name, func)
        end
        @bundle_worker.tap do |worker|
          worker.instance_variable_set(:@func, func) if func
        end
      end

      def cache_path
        Bundler.user_cache.join("compact_index", remote.cache_slug)
      end

      def client_fetcher
        ClientFetcher.new(self, Bundler.ui)
      end

      ClientFetcher = Struct.new(:fetcher, :ui) do
        def call(path, headers)
          fetcher.downloader.fetch(fetcher.fetch_uri + path, headers)
        rescue NetworkDownError => e
          raise unless Bundler.feature_flag.allow_offline_install? && headers["If-None-Match"]
          ui.warn "Using the cached data for the new index because of a network error: #{e}"
          Net::HTTPNotModified.new(nil, nil, nil)
        end
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class Fetcher
    class Downloader
      attr_reader :connection
      attr_reader :redirect_limit

      def initialize(connection, redirect_limit)
        @connection = connection
        @redirect_limit = redirect_limit
      end

      def fetch(uri, headers = {}, counter = 0)
        raise HTTPError, "Too many redirects" if counter >= redirect_limit

        filtered_uri = URICredentialsFilter.credential_filtered_uri(uri)

        response = request(uri, headers)
        Bundler.ui.debug("HTTP #{response.code} #{response.message} #{filtered_uri}")

        case response
        when Net::HTTPSuccess, Net::HTTPNotModified
          response
        when Net::HTTPRedirection
          new_uri = Bundler::URI.parse(response["location"])
          if new_uri.host == uri.host
            new_uri.user = uri.user
            new_uri.password = uri.password
          end
          fetch(new_uri, headers, counter + 1)
        when Net::HTTPRequestedRangeNotSatisfiable
          new_headers = headers.dup
          new_headers.delete("Range")
          new_headers["Accept-Encoding"] = "gzip"
          fetch(uri, new_headers)
        when Net::HTTPRequestEntityTooLarge
          raise FallbackError, response.body
        when Net::HTTPTooManyRequests
          raise TooManyRequestsError, response.body
        when Net::HTTPUnauthorized
          raise BadAuthenticationError, uri.host if uri.userinfo
          raise AuthenticationRequiredError, uri.host
        when Net::HTTPNotFound
          raise FallbackError, "Net::HTTPNotFound: #{filtered_uri}"
        else
          raise HTTPError, "#{response.class}#{": #{response.body}" unless response.body.empty?}"
        end
      end

      def request(uri, headers)
        validate_uri_scheme!(uri)

        filtered_uri = URICredentialsFilter.credential_filtered_uri(uri)

        Bundler.ui.debug "HTTP GET #{filtered_uri}"
        req = Net::HTTP::Get.new uri.request_uri, headers
        if uri.user
          user = CGI.unescape(uri.user)
          password = uri.password ? CGI.unescape(uri.password) : nil
          req.basic_auth(user, password)
        end
        connection.request(uri, req)
      rescue NoMethodError => e
        raise unless ["undefined method", "use_ssl="].all? {|snippet| e.message.include? snippet }
        raise LoadError.new("cannot load such file -- openssl")
      rescue OpenSSL::SSL::SSLError
        raise CertificateFailureError.new(uri)
      rescue *HTTP_ERRORS => e
        Bundler.ui.trace e
        if e.is_a?(SocketError) || e.message =~ /host down:/
          raise NetworkDownError, "Could not reach host #{uri.host}. Check your network " \
            "connection and try again."
        else
          raise HTTPError, "Network error while fetching #{filtered_uri}" \
            " (#{e})"
        end
      end

      private

      def validate_uri_scheme!(uri)
        return if uri.scheme =~ /\Ahttps?\z/
        raise InvalidOption,
          "The request uri `#{uri}` has an invalid scheme (`#{uri.scheme}`). " \
          "Did you mean `http` or `https`?"
      end
    end
  end
end
# frozen_string_literal: true

require_relative "base"
require "cgi"

module Bundler
  class Fetcher
    class Dependency < Base
      def available?
        @available ||= fetch_uri.scheme != "file" && downloader.fetch(dependency_api_uri)
      rescue NetworkDownError => e
        raise HTTPError, e.message
      rescue AuthenticationRequiredError
        # Fail since we got a 401 from the server.
        raise
      rescue HTTPError
        false
      end

      def api_fetcher?
        true
      end

      def specs(gem_names, full_dependency_list = [], last_spec_list = [])
        query_list = gem_names.uniq - full_dependency_list

        log_specs "Query List: #{query_list.inspect}"

        return last_spec_list if query_list.empty?

        spec_list, deps_list = Bundler::Retry.new("dependency api", FAIL_ERRORS).attempts do
          dependency_specs(query_list)
        end

        returned_gems = spec_list.map(&:first).uniq
        specs(deps_list, full_dependency_list + returned_gems, spec_list + last_spec_list)
      rescue MarshalError
        Bundler.ui.info "" unless Bundler.ui.debug? # new line now that the dots are over
        Bundler.ui.debug "could not fetch from the dependency API, trying the full index"
        nil
      rescue HTTPError, GemspecError
        Bundler.ui.info "" unless Bundler.ui.debug? # new line now that the dots are over
        Bundler.ui.debug "could not fetch from the dependency API\nit's suggested to retry using the full index via `bundle install --full-index`"
        nil
      end

      def dependency_specs(gem_names)
        Bundler.ui.debug "Query Gemcutter Dependency Endpoint API: #{gem_names.join(",")}"

        gem_list = unmarshalled_dep_gems(gem_names)
        get_formatted_specs_and_deps(gem_list)
      end

      def unmarshalled_dep_gems(gem_names)
        gem_list = []
        gem_names.each_slice(Source::Rubygems::API_REQUEST_SIZE) do |names|
          marshalled_deps = downloader.fetch(dependency_api_uri(names)).body
          gem_list.concat(Bundler.load_marshal(marshalled_deps))
        end
        gem_list
      end

      def get_formatted_specs_and_deps(gem_list)
        deps_list = []
        spec_list = []

        gem_list.each do |s|
          deps_list.concat(s[:dependencies].map(&:first))
          deps = s[:dependencies].map {|n, d| [n, d.split(", ")] }
          spec_list.push([s[:name], s[:number], s[:platform], deps])
        end
        [spec_list, deps_list]
      end

      def dependency_api_uri(gem_names = [])
        uri = fetch_uri + "api/v1/dependencies"
        uri.query = "gems=#{CGI.escape(gem_names.sort.join(","))}" if gem_names.any?
        uri
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class Index
    include Enumerable

    def self.build
      i = new
      yield i
      i
    end

    attr_reader :specs, :all_specs, :sources
    protected :specs, :all_specs

    RUBY = "ruby".freeze
    NULL = "\0".freeze

    def initialize
      @sources = []
      @cache = {}
      @specs = Hash.new {|h, k| h[k] = {} }
      @all_specs = Hash.new {|h, k| h[k] = EMPTY_SEARCH }
    end

    def initialize_copy(o)
      @sources = o.sources.dup
      @cache = {}
      @specs = Hash.new {|h, k| h[k] = {} }
      @all_specs = Hash.new {|h, k| h[k] = EMPTY_SEARCH }

      o.specs.each do |name, hash|
        @specs[name] = hash.dup
      end
      o.all_specs.each do |name, array|
        @all_specs[name] = array.dup
      end
    end

    def inspect
      "#<#{self.class}:0x#{object_id} sources=#{sources.map(&:inspect)} specs.size=#{specs.size}>"
    end

    def empty?
      each { return false }
      true
    end

    def search_all(name)
      all_matches = local_search(name) + @all_specs[name]
      @sources.each do |source|
        all_matches.concat(source.search_all(name))
      end
      all_matches
    end

    # Search this index's specs, and any source indexes that this index knows
    # about, returning all of the results.
    def search(query, base = nil)
      sort_specs(unsorted_search(query, base))
    end

    def unsorted_search(query, base)
      results = local_search(query, base)

      seen = results.map(&:full_name).uniq unless @sources.empty?

      @sources.each do |source|
        source.unsorted_search(query, base).each do |spec|
          next if seen.include?(spec.full_name)

          seen << spec.full_name
          results << spec
        end
      end

      results
    end
    protected :unsorted_search

    def self.sort_specs(specs)
      specs.sort_by do |s|
        platform_string = s.platform.to_s
        [s.version, platform_string == RUBY ? NULL : platform_string]
      end
    end

    def sort_specs(specs)
      self.class.sort_specs(specs)
    end

    def local_search(query, base = nil)
      case query
      when Gem::Specification, RemoteSpecification, LazySpecification, EndpointSpecification then search_by_spec(query)
      when String then specs_by_name(query)
      when Gem::Dependency then search_by_dependency(query, base)
      when DepProxy then search_by_dependency(query.dep, base)
      else
        raise "You can't search for a #{query.inspect}."
      end
    end

    alias_method :[], :search

    def <<(spec)
      @specs[spec.name][spec.full_name] = spec
      spec
    end

    def each(&blk)
      return enum_for(:each) unless blk
      specs.values.each do |spec_sets|
        spec_sets.values.each(&blk)
      end
      sources.each {|s| s.each(&blk) }
      self
    end

    def spec_names
      names = specs.keys + sources.map(&:spec_names)
      names.uniq!
      names
    end

    def unmet_dependency_names
      dependency_names.select do |name|
        search(name).empty?
      end
    end

    def dependency_names
      names = []
      each do |spec|
        spec.dependencies.each do |dep|
          next if dep.type == :development
          names << dep.name
        end
      end
      names.uniq
    end

    def use(other, override_dupes = false)
      return unless other
      other.each do |s|
        if (dupes = search_by_spec(s)) && !dupes.empty?
          # safe to << since it's a new array when it has contents
          @all_specs[s.name] = dupes << s
          next unless override_dupes
        end
        self << s
      end
      self
    end

    def size
      @sources.inject(@specs.size) do |size, source|
        size += source.size
      end
    end

    # Whether all the specs in self are in other
    # TODO: rename to #include?
    def ==(other)
      all? do |spec|
        other_spec = other[spec].first
        other_spec && dependencies_eql?(spec, other_spec) && spec.source == other_spec.source
      end
    end

    def dependencies_eql?(spec, other_spec)
      deps       = spec.dependencies.select {|d| d.type != :development }
      other_deps = other_spec.dependencies.select {|d| d.type != :development }
      deps.sort == other_deps.sort
    end

    def add_source(index)
      raise ArgumentError, "Source must be an index, not #{index.class}" unless index.is_a?(Index)
      @sources << index
      @sources.uniq! # need to use uniq! here instead of checking for the item before adding
    end

    private

    def specs_by_name(name)
      @specs[name].values
    end

    def search_by_dependency(dependency, base = nil)
      @cache[base || false] ||= {}
      @cache[base || false][dependency] ||= begin
        specs = specs_by_name(dependency.name)
        specs += base if base
        found = specs.select do |spec|
          next true if spec.source.is_a?(Source::Gemspec)
          if base # allow all platforms when searching from a lockfile
            dependency.matches_spec?(spec)
          else
            dependency.matches_spec?(spec) && Gem::Platform.match_spec?(spec)
          end
        end

        found
      end
    end

    EMPTY_SEARCH = [].freeze

    def search_by_spec(spec)
      spec = @specs[spec.name][spec.full_name]
      spec ? [spec] : EMPTY_SEARCH
    end
  end
end
# frozen_string_literal: true

module Bundler
  # used for Creating Specifications from the Gemcutter Endpoint
  class EndpointSpecification < Gem::Specification
    ILLFORMED_MESSAGE = 'Ill-formed requirement ["#<YAML::Syck::DefaultKey'.freeze
    include MatchPlatform

    attr_reader :name, :version, :platform, :required_rubygems_version, :required_ruby_version, :checksum
    attr_accessor :source, :remote, :dependencies

    def initialize(name, version, platform, dependencies, metadata = nil)
      super()
      @name         = name
      @version      = Gem::Version.create version
      @platform     = platform
      @dependencies = dependencies.map {|dep, reqs| build_dependency(dep, reqs) }

      @loaded_from          = nil
      @remote_specification = nil

      parse_metadata(metadata)
    end

    def fetch_platform
      @platform
    end

    # needed for standalone, load required_paths from local gemspec
    # after the gem is installed
    def require_paths
      if @remote_specification
        @remote_specification.require_paths
      elsif _local_specification
        _local_specification.require_paths
      else
        super
      end
    end

    # needed for inline
    def load_paths
      # remote specs aren't installed, and can't have load_paths
      if _local_specification
        _local_specification.load_paths
      else
        super
      end
    end

    # needed for binstubs
    def executables
      if @remote_specification
        @remote_specification.executables
      elsif _local_specification
        _local_specification.executables
      else
        super
      end
    end

    # needed for bundle clean
    def bindir
      if @remote_specification
        @remote_specification.bindir
      elsif _local_specification
        _local_specification.bindir
      else
        super
      end
    end

    # needed for post_install_messages during install
    def post_install_message
      if @remote_specification
        @remote_specification.post_install_message
      elsif _local_specification
        _local_specification.post_install_message
      else
        super
      end
    end

    # needed for "with native extensions" during install
    def extensions
      if @remote_specification
        @remote_specification.extensions
      elsif _local_specification
        _local_specification.extensions
      else
        super
      end
    end

    def _local_specification
      return unless @loaded_from && File.exist?(local_specification_path)
      eval(File.read(local_specification_path)).tap do |spec|
        spec.loaded_from = @loaded_from
      end
    end

    def __swap__(spec)
      SharedHelpers.ensure_same_dependencies(self, dependencies, spec.dependencies)
      @remote_specification = spec
    end

    private

    def local_specification_path
      "#{base_dir}/specifications/#{full_name}.gemspec"
    end

    def parse_metadata(data)
      return unless data
      data.each do |k, v|
        next unless v
        case k.to_s
        when "checksum"
          @checksum = v.last
        when "rubygems"
          @required_rubygems_version = Gem::Requirement.new(v)
        when "ruby"
          @required_ruby_version = Gem::Requirement.new(v)
        end
      end
    rescue StandardError => e
      raise GemspecError, "There was an error parsing the metadata for the gem #{name} (#{version}): #{e.class}\n#{e}\nThe metadata was #{data.inspect}"
    end

    def build_dependency(name, requirements)
      Gem::Dependency.new(name, requirements)
    rescue ArgumentError => e
      raise unless e.message.include?(ILLFORMED_MESSAGE)
      puts # we shouldn't print the error message on the "fetching info" status line
      raise GemspecError,
        "Unfortunately, the gem #{name} (#{version}) has an invalid " \
        "gemspec.\nPlease ask the gem author to yank the bad version to fix " \
        "this issue. For more information, see http://bit.ly/syck-defaultkey."
    end
  end
end
# frozen_string_literal: true

require_relative "worker"
require_relative "installer/parallel_installer"
require_relative "installer/standalone"
require_relative "installer/gem_installer"

module Bundler
  class Installer
    class << self
      attr_accessor :ambiguous_gems

      Installer.ambiguous_gems = []
    end

    attr_reader :post_install_messages

    # Begins the installation process for Bundler.
    # For more information see the #run method on this class.
    def self.install(root, definition, options = {})
      installer = new(root, definition)
      Plugin.hook(Plugin::Events::GEM_BEFORE_INSTALL_ALL, definition.dependencies)
      installer.run(options)
      Plugin.hook(Plugin::Events::GEM_AFTER_INSTALL_ALL, definition.dependencies)
      installer
    end

    def initialize(root, definition)
      @root = root
      @definition = definition
      @post_install_messages = {}
    end

    # Runs the install procedures for a specific Gemfile.
    #
    # Firstly, this method will check to see if `Bundler.bundle_path` exists
    # and if not then Bundler will create the directory. This is usually the same
    # location as RubyGems which typically is the `~/.gem` directory
    # unless other specified.
    #
    # Secondly, it checks if Bundler has been configured to be "frozen".
    # Frozen ensures that the Gemfile and the Gemfile.lock file are matching.
    # This stops a situation where a developer may update the Gemfile but may not run
    # `bundle install`, which leads to the Gemfile.lock file not being correctly updated.
    # If this file is not correctly updated then any other developer running
    # `bundle install` will potentially not install the correct gems.
    #
    # Thirdly, Bundler checks if there are any dependencies specified in the Gemfile.
    # If there are no dependencies specified then Bundler returns a warning message stating
    # so and this method returns.
    #
    # Fourthly, Bundler checks if the Gemfile.lock exists, and if so
    # then proceeds to set up a definition based on the Gemfile and the Gemfile.lock.
    # During this step Bundler will also download information about any new gems
    # that are not in the Gemfile.lock and resolve any dependencies if needed.
    #
    # Fifthly, Bundler resolves the dependencies either through a cache of gems or by remote.
    # This then leads into the gems being installed, along with stubs for their executables,
    # but only if the --binstubs option has been passed or Bundler.options[:bin] has been set
    # earlier.
    #
    # Sixthly, a new Gemfile.lock is created from the installed gems to ensure that the next time
    # that a user runs `bundle install` they will receive any updates from this process.
    #
    # Finally, if the user has specified the standalone flag, Bundler will generate the needed
    # require paths and save them in a `setup.rb` file. See `bundle standalone --help` for more
    # information.
    def run(options)
      create_bundle_path

      ProcessLock.lock do
        if Bundler.frozen_bundle?
          @definition.ensure_equivalent_gemfile_and_lockfile(options[:deployment])
        end

        if @definition.dependencies.empty?
          Bundler.ui.warn "The Gemfile specifies no dependencies"
          lock
          return
        end

        if resolve_if_needed(options)
          ensure_specs_are_compatible!
          load_plugins
          options.delete(:jobs)
        else
          options[:jobs] = 1 # to avoid the overhead of Bundler::Worker
        end
        install(options)

        Gem::Specification.reset # invalidate gem specification cache so that installed gems are immediately available

        lock unless Bundler.frozen_bundle?
        Standalone.new(options[:standalone], @definition).generate if options[:standalone]
      end
    end

    def generate_bundler_executable_stubs(spec, options = {})
      if options[:binstubs_cmd] && spec.executables.empty?
        options = {}
        spec.runtime_dependencies.each do |dep|
          bins = @definition.specs[dep].first.executables
          options[dep.name] = bins unless bins.empty?
        end
        if options.any?
          Bundler.ui.warn "#{spec.name} has no executables, but you may want " \
            "one from a gem it depends on."
          options.each {|name, bins| Bundler.ui.warn "  #{name} has: #{bins.join(", ")}" }
        else
          Bundler.ui.warn "There are no executables for the gem #{spec.name}."
        end
        return
      end

      # double-assignment to avoid warnings about variables that will be used by ERB
      bin_path = Bundler.bin_path
      bin_path = bin_path
      relative_gemfile_path = Bundler.default_gemfile.relative_path_from(bin_path)
      relative_gemfile_path = relative_gemfile_path
      ruby_command = Thor::Util.ruby_command
      ruby_command = ruby_command
      template_path = File.expand_path("../templates/Executable", __FILE__)
      if spec.name == "bundler"
        template_path += ".bundler"
        spec.executables = %(bundle)
      end
      template = File.read(template_path)

      exists = []
      spec.executables.each do |executable|
        binstub_path = "#{bin_path}/#{executable}"
        if File.exist?(binstub_path) && !options[:force]
          exists << executable
          next
        end

        mode = Gem.win_platform? ? "wb:UTF-8" : "w"
        require "erb"
        content = if RUBY_VERSION >= "2.6"
          ERB.new(template, :trim_mode => "-").result(binding)
        else
          ERB.new(template, nil, "-").result(binding)
        end

        File.write(binstub_path, content, :mode => mode, :perm => 0o777 & ~File.umask)
        if Gem.win_platform? || options[:all_platforms]
          prefix = "@ruby -x \"%~f0\" %*\n@exit /b %ERRORLEVEL%\n\n"
          File.write("#{binstub_path}.cmd", prefix + content, :mode => mode)
        end
      end

      if options[:binstubs_cmd] && exists.any?
        case exists.size
        when 1
          Bundler.ui.warn "Skipped #{exists[0]} since it already exists."
        when 2
          Bundler.ui.warn "Skipped #{exists.join(" and ")} since they already exist."
        else
          items = exists[0...-1].empty? ? nil : exists[0...-1].join(", ")
          skipped = [items, exists[-1]].compact.join(" and ")
          Bundler.ui.warn "Skipped #{skipped} since they already exist."
        end
        Bundler.ui.warn "If you want to overwrite skipped stubs, use --force."
      end
    end

    def generate_standalone_bundler_executable_stubs(spec, options = {})
      # double-assignment to avoid warnings about variables that will be used by ERB
      bin_path = Bundler.bin_path
      unless path = Bundler.settings[:path]
        raise "Can't standalone without an explicit path set"
      end
      standalone_path = Bundler.root.join(path).relative_path_from(bin_path)
      standalone_path = standalone_path
      template = File.read(File.expand_path("../templates/Executable.standalone", __FILE__))
      ruby_command = Thor::Util.ruby_command
      ruby_command = ruby_command

      spec.executables.each do |executable|
        next if executable == "bundle"
        executable_path = Pathname(spec.full_gem_path).join(spec.bindir, executable).relative_path_from(bin_path)
        executable_path = executable_path

        mode = Gem.win_platform? ? "wb:UTF-8" : "w"
        require "erb"
        content = if RUBY_VERSION >= "2.6"
          ERB.new(template, :trim_mode => "-").result(binding)
        else
          ERB.new(template, nil, "-").result(binding)
        end

        File.write("#{bin_path}/#{executable}", content, :mode => mode, :perm => 0o755)
        if Gem.win_platform? || options[:all_platforms]
          prefix = "@ruby -x \"%~f0\" %*\n@exit /b %ERRORLEVEL%\n\n"
          File.write("#{bin_path}/#{executable}.cmd", prefix + content, :mode => mode)
        end
      end
    end

    private

    # the order that the resolver provides is significant, since
    # dependencies might affect the installation of a gem.
    # that said, it's a rare situation (other than rake), and parallel
    # installation is SO MUCH FASTER. so we let people opt in.
    def install(options)
      force = options["force"]
      jobs = installation_parallelization(options)
      install_in_parallel jobs, options[:standalone], force
    end

    def installation_parallelization(options)
      if jobs = options.delete(:jobs)
        return jobs
      end

      if jobs = Bundler.settings[:jobs]
        return jobs
      end

      # Parallelization has some issues on Windows, so it's not yet the default
      return 1 if Gem.win_platform?

      Bundler.settings.processor_count
    end

    def load_plugins
      Bundler.rubygems.load_plugins

      requested_path_gems = @definition.requested_specs.select {|s| s.source.is_a?(Source::Path) }
      path_plugin_files = requested_path_gems.map do |spec|
        begin
          Bundler.rubygems.spec_matches_for_glob(spec, "rubygems_plugin#{Bundler.rubygems.suffix_pattern}")
        rescue TypeError
          error_message = "#{spec.name} #{spec.version} has an invalid gemspec"
          raise Gem::InvalidSpecificationException, error_message
        end
      end.flatten
      Bundler.rubygems.load_plugin_files(path_plugin_files)
      Bundler.rubygems.load_env_plugins
    end

    def ensure_specs_are_compatible!
      system_ruby = Bundler::RubyVersion.system
      rubygems_version = Gem::Version.create(Gem::VERSION)
      @definition.specs.each do |spec|
        if required_ruby_version = spec.required_ruby_version
          unless required_ruby_version.satisfied_by?(system_ruby.gem_version)
            raise InstallError, "#{spec.full_name} requires ruby version #{required_ruby_version}, " \
              "which is incompatible with the current version, #{system_ruby}"
          end
        end
        next unless required_rubygems_version = spec.required_rubygems_version
        unless required_rubygems_version.satisfied_by?(rubygems_version)
          raise InstallError, "#{spec.full_name} requires rubygems version #{required_rubygems_version}, " \
            "which is incompatible with the current version, #{rubygems_version}"
        end
      end
    end

    def install_in_parallel(size, standalone, force = false)
      spec_installations = ParallelInstaller.call(self, @definition.specs, size, standalone, force)
      spec_installations.each do |installation|
        post_install_messages[installation.name] = installation.post_install_message if installation.has_post_install_message?
      end
    end

    def create_bundle_path
      SharedHelpers.filesystem_access(Bundler.bundle_path.to_s) do |p|
        Bundler.mkdir_p(p)
      end unless Bundler.bundle_path.exist?
    rescue Errno::EEXIST
      raise PathError, "Could not install to path `#{Bundler.bundle_path}` " \
        "because a file already exists at that path. Either remove or rename the file so the directory can be created."
    end

    # returns whether or not a re-resolve was needed
    def resolve_if_needed(options)
      if !@definition.unlocking? && !options["force"] && !Bundler.settings[:inline] && Bundler.default_lockfile.file?
        return false if @definition.nothing_changed? && !@definition.missing_specs?
      end

      options["local"] ? @definition.resolve_with_cache! : @definition.resolve_remotely!
      true
    end

    def lock(opts = {})
      @definition.lock(Bundler.default_lockfile, opts[:preserve_unknown_sections])
    end
  end
end
# frozen_string_literal: true

module Bundler
  class RubyVersion
    attr_reader :versions,
      :patchlevel,
      :engine,
      :engine_versions,
      :gem_version,
      :engine_gem_version

    def initialize(versions, patchlevel, engine, engine_version)
      # The parameters to this method must satisfy the
      # following constraints, which are verified in
      # the DSL:
      #
      # * If an engine is specified, an engine version
      #   must also be specified
      # * If an engine version is specified, an engine
      #   must also be specified
      # * If the engine is "ruby", the engine version
      #   must not be specified, or the engine version
      #   specified must match the version.

      @versions = Array(versions).map do |v|
        op, v = Gem::Requirement.parse(v)
        op == "=" ? v.to_s : "#{op} #{v}"
      end

      @gem_version        = Gem::Requirement.create(@versions.first).requirements.first.last
      @input_engine       = engine && engine.to_s
      @engine             = engine && engine.to_s || "ruby"
      @engine_versions    = (engine_version && Array(engine_version)) || @versions
      @engine_gem_version = Gem::Requirement.create(@engine_versions.first).requirements.first.last
      @patchlevel         = patchlevel
    end

    def to_s(versions = self.versions)
      output = String.new("ruby #{versions_string(versions)}")
      output << "p#{patchlevel}" if patchlevel
      output << " (#{engine} #{versions_string(engine_versions)})" unless engine == "ruby"

      output
    end

    # @private
    PATTERN = /
      ruby\s
      ([\d.]+) # ruby version
      (?:p(-?\d+))? # optional patchlevel
      (?:\s\((\S+)\s(.+)\))? # optional engine info
    /xo.freeze

    # Returns a RubyVersion from the given string.
    # @param [String] the version string to match.
    # @return [RubyVersion,Nil] The version if the string is a valid RubyVersion
    #         description, and nil otherwise.
    def self.from_string(string)
      new($1, $2, $3, $4) if string =~ PATTERN
    end

    def single_version_string
      to_s(gem_version)
    end

    def ==(other)
      versions == other.versions &&
        engine == other.engine &&
        engine_versions == other.engine_versions &&
        patchlevel == other.patchlevel
    end

    def host
      @host ||= [
        RbConfig::CONFIG["host_cpu"],
        RbConfig::CONFIG["host_vendor"],
        RbConfig::CONFIG["host_os"],
      ].join("-")
    end

    # Returns a tuple of these things:
    #   [diff, this, other]
    #   The priority of attributes are
    #   1. engine
    #   2. ruby_version
    #   3. engine_version
    def diff(other)
      raise ArgumentError, "Can only diff with a RubyVersion, not a #{other.class}" unless other.is_a?(RubyVersion)
      if engine != other.engine && @input_engine
        [:engine, engine, other.engine]
      elsif versions.empty? || !matches?(versions, other.gem_version)
        [:version, versions_string(versions), versions_string(other.versions)]
      elsif @input_engine && !matches?(engine_versions, other.engine_gem_version)
        [:engine_version, versions_string(engine_versions), versions_string(other.engine_versions)]
      elsif patchlevel && (!patchlevel.is_a?(String) || !other.patchlevel.is_a?(String) || !matches?(patchlevel, other.patchlevel))
        [:patchlevel, patchlevel, other.patchlevel]
      end
    end

    def versions_string(versions)
      Array(versions).join(", ")
    end

    def self.system
      ruby_engine = RUBY_ENGINE.dup
      ruby_version = ENV.fetch("BUNDLER_SPEC_RUBY_VERSION") { RUBY_VERSION }.dup
      ruby_engine_version = RUBY_ENGINE_VERSION.dup
      patchlevel = RUBY_PATCHLEVEL.to_s

      @ruby_version ||= RubyVersion.new(ruby_version, patchlevel, ruby_engine, ruby_engine_version)
    end

    def to_gem_version_with_patchlevel
      @gem_version_with_patch ||= begin
        Gem::Version.create("#{@gem_version}.#{@patchlevel}")
      rescue ArgumentError
        @gem_version
      end
    end

    def exact?
      return @exact if defined?(@exact)
      @exact = versions.all? {|v| Gem::Requirement.create(v).exact? }
    end

    private

    def matches?(requirements, version)
      # Handles RUBY_PATCHLEVEL of -1 for instances like ruby-head
      return requirements == version if requirements.to_s == "-1" || version.to_s == "-1"

      Array(requirements).all? do |requirement|
        Gem::Requirement.create(requirement).satisfied_by?(Gem::Version.create(version))
      end
    end
  end
end
# frozen_string_literal: true

require_relative "rubygems_integration"
require_relative "source/git/git_proxy"

module Bundler
  class Env
    def self.write(io)
      io.write report
    end

    def self.report(options = {})
      print_gemfile = options.delete(:print_gemfile) { true }
      print_gemspecs = options.delete(:print_gemspecs) { true }

      out = String.new
      append_formatted_table("Environment", environment, out)
      append_formatted_table("Bundler Build Metadata", BuildMetadata.to_h, out)

      unless Bundler.settings.all.empty?
        out << "\n## Bundler settings\n\n```\n"
        Bundler.settings.all.each do |setting|
          out << setting << "\n"
          Bundler.settings.pretty_values_for(setting).each do |line|
            out << "  " << line << "\n"
          end
        end
        out << "```\n"
      end

      return out unless SharedHelpers.in_bundle?

      if print_gemfile
        gemfiles = [Bundler.default_gemfile]
        begin
          gemfiles = Bundler.definition.gemfiles
        rescue GemfileNotFound
          nil
        end

        out << "\n## Gemfile\n"
        gemfiles.each do |gemfile|
          out << "\n### #{Pathname.new(gemfile).relative_path_from(SharedHelpers.pwd)}\n\n"
          out << "```ruby\n" << read_file(gemfile).chomp << "\n```\n"
        end

        out << "\n### #{Bundler.default_lockfile.relative_path_from(SharedHelpers.pwd)}\n\n"
        out << "```\n" << read_file(Bundler.default_lockfile).chomp << "\n```\n"
      end

      if print_gemspecs
        dsl = Dsl.new.tap {|d| d.eval_gemfile(Bundler.default_gemfile) }
        out << "\n## Gemspecs\n" unless dsl.gemspecs.empty?
        dsl.gemspecs.each do |gs|
          out << "\n### #{File.basename(gs.loaded_from)}"
          out << "\n\n```ruby\n" << read_file(gs.loaded_from).chomp << "\n```\n"
        end
      end

      out
    end

    def self.read_file(filename)
      Bundler.read_file(filename.to_s).strip
    rescue Errno::ENOENT
      "<No #{filename} found>"
    rescue RuntimeError => e
      "#{e.class}: #{e.message}"
    end

    def self.ruby_version
      str = String.new(RUBY_VERSION)
      str << "p#{RUBY_PATCHLEVEL}" if defined? RUBY_PATCHLEVEL
      str << " (#{RUBY_RELEASE_DATE} revision #{RUBY_REVISION}) [#{RUBY_PLATFORM}]"
    end

    def self.git_version
      Bundler::Source::Git::GitProxy.new(nil, nil, nil).full_version
    rescue Bundler::Source::Git::GitNotInstalledError
      "not installed"
    end

    def self.version_of(script)
      return "not installed" unless Bundler.which(script)
      `#{script} --version`.chomp
    end

    def self.chruby_version
      return "not installed" unless Bundler.which("chruby-exec")
      `chruby-exec -- chruby --version`.
        sub(/.*^chruby: (#{Gem::Version::VERSION_PATTERN}).*/m, '\1')
    end

    def self.environment
      out = []

      out << ["Bundler", Bundler::VERSION]
      out << ["  Platforms", Gem.platforms.join(", ")]
      out << ["Ruby", ruby_version]
      out << ["  Full Path", Gem.ruby]
      out << ["  Config Dir", Pathname.new(Gem::ConfigFile::SYSTEM_WIDE_CONFIG_FILE).dirname]
      out << ["RubyGems", Gem::VERSION]
      out << ["  Gem Home", Gem.dir]
      out << ["  Gem Path", Gem.path.join(File::PATH_SEPARATOR)]
      out << ["  User Home", Gem.user_home]
      out << ["  User Path", Gem.user_dir]
      out << ["  Bin Dir", Gem.bindir]
      if defined?(OpenSSL::SSL)
        out << ["OpenSSL"]
        out << ["  Compiled", OpenSSL::OPENSSL_VERSION] if defined?(OpenSSL::OPENSSL_VERSION)
        out << ["  Loaded", OpenSSL::OPENSSL_LIBRARY_VERSION] if defined?(OpenSSL::OPENSSL_LIBRARY_VERSION)
        out << ["  Cert File", OpenSSL::X509::DEFAULT_CERT_FILE] if defined?(OpenSSL::X509::DEFAULT_CERT_FILE)
        out << ["  Cert Dir", OpenSSL::X509::DEFAULT_CERT_DIR] if defined?(OpenSSL::X509::DEFAULT_CERT_DIR)
      end
      out << ["Tools"]
      out << ["  Git", git_version]
      out << ["  RVM", ENV.fetch("rvm_version") { version_of("rvm") }]
      out << ["  rbenv", version_of("rbenv")]
      out << ["  chruby", chruby_version]

      %w[rubygems-bundler open_gem].each do |name|
        specs = Bundler.rubygems.find_name(name)
        out << ["  #{name}", "(#{specs.map(&:version).join(",")})"] unless specs.empty?
      end
      if (exe = caller.last.split(":").first) && exe =~ %r{(exe|bin)/bundler?\z}
        shebang = File.read(exe).lines.first
        shebang.sub!(/^#!\s*/, "")
        unless shebang.start_with?(Gem.ruby, "/usr/bin/env ruby")
          out << ["Gem.ruby", Gem.ruby]
          out << ["bundle #!", shebang]
        end
      end

      out
    end

    def self.append_formatted_table(title, pairs, out)
      return if pairs.empty?
      out << "\n" unless out.empty?
      out << "## #{title}\n\n```\n"
      ljust = pairs.map {|k, _v| k.to_s.length }.max
      pairs.each do |k, v|
        out << "#{k.to_s.ljust(ljust)}  #{v}\n"
      end
      out << "```\n"
    end

    private_class_method :read_file, :ruby_version, :git_version, :append_formatted_table, :version_of, :chruby_version
  end
end
# frozen_string_literal: true

module Bundler
  class Runtime
    include SharedHelpers

    def initialize(root, definition)
      @root = root
      @definition = definition
    end

    def setup(*groups)
      @definition.ensure_equivalent_gemfile_and_lockfile if Bundler.frozen_bundle?

      # Has to happen first
      clean_load_path

      specs = @definition.specs_for(groups)

      SharedHelpers.set_bundle_environment
      Bundler.rubygems.replace_entrypoints(specs)

      # Activate the specs
      load_paths = specs.map do |spec|
        check_for_activated_spec!(spec)

        Bundler.rubygems.mark_loaded(spec)
        spec.load_paths.reject {|path| $LOAD_PATH.include?(path) }
      end.reverse.flatten

      Bundler.rubygems.add_to_load_path(load_paths)

      setup_manpath

      lock(:preserve_unknown_sections => true)

      self
    end

    def require(*groups)
      groups.map!(&:to_sym)
      groups = [:default] if groups.empty?

      @definition.dependencies.each do |dep|
        # Skip the dependency if it is not in any of the requested groups, or
        # not for the current platform, or doesn't match the gem constraints.
        next unless (dep.groups & groups).any? && dep.should_include?

        required_file = nil

        begin
          # Loop through all the specified autorequires for the
          # dependency. If there are none, use the dependency's name
          # as the autorequire.
          Array(dep.autorequire || dep.name).each do |file|
            # Allow `require: true` as an alias for `require: <name>`
            file = dep.name if file == true
            required_file = file
            begin
              Kernel.require file
            rescue RuntimeError => e
              raise e if e.is_a?(LoadError) # we handle this a little later
              raise Bundler::GemRequireError.new e,
                "There was an error while trying to load the gem '#{file}'."
            end
          end
        rescue LoadError => e
          raise if dep.autorequire || e.path != required_file

          if dep.autorequire.nil? && dep.name.include?("-")
            begin
              namespaced_file = dep.name.tr("-", "/")
              Kernel.require namespaced_file
            rescue LoadError => e
              raise if e.path != namespaced_file
            end
          end
        end
      end
    end

    def self.definition_method(meth)
      define_method(meth) do
        raise ArgumentError, "no definition when calling Runtime##{meth}" unless @definition
        @definition.send(meth)
      end
    end
    private_class_method :definition_method

    definition_method :requested_specs
    definition_method :specs
    definition_method :dependencies
    definition_method :current_dependencies
    definition_method :requires

    def lock(opts = {})
      return if @definition.nothing_changed? && !@definition.unlocking?
      @definition.lock(Bundler.default_lockfile, opts[:preserve_unknown_sections])
    end

    alias_method :gems, :specs

    def cache(custom_path = nil, local = false)
      cache_path = Bundler.app_cache(custom_path)
      SharedHelpers.filesystem_access(cache_path) do |p|
        FileUtils.mkdir_p(p)
      end unless File.exist?(cache_path)

      Bundler.ui.info "Updating files in #{Bundler.settings.app_cache_path}"

      specs_to_cache = if Bundler.settings[:cache_all_platforms]
        @definition.resolve.materialized_for_all_platforms
      else
        begin
          specs
        rescue GemNotFound
          if local
            Bundler.ui.warn "Some gems seem to be missing from your #{Bundler.settings.app_cache_path} directory."
          end

          raise
        end
      end

      specs_to_cache.each do |spec|
        next if spec.name == "bundler"
        next if spec.source.is_a?(Source::Gemspec)
        spec.source.send(:fetch_gem, spec) if Bundler.settings[:cache_all_platforms] && spec.source.respond_to?(:fetch_gem, true)
        spec.source.cache(spec, custom_path) if spec.source.respond_to?(:cache)
      end

      Dir[cache_path.join("*/.git")].each do |git_dir|
        FileUtils.rm_rf(git_dir)
        FileUtils.touch(File.expand_path("../.bundlecache", git_dir))
      end

      prune_cache(cache_path) unless Bundler.settings[:no_prune]
    end

    def prune_cache(cache_path)
      SharedHelpers.filesystem_access(cache_path) do |p|
        FileUtils.mkdir_p(p)
      end unless File.exist?(cache_path)
      resolve = @definition.resolve
      prune_gem_cache(resolve, cache_path)
      prune_git_and_path_cache(resolve, cache_path)
    end

    def clean(dry_run = false)
      gem_bins             = Dir["#{Gem.dir}/bin/*"]
      git_dirs             = Dir["#{Gem.dir}/bundler/gems/*"]
      git_cache_dirs       = Dir["#{Gem.dir}/cache/bundler/git/*"]
      gem_dirs             = Dir["#{Gem.dir}/gems/*"]
      gem_files            = Dir["#{Gem.dir}/cache/*.gem"]
      gemspec_files        = Dir["#{Gem.dir}/specifications/*.gemspec"]
      extension_dirs       = Dir["#{Gem.dir}/extensions/*/*/*"] + Dir["#{Gem.dir}/bundler/gems/extensions/*/*/*"]
      spec_gem_paths       = []
      # need to keep git sources around
      spec_git_paths       = @definition.spec_git_paths
      spec_git_cache_dirs  = []
      spec_gem_executables = []
      spec_cache_paths     = []
      spec_gemspec_paths   = []
      spec_extension_paths = []
      Bundler.rubygems.add_default_gems_to(specs).values.each do |spec|
        spec_gem_paths << spec.full_gem_path
        # need to check here in case gems are nested like for the rails git repo
        md = %r{(.+bundler/gems/.+-[a-f0-9]{7,12})}.match(spec.full_gem_path)
        spec_git_paths << md[1] if md
        spec_gem_executables << spec.executables.collect do |executable|
          e = "#{Bundler.rubygems.gem_bindir}/#{executable}"
          [e, "#{e}.bat"]
        end
        spec_cache_paths << spec.cache_file
        spec_gemspec_paths << spec.spec_file
        spec_extension_paths << spec.extension_dir if spec.respond_to?(:extension_dir)
        spec_git_cache_dirs << spec.source.cache_path.to_s if spec.source.is_a?(Bundler::Source::Git)
      end
      spec_gem_paths.uniq!
      spec_gem_executables.flatten!

      stale_gem_bins       = gem_bins - spec_gem_executables
      stale_git_dirs       = git_dirs - spec_git_paths - ["#{Gem.dir}/bundler/gems/extensions"]
      stale_git_cache_dirs = git_cache_dirs - spec_git_cache_dirs
      stale_gem_dirs       = gem_dirs - spec_gem_paths
      stale_gem_files      = gem_files - spec_cache_paths
      stale_gemspec_files  = gemspec_files - spec_gemspec_paths
      stale_extension_dirs = extension_dirs - spec_extension_paths

      removed_stale_gem_dirs = stale_gem_dirs.collect {|dir| remove_dir(dir, dry_run) }
      removed_stale_git_dirs = stale_git_dirs.collect {|dir| remove_dir(dir, dry_run) }
      output = removed_stale_gem_dirs + removed_stale_git_dirs

      unless dry_run
        stale_files = stale_gem_bins + stale_gem_files + stale_gemspec_files
        stale_files.each do |file|
          SharedHelpers.filesystem_access(File.dirname(file)) do |_p|
            FileUtils.rm(file) if File.exist?(file)
          end
        end

        stale_dirs = stale_git_cache_dirs + stale_extension_dirs
        stale_dirs.each do |stale_dir|
          SharedHelpers.filesystem_access(stale_dir) do |dir|
            FileUtils.rm_rf(dir) if File.exist?(dir)
          end
        end
      end

      output
    end

    private

    def prune_gem_cache(resolve, cache_path)
      cached = Dir["#{cache_path}/*.gem"]

      cached = cached.delete_if do |path|
        spec = Bundler.rubygems.spec_from_gem path

        resolve.any? do |s|
          s.name == spec.name && s.version == spec.version && !s.source.is_a?(Bundler::Source::Git)
        end
      end

      if cached.any?
        Bundler.ui.info "Removing outdated .gem files from #{Bundler.settings.app_cache_path}"

        cached.each do |path|
          Bundler.ui.info "  * #{File.basename(path)}"
          File.delete(path)
        end
      end
    end

    def prune_git_and_path_cache(resolve, cache_path)
      cached = Dir["#{cache_path}/*/.bundlecache"]

      cached = cached.delete_if do |path|
        name = File.basename(File.dirname(path))

        resolve.any? do |s|
          source = s.source
          source.respond_to?(:app_cache_dirname) && source.app_cache_dirname == name
        end
      end

      if cached.any?
        Bundler.ui.info "Removing outdated git and path gems from #{Bundler.settings.app_cache_path}"

        cached.each do |path|
          path = File.dirname(path)
          Bundler.ui.info "  * #{File.basename(path)}"
          FileUtils.rm_rf(path)
        end
      end
    end

    def setup_manpath
      # Add man/ subdirectories from activated bundles to MANPATH for man(1)
      manuals = $LOAD_PATH.map do |path|
        man_subdir = path.sub(/lib$/, "man")
        man_subdir unless Dir[man_subdir + "/man?/"].empty?
      end.compact

      return if manuals.empty?
      Bundler::SharedHelpers.set_env "MANPATH", manuals.concat(
        ENV["MANPATH"] ? ENV["MANPATH"].to_s.split(File::PATH_SEPARATOR) : [""]
      ).uniq.join(File::PATH_SEPARATOR)
    end

    def remove_dir(dir, dry_run)
      full_name = Pathname.new(dir).basename.to_s

      parts    = full_name.split("-")
      name     = parts[0..-2].join("-")
      version  = parts.last
      output   = "#{name} (#{version})"

      if dry_run
        Bundler.ui.info "Would have removed #{output}"
      else
        Bundler.ui.info "Removing #{output}"
        FileUtils.rm_rf(dir)
      end

      output
    end

    def check_for_activated_spec!(spec)
      return unless activated_spec = Bundler.rubygems.loaded_specs(spec.name)
      return if activated_spec.version == spec.version

      suggestion = if activated_spec.default_gem?
        "Since #{spec.name} is a default gem, you can either remove your dependency on it" \
        " or try updating to a newer version of bundler that supports #{spec.name} as a default gem."
      else
        "Prepending `bundle exec` to your command may solve this."
      end

      e = Gem::LoadError.new "You have already activated #{activated_spec.name} #{activated_spec.version}, " \
                             "but your Gemfile requires #{spec.name} #{spec.version}. #{suggestion}"
      e.name = spec.name
      if e.respond_to?(:requirement=)
        e.requirement = Gem::Requirement.new(spec.version.to_s)
      else
        e.version_requirement = Gem::Requirement.new(spec.version.to_s)
      end
      raise e
    end
  end
end
# frozen_string_literal: true

require_relative "vendored_persistent"
require "cgi"
require "securerandom"
require "zlib"
require "rubygems/request"

module Bundler
  # Handles all the fetching with the rubygems server
  class Fetcher
    autoload :CompactIndex, File.expand_path("fetcher/compact_index", __dir__)
    autoload :Downloader, File.expand_path("fetcher/downloader", __dir__)
    autoload :Dependency, File.expand_path("fetcher/dependency", __dir__)
    autoload :Index, File.expand_path("fetcher/index", __dir__)

    # This error is raised when it looks like the network is down
    class NetworkDownError < HTTPError; end
    # This error is raised if we should rate limit our requests to the API
    class TooManyRequestsError < HTTPError; end
    # This error is raised if the API returns a 413 (only printed in verbose)
    class FallbackError < HTTPError; end
    # This is the error raised if OpenSSL fails the cert verification
    class CertificateFailureError < HTTPError
      def initialize(remote_uri)
        remote_uri = filter_uri(remote_uri)
        super "Could not verify the SSL certificate for #{remote_uri}.\nThere" \
          " is a chance you are experiencing a man-in-the-middle attack, but" \
          " most likely your system doesn't have the CA certificates needed" \
          " for verification. For information about OpenSSL certificates, see" \
          " https://railsapps.github.io/openssl-certificate-verify-failed.html." \
          " To connect without using SSL, edit your Gemfile" \
          " sources and change 'https' to 'http'."
      end
    end
    # This is the error raised when a source is HTTPS and OpenSSL didn't load
    class SSLError < HTTPError
      def initialize(msg = nil)
        super msg || "Could not load OpenSSL.\n" \
            "You must recompile Ruby with OpenSSL support or change the sources in your " \
            "Gemfile from 'https' to 'http'. Instructions for compiling with OpenSSL " \
            "using RVM are available at rvm.io/packages/openssl."
      end
    end
    # This error is raised if HTTP authentication is required, but not provided.
    class AuthenticationRequiredError < HTTPError
      def initialize(remote_uri)
        remote_uri = filter_uri(remote_uri)
        super "Authentication is required for #{remote_uri}.\n" \
          "Please supply credentials for this source. You can do this by running:\n" \
          "`bundle config set --global #{remote_uri} username:password`\n" \
          "or by storing the credentials in the `#{Settings.key_for(remote_uri)}` environment variable"
      end
    end
    # This error is raised if HTTP authentication is provided, but incorrect.
    class BadAuthenticationError < HTTPError
      def initialize(remote_uri)
        remote_uri = filter_uri(remote_uri)
        super "Bad username or password for #{remote_uri}.\n" \
          "Please double-check your credentials and correct them."
      end
    end

    # Exceptions classes that should bypass retry attempts. If your password didn't work the
    # first time, it's not going to the third time.
    NET_ERRORS = [:HTTPBadGateway, :HTTPBadRequest, :HTTPFailedDependency,
                  :HTTPForbidden, :HTTPInsufficientStorage, :HTTPMethodNotAllowed,
                  :HTTPMovedPermanently, :HTTPNoContent, :HTTPNotFound,
                  :HTTPNotImplemented, :HTTPPreconditionFailed, :HTTPRequestEntityTooLarge,
                  :HTTPRequestURITooLong, :HTTPUnauthorized, :HTTPUnprocessableEntity,
                  :HTTPUnsupportedMediaType, :HTTPVersionNotSupported].freeze
    FAIL_ERRORS = begin
      fail_errors = [AuthenticationRequiredError, BadAuthenticationError, FallbackError]
      fail_errors << Gem::Requirement::BadRequirementError if defined?(Gem::Requirement::BadRequirementError)
      fail_errors.concat(NET_ERRORS.map {|e| SharedHelpers.const_get_safely(e, Net) }.compact)
    end.freeze

    class << self
      attr_accessor :disable_endpoint, :api_timeout, :redirect_limit, :max_retries
    end

    self.redirect_limit = Bundler.settings[:redirect] # How many redirects to allow in one request
    self.api_timeout    = Bundler.settings[:timeout] # How long to wait for each API call
    self.max_retries    = Bundler.settings[:retry] # How many retries for the API call

    def initialize(remote)
      @remote = remote

      Socket.do_not_reverse_lookup = true
      connection # create persistent connection
    end

    def uri
      @remote.anonymized_uri
    end

    # fetch a gem specification
    def fetch_spec(spec)
      spec -= [nil, "ruby", ""]
      spec_file_name = "#{spec.join "-"}.gemspec"

      uri = Bundler::URI.parse("#{remote_uri}#{Gem::MARSHAL_SPEC_DIR}#{spec_file_name}.rz")
      if uri.scheme == "file"
        path = Bundler.rubygems.correct_for_windows_path(uri.path)
        Bundler.load_marshal Bundler.rubygems.inflate(Gem.read_binary(path))
      elsif cached_spec_path = gemspec_cached_path(spec_file_name)
        Bundler.load_gemspec(cached_spec_path)
      else
        Bundler.load_marshal Bundler.rubygems.inflate(downloader.fetch(uri).body)
      end
    rescue MarshalError
      raise HTTPError, "Gemspec #{spec} contained invalid data.\n" \
        "Your network or your gem server is probably having issues right now."
    end

    # return the specs in the bundler format as an index with retries
    def specs_with_retry(gem_names, source)
      Bundler::Retry.new("fetcher", FAIL_ERRORS).attempts do
        specs(gem_names, source)
      end
    end

    # return the specs in the bundler format as an index
    def specs(gem_names, source)
      old = Bundler.rubygems.sources
      index = Bundler::Index.new

      if Bundler::Fetcher.disable_endpoint
        @use_api = false
        specs = fetchers.last.specs(gem_names)
      else
        specs = []
        fetchers.shift until fetchers.first.available? || fetchers.empty?
        fetchers.dup.each do |f|
          break unless f.api_fetcher? && !gem_names || !specs = f.specs(gem_names)
          fetchers.delete(f)
        end
        @use_api = false if fetchers.none?(&:api_fetcher?)
      end

      specs.each do |name, version, platform, dependencies, metadata|
        spec = if dependencies
          EndpointSpecification.new(name, version, platform, dependencies, metadata)
        else
          RemoteSpecification.new(name, version, platform, self)
        end
        spec.source = source
        spec.remote = @remote
        index << spec
      end

      index
    rescue CertificateFailureError
      Bundler.ui.info "" if gem_names && use_api # newline after dots
      raise
    ensure
      Bundler.rubygems.sources = old
    end

    def use_api
      return @use_api if defined?(@use_api)

      fetchers.shift until fetchers.first.available?

      @use_api = if remote_uri.scheme == "file" || Bundler::Fetcher.disable_endpoint
        false
      else
        fetchers.first.api_fetcher?
      end
    end

    def user_agent
      @user_agent ||= begin
        ruby = Bundler::RubyVersion.system

        agent = String.new("bundler/#{Bundler::VERSION}")
        agent << " rubygems/#{Gem::VERSION}"
        agent << " ruby/#{ruby.versions_string(ruby.versions)}"
        agent << " (#{ruby.host})"
        agent << " command/#{ARGV.first}"

        if ruby.engine != "ruby"
          # engine_version raises on unknown engines
          engine_version = begin
                             ruby.engine_versions
                           rescue RuntimeError
                             "???"
                           end
          agent << " #{ruby.engine}/#{ruby.versions_string(engine_version)}"
        end

        agent << " options/#{Bundler.settings.all.join(",")}"

        agent << " ci/#{cis.join(",")}" if cis.any?

        # add a random ID so we can consolidate runs server-side
        agent << " " << SecureRandom.hex(8)

        # add any user agent strings set in the config
        extra_ua = Bundler.settings[:user_agent]
        agent << " " << extra_ua if extra_ua

        agent
      end
    end

    def fetchers
      @fetchers ||= FETCHERS.map {|f| f.new(downloader, @remote, uri) }
    end

    def http_proxy
      return unless uri = connection.proxy_uri
      uri.to_s
    end

    def inspect
      "#<#{self.class}:0x#{object_id} uri=#{uri}>"
    end

    private

    FETCHERS = [CompactIndex, Dependency, Index].freeze

    def cis
      env_cis = {
        "TRAVIS" => "travis",
        "CIRCLECI" => "circle",
        "SEMAPHORE" => "semaphore",
        "JENKINS_URL" => "jenkins",
        "BUILDBOX" => "buildbox",
        "GO_SERVER_URL" => "go",
        "SNAP_CI" => "snap",
        "GITLAB_CI" => "gitlab",
        "CI_NAME" => ENV["CI_NAME"],
        "CI" => "ci",
      }
      env_cis.find_all {|env, _| ENV[env] }.map {|_, ci| ci }
    end

    def connection
      @connection ||= begin
        needs_ssl = remote_uri.scheme == "https" ||
          Bundler.settings[:ssl_verify_mode] ||
          Bundler.settings[:ssl_client_cert]
        raise SSLError if needs_ssl && !defined?(OpenSSL::SSL)

        con = PersistentHTTP.new :name => "bundler", :proxy => :ENV
        if gem_proxy = Bundler.rubygems.configuration[:http_proxy]
          con.proxy = Bundler::URI.parse(gem_proxy) if gem_proxy != :no_proxy
        end

        if remote_uri.scheme == "https"
          con.verify_mode = (Bundler.settings[:ssl_verify_mode] ||
            OpenSSL::SSL::VERIFY_PEER)
          con.cert_store = bundler_cert_store
        end

        ssl_client_cert = Bundler.settings[:ssl_client_cert] ||
          (Bundler.rubygems.configuration.ssl_client_cert if
            Bundler.rubygems.configuration.respond_to?(:ssl_client_cert))
        if ssl_client_cert
          pem = File.read(ssl_client_cert)
          con.cert = OpenSSL::X509::Certificate.new(pem)
          con.key  = OpenSSL::PKey::RSA.new(pem)
        end

        con.read_timeout = Fetcher.api_timeout
        con.open_timeout = Fetcher.api_timeout
        con.override_headers["User-Agent"] = user_agent
        con.override_headers["X-Gemfile-Source"] = @remote.original_uri.to_s if @remote.original_uri
        con
      end
    end

    # cached gem specification path, if one exists
    def gemspec_cached_path(spec_file_name)
      paths = Bundler.rubygems.spec_cache_dirs.map {|dir| File.join(dir, spec_file_name) }
      paths = paths.select {|path| File.file? path }
      paths.first
    end

    HTTP_ERRORS = [
      Timeout::Error, EOFError, SocketError, Errno::ENETDOWN, Errno::ENETUNREACH,
      Errno::EINVAL, Errno::ECONNRESET, Errno::ETIMEDOUT, Errno::EAGAIN,
      Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError,
      PersistentHTTP::Error, Zlib::BufError, Errno::EHOSTUNREACH
    ].freeze

    def bundler_cert_store
      store = OpenSSL::X509::Store.new
      ssl_ca_cert = Bundler.settings[:ssl_ca_cert] ||
        (Bundler.rubygems.configuration.ssl_ca_cert if
          Bundler.rubygems.configuration.respond_to?(:ssl_ca_cert))
      if ssl_ca_cert
        if File.directory? ssl_ca_cert
          store.add_path ssl_ca_cert
        else
          store.add_file ssl_ca_cert
        end
      else
        store.set_default_paths
        Gem::Request.get_cert_files.each {|c| store.add_file c }
      end
      store
    end

    private

    def remote_uri
      @remote.uri
    end

    def downloader
      @downloader ||= Downloader.new(connection, self.class.redirect_limit)
    end
  end
end
# frozen_string_literal: true

module Bundler
  class Gemdeps
    def initialize(runtime)
      @runtime = runtime
    end

    def requested_specs
      @runtime.requested_specs
    end

    def specs
      @runtime.specs
    end

    def dependencies
      @runtime.dependencies
    end

    def current_dependencies
      @runtime.current_dependencies
    end

    def requires
      @runtime.requires
    end
  end
end
# frozen_string_literal: true

module Bundler
  # Represents a lazily loaded gem specification, where the full specification
  # is on the source server in rubygems' "quick" index. The proxy object is to
  # be seeded with what we're given from the source's abbreviated index - the
  # full specification will only be fetched when necessary.
  class RemoteSpecification
    include MatchPlatform
    include Comparable

    attr_reader :name, :version, :platform
    attr_writer :dependencies
    attr_accessor :source, :remote

    def initialize(name, version, platform, spec_fetcher)
      @name         = name
      @version      = Gem::Version.create version
      @platform     = platform
      @spec_fetcher = spec_fetcher
      @dependencies = nil
    end

    # Needed before installs, since the arch matters then and quick
    # specs don't bother to include the arch in the platform string
    def fetch_platform
      @platform = _remote_specification.platform
    end

    def full_name
      if platform == Gem::Platform::RUBY || platform.nil?
        "#{@name}-#{@version}"
      else
        "#{@name}-#{@version}-#{platform}"
      end
    end

    # Compare this specification against another object. Using sort_obj
    # is compatible with Gem::Specification and other Bundler or RubyGems
    # objects. Otherwise, use the default Object comparison.
    def <=>(other)
      if other.respond_to?(:sort_obj)
        sort_obj <=> other.sort_obj
      else
        super
      end
    end

    # Because Rubyforge cannot be trusted to provide valid specifications
    # once the remote gem is downloaded, the backend specification will
    # be swapped out.
    def __swap__(spec)
      raise APIResponseInvalidDependenciesError unless spec.dependencies.all? {|d| d.is_a?(Gem::Dependency) }

      SharedHelpers.ensure_same_dependencies(self, dependencies, spec.dependencies)
      @_remote_specification = spec
    end

    # Create a delegate used for sorting. This strategy is copied from
    # RubyGems 2.23 and ensures that Bundler's specifications can be
    # compared and sorted with RubyGems' own specifications.
    #
    # @see #<=>
    # @see Gem::Specification#sort_obj
    #
    # @return [Array] an object you can use to compare and sort this
    #   specification against other specifications
    def sort_obj
      [@name, @version, @platform == Gem::Platform::RUBY ? -1 : 1]
    end

    def to_s
      "#<#{self.class} name=#{name} version=#{version} platform=#{platform}>"
    end

    def dependencies
      @dependencies ||= begin
        deps = method_missing(:dependencies)

        # allow us to handle when the specs dependencies are an array of array of string
        # in order to delay the crash to `#__swap__` where it results in a friendlier error
        # see https://github.com/rubygems/bundler/issues/5797
        deps = deps.map {|d| d.is_a?(Gem::Dependency) ? d : Gem::Dependency.new(*d) }

        deps
      end
    end

    def git_version
      return unless loaded_from && source.is_a?(Bundler::Source::Git)
      " #{source.revision[0..6]}"
    end

    private

    def to_ary
      nil
    end

    def _remote_specification
      @_remote_specification ||= @spec_fetcher.fetch_spec([@name, @version, @platform])
      @_remote_specification || raise(GemspecError, "Gemspec data for #{full_name} was" \
        " missing from the server! Try installing with `--full-index` as a workaround.")
    end

    def method_missing(method, *args, &blk)
      _remote_specification.send(method, *args, &blk)
    end

    def respond_to?(method, include_all = false)
      super || _remote_specification.respond_to?(method, include_all)
    end
    public :respond_to?
  end
end
# frozen_string_literal: true

module Bundler
  class Settings
    class Validator
      class Rule
        attr_reader :description

        def initialize(keys, description, &validate)
          @keys = keys
          @description = description
          @validate = validate
        end

        def validate!(key, value, settings)
          instance_exec(key, value, settings, &@validate)
        end

        def fail!(key, value, *reasons)
          reasons.unshift @description
          raise InvalidOption, "Setting `#{key}` to #{value.inspect} failed:\n#{reasons.map {|r| " - #{r}" }.join("\n")}"
        end

        def set(settings, key, value, *reasons)
          hash_key = k(key)
          return if settings[hash_key] == value
          reasons.unshift @description
          Bundler.ui.info "Setting `#{key}` to #{value.inspect}, since #{reasons.join(", ")}"
          if value.nil?
            settings.delete(hash_key)
          else
            settings[hash_key] = value
          end
        end

        def k(key)
          Bundler.settings.key_for(key)
        end
      end

      def self.rules
        @rules ||= Hash.new {|h, k| h[k] = [] }
      end
      private_class_method :rules

      def self.rule(keys, description, &blk)
        rule = Rule.new(keys, description, &blk)
        keys.each {|k| rules[k] << rule }
      end
      private_class_method :rule

      def self.validate!(key, value, settings)
        rules_to_validate = rules[key]
        rules_to_validate.each {|rule| rule.validate!(key, value, settings) }
      end

      rule %w[path path.system], "path and path.system are mutually exclusive" do |key, value, settings|
        if key == "path" && value
          set(settings, "path.system", nil)
        elsif key == "path.system" && value
          set(settings, :path, nil)
        end
      end

      rule %w[with without], "a group cannot be in both `with` & `without` simultaneously" do |key, value, settings|
        with = settings.fetch(k(:with), "").split(":").map(&:to_sym)
        without = settings.fetch(k(:without), "").split(":").map(&:to_sym)

        other_key = key == "with" ? :without : :with
        other_setting = key == "with" ? without : with

        conflicting = with & without
        if conflicting.any?
          fail!(key, value, "`#{other_key}` is current set to #{other_setting.inspect}", "the `#{conflicting.join("`, `")}` groups conflict")
        end
      end

      rule %w[path], "relative paths are expanded relative to the current working directory" do |key, value, settings|
        next if value.nil?

        path = Pathname.new(value)
        next if !path.relative? || !Bundler.feature_flag.path_relative_to_cwd?

        path = path.expand_path

        root = begin
                 Bundler.root
               rescue GemfileNotFound
                 Pathname.pwd.expand_path
               end

        path = begin
                 path.relative_path_from(root)
               rescue ArgumentError
                 path
               end

        set(settings, key, path.to_s)
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class LockfileGenerator
    attr_reader :definition
    attr_reader :out

    # @private
    def initialize(definition)
      @definition = definition
      @out = String.new
    end

    def self.generate(definition)
      new(definition).generate!
    end

    def generate!
      add_sources
      add_platforms
      add_dependencies
      add_locked_ruby_version
      add_bundled_with

      out
    end

    private

    def add_sources
      definition.send(:sources).lock_sources.each_with_index do |source, idx|
        out << "\n" unless idx.zero?

        # Add the source header
        out << source.to_lock

        # Find all specs for this source
        specs = definition.resolve.select {|s| source.can_lock?(s) }
        add_specs(specs)
      end
    end

    def add_specs(specs)
      # This needs to be sorted by full name so that
      # gems with the same name, but different platform
      # are ordered consistently
      specs.sort_by(&:full_name).each do |spec|
        next if spec.name == "bundler".freeze
        out << spec.to_lock
      end
    end

    def add_platforms
      add_section("PLATFORMS", definition.platforms)
    end

    def add_dependencies
      out << "\nDEPENDENCIES\n"

      handled = []
      definition.dependencies.sort_by(&:to_s).each do |dep|
        next if handled.include?(dep.name)
        out << dep.to_lock
        handled << dep.name
      end
    end

    def add_locked_ruby_version
      return unless locked_ruby_version = definition.locked_ruby_version
      add_section("RUBY VERSION", locked_ruby_version.to_s)
    end

    def add_bundled_with
      add_section("BUNDLED WITH", definition.locked_bundler_version.to_s)
    end

    def add_section(name, value)
      out << "\n#{name}\n"
      case value
      when Array
        value.map(&:to_s).sort.each do |val|
          out << "  #{val}\n"
        end
      when Hash
        value.to_a.sort_by {|k, _| k.to_s }.each do |key, val|
          out << "  #{key}: #{val}\n"
        end
      when String
        out << "   #{value}\n"
      else
        raise ArgumentError, "#{value.inspect} can't be serialized in a lockfile"
      end
    end
  end
end
class Bundler::Persistent::Net::HTTP::Persistent::TimedStackMulti < Bundler::ConnectionPool::TimedStack # :nodoc:

  ##
  # Returns a new hash that has arrays for keys
  #
  # Using a class method to limit the bindings referenced by the hash's
  # default_proc

  def self.hash_of_arrays # :nodoc:
    Hash.new { |h,k| h[k] = [] }
  end

  def initialize(size = 0, &block)
    super

    @enqueued = 0
    @ques = self.class.hash_of_arrays
    @lru = {}
    @key = :"connection_args-#{object_id}"
  end

  def empty?
    (@created - @enqueued) >= @max
  end

  def length
    @max - @created + @enqueued
  end

  private

  def connection_stored? options = {} # :nodoc:
    !@ques[options[:connection_args]].empty?
  end

  def fetch_connection options = {} # :nodoc:
    connection_args = options[:connection_args]

    @enqueued -= 1
    lru_update connection_args
    @ques[connection_args].pop
  end

  def lru_update connection_args # :nodoc:
    @lru.delete connection_args
    @lru[connection_args] = true
  end

  def shutdown_connections # :nodoc:
    @ques.each_key do |key|
      super connection_args: key
    end
  end

  def store_connection obj, options = {} # :nodoc:
    @ques[options[:connection_args]].push obj
    @enqueued += 1
  end

  def try_create options = {} # :nodoc:
    connection_args = options[:connection_args]

    if @created >= @max && @enqueued >= 1
      oldest, = @lru.first
      @lru.delete oldest
      @ques[oldest].pop

      @created -= 1
    end

    if @created < @max
      @created += 1
      lru_update connection_args
      return @create_block.call(connection_args)
    end
  end

end

##
# A Net::HTTP connection wrapper that holds extra information for managing the
# connection's lifetime.

class Bundler::Persistent::Net::HTTP::Persistent::Connection # :nodoc:

  attr_accessor :http

  attr_accessor :last_use

  attr_accessor :requests

  attr_accessor :ssl_generation

  def initialize http_class, http_args, ssl_generation
    @http           = http_class.new(*http_args)
    @ssl_generation = ssl_generation

    reset
  end

  def finish
    @http.finish
  rescue IOError
  ensure
    reset
  end

  def reset
    @last_use = Bundler::Persistent::Net::HTTP::Persistent::EPOCH
    @requests = 0
  end

  def ressl ssl_generation
    @ssl_generation = ssl_generation

    finish
  end

end
class Bundler::Persistent::Net::HTTP::Persistent::Pool < Bundler::ConnectionPool # :nodoc:

  attr_reader :available # :nodoc:
  attr_reader :key # :nodoc:

  def initialize(options = {}, &block)
    super

    @available = Bundler::Persistent::Net::HTTP::Persistent::TimedStackMulti.new(@size, &block)
    @key = "current-#{@available.object_id}"
  end

  def checkin net_http_args
    stack = Thread.current[@key][net_http_args] ||= []

    raise Bundler::ConnectionPool::Error, 'no connections are checked out' if
      stack.empty?

    conn = stack.pop

    if stack.empty?
      @available.push conn, connection_args: net_http_args

      Thread.current[@key].delete(net_http_args)
      Thread.current[@key] = nil if Thread.current[@key].empty?
    end

    nil
  end

  def checkout net_http_args
    stacks = Thread.current[@key] ||= {}
    stack  = stacks[net_http_args] ||= []

    if stack.empty? then
      conn = @available.pop connection_args: net_http_args
    else
      conn = stack.last
    end

    stack.push conn

    conn
  end

  def shutdown
    Thread.current[@key] = nil
    super
  end
end

require_relative 'timed_stack_multi'

require 'net/http'
require_relative '../../../../uri/lib/uri'
require 'cgi' # for escaping
require_relative '../../../../connection_pool/lib/connection_pool'

autoload :OpenSSL, 'openssl'

##
# Persistent connections for Net::HTTP
#
# Bundler::Persistent::Net::HTTP::Persistent maintains persistent connections across all the
# servers you wish to talk to.  For each host:port you communicate with a
# single persistent connection is created.
#
# Connections will be shared across threads through a connection pool to
# increase reuse of connections.
#
# You can shut down any remaining HTTP connections when done by calling
# #shutdown.
#
# Example:
#
#   require 'bundler/vendor/net-http-persistent/lib/net/http/persistent'
#
#   uri = Bundler::URI 'http://example.com/awesome/web/service'
#
#   http = Bundler::Persistent::Net::HTTP::Persistent.new
#
#   # perform a GET
#   response = http.request uri
#
#   # or
#
#   get = Net::HTTP::Get.new uri.request_uri
#   response = http.request get
#
#   # create a POST
#   post_uri = uri + 'create'
#   post = Net::HTTP::Post.new post_uri.path
#   post.set_form_data 'some' => 'cool data'
#
#   # perform the POST, the Bundler::URI is always required
#   response http.request post_uri, post
#
# Note that for GET, HEAD and other requests that do not have a body you want
# to use Bundler::URI#request_uri not Bundler::URI#path.  The request_uri contains the query
# params which are sent in the body for other requests.
#
# == TLS/SSL
#
# TLS connections are automatically created depending upon the scheme of the
# Bundler::URI.  TLS connections are automatically verified against the default
# certificate store for your computer.  You can override this by changing
# verify_mode or by specifying an alternate cert_store.
#
# Here are the TLS settings, see the individual methods for documentation:
#
# #certificate        :: This client's certificate
# #ca_file            :: The certificate-authorities
# #ca_path            :: Directory with certificate-authorities
# #cert_store         :: An SSL certificate store
# #ciphers            :: List of SSl ciphers allowed
# #private_key        :: The client's SSL private key
# #reuse_ssl_sessions :: Reuse a previously opened SSL session for a new
#                        connection
# #ssl_timeout        :: Session lifetime
# #ssl_version        :: Which specific SSL version to use
# #verify_callback    :: For server certificate verification
# #verify_depth       :: Depth of certificate verification
# #verify_mode        :: How connections should be verified
#
# == Proxies
#
# A proxy can be set through #proxy= or at initialization time by providing a
# second argument to ::new.  The proxy may be the Bundler::URI of the proxy server or
# <code>:ENV</code> which will consult environment variables.
#
# See #proxy= and #proxy_from_env for details.
#
# == Headers
#
# Headers may be specified for use in every request.  #headers are appended to
# any headers on the request.  #override_headers replace existing headers on
# the request.
#
# The difference between the two can be seen in setting the User-Agent.  Using
# <code>http.headers['User-Agent'] = 'MyUserAgent'</code> will send "Ruby,
# MyUserAgent" while <code>http.override_headers['User-Agent'] =
# 'MyUserAgent'</code> will send "MyUserAgent".
#
# == Tuning
#
# === Segregation
#
# Each Bundler::Persistent::Net::HTTP::Persistent instance has its own pool of connections.  There
# is no sharing with other instances (as was true in earlier versions).
#
# === Idle Timeout
#
# If a connection hasn't been used for this number of seconds it will
# automatically be reset upon the next use to avoid attempting to send to a
# closed connection.  The default value is 5 seconds. nil means no timeout.
# Set through #idle_timeout.
#
# Reducing this value may help avoid the "too many connection resets" error
# when sending non-idempotent requests while increasing this value will cause
# fewer round-trips.
#
# === Read Timeout
#
# The amount of time allowed between reading two chunks from the socket.  Set
# through #read_timeout
#
# === Max Requests
#
# The number of requests that should be made before opening a new connection.
# Typically many keep-alive capable servers tune this to 100 or less, so the
# 101st request will fail with ECONNRESET. If unset (default), this value has
# no effect, if set, connections will be reset on the request after
# max_requests.
#
# === Open Timeout
#
# The amount of time to wait for a connection to be opened.  Set through
# #open_timeout.
#
# === Socket Options
#
# Socket options may be set on newly-created connections.  See #socket_options
# for details.
#
# === Connection Termination
#
# If you are done using the Bundler::Persistent::Net::HTTP::Persistent instance you may shut down
# all the connections in the current thread with #shutdown.  This is not
# recommended for normal use, it should only be used when it will be several
# minutes before you make another HTTP request.
#
# If you are using multiple threads, call #shutdown in each thread when the
# thread is done making requests.  If you don't call shutdown, that's OK.
# Ruby will automatically garbage collect and shutdown your HTTP connections
# when the thread terminates.

class Bundler::Persistent::Net::HTTP::Persistent

  ##
  # The beginning of Time

  EPOCH = Time.at 0 # :nodoc:

  ##
  # Is OpenSSL available?  This test works with autoload

  HAVE_OPENSSL = defined? OpenSSL::SSL # :nodoc:

  ##
  # The default connection pool size is 1/4 the allowed open files
  # (<code>ulimit -n</code>) or 256 if your OS does not support file handle
  # limits (typically windows).

  if Process.const_defined? :RLIMIT_NOFILE
    open_file_limits = Process.getrlimit(Process::RLIMIT_NOFILE)

    # Under JRuby on Windows Process responds to `getrlimit` but returns something that does not match docs
    if open_file_limits.respond_to?(:first)
      DEFAULT_POOL_SIZE = open_file_limits.first / 4
    else
      DEFAULT_POOL_SIZE = 256
    end
  else
    DEFAULT_POOL_SIZE = 256
  end

  ##
  # The version of Bundler::Persistent::Net::HTTP::Persistent you are using

  VERSION = '4.0.0'

  ##
  # Error class for errors raised by Bundler::Persistent::Net::HTTP::Persistent.  Various
  # SystemCallErrors are re-raised with a human-readable message under this
  # class.

  class Error < StandardError; end

  ##
  # Use this method to detect the idle timeout of the host at +uri+.  The
  # value returned can be used to configure #idle_timeout.  +max+ controls the
  # maximum idle timeout to detect.
  #
  # After
  #
  # Idle timeout detection is performed by creating a connection then
  # performing a HEAD request in a loop until the connection terminates
  # waiting one additional second per loop.
  #
  # NOTE:  This may not work on ruby > 1.9.

  def self.detect_idle_timeout uri, max = 10
    uri = Bundler::URI uri unless Bundler::URI::Generic === uri
    uri += '/'

    req = Net::HTTP::Head.new uri.request_uri

    http = new 'net-http-persistent detect_idle_timeout'

    http.connection_for uri do |connection|
      sleep_time = 0

      http = connection.http

      loop do
        response = http.request req

        $stderr.puts "HEAD #{uri} => #{response.code}" if $DEBUG

        unless Net::HTTPOK === response then
          raise Error, "bad response code #{response.code} detecting idle timeout"
        end

        break if sleep_time >= max

        sleep_time += 1

        $stderr.puts "sleeping #{sleep_time}" if $DEBUG
        sleep sleep_time
      end
    end
  rescue
    # ignore StandardErrors, we've probably found the idle timeout.
  ensure
    return sleep_time unless $!
  end

  ##
  # This client's OpenSSL::X509::Certificate

  attr_reader :certificate

  ##
  # For Net::HTTP parity

  alias cert certificate

  ##
  # An SSL certificate authority.  Setting this will set verify_mode to
  # VERIFY_PEER.

  attr_reader :ca_file

  ##
  # A directory of SSL certificates to be used as certificate authorities.
  # Setting this will set verify_mode to VERIFY_PEER.

  attr_reader :ca_path

  ##
  # An SSL certificate store.  Setting this will override the default
  # certificate store.  See verify_mode for more information.

  attr_reader :cert_store

  ##
  # The ciphers allowed for SSL connections

  attr_reader :ciphers

  ##
  # Sends debug_output to this IO via Net::HTTP#set_debug_output.
  #
  # Never use this method in production code, it causes a serious security
  # hole.

  attr_accessor :debug_output

  ##
  # Current connection generation

  attr_reader :generation # :nodoc:

  ##
  # Headers that are added to every request using Net::HTTP#add_field

  attr_reader :headers

  ##
  # Maps host:port to an HTTP version.  This allows us to enable version
  # specific features.

  attr_reader :http_versions

  ##
  # Maximum time an unused connection can remain idle before being
  # automatically closed.

  attr_accessor :idle_timeout

  ##
  # Maximum number of requests on a connection before it is considered expired
  # and automatically closed.

  attr_accessor :max_requests

  ##
  # Number of retries to perform if a request fails.
  #
  # See also #max_retries=, Net::HTTP#max_retries=.

  attr_reader :max_retries

  ##
  # The value sent in the Keep-Alive header.  Defaults to 30.  Not needed for
  # HTTP/1.1 servers.
  #
  # This may not work correctly for HTTP/1.0 servers
  #
  # This method may be removed in a future version as RFC 2616 does not
  # require this header.

  attr_accessor :keep_alive

  ##
  # The name for this collection of persistent connections.

  attr_reader :name

  ##
  # Seconds to wait until a connection is opened.  See Net::HTTP#open_timeout

  attr_accessor :open_timeout

  ##
  # Headers that are added to every request using Net::HTTP#[]=

  attr_reader :override_headers

  ##
  # This client's SSL private key

  attr_reader :private_key

  ##
  # For Net::HTTP parity

  alias key private_key

  ##
  # The URL through which requests will be proxied

  attr_reader :proxy_uri

  ##
  # List of host suffixes which will not be proxied

  attr_reader :no_proxy

  ##
  # Test-only accessor for the connection pool

  attr_reader :pool # :nodoc:

  ##
  # Seconds to wait until reading one block.  See Net::HTTP#read_timeout

  attr_accessor :read_timeout

  ##
  # Seconds to wait until writing one block.  See Net::HTTP#write_timeout

  attr_accessor :write_timeout

  ##
  # By default SSL sessions are reused to avoid extra SSL handshakes.  Set
  # this to false if you have problems communicating with an HTTPS server
  # like:
  #
  #   SSL_connect [...] read finished A: unexpected message (OpenSSL::SSL::SSLError)

  attr_accessor :reuse_ssl_sessions

  ##
  # An array of options for Socket#setsockopt.
  #
  # By default the TCP_NODELAY option is set on sockets.
  #
  # To set additional options append them to this array:
  #
  #   http.socket_options << [Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, 1]

  attr_reader :socket_options

  ##
  # Current SSL connection generation

  attr_reader :ssl_generation # :nodoc:

  ##
  # SSL session lifetime

  attr_reader :ssl_timeout

  ##
  # SSL version to use.
  #
  # By default, the version will be negotiated automatically between client
  # and server.  Ruby 1.9 and newer only. Deprecated since Ruby 2.5.

  attr_reader :ssl_version

  ##
  # Minimum SSL version to use, e.g. :TLS1_1
  #
  # By default, the version will be negotiated automatically between client
  # and server.  Ruby 2.5 and newer only.

  attr_reader :min_version

  ##
  # Maximum SSL version to use, e.g. :TLS1_2
  #
  # By default, the version will be negotiated automatically between client
  # and server.  Ruby 2.5 and newer only.

  attr_reader :max_version

  ##
  # Where this instance's last-use times live in the thread local variables

  attr_reader :timeout_key # :nodoc:

  ##
  # SSL verification callback.  Used when ca_file or ca_path is set.

  attr_reader :verify_callback

  ##
  # Sets the depth of SSL certificate verification

  attr_reader :verify_depth

  ##
  # HTTPS verify mode.  Defaults to OpenSSL::SSL::VERIFY_PEER which verifies
  # the server certificate.
  #
  # If no ca_file, ca_path or cert_store is set the default system certificate
  # store is used.
  #
  # You can use +verify_mode+ to override any default values.

  attr_reader :verify_mode

  ##
  # Creates a new Bundler::Persistent::Net::HTTP::Persistent.
  #
  # Set a +name+ for fun.  Your library name should be good enough, but this
  # otherwise has no purpose.
  #
  # +proxy+ may be set to a Bundler::URI::HTTP or :ENV to pick up proxy options from
  # the environment.  See proxy_from_env for details.
  #
  # In order to use a Bundler::URI for the proxy you may need to do some extra work
  # beyond Bundler::URI parsing if the proxy requires a password:
  #
  #   proxy = Bundler::URI 'http://proxy.example'
  #   proxy.user     = 'AzureDiamond'
  #   proxy.password = 'hunter2'
  #
  # Set +pool_size+ to limit the maximum number of connections allowed.
  # Defaults to 1/4 the number of allowed file handles or 256 if your OS does
  # not support a limit on allowed file handles.  You can have no more than
  # this many threads with active HTTP transactions.

  def initialize name: nil, proxy: nil, pool_size: DEFAULT_POOL_SIZE
    @name = name

    @debug_output     = nil
    @proxy_uri        = nil
    @no_proxy         = []
    @headers          = {}
    @override_headers = {}
    @http_versions    = {}
    @keep_alive       = 30
    @open_timeout     = nil
    @read_timeout     = nil
    @write_timeout    = nil
    @idle_timeout     = 5
    @max_requests     = nil
    @max_retries      = 1
    @socket_options   = []
    @ssl_generation   = 0 # incremented when SSL session variables change

    @socket_options << [Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1] if
      Socket.const_defined? :TCP_NODELAY

    @pool = Bundler::Persistent::Net::HTTP::Persistent::Pool.new size: pool_size do |http_args|
      Bundler::Persistent::Net::HTTP::Persistent::Connection.new Net::HTTP, http_args, @ssl_generation
    end

    @certificate        = nil
    @ca_file            = nil
    @ca_path            = nil
    @ciphers            = nil
    @private_key        = nil
    @ssl_timeout        = nil
    @ssl_version        = nil
    @min_version        = nil
    @max_version        = nil
    @verify_callback    = nil
    @verify_depth       = nil
    @verify_mode        = nil
    @cert_store         = nil

    @generation         = 0 # incremented when proxy Bundler::URI changes

    if HAVE_OPENSSL then
      @verify_mode        = OpenSSL::SSL::VERIFY_PEER
      @reuse_ssl_sessions = OpenSSL::SSL.const_defined? :Session
    end

    self.proxy = proxy if proxy
  end

  ##
  # Sets this client's OpenSSL::X509::Certificate

  def certificate= certificate
    @certificate = certificate

    reconnect_ssl
  end

  # For Net::HTTP parity
  alias cert= certificate=

  ##
  # Sets the SSL certificate authority file.

  def ca_file= file
    @ca_file = file

    reconnect_ssl
  end

  ##
  # Sets the SSL certificate authority path.

  def ca_path= path
    @ca_path = path

    reconnect_ssl
  end

  ##
  # Overrides the default SSL certificate store used for verifying
  # connections.

  def cert_store= store
    @cert_store = store

    reconnect_ssl
  end

  ##
  # The ciphers allowed for SSL connections

  def ciphers= ciphers
    @ciphers = ciphers

    reconnect_ssl
  end

  ##
  # Creates a new connection for +uri+

  def connection_for uri
    use_ssl = uri.scheme.downcase == 'https'

    net_http_args = [uri.hostname, uri.port]

    # I'm unsure if uri.host or uri.hostname should be checked against
    # the proxy bypass list.
    if @proxy_uri and not proxy_bypass? uri.host, uri.port then
      net_http_args.concat @proxy_args
    else
      net_http_args.concat [nil, nil, nil, nil]
    end

    connection = @pool.checkout net_http_args

    http = connection.http

    connection.ressl @ssl_generation if
      connection.ssl_generation != @ssl_generation

    if not http.started? then
      ssl   http if use_ssl
      start http
    elsif expired? connection then
      reset connection
    end

    http.keep_alive_timeout = @idle_timeout  if @idle_timeout
    http.max_retries        = @max_retries   if http.respond_to?(:max_retries=)
    http.read_timeout       = @read_timeout  if @read_timeout
    http.write_timeout      = @write_timeout if
      @write_timeout && http.respond_to?(:write_timeout=)

    return yield connection
  rescue Errno::ECONNREFUSED
    address = http.proxy_address || http.address
    port    = http.proxy_port    || http.port

    raise Error, "connection refused: #{address}:#{port}"
  rescue Errno::EHOSTDOWN
    address = http.proxy_address || http.address
    port    = http.proxy_port    || http.port

    raise Error, "host down: #{address}:#{port}"
  ensure
    @pool.checkin net_http_args
  end

  ##
  # CGI::escape wrapper

  def escape str
    CGI.escape str if str
  end

  ##
  # CGI::unescape wrapper

  def unescape str
    CGI.unescape str if str
  end


  ##
  # Returns true if the connection should be reset due to an idle timeout, or
  # maximum request count, false otherwise.

  def expired? connection
    return true  if     @max_requests && connection.requests >= @max_requests
    return false unless @idle_timeout
    return true  if     @idle_timeout.zero?

    Time.now - connection.last_use > @idle_timeout
  end

  ##
  # Starts the Net::HTTP +connection+

  def start http
    http.set_debug_output @debug_output if @debug_output
    http.open_timeout = @open_timeout if @open_timeout

    http.start

    socket = http.instance_variable_get :@socket

    if socket then # for fakeweb
      @socket_options.each do |option|
        socket.io.setsockopt(*option)
      end
    end
  end

  ##
  # Finishes the Net::HTTP +connection+

  def finish connection
    connection.finish

    connection.http.instance_variable_set :@last_communicated, nil
    connection.http.instance_variable_set :@ssl_session, nil unless
      @reuse_ssl_sessions
  end

  ##
  # Returns the HTTP protocol version for +uri+

  def http_version uri
    @http_versions["#{uri.hostname}:#{uri.port}"]
  end

  ##
  # Adds "http://" to the String +uri+ if it is missing.

  def normalize_uri uri
    (uri =~ /^https?:/) ? uri : "http://#{uri}"
  end

  ##
  # Set the maximum number of retries for a request.
  #
  # Defaults to one retry.
  #
  # Set this to 0 to disable retries.

  def max_retries= retries
    retries = retries.to_int

    raise ArgumentError, "max_retries must be positive" if retries < 0

    @max_retries = retries

    reconnect
  end

  ##
  # Sets this client's SSL private key

  def private_key= key
    @private_key = key

    reconnect_ssl
  end

  # For Net::HTTP parity
  alias key= private_key=

  ##
  # Sets the proxy server.  The +proxy+ may be the Bundler::URI of the proxy server,
  # the symbol +:ENV+ which will read the proxy from the environment or nil to
  # disable use of a proxy.  See #proxy_from_env for details on setting the
  # proxy from the environment.
  #
  # If the proxy Bundler::URI is set after requests have been made, the next request
  # will shut-down and re-open all connections.
  #
  # The +no_proxy+ query parameter can be used to specify hosts which shouldn't
  # be reached via proxy; if set it should be a comma separated list of
  # hostname suffixes, optionally with +:port+ appended, for example
  # <tt>example.com,some.host:8080</tt>.

  def proxy= proxy
    @proxy_uri = case proxy
                 when :ENV      then proxy_from_env
                 when Bundler::URI::HTTP then proxy
                 when nil       then # ignore
                 else raise ArgumentError, 'proxy must be :ENV or a Bundler::URI::HTTP'
                 end

    @no_proxy.clear

    if @proxy_uri then
      @proxy_args = [
        @proxy_uri.hostname,
        @proxy_uri.port,
        unescape(@proxy_uri.user),
        unescape(@proxy_uri.password),
      ]

      @proxy_connection_id = [nil, *@proxy_args].join ':'

      if @proxy_uri.query then
        @no_proxy = CGI.parse(@proxy_uri.query)['no_proxy'].join(',').downcase.split(',').map { |x| x.strip }.reject { |x| x.empty? }
      end
    end

    reconnect
    reconnect_ssl
  end

  ##
  # Creates a Bundler::URI for an HTTP proxy server from ENV variables.
  #
  # If +HTTP_PROXY+ is set a proxy will be returned.
  #
  # If +HTTP_PROXY_USER+ or +HTTP_PROXY_PASS+ are set the Bundler::URI is given the
  # indicated user and password unless HTTP_PROXY contains either of these in
  # the Bundler::URI.
  #
  # The +NO_PROXY+ ENV variable can be used to specify hosts which shouldn't
  # be reached via proxy; if set it should be a comma separated list of
  # hostname suffixes, optionally with +:port+ appended, for example
  # <tt>example.com,some.host:8080</tt>. When set to <tt>*</tt> no proxy will
  # be returned.
  #
  # For Windows users, lowercase ENV variables are preferred over uppercase ENV
  # variables.

  def proxy_from_env
    env_proxy = ENV['http_proxy'] || ENV['HTTP_PROXY']

    return nil if env_proxy.nil? or env_proxy.empty?

    uri = Bundler::URI normalize_uri env_proxy

    env_no_proxy = ENV['no_proxy'] || ENV['NO_PROXY']

    # '*' is special case for always bypass
    return nil if env_no_proxy == '*'

    if env_no_proxy then
      uri.query = "no_proxy=#{escape(env_no_proxy)}"
    end

    unless uri.user or uri.password then
      uri.user     = escape ENV['http_proxy_user'] || ENV['HTTP_PROXY_USER']
      uri.password = escape ENV['http_proxy_pass'] || ENV['HTTP_PROXY_PASS']
    end

    uri
  end

  ##
  # Returns true when proxy should by bypassed for host.

  def proxy_bypass? host, port
    host = host.downcase
    host_port = [host, port].join ':'

    @no_proxy.each do |name|
      return true if host[-name.length, name.length] == name or
         host_port[-name.length, name.length] == name
    end

    false
  end

  ##
  # Forces reconnection of all HTTP connections, including TLS/SSL
  # connections.

  def reconnect
    @generation += 1
  end

  ##
  # Forces reconnection of only TLS/SSL connections.

  def reconnect_ssl
    @ssl_generation += 1
  end

  ##
  # Finishes then restarts the Net::HTTP +connection+

  def reset connection
    http = connection.http

    finish connection

    start http
  rescue Errno::ECONNREFUSED
    e = Error.new "connection refused: #{http.address}:#{http.port}"
    e.set_backtrace $@
    raise e
  rescue Errno::EHOSTDOWN
    e = Error.new "host down: #{http.address}:#{http.port}"
    e.set_backtrace $@
    raise e
  end

  ##
  # Makes a request on +uri+.  If +req+ is nil a Net::HTTP::Get is performed
  # against +uri+.
  #
  # If a block is passed #request behaves like Net::HTTP#request (the body of
  # the response will not have been read).
  #
  # +req+ must be a Net::HTTPGenericRequest subclass (see Net::HTTP for a list).

  def request uri, req = nil, &block
    uri      = Bundler::URI uri
    req      = request_setup req || uri
    response = nil

    connection_for uri do |connection|
      http = connection.http

      begin
        connection.requests += 1

        response = http.request req, &block

        if req.connection_close? or
          (response.http_version <= '1.0' and
            not response.connection_keep_alive?) or
            response.connection_close? then
          finish connection
        end
      rescue Exception # make sure to close the connection when it was interrupted
        finish connection

        raise
      ensure
        connection.last_use = Time.now
      end
    end

    @http_versions["#{uri.hostname}:#{uri.port}"] ||= response.http_version

    response
  end

  ##
  # Creates a GET request if +req_or_uri+ is a Bundler::URI and adds headers to the
  # request.
  #
  # Returns the request.

  def request_setup req_or_uri # :nodoc:
    req = if req_or_uri.respond_to? 'request_uri' then
            Net::HTTP::Get.new req_or_uri.request_uri
          else
            req_or_uri
          end

    @headers.each do |pair|
      req.add_field(*pair)
    end

    @override_headers.each do |name, value|
      req[name] = value
    end

    unless req['Connection'] then
      req.add_field 'Connection', 'keep-alive'
      req.add_field 'Keep-Alive', @keep_alive
    end

    req
  end

  ##
  # Shuts down all connections
  #
  # *NOTE*: Calling shutdown for can be dangerous!
  #
  # If any thread is still using a connection it may cause an error!  Call
  # #shutdown when you are completely done making requests!

  def shutdown
    @pool.shutdown { |http| http.finish }
  end

  ##
  # Enables SSL on +connection+

  def ssl connection
    connection.use_ssl = true

    connection.ciphers     = @ciphers     if @ciphers
    connection.ssl_timeout = @ssl_timeout if @ssl_timeout
    connection.ssl_version = @ssl_version if @ssl_version
    connection.min_version = @min_version if @min_version
    connection.max_version = @max_version if @max_version

    connection.verify_depth = @verify_depth
    connection.verify_mode  = @verify_mode

    if OpenSSL::SSL::VERIFY_PEER == OpenSSL::SSL::VERIFY_NONE and
       not Object.const_defined?(:I_KNOW_THAT_OPENSSL_VERIFY_PEER_EQUALS_VERIFY_NONE_IS_WRONG) then
      warn <<-WARNING
                             !!!SECURITY WARNING!!!

The SSL HTTP connection to:

  #{connection.address}:#{connection.port}

                           !!!MAY NOT BE VERIFIED!!!

On your platform your OpenSSL implementation is broken.

There is no difference between the values of VERIFY_NONE and VERIFY_PEER.

This means that attempting to verify the security of SSL connections may not
work.  This exposes you to man-in-the-middle exploits, snooping on the
contents of your connection and other dangers to the security of your data.

To disable this warning define the following constant at top-level in your
application:

  I_KNOW_THAT_OPENSSL_VERIFY_PEER_EQUALS_VERIFY_NONE_IS_WRONG = nil

      WARNING
    end

    connection.ca_file = @ca_file if @ca_file
    connection.ca_path = @ca_path if @ca_path

    if @ca_file or @ca_path then
      connection.verify_mode = OpenSSL::SSL::VERIFY_PEER
      connection.verify_callback = @verify_callback if @verify_callback
    end

    if @certificate and @private_key then
      connection.cert = @certificate
      connection.key  = @private_key
    end

    connection.cert_store = if @cert_store then
                              @cert_store
                            else
                              store = OpenSSL::X509::Store.new
                              store.set_default_paths
                              store
                            end
  end

  ##
  # SSL session lifetime

  def ssl_timeout= ssl_timeout
    @ssl_timeout = ssl_timeout

    reconnect_ssl
  end

  ##
  # SSL version to use

  def ssl_version= ssl_version
    @ssl_version = ssl_version

    reconnect_ssl
  end

  ##
  # Minimum SSL version to use

  def min_version= min_version
    @min_version = min_version

    reconnect_ssl
  end

  ##
  # maximum SSL version to use

  def max_version= max_version
    @max_version = max_version

    reconnect_ssl
  end

  ##
  # Sets the depth of SSL certificate verification

  def verify_depth= verify_depth
    @verify_depth = verify_depth

    reconnect_ssl
  end

  ##
  # Sets the HTTPS verify mode.  Defaults to OpenSSL::SSL::VERIFY_PEER.
  #
  # Setting this to VERIFY_NONE is a VERY BAD IDEA and should NEVER be used.
  # Securely transfer the correct certificate and update the default
  # certificate store or set the ca file instead.

  def verify_mode= verify_mode
    @verify_mode = verify_mode

    reconnect_ssl
  end

  ##
  # SSL verification callback.

  def verify_callback= callback
    @verify_callback = callback

    reconnect_ssl
  end
end

require_relative 'persistent/connection'
require_relative 'persistent/pool'

# 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 Bundler::FileUtils
#
# Namespace for several file utility methods for copying, moving, removing, etc.
#
# === Module Functions
#
#   require 'bundler/vendor/fileutils/lib/fileutils'
#
#   Bundler::FileUtils.cd(dir, **options)
#   Bundler::FileUtils.cd(dir, **options) {|dir| block }
#   Bundler::FileUtils.pwd()
#   Bundler::FileUtils.mkdir(dir, **options)
#   Bundler::FileUtils.mkdir(list, **options)
#   Bundler::FileUtils.mkdir_p(dir, **options)
#   Bundler::FileUtils.mkdir_p(list, **options)
#   Bundler::FileUtils.rmdir(dir, **options)
#   Bundler::FileUtils.rmdir(list, **options)
#   Bundler::FileUtils.ln(target, link, **options)
#   Bundler::FileUtils.ln(targets, dir, **options)
#   Bundler::FileUtils.ln_s(target, link, **options)
#   Bundler::FileUtils.ln_s(targets, dir, **options)
#   Bundler::FileUtils.ln_sf(target, link, **options)
#   Bundler::FileUtils.cp(src, dest, **options)
#   Bundler::FileUtils.cp(list, dir, **options)
#   Bundler::FileUtils.cp_r(src, dest, **options)
#   Bundler::FileUtils.cp_r(list, dir, **options)
#   Bundler::FileUtils.mv(src, dest, **options)
#   Bundler::FileUtils.mv(list, dir, **options)
#   Bundler::FileUtils.rm(list, **options)
#   Bundler::FileUtils.rm_r(list, **options)
#   Bundler::FileUtils.rm_rf(list, **options)
#   Bundler::FileUtils.install(src, dest, **options)
#   Bundler::FileUtils.chmod(mode, list, **options)
#   Bundler::FileUtils.chmod_R(mode, list, **options)
#   Bundler::FileUtils.chown(user, group, list, **options)
#   Bundler::FileUtils.chown_R(user, group, list, **options)
#   Bundler::FileUtils.touch(list, **options)
#
# Possible <tt>options</tt> are:
#
# <tt>:force</tt> :: forced operation (rewrite files if exist, remove
#                    directories if not empty, etc.);
# <tt>:verbose</tt> :: print command to be run, in bash syntax, before
#                      performing it;
# <tt>:preserve</tt> :: preserve object's group, user and modification
#                       time on copying;
# <tt>:noop</tt> :: no changes are made (usable in combination with
#                   <tt>:verbose</tt> 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:
#
#   Bundler::FileUtils.copy_entry(src, dest, preserve = false, dereference_root = false, remove_destination = false)
#   Bundler::FileUtils.copy_file(src, dest, preserve = false, dereference = true)
#   Bundler::FileUtils.copy_stream(srcstream, deststream)
#   Bundler::FileUtils.remove_entry(path, force = false)
#   Bundler::FileUtils.remove_entry_secure(path, force = false)
#   Bundler::FileUtils.remove_file(path, force = false)
#   Bundler::FileUtils.compare_file(path_a, path_b)
#   Bundler::FileUtils.compare_stream(stream_a, stream_b)
#   Bundler::FileUtils.uptodate?(file, cmp_list)
#
# == module Bundler::FileUtils::Verbose
#
# This module has all methods of Bundler::FileUtils module, but it outputs messages
# before acting.  This equates to passing the <tt>:verbose</tt> flag to methods
# in Bundler::FileUtils.
#
# == module Bundler::FileUtils::NoWrite
#
# This module has all methods of Bundler::FileUtils module, but never changes
# files/directories.  This equates to passing the <tt>:noop</tt> flag to methods
# in Bundler::FileUtils.
#
# == module Bundler::FileUtils::DryRun
#
# This module has all methods of Bundler::FileUtils module, but never changes
# files/directories.  This equates to passing the <tt>:noop</tt> and
# <tt>:verbose</tt> flags to methods in Bundler::FileUtils.
#
module Bundler::FileUtils
  VERSION = "1.4.1"

  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.
  #
  #   Bundler::FileUtils.cd('/')  # change directory
  #
  #   Bundler::FileUtils.cd('/', verbose: true)   # change directory and report it
  #
  #   Bundler::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.
  #
  #   Bundler::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.
  #
  #   Bundler::FileUtils.mkdir 'test'
  #   Bundler::FileUtils.mkdir %w(tmp data)
  #   Bundler::FileUtils.mkdir 'notexist', noop: true  # Does not really create.
  #   Bundler::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,
  #
  #   Bundler::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.map {|path| remove_trailing_slash(path)}.each do |path|
      # optimize for the most common case
      begin
        fu_mkdir path, mode
        next
      rescue SystemCallError
        next if File.directory?(path)
      end

      stack = []
      until path == stack.last   # dirname("/")=="/", dirname("C:/")=="C:/"
        stack.push path
        path = File.dirname(path)
      end
      stack.pop                 # root directory should exist
      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.
  #
  #   Bundler::FileUtils.rmdir 'somedir'
  #   Bundler::FileUtils.rmdir %w(somedir anydir otherdir)
  #   # Does not really remove directory; outputs message.
  #   Bundler::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:
  #   Bundler::FileUtils.ln(target, link, force: nil, noop: nil, verbose: nil)
  #   Bundler::FileUtils.ln(target,  dir, force: nil, noop: nil, verbose: nil)
  #   Bundler::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+.
  #
  #   Bundler::FileUtils.ln 'gcc', 'cc', verbose: true
  #   Bundler::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.
  #
  #   Bundler::FileUtils.cd '/sbin'
  #   Bundler::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.
  #
  #   Bundler::FileUtils.rm_r site_ruby + '/mylib', force: true
  #   Bundler::FileUtils.cp_lr 'lib/', site_ruby + '/mylib'
  #
  #   # Examples of linking several files to target directory.
  #   Bundler::FileUtils.cp_lr %w(mail.rb field.rb debug/), site_ruby + '/tmail'
  #   Bundler::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.
  #   Bundler::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:
  #   Bundler::FileUtils.ln_s(target, link, force: nil, noop: nil, verbose: nil)
  #   Bundler::FileUtils.ln_s(target,  dir, force: nil, noop: nil, verbose: nil)
  #   Bundler::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 <tt>force</tt> option is set, overwrites +link+.
  #
  #   Bundler::FileUtils.ln_s '/usr/bin/ruby', '/usr/local/bin/ruby'
  #   Bundler::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.
  #
  #   Bundler::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:
  #   Bundler::FileUtils.ln_sf(*args)
  #
  # Same as
  #
  #   Bundler::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.
  #
  #   Bundler::FileUtils.cp 'eval.c', 'eval.c.org'
  #   Bundler::FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6'
  #   Bundler::FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6', verbose: true
  #   Bundler::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
  #   Bundler::FileUtils.rm_r site_ruby + '/mylib', force: true
  #   Bundler::FileUtils.cp_r 'lib/', site_ruby + '/mylib'
  #
  #   # Examples of copying several files to target directory.
  #   Bundler::FileUtils.cp_r %w(mail.rb field.rb debug/), site_ruby + '/tmail'
  #   Bundler::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.
  #   Bundler::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.
  #
  #   Bundler::FileUtils.mv 'badname.rb', 'goodname.rb'
  #   Bundler::FileUtils.mv 'stuff.rb', '/notexist/lib/ruby', force: true  # no error
  #
  #   Bundler::FileUtils.mv %w(junk.txt dust.txt), '/home/foo/.trash/'
  #   Bundler::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.
  #
  #   Bundler::FileUtils.rm %w( junk.txt dust.txt )
  #   Bundler::FileUtils.rm Dir.glob('*.so')
  #   Bundler::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
  #
  #   Bundler::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.
  #
  #   Bundler::FileUtils.rm_r Dir.glob('/tmp/*')
  #   Bundler::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 <tt>secure: false</tt>.
  #
  # 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
  #
  #   Bundler::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, Bundler::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.
  #
  #   Bundler::FileUtils.compare_file('somefile', 'somefile')       #=> true
  #   Bundler::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)

    if RUBY_VERSION > "2.4"
      sa = String.new(capacity: bsize)
      sb = String.new(capacity: bsize)
    else
      sa = String.new
      sb = String.new
    end

    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.
  #
  #   Bundler::FileUtils.install 'ruby', '/usr/local/bin/ruby', mode: 0755, verbose: true
  #   Bundler::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:
    mode = if File::Stat === path
             path.mode
           else
             File.stat(path).mode
           end
    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 FileTest.directory? path
              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
  #   Bundler::FileUtils.chmod 0755, 'somecommand'
  #   Bundler::FileUtils.chmod 0644, %w(my.rb your.rb his.rb her.rb)
  #   Bundler::FileUtils.chmod 0755, '/usr/bin/ruby', verbose: true
  #
  # Symbolic mode is
  #   Bundler::FileUtils.chmod "u=wrx,go=rx", 'somecommand'
  #   Bundler::FileUtils.chmod "u=wr,go=rr", %w(my.rb your.rb his.rb her.rb)
  #   Bundler::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+.
  #
  #   Bundler::FileUtils.chmod_R 0700, "/tmp/app.#{$$}"
  #   Bundler::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.
  #
  #   Bundler::FileUtils.chown 'root', 'staff', '/usr/local/bin/ruby'
  #   Bundler::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.
  #
  #   Bundler::FileUtils.chown_R 'www', 'www', '/var/www/htdocs'
  #   Bundler::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.
  #
  #   Bundler::FileUtils.touch 'timestamp'
  #   Bundler::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] = ::Encoding::UTF_8 if fu_windows?

      files = if Dir.respond_to?(:children)
        Dir.children(path, **opts)
      else
        Dir.entries(path(), **opts)
           .reject {|n| n == '.' or n == '..' }
      end

      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
    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
        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 == '.'
      File.join(dir, base)
    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 ||= $stderr
    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 Bundler::FileUtils.commands  #=> ["chmod", "cp", "cp_r", "install", ...]
  #
  def self.commands
    OPT_TABLE.keys
  end

  #
  # Returns an Array of option names.
  #
  #   p Bundler::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 Bundler::FileUtils.have_option?(:cp, :noop)     #=> true
  #   p Bundler::FileUtils.have_option?(:rm, :force)    #=> true
  #   p Bundler::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 Bundler::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 Bundler::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
    ::Bundler::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 Bundler::FileUtils module, but it outputs messages
  # before acting.  This equates to passing the <tt>:verbose</tt> flag to
  # methods in Bundler::FileUtils.
  #
  module Verbose
    include Bundler::FileUtils
    names = ::Bundler::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(*::Bundler::FileUtils::METHODS)
    end
  end

  #
  # This module has all methods of Bundler::FileUtils module, but never changes
  # files/directories.  This equates to passing the <tt>:noop</tt> flag
  # to methods in Bundler::FileUtils.
  #
  module NoWrite
    include Bundler::FileUtils
    include LowMethods
    names = ::Bundler::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(*::Bundler::FileUtils::METHODS)
    end
  end

  #
  # This module has all methods of Bundler::FileUtils module, but never changes
  # files/directories, with printing message before acting.
  # This equates to passing the <tt>:noop</tt> and <tt>:verbose</tt> flag
  # to methods in Bundler::FileUtils.
  #
  module DryRun
    include Bundler::FileUtils
    include LowMethods
    names = ::Bundler::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(*::Bundler::FileUtils::METHODS)
    end
  end

end
This project is licensed under the MIT license.

Copyright (c) 2014 Samuel E. Giddins segiddins@segiddins.me

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.
# frozen_string_literal: true

require_relative 'molinillo/gem_metadata'
require_relative 'molinillo/errors'
require_relative 'molinillo/resolver'
require_relative 'molinillo/modules/ui'
require_relative 'molinillo/modules/specification_provider'

# Bundler::Molinillo is a generic dependency resolution algorithm.
module Bundler::Molinillo
end
# frozen_string_literal: true

require_relative '../../../../vendored_tsort'

require_relative 'dependency_graph/log'
require_relative 'dependency_graph/vertex'

module Bundler::Molinillo
  # A directed acyclic graph that is tuned to hold named dependencies
  class DependencyGraph
    include Enumerable

    # Enumerates through the vertices of the graph.
    # @return [Array<Vertex>] The graph's vertices.
    def each
      return vertices.values.each unless block_given?
      vertices.values.each { |v| yield v }
    end

    include Bundler::TSort

    # @!visibility private
    alias tsort_each_node each

    # @!visibility private
    def tsort_each_child(vertex, &block)
      vertex.successors.each(&block)
    end

    # Topologically sorts the given vertices.
    # @param [Enumerable<Vertex>] vertices the vertices to be sorted, which must
    #   all belong to the same graph.
    # @return [Array<Vertex>] The sorted vertices.
    def self.tsort(vertices)
      TSort.tsort(
        lambda { |b| vertices.each(&b) },
        lambda { |v, &b| (v.successors & vertices).each(&b) }
      )
    end

    # A directed edge of a {DependencyGraph}
    # @attr [Vertex] origin The origin of the directed edge
    # @attr [Vertex] destination The destination of the directed edge
    # @attr [Object] requirement The requirement the directed edge represents
    Edge = Struct.new(:origin, :destination, :requirement)

    # @return [{String => Vertex}] the vertices of the dependency graph, keyed
    #   by {Vertex#name}
    attr_reader :vertices

    # @return [Log] the op log for this graph
    attr_reader :log

    # Initializes an empty dependency graph
    def initialize
      @vertices = {}
      @log = Log.new
    end

    # Tags the current state of the dependency as the given tag
    # @param  [Object] tag an opaque tag for the current state of the graph
    # @return [Void]
    def tag(tag)
      log.tag(self, tag)
    end

    # Rewinds the graph to the state tagged as `tag`
    # @param  [Object] tag the tag to rewind to
    # @return [Void]
    def rewind_to(tag)
      log.rewind_to(self, tag)
    end

    # Initializes a copy of a {DependencyGraph}, ensuring that all {#vertices}
    # are properly copied.
    # @param [DependencyGraph] other the graph to copy.
    def initialize_copy(other)
      super
      @vertices = {}
      @log = other.log.dup
      traverse = lambda do |new_v, old_v|
        return if new_v.outgoing_edges.size == old_v.outgoing_edges.size
        old_v.outgoing_edges.each do |edge|
          destination = add_vertex(edge.destination.name, edge.destination.payload)
          add_edge_no_circular(new_v, destination, edge.requirement)
          traverse.call(destination, edge.destination)
        end
      end
      other.vertices.each do |name, vertex|
        new_vertex = add_vertex(name, vertex.payload, vertex.root?)
        new_vertex.explicit_requirements.replace(vertex.explicit_requirements)
        traverse.call(new_vertex, vertex)
      end
    end

    # @return [String] a string suitable for debugging
    def inspect
      "#{self.class}:#{vertices.values.inspect}"
    end

    # @param [Hash] options options for dot output.
    # @return [String] Returns a dot format representation of the graph
    def to_dot(options = {})
      edge_label = options.delete(:edge_label)
      raise ArgumentError, "Unknown options: #{options.keys}" unless options.empty?

      dot_vertices = []
      dot_edges = []
      vertices.each do |n, v|
        dot_vertices << "  #{n} [label=\"{#{n}|#{v.payload}}\"]"
        v.outgoing_edges.each do |e|
          label = edge_label ? edge_label.call(e) : e.requirement
          dot_edges << "  #{e.origin.name} -> #{e.destination.name} [label=#{label.to_s.dump}]"
        end
      end

      dot_vertices.uniq!
      dot_vertices.sort!
      dot_edges.uniq!
      dot_edges.sort!

      dot = dot_vertices.unshift('digraph G {').push('') + dot_edges.push('}')
      dot.join("\n")
    end

    # @param [DependencyGraph] other
    # @return [Boolean] whether the two dependency graphs are equal, determined
    #   by a recursive traversal of each {#root_vertices} and its
    #   {Vertex#successors}
    def ==(other)
      return false unless other
      return true if equal?(other)
      vertices.each do |name, vertex|
        other_vertex = other.vertex_named(name)
        return false unless other_vertex
        return false unless vertex.payload == other_vertex.payload
        return false unless other_vertex.successors.to_set == vertex.successors.to_set
      end
    end

    # @param [String] name
    # @param [Object] payload
    # @param [Array<String>] parent_names
    # @param [Object] requirement the requirement that is requiring the child
    # @return [void]
    def add_child_vertex(name, payload, parent_names, requirement)
      root = !parent_names.delete(nil) { true }
      vertex = add_vertex(name, payload, root)
      vertex.explicit_requirements << requirement if root
      parent_names.each do |parent_name|
        parent_vertex = vertex_named(parent_name)
        add_edge(parent_vertex, vertex, requirement)
      end
      vertex
    end

    # Adds a vertex with the given name, or updates the existing one.
    # @param [String] name
    # @param [Object] payload
    # @return [Vertex] the vertex that was added to `self`
    def add_vertex(name, payload, root = false)
      log.add_vertex(self, name, payload, root)
    end

    # Detaches the {#vertex_named} `name` {Vertex} from the graph, recursively
    # removing any non-root vertices that were orphaned in the process
    # @param [String] name
    # @return [Array<Vertex>] the vertices which have been detached
    def detach_vertex_named(name)
      log.detach_vertex_named(self, name)
    end

    # @param [String] name
    # @return [Vertex,nil] the vertex with the given name
    def vertex_named(name)
      vertices[name]
    end

    # @param [String] name
    # @return [Vertex,nil] the root vertex with the given name
    def root_vertex_named(name)
      vertex = vertex_named(name)
      vertex if vertex && vertex.root?
    end

    # Adds a new {Edge} to the dependency graph
    # @param [Vertex] origin
    # @param [Vertex] destination
    # @param [Object] requirement the requirement that this edge represents
    # @return [Edge] the added edge
    def add_edge(origin, destination, requirement)
      if destination.path_to?(origin)
        raise CircularDependencyError.new(path(destination, origin))
      end
      add_edge_no_circular(origin, destination, requirement)
    end

    # Deletes an {Edge} from the dependency graph
    # @param [Edge] edge
    # @return [Void]
    def delete_edge(edge)
      log.delete_edge(self, edge.origin.name, edge.destination.name, edge.requirement)
    end

    # Sets the payload of the vertex with the given name
    # @param [String] name the name of the vertex
    # @param [Object] payload the payload
    # @return [Void]
    def set_payload(name, payload)
      log.set_payload(self, name, payload)
    end

    private

    # Adds a new {Edge} to the dependency graph without checking for
    # circularity.
    # @param (see #add_edge)
    # @return (see #add_edge)
    def add_edge_no_circular(origin, destination, requirement)
      log.add_edge_no_circular(self, origin.name, destination.name, requirement)
    end

    # Returns the path between two vertices
    # @raise [ArgumentError] if there is no path between the vertices
    # @param [Vertex] from
    # @param [Vertex] to
    # @return [Array<Vertex>] the shortest path from `from` to `to`
    def path(from, to)
      distances = Hash.new(vertices.size + 1)
      distances[from.name] = 0
      predecessors = {}
      each do |vertex|
        vertex.successors.each do |successor|
          if distances[successor.name] > distances[vertex.name] + 1
            distances[successor.name] = distances[vertex.name] + 1
            predecessors[successor] = vertex
          end
        end
      end

      path = [to]
      while before = predecessors[to]
        path << before
        to = before
        break if to == from
      end

      unless path.last.equal?(from)
        raise ArgumentError, "There is no path from #{from.name} to #{to.name}"
      end

      path.reverse
    end
  end
end
# frozen_string_literal: true

module Bundler::Molinillo
  class Resolver
    # A specific resolution from a given {Resolver}
    class Resolution
      # A conflict that the resolution process encountered
      # @attr [Object] requirement the requirement that immediately led to the conflict
      # @attr [{String,Nil=>[Object]}] requirements the requirements that caused the conflict
      # @attr [Object, nil] existing the existing spec that was in conflict with
      #   the {#possibility}
      # @attr [Object] possibility_set the set of specs that was unable to be
      #   activated due to a conflict.
      # @attr [Object] locked_requirement the relevant locking requirement.
      # @attr [Array<Array<Object>>] requirement_trees the different requirement
      #   trees that led to every requirement for the conflicting name.
      # @attr [{String=>Object}] activated_by_name the already-activated specs.
      # @attr [Object] underlying_error an error that has occurred during resolution, and
      #    will be raised at the end of it if no resolution is found.
      Conflict = Struct.new(
        :requirement,
        :requirements,
        :existing,
        :possibility_set,
        :locked_requirement,
        :requirement_trees,
        :activated_by_name,
        :underlying_error
      )

      class Conflict
        # @return [Object] a spec that was unable to be activated due to a conflict
        def possibility
          possibility_set && possibility_set.latest_version
        end
      end

      # A collection of possibility states that share the same dependencies
      # @attr [Array] dependencies the dependencies for this set of possibilities
      # @attr [Array] possibilities the possibilities
      PossibilitySet = Struct.new(:dependencies, :possibilities)

      class PossibilitySet
        # String representation of the possibility set, for debugging
        def to_s
          "[#{possibilities.join(', ')}]"
        end

        # @return [Object] most up-to-date dependency in the possibility set
        def latest_version
          possibilities.last
        end
      end

      # Details of the state to unwind to when a conflict occurs, and the cause of the unwind
      # @attr [Integer] state_index the index of the state to unwind to
      # @attr [Object] state_requirement the requirement of the state we're unwinding to
      # @attr [Array] requirement_tree for the requirement we're relaxing
      # @attr [Array] conflicting_requirements the requirements that combined to cause the conflict
      # @attr [Array] requirement_trees for the conflict
      # @attr [Array] requirements_unwound_to_instead array of unwind requirements that were chosen over this unwind
      UnwindDetails = Struct.new(
        :state_index,
        :state_requirement,
        :requirement_tree,
        :conflicting_requirements,
        :requirement_trees,
        :requirements_unwound_to_instead
      )

      class UnwindDetails
        include Comparable

        # We compare UnwindDetails when choosing which state to unwind to. If
        # two options have the same state_index we prefer the one most
        # removed from a requirement that caused the conflict. Both options
        # would unwind to the same state, but a `grandparent` option will
        # filter out fewer of its possibilities after doing so - where a state
        # is both a `parent` and a `grandparent` to requirements that have
        # caused a conflict this is the correct behaviour.
        # @param [UnwindDetail] other UnwindDetail to be compared
        # @return [Integer] integer specifying ordering
        def <=>(other)
          if state_index > other.state_index
            1
          elsif state_index == other.state_index
            reversed_requirement_tree_index <=> other.reversed_requirement_tree_index
          else
            -1
          end
        end

        # @return [Integer] index of state requirement in reversed requirement tree
        #    (the conflicting requirement itself will be at position 0)
        def reversed_requirement_tree_index
          @reversed_requirement_tree_index ||=
            if state_requirement
              requirement_tree.reverse.index(state_requirement)
            else
              999_999
            end
        end

        # @return [Boolean] where the requirement of the state we're unwinding
        #    to directly caused the conflict. Note: in this case, it is
        #    impossible for the state we're unwinding to to be a parent of
        #    any of the other conflicting requirements (or we would have
        #    circularity)
        def unwinding_to_primary_requirement?
          requirement_tree.last == state_requirement
        end

        # @return [Array] array of sub-dependencies to avoid when choosing a
        #    new possibility for the state we've unwound to. Only relevant for
        #    non-primary unwinds
        def sub_dependencies_to_avoid
          @requirements_to_avoid ||=
            requirement_trees.map do |tree|
              index = tree.index(state_requirement)
              tree[index + 1] if index
            end.compact
        end

        # @return [Array] array of all the requirements that led to the need for
        #    this unwind
        def all_requirements
          @all_requirements ||= requirement_trees.flatten(1)
        end
      end

      # @return [SpecificationProvider] the provider that knows about
      #   dependencies, requirements, specifications, versions, etc.
      attr_reader :specification_provider

      # @return [UI] the UI that knows how to communicate feedback about the
      #   resolution process back to the user
      attr_reader :resolver_ui

      # @return [DependencyGraph] the base dependency graph to which
      #   dependencies should be 'locked'
      attr_reader :base

      # @return [Array] the dependencies that were explicitly required
      attr_reader :original_requested

      # Initializes a new resolution.
      # @param [SpecificationProvider] specification_provider
      #   see {#specification_provider}
      # @param [UI] resolver_ui see {#resolver_ui}
      # @param [Array] requested see {#original_requested}
      # @param [DependencyGraph] base see {#base}
      def initialize(specification_provider, resolver_ui, requested, base)
        @specification_provider = specification_provider
        @resolver_ui = resolver_ui
        @original_requested = requested
        @base = base
        @states = []
        @iteration_counter = 0
        @parents_of = Hash.new { |h, k| h[k] = [] }
      end

      # Resolves the {#original_requested} dependencies into a full dependency
      #   graph
      # @raise [ResolverError] if successful resolution is impossible
      # @return [DependencyGraph] the dependency graph of successfully resolved
      #   dependencies
      def resolve
        start_resolution

        while state
          break if !state.requirement && state.requirements.empty?
          indicate_progress
          if state.respond_to?(:pop_possibility_state) # DependencyState
            debug(depth) { "Creating possibility state for #{requirement} (#{possibilities.count} remaining)" }
            state.pop_possibility_state.tap do |s|
              if s
                states.push(s)
                activated.tag(s)
              end
            end
          end
          process_topmost_state
        end

        resolve_activated_specs
      ensure
        end_resolution
      end

      # @return [Integer] the number of resolver iterations in between calls to
      #   {#resolver_ui}'s {UI#indicate_progress} method
      attr_accessor :iteration_rate
      private :iteration_rate

      # @return [Time] the time at which resolution began
      attr_accessor :started_at
      private :started_at

      # @return [Array<ResolutionState>] the stack of states for the resolution
      attr_accessor :states
      private :states

      private

      # Sets up the resolution process
      # @return [void]
      def start_resolution
        @started_at = Time.now

        push_initial_state

        debug { "Starting resolution (#{@started_at})\nUser-requested dependencies: #{original_requested}" }
        resolver_ui.before_resolution
      end

      def resolve_activated_specs
        activated.vertices.each do |_, vertex|
          next unless vertex.payload

          latest_version = vertex.payload.possibilities.reverse_each.find do |possibility|
            vertex.requirements.all? { |req| requirement_satisfied_by?(req, activated, possibility) }
          end

          activated.set_payload(vertex.name, latest_version)
        end
        activated.freeze
      end

      # Ends the resolution process
      # @return [void]
      def end_resolution
        resolver_ui.after_resolution
        debug do
          "Finished resolution (#{@iteration_counter} steps) " \
          "(Took #{(ended_at = Time.now) - @started_at} seconds) (#{ended_at})"
        end
        debug { 'Unactivated: ' + Hash[activated.vertices.reject { |_n, v| v.payload }].keys.join(', ') } if state
        debug { 'Activated: ' + Hash[activated.vertices.select { |_n, v| v.payload }].keys.join(', ') } if state
      end

      require_relative 'state'
      require_relative 'modules/specification_provider'

      require_relative 'delegates/resolution_state'
      require_relative 'delegates/specification_provider'

      include Bundler::Molinillo::Delegates::ResolutionState
      include Bundler::Molinillo::Delegates::SpecificationProvider

      # Processes the topmost available {RequirementState} on the stack
      # @return [void]
      def process_topmost_state
        if possibility
          attempt_to_activate
        else
          create_conflict
          unwind_for_conflict
        end
      rescue CircularDependencyError => underlying_error
        create_conflict(underlying_error)
        unwind_for_conflict
      end

      # @return [Object] the current possibility that the resolution is trying
      #   to activate
      def possibility
        possibilities.last
      end

      # @return [RequirementState] the current state the resolution is
      #   operating upon
      def state
        states.last
      end

      # Creates and pushes the initial state for the resolution, based upon the
      # {#requested} dependencies
      # @return [void]
      def push_initial_state
        graph = DependencyGraph.new.tap do |dg|
          original_requested.each do |requested|
            vertex = dg.add_vertex(name_for(requested), nil, true)
            vertex.explicit_requirements << requested
          end
          dg.tag(:initial_state)
        end

        push_state_for_requirements(original_requested, true, graph)
      end

      # Unwinds the states stack because a conflict has been encountered
      # @return [void]
      def unwind_for_conflict
        details_for_unwind = build_details_for_unwind
        unwind_options = unused_unwind_options
        debug(depth) { "Unwinding for conflict: #{requirement} to #{details_for_unwind.state_index / 2}" }
        conflicts.tap do |c|
          sliced_states = states.slice!((details_for_unwind.state_index + 1)..-1)
          raise_error_unless_state(c)
          activated.rewind_to(sliced_states.first || :initial_state) if sliced_states
          state.conflicts = c
          state.unused_unwind_options = unwind_options
          filter_possibilities_after_unwind(details_for_unwind)
          index = states.size - 1
          @parents_of.each { |_, a| a.reject! { |i| i >= index } }
          state.unused_unwind_options.reject! { |uw| uw.state_index >= index }
        end
      end

      # Raises a VersionConflict error, or any underlying error, if there is no
      # current state
      # @return [void]
      def raise_error_unless_state(conflicts)
        return if state

        error = conflicts.values.map(&:underlying_error).compact.first
        raise error || VersionConflict.new(conflicts, specification_provider)
      end

      # @return [UnwindDetails] Details of the nearest index to which we could unwind
      def build_details_for_unwind
        # Get the possible unwinds for the current conflict
        current_conflict = conflicts[name]
        binding_requirements = binding_requirements_for_conflict(current_conflict)
        unwind_details = unwind_options_for_requirements(binding_requirements)

        last_detail_for_current_unwind = unwind_details.sort.last
        current_detail = last_detail_for_current_unwind

        # Look for past conflicts that could be unwound to affect the
        # requirement tree for the current conflict
        all_reqs = last_detail_for_current_unwind.all_requirements
        all_reqs_size = all_reqs.size
        relevant_unused_unwinds = unused_unwind_options.select do |alternative|
          diff_reqs = all_reqs - alternative.requirements_unwound_to_instead
          next if diff_reqs.size == all_reqs_size
          # Find the highest index unwind whilst looping through
          current_detail = alternative if alternative > current_detail
          alternative
        end

        # Add the current unwind options to the `unused_unwind_options` array.
        # The "used" option will be filtered out during `unwind_for_conflict`.
        state.unused_unwind_options += unwind_details.reject { |detail| detail.state_index == -1 }

        # Update the requirements_unwound_to_instead on any relevant unused unwinds
        relevant_unused_unwinds.each do |d|
          (d.requirements_unwound_to_instead << current_detail.state_requirement).uniq!
        end
        unwind_details.each do |d|
          (d.requirements_unwound_to_instead << current_detail.state_requirement).uniq!
        end

        current_detail
      end

      # @param [Array<Object>] binding_requirements array of requirements that combine to create a conflict
      # @return [Array<UnwindDetails>] array of UnwindDetails that have a chance
      #    of resolving the passed requirements
      def unwind_options_for_requirements(binding_requirements)
        unwind_details = []

        trees = []
        binding_requirements.reverse_each do |r|
          partial_tree = [r]
          trees << partial_tree
          unwind_details << UnwindDetails.new(-1, nil, partial_tree, binding_requirements, trees, [])

          # If this requirement has alternative possibilities, check if any would
          # satisfy the other requirements that created this conflict
          requirement_state = find_state_for(r)
          if conflict_fixing_possibilities?(requirement_state, binding_requirements)
            unwind_details << UnwindDetails.new(
              states.index(requirement_state),
              r,
              partial_tree,
              binding_requirements,
              trees,
              []
            )
          end

          # Next, look at the parent of this requirement, and check if the requirement
          # could have been avoided if an alternative PossibilitySet had been chosen
          parent_r = parent_of(r)
          next if parent_r.nil?
          partial_tree.unshift(parent_r)
          requirement_state = find_state_for(parent_r)
          if requirement_state.possibilities.any? { |set| !set.dependencies.include?(r) }
            unwind_details << UnwindDetails.new(
              states.index(requirement_state),
              parent_r,
              partial_tree,
              binding_requirements,
              trees,
              []
            )
          end

          # Finally, look at the grandparent and up of this requirement, looking
          # for any possibilities that wouldn't create their parent requirement
          grandparent_r = parent_of(parent_r)
          until grandparent_r.nil?
            partial_tree.unshift(grandparent_r)
            requirement_state = find_state_for(grandparent_r)
            if requirement_state.possibilities.any? { |set| !set.dependencies.include?(parent_r) }
              unwind_details << UnwindDetails.new(
                states.index(requirement_state),
                grandparent_r,
                partial_tree,
                binding_requirements,
                trees,
                []
              )
            end
            parent_r = grandparent_r
            grandparent_r = parent_of(parent_r)
          end
        end

        unwind_details
      end

      # @param [DependencyState] state
      # @param [Array] binding_requirements array of requirements
      # @return [Boolean] whether or not the given state has any possibilities
      #    that could satisfy the given requirements
      def conflict_fixing_possibilities?(state, binding_requirements)
        return false unless state

        state.possibilities.any? do |possibility_set|
          possibility_set.possibilities.any? do |poss|
            possibility_satisfies_requirements?(poss, binding_requirements)
          end
        end
      end

      # Filter's a state's possibilities to remove any that would not fix the
      # conflict we've just rewound from
      # @param [UnwindDetails] unwind_details details of the conflict just
      #   unwound from
      # @return [void]
      def filter_possibilities_after_unwind(unwind_details)
        return unless state && !state.possibilities.empty?

        if unwind_details.unwinding_to_primary_requirement?
          filter_possibilities_for_primary_unwind(unwind_details)
        else
          filter_possibilities_for_parent_unwind(unwind_details)
        end
      end

      # Filter's a state's possibilities to remove any that would not satisfy
      # the requirements in the conflict we've just rewound from
      # @param [UnwindDetails] unwind_details details of the conflict just unwound from
      # @return [void]
      def filter_possibilities_for_primary_unwind(unwind_details)
        unwinds_to_state = unused_unwind_options.select { |uw| uw.state_index == unwind_details.state_index }
        unwinds_to_state << unwind_details
        unwind_requirement_sets = unwinds_to_state.map(&:conflicting_requirements)

        state.possibilities.reject! do |possibility_set|
          possibility_set.possibilities.none? do |poss|
            unwind_requirement_sets.any? do |requirements|
              possibility_satisfies_requirements?(poss, requirements)
            end
          end
        end
      end

      # @param [Object] possibility a single possibility
      # @param [Array] requirements an array of requirements
      # @return [Boolean] whether the possibility satisfies all of the
      #    given requirements
      def possibility_satisfies_requirements?(possibility, requirements)
        name = name_for(possibility)

        activated.tag(:swap)
        activated.set_payload(name, possibility) if activated.vertex_named(name)
        satisfied = requirements.all? { |r| requirement_satisfied_by?(r, activated, possibility) }
        activated.rewind_to(:swap)

        satisfied
      end

      # Filter's a state's possibilities to remove any that would (eventually)
      # create a requirement in the conflict we've just rewound from
      # @param [UnwindDetails] unwind_details details of the conflict just unwound from
      # @return [void]
      def filter_possibilities_for_parent_unwind(unwind_details)
        unwinds_to_state = unused_unwind_options.select { |uw| uw.state_index == unwind_details.state_index }
        unwinds_to_state << unwind_details

        primary_unwinds = unwinds_to_state.select(&:unwinding_to_primary_requirement?).uniq
        parent_unwinds = unwinds_to_state.uniq - primary_unwinds

        allowed_possibility_sets = primary_unwinds.flat_map do |unwind|
          states[unwind.state_index].possibilities.select do |possibility_set|
            possibility_set.possibilities.any? do |poss|
              possibility_satisfies_requirements?(poss, unwind.conflicting_requirements)
            end
          end
        end

        requirements_to_avoid = parent_unwinds.flat_map(&:sub_dependencies_to_avoid)

        state.possibilities.reject! do |possibility_set|
          !allowed_possibility_sets.include?(possibility_set) &&
            (requirements_to_avoid - possibility_set.dependencies).empty?
        end
      end

      # @param [Conflict] conflict
      # @return [Array] minimal array of requirements that would cause the passed
      #    conflict to occur.
      def binding_requirements_for_conflict(conflict)
        return [conflict.requirement] if conflict.possibility.nil?

        possible_binding_requirements = conflict.requirements.values.flatten(1).uniq

        # When there's a `CircularDependency` error the conflicting requirement
        # (the one causing the circular) won't be `conflict.requirement`
        # (which won't be for the right state, because we won't have created it,
        # because it's circular).
        # We need to make sure we have that requirement in the conflict's list,
        # otherwise we won't be able to unwind properly, so we just return all
        # the requirements for the conflict.
        return possible_binding_requirements if conflict.underlying_error

        possibilities = search_for(conflict.requirement)

        # If all the requirements together don't filter out all possibilities,
        # then the only two requirements we need to consider are the initial one
        # (where the dependency's version was first chosen) and the last
        if binding_requirement_in_set?(nil, possible_binding_requirements, possibilities)
          return [conflict.requirement, requirement_for_existing_name(name_for(conflict.requirement))].compact
        end

        # Loop through the possible binding requirements, removing each one
        # that doesn't bind. Use a `reverse_each` as we want the earliest set of
        # binding requirements, and don't use `reject!` as we wish to refine the
        # array *on each iteration*.
        binding_requirements = possible_binding_requirements.dup
        possible_binding_requirements.reverse_each do |req|
          next if req == conflict.requirement
          unless binding_requirement_in_set?(req, binding_requirements, possibilities)
            binding_requirements -= [req]
          end
        end

        binding_requirements
      end

      # @param [Object] requirement we wish to check
      # @param [Array] possible_binding_requirements array of requirements
      # @param [Array] possibilities array of possibilities the requirements will be used to filter
      # @return [Boolean] whether or not the given requirement is required to filter
      #    out all elements of the array of possibilities.
      def binding_requirement_in_set?(requirement, possible_binding_requirements, possibilities)
        possibilities.any? do |poss|
          possibility_satisfies_requirements?(poss, possible_binding_requirements - [requirement])
        end
      end

      # @param [Object] requirement
      # @return [Object] the requirement that led to `requirement` being added
      #   to the list of requirements.
      def parent_of(requirement)
        return unless requirement
        return unless index = @parents_of[requirement].last
        return unless parent_state = @states[index]
        parent_state.requirement
      end

      # @param [String] name
      # @return [Object] the requirement that led to a version of a possibility
      #   with the given name being activated.
      def requirement_for_existing_name(name)
        return nil unless vertex = activated.vertex_named(name)
        return nil unless vertex.payload
        states.find { |s| s.name == name }.requirement
      end

      # @param [Object] requirement
      # @return [ResolutionState] the state whose `requirement` is the given
      #   `requirement`.
      def find_state_for(requirement)
        return nil unless requirement
        states.find { |i| requirement == i.requirement }
      end

      # @param [Object] underlying_error
      # @return [Conflict] a {Conflict} that reflects the failure to activate
      #   the {#possibility} in conjunction with the current {#state}
      def create_conflict(underlying_error = nil)
        vertex = activated.vertex_named(name)
        locked_requirement = locked_requirement_named(name)

        requirements = {}
        unless vertex.explicit_requirements.empty?
          requirements[name_for_explicit_dependency_source] = vertex.explicit_requirements
        end
        requirements[name_for_locking_dependency_source] = [locked_requirement] if locked_requirement
        vertex.incoming_edges.each do |edge|
          (requirements[edge.origin.payload.latest_version] ||= []).unshift(edge.requirement)
        end

        activated_by_name = {}
        activated.each { |v| activated_by_name[v.name] = v.payload.latest_version if v.payload }
        conflicts[name] = Conflict.new(
          requirement,
          requirements,
          vertex.payload && vertex.payload.latest_version,
          possibility,
          locked_requirement,
          requirement_trees,
          activated_by_name,
          underlying_error
        )
      end

      # @return [Array<Array<Object>>] The different requirement
      #   trees that led to every requirement for the current spec.
      def requirement_trees
        vertex = activated.vertex_named(name)
        vertex.requirements.map { |r| requirement_tree_for(r) }
      end

      # @param [Object] requirement
      # @return [Array<Object>] the list of requirements that led to
      #   `requirement` being required.
      def requirement_tree_for(requirement)
        tree = []
        while requirement
          tree.unshift(requirement)
          requirement = parent_of(requirement)
        end
        tree
      end

      # Indicates progress roughly once every second
      # @return [void]
      def indicate_progress
        @iteration_counter += 1
        @progress_rate ||= resolver_ui.progress_rate
        if iteration_rate.nil?
          if Time.now - started_at >= @progress_rate
            self.iteration_rate = @iteration_counter
          end
        end

        if iteration_rate && (@iteration_counter % iteration_rate) == 0
          resolver_ui.indicate_progress
        end
      end

      # Calls the {#resolver_ui}'s {UI#debug} method
      # @param [Integer] depth the depth of the {#states} stack
      # @param [Proc] block a block that yields a {#to_s}
      # @return [void]
      def debug(depth = 0, &block)
        resolver_ui.debug(depth, &block)
      end

      # Attempts to activate the current {#possibility}
      # @return [void]
      def attempt_to_activate
        debug(depth) { 'Attempting to activate ' + possibility.to_s }
        existing_vertex = activated.vertex_named(name)
        if existing_vertex.payload
          debug(depth) { "Found existing spec (#{existing_vertex.payload})" }
          attempt_to_filter_existing_spec(existing_vertex)
        else
          latest = possibility.latest_version
          possibility.possibilities.select! do |possibility|
            requirement_satisfied_by?(requirement, activated, possibility)
          end
          if possibility.latest_version.nil?
            # ensure there's a possibility for better error messages
            possibility.possibilities << latest if latest
            create_conflict
            unwind_for_conflict
          else
            activate_new_spec
          end
        end
      end

      # Attempts to update the existing vertex's `PossibilitySet` with a filtered version
      # @return [void]
      def attempt_to_filter_existing_spec(vertex)
        filtered_set = filtered_possibility_set(vertex)
        if !filtered_set.possibilities.empty?
          activated.set_payload(name, filtered_set)
          new_requirements = requirements.dup
          push_state_for_requirements(new_requirements, false)
        else
          create_conflict
          debug(depth) { "Unsatisfied by existing spec (#{vertex.payload})" }
          unwind_for_conflict
        end
      end

      # Generates a filtered version of the existing vertex's `PossibilitySet` using the
      # current state's `requirement`
      # @param [Object] vertex existing vertex
      # @return [PossibilitySet] filtered possibility set
      def filtered_possibility_set(vertex)
        PossibilitySet.new(vertex.payload.dependencies, vertex.payload.possibilities & possibility.possibilities)
      end

      # @param [String] requirement_name the spec name to search for
      # @return [Object] the locked spec named `requirement_name`, if one
      #   is found on {#base}
      def locked_requirement_named(requirement_name)
        vertex = base.vertex_named(requirement_name)
        vertex && vertex.payload
      end

      # Add the current {#possibility} to the dependency graph of the current
      # {#state}
      # @return [void]
      def activate_new_spec
        conflicts.delete(name)
        debug(depth) { "Activated #{name} at #{possibility}" }
        activated.set_payload(name, possibility)
        require_nested_dependencies_for(possibility)
      end

      # Requires the dependencies that the recently activated spec has
      # @param [Object] possibility_set the PossibilitySet that has just been
      #   activated
      # @return [void]
      def require_nested_dependencies_for(possibility_set)
        nested_dependencies = dependencies_for(possibility_set.latest_version)
        debug(depth) { "Requiring nested dependencies (#{nested_dependencies.join(', ')})" }
        nested_dependencies.each do |d|
          activated.add_child_vertex(name_for(d), nil, [name_for(possibility_set.latest_version)], d)
          parent_index = states.size - 1
          parents = @parents_of[d]
          parents << parent_index if parents.empty?
        end

        push_state_for_requirements(requirements + nested_dependencies, !nested_dependencies.empty?)
      end

      # Pushes a new {DependencyState} that encapsulates both existing and new
      # requirements
      # @param [Array] new_requirements
      # @param [Boolean] requires_sort
      # @param [Object] new_activated
      # @return [void]
      def push_state_for_requirements(new_requirements, requires_sort = true, new_activated = activated)
        new_requirements = sort_dependencies(new_requirements.uniq, new_activated, conflicts) if requires_sort
        new_requirement = nil
        loop do
          new_requirement = new_requirements.shift
          break if new_requirement.nil? || states.none? { |s| s.requirement == new_requirement }
        end
        new_name = new_requirement ? name_for(new_requirement) : ''.freeze
        possibilities = possibilities_for_requirement(new_requirement)
        handle_missing_or_push_dependency_state DependencyState.new(
          new_name, new_requirements, new_activated,
          new_requirement, possibilities, depth, conflicts.dup, unused_unwind_options.dup
        )
      end

      # Checks a proposed requirement with any existing locked requirement
      # before generating an array of possibilities for it.
      # @param [Object] requirement the proposed requirement
      # @param [Object] activated
      # @return [Array] possibilities
      def possibilities_for_requirement(requirement, activated = self.activated)
        return [] unless requirement
        if locked_requirement_named(name_for(requirement))
          return locked_requirement_possibility_set(requirement, activated)
        end

        group_possibilities(search_for(requirement))
      end

      # @param [Object] requirement the proposed requirement
      # @param [Object] activated
      # @return [Array] possibility set containing only the locked requirement, if any
      def locked_requirement_possibility_set(requirement, activated = self.activated)
        all_possibilities = search_for(requirement)
        locked_requirement = locked_requirement_named(name_for(requirement))

        # Longwinded way to build a possibilities array with either the locked
        # requirement or nothing in it. Required, since the API for
        # locked_requirement isn't guaranteed.
        locked_possibilities = all_possibilities.select do |possibility|
          requirement_satisfied_by?(locked_requirement, activated, possibility)
        end

        group_possibilities(locked_possibilities)
      end

      # Build an array of PossibilitySets, with each element representing a group of
      # dependency versions that all have the same sub-dependency version constraints
      # and are contiguous.
      # @param [Array] possibilities an array of possibilities
      # @return [Array<PossibilitySet>] an array of possibility sets
      def group_possibilities(possibilities)
        possibility_sets = []
        current_possibility_set = nil

        possibilities.reverse_each do |possibility|
          dependencies = dependencies_for(possibility)
          if current_possibility_set && dependencies_equal?(current_possibility_set.dependencies, dependencies)
            current_possibility_set.possibilities.unshift(possibility)
          else
            possibility_sets.unshift(PossibilitySet.new(dependencies, [possibility]))
            current_possibility_set = possibility_sets.first
          end
        end

        possibility_sets
      end

      # Pushes a new {DependencyState}.
      # If the {#specification_provider} says to
      # {SpecificationProvider#allow_missing?} that particular requirement, and
      # there are no possibilities for that requirement, then `state` is not
      # pushed, and the vertex in {#activated} is removed, and we continue
      # resolving the remaining requirements.
      # @param [DependencyState] state
      # @return [void]
      def handle_missing_or_push_dependency_state(state)
        if state.requirement && state.possibilities.empty? && allow_missing?(state.requirement)
          state.activated.detach_vertex_named(state.name)
          push_state_for_requirements(state.requirements.dup, false, state.activated)
        else
          states.push(state).tap { activated.tag(state) }
        end
      end
    end
  end
end
# frozen_string_literal: true

require_relative 'action'
module Bundler::Molinillo
  class DependencyGraph
    # @!visibility private
    # (see DependencyGraph#add_edge_no_circular)
    class AddEdgeNoCircular < Action
      # @!group Action

      # (see Action.action_name)
      def self.action_name
        :add_vertex
      end

      # (see Action#up)
      def up(graph)
        edge = make_edge(graph)
        edge.origin.outgoing_edges << edge
        edge.destination.incoming_edges << edge
        edge
      end

      # (see Action#down)
      def down(graph)
        edge = make_edge(graph)
        delete_first(edge.origin.outgoing_edges, edge)
        delete_first(edge.destination.incoming_edges, edge)
      end

      # @!group AddEdgeNoCircular

      # @return [String] the name of the origin of the edge
      attr_reader :origin

      # @return [String] the name of the destination of the edge
      attr_reader :destination

      # @return [Object] the requirement that the edge represents
      attr_reader :requirement

      # @param  [DependencyGraph] graph the graph to find vertices from
      # @return [Edge] The edge this action adds
      def make_edge(graph)
        Edge.new(graph.vertex_named(origin), graph.vertex_named(destination), requirement)
      end

      # Initialize an action to add an edge to a dependency graph
      # @param [String] origin the name of the origin of the edge
      # @param [String] destination the name of the destination of the edge
      # @param [Object] requirement the requirement that the edge represents
      def initialize(origin, destination, requirement)
        @origin = origin
        @destination = destination
        @requirement = requirement
      end

      private

      def delete_first(array, item)
        return unless index = array.index(item)
        array.delete_at(index)
      end
    end
  end
end
# frozen_string_literal: true

require_relative 'action'
module Bundler::Molinillo
  class DependencyGraph
    # @!visibility private
    # @see DependencyGraph#set_payload
    class SetPayload < Action # :nodoc:
      # @!group Action

      # (see Action.action_name)
      def self.action_name
        :set_payload
      end

      # (see Action#up)
      def up(graph)
        vertex = graph.vertex_named(name)
        @old_payload = vertex.payload
        vertex.payload = payload
      end

      # (see Action#down)
      def down(graph)
        graph.vertex_named(name).payload = @old_payload
      end

      # @!group SetPayload

      # @return [String] the name of the vertex
      attr_reader :name

      # @return [Object] the payload for the vertex
      attr_reader :payload

      # Initialize an action to add set the payload for a vertex in a dependency
      # graph
      # @param [String] name the name of the vertex
      # @param [Object] payload the payload for the vertex
      def initialize(name, payload)
        @name = name
        @payload = payload
      end
    end
  end
end
# frozen_string_literal: true

module Bundler::Molinillo
  class DependencyGraph
    # An action that modifies a {DependencyGraph} that is reversible.
    # @abstract
    class Action
      # rubocop:disable Lint/UnusedMethodArgument

      # @return [Symbol] The name of the action.
      def self.action_name
        raise 'Abstract'
      end

      # Performs the action on the given graph.
      # @param  [DependencyGraph] graph the graph to perform the action on.
      # @return [Void]
      def up(graph)
        raise 'Abstract'
      end

      # Reverses the action on the given graph.
      # @param  [DependencyGraph] graph the graph to reverse the action on.
      # @return [Void]
      def down(graph)
        raise 'Abstract'
      end

      # @return [Action,Nil] The previous action
      attr_accessor :previous

      # @return [Action,Nil] The next action
      attr_accessor :next
    end
  end
end
# frozen_string_literal: true

require_relative 'action'
module Bundler::Molinillo
  class DependencyGraph
    # @!visibility private
    # (see DependencyGraph#delete_edge)
    class DeleteEdge < Action
      # @!group Action

      # (see Action.action_name)
      def self.action_name
        :delete_edge
      end

      # (see Action#up)
      def up(graph)
        edge = make_edge(graph)
        edge.origin.outgoing_edges.delete(edge)
        edge.destination.incoming_edges.delete(edge)
      end

      # (see Action#down)
      def down(graph)
        edge = make_edge(graph)
        edge.origin.outgoing_edges << edge
        edge.destination.incoming_edges << edge
        edge
      end

      # @!group DeleteEdge

      # @return [String] the name of the origin of the edge
      attr_reader :origin_name

      # @return [String] the name of the destination of the edge
      attr_reader :destination_name

      # @return [Object] the requirement that the edge represents
      attr_reader :requirement

      # @param  [DependencyGraph] graph the graph to find vertices from
      # @return [Edge] The edge this action adds
      def make_edge(graph)
        Edge.new(
          graph.vertex_named(origin_name),
          graph.vertex_named(destination_name),
          requirement
        )
      end

      # Initialize an action to add an edge to a dependency graph
      # @param [String] origin_name the name of the origin of the edge
      # @param [String] destination_name the name of the destination of the edge
      # @param [Object] requirement the requirement that the edge represents
      def initialize(origin_name, destination_name, requirement)
        @origin_name = origin_name
        @destination_name = destination_name
        @requirement = requirement
      end
    end
  end
end
# frozen_string_literal: true

require_relative 'action'
module Bundler::Molinillo
  class DependencyGraph
    # @!visibility private
    # @see DependencyGraph#tag
    class Tag < Action
      # @!group Action

      # (see Action.action_name)
      def self.action_name
        :tag
      end

      # (see Action#up)
      def up(graph)
      end

      # (see Action#down)
      def down(graph)
      end

      # @!group Tag

      # @return [Object] An opaque tag
      attr_reader :tag

      # Initialize an action to tag a state of a dependency graph
      # @param [Object] tag an opaque tag
      def initialize(tag)
        @tag = tag
      end
    end
  end
end
# frozen_string_literal: true

require_relative 'action'
module Bundler::Molinillo
  class DependencyGraph
    # @!visibility private
    # @see DependencyGraph#detach_vertex_named
    class DetachVertexNamed < Action
      # @!group Action

      # (see Action#name)
      def self.action_name
        :add_vertex
      end

      # (see Action#up)
      def up(graph)
        return [] unless @vertex = graph.vertices.delete(name)

        removed_vertices = [@vertex]
        @vertex.outgoing_edges.each do |e|
          v = e.destination
          v.incoming_edges.delete(e)
          if !v.root? && v.incoming_edges.empty?
            removed_vertices.concat graph.detach_vertex_named(v.name)
          end
        end

        @vertex.incoming_edges.each do |e|
          v = e.origin
          v.outgoing_edges.delete(e)
        end

        removed_vertices
      end

      # (see Action#down)
      def down(graph)
        return unless @vertex
        graph.vertices[@vertex.name] = @vertex
        @vertex.outgoing_edges.each do |e|
          e.destination.incoming_edges << e
        end
        @vertex.incoming_edges.each do |e|
          e.origin.outgoing_edges << e
        end
      end

      # @!group DetachVertexNamed

      # @return [String] the name of the vertex to detach
      attr_reader :name

      # Initialize an action to detach a vertex from a dependency graph
      # @param [String] name the name of the vertex to detach
      def initialize(name)
        @name = name
      end
    end
  end
end
# frozen_string_literal: true

require_relative 'action'
module Bundler::Molinillo
  class DependencyGraph
    # @!visibility private
    # (see DependencyGraph#add_vertex)
    class AddVertex < Action # :nodoc:
      # @!group Action

      # (see Action.action_name)
      def self.action_name
        :add_vertex
      end

      # (see Action#up)
      def up(graph)
        if existing = graph.vertices[name]
          @existing_payload = existing.payload
          @existing_root = existing.root
        end
        vertex = existing || Vertex.new(name, payload)
        graph.vertices[vertex.name] = vertex
        vertex.payload ||= payload
        vertex.root ||= root
        vertex
      end

      # (see Action#down)
      def down(graph)
        if defined?(@existing_payload)
          vertex = graph.vertices[name]
          vertex.payload = @existing_payload
          vertex.root = @existing_root
        else
          graph.vertices.delete(name)
        end
      end

      # @!group AddVertex

      # @return [String] the name of the vertex
      attr_reader :name

      # @return [Object] the payload for the vertex
      attr_reader :payload

      # @return [Boolean] whether the vertex is root or not
      attr_reader :root

      # Initialize an action to add a vertex to a dependency graph
      # @param [String] name the name of the vertex
      # @param [Object] payload the payload for the vertex
      # @param [Boolean] root whether the vertex is root or not
      def initialize(name, payload, root)
        @name = name
        @payload = payload
        @root = root
      end
    end
  end
end
# frozen_string_literal: true

require_relative 'add_edge_no_circular'
require_relative 'add_vertex'
require_relative 'delete_edge'
require_relative 'detach_vertex_named'
require_relative 'set_payload'
require_relative 'tag'

module Bundler::Molinillo
  class DependencyGraph
    # A log for dependency graph actions
    class Log
      # Initializes an empty log
      def initialize
        @current_action = @first_action = nil
      end

      # @!macro [new] action
      #   {include:DependencyGraph#$0}
      #   @param [Graph] graph the graph to perform the action on
      #   @param (see DependencyGraph#$0)
      #   @return (see DependencyGraph#$0)

      # @macro action
      def tag(graph, tag)
        push_action(graph, Tag.new(tag))
      end

      # @macro action
      def add_vertex(graph, name, payload, root)
        push_action(graph, AddVertex.new(name, payload, root))
      end

      # @macro action
      def detach_vertex_named(graph, name)
        push_action(graph, DetachVertexNamed.new(name))
      end

      # @macro action
      def add_edge_no_circular(graph, origin, destination, requirement)
        push_action(graph, AddEdgeNoCircular.new(origin, destination, requirement))
      end

      # {include:DependencyGraph#delete_edge}
      # @param [Graph] graph the graph to perform the action on
      # @param [String] origin_name
      # @param [String] destination_name
      # @param [Object] requirement
      # @return (see DependencyGraph#delete_edge)
      def delete_edge(graph, origin_name, destination_name, requirement)
        push_action(graph, DeleteEdge.new(origin_name, destination_name, requirement))
      end

      # @macro action
      def set_payload(graph, name, payload)
        push_action(graph, SetPayload.new(name, payload))
      end

      # Pops the most recent action from the log and undoes the action
      # @param [DependencyGraph] graph
      # @return [Action] the action that was popped off the log
      def pop!(graph)
        return unless action = @current_action
        unless @current_action = action.previous
          @first_action = nil
        end
        action.down(graph)
        action
      end

      extend Enumerable

      # @!visibility private
      # Enumerates each action in the log
      # @yield [Action]
      def each
        return enum_for unless block_given?
        action = @first_action
        loop do
          break unless action
          yield action
          action = action.next
        end
        self
      end

      # @!visibility private
      # Enumerates each action in the log in reverse order
      # @yield [Action]
      def reverse_each
        return enum_for(:reverse_each) unless block_given?
        action = @current_action
        loop do
          break unless action
          yield action
          action = action.previous
        end
        self
      end

      # @macro action
      def rewind_to(graph, tag)
        loop do
          action = pop!(graph)
          raise "No tag #{tag.inspect} found" unless action
          break if action.class.action_name == :tag && action.tag == tag
        end
      end

      private

      # Adds the given action to the log, running the action
      # @param [DependencyGraph] graph
      # @param [Action] action
      # @return The value returned by `action.up`
      def push_action(graph, action)
        action.previous = @current_action
        @current_action.next = action if @current_action
        @current_action = action
        @first_action ||= action
        action.up(graph)
      end
    end
  end
end
# frozen_string_literal: true

module Bundler::Molinillo
  class DependencyGraph
    # A vertex in a {DependencyGraph} that encapsulates a {#name} and a
    # {#payload}
    class Vertex
      # @return [String] the name of the vertex
      attr_accessor :name

      # @return [Object] the payload the vertex holds
      attr_accessor :payload

      # @return [Array<Object>] the explicit requirements that required
      #   this vertex
      attr_reader :explicit_requirements

      # @return [Boolean] whether the vertex is considered a root vertex
      attr_accessor :root
      alias root? root

      # Initializes a vertex with the given name and payload.
      # @param [String] name see {#name}
      # @param [Object] payload see {#payload}
      def initialize(name, payload)
        @name = name.frozen? ? name : name.dup.freeze
        @payload = payload
        @explicit_requirements = []
        @outgoing_edges = []
        @incoming_edges = []
      end

      # @return [Array<Object>] all of the requirements that required
      #   this vertex
      def requirements
        (incoming_edges.map(&:requirement) + explicit_requirements).uniq
      end

      # @return [Array<Edge>] the edges of {#graph} that have `self` as their
      #   {Edge#origin}
      attr_accessor :outgoing_edges

      # @return [Array<Edge>] the edges of {#graph} that have `self` as their
      #   {Edge#destination}
      attr_accessor :incoming_edges

      # @return [Array<Vertex>] the vertices of {#graph} that have an edge with
      #   `self` as their {Edge#destination}
      def predecessors
        incoming_edges.map(&:origin)
      end

      # @return [Set<Vertex>] the vertices of {#graph} where `self` is a
      #   {#descendent?}
      def recursive_predecessors
        _recursive_predecessors
      end

      # @param [Set<Vertex>] vertices the set to add the predecessors to
      # @return [Set<Vertex>] the vertices of {#graph} where `self` is a
      #   {#descendent?}
      def _recursive_predecessors(vertices = new_vertex_set)
        incoming_edges.each do |edge|
          vertex = edge.origin
          next unless vertices.add?(vertex)
          vertex._recursive_predecessors(vertices)
        end

        vertices
      end
      protected :_recursive_predecessors

      # @return [Array<Vertex>] the vertices of {#graph} that have an edge with
      #   `self` as their {Edge#origin}
      def successors
        outgoing_edges.map(&:destination)
      end

      # @return [Set<Vertex>] the vertices of {#graph} where `self` is an
      #   {#ancestor?}
      def recursive_successors
        _recursive_successors
      end

      # @param [Set<Vertex>] vertices the set to add the successors to
      # @return [Set<Vertex>] the vertices of {#graph} where `self` is an
      #   {#ancestor?}
      def _recursive_successors(vertices = new_vertex_set)
        outgoing_edges.each do |edge|
          vertex = edge.destination
          next unless vertices.add?(vertex)
          vertex._recursive_successors(vertices)
        end

        vertices
      end
      protected :_recursive_successors

      # @return [String] a string suitable for debugging
      def inspect
        "#{self.class}:#{name}(#{payload.inspect})"
      end

      # @return [Boolean] whether the two vertices are equal, determined
      #   by a recursive traversal of each {Vertex#successors}
      def ==(other)
        return true if equal?(other)
        shallow_eql?(other) &&
          successors.to_set == other.successors.to_set
      end

      # @param  [Vertex] other the other vertex to compare to
      # @return [Boolean] whether the two vertices are equal, determined
      #   solely by {#name} and {#payload} equality
      def shallow_eql?(other)
        return true if equal?(other)
        other &&
          name == other.name &&
          payload == other.payload
      end

      alias eql? ==

      # @return [Fixnum] a hash for the vertex based upon its {#name}
      def hash
        name.hash
      end

      # Is there a path from `self` to `other` following edges in the
      # dependency graph?
      # @return whether there is a path following edges within this {#graph}
      def path_to?(other)
        _path_to?(other)
      end

      alias descendent? path_to?

      # @param [Vertex] other the vertex to check if there's a path to
      # @param [Set<Vertex>] visited the vertices of {#graph} that have been visited
      # @return [Boolean] whether there is a path to `other` from `self`
      def _path_to?(other, visited = new_vertex_set)
        return false unless visited.add?(self)
        return true if equal?(other)
        successors.any? { |v| v._path_to?(other, visited) }
      end
      protected :_path_to?

      # Is there a path from `other` to `self` following edges in the
      # dependency graph?
      # @return whether there is a path following edges within this {#graph}
      def ancestor?(other)
        other.path_to?(self)
      end

      alias is_reachable_from? ancestor?

      def new_vertex_set
        require 'set'
        Set.new
      end
      private :new_vertex_set
    end
  end
end
# frozen_string_literal: true

require_relative 'dependency_graph'

module Bundler::Molinillo
  # This class encapsulates a dependency resolver.
  # The resolver is responsible for determining which set of dependencies to
  # activate, with feedback from the {#specification_provider}
  #
  #
  class Resolver
    require_relative 'resolution'

    # @return [SpecificationProvider] the specification provider used
    #   in the resolution process
    attr_reader :specification_provider

    # @return [UI] the UI module used to communicate back to the user
    #   during the resolution process
    attr_reader :resolver_ui

    # Initializes a new resolver.
    # @param  [SpecificationProvider] specification_provider
    #   see {#specification_provider}
    # @param  [UI] resolver_ui
    #   see {#resolver_ui}
    def initialize(specification_provider, resolver_ui)
      @specification_provider = specification_provider
      @resolver_ui = resolver_ui
    end

    # Resolves the requested dependencies into a {DependencyGraph},
    # locking to the base dependency graph (if specified)
    # @param [Array] requested an array of 'requested' dependencies that the
    #   {#specification_provider} can understand
    # @param [DependencyGraph,nil] base the base dependency graph to which
    #   dependencies should be 'locked'
    def resolve(requested, base = DependencyGraph.new)
      Resolution.new(specification_provider,
                     resolver_ui,
                     requested,
                     base).
        resolve
    end
  end
end
# frozen_string_literal: true

module Bundler::Molinillo
  # An error that occurred during the resolution process
  class ResolverError < StandardError; end

  # An error caused by searching for a dependency that is completely unknown,
  # i.e. has no versions available whatsoever.
  class NoSuchDependencyError < ResolverError
    # @return [Object] the dependency that could not be found
    attr_accessor :dependency

    # @return [Array<Object>] the specifications that depended upon {#dependency}
    attr_accessor :required_by

    # Initializes a new error with the given missing dependency.
    # @param [Object] dependency @see {#dependency}
    # @param [Array<Object>] required_by @see {#required_by}
    def initialize(dependency, required_by = [])
      @dependency = dependency
      @required_by = required_by.uniq
      super()
    end

    # The error message for the missing dependency, including the specifications
    # that had this dependency.
    def message
      sources = required_by.map { |r| "`#{r}`" }.join(' and ')
      message = "Unable to find a specification for `#{dependency}`"
      message += " depended upon by #{sources}" unless sources.empty?
      message
    end
  end

  # An error caused by attempting to fulfil a dependency that was circular
  #
  # @note This exception will be thrown if and only if a {Vertex} is added to a
  #   {DependencyGraph} that has a {DependencyGraph::Vertex#path_to?} an
  #   existing {DependencyGraph::Vertex}
  class CircularDependencyError < ResolverError
    # [Set<Object>] the dependencies responsible for causing the error
    attr_reader :dependencies

    # Initializes a new error with the given circular vertices.
    # @param [Array<DependencyGraph::Vertex>] vertices the vertices in the dependency
    #   that caused the error
    def initialize(vertices)
      super "There is a circular dependency between #{vertices.map(&:name).join(' and ')}"
      @dependencies = vertices.map { |vertex| vertex.payload.possibilities.last }.to_set
    end
  end

  # An error caused by conflicts in version
  class VersionConflict < ResolverError
    # @return [{String => Resolution::Conflict}] the conflicts that caused
    #   resolution to fail
    attr_reader :conflicts

    # @return [SpecificationProvider] the specification provider used during
    #   resolution
    attr_reader :specification_provider

    # Initializes a new error with the given version conflicts.
    # @param [{String => Resolution::Conflict}] conflicts see {#conflicts}
    # @param [SpecificationProvider] specification_provider see {#specification_provider}
    def initialize(conflicts, specification_provider)
      pairs = []
      conflicts.values.flat_map(&:requirements).each do |conflicting|
        conflicting.each do |source, conflict_requirements|
          conflict_requirements.each do |c|
            pairs << [c, source]
          end
        end
      end

      super "Unable to satisfy the following requirements:\n\n" \
        "#{pairs.map { |r, d| "- `#{r}` required by `#{d}`" }.join("\n")}"

      @conflicts = conflicts
      @specification_provider = specification_provider
    end

    require_relative 'delegates/specification_provider'
    include Delegates::SpecificationProvider

    # @return [String] An error message that includes requirement trees,
    #   which is much more detailed & customizable than the default message
    # @param [Hash] opts the options to create a message with.
    # @option opts [String] :solver_name The user-facing name of the solver
    # @option opts [String] :possibility_type The generic name of a possibility
    # @option opts [Proc] :reduce_trees A proc that reduced the list of requirement trees
    # @option opts [Proc] :printable_requirement A proc that pretty-prints requirements
    # @option opts [Proc] :additional_message_for_conflict A proc that appends additional
    #   messages for each conflict
    # @option opts [Proc] :version_for_spec A proc that returns the version number for a
    #   possibility
    def message_with_trees(opts = {})
      solver_name = opts.delete(:solver_name) { self.class.name.split('::').first }
      possibility_type = opts.delete(:possibility_type) { 'possibility named' }
      reduce_trees = opts.delete(:reduce_trees) { proc { |trees| trees.uniq.sort_by(&:to_s) } }
      printable_requirement = opts.delete(:printable_requirement) { proc { |req| req.to_s } }
      additional_message_for_conflict = opts.delete(:additional_message_for_conflict) { proc {} }
      version_for_spec = opts.delete(:version_for_spec) { proc(&:to_s) }
      incompatible_version_message_for_conflict = opts.delete(:incompatible_version_message_for_conflict) do
        proc do |name, _conflict|
          %(#{solver_name} could not find compatible versions for #{possibility_type} "#{name}":)
        end
      end

      conflicts.sort.reduce(''.dup) do |o, (name, conflict)|
        o << "\n" << incompatible_version_message_for_conflict.call(name, conflict) << "\n"
        if conflict.locked_requirement
          o << %(  In snapshot (#{name_for_locking_dependency_source}):\n)
          o << %(    #{printable_requirement.call(conflict.locked_requirement)}\n)
          o << %(\n)
        end
        o << %(  In #{name_for_explicit_dependency_source}:\n)
        trees = reduce_trees.call(conflict.requirement_trees)

        o << trees.map do |tree|
          t = ''.dup
          depth = 2
          tree.each do |req|
            t << '  ' * depth << printable_requirement.call(req)
            unless tree.last == req
              if spec = conflict.activated_by_name[name_for(req)]
                t << %( was resolved to #{version_for_spec.call(spec)}, which)
              end
              t << %( depends on)
            end
            t << %(\n)
            depth += 1
          end
          t
        end.join("\n")

        additional_message_for_conflict.call(o, name, conflict)

        o
      end.strip
    end
  end
end
# frozen_string_literal: true

module Bundler::Molinillo
  # @!visibility private
  module Delegates
    # Delegates all {Bundler::Molinillo::ResolutionState} methods to a `#state` property.
    module ResolutionState
      # (see Bundler::Molinillo::ResolutionState#name)
      def name
        current_state = state || Bundler::Molinillo::ResolutionState.empty
        current_state.name
      end

      # (see Bundler::Molinillo::ResolutionState#requirements)
      def requirements
        current_state = state || Bundler::Molinillo::ResolutionState.empty
        current_state.requirements
      end

      # (see Bundler::Molinillo::ResolutionState#activated)
      def activated
        current_state = state || Bundler::Molinillo::ResolutionState.empty
        current_state.activated
      end

      # (see Bundler::Molinillo::ResolutionState#requirement)
      def requirement
        current_state = state || Bundler::Molinillo::ResolutionState.empty
        current_state.requirement
      end

      # (see Bundler::Molinillo::ResolutionState#possibilities)
      def possibilities
        current_state = state || Bundler::Molinillo::ResolutionState.empty
        current_state.possibilities
      end

      # (see Bundler::Molinillo::ResolutionState#depth)
      def depth
        current_state = state || Bundler::Molinillo::ResolutionState.empty
        current_state.depth
      end

      # (see Bundler::Molinillo::ResolutionState#conflicts)
      def conflicts
        current_state = state || Bundler::Molinillo::ResolutionState.empty
        current_state.conflicts
      end

      # (see Bundler::Molinillo::ResolutionState#unused_unwind_options)
      def unused_unwind_options
        current_state = state || Bundler::Molinillo::ResolutionState.empty
        current_state.unused_unwind_options
      end
    end
  end
end
# frozen_string_literal: true

module Bundler::Molinillo
  module Delegates
    # Delegates all {Bundler::Molinillo::SpecificationProvider} methods to a
    # `#specification_provider` property.
    module SpecificationProvider
      # (see Bundler::Molinillo::SpecificationProvider#search_for)
      def search_for(dependency)
        with_no_such_dependency_error_handling do
          specification_provider.search_for(dependency)
        end
      end

      # (see Bundler::Molinillo::SpecificationProvider#dependencies_for)
      def dependencies_for(specification)
        with_no_such_dependency_error_handling do
          specification_provider.dependencies_for(specification)
        end
      end

      # (see Bundler::Molinillo::SpecificationProvider#requirement_satisfied_by?)
      def requirement_satisfied_by?(requirement, activated, spec)
        with_no_such_dependency_error_handling do
          specification_provider.requirement_satisfied_by?(requirement, activated, spec)
        end
      end

      # (see Bundler::Molinillo::SpecificationProvider#dependencies_equal?)
      def dependencies_equal?(dependencies, other_dependencies)
        with_no_such_dependency_error_handling do
          specification_provider.dependencies_equal?(dependencies, other_dependencies)
        end
      end

      # (see Bundler::Molinillo::SpecificationProvider#name_for)
      def name_for(dependency)
        with_no_such_dependency_error_handling do
          specification_provider.name_for(dependency)
        end
      end

      # (see Bundler::Molinillo::SpecificationProvider#name_for_explicit_dependency_source)
      def name_for_explicit_dependency_source
        with_no_such_dependency_error_handling do
          specification_provider.name_for_explicit_dependency_source
        end
      end

      # (see Bundler::Molinillo::SpecificationProvider#name_for_locking_dependency_source)
      def name_for_locking_dependency_source
        with_no_such_dependency_error_handling do
          specification_provider.name_for_locking_dependency_source
        end
      end

      # (see Bundler::Molinillo::SpecificationProvider#sort_dependencies)
      def sort_dependencies(dependencies, activated, conflicts)
        with_no_such_dependency_error_handling do
          specification_provider.sort_dependencies(dependencies, activated, conflicts)
        end
      end

      # (see Bundler::Molinillo::SpecificationProvider#allow_missing?)
      def allow_missing?(dependency)
        with_no_such_dependency_error_handling do
          specification_provider.allow_missing?(dependency)
        end
      end

      private

      # Ensures any raised {NoSuchDependencyError} has its
      # {NoSuchDependencyError#required_by} set.
      # @yield
      def with_no_such_dependency_error_handling
        yield
      rescue NoSuchDependencyError => error
        if state
          vertex = activated.vertex_named(name_for(error.dependency))
          error.required_by += vertex.incoming_edges.map { |e| e.origin.name }
          error.required_by << name_for_explicit_dependency_source unless vertex.explicit_requirements.empty?
        end
        raise
      end
    end
  end
end
# frozen_string_literal: true

module Bundler::Molinillo
  # The version of Bundler::Molinillo.
  VERSION = '0.7.0'.freeze
end
# frozen_string_literal: true

module Bundler::Molinillo
  # Conveys information about the resolution process to a user.
  module UI
    # The {IO} object that should be used to print output. `STDOUT`, by default.
    #
    # @return [IO]
    def output
      STDOUT
    end

    # Called roughly every {#progress_rate}, this method should convey progress
    # to the user.
    #
    # @return [void]
    def indicate_progress
      output.print '.' unless debug?
    end

    # How often progress should be conveyed to the user via
    # {#indicate_progress}, in seconds. A third of a second, by default.
    #
    # @return [Float]
    def progress_rate
      0.33
    end

    # Called before resolution begins.
    #
    # @return [void]
    def before_resolution
      output.print 'Resolving dependencies...'
    end

    # Called after resolution ends (either successfully or with an error).
    # By default, prints a newline.
    #
    # @return [void]
    def after_resolution
      output.puts
    end

    # Conveys debug information to the user.
    #
    # @param [Integer] depth the current depth of the resolution process.
    # @return [void]
    def debug(depth = 0)
      if debug?
        debug_info = yield
        debug_info = debug_info.inspect unless debug_info.is_a?(String)
        debug_info = debug_info.split("\n").map { |s| ":#{depth.to_s.rjust 4}: #{s}" }
        output.puts debug_info
      end
    end

    # Whether or not debug messages should be printed.
    # By default, whether or not the `MOLINILLO_DEBUG` environment variable is
    # set.
    #
    # @return [Boolean]
    def debug?
      return @debug_mode if defined?(@debug_mode)
      @debug_mode = ENV['MOLINILLO_DEBUG']
    end
  end
end
# frozen_string_literal: true

module Bundler::Molinillo
  # Provides information about specifications and dependencies to the resolver,
  # allowing the {Resolver} class to remain generic while still providing power
  # and flexibility.
  #
  # This module contains the methods that users of Bundler::Molinillo must to implement,
  # using knowledge of their own model classes.
  module SpecificationProvider
    # Search for the specifications that match the given dependency.
    # The specifications in the returned array will be considered in reverse
    # order, so the latest version ought to be last.
    # @note This method should be 'pure', i.e. the return value should depend
    #   only on the `dependency` parameter.
    #
    # @param [Object] dependency
    # @return [Array<Object>] the specifications that satisfy the given
    #   `dependency`.
    def search_for(dependency)
      []
    end

    # Returns the dependencies of `specification`.
    # @note This method should be 'pure', i.e. the return value should depend
    #   only on the `specification` parameter.
    #
    # @param [Object] specification
    # @return [Array<Object>] the dependencies that are required by the given
    #   `specification`.
    def dependencies_for(specification)
      []
    end

    # Determines whether the given `requirement` is satisfied by the given
    # `spec`, in the context of the current `activated` dependency graph.
    #
    # @param [Object] requirement
    # @param [DependencyGraph] activated the current dependency graph in the
    #   resolution process.
    # @param [Object] spec
    # @return [Boolean] whether `requirement` is satisfied by `spec` in the
    #   context of the current `activated` dependency graph.
    def requirement_satisfied_by?(requirement, activated, spec)
      true
    end

    # Determines whether two arrays of dependencies are equal, and thus can be
    # grouped.
    #
    # @param [Array<Object>] dependencies
    # @param [Array<Object>] other_dependencies
    # @return [Boolean] whether `dependencies` and `other_dependencies` should
    #   be considered equal.
    def dependencies_equal?(dependencies, other_dependencies)
      dependencies == other_dependencies
    end

    # Returns the name for the given `dependency`.
    # @note This method should be 'pure', i.e. the return value should depend
    #   only on the `dependency` parameter.
    #
    # @param [Object] dependency
    # @return [String] the name for the given `dependency`.
    def name_for(dependency)
      dependency.to_s
    end

    # @return [String] the name of the source of explicit dependencies, i.e.
    #   those passed to {Resolver#resolve} directly.
    def name_for_explicit_dependency_source
      'user-specified dependency'
    end

    # @return [String] the name of the source of 'locked' dependencies, i.e.
    #   those passed to {Resolver#resolve} directly as the `base`
    def name_for_locking_dependency_source
      'Lockfile'
    end

    # Sort dependencies so that the ones that are easiest to resolve are first.
    # Easiest to resolve is (usually) defined by:
    #   1) Is this dependency already activated?
    #   2) How relaxed are the requirements?
    #   3) Are there any conflicts for this dependency?
    #   4) How many possibilities are there to satisfy this dependency?
    #
    # @param [Array<Object>] dependencies
    # @param [DependencyGraph] activated the current dependency graph in the
    #   resolution process.
    # @param [{String => Array<Conflict>}] conflicts
    # @return [Array<Object>] a sorted copy of `dependencies`.
    def sort_dependencies(dependencies, activated, conflicts)
      dependencies.sort_by do |dependency|
        name = name_for(dependency)
        [
          activated.vertex_named(name).payload ? 0 : 1,
          conflicts[name] ? 0 : 1,
        ]
      end
    end

    # Returns whether this dependency, which has no possible matching
    # specifications, can safely be ignored.
    #
    # @param [Object] dependency
    # @return [Boolean] whether this dependency can safely be skipped.
    def allow_missing?(dependency)
      false
    end
  end
end
# frozen_string_literal: true

module Bundler::Molinillo
  # A state that a {Resolution} can be in
  # @attr [String] name the name of the current requirement
  # @attr [Array<Object>] requirements currently unsatisfied requirements
  # @attr [DependencyGraph] activated the graph of activated dependencies
  # @attr [Object] requirement the current requirement
  # @attr [Object] possibilities the possibilities to satisfy the current requirement
  # @attr [Integer] depth the depth of the resolution
  # @attr [Hash] conflicts unresolved conflicts, indexed by dependency name
  # @attr [Array<UnwindDetails>] unused_unwind_options unwinds for previous conflicts that weren't explored
  ResolutionState = Struct.new(
    :name,
    :requirements,
    :activated,
    :requirement,
    :possibilities,
    :depth,
    :conflicts,
    :unused_unwind_options
  )

  class ResolutionState
    # Returns an empty resolution state
    # @return [ResolutionState] an empty state
    def self.empty
      new(nil, [], DependencyGraph.new, nil, nil, 0, {}, [])
    end
  end

  # A state that encapsulates a set of {#requirements} with an {Array} of
  # possibilities
  class DependencyState < ResolutionState
    # Removes a possibility from `self`
    # @return [PossibilityState] a state with a single possibility,
    #  the possibility that was removed from `self`
    def pop_possibility_state
      PossibilityState.new(
        name,
        requirements.dup,
        activated,
        requirement,
        [possibilities.pop],
        depth + 1,
        conflicts.dup,
        unused_unwind_options.dup
      ).tap do |state|
        state.activated.tag(state)
      end
    end
  end

  # A state that encapsulates a single possibility to fulfill the given
  # {#requirement}
  class PossibilityState < ResolutionState
  end
end
# frozen_string_literal: true

#--
# tsort.rb - provides a module for topological sorting and strongly connected components.
#++
#

#
# TSort implements topological sorting using Tarjan's algorithm for
# strongly connected components.
#
# TSort is designed to be able to be used with any object which can be
# interpreted as a directed graph.
#
# TSort requires two methods to interpret an object as a graph,
# tsort_each_node and tsort_each_child.
#
# * tsort_each_node is used to iterate for all nodes over a graph.
# * tsort_each_child is used to iterate for child nodes of a given node.
#
# The equality of nodes are defined by eql? and hash since
# TSort uses Hash internally.
#
# == A Simple Example
#
# The following example demonstrates how to mix the TSort module into an
# existing class (in this case, Hash). Here, we're treating each key in
# the hash as a node in the graph, and so we simply alias the required
# #tsort_each_node method to Hash's #each_key method. For each key in the
# hash, the associated value is an array of the node's child nodes. This
# choice in turn leads to our implementation of the required #tsort_each_child
# method, which fetches the array of child nodes and then iterates over that
# array using the user-supplied block.
#
#   require 'tsort'
#
#   class Hash
#     include TSort
#     alias tsort_each_node each_key
#     def tsort_each_child(node, &block)
#       fetch(node).each(&block)
#     end
#   end
#
#   {1=>[2, 3], 2=>[3], 3=>[], 4=>[]}.tsort
#   #=> [3, 2, 1, 4]
#
#   {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}.strongly_connected_components
#   #=> [[4], [2, 3], [1]]
#
# == A More Realistic Example
#
# A very simple `make' like tool can be implemented as follows:
#
#   require 'tsort'
#
#   class Make
#     def initialize
#       @dep = {}
#       @dep.default = []
#     end
#
#     def rule(outputs, inputs=[], &block)
#       triple = [outputs, inputs, block]
#       outputs.each {|f| @dep[f] = [triple]}
#       @dep[triple] = inputs
#     end
#
#     def build(target)
#       each_strongly_connected_component_from(target) {|ns|
#         if ns.length != 1
#           fs = ns.delete_if {|n| Array === n}
#           raise TSort::Cyclic.new("cyclic dependencies: #{fs.join ', '}")
#         end
#         n = ns.first
#         if Array === n
#           outputs, inputs, block = n
#           inputs_time = inputs.map {|f| File.mtime f}.max
#           begin
#             outputs_time = outputs.map {|f| File.mtime f}.min
#           rescue Errno::ENOENT
#             outputs_time = nil
#           end
#           if outputs_time == nil ||
#              inputs_time != nil && outputs_time <= inputs_time
#             sleep 1 if inputs_time != nil && inputs_time.to_i == Time.now.to_i
#             block.call
#           end
#         end
#       }
#     end
#
#     def tsort_each_child(node, &block)
#       @dep[node].each(&block)
#     end
#     include TSort
#   end
#
#   def command(arg)
#     print arg, "\n"
#     system arg
#   end
#
#   m = Make.new
#   m.rule(%w[t1]) { command 'date > t1' }
#   m.rule(%w[t2]) { command 'date > t2' }
#   m.rule(%w[t3]) { command 'date > t3' }
#   m.rule(%w[t4], %w[t1 t3]) { command 'cat t1 t3 > t4' }
#   m.rule(%w[t5], %w[t4 t2]) { command 'cat t4 t2 > t5' }
#   m.build('t5')
#
# == Bugs
#
# * 'tsort.rb' is wrong name because this library uses
#   Tarjan's algorithm for strongly connected components.
#   Although 'strongly_connected_components.rb' is correct but too long.
#
# == References
#
# R. E. Tarjan, "Depth First Search and Linear Graph Algorithms",
# <em>SIAM Journal on Computing</em>, Vol. 1, No. 2, pp. 146-160, June 1972.
#
module Bundler
  module TSort
    class Cyclic < StandardError
    end

    # Returns a topologically sorted array of nodes.
    # The array is sorted from children to parents, i.e.
    # the first element has no child and the last node has no parent.
    #
    # If there is a cycle, TSort::Cyclic is raised.
    #
    #   class G
    #     include TSort
    #     def initialize(g)
    #       @g = g
    #     end
    #     def tsort_each_child(n, &b) @g[n].each(&b) end
    #     def tsort_each_node(&b) @g.each_key(&b) end
    #   end
    #
    #   graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
    #   p graph.tsort #=> [4, 2, 3, 1]
    #
    #   graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
    #   p graph.tsort # raises TSort::Cyclic
    #
    def tsort
      each_node = method(:tsort_each_node)
      each_child = method(:tsort_each_child)
      TSort.tsort(each_node, each_child)
    end

    # Returns a topologically sorted array of nodes.
    # The array is sorted from children to parents, i.e.
    # the first element has no child and the last node has no parent.
    #
    # The graph is represented by _each_node_ and _each_child_.
    # _each_node_ should have +call+ method which yields for each node in the graph.
    # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
    #
    # If there is a cycle, TSort::Cyclic is raised.
    #
    #   g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
    #   each_node = lambda {|&b| g.each_key(&b) }
    #   each_child = lambda {|n, &b| g[n].each(&b) }
    #   p TSort.tsort(each_node, each_child) #=> [4, 2, 3, 1]
    #
    #   g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
    #   each_node = lambda {|&b| g.each_key(&b) }
    #   each_child = lambda {|n, &b| g[n].each(&b) }
    #   p TSort.tsort(each_node, each_child) # raises TSort::Cyclic
    #
    def TSort.tsort(each_node, each_child)
      TSort.tsort_each(each_node, each_child).to_a
    end

    # The iterator version of the #tsort method.
    # <tt><em>obj</em>.tsort_each</tt> is similar to <tt><em>obj</em>.tsort.each</tt>, but
    # modification of _obj_ during the iteration may lead to unexpected results.
    #
    # #tsort_each returns +nil+.
    # If there is a cycle, TSort::Cyclic is raised.
    #
    #   class G
    #     include TSort
    #     def initialize(g)
    #       @g = g
    #     end
    #     def tsort_each_child(n, &b) @g[n].each(&b) end
    #     def tsort_each_node(&b) @g.each_key(&b) end
    #   end
    #
    #   graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
    #   graph.tsort_each {|n| p n }
    #   #=> 4
    #   #   2
    #   #   3
    #   #   1
    #
    def tsort_each(&block) # :yields: node
      each_node = method(:tsort_each_node)
      each_child = method(:tsort_each_child)
      TSort.tsort_each(each_node, each_child, &block)
    end

    # The iterator version of the TSort.tsort method.
    #
    # The graph is represented by _each_node_ and _each_child_.
    # _each_node_ should have +call+ method which yields for each node in the graph.
    # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
    #
    #   g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
    #   each_node = lambda {|&b| g.each_key(&b) }
    #   each_child = lambda {|n, &b| g[n].each(&b) }
    #   TSort.tsort_each(each_node, each_child) {|n| p n }
    #   #=> 4
    #   #   2
    #   #   3
    #   #   1
    #
    def TSort.tsort_each(each_node, each_child) # :yields: node
      return to_enum(__method__, each_node, each_child) unless block_given?

      TSort.each_strongly_connected_component(each_node, each_child) {|component|
        if component.size == 1
          yield component.first
        else
          raise Cyclic.new("topological sort failed: #{component.inspect}")
        end
      }
    end

    # Returns strongly connected components as an array of arrays of nodes.
    # The array is sorted from children to parents.
    # Each elements of the array represents a strongly connected component.
    #
    #   class G
    #     include TSort
    #     def initialize(g)
    #       @g = g
    #     end
    #     def tsort_each_child(n, &b) @g[n].each(&b) end
    #     def tsort_each_node(&b) @g.each_key(&b) end
    #   end
    #
    #   graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
    #   p graph.strongly_connected_components #=> [[4], [2], [3], [1]]
    #
    #   graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
    #   p graph.strongly_connected_components #=> [[4], [2, 3], [1]]
    #
    def strongly_connected_components
      each_node = method(:tsort_each_node)
      each_child = method(:tsort_each_child)
      TSort.strongly_connected_components(each_node, each_child)
    end

    # Returns strongly connected components as an array of arrays of nodes.
    # The array is sorted from children to parents.
    # Each elements of the array represents a strongly connected component.
    #
    # The graph is represented by _each_node_ and _each_child_.
    # _each_node_ should have +call+ method which yields for each node in the graph.
    # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
    #
    #   g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
    #   each_node = lambda {|&b| g.each_key(&b) }
    #   each_child = lambda {|n, &b| g[n].each(&b) }
    #   p TSort.strongly_connected_components(each_node, each_child)
    #   #=> [[4], [2], [3], [1]]
    #
    #   g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
    #   each_node = lambda {|&b| g.each_key(&b) }
    #   each_child = lambda {|n, &b| g[n].each(&b) }
    #   p TSort.strongly_connected_components(each_node, each_child)
    #   #=> [[4], [2, 3], [1]]
    #
    def TSort.strongly_connected_components(each_node, each_child)
      TSort.each_strongly_connected_component(each_node, each_child).to_a
    end

    # The iterator version of the #strongly_connected_components method.
    # <tt><em>obj</em>.each_strongly_connected_component</tt> is similar to
    # <tt><em>obj</em>.strongly_connected_components.each</tt>, but
    # modification of _obj_ during the iteration may lead to unexpected results.
    #
    # #each_strongly_connected_component returns +nil+.
    #
    #   class G
    #     include TSort
    #     def initialize(g)
    #       @g = g
    #     end
    #     def tsort_each_child(n, &b) @g[n].each(&b) end
    #     def tsort_each_node(&b) @g.each_key(&b) end
    #   end
    #
    #   graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
    #   graph.each_strongly_connected_component {|scc| p scc }
    #   #=> [4]
    #   #   [2]
    #   #   [3]
    #   #   [1]
    #
    #   graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
    #   graph.each_strongly_connected_component {|scc| p scc }
    #   #=> [4]
    #   #   [2, 3]
    #   #   [1]
    #
    def each_strongly_connected_component(&block) # :yields: nodes
      each_node = method(:tsort_each_node)
      each_child = method(:tsort_each_child)
      TSort.each_strongly_connected_component(each_node, each_child, &block)
    end

    # The iterator version of the TSort.strongly_connected_components method.
    #
    # The graph is represented by _each_node_ and _each_child_.
    # _each_node_ should have +call+ method which yields for each node in the graph.
    # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
    #
    #   g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
    #   each_node = lambda {|&b| g.each_key(&b) }
    #   each_child = lambda {|n, &b| g[n].each(&b) }
    #   TSort.each_strongly_connected_component(each_node, each_child) {|scc| p scc }
    #   #=> [4]
    #   #   [2]
    #   #   [3]
    #   #   [1]
    #
    #   g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
    #   each_node = lambda {|&b| g.each_key(&b) }
    #   each_child = lambda {|n, &b| g[n].each(&b) }
    #   TSort.each_strongly_connected_component(each_node, each_child) {|scc| p scc }
    #   #=> [4]
    #   #   [2, 3]
    #   #   [1]
    #
    def TSort.each_strongly_connected_component(each_node, each_child) # :yields: nodes
      return to_enum(__method__, each_node, each_child) unless block_given?

      id_map = {}
      stack = []
      each_node.call {|node|
        unless id_map.include? node
          TSort.each_strongly_connected_component_from(node, each_child, id_map, stack) {|c|
            yield c
          }
        end
      }
      nil
    end

    # Iterates over strongly connected component in the subgraph reachable from
    # _node_.
    #
    # Return value is unspecified.
    #
    # #each_strongly_connected_component_from doesn't call #tsort_each_node.
    #
    #   class G
    #     include TSort
    #     def initialize(g)
    #       @g = g
    #     end
    #     def tsort_each_child(n, &b) @g[n].each(&b) end
    #     def tsort_each_node(&b) @g.each_key(&b) end
    #   end
    #
    #   graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
    #   graph.each_strongly_connected_component_from(2) {|scc| p scc }
    #   #=> [4]
    #   #   [2]
    #
    #   graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
    #   graph.each_strongly_connected_component_from(2) {|scc| p scc }
    #   #=> [4]
    #   #   [2, 3]
    #
    def each_strongly_connected_component_from(node, id_map={}, stack=[], &block) # :yields: nodes
      TSort.each_strongly_connected_component_from(node, method(:tsort_each_child), id_map, stack, &block)
    end

    # Iterates over strongly connected components in a graph.
    # The graph is represented by _node_ and _each_child_.
    #
    # _node_ is the first node.
    # _each_child_ should have +call+ method which takes a node argument
    # and yields for each child node.
    #
    # Return value is unspecified.
    #
    # #TSort.each_strongly_connected_component_from is a class method and
    # it doesn't need a class to represent a graph which includes TSort.
    #
    #   graph = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
    #   each_child = lambda {|n, &b| graph[n].each(&b) }
    #   TSort.each_strongly_connected_component_from(1, each_child) {|scc|
    #     p scc
    #   }
    #   #=> [4]
    #   #   [2, 3]
    #   #   [1]
    #
    def TSort.each_strongly_connected_component_from(node, each_child, id_map={}, stack=[]) # :yields: nodes
      return to_enum(__method__, node, each_child, id_map, stack) unless block_given?

      minimum_id = node_id = id_map[node] = id_map.size
      stack_length = stack.length
      stack << node

      each_child.call(node) {|child|
        if id_map.include? child
          child_id = id_map[child]
          minimum_id = child_id if child_id && child_id < minimum_id
        else
          sub_minimum_id =
            TSort.each_strongly_connected_component_from(child, each_child, id_map, stack) {|c|
              yield c
            }
          minimum_id = sub_minimum_id if sub_minimum_id < minimum_id
        end
      }

      if node_id == minimum_id
        component = stack.slice!(stack_length .. -1)
        component.each {|n| id_map[n] = nil}
        yield component
      end

      minimum_id
    end

    # Should be implemented by a extended class.
    #
    # #tsort_each_node is used to iterate for all nodes over a graph.
    #
    def tsort_each_node # :yields: node
      raise NotImplementedError.new
    end

    # Should be implemented by a extended class.
    #
    # #tsort_each_child is used to iterate for child nodes of _node_.
    #
    def tsort_each_child(node) # :yields: child
      raise NotImplementedError.new
    end
  end
end
# frozen_string_literal: true
#
# tmpdir - retrieve temporary directory path
#
# $Id$
#

require_relative '../../fileutils/lib/fileutils'
begin
  require 'etc.so'
rescue LoadError # rescue LoadError for miniruby
end

class Bundler::Dir < Dir

  @systmpdir ||= defined?(Etc.systmpdir) ? Etc.systmpdir : '/tmp'

  ##
  # Returns the operating system's temporary file path.

  def self.tmpdir
    tmp = nil
    ['TMPDIR', 'TMP', 'TEMP', ['system temporary path', @systmpdir], ['/tmp']*2, ['.']*2].each do |name, dir = ENV[name]|
      next if !dir
      dir = File.expand_path(dir)
      stat = File.stat(dir) rescue next
      case
      when !stat.directory?
        warn "#{name} is not a directory: #{dir}"
      when !stat.writable?
        warn "#{name} is not writable: #{dir}"
      when stat.world_writable? && !stat.sticky?
        warn "#{name} is world-writable: #{dir}"
      else
        tmp = dir
        break
      end
    end
    raise ArgumentError, "could not find a temporary directory" unless tmp
    tmp
  end

  # Bundler::Dir.mktmpdir creates a temporary directory.
  #
  # The directory is created with 0700 permission.
  # Application should not change the permission to make the temporary directory accessible from other users.
  #
  # The prefix and suffix of the name of the directory is specified by
  # the optional first argument, <i>prefix_suffix</i>.
  # - If it is not specified or nil, "d" is used as the prefix and no suffix is used.
  # - If it is a string, it is used as the prefix and no suffix is used.
  # - If it is an array, first element is used as the prefix and second element is used as a suffix.
  #
  #  Bundler::Dir.mktmpdir {|dir| dir is ".../d..." }
  #  Bundler::Dir.mktmpdir("foo") {|dir| dir is ".../foo..." }
  #  Bundler::Dir.mktmpdir(["foo", "bar"]) {|dir| dir is ".../foo...bar" }
  #
  # The directory is created under Bundler::Dir.tmpdir or
  # the optional second argument <i>tmpdir</i> if non-nil value is given.
  #
  #  Bundler::Dir.mktmpdir {|dir| dir is "#{Bundler::Dir.tmpdir}/d..." }
  #  Bundler::Dir.mktmpdir(nil, "/var/tmp") {|dir| dir is "/var/tmp/d..." }
  #
  # If a block is given,
  # it is yielded with the path of the directory.
  # The directory and its contents are removed
  # using Bundler::FileUtils.remove_entry before Bundler::Dir.mktmpdir returns.
  # The value of the block is returned.
  #
  #  Bundler::Dir.mktmpdir {|dir|
  #    # use the directory...
  #    open("#{dir}/foo", "w") { ... }
  #  }
  #
  # If a block is not given,
  # The path of the directory is returned.
  # In this case, Bundler::Dir.mktmpdir doesn't remove the directory.
  #
  #  dir = Bundler::Dir.mktmpdir
  #  begin
  #    # use the directory...
  #    open("#{dir}/foo", "w") { ... }
  #  ensure
  #    # remove the directory.
  #    Bundler::FileUtils.remove_entry dir
  #  end
  #
  def self.mktmpdir(prefix_suffix=nil, *rest, **options)
    base = nil
    path = Tmpname.create(prefix_suffix || "d", *rest, **options) {|p, _, _, d|
      base = d
      mkdir(p, 0700)
    }
    if block_given?
      begin
        yield path.dup
      ensure
        unless base
          stat = File.stat(File.dirname(path))
          if stat.world_writable? and !stat.sticky?
            raise ArgumentError, "parent directory is world writable but not sticky"
          end
        end
        Bundler::FileUtils.remove_entry path
      end
    else
      path
    end
  end

  module Tmpname # :nodoc:
    module_function

    def tmpdir
      Bundler::Dir.tmpdir
    end

    UNUSABLE_CHARS = "^,-.0-9A-Z_a-z~"

    class << (RANDOM = Random.new)
      MAX = 36**6 # < 0x100000000
      def next
        rand(MAX).to_s(36)
      end
    end
    private_constant :RANDOM

    def create(basename, tmpdir=nil, max_try: nil, **opts)
      origdir = tmpdir
      tmpdir ||= tmpdir()
      n = nil
      prefix, suffix = basename
      prefix = (String.try_convert(prefix) or
                raise ArgumentError, "unexpected prefix: #{prefix.inspect}")
      prefix = prefix.delete(UNUSABLE_CHARS)
      suffix &&= (String.try_convert(suffix) or
                  raise ArgumentError, "unexpected suffix: #{suffix.inspect}")
      suffix &&= suffix.delete(UNUSABLE_CHARS)
      begin
        t = Time.now.strftime("%Y%m%d")
        path = "#{prefix}#{t}-#{$$}-#{RANDOM.next}"\
               "#{n ? %[-#{n}] : ''}#{suffix||''}"
        path = File.join(tmpdir, path)
        yield(path, n, opts, origdir)
      rescue Errno::EEXIST
        n ||= 0
        n += 1
        retry if !max_try or n < max_try
        raise "cannot generate temporary name using `#{basename}' under `#{tmpdir}'"
      end
      path
    end
  end
end
Copyright (c) 2011 Mike Perham

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 Bundler::ConnectionPool
  class Wrapper < ::BasicObject
    METHODS = [:with, :pool_shutdown, :wrapped_pool]

    def initialize(options = {}, &block)
      @pool = options.fetch(:pool) { ::Bundler::ConnectionPool.new(options, &block) }
    end

    def wrapped_pool
      @pool
    end

    def with(&block)
      @pool.with(&block)
    end

    def pool_shutdown(&block)
      @pool.shutdown(&block)
    end

    def pool_size
      @pool.size
    end

    def pool_available
      @pool.available
    end

    def respond_to?(id, *args)
      METHODS.include?(id) || with { |c| c.respond_to?(id, *args) }
    end

    # rubocop:disable Style/MethodMissingSuper
    # rubocop:disable Style/MissingRespondToMissing
    if ::RUBY_VERSION >= "3.0.0"
      def method_missing(name, *args, **kwargs, &block)
        with do |connection|
          connection.send(name, *args, **kwargs, &block)
        end
      end
    elsif ::RUBY_VERSION >= "2.7.0"
      ruby2_keywords def method_missing(name, *args, &block)
        with do |connection|
          connection.send(name, *args, &block)
        end
      end
    else
      def method_missing(name, *args, &block)
        with do |connection|
          connection.send(name, *args, &block)
        end
      end
    end
    # rubocop:enable Style/MethodMissingSuper
    # rubocop:enable Style/MissingRespondToMissing
  end
end
##
# The TimedStack manages a pool of homogeneous connections (or any resource
# you wish to manage).  Connections are created lazily up to a given maximum
# number.

# Examples:
#
#    ts = TimedStack.new(1) { MyConnection.new }
#
#    # fetch a connection
#    conn = ts.pop
#
#    # return a connection
#    ts.push conn
#
#    conn = ts.pop
#    ts.pop timeout: 5
#    #=> raises Bundler::ConnectionPool::TimeoutError after 5 seconds

class Bundler::ConnectionPool::TimedStack
  attr_reader :max

  ##
  # Creates a new pool with +size+ connections that are created from the given
  # +block+.

  def initialize(size = 0, &block)
    @create_block = block
    @created = 0
    @que = []
    @max = size
    @mutex = Thread::Mutex.new
    @resource = Thread::ConditionVariable.new
    @shutdown_block = nil
  end

  ##
  # Returns +obj+ to the stack.  +options+ is ignored in TimedStack but may be
  # used by subclasses that extend TimedStack.

  def push(obj, options = {})
    @mutex.synchronize do
      if @shutdown_block
        @shutdown_block.call(obj)
      else
        store_connection obj, options
      end

      @resource.broadcast
    end
  end
  alias << push

  ##
  # Retrieves a connection from the stack.  If a connection is available it is
  # immediately returned.  If no connection is available within the given
  # timeout a Bundler::ConnectionPool::TimeoutError is raised.
  #
  # +:timeout+ is the only checked entry in +options+ and is preferred over
  # the +timeout+ argument (which will be removed in a future release).  Other
  # options may be used by subclasses that extend TimedStack.

  def pop(timeout = 0.5, options = {})
    options, timeout = timeout, 0.5 if Hash === timeout
    timeout = options.fetch :timeout, timeout

    deadline = current_time + timeout
    @mutex.synchronize do
      loop do
        raise Bundler::ConnectionPool::PoolShuttingDownError if @shutdown_block
        return fetch_connection(options) if connection_stored?(options)

        connection = try_create(options)
        return connection if connection

        to_wait = deadline - current_time
        raise Bundler::ConnectionPool::TimeoutError, "Waited #{timeout} sec" if to_wait <= 0
        @resource.wait(@mutex, to_wait)
      end
    end
  end

  ##
  # Shuts down the TimedStack by passing each connection to +block+ and then
  # removing it from the pool. Attempting to checkout a connection after
  # shutdown will raise +Bundler::ConnectionPool::PoolShuttingDownError+ unless
  # +:reload+ is +true+.

  def shutdown(reload: false, &block)
    raise ArgumentError, "shutdown must receive a block" unless block_given?

    @mutex.synchronize do
      @shutdown_block = block
      @resource.broadcast

      shutdown_connections
      @shutdown_block = nil if reload
    end
  end

  ##
  # Returns +true+ if there are no available connections.

  def empty?
    (@created - @que.length) >= @max
  end

  ##
  # The number of connections available on the stack.

  def length
    @max - @created + @que.length
  end

  private

  def current_time
    Process.clock_gettime(Process::CLOCK_MONOTONIC)
  end

  ##
  # This is an extension point for TimedStack and is called with a mutex.
  #
  # This method must returns true if a connection is available on the stack.

  def connection_stored?(options = nil)
    !@que.empty?
  end

  ##
  # This is an extension point for TimedStack and is called with a mutex.
  #
  # This method must return a connection from the stack.

  def fetch_connection(options = nil)
    @que.pop
  end

  ##
  # This is an extension point for TimedStack and is called with a mutex.
  #
  # This method must shut down all connections on the stack.

  def shutdown_connections(options = nil)
    while connection_stored?(options)
      conn = fetch_connection(options)
      @shutdown_block.call(conn)
    end
    @created = 0
  end

  ##
  # This is an extension point for TimedStack and is called with a mutex.
  #
  # This method must return +obj+ to the stack.

  def store_connection(obj, options = nil)
    @que.push obj
  end

  ##
  # This is an extension point for TimedStack and is called with a mutex.
  #
  # This method must create a connection if and only if the total number of
  # connections allowed has not been met.

  def try_create(options = nil)
    unless @created == @max
      object = @create_block.call
      @created += 1
      object
    end
  end
end
class Bundler::ConnectionPool
  VERSION = "2.3.0"
end
require "timeout"
require_relative "connection_pool/version"

class Bundler::ConnectionPool
  class Error < ::RuntimeError; end
  class PoolShuttingDownError < ::Bundler::ConnectionPool::Error; end
  class TimeoutError < ::Timeout::Error; end
end

# Generic connection pool class for sharing a limited number of objects or network connections
# among many threads.  Note: pool elements are lazily created.
#
# Example usage with block (faster):
#
#    @pool = Bundler::ConnectionPool.new { Redis.new }
#    @pool.with do |redis|
#      redis.lpop('my-list') if redis.llen('my-list') > 0
#    end
#
# Using optional timeout override (for that single invocation)
#
#    @pool.with(timeout: 2.0) do |redis|
#      redis.lpop('my-list') if redis.llen('my-list') > 0
#    end
#
# Example usage replacing an existing connection (slower):
#
#    $redis = Bundler::ConnectionPool.wrap { Redis.new }
#
#    def do_work
#      $redis.lpop('my-list') if $redis.llen('my-list') > 0
#    end
#
# Accepts the following options:
# - :size - number of connections to pool, defaults to 5
# - :timeout - amount of time to wait for a connection if none currently available, defaults to 5 seconds
#
class Bundler::ConnectionPool
  DEFAULTS = {size: 5, timeout: 5}

  def self.wrap(options, &block)
    Wrapper.new(options, &block)
  end

  def initialize(options = {}, &block)
    raise ArgumentError, "Connection pool requires a block" unless block

    options = DEFAULTS.merge(options)

    @size = Integer(options.fetch(:size))
    @timeout = options.fetch(:timeout)

    @available = TimedStack.new(@size, &block)
    @key = :"pool-#{@available.object_id}"
    @key_count = :"pool-#{@available.object_id}-count"
  end

  def with(options = {})
    Thread.handle_interrupt(Exception => :never) do
      conn = checkout(options)
      begin
        Thread.handle_interrupt(Exception => :immediate) do
          yield conn
        end
      ensure
        checkin
      end
    end
  end
  alias then with

  def checkout(options = {})
    if ::Thread.current[@key]
      ::Thread.current[@key_count] += 1
      ::Thread.current[@key]
    else
      ::Thread.current[@key_count] = 1
      ::Thread.current[@key] = @available.pop(options[:timeout] || @timeout)
    end
  end

  def checkin
    if ::Thread.current[@key]
      if ::Thread.current[@key_count] == 1
        @available.push(::Thread.current[@key])
        ::Thread.current[@key] = nil
        ::Thread.current[@key_count] = nil
      else
        ::Thread.current[@key_count] -= 1
      end
    else
      raise Bundler::ConnectionPool::Error, "no connections are checked out"
    end

    nil
  end

  ##
  # Shuts down the Bundler::ConnectionPool by passing each connection to +block+ and
  # then removing it from the pool. Attempting to checkout a connection after
  # shutdown will raise +Bundler::ConnectionPool::PoolShuttingDownError+.

  def shutdown(&block)
    @available.shutdown(&block)
  end

  ##
  # Reloads the Bundler::ConnectionPool by passing each connection to +block+ and then
  # removing it the pool. Subsequent checkouts will create new connections as
  # needed.

  def reload(&block)
    @available.shutdown(reload: true, &block)
  end

  # Size of this connection pool
  attr_reader :size

  # Number of pool entries available for checkout at this instant.
  def available
    @available.length
  end
end

require_relative "connection_pool/timed_stack"
require_relative "connection_pool/wrapper"
# frozen_string_literal: false
# Bundler::URI is a module providing classes to handle Uniform Resource Identifiers
# (RFC2396[http://tools.ietf.org/html/rfc2396]).
#
# == Features
#
# * Uniform way of handling URIs.
# * Flexibility to introduce custom Bundler::URI schemes.
# * Flexibility to have an alternate Bundler::URI::Parser (or just different patterns
#   and regexp's).
#
# == Basic example
#
#   require 'bundler/vendor/uri/lib/uri'
#
#   uri = Bundler::URI("http://foo.com/posts?id=30&limit=5#time=1305298413")
#   #=> #<Bundler::URI::HTTP http://foo.com/posts?id=30&limit=5#time=1305298413>
#
#   uri.scheme    #=> "http"
#   uri.host      #=> "foo.com"
#   uri.path      #=> "/posts"
#   uri.query     #=> "id=30&limit=5"
#   uri.fragment  #=> "time=1305298413"
#
#   uri.to_s      #=> "http://foo.com/posts?id=30&limit=5#time=1305298413"
#
# == Adding custom URIs
#
#   module Bundler::URI
#     class RSYNC < Generic
#       DEFAULT_PORT = 873
#     end
#     @@schemes['RSYNC'] = RSYNC
#   end
#   #=> Bundler::URI::RSYNC
#
#   Bundler::URI.scheme_list
#   #=> {"FILE"=>Bundler::URI::File, "FTP"=>Bundler::URI::FTP, "HTTP"=>Bundler::URI::HTTP,
#   #    "HTTPS"=>Bundler::URI::HTTPS, "LDAP"=>Bundler::URI::LDAP, "LDAPS"=>Bundler::URI::LDAPS,
#   #    "MAILTO"=>Bundler::URI::MailTo, "RSYNC"=>Bundler::URI::RSYNC}
#
#   uri = Bundler::URI("rsync://rsync.foo.com")
#   #=> #<Bundler::URI::RSYNC rsync://rsync.foo.com>
#
# == RFC References
#
# A good place to view an RFC spec is http://www.ietf.org/rfc.html.
#
# Here is a list of all related RFC's:
# - RFC822[http://tools.ietf.org/html/rfc822]
# - RFC1738[http://tools.ietf.org/html/rfc1738]
# - RFC2255[http://tools.ietf.org/html/rfc2255]
# - RFC2368[http://tools.ietf.org/html/rfc2368]
# - RFC2373[http://tools.ietf.org/html/rfc2373]
# - RFC2396[http://tools.ietf.org/html/rfc2396]
# - RFC2732[http://tools.ietf.org/html/rfc2732]
# - RFC3986[http://tools.ietf.org/html/rfc3986]
#
# == Class tree
#
# - Bundler::URI::Generic (in uri/generic.rb)
#   - Bundler::URI::File - (in uri/file.rb)
#   - Bundler::URI::FTP - (in uri/ftp.rb)
#   - Bundler::URI::HTTP - (in uri/http.rb)
#     - Bundler::URI::HTTPS - (in uri/https.rb)
#   - Bundler::URI::LDAP - (in uri/ldap.rb)
#     - Bundler::URI::LDAPS - (in uri/ldaps.rb)
#   - Bundler::URI::MailTo - (in uri/mailto.rb)
# - Bundler::URI::Parser - (in uri/common.rb)
# - Bundler::URI::REGEXP - (in uri/common.rb)
#   - Bundler::URI::REGEXP::PATTERN - (in uri/common.rb)
# - Bundler::URI::Util - (in uri/common.rb)
# - Bundler::URI::Escape - (in uri/common.rb)
# - Bundler::URI::Error - (in uri/common.rb)
#   - Bundler::URI::InvalidURIError - (in uri/common.rb)
#   - Bundler::URI::InvalidComponentError - (in uri/common.rb)
#   - Bundler::URI::BadURIError - (in uri/common.rb)
#
# == Copyright Info
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# Documentation::
#   Akira Yamada <akira@ruby-lang.org>
#   Dmitry V. Sabanin <sdmitry@lrn.ru>
#   Vincent Batts <vbatts@hashbangbash.com>
# License::
#  Copyright (c) 2001 akira yamada <akira@ruby-lang.org>
#  You can redistribute it and/or modify it under the same term as Ruby.
# Revision:: $Id$
#

module Bundler::URI
end

require_relative 'uri/version'
require_relative 'uri/common'
require_relative 'uri/generic'
require_relative 'uri/file'
require_relative 'uri/ftp'
require_relative 'uri/http'
require_relative 'uri/https'
require_relative 'uri/ldap'
require_relative 'uri/ldaps'
require_relative 'uri/mailto'
# frozen_string_literal: false
# = uri/ftp.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# License:: You can redistribute it and/or modify it under the same term as Ruby.
# Revision:: $Id$
#
# See Bundler::URI for general documentation
#

require_relative 'generic'

module Bundler::URI

  #
  # FTP Bundler::URI syntax is defined by RFC1738 section 3.2.
  #
  # This class will be redesigned because of difference of implementations;
  # the structure of its path. draft-hoffman-ftp-uri-04 is a draft but it
  # is a good summary about the de facto spec.
  # http://tools.ietf.org/html/draft-hoffman-ftp-uri-04
  #
  class FTP < Generic
    # A Default port of 21 for Bundler::URI::FTP.
    DEFAULT_PORT = 21

    #
    # An Array of the available components for Bundler::URI::FTP.
    #
    COMPONENT = [
      :scheme,
      :userinfo, :host, :port,
      :path, :typecode
    ].freeze

    #
    # Typecode is "a", "i", or "d".
    #
    # * "a" indicates a text file (the FTP command was ASCII)
    # * "i" indicates a binary file (FTP command IMAGE)
    # * "d" indicates the contents of a directory should be displayed
    #
    TYPECODE = ['a', 'i', 'd'].freeze

    # Typecode prefix ";type=".
    TYPECODE_PREFIX = ';type='.freeze

    def self.new2(user, password, host, port, path,
                  typecode = nil, arg_check = true) # :nodoc:
      # Do not use this method!  Not tested.  [Bug #7301]
      # This methods remains just for compatibility,
      # Keep it undocumented until the active maintainer is assigned.
      typecode = nil if typecode.size == 0
      if typecode && !TYPECODE.include?(typecode)
        raise ArgumentError,
          "bad typecode is specified: #{typecode}"
      end

      # do escape

      self.new('ftp',
               [user, password],
               host, port, nil,
               typecode ? path + TYPECODE_PREFIX + typecode : path,
               nil, nil, nil, arg_check)
    end

    #
    # == Description
    #
    # Creates a new Bundler::URI::FTP object from components, with syntax checking.
    #
    # The components accepted are +userinfo+, +host+, +port+, +path+, and
    # +typecode+.
    #
    # The components should be provided either as an Array, or as a Hash
    # with keys formed by preceding the component names with a colon.
    #
    # If an Array is used, the components must be passed in the
    # order <code>[userinfo, host, port, path, typecode]</code>.
    #
    # If the path supplied is absolute, it will be escaped in order to
    # make it absolute in the Bundler::URI.
    #
    # Examples:
    #
    #     require 'bundler/vendor/uri/lib/uri'
    #
    #     uri1 = Bundler::URI::FTP.build(['user:password', 'ftp.example.com', nil,
    #       '/path/file.zip', 'i'])
    #     uri1.to_s  # => "ftp://user:password@ftp.example.com/%2Fpath/file.zip;type=i"
    #
    #     uri2 = Bundler::URI::FTP.build({:host => 'ftp.example.com',
    #       :path => 'ruby/src'})
    #     uri2.to_s  # => "ftp://ftp.example.com/ruby/src"
    #
    def self.build(args)

      # Fix the incoming path to be generic URL syntax
      # FTP path  ->  URL path
      # foo/bar       /foo/bar
      # /foo/bar      /%2Ffoo/bar
      #
      if args.kind_of?(Array)
        args[3] = '/' + args[3].sub(/^\//, '%2F')
      else
        args[:path] = '/' + args[:path].sub(/^\//, '%2F')
      end

      tmp = Util::make_components_hash(self, args)

      if tmp[:typecode]
        if tmp[:typecode].size == 1
          tmp[:typecode] = TYPECODE_PREFIX + tmp[:typecode]
        end
        tmp[:path] << tmp[:typecode]
      end

      return super(tmp)
    end

    #
    # == Description
    #
    # Creates a new Bundler::URI::FTP object from generic URL components with no
    # syntax checking.
    #
    # Unlike build(), this method does not escape the path component as
    # required by RFC1738; instead it is treated as per RFC2396.
    #
    # Arguments are +scheme+, +userinfo+, +host+, +port+, +registry+, +path+,
    # +opaque+, +query+, and +fragment+, in that order.
    #
    def initialize(scheme,
                   userinfo, host, port, registry,
                   path, opaque,
                   query,
                   fragment,
                   parser = nil,
                   arg_check = false)
      raise InvalidURIError unless path
      path = path.sub(/^\//,'')
      path.sub!(/^%2F/,'/')
      super(scheme, userinfo, host, port, registry, path, opaque,
            query, fragment, parser, arg_check)
      @typecode = nil
      if tmp = @path.index(TYPECODE_PREFIX)
        typecode = @path[tmp + TYPECODE_PREFIX.size..-1]
        @path = @path[0..tmp - 1]

        if arg_check
          self.typecode = typecode
        else
          self.set_typecode(typecode)
        end
      end
    end

    # typecode accessor.
    #
    # See Bundler::URI::FTP::COMPONENT.
    attr_reader :typecode

    # Validates typecode +v+,
    # returns +true+ or +false+.
    #
    def check_typecode(v)
      if TYPECODE.include?(v)
        return true
      else
        raise InvalidComponentError,
          "bad typecode(expected #{TYPECODE.join(', ')}): #{v}"
      end
    end
    private :check_typecode

    # Private setter for the typecode +v+.
    #
    # See also Bundler::URI::FTP.typecode=.
    #
    def set_typecode(v)
      @typecode = v
    end
    protected :set_typecode

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the typecode +v+
    # (with validation).
    #
    # See also Bundler::URI::FTP.check_typecode.
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   uri = Bundler::URI.parse("ftp://john@ftp.example.com/my_file.img")
    #   #=> #<Bundler::URI::FTP ftp://john@ftp.example.com/my_file.img>
    #   uri.typecode = "i"
    #   uri
    #   #=> #<Bundler::URI::FTP ftp://john@ftp.example.com/my_file.img;type=i>
    #
    def typecode=(typecode)
      check_typecode(typecode)
      set_typecode(typecode)
      typecode
    end

    def merge(oth) # :nodoc:
      tmp = super(oth)
      if self != tmp
        tmp.set_typecode(oth.typecode)
      end

      return tmp
    end

    # Returns the path from an FTP Bundler::URI.
    #
    # RFC 1738 specifically states that the path for an FTP Bundler::URI does not
    # include the / which separates the Bundler::URI path from the Bundler::URI host. Example:
    #
    # <code>ftp://ftp.example.com/pub/ruby</code>
    #
    # The above Bundler::URI indicates that the client should connect to
    # ftp.example.com then cd to pub/ruby from the initial login directory.
    #
    # If you want to cd to an absolute directory, you must include an
    # escaped / (%2F) in the path. Example:
    #
    # <code>ftp://ftp.example.com/%2Fpub/ruby</code>
    #
    # This method will then return "/pub/ruby".
    #
    def path
      return @path.sub(/^\//,'').sub(/^%2F/,'/')
    end

    # Private setter for the path of the Bundler::URI::FTP.
    def set_path(v)
      super("/" + v.sub(/^\//, "%2F"))
    end
    protected :set_path

    # Returns a String representation of the Bundler::URI::FTP.
    def to_s
      save_path = nil
      if @typecode
        save_path = @path
        @path = @path + TYPECODE_PREFIX + @typecode
      end
      str = super
      if @typecode
        @path = save_path
      end

      return str
    end
  end
  @@schemes['FTP'] = FTP
end
# frozen_string_literal: false
# = uri/https.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# License:: You can redistribute it and/or modify it under the same term as Ruby.
# Revision:: $Id$
#
# See Bundler::URI for general documentation
#

require_relative 'http'

module Bundler::URI

  # The default port for HTTPS URIs is 443, and the scheme is 'https:' rather
  # than 'http:'. Other than that, HTTPS URIs are identical to HTTP URIs;
  # see Bundler::URI::HTTP.
  class HTTPS < HTTP
    # A Default port of 443 for Bundler::URI::HTTPS
    DEFAULT_PORT = 443
  end
  @@schemes['HTTPS'] = HTTPS
end
# frozen_string_literal: true

require_relative 'generic'

module Bundler::URI

  #
  # The "file" Bundler::URI is defined by RFC8089.
  #
  class File < Generic
    # A Default port of nil for Bundler::URI::File.
    DEFAULT_PORT = nil

    #
    # An Array of the available components for Bundler::URI::File.
    #
    COMPONENT = [
      :scheme,
      :host,
      :path
    ].freeze

    #
    # == Description
    #
    # Creates a new Bundler::URI::File object from components, with syntax checking.
    #
    # The components accepted are +host+ and +path+.
    #
    # The components should be provided either as an Array, or as a Hash
    # with keys formed by preceding the component names with a colon.
    #
    # If an Array is used, the components must be passed in the
    # order <code>[host, path]</code>.
    #
    # Examples:
    #
    #     require 'bundler/vendor/uri/lib/uri'
    #
    #     uri1 = Bundler::URI::File.build(['host.example.com', '/path/file.zip'])
    #     uri1.to_s  # => "file://host.example.com/path/file.zip"
    #
    #     uri2 = Bundler::URI::File.build({:host => 'host.example.com',
    #       :path => '/ruby/src'})
    #     uri2.to_s  # => "file://host.example.com/ruby/src"
    #
    def self.build(args)
      tmp = Util::make_components_hash(self, args)
      super(tmp)
    end

    # Protected setter for the host component +v+.
    #
    # See also Bundler::URI::Generic.host=.
    #
    def set_host(v)
      v = "" if v.nil? || v == "localhost"
      @host = v
    end

    # do nothing
    def set_port(v)
    end

    # raise InvalidURIError
    def check_userinfo(user)
      raise Bundler::URI::InvalidURIError, "can not set userinfo for file Bundler::URI"
    end

    # raise InvalidURIError
    def check_user(user)
      raise Bundler::URI::InvalidURIError, "can not set user for file Bundler::URI"
    end

    # raise InvalidURIError
    def check_password(user)
      raise Bundler::URI::InvalidURIError, "can not set password for file Bundler::URI"
    end

    # do nothing
    def set_userinfo(v)
    end

    # do nothing
    def set_user(v)
    end

    # do nothing
    def set_password(v)
    end
  end

  @@schemes['FILE'] = File
end
# frozen_string_literal: true
#--
# = uri/common.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# Revision:: $Id$
# License::
#   You can redistribute it and/or modify it under the same term as Ruby.
#
# See Bundler::URI for general documentation
#

require_relative "rfc2396_parser"
require_relative "rfc3986_parser"

module Bundler::URI
  REGEXP = RFC2396_REGEXP
  Parser = RFC2396_Parser
  RFC3986_PARSER = RFC3986_Parser.new

  # Bundler::URI::Parser.new
  DEFAULT_PARSER = Parser.new
  DEFAULT_PARSER.pattern.each_pair do |sym, str|
    unless REGEXP::PATTERN.const_defined?(sym)
      REGEXP::PATTERN.const_set(sym, str)
    end
  end
  DEFAULT_PARSER.regexp.each_pair do |sym, str|
    const_set(sym, str)
  end

  module Util # :nodoc:
    def make_components_hash(klass, array_hash)
      tmp = {}
      if array_hash.kind_of?(Array) &&
          array_hash.size == klass.component.size - 1
        klass.component[1..-1].each_index do |i|
          begin
            tmp[klass.component[i + 1]] = array_hash[i].clone
          rescue TypeError
            tmp[klass.component[i + 1]] = array_hash[i]
          end
        end

      elsif array_hash.kind_of?(Hash)
        array_hash.each do |key, value|
          begin
            tmp[key] = value.clone
          rescue TypeError
            tmp[key] = value
          end
        end
      else
        raise ArgumentError,
          "expected Array of or Hash of components of #{klass} (#{klass.component[1..-1].join(', ')})"
      end
      tmp[:scheme] = klass.to_s.sub(/\A.*::/, '').downcase

      return tmp
    end
    module_function :make_components_hash
  end

  # Module for escaping unsafe characters with codes.
  module Escape
    #
    # == Synopsis
    #
    #   Bundler::URI.escape(str [, unsafe])
    #
    # == Args
    #
    # +str+::
    #   String to replaces in.
    # +unsafe+::
    #   Regexp that matches all symbols that must be replaced with codes.
    #   By default uses <tt>UNSAFE</tt>.
    #   When this argument is a String, it represents a character set.
    #
    # == Description
    #
    # Escapes the string, replacing all unsafe characters with codes.
    #
    # This method is obsolete and should not be used. Instead, use
    # CGI.escape, Bundler::URI.encode_www_form or Bundler::URI.encode_www_form_component
    # depending on your specific use case.
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   enc_uri = Bundler::URI.escape("http://example.com/?a=\11\15")
    #   # => "http://example.com/?a=%09%0D"
    #
    #   Bundler::URI.unescape(enc_uri)
    #   # => "http://example.com/?a=\t\r"
    #
    #   Bundler::URI.escape("@?@!", "!?")
    #   # => "@%3F@%21"
    #
    def escape(*arg)
      warn "Bundler::URI.escape is obsolete", uplevel: 1
      DEFAULT_PARSER.escape(*arg)
    end
    alias encode escape
    #
    # == Synopsis
    #
    #   Bundler::URI.unescape(str)
    #
    # == Args
    #
    # +str+::
    #   String to unescape.
    #
    # == Description
    #
    # This method is obsolete and should not be used. Instead, use
    # CGI.unescape, Bundler::URI.decode_www_form or Bundler::URI.decode_www_form_component
    # depending on your specific use case.
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   enc_uri = Bundler::URI.escape("http://example.com/?a=\11\15")
    #   # => "http://example.com/?a=%09%0D"
    #
    #   Bundler::URI.unescape(enc_uri)
    #   # => "http://example.com/?a=\t\r"
    #
    def unescape(*arg)
      warn "Bundler::URI.unescape is obsolete", uplevel: 1
      DEFAULT_PARSER.unescape(*arg)
    end
    alias decode unescape
  end # module Escape

  extend Escape
  include REGEXP

  @@schemes = {}
  # Returns a Hash of the defined schemes.
  def self.scheme_list
    @@schemes
  end

  #
  # Base class for all Bundler::URI exceptions.
  #
  class Error < StandardError; end
  #
  # Not a Bundler::URI.
  #
  class InvalidURIError < Error; end
  #
  # Not a Bundler::URI component.
  #
  class InvalidComponentError < Error; end
  #
  # Bundler::URI is valid, bad usage is not.
  #
  class BadURIError < Error; end

  #
  # == Synopsis
  #
  #   Bundler::URI::split(uri)
  #
  # == Args
  #
  # +uri+::
  #   String with Bundler::URI.
  #
  # == Description
  #
  # Splits the string on following parts and returns array with result:
  #
  # * Scheme
  # * Userinfo
  # * Host
  # * Port
  # * Registry
  # * Path
  # * Opaque
  # * Query
  # * Fragment
  #
  # == Usage
  #
  #   require 'bundler/vendor/uri/lib/uri'
  #
  #   Bundler::URI.split("http://www.ruby-lang.org/")
  #   # => ["http", nil, "www.ruby-lang.org", nil, nil, "/", nil, nil, nil]
  #
  def self.split(uri)
    RFC3986_PARSER.split(uri)
  end

  #
  # == Synopsis
  #
  #   Bundler::URI::parse(uri_str)
  #
  # == Args
  #
  # +uri_str+::
  #   String with Bundler::URI.
  #
  # == Description
  #
  # Creates one of the Bundler::URI's subclasses instance from the string.
  #
  # == Raises
  #
  # Bundler::URI::InvalidURIError::
  #   Raised if Bundler::URI given is not a correct one.
  #
  # == Usage
  #
  #   require 'bundler/vendor/uri/lib/uri'
  #
  #   uri = Bundler::URI.parse("http://www.ruby-lang.org/")
  #   # => #<Bundler::URI::HTTP http://www.ruby-lang.org/>
  #   uri.scheme
  #   # => "http"
  #   uri.host
  #   # => "www.ruby-lang.org"
  #
  # It's recommended to first ::escape the provided +uri_str+ if there are any
  # invalid Bundler::URI characters.
  #
  def self.parse(uri)
    RFC3986_PARSER.parse(uri)
  end

  #
  # == Synopsis
  #
  #   Bundler::URI::join(str[, str, ...])
  #
  # == Args
  #
  # +str+::
  #   String(s) to work with, will be converted to RFC3986 URIs before merging.
  #
  # == Description
  #
  # Joins URIs.
  #
  # == Usage
  #
  #   require 'bundler/vendor/uri/lib/uri'
  #
  #   Bundler::URI.join("http://example.com/","main.rbx")
  #   # => #<Bundler::URI::HTTP http://example.com/main.rbx>
  #
  #   Bundler::URI.join('http://example.com', 'foo')
  #   # => #<Bundler::URI::HTTP http://example.com/foo>
  #
  #   Bundler::URI.join('http://example.com', '/foo', '/bar')
  #   # => #<Bundler::URI::HTTP http://example.com/bar>
  #
  #   Bundler::URI.join('http://example.com', '/foo', 'bar')
  #   # => #<Bundler::URI::HTTP http://example.com/bar>
  #
  #   Bundler::URI.join('http://example.com', '/foo/', 'bar')
  #   # => #<Bundler::URI::HTTP http://example.com/foo/bar>
  #
  def self.join(*str)
    RFC3986_PARSER.join(*str)
  end

  #
  # == Synopsis
  #
  #   Bundler::URI::extract(str[, schemes][,&blk])
  #
  # == Args
  #
  # +str+::
  #   String to extract URIs from.
  # +schemes+::
  #   Limit Bundler::URI matching to specific schemes.
  #
  # == Description
  #
  # Extracts URIs from a string. If block given, iterates through all matched URIs.
  # Returns nil if block given or array with matches.
  #
  # == Usage
  #
  #   require "bundler/vendor/uri/lib/uri"
  #
  #   Bundler::URI.extract("text here http://foo.example.org/bla and here mailto:test@example.com and here also.")
  #   # => ["http://foo.example.com/bla", "mailto:test@example.com"]
  #
  def self.extract(str, schemes = nil, &block)
    warn "Bundler::URI.extract is obsolete", uplevel: 1 if $VERBOSE
    DEFAULT_PARSER.extract(str, schemes, &block)
  end

  #
  # == Synopsis
  #
  #   Bundler::URI::regexp([match_schemes])
  #
  # == Args
  #
  # +match_schemes+::
  #   Array of schemes. If given, resulting regexp matches to URIs
  #   whose scheme is one of the match_schemes.
  #
  # == Description
  #
  # Returns a Regexp object which matches to Bundler::URI-like strings.
  # The Regexp object returned by this method includes arbitrary
  # number of capture group (parentheses).  Never rely on it's number.
  #
  # == Usage
  #
  #   require 'bundler/vendor/uri/lib/uri'
  #
  #   # extract first Bundler::URI from html_string
  #   html_string.slice(Bundler::URI.regexp)
  #
  #   # remove ftp URIs
  #   html_string.sub(Bundler::URI.regexp(['ftp']), '')
  #
  #   # You should not rely on the number of parentheses
  #   html_string.scan(Bundler::URI.regexp) do |*matches|
  #     p $&
  #   end
  #
  def self.regexp(schemes = nil)
    warn "Bundler::URI.regexp is obsolete", uplevel: 1 if $VERBOSE
    DEFAULT_PARSER.make_regexp(schemes)
  end

  TBLENCWWWCOMP_ = {} # :nodoc:
  256.times do |i|
    TBLENCWWWCOMP_[-i.chr] = -('%%%02X' % i)
  end
  TBLENCWWWCOMP_[' '] = '+'
  TBLENCWWWCOMP_.freeze
  TBLDECWWWCOMP_ = {} # :nodoc:
  256.times do |i|
    h, l = i>>4, i&15
    TBLDECWWWCOMP_[-('%%%X%X' % [h, l])] = -i.chr
    TBLDECWWWCOMP_[-('%%%x%X' % [h, l])] = -i.chr
    TBLDECWWWCOMP_[-('%%%X%x' % [h, l])] = -i.chr
    TBLDECWWWCOMP_[-('%%%x%x' % [h, l])] = -i.chr
  end
  TBLDECWWWCOMP_['+'] = ' '
  TBLDECWWWCOMP_.freeze

  # Encodes given +str+ to URL-encoded form data.
  #
  # This method doesn't convert *, -, ., 0-9, A-Z, _, a-z, but does convert SP
  # (ASCII space) to + and converts others to %XX.
  #
  # If +enc+ is given, convert +str+ to the encoding before percent encoding.
  #
  # This is an implementation of
  # http://www.w3.org/TR/2013/CR-html5-20130806/forms.html#url-encoded-form-data.
  #
  # See Bundler::URI.decode_www_form_component, Bundler::URI.encode_www_form.
  def self.encode_www_form_component(str, enc=nil)
    str = str.to_s.dup
    if str.encoding != Encoding::ASCII_8BIT
      if enc && enc != Encoding::ASCII_8BIT
        str.encode!(Encoding::UTF_8, invalid: :replace, undef: :replace)
        str.encode!(enc, fallback: ->(x){"&##{x.ord};"})
      end
      str.force_encoding(Encoding::ASCII_8BIT)
    end
    str.gsub!(/[^*\-.0-9A-Z_a-z]/, TBLENCWWWCOMP_)
    str.force_encoding(Encoding::US_ASCII)
  end

  # Decodes given +str+ of URL-encoded form data.
  #
  # This decodes + to SP.
  #
  # See Bundler::URI.encode_www_form_component, Bundler::URI.decode_www_form.
  def self.decode_www_form_component(str, enc=Encoding::UTF_8)
    raise ArgumentError, "invalid %-encoding (#{str})" if /%(?!\h\h)/ =~ str
    str.b.gsub(/\+|%\h\h/, TBLDECWWWCOMP_).force_encoding(enc)
  end

  # Generates URL-encoded form data from given +enum+.
  #
  # This generates application/x-www-form-urlencoded data defined in HTML5
  # from given an Enumerable object.
  #
  # This internally uses Bundler::URI.encode_www_form_component(str).
  #
  # This method doesn't convert the encoding of given items, so convert them
  # before calling this method if you want to send data as other than original
  # encoding or mixed encoding data. (Strings which are encoded in an HTML5
  # ASCII incompatible encoding are converted to UTF-8.)
  #
  # This method doesn't handle files.  When you send a file, use
  # multipart/form-data.
  #
  # This refers http://url.spec.whatwg.org/#concept-urlencoded-serializer
  #
  #    Bundler::URI.encode_www_form([["q", "ruby"], ["lang", "en"]])
  #    #=> "q=ruby&lang=en"
  #    Bundler::URI.encode_www_form("q" => "ruby", "lang" => "en")
  #    #=> "q=ruby&lang=en"
  #    Bundler::URI.encode_www_form("q" => ["ruby", "perl"], "lang" => "en")
  #    #=> "q=ruby&q=perl&lang=en"
  #    Bundler::URI.encode_www_form([["q", "ruby"], ["q", "perl"], ["lang", "en"]])
  #    #=> "q=ruby&q=perl&lang=en"
  #
  # See Bundler::URI.encode_www_form_component, Bundler::URI.decode_www_form.
  def self.encode_www_form(enum, enc=nil)
    enum.map do |k,v|
      if v.nil?
        encode_www_form_component(k, enc)
      elsif v.respond_to?(:to_ary)
        v.to_ary.map do |w|
          str = encode_www_form_component(k, enc)
          unless w.nil?
            str << '='
            str << encode_www_form_component(w, enc)
          end
        end.join('&')
      else
        str = encode_www_form_component(k, enc)
        str << '='
        str << encode_www_form_component(v, enc)
      end
    end.join('&')
  end

  # Decodes URL-encoded form data from given +str+.
  #
  # This decodes application/x-www-form-urlencoded data
  # and returns an array of key-value arrays.
  #
  # This refers http://url.spec.whatwg.org/#concept-urlencoded-parser,
  # so this supports only &-separator, and doesn't support ;-separator.
  #
  #    ary = Bundler::URI.decode_www_form("a=1&a=2&b=3")
  #    ary                   #=> [['a', '1'], ['a', '2'], ['b', '3']]
  #    ary.assoc('a').last   #=> '1'
  #    ary.assoc('b').last   #=> '3'
  #    ary.rassoc('a').last  #=> '2'
  #    Hash[ary]             #=> {"a"=>"2", "b"=>"3"}
  #
  # See Bundler::URI.decode_www_form_component, Bundler::URI.encode_www_form.
  def self.decode_www_form(str, enc=Encoding::UTF_8, separator: '&', use__charset_: false, isindex: false)
    raise ArgumentError, "the input of #{self.name}.#{__method__} must be ASCII only string" unless str.ascii_only?
    ary = []
    return ary if str.empty?
    enc = Encoding.find(enc)
    str.b.each_line(separator) do |string|
      string.chomp!(separator)
      key, sep, val = string.partition('=')
      if isindex
        if sep.empty?
          val = key
          key = +''
        end
        isindex = false
      end

      if use__charset_ and key == '_charset_' and e = get_encoding(val)
        enc = e
        use__charset_ = false
      end

      key.gsub!(/\+|%\h\h/, TBLDECWWWCOMP_)
      if val
        val.gsub!(/\+|%\h\h/, TBLDECWWWCOMP_)
      else
        val = +''
      end

      ary << [key, val]
    end
    ary.each do |k, v|
      k.force_encoding(enc)
      k.scrub!
      v.force_encoding(enc)
      v.scrub!
    end
    ary
  end

  private
=begin command for WEB_ENCODINGS_
  curl https://encoding.spec.whatwg.org/encodings.json|
  ruby -rjson -e 'H={}
  h={
    "shift_jis"=>"Windows-31J",
    "euc-jp"=>"cp51932",
    "iso-2022-jp"=>"cp50221",
    "x-mac-cyrillic"=>"macCyrillic",
  }
  JSON($<.read).map{|x|x["encodings"]}.flatten.each{|x|
    Encoding.find(n=h.fetch(n=x["name"].downcase,n))rescue next
    x["labels"].each{|y|H[y]=n}
  }
  puts "{"
  H.each{|k,v|puts %[  #{k.dump}=>#{v.dump},]}
  puts "}"
'
=end
  WEB_ENCODINGS_ = {
    "unicode-1-1-utf-8"=>"utf-8",
    "utf-8"=>"utf-8",
    "utf8"=>"utf-8",
    "866"=>"ibm866",
    "cp866"=>"ibm866",
    "csibm866"=>"ibm866",
    "ibm866"=>"ibm866",
    "csisolatin2"=>"iso-8859-2",
    "iso-8859-2"=>"iso-8859-2",
    "iso-ir-101"=>"iso-8859-2",
    "iso8859-2"=>"iso-8859-2",
    "iso88592"=>"iso-8859-2",
    "iso_8859-2"=>"iso-8859-2",
    "iso_8859-2:1987"=>"iso-8859-2",
    "l2"=>"iso-8859-2",
    "latin2"=>"iso-8859-2",
    "csisolatin3"=>"iso-8859-3",
    "iso-8859-3"=>"iso-8859-3",
    "iso-ir-109"=>"iso-8859-3",
    "iso8859-3"=>"iso-8859-3",
    "iso88593"=>"iso-8859-3",
    "iso_8859-3"=>"iso-8859-3",
    "iso_8859-3:1988"=>"iso-8859-3",
    "l3"=>"iso-8859-3",
    "latin3"=>"iso-8859-3",
    "csisolatin4"=>"iso-8859-4",
    "iso-8859-4"=>"iso-8859-4",
    "iso-ir-110"=>"iso-8859-4",
    "iso8859-4"=>"iso-8859-4",
    "iso88594"=>"iso-8859-4",
    "iso_8859-4"=>"iso-8859-4",
    "iso_8859-4:1988"=>"iso-8859-4",
    "l4"=>"iso-8859-4",
    "latin4"=>"iso-8859-4",
    "csisolatincyrillic"=>"iso-8859-5",
    "cyrillic"=>"iso-8859-5",
    "iso-8859-5"=>"iso-8859-5",
    "iso-ir-144"=>"iso-8859-5",
    "iso8859-5"=>"iso-8859-5",
    "iso88595"=>"iso-8859-5",
    "iso_8859-5"=>"iso-8859-5",
    "iso_8859-5:1988"=>"iso-8859-5",
    "arabic"=>"iso-8859-6",
    "asmo-708"=>"iso-8859-6",
    "csiso88596e"=>"iso-8859-6",
    "csiso88596i"=>"iso-8859-6",
    "csisolatinarabic"=>"iso-8859-6",
    "ecma-114"=>"iso-8859-6",
    "iso-8859-6"=>"iso-8859-6",
    "iso-8859-6-e"=>"iso-8859-6",
    "iso-8859-6-i"=>"iso-8859-6",
    "iso-ir-127"=>"iso-8859-6",
    "iso8859-6"=>"iso-8859-6",
    "iso88596"=>"iso-8859-6",
    "iso_8859-6"=>"iso-8859-6",
    "iso_8859-6:1987"=>"iso-8859-6",
    "csisolatingreek"=>"iso-8859-7",
    "ecma-118"=>"iso-8859-7",
    "elot_928"=>"iso-8859-7",
    "greek"=>"iso-8859-7",
    "greek8"=>"iso-8859-7",
    "iso-8859-7"=>"iso-8859-7",
    "iso-ir-126"=>"iso-8859-7",
    "iso8859-7"=>"iso-8859-7",
    "iso88597"=>"iso-8859-7",
    "iso_8859-7"=>"iso-8859-7",
    "iso_8859-7:1987"=>"iso-8859-7",
    "sun_eu_greek"=>"iso-8859-7",
    "csiso88598e"=>"iso-8859-8",
    "csisolatinhebrew"=>"iso-8859-8",
    "hebrew"=>"iso-8859-8",
    "iso-8859-8"=>"iso-8859-8",
    "iso-8859-8-e"=>"iso-8859-8",
    "iso-ir-138"=>"iso-8859-8",
    "iso8859-8"=>"iso-8859-8",
    "iso88598"=>"iso-8859-8",
    "iso_8859-8"=>"iso-8859-8",
    "iso_8859-8:1988"=>"iso-8859-8",
    "visual"=>"iso-8859-8",
    "csisolatin6"=>"iso-8859-10",
    "iso-8859-10"=>"iso-8859-10",
    "iso-ir-157"=>"iso-8859-10",
    "iso8859-10"=>"iso-8859-10",
    "iso885910"=>"iso-8859-10",
    "l6"=>"iso-8859-10",
    "latin6"=>"iso-8859-10",
    "iso-8859-13"=>"iso-8859-13",
    "iso8859-13"=>"iso-8859-13",
    "iso885913"=>"iso-8859-13",
    "iso-8859-14"=>"iso-8859-14",
    "iso8859-14"=>"iso-8859-14",
    "iso885914"=>"iso-8859-14",
    "csisolatin9"=>"iso-8859-15",
    "iso-8859-15"=>"iso-8859-15",
    "iso8859-15"=>"iso-8859-15",
    "iso885915"=>"iso-8859-15",
    "iso_8859-15"=>"iso-8859-15",
    "l9"=>"iso-8859-15",
    "iso-8859-16"=>"iso-8859-16",
    "cskoi8r"=>"koi8-r",
    "koi"=>"koi8-r",
    "koi8"=>"koi8-r",
    "koi8-r"=>"koi8-r",
    "koi8_r"=>"koi8-r",
    "koi8-ru"=>"koi8-u",
    "koi8-u"=>"koi8-u",
    "dos-874"=>"windows-874",
    "iso-8859-11"=>"windows-874",
    "iso8859-11"=>"windows-874",
    "iso885911"=>"windows-874",
    "tis-620"=>"windows-874",
    "windows-874"=>"windows-874",
    "cp1250"=>"windows-1250",
    "windows-1250"=>"windows-1250",
    "x-cp1250"=>"windows-1250",
    "cp1251"=>"windows-1251",
    "windows-1251"=>"windows-1251",
    "x-cp1251"=>"windows-1251",
    "ansi_x3.4-1968"=>"windows-1252",
    "ascii"=>"windows-1252",
    "cp1252"=>"windows-1252",
    "cp819"=>"windows-1252",
    "csisolatin1"=>"windows-1252",
    "ibm819"=>"windows-1252",
    "iso-8859-1"=>"windows-1252",
    "iso-ir-100"=>"windows-1252",
    "iso8859-1"=>"windows-1252",
    "iso88591"=>"windows-1252",
    "iso_8859-1"=>"windows-1252",
    "iso_8859-1:1987"=>"windows-1252",
    "l1"=>"windows-1252",
    "latin1"=>"windows-1252",
    "us-ascii"=>"windows-1252",
    "windows-1252"=>"windows-1252",
    "x-cp1252"=>"windows-1252",
    "cp1253"=>"windows-1253",
    "windows-1253"=>"windows-1253",
    "x-cp1253"=>"windows-1253",
    "cp1254"=>"windows-1254",
    "csisolatin5"=>"windows-1254",
    "iso-8859-9"=>"windows-1254",
    "iso-ir-148"=>"windows-1254",
    "iso8859-9"=>"windows-1254",
    "iso88599"=>"windows-1254",
    "iso_8859-9"=>"windows-1254",
    "iso_8859-9:1989"=>"windows-1254",
    "l5"=>"windows-1254",
    "latin5"=>"windows-1254",
    "windows-1254"=>"windows-1254",
    "x-cp1254"=>"windows-1254",
    "cp1255"=>"windows-1255",
    "windows-1255"=>"windows-1255",
    "x-cp1255"=>"windows-1255",
    "cp1256"=>"windows-1256",
    "windows-1256"=>"windows-1256",
    "x-cp1256"=>"windows-1256",
    "cp1257"=>"windows-1257",
    "windows-1257"=>"windows-1257",
    "x-cp1257"=>"windows-1257",
    "cp1258"=>"windows-1258",
    "windows-1258"=>"windows-1258",
    "x-cp1258"=>"windows-1258",
    "x-mac-cyrillic"=>"macCyrillic",
    "x-mac-ukrainian"=>"macCyrillic",
    "chinese"=>"gbk",
    "csgb2312"=>"gbk",
    "csiso58gb231280"=>"gbk",
    "gb2312"=>"gbk",
    "gb_2312"=>"gbk",
    "gb_2312-80"=>"gbk",
    "gbk"=>"gbk",
    "iso-ir-58"=>"gbk",
    "x-gbk"=>"gbk",
    "gb18030"=>"gb18030",
    "big5"=>"big5",
    "big5-hkscs"=>"big5",
    "cn-big5"=>"big5",
    "csbig5"=>"big5",
    "x-x-big5"=>"big5",
    "cseucpkdfmtjapanese"=>"cp51932",
    "euc-jp"=>"cp51932",
    "x-euc-jp"=>"cp51932",
    "csiso2022jp"=>"cp50221",
    "iso-2022-jp"=>"cp50221",
    "csshiftjis"=>"Windows-31J",
    "ms932"=>"Windows-31J",
    "ms_kanji"=>"Windows-31J",
    "shift-jis"=>"Windows-31J",
    "shift_jis"=>"Windows-31J",
    "sjis"=>"Windows-31J",
    "windows-31j"=>"Windows-31J",
    "x-sjis"=>"Windows-31J",
    "cseuckr"=>"euc-kr",
    "csksc56011987"=>"euc-kr",
    "euc-kr"=>"euc-kr",
    "iso-ir-149"=>"euc-kr",
    "korean"=>"euc-kr",
    "ks_c_5601-1987"=>"euc-kr",
    "ks_c_5601-1989"=>"euc-kr",
    "ksc5601"=>"euc-kr",
    "ksc_5601"=>"euc-kr",
    "windows-949"=>"euc-kr",
    "utf-16be"=>"utf-16be",
    "utf-16"=>"utf-16le",
    "utf-16le"=>"utf-16le",
  } # :nodoc:

  # :nodoc:
  # return encoding or nil
  # http://encoding.spec.whatwg.org/#concept-encoding-get
  def self.get_encoding(label)
    Encoding.find(WEB_ENCODINGS_[label.to_str.strip.downcase]) rescue nil
  end
end # module Bundler::URI

module Bundler

  #
  # Returns +uri+ converted to an Bundler::URI object.
  #
  def URI(uri)
    if uri.is_a?(Bundler::URI::Generic)
      uri
    elsif uri = String.try_convert(uri)
      Bundler::URI.parse(uri)
    else
      raise ArgumentError,
        "bad argument (expected Bundler::URI object or Bundler::URI string)"
    end
  end
  module_function :URI
end
# frozen_string_literal: false
module Bundler::URI
  class RFC3986_Parser # :nodoc:
    # Bundler::URI defined in RFC3986
    # this regexp is modified not to host is not empty string
    RFC3986_URI = /\A(?<Bundler::URI>(?<scheme>[A-Za-z][+\-.0-9A-Za-z]*+):(?<hier-part>\/\/(?<authority>(?:(?<userinfo>(?:%\h\h|[!$&-.0-;=A-Z_a-z~])*+)@)?(?<host>(?<IP-literal>\[(?:(?<IPv6address>(?:\h{1,4}:){6}(?<ls32>\h{1,4}:\h{1,4}|(?<IPv4address>(?<dec-octet>[1-9]\d|1\d{2}|2[0-4]\d|25[0-5]|\d)\.\g<dec-octet>\.\g<dec-octet>\.\g<dec-octet>))|::(?:\h{1,4}:){5}\g<ls32>|\h{1,4}?::(?:\h{1,4}:){4}\g<ls32>|(?:(?:\h{1,4}:)?\h{1,4})?::(?:\h{1,4}:){3}\g<ls32>|(?:(?:\h{1,4}:){,2}\h{1,4})?::(?:\h{1,4}:){2}\g<ls32>|(?:(?:\h{1,4}:){,3}\h{1,4})?::\h{1,4}:\g<ls32>|(?:(?:\h{1,4}:){,4}\h{1,4})?::\g<ls32>|(?:(?:\h{1,4}:){,5}\h{1,4})?::\h{1,4}|(?:(?:\h{1,4}:){,6}\h{1,4})?::)|(?<IPvFuture>v\h++\.[!$&-.0-;=A-Z_a-z~]++))\])|\g<IPv4address>|(?<reg-name>(?:%\h\h|[!$&-.0-9;=A-Z_a-z~])++))?(?::(?<port>\d*+))?)(?<path-abempty>(?:\/(?<segment>(?:%\h\h|[!$&-.0-;=@-Z_a-z~])*+))*+)|(?<path-absolute>\/(?:(?<segment-nz>(?:%\h\h|[!$&-.0-;=@-Z_a-z~])++)(?:\/\g<segment>)*+)?)|(?<path-rootless>\g<segment-nz>(?:\/\g<segment>)*+)|(?<path-empty>))(?:\?(?<query>[^#]*+))?(?:\#(?<fragment>(?:%\h\h|[!$&-.0-;=@-Z_a-z~\/?])*+))?)\z/
    RFC3986_relative_ref = /\A(?<relative-ref>(?<relative-part>\/\/(?<authority>(?:(?<userinfo>(?:%\h\h|[!$&-.0-;=A-Z_a-z~])*+)@)?(?<host>(?<IP-literal>\[(?:(?<IPv6address>(?:\h{1,4}:){6}(?<ls32>\h{1,4}:\h{1,4}|(?<IPv4address>(?<dec-octet>[1-9]\d|1\d{2}|2[0-4]\d|25[0-5]|\d)\.\g<dec-octet>\.\g<dec-octet>\.\g<dec-octet>))|::(?:\h{1,4}:){5}\g<ls32>|\h{1,4}?::(?:\h{1,4}:){4}\g<ls32>|(?:(?:\h{1,4}:){,1}\h{1,4})?::(?:\h{1,4}:){3}\g<ls32>|(?:(?:\h{1,4}:){,2}\h{1,4})?::(?:\h{1,4}:){2}\g<ls32>|(?:(?:\h{1,4}:){,3}\h{1,4})?::\h{1,4}:\g<ls32>|(?:(?:\h{1,4}:){,4}\h{1,4})?::\g<ls32>|(?:(?:\h{1,4}:){,5}\h{1,4})?::\h{1,4}|(?:(?:\h{1,4}:){,6}\h{1,4})?::)|(?<IPvFuture>v\h++\.[!$&-.0-;=A-Z_a-z~]++))\])|\g<IPv4address>|(?<reg-name>(?:%\h\h|[!$&-.0-9;=A-Z_a-z~])++))?(?::(?<port>\d*+))?)(?<path-abempty>(?:\/(?<segment>(?:%\h\h|[!$&-.0-;=@-Z_a-z~])*+))*+)|(?<path-absolute>\/(?:(?<segment-nz>(?:%\h\h|[!$&-.0-;=@-Z_a-z~])++)(?:\/\g<segment>)*+)?)|(?<path-noscheme>(?<segment-nz-nc>(?:%\h\h|[!$&-.0-9;=@-Z_a-z~])++)(?:\/\g<segment>)*+)|(?<path-empty>))(?:\?(?<query>[^#]*+))?(?:\#(?<fragment>(?:%\h\h|[!$&-.0-;=@-Z_a-z~\/?])*+))?)\z/
    attr_reader :regexp

    def initialize
      @regexp = default_regexp.each_value(&:freeze).freeze
    end

    def split(uri) #:nodoc:
      begin
        uri = uri.to_str
      rescue NoMethodError
        raise InvalidURIError, "bad Bundler::URI(is not Bundler::URI?): #{uri.inspect}"
      end
      uri.ascii_only? or
        raise InvalidURIError, "Bundler::URI must be ascii only #{uri.dump}"
      if m = RFC3986_URI.match(uri)
        query = m["query".freeze]
        scheme = m["scheme".freeze]
        opaque = m["path-rootless".freeze]
        if opaque
          opaque << "?#{query}" if query
          [ scheme,
            nil, # userinfo
            nil, # host
            nil, # port
            nil, # registry
            nil, # path
            opaque,
            nil, # query
            m["fragment".freeze]
          ]
        else # normal
          [ scheme,
            m["userinfo".freeze],
            m["host".freeze],
            m["port".freeze],
            nil, # registry
            (m["path-abempty".freeze] ||
             m["path-absolute".freeze] ||
             m["path-empty".freeze]),
            nil, # opaque
            query,
            m["fragment".freeze]
          ]
        end
      elsif m = RFC3986_relative_ref.match(uri)
        [ nil, # scheme
          m["userinfo".freeze],
          m["host".freeze],
          m["port".freeze],
          nil, # registry,
          (m["path-abempty".freeze] ||
           m["path-absolute".freeze] ||
           m["path-noscheme".freeze] ||
           m["path-empty".freeze]),
          nil, # opaque
          m["query".freeze],
          m["fragment".freeze]
        ]
      else
        raise InvalidURIError, "bad Bundler::URI(is not Bundler::URI?): #{uri.inspect}"
      end
    end

    def parse(uri) # :nodoc:
      scheme, userinfo, host, port,
        registry, path, opaque, query, fragment = self.split(uri)
      scheme_list = Bundler::URI.scheme_list
      if scheme && scheme_list.include?(uc = scheme.upcase)
        scheme_list[uc].new(scheme, userinfo, host, port,
                            registry, path, opaque, query,
                            fragment, self)
      else
        Generic.new(scheme, userinfo, host, port,
                    registry, path, opaque, query,
                    fragment, self)
      end
    end


    def join(*uris) # :nodoc:
      uris[0] = convert_to_uri(uris[0])
      uris.inject :merge
    end

    @@to_s = Kernel.instance_method(:to_s)
    def inspect
      @@to_s.bind_call(self)
    end

    private

    def default_regexp # :nodoc:
      {
        SCHEME: /\A[A-Za-z][A-Za-z0-9+\-.]*\z/,
        USERINFO: /\A(?:%\h\h|[!$&-.0-;=A-Z_a-z~])*\z/,
        HOST: /\A(?:(?<IP-literal>\[(?:(?<IPv6address>(?:\h{1,4}:){6}(?<ls32>\h{1,4}:\h{1,4}|(?<IPv4address>(?<dec-octet>[1-9]\d|1\d{2}|2[0-4]\d|25[0-5]|\d)\.\g<dec-octet>\.\g<dec-octet>\.\g<dec-octet>))|::(?:\h{1,4}:){5}\g<ls32>|\h{,4}::(?:\h{1,4}:){4}\g<ls32>|(?:(?:\h{1,4}:)?\h{1,4})?::(?:\h{1,4}:){3}\g<ls32>|(?:(?:\h{1,4}:){,2}\h{1,4})?::(?:\h{1,4}:){2}\g<ls32>|(?:(?:\h{1,4}:){,3}\h{1,4})?::\h{1,4}:\g<ls32>|(?:(?:\h{1,4}:){,4}\h{1,4})?::\g<ls32>|(?:(?:\h{1,4}:){,5}\h{1,4})?::\h{1,4}|(?:(?:\h{1,4}:){,6}\h{1,4})?::)|(?<IPvFuture>v\h+\.[!$&-.0-;=A-Z_a-z~]+))\])|\g<IPv4address>|(?<reg-name>(?:%\h\h|[!$&-.0-9;=A-Z_a-z~])*))\z/,
        ABS_PATH: /\A\/(?:%\h\h|[!$&-.0-;=@-Z_a-z~])*(?:\/(?:%\h\h|[!$&-.0-;=@-Z_a-z~])*)*\z/,
        REL_PATH: /\A(?:%\h\h|[!$&-.0-;=@-Z_a-z~])+(?:\/(?:%\h\h|[!$&-.0-;=@-Z_a-z~])*)*\z/,
        QUERY: /\A(?:%\h\h|[!$&-.0-;=@-Z_a-z~\/?])*\z/,
        FRAGMENT: /\A(?:%\h\h|[!$&-.0-;=@-Z_a-z~\/?])*\z/,
        OPAQUE: /\A(?:[^\/].*)?\z/,
        PORT: /\A[\x09\x0a\x0c\x0d ]*+\d*[\x09\x0a\x0c\x0d ]*\z/,
      }
    end

    def convert_to_uri(uri)
      if uri.is_a?(Bundler::URI::Generic)
        uri
      elsif uri = String.try_convert(uri)
        parse(uri)
      else
        raise ArgumentError,
          "bad argument (expected Bundler::URI object or Bundler::URI string)"
      end
    end

  end # class Parser
end # module Bundler::URI
# frozen_string_literal: false
# = uri/http.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# License:: You can redistribute it and/or modify it under the same term as Ruby.
# Revision:: $Id$
#
# See Bundler::URI for general documentation
#

require_relative 'generic'

module Bundler::URI

  #
  # The syntax of HTTP URIs is defined in RFC1738 section 3.3.
  #
  # Note that the Ruby Bundler::URI library allows HTTP URLs containing usernames and
  # passwords. This is not legal as per the RFC, but used to be
  # supported in Internet Explorer 5 and 6, before the MS04-004 security
  # update. See <URL:http://support.microsoft.com/kb/834489>.
  #
  class HTTP < Generic
    # A Default port of 80 for Bundler::URI::HTTP.
    DEFAULT_PORT = 80

    # An Array of the available components for Bundler::URI::HTTP.
    COMPONENT = %i[
      scheme
      userinfo host port
      path
      query
      fragment
    ].freeze

    #
    # == Description
    #
    # Creates a new Bundler::URI::HTTP object from components, with syntax checking.
    #
    # The components accepted are userinfo, host, port, path, query, and
    # fragment.
    #
    # The components should be provided either as an Array, or as a Hash
    # with keys formed by preceding the component names with a colon.
    #
    # If an Array is used, the components must be passed in the
    # order <code>[userinfo, host, port, path, query, fragment]</code>.
    #
    # Example:
    #
    #     uri = Bundler::URI::HTTP.build(host: 'www.example.com', path: '/foo/bar')
    #
    #     uri = Bundler::URI::HTTP.build([nil, "www.example.com", nil, "/path",
    #       "query", 'fragment'])
    #
    # Currently, if passed userinfo components this method generates
    # invalid HTTP URIs as per RFC 1738.
    #
    def self.build(args)
      tmp = Util.make_components_hash(self, args)
      super(tmp)
    end

    #
    # == Description
    #
    # Returns the full path for an HTTP request, as required by Net::HTTP::Get.
    #
    # If the Bundler::URI contains a query, the full path is Bundler::URI#path + '?' + Bundler::URI#query.
    # Otherwise, the path is simply Bundler::URI#path.
    #
    # Example:
    #
    #     uri = Bundler::URI::HTTP.build(path: '/foo/bar', query: 'test=true')
    #     uri.request_uri #  => "/foo/bar?test=true"
    #
    def request_uri
      return unless @path

      url = @query ? "#@path?#@query" : @path.dup
      url.start_with?(?/.freeze) ? url : ?/ + url
    end
  end

  @@schemes['HTTP'] = HTTP

end
# frozen_string_literal: false
# = uri/ldap.rb
#
# License:: You can redistribute it and/or modify it under the same term as Ruby.
#
# See Bundler::URI for general documentation
#

require_relative 'ldap'

module Bundler::URI

  # The default port for LDAPS URIs is 636, and the scheme is 'ldaps:' rather
  # than 'ldap:'. Other than that, LDAPS URIs are identical to LDAP URIs;
  # see Bundler::URI::LDAP.
  class LDAPS < LDAP
    # A Default port of 636 for Bundler::URI::LDAPS
    DEFAULT_PORT = 636
  end
  @@schemes['LDAPS'] = LDAPS
end
# frozen_string_literal: false
# = uri/mailto.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# License:: You can redistribute it and/or modify it under the same term as Ruby.
# Revision:: $Id$
#
# See Bundler::URI for general documentation
#

require_relative 'generic'

module Bundler::URI

  #
  # RFC6068, the mailto URL scheme.
  #
  class MailTo < Generic
    include REGEXP

    # A Default port of nil for Bundler::URI::MailTo.
    DEFAULT_PORT = nil

    # An Array of the available components for Bundler::URI::MailTo.
    COMPONENT = [ :scheme, :to, :headers ].freeze

    # :stopdoc:
    #  "hname" and "hvalue" are encodings of an RFC 822 header name and
    #  value, respectively. As with "to", all URL reserved characters must
    #  be encoded.
    #
    #  "#mailbox" is as specified in RFC 822 [RFC822]. This means that it
    #  consists of zero or more comma-separated mail addresses, possibly
    #  including "phrase" and "comment" components. Note that all URL
    #  reserved characters in "to" must be encoded: in particular,
    #  parentheses, commas, and the percent sign ("%"), which commonly occur
    #  in the "mailbox" syntax.
    #
    #  Within mailto URLs, the characters "?", "=", "&" are reserved.

    # ; RFC 6068
    # hfields      = "?" hfield *( "&" hfield )
    # hfield       = hfname "=" hfvalue
    # hfname       = *qchar
    # hfvalue      = *qchar
    # qchar        = unreserved / pct-encoded / some-delims
    # some-delims  = "!" / "$" / "'" / "(" / ")" / "*"
    #              / "+" / "," / ";" / ":" / "@"
    #
    # ; RFC3986
    # unreserved   = ALPHA / DIGIT / "-" / "." / "_" / "~"
    # pct-encoded  = "%" HEXDIG HEXDIG
    HEADER_REGEXP  = /\A(?<hfield>(?:%\h\h|[!$'-.0-;@-Z_a-z~])*=(?:%\h\h|[!$'-.0-;@-Z_a-z~])*)(?:&\g<hfield>)*\z/
    # practical regexp for email address
    # https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
    EMAIL_REGEXP = /\A[a-zA-Z0-9.!\#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\z/
    # :startdoc:

    #
    # == Description
    #
    # Creates a new Bundler::URI::MailTo object from components, with syntax checking.
    #
    # Components can be provided as an Array or Hash. If an Array is used,
    # the components must be supplied as <code>[to, headers]</code>.
    #
    # If a Hash is used, the keys are the component names preceded by colons.
    #
    # The headers can be supplied as a pre-encoded string, such as
    # <code>"subject=subscribe&cc=address"</code>, or as an Array of Arrays
    # like <code>[['subject', 'subscribe'], ['cc', 'address']]</code>.
    #
    # Examples:
    #
    #    require 'bundler/vendor/uri/lib/uri'
    #
    #    m1 = Bundler::URI::MailTo.build(['joe@example.com', 'subject=Ruby'])
    #    m1.to_s  # => "mailto:joe@example.com?subject=Ruby"
    #
    #    m2 = Bundler::URI::MailTo.build(['john@example.com', [['Subject', 'Ruby'], ['Cc', 'jack@example.com']]])
    #    m2.to_s  # => "mailto:john@example.com?Subject=Ruby&Cc=jack@example.com"
    #
    #    m3 = Bundler::URI::MailTo.build({:to => 'listman@example.com', :headers => [['subject', 'subscribe']]})
    #    m3.to_s  # => "mailto:listman@example.com?subject=subscribe"
    #
    def self.build(args)
      tmp = Util.make_components_hash(self, args)

      case tmp[:to]
      when Array
        tmp[:opaque] = tmp[:to].join(',')
      when String
        tmp[:opaque] = tmp[:to].dup
      else
        tmp[:opaque] = ''
      end

      if tmp[:headers]
        query =
          case tmp[:headers]
          when Array
            tmp[:headers].collect { |x|
              if x.kind_of?(Array)
                x[0] + '=' + x[1..-1].join
              else
                x.to_s
              end
            }.join('&')
          when Hash
            tmp[:headers].collect { |h,v|
              h + '=' + v
            }.join('&')
          else
            tmp[:headers].to_s
          end
        unless query.empty?
          tmp[:opaque] << '?' << query
        end
      end

      super(tmp)
    end

    #
    # == Description
    #
    # Creates a new Bundler::URI::MailTo object from generic URL components with
    # no syntax checking.
    #
    # This method is usually called from Bundler::URI::parse, which checks
    # the validity of each component.
    #
    def initialize(*arg)
      super(*arg)

      @to = nil
      @headers = []

      # The RFC3986 parser does not normally populate opaque
      @opaque = "?#{@query}" if @query && !@opaque

      unless @opaque
        raise InvalidComponentError,
          "missing opaque part for mailto URL"
      end
      to, header = @opaque.split('?', 2)
      # allow semicolon as a addr-spec separator
      # http://support.microsoft.com/kb/820868
      unless /\A(?:[^@,;]+@[^@,;]+(?:\z|[,;]))*\z/ =~ to
        raise InvalidComponentError,
          "unrecognised opaque part for mailtoURL: #{@opaque}"
      end

      if arg[10] # arg_check
        self.to = to
        self.headers = header
      else
        set_to(to)
        set_headers(header)
      end
    end

    # The primary e-mail address of the URL, as a String.
    attr_reader :to

    # E-mail headers set by the URL, as an Array of Arrays.
    attr_reader :headers

    # Checks the to +v+ component.
    def check_to(v)
      return true unless v
      return true if v.size == 0

      v.split(/[,;]/).each do |addr|
        # check url safety as path-rootless
        if /\A(?:%\h\h|[!$&-.0-;=@-Z_a-z~])*\z/ !~ addr
          raise InvalidComponentError,
            "an address in 'to' is invalid as Bundler::URI #{addr.dump}"
        end

        # check addr-spec
        # don't s/\+/ /g
        addr.gsub!(/%\h\h/, Bundler::URI::TBLDECWWWCOMP_)
        if EMAIL_REGEXP !~ addr
          raise InvalidComponentError,
            "an address in 'to' is invalid as uri-escaped addr-spec #{addr.dump}"
        end
      end

      true
    end
    private :check_to

    # Private setter for to +v+.
    def set_to(v)
      @to = v
    end
    protected :set_to

    # Setter for to +v+.
    def to=(v)
      check_to(v)
      set_to(v)
      v
    end

    # Checks the headers +v+ component against either
    # * HEADER_REGEXP
    def check_headers(v)
      return true unless v
      return true if v.size == 0
      if HEADER_REGEXP !~ v
        raise InvalidComponentError,
          "bad component(expected opaque component): #{v}"
      end

      true
    end
    private :check_headers

    # Private setter for headers +v+.
    def set_headers(v)
      @headers = []
      if v
        v.split('&').each do |x|
          @headers << x.split(/=/, 2)
        end
      end
    end
    protected :set_headers

    # Setter for headers +v+.
    def headers=(v)
      check_headers(v)
      set_headers(v)
      v
    end

    # Constructs String from Bundler::URI.
    def to_s
      @scheme + ':' +
        if @to
          @to
        else
          ''
        end +
        if @headers.size > 0
          '?' + @headers.collect{|x| x.join('=')}.join('&')
        else
          ''
        end +
        if @fragment
          '#' + @fragment
        else
          ''
        end
    end

    # Returns the RFC822 e-mail text equivalent of the URL, as a String.
    #
    # Example:
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   uri = Bundler::URI.parse("mailto:ruby-list@ruby-lang.org?Subject=subscribe&cc=myaddr")
    #   uri.to_mailtext
    #   # => "To: ruby-list@ruby-lang.org\nSubject: subscribe\nCc: myaddr\n\n\n"
    #
    def to_mailtext
      to = Bundler::URI.decode_www_form_component(@to)
      head = ''
      body = ''
      @headers.each do |x|
        case x[0]
        when 'body'
          body = Bundler::URI.decode_www_form_component(x[1])
        when 'to'
          to << ', ' + Bundler::URI.decode_www_form_component(x[1])
        else
          head << Bundler::URI.decode_www_form_component(x[0]).capitalize + ': ' +
            Bundler::URI.decode_www_form_component(x[1])  + "\n"
        end
      end

      "To: #{to}
#{head}
#{body}
"
    end
    alias to_rfc822text to_mailtext
  end

  @@schemes['MAILTO'] = MailTo
end
# frozen_string_literal: false
# = uri/ldap.rb
#
# Author::
#  Takaaki Tateishi <ttate@jaist.ac.jp>
#  Akira Yamada <akira@ruby-lang.org>
# License::
#   Bundler::URI::LDAP is copyrighted free software by Takaaki Tateishi and Akira Yamada.
#   You can redistribute it and/or modify it under the same term as Ruby.
# Revision:: $Id$
#
# See Bundler::URI for general documentation
#

require_relative 'generic'

module Bundler::URI

  #
  # LDAP Bundler::URI SCHEMA (described in RFC2255).
  #--
  # ldap://<host>/<dn>[?<attrs>[?<scope>[?<filter>[?<extensions>]]]]
  #++
  class LDAP < Generic

    # A Default port of 389 for Bundler::URI::LDAP.
    DEFAULT_PORT = 389

    # An Array of the available components for Bundler::URI::LDAP.
    COMPONENT = [
      :scheme,
      :host, :port,
      :dn,
      :attributes,
      :scope,
      :filter,
      :extensions,
    ].freeze

    # Scopes available for the starting point.
    #
    # * SCOPE_BASE - the Base DN
    # * SCOPE_ONE  - one level under the Base DN, not including the base DN and
    #   not including any entries under this
    # * SCOPE_SUB  - subtrees, all entries at all levels
    #
    SCOPE = [
      SCOPE_ONE = 'one',
      SCOPE_SUB = 'sub',
      SCOPE_BASE = 'base',
    ].freeze

    #
    # == Description
    #
    # Creates a new Bundler::URI::LDAP object from components, with syntax checking.
    #
    # The components accepted are host, port, dn, attributes,
    # scope, filter, and extensions.
    #
    # The components should be provided either as an Array, or as a Hash
    # with keys formed by preceding the component names with a colon.
    #
    # If an Array is used, the components must be passed in the
    # order <code>[host, port, dn, attributes, scope, filter, extensions]</code>.
    #
    # Example:
    #
    #     uri = Bundler::URI::LDAP.build({:host => 'ldap.example.com',
    #       :dn => '/dc=example'})
    #
    #     uri = Bundler::URI::LDAP.build(["ldap.example.com", nil,
    #       "/dc=example;dc=com", "query", nil, nil, nil])
    #
    def self.build(args)
      tmp = Util::make_components_hash(self, args)

      if tmp[:dn]
        tmp[:path] = tmp[:dn]
      end

      query = []
      [:extensions, :filter, :scope, :attributes].collect do |x|
        next if !tmp[x] && query.size == 0
        query.unshift(tmp[x])
      end

      tmp[:query] = query.join('?')

      return super(tmp)
    end

    #
    # == Description
    #
    # Creates a new Bundler::URI::LDAP object from generic Bundler::URI components as per
    # RFC 2396. No LDAP-specific syntax checking is performed.
    #
    # Arguments are +scheme+, +userinfo+, +host+, +port+, +registry+, +path+,
    # +opaque+, +query+, and +fragment+, in that order.
    #
    # Example:
    #
    #     uri = Bundler::URI::LDAP.new("ldap", nil, "ldap.example.com", nil, nil,
    #       "/dc=example;dc=com", nil, "query", nil)
    #
    # See also Bundler::URI::Generic.new.
    #
    def initialize(*arg)
      super(*arg)

      if @fragment
        raise InvalidURIError, 'bad LDAP URL'
      end

      parse_dn
      parse_query
    end

    # Private method to cleanup +dn+ from using the +path+ component attribute.
    def parse_dn
      @dn = @path[1..-1]
    end
    private :parse_dn

    # Private method to cleanup +attributes+, +scope+, +filter+, and +extensions+
    # from using the +query+ component attribute.
    def parse_query
      @attributes = nil
      @scope      = nil
      @filter     = nil
      @extensions = nil

      if @query
        attrs, scope, filter, extensions = @query.split('?')

        @attributes = attrs if attrs && attrs.size > 0
        @scope      = scope if scope && scope.size > 0
        @filter     = filter if filter && filter.size > 0
        @extensions = extensions if extensions && extensions.size > 0
      end
    end
    private :parse_query

    # Private method to assemble +query+ from +attributes+, +scope+, +filter+, and +extensions+.
    def build_path_query
      @path = '/' + @dn

      query = []
      [@extensions, @filter, @scope, @attributes].each do |x|
        next if !x && query.size == 0
        query.unshift(x)
      end
      @query = query.join('?')
    end
    private :build_path_query

    # Returns dn.
    def dn
      @dn
    end

    # Private setter for dn +val+.
    def set_dn(val)
      @dn = val
      build_path_query
      @dn
    end
    protected :set_dn

    # Setter for dn +val+.
    def dn=(val)
      set_dn(val)
      val
    end

    # Returns attributes.
    def attributes
      @attributes
    end

    # Private setter for attributes +val+.
    def set_attributes(val)
      @attributes = val
      build_path_query
      @attributes
    end
    protected :set_attributes

    # Setter for attributes +val+.
    def attributes=(val)
      set_attributes(val)
      val
    end

    # Returns scope.
    def scope
      @scope
    end

    # Private setter for scope +val+.
    def set_scope(val)
      @scope = val
      build_path_query
      @scope
    end
    protected :set_scope

    # Setter for scope +val+.
    def scope=(val)
      set_scope(val)
      val
    end

    # Returns filter.
    def filter
      @filter
    end

    # Private setter for filter +val+.
    def set_filter(val)
      @filter = val
      build_path_query
      @filter
    end
    protected :set_filter

    # Setter for filter +val+.
    def filter=(val)
      set_filter(val)
      val
    end

    # Returns extensions.
    def extensions
      @extensions
    end

    # Private setter for extensions +val+.
    def set_extensions(val)
      @extensions = val
      build_path_query
      @extensions
    end
    protected :set_extensions

    # Setter for extensions +val+.
    def extensions=(val)
      set_extensions(val)
      val
    end

    # Checks if Bundler::URI has a path.
    # For Bundler::URI::LDAP this will return +false+.
    def hierarchical?
      false
    end
  end

  @@schemes['LDAP'] = LDAP
end
# frozen_string_literal: false
#--
# = uri/common.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# Revision:: $Id$
# License::
#   You can redistribute it and/or modify it under the same term as Ruby.
#
# See Bundler::URI for general documentation
#

module Bundler::URI
  #
  # Includes Bundler::URI::REGEXP::PATTERN
  #
  module RFC2396_REGEXP
    #
    # Patterns used to parse Bundler::URI's
    #
    module PATTERN
      # :stopdoc:

      # RFC 2396 (Bundler::URI Generic Syntax)
      # RFC 2732 (IPv6 Literal Addresses in URL's)
      # RFC 2373 (IPv6 Addressing Architecture)

      # alpha         = lowalpha | upalpha
      ALPHA = "a-zA-Z"
      # alphanum      = alpha | digit
      ALNUM = "#{ALPHA}\\d"

      # hex           = digit | "A" | "B" | "C" | "D" | "E" | "F" |
      #                         "a" | "b" | "c" | "d" | "e" | "f"
      HEX     = "a-fA-F\\d"
      # escaped       = "%" hex hex
      ESCAPED = "%[#{HEX}]{2}"
      # mark          = "-" | "_" | "." | "!" | "~" | "*" | "'" |
      #                 "(" | ")"
      # unreserved    = alphanum | mark
      UNRESERVED = "\\-_.!~*'()#{ALNUM}"
      # reserved      = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
      #                 "$" | ","
      # reserved      = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
      #                 "$" | "," | "[" | "]" (RFC 2732)
      RESERVED = ";/?:@&=+$,\\[\\]"

      # domainlabel   = alphanum | alphanum *( alphanum | "-" ) alphanum
      DOMLABEL = "(?:[#{ALNUM}](?:[-#{ALNUM}]*[#{ALNUM}])?)"
      # toplabel      = alpha | alpha *( alphanum | "-" ) alphanum
      TOPLABEL = "(?:[#{ALPHA}](?:[-#{ALNUM}]*[#{ALNUM}])?)"
      # hostname      = *( domainlabel "." ) toplabel [ "." ]
      HOSTNAME = "(?:#{DOMLABEL}\\.)*#{TOPLABEL}\\.?"

      # :startdoc:
    end # PATTERN

    # :startdoc:
  end # REGEXP

  # Class that parses String's into Bundler::URI's.
  #
  # It contains a Hash set of patterns and Regexp's that match and validate.
  #
  class RFC2396_Parser
    include RFC2396_REGEXP

    #
    # == Synopsis
    #
    #   Bundler::URI::Parser.new([opts])
    #
    # == Args
    #
    # The constructor accepts a hash as options for parser.
    # Keys of options are pattern names of Bundler::URI components
    # and values of options are pattern strings.
    # The constructor generates set of regexps for parsing URIs.
    #
    # You can use the following keys:
    #
    #   * :ESCAPED (Bundler::URI::PATTERN::ESCAPED in default)
    #   * :UNRESERVED (Bundler::URI::PATTERN::UNRESERVED in default)
    #   * :DOMLABEL (Bundler::URI::PATTERN::DOMLABEL in default)
    #   * :TOPLABEL (Bundler::URI::PATTERN::TOPLABEL in default)
    #   * :HOSTNAME (Bundler::URI::PATTERN::HOSTNAME in default)
    #
    # == Examples
    #
    #   p = Bundler::URI::Parser.new(:ESCAPED => "(?:%[a-fA-F0-9]{2}|%u[a-fA-F0-9]{4})")
    #   u = p.parse("http://example.jp/%uABCD") #=> #<Bundler::URI::HTTP http://example.jp/%uABCD>
    #   Bundler::URI.parse(u.to_s) #=> raises Bundler::URI::InvalidURIError
    #
    #   s = "http://example.com/ABCD"
    #   u1 = p.parse(s) #=> #<Bundler::URI::HTTP http://example.com/ABCD>
    #   u2 = Bundler::URI.parse(s) #=> #<Bundler::URI::HTTP http://example.com/ABCD>
    #   u1 == u2 #=> true
    #   u1.eql?(u2) #=> false
    #
    def initialize(opts = {})
      @pattern = initialize_pattern(opts)
      @pattern.each_value(&:freeze)
      @pattern.freeze

      @regexp = initialize_regexp(@pattern)
      @regexp.each_value(&:freeze)
      @regexp.freeze
    end

    # The Hash of patterns.
    #
    # See also Bundler::URI::Parser.initialize_pattern.
    attr_reader :pattern

    # The Hash of Regexp.
    #
    # See also Bundler::URI::Parser.initialize_regexp.
    attr_reader :regexp

    # Returns a split Bundler::URI against regexp[:ABS_URI].
    def split(uri)
      case uri
      when ''
        # null uri

      when @regexp[:ABS_URI]
        scheme, opaque, userinfo, host, port,
          registry, path, query, fragment = $~[1..-1]

        # Bundler::URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]

        # absoluteURI   = scheme ":" ( hier_part | opaque_part )
        # hier_part     = ( net_path | abs_path ) [ "?" query ]
        # opaque_part   = uric_no_slash *uric

        # abs_path      = "/"  path_segments
        # net_path      = "//" authority [ abs_path ]

        # authority     = server | reg_name
        # server        = [ [ userinfo "@" ] hostport ]

        if !scheme
          raise InvalidURIError,
            "bad Bundler::URI(absolute but no scheme): #{uri}"
        end
        if !opaque && (!path && (!host && !registry))
          raise InvalidURIError,
            "bad Bundler::URI(absolute but no path): #{uri}"
        end

      when @regexp[:REL_URI]
        scheme = nil
        opaque = nil

        userinfo, host, port, registry,
          rel_segment, abs_path, query, fragment = $~[1..-1]
        if rel_segment && abs_path
          path = rel_segment + abs_path
        elsif rel_segment
          path = rel_segment
        elsif abs_path
          path = abs_path
        end

        # Bundler::URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]

        # relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]

        # net_path      = "//" authority [ abs_path ]
        # abs_path      = "/"  path_segments
        # rel_path      = rel_segment [ abs_path ]

        # authority     = server | reg_name
        # server        = [ [ userinfo "@" ] hostport ]

      else
        raise InvalidURIError, "bad Bundler::URI(is not Bundler::URI?): #{uri}"
      end

      path = '' if !path && !opaque # (see RFC2396 Section 5.2)
      ret = [
        scheme,
        userinfo, host, port,         # X
        registry,                     # X
        path,                         # Y
        opaque,                       # Y
        query,
        fragment
      ]
      return ret
    end

    #
    # == Args
    #
    # +uri+::
    #    String
    #
    # == Description
    #
    # Parses +uri+ and constructs either matching Bundler::URI scheme object
    # (File, FTP, HTTP, HTTPS, LDAP, LDAPS, or MailTo) or Bundler::URI::Generic.
    #
    # == Usage
    #
    #   p = Bundler::URI::Parser.new
    #   p.parse("ldap://ldap.example.com/dc=example?user=john")
    #   #=> #<Bundler::URI::LDAP ldap://ldap.example.com/dc=example?user=john>
    #
    def parse(uri)
      scheme, userinfo, host, port,
        registry, path, opaque, query, fragment = self.split(uri)

      if scheme && Bundler::URI.scheme_list.include?(scheme.upcase)
        Bundler::URI.scheme_list[scheme.upcase].new(scheme, userinfo, host, port,
                                           registry, path, opaque, query,
                                           fragment, self)
      else
        Generic.new(scheme, userinfo, host, port,
                    registry, path, opaque, query,
                    fragment, self)
      end
    end


    #
    # == Args
    #
    # +uris+::
    #    an Array of Strings
    #
    # == Description
    #
    # Attempts to parse and merge a set of URIs.
    #
    def join(*uris)
      uris[0] = convert_to_uri(uris[0])
      uris.inject :merge
    end

    #
    # :call-seq:
    #   extract( str )
    #   extract( str, schemes )
    #   extract( str, schemes ) {|item| block }
    #
    # == Args
    #
    # +str+::
    #    String to search
    # +schemes+::
    #    Patterns to apply to +str+
    #
    # == Description
    #
    # Attempts to parse and merge a set of URIs.
    # If no +block+ given, then returns the result,
    # else it calls +block+ for each element in result.
    #
    # See also Bundler::URI::Parser.make_regexp.
    #
    def extract(str, schemes = nil)
      if block_given?
        str.scan(make_regexp(schemes)) { yield $& }
        nil
      else
        result = []
        str.scan(make_regexp(schemes)) { result.push $& }
        result
      end
    end

    # Returns Regexp that is default self.regexp[:ABS_URI_REF],
    # unless +schemes+ is provided. Then it is a Regexp.union with self.pattern[:X_ABS_URI].
    def make_regexp(schemes = nil)
      unless schemes
        @regexp[:ABS_URI_REF]
      else
        /(?=#{Regexp.union(*schemes)}:)#{@pattern[:X_ABS_URI]}/x
      end
    end

    #
    # :call-seq:
    #   escape( str )
    #   escape( str, unsafe )
    #
    # == Args
    #
    # +str+::
    #    String to make safe
    # +unsafe+::
    #    Regexp to apply. Defaults to self.regexp[:UNSAFE]
    #
    # == Description
    #
    # Constructs a safe String from +str+, removing unsafe characters,
    # replacing them with codes.
    #
    def escape(str, unsafe = @regexp[:UNSAFE])
      unless unsafe.kind_of?(Regexp)
        # perhaps unsafe is String object
        unsafe = Regexp.new("[#{Regexp.quote(unsafe)}]", false)
      end
      str.gsub(unsafe) do
        us = $&
        tmp = ''
        us.each_byte do |uc|
          tmp << sprintf('%%%02X', uc)
        end
        tmp
      end.force_encoding(Encoding::US_ASCII)
    end

    #
    # :call-seq:
    #   unescape( str )
    #   unescape( str, escaped )
    #
    # == Args
    #
    # +str+::
    #    String to remove escapes from
    # +escaped+::
    #    Regexp to apply. Defaults to self.regexp[:ESCAPED]
    #
    # == Description
    #
    # Removes escapes from +str+.
    #
    def unescape(str, escaped = @regexp[:ESCAPED])
      enc = str.encoding
      enc = Encoding::UTF_8 if enc == Encoding::US_ASCII
      str.gsub(escaped) { [$&[1, 2]].pack('H2').force_encoding(enc) }
    end

    @@to_s = Kernel.instance_method(:to_s)
    def inspect
      @@to_s.bind_call(self)
    end

    private

    # Constructs the default Hash of patterns.
    def initialize_pattern(opts = {})
      ret = {}
      ret[:ESCAPED] = escaped = (opts.delete(:ESCAPED) || PATTERN::ESCAPED)
      ret[:UNRESERVED] = unreserved = opts.delete(:UNRESERVED) || PATTERN::UNRESERVED
      ret[:RESERVED] = reserved = opts.delete(:RESERVED) || PATTERN::RESERVED
      ret[:DOMLABEL] = opts.delete(:DOMLABEL) || PATTERN::DOMLABEL
      ret[:TOPLABEL] = opts.delete(:TOPLABEL) || PATTERN::TOPLABEL
      ret[:HOSTNAME] = hostname = opts.delete(:HOSTNAME)

      # RFC 2396 (Bundler::URI Generic Syntax)
      # RFC 2732 (IPv6 Literal Addresses in URL's)
      # RFC 2373 (IPv6 Addressing Architecture)

      # uric          = reserved | unreserved | escaped
      ret[:URIC] = uric = "(?:[#{unreserved}#{reserved}]|#{escaped})"
      # uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
      #                 "&" | "=" | "+" | "$" | ","
      ret[:URIC_NO_SLASH] = uric_no_slash = "(?:[#{unreserved};?:@&=+$,]|#{escaped})"
      # query         = *uric
      ret[:QUERY] = query = "#{uric}*"
      # fragment      = *uric
      ret[:FRAGMENT] = fragment = "#{uric}*"

      # hostname      = *( domainlabel "." ) toplabel [ "." ]
      # reg-name      = *( unreserved / pct-encoded / sub-delims ) # RFC3986
      unless hostname
        ret[:HOSTNAME] = hostname = "(?:[a-zA-Z0-9\\-.]|%\\h\\h)+"
      end

      # RFC 2373, APPENDIX B:
      # IPv6address = hexpart [ ":" IPv4address ]
      # IPv4address   = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
      # hexpart = hexseq | hexseq "::" [ hexseq ] | "::" [ hexseq ]
      # hexseq  = hex4 *( ":" hex4)
      # hex4    = 1*4HEXDIG
      #
      # XXX: This definition has a flaw. "::" + IPv4address must be
      # allowed too.  Here is a replacement.
      #
      # IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
      ret[:IPV4ADDR] = ipv4addr = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"
      # hex4     = 1*4HEXDIG
      hex4 = "[#{PATTERN::HEX}]{1,4}"
      # lastpart = hex4 | IPv4address
      lastpart = "(?:#{hex4}|#{ipv4addr})"
      # hexseq1  = *( hex4 ":" ) hex4
      hexseq1 = "(?:#{hex4}:)*#{hex4}"
      # hexseq2  = *( hex4 ":" ) lastpart
      hexseq2 = "(?:#{hex4}:)*#{lastpart}"
      # IPv6address = hexseq2 | [ hexseq1 ] "::" [ hexseq2 ]
      ret[:IPV6ADDR] = ipv6addr = "(?:#{hexseq2}|(?:#{hexseq1})?::(?:#{hexseq2})?)"

      # IPv6prefix  = ( hexseq1 | [ hexseq1 ] "::" [ hexseq1 ] ) "/" 1*2DIGIT
      # unused

      # ipv6reference = "[" IPv6address "]" (RFC 2732)
      ret[:IPV6REF] = ipv6ref = "\\[#{ipv6addr}\\]"

      # host          = hostname | IPv4address
      # host          = hostname | IPv4address | IPv6reference (RFC 2732)
      ret[:HOST] = host = "(?:#{hostname}|#{ipv4addr}|#{ipv6ref})"
      # port          = *digit
      ret[:PORT] = port = '\d*'
      # hostport      = host [ ":" port ]
      ret[:HOSTPORT] = hostport = "#{host}(?::#{port})?"

      # userinfo      = *( unreserved | escaped |
      #                    ";" | ":" | "&" | "=" | "+" | "$" | "," )
      ret[:USERINFO] = userinfo = "(?:[#{unreserved};:&=+$,]|#{escaped})*"

      # pchar         = unreserved | escaped |
      #                 ":" | "@" | "&" | "=" | "+" | "$" | ","
      pchar = "(?:[#{unreserved}:@&=+$,]|#{escaped})"
      # param         = *pchar
      param = "#{pchar}*"
      # segment       = *pchar *( ";" param )
      segment = "#{pchar}*(?:;#{param})*"
      # path_segments = segment *( "/" segment )
      ret[:PATH_SEGMENTS] = path_segments = "#{segment}(?:/#{segment})*"

      # server        = [ [ userinfo "@" ] hostport ]
      server = "(?:#{userinfo}@)?#{hostport}"
      # reg_name      = 1*( unreserved | escaped | "$" | "," |
      #                     ";" | ":" | "@" | "&" | "=" | "+" )
      ret[:REG_NAME] = reg_name = "(?:[#{unreserved}$,;:@&=+]|#{escaped})+"
      # authority     = server | reg_name
      authority = "(?:#{server}|#{reg_name})"

      # rel_segment   = 1*( unreserved | escaped |
      #                     ";" | "@" | "&" | "=" | "+" | "$" | "," )
      ret[:REL_SEGMENT] = rel_segment = "(?:[#{unreserved};@&=+$,]|#{escaped})+"

      # scheme        = alpha *( alpha | digit | "+" | "-" | "." )
      ret[:SCHEME] = scheme = "[#{PATTERN::ALPHA}][\\-+.#{PATTERN::ALPHA}\\d]*"

      # abs_path      = "/"  path_segments
      ret[:ABS_PATH] = abs_path = "/#{path_segments}"
      # rel_path      = rel_segment [ abs_path ]
      ret[:REL_PATH] = rel_path = "#{rel_segment}(?:#{abs_path})?"
      # net_path      = "//" authority [ abs_path ]
      ret[:NET_PATH] = net_path = "//#{authority}(?:#{abs_path})?"

      # hier_part     = ( net_path | abs_path ) [ "?" query ]
      ret[:HIER_PART] = hier_part = "(?:#{net_path}|#{abs_path})(?:\\?(?:#{query}))?"
      # opaque_part   = uric_no_slash *uric
      ret[:OPAQUE_PART] = opaque_part = "#{uric_no_slash}#{uric}*"

      # absoluteURI   = scheme ":" ( hier_part | opaque_part )
      ret[:ABS_URI] = abs_uri = "#{scheme}:(?:#{hier_part}|#{opaque_part})"
      # relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]
      ret[:REL_URI] = rel_uri = "(?:#{net_path}|#{abs_path}|#{rel_path})(?:\\?#{query})?"

      # Bundler::URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
      ret[:URI_REF] = "(?:#{abs_uri}|#{rel_uri})?(?:##{fragment})?"

      ret[:X_ABS_URI] = "
        (#{scheme}):                           (?# 1: scheme)
        (?:
           (#{opaque_part})                    (?# 2: opaque)
        |
           (?:(?:
             //(?:
                 (?:(?:(#{userinfo})@)?        (?# 3: userinfo)
                   (?:(#{host})(?::(\\d*))?))? (?# 4: host, 5: port)
               |
                 (#{reg_name})                 (?# 6: registry)
               )
             |
             (?!//))                           (?# XXX: '//' is the mark for hostport)
             (#{abs_path})?                    (?# 7: path)
           )(?:\\?(#{query}))?                 (?# 8: query)
        )
        (?:\\#(#{fragment}))?                  (?# 9: fragment)
      "

      ret[:X_REL_URI] = "
        (?:
          (?:
            //
            (?:
              (?:(#{userinfo})@)?       (?# 1: userinfo)
                (#{host})?(?::(\\d*))?  (?# 2: host, 3: port)
            |
              (#{reg_name})             (?# 4: registry)
            )
          )
        |
          (#{rel_segment})              (?# 5: rel_segment)
        )?
        (#{abs_path})?                  (?# 6: abs_path)
        (?:\\?(#{query}))?              (?# 7: query)
        (?:\\#(#{fragment}))?           (?# 8: fragment)
      "

      ret
    end

    # Constructs the default Hash of Regexp's.
    def initialize_regexp(pattern)
      ret = {}

      # for Bundler::URI::split
      ret[:ABS_URI] = Regexp.new('\A\s*+' + pattern[:X_ABS_URI] + '\s*\z', Regexp::EXTENDED)
      ret[:REL_URI] = Regexp.new('\A\s*+' + pattern[:X_REL_URI] + '\s*\z', Regexp::EXTENDED)

      # for Bundler::URI::extract
      ret[:URI_REF]     = Regexp.new(pattern[:URI_REF])
      ret[:ABS_URI_REF] = Regexp.new(pattern[:X_ABS_URI], Regexp::EXTENDED)
      ret[:REL_URI_REF] = Regexp.new(pattern[:X_REL_URI], Regexp::EXTENDED)

      # for Bundler::URI::escape/unescape
      ret[:ESCAPED] = Regexp.new(pattern[:ESCAPED])
      ret[:UNSAFE]  = Regexp.new("[^#{pattern[:UNRESERVED]}#{pattern[:RESERVED]}]")

      # for Generic#initialize
      ret[:SCHEME]   = Regexp.new("\\A#{pattern[:SCHEME]}\\z")
      ret[:USERINFO] = Regexp.new("\\A#{pattern[:USERINFO]}\\z")
      ret[:HOST]     = Regexp.new("\\A#{pattern[:HOST]}\\z")
      ret[:PORT]     = Regexp.new("\\A#{pattern[:PORT]}\\z")
      ret[:OPAQUE]   = Regexp.new("\\A#{pattern[:OPAQUE_PART]}\\z")
      ret[:REGISTRY] = Regexp.new("\\A#{pattern[:REG_NAME]}\\z")
      ret[:ABS_PATH] = Regexp.new("\\A#{pattern[:ABS_PATH]}\\z")
      ret[:REL_PATH] = Regexp.new("\\A#{pattern[:REL_PATH]}\\z")
      ret[:QUERY]    = Regexp.new("\\A#{pattern[:QUERY]}\\z")
      ret[:FRAGMENT] = Regexp.new("\\A#{pattern[:FRAGMENT]}\\z")

      ret
    end

    def convert_to_uri(uri)
      if uri.is_a?(Bundler::URI::Generic)
        uri
      elsif uri = String.try_convert(uri)
        parse(uri)
      else
        raise ArgumentError,
          "bad argument (expected Bundler::URI object or Bundler::URI string)"
      end
    end

  end # class Parser
end # module Bundler::URI
module Bundler::URI
  # :stopdoc:
  VERSION_CODE = '00100003'.freeze
  VERSION = VERSION_CODE.scan(/../).collect{|n| n.to_i}.join('.').freeze
  # :startdoc:
end
# frozen_string_literal: true

# = uri/generic.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# License:: You can redistribute it and/or modify it under the same term as Ruby.
# Revision:: $Id$
#
# See Bundler::URI for general documentation
#

require_relative 'common'
autoload :IPSocket, 'socket'
autoload :IPAddr, 'ipaddr'

module Bundler::URI

  #
  # Base class for all Bundler::URI classes.
  # Implements generic Bundler::URI syntax as per RFC 2396.
  #
  class Generic
    include Bundler::URI

    #
    # A Default port of nil for Bundler::URI::Generic.
    #
    DEFAULT_PORT = nil

    #
    # Returns default port.
    #
    def self.default_port
      self::DEFAULT_PORT
    end

    #
    # Returns default port.
    #
    def default_port
      self.class.default_port
    end

    #
    # An Array of the available components for Bundler::URI::Generic.
    #
    COMPONENT = [
      :scheme,
      :userinfo, :host, :port, :registry,
      :path, :opaque,
      :query,
      :fragment
    ].freeze

    #
    # Components of the Bundler::URI in the order.
    #
    def self.component
      self::COMPONENT
    end

    USE_REGISTRY = false # :nodoc:

    def self.use_registry # :nodoc:
      self::USE_REGISTRY
    end

    #
    # == Synopsis
    #
    # See ::new.
    #
    # == Description
    #
    # At first, tries to create a new Bundler::URI::Generic instance using
    # Bundler::URI::Generic::build. But, if exception Bundler::URI::InvalidComponentError is raised,
    # then it does Bundler::URI::Escape.escape all Bundler::URI components and tries again.
    #
    def self.build2(args)
      begin
        return self.build(args)
      rescue InvalidComponentError
        if args.kind_of?(Array)
          return self.build(args.collect{|x|
            if x.is_a?(String)
              DEFAULT_PARSER.escape(x)
            else
              x
            end
          })
        elsif args.kind_of?(Hash)
          tmp = {}
          args.each do |key, value|
            tmp[key] = if value
                DEFAULT_PARSER.escape(value)
              else
                value
              end
          end
          return self.build(tmp)
        end
      end
    end

    #
    # == Synopsis
    #
    # See ::new.
    #
    # == Description
    #
    # Creates a new Bundler::URI::Generic instance from components of Bundler::URI::Generic
    # with check.  Components are: scheme, userinfo, host, port, registry, path,
    # opaque, query, and fragment. You can provide arguments either by an Array or a Hash.
    # See ::new for hash keys to use or for order of array items.
    #
    def self.build(args)
      if args.kind_of?(Array) &&
          args.size == ::Bundler::URI::Generic::COMPONENT.size
        tmp = args.dup
      elsif args.kind_of?(Hash)
        tmp = ::Bundler::URI::Generic::COMPONENT.collect do |c|
          if args.include?(c)
            args[c]
          else
            nil
          end
        end
      else
        component = self.class.component rescue ::Bundler::URI::Generic::COMPONENT
        raise ArgumentError,
        "expected Array of or Hash of components of #{self.class} (#{component.join(', ')})"
      end

      tmp << nil
      tmp << true
      return self.new(*tmp)
    end

    #
    # == Args
    #
    # +scheme+::
    #   Protocol scheme, i.e. 'http','ftp','mailto' and so on.
    # +userinfo+::
    #   User name and password, i.e. 'sdmitry:bla'.
    # +host+::
    #   Server host name.
    # +port+::
    #   Server port.
    # +registry+::
    #   Registry of naming authorities.
    # +path+::
    #   Path on server.
    # +opaque+::
    #   Opaque part.
    # +query+::
    #   Query data.
    # +fragment+::
    #   Part of the Bundler::URI after '#' character.
    # +parser+::
    #   Parser for internal use [Bundler::URI::DEFAULT_PARSER by default].
    # +arg_check+::
    #   Check arguments [false by default].
    #
    # == Description
    #
    # Creates a new Bundler::URI::Generic instance from ``generic'' components without check.
    #
    def initialize(scheme,
                   userinfo, host, port, registry,
                   path, opaque,
                   query,
                   fragment,
                   parser = DEFAULT_PARSER,
                   arg_check = false)
      @scheme = nil
      @user = nil
      @password = nil
      @host = nil
      @port = nil
      @path = nil
      @query = nil
      @opaque = nil
      @fragment = nil
      @parser = parser == DEFAULT_PARSER ? nil : parser

      if arg_check
        self.scheme = scheme
        self.userinfo = userinfo
        self.hostname = host
        self.port = port
        self.path = path
        self.query = query
        self.opaque = opaque
        self.fragment = fragment
      else
        self.set_scheme(scheme)
        self.set_userinfo(userinfo)
        self.set_host(host)
        self.set_port(port)
        self.set_path(path)
        self.query = query
        self.set_opaque(opaque)
        self.fragment=(fragment)
      end
      if registry
        raise InvalidURIError,
          "the scheme #{@scheme} does not accept registry part: #{registry} (or bad hostname?)"
      end

      @scheme&.freeze
      self.set_path('') if !@path && !@opaque # (see RFC2396 Section 5.2)
      self.set_port(self.default_port) if self.default_port && !@port
    end

    #
    # Returns the scheme component of the Bundler::URI.
    #
    #   Bundler::URI("http://foo/bar/baz").scheme #=> "http"
    #
    attr_reader :scheme

    # Returns the host component of the Bundler::URI.
    #
    #   Bundler::URI("http://foo/bar/baz").host #=> "foo"
    #
    # It returns nil if no host component exists.
    #
    #   Bundler::URI("mailto:foo@example.org").host #=> nil
    #
    # The component does not contain the port number.
    #
    #   Bundler::URI("http://foo:8080/bar/baz").host #=> "foo"
    #
    # Since IPv6 addresses are wrapped with brackets in URIs,
    # this method returns IPv6 addresses wrapped with brackets.
    # This form is not appropriate to pass to socket methods such as TCPSocket.open.
    # If unwrapped host names are required, use the #hostname method.
    #
    #   Bundler::URI("http://[::1]/bar/baz").host     #=> "[::1]"
    #   Bundler::URI("http://[::1]/bar/baz").hostname #=> "::1"
    #
    attr_reader :host

    # Returns the port component of the Bundler::URI.
    #
    #   Bundler::URI("http://foo/bar/baz").port      #=> 80
    #   Bundler::URI("http://foo:8080/bar/baz").port #=> 8080
    #
    attr_reader :port

    def registry # :nodoc:
      nil
    end

    # Returns the path component of the Bundler::URI.
    #
    #   Bundler::URI("http://foo/bar/baz").path #=> "/bar/baz"
    #
    attr_reader :path

    # Returns the query component of the Bundler::URI.
    #
    #   Bundler::URI("http://foo/bar/baz?search=FooBar").query #=> "search=FooBar"
    #
    attr_reader :query

    # Returns the opaque part of the Bundler::URI.
    #
    #   Bundler::URI("mailto:foo@example.org").opaque #=> "foo@example.org"
    #   Bundler::URI("http://foo/bar/baz").opaque     #=> nil
    #
    # The portion of the path that does not make use of the slash '/'.
    # The path typically refers to an absolute path or an opaque part.
    # (See RFC2396 Section 3 and 5.2.)
    #
    attr_reader :opaque

    # Returns the fragment component of the Bundler::URI.
    #
    #   Bundler::URI("http://foo/bar/baz?search=FooBar#ponies").fragment #=> "ponies"
    #
    attr_reader :fragment

    # Returns the parser to be used.
    #
    # Unless a Bundler::URI::Parser is defined, DEFAULT_PARSER is used.
    #
    def parser
      if !defined?(@parser) || !@parser
        DEFAULT_PARSER
      else
        @parser || DEFAULT_PARSER
      end
    end

    # Replaces self by other Bundler::URI object.
    #
    def replace!(oth)
      if self.class != oth.class
        raise ArgumentError, "expected #{self.class} object"
      end

      component.each do |c|
        self.__send__("#{c}=", oth.__send__(c))
      end
    end
    private :replace!

    #
    # Components of the Bundler::URI in the order.
    #
    def component
      self.class.component
    end

    #
    # Checks the scheme +v+ component against the Bundler::URI::Parser Regexp for :SCHEME.
    #
    def check_scheme(v)
      if v && parser.regexp[:SCHEME] !~ v
        raise InvalidComponentError,
          "bad component(expected scheme component): #{v}"
      end

      return true
    end
    private :check_scheme

    # Protected setter for the scheme component +v+.
    #
    # See also Bundler::URI::Generic.scheme=.
    #
    def set_scheme(v)
      @scheme = v&.downcase
    end
    protected :set_scheme

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the scheme component +v+
    # (with validation).
    #
    # See also Bundler::URI::Generic.check_scheme.
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   uri = Bundler::URI.parse("http://my.example.com")
    #   uri.scheme = "https"
    #   uri.to_s  #=> "https://my.example.com"
    #
    def scheme=(v)
      check_scheme(v)
      set_scheme(v)
      v
    end

    #
    # Checks the +user+ and +password+.
    #
    # If +password+ is not provided, then +user+ is
    # split, using Bundler::URI::Generic.split_userinfo, to
    # pull +user+ and +password.
    #
    # See also Bundler::URI::Generic.check_user, Bundler::URI::Generic.check_password.
    #
    def check_userinfo(user, password = nil)
      if !password
        user, password = split_userinfo(user)
      end
      check_user(user)
      check_password(password, user)

      return true
    end
    private :check_userinfo

    #
    # Checks the user +v+ component for RFC2396 compliance
    # and against the Bundler::URI::Parser Regexp for :USERINFO.
    #
    # Can not have a registry or opaque component defined,
    # with a user component defined.
    #
    def check_user(v)
      if @opaque
        raise InvalidURIError,
          "can not set user with opaque"
      end

      return v unless v

      if parser.regexp[:USERINFO] !~ v
        raise InvalidComponentError,
          "bad component(expected userinfo component or user component): #{v}"
      end

      return true
    end
    private :check_user

    #
    # Checks the password +v+ component for RFC2396 compliance
    # and against the Bundler::URI::Parser Regexp for :USERINFO.
    #
    # Can not have a registry or opaque component defined,
    # with a user component defined.
    #
    def check_password(v, user = @user)
      if @opaque
        raise InvalidURIError,
          "can not set password with opaque"
      end
      return v unless v

      if !user
        raise InvalidURIError,
          "password component depends user component"
      end

      if parser.regexp[:USERINFO] !~ v
        raise InvalidComponentError,
          "bad password component"
      end

      return true
    end
    private :check_password

    #
    # Sets userinfo, argument is string like 'name:pass'.
    #
    def userinfo=(userinfo)
      if userinfo.nil?
        return nil
      end
      check_userinfo(*userinfo)
      set_userinfo(*userinfo)
      # returns userinfo
    end

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the +user+ component
    # (with validation).
    #
    # See also Bundler::URI::Generic.check_user.
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   uri = Bundler::URI.parse("http://john:S3nsit1ve@my.example.com")
    #   uri.user = "sam"
    #   uri.to_s  #=> "http://sam:V3ry_S3nsit1ve@my.example.com"
    #
    def user=(user)
      check_user(user)
      set_user(user)
      # returns user
    end

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the +password+ component
    # (with validation).
    #
    # See also Bundler::URI::Generic.check_password.
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   uri = Bundler::URI.parse("http://john:S3nsit1ve@my.example.com")
    #   uri.password = "V3ry_S3nsit1ve"
    #   uri.to_s  #=> "http://john:V3ry_S3nsit1ve@my.example.com"
    #
    def password=(password)
      check_password(password)
      set_password(password)
      # returns password
    end

    # Protected setter for the +user+ component, and +password+ if available
    # (with validation).
    #
    # See also Bundler::URI::Generic.userinfo=.
    #
    def set_userinfo(user, password = nil)
      unless password
        user, password = split_userinfo(user)
      end
      @user     = user
      @password = password if password

      [@user, @password]
    end
    protected :set_userinfo

    # Protected setter for the user component +v+.
    #
    # See also Bundler::URI::Generic.user=.
    #
    def set_user(v)
      set_userinfo(v, @password)
      v
    end
    protected :set_user

    # Protected setter for the password component +v+.
    #
    # See also Bundler::URI::Generic.password=.
    #
    def set_password(v)
      @password = v
      # returns v
    end
    protected :set_password

    # Returns the userinfo +ui+ as <code>[user, password]</code>
    # if properly formatted as 'user:password'.
    def split_userinfo(ui)
      return nil, nil unless ui
      user, password = ui.split(':', 2)

      return user, password
    end
    private :split_userinfo

    # Escapes 'user:password' +v+ based on RFC 1738 section 3.1.
    def escape_userpass(v)
      parser.escape(v, /[@:\/]/o) # RFC 1738 section 3.1 #/
    end
    private :escape_userpass

    # Returns the userinfo, either as 'user' or 'user:password'.
    def userinfo
      if @user.nil?
        nil
      elsif @password.nil?
        @user
      else
        @user + ':' + @password
      end
    end

    # Returns the user component.
    def user
      @user
    end

    # Returns the password component.
    def password
      @password
    end

    #
    # Checks the host +v+ component for RFC2396 compliance
    # and against the Bundler::URI::Parser Regexp for :HOST.
    #
    # Can not have a registry or opaque component defined,
    # with a host component defined.
    #
    def check_host(v)
      return v unless v

      if @opaque
        raise InvalidURIError,
          "can not set host with registry or opaque"
      elsif parser.regexp[:HOST] !~ v
        raise InvalidComponentError,
          "bad component(expected host component): #{v}"
      end

      return true
    end
    private :check_host

    # Protected setter for the host component +v+.
    #
    # See also Bundler::URI::Generic.host=.
    #
    def set_host(v)
      @host = v
    end
    protected :set_host

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the host component +v+
    # (with validation).
    #
    # See also Bundler::URI::Generic.check_host.
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   uri = Bundler::URI.parse("http://my.example.com")
    #   uri.host = "foo.com"
    #   uri.to_s  #=> "http://foo.com"
    #
    def host=(v)
      check_host(v)
      set_host(v)
      v
    end

    # Extract the host part of the Bundler::URI and unwrap brackets for IPv6 addresses.
    #
    # This method is the same as Bundler::URI::Generic#host except
    # brackets for IPv6 (and future IP) addresses are removed.
    #
    #   uri = Bundler::URI("http://[::1]/bar")
    #   uri.hostname      #=> "::1"
    #   uri.host          #=> "[::1]"
    #
    def hostname
      v = self.host
      /\A\[(.*)\]\z/ =~ v ? $1 : v
    end

    # Sets the host part of the Bundler::URI as the argument with brackets for IPv6 addresses.
    #
    # This method is the same as Bundler::URI::Generic#host= except
    # the argument can be a bare IPv6 address.
    #
    #   uri = Bundler::URI("http://foo/bar")
    #   uri.hostname = "::1"
    #   uri.to_s  #=> "http://[::1]/bar"
    #
    # If the argument seems to be an IPv6 address,
    # it is wrapped with brackets.
    #
    def hostname=(v)
      v = "[#{v}]" if /\A\[.*\]\z/ !~ v && /:/ =~ v
      self.host = v
    end

    #
    # Checks the port +v+ component for RFC2396 compliance
    # and against the Bundler::URI::Parser Regexp for :PORT.
    #
    # Can not have a registry or opaque component defined,
    # with a port component defined.
    #
    def check_port(v)
      return v unless v

      if @opaque
        raise InvalidURIError,
          "can not set port with registry or opaque"
      elsif !v.kind_of?(Integer) && parser.regexp[:PORT] !~ v
        raise InvalidComponentError,
          "bad component(expected port component): #{v.inspect}"
      end

      return true
    end
    private :check_port

    # Protected setter for the port component +v+.
    #
    # See also Bundler::URI::Generic.port=.
    #
    def set_port(v)
      v = v.empty? ? nil : v.to_i unless !v || v.kind_of?(Integer)
      @port = v
    end
    protected :set_port

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the port component +v+
    # (with validation).
    #
    # See also Bundler::URI::Generic.check_port.
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   uri = Bundler::URI.parse("http://my.example.com")
    #   uri.port = 8080
    #   uri.to_s  #=> "http://my.example.com:8080"
    #
    def port=(v)
      check_port(v)
      set_port(v)
      port
    end

    def check_registry(v) # :nodoc:
      raise InvalidURIError, "can not set registry"
    end
    private :check_registry

    def set_registry(v) #:nodoc:
      raise InvalidURIError, "can not set registry"
    end
    protected :set_registry

    def registry=(v)
      raise InvalidURIError, "can not set registry"
    end

    #
    # Checks the path +v+ component for RFC2396 compliance
    # and against the Bundler::URI::Parser Regexp
    # for :ABS_PATH and :REL_PATH.
    #
    # Can not have a opaque component defined,
    # with a path component defined.
    #
    def check_path(v)
      # raise if both hier and opaque are not nil, because:
      # absoluteURI   = scheme ":" ( hier_part | opaque_part )
      # hier_part     = ( net_path | abs_path ) [ "?" query ]
      if v && @opaque
        raise InvalidURIError,
          "path conflicts with opaque"
      end

      # If scheme is ftp, path may be relative.
      # See RFC 1738 section 3.2.2, and RFC 2396.
      if @scheme && @scheme != "ftp"
        if v && v != '' && parser.regexp[:ABS_PATH] !~ v
          raise InvalidComponentError,
            "bad component(expected absolute path component): #{v}"
        end
      else
        if v && v != '' && parser.regexp[:ABS_PATH] !~ v &&
           parser.regexp[:REL_PATH] !~ v
          raise InvalidComponentError,
            "bad component(expected relative path component): #{v}"
        end
      end

      return true
    end
    private :check_path

    # Protected setter for the path component +v+.
    #
    # See also Bundler::URI::Generic.path=.
    #
    def set_path(v)
      @path = v
    end
    protected :set_path

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the path component +v+
    # (with validation).
    #
    # See also Bundler::URI::Generic.check_path.
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   uri = Bundler::URI.parse("http://my.example.com/pub/files")
    #   uri.path = "/faq/"
    #   uri.to_s  #=> "http://my.example.com/faq/"
    #
    def path=(v)
      check_path(v)
      set_path(v)
      v
    end

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the query component +v+.
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   uri = Bundler::URI.parse("http://my.example.com/?id=25")
    #   uri.query = "id=1"
    #   uri.to_s  #=> "http://my.example.com/?id=1"
    #
    def query=(v)
      return @query = nil unless v
      raise InvalidURIError, "query conflicts with opaque" if @opaque

      x = v.to_str
      v = x.dup if x.equal? v
      v.encode!(Encoding::UTF_8) rescue nil
      v.delete!("\t\r\n")
      v.force_encoding(Encoding::ASCII_8BIT)
      raise InvalidURIError, "invalid percent escape: #{$1}" if /(%\H\H)/n.match(v)
      v.gsub!(/(?!%\h\h|[!$-&(-;=?-_a-~])./n.freeze){'%%%02X' % $&.ord}
      v.force_encoding(Encoding::US_ASCII)
      @query = v
    end

    #
    # Checks the opaque +v+ component for RFC2396 compliance and
    # against the Bundler::URI::Parser Regexp for :OPAQUE.
    #
    # Can not have a host, port, user, or path component defined,
    # with an opaque component defined.
    #
    def check_opaque(v)
      return v unless v

      # raise if both hier and opaque are not nil, because:
      # absoluteURI   = scheme ":" ( hier_part | opaque_part )
      # hier_part     = ( net_path | abs_path ) [ "?" query ]
      if @host || @port || @user || @path  # userinfo = @user + ':' + @password
        raise InvalidURIError,
          "can not set opaque with host, port, userinfo or path"
      elsif v && parser.regexp[:OPAQUE] !~ v
        raise InvalidComponentError,
          "bad component(expected opaque component): #{v}"
      end

      return true
    end
    private :check_opaque

    # Protected setter for the opaque component +v+.
    #
    # See also Bundler::URI::Generic.opaque=.
    #
    def set_opaque(v)
      @opaque = v
    end
    protected :set_opaque

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the opaque component +v+
    # (with validation).
    #
    # See also Bundler::URI::Generic.check_opaque.
    #
    def opaque=(v)
      check_opaque(v)
      set_opaque(v)
      v
    end

    #
    # Checks the fragment +v+ component against the Bundler::URI::Parser Regexp for :FRAGMENT.
    #
    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the fragment component +v+
    # (with validation).
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   uri = Bundler::URI.parse("http://my.example.com/?id=25#time=1305212049")
    #   uri.fragment = "time=1305212086"
    #   uri.to_s  #=> "http://my.example.com/?id=25#time=1305212086"
    #
    def fragment=(v)
      return @fragment = nil unless v

      x = v.to_str
      v = x.dup if x.equal? v
      v.encode!(Encoding::UTF_8) rescue nil
      v.delete!("\t\r\n")
      v.force_encoding(Encoding::ASCII_8BIT)
      v.gsub!(/(?!%\h\h|[!-~])./n){'%%%02X' % $&.ord}
      v.force_encoding(Encoding::US_ASCII)
      @fragment = v
    end

    #
    # Returns true if Bundler::URI is hierarchical.
    #
    # == Description
    #
    # Bundler::URI has components listed in order of decreasing significance from left to right,
    # see RFC3986 https://tools.ietf.org/html/rfc3986 1.2.3.
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   uri = Bundler::URI.parse("http://my.example.com/")
    #   uri.hierarchical?
    #   #=> true
    #   uri = Bundler::URI.parse("mailto:joe@example.com")
    #   uri.hierarchical?
    #   #=> false
    #
    def hierarchical?
      if @path
        true
      else
        false
      end
    end

    #
    # Returns true if Bundler::URI has a scheme (e.g. http:// or https://) specified.
    #
    def absolute?
      if @scheme
        true
      else
        false
      end
    end
    alias absolute absolute?

    #
    # Returns true if Bundler::URI does not have a scheme (e.g. http:// or https://) specified.
    #
    def relative?
      !absolute?
    end

    #
    # Returns an Array of the path split on '/'.
    #
    def split_path(path)
      path.split("/", -1)
    end
    private :split_path

    #
    # Merges a base path +base+, with relative path +rel+,
    # returns a modified base path.
    #
    def merge_path(base, rel)

      # RFC2396, Section 5.2, 5)
      # RFC2396, Section 5.2, 6)
      base_path = split_path(base)
      rel_path  = split_path(rel)

      # RFC2396, Section 5.2, 6), a)
      base_path << '' if base_path.last == '..'
      while i = base_path.index('..')
        base_path.slice!(i - 1, 2)
      end

      if (first = rel_path.first) and first.empty?
        base_path.clear
        rel_path.shift
      end

      # RFC2396, Section 5.2, 6), c)
      # RFC2396, Section 5.2, 6), d)
      rel_path.push('') if rel_path.last == '.' || rel_path.last == '..'
      rel_path.delete('.')

      # RFC2396, Section 5.2, 6), e)
      tmp = []
      rel_path.each do |x|
        if x == '..' &&
            !(tmp.empty? || tmp.last == '..')
          tmp.pop
        else
          tmp << x
        end
      end

      add_trailer_slash = !tmp.empty?
      if base_path.empty?
        base_path = [''] # keep '/' for root directory
      elsif add_trailer_slash
        base_path.pop
      end
      while x = tmp.shift
        if x == '..'
          # RFC2396, Section 4
          # a .. or . in an absolute path has no special meaning
          base_path.pop if base_path.size > 1
        else
          # if x == '..'
          #   valid absolute (but abnormal) path "/../..."
          # else
          #   valid absolute path
          # end
          base_path << x
          tmp.each {|t| base_path << t}
          add_trailer_slash = false
          break
        end
      end
      base_path.push('') if add_trailer_slash

      return base_path.join('/')
    end
    private :merge_path

    #
    # == Args
    #
    # +oth+::
    #    Bundler::URI or String
    #
    # == Description
    #
    # Destructive form of #merge.
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   uri = Bundler::URI.parse("http://my.example.com")
    #   uri.merge!("/main.rbx?page=1")
    #   uri.to_s  # => "http://my.example.com/main.rbx?page=1"
    #
    def merge!(oth)
      t = merge(oth)
      if self == t
        nil
      else
        replace!(t)
        self
      end
    end

    #
    # == Args
    #
    # +oth+::
    #    Bundler::URI or String
    #
    # == Description
    #
    # Merges two URIs.
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   uri = Bundler::URI.parse("http://my.example.com")
    #   uri.merge("/main.rbx?page=1")
    #   # => "http://my.example.com/main.rbx?page=1"
    #
    def merge(oth)
      rel = parser.send(:convert_to_uri, oth)

      if rel.absolute?
        #raise BadURIError, "both Bundler::URI are absolute" if absolute?
        # hmm... should return oth for usability?
        return rel
      end

      unless self.absolute?
        raise BadURIError, "both Bundler::URI are relative"
      end

      base = self.dup

      authority = rel.userinfo || rel.host || rel.port

      # RFC2396, Section 5.2, 2)
      if (rel.path.nil? || rel.path.empty?) && !authority && !rel.query
        base.fragment=(rel.fragment) if rel.fragment
        return base
      end

      base.query = nil
      base.fragment=(nil)

      # RFC2396, Section 5.2, 4)
      if !authority
        base.set_path(merge_path(base.path, rel.path)) if base.path && rel.path
      else
        # RFC2396, Section 5.2, 4)
        base.set_path(rel.path) if rel.path
      end

      # RFC2396, Section 5.2, 7)
      base.set_userinfo(rel.userinfo) if rel.userinfo
      base.set_host(rel.host)         if rel.host
      base.set_port(rel.port)         if rel.port
      base.query = rel.query       if rel.query
      base.fragment=(rel.fragment) if rel.fragment

      return base
    end # merge
    alias + merge

    # :stopdoc:
    def route_from_path(src, dst)
      case dst
      when src
        # RFC2396, Section 4.2
        return ''
      when %r{(?:\A|/)\.\.?(?:/|\z)}
        # dst has abnormal absolute path,
        # like "/./", "/../", "/x/../", ...
        return dst.dup
      end

      src_path = src.scan(%r{[^/]*/})
      dst_path = dst.scan(%r{[^/]*/?})

      # discard same parts
      while !dst_path.empty? && dst_path.first == src_path.first
        src_path.shift
        dst_path.shift
      end

      tmp = dst_path.join

      # calculate
      if src_path.empty?
        if tmp.empty?
          return './'
        elsif dst_path.first.include?(':') # (see RFC2396 Section 5)
          return './' + tmp
        else
          return tmp
        end
      end

      return '../' * src_path.size + tmp
    end
    private :route_from_path
    # :startdoc:

    # :stopdoc:
    def route_from0(oth)
      oth = parser.send(:convert_to_uri, oth)
      if self.relative?
        raise BadURIError,
          "relative Bundler::URI: #{self}"
      end
      if oth.relative?
        raise BadURIError,
          "relative Bundler::URI: #{oth}"
      end

      if self.scheme != oth.scheme
        return self, self.dup
      end
      rel = Bundler::URI::Generic.new(nil, # it is relative Bundler::URI
                             self.userinfo, self.host, self.port,
                             nil, self.path, self.opaque,
                             self.query, self.fragment, parser)

      if rel.userinfo != oth.userinfo ||
          rel.host.to_s.downcase != oth.host.to_s.downcase ||
          rel.port != oth.port

        if self.userinfo.nil? && self.host.nil?
          return self, self.dup
        end

        rel.set_port(nil) if rel.port == oth.default_port
        return rel, rel
      end
      rel.set_userinfo(nil)
      rel.set_host(nil)
      rel.set_port(nil)

      if rel.path && rel.path == oth.path
        rel.set_path('')
        rel.query = nil if rel.query == oth.query
        return rel, rel
      elsif rel.opaque && rel.opaque == oth.opaque
        rel.set_opaque('')
        rel.query = nil if rel.query == oth.query
        return rel, rel
      end

      # you can modify `rel', but can not `oth'.
      return oth, rel
    end
    private :route_from0
    # :startdoc:

    #
    # == Args
    #
    # +oth+::
    #    Bundler::URI or String
    #
    # == Description
    #
    # Calculates relative path from oth to self.
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   uri = Bundler::URI.parse('http://my.example.com/main.rbx?page=1')
    #   uri.route_from('http://my.example.com')
    #   #=> #<Bundler::URI::Generic /main.rbx?page=1>
    #
    def route_from(oth)
      # you can modify `rel', but can not `oth'.
      begin
        oth, rel = route_from0(oth)
      rescue
        raise $!.class, $!.message
      end
      if oth == rel
        return rel
      end

      rel.set_path(route_from_path(oth.path, self.path))
      if rel.path == './' && self.query
        # "./?foo" -> "?foo"
        rel.set_path('')
      end

      return rel
    end

    alias - route_from

    #
    # == Args
    #
    # +oth+::
    #    Bundler::URI or String
    #
    # == Description
    #
    # Calculates relative path to oth from self.
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   uri = Bundler::URI.parse('http://my.example.com')
    #   uri.route_to('http://my.example.com/main.rbx?page=1')
    #   #=> #<Bundler::URI::Generic /main.rbx?page=1>
    #
    def route_to(oth)
      parser.send(:convert_to_uri, oth).route_from(self)
    end

    #
    # Returns normalized Bundler::URI.
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   Bundler::URI("HTTP://my.EXAMPLE.com").normalize
    #   #=> #<Bundler::URI::HTTP http://my.example.com/>
    #
    # Normalization here means:
    #
    # * scheme and host are converted to lowercase,
    # * an empty path component is set to "/".
    #
    def normalize
      uri = dup
      uri.normalize!
      uri
    end

    #
    # Destructive version of #normalize.
    #
    def normalize!
      if path&.empty?
        set_path('/')
      end
      if scheme && scheme != scheme.downcase
        set_scheme(self.scheme.downcase)
      end
      if host && host != host.downcase
        set_host(self.host.downcase)
      end
    end

    #
    # Constructs String from Bundler::URI.
    #
    def to_s
      str = ''.dup
      if @scheme
        str << @scheme
        str << ':'
      end

      if @opaque
        str << @opaque
      else
        if @host || %w[file postgres].include?(@scheme)
          str << '//'
        end
        if self.userinfo
          str << self.userinfo
          str << '@'
        end
        if @host
          str << @host
        end
        if @port && @port != self.default_port
          str << ':'
          str << @port.to_s
        end
        str << @path
        if @query
          str << '?'
          str << @query
        end
      end
      if @fragment
        str << '#'
        str << @fragment
      end
      str
    end

    #
    # Compares two URIs.
    #
    def ==(oth)
      if self.class == oth.class
        self.normalize.component_ary == oth.normalize.component_ary
      else
        false
      end
    end

    def hash
      self.component_ary.hash
    end

    def eql?(oth)
      self.class == oth.class &&
      parser == oth.parser &&
      self.component_ary.eql?(oth.component_ary)
    end

=begin

--- Bundler::URI::Generic#===(oth)

=end
#    def ===(oth)
#      raise NotImplementedError
#    end

=begin
=end


    # Returns an Array of the components defined from the COMPONENT Array.
    def component_ary
      component.collect do |x|
        self.send(x)
      end
    end
    protected :component_ary

    # == Args
    #
    # +components+::
    #    Multiple Symbol arguments defined in Bundler::URI::HTTP.
    #
    # == Description
    #
    # Selects specified components from Bundler::URI.
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   uri = Bundler::URI.parse('http://myuser:mypass@my.example.com/test.rbx')
    #   uri.select(:userinfo, :host, :path)
    #   # => ["myuser:mypass", "my.example.com", "/test.rbx"]
    #
    def select(*components)
      components.collect do |c|
        if component.include?(c)
          self.send(c)
        else
          raise ArgumentError,
            "expected of components of #{self.class} (#{self.class.component.join(', ')})"
        end
      end
    end

    def inspect
      "#<#{self.class} #{self}>"
    end

    #
    # == Args
    #
    # +v+::
    #    Bundler::URI or String
    #
    # == Description
    #
    # Attempts to parse other Bundler::URI +oth+,
    # returns [parsed_oth, self].
    #
    # == Usage
    #
    #   require 'bundler/vendor/uri/lib/uri'
    #
    #   uri = Bundler::URI.parse("http://my.example.com")
    #   uri.coerce("http://foo.com")
    #   #=> [#<Bundler::URI::HTTP http://foo.com>, #<Bundler::URI::HTTP http://my.example.com>]
    #
    def coerce(oth)
      case oth
      when String
        oth = parser.parse(oth)
      else
        super
      end

      return oth, self
    end

    # Returns a proxy Bundler::URI.
    # The proxy Bundler::URI is obtained from environment variables such as http_proxy,
    # ftp_proxy, no_proxy, etc.
    # If there is no proper proxy, nil is returned.
    #
    # If the optional parameter +env+ is specified, it is used instead of ENV.
    #
    # Note that capitalized variables (HTTP_PROXY, FTP_PROXY, NO_PROXY, etc.)
    # are examined, too.
    #
    # But http_proxy and HTTP_PROXY is treated specially under CGI environment.
    # It's because HTTP_PROXY may be set by Proxy: header.
    # So HTTP_PROXY is not used.
    # http_proxy is not used too if the variable is case insensitive.
    # CGI_HTTP_PROXY can be used instead.
    def find_proxy(env=ENV)
      raise BadURIError, "relative Bundler::URI: #{self}" if self.relative?
      name = self.scheme.downcase + '_proxy'
      proxy_uri = nil
      if name == 'http_proxy' && env.include?('REQUEST_METHOD') # CGI?
        # HTTP_PROXY conflicts with *_proxy for proxy settings and
        # HTTP_* for header information in CGI.
        # So it should be careful to use it.
        pairs = env.reject {|k, v| /\Ahttp_proxy\z/i !~ k }
        case pairs.length
        when 0 # no proxy setting anyway.
          proxy_uri = nil
        when 1
          k, _ = pairs.shift
          if k == 'http_proxy' && env[k.upcase] == nil
            # http_proxy is safe to use because ENV is case sensitive.
            proxy_uri = env[name]
          else
            proxy_uri = nil
          end
        else # http_proxy is safe to use because ENV is case sensitive.
          proxy_uri = env.to_hash[name]
        end
        if !proxy_uri
          # Use CGI_HTTP_PROXY.  cf. libwww-perl.
          proxy_uri = env["CGI_#{name.upcase}"]
        end
      elsif name == 'http_proxy'
        unless proxy_uri = env[name]
          if proxy_uri = env[name.upcase]
            warn 'The environment variable HTTP_PROXY is discouraged.  Use http_proxy.', uplevel: 1
          end
        end
      else
        proxy_uri = env[name] || env[name.upcase]
      end

      if proxy_uri.nil? || proxy_uri.empty?
        return nil
      end

      if self.hostname
        begin
          addr = IPSocket.getaddress(self.hostname)
          return nil if /\A127\.|\A::1\z/ =~ addr
        rescue SocketError
        end
      end

      name = 'no_proxy'
      if no_proxy = env[name] || env[name.upcase]
        return nil unless Bundler::URI::Generic.use_proxy?(self.hostname, addr, self.port, no_proxy)
      end
      Bundler::URI.parse(proxy_uri)
    end

    def self.use_proxy?(hostname, addr, port, no_proxy) # :nodoc:
      hostname = hostname.downcase
      dothostname = ".#{hostname}"
      no_proxy.scan(/([^:,\s]+)(?::(\d+))?/) {|p_host, p_port|
        if !p_port || port == p_port.to_i
          if p_host.start_with?('.')
            return false if hostname.end_with?(p_host.downcase)
          else
            return false if dothostname.end_with?(".#{p_host.downcase}")
          end
          if addr
            begin
              return false if IPAddr.new(p_host).include?(addr)
            rescue IPAddr::InvalidAddressError
              next
            end
          end
        end
      }
      true
    end
  end
end
Copyright (c) 2008 Yehuda Katz, Eric Hodel, 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.
require_relative "thor/base"

class Bundler::Thor
  $thor_runner ||= false
  class << self
    # Allows for custom "Command" package naming.
    #
    # === Parameters
    # name<String>
    # options<Hash>
    #
    def package_name(name, _ = {})
      @package_name = name.nil? || name == "" ? nil : name
    end

    # Sets the default command when thor is executed without an explicit command to be called.
    #
    # ==== Parameters
    # meth<Symbol>:: name of the default command
    #
    def default_command(meth = nil)
      if meth
        @default_command = meth == :none ? "help" : meth.to_s
      else
        @default_command ||= from_superclass(:default_command, "help")
      end
    end
    alias_method :default_task, :default_command

    # Registers another Bundler::Thor subclass as a command.
    #
    # ==== Parameters
    # klass<Class>:: Bundler::Thor subclass to register
    # command<String>:: Subcommand name to use
    # usage<String>:: Short usage for the subcommand
    # description<String>:: Description for the subcommand
    def register(klass, subcommand_name, usage, description, options = {})
      if klass <= Bundler::Thor::Group
        desc usage, description, options
        define_method(subcommand_name) { |*args| invoke(klass, args) }
      else
        desc usage, description, options
        subcommand subcommand_name, klass
      end
    end

    # Defines the usage and the description of the next command.
    #
    # ==== Parameters
    # usage<String>
    # description<String>
    # options<String>
    #
    def desc(usage, description, options = {})
      if options[:for]
        command = find_and_refresh_command(options[:for])
        command.usage = usage             if usage
        command.description = description if description
      else
        @usage = usage
        @desc = description
        @hide = options[:hide] || false
      end
    end

    # Defines the long description of the next command.
    #
    # ==== Parameters
    # long description<String>
    #
    def long_desc(long_description, options = {})
      if options[:for]
        command = find_and_refresh_command(options[:for])
        command.long_description = long_description if long_description
      else
        @long_desc = long_description
      end
    end

    # Maps an input to a command. If you define:
    #
    #   map "-T" => "list"
    #
    # Running:
    #
    #   thor -T
    #
    # Will invoke the list command.
    #
    # ==== Parameters
    # Hash[String|Array => Symbol]:: Maps the string or the strings in the array to the given command.
    #
    def map(mappings = nil, **kw)
      @map ||= from_superclass(:map, {})

      if mappings && !kw.empty?
        mappings = kw.merge!(mappings)
      else
        mappings ||= kw
      end
      if mappings
        mappings.each do |key, value|
          if key.respond_to?(:each)
            key.each { |subkey| @map[subkey] = value }
          else
            @map[key] = value
          end
        end
      end

      @map
    end

    # Declares the options for the next command to be declared.
    #
    # ==== Parameters
    # Hash[Symbol => Object]:: The hash key is the name of the option and the value
    # is the type of the option. Can be :string, :array, :hash, :boolean, :numeric
    # or :required (string). If you give a value, the type of the value is used.
    #
    def method_options(options = nil)
      @method_options ||= {}
      build_options(options, @method_options) if options
      @method_options
    end

    alias_method :options, :method_options

    # Adds an option to the set of method options. If :for is given as option,
    # it allows you to change the options from a previous defined command.
    #
    #   def previous_command
    #     # magic
    #   end
    #
    #   method_option :foo => :bar, :for => :previous_command
    #
    #   def next_command
    #     # magic
    #   end
    #
    # ==== Parameters
    # name<Symbol>:: The name of the argument.
    # options<Hash>:: Described below.
    #
    # ==== Options
    # :desc     - Description for the argument.
    # :required - If the argument is required or not.
    # :default  - Default value for this argument. It cannot be required and have default values.
    # :aliases  - Aliases for this option.
    # :type     - The type of the argument, can be :string, :hash, :array, :numeric or :boolean.
    # :banner   - String to show on usage notes.
    # :hide     - If you want to hide this option from the help.
    #
    def method_option(name, options = {})
      scope = if options[:for]
        find_and_refresh_command(options[:for]).options
      else
        method_options
      end

      build_option(name, options, scope)
    end
    alias_method :option, :method_option

    # Prints help information for the given command.
    #
    # ==== Parameters
    # shell<Bundler::Thor::Shell>
    # command_name<String>
    #
    def command_help(shell, command_name)
      meth = normalize_command_name(command_name)
      command = all_commands[meth]
      handle_no_command_error(meth) unless command

      shell.say "Usage:"
      shell.say "  #{banner(command).split("\n").join("\n  ")}"
      shell.say
      class_options_help(shell, nil => command.options.values)
      if command.long_description
        shell.say "Description:"
        shell.print_wrapped(command.long_description, :indent => 2)
      else
        shell.say command.description
      end
    end
    alias_method :task_help, :command_help

    # Prints help information for this class.
    #
    # ==== Parameters
    # shell<Bundler::Thor::Shell>
    #
    def help(shell, subcommand = false)
      list = printable_commands(true, subcommand)
      Bundler::Thor::Util.thor_classes_in(self).each do |klass|
        list += klass.printable_commands(false)
      end
      list.sort! { |a, b| a[0] <=> b[0] }

      if defined?(@package_name) && @package_name
        shell.say "#{@package_name} commands:"
      else
        shell.say "Commands:"
      end

      shell.print_table(list, :indent => 2, :truncate => true)
      shell.say
      class_options_help(shell)
    end

    # Returns commands ready to be printed.
    def printable_commands(all = true, subcommand = false)
      (all ? all_commands : commands).map do |_, command|
        next if command.hidden?
        item = []
        item << banner(command, false, subcommand)
        item << (command.description ? "# #{command.description.gsub(/\s+/m, ' ')}" : "")
        item
      end.compact
    end
    alias_method :printable_tasks, :printable_commands

    def subcommands
      @subcommands ||= from_superclass(:subcommands, [])
    end
    alias_method :subtasks, :subcommands

    def subcommand_classes
      @subcommand_classes ||= {}
    end

    def subcommand(subcommand, subcommand_class)
      subcommands << subcommand.to_s
      subcommand_class.subcommand_help subcommand
      subcommand_classes[subcommand.to_s] = subcommand_class

      define_method(subcommand) do |*args|
        args, opts = Bundler::Thor::Arguments.split(args)
        invoke_args = [args, opts, {:invoked_via_subcommand => true, :class_options => options}]
        invoke_args.unshift "help" if opts.delete("--help") || opts.delete("-h")
        invoke subcommand_class, *invoke_args
      end
      subcommand_class.commands.each do |_meth, command|
        command.ancestor_name = subcommand
      end
    end
    alias_method :subtask, :subcommand

    # Extend check unknown options to accept a hash of conditions.
    #
    # === Parameters
    # options<Hash>: A hash containing :only and/or :except keys
    def check_unknown_options!(options = {})
      @check_unknown_options ||= {}
      options.each do |key, value|
        if value
          @check_unknown_options[key] = Array(value)
        else
          @check_unknown_options.delete(key)
        end
      end
      @check_unknown_options
    end

    # Overwrite check_unknown_options? to take subcommands and options into account.
    def check_unknown_options?(config) #:nodoc:
      options = check_unknown_options
      return false unless options

      command = config[:current_command]
      return true unless command

      name = command.name

      if subcommands.include?(name)
        false
      elsif options[:except]
        !options[:except].include?(name.to_sym)
      elsif options[:only]
        options[:only].include?(name.to_sym)
      else
        true
      end
    end

    # Stop parsing of options as soon as an unknown option or a regular
    # argument is encountered.  All remaining arguments are passed to the command.
    # This is useful if you have a command that can receive arbitrary additional
    # options, and where those additional options should not be handled by
    # Bundler::Thor.
    #
    # ==== Example
    #
    # To better understand how this is useful, let's consider a command that calls
    # an external command.  A user may want to pass arbitrary options and
    # arguments to that command.  The command itself also accepts some options,
    # which should be handled by Bundler::Thor.
    #
    #   class_option "verbose",  :type => :boolean
    #   stop_on_unknown_option! :exec
    #   check_unknown_options!  :except => :exec
    #
    #   desc "exec", "Run a shell command"
    #   def exec(*args)
    #     puts "diagnostic output" if options[:verbose]
    #     Kernel.exec(*args)
    #   end
    #
    # Here +exec+ can be called with +--verbose+ to get diagnostic output,
    # e.g.:
    #
    #   $ thor exec --verbose echo foo
    #   diagnostic output
    #   foo
    #
    # But if +--verbose+ is given after +echo+, it is passed to +echo+ instead:
    #
    #   $ thor exec echo --verbose foo
    #   --verbose foo
    #
    # ==== Parameters
    # Symbol ...:: A list of commands that should be affected.
    def stop_on_unknown_option!(*command_names)
      @stop_on_unknown_option = stop_on_unknown_option | command_names
    end

    def stop_on_unknown_option?(command) #:nodoc:
      command && stop_on_unknown_option.include?(command.name.to_sym)
    end

    # Disable the check for required options for the given commands.
    # This is useful if you have a command that does not need the required options
    # to work, like help.
    #
    # ==== Parameters
    # Symbol ...:: A list of commands that should be affected.
    def disable_required_check!(*command_names)
      @disable_required_check = disable_required_check | command_names
    end

    def disable_required_check?(command) #:nodoc:
      command && disable_required_check.include?(command.name.to_sym)
    end

  protected

    def stop_on_unknown_option #:nodoc:
      @stop_on_unknown_option ||= []
    end

    # help command has the required check disabled by default.
    def disable_required_check #:nodoc:
      @disable_required_check ||= [:help]
    end

    # The method responsible for dispatching given the args.
    def dispatch(meth, given_args, given_opts, config) #:nodoc: # rubocop:disable MethodLength
      meth ||= retrieve_command_name(given_args)
      command = all_commands[normalize_command_name(meth)]

      if !command && config[:invoked_via_subcommand]
        # We're a subcommand and our first argument didn't match any of our
        # commands. So we put it back and call our default command.
        given_args.unshift(meth)
        command = all_commands[normalize_command_name(default_command)]
      end

      if command
        args, opts = Bundler::Thor::Options.split(given_args)
        if stop_on_unknown_option?(command) && !args.empty?
          # given_args starts with a non-option, so we treat everything as
          # ordinary arguments
          args.concat opts
          opts.clear
        end
      else
        args = given_args
        opts = nil
        command = dynamic_command_class.new(meth)
      end

      opts = given_opts || opts || []
      config[:current_command] = command
      config[:command_options] = command.options

      instance = new(args, opts, config)
      yield instance if block_given?
      args = instance.args
      trailing = args[Range.new(arguments.size, -1)]
      instance.invoke_command(command, trailing || [])
    end

    # The banner for this class. You can customize it if you are invoking the
    # thor class by another ways which is not the Bundler::Thor::Runner. It receives
    # the command that is going to be invoked and a boolean which indicates if
    # the namespace should be displayed as arguments.
    #
    def banner(command, namespace = nil, subcommand = false)
      command.formatted_usage(self, $thor_runner, subcommand).split("\n").map do |formatted_usage|
        "#{basename} #{formatted_usage}"
      end.join("\n")
    end

    def baseclass #:nodoc:
      Bundler::Thor
    end

    def dynamic_command_class #:nodoc:
      Bundler::Thor::DynamicCommand
    end

    def create_command(meth) #:nodoc:
      @usage ||= nil
      @desc ||= nil
      @long_desc ||= nil
      @hide ||= nil

      if @usage && @desc
        base_class = @hide ? Bundler::Thor::HiddenCommand : Bundler::Thor::Command
        commands[meth] = base_class.new(meth, @desc, @long_desc, @usage, method_options)
        @usage, @desc, @long_desc, @method_options, @hide = nil
        true
      elsif all_commands[meth] || meth == "method_missing"
        true
      else
        puts "[WARNING] Attempted to create command #{meth.inspect} without usage or description. " \
             "Call desc if you want this method to be available as command or declare it inside a " \
             "no_commands{} block. Invoked from #{caller[1].inspect}."
        false
      end
    end
    alias_method :create_task, :create_command

    def initialize_added #:nodoc:
      class_options.merge!(method_options)
      @method_options = nil
    end

    # Retrieve the command name from given args.
    def retrieve_command_name(args) #:nodoc:
      meth = args.first.to_s unless args.empty?
      args.shift if meth && (map[meth] || meth !~ /^\-/)
    end
    alias_method :retrieve_task_name, :retrieve_command_name

    # receives a (possibly nil) command name and returns a name that is in
    # the commands hash. In addition to normalizing aliases, this logic
    # will determine if a shortened command is an unambiguous substring of
    # a command or alias.
    #
    # +normalize_command_name+ also converts names like +animal-prison+
    # into +animal_prison+.
    def normalize_command_name(meth) #:nodoc:
      return default_command.to_s.tr("-", "_") unless meth

      possibilities = find_command_possibilities(meth)
      raise AmbiguousTaskError, "Ambiguous command #{meth} matches [#{possibilities.join(', ')}]" if possibilities.size > 1

      if possibilities.empty?
        meth ||= default_command
      elsif map[meth]
        meth = map[meth]
      else
        meth = possibilities.first
      end

      meth.to_s.tr("-", "_") # treat foo-bar as foo_bar
    end
    alias_method :normalize_task_name, :normalize_command_name

    # this is the logic that takes the command name passed in by the user
    # and determines whether it is an unambiguous substrings of a command or
    # alias name.
    def find_command_possibilities(meth)
      len = meth.to_s.length
      possibilities = all_commands.merge(map).keys.select { |n| meth == n[0, len] }.sort
      unique_possibilities = possibilities.map { |k| map[k] || k }.uniq

      if possibilities.include?(meth)
        [meth]
      elsif unique_possibilities.size == 1
        unique_possibilities
      else
        possibilities
      end
    end
    alias_method :find_task_possibilities, :find_command_possibilities

    def subcommand_help(cmd)
      desc "help [COMMAND]", "Describe subcommands or one specific subcommand"
      class_eval "
        def help(command = nil, subcommand = true); super; end
"
    end
    alias_method :subtask_help, :subcommand_help
  end

  include Bundler::Thor::Base

  map HELP_MAPPINGS => :help

  desc "help [COMMAND]", "Describe available commands or one specific command"
  def help(command = nil, subcommand = false)
    if command
      if self.class.subcommands.include? command
        self.class.subcommand_classes[command].help(shell, true)
      else
        self.class.command_help(shell, command)
      end
    else
      self.class.help(shell, subcommand)
    end
  end
end
require_relative "../thor"
require_relative "group"

require "yaml"
require "digest/md5"
require "pathname"

class Bundler::Thor::Runner < Bundler::Thor #:nodoc: # rubocop:disable ClassLength
  autoload :OpenURI, "open-uri"

  map "-T" => :list, "-i" => :install, "-u" => :update, "-v" => :version

  def self.banner(command, all = false, subcommand = false)
    "thor " + command.formatted_usage(self, all, subcommand)
  end

  def self.exit_on_failure?
    true
  end

  # Override Bundler::Thor#help so it can give information about any class and any method.
  #
  def help(meth = nil)
    if meth && !respond_to?(meth)
      initialize_thorfiles(meth)
      klass, command = Bundler::Thor::Util.find_class_and_command_by_namespace(meth)
      self.class.handle_no_command_error(command, false) if klass.nil?
      klass.start(["-h", command].compact, :shell => shell)
    else
      super
    end
  end

  # If a command is not found on Bundler::Thor::Runner, method missing is invoked and
  # Bundler::Thor::Runner is then responsible for finding the command in all classes.
  #
  def method_missing(meth, *args)
    meth = meth.to_s
    initialize_thorfiles(meth)
    klass, command = Bundler::Thor::Util.find_class_and_command_by_namespace(meth)
    self.class.handle_no_command_error(command, false) if klass.nil?
    args.unshift(command) if command
    klass.start(args, :shell => shell)
  end

  desc "install NAME", "Install an optionally named Bundler::Thor file into your system commands"
  method_options :as => :string, :relative => :boolean, :force => :boolean
  def install(name) # rubocop:disable MethodLength
    initialize_thorfiles

    # If a directory name is provided as the argument, look for a 'main.thor'
    # command in said directory.
    begin
      if File.directory?(File.expand_path(name))
        base = File.join(name, "main.thor")
        package = :directory
        contents = open(base, &:read)
      else
        base = name
        package = :file
        contents = open(name, &:read)
      end
    rescue OpenURI::HTTPError
      raise Error, "Error opening URI '#{name}'"
    rescue Errno::ENOENT
      raise Error, "Error opening file '#{name}'"
    end

    say "Your Thorfile contains:"
    say contents

    unless options["force"]
      return false if no?("Do you wish to continue [y/N]?")
    end

    as = options["as"] || begin
      first_line = contents.split("\n")[0]
      (match = first_line.match(/\s*#\s*module:\s*([^\n]*)/)) ? match[1].strip : nil
    end

    unless as
      basename = File.basename(name)
      as = ask("Please specify a name for #{name} in the system repository [#{basename}]:")
      as = basename if as.empty?
    end

    location = if options[:relative] || name =~ %r{^https?://}
      name
    else
      File.expand_path(name)
    end

    thor_yaml[as] = {
      :filename   => Digest::MD5.hexdigest(name + as),
      :location   => location,
      :namespaces => Bundler::Thor::Util.namespaces_in_content(contents, base)
    }

    save_yaml(thor_yaml)
    say "Storing thor file in your system repository"
    destination = File.join(thor_root, thor_yaml[as][:filename])

    if package == :file
      File.open(destination, "w") { |f| f.puts contents }
    else
      require "fileutils"
      FileUtils.cp_r(name, destination)
    end

    thor_yaml[as][:filename] # Indicate success
  end

  desc "version", "Show Bundler::Thor version"
  def version
    require_relative "version"
    say "Bundler::Thor #{Bundler::Thor::VERSION}"
  end

  desc "uninstall NAME", "Uninstall a named Bundler::Thor module"
  def uninstall(name)
    raise Error, "Can't find module '#{name}'" unless thor_yaml[name]
    say "Uninstalling #{name}."
    require "fileutils"
    FileUtils.rm_rf(File.join(thor_root, (thor_yaml[name][:filename]).to_s))

    thor_yaml.delete(name)
    save_yaml(thor_yaml)

    puts "Done."
  end

  desc "update NAME", "Update a Bundler::Thor file from its original location"
  def update(name)
    raise Error, "Can't find module '#{name}'" if !thor_yaml[name] || !thor_yaml[name][:location]

    say "Updating '#{name}' from #{thor_yaml[name][:location]}"

    old_filename = thor_yaml[name][:filename]
    self.options = options.merge("as" => name)

    if File.directory? File.expand_path(name)
      require "fileutils"
      FileUtils.rm_rf(File.join(thor_root, old_filename))

      thor_yaml.delete(old_filename)
      save_yaml(thor_yaml)

      filename = install(name)
    else
      filename = install(thor_yaml[name][:location])
    end

    File.delete(File.join(thor_root, old_filename)) unless filename == old_filename
  end

  desc "installed", "List the installed Bundler::Thor modules and commands"
  method_options :internal => :boolean
  def installed
    initialize_thorfiles(nil, true)
    display_klasses(true, options["internal"])
  end

  desc "list [SEARCH]", "List the available thor commands (--substring means .*SEARCH)"
  method_options :substring => :boolean, :group => :string, :all => :boolean, :debug => :boolean
  def list(search = "")
    initialize_thorfiles

    search = ".*#{search}" if options["substring"]
    search = /^#{search}.*/i
    group  = options[:group] || "standard"

    klasses = Bundler::Thor::Base.subclasses.select do |k|
      (options[:all] || k.group == group) && k.namespace =~ search
    end

    display_klasses(false, false, klasses)
  end

private

  def thor_root
    Bundler::Thor::Util.thor_root
  end

  def thor_yaml
    @thor_yaml ||= begin
      yaml_file = File.join(thor_root, "thor.yml")
      yaml = YAML.load_file(yaml_file) if File.exist?(yaml_file)
      yaml || {}
    end
  end

  # Save the yaml file. If none exists in thor root, creates one.
  #
  def save_yaml(yaml)
    yaml_file = File.join(thor_root, "thor.yml")

    unless File.exist?(yaml_file)
      require "fileutils"
      FileUtils.mkdir_p(thor_root)
      yaml_file = File.join(thor_root, "thor.yml")
      FileUtils.touch(yaml_file)
    end

    File.open(yaml_file, "w") { |f| f.puts yaml.to_yaml }
  end

  # Load the Thorfiles. If relevant_to is supplied, looks for specific files
  # in the thor_root instead of loading them all.
  #
  # By default, it also traverses the current path until find Bundler::Thor files, as
  # described in thorfiles. This look up can be skipped by supplying
  # skip_lookup true.
  #
  def initialize_thorfiles(relevant_to = nil, skip_lookup = false)
    thorfiles(relevant_to, skip_lookup).each do |f|
      Bundler::Thor::Util.load_thorfile(f, nil, options[:debug]) unless Bundler::Thor::Base.subclass_files.keys.include?(File.expand_path(f))
    end
  end

  # Finds Thorfiles by traversing from your current directory down to the root
  # directory of your system. If at any time we find a Bundler::Thor file, we stop.
  #
  # We also ensure that system-wide Thorfiles are loaded first, so local
  # Thorfiles can override them.
  #
  # ==== Example
  #
  # If we start at /Users/wycats/dev/thor ...
  #
  # 1. /Users/wycats/dev/thor
  # 2. /Users/wycats/dev
  # 3. /Users/wycats <-- we find a Thorfile here, so we stop
  #
  # Suppose we start at c:\Documents and Settings\james\dev\thor ...
  #
  # 1. c:\Documents and Settings\james\dev\thor
  # 2. c:\Documents and Settings\james\dev
  # 3. c:\Documents and Settings\james
  # 4. c:\Documents and Settings
  # 5. c:\ <-- no Thorfiles found!
  #
  def thorfiles(relevant_to = nil, skip_lookup = false)
    thorfiles = []

    unless skip_lookup
      Pathname.pwd.ascend do |path|
        thorfiles = Bundler::Thor::Util.globs_for(path).map { |g| Dir[g] }.flatten
        break unless thorfiles.empty?
      end
    end

    files  = (relevant_to ? thorfiles_relevant_to(relevant_to) : Bundler::Thor::Util.thor_root_glob)
    files += thorfiles
    files -= ["#{thor_root}/thor.yml"]

    files.map! do |file|
      File.directory?(file) ? File.join(file, "main.thor") : file
    end
  end

  # Load Thorfiles relevant to the given method. If you provide "foo:bar" it
  # will load all thor files in the thor.yaml that has "foo" e "foo:bar"
  # namespaces registered.
  #
  def thorfiles_relevant_to(meth)
    lookup = [meth, meth.split(":")[0...-1].join(":")]

    files = thor_yaml.select do |_, v|
      v[:namespaces] && !(v[:namespaces] & lookup).empty?
    end

    files.map { |_, v| File.join(thor_root, (v[:filename]).to_s) }
  end

  # Display information about the given klasses. If with_module is given,
  # it shows a table with information extracted from the yaml file.
  #
  def display_klasses(with_modules = false, show_internal = false, klasses = Bundler::Thor::Base.subclasses)
    klasses -= [Bundler::Thor, Bundler::Thor::Runner, Bundler::Thor::Group] unless show_internal

    raise Error, "No Bundler::Thor commands available" if klasses.empty?
    show_modules if with_modules && !thor_yaml.empty?

    list = Hash.new { |h, k| h[k] = [] }
    groups = klasses.select { |k| k.ancestors.include?(Bundler::Thor::Group) }

    # Get classes which inherit from Bundler::Thor
    (klasses - groups).each { |k| list[k.namespace.split(":").first] += k.printable_commands(false) }

    # Get classes which inherit from Bundler::Thor::Base
    groups.map! { |k| k.printable_commands(false).first }
    list["root"] = groups

    # Order namespaces with default coming first
    list = list.sort { |a, b| a[0].sub(/^default/, "") <=> b[0].sub(/^default/, "") }
    list.each { |n, commands| display_commands(n, commands) unless commands.empty? }
  end

  def display_commands(namespace, list) #:nodoc:
    list.sort! { |a, b| a[0] <=> b[0] }

    say shell.set_color(namespace, :blue, true)
    say "-" * namespace.size

    print_table(list, :truncate => true)
    say
  end
  alias_method :display_tasks, :display_commands

  def show_modules #:nodoc:
    info = []
    labels = %w(Modules Namespaces)

    info << labels
    info << ["-" * labels[0].size, "-" * labels[1].size]

    thor_yaml.each do |name, hash|
      info << [name, hash[:namespaces].join(", ")]
    end

    print_table info
    say ""
  end
end
require_relative "command"
require_relative "core_ext/hash_with_indifferent_access"
require_relative "error"
require_relative "invocation"
require_relative "nested_context"
require_relative "parser"
require_relative "shell"
require_relative "line_editor"
require_relative "util"

class Bundler::Thor
  autoload :Actions,    File.expand_path("actions", __dir__)
  autoload :RakeCompat, File.expand_path("rake_compat", __dir__)
  autoload :Group,      File.expand_path("group", __dir__)

  # Shortcuts for help.
  HELP_MAPPINGS       = %w(-h -? --help -D)

  # Bundler::Thor methods that should not be overwritten by the user.
  THOR_RESERVED_WORDS = %w(invoke shell options behavior root destination_root relative_root
                           action add_file create_file in_root inside run run_ruby_script)

  TEMPLATE_EXTNAME = ".tt"

  class << self
    def deprecation_warning(message) #:nodoc:
      unless ENV['THOR_SILENCE_DEPRECATION']
        warn "Deprecation warning: #{message}\n" +
          'You can silence deprecations warning by setting the environment variable THOR_SILENCE_DEPRECATION.'
      end
    end
  end

  module Base
    attr_accessor :options, :parent_options, :args

    # It receives arguments in an Array and two hashes, one for options and
    # other for configuration.
    #
    # Notice that it does not check if all required arguments were supplied.
    # It should be done by the parser.
    #
    # ==== Parameters
    # args<Array[Object]>:: An array of objects. The objects are applied to their
    #                       respective accessors declared with <tt>argument</tt>.
    #
    # options<Hash>:: An options hash that will be available as self.options.
    #                 The hash given is converted to a hash with indifferent
    #                 access, magic predicates (options.skip?) and then frozen.
    #
    # config<Hash>:: Configuration for this Bundler::Thor class.
    #
    def initialize(args = [], local_options = {}, config = {})
      parse_options = self.class.class_options

      # The start method splits inbound arguments at the first argument
      # that looks like an option (starts with - or --). It then calls
      # new, passing in the two halves of the arguments Array as the
      # first two parameters.

      command_options = config.delete(:command_options) # hook for start
      parse_options = parse_options.merge(command_options) if command_options
      if local_options.is_a?(Array)
        array_options = local_options
        hash_options = {}
      else
        # Handle the case where the class was explicitly instantiated
        # with pre-parsed options.
        array_options = []
        hash_options = local_options
      end

      # Let Bundler::Thor::Options parse the options first, so it can remove
      # declared options from the array. This will leave us with
      # a list of arguments that weren't declared.
      stop_on_unknown = self.class.stop_on_unknown_option? config[:current_command]
      disable_required_check = self.class.disable_required_check? config[:current_command]
      opts = Bundler::Thor::Options.new(parse_options, hash_options, stop_on_unknown, disable_required_check)
      self.options = opts.parse(array_options)
      self.options = config[:class_options].merge(options) if config[:class_options]

      # If unknown options are disallowed, make sure that none of the
      # remaining arguments looks like an option.
      opts.check_unknown! if self.class.check_unknown_options?(config)

      # Add the remaining arguments from the options parser to the
      # arguments passed in to initialize. Then remove any positional
      # arguments declared using #argument (this is primarily used
      # by Bundler::Thor::Group). Tis will leave us with the remaining
      # positional arguments.
      to_parse  = args
      to_parse += opts.remaining unless self.class.strict_args_position?(config)

      thor_args = Bundler::Thor::Arguments.new(self.class.arguments)
      thor_args.parse(to_parse).each { |k, v| __send__("#{k}=", v) }
      @args = thor_args.remaining
    end

    class << self
      def included(base) #:nodoc:
        super(base)
        base.extend ClassMethods
        base.send :include, Invocation
        base.send :include, Shell
      end

      # Returns the classes that inherits from Bundler::Thor or Bundler::Thor::Group.
      #
      # ==== Returns
      # Array[Class]
      #
      def subclasses
        @subclasses ||= []
      end

      # Returns the files where the subclasses are kept.
      #
      # ==== Returns
      # Hash[path<String> => Class]
      #
      def subclass_files
        @subclass_files ||= Hash.new { |h, k| h[k] = [] }
      end

      # Whenever a class inherits from Bundler::Thor or Bundler::Thor::Group, we should track the
      # class and the file on Bundler::Thor::Base. This is the method responsible for it.
      #
      def register_klass_file(klass) #:nodoc:
        file = caller[1].match(/(.*):\d+/)[1]
        Bundler::Thor::Base.subclasses << klass unless Bundler::Thor::Base.subclasses.include?(klass)

        file_subclasses = Bundler::Thor::Base.subclass_files[File.expand_path(file)]
        file_subclasses << klass unless file_subclasses.include?(klass)
      end
    end

    module ClassMethods
      def attr_reader(*) #:nodoc:
        no_commands { super }
      end

      def attr_writer(*) #:nodoc:
        no_commands { super }
      end

      def attr_accessor(*) #:nodoc:
        no_commands { super }
      end

      # If you want to raise an error for unknown options, call check_unknown_options!
      # This is disabled by default to allow dynamic invocations.
      def check_unknown_options!
        @check_unknown_options = true
      end

      def check_unknown_options #:nodoc:
        @check_unknown_options ||= from_superclass(:check_unknown_options, false)
      end

      def check_unknown_options?(config) #:nodoc:
        !!check_unknown_options
      end

      # If you want to raise an error when the default value of an option does not match
      # the type call check_default_type!
      # This will be the default; for compatibility a deprecation warning is issued if necessary.
      def check_default_type!
        @check_default_type = true
      end

      # If you want to use defaults that don't match the type of an option,
      # either specify `check_default_type: false` or call `allow_incompatible_default_type!`
      def allow_incompatible_default_type!
        @check_default_type = false
      end

      def check_default_type #:nodoc:
        @check_default_type = from_superclass(:check_default_type, nil) unless defined?(@check_default_type)
        @check_default_type
      end

      # If true, option parsing is suspended as soon as an unknown option or a
      # regular argument is encountered.  All remaining arguments are passed to
      # the command as regular arguments.
      def stop_on_unknown_option?(command_name) #:nodoc:
        false
      end

      # If true, option set will not suspend the execution of the command when
      # a required option is not provided.
      def disable_required_check?(command_name) #:nodoc:
        false
      end

      # If you want only strict string args (useful when cascading thor classes),
      # call strict_args_position! This is disabled by default to allow dynamic
      # invocations.
      def strict_args_position!
        @strict_args_position = true
      end

      def strict_args_position #:nodoc:
        @strict_args_position ||= from_superclass(:strict_args_position, false)
      end

      def strict_args_position?(config) #:nodoc:
        !!strict_args_position
      end

      # Adds an argument to the class and creates an attr_accessor for it.
      #
      # Arguments are different from options in several aspects. The first one
      # is how they are parsed from the command line, arguments are retrieved
      # from position:
      #
      #   thor command NAME
      #
      # Instead of:
      #
      #   thor command --name=NAME
      #
      # Besides, arguments are used inside your code as an accessor (self.argument),
      # while options are all kept in a hash (self.options).
      #
      # Finally, arguments cannot have type :default or :boolean but can be
      # optional (supplying :optional => :true or :required => false), although
      # you cannot have a required argument after a non-required argument. If you
      # try it, an error is raised.
      #
      # ==== Parameters
      # name<Symbol>:: The name of the argument.
      # options<Hash>:: Described below.
      #
      # ==== Options
      # :desc     - Description for the argument.
      # :required - If the argument is required or not.
      # :optional - If the argument is optional or not.
      # :type     - The type of the argument, can be :string, :hash, :array, :numeric.
      # :default  - Default value for this argument. It cannot be required and have default values.
      # :banner   - String to show on usage notes.
      #
      # ==== Errors
      # ArgumentError:: Raised if you supply a required argument after a non required one.
      #
      def argument(name, options = {})
        is_thor_reserved_word?(name, :argument)
        no_commands { attr_accessor name }

        required = if options.key?(:optional)
          !options[:optional]
        elsif options.key?(:required)
          options[:required]
        else
          options[:default].nil?
        end

        remove_argument name

        if required
          arguments.each do |argument|
            next if argument.required?
            raise ArgumentError, "You cannot have #{name.to_s.inspect} as required argument after " \
                                "the non-required argument #{argument.human_name.inspect}."
          end
        end

        options[:required] = required

        arguments << Bundler::Thor::Argument.new(name, options)
      end

      # Returns this class arguments, looking up in the ancestors chain.
      #
      # ==== Returns
      # Array[Bundler::Thor::Argument]
      #
      def arguments
        @arguments ||= from_superclass(:arguments, [])
      end

      # Adds a bunch of options to the set of class options.
      #
      #   class_options :foo => false, :bar => :required, :baz => :string
      #
      # If you prefer more detailed declaration, check class_option.
      #
      # ==== Parameters
      # Hash[Symbol => Object]
      #
      def class_options(options = nil)
        @class_options ||= from_superclass(:class_options, {})
        build_options(options, @class_options) if options
        @class_options
      end

      # Adds an option to the set of class options
      #
      # ==== Parameters
      # name<Symbol>:: The name of the argument.
      # options<Hash>:: Described below.
      #
      # ==== Options
      # :desc::     -- Description for the argument.
      # :required:: -- If the argument is required or not.
      # :default::  -- Default value for this argument.
      # :group::    -- The group for this options. Use by class options to output options in different levels.
      # :aliases::  -- Aliases for this option. <b>Note:</b> Bundler::Thor follows a convention of one-dash-one-letter options. Thus aliases like "-something" wouldn't be parsed; use either "\--something" or "-s" instead.
      # :type::     -- The type of the argument, can be :string, :hash, :array, :numeric or :boolean.
      # :banner::   -- String to show on usage notes.
      # :hide::     -- If you want to hide this option from the help.
      #
      def class_option(name, options = {})
        build_option(name, options, class_options)
      end

      # Removes a previous defined argument. If :undefine is given, undefine
      # accessors as well.
      #
      # ==== Parameters
      # names<Array>:: Arguments to be removed
      #
      # ==== Examples
      #
      #   remove_argument :foo
      #   remove_argument :foo, :bar, :baz, :undefine => true
      #
      def remove_argument(*names)
        options = names.last.is_a?(Hash) ? names.pop : {}

        names.each do |name|
          arguments.delete_if { |a| a.name == name.to_s }
          undef_method name, "#{name}=" if options[:undefine]
        end
      end

      # Removes a previous defined class option.
      #
      # ==== Parameters
      # names<Array>:: Class options to be removed
      #
      # ==== Examples
      #
      #   remove_class_option :foo
      #   remove_class_option :foo, :bar, :baz
      #
      def remove_class_option(*names)
        names.each do |name|
          class_options.delete(name)
        end
      end

      # Defines the group. This is used when thor list is invoked so you can specify
      # that only commands from a pre-defined group will be shown. Defaults to standard.
      #
      # ==== Parameters
      # name<String|Symbol>
      #
      def group(name = nil)
        if name
          @group = name.to_s
        else
          @group ||= from_superclass(:group, "standard")
        end
      end

      # Returns the commands for this Bundler::Thor class.
      #
      # ==== Returns
      # Hash:: An ordered hash with commands names as keys and Bundler::Thor::Command
      #        objects as values.
      #
      def commands
        @commands ||= Hash.new
      end
      alias_method :tasks, :commands

      # Returns the commands for this Bundler::Thor class and all subclasses.
      #
      # ==== Returns
      # Hash:: An ordered hash with commands names as keys and Bundler::Thor::Command
      #        objects as values.
      #
      def all_commands
        @all_commands ||= from_superclass(:all_commands, Hash.new)
        @all_commands.merge!(commands)
      end
      alias_method :all_tasks, :all_commands

      # Removes a given command from this Bundler::Thor class. This is usually done if you
      # are inheriting from another class and don't want it to be available
      # anymore.
      #
      # By default it only remove the mapping to the command. But you can supply
      # :undefine => true to undefine the method from the class as well.
      #
      # ==== Parameters
      # name<Symbol|String>:: The name of the command to be removed
      # options<Hash>:: You can give :undefine => true if you want commands the method
      #                 to be undefined from the class as well.
      #
      def remove_command(*names)
        options = names.last.is_a?(Hash) ? names.pop : {}

        names.each do |name|
          commands.delete(name.to_s)
          all_commands.delete(name.to_s)
          undef_method name if options[:undefine]
        end
      end
      alias_method :remove_task, :remove_command

      # All methods defined inside the given block are not added as commands.
      #
      # So you can do:
      #
      #   class MyScript < Bundler::Thor
      #     no_commands do
      #       def this_is_not_a_command
      #       end
      #     end
      #   end
      #
      # You can also add the method and remove it from the command list:
      #
      #   class MyScript < Bundler::Thor
      #     def this_is_not_a_command
      #     end
      #     remove_command :this_is_not_a_command
      #   end
      #
      def no_commands(&block)
        no_commands_context.enter(&block)
      end

      alias_method :no_tasks, :no_commands

      def no_commands_context
        @no_commands_context ||= NestedContext.new
      end

      def no_commands?
        no_commands_context.entered?
      end

      # Sets the namespace for the Bundler::Thor or Bundler::Thor::Group class. By default the
      # namespace is retrieved from the class name. If your Bundler::Thor class is named
      # Scripts::MyScript, the help method, for example, will be called as:
      #
      #   thor scripts:my_script -h
      #
      # If you change the namespace:
      #
      #   namespace :my_scripts
      #
      # You change how your commands are invoked:
      #
      #   thor my_scripts -h
      #
      # Finally, if you change your namespace to default:
      #
      #   namespace :default
      #
      # Your commands can be invoked with a shortcut. Instead of:
      #
      #   thor :my_command
      #
      def namespace(name = nil)
        if name
          @namespace = name.to_s
        else
          @namespace ||= Bundler::Thor::Util.namespace_from_thor_class(self)
        end
      end

      # Parses the command and options from the given args, instantiate the class
      # and invoke the command. This method is used when the arguments must be parsed
      # from an array. If you are inside Ruby and want to use a Bundler::Thor class, you
      # can simply initialize it:
      #
      #   script = MyScript.new(args, options, config)
      #   script.invoke(:command, first_arg, second_arg, third_arg)
      #
      def start(given_args = ARGV, config = {})
        config[:shell] ||= Bundler::Thor::Base.shell.new
        dispatch(nil, given_args.dup, nil, config)
      rescue Bundler::Thor::Error => e
        config[:debug] || ENV["THOR_DEBUG"] == "1" ? (raise e) : config[:shell].error(e.message)
        exit(false) if exit_on_failure?
      rescue Errno::EPIPE
        # This happens if a thor command is piped to something like `head`,
        # which closes the pipe when it's done reading. This will also
        # mean that if the pipe is closed, further unnecessary
        # computation will not occur.
        exit(true)
      end

      # Allows to use private methods from parent in child classes as commands.
      #
      # ==== Parameters
      #   names<Array>:: Method names to be used as commands
      #
      # ==== Examples
      #
      #   public_command :foo
      #   public_command :foo, :bar, :baz
      #
      def public_command(*names)
        names.each do |name|
          class_eval "def #{name}(*); super end"
        end
      end
      alias_method :public_task, :public_command

      def handle_no_command_error(command, has_namespace = $thor_runner) #:nodoc:
        raise UndefinedCommandError.new(command, all_commands.keys, (namespace if has_namespace))
      end
      alias_method :handle_no_task_error, :handle_no_command_error

      def handle_argument_error(command, error, args, arity) #:nodoc:
        name = [command.ancestor_name, command.name].compact.join(" ")
        msg = "ERROR: \"#{basename} #{name}\" was called with ".dup
        msg << "no arguments"               if     args.empty?
        msg << "arguments " << args.inspect unless args.empty?
        msg << "\nUsage: \"#{banner(command).split("\n").join("\"\n       \"")}\""
        raise InvocationError, msg
      end

      # A flag that makes the process exit with status 1 if any error happens.
      def exit_on_failure?
        Bundler::Thor.deprecation_warning "Bundler::Thor exit with status 0 on errors. To keep this behavior, you must define `exit_on_failure?` in `#{self.name}`"
        false
      end

    protected

      # Prints the class options per group. If an option does not belong to
      # any group, it's printed as Class option.
      #
      def class_options_help(shell, groups = {}) #:nodoc:
        # Group options by group
        class_options.each do |_, value|
          groups[value.group] ||= []
          groups[value.group] << value
        end

        # Deal with default group
        global_options = groups.delete(nil) || []
        print_options(shell, global_options)

        # Print all others
        groups.each do |group_name, options|
          print_options(shell, options, group_name)
        end
      end

      # Receives a set of options and print them.
      def print_options(shell, options, group_name = nil)
        return if options.empty?

        list = []
        padding = options.map { |o| o.aliases.size }.max.to_i * 4

        options.each do |option|
          next if option.hide
          item = [option.usage(padding)]
          item.push(option.description ? "# #{option.description}" : "")

          list << item
          list << ["", "# Default: #{option.default}"] if option.show_default?
          list << ["", "# Possible values: #{option.enum.join(', ')}"] if option.enum
        end

        shell.say(group_name ? "#{group_name} options:" : "Options:")
        shell.print_table(list, :indent => 2)
        shell.say ""
      end

      # Raises an error if the word given is a Bundler::Thor reserved word.
      def is_thor_reserved_word?(word, type) #:nodoc:
        return false unless THOR_RESERVED_WORDS.include?(word.to_s)
        raise "#{word.inspect} is a Bundler::Thor reserved word and cannot be defined as #{type}"
      end

      # Build an option and adds it to the given scope.
      #
      # ==== Parameters
      # name<Symbol>:: The name of the argument.
      # options<Hash>:: Described in both class_option and method_option.
      # scope<Hash>:: Options hash that is being built up
      def build_option(name, options, scope) #:nodoc:
        scope[name] = Bundler::Thor::Option.new(name, {:check_default_type => check_default_type}.merge!(options))
      end

      # Receives a hash of options, parse them and add to the scope. This is a
      # fast way to set a bunch of options:
      #
      #   build_options :foo => true, :bar => :required, :baz => :string
      #
      # ==== Parameters
      # Hash[Symbol => Object]
      def build_options(options, scope) #:nodoc:
        options.each do |key, value|
          scope[key] = Bundler::Thor::Option.parse(key, value)
        end
      end

      # Finds a command with the given name. If the command belongs to the current
      # class, just return it, otherwise dup it and add the fresh copy to the
      # current command hash.
      def find_and_refresh_command(name) #:nodoc:
        if commands[name.to_s]
          commands[name.to_s]
        elsif command = all_commands[name.to_s] # rubocop:disable AssignmentInCondition
          commands[name.to_s] = command.clone
        else
          raise ArgumentError, "You supplied :for => #{name.inspect}, but the command #{name.inspect} could not be found."
        end
      end
      alias_method :find_and_refresh_task, :find_and_refresh_command

      # Everytime someone inherits from a Bundler::Thor class, register the klass
      # and file into baseclass.
      def inherited(klass)
        super(klass)
        Bundler::Thor::Base.register_klass_file(klass)
        klass.instance_variable_set(:@no_commands, 0)
      end

      # Fire this callback whenever a method is added. Added methods are
      # tracked as commands by invoking the create_command method.
      def method_added(meth)
        super(meth)
        meth = meth.to_s

        if meth == "initialize"
          initialize_added
          return
        end

        # Return if it's not a public instance method
        return unless public_method_defined?(meth.to_sym)

        return if no_commands? || !create_command(meth)

        is_thor_reserved_word?(meth, :command)
        Bundler::Thor::Base.register_klass_file(self)
      end

      # Retrieves a value from superclass. If it reaches the baseclass,
      # returns default.
      def from_superclass(method, default = nil)
        if self == baseclass || !superclass.respond_to?(method, true)
          default
        else
          value = superclass.send(method)

          # Ruby implements `dup` on Object, but raises a `TypeError`
          # if the method is called on immediates. As a result, we
          # don't have a good way to check whether dup will succeed
          # without calling it and rescuing the TypeError.
          begin
            value.dup
          rescue TypeError
            value
          end

        end
      end

      #
      # The basename of the program invoking the thor class.
      #
      def basename
        File.basename($PROGRAM_NAME).split(" ").first
      end

      # SIGNATURE: Sets the baseclass. This is where the superclass lookup
      # finishes.
      def baseclass #:nodoc:
      end

      # SIGNATURE: Creates a new command if valid_command? is true. This method is
      # called when a new method is added to the class.
      def create_command(meth) #:nodoc:
      end
      alias_method :create_task, :create_command

      # SIGNATURE: Defines behavior when the initialize method is added to the
      # class.
      def initialize_added #:nodoc:
      end

      # SIGNATURE: The hook invoked by start.
      def dispatch(command, given_args, given_opts, config) #:nodoc:
        raise NotImplementedError
      end
    end
  end
end
class Bundler::Thor
  class Argument #:nodoc:
    VALID_TYPES = [:numeric, :hash, :array, :string]

    attr_reader :name, :description, :enum, :required, :type, :default, :banner
    alias_method :human_name, :name

    def initialize(name, options = {})
      class_name = self.class.name.split("::").last

      type = options[:type]

      raise ArgumentError, "#{class_name} name can't be nil."                         if name.nil?
      raise ArgumentError, "Type :#{type} is not valid for #{class_name.downcase}s."  if type && !valid_type?(type)

      @name        = name.to_s
      @description = options[:desc]
      @required    = options.key?(:required) ? options[:required] : true
      @type        = (type || :string).to_sym
      @default     = options[:default]
      @banner      = options[:banner] || default_banner
      @enum        = options[:enum]

      validate! # Trigger specific validations
    end

    def usage
      required? ? banner : "[#{banner}]"
    end

    def required?
      required
    end

    def show_default?
      case default
      when Array, String, Hash
        !default.empty?
      else
        default
      end
    end

  protected

    def validate!
      raise ArgumentError, "An argument cannot be required and have default value." if required? && !default.nil?
      raise ArgumentError, "An argument cannot have an enum other than an array." if @enum && !@enum.is_a?(Array)
    end

    def valid_type?(type)
      self.class::VALID_TYPES.include?(type.to_sym)
    end

    def default_banner
      case type
      when :boolean
        nil
      when :string, :default
        human_name.upcase
      when :numeric
        "N"
      when :hash
        "key:value"
      when :array
        "one two three"
      end
    end
  end
end
class Bundler::Thor
  class Option < Argument #:nodoc:
    attr_reader :aliases, :group, :lazy_default, :hide, :repeatable

    VALID_TYPES = [:boolean, :numeric, :hash, :array, :string]

    def initialize(name, options = {})
      @check_default_type = options[:check_default_type]
      options[:required] = false unless options.key?(:required)
      @repeatable     = options.fetch(:repeatable, false)
      super
      @lazy_default   = options[:lazy_default]
      @group          = options[:group].to_s.capitalize if options[:group]
      @aliases        = Array(options[:aliases])
      @hide           = options[:hide]
    end

    # This parse quick options given as method_options. It makes several
    # assumptions, but you can be more specific using the option method.
    #
    #   parse :foo => "bar"
    #   #=> Option foo with default value bar
    #
    #   parse [:foo, :baz] => "bar"
    #   #=> Option foo with default value bar and alias :baz
    #
    #   parse :foo => :required
    #   #=> Required option foo without default value
    #
    #   parse :foo => 2
    #   #=> Option foo with default value 2 and type numeric
    #
    #   parse :foo => :numeric
    #   #=> Option foo without default value and type numeric
    #
    #   parse :foo => true
    #   #=> Option foo with default value true and type boolean
    #
    # The valid types are :boolean, :numeric, :hash, :array and :string. If none
    # is given a default type is assumed. This default type accepts arguments as
    # string (--foo=value) or booleans (just --foo).
    #
    # By default all options are optional, unless :required is given.
    #
    def self.parse(key, value)
      if key.is_a?(Array)
        name, *aliases = key
      else
        name = key
        aliases = []
      end

      name    = name.to_s
      default = value

      type = case value
      when Symbol
        default = nil
        if VALID_TYPES.include?(value)
          value
        elsif required = (value == :required) # rubocop:disable AssignmentInCondition
          :string
        end
      when TrueClass, FalseClass
        :boolean
      when Numeric
        :numeric
      when Hash, Array, String
        value.class.name.downcase.to_sym
      end

      new(name.to_s, :required => required, :type => type, :default => default, :aliases => aliases)
    end

    def switch_name
      @switch_name ||= dasherized? ? name : dasherize(name)
    end

    def human_name
      @human_name ||= dasherized? ? undasherize(name) : name
    end

    def usage(padding = 0)
      sample = if banner && !banner.to_s.empty?
        "#{switch_name}=#{banner}".dup
      else
        switch_name
      end

      sample = "[#{sample}]".dup unless required?

      if boolean?
        sample << ", [#{dasherize('no-' + human_name)}]" unless (name == "force") || name.start_with?("no-")
      end

      if aliases.empty?
        (" " * padding) << sample
      else
        "#{aliases.join(', ')}, #{sample}"
      end
    end

    VALID_TYPES.each do |type|
      class_eval <<-RUBY, __FILE__, __LINE__ + 1
        def #{type}?
          self.type == #{type.inspect}
        end
      RUBY
    end

  protected

    def validate!
      raise ArgumentError, "An option cannot be boolean and required." if boolean? && required?
      validate_default_type!
    end

    def validate_default_type!
      default_type = case @default
      when nil
        return
      when TrueClass, FalseClass
        required? ? :string : :boolean
      when Numeric
        :numeric
      when Symbol
        :string
      when Hash, Array, String
        @default.class.name.downcase.to_sym
      end

      expected_type = (@repeatable && @type != :hash) ? :array : @type

      if default_type != expected_type
        err = "Expected #{expected_type} default value for '#{switch_name}'; got #{@default.inspect} (#{default_type})"

        if @check_default_type
          raise ArgumentError, err
        elsif @check_default_type == nil
          Bundler::Thor.deprecation_warning "#{err}.\n" +
            'This will be rejected in the future unless you explicitly pass the options `check_default_type: false`' +
            ' or call `allow_incompatible_default_type!` in your code'
        end
      end
    end

    def dasherized?
      name.index("-") == 0
    end

    def undasherize(str)
      str.sub(/^-{1,2}/, "")
    end

    def dasherize(str)
      (str.length > 1 ? "--" : "-") + str.tr("_", "-")
    end
  end
end
class Bundler::Thor
  class Arguments #:nodoc: # rubocop:disable ClassLength
    NUMERIC = /[-+]?(\d*\.\d+|\d+)/

    # Receives an array of args and returns two arrays, one with arguments
    # and one with switches.
    #
    def self.split(args)
      arguments = []

      args.each do |item|
        break if item.is_a?(String) && item =~ /^-/
        arguments << item
      end

      [arguments, args[Range.new(arguments.size, -1)]]
    end

    def self.parse(*args)
      to_parse = args.pop
      new(*args).parse(to_parse)
    end

    # Takes an array of Bundler::Thor::Argument objects.
    #
    def initialize(arguments = [])
      @assigns = {}
      @non_assigned_required = []
      @switches = arguments

      arguments.each do |argument|
        if !argument.default.nil?
          begin
            @assigns[argument.human_name] = argument.default.dup
          rescue TypeError  # Compatibility shim for un-dup-able Fixnum in Ruby < 2.4
            @assigns[argument.human_name] = argument.default
          end
        elsif argument.required?
          @non_assigned_required << argument
        end
      end
    end

    def parse(args)
      @pile = args.dup

      @switches.each do |argument|
        break unless peek
        @non_assigned_required.delete(argument)
        @assigns[argument.human_name] = send(:"parse_#{argument.type}", argument.human_name)
      end

      check_requirement!
      @assigns
    end

    def remaining
      @pile
    end

  private

    def no_or_skip?(arg)
      arg =~ /^--(no|skip)-([-\w]+)$/
      $2
    end

    def last?
      @pile.empty?
    end

    def peek
      @pile.first
    end

    def shift
      @pile.shift
    end

    def unshift(arg)
      if arg.is_a?(Array)
        @pile = arg + @pile
      else
        @pile.unshift(arg)
      end
    end

    def current_is_value?
      peek && peek.to_s !~ /^-{1,2}\S+/
    end

    # Runs through the argument array getting strings that contains ":" and
    # mark it as a hash:
    #
    #   [ "name:string", "age:integer" ]
    #
    # Becomes:
    #
    #   { "name" => "string", "age" => "integer" }
    #
    def parse_hash(name)
      return shift if peek.is_a?(Hash)
      hash = {}

      while current_is_value? && peek.include?(":")
        key, value = shift.split(":", 2)
        raise MalformattedArgumentError, "You can't specify '#{key}' more than once in option '#{name}'; got #{key}:#{hash[key]} and #{key}:#{value}" if hash.include? key
        hash[key] = value
      end
      hash
    end

    # Runs through the argument array getting all strings until no string is
    # found or a switch is found.
    #
    #   ["a", "b", "c"]
    #
    # And returns it as an array:
    #
    #   ["a", "b", "c"]
    #
    def parse_array(name)
      return shift if peek.is_a?(Array)
      array = []
      array << shift while current_is_value?
      array
    end

    # Check if the peek is numeric format and return a Float or Integer.
    # Check if the peek is included in enum if enum is provided.
    # Otherwise raises an error.
    #
    def parse_numeric(name)
      return shift if peek.is_a?(Numeric)

      unless peek =~ NUMERIC && $& == peek
        raise MalformattedArgumentError, "Expected numeric value for '#{name}'; got #{peek.inspect}"
      end

      value = $&.index(".") ? shift.to_f : shift.to_i
      if @switches.is_a?(Hash) && switch = @switches[name]
        if switch.enum && !switch.enum.include?(value)
          raise MalformattedArgumentError, "Expected '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}"
        end
      end
      value
    end

    # Parse string:
    # for --string-arg, just return the current value in the pile
    # for --no-string-arg, nil
    # Check if the peek is included in enum if enum is provided. Otherwise raises an error.
    #
    def parse_string(name)
      if no_or_skip?(name)
        nil
      else
        value = shift
        if @switches.is_a?(Hash) && switch = @switches[name]
          if switch.enum && !switch.enum.include?(value)
            raise MalformattedArgumentError, "Expected '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}"
          end
        end
        value
      end
    end

    # Raises an error if @non_assigned_required array is not empty.
    #
    def check_requirement!
      return if @non_assigned_required.empty?
      names = @non_assigned_required.map do |o|
        o.respond_to?(:switch_name) ? o.switch_name : o.human_name
      end.join("', '")
      class_name = self.class.name.split("::").last.downcase
      raise RequiredArgumentMissingError, "No value provided for required #{class_name} '#{names}'"
    end
  end
end
class Bundler::Thor
  class Options < Arguments #:nodoc: # rubocop:disable ClassLength
    LONG_RE     = /^(--\w+(?:-\w+)*)$/
    SHORT_RE    = /^(-[a-z])$/i
    EQ_RE       = /^(--\w+(?:-\w+)*|-[a-z])=(.*)$/i
    SHORT_SQ_RE = /^-([a-z]{2,})$/i # Allow either -x -v or -xv style for single char args
    SHORT_NUM   = /^(-[a-z])#{NUMERIC}$/i
    OPTS_END    = "--".freeze

    # Receives a hash and makes it switches.
    def self.to_switches(options)
      options.map do |key, value|
        case value
        when true
          "--#{key}"
        when Array
          "--#{key} #{value.map(&:inspect).join(' ')}"
        when Hash
          "--#{key} #{value.map { |k, v| "#{k}:#{v}" }.join(' ')}"
        when nil, false
          nil
        else
          "--#{key} #{value.inspect}"
        end
      end.compact.join(" ")
    end

    # Takes a hash of Bundler::Thor::Option and a hash with defaults.
    #
    # If +stop_on_unknown+ is true, #parse will stop as soon as it encounters
    # an unknown option or a regular argument.
    def initialize(hash_options = {}, defaults = {}, stop_on_unknown = false, disable_required_check = false)
      @stop_on_unknown = stop_on_unknown
      @disable_required_check = disable_required_check
      options = hash_options.values
      super(options)

      # Add defaults
      defaults.each do |key, value|
        @assigns[key.to_s] = value
        @non_assigned_required.delete(hash_options[key])
      end

      @shorts = {}
      @switches = {}
      @extra = []
      @stopped_parsing_after_extra_index = nil

      options.each do |option|
        @switches[option.switch_name] = option

        option.aliases.each do |short|
          name = short.to_s.sub(/^(?!\-)/, "-")
          @shorts[name] ||= option.switch_name
        end
      end
    end

    def remaining
      @extra
    end

    def peek
      return super unless @parsing_options

      result = super
      if result == OPTS_END
        shift
        @parsing_options = false
        @stopped_parsing_after_extra_index ||= @extra.size
        super
      else
        result
      end
    end

    def parse(args) # rubocop:disable MethodLength
      @pile = args.dup
      @parsing_options = true

      while peek
        if parsing_options?
          match, is_switch = current_is_switch?
          shifted = shift

          if is_switch
            case shifted
            when SHORT_SQ_RE
              unshift($1.split("").map { |f| "-#{f}" })
              next
            when EQ_RE, SHORT_NUM
              unshift($2)
              switch = $1
            when LONG_RE, SHORT_RE
              switch = $1
            end

            switch = normalize_switch(switch)
            option = switch_option(switch)
            result = parse_peek(switch, option)
            assign_result!(option, result)
          elsif @stop_on_unknown
            @parsing_options = false
            @extra << shifted
            @stopped_parsing_after_extra_index ||= @extra.size
            @extra << shift while peek
            break
          elsif match
            @extra << shifted
            @extra << shift while peek && peek !~ /^-/
          else
            @extra << shifted
          end
        else
          @extra << shift
        end
      end

      check_requirement! unless @disable_required_check

      assigns = Bundler::Thor::CoreExt::HashWithIndifferentAccess.new(@assigns)
      assigns.freeze
      assigns
    end

    def check_unknown!
      to_check = @stopped_parsing_after_extra_index ? @extra[0...@stopped_parsing_after_extra_index] : @extra

      # an unknown option starts with - or -- and has no more --'s afterward.
      unknown = to_check.select { |str| str =~ /^--?(?:(?!--).)*$/ }
      raise UnknownArgumentError.new(@switches.keys, unknown) unless unknown.empty?
    end

  protected

    def assign_result!(option, result)
      if option.repeatable && option.type == :hash
        (@assigns[option.human_name] ||= {}).merge!(result)
      elsif option.repeatable
        (@assigns[option.human_name] ||= []) << result
      else
        @assigns[option.human_name] = result
      end
    end

    # Check if the current value in peek is a registered switch.
    #
    # Two booleans are returned.  The first is true if the current value
    # starts with a hyphen; the second is true if it is a registered switch.
    def current_is_switch?
      case peek
      when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM
        [true, switch?($1)]
      when SHORT_SQ_RE
        [true, $1.split("").any? { |f| switch?("-#{f}") }]
      else
        [false, false]
      end
    end

    def current_is_switch_formatted?
      case peek
      when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM, SHORT_SQ_RE
        true
      else
        false
      end
    end

    def current_is_value?
      peek && (!parsing_options? || super)
    end

    def switch?(arg)
      !switch_option(normalize_switch(arg)).nil?
    end

    def switch_option(arg)
      if match = no_or_skip?(arg) # rubocop:disable AssignmentInCondition
        @switches[arg] || @switches["--#{match}"]
      else
        @switches[arg]
      end
    end

    # Check if the given argument is actually a shortcut.
    #
    def normalize_switch(arg)
      (@shorts[arg] || arg).tr("_", "-")
    end

    def parsing_options?
      peek
      @parsing_options
    end

    # Parse boolean values which can be given as --foo=true, --foo or --no-foo.
    #
    def parse_boolean(switch)
      if current_is_value?
        if ["true", "TRUE", "t", "T", true].include?(peek)
          shift
          true
        elsif ["false", "FALSE", "f", "F", false].include?(peek)
          shift
          false
        else
          @switches.key?(switch) || !no_or_skip?(switch)
        end
      else
        @switches.key?(switch) || !no_or_skip?(switch)
      end
    end

    # Parse the value at the peek analyzing if it requires an input or not.
    #
    def parse_peek(switch, option)
      if parsing_options? && (current_is_switch_formatted? || last?)
        if option.boolean?
          # No problem for boolean types
        elsif no_or_skip?(switch)
          return nil # User set value to nil
        elsif option.string? && !option.required?
          # Return the default if there is one, else the human name
          return option.lazy_default || option.default || option.human_name
        elsif option.lazy_default
          return option.lazy_default
        else
          raise MalformattedArgumentError, "No value provided for option '#{switch}'"
        end
      end

      @non_assigned_required.delete(option)
      send(:"parse_#{option.type}", switch)
    end
  end
end
require_relative "basic"

class Bundler::Thor
  module Shell
    # Inherit from Bundler::Thor::Shell::Basic and add set_color behavior. Check
    # Bundler::Thor::Shell::Basic to see all available methods.
    #
    class HTML < Basic
      # The start of an HTML bold sequence.
      BOLD       = "font-weight: bold"

      # Set the terminal's foreground HTML color to black.
      BLACK      = "color: black"
      # Set the terminal's foreground HTML color to red.
      RED        = "color: red"
      # Set the terminal's foreground HTML color to green.
      GREEN      = "color: green"
      # Set the terminal's foreground HTML color to yellow.
      YELLOW     = "color: yellow"
      # Set the terminal's foreground HTML color to blue.
      BLUE       = "color: blue"
      # Set the terminal's foreground HTML color to magenta.
      MAGENTA    = "color: magenta"
      # Set the terminal's foreground HTML color to cyan.
      CYAN       = "color: cyan"
      # Set the terminal's foreground HTML color to white.
      WHITE      = "color: white"

      # Set the terminal's background HTML color to black.
      ON_BLACK   = "background-color: black"
      # Set the terminal's background HTML color to red.
      ON_RED     = "background-color: red"
      # Set the terminal's background HTML color to green.
      ON_GREEN   = "background-color: green"
      # Set the terminal's background HTML color to yellow.
      ON_YELLOW  = "background-color: yellow"
      # Set the terminal's background HTML color to blue.
      ON_BLUE    = "background-color: blue"
      # Set the terminal's background HTML color to magenta.
      ON_MAGENTA = "background-color: magenta"
      # Set the terminal's background HTML color to cyan.
      ON_CYAN    = "background-color: cyan"
      # Set the terminal's background HTML color to white.
      ON_WHITE   = "background-color: white"

      # Set color by using a string 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 Highline implementation and it automatically appends CLEAR to the end
      # of the returned String.
      #
      def set_color(string, *colors)
        if colors.all? { |color| color.is_a?(Symbol) || color.is_a?(String) }
          html_colors = colors.map { |color| lookup_color(color) }
          "<span style=\"#{html_colors.join('; ')};\">#{Bundler::Thor::Util.escape_html(string)}</span>"
        else
          color, bold = colors
          html_color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol)
          styles = [html_color]
          styles << BOLD if bold
          "<span style=\"#{styles.join('; ')};\">#{Bundler::Thor::Util.escape_html(string)}</span>"
        end
      end

      # Ask something to the user and receives a response.
      #
      # ==== Example
      # ask("What is your name?")
      #
      # TODO: Implement #ask for Bundler::Thor::Shell::HTML
      def ask(statement, color = nil)
        raise NotImplementedError, "Implement #ask for Bundler::Thor::Shell::HTML"
      end

    protected

      def can_display_colors?
        true
      end

      # Overwrite show_diff to show diff with colors if Diff::LCS is
      # available.
      #
      def show_diff(destination, content) #:nodoc:
        if diff_lcs_loaded? && ENV["THOR_DIFF"].nil? && ENV["RAILS_DIFF"].nil?
          actual  = File.binread(destination).to_s.split("\n")
          content = content.to_s.split("\n")

          Diff::LCS.sdiff(actual, content).each do |diff|
            output_diff_line(diff)
          end
        else
          super
        end
      end

      def output_diff_line(diff) #:nodoc:
        case diff.action
        when "-"
          say "- #{diff.old_element.chomp}", :red, true
        when "+"
          say "+ #{diff.new_element.chomp}", :green, true
        when "!"
          say "- #{diff.old_element.chomp}", :red, true
          say "+ #{diff.new_element.chomp}", :green, true
        else
          say "  #{diff.old_element.chomp}", nil, true
        end
      end

      # Check if Diff::LCS is loaded. If it is, use it to create pretty output
      # for diff.
      #
      def diff_lcs_loaded? #:nodoc:
        return true if defined?(Diff::LCS)
        return @diff_lcs_loaded unless @diff_lcs_loaded.nil?

        @diff_lcs_loaded = begin
          require "diff/lcs"
          true
        rescue LoadError
          false
        end
      end
    end
  end
end
class Bundler::Thor
  module Shell
    class Basic
      DEFAULT_TERMINAL_WIDTH = 80

      attr_accessor :base
      attr_reader   :padding

      # Initialize base, mute and padding to nil.
      #
      def initialize #:nodoc:
        @base = nil
        @mute = false
        @padding = 0
        @always_force = false
      end

      # Mute everything that's inside given block
      #
      def mute
        @mute = true
        yield
      ensure
        @mute = false
      end

      # Check if base is muted
      #
      def mute?
        @mute
      end

      # Sets the output padding, not allowing less than zero values.
      #
      def padding=(value)
        @padding = [0, value].max
      end

      # Sets the output padding while executing a block and resets it.
      #
      def indent(count = 1)
        orig_padding = padding
        self.padding = padding + count
        yield
        self.padding = orig_padding
      end

      # Asks something to the user and receives a response.
      #
      # If a default value is specified it will be presented to the user
      # and allows them to select that value with an empty response. This
      # option is ignored when limited answers are supplied.
      #
      # If asked to limit the correct responses, you can pass in an
      # array of acceptable answers.  If one of those is not supplied,
      # they will be shown a message stating that one of those answers
      # must be given and re-asked the question.
      #
      # If asking for sensitive information, the :echo option can be set
      # to false to mask user input from $stdin.
      #
      # If the required input is a path, then set the path option to
      # true. This will enable tab completion for file paths relative
      # to the current working directory on systems that support
      # Readline.
      #
      # ==== Example
      # ask("What is your name?")
      #
      # ask("What is the planet furthest from the sun?", :default => "Pluto")
      #
      # ask("What is your favorite Neopolitan flavor?", :limited_to => ["strawberry", "chocolate", "vanilla"])
      #
      # ask("What is your password?", :echo => false)
      #
      # ask("Where should the file be saved?", :path => true)
      #
      def ask(statement, *args)
        options = args.last.is_a?(Hash) ? args.pop : {}
        color = args.first

        if options[:limited_to]
          ask_filtered(statement, color, options)
        else
          ask_simply(statement, color, options)
        end
      end

      # Say (print) something to the user. If the sentence ends with a whitespace
      # or tab character, a new line is not appended (print + flush). Otherwise
      # are passed straight to puts (behavior got from Highline).
      #
      # ==== Example
      # say("I know you knew that.")
      #
      def say(message = "", color = nil, force_new_line = (message.to_s !~ /( |\t)\Z/))
        return if quiet?

        buffer = prepare_message(message, *color)
        buffer << "\n" if force_new_line && !message.to_s.end_with?("\n")

        stdout.print(buffer)
        stdout.flush
      end

      # Say a status with the given color and appends the message. Since this
      # method is used frequently by actions, it allows nil or false to be given
      # in log_status, avoiding the message from being shown. If a Symbol is
      # given in log_status, it's used as the color.
      #
      def say_status(status, message, log_status = true)
        return if quiet? || log_status == false
        spaces = "  " * (padding + 1)
        color  = log_status.is_a?(Symbol) ? log_status : :green

        status = status.to_s.rjust(12)
        status = set_color status, color, true if color

        buffer = "#{status}#{spaces}#{message}"
        buffer = "#{buffer}\n" unless buffer.end_with?("\n")

        stdout.print(buffer)
        stdout.flush
      end

      # Make a question the to user and returns true if the user replies "y" or
      # "yes".
      #
      def yes?(statement, color = nil)
        !!(ask(statement, color, :add_to_history => false) =~ is?(:yes))
      end

      # Make a question the to user and returns true if the user replies "n" or
      # "no".
      #
      def no?(statement, color = nil)
        !!(ask(statement, color, :add_to_history => false) =~ is?(:no))
      end

      # Prints values in columns
      #
      # ==== Parameters
      # Array[String, String, ...]
      #
      def print_in_columns(array)
        return if array.empty?
        colwidth = (array.map { |el| el.to_s.size }.max || 0) + 2
        array.each_with_index do |value, index|
          # Don't output trailing spaces when printing the last column
          if ((((index + 1) % (terminal_width / colwidth))).zero? && !index.zero?) || index + 1 == array.length
            stdout.puts value
          else
            stdout.printf("%-#{colwidth}s", value)
          end
        end
      end

      # Prints a table.
      #
      # ==== Parameters
      # Array[Array[String, String, ...]]
      #
      # ==== Options
      # indent<Integer>:: Indent the first column by indent value.
      # colwidth<Integer>:: Force the first column to colwidth spaces wide.
      #
      def print_table(array, options = {}) # rubocop:disable MethodLength
        return if array.empty?

        formats = []
        indent = options[:indent].to_i
        colwidth = options[:colwidth]
        options[:truncate] = terminal_width if options[:truncate] == true

        formats << "%-#{colwidth + 2}s".dup if colwidth
        start = colwidth ? 1 : 0

        colcount = array.max { |a, b| a.size <=> b.size }.size

        maximas = []

        start.upto(colcount - 1) do |index|
          maxima = array.map { |row| row[index] ? row[index].to_s.size : 0 }.max
          maximas << maxima
          formats << if index == colcount - 1
                       # Don't output 2 trailing spaces when printing the last column
                       "%-s".dup
                     else
                       "%-#{maxima + 2}s".dup
                     end
        end

        formats[0] = formats[0].insert(0, " " * indent)
        formats << "%s"

        array.each do |row|
          sentence = "".dup

          row.each_with_index do |column, index|
            maxima = maximas[index]

            f = if column.is_a?(Numeric)
              if index == row.size - 1
                # Don't output 2 trailing spaces when printing the last column
                "%#{maxima}s"
              else
                "%#{maxima}s  "
              end
            else
              formats[index]
            end
            sentence << f % column.to_s
          end

          sentence = truncate(sentence, options[:truncate]) if options[:truncate]
          stdout.puts sentence
        end
      end

      # Prints a long string, word-wrapping the text to the current width of the
      # terminal display. Ideal for printing heredocs.
      #
      # ==== Parameters
      # String
      #
      # ==== Options
      # indent<Integer>:: Indent each line of the printed paragraph by indent value.
      #
      def print_wrapped(message, options = {})
        indent = options[:indent] || 0
        width = terminal_width - indent
        paras = message.split("\n\n")

        paras.map! do |unwrapped|
          words = unwrapped.split(" ")
          counter = words.first.length
          words.inject do |memo, word|
            word = word.gsub(/\n\005/, "\n").gsub(/\005/, "\n")
            counter = 0 if word.include? "\n"
            if (counter + word.length + 1) < width
              memo = "#{memo} #{word}"
              counter += (word.length + 1)
            else
              memo = "#{memo}\n#{word}"
              counter = word.length
            end
            memo
          end
        end.compact!

        paras.each do |para|
          para.split("\n").each do |line|
            stdout.puts line.insert(0, " " * indent)
          end
          stdout.puts unless para == paras.last
        end
      end

      # Deals with file collision and returns true if the file should be
      # overwritten and false otherwise. If a block is given, it uses the block
      # response as the content for the diff.
      #
      # ==== Parameters
      # destination<String>:: the destination file to solve conflicts
      # block<Proc>:: an optional block that returns the value to be used in diff and merge
      #
      def file_collision(destination)
        return true if @always_force
        options = block_given? ? "[Ynaqdhm]" : "[Ynaqh]"

        loop do
          answer = ask(
            %[Overwrite #{destination}? (enter "h" for help) #{options}],
            :add_to_history => false
          )

          case answer
          when nil
            say ""
            return true
          when is?(:yes), is?(:force), ""
            return true
          when is?(:no), is?(:skip)
            return false
          when is?(:always)
            return @always_force = true
          when is?(:quit)
            say "Aborting..."
            raise SystemExit
          when is?(:diff)
            show_diff(destination, yield) if block_given?
            say "Retrying..."
          when is?(:merge)
            if block_given? && !merge_tool.empty?
              merge(destination, yield)
              return nil
            end

            say "Please specify merge tool to `THOR_MERGE` env."
          else
            say file_collision_help
          end
        end
      end

      # This code was copied from Rake, available under MIT-LICENSE
      # Copyright (c) 2003, 2004 Jim Weirich
      def terminal_width
        result = if ENV["THOR_COLUMNS"]
          ENV["THOR_COLUMNS"].to_i
        else
          unix? ? dynamic_width : DEFAULT_TERMINAL_WIDTH
        end
        result < 10 ? DEFAULT_TERMINAL_WIDTH : result
      rescue
        DEFAULT_TERMINAL_WIDTH
      end

      # Called if something goes wrong during the execution. This is used by Bundler::Thor
      # internally and should not be used inside your scripts. If something went
      # wrong, you can always raise an exception. If you raise a Bundler::Thor::Error, it
      # will be rescued and wrapped in the method below.
      #
      def error(statement)
        stderr.puts statement
      end

      # Apply color to the given string with optional bold. Disabled in the
      # Bundler::Thor::Shell::Basic class.
      #
      def set_color(string, *) #:nodoc:
        string
      end

    protected

      def prepare_message(message, *color)
        spaces = "  " * padding
        spaces + set_color(message.to_s, *color)
      end

      def can_display_colors?
        false
      end

      def lookup_color(color)
        return color unless color.is_a?(Symbol)
        self.class.const_get(color.to_s.upcase)
      end

      def stdout
        $stdout
      end

      def stderr
        $stderr
      end

      def is?(value) #:nodoc:
        value = value.to_s

        if value.size == 1
          /\A#{value}\z/i
        else
          /\A(#{value}|#{value[0, 1]})\z/i
        end
      end

      def file_collision_help #:nodoc:
        <<-HELP
        Y - yes, overwrite
        n - no, do not overwrite
        a - all, overwrite this and all others
        q - quit, abort
        d - diff, show the differences between the old and the new
        h - help, show this help
        m - merge, run merge tool
        HELP
      end

      def show_diff(destination, content) #:nodoc:
        diff_cmd = ENV["THOR_DIFF"] || ENV["RAILS_DIFF"] || "diff -u"

        require "tempfile"
        Tempfile.open(File.basename(destination), File.dirname(destination)) do |temp|
          temp.write content
          temp.rewind
          system %(#{diff_cmd} "#{destination}" "#{temp.path}")
        end
      end

      def quiet? #:nodoc:
        mute? || (base && base.options[:quiet])
      end

      # Calculate the dynamic width of the terminal
      def dynamic_width
        @dynamic_width ||= (dynamic_width_stty.nonzero? || dynamic_width_tput)
      end

      def dynamic_width_stty
        `stty size 2>/dev/null`.split[1].to_i
      end

      def dynamic_width_tput
        `tput cols 2>/dev/null`.to_i
      end

      def unix?
        RUBY_PLATFORM =~ /(aix|darwin|linux|(net|free|open)bsd|cygwin|solaris|irix|hpux)/i
      end

      def truncate(string, width)
        as_unicode do
          chars = string.chars.to_a
          if chars.length <= width
            chars.join
          else
            chars[0, width - 3].join + "..."
          end
        end
      end

      if "".respond_to?(:encode)
        def as_unicode
          yield
        end
      else
        def as_unicode
          old = $KCODE
          $KCODE = "U"
          yield
        ensure
          $KCODE = old
        end
      end

      def ask_simply(statement, color, options)
        default = options[:default]
        message = [statement, ("(#{default})" if default), nil].uniq.join(" ")
        message = prepare_message(message, *color)
        result = Bundler::Thor::LineEditor.readline(message, options)

        return unless result

        result = result.strip

        if default && result == ""
          default
        else
          result
        end
      end

      def ask_filtered(statement, color, options)
        answer_set = options[:limited_to]
        case_insensitive = options.fetch(:case_insensitive, false)
        correct_answer = nil
        until correct_answer
          answers = answer_set.join(", ")
          answer = ask_simply("#{statement} [#{answers}]", color, options)
          correct_answer = answer_match(answer_set, answer, case_insensitive)
          say("Your response must be one of: [#{answers}]. Please try again.") unless correct_answer
        end
        correct_answer
      end

      def answer_match(possibilities, answer, case_insensitive)
        if case_insensitive
          possibilities.detect{ |possibility| possibility.downcase == answer.downcase }
        else
          possibilities.detect{ |possibility| possibility == answer }
        end
      end

      def merge(destination, content) #:nodoc:
        require "tempfile"
        Tempfile.open([File.basename(destination), File.extname(destination)], File.dirname(destination)) do |temp|
          temp.write content
          temp.rewind
          system %(#{merge_tool} "#{temp.path}" "#{destination}")
        end
      end

      def merge_tool #:nodoc:
        @merge_tool ||= ENV["THOR_MERGE"] || git_merge_tool
      end

      def git_merge_tool #:nodoc:
        `git config merge.tool`.rstrip rescue ""
      end
    end
  end
end
require_relative "basic"

class Bundler::Thor
  module Shell
    # Inherit from Bundler::Thor::Shell::Basic and add set_color behavior. Check
    # Bundler::Thor::Shell::Basic to see all available methods.
    #
    class Color < Basic
      # Embed in a String to clear all previous ANSI sequences.
      CLEAR      = "\e[0m"
      # The start of an ANSI bold sequence.
      BOLD       = "\e[1m"

      # Set the terminal's foreground ANSI color to black.
      BLACK      = "\e[30m"
      # Set the terminal's foreground ANSI color to red.
      RED        = "\e[31m"
      # Set the terminal's foreground ANSI color to green.
      GREEN      = "\e[32m"
      # Set the terminal's foreground ANSI color to yellow.
      YELLOW     = "\e[33m"
      # Set the terminal's foreground ANSI color to blue.
      BLUE       = "\e[34m"
      # Set the terminal's foreground ANSI color to magenta.
      MAGENTA    = "\e[35m"
      # Set the terminal's foreground ANSI color to cyan.
      CYAN       = "\e[36m"
      # Set the terminal's foreground ANSI color to white.
      WHITE      = "\e[37m"

      # Set the terminal's background ANSI color to black.
      ON_BLACK   = "\e[40m"
      # Set the terminal's background ANSI color to red.
      ON_RED     = "\e[41m"
      # Set the terminal's background ANSI color to green.
      ON_GREEN   = "\e[42m"
      # Set the terminal's background ANSI color to yellow.
      ON_YELLOW  = "\e[43m"
      # Set the terminal's background ANSI color to blue.
      ON_BLUE    = "\e[44m"
      # Set the terminal's background ANSI color to magenta.
      ON_MAGENTA = "\e[45m"
      # Set the terminal's background ANSI color to cyan.
      ON_CYAN    = "\e[46m"
      # Set the terminal's background ANSI color to white.
      ON_WHITE   = "\e[47m"

      # Set color by using a string 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 Highline implementation and it automatically appends CLEAR to the end
      # of the returned String.
      #
      # Pass foreground, background and bold options to this method as
      # symbols.
      #
      # Example:
      #
      #   set_color "Hi!", :red, :on_white, :bold
      #
      # The available colors are:
      #
      #   :bold
      #   :black
      #   :red
      #   :green
      #   :yellow
      #   :blue
      #   :magenta
      #   :cyan
      #   :white
      #   :on_black
      #   :on_red
      #   :on_green
      #   :on_yellow
      #   :on_blue
      #   :on_magenta
      #   :on_cyan
      #   :on_white
      def set_color(string, *colors)
        if colors.compact.empty? || !can_display_colors?
          string
        elsif colors.all? { |color| color.is_a?(Symbol) || color.is_a?(String) }
          ansi_colors = colors.map { |color| lookup_color(color) }
          "#{ansi_colors.join}#{string}#{CLEAR}"
        else
          # The old API was `set_color(color, bold=boolean)`. We
          # continue to support the old API because you should never
          # break old APIs unnecessarily :P
          foreground, bold = colors
          foreground = self.class.const_get(foreground.to_s.upcase) if foreground.is_a?(Symbol)

          bold       = bold ? BOLD : ""
          "#{bold}#{foreground}#{string}#{CLEAR}"
        end
      end

    protected

      def can_display_colors?
        are_colors_supported? && !are_colors_disabled?
      end

      def are_colors_supported?
        stdout.tty? && ENV["TERM"] != "dumb"
      end

      def are_colors_disabled?
        !ENV['NO_COLOR'].nil?
      end

      # Overwrite show_diff to show diff with colors if Diff::LCS is
      # available.
      #
      def show_diff(destination, content) #:nodoc:
        if diff_lcs_loaded? && ENV["THOR_DIFF"].nil? && ENV["RAILS_DIFF"].nil?
          actual  = File.binread(destination).to_s.split("\n")
          content = content.to_s.split("\n")

          Diff::LCS.sdiff(actual, content).each do |diff|
            output_diff_line(diff)
          end
        else
          super
        end
      end

      def output_diff_line(diff) #:nodoc:
        case diff.action
        when "-"
          say "- #{diff.old_element.chomp}", :red, true
        when "+"
          say "+ #{diff.new_element.chomp}", :green, true
        when "!"
          say "- #{diff.old_element.chomp}", :red, true
          say "+ #{diff.new_element.chomp}", :green, true
        else
          say "  #{diff.old_element.chomp}", nil, true
        end
      end

      # Check if Diff::LCS is loaded. If it is, use it to create pretty output
      # for diff.
      #
      def diff_lcs_loaded? #:nodoc:
        return true if defined?(Diff::LCS)
        return @diff_lcs_loaded unless @diff_lcs_loaded.nil?

        @diff_lcs_loaded = begin
          require "diff/lcs"
          true
        rescue LoadError
          false
        end
      end
    end
  end
end
require "erb"

class Bundler::Thor
  module Actions
    # Copies the file from the relative source to the relative destination. If
    # the destination is not given it's assumed to be equal to the source.
    #
    # ==== Parameters
    # source<String>:: the relative path to the source root.
    # destination<String>:: the relative path to the destination root.
    # config<Hash>:: give :verbose => false to not log the status, and
    #                :mode => :preserve, to preserve the file mode from the source.

    #
    # ==== Examples
    #
    #   copy_file "README", "doc/README"
    #
    #   copy_file "doc/README"
    #
    def copy_file(source, *args, &block)
      config = args.last.is_a?(Hash) ? args.pop : {}
      destination = args.first || source
      source = File.expand_path(find_in_source_paths(source.to_s))

      resulting_destination = create_file destination, nil, config do
        content = File.binread(source)
        content = yield(content) if block
        content
      end
      if config[:mode] == :preserve
        mode = File.stat(source).mode
        chmod(resulting_destination, mode, config)
      end
    end

    # Links the file from the relative source to the relative destination. If
    # the destination is not given it's assumed to be equal to the source.
    #
    # ==== Parameters
    # source<String>:: the relative path to the source root.
    # destination<String>:: the relative path to the destination root.
    # config<Hash>:: give :verbose => false to not log the status.
    #
    # ==== Examples
    #
    #   link_file "README", "doc/README"
    #
    #   link_file "doc/README"
    #
    def link_file(source, *args)
      config = args.last.is_a?(Hash) ? args.pop : {}
      destination = args.first || source
      source = File.expand_path(find_in_source_paths(source.to_s))

      create_link destination, source, config
    end

    # Gets the content at the given address and places it at the given relative
    # destination. If a block is given instead of destination, the content of
    # the url is yielded and used as location.
    #
    # +get+ relies on open-uri, so passing application user input would provide
    # a command injection attack vector.
    #
    # ==== Parameters
    # source<String>:: the address of the given content.
    # destination<String>:: the relative path to the destination root.
    # config<Hash>:: give :verbose => false to not log the status.
    #
    # ==== Examples
    #
    #   get "http://gist.github.com/103208", "doc/README"
    #
    #   get "http://gist.github.com/103208" do |content|
    #     content.split("\n").first
    #   end
    #
    def get(source, *args, &block)
      config = args.last.is_a?(Hash) ? args.pop : {}
      destination = args.first

      render = if source =~ %r{^https?\://}
        require "open-uri"
        URI.send(:open, source) { |input| input.binmode.read }
      else
        source = File.expand_path(find_in_source_paths(source.to_s))
        open(source) { |input| input.binmode.read }
      end

      destination ||= if block_given?
        block.arity == 1 ? yield(render) : yield
      else
        File.basename(source)
      end

      create_file destination, render, config
    end

    # Gets an ERB template at the relative source, executes it and makes a copy
    # at the relative destination. If the destination is not given it's assumed
    # to be equal to the source removing .tt from the filename.
    #
    # ==== Parameters
    # source<String>:: the relative path to the source root.
    # destination<String>:: the relative path to the destination root.
    # config<Hash>:: give :verbose => false to not log the status.
    #
    # ==== Examples
    #
    #   template "README", "doc/README"
    #
    #   template "doc/README"
    #
    def template(source, *args, &block)
      config = args.last.is_a?(Hash) ? args.pop : {}
      destination = args.first || source.sub(/#{TEMPLATE_EXTNAME}$/, "")

      source  = File.expand_path(find_in_source_paths(source.to_s))
      context = config.delete(:context) || instance_eval("binding")

      create_file destination, nil, config do
        match = ERB.version.match(/(\d+\.\d+\.\d+)/)
        capturable_erb = if match && match[1] >= "2.2.0" # Ruby 2.6+
          CapturableERB.new(::File.binread(source), :trim_mode => "-", :eoutvar => "@output_buffer")
        else
          CapturableERB.new(::File.binread(source), nil, "-", "@output_buffer")
        end
        content = capturable_erb.tap do |erb|
          erb.filename = source
        end.result(context)
        content = yield(content) if block
        content
      end
    end

    # Changes the mode of the given file or directory.
    #
    # ==== Parameters
    # mode<Integer>:: the file mode
    # path<String>:: the name of the file to change mode
    # config<Hash>:: give :verbose => false to not log the status.
    #
    # ==== Example
    #
    #   chmod "script/server", 0755
    #
    def chmod(path, mode, config = {})
      return unless behavior == :invoke
      path = File.expand_path(path, destination_root)
      say_status :chmod, relative_to_original_destination_root(path), config.fetch(:verbose, true)
      unless options[:pretend]
        require "fileutils"
        FileUtils.chmod_R(mode, path)
      end
    end

    # Prepend text to a file. Since it depends on insert_into_file, it's reversible.
    #
    # ==== Parameters
    # path<String>:: path of the file to be changed
    # data<String>:: the data to prepend to the file, can be also given as a block.
    # config<Hash>:: give :verbose => false to not log the status.
    #
    # ==== Example
    #
    #   prepend_to_file 'config/environments/test.rb', 'config.gem "rspec"'
    #
    #   prepend_to_file 'config/environments/test.rb' do
    #     'config.gem "rspec"'
    #   end
    #
    def prepend_to_file(path, *args, &block)
      config = args.last.is_a?(Hash) ? args.pop : {}
      config[:after] = /\A/
      insert_into_file(path, *(args << config), &block)
    end
    alias_method :prepend_file, :prepend_to_file

    # Append text to a file. Since it depends on insert_into_file, it's reversible.
    #
    # ==== Parameters
    # path<String>:: path of the file to be changed
    # data<String>:: the data to append to the file, can be also given as a block.
    # config<Hash>:: give :verbose => false to not log the status.
    #
    # ==== Example
    #
    #   append_to_file 'config/environments/test.rb', 'config.gem "rspec"'
    #
    #   append_to_file 'config/environments/test.rb' do
    #     'config.gem "rspec"'
    #   end
    #
    def append_to_file(path, *args, &block)
      config = args.last.is_a?(Hash) ? args.pop : {}
      config[:before] = /\z/
      insert_into_file(path, *(args << config), &block)
    end
    alias_method :append_file, :append_to_file

    # Injects text right after the class definition. Since it depends on
    # insert_into_file, it's reversible.
    #
    # ==== Parameters
    # path<String>:: path of the file to be changed
    # klass<String|Class>:: the class to be manipulated
    # data<String>:: the data to append to the class, can be also given as a block.
    # config<Hash>:: give :verbose => false to not log the status.
    #
    # ==== Examples
    #
    #   inject_into_class "app/controllers/application_controller.rb", ApplicationController, "  filter_parameter :password\n"
    #
    #   inject_into_class "app/controllers/application_controller.rb", ApplicationController do
    #     "  filter_parameter :password\n"
    #   end
    #
    def inject_into_class(path, klass, *args, &block)
      config = args.last.is_a?(Hash) ? args.pop : {}
      config[:after] = /class #{klass}\n|class #{klass} .*\n/
      insert_into_file(path, *(args << config), &block)
    end

    # Injects text right after the module definition. Since it depends on
    # insert_into_file, it's reversible.
    #
    # ==== Parameters
    # path<String>:: path of the file to be changed
    # module_name<String|Class>:: the module to be manipulated
    # data<String>:: the data to append to the class, can be also given as a block.
    # config<Hash>:: give :verbose => false to not log the status.
    #
    # ==== Examples
    #
    #   inject_into_module "app/helpers/application_helper.rb", ApplicationHelper, "  def help; 'help'; end\n"
    #
    #   inject_into_module "app/helpers/application_helper.rb", ApplicationHelper do
    #     "  def help; 'help'; end\n"
    #   end
    #
    def inject_into_module(path, module_name, *args, &block)
      config = args.last.is_a?(Hash) ? args.pop : {}
      config[:after] = /module #{module_name}\n|module #{module_name} .*\n/
      insert_into_file(path, *(args << config), &block)
    end

    # Run a regular expression replacement on a file.
    #
    # ==== Parameters
    # path<String>:: path of the file to be changed
    # flag<Regexp|String>:: the regexp or string to be replaced
    # replacement<String>:: the replacement, can be also given as a block
    # config<Hash>:: give :verbose => false to not log the status, and
    #                :force => true, to force the replacement regardless of runner behavior.
    #
    # ==== Example
    #
    #   gsub_file 'app/controllers/application_controller.rb', /#\s*(filter_parameter_logging :password)/, '\1'
    #
    #   gsub_file 'README', /rake/, :green do |match|
    #     match << " no more. Use thor!"
    #   end
    #
    def gsub_file(path, flag, *args, &block)
      config = args.last.is_a?(Hash) ? args.pop : {}

      return unless behavior == :invoke || config.fetch(:force, false)

      path = File.expand_path(path, destination_root)
      say_status :gsub, relative_to_original_destination_root(path), config.fetch(:verbose, true)

      unless options[:pretend]
        content = File.binread(path)
        content.gsub!(flag, *args, &block)
        File.open(path, "wb") { |file| file.write(content) }
      end
    end

    # Uncomment all lines matching a given regex.  It will leave the space
    # which existed before the comment hash in tact but will remove any spacing
    # between the comment hash and the beginning of the line.
    #
    # ==== Parameters
    # path<String>:: path of the file to be changed
    # flag<Regexp|String>:: the regexp or string used to decide which lines to uncomment
    # config<Hash>:: give :verbose => false to not log the status.
    #
    # ==== Example
    #
    #   uncomment_lines 'config/initializers/session_store.rb', /active_record/
    #
    def uncomment_lines(path, flag, *args)
      flag = flag.respond_to?(:source) ? flag.source : flag

      gsub_file(path, /^(\s*)#[[:blank:]]*(.*#{flag})/, '\1\2', *args)
    end

    # Comment all lines matching a given regex.  It will leave the space
    # which existed before the beginning of the line in tact and will insert
    # a single space after the comment hash.
    #
    # ==== Parameters
    # path<String>:: path of the file to be changed
    # flag<Regexp|String>:: the regexp or string used to decide which lines to comment
    # config<Hash>:: give :verbose => false to not log the status.
    #
    # ==== Example
    #
    #   comment_lines 'config/initializers/session_store.rb', /cookie_store/
    #
    def comment_lines(path, flag, *args)
      flag = flag.respond_to?(:source) ? flag.source : flag

      gsub_file(path, /^(\s*)([^#\n]*#{flag})/, '\1# \2', *args)
    end

    # Removes a file at the given location.
    #
    # ==== Parameters
    # path<String>:: path of the file to be changed
    # config<Hash>:: give :verbose => false to not log the status.
    #
    # ==== Example
    #
    #   remove_file 'README'
    #   remove_file 'app/controllers/application_controller.rb'
    #
    def remove_file(path, config = {})
      return unless behavior == :invoke
      path = File.expand_path(path, destination_root)

      say_status :remove, relative_to_original_destination_root(path), config.fetch(:verbose, true)
      if !options[:pretend] && File.exist?(path)
        require "fileutils"
        ::FileUtils.rm_rf(path)
      end
    end
    alias_method :remove_dir, :remove_file

    attr_accessor :output_buffer
    private :output_buffer, :output_buffer=

  private

    def concat(string)
      @output_buffer.concat(string)
    end

    def capture(*args)
      with_output_buffer { yield(*args) }
    end

    def with_output_buffer(buf = "".dup) #:nodoc:
      raise ArgumentError, "Buffer can not be a frozen object" if buf.frozen?
      old_buffer = output_buffer
      self.output_buffer = buf
      yield
      output_buffer
    ensure
      self.output_buffer = old_buffer
    end

    # Bundler::Thor::Actions#capture depends on what kind of buffer is used in ERB.
    # Thus CapturableERB fixes ERB to use String buffer.
    class CapturableERB < ERB
      def set_eoutvar(compiler, eoutvar = "_erbout")
        compiler.put_cmd = "#{eoutvar}.concat"
        compiler.insert_cmd = "#{eoutvar}.concat"
        compiler.pre_cmd = ["#{eoutvar} = ''.dup"]
        compiler.post_cmd = [eoutvar]
      end
    end
  end
end
require_relative "empty_directory"

class Bundler::Thor
  module Actions
    # Create a new file relative to the destination root with the given data,
    # which is the return value of a block or a data string.
    #
    # ==== Parameters
    # destination<String>:: the relative path to the destination root.
    # data<String|NilClass>:: the data to append to the file.
    # config<Hash>:: give :verbose => false to not log the status.
    #
    # ==== Examples
    #
    #   create_file "lib/fun_party.rb" do
    #     hostname = ask("What is the virtual hostname I should use?")
    #     "vhost.name = #{hostname}"
    #   end
    #
    #   create_file "config/apache.conf", "your apache config"
    #
    def create_file(destination, *args, &block)
      config = args.last.is_a?(Hash) ? args.pop : {}
      data = args.first
      action CreateFile.new(self, destination, block || data.to_s, config)
    end
    alias_method :add_file, :create_file

    # CreateFile is a subset of Template, which instead of rendering a file with
    # ERB, it gets the content from the user.
    #
    class CreateFile < EmptyDirectory #:nodoc:
      attr_reader :data

      def initialize(base, destination, data, config = {})
        @data = data
        super(base, destination, config)
      end

      # Checks if the content of the file at the destination is identical to the rendered result.
      #
      # ==== Returns
      # Boolean:: true if it is identical, false otherwise.
      #
      def identical?
        exists? && File.binread(destination) == render
      end

      # Holds the content to be added to the file.
      #
      def render
        @render ||= if data.is_a?(Proc)
          data.call
        else
          data
        end
      end

      def invoke!
        invoke_with_conflict_check do
          require "fileutils"
          FileUtils.mkdir_p(File.dirname(destination))
          File.open(destination, "wb") { |f| f.write render }
        end
        given_destination
      end

    protected

      # Now on conflict we check if the file is identical or not.
      #
      def on_conflict_behavior(&block)
        if identical?
          say_status :identical, :blue
        else
          options = base.options.merge(config)
          force_or_skip_or_conflict(options[:force], options[:skip], &block)
        end
      end

      # If force is true, run the action, otherwise check if it's not being
      # skipped. If both are false, show the file_collision menu, if the menu
      # returns true, force it, otherwise skip.
      #
      def force_or_skip_or_conflict(force, skip, &block)
        if force
          say_status :force, :yellow
          yield unless pretend?
        elsif skip
          say_status :skip, :yellow
        else
          say_status :conflict, :red
          force_or_skip_or_conflict(force_on_collision?, true, &block)
        end
      end

      # Shows the file collision menu to the user and gets the result.
      #
      def force_on_collision?
        base.shell.file_collision(destination) { render }
      end
    end
  end
end
require_relative "create_file"

class Bundler::Thor
  module Actions
    # Create a new file relative to the destination root from the given source.
    #
    # ==== Parameters
    # destination<String>:: the relative path to the destination root.
    # source<String|NilClass>:: the relative path to the source root.
    # config<Hash>:: give :verbose => false to not log the status.
    #   :: give :symbolic => false for hard link.
    #
    # ==== Examples
    #
    #   create_link "config/apache.conf", "/etc/apache.conf"
    #
    def create_link(destination, *args)
      config = args.last.is_a?(Hash) ? args.pop : {}
      source = args.first
      action CreateLink.new(self, destination, source, config)
    end
    alias_method :add_link, :create_link

    # CreateLink is a subset of CreateFile, which instead of taking a block of
    # data, just takes a source string from the user.
    #
    class CreateLink < CreateFile #:nodoc:
      attr_reader :data

      # Checks if the content of the file at the destination is identical to the rendered result.
      #
      # ==== Returns
      # Boolean:: true if it is identical, false otherwise.
      #
      def identical?
        source = File.expand_path(render, File.dirname(destination))
        exists? && File.identical?(source, destination)
      end

      def invoke!
        invoke_with_conflict_check do
          require "fileutils"
          FileUtils.mkdir_p(File.dirname(destination))
          # Create a symlink by default
          config[:symbolic] = true if config[:symbolic].nil?
          File.unlink(destination) if exists?
          if config[:symbolic]
            File.symlink(render, destination)
          else
            File.link(render, destination)
          end
        end
        given_destination
      end

      def exists?
        super || File.symlink?(destination)
      end
    end
  end
end
class Bundler::Thor
  module Actions
    # Creates an empty directory.
    #
    # ==== Parameters
    # destination<String>:: the relative path to the destination root.
    # config<Hash>:: give :verbose => false to not log the status.
    #
    # ==== Examples
    #
    #   empty_directory "doc"
    #
    def empty_directory(destination, config = {})
      action EmptyDirectory.new(self, destination, config)
    end

    # Class which holds create directory logic. This is the base class for
    # other actions like create_file and directory.
    #
    # This implementation is based in Templater actions, created by Jonas Nicklas
    # and Michael S. Klishin under MIT LICENSE.
    #
    class EmptyDirectory #:nodoc:
      attr_reader :base, :destination, :given_destination, :relative_destination, :config

      # Initializes given the source and destination.
      #
      # ==== Parameters
      # base<Bundler::Thor::Base>:: A Bundler::Thor::Base instance
      # source<String>:: Relative path to the source of this file
      # destination<String>:: Relative path to the destination of this file
      # config<Hash>:: give :verbose => false to not log the status.
      #
      def initialize(base, destination, config = {})
        @base = base
        @config = {:verbose => true}.merge(config)
        self.destination = destination
      end

      # Checks if the destination file already exists.
      #
      # ==== Returns
      # Boolean:: true if the file exists, false otherwise.
      #
      def exists?
        ::File.exist?(destination)
      end

      def invoke!
        invoke_with_conflict_check do
          require "fileutils"
          ::FileUtils.mkdir_p(destination)
        end
      end

      def revoke!
        say_status :remove, :red
        require "fileutils"
        ::FileUtils.rm_rf(destination) if !pretend? && exists?
        given_destination
      end

    protected

      # Shortcut for pretend.
      #
      def pretend?
        base.options[:pretend]
      end

      # Sets the absolute destination value from a relative destination value.
      # It also stores the given and relative destination. Let's suppose our
      # script is being executed on "dest", it sets the destination root to
      # "dest". The destination, given_destination and relative_destination
      # are related in the following way:
      #
      #   inside "bar" do
      #     empty_directory "baz"
      #   end
      #
      #   destination          #=> dest/bar/baz
      #   relative_destination #=> bar/baz
      #   given_destination    #=> baz
      #
      def destination=(destination)
        return unless destination
        @given_destination = convert_encoded_instructions(destination.to_s)
        @destination = ::File.expand_path(@given_destination, base.destination_root)
        @relative_destination = base.relative_to_original_destination_root(@destination)
      end

      # Filenames in the encoded form are converted. If you have a file:
      #
      #   %file_name%.rb
      #
      # It calls #file_name from the base and replaces %-string with the
      # return value (should be String) of #file_name:
      #
      #   user.rb
      #
      # The method referenced can be either public or private.
      #
      def convert_encoded_instructions(filename)
        filename.gsub(/%(.*?)%/) do |initial_string|
          method = $1.strip
          base.respond_to?(method, true) ? base.send(method) : initial_string
        end
      end

      # Receives a hash of options and just execute the block if some
      # conditions are met.
      #
      def invoke_with_conflict_check(&block)
        if exists?
          on_conflict_behavior(&block)
        else
          yield unless pretend?
          say_status :create, :green
        end

        destination
      rescue Errno::EISDIR, Errno::EEXIST
        on_file_clash_behavior
      end

      def on_file_clash_behavior
        say_status :file_clash, :red
      end

      # What to do when the destination file already exists.
      #
      def on_conflict_behavior
        say_status :exist, :blue
      end

      # Shortcut to say_status shell method.
      #
      def say_status(status, color)
        base.shell.say_status status, relative_destination, color if config[:verbose]
      end
    end
  end
end
require_relative "empty_directory"

class Bundler::Thor
  module Actions
    # Copies recursively the files from source directory to root directory.
    # If any of the files finishes with .tt, it's considered to be a template
    # and is placed in the destination without the extension .tt. If any
    # empty directory is found, it's copied and all .empty_directory files are
    # ignored. If any file name is wrapped within % signs, the text within
    # the % signs will be executed as a method and replaced with the returned
    # value. Let's suppose a doc directory with the following files:
    #
    #   doc/
    #     components/.empty_directory
    #     README
    #     rdoc.rb.tt
    #     %app_name%.rb
    #
    # When invoked as:
    #
    #   directory "doc"
    #
    # It will create a doc directory in the destination with the following
    # files (assuming that the `app_name` method returns the value "blog"):
    #
    #   doc/
    #     components/
    #     README
    #     rdoc.rb
    #     blog.rb
    #
    # <b>Encoded path note:</b> Since Bundler::Thor internals use Object#respond_to? to check if it can
    # expand %something%, this `something` should be a public method in the class calling
    # #directory. If a method is private, Bundler::Thor stack raises PrivateMethodEncodedError.
    #
    # ==== Parameters
    # source<String>:: the relative path to the source root.
    # destination<String>:: the relative path to the destination root.
    # config<Hash>:: give :verbose => false to not log the status.
    #                If :recursive => false, does not look for paths recursively.
    #                If :mode => :preserve, preserve the file mode from the source.
    #                If :exclude_pattern => /regexp/, prevents copying files that match that regexp.
    #
    # ==== Examples
    #
    #   directory "doc"
    #   directory "doc", "docs", :recursive => false
    #
    def directory(source, *args, &block)
      config = args.last.is_a?(Hash) ? args.pop : {}
      destination = args.first || source
      action Directory.new(self, source, destination || source, config, &block)
    end

    class Directory < EmptyDirectory #:nodoc:
      attr_reader :source

      def initialize(base, source, destination = nil, config = {}, &block)
        @source = File.expand_path(Dir[Util.escape_globs(base.find_in_source_paths(source.to_s))].first)
        @block  = block
        super(base, destination, {:recursive => true}.merge(config))
      end

      def invoke!
        base.empty_directory given_destination, config
        execute!
      end

      def revoke!
        execute!
      end

    protected

      def execute!
        lookup = Util.escape_globs(source)
        lookup = config[:recursive] ? File.join(lookup, "**") : lookup
        lookup = file_level_lookup(lookup)

        files(lookup).sort.each do |file_source|
          next if File.directory?(file_source)
          next if config[:exclude_pattern] && file_source.match(config[:exclude_pattern])
          file_destination = File.join(given_destination, file_source.gsub(source, "."))
          file_destination.gsub!("/./", "/")

          case file_source
          when /\.empty_directory$/
            dirname = File.dirname(file_destination).gsub(%r{/\.$}, "")
            next if dirname == given_destination
            base.empty_directory(dirname, config)
          when /#{TEMPLATE_EXTNAME}$/
            base.template(file_source, file_destination[0..-4], config, &@block)
          else
            base.copy_file(file_source, file_destination, config, &@block)
          end
        end
      end

      def file_level_lookup(previous_lookup)
        File.join(previous_lookup, "*")
      end

      def files(lookup)
        Dir.glob(lookup, File::FNM_DOTMATCH)
      end
    end
  end
end
require_relative "empty_directory"

class Bundler::Thor
  module Actions
    # Injects the given content into a file. Different from gsub_file, this
    # method is reversible.
    #
    # ==== Parameters
    # destination<String>:: Relative path to the destination root
    # data<String>:: Data to add to the file. Can be given as a block.
    # config<Hash>:: give :verbose => false to not log the status and the flag
    #                for injection (:after or :before) or :force => true for
    #                insert two or more times the same content.
    #
    # ==== Examples
    #
    #   insert_into_file "config/environment.rb", "config.gem :thor", :after => "Rails::Initializer.run do |config|\n"
    #
    #   insert_into_file "config/environment.rb", :after => "Rails::Initializer.run do |config|\n" do
    #     gems = ask "Which gems would you like to add?"
    #     gems.split(" ").map{ |gem| "  config.gem :#{gem}" }.join("\n")
    #   end
    #
    WARNINGS = { unchanged_no_flag: 'File unchanged! The supplied flag value not found!' }

    def insert_into_file(destination, *args, &block)
      data = block_given? ? block : args.shift

      config = args.shift || {}
      config[:after] = /\z/ unless config.key?(:before) || config.key?(:after)

      action InjectIntoFile.new(self, destination, data, config)
    end
    alias_method :inject_into_file, :insert_into_file

    class InjectIntoFile < EmptyDirectory #:nodoc:
      attr_reader :replacement, :flag, :behavior

      def initialize(base, destination, data, config)
        super(base, destination, {:verbose => true}.merge(config))

        @behavior, @flag = if @config.key?(:after)
          [:after, @config.delete(:after)]
        else
          [:before, @config.delete(:before)]
        end

        @replacement = data.is_a?(Proc) ? data.call : data
        @flag = Regexp.escape(@flag) unless @flag.is_a?(Regexp)
      end

      def invoke!
        content = if @behavior == :after
          '\0' + replacement
        else
          replacement + '\0'
        end

        if exists?
          if replace!(/#{flag}/, content, config[:force])
            say_status(:invoke)
          else
            say_status(:unchanged, warning: WARNINGS[:unchanged_no_flag], color: :red)
          end
        else
          unless pretend?
            raise Bundler::Thor::Error, "The file #{ destination } does not appear to exist"
          end
        end
      end

      def revoke!
        say_status :revoke

        regexp = if @behavior == :after
          content = '\1\2'
          /(#{flag})(.*)(#{Regexp.escape(replacement)})/m
        else
          content = '\2\3'
          /(#{Regexp.escape(replacement)})(.*)(#{flag})/m
        end

        replace!(regexp, content, true)
      end

    protected

      def say_status(behavior, warning: nil, color: nil)
        status = if behavior == :invoke
          if flag == /\A/
            :prepend
          elsif flag == /\z/
            :append
          else
            :insert
          end
        elsif warning
          warning
        else
          :subtract
        end

        super(status, (color || config[:verbose]))
      end

      # Adds the content to the file.
      #
      def replace!(regexp, string, force)
        return if pretend?
        content = File.read(destination)
        if force || !content.include?(replacement)
          success = content.gsub!(regexp, string)

          File.open(destination, "wb") { |file| file.write(content) }
          success
        end
      end
    end
  end
end
require_relative "actions/create_file"
require_relative "actions/create_link"
require_relative "actions/directory"
require_relative "actions/empty_directory"
require_relative "actions/file_manipulation"
require_relative "actions/inject_into_file"

class Bundler::Thor
  module Actions
    attr_accessor :behavior

    def self.included(base) #:nodoc:
      super(base)
      base.extend ClassMethods
    end

    module ClassMethods
      # Hold source paths for one Bundler::Thor instance. source_paths_for_search is the
      # method responsible to gather source_paths from this current class,
      # inherited paths and the source root.
      #
      def source_paths
        @_source_paths ||= []
      end

      # Stores and return the source root for this class
      def source_root(path = nil)
        @_source_root = path if path
        @_source_root ||= nil
      end

      # Returns the source paths in the following order:
      #
      #   1) This class source paths
      #   2) Source root
      #   3) Parents source paths
      #
      def source_paths_for_search
        paths = []
        paths += source_paths
        paths << source_root if source_root
        paths += from_superclass(:source_paths, [])
        paths
      end

      # Add runtime options that help actions execution.
      #
      def add_runtime_options!
        class_option :force, :type => :boolean, :aliases => "-f", :group => :runtime,
                             :desc => "Overwrite files that already exist"

        class_option :pretend, :type => :boolean, :aliases => "-p", :group => :runtime,
                               :desc => "Run but do not make any changes"

        class_option :quiet, :type => :boolean, :aliases => "-q", :group => :runtime,
                             :desc => "Suppress status output"

        class_option :skip, :type => :boolean, :aliases => "-s", :group => :runtime,
                            :desc => "Skip files that already exist"
      end
    end

    # Extends initializer to add more configuration options.
    #
    # ==== Configuration
    # behavior<Symbol>:: The actions default behavior. Can be :invoke or :revoke.
    #                    It also accepts :force, :skip and :pretend to set the behavior
    #                    and the respective option.
    #
    # destination_root<String>:: The root directory needed for some actions.
    #
    def initialize(args = [], options = {}, config = {})
      self.behavior = case config[:behavior].to_s
      when "force", "skip"
        _cleanup_options_and_set(options, config[:behavior])
        :invoke
      when "revoke"
        :revoke
      else
        :invoke
      end

      super
      self.destination_root = config[:destination_root]
    end

    # Wraps an action object and call it accordingly to the thor class behavior.
    #
    def action(instance) #:nodoc:
      if behavior == :revoke
        instance.revoke!
      else
        instance.invoke!
      end
    end

    # Returns the root for this thor class (also aliased as destination root).
    #
    def destination_root
      @destination_stack.last
    end

    # Sets the root for this thor class. Relatives path are added to the
    # directory where the script was invoked and expanded.
    #
    def destination_root=(root)
      @destination_stack ||= []
      @destination_stack[0] = File.expand_path(root || "")
    end

    # Returns the given path relative to the absolute root (ie, root where
    # the script started).
    #
    def relative_to_original_destination_root(path, remove_dot = true)
      root = @destination_stack[0]
      if path.start_with?(root) && [File::SEPARATOR, File::ALT_SEPARATOR, nil, ''].include?(path[root.size..root.size])
        path = path.dup
        path[0...root.size] = '.'
        remove_dot ? (path[2..-1] || "") : path
      else
        path
      end
    end

    # Holds source paths in instance so they can be manipulated.
    #
    def source_paths
      @source_paths ||= self.class.source_paths_for_search
    end

    # Receives a file or directory and search for it in the source paths.
    #
    def find_in_source_paths(file)
      possible_files = [file, file + TEMPLATE_EXTNAME]
      relative_root = relative_to_original_destination_root(destination_root, false)

      source_paths.each do |source|
        possible_files.each do |f|
          source_file = File.expand_path(f, File.join(source, relative_root))
          return source_file if File.exist?(source_file)
        end
      end

      message = "Could not find #{file.inspect} in any of your source paths. ".dup

      unless self.class.source_root
        message << "Please invoke #{self.class.name}.source_root(PATH) with the PATH containing your templates. "
      end

      message << if source_paths.empty?
                   "Currently you have no source paths."
                 else
                   "Your current source paths are: \n#{source_paths.join("\n")}"
                 end

      raise Error, message
    end

    # Do something in the root or on a provided subfolder. If a relative path
    # is given it's referenced from the current root. The full path is yielded
    # to the block you provide. The path is set back to the previous path when
    # the method exits.
    #
    # ==== Parameters
    # dir<String>:: the directory to move to.
    # config<Hash>:: give :verbose => true to log and use padding.
    #
    def inside(dir = "", config = {}, &block)
      verbose = config.fetch(:verbose, false)
      pretend = options[:pretend]

      say_status :inside, dir, verbose
      shell.padding += 1 if verbose
      @destination_stack.push File.expand_path(dir, destination_root)

      # If the directory doesnt exist and we're not pretending
      if !File.exist?(destination_root) && !pretend
        require "fileutils"
        FileUtils.mkdir_p(destination_root)
      end

      if pretend
        # In pretend mode, just yield down to the block
        block.arity == 1 ? yield(destination_root) : yield
      else
        require "fileutils"
        FileUtils.cd(destination_root) { block.arity == 1 ? yield(destination_root) : yield }
      end

      @destination_stack.pop
      shell.padding -= 1 if verbose
    end

    # Goes to the root and execute the given block.
    #
    def in_root
      inside(@destination_stack.first) { yield }
    end

    # Loads an external file and execute it in the instance binding.
    #
    # ==== Parameters
    # path<String>:: The path to the file to execute. Can be a web address or
    #                a relative path from the source root.
    #
    # ==== Examples
    #
    #   apply "http://gist.github.com/103208"
    #
    #   apply "recipes/jquery.rb"
    #
    def apply(path, config = {})
      verbose = config.fetch(:verbose, true)
      is_uri  = path =~ %r{^https?\://}
      path    = find_in_source_paths(path) unless is_uri

      say_status :apply, path, verbose
      shell.padding += 1 if verbose

      contents = if is_uri
        require "open-uri"
        URI.open(path, "Accept" => "application/x-thor-template", &:read)
      else
        open(path, &:read)
      end

      instance_eval(contents, path)
      shell.padding -= 1 if verbose
    end

    # Executes a command returning the contents of the command.
    #
    # ==== Parameters
    # command<String>:: the command to be executed.
    # config<Hash>:: give :verbose => false to not log the status, :capture => true to hide to output. Specify :with
    #                to append an executable to command execution.
    #
    # ==== Example
    #
    #   inside('vendor') do
    #     run('ln -s ~/edge rails')
    #   end
    #
    def run(command, config = {})
      return unless behavior == :invoke

      destination = relative_to_original_destination_root(destination_root, false)
      desc = "#{command} from #{destination.inspect}"

      if config[:with]
        desc = "#{File.basename(config[:with].to_s)} #{desc}"
        command = "#{config[:with]} #{command}"
      end

      say_status :run, desc, config.fetch(:verbose, true)

      return if options[:pretend]

      env_splat = [config[:env]] if config[:env]

      if config[:capture]
        require "open3"
        result, status = Open3.capture2e(*env_splat, command.to_s)
        success = status.success?
      else
        result = system(*env_splat, command.to_s)
        success = result
      end

      abort if !success && config.fetch(:abort_on_failure, self.class.exit_on_failure?)

      result
    end

    # Executes a ruby script (taking into account WIN32 platform quirks).
    #
    # ==== Parameters
    # command<String>:: the command to be executed.
    # config<Hash>:: give :verbose => false to not log the status.
    #
    def run_ruby_script(command, config = {})
      return unless behavior == :invoke
      run command, config.merge(:with => Bundler::Thor::Util.ruby_command)
    end

    # Run a thor command. A hash of options can be given and it's converted to
    # switches.
    #
    # ==== Parameters
    # command<String>:: the command to be invoked
    # args<Array>:: arguments to the command
    # config<Hash>:: give :verbose => false to not log the status, :capture => true to hide to output.
    #                Other options are given as parameter to Bundler::Thor.
    #
    #
    # ==== Examples
    #
    #   thor :install, "http://gist.github.com/103208"
    #   #=> thor install http://gist.github.com/103208
    #
    #   thor :list, :all => true, :substring => 'rails'
    #   #=> thor list --all --substring=rails
    #
    def thor(command, *args)
      config  = args.last.is_a?(Hash) ? args.pop : {}
      verbose = config.key?(:verbose) ? config.delete(:verbose) : true
      pretend = config.key?(:pretend) ? config.delete(:pretend) : false
      capture = config.key?(:capture) ? config.delete(:capture) : false

      args.unshift(command)
      args.push Bundler::Thor::Options.to_switches(config)
      command = args.join(" ").strip

      run command, :with => :thor, :verbose => verbose, :pretend => pretend, :capture => capture
    end

  protected

    # Allow current root to be shared between invocations.
    #
    def _shared_configuration #:nodoc:
      super.merge!(:destination_root => destination_root)
    end

    def _cleanup_options_and_set(options, key) #:nodoc:
      case options
      when Array
        %w(--force -f --skip -s).each { |i| options.delete(i) }
        options << "--#{key}"
      when Hash
        [:force, :skip, "force", "skip"].each { |i| options.delete(i) }
        options.merge!(key => true)
      end
    end
  end
end
class Bundler::Thor
  class NestedContext
    def initialize
      @depth = 0
    end

    def enter
      push

      yield
    ensure
      pop
    end

    def entered?
      @depth > 0
    end

    private

    def push
      @depth += 1
    end

    def pop
      @depth -= 1
    end
  end
end
require_relative "parser/argument"
require_relative "parser/arguments"
require_relative "parser/option"
require_relative "parser/options"
class Bundler::Thor
  module Invocation
    def self.included(base) #:nodoc:
      super(base)
      base.extend ClassMethods
    end

    module ClassMethods
      # This method is responsible for receiving a name and find the proper
      # class and command for it. The key is an optional parameter which is
      # available only in class methods invocations (i.e. in Bundler::Thor::Group).
      def prepare_for_invocation(key, name) #:nodoc:
        case name
        when Symbol, String
          Bundler::Thor::Util.find_class_and_command_by_namespace(name.to_s, !key)
        else
          name
        end
      end
    end

    # Make initializer aware of invocations and the initialization args.
    def initialize(args = [], options = {}, config = {}, &block) #:nodoc:
      @_invocations = config[:invocations] || Hash.new { |h, k| h[k] = [] }
      @_initializer = [args, options, config]
      super
    end

    # Make the current command chain accessible with in a Bundler::Thor-(sub)command
    def current_command_chain
      @_invocations.values.flatten.map(&:to_sym)
    end

    # Receives a name and invokes it. The name can be a string (either "command" or
    # "namespace:command"), a Bundler::Thor::Command, a Class or a Bundler::Thor instance. If the
    # command cannot be guessed by name, it can also be supplied as second argument.
    #
    # You can also supply the arguments, options and configuration values for
    # the command to be invoked, if none is given, the same values used to
    # initialize the invoker are used to initialize the invoked.
    #
    # When no name is given, it will invoke the default command of the current class.
    #
    # ==== Examples
    #
    #   class A < Bundler::Thor
    #     def foo
    #       invoke :bar
    #       invoke "b:hello", ["Erik"]
    #     end
    #
    #     def bar
    #       invoke "b:hello", ["Erik"]
    #     end
    #   end
    #
    #   class B < Bundler::Thor
    #     def hello(name)
    #       puts "hello #{name}"
    #     end
    #   end
    #
    # You can notice that the method "foo" above invokes two commands: "bar",
    # which belongs to the same class and "hello" which belongs to the class B.
    #
    # By using an invocation system you ensure that a command is invoked only once.
    # In the example above, invoking "foo" will invoke "b:hello" just once, even
    # if it's invoked later by "bar" method.
    #
    # When class A invokes class B, all arguments used on A initialization are
    # supplied to B. This allows lazy parse of options. Let's suppose you have
    # some rspec commands:
    #
    #   class Rspec < Bundler::Thor::Group
    #     class_option :mock_framework, :type => :string, :default => :rr
    #
    #     def invoke_mock_framework
    #       invoke "rspec:#{options[:mock_framework]}"
    #     end
    #   end
    #
    # As you noticed, it invokes the given mock framework, which might have its
    # own options:
    #
    #   class Rspec::RR < Bundler::Thor::Group
    #     class_option :style, :type => :string, :default => :mock
    #   end
    #
    # Since it's not rspec concern to parse mock framework options, when RR
    # is invoked all options are parsed again, so RR can extract only the options
    # that it's going to use.
    #
    # If you want Rspec::RR to be initialized with its own set of options, you
    # have to do that explicitly:
    #
    #   invoke "rspec:rr", [], :style => :foo
    #
    # Besides giving an instance, you can also give a class to invoke:
    #
    #   invoke Rspec::RR, [], :style => :foo
    #
    def invoke(name = nil, *args)
      if name.nil?
        warn "[Bundler::Thor] Calling invoke() without argument is deprecated. Please use invoke_all instead.\n#{caller.join("\n")}"
        return invoke_all
      end

      args.unshift(nil) if args.first.is_a?(Array) || args.first.nil?
      command, args, opts, config = args

      klass, command = _retrieve_class_and_command(name, command)
      raise "Missing Bundler::Thor class for invoke #{name}" unless klass
      raise "Expected Bundler::Thor class, got #{klass}" unless klass <= Bundler::Thor::Base

      args, opts, config = _parse_initialization_options(args, opts, config)
      klass.send(:dispatch, command, args, opts, config) do |instance|
        instance.parent_options = options
      end
    end

    # Invoke the given command if the given args.
    def invoke_command(command, *args) #:nodoc:
      current = @_invocations[self.class]

      unless current.include?(command.name)
        current << command.name
        command.run(self, *args)
      end
    end
    alias_method :invoke_task, :invoke_command

    # Invoke all commands for the current instance.
    def invoke_all #:nodoc:
      self.class.all_commands.map { |_, command| invoke_command(command) }
    end

    # Invokes using shell padding.
    def invoke_with_padding(*args)
      with_padding { invoke(*args) }
    end

  protected

    # Configuration values that are shared between invocations.
    def _shared_configuration #:nodoc:
      {:invocations => @_invocations}
    end

    # This method simply retrieves the class and command to be invoked.
    # If the name is nil or the given name is a command in the current class,
    # use the given name and return self as class. Otherwise, call
    # prepare_for_invocation in the current class.
    def _retrieve_class_and_command(name, sent_command = nil) #:nodoc:
      if name.nil?
        [self.class, nil]
      elsif self.class.all_commands[name.to_s]
        [self.class, name.to_s]
      else
        klass, command = self.class.prepare_for_invocation(nil, name)
        [klass, command || sent_command]
      end
    end
    alias_method :_retrieve_class_and_task, :_retrieve_class_and_command

    # Initialize klass using values stored in the @_initializer.
    def _parse_initialization_options(args, opts, config) #:nodoc:
      stored_args, stored_opts, stored_config = @_initializer

      args ||= stored_args.dup
      opts ||= stored_opts.dup

      config ||= {}
      config = stored_config.merge(_shared_configuration).merge!(config)

      [args, opts, config]
    end
  end
end
require "rbconfig"

class Bundler::Thor
  module Base
    class << self
      attr_writer :shell

      # Returns the shell used in all Bundler::Thor classes. If you are in a Unix platform
      # it will use a colored log, otherwise it will use a basic one without color.
      #
      def shell
        @shell ||= if ENV["THOR_SHELL"] && !ENV["THOR_SHELL"].empty?
          Bundler::Thor::Shell.const_get(ENV["THOR_SHELL"])
        elsif RbConfig::CONFIG["host_os"] =~ /mswin|mingw/ && !ENV["ANSICON"]
          Bundler::Thor::Shell::Basic
        else
          Bundler::Thor::Shell::Color
        end
      end
    end
  end

  module Shell
    SHELL_DELEGATED_METHODS = [:ask, :error, :set_color, :yes?, :no?, :say, :say_status, :print_in_columns, :print_table, :print_wrapped, :file_collision, :terminal_width]
    attr_writer :shell

    autoload :Basic, File.expand_path("shell/basic", __dir__)
    autoload :Color, File.expand_path("shell/color", __dir__)
    autoload :HTML,  File.expand_path("shell/html", __dir__)

    # Add shell to initialize config values.
    #
    # ==== Configuration
    # shell<Object>:: An instance of the shell to be used.
    #
    # ==== Examples
    #
    #   class MyScript < Bundler::Thor
    #     argument :first, :type => :numeric
    #   end
    #
    #   MyScript.new [1.0], { :foo => :bar }, :shell => Bundler::Thor::Shell::Basic.new
    #
    def initialize(args = [], options = {}, config = {})
      super
      self.shell = config[:shell]
      shell.base ||= self if shell.respond_to?(:base)
    end

    # Holds the shell for the given Bundler::Thor instance. If no shell is given,
    # it gets a default shell from Bundler::Thor::Base.shell.
    def shell
      @shell ||= Bundler::Thor::Base.shell.new
    end

    # Common methods that are delegated to the shell.
    SHELL_DELEGATED_METHODS.each do |method|
      module_eval <<-METHOD, __FILE__, __LINE__ + 1
        def #{method}(*args,&block)
          shell.#{method}(*args,&block)
        end
      METHOD
    end

    # Yields the given block with padding.
    def with_padding
      shell.padding += 1
      yield
    ensure
      shell.padding -= 1
    end

  protected

    # Allow shell to be shared between invocations.
    #
    def _shared_configuration #:nodoc:
      super.merge!(:shell => shell)
    end
  end
end
require "rbconfig"

class Bundler::Thor
  module Sandbox #:nodoc:
  end

  # This module holds several utilities:
  #
  # 1) Methods to convert thor namespaces to constants and vice-versa.
  #
  #   Bundler::Thor::Util.namespace_from_thor_class(Foo::Bar::Baz) #=> "foo:bar:baz"
  #
  # 2) Loading thor files and sandboxing:
  #
  #   Bundler::Thor::Util.load_thorfile("~/.thor/foo")
  #
  module Util
    class << self
      # Receives a namespace and search for it in the Bundler::Thor::Base subclasses.
      #
      # ==== Parameters
      # namespace<String>:: The namespace to search for.
      #
      def find_by_namespace(namespace)
        namespace = "default#{namespace}" if namespace.empty? || namespace =~ /^:/
        Bundler::Thor::Base.subclasses.detect { |klass| klass.namespace == namespace }
      end

      # Receives a constant and converts it to a Bundler::Thor namespace. Since Bundler::Thor
      # commands can be added to a sandbox, this method is also responsible for
      # removing the sandbox namespace.
      #
      # This method should not be used in general because it's used to deal with
      # older versions of Bundler::Thor. On current versions, if you need to get the
      # namespace from a class, just call namespace on it.
      #
      # ==== Parameters
      # constant<Object>:: The constant to be converted to the thor path.
      #
      # ==== Returns
      # String:: If we receive Foo::Bar::Baz it returns "foo:bar:baz"
      #
      def namespace_from_thor_class(constant)
        constant = constant.to_s.gsub(/^Bundler::Thor::Sandbox::/, "")
        constant = snake_case(constant).squeeze(":")
        constant
      end

      # Given the contents, evaluate it inside the sandbox and returns the
      # namespaces defined in the sandbox.
      #
      # ==== Parameters
      # contents<String>
      #
      # ==== Returns
      # Array[Object]
      #
      def namespaces_in_content(contents, file = __FILE__)
        old_constants = Bundler::Thor::Base.subclasses.dup
        Bundler::Thor::Base.subclasses.clear

        load_thorfile(file, contents)

        new_constants = Bundler::Thor::Base.subclasses.dup
        Bundler::Thor::Base.subclasses.replace(old_constants)

        new_constants.map!(&:namespace)
        new_constants.compact!
        new_constants
      end

      # Returns the thor classes declared inside the given class.
      #
      def thor_classes_in(klass)
        stringfied_constants = klass.constants.map(&:to_s)
        Bundler::Thor::Base.subclasses.select do |subclass|
          next unless subclass.name
          stringfied_constants.include?(subclass.name.gsub("#{klass.name}::", ""))
        end
      end

      # Receives a string and convert it to snake case. SnakeCase returns snake_case.
      #
      # ==== Parameters
      # String
      #
      # ==== Returns
      # String
      #
      def snake_case(str)
        return str.downcase if str =~ /^[A-Z_]+$/
        str.gsub(/\B[A-Z]/, '_\&').squeeze("_") =~ /_*(.*)/
        $+.downcase
      end

      # Receives a string and convert it to camel case. camel_case returns CamelCase.
      #
      # ==== Parameters
      # String
      #
      # ==== Returns
      # String
      #
      def camel_case(str)
        return str if str !~ /_/ && str =~ /[A-Z]+.*/
        str.split("_").map(&:capitalize).join
      end

      # Receives a namespace and tries to retrieve a Bundler::Thor or Bundler::Thor::Group class
      # from it. It first searches for a class using the all the given namespace,
      # if it's not found, removes the highest entry and searches for the class
      # again. If found, returns the highest entry as the class name.
      #
      # ==== Examples
      #
      #   class Foo::Bar < Bundler::Thor
      #     def baz
      #     end
      #   end
      #
      #   class Baz::Foo < Bundler::Thor::Group
      #   end
      #
      #   Bundler::Thor::Util.namespace_to_thor_class("foo:bar")     #=> Foo::Bar, nil # will invoke default command
      #   Bundler::Thor::Util.namespace_to_thor_class("baz:foo")     #=> Baz::Foo, nil
      #   Bundler::Thor::Util.namespace_to_thor_class("foo:bar:baz") #=> Foo::Bar, "baz"
      #
      # ==== Parameters
      # namespace<String>
      #
      def find_class_and_command_by_namespace(namespace, fallback = true)
        if namespace.include?(":") # look for a namespaced command
          pieces  = namespace.split(":")
          command = pieces.pop
          klass   = Bundler::Thor::Util.find_by_namespace(pieces.join(":"))
        end
        unless klass # look for a Bundler::Thor::Group with the right name
          klass = Bundler::Thor::Util.find_by_namespace(namespace)
          command = nil
        end
        if !klass && fallback # try a command in the default namespace
          command = namespace
          klass   = Bundler::Thor::Util.find_by_namespace("")
        end
        [klass, command]
      end
      alias_method :find_class_and_task_by_namespace, :find_class_and_command_by_namespace

      # Receives a path and load the thor file in the path. The file is evaluated
      # inside the sandbox to avoid namespacing conflicts.
      #
      def load_thorfile(path, content = nil, debug = false)
        content ||= File.binread(path)

        begin
          Bundler::Thor::Sandbox.class_eval(content, path)
        rescue StandardError => e
          $stderr.puts("WARNING: unable to load thorfile #{path.inspect}: #{e.message}")
          if debug
            $stderr.puts(*e.backtrace)
          else
            $stderr.puts(e.backtrace.first)
          end
        end
      end

      def user_home
        @@user_home ||= if ENV["HOME"]
          ENV["HOME"]
        elsif ENV["USERPROFILE"]
          ENV["USERPROFILE"]
        elsif ENV["HOMEDRIVE"] && ENV["HOMEPATH"]
          File.join(ENV["HOMEDRIVE"], ENV["HOMEPATH"])
        elsif ENV["APPDATA"]
          ENV["APPDATA"]
        else
          begin
            File.expand_path("~")
          rescue
            if File::ALT_SEPARATOR
              "C:/"
            else
              "/"
            end
          end
        end
      end

      # Returns the root where thor files are located, depending on the OS.
      #
      def thor_root
        File.join(user_home, ".thor").tr('\\', "/")
      end

      # Returns the files in the thor root. On Windows thor_root will be something
      # like this:
      #
      #   C:\Documents and Settings\james\.thor
      #
      # If we don't #gsub the \ character, Dir.glob will fail.
      #
      def thor_root_glob
        files = Dir["#{escape_globs(thor_root)}/*"]

        files.map! do |file|
          File.directory?(file) ? File.join(file, "main.thor") : file
        end
      end

      # Where to look for Bundler::Thor files.
      #
      def globs_for(path)
        path = escape_globs(path)
        ["#{path}/Thorfile", "#{path}/*.thor", "#{path}/tasks/*.thor", "#{path}/lib/tasks/*.thor"]
      end

      # Return the path to the ruby interpreter taking into account multiple
      # installations and windows extensions.
      #
      def ruby_command
        @ruby_command ||= begin
          ruby_name = RbConfig::CONFIG["ruby_install_name"]
          ruby = File.join(RbConfig::CONFIG["bindir"], ruby_name)
          ruby << RbConfig::CONFIG["EXEEXT"]

          # avoid using different name than ruby (on platforms supporting links)
          if ruby_name != "ruby" && File.respond_to?(:readlink)
            begin
              alternate_ruby = File.join(RbConfig::CONFIG["bindir"], "ruby")
              alternate_ruby << RbConfig::CONFIG["EXEEXT"]

              # ruby is a symlink
              if File.symlink? alternate_ruby
                linked_ruby = File.readlink alternate_ruby

                # symlink points to 'ruby_install_name'
                ruby = alternate_ruby if linked_ruby == ruby_name || linked_ruby == ruby
              end
            rescue NotImplementedError # rubocop:disable HandleExceptions
              # just ignore on windows
            end
          end

          # escape string in case path to ruby executable contain spaces.
          ruby.sub!(/.*\s.*/m, '"\&"')
          ruby
        end
      end

      # Returns a string that has had any glob characters escaped.
      # The glob characters are `* ? { } [ ]`.
      #
      # ==== Examples
      #
      #   Bundler::Thor::Util.escape_globs('[apps]')   # => '\[apps\]'
      #
      # ==== Parameters
      # String
      #
      # ==== Returns
      # String
      #
      def escape_globs(path)
        path.to_s.gsub(/[*?{}\[\]]/, '\\\\\\&')
      end

      # Returns a string that has had any HTML characters escaped.
      #
      # ==== Examples
      #
      #   Bundler::Thor::Util.escape_html('<div>')   # => "&lt;div&gt;"
      #
      # ==== Parameters
      # String
      #
      # ==== Returns
      # String
      #
      def escape_html(string)
        CGI.escapeHTML(string)
      end
    end
  end
end
require_relative "base"

# Bundler::Thor has a special class called Bundler::Thor::Group. The main difference to Bundler::Thor class
# is that it invokes all commands at once. It also include some methods that allows
# invocations to be done at the class method, which are not available to Bundler::Thor
# commands.
class Bundler::Thor::Group
  class << self
    # The description for this Bundler::Thor::Group. If none is provided, but a source root
    # exists, tries to find the USAGE one folder above it, otherwise searches
    # in the superclass.
    #
    # ==== Parameters
    # description<String>:: The description for this Bundler::Thor::Group.
    #
    def desc(description = nil)
      if description
        @desc = description
      else
        @desc ||= from_superclass(:desc, nil)
      end
    end

    # Prints help information.
    #
    # ==== Options
    # short:: When true, shows only usage.
    #
    def help(shell)
      shell.say "Usage:"
      shell.say "  #{banner}\n"
      shell.say
      class_options_help(shell)
      shell.say desc if desc
    end

    # Stores invocations for this class merging with superclass values.
    #
    def invocations #:nodoc:
      @invocations ||= from_superclass(:invocations, {})
    end

    # Stores invocation blocks used on invoke_from_option.
    #
    def invocation_blocks #:nodoc:
      @invocation_blocks ||= from_superclass(:invocation_blocks, {})
    end

    # Invoke the given namespace or class given. It adds an instance
    # method that will invoke the klass and command. You can give a block to
    # configure how it will be invoked.
    #
    # The namespace/class given will have its options showed on the help
    # usage. Check invoke_from_option for more information.
    #
    def invoke(*names, &block)
      options = names.last.is_a?(Hash) ? names.pop : {}
      verbose = options.fetch(:verbose, true)

      names.each do |name|
        invocations[name] = false
        invocation_blocks[name] = block if block_given?

        class_eval <<-METHOD, __FILE__, __LINE__ + 1
          def _invoke_#{name.to_s.gsub(/\W/, '_')}
            klass, command = self.class.prepare_for_invocation(nil, #{name.inspect})

            if klass
              say_status :invoke, #{name.inspect}, #{verbose.inspect}
              block = self.class.invocation_blocks[#{name.inspect}]
              _invoke_for_class_method klass, command, &block
            else
              say_status :error, %(#{name.inspect} [not found]), :red
            end
          end
        METHOD
      end
    end

    # Invoke a thor class based on the value supplied by the user to the
    # given option named "name". A class option must be created before this
    # method is invoked for each name given.
    #
    # ==== Examples
    #
    #   class GemGenerator < Bundler::Thor::Group
    #     class_option :test_framework, :type => :string
    #     invoke_from_option :test_framework
    #   end
    #
    # ==== Boolean options
    #
    # In some cases, you want to invoke a thor class if some option is true or
    # false. This is automatically handled by invoke_from_option. Then the
    # option name is used to invoke the generator.
    #
    # ==== Preparing for invocation
    #
    # In some cases you want to customize how a specified hook is going to be
    # invoked. You can do that by overwriting the class method
    # prepare_for_invocation. The class method must necessarily return a klass
    # and an optional command.
    #
    # ==== Custom invocations
    #
    # You can also supply a block to customize how the option is going to be
    # invoked. The block receives two parameters, an instance of the current
    # class and the klass to be invoked.
    #
    def invoke_from_option(*names, &block)
      options = names.last.is_a?(Hash) ? names.pop : {}
      verbose = options.fetch(:verbose, :white)

      names.each do |name|
        unless class_options.key?(name)
          raise ArgumentError, "You have to define the option #{name.inspect} " \
                              "before setting invoke_from_option."
        end

        invocations[name] = true
        invocation_blocks[name] = block if block_given?

        class_eval <<-METHOD, __FILE__, __LINE__ + 1
          def _invoke_from_option_#{name.to_s.gsub(/\W/, '_')}
            return unless options[#{name.inspect}]

            value = options[#{name.inspect}]
            value = #{name.inspect} if TrueClass === value
            klass, command = self.class.prepare_for_invocation(#{name.inspect}, value)

            if klass
              say_status :invoke, value, #{verbose.inspect}
              block = self.class.invocation_blocks[#{name.inspect}]
              _invoke_for_class_method klass, command, &block
            else
              say_status :error, %(\#{value} [not found]), :red
            end
          end
        METHOD
      end
    end

    # Remove a previously added invocation.
    #
    # ==== Examples
    #
    #   remove_invocation :test_framework
    #
    def remove_invocation(*names)
      names.each do |name|
        remove_command(name)
        remove_class_option(name)
        invocations.delete(name)
        invocation_blocks.delete(name)
      end
    end

    # Overwrite class options help to allow invoked generators options to be
    # shown recursively when invoking a generator.
    #
    def class_options_help(shell, groups = {}) #:nodoc:
      get_options_from_invocations(groups, class_options) do |klass|
        klass.send(:get_options_from_invocations, groups, class_options)
      end
      super(shell, groups)
    end

    # Get invocations array and merge options from invocations. Those
    # options are added to group_options hash. Options that already exists
    # in base_options are not added twice.
    #
    def get_options_from_invocations(group_options, base_options) #:nodoc: # rubocop:disable MethodLength
      invocations.each do |name, from_option|
        value = if from_option
          option = class_options[name]
          option.type == :boolean ? name : option.default
        else
          name
        end
        next unless value

        klass, _ = prepare_for_invocation(name, value)
        next unless klass && klass.respond_to?(:class_options)

        value = value.to_s
        human_name = value.respond_to?(:classify) ? value.classify : value

        group_options[human_name] ||= []
        group_options[human_name] += klass.class_options.values.select do |class_option|
          base_options[class_option.name.to_sym].nil? && class_option.group.nil? &&
            !group_options.values.flatten.any? { |i| i.name == class_option.name }
        end

        yield klass if block_given?
      end
    end

    # Returns commands ready to be printed.
    def printable_commands(*)
      item = []
      item << banner
      item << (desc ? "# #{desc.gsub(/\s+/m, ' ')}" : "")
      [item]
    end
    alias_method :printable_tasks, :printable_commands

    def handle_argument_error(command, error, _args, arity) #:nodoc:
      msg = "#{basename} #{command.name} takes #{arity} argument".dup
      msg << "s" if arity > 1
      msg << ", but it should not."
      raise error, msg
    end

  protected

    # The method responsible for dispatching given the args.
    def dispatch(command, given_args, given_opts, config) #:nodoc:
      if Bundler::Thor::HELP_MAPPINGS.include?(given_args.first)
        help(config[:shell])
        return
      end

      args, opts = Bundler::Thor::Options.split(given_args)
      opts = given_opts || opts

      instance = new(args, opts, config)
      yield instance if block_given?

      if command
        instance.invoke_command(all_commands[command])
      else
        instance.invoke_all
      end
    end

    # The banner for this class. You can customize it if you are invoking the
    # thor class by another ways which is not the Bundler::Thor::Runner.
    def banner
      "#{basename} #{self_command.formatted_usage(self, false)}"
    end

    # Represents the whole class as a command.
    def self_command #:nodoc:
      Bundler::Thor::DynamicCommand.new(namespace, class_options)
    end
    alias_method :self_task, :self_command

    def baseclass #:nodoc:
      Bundler::Thor::Group
    end

    def create_command(meth) #:nodoc:
      commands[meth.to_s] = Bundler::Thor::Command.new(meth, nil, nil, nil, nil)
      true
    end
    alias_method :create_task, :create_command
  end

  include Bundler::Thor::Base

protected

  # Shortcut to invoke with padding and block handling. Use internally by
  # invoke and invoke_from_option class methods.
  def _invoke_for_class_method(klass, command = nil, *args, &block) #:nodoc:
    with_padding do
      if block
        case block.arity
        when 3
          yield(self, klass, command)
        when 2
          yield(self, klass)
        when 1
          instance_exec(klass, &block)
        end
      else
        invoke klass, command, *args
      end
    end
  end
end
class Bundler::Thor
  module LineEditor
    class Readline < Basic
      def self.available?
        begin
          require "readline"
        rescue LoadError
        end

        Object.const_defined?(:Readline)
      end

      def readline
        if echo?
          ::Readline.completion_append_character = nil
          # rb-readline does not allow Readline.completion_proc= to receive nil.
          if complete = completion_proc
            ::Readline.completion_proc = complete
          end
          ::Readline.readline(prompt, add_to_history?)
        else
          super
        end
      end

    private

      def add_to_history?
        options.fetch(:add_to_history, true)
      end

      def completion_proc
        if use_path_completion?
          proc { |text| PathCompletion.new(text).matches }
        elsif completion_options.any?
          proc do |text|
            completion_options.select { |option| option.start_with?(text) }
          end
        end
      end

      def completion_options
        options.fetch(:limited_to, [])
      end

      def use_path_completion?
        options.fetch(:path, false)
      end

      class PathCompletion
        attr_reader :text
        private :text

        def initialize(text)
          @text = text
        end

        def matches
          relative_matches
        end

      private

        def relative_matches
          absolute_matches.map { |path| path.sub(base_path, "") }
        end

        def absolute_matches
          Dir[glob_pattern].map do |path|
            if File.directory?(path)
              "#{path}/"
            else
              path
            end
          end
        end

        def glob_pattern
          "#{base_path}#{text}*"
        end

        def base_path
          "#{Dir.pwd}/"
        end
      end
    end
  end
end
class Bundler::Thor
  module LineEditor
    class Basic
      attr_reader :prompt, :options

      def self.available?
        true
      end

      def initialize(prompt, options)
        @prompt = prompt
        @options = options
      end

      def readline
        $stdout.print(prompt)
        get_input
      end

    private

      def get_input
        if echo?
          $stdin.gets
        else
          # Lazy-load io/console since it is gem-ified as of 2.3
          require "io/console"
          $stdin.noecho(&:gets)
        end
      end

      def echo?
        options.fetch(:echo, true)
      end
    end
  end
end
class Bundler::Thor
  module CoreExt #:nodoc:
    # A hash with indifferent access and magic predicates.
    #
    #   hash = Bundler::Thor::CoreExt::HashWithIndifferentAccess.new 'foo' => 'bar', 'baz' => 'bee', 'force' => true
    #
    #   hash[:foo]  #=> 'bar'
    #   hash['foo'] #=> 'bar'
    #   hash.foo?   #=> true
    #
    class HashWithIndifferentAccess < ::Hash #:nodoc:
      def initialize(hash = {})
        super()
        hash.each do |key, value|
          self[convert_key(key)] = value
        end
      end

      def [](key)
        super(convert_key(key))
      end

      def []=(key, value)
        super(convert_key(key), value)
      end

      def delete(key)
        super(convert_key(key))
      end

      def fetch(key, *args)
        super(convert_key(key), *args)
      end

      def key?(key)
        super(convert_key(key))
      end

      def values_at(*indices)
        indices.map { |key| self[convert_key(key)] }
      end

      def merge(other)
        dup.merge!(other)
      end

      def merge!(other)
        other.each do |key, value|
          self[convert_key(key)] = value
        end
        self
      end

      def reverse_merge(other)
        self.class.new(other).merge(self)
      end

      def reverse_merge!(other_hash)
        replace(reverse_merge(other_hash))
      end

      def replace(other_hash)
        super(other_hash)
      end

      # Convert to a Hash with String keys.
      def to_hash
        Hash.new(default).merge!(self)
      end

    protected

      def convert_key(key)
        key.is_a?(Symbol) ? key.to_s : key
      end

      # Magic predicates. For instance:
      #
      #   options.force?                  # => !!options['force']
      #   options.shebang                 # => "/usr/lib/local/ruby"
      #   options.test_framework?(:rspec) # => options[:test_framework] == :rspec
      #
      def method_missing(method, *args)
        method = method.to_s
        if method =~ /^(\w+)\?$/
          if args.empty?
            !!self[$1]
          else
            self[$1] == args.first
          end
        else
          self[method]
        end
      end
    end
  end
end
class Bundler::Thor
  Correctable = if defined?(DidYouMean::SpellChecker) && defined?(DidYouMean::Correctable) # rubocop:disable Naming/ConstantName
                  # In order to support versions of Ruby that don't have keyword
                  # arguments, we need our own spell checker class that doesn't take key
                  # words. Even though this code wouldn't be hit because of the check
                  # above, it's still necessary because the interpreter would otherwise be
                  # unable to parse the file.
                  class NoKwargSpellChecker < DidYouMean::SpellChecker # :nodoc:
                    def initialize(dictionary)
                      @dictionary = dictionary
                    end
                  end

                  DidYouMean::Correctable
                end

  # Bundler::Thor::Error is raised when it's caused by wrong usage of thor classes. Those
  # errors have their backtrace suppressed and are nicely shown to the user.
  #
  # Errors that are caused by the developer, like declaring a method which
  # overwrites a thor keyword, SHOULD NOT raise a Bundler::Thor::Error. This way, we
  # ensure that developer errors are shown with full backtrace.
  class Error < StandardError
  end

  # Raised when a command was not found.
  class UndefinedCommandError < Error
    class SpellChecker
      attr_reader :error

      def initialize(error)
        @error = error
      end

      def corrections
        @corrections ||= spell_checker.correct(error.command).map(&:inspect)
      end

      def spell_checker
        NoKwargSpellChecker.new(error.all_commands)
      end
    end

    attr_reader :command, :all_commands

    def initialize(command, all_commands, namespace)
      @command = command
      @all_commands = all_commands

      message = "Could not find command #{command.inspect}"
      message = namespace ? "#{message} in #{namespace.inspect} namespace." : "#{message}."

      super(message)
    end

    prepend Correctable if Correctable
  end
  UndefinedTaskError = UndefinedCommandError

  class AmbiguousCommandError < Error
  end
  AmbiguousTaskError = AmbiguousCommandError

  # Raised when a command was found, but not invoked properly.
  class InvocationError < Error
  end

  class UnknownArgumentError < Error
    class SpellChecker
      attr_reader :error

      def initialize(error)
        @error = error
      end

      def corrections
        @corrections ||=
          error.unknown.flat_map { |unknown| spell_checker.correct(unknown) }.uniq.map(&:inspect)
      end

      def spell_checker
        @spell_checker ||= NoKwargSpellChecker.new(error.switches)
      end
    end

    attr_reader :switches, :unknown

    def initialize(switches, unknown)
      @switches = switches
      @unknown = unknown

      super("Unknown switches #{unknown.map(&:inspect).join(', ')}")
    end

    prepend Correctable if Correctable
  end

  class RequiredArgumentMissingError < InvocationError
  end

  class MalformattedArgumentError < InvocationError
  end

  if Correctable
    DidYouMean::SPELL_CHECKERS.merge!(
      'Bundler::Thor::UndefinedCommandError' => UndefinedCommandError::SpellChecker,
      'Bundler::Thor::UnknownArgumentError' => UnknownArgumentError::SpellChecker
    )
  end
end
class Bundler::Thor
  class Command < Struct.new(:name, :description, :long_description, :usage, :options, :ancestor_name)
    FILE_REGEXP = /^#{Regexp.escape(File.dirname(__FILE__))}/

    def initialize(name, description, long_description, usage, options = nil)
      super(name.to_s, description, long_description, usage, options || {})
    end

    def initialize_copy(other) #:nodoc:
      super(other)
      self.options = other.options.dup if other.options
    end

    def hidden?
      false
    end

    # By default, a command invokes a method in the thor class. You can change this
    # implementation to create custom commands.
    def run(instance, args = [])
      arity = nil

      if private_method?(instance)
        instance.class.handle_no_command_error(name)
      elsif public_method?(instance)
        arity = instance.method(name).arity
        instance.__send__(name, *args)
      elsif local_method?(instance, :method_missing)
        instance.__send__(:method_missing, name.to_sym, *args)
      else
        instance.class.handle_no_command_error(name)
      end
    rescue ArgumentError => e
      handle_argument_error?(instance, e, caller) ? instance.class.handle_argument_error(self, e, args, arity) : (raise e)
    rescue NoMethodError => e
      handle_no_method_error?(instance, e, caller) ? instance.class.handle_no_command_error(name) : (raise e)
    end

    # Returns the formatted usage by injecting given required arguments
    # and required options into the given usage.
    def formatted_usage(klass, namespace = true, subcommand = false)
      if ancestor_name
        formatted = "#{ancestor_name} ".dup # add space
      elsif namespace
        namespace = klass.namespace
        formatted = "#{namespace.gsub(/^(default)/, '')}:".dup
      end
      formatted ||= "#{klass.namespace.split(':').last} ".dup if subcommand

      formatted ||= "".dup

      Array(usage).map do |specific_usage|
        formatted_specific_usage = formatted

        formatted_specific_usage += required_arguments_for(klass, specific_usage)

        # Add required options
        formatted_specific_usage += " #{required_options}"

        # Strip and go!
        formatted_specific_usage.strip
      end.join("\n")
    end

  protected

    # Add usage with required arguments
    def required_arguments_for(klass, usage)
      if klass && !klass.arguments.empty?
        usage.to_s.gsub(/^#{name}/) do |match|
          match << " " << klass.arguments.map(&:usage).compact.join(" ")
        end
      else
        usage.to_s
      end
    end

    def not_debugging?(instance)
      !(instance.class.respond_to?(:debugging) && instance.class.debugging)
    end

    def required_options
      @required_options ||= options.map { |_, o| o.usage if o.required? }.compact.sort.join(" ")
    end

    # Given a target, checks if this class name is a public method.
    def public_method?(instance) #:nodoc:
      !(instance.public_methods & [name.to_s, name.to_sym]).empty?
    end

    def private_method?(instance)
      !(instance.private_methods & [name.to_s, name.to_sym]).empty?
    end

    def local_method?(instance, name)
      methods = instance.public_methods(false) + instance.private_methods(false) + instance.protected_methods(false)
      !(methods & [name.to_s, name.to_sym]).empty?
    end

    def sans_backtrace(backtrace, caller) #:nodoc:
      saned = backtrace.reject { |frame| frame =~ FILE_REGEXP || (frame =~ /\.java:/ && RUBY_PLATFORM =~ /java/) || (frame =~ %r{^kernel/} && RUBY_ENGINE =~ /rbx/) }
      saned - caller
    end

    def handle_argument_error?(instance, error, caller)
      not_debugging?(instance) && (error.message =~ /wrong number of arguments/ || error.message =~ /given \d*, expected \d*/) && begin
        saned = sans_backtrace(error.backtrace, caller)
        saned.empty? || saned.size == 1
      end
    end

    def handle_no_method_error?(instance, error, caller)
      not_debugging?(instance) &&
        error.message =~ /^undefined method `#{name}' for #{Regexp.escape(instance.to_s)}$/
    end
  end
  Task = Command

  # A command that is hidden in help messages but still invocable.
  class HiddenCommand < Command
    def hidden?
      true
    end
  end
  HiddenTask = HiddenCommand

  # A dynamic command that handles method missing scenarios.
  class DynamicCommand < Command
    def initialize(name, options = nil)
      super(name.to_s, "A dynamically-generated command", name.to_s, name.to_s, options)
    end

    def run(instance, args = [])
      if (instance.methods & [name.to_s, name.to_sym]).empty?
        super
      else
        instance.class.handle_no_command_error(name)
      end
    end
  end
  DynamicTask = DynamicCommand
end
class Bundler::Thor
  VERSION = "1.1.0"
end
require_relative "line_editor/basic"
require_relative "line_editor/readline"

class Bundler::Thor
  module LineEditor
    def self.readline(prompt, options = {})
      best_available.new(prompt, options).readline
    end

    def self.best_available
      [
        Bundler::Thor::LineEditor::Readline,
        Bundler::Thor::LineEditor::Basic
      ].detect(&:available?)
    end
  end
end
require "rake"
require "rake/dsl_definition"

class Bundler::Thor
  # Adds a compatibility layer to your Bundler::Thor classes which allows you to use
  # rake package tasks. For example, to use rspec rake tasks, one can do:
  #
  #   require 'bundler/vendor/thor/lib/thor/rake_compat'
  #   require 'rspec/core/rake_task'
  #
  #   class Default < Bundler::Thor
  #     include Bundler::Thor::RakeCompat
  #
  #     RSpec::Core::RakeTask.new(:spec) do |t|
  #       t.spec_opts = ['--options', './.rspec']
  #       t.spec_files = FileList['spec/**/*_spec.rb']
  #     end
  #   end
  #
  module RakeCompat
    include Rake::DSL if defined?(Rake::DSL)

    def self.rake_classes
      @rake_classes ||= []
    end

    def self.included(base)
      super(base)
      # Hack. Make rakefile point to invoker, so rdoc task is generated properly.
      rakefile = File.basename(caller[0].match(/(.*):\d+/)[1])
      Rake.application.instance_variable_set(:@rakefile, rakefile)
      rake_classes << base
    end
  end
end

# override task on (main), for compatibility with Rake 0.9
instance_eval do
  alias rake_namespace namespace

  def task(*)
    task = super

    if klass = Bundler::Thor::RakeCompat.rake_classes.last # rubocop:disable AssignmentInCondition
      non_namespaced_name = task.name.split(":").last

      description = non_namespaced_name
      description << task.arg_names.map { |n| n.to_s.upcase }.join(" ")
      description.strip!

      klass.desc description, Rake.application.last_description || non_namespaced_name
      Rake.application.last_description = nil
      klass.send :define_method, non_namespaced_name do |*args|
        Rake::Task[task.name.to_sym].invoke(*args)
      end
    end

    task
  end

  def namespace(name)
    if klass = Bundler::Thor::RakeCompat.rake_classes.last # rubocop:disable AssignmentInCondition
      const_name = Bundler::Thor::Util.camel_case(name.to_s).to_sym
      klass.const_set(const_name, Class.new(Bundler::Thor))
      new_klass = klass.const_get(const_name)
      Bundler::Thor::RakeCompat.rake_classes << new_klass
    end

    super
    Bundler::Thor::RakeCompat.rake_classes.pop
  end
end
# frozen_string_literal: true

module Bundler
  # A stub yaml serializer that can handle only hashes and strings (as of now).
  module YAMLSerializer
    module_function

    def dump(hash)
      yaml = String.new("---")
      yaml << dump_hash(hash)
    end

    def dump_hash(hash)
      yaml = String.new("\n")
      hash.each do |k, v|
        yaml << k << ":"
        if v.is_a?(Hash)
          yaml << dump_hash(v).gsub(/^(?!$)/, "  ") # indent all non-empty lines
        elsif v.is_a?(Array) # Expected to be array of strings
          yaml << "\n- " << v.map {|s| s.to_s.gsub(/\s+/, " ").inspect }.join("\n- ") << "\n"
        else
          yaml << " " << v.to_s.gsub(/\s+/, " ").inspect << "\n"
        end
      end
      yaml
    end

    ARRAY_REGEX = /
      ^
      (?:[ ]*-[ ]) # '- ' before array items
      (['"]?) # optional opening quote
      (.*) # value
      \1 # matching closing quote
      $
    /xo.freeze

    HASH_REGEX = /
      ^
      ([ ]*) # indentations
      (.+) # key
      (?::(?=(?:\s|$))) # :  (without the lookahead the #key includes this when : is present in value)
      [ ]?
      (['"]?) # optional opening quote
      (.*) # value
      \3 # matching closing quote
      $
    /xo.freeze

    def load(str)
      res = {}
      stack = [res]
      last_hash = nil
      last_empty_key = nil
      str.split(/\r?\n/).each do |line|
        if match = HASH_REGEX.match(line)
          indent, key, quote, val = match.captures
          key = convert_to_backward_compatible_key(key)
          depth = indent.scan(/  /).length
          if quote.empty? && val.empty?
            new_hash = {}
            stack[depth][key] = new_hash
            stack[depth + 1] = new_hash
            last_empty_key = key
            last_hash = stack[depth]
          else
            stack[depth][key] = val
          end
        elsif match = ARRAY_REGEX.match(line)
          _, val = match.captures
          last_hash[last_empty_key] = [] unless last_hash[last_empty_key].is_a?(Array)

          last_hash[last_empty_key].push(val)
        end
      end
      res
    end

    # for settings' keys
    def convert_to_backward_compatible_key(key)
      key = "#{key}/" if key =~ /https?:/i && key !~ %r{/\Z}
      key = key.gsub(".", "__") if key.include?(".")
      key
    end

    class << self
      private :dump_hash, :convert_to_backward_compatible_key
    end
  end
end
# frozen_string_literal: true

module Bundler
  module UI
    autoload :RGProxy, File.expand_path("ui/rg_proxy", __dir__)
    autoload :Shell,   File.expand_path("ui/shell", __dir__)
    autoload :Silent,  File.expand_path("ui/silent", __dir__)
  end
end
# frozen_string_literal: true

module Bundler
  class Worker
    POISON = Object.new

    class WrappedException < StandardError
      attr_reader :exception
      def initialize(exn)
        @exception = exn
      end
    end

    # @return [String] the name of the worker
    attr_reader :name

    # Creates a worker pool of specified size
    #
    # @param size [Integer] Size of pool
    # @param name [String] name the name of the worker
    # @param func [Proc] job to run in inside the worker pool
    def initialize(size, name, func)
      @name = name
      @request_queue = Thread::Queue.new
      @response_queue = Thread::Queue.new
      @func = func
      @size = size
      @threads = nil
      @previous_interrupt_handler = nil
    end

    # Enqueue a request to be executed in the worker pool
    #
    # @param obj [String] mostly it is name of spec that should be downloaded
    def enq(obj)
      create_threads unless @threads
      @request_queue.enq obj
    end

    # Retrieves results of job function being executed in worker pool
    def deq
      result = @response_queue.deq
      raise result.exception if result.is_a?(WrappedException)
      result
    end

    def stop
      stop_threads
    end

    private

    def process_queue(i)
      loop do
        obj = @request_queue.deq
        break if obj.equal? POISON
        @response_queue.enq apply_func(obj, i)
      end
    end

    def apply_func(obj, i)
      @func.call(obj, i)
    rescue Exception => e # rubocop:disable Lint/RescueException
      WrappedException.new(e)
    end

    # Stop the worker threads by sending a poison object down the request queue
    # so as worker threads after retrieving it, shut themselves down
    def stop_threads
      return unless @threads

      @threads.each { @request_queue.enq POISON }
      @threads.each(&:join)

      remove_interrupt_handler

      @threads = nil
    end

    def abort_threads
      Bundler.ui.debug("\n#{caller.join("\n")}")
      @threads.each(&:exit)
      exit 1
    end

    def create_threads
      creation_errors = []

      @threads = Array.new(@size) do |i|
        begin
          Thread.start { process_queue(i) }.tap do |thread|
            thread.name = "#{name} Worker ##{i}" if thread.respond_to?(:name=)
          end
        rescue ThreadError => e
          creation_errors << e
          nil
        end
      end.compact

      add_interrupt_handler unless @threads.empty?

      return if creation_errors.empty?

      message = "Failed to create threads for the #{name} worker: #{creation_errors.map(&:to_s).uniq.join(", ")}"
      raise ThreadCreationError, message if @threads.empty?
      Bundler.ui.info message
    end

    def add_interrupt_handler
      @previous_interrupt_handler = trap("INT") { abort_threads }
    end

    def remove_interrupt_handler
      return unless @previous_interrupt_handler

      trap "INT", @previous_interrupt_handler
    end
  end
end
# frozen_string_literal: true

require_relative "shared_helpers"

if Bundler::SharedHelpers.in_bundle?
  require_relative "../bundler"

  if STDOUT.tty? || ENV["BUNDLER_FORCE_TTY"]
    begin
      Bundler.ui.silence { Bundler.setup }
    rescue Bundler::BundlerError => e
      Bundler.ui.error e.message
      Bundler.ui.warn e.backtrace.join("\n") if ENV["DEBUG"]
      if e.is_a?(Bundler::GemNotFound)
        Bundler.ui.warn "Run `bundle install` to install missing gems."
      end
      exit e.status_code
    end
  else
    Bundler.ui.silence { Bundler.setup }
  end

  # We might be in the middle of shelling out to rubygems
  # (RUBYOPT=-rbundler/setup), so we need to give rubygems the opportunity of
  # not being silent.
  Gem::DefaultUserInteraction.ui = nil
end
# frozen_string_literal: true

require_relative "vendored_tsort"

module Bundler
  class SpecSet
    include Enumerable
    include TSort

    def initialize(specs)
      @specs = specs
    end

    def for(dependencies, check = false, match_current_platform = false)
      handled = []
      deps = dependencies.dup
      specs = []

      loop do
        break unless dep = deps.shift
        next if handled.any?{|d| d.name == dep.name && (match_current_platform || d.__platform == dep.__platform) } || dep.name == "bundler"

        handled << dep

        specs_for_dep = spec_for_dependency(dep, match_current_platform)
        if specs_for_dep.any?
          match_current_platform ? specs += specs_for_dep : specs |= specs_for_dep

          specs_for_dep.first.dependencies.each do |d|
            next if d.type == :development
            d = DepProxy.get_proxy(d, dep.__platform) unless match_current_platform
            deps << d
          end
        elsif check
          return false
        end
      end

      if spec = lookup["bundler"].first
        specs << spec
      end

      check ? true : specs
    end

    def [](key)
      key = key.name if key.respond_to?(:name)
      lookup[key].reverse
    end

    def []=(key, value)
      @specs << value
      @lookup = nil
      @sorted = nil
    end

    def sort!
      self
    end

    def to_a
      sorted.dup
    end

    def to_hash
      lookup.dup
    end

    def materialize(deps)
      materialized = self.for(deps, false, true)

      materialized.map! do |s|
        next s unless s.is_a?(LazySpecification)
        s.source.local!
        s.__materialize__ || s
      end
      SpecSet.new(materialized)
    end

    # Materialize for all the specs in the spec set, regardless of what platform they're for
    # This is in contrast to how for does platform filtering (and specifically different from how `materialize` calls `for` only for the current platform)
    # @return [Array<Gem::Specification>]
    def materialized_for_all_platforms
      @specs.map do |s|
        next s unless s.is_a?(LazySpecification)
        s.source.local!
        s.source.remote!
        spec = s.__materialize__
        raise GemNotFound, "Could not find #{s.full_name} in any of the sources" unless spec
        spec
      end
    end

    def missing_specs
      @specs.select {|s| s.is_a?(LazySpecification) }
    end

    def merge(set)
      arr = sorted.dup
      set.each do |set_spec|
        full_name = set_spec.full_name
        next if arr.any? {|spec| spec.full_name == full_name }
        arr << set_spec
      end
      SpecSet.new(arr)
    end

    def find_by_name_and_platform(name, platform)
      @specs.detect {|spec| spec.name == name && spec.match_platform(platform) }
    end

    def what_required(spec)
      unless req = find {|s| s.dependencies.any? {|d| d.type == :runtime && d.name == spec.name } }
        return [spec]
      end
      what_required(req) << spec
    end

    def <<(spec)
      @specs << spec
    end

    def length
      @specs.length
    end

    def size
      @specs.size
    end

    def empty?
      @specs.empty?
    end

    def each(&b)
      sorted.each(&b)
    end

    private

    def sorted
      rake = @specs.find {|s| s.name == "rake" }
      begin
        @sorted ||= ([rake] + tsort).compact.uniq
      rescue TSort::Cyclic => error
        cgems = extract_circular_gems(error)
        raise CyclicDependencyError, "Your bundle requires gems that depend" \
          " on each other, creating an infinite loop. Please remove either" \
          " gem '#{cgems[1]}' or gem '#{cgems[0]}' and try again."
      end
    end

    def extract_circular_gems(error)
      error.message.scan(/@name="(.*?)"/).flatten
    end

    def lookup
      @lookup ||= begin
        lookup = Hash.new {|h, k| h[k] = [] }
        Index.sort_specs(@specs).reverse_each do |s|
          lookup[s.name] << s
        end
        lookup
      end
    end

    def tsort_each_node
      # MUST sort by name for backwards compatibility
      @specs.sort_by(&:name).each {|s| yield s }
    end

    def spec_for_dependency(dep, match_current_platform)
      specs_for_platforms = lookup[dep.name]
      if match_current_platform
        GemHelpers.select_best_platform_match(specs_for_platforms.select{|s| Gem::Platform.match_spec?(s) }, Bundler.local_platform)
      else
        GemHelpers.select_best_platform_match(specs_for_platforms, dep.__platform)
      end
    end

    def tsort_each_child(s)
      s.dependencies.sort_by(&:name).each do |d|
        next if d.type == :development
        lookup[d.name].each {|s2| yield s2 }
      end
    end
  end
end
# frozen_string_literal: true

module Bundler; end
require_relative "vendor/tsort/lib/tsort"
# frozen_string_literal: true

require "pathname"

require "rubygems/specification"

# Possible use in Gem::Specification#source below and require
# shouldn't be deferred.
require "rubygems/source"

require_relative "match_platform"

module Gem
  class Specification
    attr_accessor :remote, :location, :relative_loaded_from

    remove_method :source
    attr_writer :source
    def source
      (defined?(@source) && @source) || Gem::Source::Installed.new
    end

    alias_method :rg_full_gem_path, :full_gem_path
    alias_method :rg_loaded_from,   :loaded_from

    def full_gem_path
      # this cannot check source.is_a?(Bundler::Plugin::API::Source)
      # because that _could_ trip the autoload, and if there are unresolved
      # gems at that time, this method could be called inside another require,
      # thus raising with that constant being undefined. Better to check a method
      if source.respond_to?(:path) || (source.respond_to?(:bundler_plugin_api_source?) && source.bundler_plugin_api_source?)
        Pathname.new(loaded_from).dirname.expand_path(source.root).to_s.tap{|x| x.untaint if RUBY_VERSION < "2.7" }
      else
        rg_full_gem_path
      end
    end

    def loaded_from
      if relative_loaded_from
        source.path.join(relative_loaded_from).to_s
      else
        rg_loaded_from
      end
    end

    def load_paths
      full_require_paths
    end

    alias_method :rg_extension_dir, :extension_dir
    def extension_dir
      @bundler_extension_dir ||= if source.respond_to?(:extension_dir_name)
        unique_extension_dir = [source.extension_dir_name, File.basename(full_gem_path)].uniq.join("-")
        File.expand_path(File.join(extensions_dir, unique_extension_dir))
      else
        rg_extension_dir
      end
    end

    remove_method :gem_dir if instance_methods(false).include?(:gem_dir)
    def gem_dir
      full_gem_path
    end

    def groups
      @groups ||= []
    end

    def git_version
      return unless loaded_from && source.is_a?(Bundler::Source::Git)
      " #{source.revision[0..6]}"
    end

    def to_gemfile(path = nil)
      gemfile = String.new("source 'https://rubygems.org'\n")
      gemfile << dependencies_to_gemfile(nondevelopment_dependencies)
      unless development_dependencies.empty?
        gemfile << "\n"
        gemfile << dependencies_to_gemfile(development_dependencies, :development)
      end
      gemfile
    end

    def nondevelopment_dependencies
      dependencies - development_dependencies
    end

    def deleted_gem?
      !default_gem? && !File.directory?(full_gem_path)
    end

    private

    def dependencies_to_gemfile(dependencies, group = nil)
      gemfile = String.new
      if dependencies.any?
        gemfile << "group :#{group} do\n" if group
        dependencies.each do |dependency|
          gemfile << "  " if group
          gemfile << %(gem "#{dependency.name}")
          req = dependency.requirements_list.first
          gemfile << %(, "#{req}") if req
          gemfile << "\n"
        end
        gemfile << "end\n" if group
      end
      gemfile
    end
  end

  class Dependency
    attr_accessor :source, :groups

    alias_method :eql?, :==

    def encode_with(coder)
      to_yaml_properties.each do |ivar|
        coder[ivar.to_s.sub(/^@/, "")] = instance_variable_get(ivar)
      end
    end

    def to_yaml_properties
      instance_variables.reject {|p| ["@source", "@groups"].include?(p.to_s) }
    end

    def to_lock
      out = String.new("  #{name}")
      unless requirement.none?
        reqs = requirement.requirements.map {|o, v| "#{o} #{v}" }.sort.reverse
        out << " (#{reqs.join(", ")})"
      end
      out
    end
  end

  # comparison is done order independently since rubygems 3.2.0.rc.2
  unless Gem::Requirement.new("> 1", "< 2") == Gem::Requirement.new("< 2", "> 1")
    class Requirement
      module OrderIndependentComparison
        def ==(other)
          if _requirements_sorted? && other._requirements_sorted?
            super
          else
            _with_sorted_requirements == other._with_sorted_requirements
          end
        end

        protected

        def _requirements_sorted?
          return @_are_requirements_sorted if defined?(@_are_requirements_sorted)
          strings = as_list
          @_are_requirements_sorted = strings == strings.sort
        end

        def _with_sorted_requirements
          @_with_sorted_requirements ||= _requirements_sorted? ? self : self.class.new(as_list.sort)
        end
      end

      prepend OrderIndependentComparison
    end
  end

  if Gem::Requirement.new("~> 2.0").hash == Gem::Requirement.new("~> 2.0.0").hash
    class Requirement
      module CorrectHashForLambdaOperator
        def hash
          if requirements.any? {|r| r.first == "~>" }
            requirements.map {|r| r.first == "~>" ? [r[0], r[1].to_s] : r }.sort.hash
          else
            super
          end
        end
      end

      prepend CorrectHashForLambdaOperator
    end
  end

  require "rubygems/platform"

  class Platform
    JAVA  = Gem::Platform.new("java") unless defined?(JAVA)
    MSWIN = Gem::Platform.new("mswin32") unless defined?(MSWIN)
    MSWIN64 = Gem::Platform.new("mswin64") unless defined?(MSWIN64)
    MINGW = Gem::Platform.new("x86-mingw32") unless defined?(MINGW)
    X64_MINGW = Gem::Platform.new("x64-mingw32") unless defined?(X64_MINGW)
  end

  Platform.singleton_class.module_eval do
    unless Platform.singleton_methods.include?(:match_spec?)
      def match_spec?(spec)
        match_gem?(spec.platform, spec.name)
      end

      def match_gem?(platform, gem_name)
        match_platforms?(platform, Gem.platforms)
      end

      private

      def match_platforms?(platform, platforms)
        platforms.any? do |local_platform|
          platform.nil? ||
            local_platform == platform ||
            (local_platform != Gem::Platform::RUBY && local_platform =~ platform)
        end
      end
    end
  end

  require "rubygems/util"

  Util.singleton_class.module_eval do
    if Util.singleton_methods.include?(:glob_files_in_dir) # since 3.0.0.beta.2
      remove_method :glob_files_in_dir
    end

    def glob_files_in_dir(glob, base_path)
      if RUBY_VERSION >= "2.5"
        Dir.glob(glob, :base => base_path).map! {|f| File.expand_path(f, base_path) }
      else
        Dir.glob(File.join(base_path.to_s.gsub(/[\[\]]/, '\\\\\\&'), glob)).map! {|f| File.expand_path(f) }
      end
    end
  end
end

module Gem
  class Specification
    include ::Bundler::MatchPlatform
  end
end
# frozen_string_literal: true

require_relative "../vendored_thor"

module Bundler
  module UI
    class Shell
      LEVELS = %w[silent error warn confirm info debug].freeze

      attr_writer :shell

      def initialize(options = {})
        Thor::Base.shell = options["no-color"] ? Thor::Shell::Basic : nil
        @shell = Thor::Base.shell.new
        @level = ENV["DEBUG"] ? "debug" : "info"
        @warning_history = []
      end

      def add_color(string, *color)
        @shell.set_color(string, *color)
      end

      def info(msg, newline = nil)
        tell_me(msg, nil, newline) if level("info")
      end

      def confirm(msg, newline = nil)
        tell_me(msg, :green, newline) if level("confirm")
      end

      def warn(msg, newline = nil, color = :yellow)
        return unless level("warn")
        return if @warning_history.include? msg
        @warning_history << msg

        tell_err(msg, color, newline)
      end

      def error(msg, newline = nil, color = :red)
        return unless level("error")
        tell_err(msg, color, newline)
      end

      def debug(msg, newline = nil)
        tell_me(msg, nil, newline) if debug?
      end

      def debug?
        level("debug")
      end

      def quiet?
        level("quiet")
      end

      def ask(msg)
        @shell.ask(msg)
      end

      def yes?(msg)
        @shell.yes?(msg)
      end

      def no?
        @shell.no?(msg)
      end

      def level=(level)
        raise ArgumentError unless LEVELS.include?(level.to_s)
        @level = level.to_s
      end

      def level(name = nil)
        return @level unless name
        unless index = LEVELS.index(name)
          raise "#{name.inspect} is not a valid level"
        end
        index <= LEVELS.index(@level)
      end

      def trace(e, newline = nil, force = false)
        return unless debug? || force
        msg = "#{e.class}: #{e.message}\n#{e.backtrace.join("\n  ")}"
        tell_me(msg, nil, newline)
      end

      def silence(&blk)
        with_level("silent", &blk)
      end

      def unprinted_warnings
        []
      end

      private

      # valimism
      def tell_me(msg, color = nil, newline = nil)
        msg = word_wrap(msg) if newline.is_a?(Hash) && newline[:wrap]
        if newline.nil?
          @shell.say(msg, color)
        else
          @shell.say(msg, color, newline)
        end
      end

      def tell_err(message, color = nil, newline = nil)
        return if @shell.send(:stderr).closed?

        newline ||= message.to_s !~ /( |\t)\Z/
        message = word_wrap(message) if newline.is_a?(Hash) && newline[:wrap]

        color = nil if color && !$stderr.tty?

        buffer = @shell.send(:prepare_message, message, *color)
        buffer << "\n" if newline && !message.to_s.end_with?("\n")

        @shell.send(:stderr).print(buffer)
        @shell.send(:stderr).flush
      end

      def strip_leading_spaces(text)
        spaces = text[/\A\s+/, 0]
        spaces ? text.gsub(/#{spaces}/, "") : text
      end

      def word_wrap(text, line_width = @shell.terminal_width)
        strip_leading_spaces(text).split("\n").collect do |line|
          line.length > line_width ? line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n").strip : line
        end * "\n"
      end

      def with_level(level)
        original = @level
        @level = level
        yield
      ensure
        @level = original
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  module UI
    class Silent
      attr_writer :shell

      def initialize
        @warnings = []
      end

      def add_color(string, color)
        string
      end

      def info(message, newline = nil)
      end

      def confirm(message, newline = nil)
      end

      def warn(message, newline = nil)
        @warnings |= [message]
      end

      def error(message, newline = nil)
      end

      def debug(message, newline = nil)
      end

      def debug?
        false
      end

      def quiet?
        false
      end

      def ask(message)
      end

      def yes?(msg)
        raise "Cannot ask yes? with a silent shell"
      end

      def no?
        raise "Cannot ask no? with a silent shell"
      end

      def level=(name)
      end

      def level(name = nil)
      end

      def trace(message, newline = nil, force = false)
      end

      def silence
        yield
      end

      def unprinted_warnings
        @warnings
      end
    end
  end
end
# frozen_string_literal: true

require_relative "../ui"
require "rubygems/user_interaction"

module Bundler
  module UI
    class RGProxy < ::Gem::SilentUI
      def initialize(ui)
        @ui = ui
        super()
      end

      def say(message)
        @ui && @ui.debug(message)
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  module URICredentialsFilter
    module_function

    def credential_filtered_uri(uri_to_anonymize)
      return uri_to_anonymize if uri_to_anonymize.nil?
      uri = uri_to_anonymize.dup
      if uri.is_a?(String)
        return uri if File.exist?(uri)

        require_relative "vendored_uri"
        uri = Bundler::URI(uri)
      end

      if uri.userinfo
        # oauth authentication
        if uri.password == "x-oauth-basic" || uri.password == "x"
          # URI as string does not display with password if no user is set
          oauth_designation = uri.password
          uri.user = oauth_designation
        end
        uri.password = nil
      end
      return uri.to_s if uri_to_anonymize.is_a?(String)
      uri
    rescue Bundler::URI::InvalidURIError # uri is not canonical uri scheme
      uri
    end

    def credential_filtered_string(str_to_filter, uri)
      return str_to_filter if uri.nil? || str_to_filter.nil?
      str_with_no_credentials = str_to_filter.dup
      anonymous_uri_str = credential_filtered_uri(uri).to_s
      uri_str = uri.to_s
      if anonymous_uri_str != uri_str
        str_with_no_credentials = str_with_no_credentials.gsub(uri_str, anonymous_uri_str)
      end
      str_with_no_credentials
    end
  end
end
# frozen_string_literal: true

begin
  require "rubygems/deprecate"
rescue LoadError
  # it's fine if it doesn't exist on the current RubyGems...
  nil
end

module Bundler
  # If Bundler::Deprecate is an autoload constant, we need to define it
  if defined?(Bundler::Deprecate) && !autoload?(:Deprecate)
    # nothing to do!
  elsif defined? ::Deprecate
    Deprecate = ::Deprecate
  elsif defined? Gem::Deprecate
    Deprecate = Gem::Deprecate
  else
    class Deprecate
    end
  end

  unless Deprecate.respond_to?(:skip_during)
    def Deprecate.skip_during
      original = skip
      self.skip = true
      yield
    ensure
      self.skip = original
    end
  end

  unless Deprecate.respond_to?(:skip)
    def Deprecate.skip
      @skip ||= false
    end
  end

  unless Deprecate.respond_to?(:skip=)
    def Deprecate.skip=(skip)
      @skip = skip
    end
  end
end
# frozen_string_literal: true

require "rubygems/installer"

module Bundler
  class RubyGemsGemInstaller < Gem::Installer
    def check_executable_overwrite(filename)
      # Bundler needs to install gems regardless of binstub overwriting
    end

    def install
      pre_install_checks

      run_pre_install_hooks

      spec.loaded_from = spec_file

      # Completely remove any previous gem files
      strict_rm_rf gem_dir
      strict_rm_rf spec.extension_dir

      SharedHelpers.filesystem_access(gem_dir, :create) do
        FileUtils.mkdir_p gem_dir, :mode => 0o755
      end

      extract_files

      build_extensions
      write_build_info_file
      run_post_build_hooks

      generate_bin
      generate_plugins

      write_spec

      SharedHelpers.filesystem_access("#{gem_home}/cache", :write) do
        write_cache_file
      end

      say spec.post_install_message unless spec.post_install_message.nil?

      run_post_install_hooks

      spec
    end

    def generate_plugins
      return unless Gem::Installer.instance_methods(false).include?(:generate_plugins)

      latest = Gem::Specification.stubs_for(spec.name).first
      return if latest && latest.version > spec.version

      ensure_writable_dir @plugins_dir

      if spec.plugins.empty?
        remove_plugins_for(spec, @plugins_dir)
      else
        regenerate_plugins_for(spec, @plugins_dir)
      end
    end

    def pre_install_checks
      super && validate_bundler_checksum(options[:bundler_expected_checksum])
    end

    def build_extensions
      extension_cache_path = options[:bundler_extension_cache_path]
      unless extension_cache_path && extension_dir = spec.extension_dir
        require "shellwords" # compensate missing require in rubygems before version 3.2.25
        return super
      end

      extension_dir = Pathname.new(extension_dir)
      build_complete = SharedHelpers.filesystem_access(extension_cache_path.join("gem.build_complete"), :read, &:file?)
      if build_complete && !options[:force]
        SharedHelpers.filesystem_access(extension_dir.parent, &:mkpath)
        SharedHelpers.filesystem_access(extension_cache_path) do
          FileUtils.cp_r extension_cache_path, spec.extension_dir
        end
      else
        require "shellwords" # compensate missing require in rubygems before version 3.2.25
        super
        if extension_dir.directory? # not made for gems without extensions
          SharedHelpers.filesystem_access(extension_cache_path.parent, &:mkpath)
          SharedHelpers.filesystem_access(extension_cache_path) do
            FileUtils.cp_r extension_dir, extension_cache_path
          end
        end
      end
    end

    private

    def strict_rm_rf(dir)
      # FileUtils.rm_rf should probably rise in case of permission issues like
      # `rm -rf` does. However, it fails to delete the folder silently due to
      # https://github.com/ruby/fileutils/issues/57. It should probably be fixed
      # inside `fileutils` but for now I`m checking whether the folder was
      # removed after it completes, and raising otherwise.
      FileUtils.rm_rf dir

      raise PermissionError.new(dir, :delete) if File.directory?(dir)
    end

    def validate_bundler_checksum(checksum)
      return true if Bundler.settings[:disable_checksum_validation]
      return true unless checksum
      return true unless source = @package.instance_variable_get(:@gem)
      return true unless source.respond_to?(:with_read_io)
      digest = source.with_read_io do |io|
        digest = SharedHelpers.digest(:SHA256).new
        digest << io.read(16_384) until io.eof?
        io.rewind
        send(checksum_type(checksum), digest)
      end
      unless digest == checksum
        raise SecurityError, <<-MESSAGE
          Bundler cannot continue installing #{spec.name} (#{spec.version}).
          The checksum for the downloaded `#{spec.full_name}.gem` does not match \
          the checksum given by the server. This means the contents of the downloaded \
          gem is different from what was uploaded to the server, and could be a potential security issue.

          To resolve this issue:
          1. delete the downloaded gem located at: `#{spec.gem_dir}/#{spec.full_name}.gem`
          2. run `bundle install`

          If you wish to continue installing the downloaded gem, and are certain it does not pose a \
          security issue despite the mismatching checksum, do the following:
          1. run `bundle config set --local disable_checksum_validation true` to turn off checksum verification
          2. run `bundle install`

          (More info: The expected SHA256 checksum was #{checksum.inspect}, but the \
          checksum for the downloaded gem was #{digest.inspect}.)
          MESSAGE
      end
      true
    end

    def checksum_type(checksum)
      case checksum.length
      when 64 then :hexdigest!
      when 44 then :base64digest!
      else raise InstallError, "The given checksum for #{spec.full_name} (#{checksum.inspect}) is not a valid SHA256 hexdigest nor base64digest"
      end
    end

    def hexdigest!(digest)
      digest.hexdigest!
    end

    def base64digest!(digest)
      if digest.respond_to?(:base64digest!)
        digest.base64digest!
      else
        [digest.digest!].pack("m0")
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class Injector
    INJECTED_GEMS = "injected gems".freeze

    def self.inject(new_deps, options = {})
      injector = new(new_deps, options)
      injector.inject(Bundler.default_gemfile, Bundler.default_lockfile)
    end

    def self.remove(gems, options = {})
      injector = new(gems, options)
      injector.remove(Bundler.default_gemfile, Bundler.default_lockfile)
    end

    def initialize(deps, options = {})
      @deps = deps
      @options = options
    end

    # @param [Pathname] gemfile_path The Gemfile in which to inject the new dependency.
    # @param [Pathname] lockfile_path The lockfile in which to inject the new dependency.
    # @return [Array]
    def inject(gemfile_path, lockfile_path)
      if Bundler.frozen_bundle?
        # ensure the lock and Gemfile are synced
        Bundler.definition.ensure_equivalent_gemfile_and_lockfile(true)
      end

      # temporarily unfreeze
      Bundler.settings.temporary(:deployment => false, :frozen => false) do
        # evaluate the Gemfile we have now
        builder = Dsl.new
        builder.eval_gemfile(gemfile_path)

        # don't inject any gems that are already in the Gemfile
        @deps -= builder.dependencies

        # add new deps to the end of the in-memory Gemfile
        # Set conservative versioning to false because
        # we want to let the resolver resolve the version first
        builder.eval_gemfile(INJECTED_GEMS, build_gem_lines(false)) if @deps.any?

        # resolve to see if the new deps broke anything
        @definition = builder.to_definition(lockfile_path, {})
        @definition.resolve_remotely!

        # since nothing broke, we can add those gems to the gemfile
        append_to(gemfile_path, build_gem_lines(@options[:conservative_versioning])) if @deps.any?

        # since we resolved successfully, write out the lockfile
        @definition.lock(Bundler.default_lockfile)

        # invalidate the cached Bundler.definition
        Bundler.reset_paths!

        # return an array of the deps that we added
        @deps
      end
    end

    # @param [Pathname] gemfile_path The Gemfile from which to remove dependencies.
    # @param [Pathname] lockfile_path The lockfile from which to remove dependencies.
    # @return [Array]
    def remove(gemfile_path, lockfile_path)
      # remove gems from each gemfiles we have
      Bundler.definition.gemfiles.each do |path|
        deps = remove_deps(path)

        show_warning("No gems were removed from the gemfile.") if deps.empty?

        deps.each {|dep| Bundler.ui.confirm "#{SharedHelpers.pretty_dependency(dep, false)} was removed." }
      end
    end

    private

    def conservative_version(spec)
      version = spec.version
      return ">= 0" if version.nil?
      segments = version.segments
      seg_end_index = version >= Gem::Version.new("1.0") ? 1 : 2

      prerelease_suffix = version.to_s.gsub(version.release.to_s, "") if version.prerelease?
      "#{version_prefix}#{segments[0..seg_end_index].join(".")}#{prerelease_suffix}"
    end

    def version_prefix
      if @options[:strict]
        "= "
      elsif @options[:optimistic]
        ">= "
      else
        "~> "
      end
    end

    def build_gem_lines(conservative_versioning)
      @deps.map do |d|
        name = d.name.dump

        requirement = if conservative_versioning
          ", \"#{conservative_version(@definition.specs[d.name][0])}\""
        else
          ", #{d.requirement.as_list.map(&:dump).join(", ")}"
        end

        if d.groups != Array(:default)
          group = d.groups.size == 1 ? ", :group => #{d.groups.first.inspect}" : ", :groups => #{d.groups.inspect}"
        end

        source = ", :source => \"#{d.source}\"" unless d.source.nil?
        git = ", :git => \"#{d.git}\"" unless d.git.nil?
        branch = ", :branch => \"#{d.branch}\"" unless d.branch.nil?

        %(gem #{name}#{requirement}#{group}#{source}#{git}#{branch})
      end.join("\n")
    end

    def append_to(gemfile_path, new_gem_lines)
      gemfile_path.open("a") do |f|
        f.puts
        f.puts new_gem_lines
      end
    end

    # evaluates a gemfile to remove the specified gem
    # from it.
    def remove_deps(gemfile_path)
      initial_gemfile = File.readlines(gemfile_path)

      Bundler.ui.info "Removing gems from #{gemfile_path}"

      # evaluate the Gemfile we have
      builder = Dsl.new
      builder.eval_gemfile(gemfile_path)

      removed_deps = remove_gems_from_dependencies(builder, @deps, gemfile_path)

      # abort the operation if no gems were removed
      # no need to operate on gemfile further
      return [] if removed_deps.empty?

      cleaned_gemfile = remove_gems_from_gemfile(@deps, gemfile_path)

      SharedHelpers.write_to_gemfile(gemfile_path, cleaned_gemfile)

      # check for errors
      # including extra gems being removed
      # or some gems not being removed
      # and return the actual removed deps
      cross_check_for_errors(gemfile_path, builder.dependencies, removed_deps, initial_gemfile)
    end

    # @param [Dsl]      builder Dsl object of current Gemfile.
    # @param [Array]    gems Array of names of gems to be removed.
    # @param [Pathname] gemfile_path Path of the Gemfile.
    # @return [Array]   Array of removed dependencies.
    def remove_gems_from_dependencies(builder, gems, gemfile_path)
      removed_deps = []

      gems.each do |gem_name|
        deleted_dep = builder.dependencies.find {|d| d.name == gem_name }

        if deleted_dep.nil?
          raise GemfileError, "`#{gem_name}` is not specified in #{gemfile_path} so it could not be removed."
        end

        builder.dependencies.delete(deleted_dep)

        removed_deps << deleted_dep
      end

      removed_deps
    end

    # @param [Array] gems            Array of names of gems to be removed.
    # @param [Pathname] gemfile_path The Gemfile from which to remove dependencies.
    def remove_gems_from_gemfile(gems, gemfile_path)
      patterns = /gem\s+(['"])#{Regexp.union(gems)}\1|gem\s*\((['"])#{Regexp.union(gems)}\2\)/
      new_gemfile = []
      multiline_removal = false
      File.readlines(gemfile_path).each do |line|
        match_data = line.match(patterns)
        if match_data && is_not_within_comment?(line, match_data)
          multiline_removal = line.rstrip.end_with?(",")
          # skip lines which match the regex
          next
        end

        # skip followup lines until line does not end with ','
        new_gemfile << line unless multiline_removal
        multiline_removal = line.rstrip.end_with?(",") if multiline_removal
      end

      # remove line \n and append them with other strings
      new_gemfile.each_with_index do |_line, index|
        if new_gemfile[index + 1] == "\n"
          new_gemfile[index] += new_gemfile[index + 1]
          new_gemfile.delete_at(index + 1)
        end
      end

      %w[group source env install_if].each {|block| remove_nested_blocks(new_gemfile, block) }

      new_gemfile.join.chomp
    end

    # @param [String] line          Individual line of gemfile content.
    # @param [MatchData] match_data Data about Regex match.
    def is_not_within_comment?(line, match_data)
      match_start_index = match_data.offset(0).first
      !line[0..match_start_index].include?("#")
    end

    # @param [Array] gemfile       Array of gemfile contents.
    # @param [String] block_name   Name of block name to look for.
    def remove_nested_blocks(gemfile, block_name)
      nested_blocks = 0

      # count number of nested blocks
      gemfile.each_with_index {|line, index| nested_blocks += 1 if !gemfile[index + 1].nil? && gemfile[index + 1].include?(block_name) && line.include?(block_name) }

      while nested_blocks >= 0
        nested_blocks -= 1

        gemfile.each_with_index do |line, index|
          next unless !line.nil? && line.strip.start_with?(block_name)
          if gemfile[index + 1] =~ /^\s*end\s*$/
            gemfile[index] = nil
            gemfile[index + 1] = nil
          end
        end

        gemfile.compact!
      end
    end

    # @param [Pathname] gemfile_path   The Gemfile from which to remove dependencies.
    # @param [Array] original_deps     Array of original dependencies.
    # @param [Array] removed_deps      Array of removed dependencies.
    # @param [Array] initial_gemfile   Contents of original Gemfile before any operation.
    def cross_check_for_errors(gemfile_path, original_deps, removed_deps, initial_gemfile)
      # evaluate the new gemfile to look for any failure cases
      builder = Dsl.new
      builder.eval_gemfile(gemfile_path)

      # record gems which were removed but not requested
      extra_removed_gems = original_deps - builder.dependencies

      # if some extra gems were removed then raise error
      # and revert Gemfile to original
      unless extra_removed_gems.empty?
        SharedHelpers.write_to_gemfile(gemfile_path, initial_gemfile.join)

        raise InvalidOption, "Gems could not be removed. #{extra_removed_gems.join(", ")} would also have been removed. Bundler cannot continue."
      end

      # record gems which could not be removed due to some reasons
      errored_deps = builder.dependencies.select {|d| d.gemfile == gemfile_path } & removed_deps.select {|d| d.gemfile == gemfile_path }

      show_warning "#{errored_deps.map(&:name).join(", ")} could not be removed." unless errored_deps.empty?

      # return actual removed dependencies
      removed_deps - errored_deps
    end

    def show_warning(message)
      Bundler.ui.info Bundler.ui.add_color(message, :yellow)
    end
  end
end
# frozen_string_literal: true

require_relative "vendored_thor"

module Bundler
  class CLI < Thor
    require_relative "cli/common"

    package_name "Bundler"

    AUTO_INSTALL_CMDS = %w[show binstubs outdated exec open console licenses clean].freeze
    PARSEABLE_COMMANDS = %w[check config help exec platform show version].freeze

    COMMAND_ALIASES = {
      "check" => "c",
      "install" => "i",
      "plugin" => "",
      "list" => "ls",
      "exec" => ["e", "ex", "exe"],
      "cache" => ["package", "pack"],
      "version" => ["-v", "--version"],
    }.freeze

    def self.start(*)
      super
    ensure
      Bundler::SharedHelpers.print_major_deprecations!
    end

    def self.dispatch(*)
      super do |i|
        i.send(:print_command)
        i.send(:warn_on_outdated_bundler)
      end
    end

    def self.all_aliases
      @all_aliases ||= begin
                         command_aliases = {}

                         COMMAND_ALIASES.each do |name, aliases|
                           Array(aliases).each do |one_alias|
                             command_aliases[one_alias] = name
                           end
                         end

                         command_aliases
                       end
    end

    def self.aliases_for(command_name)
      COMMAND_ALIASES.select {|k, _| k == command_name }.invert
    end

    def initialize(*args)
      super

      custom_gemfile = options[:gemfile] || Bundler.settings[:gemfile]
      if custom_gemfile && !custom_gemfile.empty?
        Bundler::SharedHelpers.set_env "BUNDLE_GEMFILE", File.expand_path(custom_gemfile)
        Bundler.reset_settings_and_root!
      end

      Bundler.settings.set_command_option_if_given :retry, options[:retry]

      current_cmd = args.last[:current_command].name
      auto_install if AUTO_INSTALL_CMDS.include?(current_cmd)
    rescue UnknownArgumentError => e
      raise InvalidOption, e.message
    ensure
      self.options ||= {}
      unprinted_warnings = Bundler.ui.unprinted_warnings
      Bundler.ui = UI::Shell.new(options)
      Bundler.ui.level = "debug" if options["verbose"]
      unprinted_warnings.each {|w| Bundler.ui.warn(w) }
    end

    check_unknown_options!(:except => [:config, :exec])
    stop_on_unknown_option! :exec

    desc "cli_help", "Prints a summary of bundler commands", :hide => true
    def cli_help
      version
      Bundler.ui.info "\n"

      primary_commands = ["install", "update", "cache", "exec", "config", "help"]

      list = self.class.printable_commands(true)
      by_name = list.group_by {|name, _message| name.match(/^bundle (\w+)/)[1] }
      utilities = by_name.keys.sort - primary_commands
      primary_commands.map! {|name| (by_name[name] || raise("no primary command #{name}")).first }
      utilities.map! {|name| by_name[name].first }

      shell.say "Bundler commands:\n\n"

      shell.say "  Primary commands:\n"
      shell.print_table(primary_commands, :indent => 4, :truncate => true)
      shell.say
      shell.say "  Utilities:\n"
      shell.print_table(utilities, :indent => 4, :truncate => true)
      shell.say
      self.class.send(:class_options_help, shell)
    end
    default_task(Bundler.feature_flag.default_cli_command)

    class_option "no-color", :type => :boolean, :desc => "Disable colorization in output"
    class_option "retry",    :type => :numeric, :aliases => "-r", :banner => "NUM",
                             :desc => "Specify the number of times you wish to attempt network commands"
    class_option "verbose", :type => :boolean, :desc => "Enable verbose output mode", :aliases => "-V"

    def help(cli = nil)
      case cli
      when "gemfile" then command = "gemfile"
      when nil       then command = "bundle"
      else command = "bundle-#{cli}"
      end

      man_path = File.expand_path("man", __dir__)
      man_pages = Hash[Dir.glob(File.join(man_path, "**", "*")).grep(/.*\.\d*\Z/).collect do |f|
        [File.basename(f, ".*"), f]
      end]

      if man_pages.include?(command)
        man_page = man_pages[command]
        if Bundler.which("man") && man_path !~ %r{^file:/.+!/META-INF/jruby.home/.+}
          Kernel.exec "man #{man_page}"
        else
          puts File.read("#{man_path}/#{File.basename(man_page)}.ronn")
        end
      elsif command_path = Bundler.which("bundler-#{cli}")
        Kernel.exec(command_path, "--help")
      else
        super
      end
    end

    def self.handle_no_command_error(command, has_namespace = $thor_runner)
      if Bundler.feature_flag.plugins? && Bundler::Plugin.command?(command)
        return Bundler::Plugin.exec_command(command, ARGV[1..-1])
      end

      return super unless command_path = Bundler.which("bundler-#{command}")

      Kernel.exec(command_path, *ARGV[1..-1])
    end

    desc "init [OPTIONS]", "Generates a Gemfile into the current working directory"
    long_desc <<-D
      Init generates a default Gemfile in the current working directory. When adding a
      Gemfile to a gem with a gemspec, the --gemspec option will automatically add each
      dependency listed in the gemspec file to the newly created Gemfile.
    D
    method_option "gemspec", :type => :string, :banner => "Use the specified .gemspec to create the Gemfile"
    def init
      require_relative "cli/init"
      Init.new(options.dup).run
    end

    desc "check [OPTIONS]", "Checks if the dependencies listed in Gemfile are satisfied by currently installed gems"
    long_desc <<-D
      Check searches the local machine for each of the gems requested in the Gemfile. If
      all gems are found, Bundler prints a success message and exits with a status of 0.
      If not, the first missing gem is listed and Bundler exits status 1.
    D
    method_option "dry-run", :type => :boolean, :default => false, :banner =>
      "Lock the Gemfile"
    method_option "gemfile", :type => :string, :banner =>
      "Use the specified gemfile instead of Gemfile"
    method_option "path", :type => :string, :banner =>
      "Specify a different path than the system default ($BUNDLE_PATH or $GEM_HOME).#{" Bundler will remember this value for future installs on this machine" unless Bundler.feature_flag.forget_cli_options?}"
    def check
      remembered_flag_deprecation("path")

      require_relative "cli/check"
      Check.new(options).run
    end

    map aliases_for("check")

    desc "remove [GEM [GEM ...]]", "Removes gems from the Gemfile"
    long_desc <<-D
      Removes the given gems from the Gemfile while ensuring that the resulting Gemfile is still valid. If the gem is not found, Bundler prints a error message and if gem could not be removed due to any reason Bundler will display a warning.
    D
    method_option "install", :type => :boolean, :banner =>
      "Runs 'bundle install' after removing the gems from the Gemfile"
    def remove(*gems)
      SharedHelpers.major_deprecation(2, "The `--install` flag has been deprecated. `bundle install` is triggered by default.") if ARGV.include?("--install")
      require_relative "cli/remove"
      Remove.new(gems, options).run
    end

    desc "install [OPTIONS]", "Install the current environment to the system"
    long_desc <<-D
      Install will install all of the gems in the current bundle, making them available
      for use. In a freshly checked out repository, this command will give you the same
      gem versions as the last person who updated the Gemfile and ran `bundle update`.

      Passing [DIR] to install (e.g. vendor) will cause the unpacked gems to be installed
      into the [DIR] directory rather than into system gems.

      If the bundle has already been installed, bundler will tell you so and then exit.
    D
    method_option "binstubs", :type => :string, :lazy_default => "bin", :banner =>
      "Generate bin stubs for bundled gems to ./bin"
    method_option "clean", :type => :boolean, :banner =>
      "Run bundle clean automatically after install"
    method_option "deployment", :type => :boolean, :banner =>
      "Install using defaults tuned for deployment environments"
    method_option "frozen", :type => :boolean, :banner =>
      "Do not allow the Gemfile.lock to be updated after this install"
    method_option "full-index", :type => :boolean, :banner =>
      "Fall back to using the single-file index of all gems"
    method_option "gemfile", :type => :string, :banner =>
      "Use the specified gemfile instead of Gemfile"
    method_option "jobs", :aliases => "-j", :type => :numeric, :banner =>
      "Specify the number of jobs to run in parallel"
    method_option "local", :type => :boolean, :banner =>
      "Do not attempt to fetch gems remotely and use the gem cache instead"
    method_option "no-cache", :type => :boolean, :banner =>
      "Don't update the existing gem cache."
    method_option "redownload", :type => :boolean, :aliases => "--force", :banner =>
      "Force downloading every gem."
    method_option "no-prune", :type => :boolean, :banner =>
      "Don't remove stale gems from the cache."
    method_option "path", :type => :string, :banner =>
      "Specify a different path than the system default ($BUNDLE_PATH or $GEM_HOME).#{" Bundler will remember this value for future installs on this machine" unless Bundler.feature_flag.forget_cli_options?}"
    method_option "quiet", :type => :boolean, :banner =>
      "Only output warnings and errors."
    method_option "shebang", :type => :string, :banner =>
      "Specify a different shebang executable name than the default (usually 'ruby')"
    method_option "standalone", :type => :array, :lazy_default => [], :banner =>
      "Make a bundle that can work without the Bundler runtime"
    method_option "system", :type => :boolean, :banner =>
      "Install to the system location ($BUNDLE_PATH or $GEM_HOME) even if the bundle was previously installed somewhere else for this application"
    method_option "trust-policy", :alias => "P", :type => :string, :banner =>
      "Gem trust policy (like gem install -P). Must be one of " +
        Bundler.rubygems.security_policy_keys.join("|")
    method_option "without", :type => :array, :banner =>
      "Exclude gems that are part of the specified named group."
    method_option "with", :type => :array, :banner =>
      "Include gems that are part of the specified named group."
    def install
      SharedHelpers.major_deprecation(2, "The `--force` option has been renamed to `--redownload`") if ARGV.include?("--force")

      %w[clean deployment frozen no-prune path shebang system without with].each do |option|
        remembered_flag_deprecation(option)
      end

      remembered_negative_flag_deprecation("no-deployment")

      require_relative "cli/install"
      Bundler.settings.temporary(:no_install => false) do
        Install.new(options.dup).run
      end
    end

    map aliases_for("install")

    desc "update [OPTIONS]", "Update the current environment"
    long_desc <<-D
      Update will install the newest versions of the gems listed in the Gemfile. Use
      update when you have changed the Gemfile, or if you want to get the newest
      possible versions of the gems in the bundle.
    D
    method_option "full-index", :type => :boolean, :banner =>
      "Fall back to using the single-file index of all gems"
    method_option "gemfile", :type => :string, :banner =>
      "Use the specified gemfile instead of Gemfile"
    method_option "group", :aliases => "-g", :type => :array, :banner =>
      "Update a specific group"
    method_option "jobs", :aliases => "-j", :type => :numeric, :banner =>
      "Specify the number of jobs to run in parallel"
    method_option "local", :type => :boolean, :banner =>
      "Do not attempt to fetch gems remotely and use the gem cache instead"
    method_option "quiet", :type => :boolean, :banner =>
      "Only output warnings and errors."
    method_option "source", :type => :array, :banner =>
      "Update a specific source (and all gems associated with it)"
    method_option "redownload", :type => :boolean, :aliases => "--force", :banner =>
      "Force downloading every gem."
    method_option "ruby", :type => :boolean, :banner =>
      "Update ruby specified in Gemfile.lock"
    method_option "bundler", :type => :string, :lazy_default => "> 0.a", :banner =>
      "Update the locked version of bundler"
    method_option "patch", :type => :boolean, :banner =>
      "Prefer updating only to next patch version"
    method_option "minor", :type => :boolean, :banner =>
      "Prefer updating only to next minor version"
    method_option "major", :type => :boolean, :banner =>
      "Prefer updating to next major version (default)"
    method_option "strict", :type => :boolean, :banner =>
      "Do not allow any gem to be updated past latest --patch | --minor | --major"
    method_option "conservative", :type => :boolean, :banner =>
      "Use bundle install conservative update behavior and do not allow shared dependencies to be updated."
    method_option "all", :type => :boolean, :banner =>
      "Update everything."
    def update(*gems)
      SharedHelpers.major_deprecation(2, "The `--force` option has been renamed to `--redownload`") if ARGV.include?("--force")
      require_relative "cli/update"
      Bundler.settings.temporary(:no_install => false) do
        Update.new(options, gems).run
      end
    end

    desc "show GEM [OPTIONS]", "Shows all gems that are part of the bundle, or the path to a given gem"
    long_desc <<-D
      Show lists the names and versions of all gems that are required by your Gemfile.
      Calling show with [GEM] will list the exact location of that gem on your machine.
    D
    method_option "paths", :type => :boolean,
                           :banner => "List the paths of all gems that are required by your Gemfile."
    method_option "outdated", :type => :boolean,
                              :banner => "Show verbose output including whether gems are outdated."
    def show(gem_name = nil)
      SharedHelpers.major_deprecation(2, "the `--outdated` flag to `bundle show` was undocumented and will be removed without replacement") if ARGV.include?("--outdated")
      require_relative "cli/show"
      Show.new(options, gem_name).run
    end

    desc "list", "List all gems in the bundle"
    method_option "name-only", :type => :boolean, :banner => "print only the gem names"
    method_option "only-group", :type => :array, :default => [], :banner => "print gems from a given set of groups"
    method_option "without-group", :type => :array, :default => [], :banner => "print all gems except from a given set of groups"
    method_option "paths", :type => :boolean, :banner => "print the path to each gem in the bundle"
    def list
      require_relative "cli/list"
      List.new(options).run
    end

    map aliases_for("list")

    desc "info GEM [OPTIONS]", "Show information for the given gem"
    method_option "path", :type => :boolean, :banner => "Print full path to gem"
    method_option "version", :type => :boolean, :banner => "Print gem version"
    def info(gem_name)
      require_relative "cli/info"
      Info.new(options, gem_name).run
    end

    desc "binstubs GEM [OPTIONS]", "Install the binstubs of the listed gem"
    long_desc <<-D
      Generate binstubs for executables in [GEM]. Binstubs are put into bin,
      or the --binstubs directory if one has been set. Calling binstubs with [GEM [GEM]]
      will create binstubs for all given gems.
    D
    method_option "force", :type => :boolean, :default => false, :banner =>
      "Overwrite existing binstubs if they exist"
    method_option "path", :type => :string, :lazy_default => "bin", :banner =>
      "Binstub destination directory (default bin)"
    method_option "shebang", :type => :string, :banner =>
      "Specify a different shebang executable name than the default (usually 'ruby')"
    method_option "standalone", :type => :boolean, :banner =>
      "Make binstubs that can work without the Bundler runtime"
    method_option "all", :type => :boolean, :banner =>
      "Install binstubs for all gems"
    method_option "all-platforms", :type => :boolean, :default => false, :banner =>
      "Install binstubs for all platforms"
    def binstubs(*gems)
      require_relative "cli/binstubs"
      Binstubs.new(options, gems).run
    end

    desc "add GEM VERSION", "Add gem to Gemfile and run bundle install"
    long_desc <<-D
      Adds the specified gem to Gemfile (if valid) and run 'bundle install' in one step.
    D
    method_option "version", :aliases => "-v", :type => :string
    method_option "group", :aliases => "-g", :type => :string
    method_option "source", :aliases => "-s", :type => :string
    method_option "git", :type => :string
    method_option "branch", :type => :string
    method_option "skip-install", :type => :boolean, :banner =>
      "Adds gem to the Gemfile but does not install it"
    method_option "optimistic", :type => :boolean, :banner => "Adds optimistic declaration of version to gem"
    method_option "strict", :type => :boolean, :banner => "Adds strict declaration of version to gem"
    def add(*gems)
      require_relative "cli/add"
      Add.new(options.dup, gems).run
    end

    desc "outdated GEM [OPTIONS]", "List installed gems with newer versions available"
    long_desc <<-D
      Outdated lists the names and versions of gems that have a newer version available
      in the given source. Calling outdated with [GEM [GEM]] will only check for newer
      versions of the given gems. Prerelease gems are ignored by default. If your gems
      are up to date, Bundler will exit with a status of 0. Otherwise, it will exit 1.

      For more information on patch level options (--major, --minor, --patch,
      --update-strict) see documentation on the same options on the update command.
    D
    method_option "group", :type => :string, :banner => "List gems from a specific group"
    method_option "groups", :type => :boolean, :banner => "List gems organized by groups"
    method_option "local", :type => :boolean, :banner =>
      "Do not attempt to fetch gems remotely and use the gem cache instead"
    method_option "pre", :type => :boolean, :banner => "Check for newer pre-release gems"
    method_option "source", :type => :array, :banner => "Check against a specific source"
    strict_is_update = Bundler.feature_flag.forget_cli_options?
    method_option "filter-strict", :type => :boolean, :aliases => strict_is_update ? [] : %w[--strict], :banner =>
      "Only list newer versions allowed by your Gemfile requirements"
    method_option "update-strict", :type => :boolean, :aliases => strict_is_update ? %w[--strict] : [], :banner =>
      "Strict conservative resolution, do not allow any gem to be updated past latest --patch | --minor | --major"
    method_option "minor", :type => :boolean, :banner => "Prefer updating only to next minor version"
    method_option "major", :type => :boolean, :banner => "Prefer updating to next major version (default)"
    method_option "patch", :type => :boolean, :banner => "Prefer updating only to next patch version"
    method_option "filter-major", :type => :boolean, :banner => "Only list major newer versions"
    method_option "filter-minor", :type => :boolean, :banner => "Only list minor newer versions"
    method_option "filter-patch", :type => :boolean, :banner => "Only list patch newer versions"
    method_option "parseable", :aliases => "--porcelain", :type => :boolean, :banner =>
      "Use minimal formatting for more parseable output"
    method_option "only-explicit", :type => :boolean, :banner =>
      "Only list gems specified in your Gemfile, not their dependencies"
    def outdated(*gems)
      require_relative "cli/outdated"
      Outdated.new(options, gems).run
    end

    desc "fund [OPTIONS]", "Lists information about gems seeking funding assistance"
    method_option "group", :aliases => "-g", :type => :array, :banner =>
      "Fetch funding information for a specific group"
    def fund
      require_relative "cli/fund"
      Fund.new(options).run
    end

    desc "cache [OPTIONS]", "Locks and then caches all of the gems into vendor/cache"
    method_option "all",  :type => :boolean,
                          :default => Bundler.feature_flag.cache_all?,
                          :banner => "Include all sources (including path and git)."
    method_option "all-platforms", :type => :boolean, :banner => "Include gems for all platforms present in the lockfile, not only the current one"
    method_option "cache-path", :type => :string, :banner =>
      "Specify a different cache path than the default (vendor/cache)."
    method_option "gemfile", :type => :string, :banner => "Use the specified gemfile instead of Gemfile"
    method_option "no-install", :type => :boolean, :banner => "Don't install the gems, only update the cache."
    method_option "no-prune", :type => :boolean, :banner => "Don't remove stale gems from the cache."
    method_option "path", :type => :string, :banner =>
      "Specify a different path than the system default ($BUNDLE_PATH or $GEM_HOME).#{" Bundler will remember this value for future installs on this machine" unless Bundler.feature_flag.forget_cli_options?}"
    method_option "quiet", :type => :boolean, :banner => "Only output warnings and errors."
    method_option "frozen", :type => :boolean, :banner =>
      "Do not allow the Gemfile.lock to be updated after this bundle cache operation's install"
    long_desc <<-D
      The cache command will copy the .gem files for every gem in the bundle into the
      directory ./vendor/cache. If you then check that directory into your source
      control repository, others who check out your source will be able to install the
      bundle without having to download any additional gems.
    D
    def cache
      SharedHelpers.major_deprecation 2,
        "The `--all` flag is deprecated because it relies on being " \
        "remembered across bundler invocations, which bundler will no longer " \
        "do in future versions. Instead please use `bundle config set cache_all true`, " \
        "and stop using this flag" if ARGV.include?("--all")

      SharedHelpers.major_deprecation 2,
        "The `--path` flag is deprecated because its semantics are unclear. " \
        "Use `bundle config cache_path` to configure the path of your cache of gems, " \
        "and `bundle config path` to configure the path where your gems are installed, " \
        "and stop using this flag" if ARGV.include?("--path")

      require_relative "cli/cache"
      Cache.new(options).run
    end

    map aliases_for("cache")

    desc "exec [OPTIONS]", "Run the command in context of the bundle"
    method_option :keep_file_descriptors, :type => :boolean, :default => true
    method_option :gemfile, :type => :string, :required => false
    long_desc <<-D
      Exec runs a command, providing it access to the gems in the bundle. While using
      bundle exec you can require and call the bundled gems as if they were installed
      into the system wide RubyGems repository.
    D
    def exec(*args)
      if ARGV.include?("--no-keep-file-descriptors")
        SharedHelpers.major_deprecation(2, "The `--no-keep-file-descriptors` has been deprecated. `bundle exec` no longer mess with your file descriptors. Close them in the exec'd script if you need to")
      end

      require_relative "cli/exec"
      Exec.new(options, args).run
    end

    map aliases_for("exec")

    desc "config NAME [VALUE]", "Retrieve or set a configuration value"
    long_desc <<-D
      Retrieves or sets a configuration value. If only one parameter is provided, retrieve the value. If two parameters are provided, replace the
      existing value with the newly provided one.

      By default, setting a configuration value sets it for all projects
      on the machine.

      If a global setting is superseded by local configuration, this command
      will show the current value, as well as any superseded values and
      where they were specified.
    D
    require_relative "cli/config"
    subcommand "config", Config

    desc "open GEM", "Opens the source directory of the given bundled gem"
    def open(name)
      require_relative "cli/open"
      Open.new(options, name).run
    end

    unless Bundler.feature_flag.bundler_3_mode?
      desc "console [GROUP]", "Opens an IRB session with the bundle pre-loaded"
      def console(group = nil)
        require_relative "cli/console"
        Console.new(options, group).run
      end
    end

    desc "version", "Prints the bundler's version information"
    def version
      cli_help = current_command.name == "cli_help"
      if cli_help || ARGV.include?("version")
        build_info = " (#{BuildMetadata.built_at} commit #{BuildMetadata.git_commit_sha})"
      end

      if !cli_help && Bundler.feature_flag.print_only_version_number?
        Bundler.ui.info "#{Bundler::VERSION}#{build_info}"
      else
        Bundler.ui.info "Bundler version #{Bundler::VERSION}#{build_info}"
      end
    end

    map aliases_for("version")

    desc "licenses", "Prints the license of all gems in the bundle"
    def licenses
      Bundler.load.specs.sort_by {|s| s.license.to_s }.reverse_each do |s|
        gem_name = s.name
        license  = s.license || s.licenses

        if license.empty?
          Bundler.ui.warn "#{gem_name}: Unknown"
        else
          Bundler.ui.info "#{gem_name}: #{license}"
        end
      end
    end

    unless Bundler.feature_flag.bundler_3_mode?
      desc "viz [OPTIONS]", "Generates a visual dependency graph", :hide => true
      long_desc <<-D
        Viz generates a PNG file of the current Gemfile as a dependency graph.
        Viz requires the ruby-graphviz gem (and its dependencies).
        The associated gems must also be installed via 'bundle install'.
      D
      method_option :file, :type => :string, :default => "gem_graph", :aliases => "-f", :desc => "The name to use for the generated file. see format option"
      method_option :format, :type => :string, :default => "png", :aliases => "-F", :desc => "This is output format option. Supported format is png, jpg, svg, dot ..."
      method_option :requirements, :type => :boolean, :default => false, :aliases => "-R", :desc => "Set to show the version of each required dependency."
      method_option :version, :type => :boolean, :default => false, :aliases => "-v", :desc => "Set to show each gem version."
      method_option :without, :type => :array, :default => [], :aliases => "-W", :banner => "GROUP[ GROUP...]", :desc => "Exclude gems that are part of the specified named group."
      def viz
        SharedHelpers.major_deprecation 2, "The `viz` command has been renamed to `graph` and moved to a plugin. See https://github.com/rubygems/bundler-graph"
        require_relative "cli/viz"
        Viz.new(options.dup).run
      end
    end

    old_gem = instance_method(:gem)

    desc "gem NAME [OPTIONS]", "Creates a skeleton for creating a rubygem"
    method_option :exe, :type => :boolean, :default => false, :aliases => ["--bin", "-b"], :desc => "Generate a binary executable for your library."
    method_option :coc, :type => :boolean, :desc => "Generate a code of conduct file. Set a default with `bundle config set --global gem.coc true`."
    method_option :edit, :type => :string, :aliases => "-e", :required => false, :banner => "EDITOR",
                         :lazy_default => [ENV["BUNDLER_EDITOR"], ENV["VISUAL"], ENV["EDITOR"]].find {|e| !e.nil? && !e.empty? },
                         :desc => "Open generated gemspec in the specified editor (defaults to $EDITOR or $BUNDLER_EDITOR)"
    method_option :ext, :type => :boolean, :default => false, :desc => "Generate the boilerplate for C extension code"
    method_option :git, :type => :boolean, :default => true, :desc => "Initialize a git repo inside your library."
    method_option :mit, :type => :boolean, :desc => "Generate an MIT license file. Set a default with `bundle config set --global gem.mit true`."
    method_option :rubocop, :type => :boolean, :desc => "Add rubocop to the generated Rakefile and gemspec. Set a default with `bundle config set --global gem.rubocop true`."
    method_option :changelog, :type => :boolean, :desc => "Generate changelog file. Set a default with `bundle config set --global gem.changelog true`."
    method_option :test, :type => :string, :lazy_default => Bundler.settings["gem.test"] || "", :aliases => "-t", :banner => "Use the specified test framework for your library",
                         :desc => "Generate a test directory for your library, either rspec, minitest or test-unit. Set a default with `bundle config set --global gem.test (rspec|minitest|test-unit)`."
    method_option :ci, :type => :string, :lazy_default => Bundler.settings["gem.ci"] || "",
                       :desc => "Generate CI configuration, either GitHub Actions, Travis CI, GitLab CI or CircleCI. Set a default with `bundle config set --global gem.ci (github|travis|gitlab|circle)`"
    method_option :linter, :type => :string, :lazy_default => Bundler.settings["gem.linter"] || "",
                           :desc => "Add a linter and code formatter, either RuboCop or Standard. Set a default with `bundle config set --global gem.linter (rubocop|standard)`"
    method_option :github_username, :type => :string, :default => Bundler.settings["gem.github_username"], :banner => "Set your username on GitHub", :desc => "Fill in GitHub username on README so that you don't have to do it manually. Set a default with `bundle config set --global gem.github_username <your_username>`."

    def gem(name)
    end

    commands["gem"].tap do |gem_command|
      def gem_command.run(instance, args = [])
        arity = 1 # name

        require_relative "cli/gem"
        cmd_args = args + [instance]
        cmd_args.unshift(instance.options)

        cmd = begin
          Gem.new(*cmd_args)
        rescue ArgumentError => e
          instance.class.handle_argument_error(self, e, args, arity)
        end

        cmd.run
      end
    end

    undef_method(:gem)
    define_method(:gem, old_gem)
    private :gem

    def self.source_root
      File.expand_path(File.join(File.dirname(__FILE__), "templates"))
    end

    desc "clean [OPTIONS]", "Cleans up unused gems in your bundler directory", :hide => true
    method_option "dry-run", :type => :boolean, :default => false, :banner =>
      "Only print out changes, do not clean gems"
    method_option "force", :type => :boolean, :default => false, :banner =>
      "Forces clean even if --path is not set"
    def clean
      require_relative "cli/clean"
      Clean.new(options.dup).run
    end

    desc "platform [OPTIONS]", "Displays platform compatibility information"
    method_option "ruby", :type => :boolean, :default => false, :banner =>
      "only display ruby related platform information"
    def platform
      require_relative "cli/platform"
      Platform.new(options).run
    end

    desc "inject GEM VERSION", "Add the named gem, with version requirements, to the resolved Gemfile", :hide => true
    method_option "source", :type => :string, :banner =>
     "Install gem from the given source"
    method_option "group", :type => :string, :banner =>
     "Install gem into a bundler group"
    def inject(name, version)
      SharedHelpers.major_deprecation 2, "The `inject` command has been replaced by the `add` command"
      require_relative "cli/inject"
      Inject.new(options.dup, name, version).run
    end

    desc "lock", "Creates a lockfile without installing"
    method_option "update", :type => :array, :lazy_default => true, :banner =>
      "ignore the existing lockfile, update all gems by default, or update list of given gems"
    method_option "local", :type => :boolean, :default => false, :banner =>
      "do not attempt to fetch remote gemspecs and use the local gem cache only"
    method_option "print", :type => :boolean, :default => false, :banner =>
      "print the lockfile to STDOUT instead of writing to the file system"
    method_option "gemfile", :type => :string, :banner =>
      "Use the specified gemfile instead of Gemfile"
    method_option "lockfile", :type => :string, :default => nil, :banner =>
      "the path the lockfile should be written to"
    method_option "full-index", :type => :boolean, :default => false, :banner =>
      "Fall back to using the single-file index of all gems"
    method_option "add-platform", :type => :array, :default => [], :banner =>
      "Add a new platform to the lockfile"
    method_option "remove-platform", :type => :array, :default => [], :banner =>
      "Remove a platform from the lockfile"
    method_option "patch", :type => :boolean, :banner =>
      "If updating, prefer updating only to next patch version"
    method_option "minor", :type => :boolean, :banner =>
      "If updating, prefer updating only to next minor version"
    method_option "major", :type => :boolean, :banner =>
      "If updating, prefer updating to next major version (default)"
    method_option "strict", :type => :boolean, :banner =>
      "If updating, do not allow any gem to be updated past latest --patch | --minor | --major"
    method_option "conservative", :type => :boolean, :banner =>
      "If updating, use bundle install conservative update behavior and do not allow shared dependencies to be updated"
    def lock
      require_relative "cli/lock"
      Lock.new(options).run
    end

    desc "env", "Print information about the environment Bundler is running under"
    def env
      Env.write($stdout)
    end

    desc "doctor [OPTIONS]", "Checks the bundle for common problems"
    long_desc <<-D
      Doctor scans the OS dependencies of each of the gems requested in the Gemfile. If
      missing dependencies are detected, Bundler prints them and exits status 1.
      Otherwise, Bundler prints a success message and exits with a status of 0.
    D
    method_option "gemfile", :type => :string, :banner =>
      "Use the specified gemfile instead of Gemfile"
    method_option "quiet", :type => :boolean, :banner =>
        "Only output warnings and errors."
    def doctor
      require_relative "cli/doctor"
      Doctor.new(options).run
    end

    desc "issue", "Learn how to report an issue in Bundler"
    def issue
      require_relative "cli/issue"
      Issue.new.run
    end

    desc "pristine [GEMS...]", "Restores installed gems to pristine condition"
    long_desc <<-D
      Restores installed gems to pristine condition from files located in the
      gem cache. Gems installed from a git repository will be issued `git
      checkout --force`.
    D
    def pristine(*gems)
      require_relative "cli/pristine"
      Pristine.new(gems).run
    end

    if Bundler.feature_flag.plugins?
      require_relative "cli/plugin"
      desc "plugin", "Manage the bundler plugins"
      subcommand "plugin", Plugin
    end

    # Reformat the arguments passed to bundle that include a --help flag
    # into the corresponding `bundle help #{command}` call
    def self.reformatted_help_args(args)
      bundler_commands = (COMMAND_ALIASES.keys + COMMAND_ALIASES.values).flatten

      help_flags = %w[--help -h]
      exec_commands = ["exec"] + COMMAND_ALIASES["exec"]

      help_used = args.index {|a| help_flags.include? a }
      exec_used = args.index {|a| exec_commands.include? a }

      command = args.find {|a| bundler_commands.include? a }
      command = all_aliases[command] if all_aliases[command]

      if exec_used && help_used
        if exec_used + help_used == 1
          %w[help exec]
        else
          args
        end
      elsif help_used
        args = args.dup
        args.delete_at(help_used)
        ["help", command || args].flatten.compact
      else
        args
      end
    end

    private

    # Automatically invoke `bundle install` and resume if
    # Bundler.settings[:auto_install] exists. This is set through config cmd
    # `bundle config set --global auto_install 1`.
    #
    # Note that this method `nil`s out the global Definition object, so it
    # should be called first, before you instantiate anything like an
    # `Installer` that'll keep a reference to the old one instead.
    def auto_install
      return unless Bundler.settings[:auto_install]

      begin
        Bundler.definition.specs
      rescue GemNotFound
        Bundler.ui.info "Automatically installing missing gems."
        Bundler.reset!
        invoke :install, []
        Bundler.reset!
      end
    end

    def current_command
      _, _, config = @_initializer
      config[:current_command]
    end

    def print_command
      return unless Bundler.ui.debug?
      cmd = current_command
      command_name = cmd.name
      return if PARSEABLE_COMMANDS.include?(command_name)
      command = ["bundle", command_name] + args
      options_to_print = options.dup
      options_to_print.delete_if do |k, v|
        next unless o = cmd.options[k]
        o.default == v
      end
      command << Thor::Options.to_switches(options_to_print.sort_by(&:first)).strip
      command.reject!(&:empty?)
      Bundler.ui.info "Running `#{command * " "}` with bundler #{Bundler::VERSION}"
    end

    def warn_on_outdated_bundler
      return if Bundler.settings[:disable_version_check]

      command_name = current_command.name
      return if PARSEABLE_COMMANDS.include?(command_name)

      return unless SharedHelpers.md5_available?

      latest = Fetcher::CompactIndex.
               new(nil, Source::Rubygems::Remote.new(Bundler::URI("https://rubygems.org")), nil).
               send(:compact_index_client).
               instance_variable_get(:@cache).
               dependencies("bundler").
               map {|d| Gem::Version.new(d.first) }.
               max
      return unless latest

      current = Gem::Version.new(VERSION)
      return if current >= latest
      latest_installed = Bundler.rubygems.find_name("bundler").map(&:version).max

      installation = "To install the latest version, run `gem install bundler#{" --pre" if latest.prerelease?}`"
      if latest_installed && latest_installed > current
        suggestion = "To update to the most recent installed version (#{latest_installed}), run `bundle update --bundler`"
        suggestion = "#{installation}\n#{suggestion}" if latest_installed < latest
      else
        suggestion = installation
      end

      Bundler.ui.warn "The latest bundler is #{latest}, but you are currently running #{current}.\n#{suggestion}"
    rescue RuntimeError
      nil
    end

    def remembered_negative_flag_deprecation(name)
      positive_name = name.gsub(/\Ano-/, "")
      option = current_command.options[positive_name]
      flag_name = "--no-" + option.switch_name.gsub(/\A--/, "")

      flag_deprecation(positive_name, flag_name, option)
    end

    def remembered_flag_deprecation(name)
      option = current_command.options[name]
      flag_name = option.switch_name

      flag_deprecation(name, flag_name, option)
    end

    def flag_deprecation(name, flag_name, option)
      name_index = ARGV.find {|arg| flag_name == arg.split("=")[0] }
      return unless name_index

      value = options[name]
      value = value.join(" ").to_s if option.type == :array

      Bundler::SharedHelpers.major_deprecation 2,
        "The `#{flag_name}` flag is deprecated because it relies on being " \
        "remembered across bundler invocations, which bundler will no longer " \
        "do in future versions. Instead please use `bundle config set --local #{name.tr("-", "_")} " \
        "'#{value}'`, and stop using this flag"
    end
  end
end
# frozen_string_literal: true

require_relative "shared_helpers"
Bundler::SharedHelpers.major_deprecation 2,
  "The Bundler task for Vlad"

# Vlad task for Bundler.
#
# Add "require 'bundler/vlad'" in your Vlad deploy.rb, and
# include the vlad:bundle:install task in your vlad:deploy task.
require_relative "deployment"

include Rake::DSL if defined? Rake::DSL

namespace :vlad do
  Bundler::Deployment.define_task(Rake::RemoteTask, :remote_task, :roles => :app)
end
# frozen_string_literal: true

module Bundler
  module VersionRanges
    NEq = Struct.new(:version)
    ReqR = Struct.new(:left, :right)
    class ReqR
      Endpoint = Struct.new(:version, :inclusive) do
        def <=>(other)
          if version.equal?(INFINITY)
            return 0 if other.version.equal?(INFINITY)
            return 1
          elsif other.version.equal?(INFINITY)
            return -1
          end

          comp = version <=> other.version
          return comp unless comp.zero?

          if inclusive && !other.inclusive
            1
          elsif !inclusive && other.inclusive
            -1
          else
            0
          end
        end
      end

      def to_s
        "#{left.inclusive ? "[" : "("}#{left.version}, #{right.version}#{right.inclusive ? "]" : ")"}"
      end
      INFINITY = begin
        inf = Object.new
        def inf.to_s
          "∞"
        end
        def inf.<=>(other)
          return 0 if other.equal?(self)
          1
        end
        inf.freeze
      end
      ZERO = Gem::Version.new("0.a")

      def cover?(v)
        return false if left.inclusive && left.version > v
        return false if !left.inclusive && left.version >= v

        if right.version != INFINITY
          return false if right.inclusive && right.version < v
          return false if !right.inclusive && right.version <= v
        end

        true
      end

      def empty?
        left.version == right.version && !(left.inclusive && right.inclusive)
      end

      def single?
        left.version == right.version
      end

      def <=>(other)
        return -1 if other.equal?(INFINITY)

        comp = left <=> other.left
        return comp unless comp.zero?

        right <=> other.right
      end

      UNIVERSAL = ReqR.new(ReqR::Endpoint.new(Gem::Version.new("0.a"), true), ReqR::Endpoint.new(ReqR::INFINITY, false)).freeze
    end

    def self.for_many(requirements)
      requirements = requirements.map(&:requirements).flatten(1).map {|r| r.join(" ") }
      requirements << ">= 0.a" if requirements.empty?
      requirement = Gem::Requirement.new(requirements)
      self.for(requirement)
    end

    def self.for(requirement)
      ranges = requirement.requirements.map do |op, v|
        case op
        when "=" then ReqR.new(ReqR::Endpoint.new(v, true), ReqR::Endpoint.new(v, true))
        when "!=" then NEq.new(v)
        when ">=" then ReqR.new(ReqR::Endpoint.new(v, true), ReqR::Endpoint.new(ReqR::INFINITY, false))
        when ">" then ReqR.new(ReqR::Endpoint.new(v, false), ReqR::Endpoint.new(ReqR::INFINITY, false))
        when "<" then ReqR.new(ReqR::Endpoint.new(ReqR::ZERO, true), ReqR::Endpoint.new(v, false))
        when "<=" then ReqR.new(ReqR::Endpoint.new(ReqR::ZERO, true), ReqR::Endpoint.new(v, true))
        when "~>" then ReqR.new(ReqR::Endpoint.new(v, true), ReqR::Endpoint.new(v.bump, false))
        else raise "unknown version op #{op} in requirement #{requirement}"
        end
      end.uniq
      ranges, neqs = ranges.partition {|r| !r.is_a?(NEq) }

      [ranges.sort, neqs.map(&:version)]
    end

    def self.empty?(ranges, neqs)
      !ranges.reduce(ReqR::UNIVERSAL) do |last_range, curr_range|
        next false unless last_range
        next false if curr_range.single? && neqs.include?(curr_range.left.version)
        next curr_range if last_range.right.version == ReqR::INFINITY
        case last_range.right.version <=> curr_range.left.version
        # higher
        when 1 then next ReqR.new(curr_range.left, last_range.right)
        # equal
        when 0
          if last_range.right.inclusive && curr_range.left.inclusive && !neqs.include?(curr_range.left.version)
            ReqR.new(curr_range.left, [curr_range.right, last_range.right].max)
          end
        # lower
        when -1 then next false
        end
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class FeatureFlag
    def self.settings_flag(flag, &default)
      unless Bundler::Settings::BOOL_KEYS.include?(flag.to_s)
        raise "Cannot use `#{flag}` as a settings feature flag since it isn't a bool key"
      end

      settings_method("#{flag}?", flag, &default)
    end
    private_class_method :settings_flag

    def self.settings_option(key, &default)
      settings_method(key, key, &default)
    end
    private_class_method :settings_option

    def self.settings_method(name, key, &default)
      define_method(name) do
        value = Bundler.settings[key]
        value = instance_eval(&default) if value.nil?
        value
      end
    end
    private_class_method :settings_method

    (1..10).each {|v| define_method("bundler_#{v}_mode?") { major_version >= v } }

    settings_flag(:allow_offline_install) { bundler_3_mode? }
    settings_flag(:auto_clean_without_path) { bundler_3_mode? }
    settings_flag(:cache_all) { bundler_3_mode? }
    settings_flag(:default_install_uses_path) { bundler_3_mode? }
    settings_flag(:forget_cli_options) { bundler_3_mode? }
    settings_flag(:global_gem_cache) { bundler_3_mode? }
    settings_flag(:path_relative_to_cwd) { bundler_3_mode? }
    settings_flag(:plugins) { @bundler_version >= Gem::Version.new("1.14") }
    settings_flag(:print_only_version_number) { bundler_3_mode? }
    settings_flag(:setup_makes_kernel_gem_public) { !bundler_3_mode? }
    settings_flag(:suppress_install_using_messages) { bundler_3_mode? }
    settings_flag(:update_requires_all_flag) { bundler_4_mode? }
    settings_flag(:use_gem_version_promoter_for_major_updates) { bundler_3_mode? }

    settings_option(:default_cli_command) { bundler_3_mode? ? :cli_help : :install }

    def initialize(bundler_version)
      @bundler_version = Gem::Version.create(bundler_version)
    end

    def major_version
      @bundler_version.segments.first
    end
    private :major_version
  end
end
# frozen_string_literal: true

module Bundler
  module Persistent
    module Net
      module HTTP
      end
    end
  end
end
require_relative "vendor/net-http-persistent/lib/net/http/persistent"

module Bundler
  class PersistentHTTP < Persistent::Net::HTTP::Persistent
    def connection_for(uri)
      super(uri) do |connection|
        result = yield connection
        warn_old_tls_version_rubygems_connection(uri, connection)
        result
      end
    end

    def warn_old_tls_version_rubygems_connection(uri, connection)
      return unless connection.http.use_ssl?
      return unless (uri.host || "").end_with?("rubygems.org")

      socket = connection.instance_variable_get(:@socket)
      return unless socket
      socket_io = socket.io
      return unless socket_io.respond_to?(:ssl_version)
      ssl_version = socket_io.ssl_version

      case ssl_version
      when /TLSv([\d\.]+)/
        version = Gem::Version.new($1)
        if version < Gem::Version.new("1.2")
          Bundler.ui.warn \
            "Warning: Your Ruby version is compiled against a copy of OpenSSL that is very old. " \
            "Starting in January 2018, RubyGems.org will refuse connection requests from these " \
            "very old versions of OpenSSL. If you will need to continue installing gems after " \
            "January 2018, please follow this guide to upgrade: http://ruby.to/tls-outdated.",
            :wrap => true
        end
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class Resolver
    require_relative "vendored_molinillo"
    require_relative "resolver/spec_group"

    include GemHelpers

    # Figures out the best possible configuration of gems that satisfies
    # the list of passed dependencies and any child dependencies without
    # causing any gem activation errors.
    #
    # ==== Parameters
    # *dependencies<Gem::Dependency>:: The list of dependencies to resolve
    #
    # ==== Returns
    # <GemBundle>,nil:: If the list of dependencies can be resolved, a
    #   collection of gemspecs is returned. Otherwise, nil is returned.
    def self.resolve(requirements, source_requirements = {}, base = [], gem_version_promoter = GemVersionPromoter.new, additional_base_requirements = [], platforms = nil)
      base = SpecSet.new(base) unless base.is_a?(SpecSet)
      resolver = new(source_requirements, base, gem_version_promoter, additional_base_requirements, platforms)
      result = resolver.start(requirements)
      SpecSet.new(SpecSet.new(result).for(requirements.reject{|dep| dep.name.end_with?("\0") }))
    end

    def initialize(source_requirements, base, gem_version_promoter, additional_base_requirements, platforms)
      @source_requirements = source_requirements
      @base = base
      @resolver = Molinillo::Resolver.new(self, self)
      @search_for = {}
      @base_dg = Molinillo::DependencyGraph.new
      @base.each do |ls|
        dep = Dependency.new(ls.name, ls.version)
        @base_dg.add_vertex(ls.name, DepProxy.get_proxy(dep, ls.platform), true)
      end
      additional_base_requirements.each {|d| @base_dg.add_vertex(d.name, d) }
      @platforms = platforms.reject {|p| p != Gem::Platform::RUBY && (platforms - [p]).any? {|pl| generic(pl) == p } }
      @resolving_only_for_ruby = platforms == [Gem::Platform::RUBY]
      @gem_version_promoter = gem_version_promoter
      @use_gvp = Bundler.feature_flag.use_gem_version_promoter_for_major_updates? || !@gem_version_promoter.major?
    end

    def start(requirements)
      @gem_version_promoter.prerelease_specified = @prerelease_specified = {}
      requirements.each {|dep| @prerelease_specified[dep.name] ||= dep.prerelease? }

      verify_gemfile_dependencies_are_found!(requirements)
      dg = @resolver.resolve(requirements, @base_dg)
      dg.
        map(&:payload).
        reject {|sg| sg.name.end_with?("\0") }.
        map(&:to_specs).
        flatten
    rescue Molinillo::VersionConflict => e
      message = version_conflict_message(e)
      raise VersionConflict.new(e.conflicts.keys.uniq, message)
    rescue Molinillo::CircularDependencyError => e
      names = e.dependencies.sort_by(&:name).map {|d| "gem '#{d.name}'" }
      raise CyclicDependencyError, "Your bundle requires gems that depend" \
        " on each other, creating an infinite loop. Please remove" \
        " #{names.count > 1 ? "either " : ""}#{names.join(" or ")}" \
        " and try again."
    end

    include Molinillo::UI

    # Conveys debug information to the user.
    #
    # @param [Integer] depth the current depth of the resolution process.
    # @return [void]
    def debug(depth = 0)
      return unless debug?
      debug_info = yield
      debug_info = debug_info.inspect unless debug_info.is_a?(String)
      puts debug_info.split("\n").map {|s| depth == 0 ? "BUNDLER: #{s}" : "BUNDLER(#{depth}): #{s}" }
    end

    def debug?
      return @debug_mode if defined?(@debug_mode)
      @debug_mode =
        ENV["BUNDLER_DEBUG_RESOLVER"] ||
        ENV["BUNDLER_DEBUG_RESOLVER_TREE"] ||
        ENV["DEBUG_RESOLVER"] ||
        ENV["DEBUG_RESOLVER_TREE"] ||
        false
    end

    def before_resolution
      Bundler.ui.info "Resolving dependencies...", debug?
    end

    def after_resolution
      Bundler.ui.info ""
    end

    def indicate_progress
      Bundler.ui.info ".", false unless debug?
    end

    include Molinillo::SpecificationProvider

    def dependencies_for(specification)
      specification.dependencies_for_activated_platforms
    end

    def search_for(dependency_proxy)
      platform = dependency_proxy.__platform
      dependency = dependency_proxy.dep
      name = dependency.name
      @search_for[dependency_proxy] ||= begin
        results = results_for(dependency, @base[name])

        if vertex = @base_dg.vertex_named(name)
          locked_requirement = vertex.payload.requirement
        end

        if !@prerelease_specified[name] && (!@use_gvp || locked_requirement.nil?)
          # Move prereleases to the beginning of the list, so they're considered
          # last during resolution.
          pre, results = results.partition {|spec| spec.version.prerelease? }
          results = pre + results
        end

        spec_groups = if results.any?
          nested = []
          results.each do |spec|
            version, specs = nested.last
            if version == spec.version
              specs << spec
            else
              nested << [spec.version, [spec]]
            end
          end
          nested.reduce([]) do |groups, (version, specs)|
            next groups if locked_requirement && !locked_requirement.satisfied_by?(version)

            specs_by_platform = Hash.new do |current_specs, current_platform|
              current_specs[current_platform] = select_best_platform_match(specs, current_platform)
            end

            spec_group_ruby = SpecGroup.create_for(specs_by_platform, [Gem::Platform::RUBY], Gem::Platform::RUBY)
            groups << spec_group_ruby if spec_group_ruby

            next groups if @resolving_only_for_ruby

            spec_group = SpecGroup.create_for(specs_by_platform, @platforms, platform)
            groups << spec_group if spec_group

            groups
          end
        else
          []
        end
        # GVP handles major itself, but it's still a bit risky to trust it with it
        # until we get it settled with new behavior. For 2.x it can take over all cases.
        if !@use_gvp
          spec_groups
        else
          @gem_version_promoter.sort_versions(dependency, spec_groups)
        end
      end
    end

    def index_for(dependency)
      source_for(dependency.name).specs
    end

    def source_for(name)
      @source_requirements[name] || @source_requirements[:default]
    end

    def results_for(dependency, base)
      index_for(dependency).search(dependency, base)
    end

    def name_for(dependency)
      dependency.name
    end

    def name_for_explicit_dependency_source
      Bundler.default_gemfile.basename.to_s
    rescue StandardError
      "Gemfile"
    end

    def name_for_locking_dependency_source
      Bundler.default_lockfile.basename.to_s
    rescue StandardError
      "Gemfile.lock"
    end

    def requirement_satisfied_by?(requirement, activated, spec)
      requirement.matches_spec?(spec) || spec.source.is_a?(Source::Gemspec)
    end

    def dependencies_equal?(dependencies, other_dependencies)
      dependencies.map(&:dep) == other_dependencies.map(&:dep)
    end

    def sort_dependencies(dependencies, activated, conflicts)
      dependencies.sort_by do |dependency|
        name = name_for(dependency)
        vertex = activated.vertex_named(name)
        [
          @base_dg.vertex_named(name) ? 0 : 1,
          vertex.payload ? 0 : 1,
          vertex.root? ? 0 : 1,
          amount_constrained(dependency),
          conflicts[name] ? 0 : 1,
          vertex.payload ? 0 : search_for(dependency).count,
          self.class.platform_sort_key(dependency.__platform),
        ]
      end
    end

    def self.platform_sort_key(platform)
      # Prefer specific platform to not specific platform
      return ["99-LAST", "", "", ""] if Gem::Platform::RUBY == platform
      ["00", *platform.to_a.map {|part| part || "" }]
    end

    private

    # returns an integer \in (-\infty, 0]
    # a number closer to 0 means the dependency is less constraining
    #
    # dependencies w/ 0 or 1 possibilities (ignoring version requirements)
    # are given very negative values, so they _always_ sort first,
    # before dependencies that are unconstrained
    def amount_constrained(dependency)
      @amount_constrained ||= {}
      @amount_constrained[dependency.name] ||= begin
        if (base = @base[dependency.name]) && !base.empty?
          dependency.requirement.satisfied_by?(base.first.version) ? 0 : 1
        else
          all = index_for(dependency).search(dependency.name).size

          if all <= 1
            all - 1_000_000
          else
            search = search_for(dependency)
            search = @prerelease_specified[dependency.name] ? search.count : search.count {|s| !s.version.prerelease? }
            search - all
          end
        end
      end
    end

    def verify_gemfile_dependencies_are_found!(requirements)
      requirements.each do |requirement|
        name = requirement.name
        next if name == "bundler"
        next unless search_for(requirement).empty?

        if (base = @base[name]) && !base.empty?
          version = base.first.version
          message = "You have requested:\n" \
            "  #{name} #{requirement.requirement}\n\n" \
            "The bundle currently has #{name} locked at #{version}.\n" \
            "Try running `bundle update #{name}`\n\n" \
            "If you are updating multiple gems in your Gemfile at once,\n" \
            "try passing them all to `bundle update`"
        else
          source = source_for(name)
          specs = source.specs.search(name)
          versions_with_platforms = specs.map {|s| [s.version, s.platform] }
          cache_message = begin
                              " or in gems cached in #{Bundler.settings.app_cache_path}" if Bundler.app_cache.exist?
                            rescue GemfileNotFound
                              nil
                            end
          message = String.new("Could not find gem '#{SharedHelpers.pretty_dependency(requirement)}' in #{source}#{cache_message}.\n")
          message << "The source contains the following versions of '#{name}': #{formatted_versions_with_platforms(versions_with_platforms)}" if versions_with_platforms.any?
        end
        raise GemNotFound, message
      end
    end

    def formatted_versions_with_platforms(versions_with_platforms)
      version_platform_strs = versions_with_platforms.map do |vwp|
        version = vwp.first
        platform = vwp.last
        version_platform_str = String.new(version.to_s)
        version_platform_str << " #{platform}" unless platform.nil? || platform == Gem::Platform::RUBY
        version_platform_str
      end
      version_platform_strs.join(", ")
    end

    def version_conflict_message(e)
      # only show essential conflicts, if possible
      conflicts = e.conflicts.dup

      if conflicts["bundler"]
        conflicts.replace("bundler" => conflicts["bundler"])
      else
        conflicts.delete_if do |_name, conflict|
          deps = conflict.requirement_trees.map(&:last).flatten(1)
          !Bundler::VersionRanges.empty?(*Bundler::VersionRanges.for_many(deps.map(&:requirement)))
        end
      end

      e = Molinillo::VersionConflict.new(conflicts, e.specification_provider) unless conflicts.empty?

      solver_name = "Bundler"
      possibility_type = "gem"
      e.message_with_trees(
        :solver_name => solver_name,
        :possibility_type => possibility_type,
        :reduce_trees => lambda do |trees|
          # called first, because we want to reduce the amount of work required to find maximal empty sets
          trees = trees.uniq {|t| t.flatten.map {|dep| [dep.name, dep.requirement] } }

          # bail out if tree size is too big for Array#combination to make any sense
          return trees if trees.size > 15
          maximal = 1.upto(trees.size).map do |size|
            trees.map(&:last).flatten(1).combination(size).to_a
          end.flatten(1).select do |deps|
            Bundler::VersionRanges.empty?(*Bundler::VersionRanges.for_many(deps.map(&:requirement)))
          end.min_by(&:size)

          trees.reject! {|t| !maximal.include?(t.last) } if maximal

          trees.sort_by {|t| t.reverse.map(&:name) }
        end,
        :printable_requirement => lambda {|req| SharedHelpers.pretty_dependency(req) },
        :additional_message_for_conflict => lambda do |o, name, conflict|
          if name == "bundler"
            o << %(\n  Current Bundler version:\n    bundler (#{Bundler::VERSION}))

            conflict_dependency = conflict.requirement
            conflict_requirement = conflict_dependency.requirement
            other_bundler_required = !conflict_requirement.satisfied_by?(Gem::Version.new(Bundler::VERSION))

            if other_bundler_required
              o << "\n\n"

              candidate_specs = source_for(:default_bundler).specs.search(conflict_dependency)
              if candidate_specs.any?
                target_version = candidate_specs.last.version
                new_command = [File.basename($PROGRAM_NAME), "_#{target_version}_", *ARGV].join(" ")
                o << "Your bundle requires a different version of Bundler than the one you're running.\n"
                o << "Install the necessary version with `gem install bundler:#{target_version}` and rerun bundler using `#{new_command}`\n"
              else
                o << "Your bundle requires a different version of Bundler than the one you're running, and that version could not be found.\n"
              end
            end
          elsif conflict.locked_requirement
            o << "\n"
            o << %(Running `bundle update` will rebuild your snapshot from scratch, using only\n)
            o << %(the gems in your Gemfile, which may resolve the conflict.\n)
          elsif !conflict.existing
            o << "\n"

            relevant_source = conflict.requirement.source || source_for(name)

            metadata_requirement = name.end_with?("\0")

            o << "Could not find gem '" unless metadata_requirement
            o << SharedHelpers.pretty_dependency(conflict.requirement)
            o << "'" unless metadata_requirement
            if conflict.requirement_trees.first.size > 1
              o << ", which is required by "
              o << "gem '#{SharedHelpers.pretty_dependency(conflict.requirement_trees.first[-2])}',"
            end
            o << " "

            o << if metadata_requirement
              "is not available in #{relevant_source}"
            else
              "in #{relevant_source}.\n"
            end
          end
        end,
        :version_for_spec => lambda {|spec| spec.version },
        :incompatible_version_message_for_conflict => lambda do |name, _conflict|
          if name.end_with?("\0")
            %(#{solver_name} found conflicting requirements for the #{name} version:)
          else
            %(#{solver_name} could not find compatible versions for #{possibility_type} "#{name}":)
          end
        end
      )
    end
  end
end
# frozen_string_literal: true

module Bundler
  class Source
    class Git
      class GitNotInstalledError < GitError
        def initialize
          msg = String.new
          msg << "You need to install git to be able to use gems from git repositories. "
          msg << "For help installing git, please refer to GitHub's tutorial at https://help.github.com/articles/set-up-git"
          super msg
        end
      end

      class GitNotAllowedError < GitError
        def initialize(command)
          msg = String.new
          msg << "Bundler is trying to run `#{command}` at runtime. You probably need to run `bundle install`. However, "
          msg << "this error message could probably be more useful. Please submit a ticket at https://github.com/rubygems/rubygems/issues/new?labels=Bundler&template=bundler-related-issue.md "
          msg << "with steps to reproduce as well as the following\n\nCALLER: #{caller.join("\n")}"
          super msg
        end
      end

      class GitCommandError < GitError
        attr_reader :command

        def initialize(command, path, extra_info = nil)
          @command = command

          msg = String.new
          msg << "Git error: command `#{command}` in directory #{path} has failed."
          msg << "\n#{extra_info}" if extra_info
          msg << "\nIf this error persists you could try removing the cache directory '#{path}'" if path.exist?
          super msg
        end
      end

      class MissingGitRevisionError < GitCommandError
        def initialize(command, destination_path, ref, repo)
          msg = "Revision #{ref} does not exist in the repository #{repo}. Maybe you misspelled it?"
          super command, destination_path, msg
        end
      end

      # The GitProxy is responsible to interact with git repositories.
      # All actions required by the Git source is encapsulated in this
      # object.
      class GitProxy
        attr_accessor :path, :uri, :ref
        attr_writer :revision

        def initialize(path, uri, ref, revision = nil, git = nil)
          @path     = path
          @uri      = uri
          @ref      = ref
          @revision = revision
          @git      = git
        end

        def revision
          @revision ||= find_local_revision
        end

        def branch
          @branch ||= allowed_with_path do
            git("rev-parse", "--abbrev-ref", "HEAD", :dir => path).strip
          end
        end

        def contains?(commit)
          allowed_with_path do
            result, status = git_null("branch", "--contains", commit, :dir => path)
            status.success? && result =~ /^\* (.*)$/
          end
        end

        def version
          git("--version").match(/(git version\s*)?((\.?\d+)+).*/)[2]
        end

        def full_version
          git("--version").sub("git version", "").strip
        end

        def checkout
          return if path.exist? && has_revision_cached?
          extra_ref = "#{ref}:#{ref}" if ref && ref.start_with?("refs/")

          Bundler.ui.info "Fetching #{URICredentialsFilter.credential_filtered_uri(uri)}"

          configured_uri = configured_uri_for(uri).to_s

          unless path.exist?
            SharedHelpers.filesystem_access(path.dirname) do |p|
              FileUtils.mkdir_p(p)
            end
            git_retry "clone", "--bare", "--no-hardlinks", "--quiet", "--", configured_uri, path.to_s
            return unless extra_ref
          end

          with_path do
            git_retry(*["fetch", "--force", "--quiet", "--tags", "--", configured_uri, "refs/heads/*:refs/heads/*", extra_ref].compact, :dir => path)
          end
        end

        def copy_to(destination, submodules = false)
          # method 1
          unless File.exist?(destination.join(".git"))
            begin
              SharedHelpers.filesystem_access(destination.dirname) do |p|
                FileUtils.mkdir_p(p)
              end
              SharedHelpers.filesystem_access(destination) do |p|
                FileUtils.rm_rf(p)
              end
              git_retry "clone", "--no-checkout", "--quiet", path.to_s, destination.to_s
              File.chmod(((File.stat(destination).mode | 0o777) & ~File.umask), destination)
            rescue Errno::EEXIST => e
              file_path = e.message[%r{.*?((?:[a-zA-Z]:)?/.*)}, 1]
              raise GitError, "Bundler could not install a gem because it needs to " \
                "create a directory, but a file exists - #{file_path}. Please delete " \
                "this file and try again."
            end
          end
          # method 2
          git_retry "fetch", "--force", "--quiet", "--tags", path.to_s, :dir => destination

          begin
            git "reset", "--hard", @revision, :dir => destination
          rescue GitCommandError => e
            raise MissingGitRevisionError.new(e.command, destination, @revision, URICredentialsFilter.credential_filtered_uri(uri))
          end

          if submodules
            git_retry "submodule", "update", "--init", "--recursive", :dir => destination
          elsif Gem::Version.create(version) >= Gem::Version.create("2.9.0")
            inner_command = "git -C $toplevel submodule deinit --force $sm_path"
            git_retry "submodule", "foreach", "--quiet", inner_command, :dir => destination
          end
        end

        private

        def git_null(*command, dir: nil)
          check_allowed(command)

          out, status = SharedHelpers.with_clean_git_env do
            capture_and_ignore_stderr(*capture3_args_for(command, dir))
          end

          [URICredentialsFilter.credential_filtered_string(out, uri), status]
        end

        def git_retry(*command, dir: nil)
          command_with_no_credentials = check_allowed(command)

          Bundler::Retry.new("`#{command_with_no_credentials}` at #{dir || SharedHelpers.pwd}").attempts do
            git(*command, :dir => dir)
          end
        end

        def git(*command, dir: nil)
          command_with_no_credentials = check_allowed(command)

          out, status = SharedHelpers.with_clean_git_env do
            capture_and_filter_stderr(*capture3_args_for(command, dir))
          end

          filtered_out = URICredentialsFilter.credential_filtered_string(out, uri)

          raise GitCommandError.new(command_with_no_credentials, dir || SharedHelpers.pwd, filtered_out) unless status.success?

          filtered_out
        end

        def has_revision_cached?
          return unless @revision
          with_path { git("cat-file", "-e", @revision, :dir => path) }
          true
        rescue GitError
          false
        end

        def remove_cache
          FileUtils.rm_rf(path)
        end

        def find_local_revision
          allowed_with_path do
            git("rev-parse", "--verify", ref || "HEAD", :dir => path).strip
          end
        rescue GitCommandError => e
          raise MissingGitRevisionError.new(e.command, path, ref, URICredentialsFilter.credential_filtered_uri(uri))
        end

        # Adds credentials to the URI as Fetcher#configured_uri_for does
        def configured_uri_for(uri)
          if /https?:/ =~ uri
            remote = Bundler::URI(uri)
            config_auth = Bundler.settings[remote.to_s] || Bundler.settings[remote.host]
            remote.userinfo ||= config_auth
            remote.to_s
          else
            uri
          end
        end

        def allow?
          allowed = @git ? @git.allow_git_ops? : true

          raise GitNotInstalledError.new if allowed && !Bundler.git_present?

          allowed
        end

        def with_path(&blk)
          checkout unless path.exist?
          blk.call
        end

        def allowed_with_path
          return with_path { yield } if allow?
          raise GitError, "The git source #{uri} is not yet checked out. Please run `bundle install` before trying to start your application"
        end

        def check_allowed(command)
          require "shellwords"
          command_with_no_credentials = URICredentialsFilter.credential_filtered_string("git #{command.shelljoin}", uri)
          raise GitNotAllowedError.new(command_with_no_credentials) unless allow?
          command_with_no_credentials
        end

        def capture_and_filter_stderr(*cmd)
          require "open3"
          return_value, captured_err, status = Open3.capture3(*cmd)
          Bundler.ui.warn URICredentialsFilter.credential_filtered_string(captured_err, uri) unless captured_err.empty?
          [return_value, status]
        end

        def capture_and_ignore_stderr(*cmd)
          require "open3"
          return_value, _, status = Open3.capture3(*cmd)
          [return_value, status]
        end

        def capture3_args_for(cmd, dir)
          return ["git", *cmd] unless dir

          if Bundler.feature_flag.bundler_3_mode? || supports_minus_c?
            ["git", "-C", dir.to_s, *cmd]
          else
            ["git", *cmd, { :chdir => dir.to_s }]
          end
        end

        def supports_minus_c?
          @supports_minus_c ||= Gem::Version.new(version) >= Gem::Version.new("1.8.5")
        end
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class Source
    class Gemspec < Path
      attr_reader :gemspec

      def initialize(options)
        super
        @gemspec = options["gemspec"]
      end

      def as_path_source
        Path.new(options)
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class Source
    class RubygemsAggregate
      attr_reader :source_map, :sources

      def initialize(sources, source_map)
        @sources = sources
        @source_map = source_map

        @index = build_index
      end

      def specs
        @index
      end

      def identifier
        to_s
      end

      def to_s
        "any of the sources"
      end

      private

      def build_index
        Index.build do |idx|
          dependency_names = source_map.pinned_spec_names

          sources.all_sources.each do |source|
            source.dependency_names = dependency_names - source_map.pinned_spec_names(source)
            idx.add_source source.specs
            dependency_names.concat(source.unmet_deps).uniq!
          end

          double_check_for_index(idx, dependency_names)
        end
      end

      # Suppose the gem Foo depends on the gem Bar.  Foo exists in Source A.  Bar has some versions that exist in both
      # sources A and B.  At this point, the API request will have found all the versions of Bar in source A,
      # but will not have found any versions of Bar from source B, which is a problem if the requested version
      # of Foo specifically depends on a version of Bar that is only found in source B. This ensures that for
      # each spec we found, we add all possible versions from all sources to the index.
      def double_check_for_index(idx, dependency_names)
        pinned_names = source_map.pinned_spec_names

        names = :names # do this so we only have to traverse to get dependency_names from the index once
        unmet_dependency_names = lambda do
          return names unless names == :names
          new_names = sources.all_sources.map(&:dependency_names_to_double_check)
          return names = nil if new_names.compact!
          names = new_names.flatten(1).concat(dependency_names)
          names.uniq!
          names -= pinned_names
          names
        end

        sources.all_sources.each do |source|
          source.double_check_for(unmet_dependency_names)
        end
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class Source
    class Metadata < Source
      def specs
        @specs ||= Index.build do |idx|
          idx << Gem::Specification.new("Ruby\0", RubyVersion.system.to_gem_version_with_patchlevel)
          idx << Gem::Specification.new("RubyGems\0", Gem::VERSION) do |s|
            s.required_rubygems_version = Gem::Requirement.default
          end

          idx << Gem::Specification.new do |s|
            s.name     = "bundler"
            s.version  = VERSION
            s.license  = "MIT"
            s.platform = Gem::Platform::RUBY
            s.source   = self
            s.authors  = ["bundler team"]
            s.bindir   = "exe"
            s.homepage = "https://bundler.io"
            s.summary  = "The best way to manage your application's dependencies"
            s.executables = %w[bundle]
            # can't point to the actual gemspec or else the require paths will be wrong
            s.loaded_from = File.expand_path("..", __FILE__)
          end

          if local_spec = Bundler.rubygems.find_name("bundler").find {|s| s.version.to_s == VERSION }
            idx << local_spec
          end

          idx.each {|s| s.source = self }
        end
      end

      def options
        {}
      end

      def install(spec, _opts = {})
        print_using_message "Using #{version_message(spec)}"
        nil
      end

      def to_s
        "the local ruby installation"
      end

      def ==(other)
        self.class == other.class
      end
      alias_method :eql?, :==

      def hash
        self.class.hash
      end

      def version_message(spec)
        "#{spec.name} #{spec.version}"
      end
    end
  end
end
# frozen_string_literal: true

require "rubygems/user_interaction"

module Bundler
  class Source
    class Rubygems < Source
      autoload :Remote, File.expand_path("rubygems/remote", __dir__)

      # Use the API when installing less than X gems
      API_REQUEST_LIMIT = 500
      # Ask for X gems per API request
      API_REQUEST_SIZE = 50

      attr_reader :remotes, :caches

      def initialize(options = {})
        @options = options
        @remotes = []
        @dependency_names = []
        @allow_remote = false
        @allow_cached = false
        @allow_local = options["allow_local"] || false
        @caches = [cache_path, *Bundler.rubygems.gem_cache]

        Array(options["remotes"]).reverse_each {|r| add_remote(r) }
      end

      def local_only!
        @specs = nil
        @allow_local = true
        @allow_cached = false
        @allow_remote = false
      end

      def local!
        return if @allow_local

        @specs = nil
        @allow_local = true
      end

      def remote!
        return if @allow_remote

        @specs = nil
        @allow_remote = true
      end

      def cached!
        return if @allow_cached

        @specs = nil
        @allow_local = true
        @allow_cached = true
      end

      def hash
        @remotes.hash
      end

      def eql?(other)
        other.is_a?(Rubygems) && other.credless_remotes == credless_remotes
      end

      alias_method :==, :eql?

      def include?(o)
        o.is_a?(Rubygems) && (o.credless_remotes - credless_remotes).empty?
      end

      def multiple_remotes?
        @remotes.size > 1
      end

      def no_remotes?
        @remotes.size == 0
      end

      def can_lock?(spec)
        return super unless multiple_remotes?
        include?(spec.source)
      end

      def options
        { "remotes" => @remotes.map(&:to_s) }
      end

      def self.from_lock(options)
        new(options)
      end

      def to_lock
        out = String.new("GEM\n")
        remotes.reverse_each do |remote|
          out << "  remote: #{suppress_configured_credentials remote}\n"
        end
        out << "  specs:\n"
      end

      def to_s
        if remotes.empty?
          "locally installed gems"
        elsif @allow_remote && @allow_cached && @allow_local
          "rubygems repository #{remote_names}, cached gems or installed locally"
        elsif @allow_remote && @allow_local
          "rubygems repository #{remote_names} or installed locally"
        elsif @allow_remote
          "rubygems repository #{remote_names}"
        elsif @allow_cached && @allow_local
          "cached gems or installed locally"
        else
          "locally installed gems"
        end
      end

      def identifier
        if remotes.empty?
          "locally installed gems"
        else
          "rubygems repository #{remote_names}"
        end
      end
      alias_method :name, :identifier

      def specs
        @specs ||= begin
          # remote_specs usually generates a way larger Index than the other
          # sources, and large_idx.use small_idx is way faster than
          # small_idx.use large_idx.
          idx = @allow_remote ? remote_specs.dup : Index.new
          idx.use(cached_specs, :override_dupes) if @allow_cached || @allow_remote
          idx.use(installed_specs, :override_dupes) if @allow_local
          idx
        end
      end

      def install(spec, opts = {})
        force = opts[:force]
        ensure_builtin_gems_cached = opts[:ensure_builtin_gems_cached]

        if ensure_builtin_gems_cached && spec.default_gem?
          if !cached_path(spec)
            cached_built_in_gem(spec) unless spec.remote
            force = true
          else
            spec.loaded_from = loaded_from(spec)
          end
        end

        if installed?(spec) && !force
          print_using_message "Using #{version_message(spec)}"
          return nil # no post-install message
        end

        # Download the gem to get the spec, because some specs that are returned
        # by rubygems.org are broken and wrong.
        if spec.remote
          # Check for this spec from other sources
          uris = [spec.remote.anonymized_uri]
          uris += remotes_for_spec(spec).map(&:anonymized_uri)
          uris.uniq!
          Installer.ambiguous_gems << [spec.name, *uris] if uris.length > 1

          path = fetch_gem(spec)
          begin
            s = Bundler.rubygems.spec_from_gem(path, Bundler.settings["trust-policy"])
            spec.__swap__(s)
          rescue Gem::Package::FormatError
            Bundler.rm_rf(path)
            raise
          end
        end

        unless Bundler.settings[:no_install]
          message = "Installing #{version_message(spec)}"
          message += " with native extensions" if spec.extensions.any?
          Bundler.ui.confirm message

          path = cached_gem(spec)
          raise GemNotFound, "Could not find #{spec.file_name} for installation" unless path
          if requires_sudo?
            install_path = Bundler.tmp(spec.full_name)
            bin_path     = install_path.join("bin")
          else
            install_path = rubygems_dir
            bin_path     = Bundler.system_bindir
          end

          Bundler.mkdir_p bin_path, :no_sudo => true unless spec.executables.empty? || Bundler.rubygems.provides?(">= 2.7.5")

          require_relative "../rubygems_gem_installer"

          installed_spec = Bundler::RubyGemsGemInstaller.at(
            path,
            :install_dir         => install_path.to_s,
            :bin_dir             => bin_path.to_s,
            :ignore_dependencies => true,
            :wrappers            => true,
            :env_shebang         => true,
            :build_args          => opts[:build_args],
            :bundler_expected_checksum => spec.respond_to?(:checksum) && spec.checksum,
            :bundler_extension_cache_path => extension_cache_path(spec)
          ).install
          spec.full_gem_path = installed_spec.full_gem_path

          # SUDO HAX
          if requires_sudo?
            Bundler.rubygems.repository_subdirectories.each do |name|
              src = File.join(install_path, name, "*")
              dst = File.join(rubygems_dir, name)
              if name == "extensions" && Dir.glob(src).any?
                src = File.join(src, "*/*")
                ext_src = Dir.glob(src).first
                ext_src.gsub!(src[0..-6], "")
                dst = File.dirname(File.join(dst, ext_src))
              end
              SharedHelpers.filesystem_access(dst) do |p|
                Bundler.mkdir_p(p)
              end
              Bundler.sudo "cp -R #{src} #{dst}" if Dir[src].any?
            end

            spec.executables.each do |exe|
              SharedHelpers.filesystem_access(Bundler.system_bindir) do |p|
                Bundler.mkdir_p(p)
              end
              Bundler.sudo "cp -R #{install_path}/bin/#{exe} #{Bundler.system_bindir}/"
            end
          end
          installed_spec.loaded_from = loaded_from(spec)
        end
        spec.loaded_from = loaded_from(spec)

        spec.post_install_message
      ensure
        Bundler.rm_rf(install_path) if requires_sudo?
      end

      def cache(spec, custom_path = nil)
        cached_path = cached_gem(spec)
        raise GemNotFound, "Missing gem file '#{spec.file_name}'." unless cached_path
        return if File.dirname(cached_path) == Bundler.app_cache.to_s
        Bundler.ui.info "  * #{File.basename(cached_path)}"
        FileUtils.cp(cached_path, Bundler.app_cache(custom_path))
      rescue Errno::EACCES => e
        Bundler.ui.debug(e)
        raise InstallError, e.message
      end

      def cached_built_in_gem(spec)
        cached_path = cached_path(spec)
        if cached_path.nil?
          remote_spec = remote_specs.search(spec).first
          if remote_spec
            cached_path = fetch_gem(remote_spec)
          else
            Bundler.ui.warn "#{spec.full_name} is built in to Ruby, and can't be cached because your Gemfile doesn't have any sources that contain it."
          end
        end
        cached_path
      end

      def add_remote(source)
        uri = normalize_uri(source)
        @remotes.unshift(uri) unless @remotes.include?(uri)
      end

      def spec_names
        if @allow_remote && dependency_api_available?
          remote_specs.spec_names
        else
          []
        end
      end

      def unmet_deps
        if @allow_remote && dependency_api_available?
          remote_specs.unmet_dependency_names
        else
          []
        end
      end

      def fetchers
        @fetchers ||= remotes.map do |uri|
          remote = Source::Rubygems::Remote.new(uri)
          Bundler::Fetcher.new(remote)
        end
      end

      def double_check_for(unmet_dependency_names)
        return unless @allow_remote
        return unless dependency_api_available?

        unmet_dependency_names = unmet_dependency_names.call
        unless unmet_dependency_names.nil?
          if api_fetchers.size <= 1
            # can't do this when there are multiple fetchers because then we might not fetch from _all_
            # of them
            unmet_dependency_names -= remote_specs.spec_names # avoid re-fetching things we've already gotten
          end
          return if unmet_dependency_names.empty?
        end

        Bundler.ui.debug "Double checking for #{unmet_dependency_names || "all specs (due to the size of the request)"} in #{self}"

        fetch_names(api_fetchers, unmet_dependency_names, specs, false)
      end

      def dependency_names_to_double_check
        names = []
        remote_specs.each do |spec|
          case spec
          when EndpointSpecification, Gem::Specification, StubSpecification, LazySpecification
            names.concat(spec.runtime_dependencies.map(&:name))
          when RemoteSpecification # from the full index
            return nil
          else
            raise "unhandled spec type (#{spec.inspect})"
          end
        end
        names
      end

      def dependency_api_available?
        api_fetchers.any?
      end

      protected

      def remote_names
        remotes.map(&:to_s).join(", ")
      end

      def credless_remotes
        if Bundler.settings[:allow_deployment_source_credential_changes]
          remotes.map(&method(:remove_auth))
        else
          remotes.map(&method(:suppress_configured_credentials))
        end
      end

      def remotes_for_spec(spec)
        specs.search_all(spec.name).inject([]) do |uris, s|
          uris << s.remote if s.remote
          uris
        end
      end

      def loaded_from(spec)
        "#{rubygems_dir}/specifications/#{spec.full_name}.gemspec"
      end

      def cached_gem(spec)
        if spec.default_gem?
          cached_built_in_gem(spec)
        else
          cached_path(spec)
        end
      end

      def cached_path(spec)
        global_cache_path = download_cache_path(spec)
        @caches << global_cache_path if global_cache_path

        possibilities = @caches.map {|p| "#{p}/#{spec.file_name}" }
        possibilities.find {|p| File.exist?(p) }
      end

      def normalize_uri(uri)
        uri = uri.to_s
        uri = "#{uri}/" unless uri =~ %r{/$}
        require_relative "../vendored_uri"
        uri = Bundler::URI(uri)
        raise ArgumentError, "The source must be an absolute URI. For example:\n" \
          "source 'https://rubygems.org'" if !uri.absolute? || (uri.is_a?(Bundler::URI::HTTP) && uri.host.nil?)
        uri
      end

      def suppress_configured_credentials(remote)
        remote_nouser = remove_auth(remote)
        if remote.userinfo && remote.userinfo == Bundler.settings[remote_nouser]
          remote_nouser
        else
          remote
        end
      end

      def remove_auth(remote)
        if remote.user || remote.password
          remote.dup.tap {|uri| uri.user = uri.password = nil }.to_s
        else
          remote.to_s
        end
      end

      def installed_specs
        @installed_specs ||= Index.build do |idx|
          Bundler.rubygems.all_specs.reverse_each do |spec|
            spec.source = self
            if Bundler.rubygems.spec_missing_extensions?(spec, false)
              Bundler.ui.debug "Source #{self} is ignoring #{spec} because it is missing extensions"
              next
            end
            idx << spec
          end
        end
      end

      def cached_specs
        @cached_specs ||= begin
          idx = @allow_local ? installed_specs.dup : Index.new

          Dir["#{cache_path}/*.gem"].each do |gemfile|
            next if gemfile =~ /^bundler\-[\d\.]+?\.gem/
            s ||= Bundler.rubygems.spec_from_gem(gemfile)
            s.source = self
            idx << s
          end

          idx
        end
      end

      def api_fetchers
        fetchers.select {|f| f.use_api && f.fetchers.first.api_fetcher? }
      end

      def remote_specs
        @remote_specs ||= Index.build do |idx|
          index_fetchers = fetchers - api_fetchers

          # gather lists from non-api sites
          fetch_names(index_fetchers, nil, idx, false)

          # because ensuring we have all the gems we need involves downloading
          # the gemspecs of those gems, if the non-api sites contain more than
          # about 500 gems, we treat all sites as non-api for speed.
          allow_api = idx.size < API_REQUEST_LIMIT && dependency_names.size < API_REQUEST_LIMIT
          Bundler.ui.debug "Need to query more than #{API_REQUEST_LIMIT} gems." \
            " Downloading full index instead..." unless allow_api

          fetch_names(api_fetchers, allow_api && dependency_names, idx, false)
        end
      end

      def fetch_names(fetchers, dependency_names, index, override_dupes)
        fetchers.each do |f|
          if dependency_names
            Bundler.ui.info "Fetching gem metadata from #{URICredentialsFilter.credential_filtered_uri(f.uri)}", Bundler.ui.debug?
            index.use f.specs_with_retry(dependency_names, self), override_dupes
            Bundler.ui.info "" unless Bundler.ui.debug? # new line now that the dots are over
          else
            Bundler.ui.info "Fetching source index from #{URICredentialsFilter.credential_filtered_uri(f.uri)}"
            index.use f.specs_with_retry(nil, self), override_dupes
          end
        end
      end

      def fetch_gem(spec)
        return false unless spec.remote

        spec.fetch_platform

        cache_path = download_cache_path(spec) || default_cache_path_for(rubygems_dir)
        gem_path = "#{cache_path}/#{spec.file_name}"

        if requires_sudo?
          download_path = Bundler.tmp(spec.full_name)
          download_cache_path = default_cache_path_for(download_path)
        else
          download_cache_path = cache_path
        end

        SharedHelpers.filesystem_access(download_cache_path) do |p|
          FileUtils.mkdir_p(p)
        end
        download_gem(spec, download_cache_path)

        if requires_sudo?
          SharedHelpers.filesystem_access(cache_path) do |p|
            Bundler.mkdir_p(p)
          end
          Bundler.sudo "mv #{download_cache_path}/#{spec.file_name} #{gem_path}"
        end

        gem_path
      ensure
        Bundler.rm_rf(download_path) if requires_sudo?
      end

      def installed?(spec)
        installed_specs[spec].any? && !spec.deleted_gem?
      end

      def requires_sudo?
        Bundler.requires_sudo?
      end

      def rubygems_dir
        Bundler.rubygems.gem_dir
      end

      def default_cache_path_for(dir)
        "#{dir}/cache"
      end

      def cache_path
        Bundler.app_cache
      end

      private

      # Checks if the requested spec exists in the global cache. If it does,
      # we copy it to the download path, and if it does not, we download it.
      #
      # @param  [Specification] spec
      #         the spec we want to download or retrieve from the cache.
      #
      # @param  [String] download_cache_path
      #         the local directory the .gem will end up in.
      #
      def download_gem(spec, download_cache_path)
        uri = spec.remote.uri
        Bundler.ui.confirm("Fetching #{version_message(spec)}")
        Bundler.rubygems.download_gem(spec, uri, download_cache_path)
      end

      # Returns the global cache path of the calling Rubygems::Source object.
      #
      # Note that the Source determines the path's subdirectory. We use this
      # subdirectory in the global cache path so that gems with the same name
      # -- and possibly different versions -- from different sources are saved
      # to their respective subdirectories and do not override one another.
      #
      # @param  [Gem::Specification] specification
      #
      # @return [Pathname] The global cache path.
      #
      def download_cache_path(spec)
        return unless Bundler.feature_flag.global_gem_cache?
        return unless remote = spec.remote
        return unless cache_slug = remote.cache_slug

        Bundler.user_cache.join("gems", cache_slug)
      end

      def extension_cache_slug(spec)
        return unless remote = spec.remote
        remote.cache_slug
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class Source
    class Path < Source
      autoload :Installer, File.expand_path("path/installer", __dir__)

      attr_reader :path, :options, :root_path, :original_path
      attr_writer :name
      attr_accessor :version

      protected :original_path

      DEFAULT_GLOB = "{,*,*/*}.gemspec".freeze

      def initialize(options)
        @options = options.dup
        @glob = options["glob"] || DEFAULT_GLOB

        @allow_cached = false
        @allow_remote = false

        @root_path = options["root_path"] || root

        if options["path"]
          @path = Pathname.new(options["path"])
          expanded_path = expand(@path)
          @path = if @path.relative?
            expanded_path.relative_path_from(root_path.expand_path)
          else
            expanded_path
          end
        end

        @name    = options["name"]
        @version = options["version"]

        # Stores the original path. If at any point we move to the
        # cached directory, we still have the original path to copy from.
        @original_path = @path
      end

      def remote!
        @local_specs = nil
        @allow_remote = true
      end

      def cached!
        @local_specs = nil
        @allow_cached = true
      end

      def self.from_lock(options)
        new(options.merge("path" => options.delete("remote")))
      end

      def to_lock
        out = String.new("PATH\n")
        out << "  remote: #{lockfile_path}\n"
        out << "  glob: #{@glob}\n" unless @glob == DEFAULT_GLOB
        out << "  specs:\n"
      end

      def to_s
        "source at `#{@path}`"
      end

      def hash
        [self.class, expanded_path, version].hash
      end

      def eql?(other)
        return unless other.class == self.class
        expanded_original_path == other.expanded_original_path &&
          version == other.version
      end

      alias_method :==, :eql?

      def name
        File.basename(expanded_path.to_s)
      end

      def install(spec, options = {})
        using_message = "Using #{version_message(spec)} from #{self}"
        using_message += " and installing its executables" unless spec.executables.empty?
        print_using_message using_message
        generate_bin(spec, :disable_extensions => true)
        nil # no post-install message
      end

      def cache(spec, custom_path = nil)
        app_cache_path = app_cache_path(custom_path)
        return unless Bundler.feature_flag.cache_all?
        return if expand(@original_path).to_s.index(root_path.to_s + "/") == 0

        unless @original_path.exist?
          raise GemNotFound, "Can't cache gem #{version_message(spec)} because #{self} is missing!"
        end

        FileUtils.rm_rf(app_cache_path)
        FileUtils.cp_r("#{@original_path}/.", app_cache_path)
        FileUtils.touch(app_cache_path.join(".bundlecache"))
      end

      def local_specs(*)
        @local_specs ||= load_spec_files
      end

      def specs
        if has_app_cache?
          @path = app_cache_path
          @expanded_path = nil # Invalidate
        end
        local_specs
      end

      def app_cache_dirname
        name
      end

      def root
        Bundler.root
      end

      def expanded_original_path
        @expanded_original_path ||= expand(original_path)
      end

      private

      def expanded_path
        @expanded_path ||= expand(path)
      end

      def expand(somepath)
        if Bundler.current_ruby.jruby? # TODO: Unify when https://github.com/rubygems/bundler/issues/7598 fixed upstream and all supported jrubies include the fix
          somepath.expand_path(root_path).expand_path
        else
          somepath.expand_path(root_path)
        end
      rescue ArgumentError => e
        Bundler.ui.debug(e)
        raise PathError, "There was an error while trying to use the path " \
          "`#{somepath}`.\nThe error message was: #{e.message}."
      end

      def lockfile_path
        return relative_path(original_path) if original_path.absolute?
        expand(original_path).relative_path_from(root)
      end

      def app_cache_path(custom_path = nil)
        @app_cache_path ||= Bundler.app_cache(custom_path).join(app_cache_dirname)
      end

      def has_app_cache?
        SharedHelpers.in_bundle? && app_cache_path.exist?
      end

      def load_gemspec(file)
        return unless spec = Bundler.load_gemspec(file)
        Bundler.rubygems.set_installed_by_version(spec)
        spec
      end

      def validate_spec(spec)
        Bundler.rubygems.validate(spec)
      end

      def load_spec_files
        index = Index.new

        if File.directory?(expanded_path)
          # We sort depth-first since `<<` will override the earlier-found specs
          Gem::Util.glob_files_in_dir(@glob, expanded_path).sort_by {|p| -p.split(File::SEPARATOR).size }.each do |file|
            next unless spec = load_gemspec(file)
            spec.source = self

            # Validation causes extension_dir to be calculated, which depends
            # on #source, so we validate here instead of load_gemspec
            validate_spec(spec)
            index << spec
          end

          if index.empty? && @name && @version
            index << Gem::Specification.new do |s|
              s.name     = @name
              s.source   = self
              s.version  = Gem::Version.new(@version)
              s.platform = Gem::Platform::RUBY
              s.summary  = "Fake gemspec for #{@name}"
              s.relative_loaded_from = "#{@name}.gemspec"
              s.authors = ["no one"]
              if expanded_path.join("bin").exist?
                executables = expanded_path.join("bin").children
                executables.reject! {|p| File.directory?(p) }
                s.executables = executables.map {|c| c.basename.to_s }
              end
            end
          end
        else
          message = String.new("The path `#{expanded_path}` ")
          message << if File.exist?(expanded_path)
            "is not a directory."
          else
            "does not exist."
          end
          raise PathError, message
        end

        index
      end

      def relative_path(path = self.path)
        if path.to_s.start_with?(root_path.to_s)
          return path.relative_path_from(root_path)
        end
        path
      end

      def generate_bin(spec, options = {})
        gem_dir = Pathname.new(spec.full_gem_path)

        # Some gem authors put absolute paths in their gemspec
        # and we have to save them from themselves
        spec.files = spec.files.map do |p|
          next p unless p =~ /\A#{Pathname::SEPARATOR_PAT}/
          next if File.directory?(p)
          begin
            Pathname.new(p).relative_path_from(gem_dir).to_s
          rescue ArgumentError
            p
          end
        end.compact

        installer = Path::Installer.new(
          spec,
          :env_shebang => false,
          :disable_extensions => options[:disable_extensions],
          :build_args => options[:build_args],
          :bundler_extension_cache_path => extension_cache_path(spec)
        )
        installer.post_install
      rescue Gem::InvalidSpecificationException => e
        Bundler.ui.warn "\n#{spec.name} at #{spec.full_gem_path} did not have a valid gemspec.\n" \
                        "This prevents bundler from installing bins or native extensions, but " \
                        "that may not affect its functionality."

        if !spec.extensions.empty? && !spec.email.empty?
          Bundler.ui.warn "If you need to use this package without installing it from a gem " \
                          "repository, please contact #{spec.email} and ask them " \
                          "to modify their .gemspec so it can work with `gem build`."
        end

        Bundler.ui.warn "The validation message from RubyGems was:\n  #{e.message}"
      end
    end
  end
end
# frozen_string_literal: true

require_relative "../../rubygems_gem_installer"

module Bundler
  class Source
    class Path
      class Installer < Bundler::RubyGemsGemInstaller
        attr_reader :spec

        def initialize(spec, options = {})
          @options            = options
          @spec               = spec
          @gem_dir            = Bundler.rubygems.path(spec.full_gem_path)
          @wrappers           = true
          @env_shebang        = true
          @format_executable  = options[:format_executable] || false
          @build_args         = options[:build_args] || Bundler.rubygems.build_args
          @gem_bin_dir        = "#{Bundler.rubygems.gem_dir}/bin"
          @disable_extensions = options[:disable_extensions]

          if Bundler.requires_sudo?
            @tmp_dir = Bundler.tmp(spec.full_name).to_s
            @bin_dir = "#{@tmp_dir}/bin"
          else
            @bin_dir = @gem_bin_dir
          end
        end

        def post_install
          run_hooks(:pre_install)

          unless @disable_extensions
            build_extensions
            run_hooks(:post_build)
          end

          generate_bin unless spec.executables.empty?

          run_hooks(:post_install)
        ensure
          Bundler.rm_rf(@tmp_dir) if Bundler.requires_sudo?
        end

        private

        def generate_bin
          super

          if Bundler.requires_sudo?
            SharedHelpers.filesystem_access(@gem_bin_dir) do |p|
              Bundler.mkdir_p(p)
            end
            spec.executables.each do |exe|
              Bundler.sudo "cp -R #{@bin_dir}/#{exe} #{@gem_bin_dir}"
            end
          end
        end

        def run_hooks(type)
          hooks_meth = "#{type}_hooks"
          return unless Gem.respond_to?(hooks_meth)
          Gem.send(hooks_meth).each do |hook|
            result = hook.call(self)
            next unless result == false
            location = " at #{$1}" if hook.inspect =~ /@(.*:\d+)/
            message = "#{type} hook#{location} failed for #{spec.full_name}"
            raise InstallHookError, message
          end
        end
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class Source
    class Rubygems
      class Remote
        attr_reader :uri, :anonymized_uri, :original_uri

        def initialize(uri)
          orig_uri = uri
          uri = Bundler.settings.mirror_for(uri)
          @original_uri = orig_uri if orig_uri != uri
          fallback_auth = Bundler.settings.credentials_for(uri)

          @uri = apply_auth(uri, fallback_auth).freeze
          @anonymized_uri = remove_auth(@uri).freeze
        end

        # @return [String] A slug suitable for use as a cache key for this
        #         remote.
        #
        def cache_slug
          @cache_slug ||= begin
            return nil unless SharedHelpers.md5_available?

            cache_uri = original_uri || uri

            host = cache_uri.to_s.start_with?("file://") ? nil : cache_uri.host

            uri_parts = [host, cache_uri.user, cache_uri.port, cache_uri.path]
            uri_digest = SharedHelpers.digest(:MD5).hexdigest(uri_parts.compact.join("."))

            uri_parts[-1] = uri_digest
            uri_parts.compact.join(".")
          end
        end

        def to_s
          "rubygems remote at #{anonymized_uri}"
        end

        private

        def apply_auth(uri, auth)
          if auth && uri.userinfo.nil?
            uri = uri.dup
            uri.userinfo = auth
          end

          uri
        rescue Bundler::URI::InvalidComponentError
          error_message = "Please CGI escape your usernames and passwords before " \
                          "setting them for authentication."
          raise HTTPError.new(error_message)
        end

        def remove_auth(uri)
          if uri.userinfo
            uri = uri.dup
            uri.user = uri.password = nil
          end

          uri
        end
      end
    end
  end
end
# frozen_string_literal: true

require_relative "../vendored_fileutils"

module Bundler
  class Source
    class Git < Path
      autoload :GitProxy, File.expand_path("git/git_proxy", __dir__)

      attr_reader :uri, :ref, :branch, :options, :glob, :submodules

      def initialize(options)
        @options = options
        @glob = options["glob"] || DEFAULT_GLOB

        @allow_cached = false
        @allow_remote = false

        # Stringify options that could be set as symbols
        %w[ref branch tag revision].each {|k| options[k] = options[k].to_s if options[k] }

        @uri        = options["uri"] || ""
        @safe_uri   = URICredentialsFilter.credential_filtered_uri(@uri)
        @branch     = options["branch"]
        @ref        = options["ref"] || options["branch"] || options["tag"]
        @submodules = options["submodules"]
        @name       = options["name"]
        @version    = options["version"].to_s.strip.gsub("-", ".pre.")

        @copied     = false
        @local      = false
      end

      def self.from_lock(options)
        new(options.merge("uri" => options.delete("remote")))
      end

      def to_lock
        out = String.new("GIT\n")
        out << "  remote: #{@uri}\n"
        out << "  revision: #{revision}\n"
        %w[ref branch tag submodules].each do |opt|
          out << "  #{opt}: #{options[opt]}\n" if options[opt]
        end
        out << "  glob: #{@glob}\n" unless default_glob?
        out << "  specs:\n"
      end

      def hash
        [self.class, uri, ref, branch, name, version, glob, submodules].hash
      end

      def eql?(other)
        other.is_a?(Git) && uri == other.uri && ref == other.ref &&
          branch == other.branch && name == other.name &&
          version == other.version && glob == other.glob &&
          submodules == other.submodules
      end

      alias_method :==, :eql?

      def to_s
        begin
          at = if local?
            path
          elsif user_ref = options["ref"]
            if ref =~ /\A[a-z0-9]{4,}\z/i
              shortref_for_display(user_ref)
            else
              user_ref
            end
          elsif ref
            ref
          else
            git_proxy.branch
          end

          rev = "at #{at}@#{shortref_for_display(revision)}"
        rescue GitError
          ""
        end

        specifiers = [rev, glob_for_display].compact
        suffix =
          if specifiers.any?
            " (#{specifiers.join(", ")})"
          else
            ""
          end

        "#{@safe_uri}#{suffix}"
      end

      def name
        File.basename(@uri, ".git")
      end

      # This is the path which is going to contain a specific
      # checkout of the git repository. When using local git
      # repos, this is set to the local repo.
      def install_path
        @install_path ||= begin
          git_scope = "#{base_name}-#{shortref_for_path(revision)}"

          path = Bundler.install_path.join(git_scope)

          if !path.exist? && Bundler.requires_sudo?
            Bundler.user_bundle_path.join(Bundler.ruby_scope).join(git_scope)
          else
            path
          end
        end
      end

      alias_method :path, :install_path

      def extension_dir_name
        "#{base_name}-#{shortref_for_path(revision)}"
      end

      def unlock!
        git_proxy.revision = nil
        options["revision"] = nil

        @unlocked = true
      end

      def local_override!(path)
        return false if local?

        original_path = path
        path = Pathname.new(path)
        path = path.expand_path(Bundler.root) unless path.relative?

        unless options["branch"] || Bundler.settings[:disable_local_branch_check]
          raise GitError, "Cannot use local override for #{name} at #{path} because " \
            ":branch is not specified in Gemfile. Specify a branch or run " \
            "`bundle config unset local.#{override_for(original_path)}` to remove the local override"
        end

        unless path.exist?
          raise GitError, "Cannot use local override for #{name} because #{path} " \
            "does not exist. Run `bundle config unset local.#{override_for(original_path)}` to remove the local override"
        end

        set_local!(path)

        # Create a new git proxy without the cached revision
        # so the Gemfile.lock always picks up the new revision.
        @git_proxy = GitProxy.new(path, uri, ref)

        if git_proxy.branch != options["branch"] && !Bundler.settings[:disable_local_branch_check]
          raise GitError, "Local override for #{name} at #{path} is using branch " \
            "#{git_proxy.branch} but Gemfile specifies #{options["branch"]}"
        end

        changed = cached_revision && cached_revision != git_proxy.revision

        if !Bundler.settings[:disable_local_revision_check] && changed && !@unlocked && !git_proxy.contains?(cached_revision)
          raise GitError, "The Gemfile lock is pointing to revision #{shortref_for_display(cached_revision)} " \
            "but the current branch in your local override for #{name} does not contain such commit. " \
            "Please make sure your branch is up to date."
        end

        changed
      end

      def specs(*)
        set_local!(app_cache_path) if has_app_cache? && !local?

        if requires_checkout? && !@copied
          fetch
          git_proxy.copy_to(install_path, submodules)
          serialize_gemspecs_in(install_path)
          @copied = true
        end

        local_specs
      end

      def install(spec, options = {})
        force = options[:force]

        print_using_message "Using #{version_message(spec)} from #{self}"

        if (requires_checkout? && !@copied) || force
          Bundler.ui.debug "  * Checking out revision: #{ref}"
          git_proxy.copy_to(install_path, submodules)
          serialize_gemspecs_in(install_path)
          @copied = true
        end

        generate_bin_options = { :disable_extensions => !Bundler.rubygems.spec_missing_extensions?(spec), :build_args => options[:build_args] }
        generate_bin(spec, generate_bin_options)

        requires_checkout? ? spec.post_install_message : nil
      end

      def cache(spec, custom_path = nil)
        app_cache_path = app_cache_path(custom_path)
        return unless Bundler.feature_flag.cache_all?
        return if path == app_cache_path
        cached!
        FileUtils.rm_rf(app_cache_path)
        git_proxy.checkout if requires_checkout?
        git_proxy.copy_to(app_cache_path, @submodules)
        serialize_gemspecs_in(app_cache_path)
      end

      def load_spec_files
        super
      rescue PathError => e
        Bundler.ui.trace e
        raise GitError, "#{self} is not yet checked out. Run `bundle install` first."
      end

      # This is the path which is going to contain a cache
      # of the git repository. When using the same git repository
      # across different projects, this cache will be shared.
      # When using local git repos, this is set to the local repo.
      def cache_path
        @cache_path ||= begin
          if Bundler.requires_sudo? || Bundler.feature_flag.global_gem_cache?
            Bundler.user_cache
          else
            Bundler.bundle_path.join("cache", "bundler")
          end.join("git", git_scope)
        end
      end

      def app_cache_dirname
        "#{base_name}-#{shortref_for_path(cached_revision || revision)}"
      end

      def revision
        git_proxy.revision
      end

      def allow_git_ops?
        @allow_remote || @allow_cached
      end

      def local?
        @local
      end

      private

      def serialize_gemspecs_in(destination)
        destination = destination.expand_path(Bundler.root) if destination.relative?
        Dir["#{destination}/#{@glob}"].each do |spec_path|
          # Evaluate gemspecs and cache the result. Gemspecs
          # in git might require git or other dependencies.
          # The gemspecs we cache should already be evaluated.
          spec = Bundler.load_gemspec(spec_path)
          next unless spec
          Bundler.rubygems.set_installed_by_version(spec)
          Bundler.rubygems.validate(spec)
          File.open(spec_path, "wb") {|file| file.write(spec.to_ruby) }
        end
      end

      def set_local!(path)
        @local       = true
        @local_specs = @git_proxy = nil
        @cache_path  = @install_path = path
      end

      def has_app_cache?
        cached_revision && super
      end

      def requires_checkout?
        allow_git_ops? && !local? && !cached_revision_checked_out?
      end

      def cached_revision_checked_out?
        cached_revision && cached_revision == revision && install_path.exist?
      end

      def base_name
        File.basename(uri.sub(%r{^(\w+://)?([^/:]+:)?(//\w*/)?(\w*/)*}, ""), ".git")
      end

      def shortref_for_display(ref)
        ref[0..6]
      end

      def shortref_for_path(ref)
        ref[0..11]
      end

      def glob_for_display
        default_glob? ? nil : "glob: #{@glob}"
      end

      def default_glob?
        @glob == DEFAULT_GLOB
      end

      def uri_hash
        if uri =~ %r{^\w+://(\w+@)?}
          # Downcase the domain component of the URI
          # and strip off a trailing slash, if one is present
          input = Bundler::URI.parse(uri).normalize.to_s.sub(%r{/$}, "")
        else
          # If there is no URI scheme, assume it is an ssh/git URI
          input = uri
        end
        # We use SHA1 here for historical reason and to preserve backward compatibility.
        # But a transition to a simpler mangling algorithm would be welcome.
        Bundler::Digest.sha1(input)
      end

      def cached_revision
        options["revision"]
      end

      def cached?
        cache_path.exist?
      end

      def git_proxy
        @git_proxy ||= GitProxy.new(cache_path, uri, ref, cached_revision, self)
      end

      def fetch
        git_proxy.checkout
      rescue GitError => e
        raise unless Bundler.feature_flag.allow_offline_install?
        Bundler.ui.warn "Using cached git data because of network errors:\n#{e}"
      end

      # no-op, since we validate when re-serializing the gemspec
      def validate_spec(_spec); end

      def load_gemspec(file)
        stub = Gem::StubSpecification.gemspec_stub(file, install_path.parent, install_path.parent)
        stub.full_gem_path = Pathname.new(file).dirname.expand_path(root).to_s.tap{|x| x.untaint if RUBY_VERSION < "2.7" }
        StubSpecification.from_stub(stub)
      end

      def git_scope
        "#{base_name}-#{uri_hash}"
      end

      def extension_cache_slug(_)
        extension_dir_name
      end

      def override_for(path)
        Bundler.settings.local_overrides.key(path)
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class DepProxy
    attr_reader :__platform, :dep

    @proxies = {}

    def self.get_proxy(dep, platform)
      @proxies[[dep, platform]] ||= new(dep, platform).freeze
    end

    def initialize(dep, platform)
      @dep = dep
      @__platform = platform
    end

    private_class_method :new

    alias_method :eql?, :==

    def type
      @dep.type
    end

    def name
      @dep.name
    end

    def requirement
      @dep.requirement
    end

    def to_s
      s = name.dup
      s << " (#{requirement})" unless requirement == Gem::Requirement.default
      s << " #{__platform}" unless __platform == Gem::Platform::RUBY
      s
    end

    def dup
      raise NoMethodError.new("DepProxy cannot be duplicated")
    end

    def clone
      raise NoMethodError.new("DepProxy cannot be cloned")
    end

    private

    def method_missing(*args, &blk)
      @dep.send(*args, &blk)
    end
  end
end
# frozen_string_literal: true

# Allows for declaring a Gemfile inline in a ruby script, optionally installing
# any gems that aren't already installed on the user's system.
#
# @note Every gem that is specified in this 'Gemfile' will be `require`d, as if
#       the user had manually called `Bundler.require`. To avoid a requested gem
#       being automatically required, add the `:require => false` option to the
#       `gem` dependency declaration.
#
# @param install [Boolean] whether gems that aren't already installed on the
#                          user's system should be installed.
#                          Defaults to `false`.
#
# @param gemfile [Proc]    a block that is evaluated as a `Gemfile`.
#
# @example Using an inline Gemfile
#
#          #!/opt/alt/ruby30/bin/ruby
#
#          require 'bundler/inline'
#
#          gemfile do
#            source 'https://rubygems.org'
#            gem 'json', require: false
#            gem 'nap', require: 'rest'
#            gem 'cocoapods', '~> 0.34.1'
#          end
#
#          puts Pod::VERSION # => "0.34.4"
#
def gemfile(install = false, options = {}, &gemfile)
  require_relative "../bundler"

  opts = options.dup
  ui = opts.delete(:ui) { Bundler::UI::Shell.new }
  ui.level = "silent" if opts.delete(:quiet)
  raise ArgumentError, "Unknown options: #{opts.keys.join(", ")}" unless opts.empty?

  begin
    old_root = Bundler.method(:root)
    bundler_module = class << Bundler; self; end
    bundler_module.send(:remove_method, :root)
    def Bundler.root
      Bundler::SharedHelpers.pwd.expand_path
    end
    old_gemfile = ENV["BUNDLE_GEMFILE"]
    Bundler::SharedHelpers.set_env "BUNDLE_GEMFILE", "Gemfile"

    Bundler::Plugin.gemfile_install(&gemfile) if Bundler.feature_flag.plugins?
    builder = Bundler::Dsl.new
    builder.instance_eval(&gemfile)
    builder.check_primary_source_safety

    Bundler.settings.temporary(:deployment => false, :frozen => false) do
      definition = builder.to_definition(nil, true)
      def definition.lock(*); end
      definition.validate_runtime!

      Bundler.ui = install ? ui : Bundler::UI::Silent.new
      if install || definition.missing_specs?
        Bundler.settings.temporary(:inline => true) do
          installer = Bundler::Installer.install(Bundler.root, definition, :system => true)
          installer.post_install_messages.each do |name, message|
            Bundler.ui.info "Post-install message from #{name}:\n#{message}"
          end
        end
      end

      runtime = Bundler::Runtime.new(nil, definition)
      runtime.setup.require
    end
  ensure
    if bundler_module
      bundler_module.send(:remove_method, :root)
      bundler_module.send(:define_method, :root, old_root)
    end

    if old_gemfile
      ENV["BUNDLE_GEMFILE"] = old_gemfile
    else
      ENV["BUNDLE_GEMFILE"] = ""
    end
  end
end
# frozen_string_literal: true

require_relative "gem_helpers"

module Bundler
  module MatchPlatform
    include GemHelpers

    def match_platform(p)
      MatchPlatform.platforms_match?(platform, p)
    end

    def self.platforms_match?(gemspec_platform, local_platform)
      return true if gemspec_platform.nil?
      return true if Gem::Platform::RUBY == gemspec_platform
      return true if local_platform == gemspec_platform
      gemspec_platform = Gem::Platform.new(gemspec_platform)
      return true if GemHelpers.generic(gemspec_platform) === local_platform
      return true if gemspec_platform === local_platform

      false
    end
  end
end
# frozen_string_literal: true

require_relative "plugin/api"

module Bundler
  module Plugin
    autoload :DSL,        File.expand_path("plugin/dsl", __dir__)
    autoload :Events,     File.expand_path("plugin/events", __dir__)
    autoload :Index,      File.expand_path("plugin/index", __dir__)
    autoload :Installer,  File.expand_path("plugin/installer", __dir__)
    autoload :SourceList, File.expand_path("plugin/source_list", __dir__)

    class MalformattedPlugin < PluginError; end
    class UndefinedCommandError < PluginError; end
    class UnknownSourceError < PluginError; end
    class PluginInstallError < PluginError; end

    PLUGIN_FILE_NAME = "plugins.rb".freeze

    module_function

    def reset!
      instance_variables.each {|i| remove_instance_variable(i) }

      @sources = {}
      @commands = {}
      @hooks_by_event = Hash.new {|h, k| h[k] = [] }
      @loaded_plugin_names = []
    end

    reset!

    # Installs a new plugin by the given name
    #
    # @param [Array<String>] names the name of plugin to be installed
    # @param [Hash] options various parameters as described in description.
    #               Refer to cli/plugin for available options
    def install(names, options)
      specs = Installer.new.install(names, options)

      save_plugins names, specs
    rescue PluginError
      specs_to_delete = specs.select {|k, _v| names.include?(k) && !index.commands.values.include?(k) }
      specs_to_delete.each_value {|spec| Bundler.rm_rf(spec.full_gem_path) }

      raise
    end

    # Uninstalls plugins by the given names
    #
    # @param [Array<String>] names the names of plugins to be uninstalled
    def uninstall(names, options)
      if names.empty? && !options[:all]
        Bundler.ui.error "No plugins to uninstall. Specify at least 1 plugin to uninstall.\n"\
          "Use --all option to uninstall all the installed plugins."
        return
      end

      names = index.installed_plugins if options[:all]
      if names.any?
        names.each do |name|
          if index.installed?(name)
            Bundler.rm_rf(index.plugin_path(name))
            index.unregister_plugin(name)
            Bundler.ui.info "Uninstalled plugin #{name}"
          else
            Bundler.ui.error "Plugin #{name} is not installed \n"
          end
        end
      else
        Bundler.ui.info "No plugins installed"
      end
    end

    # List installed plugins and commands
    #
    def list
      installed_plugins = index.installed_plugins
      if installed_plugins.any?
        output = String.new
        installed_plugins.each do |plugin|
          output << "#{plugin}\n"
          output << "-----\n"
          index.plugin_commands(plugin).each do |command|
            output << "  #{command}\n"
          end
          output << "\n"
        end
      else
        output = "No plugins installed"
      end
      Bundler.ui.info output
    end

    # Evaluates the Gemfile with a limited DSL and installs the plugins
    # specified by plugin method
    #
    # @param [Pathname] gemfile path
    # @param [Proc] block that can be evaluated for (inline) Gemfile
    def gemfile_install(gemfile = nil, &inline)
      Bundler.settings.temporary(:frozen => false, :deployment => false) do
        builder = DSL.new
        if block_given?
          builder.instance_eval(&inline)
        else
          builder.eval_gemfile(gemfile)
        end
        builder.check_primary_source_safety
        definition = builder.to_definition(nil, true)

        return if definition.dependencies.empty?

        plugins = definition.dependencies.map(&:name).reject {|p| index.installed? p }
        installed_specs = Installer.new.install_definition(definition)

        save_plugins plugins, installed_specs, builder.inferred_plugins
      end
    rescue RuntimeError => e
      unless e.is_a?(GemfileError)
        Bundler.ui.error "Failed to install plugin: #{e.message}\n  #{e.backtrace[0]}"
      end
      raise
    end

    # The index object used to store the details about the plugin
    def index
      @index ||= Index.new
    end

    # The directory root for all plugin related data
    #
    # If run in an app, points to local root, in app_config_path
    # Otherwise, points to global root, in Bundler.user_bundle_path("plugin")
    def root
      @root ||= if SharedHelpers.in_bundle?
        local_root
      else
        global_root
      end
    end

    def local_root
      Bundler.app_config_path.join("plugin")
    end

    # The global directory root for all plugin related data
    def global_root
      Bundler.user_bundle_path("plugin")
    end

    # The cache directory for plugin stuffs
    def cache
      @cache ||= root.join("cache")
    end

    # To be called via the API to register to handle a command
    def add_command(command, cls)
      @commands[command] = cls
    end

    # Checks if any plugin handles the command
    def command?(command)
      !index.command_plugin(command).nil?
    end

    # To be called from Cli class to pass the command and argument to
    # appropriate plugin class
    def exec_command(command, args)
      raise UndefinedCommandError, "Command `#{command}` not found" unless command? command

      load_plugin index.command_plugin(command) unless @commands.key? command

      @commands[command].new.exec(command, args)
    end

    # To be called via the API to register to handle a source plugin
    def add_source(source, cls)
      @sources[source] = cls
    end

    # Checks if any plugin declares the source
    def source?(name)
      !index.source_plugin(name.to_s).nil?
    end

    # @return [Class] that handles the source. The class includes API::Source
    def source(name)
      raise UnknownSourceError, "Source #{name} not found" unless source? name

      load_plugin(index.source_plugin(name)) unless @sources.key? name

      @sources[name]
    end

    # @param [Hash] The options that are present in the lock file
    # @return [API::Source] the instance of the class that handles the source
    #                       type passed in locked_opts
    def source_from_lock(locked_opts)
      src = source(locked_opts["type"])

      src.new(locked_opts.merge("uri" => locked_opts["remote"]))
    end

    # To be called via the API to register a hooks and corresponding block that
    # will be called to handle the hook
    def add_hook(event, &block)
      unless Events.defined_event?(event)
        raise ArgumentError, "Event '#{event}' not defined in Bundler::Plugin::Events"
      end
      @hooks_by_event[event.to_s] << block
    end

    # Runs all the hooks that are registered for the passed event
    #
    # It passes the passed arguments and block to the block registered with
    # the api.
    #
    # @param [String] event
    def hook(event, *args, &arg_blk)
      return unless Bundler.feature_flag.plugins?
      unless Events.defined_event?(event)
        raise ArgumentError, "Event '#{event}' not defined in Bundler::Plugin::Events"
      end

      plugins = index.hook_plugins(event)
      return unless plugins.any?

      (plugins - @loaded_plugin_names).each {|name| load_plugin(name) }

      @hooks_by_event[event].each {|blk| blk.call(*args, &arg_blk) }
    end

    # currently only intended for specs
    #
    # @return [String, nil] installed path
    def installed?(plugin)
      Index.new.installed?(plugin)
    end

    # Post installation processing and registering with index
    #
    # @param [Array<String>] plugins list to be installed
    # @param [Hash] specs of plugins mapped to installation path (currently they
    #               contain all the installed specs, including plugins)
    # @param [Array<String>] names of inferred source plugins that can be ignored
    def save_plugins(plugins, specs, optional_plugins = [])
      plugins.each do |name|
        next if index.installed?(name)

        spec = specs[name]

        save_plugin(name, spec, optional_plugins.include?(name))
      end
    end

    # Checks if the gem is good to be a plugin
    #
    # At present it only checks whether it contains plugins.rb file
    #
    # @param [Pathname] plugin_path the path plugin is installed at
    # @raise [MalformattedPlugin] if plugins.rb file is not found
    def validate_plugin!(plugin_path)
      plugin_file = plugin_path.join(PLUGIN_FILE_NAME)
      raise MalformattedPlugin, "#{PLUGIN_FILE_NAME} was not found in the plugin." unless plugin_file.file?
    end

    # Validates and registers a plugin.
    #
    # @param [String] name the name of the plugin
    # @param [Specification] spec of installed plugin
    # @param [Boolean] optional_plugin, removed if there is conflict with any
    #                     other plugin (used for default source plugins)
    #
    # @raise [PluginInstallError] if validation or registration raises any error
    def save_plugin(name, spec, optional_plugin = false)
      validate_plugin! Pathname.new(spec.full_gem_path)
      installed = register_plugin(name, spec, optional_plugin)
      Bundler.ui.info "Installed plugin #{name}" if installed
    rescue PluginError => e
      raise PluginInstallError, "Failed to install plugin `#{spec.name}`, due to #{e.class} (#{e.message})"
    end

    # Runs the plugins.rb file in an isolated namespace, records the plugin
    # actions it registers for and then passes the data to index to be stored.
    #
    # @param [String] name the name of the plugin
    # @param [Specification] spec of installed plugin
    # @param [Boolean] optional_plugin, removed if there is conflict with any
    #                     other plugin (used for default source plugins)
    #
    # @raise [MalformattedPlugin] if plugins.rb raises any error
    def register_plugin(name, spec, optional_plugin = false)
      commands = @commands
      sources = @sources
      hooks = @hooks_by_event

      @commands = {}
      @sources = {}
      @hooks_by_event = Hash.new {|h, k| h[k] = [] }

      load_paths = spec.load_paths
      Bundler.rubygems.add_to_load_path(load_paths)
      path = Pathname.new spec.full_gem_path

      begin
        load path.join(PLUGIN_FILE_NAME), true
      rescue StandardError => e
        raise MalformattedPlugin, "#{e.class}: #{e.message}"
      end

      if optional_plugin && @sources.keys.any? {|s| source? s }
        Bundler.rm_rf(path)
        false
      else
        index.register_plugin(name, path.to_s, load_paths, @commands.keys,
          @sources.keys, @hooks_by_event.keys)
        true
      end
    ensure
      @commands = commands
      @sources = sources
      @hooks_by_event = hooks
    end

    # Executes the plugins.rb file
    #
    # @param [String] name of the plugin
    def load_plugin(name)
      return unless name && !name.empty?

      # Need to ensure before this that plugin root where the rest of gems
      # are installed to be on load path to support plugin deps. Currently not
      # done to avoid conflicts
      path = index.plugin_path(name)

      Bundler.rubygems.add_to_load_path(index.load_paths(name))

      load path.join(PLUGIN_FILE_NAME)

      @loaded_plugin_names << name
    rescue RuntimeError => e
      Bundler.ui.error "Failed loading plugin #{name}: #{e.message}"
      raise
    end

    class << self
      private :load_plugin, :register_plugin, :save_plugins, :validate_plugin!
    end
  end
end
# frozen_string_literal: true

module Bundler
  class EnvironmentPreserver
    INTENTIONALLY_NIL = "BUNDLER_ENVIRONMENT_PRESERVER_INTENTIONALLY_NIL".freeze
    BUNDLER_KEYS = %w[
      BUNDLE_BIN_PATH
      BUNDLE_GEMFILE
      BUNDLER_VERSION
      GEM_HOME
      GEM_PATH
      MANPATH
      PATH
      RB_USER_INSTALL
      RUBYLIB
      RUBYOPT
    ].map(&:freeze).freeze
    BUNDLER_PREFIX = "BUNDLER_ORIG_".freeze

    def self.from_env
      new(env_to_hash(ENV), BUNDLER_KEYS)
    end

    def self.env_to_hash(env)
      to_hash = env.to_hash
      return to_hash unless Gem.win_platform?

      to_hash.each_with_object({}) {|(k,v), a| a[k.upcase] = v }
    end

    # @param env [Hash]
    # @param keys [Array<String>]
    def initialize(env, keys)
      @original = env
      @keys = keys
      @prefix = BUNDLER_PREFIX
    end

    # Replaces `ENV` with the bundler environment variables backed up
    def replace_with_backup
      unless Gem.win_platform?
        ENV.replace(backup)
        return
      end

      # Fallback logic for Windows below to workaround
      # https://bugs.ruby-lang.org/issues/16798. Can be dropped once all
      # supported rubies include the fix for that.

      ENV.clear

      backup.each {|k, v| ENV[k] = v }
    end

    # @return [Hash]
    def backup
      env = @original.clone
      @keys.each do |key|
        value = env[key]
        if !value.nil? && !value.empty?
          env[@prefix + key] ||= value
        elsif value.nil?
          env[@prefix + key] ||= INTENTIONALLY_NIL
        end
      end
      env
    end

    # @return [Hash]
    def restore
      env = @original.clone
      @keys.each do |key|
        value_original = env[@prefix + key]
        next if value_original.nil? || value_original.empty?
        if value_original == INTENTIONALLY_NIL
          env.delete(key)
        else
          env[key] = value_original
        end
        env.delete(@prefix + key)
      end
      env
    end
  end
end
# frozen_string_literal: true

require_relative "../vendored_fileutils"

module Bundler
  class CompactIndexClient
    class Updater
      class MisMatchedChecksumError < Error
        def initialize(path, server_checksum, local_checksum)
          @path = path
          @server_checksum = server_checksum
          @local_checksum = local_checksum
        end

        def message
          "The checksum of /#{@path} does not match the checksum provided by the server! Something is wrong " \
            "(local checksum is #{@local_checksum.inspect}, was expecting #{@server_checksum.inspect})."
        end
      end

      def initialize(fetcher)
        @fetcher = fetcher
        require_relative "../vendored_tmpdir"
      end

      def update(local_path, remote_path, retrying = nil)
        headers = {}

        Bundler::Dir.mktmpdir("bundler-compact-index-") do |local_temp_dir|
          local_temp_path = Pathname.new(local_temp_dir).join(local_path.basename)

          # first try to fetch any new bytes on the existing file
          if retrying.nil? && local_path.file?
            SharedHelpers.filesystem_access(local_temp_path) do
              FileUtils.cp local_path, local_temp_path
            end
            headers["If-None-Match"] = etag_for(local_temp_path)
            headers["Range"] =
              if local_temp_path.size.nonzero?
                # Subtract a byte to ensure the range won't be empty.
                # Avoids 416 (Range Not Satisfiable) responses.
                "bytes=#{local_temp_path.size - 1}-"
              else
                "bytes=#{local_temp_path.size}-"
              end
          end

          response = @fetcher.call(remote_path, headers)
          return nil if response.is_a?(Net::HTTPNotModified)

          content = response.body

          etag = (response["ETag"] || "").gsub(%r{\AW/}, "")
          correct_response = SharedHelpers.filesystem_access(local_temp_path) do
            if response.is_a?(Net::HTTPPartialContent) && local_temp_path.size.nonzero?
              local_temp_path.open("a") {|f| f << slice_body(content, 1..-1) }

              etag_for(local_temp_path) == etag
            else
              local_temp_path.open("wb") {|f| f << content }

              etag.length.zero? || etag_for(local_temp_path) == etag
            end
          end

          if correct_response
            SharedHelpers.filesystem_access(local_path) do
              FileUtils.mv(local_temp_path, local_path)
            end
            return nil
          end

          if retrying
            raise MisMatchedChecksumError.new(remote_path, etag, etag_for(local_temp_path))
          end

          update(local_path, remote_path, :retrying)
        end
      rescue Zlib::GzipFile::Error
        raise Bundler::HTTPError
      end

      def etag_for(path)
        sum = checksum_for_file(path)
        sum ? %("#{sum}") : nil
      end

      def slice_body(body, range)
        body.byteslice(range)
      end

      def checksum_for_file(path)
        return nil unless path.file?
        # This must use File.read instead of Digest.file().hexdigest
        # because we need to preserve \n line endings on windows when calculating
        # the checksum
        SharedHelpers.filesystem_access(path, :read) do
          SharedHelpers.digest(:MD5).hexdigest(File.read(path))
        end
      end
    end
  end
end
# frozen_string_literal: true

require_relative "gem_parser"

module Bundler
  class CompactIndexClient
    class Cache
      attr_reader :directory

      def initialize(directory)
        @directory = Pathname.new(directory).expand_path
        info_roots.each do |dir|
          SharedHelpers.filesystem_access(dir) do
            FileUtils.mkdir_p(dir)
          end
        end
      end

      def names
        lines(names_path)
      end

      def names_path
        directory.join("names")
      end

      def versions
        versions_by_name = Hash.new {|hash, key| hash[key] = [] }
        info_checksums_by_name = {}

        lines(versions_path).each do |line|
          name, versions_string, info_checksum = line.split(" ", 3)
          info_checksums_by_name[name] = info_checksum || ""
          versions_string.split(",").each do |version|
            if version.start_with?("-")
              version = version[1..-1].split("-", 2).unshift(name)
              versions_by_name[name].delete(version)
            else
              version = version.split("-", 2).unshift(name)
              versions_by_name[name] << version
            end
          end
        end

        [versions_by_name, info_checksums_by_name]
      end

      def versions_path
        directory.join("versions")
      end

      def checksums
        checksums = {}

        lines(versions_path).each do |line|
          name, _, checksum = line.split(" ", 3)
          checksums[name] = checksum
        end

        checksums
      end

      def dependencies(name)
        lines(info_path(name)).map do |line|
          parse_gem(line)
        end
      end

      def info_path(name)
        name = name.to_s
        if name =~ /[^a-z0-9_-]/
          name += "-#{SharedHelpers.digest(:MD5).hexdigest(name).downcase}"
          info_roots.last.join(name)
        else
          info_roots.first.join(name)
        end
      end

      def specific_dependency(name, version, platform)
        pattern = [version, platform].compact.join("-")
        return nil if pattern.empty?

        gem_lines = info_path(name).read
        gem_line = gem_lines[/^#{Regexp.escape(pattern)}\b.*/, 0]
        gem_line ? parse_gem(gem_line) : nil
      end

      private

      def lines(path)
        return [] unless path.file?
        lines = SharedHelpers.filesystem_access(path, :read, &:read).split("\n")
        header = lines.index("---")
        header ? lines[header + 1..-1] : lines
      end

      def parse_gem(line)
        @dependency_parser ||= GemParser.new
        @dependency_parser.parse(line)
      end

      def info_roots
        [
          directory.join("info"),
          directory.join("info-special-characters"),
        ]
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CompactIndexClient
    if defined?(Gem::Resolver::APISet::GemParser)
      GemParser = Gem::Resolver::APISet::GemParser
    else
      class GemParser
        def parse(line)
          version_and_platform, rest = line.split(" ", 2)
          version, platform = version_and_platform.split("-", 2)
          dependencies, requirements = rest.split("|", 2).map {|s| s.split(",") } if rest
          dependencies = dependencies ? dependencies.map {|d| parse_dependency(d) } : []
          requirements = requirements ? requirements.map {|d| parse_dependency(d) } : []
          [version, platform, dependencies, requirements]
        end

        private

        def parse_dependency(string)
          dependency = string.split(":")
          dependency[-1] = dependency[-1].split("&") if dependency.size > 1
          dependency
        end
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  # Returns current version of Ruby
  #
  # @return [CurrentRuby] Current version of Ruby
  def self.current_ruby
    @current_ruby ||= CurrentRuby.new
  end

  class CurrentRuby
    KNOWN_MINOR_VERSIONS = %w[
      1.8
      1.9
      2.0
      2.1
      2.2
      2.3
      2.4
      2.5
      2.6
      2.7
      3.0
    ].freeze

    KNOWN_MAJOR_VERSIONS = KNOWN_MINOR_VERSIONS.map {|v| v.split(".", 2).first }.uniq.freeze

    KNOWN_PLATFORMS = %w[
      jruby
      maglev
      mingw
      mri
      mswin
      mswin64
      rbx
      ruby
      truffleruby
      x64_mingw
    ].freeze

    def ruby?
      return true if Bundler::GemHelpers.generic_local_platform == Gem::Platform::RUBY

      !mswin? && (RUBY_ENGINE == "ruby" || RUBY_ENGINE == "rbx" || RUBY_ENGINE == "maglev" || RUBY_ENGINE == "truffleruby")
    end

    def mri?
      !mswin? && RUBY_ENGINE == "ruby"
    end

    def rbx?
      ruby? && RUBY_ENGINE == "rbx"
    end

    def jruby?
      RUBY_ENGINE == "jruby"
    end

    def maglev?
      RUBY_ENGINE == "maglev"
    end

    def truffleruby?
      RUBY_ENGINE == "truffleruby"
    end

    def mswin?
      Gem.win_platform?
    end

    def mswin64?
      Gem.win_platform? && Bundler.local_platform != Gem::Platform::RUBY && Bundler.local_platform.os == "mswin64" && Bundler.local_platform.cpu == "x64"
    end

    def mingw?
      Gem.win_platform? && Bundler.local_platform != Gem::Platform::RUBY && Bundler.local_platform.os == "mingw32" && Bundler.local_platform.cpu != "x64"
    end

    def x64_mingw?
      Gem.win_platform? && Bundler.local_platform != Gem::Platform::RUBY && Bundler.local_platform.os == "mingw32" && Bundler.local_platform.cpu == "x64"
    end

    (KNOWN_MINOR_VERSIONS + KNOWN_MAJOR_VERSIONS).each do |version|
      trimmed_version = version.tr(".", "")
      define_method(:"on_#{trimmed_version}?") do
        RUBY_VERSION.start_with?("#{version}.")
      end

      KNOWN_PLATFORMS.each do |platform|
        define_method(:"#{platform}_#{trimmed_version}?") do
          send(:"#{platform}?") && send(:"on_#{trimmed_version}?")
        end
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  module GemHelpers
    GENERIC_CACHE = { Gem::Platform::RUBY => Gem::Platform::RUBY } # rubocop:disable Style/MutableConstant
    GENERICS = [
      [Gem::Platform.new("java"), Gem::Platform.new("java")],
      [Gem::Platform.new("mswin32"), Gem::Platform.new("mswin32")],
      [Gem::Platform.new("mswin64"), Gem::Platform.new("mswin64")],
      [Gem::Platform.new("universal-mingw32"), Gem::Platform.new("universal-mingw32")],
      [Gem::Platform.new("x64-mingw32"), Gem::Platform.new("x64-mingw32")],
      [Gem::Platform.new("x86_64-mingw32"), Gem::Platform.new("x64-mingw32")],
      [Gem::Platform.new("mingw32"), Gem::Platform.new("x86-mingw32")],
    ].freeze

    def generic(p)
      GENERIC_CACHE[p] ||= begin
        _, found = GENERICS.find do |match, _generic|
          p.os == match.os && (!match.cpu || p.cpu == match.cpu)
        end
        found || Gem::Platform::RUBY
      end
    end
    module_function :generic

    def generic_local_platform
      generic(local_platform)
    end
    module_function :generic_local_platform

    def local_platform
      Bundler.local_platform
    end
    module_function :local_platform

    def platform_specificity_match(spec_platform, user_platform)
      spec_platform = Gem::Platform.new(spec_platform)

      PlatformMatch.specificity_score(spec_platform, user_platform)
    end
    module_function :platform_specificity_match

    def select_best_platform_match(specs, platform)
      matching = specs.select {|spec| spec.match_platform(platform) }
      exact = matching.select {|spec| spec.platform == platform }
      return exact if exact.any?

      sorted_matching = matching.sort_by {|spec| platform_specificity_match(spec.platform, platform) }
      exemplary_spec = sorted_matching.first

      sorted_matching.take_while{|spec| same_specificity(platform, spec, exemplary_spec) && same_deps(spec, exemplary_spec) }
    end
    module_function :select_best_platform_match

    class PlatformMatch
      def self.specificity_score(spec_platform, user_platform)
        return -1 if spec_platform == user_platform
        return 1_000_000 if spec_platform.nil? || spec_platform == Gem::Platform::RUBY || user_platform == Gem::Platform::RUBY

        os_match(spec_platform, user_platform) +
          cpu_match(spec_platform, user_platform) * 10 +
          platform_version_match(spec_platform, user_platform) * 100
      end

      def self.os_match(spec_platform, user_platform)
        if spec_platform.os == user_platform.os
          0
        else
          1
        end
      end

      def self.cpu_match(spec_platform, user_platform)
        if spec_platform.cpu == user_platform.cpu
          0
        elsif spec_platform.cpu == "arm" && user_platform.cpu.to_s.start_with?("arm")
          0
        elsif spec_platform.cpu.nil? || spec_platform.cpu == "universal"
          1
        else
          2
        end
      end

      def self.platform_version_match(spec_platform, user_platform)
        if spec_platform.version == user_platform.version
          0
        elsif spec_platform.version.nil?
          1
        else
          2
        end
      end
    end

    def same_specificity(platform, spec, exemplary_spec)
      platform_specificity_match(spec.platform, platform) == platform_specificity_match(exemplary_spec.platform, platform)
    end
    module_function :same_specificity

    def same_deps(spec, exemplary_spec)
      same_runtime_deps = spec.dependencies.sort == exemplary_spec.dependencies.sort
      return same_runtime_deps unless spec.is_a?(Gem::Specification) && exemplary_spec.is_a?(Gem::Specification)

      same_metadata_deps = spec.required_ruby_version == exemplary_spec.required_ruby_version && spec.required_rubygems_version == exemplary_spec.required_rubygems_version
      same_runtime_deps && same_metadata_deps
    end
    module_function :same_deps
  end
end
# frozen_string_literal: true

require "rake/clean"
CLOBBER.include "pkg"

require_relative "gem_helper"
Bundler::GemHelper.install_tasks
# frozen_string_literal: true

module Bundler
  WINDOWS = RbConfig::CONFIG["host_os"] =~ /(msdos|mswin|djgpp|mingw)/
  FREEBSD = RbConfig::CONFIG["host_os"] =~ /bsd/
  NULL    = WINDOWS ? "NUL" : "/dev/null"
end
# frozen_string_literal: true

module Bundler
  class Settings
    autoload :Mirror,  File.expand_path("mirror", __dir__)
    autoload :Mirrors, File.expand_path("mirror", __dir__)
    autoload :Validator, File.expand_path("settings/validator", __dir__)

    BOOL_KEYS = %w[
      allow_deployment_source_credential_changes
      allow_offline_install
      auto_clean_without_path
      auto_install
      cache_all
      cache_all_platforms
      clean
      default_install_uses_path
      deployment
      disable_checksum_validation
      disable_exec_load
      disable_local_branch_check
      disable_local_revision_check
      disable_shared_gems
      disable_version_check
      force_ruby_platform
      forget_cli_options
      frozen
      gem.changelog
      gem.coc
      gem.mit
      git.allow_insecure
      global_gem_cache
      ignore_messages
      init_gems_rb
      inline
      no_install
      no_prune
      path_relative_to_cwd
      path.system
      plugins
      prefer_patch
      print_only_version_number
      setup_makes_kernel_gem_public
      silence_deprecations
      silence_root_warning
      suppress_install_using_messages
      update_requires_all_flag
      use_gem_version_promoter_for_major_updates
    ].freeze

    NUMBER_KEYS = %w[
      jobs
      redirect
      retry
      ssl_verify_mode
      timeout
    ].freeze

    ARRAY_KEYS = %w[
      with
      without
    ].freeze

    STRING_KEYS = %w[
      bin
      cache_path
      console
      gem.ci
      gem.github_username
      gem.linter
      gem.rubocop
      gem.test
      gemfile
      path
      shebang
      system_bindir
      trust-policy
    ].freeze

    DEFAULT_CONFIG = {
      "BUNDLE_SILENCE_DEPRECATIONS" => false,
      "BUNDLE_DISABLE_VERSION_CHECK" => true,
      "BUNDLE_PREFER_PATCH" => false,
      "BUNDLE_REDIRECT" => 5,
      "BUNDLE_RETRY" => 3,
      "BUNDLE_TIMEOUT" => 10,
    }.freeze

    def initialize(root = nil)
      @root            = root
      @local_config    = load_config(local_config_file)
      @env_config      = ENV.to_h.select {|key, _value| key =~ /\ABUNDLE_.+/ }
      @global_config   = load_config(global_config_file)
      @temporary       = {}
    end

    def [](name)
      key = key_for(name)
      value = configs.values.map {|config| config[key] }.compact.first

      converted_value(value, name)
    end

    def set_command_option(key, value)
      if Bundler.feature_flag.forget_cli_options?
        temporary(key => value)
        value
      else
        set_local(key, value)
      end
    end

    def set_command_option_if_given(key, value)
      return if value.nil?
      set_command_option(key, value)
    end

    def set_local(key, value)
      local_config_file || raise(GemfileNotFound, "Could not locate Gemfile")

      set_key(key, value, @local_config, local_config_file)
    end

    def temporary(update)
      existing = Hash[update.map {|k, _| [k, @temporary[key_for(k)]] }]
      update.each do |k, v|
        set_key(k, v, @temporary, nil)
      end
      return unless block_given?
      begin
        yield
      ensure
        existing.each {|k, v| set_key(k, v, @temporary, nil) }
      end
    end

    def set_global(key, value)
      set_key(key, value, @global_config, global_config_file)
    end

    def all
      keys = @temporary.keys | @global_config.keys | @local_config.keys | @env_config.keys

      keys.map do |key|
        key.sub(/^BUNDLE_/, "").gsub(/___/, "-").gsub(/__/, ".").downcase
      end.sort
    end

    def local_overrides
      repos = {}
      all.each do |k|
        repos[$'] = self[k] if k =~ /^local\./
      end
      repos
    end

    def mirror_for(uri)
      if uri.is_a?(String)
        require_relative "vendored_uri"
        uri = Bundler::URI(uri)
      end

      gem_mirrors.for(uri.to_s).uri
    end

    def credentials_for(uri)
      self[uri.to_s] || self[uri.host]
    end

    def gem_mirrors
      all.inject(Mirrors.new) do |mirrors, k|
        mirrors.parse(k, self[k]) if k.start_with?("mirror.")
        mirrors
      end
    end

    def locations(key)
      key = key_for(key)
      configs.keys.inject({}) do |partial_locations, level|
        value_on_level = configs[level][key]
        partial_locations[level] = value_on_level unless value_on_level.nil?
        partial_locations
      end
    end

    def pretty_values_for(exposed_key)
      key = key_for(exposed_key)

      locations = []

      if value = @temporary[key]
        locations << "Set for the current command: #{printable_value(value, exposed_key).inspect}"
      end

      if value = @local_config[key]
        locations << "Set for your local app (#{local_config_file}): #{printable_value(value, exposed_key).inspect}"
      end

      if value = @env_config[key]
        locations << "Set via #{key}: #{printable_value(value, exposed_key).inspect}"
      end

      if value = @global_config[key]
        locations << "Set for the current user (#{global_config_file}): #{printable_value(value, exposed_key).inspect}"
      end

      return ["You have not configured a value for `#{exposed_key}`"] if locations.empty?
      locations
    end

    def processor_count
      require "etc"
      Etc.nprocessors
    rescue StandardError
      1
    end

    # for legacy reasons, in Bundler 2, we do not respect :disable_shared_gems
    def path
      configs.each do |_level, settings|
        path = value_for("path", settings)
        path_system = value_for("path.system", settings)
        disabled_shared_gems = value_for("disable_shared_gems", settings)
        next if path.nil? && path_system.nil? && disabled_shared_gems.nil?
        system_path = path_system || (disabled_shared_gems == false)
        return Path.new(path, system_path)
      end

      Path.new(nil, false)
    end

    Path = Struct.new(:explicit_path, :system_path) do
      def path
        path = base_path
        path = File.join(path, Bundler.ruby_scope) unless use_system_gems?
        path
      end

      def use_system_gems?
        return true if system_path
        return false if explicit_path
        !Bundler.feature_flag.default_install_uses_path?
      end

      def base_path
        path = explicit_path
        path ||= ".bundle" unless use_system_gems?
        path ||= Bundler.rubygems.gem_dir
        path
      end

      def base_path_relative_to_pwd
        base_path = Pathname.new(self.base_path)
        expanded_base_path = base_path.expand_path(Bundler.root)
        relative_path = expanded_base_path.relative_path_from(Pathname.pwd)
        if relative_path.to_s.start_with?("..")
          relative_path = base_path if base_path.absolute?
        else
          relative_path = Pathname.new(File.join(".", relative_path))
        end
        relative_path
      rescue ArgumentError
        expanded_base_path
      end

      def validate!
        return unless explicit_path && system_path
        path = Bundler.settings.pretty_values_for(:path)
        path.unshift(nil, "path:") unless path.empty?
        system_path = Bundler.settings.pretty_values_for("path.system")
        system_path.unshift(nil, "path.system:") unless system_path.empty?
        disable_shared_gems = Bundler.settings.pretty_values_for(:disable_shared_gems)
        disable_shared_gems.unshift(nil, "disable_shared_gems:") unless disable_shared_gems.empty?
        raise InvalidOption,
          "Using a custom path while using system gems is unsupported.\n#{path.join("\n")}\n#{system_path.join("\n")}\n#{disable_shared_gems.join("\n")}"
      end
    end

    def allow_sudo?
      key = key_for(:path)
      path_configured = @temporary.key?(key) || @local_config.key?(key)
      !path_configured
    end

    def ignore_config?
      ENV["BUNDLE_IGNORE_CONFIG"]
    end

    def app_cache_path
      @app_cache_path ||= self[:cache_path] || "vendor/cache"
    end

    def validate!
      all.each do |raw_key|
        [@local_config, @env_config, @global_config].each do |settings|
          value = value_for(raw_key, settings)
          Validator.validate!(raw_key, value, settings.dup)
        end
      end
    end

    def key_for(key)
      self.class.key_for(key)
    end

    private

    def configs
      {
        :temporary => @temporary,
        :local => @local_config,
        :env => @env_config,
        :global => @global_config,
        :default => DEFAULT_CONFIG,
      }
    end

    def value_for(name, config)
      converted_value(config[key_for(name)], name)
    end

    def parent_setting_for(name)
      split_specific_setting_for(name)[0]
    end

    def specific_gem_for(name)
      split_specific_setting_for(name)[1]
    end

    def split_specific_setting_for(name)
      name.split(".")
    end

    def is_bool(name)
      BOOL_KEYS.include?(name.to_s) || BOOL_KEYS.include?(parent_setting_for(name.to_s))
    end

    def is_string(name)
      STRING_KEYS.include?(name.to_s) || name.to_s.start_with?("local.") || name.to_s.start_with?("mirror.") || name.to_s.start_with?("build.")
    end

    def to_bool(value)
      case value
      when nil, /\A(false|f|no|n|0|)\z/i, false
        false
      else
        true
      end
    end

    def is_num(key)
      NUMBER_KEYS.include?(key.to_s)
    end

    def is_array(key)
      ARRAY_KEYS.include?(key.to_s)
    end

    def is_credential(key)
      key == "gem.push_key"
    end

    def is_userinfo(value)
      value.include?(":")
    end

    def to_array(value)
      return [] unless value
      value.split(":").map(&:to_sym)
    end

    def array_to_s(array)
      array = Array(array)
      return nil if array.empty?
      array.join(":").tr(" ", ":")
    end

    def set_key(raw_key, value, hash, file)
      raw_key = raw_key.to_s
      value = array_to_s(value) if is_array(raw_key)

      key = key_for(raw_key)

      return if hash[key] == value

      hash[key] = value
      hash.delete(key) if value.nil?

      Validator.validate!(raw_key, converted_value(value, raw_key), hash)

      return unless file
      SharedHelpers.filesystem_access(file) do |p|
        FileUtils.mkdir_p(p.dirname)
        require_relative "yaml_serializer"
        p.open("w") {|f| f.write(YAMLSerializer.dump(hash)) }
      end
    end

    def converted_value(value, key)
      if is_array(key)
        to_array(value)
      elsif value.nil?
        nil
      elsif is_bool(key) || value == "false"
        to_bool(value)
      elsif is_num(key)
        value.to_i
      else
        value.to_s
      end
    end

    def printable_value(value, key)
      converted = converted_value(value, key)
      return converted unless converted.is_a?(String)

      if is_string(key)
        converted
      elsif is_credential(key)
        "[REDACTED]"
      elsif is_userinfo(converted)
        username, pass = converted.split(":", 2)

        if pass == "x-oauth-basic"
          username = "[REDACTED]"
        else
          pass = "[REDACTED]"
        end

        [username, pass].join(":")
      else
        converted
      end
    end

    def global_config_file
      if ENV["BUNDLE_CONFIG"] && !ENV["BUNDLE_CONFIG"].empty?
        Pathname.new(ENV["BUNDLE_CONFIG"])
      elsif ENV["BUNDLE_USER_CONFIG"] && !ENV["BUNDLE_USER_CONFIG"].empty?
        Pathname.new(ENV["BUNDLE_USER_CONFIG"])
      elsif ENV["BUNDLE_USER_HOME"] && !ENV["BUNDLE_USER_HOME"].empty?
        Pathname.new(ENV["BUNDLE_USER_HOME"]).join("config")
      elsif Bundler.rubygems.user_home && !Bundler.rubygems.user_home.empty?
        Pathname.new(Bundler.rubygems.user_home).join(".bundle/config")
      end
    end

    def local_config_file
      Pathname.new(@root).join("config") if @root
    end

    def load_config(config_file)
      return {} if !config_file || ignore_config?
      SharedHelpers.filesystem_access(config_file, :read) do |file|
        valid_file = file.exist? && !file.size.zero?
        return {} unless valid_file
        require_relative "yaml_serializer"
        YAMLSerializer.load(file.read).inject({}) do |config, (k, v)|
          new_k = k

          if k.include?("-")
            Bundler.ui.warn "Your #{file} config includes `#{k}`, which contains the dash character (`-`).\n" \
              "This is deprecated, because configuration through `ENV` should be possible, but `ENV` keys cannot include dashes.\n" \
              "Please edit #{file} and replace any dashes in configuration keys with a triple underscore (`___`)."

            new_k = k.gsub("-", "___")
          end

          config[new_k] = v
          config
        end
      end
    end

    PER_URI_OPTIONS = %w[
      fallback_timeout
    ].freeze

    NORMALIZE_URI_OPTIONS_PATTERN =
      /
        \A
        (\w+\.)? # optional prefix key
        (https?.*?) # URI
        (\.#{Regexp.union(PER_URI_OPTIONS)})? # optional suffix key
        \z
      /ix.freeze

    def self.key_for(key)
      key = normalize_uri(key).to_s if key.is_a?(String) && /https?:/ =~ key
      key = key.to_s.gsub(".", "__").gsub("-", "___").upcase
      "BUNDLE_#{key}"
    end

    # TODO: duplicates Rubygems#normalize_uri
    # TODO: is this the correct place to validate mirror URIs?
    def self.normalize_uri(uri)
      uri = uri.to_s
      if uri =~ NORMALIZE_URI_OPTIONS_PATTERN
        prefix = $1
        uri = $2
        suffix = $3
      end
      uri = "#{uri}/" unless uri.end_with?("/")
      require_relative "vendored_uri"
      uri = Bundler::URI(uri)
      unless uri.absolute?
        raise ArgumentError, format("Gem sources must be absolute. You provided '%s'.", uri)
      end
      "#{prefix}#{uri}#{suffix}"
    end
  end
end
# frozen_string_literal: true

require_relative "shared_helpers"
Bundler::SharedHelpers.major_deprecation 2,
  "The Bundler task for Capistrano. Please use https://github.com/capistrano/bundler"

# Capistrano task for Bundler.
#
# Add "require 'bundler/capistrano'" in your Capistrano deploy.rb, and
# Bundler will be activated after each new deployment.
require_relative "deployment"
require "capistrano/version"

if defined?(Capistrano::Version) && Gem::Version.new(Capistrano::Version).release >= Gem::Version.new("3.0")
  raise "For Capistrano 3.x integration, please use https://github.com/capistrano/bundler"
end

Capistrano::Configuration.instance(:must_exist).load do
  before "deploy:finalize_update", "bundle:install"
  Bundler::Deployment.define_task(self, :task, :except => { :no_release => true })
  set :rake, lambda { "#{fetch(:bundle_cmd, "bundle")} exec rake" }
end
# frozen_string_literal: true

# Psych could be in the stdlib
# but it's too late if Syck is already loaded
begin
  require "psych" unless defined?(Syck)
rescue LoadError
  # Apparently Psych wasn't available. Oh well.
end

# At least load the YAML stdlib, whatever that may be
require "yaml" unless defined?(YAML.dump)

module Bundler
  # On encountering invalid YAML,
  # Psych raises Psych::SyntaxError
  if defined?(::Psych::SyntaxError)
    YamlLibrarySyntaxError = ::Psych::SyntaxError
  else # Syck raises ArgumentError
    YamlLibrarySyntaxError = ::ArgumentError
  end
end
# frozen_string_literal: true

require "pathname"
require "rbconfig"

require_relative "version"
require_relative "constants"
require_relative "rubygems_integration"
require_relative "current_ruby"

module Bundler
  module SharedHelpers
    def root
      gemfile = find_gemfile
      raise GemfileNotFound, "Could not locate Gemfile" unless gemfile
      Pathname.new(gemfile).tap{|x| x.untaint if RUBY_VERSION < "2.7" }.expand_path.parent
    end

    def default_gemfile
      gemfile = find_gemfile
      raise GemfileNotFound, "Could not locate Gemfile" unless gemfile
      Pathname.new(gemfile).tap{|x| x.untaint if RUBY_VERSION < "2.7" }.expand_path
    end

    def default_lockfile
      gemfile = default_gemfile

      case gemfile.basename.to_s
      when "gems.rb" then Pathname.new(gemfile.sub(/.rb$/, ".locked"))
      else Pathname.new("#{gemfile}.lock")
      end.tap{|x| x.untaint if RUBY_VERSION < "2.7" }
    end

    def default_bundle_dir
      bundle_dir = find_directory(".bundle")
      return nil unless bundle_dir

      bundle_dir = Pathname.new(bundle_dir)

      global_bundle_dir = Bundler.user_home.join(".bundle")
      return nil if bundle_dir == global_bundle_dir

      bundle_dir
    end

    def in_bundle?
      find_gemfile
    end

    def chdir(dir, &blk)
      Bundler.rubygems.ext_lock.synchronize do
        Dir.chdir dir, &blk
      end
    end

    def pwd
      Bundler.rubygems.ext_lock.synchronize do
        Pathname.pwd
      end
    end

    def with_clean_git_env(&block)
      keys    = %w[GIT_DIR GIT_WORK_TREE]
      old_env = keys.inject({}) do |h, k|
        h.update(k => ENV[k])
      end

      keys.each {|key| ENV.delete(key) }

      block.call
    ensure
      keys.each {|key| ENV[key] = old_env[key] }
    end

    def set_bundle_environment
      set_bundle_variables
      set_path
      set_rubyopt
      set_rubylib
    end

    # Rescues permissions errors raised by file system operations
    # (ie. Errno:EACCESS, Errno::EAGAIN) and raises more friendly errors instead.
    #
    # @param path [String] the path that the action will be attempted to
    # @param action [Symbol, #to_s] the type of operation that will be
    #   performed. For example: :write, :read, :exec
    #
    # @yield path
    #
    # @raise [Bundler::PermissionError] if Errno:EACCES is raised in the
    #   given block
    # @raise [Bundler::TemporaryResourceError] if Errno:EAGAIN is raised in the
    #   given block
    #
    # @example
    #   filesystem_access("vendor/cache", :write) do
    #     FileUtils.mkdir_p("vendor/cache")
    #   end
    #
    # @see {Bundler::PermissionError}
    def filesystem_access(path, action = :write, &block)
      yield(path.dup.tap{|x| x.untaint if RUBY_VERSION < "2.7" })
    rescue Errno::EACCES
      raise PermissionError.new(path, action)
    rescue Errno::EAGAIN
      raise TemporaryResourceError.new(path, action)
    rescue Errno::EPROTO
      raise VirtualProtocolError.new
    rescue Errno::ENOSPC
      raise NoSpaceOnDeviceError.new(path, action)
    rescue *[const_get_safely(:ENOTSUP, Errno)].compact
      raise OperationNotSupportedError.new(path, action)
    rescue Errno::EEXIST, Errno::ENOENT
      raise
    rescue SystemCallError => e
      raise GenericSystemCallError.new(e, "There was an error accessing `#{path}`.")
    end

    def const_get_safely(constant_name, namespace)
      const_in_namespace = namespace.constants.include?(constant_name.to_s) ||
        namespace.constants.include?(constant_name.to_sym)
      return nil unless const_in_namespace
      namespace.const_get(constant_name)
    end

    def major_deprecation(major_version, message, print_caller_location: false)
      if print_caller_location
        caller_location = caller_locations(2, 2).first
        message = "#{message} (called at #{caller_location.path}:#{caller_location.lineno})"
      end

      bundler_major_version = Bundler.bundler_major_version
      if bundler_major_version > major_version
        require_relative "errors"
        raise DeprecatedError, "[REMOVED] #{message}"
      end

      return unless bundler_major_version >= major_version && prints_major_deprecations?
      Bundler.ui.warn("[DEPRECATED] #{message}")
    end

    def print_major_deprecations!
      multiple_gemfiles = search_up(".") do |dir|
        gemfiles = gemfile_names.select {|gf| File.file? File.expand_path(gf, dir) }
        next if gemfiles.empty?
        break gemfiles.size != 1
      end
      return unless multiple_gemfiles
      message = "Multiple gemfiles (gems.rb and Gemfile) detected. " \
                "Make sure you remove Gemfile and Gemfile.lock since bundler is ignoring them in favor of gems.rb and gems.rb.locked."
      Bundler.ui.warn message
    end

    def ensure_same_dependencies(spec, old_deps, new_deps)
      new_deps = new_deps.reject {|d| d.type == :development }
      old_deps = old_deps.reject {|d| d.type == :development }

      without_type = proc {|d| Gem::Dependency.new(d.name, d.requirements_list.sort) }
      new_deps.map!(&without_type)
      old_deps.map!(&without_type)

      extra_deps = new_deps - old_deps
      return if extra_deps.empty?

      Bundler.ui.debug "#{spec.full_name} from #{spec.remote} has either corrupted API or lockfile dependencies" \
        " (was expecting #{old_deps.map(&:to_s)}, but the real spec has #{new_deps.map(&:to_s)})"
      raise APIResponseMismatchError,
        "Downloading #{spec.full_name} revealed dependencies not in the API or the lockfile (#{extra_deps.join(", ")})." \
        "\nEither installing with `--full-index` or running `bundle update #{spec.name}` should fix the problem."
    end

    def pretty_dependency(dep, print_source = false)
      msg = String.new(dep.name)
      msg << " (#{dep.requirement})" unless dep.requirement == Gem::Requirement.default

      if dep.is_a?(Bundler::Dependency)
        platform_string = dep.platforms.join(", ")
        msg << " " << platform_string if !platform_string.empty? && platform_string != Gem::Platform::RUBY
      end

      msg << " from the `#{dep.source}` source" if print_source && dep.source
      msg
    end

    def md5_available?
      return @md5_available if defined?(@md5_available)
      @md5_available = begin
        require "openssl"
        ::OpenSSL::Digest.digest("MD5", "")
        true
      rescue LoadError
        true
      rescue ::OpenSSL::Digest::DigestError
        false
      end
    end

    def digest(name)
      require "digest"
      Digest(name)
    end

    def write_to_gemfile(gemfile_path, contents)
      filesystem_access(gemfile_path) {|g| File.open(g, "w") {|file| file.puts contents } }
    end

    private

    def validate_bundle_path
      path_separator = Bundler.rubygems.path_separator
      return unless Bundler.bundle_path.to_s.split(path_separator).size > 1
      message = "Your bundle path contains text matching #{path_separator.inspect}, " \
                "which is the path separator for your system. Bundler cannot " \
                "function correctly when the Bundle path contains the " \
                "system's PATH separator. Please change your " \
                "bundle path to not match #{path_separator.inspect}." \
                "\nYour current bundle path is '#{Bundler.bundle_path}'."
      raise Bundler::PathError, message
    end

    def find_gemfile
      given = ENV["BUNDLE_GEMFILE"]
      return given if given && !given.empty?
      find_file(*gemfile_names)
    end

    def gemfile_names
      ["gems.rb", "Gemfile"]
    end

    def find_file(*names)
      search_up(*names) do |filename|
        return filename if File.file?(filename)
      end
    end

    def find_directory(*names)
      search_up(*names) do |dirname|
        return dirname if File.directory?(dirname)
      end
    end

    def search_up(*names)
      previous = nil
      current  = File.expand_path(SharedHelpers.pwd).tap{|x| x.untaint if RUBY_VERSION < "2.7" }

      until !File.directory?(current) || current == previous
        if ENV["BUNDLE_SPEC_RUN"]
          # avoid stepping above the tmp directory when testing
          gemspec = if ENV["GEM_COMMAND"]
            # for Ruby Core
            "lib/bundler/bundler.gemspec"
          else
            "bundler.gemspec"
          end

          # avoid stepping above the tmp directory when testing
          return nil if File.file?(File.join(current, gemspec))
        end

        names.each do |name|
          filename = File.join(current, name)
          yield filename
        end
        previous = current
        current = File.expand_path("..", current)
      end
    end

    def set_env(key, value)
      raise ArgumentError, "new key #{key}" unless EnvironmentPreserver::BUNDLER_KEYS.include?(key)
      orig_key = "#{EnvironmentPreserver::BUNDLER_PREFIX}#{key}"
      orig = ENV[key]
      orig ||= EnvironmentPreserver::INTENTIONALLY_NIL
      ENV[orig_key] ||= orig

      ENV[key] = value
    end
    public :set_env

    def set_bundle_variables
      # bundler exe & lib folders have same root folder, typical gem installation
      exe_file = File.expand_path("../../../exe/bundle", __FILE__)

      # for Ruby core repository testing
      exe_file = File.expand_path("../../../libexec/bundle", __FILE__) unless File.exist?(exe_file)

      # bundler is a default gem, exe path is separate
      exe_file = Bundler.rubygems.bin_path("bundler", "bundle", VERSION) unless File.exist?(exe_file)

      Bundler::SharedHelpers.set_env "BUNDLE_BIN_PATH", exe_file
      Bundler::SharedHelpers.set_env "BUNDLE_GEMFILE", find_gemfile.to_s
      Bundler::SharedHelpers.set_env "BUNDLER_VERSION", Bundler::VERSION
    end

    def set_path
      validate_bundle_path
      paths = (ENV["PATH"] || "").split(File::PATH_SEPARATOR)
      paths.unshift "#{Bundler.bundle_path}/bin"
      Bundler::SharedHelpers.set_env "PATH", paths.uniq.join(File::PATH_SEPARATOR)
    end

    def set_rubyopt
      rubyopt = [ENV["RUBYOPT"]].compact
      setup_require = "-r#{File.expand_path("setup", __dir__)}"
      return if !rubyopt.empty? && rubyopt.first =~ /#{setup_require}/
      rubyopt.unshift setup_require
      Bundler::SharedHelpers.set_env "RUBYOPT", rubyopt.join(" ")
    end

    def set_rubylib
      rubylib = (ENV["RUBYLIB"] || "").split(File::PATH_SEPARATOR)
      rubylib.unshift bundler_ruby_lib unless RbConfig::CONFIG["rubylibdir"] == bundler_ruby_lib
      Bundler::SharedHelpers.set_env "RUBYLIB", rubylib.uniq.join(File::PATH_SEPARATOR)
    end

    def bundler_ruby_lib
      resolve_path File.expand_path("../..", __FILE__)
    end

    def clean_load_path
      loaded_gem_paths = Bundler.rubygems.loaded_gem_paths

      $LOAD_PATH.reject! do |p|
        resolved_path = resolve_path(p)
        next if $LOADED_FEATURES.any? {|lf| lf.start_with?(resolved_path) }
        loaded_gem_paths.delete(p)
      end
      $LOAD_PATH.uniq!
    end

    def resolve_path(path)
      expanded = File.expand_path(path)
      return expanded unless File.respond_to?(:realpath) && File.exist?(expanded)

      File.realpath(expanded)
    end

    def prints_major_deprecations?
      require_relative "../bundler"
      return false if Bundler.settings[:silence_deprecations]
      require_relative "deprecate"
      return false if Bundler::Deprecate.skip
      true
    end

    extend self
  end
end
# frozen_string_literal: true

module Bundler
  # This is the interfacing class represents the API that we intend to provide
  # the plugins to use.
  #
  # For plugins to be independent of the Bundler internals they shall limit their
  # interactions to methods of this class only. This will save them from breaking
  # when some internal change.
  #
  # Currently we are delegating the methods defined in Bundler class to
  # itself. So, this class acts as a buffer.
  #
  # If there is some change in the Bundler class that is incompatible to its
  # previous behavior or if otherwise desired, we can reimplement(or implement)
  # the method to preserve compatibility.
  #
  # To use this, either the class can inherit this class or use it directly.
  # For example of both types of use, refer the file `spec/plugins/command.rb`
  #
  # To use it without inheriting, you will have to create an object of this
  # to use the functions (except for declaration functions like command, source,
  # and hooks).
  module Plugin
    class API
      autoload :Source, File.expand_path("api/source", __dir__)

      # The plugins should declare that they handle a command through this helper.
      #
      # @param [String] command being handled by them
      # @param [Class] (optional) class that handles the command. If not
      #                 provided, the `self` class will be used.
      def self.command(command, cls = self)
        Plugin.add_command command, cls
      end

      # The plugins should declare that they provide a installation source
      # through this helper.
      #
      # @param [String] the source type they provide
      # @param [Class] (optional) class that handles the source. If not
      #                 provided, the `self` class will be used.
      def self.source(source, cls = self)
        cls.send :include, Bundler::Plugin::API::Source
        Plugin.add_source source, cls
      end

      def self.hook(event, &block)
        Plugin.add_hook(event, &block)
      end

      # The cache dir to be used by the plugins for storage
      #
      # @return [Pathname] path of the cache dir
      def cache_dir
        Plugin.cache.join("plugins")
      end

      # A tmp dir to be used by plugins
      # Accepts names that get concatenated as suffix
      #
      # @return [Pathname] object for the new directory created
      def tmp(*names)
        Bundler.tmp(["plugin", *names].join("-"))
      end

      def method_missing(name, *args, &blk)
        return Bundler.send(name, *args, &blk) if Bundler.respond_to?(name)

        return SharedHelpers.send(name, *args, &blk) if SharedHelpers.respond_to?(name)

        super
      end

      def respond_to_missing?(name, include_private = false)
        SharedHelpers.respond_to?(name, include_private) ||
          Bundler.respond_to?(name, include_private) || super
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  # Manages which plugins are installed and their sources. This also is supposed to map
  # which plugin does what (currently the features are not implemented so this class is
  # now a stub class).
  module Plugin
    class Index
      class CommandConflict < PluginError
        def initialize(plugin, commands)
          msg = "Command(s) `#{commands.join("`, `")}` declared by #{plugin} are already registered."
          super msg
        end
      end

      class SourceConflict < PluginError
        def initialize(plugin, sources)
          msg = "Source(s) `#{sources.join("`, `")}` declared by #{plugin} are already registered."
          super msg
        end
      end

      attr_reader :commands

      def initialize
        @plugin_paths = {}
        @commands = {}
        @sources = {}
        @hooks = {}
        @load_paths = {}

        begin
          load_index(global_index_file, true)
        rescue GenericSystemCallError
          # no need to fail when on a read-only FS, for example
          nil
        end
        load_index(local_index_file) if SharedHelpers.in_bundle?
      end

      # This function is to be called when a new plugin is installed. This
      # function shall add the functions of the plugin to existing maps and also
      # the name to source location.
      #
      # @param [String] name of the plugin to be registered
      # @param [String] path where the plugin is installed
      # @param [Array<String>] load_paths for the plugin
      # @param [Array<String>] commands that are handled by the plugin
      # @param [Array<String>] sources that are handled by the plugin
      def register_plugin(name, path, load_paths, commands, sources, hooks)
        old_commands = @commands.dup

        common = commands & @commands.keys
        raise CommandConflict.new(name, common) unless common.empty?
        commands.each {|c| @commands[c] = name }

        common = sources & @sources.keys
        raise SourceConflict.new(name, common) unless common.empty?
        sources.each {|k| @sources[k] = name }

        hooks.each do |event|
          event_hooks = (@hooks[event] ||= []) << name
          event_hooks.uniq!
        end

        @plugin_paths[name] = path
        @load_paths[name] = load_paths
        save_index
      rescue StandardError
        @commands = old_commands
        raise
      end

      def unregister_plugin(name)
        @commands.delete_if {|_, v| v == name }
        @sources.delete_if {|_, v| v == name }
        @hooks.each do |hook, names|
          names.delete(name)
          @hooks.delete(hook) if names.empty?
        end
        @plugin_paths.delete(name)
        @load_paths.delete(name)
        save_index
      end

      # Path of default index file
      def index_file
        Plugin.root.join("index")
      end

      # Path where the global index file is stored
      def global_index_file
        Plugin.global_root.join("index")
      end

      # Path where the local index file is stored
      def local_index_file
        Plugin.local_root.join("index")
      end

      def plugin_path(name)
        Pathname.new @plugin_paths[name]
      end

      def load_paths(name)
        @load_paths[name]
      end

      # Fetch the name of plugin handling the command
      def command_plugin(command)
        @commands[command]
      end

      def installed?(name)
        @plugin_paths[name]
      end

      def installed_plugins
        @plugin_paths.keys
      end

      def plugin_commands(plugin)
        @commands.find_all {|_, n| n == plugin }.map(&:first)
      end

      def source?(source)
        @sources.key? source
      end

      def source_plugin(name)
        @sources[name]
      end

      # Returns the list of plugin names handling the passed event
      def hook_plugins(event)
        @hooks[event] || []
      end

      private

      # Reads the index file from the directory and initializes the instance
      # variables.
      #
      # It skips the sources if the second param is true
      # @param [Pathname] index file path
      # @param [Boolean] is the index file global index
      def load_index(index_file, global = false)
        SharedHelpers.filesystem_access(index_file, :read) do |index_f|
          valid_file = index_f && index_f.exist? && !index_f.size.zero?
          break unless valid_file

          data = index_f.read

          require_relative "../yaml_serializer"
          index = YAMLSerializer.load(data)

          @commands.merge!(index["commands"])
          @hooks.merge!(index["hooks"])
          @load_paths.merge!(index["load_paths"])
          @plugin_paths.merge!(index["plugin_paths"])
          @sources.merge!(index["sources"]) unless global
        end
      end

      # Should be called when any of the instance variables change. Stores the
      # instance variables in YAML format. (The instance variables are supposed
      # to be only String key value pairs)
      def save_index
        index = {
          "commands"     => @commands,
          "hooks"        => @hooks,
          "load_paths"   => @load_paths,
          "plugin_paths" => @plugin_paths,
          "sources"      => @sources,
        }

        require_relative "../yaml_serializer"
        SharedHelpers.filesystem_access(index_file) do |index_f|
          FileUtils.mkdir_p(index_f.dirname)
          File.open(index_f, "w") {|f| f.puts YAMLSerializer.dump(index) }
        end
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  # Handles the installation of plugin in appropriate directories.
  #
  # This class is supposed to be wrapper over the existing gem installation infra
  # but currently it itself handles everything as the Source's subclasses (e.g. Source::RubyGems)
  # are heavily dependent on the Gemfile.
  module Plugin
    class Installer
      autoload :Rubygems, File.expand_path("installer/rubygems", __dir__)
      autoload :Git,      File.expand_path("installer/git", __dir__)

      def install(names, options)
        check_sources_consistency!(options)

        version = options[:version] || [">= 0"]

        if options[:git]
          install_git(names, version, options)
        elsif options[:local_git]
          install_local_git(names, version, options)
        else
          sources = options[:source] || Bundler.rubygems.sources
          install_rubygems(names, version, sources)
        end
      end

      # Installs the plugin from Definition object created by limited parsing of
      # Gemfile searching for plugins to be installed
      #
      # @param [Definition] definition object
      # @return [Hash] map of names to their specs they are installed with
      def install_definition(definition)
        def definition.lock(*); end
        definition.resolve_remotely!
        specs = definition.specs

        install_from_specs specs
      end

      private

      def check_sources_consistency!(options)
        if options.key?(:git) && options.key?(:local_git)
          raise InvalidOption, "Remote and local plugin git sources can't be both specified"
        end
      end

      def install_git(names, version, options)
        uri = options.delete(:git)
        options["uri"] = uri

        install_all_sources(names, version, options, options[:source])
      end

      def install_local_git(names, version, options)
        uri = options.delete(:local_git)
        options["uri"] = uri

        install_all_sources(names, version, options, options[:source])
      end

      # Installs the plugin from rubygems source and returns the path where the
      # plugin was installed
      #
      # @param [String] name of the plugin gem to search in the source
      # @param [Array] version of the gem to install
      # @param [String, Array<String>] source(s) to resolve the gem
      #
      # @return [Hash] map of names to the specs of plugins installed
      def install_rubygems(names, version, sources)
        install_all_sources(names, version, nil, sources)
      end

      def install_all_sources(names, version, git_source_options, rubygems_source)
        source_list = SourceList.new

        source_list.add_git_source(git_source_options) if git_source_options
        Array(rubygems_source).each {|remote| source_list.add_global_rubygems_remote(remote) } if rubygems_source

        deps = names.map {|name| Dependency.new name, version }

        Bundler.configure_gem_home_and_path(Plugin.root)

        definition = Definition.new(nil, deps, source_list, true)
        install_definition(definition)
      end

      # Installs the plugins and deps from the provided specs and returns map of
      # gems to their paths
      #
      # @param specs to install
      #
      # @return [Hash] map of names to the specs
      def install_from_specs(specs)
        paths = {}

        specs.each do |spec|
          spec.source.install spec

          paths[spec.name] = spec
        end

        paths
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  module Plugin
    module Events
      def self.define(const, event)
        const = const.to_sym.freeze
        if const_defined?(const) && const_get(const) != event
          raise ArgumentError, "Attempting to reassign #{const} to a different value"
        end
        const_set(const, event) unless const_defined?(const)
        @events ||= {}
        @events[event] = const
      end
      private_class_method :define

      def self.reset
        @events.each_value do |const|
          remove_const(const)
        end
        @events = nil
      end
      private_class_method :reset

      # Check if an event has been defined
      # @param event [String] An event to check
      # @return [Boolean] A boolean indicating if the event has been defined
      def self.defined_event?(event)
        @events ||= {}
        @events.key?(event)
      end

      # @!parse
      #   A hook called before each individual gem is installed
      #   Includes a Bundler::ParallelInstaller::SpecInstallation.
      #   No state, error, post_install_message will be present as nothing has installed yet
      #   GEM_BEFORE_INSTALL = "before-install"
      define :GEM_BEFORE_INSTALL, "before-install"

      # @!parse
      #   A hook called after each individual gem is installed
      #   Includes a Bundler::ParallelInstaller::SpecInstallation.
      #     - If state is failed, an error will be present.
      #     - If state is success, a post_install_message may be present.
      #   GEM_AFTER_INSTALL = "after-install"
      define :GEM_AFTER_INSTALL,  "after-install"

      # @!parse
      #   A hook called before any gems install
      #   Includes an Array of Bundler::Dependency objects
      #   GEM_BEFORE_INSTALL_ALL = "before-install-all"
      define :GEM_BEFORE_INSTALL_ALL, "before-install-all"

      # @!parse
      #   A hook called after any gems install
      #   Includes an Array of Bundler::Dependency objects
      #   GEM_AFTER_INSTALL_ALL = "after-install-all"
      define :GEM_AFTER_INSTALL_ALL,  "after-install-all"
    end
  end
end
# frozen_string_literal: true

module Bundler
  module Plugin
    class API
      # This class provides the base to build source plugins
      # All the method here are required to build a source plugin (except
      # `uri_hash`, `gem_install_dir`; they are helpers).
      #
      # Defaults for methods, where ever possible are provided which is
      # expected to work. But, all source plugins have to override
      # `fetch_gemspec_files` and `install`. Defaults are also not provided for
      # `remote!`, `cache!` and `unlock!`.
      #
      # The defaults shall work for most situations but nevertheless they can
      # be (preferably should be) overridden as per the plugins' needs safely
      # (as long as they behave as expected).
      # On overriding `initialize` you should call super first.
      #
      # If required plugin should override `hash`, `==` and `eql?` methods to be
      # able to match objects representing same sources, but may be created in
      # different situation (like form gemfile and lockfile). The default ones
      # checks only for class and uri, but elaborate source plugins may need
      # more comparisons (e.g. git checking on branch or tag).
      #
      # @!attribute [r] uri
      #   @return [String] the remote specified with `source` block in Gemfile
      #
      # @!attribute [r] options
      #   @return [String] options passed during initialization (either from
      #     lockfile or Gemfile)
      #
      # @!attribute [r] name
      #   @return [String] name that can be used to uniquely identify a source
      #
      # @!attribute [rw] dependency_names
      #   @return [Array<String>] Names of dependencies that the source should
      #     try to resolve. It is not necessary to use this list internally. This
      #     is present to be compatible with `Definition` and is used by
      #     rubygems source.
      module Source
        attr_reader :uri, :options, :name
        attr_accessor :dependency_names

        def initialize(opts)
          @options = opts
          @dependency_names = []
          @uri = opts["uri"]
          @type = opts["type"]
          @name = opts["name"] || "#{@type} at #{@uri}"
        end

        # This is used by the default `spec` method to constructs the
        # Specification objects for the gems and versions that can be installed
        # by this source plugin.
        #
        # Note: If the spec method is overridden, this function is not necessary
        #
        # @return [Array<String>] paths of the gemspec files for gems that can
        #                         be installed
        def fetch_gemspec_files
          []
        end

        # Options to be saved in the lockfile so that the source plugin is able
        # to check out same version of gem later.
        #
        # There options are passed when the source plugin is created from the
        # lock file.
        #
        # @return [Hash]
        def options_to_lock
          {}
        end

        # Install the gem specified by the spec at appropriate path.
        # `install_path` provides a sufficient default, if the source can only
        # satisfy one gem,  but is not binding.
        #
        # @return [String] post installation message (if any)
        def install(spec, opts)
          raise MalformattedPlugin, "Source plugins need to override the install method."
        end

        # It builds extensions, generates bins and installs them for the spec
        # provided.
        #
        # It depends on `spec.loaded_from` to get full_gem_path. The source
        # plugins should set that.
        #
        # It should be called in `install` after the plugin is done placing the
        # gem at correct install location.
        #
        # It also runs Gem hooks `pre_install`, `post_build` and `post_install`
        #
        # Note: Do not override if you don't know what you are doing.
        def post_install(spec, disable_exts = false)
          opts = { :env_shebang => false, :disable_extensions => disable_exts }
          installer = Bundler::Source::Path::Installer.new(spec, opts)
          installer.post_install
        end

        # A default installation path to install a single gem. If the source
        # servers multiple gems, it's not of much use and the source should one
        # of its own.
        def install_path
          @install_path ||=
            begin
              base_name = File.basename(Bundler::URI.parse(uri).normalize.path)

              gem_install_dir.join("#{base_name}-#{uri_hash[0..11]}")
            end
        end

        # Parses the gemspec files to find the specs for the gems that can be
        # satisfied by the source.
        #
        # Few important points to keep in mind:
        #   - If the gems are not installed then it shall return specs for all
        #   the gems it can satisfy
        #   - If gem is installed (that is to be detected by the plugin itself)
        #   then it shall return at least the specs that are installed.
        #   - The `loaded_from` for each of the specs shall be correct (it is
        #   used to find the load path)
        #
        # @return [Bundler::Index] index containing the specs
        def specs
          files = fetch_gemspec_files

          Bundler::Index.build do |index|
            files.each do |file|
              next unless spec = Bundler.load_gemspec(file)
              Bundler.rubygems.set_installed_by_version(spec)

              spec.source = self
              Bundler.rubygems.validate(spec)

              index << spec
            end
          end
        end

        # Set internal representation to fetch the gems/specs locally.
        #
        # When this is called, the source should try to fetch the specs and
        # install from the local system.
        def local!
        end

        # Set internal representation to fetch the gems/specs from remote.
        #
        # When this is called, the source should try to fetch the specs and
        # install from remote path.
        def remote!
        end

        # Set internal representation to fetch the gems/specs from app cache.
        #
        # When this is called, the source should try to fetch the specs and
        # install from the path provided by `app_cache_path`.
        def cached!
        end

        # This is called to update the spec and installation.
        #
        # If the source plugin is loaded from lockfile or otherwise, it shall
        # refresh the cache/specs (e.g. git sources can make a fresh clone).
        def unlock!
        end

        # Name of directory where plugin the is expected to cache the gems when
        # #cache is called.
        #
        # Also this name is matched against the directories in cache for pruning
        #
        # This is used by `app_cache_path`
        def app_cache_dirname
          base_name = File.basename(Bundler::URI.parse(uri).normalize.path)
          "#{base_name}-#{uri_hash}"
        end

        # This method is called while caching to save copy of the gems that the
        # source can resolve to path provided by `app_cache_app`so that they can
        # be reinstalled from the cache without querying the remote (i.e. an
        # alternative to remote)
        #
        # This is stored with the app and source plugins should try to provide
        # specs and install only from this cache when `cached!` is called.
        #
        # This cache is different from the internal caching that can be done
        # at sub paths of `cache_path` (from API). This can be though as caching
        # by bundler.
        def cache(spec, custom_path = nil)
          new_cache_path = app_cache_path(custom_path)

          FileUtils.rm_rf(new_cache_path)
          FileUtils.cp_r(install_path, new_cache_path)
          FileUtils.touch(app_cache_path.join(".bundlecache"))
        end

        # This shall check if two source object represent the same source.
        #
        # The comparison shall take place only on the attribute that can be
        # inferred from the options passed from Gemfile and not on attributes
        # that are used to pin down the gem to specific version (e.g. Git
        # sources should compare on branch and tag but not on commit hash)
        #
        # The sources objects are constructed from Gemfile as well as from
        # lockfile. To converge the sources, it is necessary that they match.
        #
        # The same applies for `eql?` and `hash`
        def ==(other)
          other.is_a?(self.class) && uri == other.uri
        end

        # When overriding `eql?` please preserve the behaviour as mentioned in
        # docstring for `==` method.
        alias_method :eql?, :==

        # When overriding `hash` please preserve the behaviour as mentioned in
        # docstring for `==` method, i.e. two methods equal by above comparison
        # should have same hash.
        def hash
          [self.class, uri].hash
        end

        # A helper method, not necessary if not used internally.
        def installed?
          File.directory?(install_path)
        end

        # The full path where the plugin should cache the gem so that it can be
        # installed latter.
        #
        # Note: Do not override if you don't know what you are doing.
        def app_cache_path(custom_path = nil)
          @app_cache_path ||= Bundler.app_cache(custom_path).join(app_cache_dirname)
        end

        # Used by definition.
        #
        # Note: Do not override if you don't know what you are doing.
        def unmet_deps
          specs.unmet_dependency_names
        end

        # Used by definition.
        #
        # Note: Do not override if you don't know what you are doing.
        def spec_names
          specs.spec_names
        end

        # Used by definition.
        #
        # Note: Do not override if you don't know what you are doing.
        def add_dependency_names(names)
          @dependencies |= Array(names)
        end

        # Note: Do not override if you don't know what you are doing.
        def can_lock?(spec)
          spec.source == self
        end

        # Generates the content to be entered into the lockfile.
        # Saves type and remote and also calls to `options_to_lock`.
        #
        # Plugin should use `options_to_lock` to save information in lockfile
        # and not override this.
        #
        # Note: Do not override if you don't know what you are doing.
        def to_lock
          out = String.new("#{LockfileParser::PLUGIN}\n")
          out << "  remote: #{@uri}\n"
          out << "  type: #{@type}\n"
          options_to_lock.each do |opt, value|
            out << "  #{opt}: #{value}\n"
          end
          out << "  specs:\n"
        end

        def to_s
          "plugin source for #{@type} with uri #{@uri}"
        end
        alias_method :identifier, :to_s

        # Note: Do not override if you don't know what you are doing.
        def include?(other)
          other == self
        end

        def uri_hash
          SharedHelpers.digest(:SHA1).hexdigest(uri)
        end

        # Note: Do not override if you don't know what you are doing.
        def gem_install_dir
          Bundler.install_path
        end

        # It is used to obtain the full_gem_path.
        #
        # spec's loaded_from path is expanded against this to get full_gem_path
        #
        # Note: Do not override if you don't know what you are doing.
        def root
          Bundler.root
        end

        # @private
        # Returns true
        def bundler_plugin_api_source?
          true
        end

        # @private
        # This API on source might not be stable, and for now we expect plugins
        # to download all specs in `#specs`, so we implement the method for
        # compatibility purposes and leave it undocumented (and don't support)
        # overriding it)
        def double_check_for(*); end
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  module Plugin
    class Installer
      class Rubygems < Bundler::Source::Rubygems
        def version_message(spec)
          "#{spec.name} #{spec.version}"
        end

        private

        def requires_sudo?
          false # Will change on implementation of project level plugins
        end

        def rubygems_dir
          Plugin.root
        end

        def cache_path
          Plugin.cache
        end
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  module Plugin
    class Installer
      class Git < Bundler::Source::Git
        def cache_path
          @cache_path ||= begin
            git_scope = "#{base_name}-#{uri_hash}"

            Plugin.cache.join("bundler", "git", git_scope)
          end
        end

        def install_path
          @install_path ||= begin
            git_scope = "#{base_name}-#{shortref_for_path(revision)}"

            Plugin.root.join("bundler", "gems", git_scope)
          end
        end

        def version_message(spec)
          "#{spec.name} #{spec.version}"
        end

        def root
          Plugin.root
        end

        def generate_bin(spec, disable_extensions = false)
          # Need to find a way without code duplication
          # For now, we can ignore this
        end
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  # SourceList object to be used while parsing the Gemfile, setting the
  # approptiate options to be used with Source classes for plugin installation
  module Plugin
    class SourceList < Bundler::SourceList
      def add_git_source(options = {})
        add_source_to_list Plugin::Installer::Git.new(options), git_sources
      end

      def add_rubygems_source(options = {})
        add_source_to_list Plugin::Installer::Rubygems.new(options), @rubygems_sources
      end

      def all_sources
        path_sources + git_sources + rubygems_sources + [metadata_source]
      end

      def default_source
        git_sources.first || global_rubygems_source
      end

      private

      def rubygems_aggregate_class
        Plugin::Installer::Rubygems
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  module Plugin
    # Dsl to parse the Gemfile looking for plugins to install
    class DSL < Bundler::Dsl
      class PluginGemfileError < PluginError; end
      alias_method :_gem, :gem # To use for plugin installation as gem

      # So that we don't have to override all there methods to dummy ones
      # explicitly.
      # They will be handled by method_missing
      [:gemspec, :gem, :install_if, :platforms, :env].each {|m| undef_method m }

      # This lists the plugins that was added automatically and not specified by
      # the user.
      #
      # When we encounter :type attribute with a source block, we add a plugin
      # by name bundler-source-<type> to list of plugins to be installed.
      #
      # These plugins are optional and are not installed when there is conflict
      # with any other plugin.
      attr_reader :inferred_plugins

      def initialize
        super
        @sources = Plugin::SourceList.new
        @inferred_plugins = [] # The source plugins inferred from :type
      end

      def plugin(name, *args)
        _gem(name, *args)
      end

      def method_missing(name, *args)
        raise PluginGemfileError, "Undefined local variable or method `#{name}' for Gemfile" unless Bundler::Dsl.method_defined? name
      end

      def source(source, *args, &blk)
        options = args.last.is_a?(Hash) ? args.pop.dup : {}
        options = normalize_hash(options)
        return super unless options.key?("type")

        plugin_name = "bundler-source-#{options["type"]}"

        return if @dependencies.any? {|d| d.name == plugin_name }

        plugin(plugin_name)
        @inferred_plugins << plugin_name
      end
    end
  end
end
# frozen_string_literal: true

require "socket"

module Bundler
  class Settings
    # Class used to build the mirror set and then find a mirror for a given URI
    #
    # @param prober [Prober object, nil] by default a TCPSocketProbe, this object
    #   will be used to probe the mirror address to validate that the mirror replies.
    class Mirrors
      def initialize(prober = nil)
        @all = Mirror.new
        @prober = prober || TCPSocketProbe.new
        @mirrors = {}
      end

      # Returns a mirror for the given uri.
      #
      # Depending on the uri having a valid mirror or not, it may be a
      #   mirror that points to the provided uri
      def for(uri)
        if @all.validate!(@prober).valid?
          @all
        else
          fetch_valid_mirror_for(Settings.normalize_uri(uri))
        end
      end

      def each
        @mirrors.each do |k, v|
          yield k, v.uri.to_s
        end
      end

      def parse(key, value)
        config = MirrorConfig.new(key, value)
        mirror = if config.all?
          @all
        else
          @mirrors[config.uri] ||= Mirror.new
        end
        config.update_mirror(mirror)
      end

      private

      def fetch_valid_mirror_for(uri)
        downcased = uri.to_s.downcase
        mirror = @mirrors[downcased] || @mirrors[Bundler::URI(downcased).host] || Mirror.new(uri)
        mirror.validate!(@prober)
        mirror = Mirror.new(uri) unless mirror.valid?
        mirror
      end
    end

    # A mirror
    #
    # Contains both the uri that should be used as a mirror and the
    #   fallback timeout which will be used for probing if the mirror
    #   replies on time or not.
    class Mirror
      DEFAULT_FALLBACK_TIMEOUT = 0.1

      attr_reader :uri, :fallback_timeout

      def initialize(uri = nil, fallback_timeout = 0)
        self.uri = uri
        self.fallback_timeout = fallback_timeout
        @valid = nil
      end

      def uri=(uri)
        @uri = if uri.nil?
          nil
        else
          Bundler::URI(uri.to_s)
        end
        @valid = nil
      end

      def fallback_timeout=(timeout)
        case timeout
        when true, "true"
          @fallback_timeout = DEFAULT_FALLBACK_TIMEOUT
        when false, "false"
          @fallback_timeout = 0
        else
          @fallback_timeout = timeout.to_i
        end
        @valid = nil
      end

      def ==(other)
        !other.nil? && uri == other.uri && fallback_timeout == other.fallback_timeout
      end

      def valid?
        return false if @uri.nil?
        return @valid unless @valid.nil?
        false
      end

      def validate!(probe = nil)
        @valid = false if uri.nil?
        if @valid.nil?
          @valid = fallback_timeout == 0 || (probe || TCPSocketProbe.new).replies?(self)
        end
        self
      end
    end

    # Class used to parse one configuration line
    #
    # Gets the configuration line and the value.
    #   This object provides a `update_mirror` method
    #   used to setup the given mirror value.
    class MirrorConfig
      attr_accessor :uri, :value

      def initialize(config_line, value)
        uri, fallback =
          config_line.match(%r{\Amirror\.(all|.+?)(\.fallback_timeout)?\/?\z}).captures
        @fallback = !fallback.nil?
        @all = false
        if uri == "all"
          @all = true
        else
          @uri = Bundler::URI(uri).absolute? ? Settings.normalize_uri(uri) : uri
        end
        @value = value
      end

      def all?
        @all
      end

      def update_mirror(mirror)
        if @fallback
          mirror.fallback_timeout = @value
        else
          mirror.uri = Settings.normalize_uri(@value)
        end
      end
    end

    # Class used for probing TCP availability for a given mirror.
    class TCPSocketProbe
      def replies?(mirror)
        MirrorSockets.new(mirror).any? do |socket, address, timeout|
          begin
            socket.connect_nonblock(address)
          rescue Errno::EINPROGRESS
            wait_for_writtable_socket(socket, address, timeout)
          rescue RuntimeError # Connection failed somehow, again
            false
          end
        end
      end

      private

      def wait_for_writtable_socket(socket, address, timeout)
        if IO.select(nil, [socket], nil, timeout)
          probe_writtable_socket(socket, address)
        else # TCP Handshake timed out, or there is something dropping packets
          false
        end
      end

      def probe_writtable_socket(socket, address)
        socket.connect_nonblock(address)
      rescue Errno::EISCONN
        true
      rescue StandardError # Connection failed
        false
      end
    end
  end

  # Class used to build the list of sockets that correspond to
  #   a given mirror.
  #
  # One mirror may correspond to many different addresses, both
  #   because of it having many dns entries or because
  #   the network interface is both ipv4 and ipv5
  class MirrorSockets
    def initialize(mirror)
      @timeout = mirror.fallback_timeout
      @addresses = Socket.getaddrinfo(mirror.uri.host, mirror.uri.port).map do |address|
        SocketAddress.new(address[0], address[3], address[1])
      end
    end

    def any?
      @addresses.any? do |address|
        socket = Socket.new(Socket.const_get(address.type), Socket::SOCK_STREAM, 0)
        socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
        value = yield socket, address.to_socket_address, @timeout
        socket.close unless socket.closed?
        value
      end
    end
  end

  # Socket address builder.
  #
  # Given a socket type, a host and a port,
  #   provides a method to build sockaddr string
  class SocketAddress
    attr_reader :type, :host, :port

    def initialize(type, host, port)
      @type = type
      @host = host
      @port = port
    end

    def to_socket_address
      Socket.pack_sockaddr_in(@port, @host)
    end
  end
end
# frozen_string_literal: true

module Bundler; end
require_relative "vendor/molinillo/lib/molinillo"
# frozen_string_literal: true

module Bundler
  class LockfileParser
    attr_reader :sources, :dependencies, :specs, :platforms, :bundler_version, :ruby_version

    BUNDLED      = "BUNDLED WITH".freeze
    DEPENDENCIES = "DEPENDENCIES".freeze
    PLATFORMS    = "PLATFORMS".freeze
    RUBY         = "RUBY VERSION".freeze
    GIT          = "GIT".freeze
    GEM          = "GEM".freeze
    PATH         = "PATH".freeze
    PLUGIN       = "PLUGIN SOURCE".freeze
    SPECS        = "  specs:".freeze
    OPTIONS      = /^  ([a-z]+): (.*)$/i.freeze
    SOURCE       = [GIT, GEM, PATH, PLUGIN].freeze

    SECTIONS_BY_VERSION_INTRODUCED = {
      Gem::Version.create("1.0") => [DEPENDENCIES, PLATFORMS, GIT, GEM, PATH].freeze,
      Gem::Version.create("1.10") => [BUNDLED].freeze,
      Gem::Version.create("1.12") => [RUBY].freeze,
      Gem::Version.create("1.13") => [PLUGIN].freeze,
    }.freeze

    KNOWN_SECTIONS = SECTIONS_BY_VERSION_INTRODUCED.values.flatten.freeze

    ENVIRONMENT_VERSION_SECTIONS = [BUNDLED, RUBY].freeze

    def self.sections_in_lockfile(lockfile_contents)
      lockfile_contents.scan(/^\w[\w ]*$/).uniq
    end

    def self.unknown_sections_in_lockfile(lockfile_contents)
      sections_in_lockfile(lockfile_contents) - KNOWN_SECTIONS
    end

    def self.sections_to_ignore(base_version = nil)
      base_version &&= base_version.release
      base_version ||= Gem::Version.create("1.0".dup)
      attributes = []
      SECTIONS_BY_VERSION_INTRODUCED.each do |version, introduced|
        next if version <= base_version
        attributes += introduced
      end
      attributes
    end

    def initialize(lockfile)
      @platforms    = []
      @sources      = []
      @dependencies = {}
      @state        = nil
      @specs        = {}

      if lockfile.match(/<<<<<<<|=======|>>>>>>>|\|\|\|\|\|\|\|/)
        raise LockfileError, "Your #{Bundler.default_lockfile.relative_path_from(SharedHelpers.pwd)} contains merge conflicts.\n" \
          "Run `git checkout HEAD -- #{Bundler.default_lockfile.relative_path_from(SharedHelpers.pwd)}` first to get a clean lock."
      end

      lockfile.split(/(?:\r?\n)+/).each do |line|
        if SOURCE.include?(line)
          @state = :source
          parse_source(line)
        elsif line == DEPENDENCIES
          @state = :dependency
        elsif line == PLATFORMS
          @state = :platform
        elsif line == RUBY
          @state = :ruby
        elsif line == BUNDLED
          @state = :bundled_with
        elsif line =~ /^[^\s]/
          @state = nil
        elsif @state
          send("parse_#{@state}", line)
        end
      end
      @specs = @specs.values.sort_by(&:identifier)
      warn_for_outdated_bundler_version
    rescue ArgumentError => e
      Bundler.ui.debug(e)
      raise LockfileError, "Your lockfile is unreadable. Run `rm #{Bundler.default_lockfile.relative_path_from(SharedHelpers.pwd)}` " \
        "and then `bundle install` to generate a new lockfile."
    end

    def warn_for_outdated_bundler_version
      return unless bundler_version
      return if bundler_version.segments.last == "dev"
      prerelease_text = bundler_version.prerelease? ? " --pre" : ""
      current_version = Gem::Version.create(Bundler::VERSION)
      return unless current_version < bundler_version
      Bundler.ui.warn "Warning: the running version of Bundler (#{current_version}) is older " \
           "than the version that created the lockfile (#{bundler_version}). We suggest you to " \
           "upgrade to the version that created the lockfile by running `gem install " \
           "bundler:#{bundler_version}#{prerelease_text}`.\n"
    end

    private

    TYPES = {
      GIT    => Bundler::Source::Git,
      GEM    => Bundler::Source::Rubygems,
      PATH   => Bundler::Source::Path,
      PLUGIN => Bundler::Plugin,
    }.freeze

    def parse_source(line)
      case line
      when SPECS
        case @type
        when PATH
          @current_source = TYPES[@type].from_lock(@opts)
          @sources << @current_source
        when GIT
          @current_source = TYPES[@type].from_lock(@opts)
          @sources << @current_source
        when GEM
          @opts["remotes"] = Array(@opts.delete("remote")).reverse
          @current_source = TYPES[@type].from_lock(@opts)
          @sources << @current_source
        when PLUGIN
          @current_source = Plugin.source_from_lock(@opts)
          @sources << @current_source
        end
      when OPTIONS
        value = $2
        value = true if value == "true"
        value = false if value == "false"

        key = $1

        if @opts[key]
          @opts[key] = Array(@opts[key])
          @opts[key] << value
        else
          @opts[key] = value
        end
      when *SOURCE
        @current_source = nil
        @opts = {}
        @type = line
      else
        parse_spec(line)
      end
    end

    space = / /
    NAME_VERSION = /
      ^(#{space}{2}|#{space}{4}|#{space}{6})(?!#{space}) # Exactly 2, 4, or 6 spaces at the start of the line
      (.*?)                                              # Name
      (?:#{space}\(([^-]*)                               # Space, followed by version
      (?:-(.*))?\))?                                     # Optional platform
      (!)?                                               # Optional pinned marker
      $                                                  # Line end
    /xo.freeze

    def parse_dependency(line)
      return unless line =~ NAME_VERSION
      spaces = $1
      return unless spaces.size == 2
      name = $2
      version = $3
      pinned = $5

      version = version.split(",").map(&:strip) if version

      dep = Bundler::Dependency.new(name, version)

      if pinned && dep.name != "bundler"
        spec = @specs.find {|_, v| v.name == dep.name }
        dep.source = spec.last.source if spec

        # Path sources need to know what the default name / version
        # to use in the case that there are no gemspecs present. A fake
        # gemspec is created based on the version set on the dependency
        # TODO: Use the version from the spec instead of from the dependency
        if version && version.size == 1 && version.first =~ /^\s*= (.+)\s*$/ && dep.source.is_a?(Bundler::Source::Path)
          dep.source.name    = name
          dep.source.version = $1
        end
      end

      @dependencies[dep.name] = dep
    end

    def parse_spec(line)
      return unless line =~ NAME_VERSION
      spaces = $1
      name = $2
      version = $3
      platform = $4

      if spaces.size == 4
        version = Gem::Version.new(version)
        platform = platform ? Gem::Platform.new(platform) : Gem::Platform::RUBY
        @current_spec = LazySpecification.new(name, version, platform)
        @current_spec.source = @current_source
        @current_source.add_dependency_names(name)

        @specs[@current_spec.identifier] = @current_spec
      elsif spaces.size == 6
        version = version.split(",").map(&:strip) if version
        dep = Gem::Dependency.new(name, version)
        @current_spec.dependencies << dep
      end
    end

    def parse_platform(line)
      @platforms << Gem::Platform.new($1) if line =~ /^  (.*)$/
    end

    def parse_bundled_with(line)
      line = line.strip
      return unless Gem::Version.correct?(line)
      @bundler_version = Gem::Version.create(line)
    end

    def parse_ruby(line)
      @ruby_version = line.strip
    end
  end
end
# frozen_string_literal: true

require "pathname"
require "set"

module Bundler
  class CompactIndexClient
    DEBUG_MUTEX = Thread::Mutex.new
    def self.debug
      return unless ENV["DEBUG_COMPACT_INDEX"]
      DEBUG_MUTEX.synchronize { warn("[#{self}] #{yield}") }
    end

    class Error < StandardError; end

    require_relative "compact_index_client/cache"
    require_relative "compact_index_client/updater"

    attr_reader :directory

    def initialize(directory, fetcher)
      @directory = Pathname.new(directory)
      @updater = Updater.new(fetcher)
      @cache = Cache.new(@directory)
      @endpoints = Set.new
      @info_checksums_by_name = {}
      @parsed_checksums = false
      @mutex = Thread::Mutex.new
    end

    def execution_mode=(block)
      Bundler::CompactIndexClient.debug { "execution_mode=" }
      @endpoints = Set.new

      @execution_mode = block
    end

    # @return [Lambda] A lambda that takes an array of inputs and a block, and
    #         maps the inputs with the block in parallel.
    #
    def execution_mode
      @execution_mode || sequentially
    end

    def sequential_execution_mode!
      self.execution_mode = sequentially
    end

    def sequentially
      @sequentially ||= lambda do |inputs, &blk|
        inputs.map(&blk)
      end
    end

    def names
      Bundler::CompactIndexClient.debug { "/names" }
      update(@cache.names_path, "names")
      @cache.names
    end

    def versions
      Bundler::CompactIndexClient.debug { "/versions" }
      update(@cache.versions_path, "versions")
      versions, @info_checksums_by_name = @cache.versions
      versions
    end

    def dependencies(names)
      Bundler::CompactIndexClient.debug { "dependencies(#{names})" }
      execution_mode.call(names) do |name|
        update_info(name)
        @cache.dependencies(name).map {|d| d.unshift(name) }
      end.flatten(1)
    end

    def spec(name, version, platform = nil)
      Bundler::CompactIndexClient.debug { "spec(name = #{name}, version = #{version}, platform = #{platform})" }
      update_info(name)
      @cache.specific_dependency(name, version, platform)
    end

    def update_and_parse_checksums!
      Bundler::CompactIndexClient.debug { "update_and_parse_checksums!" }
      return @info_checksums_by_name if @parsed_checksums
      update(@cache.versions_path, "versions")
      @info_checksums_by_name = @cache.checksums
      @parsed_checksums = true
    end

    private

    def update(local_path, remote_path)
      Bundler::CompactIndexClient.debug { "update(#{local_path}, #{remote_path})" }
      unless synchronize { @endpoints.add?(remote_path) }
        Bundler::CompactIndexClient.debug { "already fetched #{remote_path}" }
        return
      end
      @updater.update(local_path, url(remote_path))
    end

    def update_info(name)
      Bundler::CompactIndexClient.debug { "update_info(#{name})" }
      path = @cache.info_path(name)
      checksum = @updater.checksum_for_file(path)
      unless existing = @info_checksums_by_name[name]
        Bundler::CompactIndexClient.debug { "skipping updating info for #{name} since it is missing from versions" }
        return
      end
      if checksum == existing
        Bundler::CompactIndexClient.debug { "skipping updating info for #{name} since the versions checksum matches the local checksum" }
        return
      end
      Bundler::CompactIndexClient.debug { "updating info for #{name} since the versions checksum #{existing} != the local checksum #{checksum}" }
      update(path, "info/#{name}")
    end

    def url(path)
      path
    end

    def synchronize
      @mutex.synchronize { yield }
    end
  end
end
# frozen_string_literal: true

require_relative "lockfile_parser"

module Bundler
  class Definition
    include GemHelpers

    attr_reader(
      :dependencies,
      :locked_deps,
      :locked_gems,
      :platforms,
      :requires,
      :ruby_version,
      :lockfile,
      :gemfiles
    )

    # Given a gemfile and lockfile creates a Bundler definition
    #
    # @param gemfile [Pathname] Path to Gemfile
    # @param lockfile [Pathname,nil] Path to Gemfile.lock
    # @param unlock [Hash, Boolean, nil] Gems that have been requested
    #   to be updated or true if all gems should be updated
    # @return [Bundler::Definition]
    def self.build(gemfile, lockfile, unlock)
      unlock ||= {}
      gemfile = Pathname.new(gemfile).expand_path

      raise GemfileNotFound, "#{gemfile} not found" unless gemfile.file?

      Dsl.evaluate(gemfile, lockfile, unlock)
    end

    #
    # How does the new system work?
    #
    # * Load information from Gemfile and Lockfile
    # * Invalidate stale locked specs
    #  * All specs from stale source are stale
    #  * All specs that are reachable only through a stale
    #    dependency are stale.
    # * If all fresh dependencies are satisfied by the locked
    #  specs, then we can try to resolve locally.
    #
    # @param lockfile [Pathname] Path to Gemfile.lock
    # @param dependencies [Array(Bundler::Dependency)] array of dependencies from Gemfile
    # @param sources [Bundler::SourceList]
    # @param unlock [Hash, Boolean, nil] Gems that have been requested
    #   to be updated or true if all gems should be updated
    # @param ruby_version [Bundler::RubyVersion, nil] Requested Ruby Version
    # @param optional_groups [Array(String)] A list of optional groups
    def initialize(lockfile, dependencies, sources, unlock, ruby_version = nil, optional_groups = [], gemfiles = [])
      if [true, false].include?(unlock)
        @unlocking_bundler = false
        @unlocking = unlock
      else
        @unlocking_bundler = unlock.delete(:bundler)
        @unlocking = unlock.any? {|_k, v| !Array(v).empty? }
      end

      @dependencies    = dependencies
      @sources         = sources
      @unlock          = unlock
      @optional_groups = optional_groups
      @remote          = false
      @specs           = nil
      @ruby_version    = ruby_version
      @gemfiles        = gemfiles

      @lockfile               = lockfile
      @lockfile_contents      = String.new
      @locked_bundler_version = nil
      @locked_ruby_version    = nil
      @new_platform = nil

      if lockfile && File.exist?(lockfile)
        @lockfile_contents = Bundler.read_file(lockfile)
        @locked_gems = LockfileParser.new(@lockfile_contents)
        @locked_platforms = @locked_gems.platforms
        @platforms = @locked_platforms.dup
        @locked_bundler_version = @locked_gems.bundler_version
        @locked_ruby_version = @locked_gems.ruby_version

        if unlock != true
          @locked_deps    = @locked_gems.dependencies
          @locked_specs   = SpecSet.new(@locked_gems.specs)
          @locked_sources = @locked_gems.sources
        else
          @unlock         = {}
          @locked_deps    = {}
          @locked_specs   = SpecSet.new([])
          @locked_sources = []
        end
      else
        @unlock         = {}
        @platforms      = []
        @locked_gems    = nil
        @locked_deps    = {}
        @locked_specs   = SpecSet.new([])
        @locked_sources = []
        @locked_platforms = []
      end

      locked_gem_sources = @locked_sources.select {|s| s.is_a?(Source::Rubygems) }
      @multisource_allowed = locked_gem_sources.size == 1 && locked_gem_sources.first.multiple_remotes? && Bundler.frozen_bundle?

      if @multisource_allowed
        unless sources.aggregate_global_source?
          msg = "Your lockfile contains a single rubygems source section with multiple remotes, which is insecure. Make sure you run `bundle install` in non frozen mode and commit the result to make your lockfile secure."

          Bundler::SharedHelpers.major_deprecation 2, msg
        end

        @sources.merged_gem_lockfile_sections!(locked_gem_sources.first)
      end

      @unlock[:sources] ||= []
      @unlock[:ruby] ||= if @ruby_version && locked_ruby_version_object
        @ruby_version.diff(locked_ruby_version_object)
      end
      @unlocking ||= @unlock[:ruby] ||= (!@locked_ruby_version ^ !@ruby_version)

      add_current_platform unless current_ruby_platform_locked? || Bundler.frozen_bundle?

      converge_path_sources_to_gemspec_sources
      @path_changes = converge_paths
      @source_changes = converge_sources

      if @unlock[:conservative]
        @unlock[:gems] ||= @dependencies.map(&:name)
      else
        eager_unlock = expand_dependencies(@unlock[:gems] || [], true)
        @unlock[:gems] = @locked_specs.for(eager_unlock, false, false).map(&:name)
      end

      @dependency_changes = converge_dependencies
      @local_changes = converge_locals

      @locked_specs_incomplete_for_platform = !@locked_specs.for(requested_dependencies & expand_dependencies(locked_dependencies), true, true)

      @requires = compute_requires
    end

    def gem_version_promoter
      @gem_version_promoter ||= begin
        locked_specs =
          if unlocking? && @locked_specs.empty? && !@lockfile_contents.empty?
            # Definition uses an empty set of locked_specs to indicate all gems
            # are unlocked, but GemVersionPromoter needs the locked_specs
            # for conservative comparison.
            Bundler::SpecSet.new(@locked_gems.specs)
          else
            @locked_specs
          end
        GemVersionPromoter.new(locked_specs, @unlock[:gems])
      end
    end

    def resolve_only_locally!
      @remote = false
      sources.local_only!
      resolve
    end

    def resolve_with_cache!
      sources.cached!
      resolve
    end

    def resolve_remotely!
      @remote = true
      sources.remote!
      resolve
    end

    # For given dependency list returns a SpecSet with Gemspec of all the required
    # dependencies.
    #  1. The method first resolves the dependencies specified in Gemfile
    #  2. After that it tries and fetches gemspec of resolved dependencies
    #
    # @return [Bundler::SpecSet]
    def specs
      @specs ||= materialize(requested_dependencies)
    end

    def new_specs
      specs - @locked_specs
    end

    def removed_specs
      @locked_specs - specs
    end

    def missing_specs
      resolve.materialize(requested_dependencies).missing_specs
    end

    def missing_specs?
      missing = missing_specs
      return false if missing.empty?
      Bundler.ui.debug "The definition is missing #{missing.map(&:full_name)}"
      true
    rescue BundlerError => e
      @resolve = nil
      @specs = nil
      @gem_version_promoter = nil

      Bundler.ui.debug "The definition is missing dependencies, failed to resolve & materialize locally (#{e})"
      true
    end

    def requested_specs
      specs_for(requested_groups)
    end

    def requested_dependencies
      dependencies_for(requested_groups)
    end

    def current_dependencies
      dependencies.select do |d|
        d.should_include? && !d.gem_platforms(@platforms).empty?
      end
    end

    def locked_dependencies
      @locked_deps.values
    end

    def specs_for(groups)
      return specs if groups.empty?
      deps = dependencies_for(groups)
      materialize(deps)
    end

    def dependencies_for(groups)
      groups.map!(&:to_sym)
      deps = current_dependencies.reject do |d|
        (d.groups & groups).empty?
      end
      expand_dependencies(deps)
    end

    # Resolve all the dependencies specified in Gemfile. It ensures that
    # dependencies that have been already resolved via locked file and are fresh
    # are reused when resolving dependencies
    #
    # @return [SpecSet] resolved dependencies
    def resolve
      @resolve ||= begin
        last_resolve = converge_locked_specs
        if Bundler.frozen_bundle?
          Bundler.ui.debug "Frozen, using resolution from the lockfile"
          last_resolve
        elsif !unlocking? && nothing_changed?
          Bundler.ui.debug("Found no changes, using resolution from the lockfile")
          last_resolve
        else
          # Run a resolve against the locally available gems
          Bundler.ui.debug("Found changes from the lockfile, re-resolving dependencies because #{change_reason}")
          expanded_dependencies = expand_dependencies(dependencies + metadata_dependencies, @remote)
          Resolver.resolve(expanded_dependencies, source_requirements, last_resolve, gem_version_promoter, additional_base_requirements_for_resolve, platforms)
        end
      end
    end

    def spec_git_paths
      sources.git_sources.map {|s| File.realpath(s.path) if File.exist?(s.path) }.compact
    end

    def groups
      dependencies.map(&:groups).flatten.uniq
    end

    def lock(file, preserve_unknown_sections = false)
      contents = to_lock

      # Convert to \r\n if the existing lock has them
      # i.e., Windows with `git config core.autocrlf=true`
      contents.gsub!(/\n/, "\r\n") if @lockfile_contents.match("\r\n")

      if @locked_bundler_version
        locked_major = @locked_bundler_version.segments.first
        current_major = Gem::Version.create(Bundler::VERSION).segments.first

        if updating_major = locked_major < current_major
          Bundler.ui.warn "Warning: the lockfile is being updated to Bundler #{current_major}, " \
                          "after which you will be unable to return to Bundler #{@locked_bundler_version.segments.first}."
        end
      end

      preserve_unknown_sections ||= !updating_major && (Bundler.frozen_bundle? || !(unlocking? || @unlocking_bundler))

      return if file && File.exist?(file) && lockfiles_equal?(@lockfile_contents, contents, preserve_unknown_sections)

      if Bundler.frozen_bundle?
        Bundler.ui.error "Cannot write a changed lockfile while frozen."
        return
      end

      SharedHelpers.filesystem_access(file) do |p|
        File.open(p, "wb") {|f| f.puts(contents) }
      end
    end

    def locked_bundler_version
      if @locked_bundler_version && @locked_bundler_version < Gem::Version.new(Bundler::VERSION)
        new_version = Bundler::VERSION
      end

      new_version || @locked_bundler_version || Bundler::VERSION
    end

    def locked_ruby_version
      return unless ruby_version
      if @unlock[:ruby] || !@locked_ruby_version
        Bundler::RubyVersion.system
      else
        @locked_ruby_version
      end
    end

    def locked_ruby_version_object
      return unless @locked_ruby_version
      @locked_ruby_version_object ||= begin
        unless version = RubyVersion.from_string(@locked_ruby_version)
          raise LockfileError, "The Ruby version #{@locked_ruby_version} from " \
            "#{@lockfile} could not be parsed. " \
            "Try running bundle update --ruby to resolve this."
        end
        version
      end
    end

    def to_lock
      require_relative "lockfile_generator"
      LockfileGenerator.generate(self)
    end

    def ensure_equivalent_gemfile_and_lockfile(explicit_flag = false)
      msg = String.new
      msg << "You are trying to install in deployment mode after changing\n" \
             "your Gemfile. Run `bundle install` elsewhere and add the\n" \
             "updated #{Bundler.default_lockfile.relative_path_from(SharedHelpers.pwd)} to version control."

      unless explicit_flag
        suggested_command = if Bundler.settings.locations("frozen").keys.&([:global, :local]).any?
          "bundle config unset frozen"
        elsif Bundler.settings.locations("deployment").keys.&([:global, :local]).any?
          "bundle config unset deployment"
        end
        msg << "\n\nIf this is a development machine, remove the #{Bundler.default_gemfile} " \
               "freeze \nby running `#{suggested_command}`."
      end

      added =   []
      deleted = []
      changed = []

      new_platforms = @platforms - @locked_platforms
      deleted_platforms = @locked_platforms - @platforms
      added.concat new_platforms.map {|p| "* platform: #{p}" }
      deleted.concat deleted_platforms.map {|p| "* platform: #{p}" }

      new_deps = @dependencies - locked_dependencies
      deleted_deps = locked_dependencies - @dependencies

      added.concat new_deps.map {|d| "* #{pretty_dep(d)}" } if new_deps.any?
      deleted.concat deleted_deps.map {|d| "* #{pretty_dep(d)}" } if deleted_deps.any?

      both_sources = Hash.new {|h, k| h[k] = [] }
      @dependencies.each {|d| both_sources[d.name][0] = d }
      locked_dependencies.each {|d| both_sources[d.name][1] = d }

      both_sources.each do |name, (dep, lock_dep)|
        next if dep.nil? || lock_dep.nil?

        gemfile_source = dep.source || sources.default_source
        lock_source = lock_dep.source || sources.default_source
        next if lock_source.include?(gemfile_source)

        gemfile_source_name = dep.source ? gemfile_source.identifier : "no specified source"
        lockfile_source_name = lock_dep.source ? lock_source.identifier : "no specified source"
        changed << "* #{name} from `#{lockfile_source_name}` to `#{gemfile_source_name}`"
      end

      reason = change_reason
      msg << "\n\n#{reason.split(", ").map(&:capitalize).join("\n")}" unless reason.strip.empty?
      msg << "\n\nYou have added to the Gemfile:\n" << added.join("\n") if added.any?
      msg << "\n\nYou have deleted from the Gemfile:\n" << deleted.join("\n") if deleted.any?
      msg << "\n\nYou have changed in the Gemfile:\n" << changed.join("\n") if changed.any?
      msg << "\n"

      raise ProductionError, msg if added.any? || deleted.any? || changed.any? || !nothing_changed?
    end

    def validate_runtime!
      validate_ruby!
      validate_platforms!
    end

    def validate_ruby!
      return unless ruby_version

      if diff = ruby_version.diff(Bundler::RubyVersion.system)
        problem, expected, actual = diff

        msg = case problem
              when :engine
                "Your Ruby engine is #{actual}, but your Gemfile specified #{expected}"
              when :version
                "Your Ruby version is #{actual}, but your Gemfile specified #{expected}"
              when :engine_version
                "Your #{Bundler::RubyVersion.system.engine} version is #{actual}, but your Gemfile specified #{ruby_version.engine} #{expected}"
              when :patchlevel
                if !expected.is_a?(String)
                  "The Ruby patchlevel in your Gemfile must be a string"
                else
                  "Your Ruby patchlevel is #{actual}, but your Gemfile specified #{expected}"
                end
        end

        raise RubyVersionMismatch, msg
      end
    end

    def validate_platforms!
      return if current_platform_locked?

      raise ProductionError, "Your bundle only supports platforms #{@platforms.map(&:to_s)} " \
        "but your local platform is #{Bundler.local_platform}. " \
        "Add the current platform to the lockfile with `bundle lock --add-platform #{Bundler.local_platform}` and try again."
    end

    def add_platform(platform)
      @new_platform ||= !@platforms.include?(platform)
      @platforms |= [platform]
    end

    def remove_platform(platform)
      return if @platforms.delete(Gem::Platform.new(platform))
      raise InvalidOption, "Unable to remove the platform `#{platform}` since the only platforms are #{@platforms.join ", "}"
    end

    def most_specific_locked_platform
      @platforms.min_by do |bundle_platform|
        platform_specificity_match(bundle_platform, local_platform)
      end
    end

    attr_reader :sources
    private :sources

    def nothing_changed?
      !@source_changes && !@dependency_changes && !@new_platform && !@path_changes && !@local_changes && !@locked_specs_incomplete_for_platform
    end

    def unlocking?
      @unlocking
    end

    private

    def materialize(dependencies)
      specs = resolve.materialize(dependencies)
      missing_specs = specs.missing_specs

      if missing_specs.any?
        missing_specs.each do |s|
          locked_gem = @locked_specs[s.name].last
          next if locked_gem.nil? || locked_gem.version != s.version || !@remote
          raise GemNotFound, "Your bundle is locked to #{locked_gem} from #{locked_gem.source}, but that version can " \
                             "no longer be found in that source. That means the author of #{locked_gem} has removed it. " \
                             "You'll need to update your bundle to a version other than #{locked_gem} that hasn't been " \
                             "removed in order to install."
        end

        raise GemNotFound, "Could not find #{missing_specs.map(&:full_name).join(", ")} in any of the sources"
      end

      unless specs["bundler"].any?
        bundler = sources.metadata_source.specs.search(Gem::Dependency.new("bundler", VERSION)).last
        specs["bundler"] = bundler
      end

      specs
    end

    def precompute_source_requirements_for_indirect_dependencies?
      @remote && sources.non_global_rubygems_sources.all?(&:dependency_api_available?) && !sources.aggregate_global_source?
    end

    def current_ruby_platform_locked?
      return false unless generic_local_platform == Gem::Platform::RUBY

      current_platform_locked?
    end

    def current_platform_locked?
      @platforms.any? do |bundle_platform|
        MatchPlatform.platforms_match?(bundle_platform, Bundler.local_platform)
      end
    end

    def add_current_platform
      add_platform(local_platform)
    end

    def change_reason
      if unlocking?
        unlock_reason = @unlock.reject {|_k, v| Array(v).empty? }.map do |k, v|
          if v == true
            k.to_s
          else
            v = Array(v)
            "#{k}: (#{v.join(", ")})"
          end
        end.join(", ")
        return "bundler is unlocking #{unlock_reason}"
      end
      [
        [@source_changes, "the list of sources changed"],
        [@dependency_changes, "the dependencies in your gemfile changed"],
        [@new_platform, "you added a new platform to your gemfile"],
        [@path_changes, "the gemspecs for path gems changed"],
        [@local_changes, "the gemspecs for git local gems changed"],
        [@locked_specs_incomplete_for_platform, "the lockfile does not have all gems needed for the current platform"],
      ].select(&:first).map(&:last).join(", ")
    end

    def pretty_dep(dep, source = false)
      SharedHelpers.pretty_dependency(dep, source)
    end

    # Check if the specs of the given source changed
    # according to the locked source.
    def specs_changed?(source)
      locked = @locked_sources.find {|s| s == source }

      !locked || dependencies_for_source_changed?(source, locked) || specs_for_source_changed?(source)
    end

    def dependencies_for_source_changed?(source, locked_source = source)
      deps_for_source = @dependencies.select {|s| s.source == source }
      locked_deps_for_source = locked_dependencies.select {|dep| dep.source == locked_source }

      deps_for_source.uniq.sort != locked_deps_for_source.sort
    end

    def specs_for_source_changed?(source)
      locked_index = Index.new
      locked_index.use(@locked_specs.select {|s| source.can_lock?(s) })

      # order here matters, since Index#== is checking source.specs.include?(locked_index)
      locked_index != source.specs
    rescue PathError, GitError => e
      Bundler.ui.debug "Assuming that #{source} has not changed since fetching its specs errored (#{e})"
      false
    end

    # Get all locals and override their matching sources.
    # Return true if any of the locals changed (for example,
    # they point to a new revision) or depend on new specs.
    def converge_locals
      locals = []

      Bundler.settings.local_overrides.map do |k, v|
        spec   = @dependencies.find {|s| s.name == k }
        source = spec && spec.source
        if source && source.respond_to?(:local_override!)
          source.unlock! if @unlock[:gems].include?(spec.name)
          locals << [source, source.local_override!(v)]
        end
      end

      sources_with_changes = locals.select do |source, changed|
        changed || specs_changed?(source)
      end.map(&:first)
      !sources_with_changes.each {|source| @unlock[:sources] << source.name }.empty?
    end

    def converge_paths
      sources.path_sources.any? do |source|
        specs_changed?(source)
      end
    end

    def converge_path_source_to_gemspec_source(source)
      return source unless source.instance_of?(Source::Path)
      gemspec_source = sources.path_sources.find {|s| s.is_a?(Source::Gemspec) && s.as_path_source == source }
      gemspec_source || source
    end

    def converge_path_sources_to_gemspec_sources
      @locked_sources.map! do |source|
        converge_path_source_to_gemspec_source(source)
      end
      @locked_specs.each do |spec|
        spec.source &&= converge_path_source_to_gemspec_source(spec.source)
      end
      @locked_deps.each do |_, dep|
        dep.source &&= converge_path_source_to_gemspec_source(dep.source)
      end
    end

    def converge_sources
      # Replace the sources from the Gemfile with the sources from the Gemfile.lock,
      # if they exist in the Gemfile.lock and are `==`. If you can't find an equivalent
      # source in the Gemfile.lock, use the one from the Gemfile.
      changes = sources.replace_sources!(@locked_sources)

      sources.all_sources.each do |source|
        # If the source is unlockable and the current command allows an unlock of
        # the source (for example, you are doing a `bundle update <foo>` of a git-pinned
        # gem), unlock it. For git sources, this means to unlock the revision, which
        # will cause the `ref` used to be the most recent for the branch (or master) if
        # an explicit `ref` is not used.
        if source.respond_to?(:unlock!) && @unlock[:sources].include?(source.name)
          source.unlock!
          changes = true
        end
      end

      changes
    end

    def converge_dependencies
      changes = false

      @dependencies.each do |dep|
        if dep.source
          dep.source = sources.get(dep.source)
        end

        unless locked_dep = @locked_deps[dep.name]
          changes = true
          next
        end

        # Gem::Dependency#== matches Gem::Dependency#type. As the lockfile
        # doesn't carry a notion of the dependency type, if you use
        # add_development_dependency in a gemspec that's loaded with the gemspec
        # directive, the lockfile dependencies and resolved dependencies end up
        # with a mismatch on #type. Work around that by setting the type on the
        # dep from the lockfile.
        locked_dep.instance_variable_set(:@type, dep.type)

        # We already know the name matches from the hash lookup
        # so we only need to check the requirement now
        changes ||= dep.requirement != locked_dep.requirement
      end

      changes
    end

    # Remove elements from the locked specs that are expired. This will most
    # commonly happen if the Gemfile has changed since the lockfile was last
    # generated
    def converge_locked_specs
      resolve = converge_specs(@locked_specs)

      diff = nil

      # Now, we unlock any sources that do not have anymore gems pinned to it
      sources.all_sources.each do |source|
        next unless source.respond_to?(:unlock!)

        unless resolve.any? {|s| s.source == source }
          diff ||= @locked_specs.to_a - resolve.to_a
          source.unlock! if diff.any? {|s| s.source == source }
        end
      end

      resolve
    end

    def converge_specs(specs)
      deps = []
      converged = []
      specs.each do |s|
        # Replace the locked dependency's source with the equivalent source from the Gemfile
        dep = @dependencies.find {|d| s.satisfies?(d) }

        if dep && (!dep.source || s.source.include?(dep.source))
          deps << dep
        end

        s.source = (dep && dep.source) || sources.get(s.source) || sources.default_source unless Bundler.frozen_bundle?

        next if @unlock[:sources].include?(s.source.name)

        # If the spec is from a path source and it doesn't exist anymore
        # then we unlock it.

        # Path sources have special logic
        if s.source.instance_of?(Source::Path) || s.source.instance_of?(Source::Gemspec)
          new_specs = begin
            s.source.specs
          rescue PathError, GitError
            # if we won't need the source (according to the lockfile),
            # don't error if the path/git source isn't available
            next if specs.
                    for(requested_dependencies, false, true).
                    none? {|locked_spec| locked_spec.source == s.source }

            raise
          end

          new_spec = new_specs[s].first

          # If the spec is no longer in the path source, unlock it. This
          # commonly happens if the version changed in the gemspec
          next unless new_spec

          s.dependencies.replace(new_spec.dependencies)
        end

        if dep.nil? && requested_dependencies.find {|d| s.name == d.name }
          @unlock[:gems] << s.name
        else
          converged << s
        end
      end

      resolve = SpecSet.new(converged)
      SpecSet.new(resolve.for(expand_dependencies(deps, true), false, false).reject{|s| @unlock[:gems].include?(s.name) })
    end

    def metadata_dependencies
      @metadata_dependencies ||= begin
        ruby_versions = ruby_version_requirements(@ruby_version)
        [
          Dependency.new("Ruby\0", ruby_versions),
          Dependency.new("RubyGems\0", Gem::VERSION),
        ]
      end
    end

    def ruby_version_requirements(ruby_version)
      return [] unless ruby_version
      if ruby_version.patchlevel
        [ruby_version.to_gem_version_with_patchlevel]
      else
        ruby_version.versions.map do |version|
          requirement = Gem::Requirement.new(version)
          if requirement.exact?
            "~> #{version}.0"
          else
            requirement
          end
        end
      end
    end

    def expand_dependencies(dependencies, remote = false)
      deps = []
      dependencies.each do |dep|
        dep = Dependency.new(dep, ">= 0") unless dep.respond_to?(:name)
        next unless remote || dep.current_platform?
        target_platforms = dep.gem_platforms(remote ? @platforms : [generic_local_platform])
        deps += expand_dependency_with_platforms(dep, target_platforms)
      end
      deps
    end

    def expand_dependency_with_platforms(dep, platforms)
      platforms.map do |p|
        DepProxy.get_proxy(dep, p)
      end
    end

    def source_requirements
      # Record the specs available in each gem's source, so that those
      # specs will be available later when the resolver knows where to
      # look for that gemspec (or its dependencies)
      source_requirements = if precompute_source_requirements_for_indirect_dependencies?
        { :default => sources.default_source }.merge(source_map.all_requirements)
      else
        { :default => Source::RubygemsAggregate.new(sources, source_map) }.merge(source_map.direct_requirements)
      end
      metadata_dependencies.each do |dep|
        source_requirements[dep.name] = sources.metadata_source
      end
      source_requirements[:default_bundler] = source_requirements["bundler"] || sources.default_source
      source_requirements["bundler"] = sources.metadata_source # needs to come last to override
      source_requirements
    end

    def requested_groups
      groups - Bundler.settings[:without] - @optional_groups + Bundler.settings[:with]
    end

    def lockfiles_equal?(current, proposed, preserve_unknown_sections)
      if preserve_unknown_sections
        sections_to_ignore = LockfileParser.sections_to_ignore(@locked_bundler_version)
        sections_to_ignore += LockfileParser.unknown_sections_in_lockfile(current)
        sections_to_ignore += LockfileParser::ENVIRONMENT_VERSION_SECTIONS
        pattern = /#{Regexp.union(sections_to_ignore)}\n(\s{2,}.*\n)+/
        whitespace_cleanup = /\n{2,}/
        current = current.gsub(pattern, "\n").gsub(whitespace_cleanup, "\n\n").strip
        proposed = proposed.gsub(pattern, "\n").gsub(whitespace_cleanup, "\n\n").strip
      end
      current == proposed
    end

    def compute_requires
      dependencies.reduce({}) do |requires, dep|
        next requires unless dep.should_include?
        requires[dep.name] = Array(dep.autorequire || dep.name).map do |file|
          # Allow `require: true` as an alias for `require: <name>`
          file == true ? dep.name : file
        end
        requires
      end
    end

    def additional_base_requirements_for_resolve
      return [] unless @locked_gems && unlocking? && !sources.expired_sources?(@locked_gems.sources)
      converge_specs(@locked_gems.specs).map do |locked_spec|
        name = locked_spec.name
        dep = Gem::Dependency.new(name, ">= #{locked_spec.version}")
        DepProxy.get_proxy(dep, locked_spec.platform)
      end
    end

    def source_map
      @source_map ||= SourceMap.new(sources, dependencies)
    end
  end
end
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-DOCTOR" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-doctor\fR \- Checks the bundle for common problems
.
.SH "SYNOPSIS"
\fBbundle doctor\fR [\-\-quiet] [\-\-gemfile=GEMFILE]
.
.SH "DESCRIPTION"
Checks your Gemfile and gem environment for common problems\. If issues are detected, Bundler prints them and exits status 1\. Otherwise, Bundler prints a success message and exits status 0\.
.
.P
Examples of common problems caught by bundle\-doctor include:
.
.IP "\(bu" 4
Invalid Bundler settings
.
.IP "\(bu" 4
Mismatched Ruby versions
.
.IP "\(bu" 4
Mismatched platforms
.
.IP "\(bu" 4
Uninstalled gems
.
.IP "\(bu" 4
Missing dependencies
.
.IP "" 0
.
.SH "OPTIONS"
.
.TP
\fB\-\-quiet\fR
Only output warnings and errors\.
.
.TP
\fB\-\-gemfile=<gemfile>\fR
The location of the Gemfile(5) which Bundler should use\. This defaults to a Gemfile(5) in the current working directory\. In general, Bundler will assume that the location of the Gemfile(5) is also the project\'s root and will try to find \fBGemfile\.lock\fR and \fBvendor/cache\fR relative to this location\.

bundle-viz(1) -- Generates a visual dependency graph for your Gemfile
=====================================================================

## SYNOPSIS

`bundle viz` [--file=FILE]
             [--format=FORMAT]
             [--requirements]
             [--version]
             [--without=GROUP GROUP]

## DESCRIPTION

`viz` generates a PNG file of the current `Gemfile(5)` as a dependency graph.
`viz` requires the ruby-graphviz gem (and its dependencies).

The associated gems must also be installed via [`bundle install(1)`](bundle-install.1.html).

## OPTIONS

* `--file`, `-f`:
  The name to use for the generated file. See `--format` option
* `--format`, `-F`:
  This is output format option. Supported format is png, jpg, svg, dot ...
* `--requirements`, `-R`:
  Set to show the version of each required dependency.
* `--version`, `-v`:
  Set to show each gem version.
* `--without`, `-W`:
  Exclude gems that are part of the specified named group.
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-UPDATE" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-update\fR \- Update your gems to the latest available versions
.
.SH "SYNOPSIS"
\fBbundle update\fR \fI*gems\fR [\-\-all] [\-\-group=NAME] [\-\-source=NAME] [\-\-local] [\-\-ruby] [\-\-bundler[=VERSION]] [\-\-full\-index] [\-\-jobs=JOBS] [\-\-quiet] [\-\-patch|\-\-minor|\-\-major] [\-\-redownload] [\-\-strict] [\-\-conservative]
.
.SH "DESCRIPTION"
Update the gems specified (all gems, if \fB\-\-all\fR flag is used), ignoring the previously installed gems specified in the \fBGemfile\.lock\fR\. In general, you should use bundle install(1) \fIbundle\-install\.1\.html\fR to install the same exact gems and versions across machines\.
.
.P
You would use \fBbundle update\fR to explicitly update the version of a gem\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-all\fR
Update all gems specified in Gemfile\.
.
.TP
\fB\-\-group=<name>\fR, \fB\-g=[<name>]\fR
Only update the gems in the specified group\. For instance, you can update all gems in the development group with \fBbundle update \-\-group development\fR\. You can also call \fBbundle update rails \-\-group test\fR to update the rails gem and all gems in the test group, for example\.
.
.TP
\fB\-\-source=<name>\fR
The name of a \fB:git\fR or \fB:path\fR source used in the Gemfile(5)\. For instance, with a \fB:git\fR source of \fBhttp://github\.com/rails/rails\.git\fR, you would call \fBbundle update \-\-source rails\fR
.
.TP
\fB\-\-local\fR
Do not attempt to fetch gems remotely and use the gem cache instead\.
.
.TP
\fB\-\-ruby\fR
Update the locked version of Ruby to the current version of Ruby\.
.
.TP
\fB\-\-bundler\fR
Update the locked version of bundler to the invoked bundler version\.
.
.TP
\fB\-\-full\-index\fR
Fall back to using the single\-file index of all gems\.
.
.TP
\fB\-\-jobs=[<number>]\fR, \fB\-j[<number>]\fR
Specify the number of jobs to run in parallel\. The default is \fB1\fR\.
.
.TP
\fB\-\-retry=[<number>]\fR
Retry failed network or git requests for \fInumber\fR times\.
.
.TP
\fB\-\-quiet\fR
Only output warnings and errors\.
.
.TP
\fB\-\-redownload\fR
Force downloading every gem\.
.
.TP
\fB\-\-patch\fR
Prefer updating only to next patch version\.
.
.TP
\fB\-\-minor\fR
Prefer updating only to next minor version\.
.
.TP
\fB\-\-major\fR
Prefer updating to next major version (default)\.
.
.TP
\fB\-\-strict\fR
Do not allow any gem to be updated past latest \fB\-\-patch\fR | \fB\-\-minor\fR | \fB\-\-major\fR\.
.
.TP
\fB\-\-conservative\fR
Use bundle install conservative update behavior and do not allow indirect dependencies to be updated\.
.
.SH "UPDATING ALL GEMS"
If you run \fBbundle update \-\-all\fR, bundler will ignore any previously installed gems and resolve all dependencies again based on the latest versions of all gems available in the sources\.
.
.P
Consider the following Gemfile(5):
.
.IP "" 4
.
.nf

source "https://rubygems\.org"

gem "rails", "3\.0\.0\.rc"
gem "nokogiri"
.
.fi
.
.IP "" 0
.
.P
When you run bundle install(1) \fIbundle\-install\.1\.html\fR the first time, bundler will resolve all of the dependencies, all the way down, and install what you need:
.
.IP "" 4
.
.nf

Fetching gem metadata from https://rubygems\.org/\.\.\.\.\.\.\.\.\.
Resolving dependencies\.\.\.
Installing builder 2\.1\.2
Installing abstract 1\.0\.0
Installing rack 1\.2\.8
Using bundler 1\.7\.6
Installing rake 10\.4\.0
Installing polyglot 0\.3\.5
Installing mime\-types 1\.25\.1
Installing i18n 0\.4\.2
Installing mini_portile 0\.6\.1
Installing tzinfo 0\.3\.42
Installing rack\-mount 0\.6\.14
Installing rack\-test 0\.5\.7
Installing treetop 1\.4\.15
Installing thor 0\.14\.6
Installing activesupport 3\.0\.0\.rc
Installing erubis 2\.6\.6
Installing activemodel 3\.0\.0\.rc
Installing arel 0\.4\.0
Installing mail 2\.2\.20
Installing activeresource 3\.0\.0\.rc
Installing actionpack 3\.0\.0\.rc
Installing activerecord 3\.0\.0\.rc
Installing actionmailer 3\.0\.0\.rc
Installing railties 3\.0\.0\.rc
Installing rails 3\.0\.0\.rc
Installing nokogiri 1\.6\.5

Bundle complete! 2 Gemfile dependencies, 26 gems total\.
Use `bundle show [gemname]` to see where a bundled gem is installed\.
.
.fi
.
.IP "" 0
.
.P
As you can see, even though you have two gems in the Gemfile(5), your application needs 26 different gems in order to run\. Bundler remembers the exact versions it installed in \fBGemfile\.lock\fR\. The next time you run bundle install(1) \fIbundle\-install\.1\.html\fR, bundler skips the dependency resolution and installs the same gems as it installed last time\.
.
.P
After checking in the \fBGemfile\.lock\fR into version control and cloning it on another machine, running bundle install(1) \fIbundle\-install\.1\.html\fR will \fIstill\fR install the gems that you installed last time\. You don\'t need to worry that a new release of \fBerubis\fR or \fBmail\fR changes the gems you use\.
.
.P
However, from time to time, you might want to update the gems you are using to the newest versions that still match the gems in your Gemfile(5)\.
.
.P
To do this, run \fBbundle update \-\-all\fR, which will ignore the \fBGemfile\.lock\fR, and resolve all the dependencies again\. Keep in mind that this process can result in a significantly different set of the 25 gems, based on the requirements of new gems that the gem authors released since the last time you ran \fBbundle update \-\-all\fR\.
.
.SH "UPDATING A LIST OF GEMS"
Sometimes, you want to update a single gem in the Gemfile(5), and leave the rest of the gems that you specified locked to the versions in the \fBGemfile\.lock\fR\.
.
.P
For instance, in the scenario above, imagine that \fBnokogiri\fR releases version \fB1\.4\.4\fR, and you want to update it \fIwithout\fR updating Rails and all of its dependencies\. To do this, run \fBbundle update nokogiri\fR\.
.
.P
Bundler will update \fBnokogiri\fR and any of its dependencies, but leave alone Rails and its dependencies\.
.
.SH "OVERLAPPING DEPENDENCIES"
Sometimes, multiple gems declared in your Gemfile(5) are satisfied by the same second\-level dependency\. For instance, consider the case of \fBthin\fR and \fBrack\-perftools\-profiler\fR\.
.
.IP "" 4
.
.nf

source "https://rubygems\.org"

gem "thin"
gem "rack\-perftools\-profiler"
.
.fi
.
.IP "" 0
.
.P
The \fBthin\fR gem depends on \fBrack >= 1\.0\fR, while \fBrack\-perftools\-profiler\fR depends on \fBrack ~> 1\.0\fR\. If you run bundle install, you get:
.
.IP "" 4
.
.nf

Fetching source index for https://rubygems\.org/
Installing daemons (1\.1\.0)
Installing eventmachine (0\.12\.10) with native extensions
Installing open4 (1\.0\.1)
Installing perftools\.rb (0\.4\.7) with native extensions
Installing rack (1\.2\.1)
Installing rack\-perftools_profiler (0\.0\.2)
Installing thin (1\.2\.7) with native extensions
Using bundler (1\.0\.0\.rc\.3)
.
.fi
.
.IP "" 0
.
.P
In this case, the two gems have their own set of dependencies, but they share \fBrack\fR in common\. If you run \fBbundle update thin\fR, bundler will update \fBdaemons\fR, \fBeventmachine\fR and \fBrack\fR, which are dependencies of \fBthin\fR, but not \fBopen4\fR or \fBperftools\.rb\fR, which are dependencies of \fBrack\-perftools_profiler\fR\. Note that \fBbundle update thin\fR will update \fBrack\fR even though it\'s \fIalso\fR a dependency of \fBrack\-perftools_profiler\fR\.
.
.P
In short, by default, when you update a gem using \fBbundle update\fR, bundler will update all dependencies of that gem, including those that are also dependencies of another gem\.
.
.P
To prevent updating indirect dependencies, prior to version 1\.14 the only option was the \fBCONSERVATIVE UPDATING\fR behavior in bundle install(1) \fIbundle\-install\.1\.html\fR:
.
.P
In this scenario, updating the \fBthin\fR version manually in the Gemfile(5), and then running bundle install(1) \fIbundle\-install\.1\.html\fR will only update \fBdaemons\fR and \fBeventmachine\fR, but not \fBrack\fR\. For more information, see the \fBCONSERVATIVE UPDATING\fR section of bundle install(1) \fIbundle\-install\.1\.html\fR\.
.
.P
Starting with 1\.14, specifying the \fB\-\-conservative\fR option will also prevent indirect dependencies from being updated\.
.
.SH "PATCH LEVEL OPTIONS"
Version 1\.14 introduced 4 patch\-level options that will influence how gem versions are resolved\. One of the following options can be used: \fB\-\-patch\fR, \fB\-\-minor\fR or \fB\-\-major\fR\. \fB\-\-strict\fR can be added to further influence resolution\.
.
.TP
\fB\-\-patch\fR
Prefer updating only to next patch version\.
.
.TP
\fB\-\-minor\fR
Prefer updating only to next minor version\.
.
.TP
\fB\-\-major\fR
Prefer updating to next major version (default)\.
.
.TP
\fB\-\-strict\fR
Do not allow any gem to be updated past latest \fB\-\-patch\fR | \fB\-\-minor\fR | \fB\-\-major\fR\.
.
.P
When Bundler is resolving what versions to use to satisfy declared requirements in the Gemfile or in parent gems, it looks up all available versions, filters out any versions that don\'t satisfy the requirement, and then, by default, sorts them from newest to oldest, considering them in that order\.
.
.P
Providing one of the patch level options (e\.g\. \fB\-\-patch\fR) changes the sort order of the satisfying versions, causing Bundler to consider the latest \fB\-\-patch\fR or \fB\-\-minor\fR version available before other versions\. Note that versions outside the stated patch level could still be resolved to if necessary to find a suitable dependency graph\.
.
.P
For example, if gem \'foo\' is locked at 1\.0\.2, with no gem requirement defined in the Gemfile, and versions 1\.0\.3, 1\.0\.4, 1\.1\.0, 1\.1\.1, 2\.0\.0 all exist, the default order of preference by default (\fB\-\-major\fR) will be "2\.0\.0, 1\.1\.1, 1\.1\.0, 1\.0\.4, 1\.0\.3, 1\.0\.2"\.
.
.P
If the \fB\-\-patch\fR option is used, the order of preference will change to "1\.0\.4, 1\.0\.3, 1\.0\.2, 1\.1\.1, 1\.1\.0, 2\.0\.0"\.
.
.P
If the \fB\-\-minor\fR option is used, the order of preference will change to "1\.1\.1, 1\.1\.0, 1\.0\.4, 1\.0\.3, 1\.0\.2, 2\.0\.0"\.
.
.P
Combining the \fB\-\-strict\fR option with any of the patch level options will remove any versions beyond the scope of the patch level option, to ensure that no gem is updated that far\.
.
.P
To continue the previous example, if both \fB\-\-patch\fR and \fB\-\-strict\fR options are used, the available versions for resolution would be "1\.0\.4, 1\.0\.3, 1\.0\.2"\. If \fB\-\-minor\fR and \fB\-\-strict\fR are used, it would be "1\.1\.1, 1\.1\.0, 1\.0\.4, 1\.0\.3, 1\.0\.2"\.
.
.P
Gem requirements as defined in the Gemfile will still be the first determining factor for what versions are available\. If the gem requirement for \fBfoo\fR in the Gemfile is \'~> 1\.0\', that will accomplish the same thing as providing the \fB\-\-minor\fR and \fB\-\-strict\fR options\.
.
.SH "PATCH LEVEL EXAMPLES"
Given the following gem specifications:
.
.IP "" 4
.
.nf

foo 1\.4\.3, requires: ~> bar 2\.0
foo 1\.4\.4, requires: ~> bar 2\.0
foo 1\.4\.5, requires: ~> bar 2\.1
foo 1\.5\.0, requires: ~> bar 2\.1
foo 1\.5\.1, requires: ~> bar 3\.0
bar with versions 2\.0\.3, 2\.0\.4, 2\.1\.0, 2\.1\.1, 3\.0\.0
.
.fi
.
.IP "" 0
.
.P
Gemfile:
.
.IP "" 4
.
.nf

gem \'foo\'
.
.fi
.
.IP "" 0
.
.P
Gemfile\.lock:
.
.IP "" 4
.
.nf

foo (1\.4\.3)
  bar (~> 2\.0)
bar (2\.0\.3)
.
.fi
.
.IP "" 0
.
.P
Cases:
.
.IP "" 4
.
.nf

#  Command Line                     Result
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
1  bundle update \-\-patch            \'foo 1\.4\.5\', \'bar 2\.1\.1\'
2  bundle update \-\-patch foo        \'foo 1\.4\.5\', \'bar 2\.1\.1\'
3  bundle update \-\-minor            \'foo 1\.5\.1\', \'bar 3\.0\.0\'
4  bundle update \-\-minor \-\-strict   \'foo 1\.5\.0\', \'bar 2\.1\.1\'
5  bundle update \-\-patch \-\-strict   \'foo 1\.4\.4\', \'bar 2\.0\.4\'
.
.fi
.
.IP "" 0
.
.P
In case 1, bar is upgraded to 2\.1\.1, a minor version increase, because the dependency from foo 1\.4\.5 required it\.
.
.P
In case 2, only foo is requested to be unlocked, but bar is also allowed to move because it\'s not a declared dependency in the Gemfile\.
.
.P
In case 3, bar goes up a whole major release, because a minor increase is preferred now for foo, and when it goes to 1\.5\.1, it requires 3\.0\.0 of bar\.
.
.P
In case 4, foo is preferred up to a minor version, but 1\.5\.1 won\'t work because the \-\-strict flag removes bar 3\.0\.0 from consideration since it\'s a major increment\.
.
.P
In case 5, both foo and bar have any minor or major increments removed from consideration because of the \-\-strict flag, so the most they can move is up to 1\.4\.4 and 2\.0\.4\.
.
.SH "RECOMMENDED WORKFLOW"
In general, when working with an application managed with bundler, you should use the following workflow:
.
.IP "\(bu" 4
After you create your Gemfile(5) for the first time, run
.
.IP
$ bundle install
.
.IP "\(bu" 4
Check the resulting \fBGemfile\.lock\fR into version control
.
.IP
$ git add Gemfile\.lock
.
.IP "\(bu" 4
When checking out this repository on another development machine, run
.
.IP
$ bundle install
.
.IP "\(bu" 4
When checking out this repository on a deployment machine, run
.
.IP
$ bundle install \-\-deployment
.
.IP "\(bu" 4
After changing the Gemfile(5) to reflect a new or update dependency, run
.
.IP
$ bundle install
.
.IP "\(bu" 4
Make sure to check the updated \fBGemfile\.lock\fR into version control
.
.IP
$ git add Gemfile\.lock
.
.IP "\(bu" 4
If bundle install(1) \fIbundle\-install\.1\.html\fR reports a conflict, manually update the specific gems that you changed in the Gemfile(5)
.
.IP
$ bundle update rails thin
.
.IP "\(bu" 4
If you want to update all the gems to the latest possible versions that still match the gems listed in the Gemfile(5), run
.
.IP
$ bundle update \-\-all
.
.IP "" 0

bundle-init(1) -- Generates a Gemfile into the current working directory
========================================================================

## SYNOPSIS

`bundle init` [--gemspec=FILE]

## DESCRIPTION

Init generates a default [`Gemfile(5)`][Gemfile(5)] in the current working directory. When
adding a [`Gemfile(5)`][Gemfile(5)] to a gem with a gemspec, the `--gemspec` option will
automatically add each dependency listed in the gemspec file to the newly
created [`Gemfile(5)`][Gemfile(5)].

## OPTIONS

* `--gemspec`:
  Use the specified .gemspec to create the [`Gemfile(5)`][Gemfile(5)]

## FILES

Included in the default [`Gemfile(5)`][Gemfile(5)]
generated is the line `# frozen_string_literal: true`. This is a magic comment
supported for the first time in Ruby 2.3. The presence of this line
results in all string literals in the file being implicitly frozen.

## SEE ALSO

[Gemfile(5)](https://bundler.io/man/gemfile.5.html)
bundle-config(1) -- Set bundler configuration options
=====================================================

## SYNOPSIS

`bundle config` [list|get|set|unset] [<name> [<value>]]

## DESCRIPTION

This command allows you to interact with Bundler's configuration system.

Bundler loads configuration settings in this order:

1. Local config (`<project_root>/.bundle/config` or `$BUNDLE_APP_CONFIG/config`)
2. Environmental variables (`ENV`)
3. Global config (`~/.bundle/config`)
4. Bundler default config

Executing `bundle config list` with will print a list of all bundler
configuration for the current bundle, and where that configuration
was set.

Executing `bundle config get <name>` will print the value of that configuration
setting, and where it was set.

Executing `bundle config set <name> <value>` will set that configuration to the
value specified for all bundles executed as the current user. The configuration
will be stored in `~/.bundle/config`. If <name> already is set, <name> will be
overridden and user will be warned.

Executing `bundle config set --global <name> <value>` works the same as above.

Executing `bundle config set --local <name> <value>` will set that configuration
in the directory for the local application. The configuration will be stored in
`<project_root>/.bundle/config`. If `BUNDLE_APP_CONFIG` is set, the configuration
will be stored in `$BUNDLE_APP_CONFIG/config`.

Executing `bundle config unset <name>` will delete the configuration in both
local and global sources.

Executing `bundle config unset --global <name>` will delete the configuration
only from the user configuration.

Executing `bundle config unset --local <name> <value>` will delete the
configuration only from the local application.

Executing bundle with the `BUNDLE_IGNORE_CONFIG` environment variable set will
cause it to ignore all configuration.

## REMEMBERING OPTIONS

Flags passed to `bundle install` or the Bundler runtime, such as `--path foo` or
`--without production`, are remembered between commands and saved to your local
application's configuration (normally, `./.bundle/config`).

However, this will be changed in bundler 3, so it's better not to rely on this
behavior. If these options must be remembered, it's better to set them using
`bundle config` (e.g., `bundle config set --local path foo`).

The options that can be configured are:

* `bin`:
   Creates a directory (defaults to `~/bin`) and place any executables from the
   gem there. These executables run in Bundler's context. If used, you might add
   this directory to your environment's `PATH` variable. For instance, if the
   `rails` gem comes with a `rails` executable, this flag will create a
   `bin/rails` executable that ensures that all referred dependencies will be
   resolved using the bundled gems.

* `deployment`:
   In deployment mode, Bundler will 'roll-out' the bundle for
   `production` use. Please check carefully if you want to have this option
   enabled in `development` or `test` environments.

* `path`:
   The location to install the specified gems to. This defaults to Rubygems'
   setting. Bundler shares this location with Rubygems, `gem install ...` will
   have gem installed there, too. Therefore, gems installed without a
   `--path ...` setting will show up by calling `gem list`. Accordingly, gems
   installed to other locations will not get listed.

* `without`:
   A space-separated list of groups referencing gems to skip during installation.

* `with`:
  A space-separated list of groups referencing gems to include during installation.

## BUILD OPTIONS

You can use `bundle config` to give Bundler the flags to pass to the gem
installer every time bundler tries to install a particular gem.

A very common example, the `mysql` gem, requires Snow Leopard users to
pass configuration flags to `gem install` to specify where to find the
`mysql_config` executable.

    gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config

Since the specific location of that executable can change from machine
to machine, you can specify these flags on a per-machine basis.

    bundle config set --global build.mysql --with-mysql-config=/usr/local/mysql/bin/mysql_config

After running this command, every time bundler needs to install the
`mysql` gem, it will pass along the flags you specified.

## CONFIGURATION KEYS

Configuration keys in bundler have two forms: the canonical form and the
environment variable form.

For instance, passing the `--without` flag to [bundle install(1)](bundle-install.1.html)
prevents Bundler from installing certain groups specified in the Gemfile(5). Bundler
persists this value in `app/.bundle/config` so that calls to `Bundler.setup`
do not try to find gems from the `Gemfile` that you didn't install. Additionally,
subsequent calls to [bundle install(1)](bundle-install.1.html) remember this setting
and skip those groups.

The canonical form of this configuration is `"without"`. To convert the canonical
form to the environment variable form, capitalize it, and prepend `BUNDLE_`. The
environment variable form of `"without"` is `BUNDLE_WITHOUT`.

Any periods in the configuration keys must be replaced with two underscores when
setting it via environment variables. The configuration key `local.rack` becomes
the environment variable `BUNDLE_LOCAL__RACK`.

## LIST OF AVAILABLE KEYS

The following is a list of all configuration keys and their purpose. You can
learn more about their operation in [bundle install(1)](bundle-install.1.html).

* `allow_deployment_source_credential_changes` (`BUNDLE_ALLOW_DEPLOYMENT_SOURCE_CREDENTIAL_CHANGES`):
   When in deployment mode, allow changing the credentials to a gem's source.
   Ex: `https://some.host.com/gems/path/` -> `https://user_name:password@some.host.com/gems/path`
* `allow_offline_install` (`BUNDLE_ALLOW_OFFLINE_INSTALL`):
   Allow Bundler to use cached data when installing without network access.
* `auto_clean_without_path` (`BUNDLE_AUTO_CLEAN_WITHOUT_PATH`):
   Automatically run `bundle clean` after installing when an explicit `path`
   has not been set and Bundler is not installing into the system gems.
* `auto_install` (`BUNDLE_AUTO_INSTALL`):
   Automatically run `bundle install` when gems are missing.
* `bin` (`BUNDLE_BIN`):
   Install executables from gems in the bundle to the specified directory.
   Defaults to `false`.
* `cache_all` (`BUNDLE_CACHE_ALL`):
   Cache all gems, including path and git gems. This needs to be explicitly
   configured on bundler 1 and bundler 2, but will be the default on bundler 3.
* `cache_all_platforms` (`BUNDLE_CACHE_ALL_PLATFORMS`):
   Cache gems for all platforms.
* `cache_path` (`BUNDLE_CACHE_PATH`):
   The directory that bundler will place cached gems in when running
   <code>bundle package</code>, and that bundler will look in when installing gems.
   Defaults to `vendor/cache`.
* `clean` (`BUNDLE_CLEAN`):
   Whether Bundler should run `bundle clean` automatically after
   `bundle install`.
* `console` (`BUNDLE_CONSOLE`):
   The console that `bundle console` starts. Defaults to `irb`.
* `default_install_uses_path` (`BUNDLE_DEFAULT_INSTALL_USES_PATH`):
   Whether a `bundle install` without an explicit `--path` argument defaults
   to installing gems in `.bundle`.
* `deployment` (`BUNDLE_DEPLOYMENT`):
   Disallow changes to the `Gemfile`. When the `Gemfile` is changed and the
   lockfile has not been updated, running Bundler commands will be blocked.
* `disable_checksum_validation` (`BUNDLE_DISABLE_CHECKSUM_VALIDATION`):
   Allow installing gems even if they do not match the checksum provided by
   RubyGems.
* `disable_exec_load` (`BUNDLE_DISABLE_EXEC_LOAD`):
   Stop Bundler from using `load` to launch an executable in-process in
   `bundle exec`.
* `disable_local_branch_check` (`BUNDLE_DISABLE_LOCAL_BRANCH_CHECK`):
   Allow Bundler to use a local git override without a branch specified in the
   Gemfile.
* `disable_local_revision_check` (`BUNDLE_DISABLE_LOCAL_REVISION_CHECK`):
   Allow Bundler to use a local git override without checking if the revision
   present in the lockfile is present in the repository.
* `disable_shared_gems` (`BUNDLE_DISABLE_SHARED_GEMS`):
   Stop Bundler from accessing gems installed to RubyGems' normal location.
* `disable_version_check` (`BUNDLE_DISABLE_VERSION_CHECK`):
   Stop Bundler from checking if a newer Bundler version is available on
   rubygems.org.
* `force_ruby_platform` (`BUNDLE_FORCE_RUBY_PLATFORM`):
   Ignore the current machine's platform and install only `ruby` platform gems.
   As a result, gems with native extensions will be compiled from source.
* `frozen` (`BUNDLE_FROZEN`):
   Disallow changes to the `Gemfile`. When the `Gemfile` is changed and the
   lockfile has not been updated, running Bundler commands will be blocked.
   Defaults to `true` when `--deployment` is used.
* `gem.github_username` (`BUNDLE_GEM__GITHUB_USERNAME`):
   Sets a GitHub username or organization to be used in `README` file when you
   create a new gem via `bundle gem` command. It can be overridden by passing an
   explicit `--github-username` flag to `bundle gem`.
* `gem.push_key` (`BUNDLE_GEM__PUSH_KEY`):
   Sets the `--key` parameter for `gem push` when using the `rake release`
   command with a private gemstash server.
* `gemfile` (`BUNDLE_GEMFILE`):
   The name of the file that bundler should use as the `Gemfile`. This location
   of this file also sets the root of the project, which is used to resolve
   relative paths in the `Gemfile`, among other things. By default, bundler
   will search up from the current working directory until it finds a
   `Gemfile`.
* `global_gem_cache` (`BUNDLE_GLOBAL_GEM_CACHE`):
   Whether Bundler should cache all gems globally, rather than locally to the
   installing Ruby installation.
* `ignore_messages` (`BUNDLE_IGNORE_MESSAGES`):
   When set, no post install messages will be printed. To silence a single gem,
   use dot notation like `ignore_messages.httparty true`.
* `init_gems_rb` (`BUNDLE_INIT_GEMS_RB`):
   Generate a `gems.rb` instead of a `Gemfile` when running `bundle init`.
* `jobs` (`BUNDLE_JOBS`):
   The number of gems Bundler can install in parallel. Defaults to 1 on Windows,
   and to the the number of processors on other platforms.
* `no_install` (`BUNDLE_NO_INSTALL`):
   Whether `bundle package` should skip installing gems.
* `no_prune` (`BUNDLE_NO_PRUNE`):
   Whether Bundler should leave outdated gems unpruned when caching.
* `path` (`BUNDLE_PATH`):
   The location on disk where all gems in your bundle will be located regardless
   of `$GEM_HOME` or `$GEM_PATH` values. Bundle gems not found in this location
   will be installed by `bundle install`. Defaults to `Gem.dir`. When --deployment
   is used, defaults to vendor/bundle.
* `path.system` (`BUNDLE_PATH__SYSTEM`):
   Whether Bundler will install gems into the default system path (`Gem.dir`).
* `path_relative_to_cwd` (`BUNDLE_PATH_RELATIVE_TO_CWD`)
   Makes `--path` relative to the CWD instead of the `Gemfile`.
* `plugins` (`BUNDLE_PLUGINS`):
   Enable Bundler's experimental plugin system.
* `prefer_patch` (BUNDLE_PREFER_PATCH):
   Prefer updating only to next patch version during updates. Makes `bundle update` calls equivalent to `bundler update --patch`.
* `print_only_version_number` (`BUNDLE_PRINT_ONLY_VERSION_NUMBER`):
   Print only version number from `bundler --version`.
* `redirect` (`BUNDLE_REDIRECT`):
   The number of redirects allowed for network requests. Defaults to `5`.
* `retry` (`BUNDLE_RETRY`):
   The number of times to retry failed network requests. Defaults to `3`.
* `setup_makes_kernel_gem_public` (`BUNDLE_SETUP_MAKES_KERNEL_GEM_PUBLIC`):
   Have `Bundler.setup` make the `Kernel#gem` method public, even though
   RubyGems declares it as private.
* `shebang` (`BUNDLE_SHEBANG`):
   The program name that should be invoked for generated binstubs. Defaults to
   the ruby install name used to generate the binstub.
* `silence_deprecations` (`BUNDLE_SILENCE_DEPRECATIONS`):
   Whether Bundler should silence deprecation warnings for behavior that will
   be changed in the next major version.
* `silence_root_warning` (`BUNDLE_SILENCE_ROOT_WARNING`):
   Silence the warning Bundler prints when installing gems as root.
* `ssl_ca_cert` (`BUNDLE_SSL_CA_CERT`):
   Path to a designated CA certificate file or folder containing multiple
   certificates for trusted CAs in PEM format.
* `ssl_client_cert` (`BUNDLE_SSL_CLIENT_CERT`):
   Path to a designated file containing a X.509 client certificate
   and key in PEM format.
* `ssl_verify_mode` (`BUNDLE_SSL_VERIFY_MODE`):
   The SSL verification mode Bundler uses when making HTTPS requests.
   Defaults to verify peer.
* `suppress_install_using_messages` (`BUNDLE_SUPPRESS_INSTALL_USING_MESSAGES`):
   Avoid printing `Using ...` messages during installation when the version of
   a gem has not changed.
* `system_bindir` (`BUNDLE_SYSTEM_BINDIR`):
   The location where RubyGems installs binstubs. Defaults to `Gem.bindir`.
* `timeout` (`BUNDLE_TIMEOUT`):
   The seconds allowed before timing out for network requests. Defaults to `10`.
* `update_requires_all_flag` (`BUNDLE_UPDATE_REQUIRES_ALL_FLAG`):
   Require passing `--all` to `bundle update` when everything should be updated,
   and disallow passing no options to `bundle update`.
* `user_agent` (`BUNDLE_USER_AGENT`):
   The custom user agent fragment Bundler includes in API requests.
* `with` (`BUNDLE_WITH`):
   A `:`-separated list of groups whose gems bundler should install.
* `without` (`BUNDLE_WITHOUT`):
   A `:`-separated list of groups whose gems bundler should not install.

In general, you should set these settings per-application by using the applicable
flag to the [bundle install(1)](bundle-install.1.html) or [bundle package(1)](bundle-package.1.html) command.

You can set them globally either via environment variables or `bundle config`,
whichever is preferable for your setup. If you use both, environment variables
will take preference over global settings.

## LOCAL GIT REPOS

Bundler also allows you to work against a git repository locally
instead of using the remote version. This can be achieved by setting
up a local override:

    bundle config set --local local.GEM_NAME /path/to/local/git/repository

For example, in order to use a local Rack repository, a developer could call:

    bundle config set --local local.rack ~/Work/git/rack

Now instead of checking out the remote git repository, the local
override will be used. Similar to a path source, every time the local
git repository change, changes will be automatically picked up by
Bundler. This means a commit in the local git repo will update the
revision in the `Gemfile.lock` to the local git repo revision. This
requires the same attention as git submodules. Before pushing to
the remote, you need to ensure the local override was pushed, otherwise
you may point to a commit that only exists in your local machine.
You'll also need to CGI escape your usernames and passwords as well.

Bundler does many checks to ensure a developer won't work with
invalid references. Particularly, we force a developer to specify
a branch in the `Gemfile` in order to use this feature. If the branch
specified in the `Gemfile` and the current branch in the local git
repository do not match, Bundler will abort. This ensures that
a developer is always working against the correct branches, and prevents
accidental locking to a different branch.

Finally, Bundler also ensures that the current revision in the
`Gemfile.lock` exists in the local git repository. By doing this, Bundler
forces you to fetch the latest changes in the remotes.

## MIRRORS OF GEM SOURCES

Bundler supports overriding gem sources with mirrors. This allows you to
configure rubygems.org as the gem source in your Gemfile while still using your
mirror to fetch gems.

    bundle config set --global mirror.SOURCE_URL MIRROR_URL

For example, to use a mirror of rubygems.org hosted at rubygems-mirror.org:

    bundle config set --global mirror.http://rubygems.org http://rubygems-mirror.org

Each mirror also provides a fallback timeout setting. If the mirror does not
respond within the fallback timeout, Bundler will try to use the original
server instead of the mirror.

    bundle config set --global mirror.SOURCE_URL.fallback_timeout TIMEOUT

For example, to fall back to rubygems.org after 3 seconds:

    bundle config set --global mirror.https://rubygems.org.fallback_timeout 3

The default fallback timeout is 0.1 seconds, but the setting can currently
only accept whole seconds (for example, 1, 15, or 30).

## CREDENTIALS FOR GEM SOURCES

Bundler allows you to configure credentials for any gem source, which allows
you to avoid putting secrets into your Gemfile.

    bundle config set --global SOURCE_HOSTNAME USERNAME:PASSWORD

For example, to save the credentials of user `claudette` for the gem source at
`gems.longerous.com`, you would run:

    bundle config set --global gems.longerous.com claudette:s00pers3krit

Or you can set the credentials as an environment variable like this:

    export BUNDLE_GEMS__LONGEROUS__COM="claudette:s00pers3krit"

For gems with a git source with HTTP(S) URL you can specify credentials like so:

    bundle config set --global https://github.com/rubygems/rubygems.git username:password

Or you can set the credentials as an environment variable like so:

    export BUNDLE_GITHUB__COM=username:password

This is especially useful for private repositories on hosts such as Github,
where you can use personal OAuth tokens:

    export BUNDLE_GITHUB__COM=abcd0123generatedtoken:x-oauth-basic

Note that any configured credentials will be redacted by informative commands
such as `bundle config list` or `bundle config get`, unless you use the
`--parseable` flag. This is to avoid unintentionally leaking credentials when
copy-pasting bundler output.

Also note that to guarantee a sane mapping between valid environment variable
names and valid host names, bundler makes the following transformations:

* Any `-` characters in a host name are mapped to a triple dash (`___`) in the
  corresponding environment variable.

* Any `.` characters in a host name are mapped to a double dash (`__`) in the
  corresponding environment variable.

This means that if you have a gem server named `my.gem-host.com`, you'll need to
use the `BUNDLE_MY__GEM___HOST__COM` variable to configure credentials for it
through ENV.

## CONFIGURE BUNDLER DIRECTORIES

Bundler's home, config, cache and plugin directories are able to be configured
through environment variables. The default location for Bundler's home directory is
`~/.bundle`, which all directories inherit from by default. The following
outlines the available environment variables and their default values

    BUNDLE_USER_HOME : $HOME/.bundle
    BUNDLE_USER_CACHE : $BUNDLE_USER_HOME/cache
    BUNDLE_USER_CONFIG : $BUNDLE_USER_HOME/config
    BUNDLE_USER_PLUGIN : $BUNDLE_USER_HOME/plugin
bundle-lock(1) -- Creates / Updates a lockfile without installing
=================================================================

## SYNOPSIS

`bundle lock` [--update]
              [--local]
              [--print]
              [--lockfile=PATH]
              [--full-index]
              [--add-platform]
              [--remove-platform]
              [--patch]
              [--minor]
              [--major]
              [--strict]
              [--conservative]

## DESCRIPTION

Lock the gems specified in Gemfile.

## OPTIONS

* `--update=<*gems>`:
  Ignores the existing lockfile. Resolve then updates lockfile. Taking a list
  of gems or updating all gems if no list is given.

* `--local`:
  Do not attempt to connect to `rubygems.org`. Instead, Bundler will use the
  gems already present in Rubygems' cache or in `vendor/cache`. Note that if a
  appropriate platform-specific gem exists on `rubygems.org` it will not be
  found.

* `--print`:
  Prints the lockfile to STDOUT instead of writing to the file system.

* `--lockfile=<path>`:
  The path where the lockfile should be written to.

* `--full-index`:
  Fall back to using the single-file index of all gems.

* `--add-platform`:
  Add a new platform to the lockfile, re-resolving for the addition of that
  platform.

* `--remove-platform`:
  Remove a platform from the lockfile.

* `--patch`:
  If updating, prefer updating only to next patch version.

* `--minor`:
  If updating, prefer updating only to next minor version.

* `--major`:
  If updating, prefer updating to next major version (default).

* `--strict`:
  If updating, do not allow any gem to be updated past latest --patch | --minor | --major.

* `--conservative`:
  If updating, use bundle install conservative update behavior and do not allow shared dependencies to be updated.

## UPDATING ALL GEMS

If you run `bundle lock` with `--update` option without list of gems, bundler will
ignore any previously installed gems and resolve all dependencies again based
on the latest versions of all gems available in the sources.

## UPDATING A LIST OF GEMS

Sometimes, you want to update a single gem in the Gemfile(5), and leave the rest of
the gems that you specified locked to the versions in the `Gemfile.lock`.

For instance, you only want to update `nokogiri`, run `bundle lock --update nokogiri`.

Bundler will update `nokogiri` and any of its dependencies, but leave the rest of the
gems that you specified locked to the versions in the `Gemfile.lock`.

## SUPPORTING OTHER PLATFORMS

If you want your bundle to support platforms other than the one you're running
locally, you can run `bundle lock --add-platform PLATFORM` to add PLATFORM to
the lockfile, force bundler to re-resolve and consider the new platform when
picking gems, all without needing to have a machine that matches PLATFORM handy
to install those platform-specific gems on.

For a full explanation of gem platforms, see `gem help platform`.

## PATCH LEVEL OPTIONS

See [bundle update(1)](bundle-update.1.html) for details.
bundle-clean(1) -- Cleans up unused gems in your bundler directory
==================================================================

## SYNOPSIS

`bundle clean` [--dry-run] [--force]

## DESCRIPTION

This command will remove all unused gems in your bundler directory. This is
useful when you have made many changes to your gem dependencies.

## OPTIONS

* `--dry-run`:
  Print the changes, but do not clean the unused gems.
* `--force`:
  Force a clean even if `--path` is not set.
bundle-gem(1) -- Generate a project skeleton for creating a rubygem
====================================================================

## SYNOPSIS

`bundle gem` <GEM_NAME> [OPTIONS]

## DESCRIPTION

Generates a directory named `GEM_NAME` with a `Rakefile`, `GEM_NAME.gemspec`,
and other supporting files and directories that can be used to develop a
rubygem with that name.

Run `rake -T` in the resulting project for a list of Rake tasks that can be used
to test and publish the gem to rubygems.org.

The generated project skeleton can be customized with OPTIONS, as explained
below. Note that these options can also be specified via Bundler's global
configuration file using the following names:

* `gem.coc`
* `gem.mit`
* `gem.test`

## OPTIONS

* `--exe` or `-b` or `--bin`:
  Specify that Bundler should create a binary executable (as `exe/GEM_NAME`)
  in the generated rubygem project. This binary will also be added to the
  `GEM_NAME.gemspec` manifest. This behavior is disabled by default.

* `--no-exe`:
  Do not create a binary (overrides `--exe` specified in the global config).

* `--coc`:
  Add a `CODE_OF_CONDUCT.md` file to the root of the generated project. If
  this option is unspecified, an interactive prompt will be displayed and the
  answer will be saved in Bundler's global config for future `bundle gem` use.

* `--no-coc`:
  Do not create a `CODE_OF_CONDUCT.md` (overrides `--coc` specified in the
  global config).

* `--ext`:
  Add boilerplate for C extension code to the generated project. This behavior
  is disabled by default.

* `--no-ext`:
  Do not add C extension code (overrides `--ext` specified in the global
  config).

* `--mit`:
  Add an MIT license to a `LICENSE.txt` file in the root of the generated
  project. Your name from the global git config is used for the copyright
  statement. If this option is unspecified, an interactive prompt will be
  displayed and the answer will be saved in Bundler's global config for future
  `bundle gem` use.

* `--no-mit`:
  Do not create a `LICENSE.txt` (overrides `--mit` specified in the global
  config).

* `-t`, `--test=minitest`, `--test=rspec`, `--test=test-unit`:
  Specify the test framework that Bundler should use when generating the
  project. Acceptable values are `minitest`, `rspec` and `test-unit`. The
  `GEM_NAME.gemspec` will be configured and a skeleton test/spec directory will
  be created based on this option. Given no option is specified:

  When Bundler is configured to generate tests, this defaults to Bundler's
  global config setting `gem.test`.

  When Bundler is configured to not generate tests, an interactive prompt will
  be displayed and the answer will be used for the current rubygem project.

  When Bundler is unconfigured, an interactive prompt will be displayed and
  the answer will be saved in Bundler's global config for future `bundle gem`
  use.

* `--ci`, `--ci=github`, `--ci=travis`, `--ci=gitlab`, `--ci=circle`:
  Specify the continuous integration service that Bundler should use when
  generating the project. Acceptable values are `github`, `travis`, `gitlab`
  and `circle`. A configuration file will be generated in the project directory.
  Given no option is specified:

  When Bundler is configured to generate CI files, this defaults to Bundler's
  global config setting `gem.ci`.

  When Bundler is configured to not generate CI files, an interactive prompt
  will be displayed and the answer will be used for the current rubygem project.

  When Bundler is unconfigured, an interactive prompt will be displayed and
  the answer will be saved in Bundler's global config for future `bundle gem`
  use.

* `--linter`, `--linter=rubocop`, `--linter=standard`:
  Specify the linter and code formatter that Bundler should add to the
  project's development dependencies. Acceptable values are `rubocop` and
  `standard`. A configuration file will be generated in the project directory.
  Given no option is specified:

  When Bundler is configured to add a linter, this defaults to Bundler's
  global config setting `gem.linter`.

  When Bundler is configured not to add a linter, an interactive prompt
  will be displayed and the answer will be used for the current rubygem project.

  When Bundler is unconfigured, an interactive prompt will be displayed and
  the answer will be saved in Bundler's global config for future `bundle gem`
  use.

* `-e`, `--edit[=EDITOR]`:
  Open the resulting GEM_NAME.gemspec in EDITOR, or the default editor if not
  specified. The default is `$BUNDLER_EDITOR`, `$VISUAL`, or `$EDITOR`.

## SEE ALSO

* [bundle config(1)](bundle-config.1.html)
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-INFO" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-info\fR \- Show information for the given gem in your bundle
.
.SH "SYNOPSIS"
\fBbundle info\fR [GEM] [\-\-path]
.
.SH "DESCRIPTION"
Print the basic information about the provided GEM such as homepage, version, path and summary\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-path\fR
Print the path of the given gem

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-ADD" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-add\fR \- Add gem to the Gemfile and run bundle install
.
.SH "SYNOPSIS"
\fBbundle add\fR \fIGEM_NAME\fR [\-\-group=GROUP] [\-\-version=VERSION] [\-\-source=SOURCE] [\-\-git=GIT] [\-\-branch=BRANCH] [\-\-skip\-install] [\-\-strict] [\-\-optimistic]
.
.SH "DESCRIPTION"
Adds the named gem to the Gemfile and run \fBbundle install\fR\. \fBbundle install\fR can be avoided by using the flag \fB\-\-skip\-install\fR\.
.
.P
Example:
.
.P
bundle add rails
.
.P
bundle add rails \-\-version "< 3\.0, > 1\.1"
.
.P
bundle add rails \-\-version "~> 5\.0\.0" \-\-source "https://gems\.example\.com" \-\-group "development"
.
.P
bundle add rails \-\-skip\-install
.
.P
bundle add rails \-\-group "development, test"
.
.SH "OPTIONS"
.
.TP
\fB\-\-version\fR, \fB\-v\fR
Specify version requirements(s) for the added gem\.
.
.TP
\fB\-\-group\fR, \fB\-g\fR
Specify the group(s) for the added gem\. Multiple groups should be separated by commas\.
.
.TP
\fB\-\-source\fR, , \fB\-s\fR
Specify the source for the added gem\.
.
.TP
\fB\-\-git\fR
Specify the git source for the added gem\.
.
.TP
\fB\-\-branch\fR
Specify the git branch for the added gem\.
.
.TP
\fB\-\-skip\-install\fR
Adds the gem to the Gemfile but does not install it\.
.
.TP
\fB\-\-optimistic\fR
Adds optimistic declaration of version
.
.TP
\fB\-\-strict\fR
Adds strict declaration of version

bundle-doctor(1) -- Checks the bundle for common problems
=========================================================

## SYNOPSIS

`bundle doctor` [--quiet]
                [--gemfile=GEMFILE]

## DESCRIPTION

Checks your Gemfile and gem environment for common problems. If issues
are detected, Bundler prints them and exits status 1. Otherwise,
Bundler prints a success message and exits status 0.

Examples of common problems caught by bundle-doctor include:

* Invalid Bundler settings
* Mismatched Ruby versions
* Mismatched platforms
* Uninstalled gems
* Missing dependencies

## OPTIONS

* `--quiet`:
  Only output warnings and errors.

* `--gemfile=<gemfile>`:
  The location of the Gemfile(5) which Bundler should use. This defaults
  to a Gemfile(5) in the current working directory. In general, Bundler
  will assume that the location of the Gemfile(5) is also the project's
  root and will try to find `Gemfile.lock` and `vendor/cache` relative
  to this location.
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-LOCK" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-lock\fR \- Creates / Updates a lockfile without installing
.
.SH "SYNOPSIS"
\fBbundle lock\fR [\-\-update] [\-\-local] [\-\-print] [\-\-lockfile=PATH] [\-\-full\-index] [\-\-add\-platform] [\-\-remove\-platform] [\-\-patch] [\-\-minor] [\-\-major] [\-\-strict] [\-\-conservative]
.
.SH "DESCRIPTION"
Lock the gems specified in Gemfile\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-update=<*gems>\fR
Ignores the existing lockfile\. Resolve then updates lockfile\. Taking a list of gems or updating all gems if no list is given\.
.
.TP
\fB\-\-local\fR
Do not attempt to connect to \fBrubygems\.org\fR\. Instead, Bundler will use the gems already present in Rubygems\' cache or in \fBvendor/cache\fR\. Note that if a appropriate platform\-specific gem exists on \fBrubygems\.org\fR it will not be found\.
.
.TP
\fB\-\-print\fR
Prints the lockfile to STDOUT instead of writing to the file system\.
.
.TP
\fB\-\-lockfile=<path>\fR
The path where the lockfile should be written to\.
.
.TP
\fB\-\-full\-index\fR
Fall back to using the single\-file index of all gems\.
.
.TP
\fB\-\-add\-platform\fR
Add a new platform to the lockfile, re\-resolving for the addition of that platform\.
.
.TP
\fB\-\-remove\-platform\fR
Remove a platform from the lockfile\.
.
.TP
\fB\-\-patch\fR
If updating, prefer updating only to next patch version\.
.
.TP
\fB\-\-minor\fR
If updating, prefer updating only to next minor version\.
.
.TP
\fB\-\-major\fR
If updating, prefer updating to next major version (default)\.
.
.TP
\fB\-\-strict\fR
If updating, do not allow any gem to be updated past latest \-\-patch | \-\-minor | \-\-major\.
.
.TP
\fB\-\-conservative\fR
If updating, use bundle install conservative update behavior and do not allow shared dependencies to be updated\.
.
.SH "UPDATING ALL GEMS"
If you run \fBbundle lock\fR with \fB\-\-update\fR option without list of gems, bundler will ignore any previously installed gems and resolve all dependencies again based on the latest versions of all gems available in the sources\.
.
.SH "UPDATING A LIST OF GEMS"
Sometimes, you want to update a single gem in the Gemfile(5), and leave the rest of the gems that you specified locked to the versions in the \fBGemfile\.lock\fR\.
.
.P
For instance, you only want to update \fBnokogiri\fR, run \fBbundle lock \-\-update nokogiri\fR\.
.
.P
Bundler will update \fBnokogiri\fR and any of its dependencies, but leave the rest of the gems that you specified locked to the versions in the \fBGemfile\.lock\fR\.
.
.SH "SUPPORTING OTHER PLATFORMS"
If you want your bundle to support platforms other than the one you\'re running locally, you can run \fBbundle lock \-\-add\-platform PLATFORM\fR to add PLATFORM to the lockfile, force bundler to re\-resolve and consider the new platform when picking gems, all without needing to have a machine that matches PLATFORM handy to install those platform\-specific gems on\.
.
.P
For a full explanation of gem platforms, see \fBgem help platform\fR\.
.
.SH "PATCH LEVEL OPTIONS"
See bundle update(1) \fIbundle\-update\.1\.html\fR for details\.
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-CHECK" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-check\fR \- Verifies if dependencies are satisfied by installed gems
.
.SH "SYNOPSIS"
\fBbundle check\fR [\-\-dry\-run] [\-\-gemfile=FILE] [\-\-path=PATH]
.
.SH "DESCRIPTION"
\fBcheck\fR searches the local machine for each of the gems requested in the Gemfile\. If all gems are found, Bundler prints a success message and exits with a status of 0\.
.
.P
If not, the first missing gem is listed and Bundler exits status 1\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-dry\-run\fR
Locks the [\fBGemfile(5)\fR][Gemfile(5)] before running the command\.
.
.TP
\fB\-\-gemfile\fR
Use the specified gemfile instead of the [\fBGemfile(5)\fR][Gemfile(5)]\.
.
.TP
\fB\-\-path\fR
Specify a different path than the system default (\fB$BUNDLE_PATH\fR or \fB$GEM_HOME\fR)\. Bundler will remember this value for future installs on this machine\.

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-CLEAN" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-clean\fR \- Cleans up unused gems in your bundler directory
.
.SH "SYNOPSIS"
\fBbundle clean\fR [\-\-dry\-run] [\-\-force]
.
.SH "DESCRIPTION"
This command will remove all unused gems in your bundler directory\. This is useful when you have made many changes to your gem dependencies\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-dry\-run\fR
Print the changes, but do not clean the unused gems\.
.
.TP
\fB\-\-force\fR
Force a clean even if \fB\-\-path\fR is not set\.

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-OPEN" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-open\fR \- Opens the source directory for a gem in your bundle
.
.SH "SYNOPSIS"
\fBbundle open\fR [GEM]
.
.SH "DESCRIPTION"
Opens the source directory of the provided GEM in your editor\.
.
.P
For this to work the \fBEDITOR\fR or \fBBUNDLER_EDITOR\fR environment variable has to be set\.
.
.P
Example:
.
.IP "" 4
.
.nf

bundle open \'rack\'
.
.fi
.
.IP "" 0
.
.P
Will open the source directory for the \'rack\' gem in your bundle\.
bundle-add(1) -- Add gem to the Gemfile and run bundle install
================================================================

## SYNOPSIS

`bundle add` <GEM_NAME> [--group=GROUP] [--version=VERSION] [--source=SOURCE] [--git=GIT] [--branch=BRANCH] [--skip-install] [--strict] [--optimistic]

## DESCRIPTION
Adds the named gem to the Gemfile and run `bundle install`. `bundle install` can be avoided by using the flag `--skip-install`.

Example:

bundle add rails

bundle add rails --version "< 3.0, > 1.1"

bundle add rails --version "~> 5.0.0" --source "https://gems.example.com" --group "development"

bundle add rails --skip-install

bundle add rails --group "development, test"

## OPTIONS
* `--version`, `-v`:
  Specify version requirements(s) for the added gem.

* `--group`, `-g`:
  Specify the group(s) for the added gem. Multiple groups should be separated by commas.

* `--source`, , `-s`:
  Specify the source for the added gem.

* `--git`:
  Specify the git source for the added gem.

* `--branch`:
  Specify the git branch for the added gem.

* `--skip-install`:
  Adds the gem to the Gemfile but does not install it.

* `--optimistic`:
  Adds optimistic declaration of version

* `--strict`:
  Adds strict declaration of version
bundle-pristine(1) -- Restores installed gems to their pristine condition
===========================================================================

## SYNOPSIS

`bundle pristine`

## DESCRIPTION

`pristine` restores the installed gems in the bundle to their pristine condition
using the local gem cache from RubyGems. For git gems, a forced checkout will be performed.

For further explanation, `bundle pristine` ignores unpacked files on disk. In other
words, this command utilizes the local `.gem` cache or the gem's git repository
as if one were installing from scratch.

Note: the Bundler gem cannot be restored to its original state with `pristine`.
One also cannot use `bundle pristine` on gems with a 'path' option in the Gemfile,
because bundler has no original copy it can restore from.

When is it practical to use `bundle pristine`?

It comes in handy when a developer is debugging a gem. `bundle pristine` is a
great way to get rid of experimental changes to a gem that one may not want.

Why use `bundle pristine` over `gem pristine --all`?

Both commands are very similar.
For context: `bundle pristine`, without arguments, cleans all gems from the lockfile.
Meanwhile, `gem pristine --all` cleans all installed gems for that Ruby version.

If a developer forgets which gems in their project they might
have been debugging, the Rubygems `gem pristine [GEMNAME]` command may be inconvenient.
One can avoid waiting for `gem pristine --all`, and instead run `bundle pristine`.
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-INIT" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-init\fR \- Generates a Gemfile into the current working directory
.
.SH "SYNOPSIS"
\fBbundle init\fR [\-\-gemspec=FILE]
.
.SH "DESCRIPTION"
Init generates a default [\fBGemfile(5)\fR][Gemfile(5)] in the current working directory\. When adding a [\fBGemfile(5)\fR][Gemfile(5)] to a gem with a gemspec, the \fB\-\-gemspec\fR option will automatically add each dependency listed in the gemspec file to the newly created [\fBGemfile(5)\fR][Gemfile(5)]\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-gemspec\fR
Use the specified \.gemspec to create the [\fBGemfile(5)\fR][Gemfile(5)]
.
.SH "FILES"
Included in the default [\fBGemfile(5)\fR][Gemfile(5)] generated is the line \fB# frozen_string_literal: true\fR\. This is a magic comment supported for the first time in Ruby 2\.3\. The presence of this line results in all string literals in the file being implicitly frozen\.
.
.SH "SEE ALSO"
Gemfile(5) \fIhttps://bundler\.io/man/gemfile\.5\.html\fR
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-PRISTINE" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-pristine\fR \- Restores installed gems to their pristine condition
.
.SH "SYNOPSIS"
\fBbundle pristine\fR
.
.SH "DESCRIPTION"
\fBpristine\fR restores the installed gems in the bundle to their pristine condition using the local gem cache from RubyGems\. For git gems, a forced checkout will be performed\.
.
.P
For further explanation, \fBbundle pristine\fR ignores unpacked files on disk\. In other words, this command utilizes the local \fB\.gem\fR cache or the gem\'s git repository as if one were installing from scratch\.
.
.P
Note: the Bundler gem cannot be restored to its original state with \fBpristine\fR\. One also cannot use \fBbundle pristine\fR on gems with a \'path\' option in the Gemfile, because bundler has no original copy it can restore from\.
.
.P
When is it practical to use \fBbundle pristine\fR?
.
.P
It comes in handy when a developer is debugging a gem\. \fBbundle pristine\fR is a great way to get rid of experimental changes to a gem that one may not want\.
.
.P
Why use \fBbundle pristine\fR over \fBgem pristine \-\-all\fR?
.
.P
Both commands are very similar\. For context: \fBbundle pristine\fR, without arguments, cleans all gems from the lockfile\. Meanwhile, \fBgem pristine \-\-all\fR cleans all installed gems for that Ruby version\.
.
.P
If a developer forgets which gems in their project they might have been debugging, the Rubygems \fBgem pristine [GEMNAME]\fR command may be inconvenient\. One can avoid waiting for \fBgem pristine \-\-all\fR, and instead run \fBbundle pristine\fR\.
bundle-install(1) -- Install the dependencies specified in your Gemfile
=======================================================================

## SYNOPSIS

`bundle install` [--binstubs[=DIRECTORY]]
                 [--clean]
                 [--deployment]
                 [--frozen]
                 [--full-index]
                 [--gemfile=GEMFILE]
                 [--jobs=NUMBER]
                 [--local]
                 [--no-cache]
                 [--no-prune]
                 [--path PATH]
                 [--quiet]
                 [--redownload]
                 [--retry=NUMBER]
                 [--shebang]
                 [--standalone[=GROUP[ GROUP...]]]
                 [--system]
                 [--trust-policy=POLICY]
                 [--with=GROUP[ GROUP...]]
                 [--without=GROUP[ GROUP...]]

## DESCRIPTION

Install the gems specified in your Gemfile(5). If this is the first
time you run bundle install (and a `Gemfile.lock` does not exist),
Bundler will fetch all remote sources, resolve dependencies and
install all needed gems.

If a `Gemfile.lock` does exist, and you have not updated your Gemfile(5),
Bundler will fetch all remote sources, but use the dependencies
specified in the `Gemfile.lock` instead of resolving dependencies.

If a `Gemfile.lock` does exist, and you have updated your Gemfile(5),
Bundler will use the dependencies in the `Gemfile.lock` for all gems
that you did not update, but will re-resolve the dependencies of
gems that you did update. You can find more information about this
update process below under [CONSERVATIVE UPDATING][].

## OPTIONS

The `--clean`, `--deployment`, `--frozen`, `--no-prune`, `--path`, `--shebang`,
`--system`, `--without` and `--with` options are deprecated because they only
make sense if they are applied to every subsequent `bundle install` run
automatically and that requires `bundler` to silently remember them. Since
`bundler` will no longer remember CLI flags in future versions, `bundle config`
(see bundle-config(1)) should be used to apply them permanently.

* `--binstubs[=<directory>]`:
  Binstubs are scripts that wrap around executables. Bundler creates a small Ruby
  file (a binstub) that loads Bundler, runs the command, and puts it in `bin/`.
  This lets you link the binstub inside of an application to the exact gem
  version the application needs.

  Creates a directory (defaults to `~/bin`) and places any executables from the
  gem there. These executables run in Bundler's context. If used, you might add
  this directory to your environment's `PATH` variable. For instance, if the
  `rails` gem comes with a `rails` executable, this flag will create a
  `bin/rails` executable that ensures that all referred dependencies will be
  resolved using the bundled gems.

* `--clean`:
  On finishing the installation Bundler is going to remove any gems not present
  in the current Gemfile(5). Don't worry, gems currently in use will not be
  removed.

  This option is deprecated in favor of the `clean` setting.

* `--deployment`:
  In [deployment mode][DEPLOYMENT MODE], Bundler will 'roll-out' the bundle for
  production or CI use. Please check carefully if you want to have this option
  enabled in your development environment.

  This option is deprecated in favor of the `deployment` setting.

* `--redownload`:
  Force download every gem, even if the required versions are already available
  locally.

* `--frozen`:
  Do not allow the Gemfile.lock to be updated after this install. Exits
  non-zero if there are going to be changes to the Gemfile.lock.

  This option is deprecated in favor of the `frozen` setting.

* `--full-index`:
  Bundler will not call Rubygems' API endpoint (default) but download and cache
  a (currently big) index file of all gems. Performance can be improved for
  large bundles that seldom change by enabling this option.

* `--gemfile=<gemfile>`:
  The location of the Gemfile(5) which Bundler should use. This defaults
  to a Gemfile(5) in the current working directory. In general, Bundler
  will assume that the location of the Gemfile(5) is also the project's
  root and will try to find `Gemfile.lock` and `vendor/cache` relative
  to this location.

* `--jobs=[<number>]`, `-j[<number>]`:
  The maximum number of parallel download and install jobs. The default
  is `1`.

* `--local`:
  Do not attempt to connect to `rubygems.org`. Instead, Bundler will use the
  gems already present in Rubygems' cache or in `vendor/cache`. Note that if an
  appropriate platform-specific gem exists on `rubygems.org` it will not be
  found.

* `--no-cache`:
  Do not update the cache in `vendor/cache` with the newly bundled gems. This
  does not remove any gems in the cache but keeps the newly bundled gems from
  being cached during the install.

* `--no-prune`:
  Don't remove stale gems from the cache when the installation finishes.

  This option is deprecated in favor of the `no_prune` setting.

* `--path=<path>`:
  The location to install the specified gems to. This defaults to Rubygems'
  setting. Bundler shares this location with Rubygems, `gem install ...` will
  have gem installed there, too. Therefore, gems installed without a
  `--path ...` setting will show up by calling `gem list`. Accordingly, gems
  installed to other locations will not get listed.

  This option is deprecated in favor of the `path` setting.

* `--quiet`:
  Do not print progress information to the standard output. Instead, Bundler
  will exit using a status code (`$?`).

* `--retry=[<number>]`:
  Retry failed network or git requests for <number> times.

* `--shebang=<ruby-executable>`:
  Uses the specified ruby executable (usually `ruby`) to execute the scripts
  created with `--binstubs`. In addition, if you use `--binstubs` together with
  `--shebang jruby` these executables will be changed to execute `jruby`
  instead.

  This option is deprecated in favor of the `shebang` setting.

* `--standalone[=<list>]`:
  Makes a bundle that can work without depending on Rubygems or Bundler at
  runtime. A space separated list of groups to install has to be specified.
  Bundler creates a directory named `bundle` and installs the bundle there. It
  also generates a `bundle/bundler/setup.rb` file to replace Bundler's own setup
  in the manner required. Using this option implicitly sets `path`, which is a
  [remembered option][REMEMBERED OPTIONS].

* `--system`:
  Installs the gems specified in the bundle to the system's Rubygems location.
  This overrides any previous configuration of `--path`.

  This option is deprecated in favor of the `system` setting.

* `--trust-policy=[<policy>]`:
  Apply the Rubygems security policy <policy>, where policy is one of
  `HighSecurity`, `MediumSecurity`, `LowSecurity`, `AlmostNoSecurity`, or
  `NoSecurity`. For more details, please see the Rubygems signing documentation
  linked below in [SEE ALSO][].

* `--with=<list>`:
  A space-separated list of groups referencing gems to install. If an
  optional group is given it is installed. If a group is given that is
  in the remembered list of groups given to --without, it is removed
  from that list.

  This option is deprecated in favor of the `with` setting.

* `--without=<list>`:
  A space-separated list of groups referencing gems to skip during installation.
  If a group is given that is in the remembered list of groups given
  to --with, it is removed from that list.

  This option is deprecated in favor of the `without` setting.

## DEPLOYMENT MODE

Bundler's defaults are optimized for development. To switch to
defaults optimized for deployment and for CI, use the `--deployment`
flag. Do not activate deployment mode on development machines, as it
will cause an error when the Gemfile(5) is modified.

1. A `Gemfile.lock` is required.

   To ensure that the same versions of the gems you developed with
   and tested with are also used in deployments, a `Gemfile.lock`
   is required.

   This is mainly to ensure that you remember to check your
   `Gemfile.lock` into version control.

2. The `Gemfile.lock` must be up to date

   In development, you can modify your Gemfile(5) and re-run
   `bundle install` to [conservatively update][CONSERVATIVE UPDATING]
   your `Gemfile.lock` snapshot.

   In deployment, your `Gemfile.lock` should be up-to-date with
   changes made in your Gemfile(5).

3. Gems are installed to `vendor/bundle` not your default system location

   In development, it's convenient to share the gems used in your
   application with other applications and other scripts that run on
   the system.

   In deployment, isolation is a more important default. In addition,
   the user deploying the application may not have permission to install
   gems to the system, or the web server may not have permission to
   read them.

   As a result, `bundle install --deployment` installs gems to
   the `vendor/bundle` directory in the application. This may be
   overridden using the `--path` option.

## SUDO USAGE

By default, Bundler installs gems to the same location as `gem install`.

In some cases, that location may not be writable by your Unix user. In
that case, Bundler will stage everything in a temporary directory,
then ask you for your `sudo` password in order to copy the gems into
their system location.

From your perspective, this is identical to installing the gems
directly into the system.

You should never use `sudo bundle install`. This is because several
other steps in `bundle install` must be performed as the current user:

* Updating your `Gemfile.lock`
* Updating your `vendor/cache`, if necessary
* Checking out private git repositories using your user's SSH keys

Of these three, the first two could theoretically be performed by
`chown`ing the resulting files to `$SUDO_USER`. The third, however,
can only be performed by invoking the `git` command as
the current user. Therefore, git gems are downloaded and installed
into `~/.bundle` rather than $GEM_HOME or $BUNDLE_PATH.

As a result, you should run `bundle install` as the current user,
and Bundler will ask for your password if it is needed to put the
gems into their final location.

## INSTALLING GROUPS

By default, `bundle install` will install all gems in all groups
in your Gemfile(5), except those declared for a different platform.

However, you can explicitly tell Bundler to skip installing
certain groups with the `--without` option. This option takes
a space-separated list of groups.

While the `--without` option will skip _installing_ the gems in the
specified groups, it will still _download_ those gems and use them to
resolve the dependencies of every gem in your Gemfile(5).

This is so that installing a different set of groups on another
 machine (such as a production server) will not change the
gems and versions that you have already developed and tested against.

`Bundler offers a rock-solid guarantee that the third-party
code you are running in development and testing is also the
third-party code you are running in production. You can choose
to exclude some of that code in different environments, but you
will never be caught flat-footed by different versions of
third-party code being used in different environments.`

For a simple illustration, consider the following Gemfile(5):

    source 'https://rubygems.org'

    gem 'sinatra'

    group :production do
      gem 'rack-perftools-profiler'
    end

In this case, `sinatra` depends on any version of Rack (`>= 1.0`), while
`rack-perftools-profiler` depends on 1.x (`~> 1.0`).

When you run `bundle install --without production` in development, we
look at the dependencies of `rack-perftools-profiler` as well. That way,
you do not spend all your time developing against Rack 2.0, using new
APIs unavailable in Rack 1.x, only to have Bundler switch to Rack 1.2
when the `production` group _is_ used.

This should not cause any problems in practice, because we do not
attempt to `install` the gems in the excluded groups, and only evaluate
as part of the dependency resolution process.

This also means that you cannot include different versions of the same
gem in different groups, because doing so would result in different
sets of dependencies used in development and production. Because of
the vagaries of the dependency resolution process, this usually
affects more than the gems you list in your Gemfile(5), and can
(surprisingly) radically change the gems you are using.

## THE GEMFILE.LOCK

When you run `bundle install`, Bundler will persist the full names
and versions of all gems that you used (including dependencies of
the gems specified in the Gemfile(5)) into a file called `Gemfile.lock`.

Bundler uses this file in all subsequent calls to `bundle install`,
which guarantees that you always use the same exact code, even
as your application moves across machines.

Because of the way dependency resolution works, even a
seemingly small change (for instance, an update to a point-release
of a dependency of a gem in your Gemfile(5)) can result in radically
different gems being needed to satisfy all dependencies.

As a result, you `SHOULD` check your `Gemfile.lock` into version
control, in both applications and gems. If you do not, every machine that
checks out your repository (including your production server) will resolve all
dependencies again, which will result in different versions of
third-party code being used if `any` of the gems in the Gemfile(5)
or any of their dependencies have been updated.

When Bundler first shipped, the `Gemfile.lock` was included in the `.gitignore`
file included with generated gems.  Over time, however, it became clear that
this practice forces the pain of broken dependencies onto new contributors,
while leaving existing contributors potentially unaware of the problem. Since
`bundle install` is usually the first step towards a contribution, the pain of
broken dependencies would discourage new contributors from contributing. As a
result, we have revised our guidance for gem authors to now recommend checking
in the lock for gems.

## CONSERVATIVE UPDATING

When you make a change to the Gemfile(5) and then run `bundle install`,
Bundler will update only the gems that you modified.

In other words, if a gem that you `did not modify` worked before
you called `bundle install`, it will continue to use the exact
same versions of all dependencies as it used before the update.

Let's take a look at an example. Here's your original Gemfile(5):

    source 'https://rubygems.org'

    gem 'actionpack', '2.3.8'
    gem 'activemerchant'

In this case, both `actionpack` and `activemerchant` depend on
`activesupport`. The `actionpack` gem depends on `activesupport 2.3.8`
and `rack ~> 1.1.0`, while the `activemerchant` gem depends on
`activesupport >= 2.3.2`, `braintree >= 2.0.0`, and `builder >= 2.0.0`.

When the dependencies are first resolved, Bundler will select
`activesupport 2.3.8`, which satisfies the requirements of both
gems in your Gemfile(5).

Next, you modify your Gemfile(5) to:

    source 'https://rubygems.org'

    gem 'actionpack', '3.0.0.rc'
    gem 'activemerchant'

The `actionpack 3.0.0.rc` gem has a number of new dependencies,
and updates the `activesupport` dependency to `= 3.0.0.rc` and
the `rack` dependency to `~> 1.2.1`.

When you run `bundle install`, Bundler notices that you changed
the `actionpack` gem, but not the `activemerchant` gem. It
evaluates the gems currently being used to satisfy its requirements:

  * `activesupport 2.3.8`:
    also used to satisfy a dependency in `activemerchant`,
    which is not being updated
  * `rack ~> 1.1.0`:
    not currently being used to satisfy another dependency

Because you did not explicitly ask to update `activemerchant`,
you would not expect it to suddenly stop working after updating
`actionpack`. However, satisfying the new `activesupport 3.0.0.rc`
dependency of actionpack requires updating one of its dependencies.

Even though `activemerchant` declares a very loose dependency
that theoretically matches `activesupport 3.0.0.rc`, Bundler treats
gems in your Gemfile(5) that have not changed as an atomic unit
together with their dependencies. In this case, the `activemerchant`
dependency is treated as `activemerchant 1.7.1 + activesupport 2.3.8`,
so `bundle install` will report that it cannot update `actionpack`.

To explicitly update `actionpack`, including its dependencies
which other gems in the Gemfile(5) still depend on, run
`bundle update actionpack` (see `bundle update(1)`).

`Summary`: In general, after making a change to the Gemfile(5) , you
should first try to run `bundle install`, which will guarantee that no
other gem in the Gemfile(5) is impacted by the change. If that
does not work, run [bundle update(1)](bundle-update.1.html).

## SEE ALSO

* [Gem install docs](http://guides.rubygems.org/rubygems-basics/#installing-gems)
* [Rubygems signing docs](http://guides.rubygems.org/security/)
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-VIZ" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-viz\fR \- Generates a visual dependency graph for your Gemfile
.
.SH "SYNOPSIS"
\fBbundle viz\fR [\-\-file=FILE] [\-\-format=FORMAT] [\-\-requirements] [\-\-version] [\-\-without=GROUP GROUP]
.
.SH "DESCRIPTION"
\fBviz\fR generates a PNG file of the current \fBGemfile(5)\fR as a dependency graph\. \fBviz\fR requires the ruby\-graphviz gem (and its dependencies)\.
.
.P
The associated gems must also be installed via \fBbundle install(1)\fR \fIbundle\-install\.1\.html\fR\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-file\fR, \fB\-f\fR
The name to use for the generated file\. See \fB\-\-format\fR option
.
.TP
\fB\-\-format\fR, \fB\-F\fR
This is output format option\. Supported format is png, jpg, svg, dot \.\.\.
.
.TP
\fB\-\-requirements\fR, \fB\-R\fR
Set to show the version of each required dependency\.
.
.TP
\fB\-\-version\fR, \fB\-v\fR
Set to show each gem version\.
.
.TP
\fB\-\-without\fR, \fB\-W\fR
Exclude gems that are part of the specified named group\.

bundle-open(1) -- Opens the source directory for a gem in your bundle
=====================================================================

## SYNOPSIS

`bundle open` [GEM]

## DESCRIPTION

Opens the source directory of the provided GEM in your editor.

For this to work the `EDITOR` or `BUNDLER_EDITOR` environment variable has to
be set.

Example:

    bundle open 'rack'

Will open the source directory for the 'rack' gem in your bundle.
bundle-info(1) -- Show information for the given gem in your bundle
=========================================================================

## SYNOPSIS

`bundle info` [GEM]
              [--path]

## DESCRIPTION

Print the basic information about the provided GEM such as homepage, version,
path and summary.

## OPTIONS

* `--path`:
Print the path of the given gem
bundle-show(1) -- Shows all the gems in your bundle, or the path to a gem
=========================================================================

## SYNOPSIS

`bundle show` [GEM]
              [--paths]

## DESCRIPTION

Without the [GEM] option, `show` will print a list of the names and versions of
all gems that are required by your [`Gemfile(5)`][Gemfile(5)], sorted by name.

Calling show with [GEM] will list the exact location of that gem on your
machine.

## OPTIONS

* `--paths`:
  List the paths of all gems that are required by your [`Gemfile(5)`][Gemfile(5)],
  sorted by gem name.
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "GEMFILE" "5" "December 2021" "" ""
.
.SH "NAME"
\fBGemfile\fR \- A format for describing gem dependencies for Ruby programs
.
.SH "SYNOPSIS"
A \fBGemfile\fR describes the gem dependencies required to execute associated Ruby code\.
.
.P
Place the \fBGemfile\fR in the root of the directory containing the associated code\. For instance, in a Rails application, place the \fBGemfile\fR in the same directory as the \fBRakefile\fR\.
.
.SH "SYNTAX"
A \fBGemfile\fR is evaluated as Ruby code, in a context which makes available a number of methods used to describe the gem requirements\.
.
.SH "GLOBAL SOURCES"
At the top of the \fBGemfile\fR, add a line for the \fBRubygems\fR source that contains the gems listed in the \fBGemfile\fR\.
.
.IP "" 4
.
.nf

source "https://rubygems\.org"
.
.fi
.
.IP "" 0
.
.P
It is possible, but not recommended as of Bundler 1\.7, to add multiple global \fBsource\fR lines\. Each of these \fBsource\fRs \fBMUST\fR be a valid Rubygems repository\.
.
.P
Sources are checked for gems following the heuristics described in \fISOURCE PRIORITY\fR\. If a gem is found in more than one global source, Bundler will print a warning after installing the gem indicating which source was used, and listing the other sources where the gem is available\. A specific source can be selected for gems that need to use a non\-standard repository, suppressing this warning, by using the \fI\fB:source\fR option\fR or a \fI\fBsource\fR block\fR\.
.
.SS "CREDENTIALS"
Some gem sources require a username and password\. Use bundle config(1) \fIbundle\-config\.1\.html\fR to set the username and password for any of the sources that need it\. The command must be run once on each computer that will install the Gemfile, but this keeps the credentials from being stored in plain text in version control\.
.
.IP "" 4
.
.nf

bundle config gems\.example\.com user:password
.
.fi
.
.IP "" 0
.
.P
For some sources, like a company Gemfury account, it may be easier to include the credentials in the Gemfile as part of the source URL\.
.
.IP "" 4
.
.nf

source "https://user:password@gems\.example\.com"
.
.fi
.
.IP "" 0
.
.P
Credentials in the source URL will take precedence over credentials set using \fBconfig\fR\.
.
.SH "RUBY"
If your application requires a specific Ruby version or engine, specify your requirements using the \fBruby\fR method, with the following arguments\. All parameters are \fBOPTIONAL\fR unless otherwise specified\.
.
.SS "VERSION (required)"
The version of Ruby that your application requires\. If your application requires an alternate Ruby engine, such as JRuby, Rubinius or TruffleRuby, this should be the Ruby version that the engine is compatible with\.
.
.IP "" 4
.
.nf

ruby "1\.9\.3"
.
.fi
.
.IP "" 0
.
.SS "ENGINE"
Each application \fImay\fR specify a Ruby engine\. If an engine is specified, an engine version \fImust\fR also be specified\.
.
.P
What exactly is an Engine? \- A Ruby engine is an implementation of the Ruby language\.
.
.IP "\(bu" 4
For background: the reference or original implementation of the Ruby programming language is called Matz\'s Ruby Interpreter \fIhttps://en\.wikipedia\.org/wiki/Ruby_MRI\fR, or MRI for short\. This is named after Ruby creator Yukihiro Matsumoto, also known as Matz\. MRI is also known as CRuby, because it is written in C\. MRI is the most widely used Ruby engine\.
.
.IP "\(bu" 4
Other implementations \fIhttps://www\.ruby\-lang\.org/en/about/\fR of Ruby exist\. Some of the more well\-known implementations include Rubinius \fIhttps://rubinius\.com/\fR, and JRuby \fIhttp://jruby\.org/\fR\. Rubinius is an alternative implementation of Ruby written in Ruby\. JRuby is an implementation of Ruby on the JVM, short for Java Virtual Machine\.
.
.IP "" 0
.
.SS "ENGINE VERSION"
Each application \fImay\fR specify a Ruby engine version\. If an engine version is specified, an engine \fImust\fR also be specified\. If the engine is "ruby" the engine version specified \fImust\fR match the Ruby version\.
.
.IP "" 4
.
.nf

ruby "1\.8\.7", :engine => "jruby", :engine_version => "1\.6\.7"
.
.fi
.
.IP "" 0
.
.SS "PATCHLEVEL"
Each application \fImay\fR specify a Ruby patchlevel\.
.
.IP "" 4
.
.nf

ruby "2\.0\.0", :patchlevel => "247"
.
.fi
.
.IP "" 0
.
.SH "GEMS"
Specify gem requirements using the \fBgem\fR method, with the following arguments\. All parameters are \fBOPTIONAL\fR unless otherwise specified\.
.
.SS "NAME (required)"
For each gem requirement, list a single \fIgem\fR line\.
.
.IP "" 4
.
.nf

gem "nokogiri"
.
.fi
.
.IP "" 0
.
.SS "VERSION"
Each \fIgem\fR \fBMAY\fR have one or more version specifiers\.
.
.IP "" 4
.
.nf

gem "nokogiri", ">= 1\.4\.2"
gem "RedCloth", ">= 4\.1\.0", "< 4\.2\.0"
.
.fi
.
.IP "" 0
.
.SS "REQUIRE AS"
Each \fIgem\fR \fBMAY\fR specify files that should be used when autorequiring via \fBBundler\.require\fR\. You may pass an array with multiple files or \fBtrue\fR if the file you want \fBrequired\fR has the same name as \fIgem\fR or \fBfalse\fR to prevent any file from being autorequired\.
.
.IP "" 4
.
.nf

gem "redis", :require => ["redis/connection/hiredis", "redis"]
gem "webmock", :require => false
gem "byebug", :require => true
.
.fi
.
.IP "" 0
.
.P
The argument defaults to the name of the gem\. For example, these are identical:
.
.IP "" 4
.
.nf

gem "nokogiri"
gem "nokogiri", :require => "nokogiri"
gem "nokogiri", :require => true
.
.fi
.
.IP "" 0
.
.SS "GROUPS"
Each \fIgem\fR \fBMAY\fR specify membership in one or more groups\. Any \fIgem\fR that does not specify membership in any group is placed in the \fBdefault\fR group\.
.
.IP "" 4
.
.nf

gem "rspec", :group => :test
gem "wirble", :groups => [:development, :test]
.
.fi
.
.IP "" 0
.
.P
The Bundler runtime allows its two main methods, \fBBundler\.setup\fR and \fBBundler\.require\fR, to limit their impact to particular groups\.
.
.IP "" 4
.
.nf

# setup adds gems to Ruby\'s load path
Bundler\.setup                    # defaults to all groups
require "bundler/setup"          # same as Bundler\.setup
Bundler\.setup(:default)          # only set up the _default_ group
Bundler\.setup(:test)             # only set up the _test_ group (but `not` _default_)
Bundler\.setup(:default, :test)   # set up the _default_ and _test_ groups, but no others

# require requires all of the gems in the specified groups
Bundler\.require                  # defaults to the _default_ group
Bundler\.require(:default)        # identical
Bundler\.require(:default, :test) # requires the _default_ and _test_ groups
Bundler\.require(:test)           # requires the _test_ group
.
.fi
.
.IP "" 0
.
.P
The Bundler CLI allows you to specify a list of groups whose gems \fBbundle install\fR should not install with the \fBwithout\fR configuration\.
.
.P
To specify multiple groups to ignore, specify a list of groups separated by spaces\.
.
.IP "" 4
.
.nf

bundle config set \-\-local without test
bundle config set \-\-local without development test
.
.fi
.
.IP "" 0
.
.P
Also, calling \fBBundler\.setup\fR with no parameters, or calling \fBrequire "bundler/setup"\fR will setup all groups except for the ones you excluded via \fB\-\-without\fR (since they are not available)\.
.
.P
Note that on \fBbundle install\fR, bundler downloads and evaluates all gems, in order to create a single canonical list of all of the required gems and their dependencies\. This means that you cannot list different versions of the same gems in different groups\. For more details, see Understanding Bundler \fIhttps://bundler\.io/rationale\.html\fR\.
.
.SS "PLATFORMS"
If a gem should only be used in a particular platform or set of platforms, you can specify them\. Platforms are essentially identical to groups, except that you do not need to use the \fB\-\-without\fR install\-time flag to exclude groups of gems for other platforms\.
.
.P
There are a number of \fBGemfile\fR platforms:
.
.TP
\fBruby\fR
C Ruby (MRI), Rubinius or TruffleRuby, but \fBNOT\fR Windows
.
.TP
\fBmri\fR
Same as \fIruby\fR, but only C Ruby (MRI)
.
.TP
\fBmingw\fR
Windows 32 bit \'mingw32\' platform (aka RubyInstaller)
.
.TP
\fBx64_mingw\fR
Windows 64 bit \'mingw32\' platform (aka RubyInstaller x64)
.
.TP
\fBrbx\fR
Rubinius
.
.TP
\fBjruby\fR
JRuby
.
.TP
\fBtruffleruby\fR
TruffleRuby
.
.TP
\fBmswin\fR
Windows
.
.P
You can restrict further by platform and version for all platforms \fIexcept\fR for \fBrbx\fR, \fBjruby\fR, \fBtruffleruby\fR and \fBmswin\fR\.
.
.P
To specify a version in addition to a platform, append the version number without the delimiter to the platform\. For example, to specify that a gem should only be used on platforms with Ruby 2\.3, use:
.
.IP "" 4
.
.nf

ruby_23
.
.fi
.
.IP "" 0
.
.P
The full list of platforms and supported versions includes:
.
.TP
\fBruby\fR
1\.8, 1\.9, 2\.0, 2\.1, 2\.2, 2\.3, 2\.4, 2\.5, 2\.6
.
.TP
\fBmri\fR
1\.8, 1\.9, 2\.0, 2\.1, 2\.2, 2\.3, 2\.4, 2\.5, 2\.6
.
.TP
\fBmingw\fR
1\.8, 1\.9, 2\.0, 2\.1, 2\.2, 2\.3, 2\.4, 2\.5, 2\.6
.
.TP
\fBx64_mingw\fR
2\.0, 2\.1, 2\.2, 2\.3, 2\.4, 2\.5, 2\.6
.
.P
As with groups, you can specify one or more platforms:
.
.IP "" 4
.
.nf

gem "weakling",   :platforms => :jruby
gem "ruby\-debug", :platforms => :mri_18
gem "nokogiri",   :platforms => [:mri_18, :jruby]
.
.fi
.
.IP "" 0
.
.P
All operations involving groups (\fBbundle install\fR \fIbundle\-install\.1\.html\fR, \fBBundler\.setup\fR, \fBBundler\.require\fR) behave exactly the same as if any groups not matching the current platform were explicitly excluded\.
.
.SS "SOURCE"
You can select an alternate Rubygems repository for a gem using the \':source\' option\.
.
.IP "" 4
.
.nf

gem "some_internal_gem", :source => "https://gems\.example\.com"
.
.fi
.
.IP "" 0
.
.P
This forces the gem to be loaded from this source and ignores any global sources declared at the top level of the file\. If the gem does not exist in this source, it will not be installed\.
.
.P
Bundler will search for child dependencies of this gem by first looking in the source selected for the parent, but if they are not found there, it will fall back on global sources using the ordering described in \fISOURCE PRIORITY\fR\.
.
.P
Selecting a specific source repository this way also suppresses the ambiguous gem warning described above in \fIGLOBAL SOURCES (#source)\fR\.
.
.P
Using the \fB:source\fR option for an individual gem will also make that source available as a possible global source for any other gems which do not specify explicit sources\. Thus, when adding gems with explicit sources, it is recommended that you also ensure all other gems in the Gemfile are using explicit sources\.
.
.SS "GIT"
If necessary, you can specify that a gem is located at a particular git repository using the \fB:git\fR parameter\. The repository can be accessed via several protocols:
.
.TP
\fBHTTP(S)\fR
gem "rails", :git => "https://github\.com/rails/rails\.git"
.
.TP
\fBSSH\fR
gem "rails", :git => "git@github\.com:rails/rails\.git"
.
.TP
\fBgit\fR
gem "rails", :git => "git://github\.com/rails/rails\.git"
.
.P
If using SSH, the user that you use to run \fBbundle install\fR \fBMUST\fR have the appropriate keys available in their \fB$HOME/\.ssh\fR\.
.
.P
\fBNOTE\fR: \fBhttp://\fR and \fBgit://\fR URLs should be avoided if at all possible\. These protocols are unauthenticated, so a man\-in\-the\-middle attacker can deliver malicious code and compromise your system\. HTTPS and SSH are strongly preferred\.
.
.P
The \fBgroup\fR, \fBplatforms\fR, and \fBrequire\fR options are available and behave exactly the same as they would for a normal gem\.
.
.P
A git repository \fBSHOULD\fR have at least one file, at the root of the directory containing the gem, with the extension \fB\.gemspec\fR\. This file \fBMUST\fR contain a valid gem specification, as expected by the \fBgem build\fR command\.
.
.P
If a git repository does not have a \fB\.gemspec\fR, bundler will attempt to create one, but it will not contain any dependencies, executables, or C extension compilation instructions\. As a result, it may fail to properly integrate into your application\.
.
.P
If a git repository does have a \fB\.gemspec\fR for the gem you attached it to, a version specifier, if provided, means that the git repository is only valid if the \fB\.gemspec\fR specifies a version matching the version specifier\. If not, bundler will print a warning\.
.
.IP "" 4
.
.nf

gem "rails", "2\.3\.8", :git => "https://github\.com/rails/rails\.git"
# bundle install will fail, because the \.gemspec in the rails
# repository\'s master branch specifies version 3\.0\.0
.
.fi
.
.IP "" 0
.
.P
If a git repository does \fBnot\fR have a \fB\.gemspec\fR for the gem you attached it to, a version specifier \fBMUST\fR be provided\. Bundler will use this version in the simple \fB\.gemspec\fR it creates\.
.
.P
Git repositories support a number of additional options\.
.
.TP
\fBbranch\fR, \fBtag\fR, and \fBref\fR
You \fBMUST\fR only specify at most one of these options\. The default is \fB:branch => "master"\fR\. For example:
.
.IP
gem "rails", :git => "https://github\.com/rails/rails\.git", :branch => "5\-0\-stable"
.
.IP
gem "rails", :git => "https://github\.com/rails/rails\.git", :tag => "v5\.0\.0"
.
.IP
gem "rails", :git => "https://github\.com/rails/rails\.git", :ref => "4aded"
.
.TP
\fBsubmodules\fR
For reference, a git submodule \fIhttps://git\-scm\.com/book/en/v2/Git\-Tools\-Submodules\fR lets you have another git repository within a subfolder of your repository\. Specify \fB:submodules => true\fR to cause bundler to expand any submodules included in the git repository
.
.P
If a git repository contains multiple \fB\.gemspecs\fR, each \fB\.gemspec\fR represents a gem located at the same place in the file system as the \fB\.gemspec\fR\.
.
.IP "" 4
.
.nf

|~rails                   [git root]
| |\-rails\.gemspec         [rails gem located here]
|~actionpack
| |\-actionpack\.gemspec    [actionpack gem located here]
|~activesupport
| |\-activesupport\.gemspec [activesupport gem located here]
|\.\.\.
.
.fi
.
.IP "" 0
.
.P
To install a gem located in a git repository, bundler changes to the directory containing the gemspec, runs \fBgem build name\.gemspec\fR and then installs the resulting gem\. The \fBgem build\fR command, which comes standard with Rubygems, evaluates the \fB\.gemspec\fR in the context of the directory in which it is located\.
.
.SS "GIT SOURCE"
A custom git source can be defined via the \fBgit_source\fR method\. Provide the source\'s name as an argument, and a block which receives a single argument and interpolates it into a string to return the full repo address:
.
.IP "" 4
.
.nf

git_source(:stash){ |repo_name| "https://stash\.corp\.acme\.pl/#{repo_name}\.git" }
gem \'rails\', :stash => \'forks/rails\'
.
.fi
.
.IP "" 0
.
.P
In addition, if you wish to choose a specific branch:
.
.IP "" 4
.
.nf

gem "rails", :stash => "forks/rails", :branch => "branch_name"
.
.fi
.
.IP "" 0
.
.SS "GITHUB"
\fBNOTE\fR: This shorthand should be avoided until Bundler 2\.0, since it currently expands to an insecure \fBgit://\fR URL\. This allows a man\-in\-the\-middle attacker to compromise your system\.
.
.P
If the git repository you want to use is hosted on GitHub and is public, you can use the :github shorthand to specify the github username and repository name (without the trailing "\.git"), separated by a slash\. If both the username and repository name are the same, you can omit one\.
.
.IP "" 4
.
.nf

gem "rails", :github => "rails/rails"
gem "rails", :github => "rails"
.
.fi
.
.IP "" 0
.
.P
Are both equivalent to
.
.IP "" 4
.
.nf

gem "rails", :git => "git://github\.com/rails/rails\.git"
.
.fi
.
.IP "" 0
.
.P
Since the \fBgithub\fR method is a specialization of \fBgit_source\fR, it accepts a \fB:branch\fR named argument\.
.
.P
You can also directly pass a pull request URL:
.
.IP "" 4
.
.nf

gem "rails", :github => "https://github\.com/rails/rails/pull/43753"
.
.fi
.
.IP "" 0
.
.P
Which is equivalent to:
.
.IP "" 4
.
.nf

gem "rails", :github => "rails/rails", branch: "refs/pull/43753/head"
.
.fi
.
.IP "" 0
.
.SS "GIST"
If the git repository you want to use is hosted as a Github Gist and is public, you can use the :gist shorthand to specify the gist identifier (without the trailing "\.git")\.
.
.IP "" 4
.
.nf

gem "the_hatch", :gist => "4815162342"
.
.fi
.
.IP "" 0
.
.P
Is equivalent to:
.
.IP "" 4
.
.nf

gem "the_hatch", :git => "https://gist\.github\.com/4815162342\.git"
.
.fi
.
.IP "" 0
.
.P
Since the \fBgist\fR method is a specialization of \fBgit_source\fR, it accepts a \fB:branch\fR named argument\.
.
.SS "BITBUCKET"
If the git repository you want to use is hosted on Bitbucket and is public, you can use the :bitbucket shorthand to specify the bitbucket username and repository name (without the trailing "\.git"), separated by a slash\. If both the username and repository name are the same, you can omit one\.
.
.IP "" 4
.
.nf

gem "rails", :bitbucket => "rails/rails"
gem "rails", :bitbucket => "rails"
.
.fi
.
.IP "" 0
.
.P
Are both equivalent to
.
.IP "" 4
.
.nf

gem "rails", :git => "https://rails@bitbucket\.org/rails/rails\.git"
.
.fi
.
.IP "" 0
.
.P
Since the \fBbitbucket\fR method is a specialization of \fBgit_source\fR, it accepts a \fB:branch\fR named argument\.
.
.SS "PATH"
You can specify that a gem is located in a particular location on the file system\. Relative paths are resolved relative to the directory containing the \fBGemfile\fR\.
.
.P
Similar to the semantics of the \fB:git\fR option, the \fB:path\fR option requires that the directory in question either contains a \fB\.gemspec\fR for the gem, or that you specify an explicit version that bundler should use\.
.
.P
Unlike \fB:git\fR, bundler does not compile C extensions for gems specified as paths\.
.
.IP "" 4
.
.nf

gem "rails", :path => "vendor/rails"
.
.fi
.
.IP "" 0
.
.P
If you would like to use multiple local gems directly from the filesystem, you can set a global \fBpath\fR option to the path containing the gem\'s files\. This will automatically load gemspec files from subdirectories\.
.
.IP "" 4
.
.nf

path \'components\' do
  gem \'admin_ui\'
  gem \'public_ui\'
end
.
.fi
.
.IP "" 0
.
.SH "BLOCK FORM OF SOURCE, GIT, PATH, GROUP and PLATFORMS"
The \fB:source\fR, \fB:git\fR, \fB:path\fR, \fB:group\fR, and \fB:platforms\fR options may be applied to a group of gems by using block form\.
.
.IP "" 4
.
.nf

source "https://gems\.example\.com" do
  gem "some_internal_gem"
  gem "another_internal_gem"
end

git "https://github\.com/rails/rails\.git" do
  gem "activesupport"
  gem "actionpack"
end

platforms :ruby do
  gem "ruby\-debug"
  gem "sqlite3"
end

group :development, :optional => true do
  gem "wirble"
  gem "faker"
end
.
.fi
.
.IP "" 0
.
.P
In the case of the group block form the :optional option can be given to prevent a group from being installed unless listed in the \fB\-\-with\fR option given to the \fBbundle install\fR command\.
.
.P
In the case of the \fBgit\fR block form, the \fB:ref\fR, \fB:branch\fR, \fB:tag\fR, and \fB:submodules\fR options may be passed to the \fBgit\fR method, and all gems in the block will inherit those options\.
.
.P
The presence of a \fBsource\fR block in a Gemfile also makes that source available as a possible global source for any other gems which do not specify explicit sources\. Thus, when defining source blocks, it is recommended that you also ensure all other gems in the Gemfile are using explicit sources, either via source blocks or \fB:source\fR directives on individual gems\.
.
.SH "INSTALL_IF"
The \fBinstall_if\fR method allows gems to be installed based on a proc or lambda\. This is especially useful for optional gems that can only be used if certain software is installed or some other conditions are met\.
.
.IP "" 4
.
.nf

install_if \-> { RUBY_PLATFORM =~ /darwin/ } do
  gem "pasteboard"
end
.
.fi
.
.IP "" 0
.
.SH "GEMSPEC"
The \fB\.gemspec\fR \fIhttp://guides\.rubygems\.org/specification\-reference/\fR file is where you provide metadata about your gem to Rubygems\. Some required Gemspec attributes include the name, description, and homepage of your gem\. This is also where you specify the dependencies your gem needs to run\.
.
.P
If you wish to use Bundler to help install dependencies for a gem while it is being developed, use the \fBgemspec\fR method to pull in the dependencies listed in the \fB\.gemspec\fR file\.
.
.P
The \fBgemspec\fR method adds any runtime dependencies as gem requirements in the default group\. It also adds development dependencies as gem requirements in the \fBdevelopment\fR group\. Finally, it adds a gem requirement on your project (\fB:path => \'\.\'\fR)\. In conjunction with \fBBundler\.setup\fR, this allows you to require project files in your test code as you would if the project were installed as a gem; you need not manipulate the load path manually or require project files via relative paths\.
.
.P
The \fBgemspec\fR method supports optional \fB:path\fR, \fB:glob\fR, \fB:name\fR, and \fB:development_group\fR options, which control where bundler looks for the \fB\.gemspec\fR, the glob it uses to look for the gemspec (defaults to: "{,\fI,\fR/*}\.gemspec"), what named \fB\.gemspec\fR it uses (if more than one is present), and which group development dependencies are included in\.
.
.P
When a \fBgemspec\fR dependency encounters version conflicts during resolution, the local version under development will always be selected \-\- even if there are remote versions that better match other requirements for the \fBgemspec\fR gem\.
.
.SH "SOURCE PRIORITY"
When attempting to locate a gem to satisfy a gem requirement, bundler uses the following priority order:
.
.IP "1." 4
The source explicitly attached to the gem (using \fB:source\fR, \fB:path\fR, or \fB:git\fR)
.
.IP "2." 4
For implicit gems (dependencies of explicit gems), any source, git, or path repository declared on the parent\. This results in bundler prioritizing the ActiveSupport gem from the Rails git repository over ones from \fBrubygems\.org\fR
.
.IP "3." 4
The sources specified via global \fBsource\fR lines, searching each source in your \fBGemfile\fR from last added to first added\.
.
.IP "" 0

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-PLATFORM" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-platform\fR \- Displays platform compatibility information
.
.SH "SYNOPSIS"
\fBbundle platform\fR [\-\-ruby]
.
.SH "DESCRIPTION"
\fBplatform\fR will display information from your Gemfile, Gemfile\.lock, and Ruby VM about your platform\.
.
.P
For instance, using this Gemfile(5):
.
.IP "" 4
.
.nf

source "https://rubygems\.org"

ruby "1\.9\.3"

gem "rack"
.
.fi
.
.IP "" 0
.
.P
If you run \fBbundle platform\fR on Ruby 1\.9\.3, it will display the following output:
.
.IP "" 4
.
.nf

Your platform is: x86_64\-linux

Your app has gems that work on these platforms:
* ruby

Your Gemfile specifies a Ruby version requirement:
* ruby 1\.9\.3

Your current platform satisfies the Ruby version requirement\.
.
.fi
.
.IP "" 0
.
.P
\fBplatform\fR will list all the platforms in your \fBGemfile\.lock\fR as well as the \fBruby\fR directive if applicable from your Gemfile(5)\. It will also let you know if the \fBruby\fR directive requirement has been met\. If \fBruby\fR directive doesn\'t match the running Ruby VM, it will tell you what part does not\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-ruby\fR
It will display the ruby directive information, so you don\'t have to parse it from the Gemfile(5)\.

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-INSTALL" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-install\fR \- Install the dependencies specified in your Gemfile
.
.SH "SYNOPSIS"
\fBbundle install\fR [\-\-binstubs[=DIRECTORY]] [\-\-clean] [\-\-deployment] [\-\-frozen] [\-\-full\-index] [\-\-gemfile=GEMFILE] [\-\-jobs=NUMBER] [\-\-local] [\-\-no\-cache] [\-\-no\-prune] [\-\-path PATH] [\-\-quiet] [\-\-redownload] [\-\-retry=NUMBER] [\-\-shebang] [\-\-standalone[=GROUP[ GROUP\.\.\.]]] [\-\-system] [\-\-trust\-policy=POLICY] [\-\-with=GROUP[ GROUP\.\.\.]] [\-\-without=GROUP[ GROUP\.\.\.]]
.
.SH "DESCRIPTION"
Install the gems specified in your Gemfile(5)\. If this is the first time you run bundle install (and a \fBGemfile\.lock\fR does not exist), Bundler will fetch all remote sources, resolve dependencies and install all needed gems\.
.
.P
If a \fBGemfile\.lock\fR does exist, and you have not updated your Gemfile(5), Bundler will fetch all remote sources, but use the dependencies specified in the \fBGemfile\.lock\fR instead of resolving dependencies\.
.
.P
If a \fBGemfile\.lock\fR does exist, and you have updated your Gemfile(5), Bundler will use the dependencies in the \fBGemfile\.lock\fR for all gems that you did not update, but will re\-resolve the dependencies of gems that you did update\. You can find more information about this update process below under \fICONSERVATIVE UPDATING\fR\.
.
.SH "OPTIONS"
The \fB\-\-clean\fR, \fB\-\-deployment\fR, \fB\-\-frozen\fR, \fB\-\-no\-prune\fR, \fB\-\-path\fR, \fB\-\-shebang\fR, \fB\-\-system\fR, \fB\-\-without\fR and \fB\-\-with\fR options are deprecated because they only make sense if they are applied to every subsequent \fBbundle install\fR run automatically and that requires \fBbundler\fR to silently remember them\. Since \fBbundler\fR will no longer remember CLI flags in future versions, \fBbundle config\fR (see bundle\-config(1)) should be used to apply them permanently\.
.
.TP
\fB\-\-binstubs[=<directory>]\fR
Binstubs are scripts that wrap around executables\. Bundler creates a small Ruby file (a binstub) that loads Bundler, runs the command, and puts it in \fBbin/\fR\. This lets you link the binstub inside of an application to the exact gem version the application needs\.
.
.IP
Creates a directory (defaults to \fB~/bin\fR) and places any executables from the gem there\. These executables run in Bundler\'s context\. If used, you might add this directory to your environment\'s \fBPATH\fR variable\. For instance, if the \fBrails\fR gem comes with a \fBrails\fR executable, this flag will create a \fBbin/rails\fR executable that ensures that all referred dependencies will be resolved using the bundled gems\.
.
.TP
\fB\-\-clean\fR
On finishing the installation Bundler is going to remove any gems not present in the current Gemfile(5)\. Don\'t worry, gems currently in use will not be removed\.
.
.IP
This option is deprecated in favor of the \fBclean\fR setting\.
.
.TP
\fB\-\-deployment\fR
In \fIdeployment mode\fR, Bundler will \'roll\-out\' the bundle for production or CI use\. Please check carefully if you want to have this option enabled in your development environment\.
.
.IP
This option is deprecated in favor of the \fBdeployment\fR setting\.
.
.TP
\fB\-\-redownload\fR
Force download every gem, even if the required versions are already available locally\.
.
.TP
\fB\-\-frozen\fR
Do not allow the Gemfile\.lock to be updated after this install\. Exits non\-zero if there are going to be changes to the Gemfile\.lock\.
.
.IP
This option is deprecated in favor of the \fBfrozen\fR setting\.
.
.TP
\fB\-\-full\-index\fR
Bundler will not call Rubygems\' API endpoint (default) but download and cache a (currently big) index file of all gems\. Performance can be improved for large bundles that seldom change by enabling this option\.
.
.TP
\fB\-\-gemfile=<gemfile>\fR
The location of the Gemfile(5) which Bundler should use\. This defaults to a Gemfile(5) in the current working directory\. In general, Bundler will assume that the location of the Gemfile(5) is also the project\'s root and will try to find \fBGemfile\.lock\fR and \fBvendor/cache\fR relative to this location\.
.
.TP
\fB\-\-jobs=[<number>]\fR, \fB\-j[<number>]\fR
The maximum number of parallel download and install jobs\. The default is \fB1\fR\.
.
.TP
\fB\-\-local\fR
Do not attempt to connect to \fBrubygems\.org\fR\. Instead, Bundler will use the gems already present in Rubygems\' cache or in \fBvendor/cache\fR\. Note that if an appropriate platform\-specific gem exists on \fBrubygems\.org\fR it will not be found\.
.
.TP
\fB\-\-no\-cache\fR
Do not update the cache in \fBvendor/cache\fR with the newly bundled gems\. This does not remove any gems in the cache but keeps the newly bundled gems from being cached during the install\.
.
.TP
\fB\-\-no\-prune\fR
Don\'t remove stale gems from the cache when the installation finishes\.
.
.IP
This option is deprecated in favor of the \fBno_prune\fR setting\.
.
.TP
\fB\-\-path=<path>\fR
The location to install the specified gems to\. This defaults to Rubygems\' setting\. Bundler shares this location with Rubygems, \fBgem install \.\.\.\fR will have gem installed there, too\. Therefore, gems installed without a \fB\-\-path \.\.\.\fR setting will show up by calling \fBgem list\fR\. Accordingly, gems installed to other locations will not get listed\.
.
.IP
This option is deprecated in favor of the \fBpath\fR setting\.
.
.TP
\fB\-\-quiet\fR
Do not print progress information to the standard output\. Instead, Bundler will exit using a status code (\fB$?\fR)\.
.
.TP
\fB\-\-retry=[<number>]\fR
Retry failed network or git requests for \fInumber\fR times\.
.
.TP
\fB\-\-shebang=<ruby\-executable>\fR
Uses the specified ruby executable (usually \fBruby\fR) to execute the scripts created with \fB\-\-binstubs\fR\. In addition, if you use \fB\-\-binstubs\fR together with \fB\-\-shebang jruby\fR these executables will be changed to execute \fBjruby\fR instead\.
.
.IP
This option is deprecated in favor of the \fBshebang\fR setting\.
.
.TP
\fB\-\-standalone[=<list>]\fR
Makes a bundle that can work without depending on Rubygems or Bundler at runtime\. A space separated list of groups to install has to be specified\. Bundler creates a directory named \fBbundle\fR and installs the bundle there\. It also generates a \fBbundle/bundler/setup\.rb\fR file to replace Bundler\'s own setup in the manner required\. Using this option implicitly sets \fBpath\fR, which is a [remembered option][REMEMBERED OPTIONS]\.
.
.TP
\fB\-\-system\fR
Installs the gems specified in the bundle to the system\'s Rubygems location\. This overrides any previous configuration of \fB\-\-path\fR\.
.
.IP
This option is deprecated in favor of the \fBsystem\fR setting\.
.
.TP
\fB\-\-trust\-policy=[<policy>]\fR
Apply the Rubygems security policy \fIpolicy\fR, where policy is one of \fBHighSecurity\fR, \fBMediumSecurity\fR, \fBLowSecurity\fR, \fBAlmostNoSecurity\fR, or \fBNoSecurity\fR\. For more details, please see the Rubygems signing documentation linked below in \fISEE ALSO\fR\.
.
.TP
\fB\-\-with=<list>\fR
A space\-separated list of groups referencing gems to install\. If an optional group is given it is installed\. If a group is given that is in the remembered list of groups given to \-\-without, it is removed from that list\.
.
.IP
This option is deprecated in favor of the \fBwith\fR setting\.
.
.TP
\fB\-\-without=<list>\fR
A space\-separated list of groups referencing gems to skip during installation\. If a group is given that is in the remembered list of groups given to \-\-with, it is removed from that list\.
.
.IP
This option is deprecated in favor of the \fBwithout\fR setting\.
.
.SH "DEPLOYMENT MODE"
Bundler\'s defaults are optimized for development\. To switch to defaults optimized for deployment and for CI, use the \fB\-\-deployment\fR flag\. Do not activate deployment mode on development machines, as it will cause an error when the Gemfile(5) is modified\.
.
.IP "1." 4
A \fBGemfile\.lock\fR is required\.
.
.IP
To ensure that the same versions of the gems you developed with and tested with are also used in deployments, a \fBGemfile\.lock\fR is required\.
.
.IP
This is mainly to ensure that you remember to check your \fBGemfile\.lock\fR into version control\.
.
.IP "2." 4
The \fBGemfile\.lock\fR must be up to date
.
.IP
In development, you can modify your Gemfile(5) and re\-run \fBbundle install\fR to \fIconservatively update\fR your \fBGemfile\.lock\fR snapshot\.
.
.IP
In deployment, your \fBGemfile\.lock\fR should be up\-to\-date with changes made in your Gemfile(5)\.
.
.IP "3." 4
Gems are installed to \fBvendor/bundle\fR not your default system location
.
.IP
In development, it\'s convenient to share the gems used in your application with other applications and other scripts that run on the system\.
.
.IP
In deployment, isolation is a more important default\. In addition, the user deploying the application may not have permission to install gems to the system, or the web server may not have permission to read them\.
.
.IP
As a result, \fBbundle install \-\-deployment\fR installs gems to the \fBvendor/bundle\fR directory in the application\. This may be overridden using the \fB\-\-path\fR option\.
.
.IP "" 0
.
.SH "SUDO USAGE"
By default, Bundler installs gems to the same location as \fBgem install\fR\.
.
.P
In some cases, that location may not be writable by your Unix user\. In that case, Bundler will stage everything in a temporary directory, then ask you for your \fBsudo\fR password in order to copy the gems into their system location\.
.
.P
From your perspective, this is identical to installing the gems directly into the system\.
.
.P
You should never use \fBsudo bundle install\fR\. This is because several other steps in \fBbundle install\fR must be performed as the current user:
.
.IP "\(bu" 4
Updating your \fBGemfile\.lock\fR
.
.IP "\(bu" 4
Updating your \fBvendor/cache\fR, if necessary
.
.IP "\(bu" 4
Checking out private git repositories using your user\'s SSH keys
.
.IP "" 0
.
.P
Of these three, the first two could theoretically be performed by \fBchown\fRing the resulting files to \fB$SUDO_USER\fR\. The third, however, can only be performed by invoking the \fBgit\fR command as the current user\. Therefore, git gems are downloaded and installed into \fB~/\.bundle\fR rather than $GEM_HOME or $BUNDLE_PATH\.
.
.P
As a result, you should run \fBbundle install\fR as the current user, and Bundler will ask for your password if it is needed to put the gems into their final location\.
.
.SH "INSTALLING GROUPS"
By default, \fBbundle install\fR will install all gems in all groups in your Gemfile(5), except those declared for a different platform\.
.
.P
However, you can explicitly tell Bundler to skip installing certain groups with the \fB\-\-without\fR option\. This option takes a space\-separated list of groups\.
.
.P
While the \fB\-\-without\fR option will skip \fIinstalling\fR the gems in the specified groups, it will still \fIdownload\fR those gems and use them to resolve the dependencies of every gem in your Gemfile(5)\.
.
.P
This is so that installing a different set of groups on another machine (such as a production server) will not change the gems and versions that you have already developed and tested against\.
.
.P
\fBBundler offers a rock\-solid guarantee that the third\-party code you are running in development and testing is also the third\-party code you are running in production\. You can choose to exclude some of that code in different environments, but you will never be caught flat\-footed by different versions of third\-party code being used in different environments\.\fR
.
.P
For a simple illustration, consider the following Gemfile(5):
.
.IP "" 4
.
.nf

source \'https://rubygems\.org\'

gem \'sinatra\'

group :production do
  gem \'rack\-perftools\-profiler\'
end
.
.fi
.
.IP "" 0
.
.P
In this case, \fBsinatra\fR depends on any version of Rack (\fB>= 1\.0\fR), while \fBrack\-perftools\-profiler\fR depends on 1\.x (\fB~> 1\.0\fR)\.
.
.P
When you run \fBbundle install \-\-without production\fR in development, we look at the dependencies of \fBrack\-perftools\-profiler\fR as well\. That way, you do not spend all your time developing against Rack 2\.0, using new APIs unavailable in Rack 1\.x, only to have Bundler switch to Rack 1\.2 when the \fBproduction\fR group \fIis\fR used\.
.
.P
This should not cause any problems in practice, because we do not attempt to \fBinstall\fR the gems in the excluded groups, and only evaluate as part of the dependency resolution process\.
.
.P
This also means that you cannot include different versions of the same gem in different groups, because doing so would result in different sets of dependencies used in development and production\. Because of the vagaries of the dependency resolution process, this usually affects more than the gems you list in your Gemfile(5), and can (surprisingly) radically change the gems you are using\.
.
.SH "THE GEMFILE\.LOCK"
When you run \fBbundle install\fR, Bundler will persist the full names and versions of all gems that you used (including dependencies of the gems specified in the Gemfile(5)) into a file called \fBGemfile\.lock\fR\.
.
.P
Bundler uses this file in all subsequent calls to \fBbundle install\fR, which guarantees that you always use the same exact code, even as your application moves across machines\.
.
.P
Because of the way dependency resolution works, even a seemingly small change (for instance, an update to a point\-release of a dependency of a gem in your Gemfile(5)) can result in radically different gems being needed to satisfy all dependencies\.
.
.P
As a result, you \fBSHOULD\fR check your \fBGemfile\.lock\fR into version control, in both applications and gems\. If you do not, every machine that checks out your repository (including your production server) will resolve all dependencies again, which will result in different versions of third\-party code being used if \fBany\fR of the gems in the Gemfile(5) or any of their dependencies have been updated\.
.
.P
When Bundler first shipped, the \fBGemfile\.lock\fR was included in the \fB\.gitignore\fR file included with generated gems\. Over time, however, it became clear that this practice forces the pain of broken dependencies onto new contributors, while leaving existing contributors potentially unaware of the problem\. Since \fBbundle install\fR is usually the first step towards a contribution, the pain of broken dependencies would discourage new contributors from contributing\. As a result, we have revised our guidance for gem authors to now recommend checking in the lock for gems\.
.
.SH "CONSERVATIVE UPDATING"
When you make a change to the Gemfile(5) and then run \fBbundle install\fR, Bundler will update only the gems that you modified\.
.
.P
In other words, if a gem that you \fBdid not modify\fR worked before you called \fBbundle install\fR, it will continue to use the exact same versions of all dependencies as it used before the update\.
.
.P
Let\'s take a look at an example\. Here\'s your original Gemfile(5):
.
.IP "" 4
.
.nf

source \'https://rubygems\.org\'

gem \'actionpack\', \'2\.3\.8\'
gem \'activemerchant\'
.
.fi
.
.IP "" 0
.
.P
In this case, both \fBactionpack\fR and \fBactivemerchant\fR depend on \fBactivesupport\fR\. The \fBactionpack\fR gem depends on \fBactivesupport 2\.3\.8\fR and \fBrack ~> 1\.1\.0\fR, while the \fBactivemerchant\fR gem depends on \fBactivesupport >= 2\.3\.2\fR, \fBbraintree >= 2\.0\.0\fR, and \fBbuilder >= 2\.0\.0\fR\.
.
.P
When the dependencies are first resolved, Bundler will select \fBactivesupport 2\.3\.8\fR, which satisfies the requirements of both gems in your Gemfile(5)\.
.
.P
Next, you modify your Gemfile(5) to:
.
.IP "" 4
.
.nf

source \'https://rubygems\.org\'

gem \'actionpack\', \'3\.0\.0\.rc\'
gem \'activemerchant\'
.
.fi
.
.IP "" 0
.
.P
The \fBactionpack 3\.0\.0\.rc\fR gem has a number of new dependencies, and updates the \fBactivesupport\fR dependency to \fB= 3\.0\.0\.rc\fR and the \fBrack\fR dependency to \fB~> 1\.2\.1\fR\.
.
.P
When you run \fBbundle install\fR, Bundler notices that you changed the \fBactionpack\fR gem, but not the \fBactivemerchant\fR gem\. It evaluates the gems currently being used to satisfy its requirements:
.
.TP
\fBactivesupport 2\.3\.8\fR
also used to satisfy a dependency in \fBactivemerchant\fR, which is not being updated
.
.TP
\fBrack ~> 1\.1\.0\fR
not currently being used to satisfy another dependency
.
.P
Because you did not explicitly ask to update \fBactivemerchant\fR, you would not expect it to suddenly stop working after updating \fBactionpack\fR\. However, satisfying the new \fBactivesupport 3\.0\.0\.rc\fR dependency of actionpack requires updating one of its dependencies\.
.
.P
Even though \fBactivemerchant\fR declares a very loose dependency that theoretically matches \fBactivesupport 3\.0\.0\.rc\fR, Bundler treats gems in your Gemfile(5) that have not changed as an atomic unit together with their dependencies\. In this case, the \fBactivemerchant\fR dependency is treated as \fBactivemerchant 1\.7\.1 + activesupport 2\.3\.8\fR, so \fBbundle install\fR will report that it cannot update \fBactionpack\fR\.
.
.P
To explicitly update \fBactionpack\fR, including its dependencies which other gems in the Gemfile(5) still depend on, run \fBbundle update actionpack\fR (see \fBbundle update(1)\fR)\.
.
.P
\fBSummary\fR: In general, after making a change to the Gemfile(5) , you should first try to run \fBbundle install\fR, which will guarantee that no other gem in the Gemfile(5) is impacted by the change\. If that does not work, run bundle update(1) \fIbundle\-update\.1\.html\fR\.
.
.SH "SEE ALSO"
.
.IP "\(bu" 4
Gem install docs \fIhttp://guides\.rubygems\.org/rubygems\-basics/#installing\-gems\fR
.
.IP "\(bu" 4
Rubygems signing docs \fIhttp://guides\.rubygems\.org/security/\fR
.
.IP "" 0

bundle-platform(1) -- Displays platform compatibility information
=================================================================

## SYNOPSIS

`bundle platform` [--ruby]

## DESCRIPTION

`platform` will display information from your Gemfile, Gemfile.lock, and Ruby
VM about your platform.

For instance, using this Gemfile(5):

    source "https://rubygems.org"

    ruby "1.9.3"

    gem "rack"

If you run `bundle platform` on Ruby 1.9.3, it will display the following output:

    Your platform is: x86_64-linux

    Your app has gems that work on these platforms:
    * ruby

    Your Gemfile specifies a Ruby version requirement:
    * ruby 1.9.3

    Your current platform satisfies the Ruby version requirement.

`platform` will list all the platforms in your `Gemfile.lock` as well as the
`ruby` directive if applicable from your Gemfile(5). It will also let you know
if the `ruby` directive requirement has been met. If `ruby` directive doesn't
match the running Ruby VM, it will tell you what part does not.

## OPTIONS

* `--ruby`:
  It will display the ruby directive information, so you don't have to
  parse it from the Gemfile(5).
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-INJECT" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-inject\fR \- Add named gem(s) with version requirements to Gemfile
.
.SH "SYNOPSIS"
\fBbundle inject\fR [GEM] [VERSION]
.
.SH "DESCRIPTION"
Adds the named gem(s) with their version requirements to the resolved [\fBGemfile(5)\fR][Gemfile(5)]\.
.
.P
This command will add the gem to both your [\fBGemfile(5)\fR][Gemfile(5)] and Gemfile\.lock if it isn\'t listed yet\.
.
.P
Example:
.
.IP "" 4
.
.nf

bundle install
bundle inject \'rack\' \'> 0\'
.
.fi
.
.IP "" 0
.
.P
This will inject the \'rack\' gem with a version greater than 0 in your [\fBGemfile(5)\fR][Gemfile(5)] and Gemfile\.lock
bundle-binstubs(1) -- Install the binstubs of the listed gems
=============================================================

## SYNOPSIS

`bundle binstubs` <GEM_NAME> [--force] [--path PATH] [--standalone]

## DESCRIPTION

Binstubs are scripts that wrap around executables. Bundler creates a
small Ruby file (a binstub) that loads Bundler, runs the command,
and puts it into `bin/`. Binstubs are a shortcut-or alternative-
to always using `bundle exec`. This gives you a file that can be run
directly, and one that will always run the correct gem version
used by the application.

For example, if you run `bundle binstubs rspec-core`, Bundler will create
the file `bin/rspec`. That file will contain enough code to load Bundler,
tell it to load the bundled gems, and then run rspec.

This command generates binstubs for executables in `GEM_NAME`.
Binstubs are put into `bin`, or the `--path` directory if one has been set.
Calling binstubs with [GEM [GEM]] will create binstubs for all given gems.

## OPTIONS

* `--force`:
  Overwrite existing binstubs if they exist.

* `--path`:
  The location to install the specified binstubs to. This defaults to `bin`.

* `--standalone`:
  Makes binstubs that can work without depending on Rubygems or Bundler at
  runtime.

* `--shebang`:
  Specify a different shebang executable name than the default (default 'ruby')

* `--all`:
  Create binstubs for all gems in the bundle.
bundle-outdated(1) -- List installed gems with newer versions available
=======================================================================

## SYNOPSIS

`bundle outdated` [GEM] [--local]
                        [--pre]
                        [--source]
                        [--strict]
                        [--parseable | --porcelain]
                        [--group=GROUP]
                        [--groups]
                        [--update-strict]
                        [--patch|--minor|--major]
                        [--filter-major]
                        [--filter-minor]
                        [--filter-patch]
                        [--only-explicit]

## DESCRIPTION

Outdated lists the names and versions of gems that have a newer version available
in the given source. Calling outdated with [GEM [GEM]] will only check for newer
versions of the given gems. Prerelease gems are ignored by default. If your gems
are up to date, Bundler will exit with a status of 0. Otherwise, it will exit 1.

## OPTIONS

* `--local`:
  Do not attempt to fetch gems remotely and use the gem cache instead.

* `--pre`:
  Check for newer pre-release gems.

* `--source`:
  Check against a specific source.

* `--strict`:
  Only list newer versions allowed by your Gemfile requirements.

* `--parseable`, `--porcelain`:
   Use minimal formatting for more parseable output.

* `--group`:
  List gems from a specific group.

* `--groups`:
  List gems organized by groups.

* `--update-strict`:
  Strict conservative resolution, do not allow any gem to be updated past latest --patch | --minor| --major.

* `--minor`:
  Prefer updating only to next minor version.

* `--major`:
  Prefer updating to next major version (default).

* `--patch`:
  Prefer updating only to next patch version.

* `--filter-major`:
  Only list major newer versions.

* `--filter-minor`:
  Only list minor newer versions.

* `--filter-patch`:
  Only list patch newer versions.

* `--only-explicit`:
  Only list gems specified in your Gemfile, not their dependencies.

## PATCH LEVEL OPTIONS

See [bundle update(1)](bundle-update.1.html) for details.

One difference between the patch level options in `bundle update` and here is the `--strict` option.
`--strict` was already an option on outdated before the patch level options were added. `--strict`
wasn't altered, and the `--update-strict` option on `outdated` reflects what `--strict` does on
`bundle update`.

## FILTERING OUTPUT

The 3 filtering options do not affect the resolution of versions, merely what versions are shown
in the output.

If the regular output shows the following:

    * faker (newest 1.6.6, installed 1.6.5, requested ~> 1.4) in groups "development, test"
    * hashie (newest 3.4.6, installed 1.2.0, requested = 1.2.0) in groups "default"
    * headless (newest 2.3.1, installed 2.2.3) in groups "test"

`--filter-major` would only show:

    * hashie (newest 3.4.6, installed 1.2.0, requested = 1.2.0) in groups "default"

`--filter-minor` would only show:

    * headless (newest 2.3.1, installed 2.2.3) in groups "test"

`--filter-patch` would only show:

    * faker (newest 1.6.6, installed 1.6.5, requested ~> 1.4) in groups "development, test"

Filter options can be combined. `--filter-minor` and `--filter-patch` would show:

    * faker (newest 1.6.6, installed 1.6.5, requested ~> 1.4) in groups "development, test"
    * headless (newest 2.3.1, installed 2.2.3) in groups "test"

Combining all three `filter` options would be the same result as providing none of them.
bundle-exec(1) -- Execute a command in the context of the bundle
================================================================

## SYNOPSIS

`bundle exec` [--keep-file-descriptors] <command>

## DESCRIPTION

This command executes the command, making all gems specified in the
[`Gemfile(5)`][Gemfile(5)] available to `require` in Ruby programs.

Essentially, if you would normally have run something like
`rspec spec/my_spec.rb`, and you want to use the gems specified
in the [`Gemfile(5)`][Gemfile(5)] and installed via [bundle install(1)](bundle-install.1.html), you
should run `bundle exec rspec spec/my_spec.rb`.

Note that `bundle exec` does not require that an executable is
available on your shell's `$PATH`.

## OPTIONS

* `--keep-file-descriptors`:
  Exec in Ruby 2.0 began discarding non-standard file descriptors. When this
  flag is passed, exec will revert to the 1.9 behaviour of passing all file
  descriptors to the new process.

## BUNDLE INSTALL --BINSTUBS

If you use the `--binstubs` flag in [bundle install(1)](bundle-install.1.html), Bundler will
automatically create a directory (which defaults to `app_root/bin`)
containing all of the executables available from gems in the bundle.

After using `--binstubs`, `bin/rspec spec/my_spec.rb` is identical
to `bundle exec rspec spec/my_spec.rb`.

## ENVIRONMENT MODIFICATIONS

`bundle exec` makes a number of changes to the shell environment,
then executes the command you specify in full.

* make sure that it's still possible to shell out to `bundle`
  from inside a command invoked by `bundle exec` (using
  `$BUNDLE_BIN_PATH`)
* put the directory containing executables (like `rails`, `rspec`,
  `rackup`) for your bundle on `$PATH`
* make sure that if bundler is invoked in the subshell, it uses
  the same `Gemfile` (by setting `BUNDLE_GEMFILE`)
* add `-rbundler/setup` to `$RUBYOPT`, which makes sure that
  Ruby programs invoked in the subshell can see the gems in
  the bundle

It also modifies Rubygems:

* disallow loading additional gems not in the bundle
* modify the `gem` method to be a no-op if a gem matching
  the requirements is in the bundle, and to raise a
  `Gem::LoadError` if it's not
* Define `Gem.refresh` to be a no-op, since the source
  index is always frozen when using bundler, and to
  prevent gems from the system leaking into the environment
* Override `Gem.bin_path` to use the gems in the bundle,
  making system executables work
* Add all gems in the bundle into Gem.loaded_specs

Finally, `bundle exec` also implicitly modifies `Gemfile.lock` if the lockfile
and the Gemfile do not match. Bundler needs the Gemfile to determine things
such as a gem's groups, `autorequire`, and platforms, etc., and that
information isn't stored in the lockfile. The Gemfile and lockfile must be
synced in order to `bundle exec` successfully, so `bundle exec`
updates the lockfile beforehand.

### Loading

By default, when attempting to `bundle exec` to a file with a ruby shebang,
Bundler will `Kernel.load` that file instead of using `Kernel.exec`. For the
vast majority of cases, this is a performance improvement. In a rare few cases,
this could cause some subtle side-effects (such as dependence on the exact
contents of `$0` or `__FILE__`) and the optimization can be disabled by enabling
the `disable_exec_load` setting.

### Shelling out

Any Ruby code that opens a subshell (like `system`, backticks, or `%x{}`) will
automatically use the current Bundler environment. If you need to shell out to
a Ruby command that is not part of your current bundle, use the
`with_clean_env` method with a block. Any subshells created inside the block
will be given the environment present before Bundler was activated. For
example, Homebrew commands run Ruby, but don't work inside a bundle:

    Bundler.with_clean_env do
      `brew install wget`
    end

Using `with_clean_env` is also necessary if you are shelling out to a different
bundle. Any Bundler commands run in a subshell will inherit the current
Gemfile, so commands that need to run in the context of a different bundle also
need to use `with_clean_env`.

    Bundler.with_clean_env do
      Dir.chdir "/other/bundler/project" do
        `bundle exec ./script`
      end
    end

Bundler provides convenience helpers that wrap `system` and `exec`, and they
can be used like this:

    Bundler.clean_system('brew install wget')
    Bundler.clean_exec('brew install wget')


## RUBYGEMS PLUGINS

At present, the Rubygems plugin system requires all files
named `rubygems_plugin.rb` on the load path of _any_ installed
gem when any Ruby code requires `rubygems.rb`. This includes
executables installed into the system, like `rails`, `rackup`,
and `rspec`.

Since Rubygems plugins can contain arbitrary Ruby code, they
commonly end up activating themselves or their dependencies.

For instance, the `gemcutter 0.5` gem depended on `json_pure`.
If you had that version of gemcutter installed (even if
you _also_ had a newer version without this problem), Rubygems
would activate `gemcutter 0.5` and `json_pure <latest>`.

If your Gemfile(5) also contained `json_pure` (or a gem
with a dependency on `json_pure`), the latest version on
your system might conflict with the version in your
Gemfile(5), or the snapshot version in your `Gemfile.lock`.

If this happens, bundler will say:

    You have already activated json_pure 1.4.6 but your Gemfile
    requires json_pure 1.4.3. Consider using bundle exec.

In this situation, you almost certainly want to remove the
underlying gem with the problematic gem plugin. In general,
the authors of these plugins (in this case, the `gemcutter`
gem) have released newer versions that are more careful in
their plugins.

You can find a list of all the gems containing gem plugins
by running

    ruby -rrubygems -e "puts Gem.find_files('rubygems_plugin.rb')"

At the very least, you should remove all but the newest
version of each gem plugin, and also remove all gem plugins
that you aren't using (`gem uninstall gem_name`).
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-SHOW" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-show\fR \- Shows all the gems in your bundle, or the path to a gem
.
.SH "SYNOPSIS"
\fBbundle show\fR [GEM] [\-\-paths]
.
.SH "DESCRIPTION"
Without the [GEM] option, \fBshow\fR will print a list of the names and versions of all gems that are required by your [\fBGemfile(5)\fR][Gemfile(5)], sorted by name\.
.
.P
Calling show with [GEM] will list the exact location of that gem on your machine\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-paths\fR
List the paths of all gems that are required by your [\fBGemfile(5)\fR][Gemfile(5)], sorted by gem name\.

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\fR \- Ruby Dependency Management
.
.SH "SYNOPSIS"
\fBbundle\fR COMMAND [\-\-no\-color] [\-\-verbose] [ARGS]
.
.SH "DESCRIPTION"
Bundler manages an \fBapplication\'s dependencies\fR through its entire life across many machines systematically and repeatably\.
.
.P
See the bundler website \fIhttps://bundler\.io\fR for information on getting started, and Gemfile(5) for more information on the \fBGemfile\fR format\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-no\-color\fR
Print all output without color
.
.TP
\fB\-\-retry\fR, \fB\-r\fR
Specify the number of times you wish to attempt network commands
.
.TP
\fB\-\-verbose\fR, \fB\-V\fR
Print out additional logging information
.
.SH "BUNDLE COMMANDS"
We divide \fBbundle\fR subcommands into primary commands and utilities:
.
.SH "PRIMARY COMMANDS"
.
.TP
\fBbundle install(1)\fR \fIbundle\-install\.1\.html\fR
Install the gems specified by the \fBGemfile\fR or \fBGemfile\.lock\fR
.
.TP
\fBbundle update(1)\fR \fIbundle\-update\.1\.html\fR
Update dependencies to their latest versions
.
.TP
\fBbundle package(1)\fR \fIbundle\-package\.1\.html\fR
Package the \.gem files required by your application into the \fBvendor/cache\fR directory
.
.TP
\fBbundle exec(1)\fR \fIbundle\-exec\.1\.html\fR
Execute a script in the current bundle
.
.TP
\fBbundle config(1)\fR \fIbundle\-config\.1\.html\fR
Specify and read configuration options for Bundler
.
.TP
\fBbundle help(1)\fR
Display detailed help for each subcommand
.
.SH "UTILITIES"
.
.TP
\fBbundle add(1)\fR \fIbundle\-add\.1\.html\fR
Add the named gem to the Gemfile and run \fBbundle install\fR
.
.TP
\fBbundle binstubs(1)\fR \fIbundle\-binstubs\.1\.html\fR
Generate binstubs for executables in a gem
.
.TP
\fBbundle check(1)\fR \fIbundle\-check\.1\.html\fR
Determine whether the requirements for your application are installed and available to Bundler
.
.TP
\fBbundle show(1)\fR \fIbundle\-show\.1\.html\fR
Show the source location of a particular gem in the bundle
.
.TP
\fBbundle outdated(1)\fR \fIbundle\-outdated\.1\.html\fR
Show all of the outdated gems in the current bundle
.
.TP
\fBbundle console(1)\fR
Start an IRB session in the current bundle
.
.TP
\fBbundle open(1)\fR \fIbundle\-open\.1\.html\fR
Open an installed gem in the editor
.
.TP
\fBbundle lock(1)\fR \fIbundle\-lock\.1\.html\fR
Generate a lockfile for your dependencies
.
.TP
\fBbundle viz(1)\fR \fIbundle\-viz\.1\.html\fR
Generate a visual representation of your dependencies
.
.TP
\fBbundle init(1)\fR \fIbundle\-init\.1\.html\fR
Generate a simple \fBGemfile\fR, placed in the current directory
.
.TP
\fBbundle gem(1)\fR \fIbundle\-gem\.1\.html\fR
Create a simple gem, suitable for development with Bundler
.
.TP
\fBbundle platform(1)\fR \fIbundle\-platform\.1\.html\fR
Display platform compatibility information
.
.TP
\fBbundle clean(1)\fR \fIbundle\-clean\.1\.html\fR
Clean up unused gems in your Bundler directory
.
.TP
\fBbundle doctor(1)\fR \fIbundle\-doctor\.1\.html\fR
Display warnings about common problems
.
.TP
\fBbundle remove(1)\fR \fIbundle\-remove\.1\.html\fR
Removes gems from the Gemfile
.
.SH "PLUGINS"
When running a command that isn\'t listed in PRIMARY COMMANDS or UTILITIES, Bundler will try to find an executable on your path named \fBbundler\-<command>\fR and execute it, passing down any extra arguments to it\.
.
.SH "OBSOLETE"
These commands are obsolete and should no longer be used:
.
.IP "\(bu" 4
\fBbundle cache(1)\fR
.
.IP "\(bu" 4
\fBbundle show(1)\fR
.
.IP "" 0

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-GEM" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-gem\fR \- Generate a project skeleton for creating a rubygem
.
.SH "SYNOPSIS"
\fBbundle gem\fR \fIGEM_NAME\fR \fIOPTIONS\fR
.
.SH "DESCRIPTION"
Generates a directory named \fBGEM_NAME\fR with a \fBRakefile\fR, \fBGEM_NAME\.gemspec\fR, and other supporting files and directories that can be used to develop a rubygem with that name\.
.
.P
Run \fBrake \-T\fR in the resulting project for a list of Rake tasks that can be used to test and publish the gem to rubygems\.org\.
.
.P
The generated project skeleton can be customized with OPTIONS, as explained below\. Note that these options can also be specified via Bundler\'s global configuration file using the following names:
.
.IP "\(bu" 4
\fBgem\.coc\fR
.
.IP "\(bu" 4
\fBgem\.mit\fR
.
.IP "\(bu" 4
\fBgem\.test\fR
.
.IP "" 0
.
.SH "OPTIONS"
.
.TP
\fB\-\-exe\fR or \fB\-b\fR or \fB\-\-bin\fR
Specify that Bundler should create a binary executable (as \fBexe/GEM_NAME\fR) in the generated rubygem project\. This binary will also be added to the \fBGEM_NAME\.gemspec\fR manifest\. This behavior is disabled by default\.
.
.TP
\fB\-\-no\-exe\fR
Do not create a binary (overrides \fB\-\-exe\fR specified in the global config)\.
.
.TP
\fB\-\-coc\fR
Add a \fBCODE_OF_CONDUCT\.md\fR file to the root of the generated project\. If this option is unspecified, an interactive prompt will be displayed and the answer will be saved in Bundler\'s global config for future \fBbundle gem\fR use\.
.
.TP
\fB\-\-no\-coc\fR
Do not create a \fBCODE_OF_CONDUCT\.md\fR (overrides \fB\-\-coc\fR specified in the global config)\.
.
.TP
\fB\-\-ext\fR
Add boilerplate for C extension code to the generated project\. This behavior is disabled by default\.
.
.TP
\fB\-\-no\-ext\fR
Do not add C extension code (overrides \fB\-\-ext\fR specified in the global config)\.
.
.TP
\fB\-\-mit\fR
Add an MIT license to a \fBLICENSE\.txt\fR file in the root of the generated project\. Your name from the global git config is used for the copyright statement\. If this option is unspecified, an interactive prompt will be displayed and the answer will be saved in Bundler\'s global config for future \fBbundle gem\fR use\.
.
.TP
\fB\-\-no\-mit\fR
Do not create a \fBLICENSE\.txt\fR (overrides \fB\-\-mit\fR specified in the global config)\.
.
.TP
\fB\-t\fR, \fB\-\-test=minitest\fR, \fB\-\-test=rspec\fR, \fB\-\-test=test\-unit\fR
Specify the test framework that Bundler should use when generating the project\. Acceptable values are \fBminitest\fR, \fBrspec\fR and \fBtest\-unit\fR\. The \fBGEM_NAME\.gemspec\fR will be configured and a skeleton test/spec directory will be created based on this option\. Given no option is specified:
.
.IP
When Bundler is configured to generate tests, this defaults to Bundler\'s global config setting \fBgem\.test\fR\.
.
.IP
When Bundler is configured to not generate tests, an interactive prompt will be displayed and the answer will be used for the current rubygem project\.
.
.IP
When Bundler is unconfigured, an interactive prompt will be displayed and the answer will be saved in Bundler\'s global config for future \fBbundle gem\fR use\.
.
.TP
\fB\-\-ci\fR, \fB\-\-ci=github\fR, \fB\-\-ci=travis\fR, \fB\-\-ci=gitlab\fR, \fB\-\-ci=circle\fR
Specify the continuous integration service that Bundler should use when generating the project\. Acceptable values are \fBgithub\fR, \fBtravis\fR, \fBgitlab\fR and \fBcircle\fR\. A configuration file will be generated in the project directory\. Given no option is specified:
.
.IP
When Bundler is configured to generate CI files, this defaults to Bundler\'s global config setting \fBgem\.ci\fR\.
.
.IP
When Bundler is configured to not generate CI files, an interactive prompt will be displayed and the answer will be used for the current rubygem project\.
.
.IP
When Bundler is unconfigured, an interactive prompt will be displayed and the answer will be saved in Bundler\'s global config for future \fBbundle gem\fR use\.
.
.TP
\fB\-\-linter\fR, \fB\-\-linter=rubocop\fR, \fB\-\-linter=standard\fR
Specify the linter and code formatter that Bundler should add to the project\'s development dependencies\. Acceptable values are \fBrubocop\fR and \fBstandard\fR\. A configuration file will be generated in the project directory\. Given no option is specified:
.
.IP
When Bundler is configured to add a linter, this defaults to Bundler\'s global config setting \fBgem\.linter\fR\.
.
.IP
When Bundler is configured not to add a linter, an interactive prompt will be displayed and the answer will be used for the current rubygem project\.
.
.IP
When Bundler is unconfigured, an interactive prompt will be displayed and the answer will be saved in Bundler\'s global config for future \fBbundle gem\fR use\.
.
.TP
\fB\-e\fR, \fB\-\-edit[=EDITOR]\fR
Open the resulting GEM_NAME\.gemspec in EDITOR, or the default editor if not specified\. The default is \fB$BUNDLER_EDITOR\fR, \fB$VISUAL\fR, or \fB$EDITOR\fR\.
.
.SH "SEE ALSO"
.
.IP "\(bu" 4
bundle config(1) \fIbundle\-config\.1\.html\fR
.
.IP "" 0

bundle-inject(1) -- Add named gem(s) with version requirements to Gemfile
=========================================================================

## SYNOPSIS

`bundle inject` [GEM] [VERSION]

## DESCRIPTION

Adds the named gem(s) with their version requirements to the resolved
[`Gemfile(5)`][Gemfile(5)].

This command will add the gem to both your [`Gemfile(5)`][Gemfile(5)] and Gemfile.lock if it
isn't listed yet.

Example:

    bundle install
    bundle inject 'rack' '> 0'

This will inject the 'rack' gem with a version greater than 0 in your
[`Gemfile(5)`][Gemfile(5)] and Gemfile.lock
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-REMOVE" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-remove\fR \- Removes gems from the Gemfile
.
.SH "SYNOPSIS"
\fBbundle remove [GEM [GEM \.\.\.]] [\-\-install]\fR
.
.SH "DESCRIPTION"
Removes the given gems from the Gemfile while ensuring that the resulting Gemfile is still valid\. If a gem cannot be removed, a warning is printed\. If a gem is already absent from the Gemfile, and error is raised\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-install\fR
Runs \fBbundle install\fR after the given gems have been removed from the Gemfile, which ensures that both the lockfile and the installed gems on disk are also updated to remove the given gem(s)\.
.
.P
Example:
.
.P
bundle remove rails
.
.P
bundle remove rails rack
.
.P
bundle remove rails rack \-\-install
bundle-remove(1) -- Removes gems from the Gemfile
===========================================================================

## SYNOPSIS

`bundle remove [GEM [GEM ...]] [--install]`

## DESCRIPTION

Removes the given gems from the Gemfile while ensuring that the resulting Gemfile is still valid. If a gem cannot be removed, a warning is printed. If a gem is already absent from the Gemfile, and error is raised.

## OPTIONS

* `--install`:
  Runs `bundle install` after the given gems have been removed from the Gemfile, which ensures that both the lockfile and the installed gems on disk are also updated to remove the given gem(s).

Example:

bundle remove rails

bundle remove rails rack

bundle remove rails rack --install
bundle-update(1) -- Update your gems to the latest available versions
=====================================================================

## SYNOPSIS

`bundle update` <*gems> [--all]
                        [--group=NAME]
                        [--source=NAME]
                        [--local]
                        [--ruby]
                        [--bundler[=VERSION]]
                        [--full-index]
                        [--jobs=JOBS]
                        [--quiet]
                        [--patch|--minor|--major]
                        [--redownload]
                        [--strict]
                        [--conservative]

## DESCRIPTION

Update the gems specified (all gems, if `--all` flag is used), ignoring
the previously installed gems specified in the `Gemfile.lock`. In
general, you should use [bundle install(1)](bundle-install.1.html) to install the same exact
gems and versions across machines.

You would use `bundle update` to explicitly update the version of a
gem.

## OPTIONS

* `--all`:
  Update all gems specified in Gemfile.

* `--group=<name>`, `-g=[<name>]`:
  Only update the gems in the specified group. For instance, you can update all gems
  in the development group with `bundle update --group development`. You can also
  call `bundle update rails --group test` to update the rails gem and all gems in
  the test group, for example.

* `--source=<name>`:
  The name of a `:git` or `:path` source used in the Gemfile(5). For
  instance, with a `:git` source of `http://github.com/rails/rails.git`,
  you would call `bundle update --source rails`

* `--local`:
  Do not attempt to fetch gems remotely and use the gem cache instead.

* `--ruby`:
  Update the locked version of Ruby to the current version of Ruby.

* `--bundler`:
  Update the locked version of bundler to the invoked bundler version.

* `--full-index`:
  Fall back to using the single-file index of all gems.

* `--jobs=[<number>]`, `-j[<number>]`:
  Specify the number of jobs to run in parallel. The default is `1`.

* `--retry=[<number>]`:
  Retry failed network or git requests for <number> times.

* `--quiet`:
  Only output warnings and errors.

* `--redownload`:
  Force downloading every gem.

* `--patch`:
  Prefer updating only to next patch version.

* `--minor`:
  Prefer updating only to next minor version.

* `--major`:
  Prefer updating to next major version (default).

* `--strict`:
  Do not allow any gem to be updated past latest `--patch` | `--minor` | `--major`.

* `--conservative`:
  Use bundle install conservative update behavior and do not allow indirect dependencies to be updated.

## UPDATING ALL GEMS

If you run `bundle update --all`, bundler will ignore
any previously installed gems and resolve all dependencies again
based on the latest versions of all gems available in the sources.

Consider the following Gemfile(5):

    source "https://rubygems.org"

    gem "rails", "3.0.0.rc"
    gem "nokogiri"

When you run [bundle install(1)](bundle-install.1.html) the first time, bundler will resolve
all of the dependencies, all the way down, and install what you need:

    Fetching gem metadata from https://rubygems.org/.........
    Resolving dependencies...
    Installing builder 2.1.2
    Installing abstract 1.0.0
    Installing rack 1.2.8
    Using bundler 1.7.6
    Installing rake 10.4.0
    Installing polyglot 0.3.5
    Installing mime-types 1.25.1
    Installing i18n 0.4.2
    Installing mini_portile 0.6.1
    Installing tzinfo 0.3.42
    Installing rack-mount 0.6.14
    Installing rack-test 0.5.7
    Installing treetop 1.4.15
    Installing thor 0.14.6
    Installing activesupport 3.0.0.rc
    Installing erubis 2.6.6
    Installing activemodel 3.0.0.rc
    Installing arel 0.4.0
    Installing mail 2.2.20
    Installing activeresource 3.0.0.rc
    Installing actionpack 3.0.0.rc
    Installing activerecord 3.0.0.rc
    Installing actionmailer 3.0.0.rc
    Installing railties 3.0.0.rc
    Installing rails 3.0.0.rc
    Installing nokogiri 1.6.5

    Bundle complete! 2 Gemfile dependencies, 26 gems total.
    Use `bundle show [gemname]` to see where a bundled gem is installed.

As you can see, even though you have two gems in the Gemfile(5), your application
needs 26 different gems in order to run. Bundler remembers the exact versions
it installed in `Gemfile.lock`. The next time you run [bundle install(1)](bundle-install.1.html), bundler skips
the dependency resolution and installs the same gems as it installed last time.

After checking in the `Gemfile.lock` into version control and cloning it on another
machine, running [bundle install(1)](bundle-install.1.html) will _still_ install the gems that you installed
last time. You don't need to worry that a new release of `erubis` or `mail` changes
the gems you use.

However, from time to time, you might want to update the gems you are using to the
newest versions that still match the gems in your Gemfile(5).

To do this, run `bundle update --all`, which will ignore the `Gemfile.lock`, and resolve
all the dependencies again. Keep in mind that this process can result in a significantly
different set of the 25 gems, based on the requirements of new gems that the gem
authors released since the last time you ran `bundle update --all`.

## UPDATING A LIST OF GEMS

Sometimes, you want to update a single gem in the Gemfile(5), and leave the rest of the
gems that you specified locked to the versions in the `Gemfile.lock`.

For instance, in the scenario above, imagine that `nokogiri` releases version `1.4.4`, and
you want to update it _without_ updating Rails and all of its dependencies. To do this,
run `bundle update nokogiri`.

Bundler will update `nokogiri` and any of its dependencies, but leave alone Rails and
its dependencies.

## OVERLAPPING DEPENDENCIES

Sometimes, multiple gems declared in your Gemfile(5) are satisfied by the same
second-level dependency. For instance, consider the case of `thin` and
`rack-perftools-profiler`.

    source "https://rubygems.org"

    gem "thin"
    gem "rack-perftools-profiler"

The `thin` gem depends on `rack >= 1.0`, while `rack-perftools-profiler` depends
on `rack ~> 1.0`. If you run bundle install, you get:

    Fetching source index for https://rubygems.org/
    Installing daemons (1.1.0)
    Installing eventmachine (0.12.10) with native extensions
    Installing open4 (1.0.1)
    Installing perftools.rb (0.4.7) with native extensions
    Installing rack (1.2.1)
    Installing rack-perftools_profiler (0.0.2)
    Installing thin (1.2.7) with native extensions
    Using bundler (1.0.0.rc.3)

In this case, the two gems have their own set of dependencies, but they share
`rack` in common. If you run `bundle update thin`, bundler will update `daemons`,
`eventmachine` and `rack`, which are dependencies of `thin`, but not `open4` or
`perftools.rb`, which are dependencies of `rack-perftools_profiler`. Note that
`bundle update thin` will update `rack` even though it's _also_ a dependency of
`rack-perftools_profiler`.

In short, by default, when you update a gem using `bundle update`, bundler will
update all dependencies of that gem, including those that are also dependencies
of another gem.

To prevent updating indirect dependencies, prior to version 1.14 the only option
was the `CONSERVATIVE UPDATING` behavior in [bundle install(1)](bundle-install.1.html):

In this scenario, updating the `thin` version manually in the Gemfile(5),
and then running [bundle install(1)](bundle-install.1.html) will only update `daemons` and `eventmachine`,
but not `rack`. For more information, see the `CONSERVATIVE UPDATING` section
of [bundle install(1)](bundle-install.1.html).

Starting with 1.14, specifying the `--conservative` option will also prevent indirect
dependencies from being updated.

## PATCH LEVEL OPTIONS

Version 1.14 introduced 4 patch-level options that will influence how gem
versions are resolved. One of the following options can be used: `--patch`,
`--minor` or `--major`. `--strict` can be added to further influence resolution.

* `--patch`:
  Prefer updating only to next patch version.

* `--minor`:
  Prefer updating only to next minor version.

* `--major`:
  Prefer updating to next major version (default).

* `--strict`:
  Do not allow any gem to be updated past latest `--patch` | `--minor` | `--major`.

When Bundler is resolving what versions to use to satisfy declared
requirements in the Gemfile or in parent gems, it looks up all
available versions, filters out any versions that don't satisfy
the requirement, and then, by default, sorts them from newest to
oldest, considering them in that order.

Providing one of the patch level options (e.g. `--patch`) changes the
sort order of the satisfying versions, causing Bundler to consider the
latest `--patch` or `--minor` version available before other versions.
Note that versions outside the stated patch level could still be
resolved to if necessary to find a suitable dependency graph.

For example, if gem 'foo' is locked at 1.0.2, with no gem requirement
defined in the Gemfile, and versions 1.0.3, 1.0.4, 1.1.0, 1.1.1, 2.0.0
all exist, the default order of preference by default (`--major`) will
be "2.0.0, 1.1.1, 1.1.0, 1.0.4, 1.0.3, 1.0.2".

If the `--patch` option is used, the order of preference will change to
"1.0.4, 1.0.3, 1.0.2, 1.1.1, 1.1.0, 2.0.0".

If the `--minor` option is used, the order of preference will change to
"1.1.1, 1.1.0, 1.0.4, 1.0.3, 1.0.2, 2.0.0".

Combining the `--strict` option with any of the patch level options
will remove any versions beyond the scope of the patch level option,
to ensure that no gem is updated that far.

To continue the previous example, if both `--patch` and `--strict`
options are used, the available versions for resolution would be
"1.0.4, 1.0.3, 1.0.2". If `--minor` and `--strict` are used, it would
be "1.1.1, 1.1.0, 1.0.4, 1.0.3, 1.0.2".

Gem requirements as defined in the Gemfile will still be the first
determining factor for what versions are available. If the gem
requirement for `foo` in the Gemfile is '~> 1.0', that will accomplish
the same thing as providing the `--minor` and `--strict` options.

## PATCH LEVEL EXAMPLES

Given the following gem specifications:

    foo 1.4.3, requires: ~> bar 2.0
    foo 1.4.4, requires: ~> bar 2.0
    foo 1.4.5, requires: ~> bar 2.1
    foo 1.5.0, requires: ~> bar 2.1
    foo 1.5.1, requires: ~> bar 3.0
    bar with versions 2.0.3, 2.0.4, 2.1.0, 2.1.1, 3.0.0

Gemfile:

    gem 'foo'

Gemfile.lock:

    foo (1.4.3)
      bar (~> 2.0)
    bar (2.0.3)

Cases:

    #  Command Line                     Result
    ------------------------------------------------------------
    1  bundle update --patch            'foo 1.4.5', 'bar 2.1.1'
    2  bundle update --patch foo        'foo 1.4.5', 'bar 2.1.1'
    3  bundle update --minor            'foo 1.5.1', 'bar 3.0.0'
    4  bundle update --minor --strict   'foo 1.5.0', 'bar 2.1.1'
    5  bundle update --patch --strict   'foo 1.4.4', 'bar 2.0.4'

In case 1, bar is upgraded to 2.1.1, a minor version increase, because
the dependency from foo 1.4.5 required it.

In case 2, only foo is requested to be unlocked, but bar is also
allowed to move because it's not a declared dependency in the Gemfile.

In case 3, bar goes up a whole major release, because a minor increase
is preferred now for foo, and when it goes to 1.5.1, it requires 3.0.0
of bar.

In case 4, foo is preferred up to a minor version, but 1.5.1 won't work
because the --strict flag removes bar 3.0.0 from consideration since
it's a major increment.

In case 5, both foo and bar have any minor or major increments removed
from consideration because of the --strict flag, so the most they can
move is up to 1.4.4 and 2.0.4.

## RECOMMENDED WORKFLOW

In general, when working with an application managed with bundler, you should
use the following workflow:

* After you create your Gemfile(5) for the first time, run

    $ bundle install

* Check the resulting `Gemfile.lock` into version control

    $ git add Gemfile.lock

* When checking out this repository on another development machine, run

    $ bundle install

* When checking out this repository on a deployment machine, run

    $ bundle install --deployment

* After changing the Gemfile(5) to reflect a new or update dependency, run

    $ bundle install

* Make sure to check the updated `Gemfile.lock` into version control

    $ git add Gemfile.lock

* If [bundle install(1)](bundle-install.1.html) reports a conflict, manually update the specific
  gems that you changed in the Gemfile(5)

    $ bundle update rails thin

* If you want to update all the gems to the latest possible versions that
  still match the gems listed in the Gemfile(5), run

    $ bundle update --all
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-LIST" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-list\fR \- List all the gems in the bundle
.
.SH "SYNOPSIS"
\fBbundle list\fR [\-\-name\-only] [\-\-paths] [\-\-without\-group=GROUP[ GROUP\.\.\.]] [\-\-only\-group=GROUP[ GROUP\.\.\.]]
.
.SH "DESCRIPTION"
Prints a list of all the gems in the bundle including their version\.
.
.P
Example:
.
.P
bundle list \-\-name\-only
.
.P
bundle list \-\-paths
.
.P
bundle list \-\-without\-group test
.
.P
bundle list \-\-only\-group dev
.
.P
bundle list \-\-only\-group dev test \-\-paths
.
.SH "OPTIONS"
.
.TP
\fB\-\-name\-only\fR
Print only the name of each gem\.
.
.TP
\fB\-\-paths\fR
Print the path to each gem in the bundle\.
.
.TP
\fB\-\-without\-group=<list>\fR
A space\-separated list of groups of gems to skip during printing\.
.
.TP
\fB\-\-only\-group=<list>\fR
A space\-separated list of groups of gems to print\.

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-CACHE" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-cache\fR \- Package your needed \fB\.gem\fR files into your application
.
.SH "SYNOPSIS"
\fBbundle cache\fR
.
.SH "DESCRIPTION"
Copy all of the \fB\.gem\fR files needed to run the application into the \fBvendor/cache\fR directory\. In the future, when running [bundle install(1)][bundle\-install], use the gems in the cache in preference to the ones on \fBrubygems\.org\fR\.
.
.SH "GIT AND PATH GEMS"
The \fBbundle cache\fR command can also package \fB:git\fR and \fB:path\fR dependencies besides \.gem files\. This needs to be explicitly enabled via the \fB\-\-all\fR option\. Once used, the \fB\-\-all\fR option will be remembered\.
.
.SH "SUPPORT FOR MULTIPLE PLATFORMS"
When using gems that have different packages for different platforms, Bundler supports caching of gems for other platforms where the Gemfile has been resolved (i\.e\. present in the lockfile) in \fBvendor/cache\fR\. This needs to be enabled via the \fB\-\-all\-platforms\fR option\. This setting will be remembered in your local bundler configuration\.
.
.SH "REMOTE FETCHING"
By default, if you run \fBbundle install(1)\fR](bundle\-install\.1\.html) after running bundle cache(1) \fIbundle\-cache\.1\.html\fR, bundler will still connect to \fBrubygems\.org\fR to check whether a platform\-specific gem exists for any of the gems in \fBvendor/cache\fR\.
.
.P
For instance, consider this Gemfile(5):
.
.IP "" 4
.
.nf

source "https://rubygems\.org"

gem "nokogiri"
.
.fi
.
.IP "" 0
.
.P
If you run \fBbundle cache\fR under C Ruby, bundler will retrieve the version of \fBnokogiri\fR for the \fB"ruby"\fR platform\. If you deploy to JRuby and run \fBbundle install\fR, bundler is forced to check to see whether a \fB"java"\fR platformed \fBnokogiri\fR exists\.
.
.P
Even though the \fBnokogiri\fR gem for the Ruby platform is \fItechnically\fR acceptable on JRuby, it has a C extension that does not run on JRuby\. As a result, bundler will, by default, still connect to \fBrubygems\.org\fR to check whether it has a version of one of your gems more specific to your platform\.
.
.P
This problem is also not limited to the \fB"java"\fR platform\. A similar (common) problem can happen when developing on Windows and deploying to Linux, or even when developing on OSX and deploying to Linux\.
.
.P
If you know for sure that the gems packaged in \fBvendor/cache\fR are appropriate for the platform you are on, you can run \fBbundle install \-\-local\fR to skip checking for more appropriate gems, and use the ones in \fBvendor/cache\fR\.
.
.P
One way to be sure that you have the right platformed versions of all your gems is to run \fBbundle cache\fR on an identical machine and check in the gems\. For instance, you can run \fBbundle cache\fR on an identical staging box during your staging process, and check in the \fBvendor/cache\fR before deploying to production\.
.
.P
By default, bundle cache(1) \fIbundle\-cache\.1\.html\fR fetches and also installs the gems to the default location\. To package the dependencies to \fBvendor/cache\fR without installing them to the local install location, you can run \fBbundle cache \-\-no\-install\fR\.
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-CONFIG" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-config\fR \- Set bundler configuration options
.
.SH "SYNOPSIS"
\fBbundle config\fR [list|get|set|unset] [\fIname\fR [\fIvalue\fR]]
.
.SH "DESCRIPTION"
This command allows you to interact with Bundler\'s configuration system\.
.
.P
Bundler loads configuration settings in this order:
.
.IP "1." 4
Local config (\fB<project_root>/\.bundle/config\fR or \fB$BUNDLE_APP_CONFIG/config\fR)
.
.IP "2." 4
Environmental variables (\fBENV\fR)
.
.IP "3." 4
Global config (\fB~/\.bundle/config\fR)
.
.IP "4." 4
Bundler default config
.
.IP "" 0
.
.P
Executing \fBbundle config list\fR with will print a list of all bundler configuration for the current bundle, and where that configuration was set\.
.
.P
Executing \fBbundle config get <name>\fR will print the value of that configuration setting, and where it was set\.
.
.P
Executing \fBbundle config set <name> <value>\fR will set that configuration to the value specified for all bundles executed as the current user\. The configuration will be stored in \fB~/\.bundle/config\fR\. If \fIname\fR already is set, \fIname\fR will be overridden and user will be warned\.
.
.P
Executing \fBbundle config set \-\-global <name> <value>\fR works the same as above\.
.
.P
Executing \fBbundle config set \-\-local <name> <value>\fR will set that configuration in the directory for the local application\. The configuration will be stored in \fB<project_root>/\.bundle/config\fR\. If \fBBUNDLE_APP_CONFIG\fR is set, the configuration will be stored in \fB$BUNDLE_APP_CONFIG/config\fR\.
.
.P
Executing \fBbundle config unset <name>\fR will delete the configuration in both local and global sources\.
.
.P
Executing \fBbundle config unset \-\-global <name>\fR will delete the configuration only from the user configuration\.
.
.P
Executing \fBbundle config unset \-\-local <name> <value>\fR will delete the configuration only from the local application\.
.
.P
Executing bundle with the \fBBUNDLE_IGNORE_CONFIG\fR environment variable set will cause it to ignore all configuration\.
.
.SH "REMEMBERING OPTIONS"
Flags passed to \fBbundle install\fR or the Bundler runtime, such as \fB\-\-path foo\fR or \fB\-\-without production\fR, are remembered between commands and saved to your local application\'s configuration (normally, \fB\./\.bundle/config\fR)\.
.
.P
However, this will be changed in bundler 3, so it\'s better not to rely on this behavior\. If these options must be remembered, it\'s better to set them using \fBbundle config\fR (e\.g\., \fBbundle config set \-\-local path foo\fR)\.
.
.P
The options that can be configured are:
.
.TP
\fBbin\fR
Creates a directory (defaults to \fB~/bin\fR) and place any executables from the gem there\. These executables run in Bundler\'s context\. If used, you might add this directory to your environment\'s \fBPATH\fR variable\. For instance, if the \fBrails\fR gem comes with a \fBrails\fR executable, this flag will create a \fBbin/rails\fR executable that ensures that all referred dependencies will be resolved using the bundled gems\.
.
.TP
\fBdeployment\fR
In deployment mode, Bundler will \'roll\-out\' the bundle for \fBproduction\fR use\. Please check carefully if you want to have this option enabled in \fBdevelopment\fR or \fBtest\fR environments\.
.
.TP
\fBpath\fR
The location to install the specified gems to\. This defaults to Rubygems\' setting\. Bundler shares this location with Rubygems, \fBgem install \.\.\.\fR will have gem installed there, too\. Therefore, gems installed without a \fB\-\-path \.\.\.\fR setting will show up by calling \fBgem list\fR\. Accordingly, gems installed to other locations will not get listed\.
.
.TP
\fBwithout\fR
A space\-separated list of groups referencing gems to skip during installation\.
.
.TP
\fBwith\fR
A space\-separated list of groups referencing gems to include during installation\.
.
.SH "BUILD OPTIONS"
You can use \fBbundle config\fR to give Bundler the flags to pass to the gem installer every time bundler tries to install a particular gem\.
.
.P
A very common example, the \fBmysql\fR gem, requires Snow Leopard users to pass configuration flags to \fBgem install\fR to specify where to find the \fBmysql_config\fR executable\.
.
.IP "" 4
.
.nf

gem install mysql \-\- \-\-with\-mysql\-config=/usr/local/mysql/bin/mysql_config
.
.fi
.
.IP "" 0
.
.P
Since the specific location of that executable can change from machine to machine, you can specify these flags on a per\-machine basis\.
.
.IP "" 4
.
.nf

bundle config set \-\-global build\.mysql \-\-with\-mysql\-config=/usr/local/mysql/bin/mysql_config
.
.fi
.
.IP "" 0
.
.P
After running this command, every time bundler needs to install the \fBmysql\fR gem, it will pass along the flags you specified\.
.
.SH "CONFIGURATION KEYS"
Configuration keys in bundler have two forms: the canonical form and the environment variable form\.
.
.P
For instance, passing the \fB\-\-without\fR flag to bundle install(1) \fIbundle\-install\.1\.html\fR prevents Bundler from installing certain groups specified in the Gemfile(5)\. Bundler persists this value in \fBapp/\.bundle/config\fR so that calls to \fBBundler\.setup\fR do not try to find gems from the \fBGemfile\fR that you didn\'t install\. Additionally, subsequent calls to bundle install(1) \fIbundle\-install\.1\.html\fR remember this setting and skip those groups\.
.
.P
The canonical form of this configuration is \fB"without"\fR\. To convert the canonical form to the environment variable form, capitalize it, and prepend \fBBUNDLE_\fR\. The environment variable form of \fB"without"\fR is \fBBUNDLE_WITHOUT\fR\.
.
.P
Any periods in the configuration keys must be replaced with two underscores when setting it via environment variables\. The configuration key \fBlocal\.rack\fR becomes the environment variable \fBBUNDLE_LOCAL__RACK\fR\.
.
.SH "LIST OF AVAILABLE KEYS"
The following is a list of all configuration keys and their purpose\. You can learn more about their operation in bundle install(1) \fIbundle\-install\.1\.html\fR\.
.
.IP "\(bu" 4
\fBallow_deployment_source_credential_changes\fR (\fBBUNDLE_ALLOW_DEPLOYMENT_SOURCE_CREDENTIAL_CHANGES\fR): When in deployment mode, allow changing the credentials to a gem\'s source\. Ex: \fBhttps://some\.host\.com/gems/path/\fR \-> \fBhttps://user_name:password@some\.host\.com/gems/path\fR
.
.IP "\(bu" 4
\fBallow_offline_install\fR (\fBBUNDLE_ALLOW_OFFLINE_INSTALL\fR): Allow Bundler to use cached data when installing without network access\.
.
.IP "\(bu" 4
\fBauto_clean_without_path\fR (\fBBUNDLE_AUTO_CLEAN_WITHOUT_PATH\fR): Automatically run \fBbundle clean\fR after installing when an explicit \fBpath\fR has not been set and Bundler is not installing into the system gems\.
.
.IP "\(bu" 4
\fBauto_install\fR (\fBBUNDLE_AUTO_INSTALL\fR): Automatically run \fBbundle install\fR when gems are missing\.
.
.IP "\(bu" 4
\fBbin\fR (\fBBUNDLE_BIN\fR): Install executables from gems in the bundle to the specified directory\. Defaults to \fBfalse\fR\.
.
.IP "\(bu" 4
\fBcache_all\fR (\fBBUNDLE_CACHE_ALL\fR): Cache all gems, including path and git gems\. This needs to be explicitly configured on bundler 1 and bundler 2, but will be the default on bundler 3\.
.
.IP "\(bu" 4
\fBcache_all_platforms\fR (\fBBUNDLE_CACHE_ALL_PLATFORMS\fR): Cache gems for all platforms\.
.
.IP "\(bu" 4
\fBcache_path\fR (\fBBUNDLE_CACHE_PATH\fR): The directory that bundler will place cached gems in when running \fBbundle package\fR, and that bundler will look in when installing gems\. Defaults to \fBvendor/cache\fR\.
.
.IP "\(bu" 4
\fBclean\fR (\fBBUNDLE_CLEAN\fR): Whether Bundler should run \fBbundle clean\fR automatically after \fBbundle install\fR\.
.
.IP "\(bu" 4
\fBconsole\fR (\fBBUNDLE_CONSOLE\fR): The console that \fBbundle console\fR starts\. Defaults to \fBirb\fR\.
.
.IP "\(bu" 4
\fBdefault_install_uses_path\fR (\fBBUNDLE_DEFAULT_INSTALL_USES_PATH\fR): Whether a \fBbundle install\fR without an explicit \fB\-\-path\fR argument defaults to installing gems in \fB\.bundle\fR\.
.
.IP "\(bu" 4
\fBdeployment\fR (\fBBUNDLE_DEPLOYMENT\fR): Disallow changes to the \fBGemfile\fR\. When the \fBGemfile\fR is changed and the lockfile has not been updated, running Bundler commands will be blocked\.
.
.IP "\(bu" 4
\fBdisable_checksum_validation\fR (\fBBUNDLE_DISABLE_CHECKSUM_VALIDATION\fR): Allow installing gems even if they do not match the checksum provided by RubyGems\.
.
.IP "\(bu" 4
\fBdisable_exec_load\fR (\fBBUNDLE_DISABLE_EXEC_LOAD\fR): Stop Bundler from using \fBload\fR to launch an executable in\-process in \fBbundle exec\fR\.
.
.IP "\(bu" 4
\fBdisable_local_branch_check\fR (\fBBUNDLE_DISABLE_LOCAL_BRANCH_CHECK\fR): Allow Bundler to use a local git override without a branch specified in the Gemfile\.
.
.IP "\(bu" 4
\fBdisable_local_revision_check\fR (\fBBUNDLE_DISABLE_LOCAL_REVISION_CHECK\fR): Allow Bundler to use a local git override without checking if the revision present in the lockfile is present in the repository\.
.
.IP "\(bu" 4
\fBdisable_shared_gems\fR (\fBBUNDLE_DISABLE_SHARED_GEMS\fR): Stop Bundler from accessing gems installed to RubyGems\' normal location\.
.
.IP "\(bu" 4
\fBdisable_version_check\fR (\fBBUNDLE_DISABLE_VERSION_CHECK\fR): Stop Bundler from checking if a newer Bundler version is available on rubygems\.org\.
.
.IP "\(bu" 4
\fBforce_ruby_platform\fR (\fBBUNDLE_FORCE_RUBY_PLATFORM\fR): Ignore the current machine\'s platform and install only \fBruby\fR platform gems\. As a result, gems with native extensions will be compiled from source\.
.
.IP "\(bu" 4
\fBfrozen\fR (\fBBUNDLE_FROZEN\fR): Disallow changes to the \fBGemfile\fR\. When the \fBGemfile\fR is changed and the lockfile has not been updated, running Bundler commands will be blocked\. Defaults to \fBtrue\fR when \fB\-\-deployment\fR is used\.
.
.IP "\(bu" 4
\fBgem\.github_username\fR (\fBBUNDLE_GEM__GITHUB_USERNAME\fR): Sets a GitHub username or organization to be used in \fBREADME\fR file when you create a new gem via \fBbundle gem\fR command\. It can be overridden by passing an explicit \fB\-\-github\-username\fR flag to \fBbundle gem\fR\.
.
.IP "\(bu" 4
\fBgem\.push_key\fR (\fBBUNDLE_GEM__PUSH_KEY\fR): Sets the \fB\-\-key\fR parameter for \fBgem push\fR when using the \fBrake release\fR command with a private gemstash server\.
.
.IP "\(bu" 4
\fBgemfile\fR (\fBBUNDLE_GEMFILE\fR): The name of the file that bundler should use as the \fBGemfile\fR\. This location of this file also sets the root of the project, which is used to resolve relative paths in the \fBGemfile\fR, among other things\. By default, bundler will search up from the current working directory until it finds a \fBGemfile\fR\.
.
.IP "\(bu" 4
\fBglobal_gem_cache\fR (\fBBUNDLE_GLOBAL_GEM_CACHE\fR): Whether Bundler should cache all gems globally, rather than locally to the installing Ruby installation\.
.
.IP "\(bu" 4
\fBignore_messages\fR (\fBBUNDLE_IGNORE_MESSAGES\fR): When set, no post install messages will be printed\. To silence a single gem, use dot notation like \fBignore_messages\.httparty true\fR\.
.
.IP "\(bu" 4
\fBinit_gems_rb\fR (\fBBUNDLE_INIT_GEMS_RB\fR): Generate a \fBgems\.rb\fR instead of a \fBGemfile\fR when running \fBbundle init\fR\.
.
.IP "\(bu" 4
\fBjobs\fR (\fBBUNDLE_JOBS\fR): The number of gems Bundler can install in parallel\. Defaults to 1 on Windows, and to the the number of processors on other platforms\.
.
.IP "\(bu" 4
\fBno_install\fR (\fBBUNDLE_NO_INSTALL\fR): Whether \fBbundle package\fR should skip installing gems\.
.
.IP "\(bu" 4
\fBno_prune\fR (\fBBUNDLE_NO_PRUNE\fR): Whether Bundler should leave outdated gems unpruned when caching\.
.
.IP "\(bu" 4
\fBpath\fR (\fBBUNDLE_PATH\fR): The location on disk where all gems in your bundle will be located regardless of \fB$GEM_HOME\fR or \fB$GEM_PATH\fR values\. Bundle gems not found in this location will be installed by \fBbundle install\fR\. Defaults to \fBGem\.dir\fR\. When \-\-deployment is used, defaults to vendor/bundle\.
.
.IP "\(bu" 4
\fBpath\.system\fR (\fBBUNDLE_PATH__SYSTEM\fR): Whether Bundler will install gems into the default system path (\fBGem\.dir\fR)\.
.
.IP "\(bu" 4
\fBpath_relative_to_cwd\fR (\fBBUNDLE_PATH_RELATIVE_TO_CWD\fR) Makes \fB\-\-path\fR relative to the CWD instead of the \fBGemfile\fR\.
.
.IP "\(bu" 4
\fBplugins\fR (\fBBUNDLE_PLUGINS\fR): Enable Bundler\'s experimental plugin system\.
.
.IP "\(bu" 4
\fBprefer_patch\fR (BUNDLE_PREFER_PATCH): Prefer updating only to next patch version during updates\. Makes \fBbundle update\fR calls equivalent to \fBbundler update \-\-patch\fR\.
.
.IP "\(bu" 4
\fBprint_only_version_number\fR (\fBBUNDLE_PRINT_ONLY_VERSION_NUMBER\fR): Print only version number from \fBbundler \-\-version\fR\.
.
.IP "\(bu" 4
\fBredirect\fR (\fBBUNDLE_REDIRECT\fR): The number of redirects allowed for network requests\. Defaults to \fB5\fR\.
.
.IP "\(bu" 4
\fBretry\fR (\fBBUNDLE_RETRY\fR): The number of times to retry failed network requests\. Defaults to \fB3\fR\.
.
.IP "\(bu" 4
\fBsetup_makes_kernel_gem_public\fR (\fBBUNDLE_SETUP_MAKES_KERNEL_GEM_PUBLIC\fR): Have \fBBundler\.setup\fR make the \fBKernel#gem\fR method public, even though RubyGems declares it as private\.
.
.IP "\(bu" 4
\fBshebang\fR (\fBBUNDLE_SHEBANG\fR): The program name that should be invoked for generated binstubs\. Defaults to the ruby install name used to generate the binstub\.
.
.IP "\(bu" 4
\fBsilence_deprecations\fR (\fBBUNDLE_SILENCE_DEPRECATIONS\fR): Whether Bundler should silence deprecation warnings for behavior that will be changed in the next major version\.
.
.IP "\(bu" 4
\fBsilence_root_warning\fR (\fBBUNDLE_SILENCE_ROOT_WARNING\fR): Silence the warning Bundler prints when installing gems as root\.
.
.IP "\(bu" 4
\fBssl_ca_cert\fR (\fBBUNDLE_SSL_CA_CERT\fR): Path to a designated CA certificate file or folder containing multiple certificates for trusted CAs in PEM format\.
.
.IP "\(bu" 4
\fBssl_client_cert\fR (\fBBUNDLE_SSL_CLIENT_CERT\fR): Path to a designated file containing a X\.509 client certificate and key in PEM format\.
.
.IP "\(bu" 4
\fBssl_verify_mode\fR (\fBBUNDLE_SSL_VERIFY_MODE\fR): The SSL verification mode Bundler uses when making HTTPS requests\. Defaults to verify peer\.
.
.IP "\(bu" 4
\fBsuppress_install_using_messages\fR (\fBBUNDLE_SUPPRESS_INSTALL_USING_MESSAGES\fR): Avoid printing \fBUsing \.\.\.\fR messages during installation when the version of a gem has not changed\.
.
.IP "\(bu" 4
\fBsystem_bindir\fR (\fBBUNDLE_SYSTEM_BINDIR\fR): The location where RubyGems installs binstubs\. Defaults to \fBGem\.bindir\fR\.
.
.IP "\(bu" 4
\fBtimeout\fR (\fBBUNDLE_TIMEOUT\fR): The seconds allowed before timing out for network requests\. Defaults to \fB10\fR\.
.
.IP "\(bu" 4
\fBupdate_requires_all_flag\fR (\fBBUNDLE_UPDATE_REQUIRES_ALL_FLAG\fR): Require passing \fB\-\-all\fR to \fBbundle update\fR when everything should be updated, and disallow passing no options to \fBbundle update\fR\.
.
.IP "\(bu" 4
\fBuser_agent\fR (\fBBUNDLE_USER_AGENT\fR): The custom user agent fragment Bundler includes in API requests\.
.
.IP "\(bu" 4
\fBwith\fR (\fBBUNDLE_WITH\fR): A \fB:\fR\-separated list of groups whose gems bundler should install\.
.
.IP "\(bu" 4
\fBwithout\fR (\fBBUNDLE_WITHOUT\fR): A \fB:\fR\-separated list of groups whose gems bundler should not install\.
.
.IP "" 0
.
.P
In general, you should set these settings per\-application by using the applicable flag to the bundle install(1) \fIbundle\-install\.1\.html\fR or bundle package(1) \fIbundle\-package\.1\.html\fR command\.
.
.P
You can set them globally either via environment variables or \fBbundle config\fR, whichever is preferable for your setup\. If you use both, environment variables will take preference over global settings\.
.
.SH "LOCAL GIT REPOS"
Bundler also allows you to work against a git repository locally instead of using the remote version\. This can be achieved by setting up a local override:
.
.IP "" 4
.
.nf

bundle config set \-\-local local\.GEM_NAME /path/to/local/git/repository
.
.fi
.
.IP "" 0
.
.P
For example, in order to use a local Rack repository, a developer could call:
.
.IP "" 4
.
.nf

bundle config set \-\-local local\.rack ~/Work/git/rack
.
.fi
.
.IP "" 0
.
.P
Now instead of checking out the remote git repository, the local override will be used\. Similar to a path source, every time the local git repository change, changes will be automatically picked up by Bundler\. This means a commit in the local git repo will update the revision in the \fBGemfile\.lock\fR to the local git repo revision\. This requires the same attention as git submodules\. Before pushing to the remote, you need to ensure the local override was pushed, otherwise you may point to a commit that only exists in your local machine\. You\'ll also need to CGI escape your usernames and passwords as well\.
.
.P
Bundler does many checks to ensure a developer won\'t work with invalid references\. Particularly, we force a developer to specify a branch in the \fBGemfile\fR in order to use this feature\. If the branch specified in the \fBGemfile\fR and the current branch in the local git repository do not match, Bundler will abort\. This ensures that a developer is always working against the correct branches, and prevents accidental locking to a different branch\.
.
.P
Finally, Bundler also ensures that the current revision in the \fBGemfile\.lock\fR exists in the local git repository\. By doing this, Bundler forces you to fetch the latest changes in the remotes\.
.
.SH "MIRRORS OF GEM SOURCES"
Bundler supports overriding gem sources with mirrors\. This allows you to configure rubygems\.org as the gem source in your Gemfile while still using your mirror to fetch gems\.
.
.IP "" 4
.
.nf

bundle config set \-\-global mirror\.SOURCE_URL MIRROR_URL
.
.fi
.
.IP "" 0
.
.P
For example, to use a mirror of rubygems\.org hosted at rubygems\-mirror\.org:
.
.IP "" 4
.
.nf

bundle config set \-\-global mirror\.http://rubygems\.org http://rubygems\-mirror\.org
.
.fi
.
.IP "" 0
.
.P
Each mirror also provides a fallback timeout setting\. If the mirror does not respond within the fallback timeout, Bundler will try to use the original server instead of the mirror\.
.
.IP "" 4
.
.nf

bundle config set \-\-global mirror\.SOURCE_URL\.fallback_timeout TIMEOUT
.
.fi
.
.IP "" 0
.
.P
For example, to fall back to rubygems\.org after 3 seconds:
.
.IP "" 4
.
.nf

bundle config set \-\-global mirror\.https://rubygems\.org\.fallback_timeout 3
.
.fi
.
.IP "" 0
.
.P
The default fallback timeout is 0\.1 seconds, but the setting can currently only accept whole seconds (for example, 1, 15, or 30)\.
.
.SH "CREDENTIALS FOR GEM SOURCES"
Bundler allows you to configure credentials for any gem source, which allows you to avoid putting secrets into your Gemfile\.
.
.IP "" 4
.
.nf

bundle config set \-\-global SOURCE_HOSTNAME USERNAME:PASSWORD
.
.fi
.
.IP "" 0
.
.P
For example, to save the credentials of user \fBclaudette\fR for the gem source at \fBgems\.longerous\.com\fR, you would run:
.
.IP "" 4
.
.nf

bundle config set \-\-global gems\.longerous\.com claudette:s00pers3krit
.
.fi
.
.IP "" 0
.
.P
Or you can set the credentials as an environment variable like this:
.
.IP "" 4
.
.nf

export BUNDLE_GEMS__LONGEROUS__COM="claudette:s00pers3krit"
.
.fi
.
.IP "" 0
.
.P
For gems with a git source with HTTP(S) URL you can specify credentials like so:
.
.IP "" 4
.
.nf

bundle config set \-\-global https://github\.com/rubygems/rubygems\.git username:password
.
.fi
.
.IP "" 0
.
.P
Or you can set the credentials as an environment variable like so:
.
.IP "" 4
.
.nf

export BUNDLE_GITHUB__COM=username:password
.
.fi
.
.IP "" 0
.
.P
This is especially useful for private repositories on hosts such as Github, where you can use personal OAuth tokens:
.
.IP "" 4
.
.nf

export BUNDLE_GITHUB__COM=abcd0123generatedtoken:x\-oauth\-basic
.
.fi
.
.IP "" 0
.
.P
Note that any configured credentials will be redacted by informative commands such as \fBbundle config list\fR or \fBbundle config get\fR, unless you use the \fB\-\-parseable\fR flag\. This is to avoid unintentionally leaking credentials when copy\-pasting bundler output\.
.
.P
Also note that to guarantee a sane mapping between valid environment variable names and valid host names, bundler makes the following transformations:
.
.IP "\(bu" 4
Any \fB\-\fR characters in a host name are mapped to a triple dash (\fB___\fR) in the corresponding environment variable\.
.
.IP "\(bu" 4
Any \fB\.\fR characters in a host name are mapped to a double dash (\fB__\fR) in the corresponding environment variable\.
.
.IP "" 0
.
.P
This means that if you have a gem server named \fBmy\.gem\-host\.com\fR, you\'ll need to use the \fBBUNDLE_MY__GEM___HOST__COM\fR variable to configure credentials for it through ENV\.
.
.SH "CONFIGURE BUNDLER DIRECTORIES"
Bundler\'s home, config, cache and plugin directories are able to be configured through environment variables\. The default location for Bundler\'s home directory is \fB~/\.bundle\fR, which all directories inherit from by default\. The following outlines the available environment variables and their default values
.
.IP "" 4
.
.nf

BUNDLE_USER_HOME : $HOME/\.bundle
BUNDLE_USER_CACHE : $BUNDLE_USER_HOME/cache
BUNDLE_USER_CONFIG : $BUNDLE_USER_HOME/config
BUNDLE_USER_PLUGIN : $BUNDLE_USER_HOME/plugin
.
.fi
.
.IP "" 0

bundle(1) -- Ruby Dependency Management
=======================================

## SYNOPSIS

`bundle` COMMAND [--no-color] [--verbose] [ARGS]

## DESCRIPTION

Bundler manages an `application's dependencies` through its entire life
across many machines systematically and repeatably.

See [the bundler website](https://bundler.io) for information on getting
started, and Gemfile(5) for more information on the `Gemfile` format.

## OPTIONS

* `--no-color`:
  Print all output without color

* `--retry`, `-r`:
  Specify the number of times you wish to attempt network commands

* `--verbose`, `-V`:
  Print out additional logging information

## BUNDLE COMMANDS

We divide `bundle` subcommands into primary commands and utilities:

## PRIMARY COMMANDS

* [`bundle install(1)`](bundle-install.1.html):
  Install the gems specified by the `Gemfile` or `Gemfile.lock`

* [`bundle update(1)`](bundle-update.1.html):
  Update dependencies to their latest versions

* [`bundle package(1)`](bundle-package.1.html):
  Package the .gem files required by your application into the
  `vendor/cache` directory

* [`bundle exec(1)`](bundle-exec.1.html):
  Execute a script in the current bundle

* [`bundle config(1)`](bundle-config.1.html):
  Specify and read configuration options for Bundler

* `bundle help(1)`:
  Display detailed help for each subcommand

## UTILITIES

* [`bundle add(1)`](bundle-add.1.html):
  Add the named gem to the Gemfile and run `bundle install`

* [`bundle binstubs(1)`](bundle-binstubs.1.html):
  Generate binstubs for executables in a gem

* [`bundle check(1)`](bundle-check.1.html):
  Determine whether the requirements for your application are installed
  and available to Bundler

* [`bundle show(1)`](bundle-show.1.html):
  Show the source location of a particular gem in the bundle

* [`bundle outdated(1)`](bundle-outdated.1.html):
  Show all of the outdated gems in the current bundle

* `bundle console(1)`:
  Start an IRB session in the current bundle

* [`bundle open(1)`](bundle-open.1.html):
  Open an installed gem in the editor

* [`bundle lock(1)`](bundle-lock.1.html):
  Generate a lockfile for your dependencies

* [`bundle viz(1)`](bundle-viz.1.html):
  Generate a visual representation of your dependencies

* [`bundle init(1)`](bundle-init.1.html):
  Generate a simple `Gemfile`, placed in the current directory

* [`bundle gem(1)`](bundle-gem.1.html):
  Create a simple gem, suitable for development with Bundler

* [`bundle platform(1)`](bundle-platform.1.html):
  Display platform compatibility information

* [`bundle clean(1)`](bundle-clean.1.html):
  Clean up unused gems in your Bundler directory

* [`bundle doctor(1)`](bundle-doctor.1.html):
  Display warnings about common problems

* [`bundle remove(1)`](bundle-remove.1.html):
  Removes gems from the Gemfile

## PLUGINS

When running a command that isn't listed in PRIMARY COMMANDS or UTILITIES,
Bundler will try to find an executable on your path named `bundler-<command>`
and execute it, passing down any extra arguments to it.

## OBSOLETE

These commands are obsolete and should no longer be used:

* `bundle cache(1)`
* `bundle show(1)`
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-BINSTUBS" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-binstubs\fR \- Install the binstubs of the listed gems
.
.SH "SYNOPSIS"
\fBbundle binstubs\fR \fIGEM_NAME\fR [\-\-force] [\-\-path PATH] [\-\-standalone]
.
.SH "DESCRIPTION"
Binstubs are scripts that wrap around executables\. Bundler creates a small Ruby file (a binstub) that loads Bundler, runs the command, and puts it into \fBbin/\fR\. Binstubs are a shortcut\-or alternative\- to always using \fBbundle exec\fR\. This gives you a file that can be run directly, and one that will always run the correct gem version used by the application\.
.
.P
For example, if you run \fBbundle binstubs rspec\-core\fR, Bundler will create the file \fBbin/rspec\fR\. That file will contain enough code to load Bundler, tell it to load the bundled gems, and then run rspec\.
.
.P
This command generates binstubs for executables in \fBGEM_NAME\fR\. Binstubs are put into \fBbin\fR, or the \fB\-\-path\fR directory if one has been set\. Calling binstubs with [GEM [GEM]] will create binstubs for all given gems\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-force\fR
Overwrite existing binstubs if they exist\.
.
.TP
\fB\-\-path\fR
The location to install the specified binstubs to\. This defaults to \fBbin\fR\.
.
.TP
\fB\-\-standalone\fR
Makes binstubs that can work without depending on Rubygems or Bundler at runtime\.
.
.TP
\fB\-\-shebang\fR
Specify a different shebang executable name than the default (default \'ruby\')
.
.TP
\fB\-\-all\fR
Create binstubs for all gems in the bundle\.

bundle-cache(1) -- Package your needed `.gem` files into your application
===========================================================================

## SYNOPSIS

`bundle cache`

## DESCRIPTION

Copy all of the `.gem` files needed to run the application into the
`vendor/cache` directory. In the future, when running [bundle install(1)][bundle-install],
use the gems in the cache in preference to the ones on `rubygems.org`.

## GIT AND PATH GEMS

The `bundle cache` command can also package `:git` and `:path` dependencies
besides .gem files. This needs to be explicitly enabled via the `--all` option.
Once used, the `--all` option will be remembered.

## SUPPORT FOR MULTIPLE PLATFORMS

When using gems that have different packages for different platforms, Bundler
supports caching of gems for other platforms where the Gemfile has been resolved
(i.e. present in the lockfile) in `vendor/cache`.  This needs to be enabled via
the `--all-platforms` option. This setting will be remembered in your local
bundler configuration.

## REMOTE FETCHING

By default, if you run `bundle install(1)`](bundle-install.1.html) after running
[bundle cache(1)](bundle-cache.1.html), bundler will still connect to `rubygems.org`
to check whether a platform-specific gem exists for any of the gems
in `vendor/cache`.

For instance, consider this Gemfile(5):

    source "https://rubygems.org"

    gem "nokogiri"

If you run `bundle cache` under C Ruby, bundler will retrieve
the version of `nokogiri` for the `"ruby"` platform. If you deploy
to JRuby and run `bundle install`, bundler is forced to check to
see whether a `"java"` platformed `nokogiri` exists.

Even though the `nokogiri` gem for the Ruby platform is
_technically_ acceptable on JRuby, it has a C extension
that does not run on JRuby. As a result, bundler will, by default,
still connect to `rubygems.org` to check whether it has a version
of one of your gems more specific to your platform.

This problem is also not limited to the `"java"` platform.
A similar (common) problem can happen when developing on Windows
and deploying to Linux, or even when developing on OSX and
deploying to Linux.

If you know for sure that the gems packaged in `vendor/cache`
are appropriate for the platform you are on, you can run
`bundle install --local` to skip checking for more appropriate
gems, and use the ones in `vendor/cache`.

One way to be sure that you have the right platformed versions
of all your gems is to run `bundle cache` on an identical
machine and check in the gems. For instance, you can run
`bundle cache` on an identical staging box during your
staging process, and check in the `vendor/cache` before
deploying to production.

By default, [bundle cache(1)](bundle-cache.1.html) fetches and also
installs the gems to the default location. To package the
dependencies to `vendor/cache` without installing them to the
local install location, you can run `bundle cache --no-install`.
bundle-list(1) -- List all the gems in the bundle
=========================================================================

## SYNOPSIS

`bundle list` [--name-only] [--paths] [--without-group=GROUP[ GROUP...]] [--only-group=GROUP[ GROUP...]]

## DESCRIPTION

Prints a list of all the gems in the bundle including their version.

Example:

bundle list --name-only

bundle list --paths

bundle list --without-group test

bundle list --only-group dev

bundle list --only-group dev test --paths

## OPTIONS

* `--name-only`:
  Print only the name of each gem.
* `--paths`:
  Print the path to each gem in the bundle.
* `--without-group=<list>`:
  A space-separated list of groups of gems to skip during printing.
* `--only-group=<list>`:
  A space-separated list of groups of gems to print.
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-OUTDATED" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-outdated\fR \- List installed gems with newer versions available
.
.SH "SYNOPSIS"
\fBbundle outdated\fR [GEM] [\-\-local] [\-\-pre] [\-\-source] [\-\-strict] [\-\-parseable | \-\-porcelain] [\-\-group=GROUP] [\-\-groups] [\-\-update\-strict] [\-\-patch|\-\-minor|\-\-major] [\-\-filter\-major] [\-\-filter\-minor] [\-\-filter\-patch] [\-\-only\-explicit]
.
.SH "DESCRIPTION"
Outdated lists the names and versions of gems that have a newer version available in the given source\. Calling outdated with [GEM [GEM]] will only check for newer versions of the given gems\. Prerelease gems are ignored by default\. If your gems are up to date, Bundler will exit with a status of 0\. Otherwise, it will exit 1\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-local\fR
Do not attempt to fetch gems remotely and use the gem cache instead\.
.
.TP
\fB\-\-pre\fR
Check for newer pre\-release gems\.
.
.TP
\fB\-\-source\fR
Check against a specific source\.
.
.TP
\fB\-\-strict\fR
Only list newer versions allowed by your Gemfile requirements\.
.
.TP
\fB\-\-parseable\fR, \fB\-\-porcelain\fR
Use minimal formatting for more parseable output\.
.
.TP
\fB\-\-group\fR
List gems from a specific group\.
.
.TP
\fB\-\-groups\fR
List gems organized by groups\.
.
.TP
\fB\-\-update\-strict\fR
Strict conservative resolution, do not allow any gem to be updated past latest \-\-patch | \-\-minor| \-\-major\.
.
.TP
\fB\-\-minor\fR
Prefer updating only to next minor version\.
.
.TP
\fB\-\-major\fR
Prefer updating to next major version (default)\.
.
.TP
\fB\-\-patch\fR
Prefer updating only to next patch version\.
.
.TP
\fB\-\-filter\-major\fR
Only list major newer versions\.
.
.TP
\fB\-\-filter\-minor\fR
Only list minor newer versions\.
.
.TP
\fB\-\-filter\-patch\fR
Only list patch newer versions\.
.
.TP
\fB\-\-only\-explicit\fR
Only list gems specified in your Gemfile, not their dependencies\.
.
.SH "PATCH LEVEL OPTIONS"
See bundle update(1) \fIbundle\-update\.1\.html\fR for details\.
.
.P
One difference between the patch level options in \fBbundle update\fR and here is the \fB\-\-strict\fR option\. \fB\-\-strict\fR was already an option on outdated before the patch level options were added\. \fB\-\-strict\fR wasn\'t altered, and the \fB\-\-update\-strict\fR option on \fBoutdated\fR reflects what \fB\-\-strict\fR does on \fBbundle update\fR\.
.
.SH "FILTERING OUTPUT"
The 3 filtering options do not affect the resolution of versions, merely what versions are shown in the output\.
.
.P
If the regular output shows the following:
.
.IP "" 4
.
.nf

* faker (newest 1\.6\.6, installed 1\.6\.5, requested ~> 1\.4) in groups "development, test"
* hashie (newest 3\.4\.6, installed 1\.2\.0, requested = 1\.2\.0) in groups "default"
* headless (newest 2\.3\.1, installed 2\.2\.3) in groups "test"
.
.fi
.
.IP "" 0
.
.P
\fB\-\-filter\-major\fR would only show:
.
.IP "" 4
.
.nf

* hashie (newest 3\.4\.6, installed 1\.2\.0, requested = 1\.2\.0) in groups "default"
.
.fi
.
.IP "" 0
.
.P
\fB\-\-filter\-minor\fR would only show:
.
.IP "" 4
.
.nf

* headless (newest 2\.3\.1, installed 2\.2\.3) in groups "test"
.
.fi
.
.IP "" 0
.
.P
\fB\-\-filter\-patch\fR would only show:
.
.IP "" 4
.
.nf

* faker (newest 1\.6\.6, installed 1\.6\.5, requested ~> 1\.4) in groups "development, test"
.
.fi
.
.IP "" 0
.
.P
Filter options can be combined\. \fB\-\-filter\-minor\fR and \fB\-\-filter\-patch\fR would show:
.
.IP "" 4
.
.nf

* faker (newest 1\.6\.6, installed 1\.6\.5, requested ~> 1\.4) in groups "development, test"
* headless (newest 2\.3\.1, installed 2\.2\.3) in groups "test"
.
.fi
.
.IP "" 0
.
.P
Combining all three \fBfilter\fR options would be the same result as providing none of them\.
Gemfile(5) -- A format for describing gem dependencies for Ruby programs
========================================================================

## SYNOPSIS

A `Gemfile` describes the gem dependencies required to execute associated
Ruby code.

Place the `Gemfile` in the root of the directory containing the associated
code. For instance, in a Rails application, place the `Gemfile` in the same
directory as the `Rakefile`.

## SYNTAX

A `Gemfile` is evaluated as Ruby code, in a context which makes available
a number of methods used to describe the gem requirements.

## GLOBAL SOURCES

At the top of the `Gemfile`, add a line for the `Rubygems` source that contains
the gems listed in the `Gemfile`.

    source "https://rubygems.org"

It is possible, but not recommended as of Bundler 1.7, to add multiple global
`source` lines. Each of these `source`s `MUST` be a valid Rubygems repository.

Sources are checked for gems following the heuristics described in
[SOURCE PRIORITY][]. If a gem is found in more than one global source, Bundler
will print a warning after installing the gem indicating which source was used,
and listing the other sources where the gem is available. A specific source can
be selected for gems that need to use a non-standard repository, suppressing
this warning, by using the [`:source` option](#SOURCE) or a
[`source` block](#BLOCK-FORM-OF-SOURCE-GIT-PATH-GROUP-and-PLATFORMS).

### CREDENTIALS

Some gem sources require a username and password. Use [bundle config(1)](bundle-config.1.html) to set
the username and password for any of the sources that need it. The command must
be run once on each computer that will install the Gemfile, but this keeps the
credentials from being stored in plain text in version control.

    bundle config gems.example.com user:password

For some sources, like a company Gemfury account, it may be easier to
include the credentials in the Gemfile as part of the source URL.

    source "https://user:password@gems.example.com"

Credentials in the source URL will take precedence over credentials set using
`config`.

## RUBY

If your application requires a specific Ruby version or engine, specify your
requirements using the `ruby` method, with the following arguments.
All parameters are `OPTIONAL` unless otherwise specified.

### VERSION (required)

The version of Ruby that your application requires. If your application
requires an alternate Ruby engine, such as JRuby, Rubinius or TruffleRuby, this
should be the Ruby version that the engine is compatible with.

    ruby "1.9.3"

### ENGINE

Each application _may_ specify a Ruby engine. If an engine is specified, an
engine version _must_ also be specified.

What exactly is an Engine?
  - A Ruby engine is an implementation of the Ruby language.

  - For background: the reference or original implementation of the Ruby
    programming language is called
    [Matz's Ruby Interpreter](https://en.wikipedia.org/wiki/Ruby_MRI), or  MRI
    for short. This is named after Ruby creator Yukihiro Matsumoto,
    also known as Matz. MRI is also known as CRuby, because it is written in C.
    MRI is the most widely used Ruby engine.

  - [Other implementations](https://www.ruby-lang.org/en/about/) of Ruby exist.
    Some of the more well-known implementations include
    [Rubinius](https://rubinius.com/), and [JRuby](http://jruby.org/).
    Rubinius is an alternative implementation of Ruby written in Ruby.
    JRuby is an implementation of Ruby on the JVM, short for Java Virtual Machine.

### ENGINE VERSION

Each application _may_ specify a Ruby engine version. If an engine version is
specified, an engine _must_ also be specified. If the engine is "ruby" the
engine version specified _must_ match the Ruby version.

    ruby "1.8.7", :engine => "jruby", :engine_version => "1.6.7"

### PATCHLEVEL

Each application _may_ specify a Ruby patchlevel.

    ruby "2.0.0", :patchlevel => "247"

## GEMS

Specify gem requirements using the `gem` method, with the following arguments.
All parameters are `OPTIONAL` unless otherwise specified.

### NAME (required)

For each gem requirement, list a single _gem_ line.

    gem "nokogiri"

### VERSION

Each _gem_ `MAY` have one or more version specifiers.

    gem "nokogiri", ">= 1.4.2"
    gem "RedCloth", ">= 4.1.0", "< 4.2.0"

### REQUIRE AS

Each _gem_ `MAY` specify files that should be used when autorequiring via
`Bundler.require`. You may pass an array with multiple files or `true` if the file
you want `required` has the same name as _gem_ or `false` to
prevent any file from being autorequired.

    gem "redis", :require => ["redis/connection/hiredis", "redis"]
    gem "webmock", :require => false
    gem "byebug", :require => true

The argument defaults to the name of the gem. For example, these are identical:

    gem "nokogiri"
    gem "nokogiri", :require => "nokogiri"
    gem "nokogiri", :require => true

### GROUPS

Each _gem_ `MAY` specify membership in one or more groups. Any _gem_ that does
not specify membership in any group is placed in the `default` group.

    gem "rspec", :group => :test
    gem "wirble", :groups => [:development, :test]

The Bundler runtime allows its two main methods, `Bundler.setup` and
`Bundler.require`, to limit their impact to particular groups.

    # setup adds gems to Ruby's load path
    Bundler.setup                    # defaults to all groups
    require "bundler/setup"          # same as Bundler.setup
    Bundler.setup(:default)          # only set up the _default_ group
    Bundler.setup(:test)             # only set up the _test_ group (but `not` _default_)
    Bundler.setup(:default, :test)   # set up the _default_ and _test_ groups, but no others

    # require requires all of the gems in the specified groups
    Bundler.require                  # defaults to the _default_ group
    Bundler.require(:default)        # identical
    Bundler.require(:default, :test) # requires the _default_ and _test_ groups
    Bundler.require(:test)           # requires the _test_ group

The Bundler CLI allows you to specify a list of groups whose gems `bundle install` should
not install with the `without` configuration.

To specify multiple groups to ignore, specify a list of groups separated by spaces.

    bundle config set --local without test
    bundle config set --local without development test

Also, calling `Bundler.setup` with no parameters, or calling `require "bundler/setup"`
will setup all groups except for the ones you excluded via `--without` (since they
are not available).

Note that on `bundle install`, bundler downloads and evaluates all gems, in order to
create a single canonical list of all of the required gems and their dependencies.
This means that you cannot list different versions of the same gems in different
groups. For more details, see [Understanding Bundler](https://bundler.io/rationale.html).

### PLATFORMS

If a gem should only be used in a particular platform or set of platforms, you can
specify them. Platforms are essentially identical to groups, except that you do not
need to use the `--without` install-time flag to exclude groups of gems for other
platforms.

There are a number of `Gemfile` platforms:

  * `ruby`:
    C Ruby (MRI), Rubinius or TruffleRuby, but `NOT` Windows
  * `mri`:
    Same as _ruby_, but only C Ruby (MRI)
  * `mingw`:
    Windows 32 bit 'mingw32' platform (aka RubyInstaller)
  * `x64_mingw`:
    Windows 64 bit 'mingw32' platform (aka RubyInstaller x64)
  * `rbx`:
    Rubinius
  * `jruby`:
    JRuby
  * `truffleruby`:
    TruffleRuby
  * `mswin`:
    Windows

You can restrict further by platform and version for all platforms *except* for
`rbx`, `jruby`, `truffleruby` and `mswin`.

To specify a version in addition to a platform, append the version number without
the delimiter to the platform. For example, to specify that a gem should only be
used on platforms with Ruby 2.3, use:

    ruby_23

The full list of platforms and supported versions includes:

  * `ruby`:
    1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6
  * `mri`:
    1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6
  * `mingw`:
    1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6
  * `x64_mingw`:
    2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6

As with groups, you can specify one or more platforms:

    gem "weakling",   :platforms => :jruby
    gem "ruby-debug", :platforms => :mri_18
    gem "nokogiri",   :platforms => [:mri_18, :jruby]

All operations involving groups ([`bundle install`](bundle-install.1.html), `Bundler.setup`,
`Bundler.require`) behave exactly the same as if any groups not
matching the current platform were explicitly excluded.

### SOURCE

You can select an alternate Rubygems repository for a gem using the ':source'
option.

    gem "some_internal_gem", :source => "https://gems.example.com"

This forces the gem to be loaded from this source and ignores any global sources
declared at the top level of the file. If the gem does not exist in this source,
it will not be installed.

Bundler will search for child dependencies of this gem by first looking in the
source selected for the parent, but if they are not found there, it will fall
back on global sources using the ordering described in [SOURCE PRIORITY][].

Selecting a specific source repository this way also suppresses the ambiguous
gem warning described above in
[GLOBAL SOURCES (#source)](#GLOBAL-SOURCES).

Using the `:source` option for an individual gem will also make that source
available as a possible global source for any other gems which do not specify
explicit sources. Thus, when adding gems with explicit sources, it is
recommended that you also ensure all other gems in the Gemfile are using
explicit sources.

### GIT

If necessary, you can specify that a gem is located at a particular
git repository using the `:git` parameter. The repository can be accessed via
several protocols:

  * `HTTP(S)`:
    gem "rails", :git => "https://github.com/rails/rails.git"
  * `SSH`:
    gem "rails", :git => "git@github.com:rails/rails.git"
  * `git`:
    gem "rails", :git => "git://github.com/rails/rails.git"

If using SSH, the user that you use to run `bundle install` `MUST` have the
appropriate keys available in their `$HOME/.ssh`.

`NOTE`: `http://` and `git://` URLs should be avoided if at all possible. These
protocols are unauthenticated, so a man-in-the-middle attacker can deliver
malicious code and compromise your system. HTTPS and SSH are strongly
preferred.

The `group`, `platforms`, and `require` options are available and behave
exactly the same as they would for a normal gem.

A git repository `SHOULD` have at least one file, at the root of the
directory containing the gem, with the extension `.gemspec`. This file
`MUST` contain a valid gem specification, as expected by the `gem build`
command.

If a git repository does not have a `.gemspec`, bundler will attempt to
create one, but it will not contain any dependencies, executables, or
C extension compilation instructions. As a result, it may fail to properly
integrate into your application.

If a git repository does have a `.gemspec` for the gem you attached it
to, a version specifier, if provided, means that the git repository is
only valid if the `.gemspec` specifies a version matching the version
specifier. If not, bundler will print a warning.

    gem "rails", "2.3.8", :git => "https://github.com/rails/rails.git"
    # bundle install will fail, because the .gemspec in the rails
    # repository's master branch specifies version 3.0.0

If a git repository does `not` have a `.gemspec` for the gem you attached
it to, a version specifier `MUST` be provided. Bundler will use this
version in the simple `.gemspec` it creates.

Git repositories support a number of additional options.

  * `branch`, `tag`, and `ref`:
    You `MUST` only specify at most one of these options. The default
    is `:branch => "master"`.  For example:

      gem "rails", :git => "https://github.com/rails/rails.git", :branch => "5-0-stable"

      gem "rails", :git => "https://github.com/rails/rails.git", :tag => "v5.0.0"

      gem "rails", :git => "https://github.com/rails/rails.git", :ref => "4aded"

  * `submodules`:
    For reference, a [git submodule](https://git-scm.com/book/en/v2/Git-Tools-Submodules)
    lets you have another git repository within a subfolder of your repository.
    Specify `:submodules => true` to cause bundler to expand any
    submodules included in the git repository

If a git repository contains multiple `.gemspecs`, each `.gemspec`
represents a gem located at the same place in the file system as
the `.gemspec`.

    |~rails                   [git root]
    | |-rails.gemspec         [rails gem located here]
    |~actionpack
    | |-actionpack.gemspec    [actionpack gem located here]
    |~activesupport
    | |-activesupport.gemspec [activesupport gem located here]
    |...

To install a gem located in a git repository, bundler changes to
the directory containing the gemspec, runs `gem build name.gemspec`
and then installs the resulting gem. The `gem build` command,
which comes standard with Rubygems, evaluates the `.gemspec` in
the context of the directory in which it is located.

### GIT SOURCE

A custom git source can be defined via the `git_source` method. Provide the source's name
as an argument, and a block which receives a single argument and interpolates it into a
string to return the full repo address:

    git_source(:stash){ |repo_name| "https://stash.corp.acme.pl/#{repo_name}.git" }
    gem 'rails', :stash => 'forks/rails'

In addition, if you wish to choose a specific branch:

    gem "rails", :stash => "forks/rails", :branch => "branch_name"

### GITHUB

`NOTE`: This shorthand should be avoided until Bundler 2.0, since it
currently expands to an insecure `git://` URL. This allows a
man-in-the-middle attacker to compromise your system.

If the git repository you want to use is hosted on GitHub and is public, you can use the
:github shorthand to specify the github username and repository name (without the
trailing ".git"), separated by a slash. If both the username and repository name are the
same, you can omit one.

    gem "rails", :github => "rails/rails"
    gem "rails", :github => "rails"

Are both equivalent to

    gem "rails", :git => "git://github.com/rails/rails.git"

Since the `github` method is a specialization of `git_source`, it accepts a `:branch` named argument.

You can also directly pass a pull request URL:

    gem "rails", :github => "https://github.com/rails/rails/pull/43753"

Which is equivalent to:

    gem "rails", :github => "rails/rails", branch: "refs/pull/43753/head"

### GIST

If the git repository you want to use is hosted as a Github Gist and is public, you can use
the :gist shorthand to specify the gist identifier (without the trailing ".git").

    gem "the_hatch", :gist => "4815162342"

Is equivalent to:

    gem "the_hatch", :git => "https://gist.github.com/4815162342.git"

Since the `gist` method is a specialization of `git_source`, it accepts a `:branch` named argument.

### BITBUCKET

If the git repository you want to use is hosted on Bitbucket and is public, you can use the
:bitbucket shorthand to specify the bitbucket username and repository name (without the
trailing ".git"), separated by a slash. If both the username and repository name are the
same, you can omit one.

    gem "rails", :bitbucket => "rails/rails"
    gem "rails", :bitbucket => "rails"

Are both equivalent to

    gem "rails", :git => "https://rails@bitbucket.org/rails/rails.git"

Since the `bitbucket` method is a specialization of `git_source`, it accepts a `:branch` named argument.

### PATH

You can specify that a gem is located in a particular location
on the file system. Relative paths are resolved relative to the
directory containing the `Gemfile`.

Similar to the semantics of the `:git` option, the `:path`
option requires that the directory in question either contains
a `.gemspec` for the gem, or that you specify an explicit
version that bundler should use.

Unlike `:git`, bundler does not compile C extensions for
gems specified as paths.

    gem "rails", :path => "vendor/rails"

If you would like to use multiple local gems directly from the filesystem, you can set a global `path` option to the path containing the gem's files. This will automatically load gemspec files from subdirectories.

    path 'components' do
      gem 'admin_ui'
      gem 'public_ui'
    end

## BLOCK FORM OF SOURCE, GIT, PATH, GROUP and PLATFORMS

The `:source`, `:git`, `:path`, `:group`, and `:platforms` options may be
applied to a group of gems by using block form.

    source "https://gems.example.com" do
      gem "some_internal_gem"
      gem "another_internal_gem"
    end

    git "https://github.com/rails/rails.git" do
      gem "activesupport"
      gem "actionpack"
    end

    platforms :ruby do
      gem "ruby-debug"
      gem "sqlite3"
    end

    group :development, :optional => true do
      gem "wirble"
      gem "faker"
    end

In the case of the group block form the :optional option can be given
to prevent a group from being installed unless listed in the `--with`
option given to the `bundle install` command.

In the case of the `git` block form, the `:ref`, `:branch`, `:tag`,
and `:submodules` options may be passed to the `git` method, and
all gems in the block will inherit those options.

The presence of a `source` block in a Gemfile also makes that source
available as a possible global source for any other gems which do not specify
explicit sources. Thus, when defining source blocks, it is
recommended that you also ensure all other gems in the Gemfile are using
explicit sources, either via source blocks or `:source` directives on
individual gems.

## INSTALL_IF

The `install_if` method allows gems to be installed based on a proc or lambda.
This is especially useful for optional gems that can only be used if certain
software is installed or some other conditions are met.

    install_if -> { RUBY_PLATFORM =~ /darwin/ } do
      gem "pasteboard"
    end

## GEMSPEC

The [`.gemspec`](http://guides.rubygems.org/specification-reference/) file is where
 you provide metadata about your gem to Rubygems. Some required Gemspec
 attributes include the name, description, and homepage of your gem. This is
 also where you specify the dependencies your gem needs to run.

If you wish to use Bundler to help install dependencies for a gem while it is
being developed, use the `gemspec` method to pull in the dependencies listed in
the `.gemspec` file.

The `gemspec` method adds any runtime dependencies as gem requirements in the
default group. It also adds development dependencies as gem requirements in the
`development` group. Finally, it adds a gem requirement on your project (`:path
=> '.'`). In conjunction with `Bundler.setup`, this allows you to require project
files in your test code as you would if the project were installed as a gem; you
need not manipulate the load path manually or require project files via relative
paths.

The `gemspec` method supports optional `:path`, `:glob`, `:name`, and `:development_group`
options, which control where bundler looks for the `.gemspec`, the glob it uses to look
for the gemspec (defaults to: "{,*,*/*}.gemspec"), what named `.gemspec` it uses
(if more than one is present), and which group development dependencies are included in.

When a `gemspec` dependency encounters version conflicts during resolution, the
local version under development will always be selected -- even if there are
remote versions that better match other requirements for the `gemspec` gem.

## SOURCE PRIORITY

When attempting to locate a gem to satisfy a gem requirement,
bundler uses the following priority order:

  1. The source explicitly attached to the gem (using `:source`, `:path`, or
     `:git`)
  2. For implicit gems (dependencies of explicit gems), any source, git, or path
     repository declared on the parent. This results in bundler prioritizing the
     ActiveSupport gem from the Rails git repository over ones from
     `rubygems.org`
  3. The sources specified via global `source` lines, searching each source in
     your `Gemfile` from last added to first added.
bundle-check(1) -- Verifies if dependencies are satisfied by installed gems
===========================================================================

## SYNOPSIS

`bundle check` [--dry-run]
               [--gemfile=FILE]
               [--path=PATH]

## DESCRIPTION

`check` searches the local machine for each of the gems requested in the
Gemfile. If all gems are found, Bundler prints a success message and exits with
a status of 0.

If not, the first missing gem is listed and Bundler exits status 1.

## OPTIONS

* `--dry-run`:
  Locks the [`Gemfile(5)`][Gemfile(5)] before running the command.
* `--gemfile`:
  Use the specified gemfile instead of the [`Gemfile(5)`][Gemfile(5)].
* `--path`:
  Specify a different path than the system default (`$BUNDLE_PATH` or `$GEM_HOME`).
  Bundler will remember this value for future installs on this machine.
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-EXEC" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-exec\fR \- Execute a command in the context of the bundle
.
.SH "SYNOPSIS"
\fBbundle exec\fR [\-\-keep\-file\-descriptors] \fIcommand\fR
.
.SH "DESCRIPTION"
This command executes the command, making all gems specified in the [\fBGemfile(5)\fR][Gemfile(5)] available to \fBrequire\fR in Ruby programs\.
.
.P
Essentially, if you would normally have run something like \fBrspec spec/my_spec\.rb\fR, and you want to use the gems specified in the [\fBGemfile(5)\fR][Gemfile(5)] and installed via bundle install(1) \fIbundle\-install\.1\.html\fR, you should run \fBbundle exec rspec spec/my_spec\.rb\fR\.
.
.P
Note that \fBbundle exec\fR does not require that an executable is available on your shell\'s \fB$PATH\fR\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-keep\-file\-descriptors\fR
Exec in Ruby 2\.0 began discarding non\-standard file descriptors\. When this flag is passed, exec will revert to the 1\.9 behaviour of passing all file descriptors to the new process\.
.
.SH "BUNDLE INSTALL \-\-BINSTUBS"
If you use the \fB\-\-binstubs\fR flag in bundle install(1) \fIbundle\-install\.1\.html\fR, Bundler will automatically create a directory (which defaults to \fBapp_root/bin\fR) containing all of the executables available from gems in the bundle\.
.
.P
After using \fB\-\-binstubs\fR, \fBbin/rspec spec/my_spec\.rb\fR is identical to \fBbundle exec rspec spec/my_spec\.rb\fR\.
.
.SH "ENVIRONMENT MODIFICATIONS"
\fBbundle exec\fR makes a number of changes to the shell environment, then executes the command you specify in full\.
.
.IP "\(bu" 4
make sure that it\'s still possible to shell out to \fBbundle\fR from inside a command invoked by \fBbundle exec\fR (using \fB$BUNDLE_BIN_PATH\fR)
.
.IP "\(bu" 4
put the directory containing executables (like \fBrails\fR, \fBrspec\fR, \fBrackup\fR) for your bundle on \fB$PATH\fR
.
.IP "\(bu" 4
make sure that if bundler is invoked in the subshell, it uses the same \fBGemfile\fR (by setting \fBBUNDLE_GEMFILE\fR)
.
.IP "\(bu" 4
add \fB\-rbundler/setup\fR to \fB$RUBYOPT\fR, which makes sure that Ruby programs invoked in the subshell can see the gems in the bundle
.
.IP "" 0
.
.P
It also modifies Rubygems:
.
.IP "\(bu" 4
disallow loading additional gems not in the bundle
.
.IP "\(bu" 4
modify the \fBgem\fR method to be a no\-op if a gem matching the requirements is in the bundle, and to raise a \fBGem::LoadError\fR if it\'s not
.
.IP "\(bu" 4
Define \fBGem\.refresh\fR to be a no\-op, since the source index is always frozen when using bundler, and to prevent gems from the system leaking into the environment
.
.IP "\(bu" 4
Override \fBGem\.bin_path\fR to use the gems in the bundle, making system executables work
.
.IP "\(bu" 4
Add all gems in the bundle into Gem\.loaded_specs
.
.IP "" 0
.
.P
Finally, \fBbundle exec\fR also implicitly modifies \fBGemfile\.lock\fR if the lockfile and the Gemfile do not match\. Bundler needs the Gemfile to determine things such as a gem\'s groups, \fBautorequire\fR, and platforms, etc\., and that information isn\'t stored in the lockfile\. The Gemfile and lockfile must be synced in order to \fBbundle exec\fR successfully, so \fBbundle exec\fR updates the lockfile beforehand\.
.
.SS "Loading"
By default, when attempting to \fBbundle exec\fR to a file with a ruby shebang, Bundler will \fBKernel\.load\fR that file instead of using \fBKernel\.exec\fR\. For the vast majority of cases, this is a performance improvement\. In a rare few cases, this could cause some subtle side\-effects (such as dependence on the exact contents of \fB$0\fR or \fB__FILE__\fR) and the optimization can be disabled by enabling the \fBdisable_exec_load\fR setting\.
.
.SS "Shelling out"
Any Ruby code that opens a subshell (like \fBsystem\fR, backticks, or \fB%x{}\fR) will automatically use the current Bundler environment\. If you need to shell out to a Ruby command that is not part of your current bundle, use the \fBwith_clean_env\fR method with a block\. Any subshells created inside the block will be given the environment present before Bundler was activated\. For example, Homebrew commands run Ruby, but don\'t work inside a bundle:
.
.IP "" 4
.
.nf

Bundler\.with_clean_env do
  `brew install wget`
end
.
.fi
.
.IP "" 0
.
.P
Using \fBwith_clean_env\fR is also necessary if you are shelling out to a different bundle\. Any Bundler commands run in a subshell will inherit the current Gemfile, so commands that need to run in the context of a different bundle also need to use \fBwith_clean_env\fR\.
.
.IP "" 4
.
.nf

Bundler\.with_clean_env do
  Dir\.chdir "/other/bundler/project" do
    `bundle exec \./script`
  end
end
.
.fi
.
.IP "" 0
.
.P
Bundler provides convenience helpers that wrap \fBsystem\fR and \fBexec\fR, and they can be used like this:
.
.IP "" 4
.
.nf

Bundler\.clean_system(\'brew install wget\')
Bundler\.clean_exec(\'brew install wget\')
.
.fi
.
.IP "" 0
.
.SH "RUBYGEMS PLUGINS"
At present, the Rubygems plugin system requires all files named \fBrubygems_plugin\.rb\fR on the load path of \fIany\fR installed gem when any Ruby code requires \fBrubygems\.rb\fR\. This includes executables installed into the system, like \fBrails\fR, \fBrackup\fR, and \fBrspec\fR\.
.
.P
Since Rubygems plugins can contain arbitrary Ruby code, they commonly end up activating themselves or their dependencies\.
.
.P
For instance, the \fBgemcutter 0\.5\fR gem depended on \fBjson_pure\fR\. If you had that version of gemcutter installed (even if you \fIalso\fR had a newer version without this problem), Rubygems would activate \fBgemcutter 0\.5\fR and \fBjson_pure <latest>\fR\.
.
.P
If your Gemfile(5) also contained \fBjson_pure\fR (or a gem with a dependency on \fBjson_pure\fR), the latest version on your system might conflict with the version in your Gemfile(5), or the snapshot version in your \fBGemfile\.lock\fR\.
.
.P
If this happens, bundler will say:
.
.IP "" 4
.
.nf

You have already activated json_pure 1\.4\.6 but your Gemfile
requires json_pure 1\.4\.3\. Consider using bundle exec\.
.
.fi
.
.IP "" 0
.
.P
In this situation, you almost certainly want to remove the underlying gem with the problematic gem plugin\. In general, the authors of these plugins (in this case, the \fBgemcutter\fR gem) have released newer versions that are more careful in their plugins\.
.
.P
You can find a list of all the gems containing gem plugins by running
.
.IP "" 4
.
.nf

ruby \-rrubygems \-e "puts Gem\.find_files(\'rubygems_plugin\.rb\')"
.
.fi
.
.IP "" 0
.
.P
At the very least, you should remove all but the newest version of each gem plugin, and also remove all gem plugins that you aren\'t using (\fBgem uninstall gem_name\fR)\.
# frozen_string_literal: true

module Bundler
  class BundlerError < StandardError
    def self.status_code(code)
      define_method(:status_code) { code }
      if match = BundlerError.all_errors.find {|_k, v| v == code }
        error, _ = match
        raise ArgumentError,
          "Trying to register #{self} for status code #{code} but #{error} is already registered"
      end
      BundlerError.all_errors[self] = code
    end

    def self.all_errors
      @all_errors ||= {}
    end
  end

  class GemfileError < BundlerError; status_code(4); end
  class InstallError < BundlerError; status_code(5); end

  # Internal error, should be rescued
  class VersionConflict < BundlerError
    attr_reader :conflicts

    def initialize(conflicts, msg = nil)
      super(msg)
      @conflicts = conflicts
    end

    status_code(6)
  end

  class GemNotFound < BundlerError; status_code(7); end
  class InstallHookError < BundlerError; status_code(8); end
  class GemfileNotFound < BundlerError; status_code(10); end
  class GitError < BundlerError; status_code(11); end
  class DeprecatedError < BundlerError; status_code(12); end
  class PathError < BundlerError; status_code(13); end
  class GemspecError < BundlerError; status_code(14); end
  class InvalidOption < BundlerError; status_code(15); end
  class ProductionError < BundlerError; status_code(16); end
  class HTTPError < BundlerError
    status_code(17)
    def filter_uri(uri)
      URICredentialsFilter.credential_filtered_uri(uri)
    end
  end
  class RubyVersionMismatch < BundlerError; status_code(18); end
  class SecurityError < BundlerError; status_code(19); end
  class LockfileError < BundlerError; status_code(20); end
  class CyclicDependencyError < BundlerError; status_code(21); end
  class GemfileLockNotFound < BundlerError; status_code(22); end
  class PluginError < BundlerError; status_code(29); end
  class SudoNotPermittedError < BundlerError; status_code(30); end
  class ThreadCreationError < BundlerError; status_code(33); end
  class APIResponseMismatchError < BundlerError; status_code(34); end
  class APIResponseInvalidDependenciesError < BundlerError; status_code(35); end
  class GemfileEvalError < GemfileError; end
  class MarshalError < StandardError; end

  class PermissionError < BundlerError
    def initialize(path, permission_type = :write)
      @path = path
      @permission_type = permission_type
    end

    def action
      case @permission_type
      when :read then "read from"
      when :write then "write to"
      when :executable, :exec then "execute"
      else @permission_type.to_s
      end
    end

    def permission_type
      case @permission_type
      when :create
        "executable permissions for all parent directories and write permissions for `#{parent_folder}`"
      when :delete
        permissions = "executable permissions for all parent directories and write permissions for `#{parent_folder}`"
        permissions += ", and the same thing for all subdirectories inside #{@path}" if File.directory?(@path)
        permissions
      else
        "#{@permission_type} permissions for that path"
      end
    end

    def parent_folder
      File.dirname(@path)
    end

    def message
      "There was an error while trying to #{action} `#{@path}`. " \
      "It is likely that you need to grant #{permission_type}."
    end

    status_code(23)
  end

  class GemRequireError < BundlerError
    attr_reader :orig_exception

    def initialize(orig_exception, msg)
      full_message = msg + "\nGem Load Error is: #{orig_exception.message}\n"\
                      "Backtrace for gem load error is:\n"\
                      "#{orig_exception.backtrace.join("\n")}\n"\
                      "Bundler Error Backtrace:\n"
      super(full_message)
      @orig_exception = orig_exception
    end

    status_code(24)
  end

  class YamlSyntaxError < BundlerError
    attr_reader :orig_exception

    def initialize(orig_exception, msg)
      super(msg)
      @orig_exception = orig_exception
    end

    status_code(25)
  end

  class TemporaryResourceError < PermissionError
    def message
      "There was an error while trying to #{action} `#{@path}`. " \
      "Some resource was temporarily unavailable. It's suggested that you try" \
      "the operation again."
    end

    status_code(26)
  end

  class VirtualProtocolError < BundlerError
    def message
      "There was an error relating to virtualization and file access. " \
      "It is likely that you need to grant access to or mount some file system correctly."
    end

    status_code(27)
  end

  class OperationNotSupportedError < PermissionError
    def message
      "Attempting to #{action} `#{@path}` is unsupported by your OS."
    end

    status_code(28)
  end

  class NoSpaceOnDeviceError < PermissionError
    def message
      "There was an error while trying to #{action} `#{@path}`. " \
      "There was insufficient space remaining on the device."
    end

    status_code(31)
  end

  class GenericSystemCallError < BundlerError
    attr_reader :underlying_error

    def initialize(underlying_error, message)
      @underlying_error = underlying_error
      super("#{message}\nThe underlying system error is #{@underlying_error.class}: #{@underlying_error}")
    end

    status_code(32)
  end
end
# frozen_string_literal: true

module Bundler; end
require_relative "vendor/fileutils/lib/fileutils"
# frozen_string_literal: true

module Bundler
  # This class contains all of the logic for determining the next version of a
  # Gem to update to based on the requested level (patch, minor, major).
  # Primarily designed to work with Resolver which will provide it the list of
  # available dependency versions as found in its index, before returning it to
  # to the resolution engine to select the best version.
  class GemVersionPromoter
    DEBUG = ENV["BUNDLER_DEBUG_RESOLVER"] || ENV["DEBUG_RESOLVER"]

    attr_reader :level, :locked_specs, :unlock_gems

    # By default, strict is false, meaning every available version of a gem
    # is returned from sort_versions. The order gives preference to the
    # requested level (:patch, :minor, :major) but in complicated requirement
    # cases some gems will by necessity by promoted past the requested level,
    # or even reverted to older versions.
    #
    # If strict is set to true, the results from sort_versions will be
    # truncated, eliminating any version outside the current level scope.
    # This can lead to unexpected outcomes or even VersionConflict exceptions
    # that report a version of a gem not existing for versions that indeed do
    # existing in the referenced source.
    attr_accessor :strict

    attr_accessor :prerelease_specified

    # Given a list of locked_specs and a list of gems to unlock creates a
    # GemVersionPromoter instance.
    #
    # @param locked_specs [SpecSet] All current locked specs. Unlike Definition
    #   where this list is empty if all gems are being updated, this should
    #   always be populated for all gems so this class can properly function.
    # @param unlock_gems [String] List of gem names being unlocked. If empty,
    #   all gems will be considered unlocked.
    # @return [GemVersionPromoter]
    def initialize(locked_specs = SpecSet.new([]), unlock_gems = [])
      @level = :major
      @strict = false
      @locked_specs = locked_specs
      @unlock_gems = unlock_gems
      @sort_versions = {}
      @prerelease_specified = {}
    end

    # @param value [Symbol] One of three Symbols: :major, :minor or :patch.
    def level=(value)
      v = case value
          when String, Symbol
            value.to_sym
      end

      raise ArgumentError, "Unexpected level #{v}. Must be :major, :minor or :patch" unless [:major, :minor, :patch].include?(v)
      @level = v
    end

    # Given a Dependency and an Array of SpecGroups of available versions for a
    # gem, this method will return the Array of SpecGroups sorted (and possibly
    # truncated if strict is true) in an order to give preference to the current
    # level (:major, :minor or :patch) when resolution is deciding what versions
    # best resolve all dependencies in the bundle.
    # @param dep [Dependency] The Dependency of the gem.
    # @param spec_groups [SpecGroup] An array of SpecGroups for the same gem
    #    named in the @dep param.
    # @return [SpecGroup] A new instance of the SpecGroup Array sorted and
    #    possibly filtered.
    def sort_versions(dep, spec_groups)
      before_result = "before sort_versions: #{debug_format_result(dep, spec_groups).inspect}" if DEBUG

      @sort_versions[dep] ||= begin
        gem_name = dep.name

        # An Array per version returned, different entries for different platforms.
        # We only need the version here so it's ok to hard code this to the first instance.
        locked_spec = locked_specs[gem_name].first

        if strict
          filter_dep_specs(spec_groups, locked_spec)
        else
          sort_dep_specs(spec_groups, locked_spec)
        end.tap do |specs|
          if DEBUG
            puts before_result
            puts " after sort_versions: #{debug_format_result(dep, specs).inspect}"
          end
        end
      end
    end

    # @return [bool] Convenience method for testing value of level variable.
    def major?
      level == :major
    end

    # @return [bool] Convenience method for testing value of level variable.
    def minor?
      level == :minor
    end

    private

    def filter_dep_specs(spec_groups, locked_spec)
      res = spec_groups.select do |spec_group|
        if locked_spec && !major?
          gsv = spec_group.version
          lsv = locked_spec.version

          must_match = minor? ? [0] : [0, 1]

          matches = must_match.map {|idx| gsv.segments[idx] == lsv.segments[idx] }
          matches.uniq == [true] ? (gsv >= lsv) : false
        else
          true
        end
      end

      sort_dep_specs(res, locked_spec)
    end

    def sort_dep_specs(spec_groups, locked_spec)
      return spec_groups unless locked_spec
      @gem_name = locked_spec.name
      @locked_version = locked_spec.version

      result = spec_groups.sort do |a, b|
        @a_ver = a.version
        @b_ver = b.version

        unless @prerelease_specified[@gem_name]
          a_pre = @a_ver.prerelease?
          b_pre = @b_ver.prerelease?

          next -1 if a_pre && !b_pre
          next  1 if b_pre && !a_pre
        end

        if major?
          @a_ver <=> @b_ver
        elsif either_version_older_than_locked
          @a_ver <=> @b_ver
        elsif segments_do_not_match(:major)
          @b_ver <=> @a_ver
        elsif !minor? && segments_do_not_match(:minor)
          @b_ver <=> @a_ver
        else
          @a_ver <=> @b_ver
        end
      end
      post_sort(result)
    end

    def either_version_older_than_locked
      @a_ver < @locked_version || @b_ver < @locked_version
    end

    def segments_do_not_match(level)
      index = [:major, :minor].index(level)
      @a_ver.segments[index] != @b_ver.segments[index]
    end

    def unlocking_gem?
      unlock_gems.empty? || unlock_gems.include?(@gem_name)
    end

    # Specific version moves can't always reliably be done during sorting
    # as not all elements are compared against each other.
    def post_sort(result)
      # default :major behavior in Bundler does not do this
      return result if major?
      if unlocking_gem?
        result
      else
        move_version_to_end(result, @locked_version)
      end
    end

    def move_version_to_end(result, version)
      move, keep = result.partition {|s| s.version.to_s == version.to_s }
      keep.concat(move)
    end

    def debug_format_result(dep, spec_groups)
      a = [dep.to_s,
           spec_groups.map {|sg| [sg.version, sg.dependencies_for_activated_platforms.map {|dp| [dp.name, dp.requirement.to_s] }] }]
      last_map = a.last.map {|sg_data| [sg_data.first.version, sg_data.last.map {|aa| aa.join(" ") }] }
      [a.first, last_map, level, strict ? :strict : :not_strict]
    end
  end
end
# frozen_string_literal: true

require_relative "../bundler"
require "shellwords"

module Bundler
  class GemHelper
    include Rake::DSL if defined? Rake::DSL

    class << self
      # set when install'd.
      attr_accessor :instance

      def install_tasks(opts = {})
        new(opts[:dir], opts[:name]).install
      end

      def tag_prefix=(prefix)
        instance.tag_prefix = prefix
      end

      def gemspec(&block)
        gemspec = instance.gemspec
        block.call(gemspec) if block
        gemspec
      end
    end

    attr_reader :spec_path, :base, :gemspec

    attr_writer :tag_prefix

    def initialize(base = nil, name = nil)
      @base = File.expand_path(base || SharedHelpers.pwd)
      gemspecs = name ? [File.join(@base, "#{name}.gemspec")] : Gem::Util.glob_files_in_dir("{,*}.gemspec", @base)
      raise "Unable to determine name from existing gemspec. Use :name => 'gemname' in #install_tasks to manually set it." unless gemspecs.size == 1
      @spec_path = gemspecs.first
      @gemspec = Bundler.load_gemspec(@spec_path)
      @tag_prefix = ""
    end

    def install
      built_gem_path = nil

      desc "Build #{name}-#{version}.gem into the pkg directory."
      task "build" do
        built_gem_path = build_gem
      end

      desc "Generate SHA512 checksum if #{name}-#{version}.gem into the checksums directory."
      task "build:checksum" => "build" do
        build_checksum(built_gem_path)
      end

      desc "Build and install #{name}-#{version}.gem into system gems."
      task "install" => "build" do
        install_gem(built_gem_path)
      end

      desc "Build and install #{name}-#{version}.gem into system gems without network access."
      task "install:local" => "build" do
        install_gem(built_gem_path, :local)
      end

      desc "Create tag #{version_tag} and build and push #{name}-#{version}.gem to #{gem_push_host}\n" \
           "To prevent publishing in RubyGems use `gem_push=no rake release`"
      task "release", [:remote] => ["build", "release:guard_clean",
                                    "release:source_control_push", "release:rubygem_push"] do
      end

      task "release:guard_clean" do
        guard_clean
      end

      task "release:source_control_push", [:remote] do |_, args|
        tag_version { git_push(args[:remote]) } unless already_tagged?
      end

      task "release:rubygem_push" => "build" do
        rubygem_push(built_gem_path) if gem_push?
      end

      GemHelper.instance = self
    end

    def build_gem
      file_name = nil
      sh([*gem_command, "build", "-V", spec_path]) do
        file_name = File.basename(built_gem_path)
        SharedHelpers.filesystem_access(File.join(base, "pkg")) {|p| FileUtils.mkdir_p(p) }
        FileUtils.mv(built_gem_path, "pkg")
        Bundler.ui.confirm "#{name} #{version} built to pkg/#{file_name}."
      end
      File.join(base, "pkg", file_name)
    end

    def install_gem(built_gem_path = nil, local = false)
      built_gem_path ||= build_gem
      cmd = [*gem_command, "install", built_gem_path.to_s]
      cmd << "--local" if local
      sh(cmd)
      Bundler.ui.confirm "#{name} (#{version}) installed."
    end

    def build_checksum(built_gem_path = nil)
      built_gem_path ||= build_gem
      SharedHelpers.filesystem_access(File.join(base, "checksums")) {|p| FileUtils.mkdir_p(p) }
      file_name = "#{File.basename(built_gem_path)}.sha512"
      require "digest/sha2"
      checksum = ::Digest::SHA512.new.hexdigest(built_gem_path.to_s)
      target = File.join(base, "checksums", file_name)
      File.write(target, checksum)
      Bundler.ui.confirm "#{name} #{version} checksum written to checksums/#{file_name}."
    end

    protected

    def rubygem_push(path)
      cmd = [*gem_command, "push", path]
      cmd << "--key" << gem_key if gem_key
      cmd << "--host" << allowed_push_host if allowed_push_host
      sh_with_input(cmd)
      Bundler.ui.confirm "Pushed #{name} #{version} to #{gem_push_host}"
    end

    def built_gem_path
      Gem::Util.glob_files_in_dir("#{name}-*.gem", base).sort_by {|f| File.mtime(f) }.last
    end

    def git_push(remote = nil)
      remote ||= default_remote
      sh("git push #{remote} refs/heads/#{current_branch}".shellsplit)
      sh("git push #{remote} refs/tags/#{version_tag}".shellsplit)
      Bundler.ui.confirm "Pushed git commits and release tag."
    end

    def default_remote
      remote_for_branch, status = sh_with_status(%W[git config --get branch.#{current_branch}.remote])
      return "origin" unless status.success?

      remote_for_branch.strip
    end

    def current_branch
      # We can replace this with `git branch --show-current` once we drop support for git < 2.22.0
      sh(%w[git rev-parse --abbrev-ref HEAD]).gsub(%r{\Aheads/}, "").strip
    end

    def allowed_push_host
      @gemspec.metadata["allowed_push_host"] if @gemspec.respond_to?(:metadata)
    end

    def gem_push_host
      env_rubygems_host = ENV["RUBYGEMS_HOST"]
      env_rubygems_host = nil if
        env_rubygems_host && env_rubygems_host.empty?

      allowed_push_host || env_rubygems_host || "rubygems.org"
    end

    def already_tagged?
      return false unless sh(%w[git tag]).split(/\n/).include?(version_tag)
      Bundler.ui.confirm "Tag #{version_tag} has already been created."
      true
    end

    def guard_clean
      clean? && committed? || raise("There are files that need to be committed first.")
    end

    def clean?
      sh_with_status(%w[git diff --exit-code])[1].success?
    end

    def committed?
      sh_with_status(%w[git diff-index --quiet --cached HEAD])[1].success?
    end

    def tag_version
      sh %W[git tag -m Version\ #{version} #{version_tag}]
      Bundler.ui.confirm "Tagged #{version_tag}."
      yield if block_given?
    rescue RuntimeError
      Bundler.ui.error "Untagging #{version_tag} due to error."
      sh_with_status %W[git tag -d #{version_tag}]
      raise
    end

    def version
      gemspec.version
    end

    def version_tag
      "#{@tag_prefix}v#{version}"
    end

    def name
      gemspec.name
    end

    def sh_with_input(cmd)
      Bundler.ui.debug(cmd)
      SharedHelpers.chdir(base) do
        abort unless Kernel.system(*cmd)
      end
    end

    def sh(cmd, &block)
      out, status = sh_with_status(cmd, &block)
      unless status.success?
        raise("Running `#{cmd.shelljoin}` failed with the following output:\n\n#{out}\n")
      end
      out
    end

    def sh_with_status(cmd, &block)
      Bundler.ui.debug(cmd)
      SharedHelpers.chdir(base) do
        outbuf = IO.popen(cmd, :err => [:child, :out], &:read)
        status = $?
        block.call(outbuf) if status.success? && block
        [outbuf, status]
      end
    end

    def gem_key
      Bundler.settings["gem.push_key"].to_s.downcase if Bundler.settings["gem.push_key"]
    end

    def gem_push?
      !%w[n no nil false off 0].include?(ENV["gem_push"].to_s.downcase)
    end

    def gem_command
      ENV["GEM_COMMAND"]&.shellsplit || ["gem"]
    end
  end
end
# frozen_string_literal: true

module Bundler
  class ProcessLock
    def self.lock(bundle_path = Bundler.bundle_path)
      lock_file_path = File.join(bundle_path, "bundler.lock")
      has_lock = false

      File.open(lock_file_path, "w") do |f|
        f.flock(File::LOCK_EX)
        has_lock = true
        yield
        f.flock(File::LOCK_UN)
      end
    rescue Errno::EACCES, Errno::ENOLCK, *[SharedHelpers.const_get_safely(:ENOTSUP, Errno)].compact
      # In the case the user does not have access to
      # create the lock file or is using NFS where
      # locks are not available we skip locking.
      yield
    ensure
      FileUtils.rm_f(lock_file_path) if has_lock
    end
  end
end
# frozen_string_literal: true

require_relative "vendored_thor"

module Bundler
  module FriendlyErrors
    module_function

    def enable!
      @disabled = false
    end

    def disabled?
      @disabled
    end

    def disable!
      @disabled = true
    end

    def log_error(error)
      case error
      when YamlSyntaxError
        Bundler.ui.error error.message
        Bundler.ui.trace error.orig_exception
      when Dsl::DSLError, GemspecError
        Bundler.ui.error error.message
      when GemRequireError
        Bundler.ui.error error.message
        Bundler.ui.trace error.orig_exception
      when BundlerError
        Bundler.ui.error error.message, :wrap => true
        Bundler.ui.trace error
      when Thor::Error
        Bundler.ui.error error.message
      when LoadError
        raise error unless error.message =~ /cannot load such file -- openssl|openssl.so|libcrypto.so/
        Bundler.ui.error "\nCould not load OpenSSL. #{error.class}: #{error}\n#{error.backtrace.join("\n  ")}"
      when Interrupt
        Bundler.ui.error "\nQuitting..."
        Bundler.ui.trace error
      when Gem::InvalidSpecificationException
        Bundler.ui.error error.message, :wrap => true
      when SystemExit
      when *[defined?(Java::JavaLang::OutOfMemoryError) && Java::JavaLang::OutOfMemoryError].compact
        Bundler.ui.error "\nYour JVM has run out of memory, and Bundler cannot continue. " \
          "You can decrease the amount of memory Bundler needs by removing gems from your Gemfile, " \
          "especially large gems. (Gems can be as large as hundreds of megabytes, and Bundler has to read those files!). " \
          "Alternatively, you can increase the amount of memory the JVM is able to use by running Bundler with jruby -J-Xmx1024m -S bundle (JRuby defaults to 500MB)."
      else request_issue_report_for(error)
      end
    end

    def exit_status(error)
      case error
      when BundlerError then error.status_code
      when Thor::Error then 15
      when SystemExit then error.status
      else 1
      end
    end

    def request_issue_report_for(e)
      Bundler.ui.error <<-EOS.gsub(/^ {8}/, ""), nil, nil
        --- ERROR REPORT TEMPLATE -------------------------------------------------------

        ```
        #{e.class}: #{e.message}
          #{e.backtrace && e.backtrace.join("\n          ").chomp}
        ```

        #{Bundler::Env.report}
        --- TEMPLATE END ----------------------------------------------------------------

      EOS

      Bundler.ui.error "Unfortunately, an unexpected error occurred, and Bundler cannot continue."

      Bundler.ui.error <<-EOS.gsub(/^ {8}/, ""), nil, :yellow

        First, try this link to see if there are any existing issue reports for this error:
        #{issues_url(e)}

        If there aren't any reports for this error yet, please fill in the new issue form located at #{new_issue_url}, and copy and paste the report template above in there.
      EOS
    end

    def issues_url(exception)
      message = exception.message.lines.first.tr(":", " ").chomp
      message = message.split("-").first if exception.is_a?(Errno)
      require "cgi"
      "https://github.com/rubygems/rubygems/search?q=" \
        "#{CGI.escape(message)}&type=Issues"
    end

    def new_issue_url
      "https://github.com/rubygems/rubygems/issues/new?labels=Bundler&template=bundler-related-issue.md"
    end
  end

  def self.with_friendly_errors
    FriendlyErrors.enable!
    yield
  rescue SignalException
    raise
  rescue Exception => e # rubocop:disable Lint/RescueException
    raise if FriendlyErrors.disabled?

    FriendlyErrors.log_error(e)
    exit FriendlyErrors.exit_status(e)
  end
end
# frozen_string_literal: true

# This code was extracted from https://github.com/Solistra/ruby-digest which is under public domain
module Bundler
  module Digest
    # The initial constant values for the 32-bit constant words A, B, C, D, and
    # E, respectively.
    SHA1_WORDS = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0].freeze

    # The 8-bit field used for bitwise `AND` masking. Defaults to `0xFFFFFFFF`.
    SHA1_MASK = 0xFFFFFFFF

    class << self
      def sha1(string)
        unless string.is_a?(String)
          raise TypeError, "can't convert #{string.class.inspect} into String"
        end

        buffer = string.b

        words = SHA1_WORDS.dup
        generate_split_buffer(buffer) do |chunk|
          w = []
          chunk.each_slice(4) do |a, b, c, d|
            w << (((a << 8 | b) << 8 | c) << 8 | d)
          end
          a, b, c, d, e = *words
          (16..79).each do |i|
            w[i] = SHA1_MASK & rotate((w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16]), 1)
          end
          0.upto(79) do |i|
            case i
            when  0..19
              f = ((b & c) | (~b & d))
              k = 0x5A827999
            when 20..39
              f = (b ^ c ^ d)
              k = 0x6ED9EBA1
            when 40..59
              f = ((b & c) | (b & d) | (c & d))
              k = 0x8F1BBCDC
            when 60..79
              f = (b ^ c ^ d)
              k = 0xCA62C1D6
            end
            t = SHA1_MASK & (SHA1_MASK & rotate(a, 5) + f + e + k + w[i])
            a, b, c, d, e = t, a, SHA1_MASK & rotate(b, 30), c, d # rubocop:disable Style/ParallelAssignment
          end
          mutated = [a, b, c, d, e]
          words.map!.with_index {|word, index| SHA1_MASK & (word + mutated[index]) }
        end

        words.pack("N*").unpack("H*").first
      end

      private

      def generate_split_buffer(string, &block)
        size   = string.bytesize * 8
        buffer = string.bytes << 128
        buffer << 0 while buffer.size % 64 != 56
        buffer.concat([size].pack("Q>").bytes)
        buffer.each_slice(64, &block)
      end

      def rotate(value, spaces)
        value << spaces | value >> (32 - spaces)
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class StubSpecification < RemoteSpecification
    def self.from_stub(stub)
      return stub if stub.is_a?(Bundler::StubSpecification)
      spec = new(stub.name, stub.version, stub.platform, nil)
      spec.stub = stub
      spec
    end

    attr_accessor :stub, :ignored

    def source=(source)
      super
      # Stub has no concept of source, which means that extension_dir may be wrong
      # This is the case for git-based gems. So, instead manually assign the extension dir
      return unless source.respond_to?(:extension_dir_name)
      path = File.join(stub.extensions_dir, source.extension_dir_name)
      stub.extension_dir = File.expand_path(path)
    end

    def to_yaml
      _remote_specification.to_yaml
    end

    # @!group Stub Delegates

    def manually_installed?
      # This is for manually installed gems which are gems that were fixed in place after a
      # failed installation. Once the issue was resolved, the user then manually created
      # the gem specification using the instructions provided by `gem help install`
      installed_by_version == Gem::Version.new(0)
    end

    # This is defined directly to avoid having to loading the full spec
    def missing_extensions?
      return false if default_gem?
      return false if extensions.empty?
      return false if File.exist? gem_build_complete_path
      return false if manually_installed?

      true
    end

    def activated
      stub.activated
    end

    def activated=(activated)
      stub.instance_variable_set(:@activated, activated)
    end

    def extensions
      stub.extensions
    end

    def gem_build_complete_path
      File.join(extension_dir, "gem.build_complete")
    end

    def default_gem?
      stub.default_gem?
    end

    def full_gem_path
      # deleted gems can have their stubs return nil, so in that case grab the
      # expired path from the full spec
      stub.full_gem_path || method_missing(:full_gem_path)
    end

    def full_require_paths
      stub.full_require_paths
    end

    def load_paths
      full_require_paths
    end

    def loaded_from
      stub.loaded_from
    end

    def matches_for_glob(glob)
      stub.matches_for_glob(glob)
    end

    def raw_require_paths
      stub.raw_require_paths
    end

    private

    def _remote_specification
      @_remote_specification ||= begin
        rs = stub.to_spec
        if rs.equal?(self) # happens when to_spec gets the spec from Gem.loaded_specs
          rs = Gem::Specification.load(loaded_from)
          Bundler.rubygems.stub_set_spec(stub, rs)
        end

        unless rs
          raise GemspecError, "The gemspec for #{full_name} at #{loaded_from}" \
            " was missing or broken. Try running `gem pristine #{name} -v #{version}`" \
            " to fix the cached spec."
        end

        rs.source = source

        rs
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class GemInstaller
    attr_reader :spec, :standalone, :worker, :force, :installer

    def initialize(spec, installer, standalone = false, worker = 0, force = false)
      @spec = spec
      @installer = installer
      @standalone = standalone
      @worker = worker
      @force = force
    end

    def install_from_spec
      post_install_message = spec_settings ? install_with_settings : install
      Bundler.ui.debug "#{worker}:  #{spec.name} (#{spec.version}) from #{spec.loaded_from}"
      generate_executable_stubs
      return true, post_install_message
    rescue Bundler::InstallHookError, Bundler::SecurityError, Bundler::APIResponseMismatchError
      raise
    rescue Errno::ENOSPC
      return false, out_of_space_message
    rescue Bundler::BundlerError, Gem::InstallError, Bundler::APIResponseInvalidDependenciesError => e
      return false, specific_failure_message(e)
    end

    private

    def specific_failure_message(e)
      message = "#{e.class}: #{e.message}\n"
      message += "  " + e.backtrace.join("\n  ") + "\n\n"
      message = message.lines.first + Bundler.ui.add_color(message.lines.drop(1).join, :clear)
      message + Bundler.ui.add_color(failure_message, :red)
    end

    def failure_message
      install_error_message
    end

    def install_error_message
      "An error occurred while installing #{spec.name} (#{spec.version}), and Bundler cannot continue."
    end

    def spec_settings
      # Fetch the build settings, if there are any
      if settings = Bundler.settings["build.#{spec.name}"]
        require "shellwords"
        Shellwords.shellsplit(settings)
      end
    end

    def install
      spec.source.install(spec, :force => force, :ensure_builtin_gems_cached => standalone, :build_args => Array(spec_settings))
    end

    def install_with_settings
      # Build arguments are global, so this is mutexed
      Bundler.rubygems.install_with_build_args([spec_settings]) { install }
    end

    def out_of_space_message
      "#{install_error_message}\nYour disk is out of space. Free some space to be able to install your bundle."
    end

    def generate_executable_stubs
      return if Bundler.feature_flag.forget_cli_options?
      return if Bundler.settings[:inline]
      if Bundler.settings[:bin] && standalone
        installer.generate_standalone_bundler_executable_stubs(spec)
      elsif Bundler.settings[:bin]
        installer.generate_bundler_executable_stubs(spec, :force => true)
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class Standalone
    def initialize(groups, definition)
      @specs = definition.specs_for(groups)
    end

    def generate
      SharedHelpers.filesystem_access(bundler_path) do |p|
        FileUtils.mkdir_p(p)
      end
      File.open File.join(bundler_path, "setup.rb"), "w" do |file|
        file.puts "require 'rbconfig'"
        file.puts reverse_rubygems_kernel_mixin
        paths.each do |path|
          if Pathname.new(path).absolute?
            file.puts %($:.unshift "#{path}")
          else
            file.puts %($:.unshift File.expand_path("\#{__dir__}/#{path}"))
          end
        end
      end
    end

    private

    def paths
      @specs.map do |spec|
        next if spec.name == "bundler"
        Array(spec.require_paths).map do |path|
          gem_path(path, spec).sub(version_dir, '#{RUBY_ENGINE}/#{RbConfig::CONFIG["ruby_version"]}')
          # This is a static string intentionally. It's interpolated at a later time.
        end
      end.flatten.compact
    end

    def version_dir
      "#{RUBY_ENGINE}/#{RbConfig::CONFIG["ruby_version"]}"
    end

    def bundler_path
      Bundler.root.join(Bundler.settings[:path], "bundler")
    end

    def gem_path(path, spec)
      full_path = Pathname.new(path).absolute? ? path : File.join(spec.full_gem_path, path)
      if spec.source.instance_of?(Source::Path)
        full_path
      else
        Pathname.new(full_path).relative_path_from(Bundler.root.join(bundler_path)).to_s
      end
    rescue TypeError
      error_message = "#{spec.name} #{spec.version} has an invalid gemspec"
      raise Gem::InvalidSpecificationException.new(error_message)
    end

    def reverse_rubygems_kernel_mixin
      <<~END
      kernel = (class << ::Kernel; self; end)
      [kernel, ::Kernel].each do |k|
        if k.private_method_defined?(:gem_original_require)
          private_require = k.private_method_defined?(:require)
          k.send(:remove_method, :require)
          k.send(:define_method, :require, k.instance_method(:gem_original_require))
          k.send(:private, :require) if private_require
        end
      end
      END
    end
  end
end
# frozen_string_literal: true

require_relative "../worker"
require_relative "gem_installer"

module Bundler
  class ParallelInstaller
    class SpecInstallation
      attr_accessor :spec, :name, :full_name, :post_install_message, :state, :error
      def initialize(spec)
        @spec = spec
        @name = spec.name
        @full_name = spec.full_name
        @state = :none
        @post_install_message = ""
        @error = nil
      end

      def installed?
        state == :installed
      end

      def enqueued?
        state == :enqueued
      end

      def failed?
        state == :failed
      end

      def ready_to_enqueue?
        state == :none
      end

      def has_post_install_message?
        !post_install_message.empty?
      end

      def ignorable_dependency?(dep)
        dep.type == :development || dep.name == @name
      end

      # Checks installed dependencies against spec's dependencies to make
      # sure needed dependencies have been installed.
      def dependencies_installed?(all_specs)
        installed_specs = all_specs.select(&:installed?).map(&:name)
        dependencies.all? {|d| installed_specs.include? d.name }
      end

      # Represents only the non-development dependencies, the ones that are
      # itself and are in the total list.
      def dependencies
        @dependencies ||= all_dependencies.reject {|dep| ignorable_dependency? dep }
      end

      def missing_lockfile_dependencies(all_spec_names)
        dependencies.reject {|dep| all_spec_names.include? dep.name }
      end

      # Represents all dependencies
      def all_dependencies
        @spec.dependencies
      end

      def to_s
        "#<#{self.class} #{full_name} (#{state})>"
      end
    end

    def self.call(*args)
      new(*args).call
    end

    attr_reader :size

    def initialize(installer, all_specs, size, standalone, force)
      @installer = installer
      @size = size
      @standalone = standalone
      @force = force
      @specs = all_specs.map {|s| SpecInstallation.new(s) }
      @spec_set = all_specs
      @rake = @specs.find {|s| s.name == "rake" }
    end

    def call
      check_for_corrupt_lockfile

      if @rake
        do_install(@rake, 0)
        Gem::Specification.reset
      end

      if @size > 1
        install_with_worker
      else
        install_serially
      end

      check_for_unmet_dependencies

      handle_error if failed_specs.any?
      @specs
    ensure
      worker_pool && worker_pool.stop
    end

    def check_for_unmet_dependencies
      unmet_dependencies = @specs.map do |s|
        [
          s,
          s.dependencies.reject {|dep| @specs.any? {|spec| dep.matches_spec?(spec.spec) } },
        ]
      end.reject {|a| a.last.empty? }
      return if unmet_dependencies.empty?

      warning = []
      warning << "Your lockfile doesn't include a valid resolution."
      warning << "You can fix this by regenerating your lockfile or trying to manually editing the bad locked gems to a version that satisfies all dependencies."
      warning << "The unmet dependencies are:"

      unmet_dependencies.each do |spec, unmet_spec_dependencies|
        unmet_spec_dependencies.each do |unmet_spec_dependency|
          warning << "* #{unmet_spec_dependency}, depended upon #{spec.full_name}, unsatisfied by #{@specs.find {|s| s.name == unmet_spec_dependency.name && !unmet_spec_dependency.matches_spec?(s.spec) }.full_name}"
        end
      end

      Bundler.ui.warn(warning.join("\n"))
    end

    def check_for_corrupt_lockfile
      missing_dependencies = @specs.map do |s|
        [
          s,
          s.missing_lockfile_dependencies(@specs.map(&:name)),
        ]
      end.reject {|a| a.last.empty? }
      return if missing_dependencies.empty?

      warning = []
      warning << "Your lockfile was created by an old Bundler that left some things out."
      if @size != 1
        warning << "Because of the missing DEPENDENCIES, we can only install gems one at a time, instead of installing #{@size} at a time."
        @size = 1
      end
      warning << "You can fix this by adding the missing gems to your Gemfile, running bundle install, and then removing the gems from your Gemfile."
      warning << "The missing gems are:"

      missing_dependencies.each do |spec, missing|
        warning << "* #{missing.map(&:name).join(", ")} depended upon by #{spec.name}"
      end

      Bundler.ui.warn(warning.join("\n"))
    end

    private

    def failed_specs
      @specs.select(&:failed?)
    end

    def install_with_worker
      enqueue_specs
      process_specs until finished_installing?
    end

    def install_serially
      until finished_installing?
        raise "failed to find a spec to enqueue while installing serially" unless spec_install = @specs.find(&:ready_to_enqueue?)
        spec_install.state = :enqueued
        do_install(spec_install, 0)
      end
    end

    def worker_pool
      @worker_pool ||= Bundler::Worker.new @size, "Parallel Installer", lambda {|spec_install, worker_num|
        do_install(spec_install, worker_num)
      }
    end

    def do_install(spec_install, worker_num)
      Plugin.hook(Plugin::Events::GEM_BEFORE_INSTALL, spec_install)
      gem_installer = Bundler::GemInstaller.new(
        spec_install.spec, @installer, @standalone, worker_num, @force
      )
      success, message = gem_installer.install_from_spec
      if success
        spec_install.state = :installed
        spec_install.post_install_message = message unless message.nil?
      else
        spec_install.error = "#{message}\n\n#{require_tree_for_spec(spec_install.spec)}"
        spec_install.state = :failed
      end
      Plugin.hook(Plugin::Events::GEM_AFTER_INSTALL, spec_install)
      spec_install
    end

    # Dequeue a spec and save its post-install message and then enqueue the
    # remaining specs.
    # Some specs might've had to wait til this spec was installed to be
    # processed so the call to `enqueue_specs` is important after every
    # dequeue.
    def process_specs
      worker_pool.deq
      enqueue_specs
    end

    def finished_installing?
      @specs.all? do |spec|
        return true if spec.failed?
        spec.installed?
      end
    end

    def handle_error
      errors = failed_specs.map(&:error)
      if exception = errors.find {|e| e.is_a?(Bundler::BundlerError) }
        raise exception
      end
      raise Bundler::InstallError, errors.join("\n\n")
    end

    def require_tree_for_spec(spec)
      tree = @spec_set.what_required(spec)
      t = String.new("In #{File.basename(SharedHelpers.default_gemfile)}:\n")
      tree.each_with_index do |s, depth|
        t << "  " * depth.succ << s.name
        unless tree.last == s
          t << %( was resolved to #{s.version}, which depends on)
        end
        t << %(\n)
      end
      t
    end

    # Keys in the remains hash represent uninstalled gems specs.
    # We enqueue all gem specs that do not have any dependencies.
    # Later we call this lambda again to install specs that depended on
    # previously installed specifications. We continue until all specs
    # are installed.
    def enqueue_specs
      @specs.select(&:ready_to_enqueue?).each do |spec|
        if spec.dependencies_installed? @specs
          spec.state = :enqueued
          worker_pool.enq spec
        end
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  # General purpose class for retrying code that may fail
  class Retry
    attr_accessor :name, :total_runs, :current_run

    class << self
      def default_attempts
        default_retries + 1
      end
      alias_method :attempts, :default_attempts

      def default_retries
        Bundler.settings[:retry]
      end
    end

    def initialize(name, exceptions = nil, retries = self.class.default_retries)
      @name = name
      @retries = retries
      @exceptions = Array(exceptions) || []
      @total_runs = @retries + 1 # will run once, then upto attempts.times
    end

    def attempt(&block)
      @current_run = 0
      @failed      = false
      @error       = nil
      run(&block) while keep_trying?
      @result
    end
    alias_method :attempts, :attempt

    private

    def run(&block)
      @failed = false
      @current_run += 1
      @result = block.call
    rescue StandardError => e
      fail_attempt(e)
    end

    def fail_attempt(e)
      @failed = true
      if last_attempt? || @exceptions.any? {|k| e.is_a?(k) }
        Bundler.ui.info "" unless Bundler.ui.debug?
        raise e
      end
      return true unless name
      Bundler.ui.info "" unless Bundler.ui.debug? # Add new line in case dots preceded this
      Bundler.ui.warn "Retrying #{name} due to error (#{current_run.next}/#{total_runs}): #{e.class} #{e.message}", Bundler.ui.debug?
    end

    def keep_trying?
      return true  if current_run.zero?
      return false if last_attempt?
      return true  if @failed
    end

    def last_attempt?
      current_run >= total_runs
    end
  end
end
# frozen_string_literal: true

module Bundler; end
require_relative "vendor/uri/lib/uri"
# frozen_string_literal: true

source "https://rubygems.org"

git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }

# gem "rails"
# frozen_string_literal: true

# A sample gems.rb
source "https://rubygems.org"

git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }

# gem "rails"
#!/usr/bin/env <%= Bundler.settings[:shebang] || RbConfig::CONFIG["ruby_install_name"] %>
# frozen_string_literal: true

#
# This file was generated by Bundler.
#
# The application '<%= executable %>' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require "rubygems"

m = Module.new do
  module_function

  def invoked_as_script?
    File.expand_path($0) == File.expand_path(__FILE__)
  end

  def env_var_version
    ENV["BUNDLER_VERSION"]
  end

  def cli_arg_version
    return unless invoked_as_script? # don't want to hijack other binstubs
    return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update`
    bundler_version = nil
    update_index = nil
    ARGV.each_with_index do |a, i|
      if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN
        bundler_version = a
      end
      next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/
      bundler_version = $1
      update_index = i
    end
    bundler_version
  end

  def gemfile
    gemfile = ENV["BUNDLE_GEMFILE"]
    return gemfile if gemfile && !gemfile.empty?

    File.expand_path("../<%= relative_gemfile_path %>", __FILE__)
  end

  def lockfile
    lockfile =
      case File.basename(gemfile)
      when "gems.rb" then gemfile.sub(/\.rb$/, gemfile)
      else "#{gemfile}.lock"
      end
    File.expand_path(lockfile)
  end

  def lockfile_version
    return unless File.file?(lockfile)
    lockfile_contents = File.read(lockfile)
    return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/
    Regexp.last_match(1)
  end

  def bundler_requirement
    @bundler_requirement ||=
      env_var_version || cli_arg_version ||
        bundler_requirement_for(lockfile_version)
  end

  def bundler_requirement_for(version)
    return "#{Gem::Requirement.default}.a" unless version

    bundler_gem_version = Gem::Version.new(version)

    requirement = bundler_gem_version.approximate_recommendation

    return requirement unless Gem::Version.new(Gem::VERSION) < Gem::Version.new("2.7.0")

    requirement += ".a" if bundler_gem_version.prerelease?

    requirement
  end

  def load_bundler!
    ENV["BUNDLE_GEMFILE"] ||= gemfile

    activate_bundler
  end

  def activate_bundler
    gem_error = activation_error_handling do
      gem "bundler", bundler_requirement
    end
    return if gem_error.nil?
    require_error = activation_error_handling do
      require "bundler/version"
    end
    return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION))
    warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`"
    exit 42
  end

  def activation_error_handling
    yield
    nil
  rescue StandardError, LoadError => e
    e
  end
end

m.load_bundler!

if m.invoked_as_script?
  load Gem.bin_path("<%= spec.name %>", "<%= executable %>")
end
#!/usr/bin/env <%= Bundler.settings[:shebang] || RbConfig::CONFIG["ruby_install_name"] %>
# frozen_string_literal: true

#
# This file was generated by Bundler.
#
# The application '<%= executable %>' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../<%= relative_gemfile_path %>",
  Pathname.new(__FILE__).realpath)

bundle_binstub = File.expand_path("../bundle", __FILE__)

if File.file?(bundle_binstub)
  if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
    load(bundle_binstub)
  else
    abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
  end
end

require "rubygems"
require "bundler/setup"

load Gem.bin_path("<%= spec.name %>", "<%= executable %>")
# <%= config[:constant_name] %>

Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/<%= config[:namespaced_path] %>`. To experiment with that code, run `bin/console` for an interactive prompt.

TODO: Delete this and the text above, and describe your gem

## Installation

Add this line to your application's Gemfile:

```ruby
gem '<%= config[:name] %>'
```

And then execute:

    $ bundle install

Or install it yourself as:

    $ gem install <%= config[:name] %>

## Usage

TODO: Write usage instructions here

## Development

After checking out the repo, run `bin/setup` to install dependencies.<% if config[:test] %> Then, run `rake <%= config[:test].sub('mini', '').sub('rspec', 'spec') %>` to run the tests.<% end %> You can also run `bin/console` for an interactive prompt that will allow you to experiment.<% if config[:bin] %> Run `bundle exec <%= config[:name] %>` to use the gem in this directory, ignoring other installed copies of this gem.<% end %>

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
<% if config[:git] -%>

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/<%= config[:github_username] %>/<%= config[:name] %>.<% if config[:coc] %> This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/<%= config[:github_username] %>/<%= config[:name] %>/blob/<%= config[:git_default_branch] %>/CODE_OF_CONDUCT.md).<% end %>
<% end -%>
<% if config[:mit] -%>

## License

The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
<% end -%>
<% if config[:git] && config[:coc] -%>

## Code of Conduct

Everyone interacting in the <%= config[:constant_name] %> project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/<%= config[:github_username] %>/<%= config[:name] %>/blob/<%= config[:git_default_branch] %>/CODE_OF_CONDUCT.md).
<% end -%>
# frozen_string_literal: true

require "test_helper"

class <%= config[:constant_name] %>Test < Minitest::Test
  def test_that_it_has_a_version_number
    refute_nil ::<%= config[:constant_name] %>::VERSION
  end

  def test_it_does_something_useful
    assert false
  end
end
# frozen_string_literal: true

$LOAD_PATH.unshift File.expand_path("../lib", __dir__)
require "<%= config[:namespaced_path] %>"

require "minitest/autorun"
# frozen_string_literal: true

require "test_helper"

class <%= config[:constant_name] %>Test < Test::Unit::TestCase
  test "VERSION" do
    assert do
      ::<%= config[:constant_name] %>.const_defined?(:VERSION)
    end
  end

  test "something useful" do
    assert_equal("expected", "actual")
  end
end
# frozen_string_literal: true

$LOAD_PATH.unshift File.expand_path("../lib", __dir__)
require "<%= config[:namespaced_path] %>"

require "test-unit"
AllCops:
  TargetRubyVersion: <%= ::Gem::Version.new(config[:required_ruby_version]).segments[0..1].join(".") %>

Style/StringLiterals:
  Enabled: true
  EnforcedStyle: double_quotes

Style/StringLiteralsInInterpolation:
  Enabled: true
  EnforcedStyle: double_quotes

Layout/LineLength:
  Max: 120
# frozen_string_literal: true

source "https://rubygems.org"

# Specify your gem's dependencies in <%= config[:name] %>.gemspec
gemspec

gem "rake", "~> 13.0"
<%- if config[:ext] -%>

gem "rake-compiler"
<%- end -%>
<%- if config[:test] -%>

gem "<%= config[:test] %>", "~> <%= config[:test_framework_version] %>"
<%- end -%>
<%- if config[:linter] == "rubocop" -%>

gem "rubocop", "~> <%= config[:linter_version] %>"
<%- elsif config[:linter] == "standard" -%>

gem "standard", "~> <%= config[:linter_version] %>"
<%- end -%>
name: Ruby

on:
  push:
    branches:
      - <%= config[:git_default_branch] %>

  pull_request:

jobs:
  build:
    runs-on: ubuntu-latest
    name: Ruby ${{ matrix.ruby }}
    strategy:
      matrix:
        ruby:
          - '<%= RUBY_VERSION %>'

    steps:
    - uses: actions/checkout@v2
    - name: Set up Ruby
      uses: ruby/setup-ruby@v1
      with:
        ruby-version: ${{ matrix.ruby }}
        bundler-cache: true
    - name: Run the default task
      run: bundle exec rake
The MIT License (MIT)

Copyright (c) <%= Time.now.year %> <%= config[:author] %>

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.
/.bundle/
/.yardoc
/_yardoc/
/coverage/
/doc/
/pkg/
/spec/reports/
/tmp/
<%- if config[:ext] -%>
*.bundle
*.so
*.o
*.a
mkmf.log
<%- end -%>
<%- if config[:test] == "rspec" -%>

# rspec failure tracking
.rspec_status
<%- end -%>
# frozen_string_literal: true

RSpec.describe <%= config[:constant_name] %> do
  it "has a version number" do
    expect(<%= config[:constant_name] %>::VERSION).not_to be nil
  end

  it "does something useful" do
    expect(false).to eq(true)
  end
end
# frozen_string_literal: true

require "<%= config[:namespaced_path] %>"

RSpec.configure do |config|
  # Enable flags like --only-failures and --next-failure
  config.example_status_persistence_file_path = ".rspec_status"

  # Disable RSpec exposing methods globally on `Module` and `main`
  config.disable_monkey_patching!

  config.expect_with :rspec do |c|
    c.syntax = :expect
  end
end
image: ruby:<%= RUBY_VERSION %>

before_script:
  - gem install bundler -v <%= Bundler::VERSION %>
  - bundle install

example_job:
  script:
    - bundle exec rake
#!/opt/alt/ruby30/bin/ruby
# frozen_string_literal: true

require "bundler/setup"
require "<%= config[:namespaced_path] %>"

# You can add fixtures and/or initialization code here to make experimenting
# with your gem easier. You can also use a different console, if you like.

# (If you use this, don't forget to add pry to your Gemfile!)
# require "pry"
# Pry.start

require "irb"
IRB.start(__FILE__)
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
set -vx

bundle install

# Do any other automated setup that you need to do here
#include "<%= config[:underscored_name] %>.h"

VALUE rb_m<%= config[:constant_array].join %>;

void
Init_<%= config[:underscored_name] %>(void)
{
  rb_m<%= config[:constant_array].join %> = rb_define_module(<%= config[:constant_name].inspect %>);
}
# frozen_string_literal: true

require "mkmf"

create_makefile(<%= config[:makefile_path].inspect %>)
#ifndef <%= config[:underscored_name].upcase %>_H
#define <%= config[:underscored_name].upcase %>_H 1

#include "ruby.h"

#endif /* <%= config[:underscored_name].upcase %>_H */
--format documentation
--color
--require spec_helper
# For available configuration options, see:
#   https://github.com/testdouble/standard
version: 2.1
jobs:
  build:
    docker:
      - image: ruby:<%= RUBY_VERSION %>
    steps:
      - checkout
      - run:
          name: Run the default task
          command: |
            gem install bundler -v <%= Bundler::VERSION %>
            bundle install
            bundle exec rake
#!/opt/alt/ruby30/bin/ruby

require "<%= config[:namespaced_path] %>"
# frozen_string_literal: true

require_relative "<%= File.basename(config[:namespaced_path]) %>/version"
<%- if config[:ext] -%>
require_relative "<%= File.basename(config[:namespaced_path]) %>/<%= config[:underscored_name] %>"
<%- end -%>

<%- config[:constant_array].each_with_index do |c, i| -%>
<%= "  " * i %>module <%= c %>
<%- end -%>
<%= "  " * config[:constant_array].size %>class Error < StandardError; end
<%= "  " * config[:constant_array].size %># Your code goes here...
<%- (config[:constant_array].size-1).downto(0) do |i| -%>
<%= "  " * i %>end
<%- end -%>
# frozen_string_literal: true

<%- config[:constant_array].each_with_index do |c, i| -%>
<%= "  " * i %>module <%= c %>
<%- end -%>
<%= "  " * config[:constant_array].size %>VERSION = "0.1.0"
<%- (config[:constant_array].size-1).downto(0) do |i| -%>
<%= "  " * i %>end
<%- end -%>
## [Unreleased]

## [0.1.0] - <%= Time.now.strftime('%F') %>

- Initial release
---
language: ruby
cache: bundler
rvm:
  - <%= RUBY_VERSION %>
before_install: gem install bundler -v <%= Bundler::VERSION %>
<%- config[:constant_array].each_with_index do |c, i| -%>
<%= "  " * i %>module <%= c %>
<%- end -%>
<%= "  " * config[:constant_array].size %>VERSION: String
<%= "  " * config[:constant_array].size %># See the writing guide of rbs: https://github.com/ruby/rbs#guides
<%- (config[:constant_array].size-1).downto(0) do |i| -%>
<%= "  " * i %>end
<%- end -%>
# Contributor Covenant Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.

## Our Standards

Examples of behavior that contributes to a positive environment for our community include:

* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community

Examples of unacceptable behavior include:

* The use of sexualized language or imagery, and sexual attention or
  advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
  address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
  professional setting

## Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.

Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at <%= config[:email] %>. All complaints will be reviewed and investigated promptly and fairly.

All community leaders are obligated to respect the privacy and security of the reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.

**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series of actions.

**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior,  harassment of an individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within the community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.

Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
# frozen_string_literal: true

require_relative "lib/<%=config[:namespaced_path]%>/version"

Gem::Specification.new do |spec|
  spec.name = <%= config[:name].inspect %>
  spec.version = <%= config[:constant_name] %>::VERSION
  spec.authors = [<%= config[:author].inspect %>]
  spec.email = [<%= config[:email].inspect %>]

  spec.summary = "TODO: Write a short summary, because RubyGems requires one."
  spec.description = "TODO: Write a longer description or delete this line."
  spec.homepage = "TODO: Put your gem's website or public repo URL here."
<%- if config[:mit] -%>
  spec.license = "MIT"
<%- end -%>
  spec.required_ruby_version = ">= <%= config[:required_ruby_version] %>"

  spec.metadata["allowed_push_host"] = "TODO: Set to your gem server 'https://example.com'"

  spec.metadata["homepage_uri"] = spec.homepage
  spec.metadata["source_code_uri"] = "TODO: Put your gem's public repo URL here."
  spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."

  # Specify which files should be added to the gem when it is released.
  # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
  spec.files = Dir.chdir(File.expand_path(__dir__)) do
    `git ls-files -z`.split("\x0").reject do |f|
      (f == __FILE__) || f.match(%r{\A(?:(?:test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
    end
  end
  spec.bindir = "exe"
  spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
  spec.require_paths = ["lib"]
<%- if config[:ext] -%>
  spec.extensions = ["ext/<%= config[:underscored_name] %>/extconf.rb"]
<%- end -%>

  # Uncomment to register a new dependency of your gem
  # spec.add_dependency "example-gem", "~> 1.0"

  # For more information and examples about making a new gem, checkout our
  # guide at: https://bundler.io/guides/creating_gem.html
end
# frozen_string_literal: true

require "bundler/gem_tasks"
<% default_task_names = [config[:test_task]].compact -%>
<% case config[:test] -%>
<% when "minitest", "test-unit" -%>
require "rake/testtask"

Rake::TestTask.new(:test) do |t|
  t.libs << "test"
  t.libs << "lib"
  t.test_files = FileList["test/**/*_test.rb"]
end

<% when "rspec" -%>
require "rspec/core/rake_task"

RSpec::Core::RakeTask.new(:spec)

<% end -%>
<% if config[:linter] == "rubocop" -%>
<% default_task_names << :rubocop -%>
require "rubocop/rake_task"

RuboCop::RakeTask.new

<% elsif config[:linter] == "standard" -%>
<% default_task_names << :standard -%>
require "standard/rake"

<% end -%>
<% if config[:ext] -%>
<% default_task_names.unshift(:clobber, :compile) -%>
require "rake/extensiontask"

task build: :compile

Rake::ExtensionTask.new("<%= config[:underscored_name] %>") do |ext|
  ext.lib_dir = "lib/<%= config[:namespaced_path] %>"
end

<% end -%>
<% if default_task_names.size == 1 -%>
task default: <%= default_task_names.first.inspect %>
<% else -%>
task default: %i[<%= default_task_names.join(" ") %>]
<% end -%>
#!/usr/bin/env <%= Bundler.settings[:shebang] || RbConfig::CONFIG["ruby_install_name"] %>
#
# This file was generated by Bundler.
#
# The application '<%= executable %>' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require "pathname"
path = Pathname.new(__FILE__)
$:.unshift File.expand_path "../<%= standalone_path %>", path.realpath

require "bundler/setup"
load File.expand_path "../<%= executable_path %>", path.realpath
# frozen_string_literal: true

require_relative "shared_helpers"
Bundler::SharedHelpers.major_deprecation 2, "Bundler no longer integrates with " \
  "Capistrano, but Capistrano provides its own integration with " \
  "Bundler via the capistrano-bundler gem. Use it instead."

module Bundler
  class Deployment
    def self.define_task(context, task_method = :task, opts = {})
      if defined?(Capistrano) && context.is_a?(Capistrano::Configuration)
        context_name = "capistrano"
        role_default = "{:except => {:no_release => true}}"
        error_type = ::Capistrano::CommandError
      else
        context_name = "vlad"
        role_default = "[:app]"
        error_type = ::Rake::CommandFailedError
      end

      roles = context.fetch(:bundle_roles, false)
      opts[:roles] = roles if roles

      context.send :namespace, :bundle do
        send :desc, <<-DESC
          Install the current Bundler environment. By default, gems will be \
          installed to the shared/bundle path. Gems in the development and \
          test group will not be installed. The install command is executed \
          with the --deployment and --quiet flags. If the bundle cmd cannot \
          be found then you can override the bundle_cmd variable to specify \
          which one it should use. The base path to the app is fetched from \
          the :latest_release variable. Set it for custom deploy layouts.

          You can override any of these defaults by setting the variables shown below.

          N.B. bundle_roles must be defined before you require 'bundler/#{context_name}' \
          in your deploy.rb file.

            set :bundle_gemfile,  "Gemfile"
            set :bundle_dir,      File.join(fetch(:shared_path), 'bundle')
            set :bundle_flags,    "--deployment --quiet"
            set :bundle_without,  [:development, :test]
            set :bundle_with,     [:mysql]
            set :bundle_cmd,      "bundle" # e.g. "/opt/ruby/bin/bundle"
            set :bundle_roles,    #{role_default} # e.g. [:app, :batch]
        DESC
        send task_method, :install, opts do
          bundle_cmd     = context.fetch(:bundle_cmd, "bundle")
          bundle_flags   = context.fetch(:bundle_flags, "--deployment --quiet")
          bundle_dir     = context.fetch(:bundle_dir, File.join(context.fetch(:shared_path), "bundle"))
          bundle_gemfile = context.fetch(:bundle_gemfile, "Gemfile")
          bundle_without = [*context.fetch(:bundle_without, [:development, :test])].compact
          bundle_with    = [*context.fetch(:bundle_with, [])].compact
          app_path = context.fetch(:latest_release)
          if app_path.to_s.empty?
            raise error_type.new("Cannot detect current release path - make sure you have deployed at least once.")
          end
          args = ["--gemfile #{File.join(app_path, bundle_gemfile)}"]
          args << "--path #{bundle_dir}" unless bundle_dir.to_s.empty?
          args << bundle_flags.to_s
          args << "--without #{bundle_without.join(" ")}" unless bundle_without.empty?
          args << "--with #{bundle_with.join(" ")}" unless bundle_with.empty?

          run "cd #{app_path} && #{bundle_cmd} install #{args.join(" ")}"
        end
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class Resolver
    class SpecGroup
      attr_accessor :name, :version, :source
      attr_accessor :activated_platforms

      def self.create_for(specs, all_platforms, specific_platform)
        specific_platform_specs = specs[specific_platform]
        return unless specific_platform_specs.any?

        platforms = all_platforms.select {|p| specs[p].any? }

        new(specific_platform_specs.first, specs, platforms)
      end

      def initialize(exemplary_spec, specs, relevant_platforms)
        @exemplary_spec = exemplary_spec
        @name = exemplary_spec.name
        @version = exemplary_spec.version
        @source = exemplary_spec.source

        @activated_platforms = relevant_platforms
        @dependencies = Hash.new do |dependencies, platforms|
          dependencies[platforms] = dependencies_for(platforms)
        end
        @specs = specs
      end

      def to_specs
        activated_platforms.map do |p|
          specs = @specs[p]
          next unless specs.any?

          specs.map do |s|
            lazy_spec = LazySpecification.new(name, version, s.platform, source)
            lazy_spec.dependencies.replace s.dependencies
            lazy_spec
          end
        end.flatten.compact.uniq
      end

      def to_s
        activated_platforms_string = sorted_activated_platforms.join(", ")
        "#{name} (#{version}) (#{activated_platforms_string})"
      end

      def dependencies_for_activated_platforms
        @dependencies[activated_platforms]
      end

      def ==(other)
        return unless other.is_a?(SpecGroup)
        name == other.name &&
          version == other.version &&
          sorted_activated_platforms == other.sorted_activated_platforms &&
          source == other.source
      end

      def eql?(other)
        return unless other.is_a?(SpecGroup)
        name.eql?(other.name) &&
          version.eql?(other.version) &&
          sorted_activated_platforms.eql?(other.sorted_activated_platforms) &&
          source.eql?(other.source)
      end

      def hash
        name.hash ^ version.hash ^ sorted_activated_platforms.hash ^ source.hash
      end

      protected

      def sorted_activated_platforms
        activated_platforms.sort_by(&:to_s)
      end

      private

      def dependencies_for(platforms)
        platforms.map do |platform|
          __dependencies(platform) + metadata_dependencies(platform)
        end.flatten
      end

      def __dependencies(platform)
        dependencies = []
        @specs[platform].first.dependencies.each do |dep|
          next if dep.type == :development
          dependencies << DepProxy.get_proxy(dep, platform)
        end
        dependencies
      end

      def metadata_dependencies(platform)
        spec = @specs[platform].first
        return [] unless spec.is_a?(Gem::Specification)
        dependencies = []
        if !spec.required_ruby_version.nil? && !spec.required_ruby_version.none?
          dependencies << DepProxy.get_proxy(Gem::Dependency.new("Ruby\0", spec.required_ruby_version), platform)
        end
        if !spec.required_rubygems_version.nil? && !spec.required_rubygems_version.none?
          dependencies << DepProxy.get_proxy(Gem::Dependency.new("RubyGems\0", spec.required_rubygems_version), platform)
        end
        dependencies
      end
    end
  end
end
# frozen_string_literal: true

module Bundler; end
require_relative "vendor/tmpdir/lib/tmpdir"
# frozen_string_literal: true

require "rubygems/dependency"
require_relative "shared_helpers"
require_relative "rubygems_ext"

module Bundler
  class Dependency < Gem::Dependency
    attr_reader :autorequire
    attr_reader :groups, :platforms, :gemfile, :git, :branch

    PLATFORM_MAP = {
      :ruby     => Gem::Platform::RUBY,
      :ruby_18  => Gem::Platform::RUBY,
      :ruby_19  => Gem::Platform::RUBY,
      :ruby_20  => Gem::Platform::RUBY,
      :ruby_21  => Gem::Platform::RUBY,
      :ruby_22  => Gem::Platform::RUBY,
      :ruby_23  => Gem::Platform::RUBY,
      :ruby_24  => Gem::Platform::RUBY,
      :ruby_25  => Gem::Platform::RUBY,
      :ruby_26  => Gem::Platform::RUBY,
      :mri      => Gem::Platform::RUBY,
      :mri_18   => Gem::Platform::RUBY,
      :mri_19   => Gem::Platform::RUBY,
      :mri_20   => Gem::Platform::RUBY,
      :mri_21   => Gem::Platform::RUBY,
      :mri_22   => Gem::Platform::RUBY,
      :mri_23   => Gem::Platform::RUBY,
      :mri_24   => Gem::Platform::RUBY,
      :mri_25   => Gem::Platform::RUBY,
      :mri_26   => Gem::Platform::RUBY,
      :rbx      => Gem::Platform::RUBY,
      :truffleruby => Gem::Platform::RUBY,
      :jruby    => Gem::Platform::JAVA,
      :jruby_18 => Gem::Platform::JAVA,
      :jruby_19 => Gem::Platform::JAVA,
      :mswin    => Gem::Platform::MSWIN,
      :mswin_18 => Gem::Platform::MSWIN,
      :mswin_19 => Gem::Platform::MSWIN,
      :mswin_20 => Gem::Platform::MSWIN,
      :mswin_21 => Gem::Platform::MSWIN,
      :mswin_22 => Gem::Platform::MSWIN,
      :mswin_23 => Gem::Platform::MSWIN,
      :mswin_24 => Gem::Platform::MSWIN,
      :mswin_25 => Gem::Platform::MSWIN,
      :mswin_26 => Gem::Platform::MSWIN,
      :mswin64    => Gem::Platform::MSWIN64,
      :mswin64_19 => Gem::Platform::MSWIN64,
      :mswin64_20 => Gem::Platform::MSWIN64,
      :mswin64_21 => Gem::Platform::MSWIN64,
      :mswin64_22 => Gem::Platform::MSWIN64,
      :mswin64_23 => Gem::Platform::MSWIN64,
      :mswin64_24 => Gem::Platform::MSWIN64,
      :mswin64_25 => Gem::Platform::MSWIN64,
      :mswin64_26 => Gem::Platform::MSWIN64,
      :mingw    => Gem::Platform::MINGW,
      :mingw_18 => Gem::Platform::MINGW,
      :mingw_19 => Gem::Platform::MINGW,
      :mingw_20 => Gem::Platform::MINGW,
      :mingw_21 => Gem::Platform::MINGW,
      :mingw_22 => Gem::Platform::MINGW,
      :mingw_23 => Gem::Platform::MINGW,
      :mingw_24 => Gem::Platform::MINGW,
      :mingw_25 => Gem::Platform::MINGW,
      :mingw_26 => Gem::Platform::MINGW,
      :x64_mingw    => Gem::Platform::X64_MINGW,
      :x64_mingw_20 => Gem::Platform::X64_MINGW,
      :x64_mingw_21 => Gem::Platform::X64_MINGW,
      :x64_mingw_22 => Gem::Platform::X64_MINGW,
      :x64_mingw_23 => Gem::Platform::X64_MINGW,
      :x64_mingw_24 => Gem::Platform::X64_MINGW,
      :x64_mingw_25 => Gem::Platform::X64_MINGW,
      :x64_mingw_26 => Gem::Platform::X64_MINGW,
    }.freeze

    def initialize(name, version, options = {}, &blk)
      type = options["type"] || :runtime
      super(name, version, type)

      @autorequire    = nil
      @groups         = Array(options["group"] || :default).map(&:to_sym)
      @source         = options["source"]
      @git            = options["git"]
      @branch         = options["branch"]
      @platforms      = Array(options["platforms"])
      @env            = options["env"]
      @should_include = options.fetch("should_include", true)
      @gemfile        = options["gemfile"]

      @autorequire = Array(options["require"] || []) if options.key?("require")
    end

    # Returns the platforms this dependency is valid for, in the same order as
    # passed in the `valid_platforms` parameter
    def gem_platforms(valid_platforms)
      return valid_platforms if @platforms.empty?

      valid_generic_platforms = valid_platforms.map {|p| [p, GemHelpers.generic(p)] }.to_h
      @gem_platforms ||= expanded_platforms.compact.uniq

      filtered_generic_platforms = valid_generic_platforms.values & @gem_platforms
      valid_generic_platforms.select {|_, v| filtered_generic_platforms.include?(v) }.keys
    end

    def expanded_platforms
      @platforms.map {|pl| PLATFORM_MAP[pl] }
    end

    def should_include?
      @should_include && current_env? && current_platform?
    end

    def current_env?
      return true unless @env
      if @env.is_a?(Hash)
        @env.all? do |key, val|
          ENV[key.to_s] && (val.is_a?(String) ? ENV[key.to_s] == val : ENV[key.to_s] =~ val)
        end
      else
        ENV[@env.to_s]
      end
    end

    def current_platform?
      return true if @platforms.empty?
      @platforms.any? do |p|
        Bundler.current_ruby.send("#{p}?")
      end
    end

    def to_lock
      out = super
      out << "!" if source
      out << "\n"
    end

    def specific?
      super
    rescue NoMethodError
      requirement != ">= 0"
    end
  end
end
# frozen_string_literal: true

module Bundler
  class SourceList
    attr_reader :path_sources,
      :git_sources,
      :plugin_sources,
      :global_path_source,
      :metadata_source

    def global_rubygems_source
      @global_rubygems_source ||= rubygems_aggregate_class.new("allow_local" => true)
    end

    def initialize
      @path_sources           = []
      @git_sources            = []
      @plugin_sources         = []
      @global_rubygems_source = nil
      @global_path_source     = nil
      @rubygems_sources       = []
      @metadata_source        = Source::Metadata.new

      @merged_gem_lockfile_sections = false
    end

    def merged_gem_lockfile_sections?
      @merged_gem_lockfile_sections
    end

    def merged_gem_lockfile_sections!(replacement_source)
      @merged_gem_lockfile_sections = true
      @global_rubygems_source = replacement_source
    end

    def aggregate_global_source?
      global_rubygems_source.multiple_remotes?
    end

    def implicit_global_source?
      global_rubygems_source.no_remotes?
    end

    def add_path_source(options = {})
      if options["gemspec"]
        add_source_to_list Source::Gemspec.new(options), path_sources
      else
        path_source = add_source_to_list Source::Path.new(options), path_sources
        @global_path_source ||= path_source if options["global"]
        path_source
      end
    end

    def add_git_source(options = {})
      add_source_to_list(Source::Git.new(options), git_sources).tap do |source|
        warn_on_git_protocol(source)
      end
    end

    def add_rubygems_source(options = {})
      new_source = Source::Rubygems.new(options)
      return @global_rubygems_source if @global_rubygems_source == new_source

      add_source_to_list new_source, @rubygems_sources
    end

    def add_plugin_source(source, options = {})
      add_source_to_list Plugin.source(source).new(options), @plugin_sources
    end

    def add_global_rubygems_remote(uri)
      global_rubygems_source.add_remote(uri)
      global_rubygems_source
    end

    def default_source
      global_path_source || global_rubygems_source
    end

    def rubygems_sources
      non_global_rubygems_sources + [global_rubygems_source]
    end

    def non_global_rubygems_sources
      @rubygems_sources
    end

    def rubygems_remotes
      rubygems_sources.map(&:remotes).flatten.uniq
    end

    def all_sources
      path_sources + git_sources + plugin_sources + rubygems_sources + [metadata_source]
    end

    def non_default_explicit_sources
      all_sources - [default_source, metadata_source]
    end

    def get(source)
      source_list_for(source).find {|s| equivalent_source?(source, s) }
    end

    def lock_sources
      lock_other_sources + lock_rubygems_sources
    end

    def lock_other_sources
      (path_sources + git_sources + plugin_sources).sort_by(&:identifier)
    end

    def lock_rubygems_sources
      if merged_gem_lockfile_sections?
        [combine_rubygems_sources]
      else
        rubygems_sources.sort_by(&:identifier)
      end
    end

    # Returns true if there are changes
    def replace_sources!(replacement_sources)
      return false if replacement_sources.empty?

      @rubygems_sources, @path_sources, @git_sources, @plugin_sources = map_sources(replacement_sources)
      @global_rubygems_source = global_replacement_source(replacement_sources)

      different_sources?(lock_sources, replacement_sources)
    end

    # Returns true if there are changes
    def expired_sources?(replacement_sources)
      return false if replacement_sources.empty?

      lock_sources = dup_with_replaced_sources(replacement_sources).lock_sources

      different_sources?(lock_sources, replacement_sources)
    end

    def local_only!
      all_sources.each(&:local_only!)
    end

    def cached!
      all_sources.each(&:cached!)
    end

    def remote!
      all_sources.each(&:remote!)
    end

    private

    def dup_with_replaced_sources(replacement_sources)
      new_source_list = dup
      new_source_list.replace_sources!(replacement_sources)
      new_source_list
    end

    def map_sources(replacement_sources)
      [@rubygems_sources, @path_sources, @git_sources, @plugin_sources].map do |sources|
        sources.map do |source|
          replacement_sources.find {|s| s == source } || source
        end
      end
    end

    def global_replacement_source(replacement_sources)
      replacement_source = replacement_sources.find {|s| s == global_rubygems_source }
      return global_rubygems_source unless replacement_source

      replacement_source.local!
      replacement_source
    end

    def different_sources?(lock_sources, replacement_sources)
      !equivalent_sources?(lock_sources, replacement_sources)
    end

    def rubygems_aggregate_class
      Source::Rubygems
    end

    def add_source_to_list(source, list)
      list.unshift(source).uniq!
      source
    end

    def source_list_for(source)
      case source
      when Source::Git          then git_sources
      when Source::Path         then path_sources
      when Source::Rubygems     then rubygems_sources
      when Plugin::API::Source  then plugin_sources
      else raise ArgumentError, "Invalid source: #{source.inspect}"
      end
    end

    def combine_rubygems_sources
      Source::Rubygems.new("remotes" => rubygems_remotes)
    end

    def warn_on_git_protocol(source)
      return if Bundler.settings["git.allow_insecure"]

      if source.uri =~ /^git\:/
        Bundler.ui.warn "The git source `#{source.uri}` uses the `git` protocol, " \
          "which transmits data without encryption. Disable this warning with " \
          "`bundle config set --local git.allow_insecure true`, or switch to the `https` " \
          "protocol to keep your data secure."
      end
    end

    def equivalent_sources?(lock_sources, replacement_sources)
      lock_sources.sort_by(&:identifier) == replacement_sources.sort_by(&:identifier)
    end

    def equivalent_source?(source, other_source)
      source == other_source
    end
  end
end
# frozen_string_literal: true

require_relative "dependency"
require_relative "ruby_dsl"

module Bundler
  class Dsl
    include RubyDsl

    def self.evaluate(gemfile, lockfile, unlock)
      builder = new
      builder.eval_gemfile(gemfile)
      builder.to_definition(lockfile, unlock)
    end

    VALID_PLATFORMS = Bundler::Dependency::PLATFORM_MAP.keys.freeze

    VALID_KEYS = %w[group groups git path glob name branch ref tag require submodules
                    platform platforms type source install_if gemfile].freeze

    GITHUB_PULL_REQUEST_URL = %r{\Ahttps://github\.com/([A-Za-z0-9_\-\.]+/[A-Za-z0-9_\-\.]+)/pull/(\d+)\z}.freeze

    attr_reader :gemspecs
    attr_accessor :dependencies

    def initialize
      @source               = nil
      @sources              = SourceList.new
      @git_sources          = {}
      @dependencies         = []
      @groups               = []
      @install_conditionals = []
      @optional_groups      = []
      @platforms            = []
      @env                  = nil
      @ruby_version         = nil
      @gemspecs             = []
      @gemfile              = nil
      @gemfiles             = []
      add_git_sources
    end

    def eval_gemfile(gemfile, contents = nil)
      expanded_gemfile_path = Pathname.new(gemfile).expand_path(@gemfile && @gemfile.parent)
      original_gemfile = @gemfile
      @gemfile = expanded_gemfile_path
      @gemfiles << expanded_gemfile_path
      contents ||= Bundler.read_file(@gemfile.to_s)
      instance_eval(contents.dup.tap{|x| x.untaint if RUBY_VERSION < "2.7" }, gemfile.to_s, 1)
    rescue Exception => e # rubocop:disable Lint/RescueException
      message = "There was an error " \
        "#{e.is_a?(GemfileEvalError) ? "evaluating" : "parsing"} " \
        "`#{File.basename gemfile.to_s}`: #{e.message}"

      raise DSLError.new(message, gemfile, e.backtrace, contents)
    ensure
      @gemfile = original_gemfile
    end

    def gemspec(opts = nil)
      opts ||= {}
      path              = opts[:path] || "."
      glob              = opts[:glob]
      name              = opts[:name]
      development_group = opts[:development_group] || :development
      expanded_path     = gemfile_root.join(path)

      gemspecs = Gem::Util.glob_files_in_dir("{,*}.gemspec", expanded_path).map {|g| Bundler.load_gemspec(g) }.compact
      gemspecs.reject! {|s| s.name != name } if name
      Index.sort_specs(gemspecs)
      specs_by_name_and_version = gemspecs.group_by {|s| [s.name, s.version] }

      case specs_by_name_and_version.size
      when 1
        specs = specs_by_name_and_version.values.first
        spec = specs.find {|s| s.match_platform(Bundler.local_platform) } || specs.first

        @gemspecs << spec

        gem spec.name, :name => spec.name, :path => path, :glob => glob

        group(development_group) do
          spec.development_dependencies.each do |dep|
            gem dep.name, *(dep.requirement.as_list + [:type => :development])
          end
        end
      when 0
        raise InvalidOption, "There are no gemspecs at #{expanded_path}"
      else
        raise InvalidOption, "There are multiple gemspecs at #{expanded_path}. " \
          "Please use the :name option to specify which one should be used"
      end
    end

    def gem(name, *args)
      options = args.last.is_a?(Hash) ? args.pop.dup : {}
      options["gemfile"] = @gemfile
      version = args || [">= 0"]

      normalize_options(name, version, options)

      dep = Dependency.new(name, version, options)

      # if there's already a dependency with this name we try to prefer one
      if current = @dependencies.find {|d| d.name == dep.name }
        deleted_dep = @dependencies.delete(current) if current.type == :development

        unless deleted_dep
          if current.requirement != dep.requirement
            return if dep.type == :development

            update_prompt = ""

            if File.basename(@gemfile) == Injector::INJECTED_GEMS
              if dep.requirements_list.include?(">= 0") && !current.requirements_list.include?(">= 0")
                update_prompt = ". Gem already added"
              else
                update_prompt = ". If you want to update the gem version, run `bundle update #{current.name}`"

                update_prompt += ". You may also need to change the version requirement specified in the Gemfile if it's too restrictive." unless current.requirements_list.include?(">= 0")
              end
            end

            raise GemfileError, "You cannot specify the same gem twice with different version requirements.\n" \
                            "You specified: #{current.name} (#{current.requirement}) and #{dep.name} (#{dep.requirement})" \
                             "#{update_prompt}"
          else
            Bundler.ui.warn "Your Gemfile lists the gem #{current.name} (#{current.requirement}) more than once.\n" \
                            "You should probably keep only one of them.\n" \
                            "Remove any duplicate entries and specify the gem only once.\n" \
                            "While it's not a problem now, it could cause errors if you change the version of one of them later."
          end

          if current.source != dep.source
            return if dep.type == :development
            raise GemfileError, "You cannot specify the same gem twice coming from different sources.\n" \
                            "You specified that #{dep.name} (#{dep.requirement}) should come from " \
                            "#{current.source || "an unspecified source"} and #{dep.source}\n"
          end
        end
      end

      @dependencies << dep
    end

    def source(source, *args, &blk)
      options = args.last.is_a?(Hash) ? args.pop.dup : {}
      options = normalize_hash(options)
      source = normalize_source(source)

      if options.key?("type")
        options["type"] = options["type"].to_s
        unless Plugin.source?(options["type"])
          raise InvalidOption, "No plugin sources available for #{options["type"]}"
        end

        unless block_given?
          raise InvalidOption, "You need to pass a block to #source with :type option"
        end

        source_opts = options.merge("uri" => source)
        with_source(@sources.add_plugin_source(options["type"], source_opts), &blk)
      elsif block_given?
        with_source(@sources.add_rubygems_source("remotes" => source), &blk)
      else
        @sources.add_global_rubygems_remote(source)
      end
    end

    def git_source(name, &block)
      unless block_given?
        raise InvalidOption, "You need to pass a block to #git_source"
      end

      if valid_keys.include?(name.to_s)
        raise InvalidOption, "You cannot use #{name} as a git source. It " \
          "is a reserved key. Reserved keys are: #{valid_keys.join(", ")}"
      end

      @git_sources[name.to_s] = block
    end

    def path(path, options = {}, &blk)
      source_options = normalize_hash(options).merge(
        "path" => Pathname.new(path),
        "root_path" => gemfile_root,
        "gemspec" => gemspecs.find {|g| g.name == options["name"] }
      )

      source_options["global"] = true unless block_given?

      source = @sources.add_path_source(source_options)
      with_source(source, &blk)
    end

    def git(uri, options = {}, &blk)
      unless block_given?
        msg = "You can no longer specify a git source by itself. Instead, \n" \
              "either use the :git option on a gem, or specify the gems that \n" \
              "bundler should find in the git source by passing a block to \n" \
              "the git method, like: \n\n" \
              "  git 'git://github.com/rails/rails.git' do\n" \
              "    gem 'rails'\n" \
              "  end"
        raise DeprecatedError, msg
      end

      with_source(@sources.add_git_source(normalize_hash(options).merge("uri" => uri)), &blk)
    end

    def github(repo, options = {})
      raise ArgumentError, "GitHub sources require a block" unless block_given?
      github_uri  = @git_sources["github"].call(repo)
      git_options = normalize_hash(options).merge("uri" => github_uri)
      git_source  = @sources.add_git_source(git_options)
      with_source(git_source) { yield }
    end

    def to_definition(lockfile, unlock)
      check_primary_source_safety
      Definition.new(lockfile, @dependencies, @sources, unlock, @ruby_version, @optional_groups, @gemfiles)
    end

    def group(*args, &blk)
      options = args.last.is_a?(Hash) ? args.pop.dup : {}
      normalize_group_options(options, args)

      @groups.concat args

      if options["optional"]
        optional_groups = args - @optional_groups
        @optional_groups.concat optional_groups
      end

      yield
    ensure
      args.each { @groups.pop }
    end

    def install_if(*args)
      @install_conditionals.concat args
      yield
    ensure
      args.each { @install_conditionals.pop }
    end

    def platforms(*platforms)
      @platforms.concat platforms
      yield
    ensure
      platforms.each { @platforms.pop }
    end
    alias_method :platform, :platforms

    def env(name)
      old = @env
      @env = name
      yield
    ensure
      @env = old
    end

    def plugin(*args)
      # Pass on
    end

    def method_missing(name, *args)
      raise GemfileError, "Undefined local variable or method `#{name}' for Gemfile"
    end

    def check_primary_source_safety
      check_path_source_safety
      check_rubygems_source_safety
    end

    private

    def add_git_sources
      git_source(:github) do |repo_name|
        warn_deprecated_git_source(:github, <<-'RUBY'.strip, 'Change any "reponame" :github sources to "username/reponame".')
"https://github.com/#{repo_name}.git"
        RUBY
        if repo_name =~ GITHUB_PULL_REQUEST_URL
          {
            "git" => "https://github.com/#{$1}.git",
            "branch" => "refs/pull/#{$2}/head",
            "ref" => nil,
            "tag" => nil,
          }
        else
          repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
          "https://github.com/#{repo_name}.git"
        end
      end

      git_source(:gist) do |repo_name|
        warn_deprecated_git_source(:gist, '"https://gist.github.com/#{repo_name}.git"')

        "https://gist.github.com/#{repo_name}.git"
      end

      git_source(:bitbucket) do |repo_name|
        warn_deprecated_git_source(:bitbucket, <<-'RUBY'.strip)
user_name, repo_name = repo_name.split("/")
repo_name ||= user_name
"https://#{user_name}@bitbucket.org/#{user_name}/#{repo_name}.git"
        RUBY

        user_name, repo_name = repo_name.split("/")
        repo_name ||= user_name
        "https://#{user_name}@bitbucket.org/#{user_name}/#{repo_name}.git"
      end
    end

    def with_source(source)
      old_source = @source
      if block_given?
        @source = source
        yield
      end
      source
    ensure
      @source = old_source
    end

    def normalize_hash(opts)
      opts.keys.each do |k|
        opts[k.to_s] = opts.delete(k) unless k.is_a?(String)
      end
      opts
    end

    def valid_keys
      @valid_keys ||= VALID_KEYS
    end

    def normalize_options(name, version, opts)
      if name.is_a?(Symbol)
        raise GemfileError, %(You need to specify gem names as Strings. Use 'gem "#{name}"' instead)
      end
      if name =~ /\s/
        raise GemfileError, %('#{name}' is not a valid gem name because it contains whitespace)
      end
      raise GemfileError, %(an empty gem name is not valid) if name.empty?

      normalize_hash(opts)

      git_names = @git_sources.keys.map(&:to_s)
      validate_keys("gem '#{name}'", opts, valid_keys + git_names)

      groups = @groups.dup
      opts["group"] = opts.delete("groups") || opts["group"]
      groups.concat Array(opts.delete("group"))
      groups = [:default] if groups.empty?

      install_if = @install_conditionals.dup
      install_if.concat Array(opts.delete("install_if"))
      install_if = install_if.reduce(true) do |memo, val|
        memo && (val.respond_to?(:call) ? val.call : val)
      end

      platforms = @platforms.dup
      opts["platforms"] = opts["platform"] || opts["platforms"]
      platforms.concat Array(opts.delete("platforms"))
      platforms.map!(&:to_sym)
      platforms.each do |p|
        next if VALID_PLATFORMS.include?(p)
        raise GemfileError, "`#{p}` is not a valid platform. The available options are: #{VALID_PLATFORMS.inspect}"
      end

      # Save sources passed in a key
      if opts.key?("source")
        source = normalize_source(opts["source"])
        opts["source"] = @sources.add_rubygems_source("remotes" => source)
      end

      git_name = (git_names & opts.keys).last
      if @git_sources[git_name]
        git_opts = @git_sources[git_name].call(opts[git_name])
        git_opts = { "git" => git_opts } if git_opts.is_a?(String)
        opts.merge!(git_opts) do |key, _gemfile_value, _git_source_value|
          raise GemfileError, %(The :#{key} option can't be used with `#{git_name}: #{opts[git_name].inspect}`)
        end
      end

      %w[git path].each do |type|
        next unless param = opts[type]
        if version.first && version.first =~ /^\s*=?\s*(\d[^\s]*)\s*$/
          options = opts.merge("name" => name, "version" => $1)
        else
          options = opts.dup
        end
        source = send(type, param, options) {}
        opts["source"] = source
      end

      opts["source"]         ||= @source
      opts["env"]            ||= @env
      opts["platforms"]      = platforms.dup
      opts["group"]          = groups
      opts["should_include"] = install_if
    end

    def normalize_group_options(opts, groups)
      normalize_hash(opts)

      groups = groups.map {|group| ":#{group}" }.join(", ")
      validate_keys("group #{groups}", opts, %w[optional])

      opts["optional"] ||= false
    end

    def validate_keys(command, opts, valid_keys)
      invalid_keys = opts.keys - valid_keys

      git_source = opts.keys & @git_sources.keys.map(&:to_s)
      if opts["branch"] && !(opts["git"] || opts["github"] || git_source.any?)
        raise GemfileError, %(The `branch` option for `#{command}` is not allowed. Only gems with a git source can specify a branch)
      end

      return true unless invalid_keys.any?

      message = String.new
      message << "You passed #{invalid_keys.map {|k| ":" + k }.join(", ")} "
      message << if invalid_keys.size > 1
        "as options for #{command}, but they are invalid."
      else
        "as an option for #{command}, but it is invalid."
      end

      message << " Valid options are: #{valid_keys.join(", ")}."
      message << " You may be able to resolve this by upgrading Bundler to the newest version."
      raise InvalidOption, message
    end

    def normalize_source(source)
      case source
      when :gemcutter, :rubygems, :rubyforge
        Bundler::SharedHelpers.major_deprecation 2, "The source :#{source} is deprecated because HTTP " \
          "requests are insecure.\nPlease change your source to 'https://" \
          "rubygems.org' if possible, or 'http://rubygems.org' if not."
        "http://rubygems.org"
      when String
        source
      else
        raise GemfileError, "Unknown source '#{source}'"
      end
    end

    def check_path_source_safety
      return if @sources.global_path_source.nil?

      msg = "You can no longer specify a path source by itself. Instead, \n" \
              "either use the :path option on a gem, or specify the gems that \n" \
              "bundler should find in the path source by passing a block to \n" \
              "the path method, like: \n\n" \
              "    path 'dir/containing/rails' do\n" \
              "      gem 'rails'\n" \
              "    end\n\n"

      SharedHelpers.major_deprecation(2, msg.strip)
    end

    def check_rubygems_source_safety
      if @sources.implicit_global_source?
        implicit_global_source_warning
      elsif @sources.aggregate_global_source?
        multiple_global_source_warning
      end
    end

    def implicit_global_source_warning
      Bundler::SharedHelpers.major_deprecation 2, "This Gemfile does not include an explicit global source. " \
        "Not using an explicit global source may result in a different lockfile being generated depending on " \
        "the gems you have installed locally before bundler is run. " \
        "Instead, define a global source in your Gemfile like this: source \"https://rubygems.org\"."
    end

    def multiple_global_source_warning
      if Bundler.feature_flag.bundler_3_mode?
        msg = "This Gemfile contains multiple primary sources. " \
          "Each source after the first must include a block to indicate which gems " \
          "should come from that source"
        raise GemfileEvalError, msg
      else
        Bundler::SharedHelpers.major_deprecation 2, "Your Gemfile contains multiple primary sources. " \
          "Using `source` more than once without a block is a security risk, and " \
          "may result in installing unexpected gems. To resolve this warning, use " \
          "a block to indicate which gems should come from the secondary source."
      end
    end

    def warn_deprecated_git_source(name, replacement, additional_message = nil)
      additional_message &&= " #{additional_message}"
      replacement = if replacement.count("\n").zero?
        "{|repo_name| #{replacement} }"
      else
        "do |repo_name|\n#{replacement.to_s.gsub(/^/, "      ")}\n    end"
      end

      Bundler::SharedHelpers.major_deprecation 3, <<-EOS
The :#{name} git source is deprecated, and will be removed in the future.#{additional_message} Add this code to the top of your Gemfile to ensure it continues to work:

    git_source(:#{name}) #{replacement}

      EOS
    end

    class DSLError < GemfileError
      # @return [String] the description that should be presented to the user.
      #
      attr_reader :description

      # @return [String] the path of the dsl file that raised the exception.
      #
      attr_reader :dsl_path

      # @return [Exception] the backtrace of the exception raised by the
      #         evaluation of the dsl file.
      #
      attr_reader :backtrace

      # @param [Exception] backtrace @see backtrace
      # @param [String]    dsl_path  @see dsl_path
      #
      def initialize(description, dsl_path, backtrace, contents = nil)
        @status_code = $!.respond_to?(:status_code) && $!.status_code

        @description = description
        @dsl_path    = dsl_path
        @backtrace   = backtrace
        @contents    = contents
      end

      def status_code
        @status_code || super
      end

      # @return [String] the contents of the DSL that cause the exception to
      #         be raised.
      #
      def contents
        @contents ||= begin
          dsl_path && File.exist?(dsl_path) && File.read(dsl_path)
        end
      end

      # The message of the exception reports the content of podspec for the
      # line that generated the original exception.
      #
      # @example Output
      #
      #   Invalid podspec at `RestKit.podspec` - undefined method
      #   `exclude_header_search_paths=' for #<Pod::Specification for
      #   `RestKit/Network (0.9.3)`>
      #
      #       from spec-repos/master/RestKit/0.9.3/RestKit.podspec:36
      #       -------------------------------------------
      #           # because it would break: #import <CoreData/CoreData.h>
      #    >      ns.exclude_header_search_paths = 'Code/RestKit.h'
      #         end
      #       -------------------------------------------
      #
      # @return [String] the message of the exception.
      #
      def to_s
        @to_s ||= begin
          trace_line, description = parse_line_number_from_description

          m = String.new("\n[!] ")
          m << description
          m << ". Bundler cannot continue.\n"

          return m unless backtrace && dsl_path && contents

          trace_line = backtrace.find {|l| l.include?(dsl_path.to_s) } || trace_line
          return m unless trace_line
          line_numer = trace_line.split(":")[1].to_i - 1
          return m unless line_numer

          lines      = contents.lines.to_a
          indent     = " #  "
          indicator  = indent.tr("#", ">")
          first_line = line_numer.zero?
          last_line  = (line_numer == (lines.count - 1))

          m << "\n"
          m << "#{indent}from #{trace_line.gsub(/:in.*$/, "")}\n"
          m << "#{indent}-------------------------------------------\n"
          m << "#{indent}#{lines[line_numer - 1]}" unless first_line
          m << "#{indicator}#{lines[line_numer]}"
          m << "#{indent}#{lines[line_numer + 1]}" unless last_line
          m << "\n" unless m.end_with?("\n")
          m << "#{indent}-------------------------------------------\n"
        end
      end

      private

      def parse_line_number_from_description
        description = self.description
        if dsl_path && description =~ /((#{Regexp.quote File.expand_path(dsl_path)}|#{Regexp.quote dsl_path.to_s}):\d+)/
          trace_line = Regexp.last_match[1]
          description = description.sub(/\n.*\n(\.\.\.)? *\^~+$/, "").sub(/#{Regexp.quote trace_line}:\s*/, "").sub("\n", " - ")
        end
        [trace_line, description]
      end
    end

    def gemfile_root
      @gemfile ||= Bundler.default_gemfile
      @gemfile.dirname
    end
  end
end
# frozen_string_literal: true

module Bundler
  def self.require_thor_actions
    require_relative "vendor/thor/lib/thor/actions"
  end
end
require_relative "vendor/thor/lib/thor"
# frozen_string_literal: true

module Bundler
  class CLI::Config < Thor
    class_option :parseable, :type => :boolean, :banner => "Use minimal formatting for more parseable output"

    def self.scope_options
      method_option :global, :type => :boolean, :banner => "Only change the global config"
      method_option :local, :type => :boolean, :banner => "Only change the local config"
    end
    private_class_method :scope_options

    desc "base NAME [VALUE]", "The Bundler 1 config interface", :hide => true
    scope_options
    method_option :delete, :type => :boolean, :banner => "delete"
    def base(name = nil, *value)
      new_args =
        if ARGV.size == 1
          ["config", "list"]
        elsif ARGV.include?("--delete")
          ARGV.map {|arg| arg == "--delete" ? "unset" : arg }
        elsif ARGV.include?("--global") || ARGV.include?("--local") || ARGV.size == 3
          ["config", "set", *ARGV[1..-1]]
        else
          ["config", "get", ARGV[1]]
        end

      SharedHelpers.major_deprecation 3,
        "Using the `config` command without a subcommand [list, get, set, unset] is deprecated and will be removed in the future. Use `bundle #{new_args.join(" ")}` instead."

      Base.new(options, name, value, self).run
    end

    desc "list", "List out all configured settings"
    def list
      Base.new(options, nil, nil, self).run
    end

    desc "get NAME", "Returns the value for the given key"
    def get(name)
      Base.new(options, name, nil, self).run
    end

    desc "set NAME VALUE", "Sets the given value for the given key"
    scope_options
    def set(name, value, *value_)
      Base.new(options, name, value_.unshift(value), self).run
    end

    desc "unset NAME", "Unsets the value for the given key"
    scope_options
    def unset(name)
      options[:delete] = true
      Base.new(options, name, nil, self).run
    end

    default_task :base

    class Base
      attr_reader :name, :value, :options, :scope, :thor

      def initialize(options, name, value, thor)
        @options = options
        @name = name
        value = Array(value)
        @value = value.empty? ? nil : value.join(" ")
        @thor = thor
        validate_scope!
      end

      def run
        unless name
          warn_unused_scope "Ignoring --#{scope}"
          confirm_all
          return
        end

        if options[:delete]
          if !explicit_scope? || scope != "global"
            Bundler.settings.set_local(name, nil)
          end
          if !explicit_scope? || scope != "local"
            Bundler.settings.set_global(name, nil)
          end
          return
        end

        if value.nil?
          warn_unused_scope "Ignoring --#{scope} since no value to set was given"

          if options[:parseable]
            if value = Bundler.settings[name]
              Bundler.ui.info("#{name}=#{value}")
            end
            return
          end

          confirm(name)
          return
        end

        Bundler.ui.info(message) if message
        Bundler.settings.send("set_#{scope}", name, new_value)
      end

      def confirm_all
        if @options[:parseable]
          thor.with_padding do
            Bundler.settings.all.each do |setting|
              val = Bundler.settings[setting]
              Bundler.ui.info "#{setting}=#{val}"
            end
          end
        else
          Bundler.ui.confirm "Settings are listed in order of priority. The top value will be used.\n"
          Bundler.settings.all.each do |setting|
            Bundler.ui.confirm setting
            show_pretty_values_for(setting)
            Bundler.ui.confirm ""
          end
        end
      end

      def confirm(name)
        Bundler.ui.confirm "Settings for `#{name}` in order of priority. The top value will be used"
        show_pretty_values_for(name)
      end

      def new_value
        pathname = Pathname.new(value)
        if name.start_with?("local.") && pathname.directory?
          pathname.expand_path.to_s
        else
          value
        end
      end

      def message
        locations = Bundler.settings.locations(name)
        if @options[:parseable]
          "#{name}=#{new_value}" if new_value
        elsif scope == "global"
          if !locations[:local].nil?
            "Your application has set #{name} to #{locations[:local].inspect}. " \
              "This will override the global value you are currently setting"
          elsif locations[:env]
            "You have a bundler environment variable for #{name} set to " \
              "#{locations[:env].inspect}. This will take precedence over the global value you are setting"
          elsif !locations[:global].nil? && locations[:global] != value
            "You are replacing the current global value of #{name}, which is currently " \
              "#{locations[:global].inspect}"
          end
        elsif scope == "local" && !locations[:local].nil? && locations[:local] != value
          "You are replacing the current local value of #{name}, which is currently " \
            "#{locations[:local].inspect}"
        end
      end

      def show_pretty_values_for(setting)
        thor.with_padding do
          Bundler.settings.pretty_values_for(setting).each do |line|
            Bundler.ui.info line
          end
        end
      end

      def explicit_scope?
        @explicit_scope
      end

      def warn_unused_scope(msg)
        return unless explicit_scope?
        return if options[:parseable]

        Bundler.ui.warn(msg)
      end

      def validate_scope!
        @explicit_scope = true
        scopes = %w[global local].select {|s| options[s] }
        case scopes.size
        when 0
          @scope = "global"
          @explicit_scope = false
        when 1
          @scope = scopes.first
        else
          raise InvalidOption,
            "The options #{scopes.join " and "} were specified. Please only use one of the switches at a time."
        end
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Pristine
    def initialize(gems)
      @gems = gems
    end

    def run
      CLI::Common.ensure_all_gems_in_lockfile!(@gems)
      definition = Bundler.definition
      definition.validate_runtime!
      installer = Bundler::Installer.new(Bundler.root, definition)

      Bundler.load.specs.each do |spec|
        next if spec.name == "bundler" # Source::Rubygems doesn't install bundler
        next if !@gems.empty? && !@gems.include?(spec.name)

        gem_name = "#{spec.name} (#{spec.version}#{spec.git_version})"
        gem_name += " (#{spec.platform})" if !spec.platform.nil? && spec.platform != Gem::Platform::RUBY

        case source = spec.source
        when Source::Rubygems
          cached_gem = spec.cache_file
          unless File.exist?(cached_gem)
            Bundler.ui.error("Failed to pristine #{gem_name}. Cached gem #{cached_gem} does not exist.")
            next
          end

          FileUtils.rm_rf spec.full_gem_path
        when Source::Git
          if source.local?
            Bundler.ui.warn("Cannot pristine #{gem_name}. Gem is locally overridden.")
            next
          end

          source.remote!
          if extension_cache_path = source.extension_cache_path(spec)
            FileUtils.rm_rf extension_cache_path
          end
          FileUtils.rm_rf spec.extension_dir
          FileUtils.rm_rf spec.full_gem_path
        else
          Bundler.ui.warn("Cannot pristine #{gem_name}. Gem is sourced from local path.")
          next
        end

        Bundler::GemInstaller.new(spec, installer, false, 0, true).install_from_spec
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Outdated
    attr_reader :options, :gems, :options_include_groups, :filter_options_patch, :sources, :strict
    attr_accessor :outdated_gems

    def initialize(options, gems)
      @options = options
      @gems = gems
      @sources = Array(options[:source])

      @filter_options_patch = options.keys & %w[filter-major filter-minor filter-patch]

      @outdated_gems = []

      @options_include_groups = [:group, :groups].any? do |v|
        options.keys.include?(v.to_s)
      end

      # the patch level options imply strict is also true. It wouldn't make
      # sense otherwise.
      @strict = options["filter-strict"] || Bundler::CLI::Common.patch_level_options(options).any?
    end

    def run
      check_for_deployment_mode!

      gems.each do |gem_name|
        Bundler::CLI::Common.select_spec(gem_name)
      end

      Bundler.definition.validate_runtime!
      current_specs = Bundler.ui.silence { Bundler.definition.resolve }

      current_dependencies = Bundler.ui.silence do
        Bundler.load.dependencies.map {|dep| [dep.name, dep] }.to_h
      end

      definition = if gems.empty? && sources.empty?
        # We're doing a full update
        Bundler.definition(true)
      else
        Bundler.definition(:gems => gems, :sources => sources)
      end

      Bundler::CLI::Common.configure_gem_version_promoter(
        Bundler.definition,
        options
      )

      definition_resolution = proc do
        options[:local] ? definition.resolve_with_cache! : definition.resolve_remotely!
      end

      if options[:parseable]
        Bundler.ui.silence(&definition_resolution)
      else
        definition_resolution.call
      end

      Bundler.ui.info ""

      # Loop through the current specs
      gemfile_specs, dependency_specs = current_specs.partition do |spec|
        current_dependencies.key? spec.name
      end

      specs = if options["only-explicit"]
        gemfile_specs
      else
        gemfile_specs + dependency_specs
      end

      specs.sort_by(&:name).uniq(&:name).each do |current_spec|
        next unless gems.empty? || gems.include?(current_spec.name)

        active_spec = retrieve_active_spec(definition, current_spec)
        next unless active_spec

        next unless filter_options_patch.empty? || update_present_via_semver_portions(current_spec, active_spec, options)

        gem_outdated = Gem::Version.new(active_spec.version) > Gem::Version.new(current_spec.version)
        next unless gem_outdated || (current_spec.git_version != active_spec.git_version)

        dependency = current_dependencies[current_spec.name]
        groups = ""
        if dependency && !options[:parseable]
          groups = dependency.groups.join(", ")
        end

        outdated_gems << {
          :active_spec => active_spec,
          :current_spec => current_spec,
          :dependency => dependency,
          :groups => groups,
        }
      end

      if outdated_gems.empty?
        unless options[:parseable]
          Bundler.ui.info(nothing_outdated_message)
        end
      else
        if options_include_groups
          relevant_outdated_gems = outdated_gems.group_by {|g| g[:groups] }.sort.flat_map do |groups, gems|
            contains_group = groups.split(", ").include?(options[:group])
            next unless options[:groups] || contains_group

            gems
          end.compact

          if options[:parseable]
            relevant_outdated_gems.each do |gems|
              print_gems(gems)
            end
          else
            print_gems_table(relevant_outdated_gems)
          end
        elsif options[:parseable]
          print_gems(outdated_gems)
        else
          print_gems_table(outdated_gems)
        end

        exit 1
      end
    end

    private

    def groups_text(group_text, groups)
      "#{group_text}#{groups.split(",").size > 1 ? "s" : ""} \"#{groups}\""
    end

    def nothing_outdated_message
      if filter_options_patch.any?
        display = filter_options_patch.map do |o|
          o.sub("filter-", "")
        end.join(" or ")

        "No #{display} updates to display.\n"
      else
        "Bundle up to date!\n"
      end
    end

    def retrieve_active_spec(definition, current_spec)
      active_spec = definition.resolve.find_by_name_and_platform(current_spec.name, current_spec.platform)
      return unless active_spec

      return active_spec if strict

      active_specs = active_spec.source.specs.search(current_spec.name).select {|spec| spec.match_platform(current_spec.platform) }.sort_by(&:version)
      if !current_spec.version.prerelease? && !options[:pre] && active_specs.size > 1
        active_specs.delete_if {|b| b.respond_to?(:version) && b.version.prerelease? }
      end
      active_specs.last
    end

    def print_gems(gems_list)
      gems_list.each do |gem|
        print_gem(
          gem[:current_spec],
          gem[:active_spec],
          gem[:dependency],
          gem[:groups],
        )
      end
    end

    def print_gems_table(gems_list)
      data = gems_list.map do |gem|
        gem_column_for(
          gem[:current_spec],
          gem[:active_spec],
          gem[:dependency],
          gem[:groups],
        )
      end

      print_indented([table_header] + data)
    end

    def print_gem(current_spec, active_spec, dependency, groups)
      spec_version = "#{active_spec.version}#{active_spec.git_version}"
      spec_version += " (from #{active_spec.loaded_from})" if Bundler.ui.debug? && active_spec.loaded_from
      current_version = "#{current_spec.version}#{current_spec.git_version}"

      if dependency && dependency.specific?
        dependency_version = %(, requested #{dependency.requirement})
      end

      spec_outdated_info = "#{active_spec.name} (newest #{spec_version}, " \
        "installed #{current_version}#{dependency_version})"

      output_message = if options[:parseable]
        spec_outdated_info.to_s
      elsif options_include_groups || groups.empty?
        "  * #{spec_outdated_info}"
      else
        "  * #{spec_outdated_info} in #{groups_text("group", groups)}"
      end

      Bundler.ui.info output_message.rstrip
    end

    def gem_column_for(current_spec, active_spec, dependency, groups)
      current_version = "#{current_spec.version}#{current_spec.git_version}"
      spec_version = "#{active_spec.version}#{active_spec.git_version}"
      dependency = dependency.requirement if dependency

      ret_val = [active_spec.name, current_version, spec_version, dependency.to_s, groups.to_s]
      ret_val << active_spec.loaded_from.to_s if Bundler.ui.debug?
      ret_val
    end

    def check_for_deployment_mode!
      return unless Bundler.frozen_bundle?
      suggested_command = if Bundler.settings.locations("frozen").keys.&([:global, :local]).any?
        "bundle config unset frozen"
      elsif Bundler.settings.locations("deployment").keys.&([:global, :local]).any?
        "bundle config unset deployment"
      end
      raise ProductionError, "You are trying to check outdated gems in " \
        "deployment mode. Run `bundle outdated` elsewhere.\n" \
        "\nIf this is a development machine, remove the " \
        "#{Bundler.default_gemfile} freeze" \
        "\nby running `#{suggested_command}`."
    end

    def update_present_via_semver_portions(current_spec, active_spec, options)
      current_major = current_spec.version.segments.first
      active_major = active_spec.version.segments.first

      update_present = false
      update_present = active_major > current_major if options["filter-major"]

      if !update_present && (options["filter-minor"] || options["filter-patch"]) && current_major == active_major
        current_minor = get_version_semver_portion_value(current_spec, 1)
        active_minor = get_version_semver_portion_value(active_spec, 1)

        update_present = active_minor > current_minor if options["filter-minor"]

        if !update_present && options["filter-patch"] && current_minor == active_minor
          current_patch = get_version_semver_portion_value(current_spec, 2)
          active_patch = get_version_semver_portion_value(active_spec, 2)

          update_present = active_patch > current_patch
        end
      end

      update_present
    end

    def get_version_semver_portion_value(spec, version_portion_index)
      version_section = spec.version.segments[version_portion_index, 1]
      version_section.to_a[0].to_i
    end

    def print_indented(matrix)
      header = matrix[0]
      data = matrix[1..-1]

      column_sizes = Array.new(header.size) do |index|
        matrix.max_by {|row| row[index].length }[index].length
      end

      Bundler.ui.info justify(header, column_sizes)

      data.sort_by! {|row| row[0] }

      data.each do |row|
        Bundler.ui.info justify(row, column_sizes)
      end
    end

    def table_header
      header = ["Gem", "Current", "Latest", "Requested", "Groups"]
      header << "Path" if Bundler.ui.debug?
      header
    end

    def justify(row, sizes)
      row.each_with_index.map do |element, index|
        element.ljust(sizes[index])
      end.join("  ").strip + "\n"
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Inject
    attr_reader :options, :name, :version, :group, :source, :gems
    def initialize(options, name, version)
      @options = options
      @name = name
      @version = version || last_version_number
      @group = options[:group].split(",") unless options[:group].nil?
      @source = options[:source]
      @gems = []
    end

    def run
      # The required arguments allow Thor to give useful feedback when the arguments
      # are incorrect. This adds those first two arguments onto the list as a whole.
      gems.unshift(source).unshift(group).unshift(version).unshift(name)

      # Build an array of Dependency objects out of the arguments
      deps = []
      # when `inject` support addition of more than one gem, then this loop will
      # help. Currently this loop is running once.
      gems.each_slice(4) do |gem_name, gem_version, gem_group, gem_source|
        ops = Gem::Requirement::OPS.map {|key, _val| key }
        has_op = ops.any? {|op| gem_version.start_with? op }
        gem_version = "~> #{gem_version}" unless has_op
        deps << Bundler::Dependency.new(gem_name, gem_version, "group" => gem_group, "source" => gem_source)
      end

      added = Injector.inject(deps, options)

      if added.any?
        Bundler.ui.confirm "Added to Gemfile:"
        Bundler.ui.confirm(added.map do |d|
          name = "'#{d.name}'"
          requirement = ", '#{d.requirement}'"
          group = ", :group => #{d.groups.inspect}" if d.groups != Array(:default)
          source = ", :source => '#{d.source}'" unless d.source.nil?
          %(gem #{name}#{requirement}#{group}#{source})
        end.join("\n"))
      else
        Bundler.ui.confirm "All gems were already present in the Gemfile"
      end
    end

    private

    def last_version_number
      definition = Bundler.definition(true)
      definition.resolve_remotely!
      specs = definition.index[name].sort_by(&:version)
      unless options[:pre]
        specs.delete_if {|b| b.respond_to?(:version) && b.version.prerelease? }
      end
      spec = specs.last
      spec.version.to_s
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Fund
    attr_reader :options

    def initialize(options)
      @options = options
    end

    def run
      Bundler.definition.validate_runtime!

      groups = Array(options[:group]).map(&:to_sym)

      deps = if groups.any?
        Bundler.definition.dependencies_for(groups)
      else
        Bundler.definition.current_dependencies
      end

      fund_info = deps.each_with_object([]) do |dep, arr|
        spec = Bundler.definition.specs[dep.name].first
        if spec.metadata.key?("funding_uri")
          arr << "* #{spec.name} (#{spec.version})\n  Funding: #{spec.metadata["funding_uri"]}"
        end
      end

      if fund_info.empty?
        Bundler.ui.info "None of the installed gems you directly depend on are looking for funding."
      else
        Bundler.ui.info fund_info.join("\n")
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Open
    attr_reader :options, :name
    def initialize(options, name)
      @options = options
      @name = name
    end

    def run
      editor = [ENV["BUNDLER_EDITOR"], ENV["VISUAL"], ENV["EDITOR"]].find {|e| !e.nil? && !e.empty? }
      return Bundler.ui.info("To open a bundled gem, set $EDITOR or $BUNDLER_EDITOR") unless editor
      return unless spec = Bundler::CLI::Common.select_spec(name, :regex_match)
      if spec.default_gem?
        Bundler.ui.info "Unable to open #{name} because it's a default gem, so the directory it would normally be installed to does not exist."
      else
        path = spec.full_gem_path
        Dir.chdir(path) do
          require "shellwords"
          command = Shellwords.split(editor) + [path]
          Bundler.with_original_env do
            system(*command)
          end || Bundler.ui.info("Could not run '#{command.join(" ")}'")
        end
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Init
    attr_reader :options
    def initialize(options)
      @options = options
    end

    def run
      if File.exist?(gemfile)
        Bundler.ui.error "#{gemfile} already exists at #{File.expand_path(gemfile)}"
        exit 1
      end

      unless File.writable?(Dir.pwd)
        Bundler.ui.error "Can not create #{gemfile} as the current directory is not writable."
        exit 1
      end

      if options[:gemspec]
        gemspec = File.expand_path(options[:gemspec])
        unless File.exist?(gemspec)
          Bundler.ui.error "Gem specification #{gemspec} doesn't exist"
          exit 1
        end

        spec = Bundler.load_gemspec_uncached(gemspec)

        File.open(gemfile, "wb") do |file|
          file << "# Generated from #{gemspec}\n"
          file << spec.to_gemfile
        end
      else
        FileUtils.cp(File.expand_path("../../templates/#{gemfile}", __FILE__), gemfile)
      end

      puts "Writing new #{gemfile} to #{SharedHelpers.pwd}/#{gemfile}"
    end

    private

    def gemfile
      @gemfile ||= Bundler.preferred_gemfile_name
    end
  end
end
# frozen_string_literal: true

require_relative "../current_ruby"

module Bundler
  class CLI::Exec
    attr_reader :options, :args, :cmd

    TRAPPED_SIGNALS = %w[INT].freeze

    def initialize(options, args)
      @options = options
      @cmd = args.shift
      @args = args
      @args << { :close_others => !options.keep_file_descriptors? } unless Bundler.current_ruby.jruby?
    end

    def run
      validate_cmd!
      SharedHelpers.set_bundle_environment
      if bin_path = Bundler.which(cmd)
        if !Bundler.settings[:disable_exec_load] && ruby_shebang?(bin_path)
          return kernel_load(bin_path, *args)
        end
        kernel_exec(bin_path, *args)
      else
        # exec using the given command
        kernel_exec(cmd, *args)
      end
    end

    private

    def validate_cmd!
      return unless cmd.nil?
      Bundler.ui.error "bundler: exec needs a command to run"
      exit 128
    end

    def kernel_exec(*args)
      Kernel.exec(*args)
    rescue Errno::EACCES, Errno::ENOEXEC
      Bundler.ui.error "bundler: not executable: #{cmd}"
      exit 126
    rescue Errno::ENOENT
      Bundler.ui.error "bundler: command not found: #{cmd}"
      Bundler.ui.warn "Install missing gem executables with `bundle install`"
      exit 127
    end

    def kernel_load(file, *args)
      args.pop if args.last.is_a?(Hash)
      ARGV.replace(args)
      $0 = file
      Process.setproctitle(process_title(file, args)) if Process.respond_to?(:setproctitle)
      require_relative "../setup"
      TRAPPED_SIGNALS.each {|s| trap(s, "DEFAULT") }
      Kernel.load(file)
    rescue SystemExit, SignalException
      raise
    rescue Exception # rubocop:disable Lint/RescueException
      Bundler.ui.error "bundler: failed to load command: #{cmd} (#{file})"
      Bundler::FriendlyErrors.disable!
      raise
    end

    def process_title(file, args)
      "#{file} #{args.join(" ")}".strip
    end

    def ruby_shebang?(file)
      possibilities = [
        "#!/opt/alt/ruby30/bin/ruby\n",
        "#!/usr/bin/env jruby\n",
        "#!/usr/bin/env truffleruby\n",
        "#!#{Gem.ruby}\n",
      ]

      if File.zero?(file)
        Bundler.ui.warn "#{file} is empty"
        return false
      end

      first_line = File.open(file, "rb") {|f| f.read(possibilities.map(&:size).max) }
      possibilities.any? {|shebang| first_line.start_with?(shebang) }
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Lock
    attr_reader :options

    def initialize(options)
      @options = options
    end

    def run
      unless Bundler.default_gemfile
        Bundler.ui.error "Unable to find a Gemfile to lock"
        exit 1
      end

      print = options[:print]
      ui = Bundler.ui
      Bundler.ui = UI::Silent.new if print

      Bundler::Fetcher.disable_endpoint = options["full-index"]

      update = options[:update]
      conservative = options[:conservative]

      if update.is_a?(Array) # unlocking specific gems
        Bundler::CLI::Common.ensure_all_gems_in_lockfile!(update)
        update = { :gems => update, :conservative => conservative }
      elsif update
        update = { :conservative => conservative } if conservative
      end
      definition = Bundler.definition(update)

      Bundler::CLI::Common.configure_gem_version_promoter(Bundler.definition, options) if options[:update]

      options["remove-platform"].each do |platform|
        definition.remove_platform(platform)
      end

      options["add-platform"].each do |platform_string|
        platform = Gem::Platform.new(platform_string)
        if platform.to_s == "unknown"
          Bundler.ui.warn "The platform `#{platform_string}` is unknown to RubyGems " \
            "and adding it will likely lead to resolution errors"
        end
        definition.add_platform(platform)
      end

      if definition.platforms.empty?
        raise InvalidOption, "Removing all platforms from the bundle is not allowed"
      end

      definition.resolve_remotely! unless options[:local]

      if print
        puts definition.to_lock
      else
        file = options[:lockfile]
        file = file ? File.expand_path(file) : Bundler.default_lockfile
        puts "Writing lockfile to #{file}"
        definition.lock(file)
      end

      Bundler.ui = ui
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Console
    attr_reader :options, :group
    def initialize(options, group)
      @options = options
      @group = group
    end

    def run
      Bundler::SharedHelpers.major_deprecation 2, "bundle console will be replaced " \
                           "by `bin/console` generated by `bundle gem <name>`"

      group ? Bundler.require(:default, *group.split(" ").map!(&:to_sym)) : Bundler.require
      ARGV.clear

      console = get_console(Bundler.settings[:console] || "irb")
      console.start
    end

    def get_console(name)
      require name
      get_constant(name)
    rescue LoadError
      Bundler.ui.error "Couldn't load console #{name}, falling back to irb"
      require "irb"
      get_constant("irb")
    end

    def get_constant(name)
      const_name = {
        "pry"  => :Pry,
        "ripl" => :Ripl,
        "irb"  => :IRB,
      }[name]
      Object.const_get(const_name)
    rescue NameError
      Bundler.ui.error "Could not find constant #{const_name}"
      exit 1
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Check
    attr_reader :options

    def initialize(options)
      @options = options
    end

    def run
      Bundler.settings.set_command_option_if_given :path, options[:path]

      definition = Bundler.definition
      definition.validate_runtime!

      begin
        definition.resolve_only_locally!
        not_installed = definition.missing_specs
      rescue GemNotFound, VersionConflict
        Bundler.ui.error "Bundler can't satisfy your Gemfile's dependencies."
        Bundler.ui.warn "Install missing gems with `bundle install`."
        exit 1
      end

      if not_installed.any?
        Bundler.ui.error "The following gems are missing"
        not_installed.each {|s| Bundler.ui.error " * #{s.name} (#{s.version})" }
        Bundler.ui.warn "Install missing gems with `bundle install`"
        exit 1
      elsif !Bundler.default_lockfile.file? && Bundler.frozen_bundle?
        Bundler.ui.error "This bundle has been frozen, but there is no #{Bundler.default_lockfile.relative_path_from(SharedHelpers.pwd)} present"
        exit 1
      else
        Bundler.load.lock(:preserve_unknown_sections => true) unless options[:"dry-run"]
        Bundler.ui.info "The Gemfile's dependencies are satisfied"
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::List
    def initialize(options)
      @options = options
      @without_group = options["without-group"].map(&:to_sym)
      @only_group = options["only-group"].map(&:to_sym)
    end

    def run
      raise InvalidOption, "The `--only-group` and `--without-group` options cannot be used together" if @only_group.any? && @without_group.any?

      raise InvalidOption, "The `--name-only` and `--paths` options cannot be used together" if @options["name-only"] && @options[:paths]

      specs = if @only_group.any? || @without_group.any?
        filtered_specs_by_groups
      else
        begin
          Bundler.load.specs
        rescue GemNotFound => e
          Bundler.ui.error e.message
          Bundler.ui.warn "Install missing gems with `bundle install`."
          exit 1
        end
      end.reject {|s| s.name == "bundler" }.sort_by(&:name)

      return Bundler.ui.info "No gems in the Gemfile" if specs.empty?

      return specs.each {|s| Bundler.ui.info s.name } if @options["name-only"]
      return specs.each {|s| Bundler.ui.info s.full_gem_path } if @options["paths"]

      Bundler.ui.info "Gems included by the bundle:"

      specs.each {|s| Bundler.ui.info "  * #{s.name} (#{s.version}#{s.git_version})" }

      Bundler.ui.info "Use `bundle info` to print more detailed information about a gem"
    end

    private

    def verify_group_exists(groups)
      (@without_group + @only_group).each do |group|
        raise InvalidOption, "`#{group}` group could not be found." unless groups.include?(group)
      end
    end

    def filtered_specs_by_groups
      definition = Bundler.definition
      groups = definition.groups

      verify_group_exists(groups)

      show_groups =
        if @without_group.any?
          groups.reject {|g| @without_group.include?(g) }
        elsif @only_group.any?
          groups.select {|g| @only_group.include?(g) }
        else
          groups
        end.map(&:to_sym)

      definition.specs_for(show_groups)
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Viz
    attr_reader :options, :gem_name
    def initialize(options)
      @options = options
    end

    def run
      # make sure we get the right `graphviz`. There is also a `graphviz`
      # gem we're not built to support
      gem "ruby-graphviz"
      require "graphviz"

      options[:without] = options[:without].join(":").tr(" ", ":").split(":")
      output_file = File.expand_path(options[:file])

      graph = Graph.new(Bundler.load, output_file, options[:version], options[:requirements], options[:format], options[:without])
      graph.viz
    rescue LoadError => e
      Bundler.ui.error e.inspect
      Bundler.ui.warn "Make sure you have the graphviz ruby gem. You can install it with:"
      Bundler.ui.warn "`gem install ruby-graphviz`"
    rescue StandardError => e
      raise unless e.message =~ /GraphViz not installed or dot not in PATH/
      Bundler.ui.error e.message
      Bundler.ui.warn "Please install GraphViz. On a Mac with Homebrew, you can run `brew install graphviz`."
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Info
    attr_reader :gem_name, :options
    def initialize(options, gem_name)
      @options = options
      @gem_name = gem_name
    end

    def run
      Bundler.ui.silence do
        Bundler.definition.validate_runtime!
        Bundler.load.lock
      end

      spec = spec_for_gem(gem_name)

      if spec
        return print_gem_path(spec) if @options[:path]
        return print_gem_version(spec) if @options[:version]
        print_gem_info(spec)
      end
    end

    private

    def spec_for_gem(gem_name)
      spec = Bundler.definition.specs.find {|s| s.name == gem_name }
      spec || default_gem_spec(gem_name) || Bundler::CLI::Common.select_spec(gem_name, :regex_match)
    end

    def default_gem_spec(gem_name)
      return unless Gem::Specification.respond_to?(:find_all_by_name)
      gem_spec = Gem::Specification.find_all_by_name(gem_name).last
      return gem_spec if gem_spec && gem_spec.respond_to?(:default_gem?) && gem_spec.default_gem?
    end

    def spec_not_found(gem_name)
      raise GemNotFound, Bundler::CLI::Common.gem_not_found_message(gem_name, Bundler.definition.dependencies)
    end

    def print_gem_version(spec)
      Bundler.ui.info spec.version.to_s
    end

    def print_gem_path(spec)
      name = spec.name
      if name == "bundler"
        path = File.expand_path("../../../..", __FILE__)
      else
        path = spec.full_gem_path
        if spec.deleted_gem?
          return Bundler.ui.warn "The gem #{name} has been deleted. It was installed at: #{path}"
        end
      end

      Bundler.ui.info path
    end

    def print_gem_info(spec)
      metadata = spec.metadata
      name = spec.name
      gem_info = String.new
      gem_info << "  * #{name} (#{spec.version}#{spec.git_version})\n"
      gem_info << "\tSummary: #{spec.summary}\n" if spec.summary
      gem_info << "\tHomepage: #{spec.homepage}\n" if spec.homepage
      gem_info << "\tDocumentation: #{metadata["documentation_uri"]}\n" if metadata.key?("documentation_uri")
      gem_info << "\tSource Code: #{metadata["source_code_uri"]}\n" if metadata.key?("source_code_uri")
      gem_info << "\tFunding: #{metadata["funding_uri"]}\n" if metadata.key?("funding_uri")
      gem_info << "\tWiki: #{metadata["wiki_uri"]}\n" if metadata.key?("wiki_uri")
      gem_info << "\tChangelog: #{metadata["changelog_uri"]}\n" if metadata.key?("changelog_uri")
      gem_info << "\tBug Tracker: #{metadata["bug_tracker_uri"]}\n" if metadata.key?("bug_tracker_uri")
      gem_info << "\tMailing List: #{metadata["mailing_list_uri"]}\n" if metadata.key?("mailing_list_uri")
      gem_info << "\tPath: #{spec.full_gem_path}\n"
      gem_info << "\tDefault Gem: yes" if spec.respond_to?(:default_gem?) && spec.default_gem?

      if name != "bundler" && spec.deleted_gem?
        return Bundler.ui.warn "The gem #{name} has been deleted. Gemspec information is still available though:\n#{gem_info}"
      end

      Bundler.ui.info gem_info
    end
  end
end
# frozen_string_literal: true

module Bundler
  module CLI::Common
    def self.output_post_install_messages(messages)
      return if Bundler.settings["ignore_messages"]
      messages.to_a.each do |name, msg|
        print_post_install_message(name, msg) unless Bundler.settings["ignore_messages.#{name}"]
      end
    end

    def self.print_post_install_message(name, msg)
      Bundler.ui.confirm "Post-install message from #{name}:"
      Bundler.ui.info msg
    end

    def self.output_fund_metadata_summary
      definition = Bundler.definition
      current_dependencies = definition.requested_dependencies
      current_specs = definition.specs

      count = current_dependencies.count {|dep| current_specs[dep.name].first.metadata.key?("funding_uri") }

      return if count.zero?

      intro = count > 1 ? "#{count} installed gems you directly depend on are" : "#{count} installed gem you directly depend on is"
      message = "#{intro} looking for funding.\n  Run `bundle fund` for details"
      Bundler.ui.info message
    end

    def self.output_without_groups_message(command)
      return if Bundler.settings[:without].empty?
      Bundler.ui.confirm without_groups_message(command)
    end

    def self.without_groups_message(command)
      command_in_past_tense = command == :install ? "installed" : "updated"
      groups = Bundler.settings[:without]
      "Gems in the #{verbalize_groups(groups)} were not #{command_in_past_tense}."
    end

    def self.verbalize_groups(groups)
      groups.map!{|g| "'#{g}'" }
      group_list = [groups[0...-1].join(", "), groups[-1..-1]].
        reject {|s| s.to_s.empty? }.join(" and ")
      group_str = groups.size == 1 ? "group" : "groups"
      "#{group_str} #{group_list}"
    end

    def self.select_spec(name, regex_match = nil)
      specs = []
      regexp = Regexp.new(name) if regex_match

      Bundler.definition.specs.each do |spec|
        return spec if spec.name == name
        specs << spec if regexp && spec.name =~ regexp
      end

      case specs.count
      when 0
        dep_in_other_group = Bundler.definition.current_dependencies.find {|dep|dep.name == name }

        if dep_in_other_group
          raise GemNotFound, "Could not find gem '#{name}', because it's in the #{verbalize_groups(dep_in_other_group.groups)}, configured to be ignored."
        else
          raise GemNotFound, gem_not_found_message(name, Bundler.definition.dependencies)
        end
      when 1
        specs.first
      else
        ask_for_spec_from(specs)
      end
    rescue RegexpError
      raise GemNotFound, gem_not_found_message(name, Bundler.definition.dependencies)
    end

    def self.ask_for_spec_from(specs)
      specs.each_with_index do |spec, index|
        Bundler.ui.info "#{index.succ} : #{spec.name}", true
      end
      Bundler.ui.info "0 : - exit -", true

      num = Bundler.ui.ask("> ").to_i
      num > 0 ? specs[num - 1] : nil
    end

    def self.gem_not_found_message(missing_gem_name, alternatives)
      require_relative "../similarity_detector"
      message = "Could not find gem '#{missing_gem_name}'."
      alternate_names = alternatives.map {|a| a.respond_to?(:name) ? a.name : a }
      suggestions = SimilarityDetector.new(alternate_names).similar_word_list(missing_gem_name)
      message += "\nDid you mean #{suggestions}?" if suggestions
      message
    end

    def self.ensure_all_gems_in_lockfile!(names, locked_gems = Bundler.locked_gems)
      return unless locked_gems

      locked_names = locked_gems.specs.map(&:name).uniq
      names.-(locked_names).each do |g|
        raise GemNotFound, gem_not_found_message(g, locked_names)
      end
    end

    def self.configure_gem_version_promoter(definition, options)
      patch_level = patch_level_options(options)
      patch_level << :patch if patch_level.empty? && Bundler.settings[:prefer_patch]
      raise InvalidOption, "Provide only one of the following options: #{patch_level.join(", ")}" unless patch_level.length <= 1

      definition.gem_version_promoter.tap do |gvp|
        gvp.level = patch_level.first || :major
        gvp.strict = options[:strict] || options["update-strict"] || options["filter-strict"]
      end
    end

    def self.patch_level_options(options)
      [:major, :minor, :patch].select {|v| options.keys.include?(v.to_s) }
    end

    def self.clean_after_install?
      clean = Bundler.settings[:clean]
      return clean unless clean.nil?
      clean ||= Bundler.feature_flag.auto_clean_without_path? && Bundler.settings[:path].nil?
      clean &&= !Bundler.use_system_gems?
      clean
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Remove
    def initialize(gems, options)
      @gems = gems
      @options = options
    end

    def run
      raise InvalidOption, "Please specify gems to remove." if @gems.empty?

      Injector.remove(@gems, {})
      Installer.install(Bundler.root, Bundler.definition)
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Update
    attr_reader :options, :gems
    def initialize(options, gems)
      @options = options
      @gems = gems
    end

    def run
      Bundler.ui.level = "warn" if options[:quiet]

      Plugin.gemfile_install(Bundler.default_gemfile) if Bundler.feature_flag.plugins?

      sources = Array(options[:source])
      groups  = Array(options[:group]).map(&:to_sym)

      full_update = gems.empty? && sources.empty? && groups.empty? && !options[:ruby] && !options[:bundler]

      if full_update && !options[:all]
        if Bundler.feature_flag.update_requires_all_flag?
          raise InvalidOption, "To update everything, pass the `--all` flag."
        end
        SharedHelpers.major_deprecation 3, "Pass --all to `bundle update` to update everything"
      elsif !full_update && options[:all]
        raise InvalidOption, "Cannot specify --all along with specific options."
      end

      conservative = options[:conservative]

      if full_update
        if conservative
          Bundler.definition(:conservative => conservative)
        else
          Bundler.definition(true)
        end
      else
        unless Bundler.default_lockfile.exist?
          raise GemfileLockNotFound, "This Bundle hasn't been installed yet. " \
            "Run `bundle install` to update and install the bundled gems."
        end
        Bundler::CLI::Common.ensure_all_gems_in_lockfile!(gems)

        if groups.any?
          deps = Bundler.definition.dependencies.select {|d| (d.groups & groups).any? }
          gems.concat(deps.map(&:name))
        end

        Bundler.definition(:gems => gems, :sources => sources, :ruby => options[:ruby],
                           :conservative => conservative,
                           :bundler => options[:bundler])
      end

      Bundler::CLI::Common.configure_gem_version_promoter(Bundler.definition, options)

      Bundler::Fetcher.disable_endpoint = options["full-index"]

      opts = options.dup
      opts["update"] = true
      opts["local"] = options[:local]

      Bundler.settings.set_command_option_if_given :jobs, opts["jobs"]

      Bundler.definition.validate_runtime!

      if locked_gems = Bundler.definition.locked_gems
        previous_locked_info = locked_gems.specs.reduce({}) do |h, s|
          h[s.name] = { :spec => s, :version => s.version, :source => s.source.identifier }
          h
        end
      end

      installer = Installer.install Bundler.root, Bundler.definition, opts
      Bundler.load.cache if Bundler.app_cache.exist?

      if CLI::Common.clean_after_install?
        require_relative "clean"
        Bundler::CLI::Clean.new(options).run
      end

      if locked_gems
        gems.each do |name|
          locked_info = previous_locked_info[name]
          next unless locked_info

          locked_spec = locked_info[:spec]
          new_spec = Bundler.definition.specs[name].first
          unless new_spec
            unless locked_spec.match_platform(Bundler.local_platform)
              Bundler.ui.warn "Bundler attempted to update #{name} but it was not considered because it is for a different platform from the current one"
            end

            next
          end

          locked_source = locked_info[:source]
          new_source = new_spec.source.identifier
          next if locked_source != new_source

          new_version = new_spec.version
          locked_version = locked_info[:version]
          if new_version < locked_version
            Bundler.ui.warn "Note: #{name} version regressed from #{locked_version} to #{new_version}"
          elsif new_version == locked_version
            Bundler.ui.warn "Bundler attempted to update #{name} but its version stayed the same"
          end
        end
      end

      Bundler.ui.confirm "Bundle updated!"
      Bundler::CLI::Common.output_without_groups_message(:update)
      Bundler::CLI::Common.output_post_install_messages installer.post_install_messages

      Bundler::CLI::Common.output_fund_metadata_summary
    end
  end
end
# frozen_string_literal: true

require_relative "../vendored_thor"
module Bundler
  class CLI::Plugin < Thor
    desc "install PLUGINS", "Install the plugin from the source"
    long_desc <<-D
      Install plugins either from the rubygems source provided (with --source option) or from a git source provided with --git (for remote repos) or --local_git (for local repos). If no sources are provided, it uses Gem.sources
   D
    method_option "source", :type => :string, :default => nil, :banner =>
      "URL of the RubyGems source to fetch the plugin from"
    method_option "version", :type => :string, :default => nil, :banner =>
      "The version of the plugin to fetch"
    method_option "git", :type => :string, :default => nil, :banner =>
      "URL of the git repo to fetch from"
    method_option "local_git", :type => :string, :default => nil, :banner =>
      "Path of the local git repo to fetch from"
    method_option "branch", :type => :string, :default => nil, :banner =>
      "The git branch to checkout"
    method_option "ref", :type => :string, :default => nil, :banner =>
      "The git revision to check out"
    def install(*plugins)
      Bundler::Plugin.install(plugins, options)
    end

    desc "uninstall PLUGINS", "Uninstall the plugins"
    long_desc <<-D
      Uninstall given list of plugins. To uninstall all the plugins, use -all option.
    D
    method_option "all", :type => :boolean, :default => nil, :banner =>
      "Uninstall all the installed plugins. If no plugin is installed, then it does nothing."
    def uninstall(*plugins)
      Bundler::Plugin.uninstall(plugins, options)
    end

    desc "list", "List the installed plugins and available commands"
    def list
      Bundler::Plugin.list
    end
  end
end
# frozen_string_literal: true

require "rbconfig"

module Bundler
  class CLI::Issue
    def run
      Bundler.ui.info <<-EOS.gsub(/^ {8}/, "")
        Did you find an issue with Bundler? Before filing a new issue,
        be sure to check out these resources:

        1. Check out our troubleshooting guide for quick fixes to common issues:
        https://github.com/rubygems/rubygems/blob/master/bundler/doc/TROUBLESHOOTING.md

        2. Instructions for common Bundler uses can be found on the documentation
        site: https://bundler.io/

        3. Information about each Bundler command can be found in the Bundler
        man pages: https://bundler.io/man/bundle.1.html

        Hopefully the troubleshooting steps above resolved your problem!  If things
        still aren't working the way you expect them to, please let us know so
        that we can diagnose and help fix the problem you're having, by filling
        in the new issue form located at
        https://github.com/rubygems/rubygems/issues/new?labels=Bundler&template=bundler-related-issue.md,
        and copy and pasting the information below.

      EOS

      Bundler.ui.info Bundler::Env.report

      Bundler.ui.info "\n## Bundle Doctor"
      doctor
    end

    def doctor
      require_relative "doctor"
      Bundler::CLI::Doctor.new({}).run
    end
  end
end
# frozen_string_literal: true

require "rbconfig"
require "shellwords"

module Bundler
  class CLI::Doctor
    DARWIN_REGEX = /\s+(.+) \(compatibility /.freeze
    LDD_REGEX = /\t\S+ => (\S+) \(\S+\)/.freeze

    attr_reader :options

    def initialize(options)
      @options = options
    end

    def otool_available?
      Bundler.which("otool")
    end

    def ldd_available?
      Bundler.which("ldd")
    end

    def dylibs_darwin(path)
      output = `/usr/bin/otool -L #{path.shellescape}`.chomp
      dylibs = output.split("\n")[1..-1].map {|l| l.match(DARWIN_REGEX).captures[0] }.uniq
      # ignore @rpath and friends
      dylibs.reject {|dylib| dylib.start_with? "@" }
    end

    def dylibs_ldd(path)
      output = `/usr/bin/ldd #{path.shellescape}`.chomp
      output.split("\n").map do |l|
        match = l.match(LDD_REGEX)
        next if match.nil?
        match.captures[0]
      end.compact
    end

    def dylibs(path)
      case RbConfig::CONFIG["host_os"]
      when /darwin/
        return [] unless otool_available?
        dylibs_darwin(path)
      when /(linux|solaris|bsd)/
        return [] unless ldd_available?
        dylibs_ldd(path)
      else # Windows, etc.
        Bundler.ui.warn("Dynamic library check not supported on this platform.")
        []
      end
    end

    def bundles_for_gem(spec)
      Dir.glob("#{spec.full_gem_path}/**/*.bundle")
    end

    def check!
      require_relative "check"
      Bundler::CLI::Check.new({}).run
    end

    def run
      Bundler.ui.level = "warn" if options[:quiet]
      Bundler.settings.validate!
      check!

      definition = Bundler.definition
      broken_links = {}

      definition.specs.each do |spec|
        bundles_for_gem(spec).each do |bundle|
          bad_paths = dylibs(bundle).select {|f| !File.exist?(f) }
          if bad_paths.any?
            broken_links[spec] ||= []
            broken_links[spec].concat(bad_paths)
          end
        end
      end

      permissions_valid = check_home_permissions

      if broken_links.any?
        message = "The following gems are missing OS dependencies:"
        broken_links.map do |spec, paths|
          paths.uniq.map do |path|
            "\n * #{spec.name}: #{path}"
          end
        end.flatten.sort.each {|m| message += m }
        raise ProductionError, message
      elsif !permissions_valid
        Bundler.ui.info "No issues found with the installed bundle"
      end
    end

    private

    def check_home_permissions
      require "find"
      files_not_readable_or_writable = []
      files_not_rw_and_owned_by_different_user = []
      files_not_owned_by_current_user_but_still_rw = []
      broken_symlinks = []
      Find.find(Bundler.bundle_path.to_s).each do |f|
        if !File.exist?(f)
          broken_symlinks << f
        elsif !File.writable?(f) || !File.readable?(f)
          if File.stat(f).uid != Process.uid
            files_not_rw_and_owned_by_different_user << f
          else
            files_not_readable_or_writable << f
          end
        elsif File.stat(f).uid != Process.uid
          files_not_owned_by_current_user_but_still_rw << f
        end
      end

      ok = true

      if broken_symlinks.any?
        Bundler.ui.warn "Broken links exist in the Bundler home. Please report them to the offending gem's upstream repo. These files are:\n - #{broken_symlinks.join("\n - ")}"

        ok = false
      end

      if files_not_owned_by_current_user_but_still_rw.any?
        Bundler.ui.warn "Files exist in the Bundler home that are owned by another " \
          "user, but are still readable/writable. These files are:\n - #{files_not_owned_by_current_user_but_still_rw.join("\n - ")}"

        ok = false
      end

      if files_not_rw_and_owned_by_different_user.any?
        Bundler.ui.warn "Files exist in the Bundler home that are owned by another " \
          "user, and are not readable/writable. These files are:\n - #{files_not_rw_and_owned_by_different_user.join("\n - ")}"

        ok = false
      end

      if files_not_readable_or_writable.any?
        Bundler.ui.warn "Files exist in the Bundler home that are not " \
          "readable/writable by the current user. These files are:\n - #{files_not_readable_or_writable.join("\n - ")}"

        ok = false
      end

      ok
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Cache
    attr_reader :options

    def initialize(options)
      @options = options
    end

    def run
      Bundler.ui.level = "warn" if options[:quiet]
      Bundler.settings.set_command_option_if_given :path, options[:path]
      Bundler.settings.set_command_option_if_given :cache_path, options["cache-path"]

      setup_cache_all
      install

      # TODO: move cache contents here now that all bundles are locked
      custom_path = Bundler.settings[:path] if options[:path]

      Bundler.settings.temporary(:cache_all_platforms => options["all-platforms"]) do
        Bundler.load.cache(custom_path)
      end
    end

    private

    def install
      require_relative "install"
      options = self.options.dup
      options["local"] = false if Bundler.settings[:cache_all_platforms]
      options["no-cache"] = true
      Bundler::CLI::Install.new(options).run
    end

    def setup_cache_all
      all = options.fetch(:all, Bundler.feature_flag.cache_all? || nil)

      Bundler.settings.set_command_option_if_given :cache_all, all
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Install
    attr_reader :options
    def initialize(options)
      @options = options
    end

    def run
      Bundler.ui.level = "warn" if options[:quiet]

      warn_if_root

      Bundler::SharedHelpers.set_env "RB_USER_INSTALL", "1" if Bundler::FREEBSD

      # Disable color in deployment mode
      Bundler.ui.shell = Thor::Shell::Basic.new if options[:deployment]

      check_for_options_conflicts

      check_trust_policy

      if options[:deployment] || options[:frozen] || Bundler.frozen_bundle?
        unless Bundler.default_lockfile.exist?
          flag   = "--deployment flag" if options[:deployment]
          flag ||= "--frozen flag"     if options[:frozen]
          flag ||= "deployment setting"
          raise ProductionError, "The #{flag} requires a #{Bundler.default_lockfile.relative_path_from(SharedHelpers.pwd)}. Please make " \
                                 "sure you have checked your #{Bundler.default_lockfile.relative_path_from(SharedHelpers.pwd)} into version control " \
                                 "before deploying."
        end

        options[:local] = true if Bundler.app_cache.exist?

        Bundler.settings.set_command_option :deployment, true if options[:deployment]
        Bundler.settings.set_command_option :frozen, true if options[:frozen]
      end

      # When install is called with --no-deployment, disable deployment mode
      if options[:deployment] == false
        Bundler.settings.set_command_option :frozen, nil
        options[:system] = true
      end

      normalize_settings

      Bundler::Fetcher.disable_endpoint = options["full-index"]

      if options["binstubs"]
        Bundler::SharedHelpers.major_deprecation 2,
          "The --binstubs option will be removed in favor of `bundle binstubs --all`"
      end

      Plugin.gemfile_install(Bundler.default_gemfile) if Bundler.feature_flag.plugins?

      definition = Bundler.definition
      definition.validate_runtime!

      installer = Installer.install(Bundler.root, definition, options)

      Bundler.settings.temporary(:cache_all_platforms => options[:local] ? false : Bundler.settings[:cache_all_platforms]) do
        Bundler.load.cache(nil, options[:local]) if Bundler.app_cache.exist? && !options["no-cache"] && !Bundler.frozen_bundle?
      end

      Bundler.ui.confirm "Bundle complete! #{dependencies_count_for(definition)}, #{gems_installed_for(definition)}."
      Bundler::CLI::Common.output_without_groups_message(:install)

      if Bundler.use_system_gems?
        Bundler.ui.confirm "Use `bundle info [gemname]` to see where a bundled gem is installed."
      else
        relative_path = Bundler.configured_bundle_path.base_path_relative_to_pwd
        Bundler.ui.confirm "Bundled gems are installed into `#{relative_path}`"
      end

      Bundler::CLI::Common.output_post_install_messages installer.post_install_messages

      warn_ambiguous_gems

      if CLI::Common.clean_after_install?
        require_relative "clean"
        Bundler::CLI::Clean.new(options).run
      end

      Bundler::CLI::Common.output_fund_metadata_summary
    rescue Gem::InvalidSpecificationException
      Bundler.ui.warn "You have one or more invalid gemspecs that need to be fixed."
      raise
    end

    private

    def warn_if_root
      return if Bundler.settings[:silence_root_warning] || Gem.win_platform? || !Process.uid.zero?
      Bundler.ui.warn "Don't run Bundler as root. Bundler can ask for sudo " \
        "if it is needed, and installing your bundle as root will break this " \
        "application for all non-root users on this machine.", :wrap => true
    end

    def dependencies_count_for(definition)
      count = definition.dependencies.count
      "#{count} Gemfile #{count == 1 ? "dependency" : "dependencies"}"
    end

    def gems_installed_for(definition)
      count = definition.specs.count
      "#{count} #{count == 1 ? "gem" : "gems"} now installed"
    end

    def check_for_group_conflicts_in_cli_options
      conflicting_groups = Array(options[:without]) & Array(options[:with])
      return if conflicting_groups.empty?
      raise InvalidOption, "You can't list a group in both with and without." \
        " The offending groups are: #{conflicting_groups.join(", ")}."
    end

    def check_for_options_conflicts
      if (options[:path] || options[:deployment]) && options[:system]
        error_message = String.new
        error_message << "You have specified both --path as well as --system. Please choose only one option.\n" if options[:path]
        error_message << "You have specified both --deployment as well as --system. Please choose only one option.\n" if options[:deployment]
        raise InvalidOption.new(error_message)
      end
    end

    def check_trust_policy
      trust_policy = options["trust-policy"]
      unless Bundler.rubygems.security_policies.keys.unshift(nil).include?(trust_policy)
        raise InvalidOption, "RubyGems doesn't know about trust policy '#{trust_policy}'. " \
          "The known policies are: #{Bundler.rubygems.security_policies.keys.join(", ")}."
      end
      Bundler.settings.set_command_option_if_given :"trust-policy", trust_policy
    end

    def normalize_groups
      options[:with] &&= options[:with].join(":").tr(" ", ":").split(":")
      options[:without] &&= options[:without].join(":").tr(" ", ":").split(":")

      check_for_group_conflicts_in_cli_options

      Bundler.settings.set_command_option :with, nil if options[:with] == []
      Bundler.settings.set_command_option :without, nil if options[:without] == []

      with = options.fetch(:with, [])
      with |= Bundler.settings[:with].map(&:to_s)
      with -= options[:without] if options[:without]

      without = options.fetch(:without, [])
      without |= Bundler.settings[:without].map(&:to_s)
      without -= options[:with] if options[:with]

      options[:with]    = with
      options[:without] = without

      unless Bundler.settings[:without] == options[:without] && Bundler.settings[:with] == options[:with]
        # need to nil them out first to get around validation for backwards compatibility
        Bundler.settings.set_command_option :without, nil
        Bundler.settings.set_command_option :with,    nil
        Bundler.settings.set_command_option :without, options[:without] - options[:with]
        Bundler.settings.set_command_option :with,    options[:with]
      end
    end

    def normalize_settings
      Bundler.settings.set_command_option :path, nil if options[:system]
      Bundler.settings.temporary(:path_relative_to_cwd => false) do
        Bundler.settings.set_command_option :path, "vendor/bundle" if Bundler.settings[:deployment] && Bundler.settings[:path].nil?
      end
      Bundler.settings.set_command_option_if_given :path, options[:path]
      Bundler.settings.temporary(:path_relative_to_cwd => false) do
        Bundler.settings.set_command_option :path, "bundle" if options["standalone"] && Bundler.settings[:path].nil?
      end

      bin_option = options["binstubs"]
      bin_option = nil if bin_option && bin_option.empty?
      Bundler.settings.set_command_option :bin, bin_option if options["binstubs"]

      Bundler.settings.set_command_option_if_given :shebang, options["shebang"]

      Bundler.settings.set_command_option_if_given :jobs, options["jobs"]

      Bundler.settings.set_command_option_if_given :no_prune, options["no-prune"]

      Bundler.settings.set_command_option_if_given :no_install, options["no-install"]

      Bundler.settings.set_command_option_if_given :clean, options["clean"]

      normalize_groups

      options[:force] = options[:redownload]
    end

    def warn_ambiguous_gems
      # TODO: remove this when we drop Bundler 1.x support
      Installer.ambiguous_gems.to_a.each do |name, installed_from_uri, *also_found_in_uris|
        Bundler.ui.warn "Warning: the gem '#{name}' was found in multiple sources."
        Bundler.ui.warn "Installed from: #{installed_from_uri}"
        Bundler.ui.warn "Also found in:"
        also_found_in_uris.each {|uri| Bundler.ui.warn "  * #{uri}" }
        Bundler.ui.warn "You should add a source requirement to restrict this gem to your preferred source."
        Bundler.ui.warn "For example:"
        Bundler.ui.warn "    gem '#{name}', :source => '#{installed_from_uri}'"
        Bundler.ui.warn "Then uninstall the gem '#{name}' (or delete all bundled gems) and then install again."
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Clean
    attr_reader :options

    def initialize(options)
      @options = options
    end

    def run
      require_path_or_force unless options[:"dry-run"]
      Bundler.load.clean(options[:"dry-run"])
    end

    protected

    def require_path_or_force
      return unless Bundler.use_system_gems? && !options[:force]
      raise InvalidOption, "Cleaning all the gems on your system is dangerous! " \
        "If you're sure you want to remove every system gem not in this " \
        "bundle, run `bundle clean --force`."
    end
  end
end
# frozen_string_literal: true

require "pathname"

module Bundler
  class CLI
    Bundler.require_thor_actions
    include Thor::Actions
  end

  class CLI::Gem
    TEST_FRAMEWORK_VERSIONS = {
      "rspec" => "3.0",
      "minitest" => "5.0",
      "test-unit" => "3.0",
    }.freeze

    attr_reader :options, :gem_name, :thor, :name, :target

    def initialize(options, gem_name, thor)
      @options = options
      @gem_name = resolve_name(gem_name)

      @thor = thor
      thor.behavior = :invoke
      thor.destination_root = nil

      @name = @gem_name
      @target = SharedHelpers.pwd.join(gem_name)

      validate_ext_name if options[:ext]
    end

    def run
      Bundler.ui.confirm "Creating gem '#{name}'..."

      underscored_name = name.tr("-", "_")
      namespaced_path = name.tr("-", "/")
      constant_name = name.gsub(/-[_-]*(?![_-]|$)/) { "::" }.gsub(/([_-]+|(::)|^)(.|$)/) { $2.to_s + $3.upcase }
      constant_array = constant_name.split("::")

      use_git = Bundler.git_present? && options[:git]

      git_author_name = use_git ? `git config user.name`.chomp : ""
      git_username = use_git ? `git config github.user`.chomp : ""
      git_user_email = use_git ? `git config user.email`.chomp : ""

      github_username = if options[:github_username].nil?
        git_username
      elsif options[:github_username] == false
        ""
      else
        options[:github_username]
      end

      config = {
        :name             => name,
        :underscored_name => underscored_name,
        :namespaced_path  => namespaced_path,
        :makefile_path    => "#{underscored_name}/#{underscored_name}",
        :constant_name    => constant_name,
        :constant_array   => constant_array,
        :author           => git_author_name.empty? ? "TODO: Write your name" : git_author_name,
        :email            => git_user_email.empty? ? "TODO: Write your email address" : git_user_email,
        :test             => options[:test],
        :ext              => options[:ext],
        :exe              => options[:exe],
        :bundler_version  => bundler_dependency_version,
        :git              => use_git,
        :github_username  => github_username.empty? ? "[USERNAME]" : github_username,
        :required_ruby_version => required_ruby_version,
      }
      ensure_safe_gem_name(name, constant_array)

      templates = {
        "#{Bundler.preferred_gemfile_name}.tt" => Bundler.preferred_gemfile_name,
        "lib/newgem.rb.tt" => "lib/#{namespaced_path}.rb",
        "lib/newgem/version.rb.tt" => "lib/#{namespaced_path}/version.rb",
        "sig/newgem.rbs.tt" => "sig/#{namespaced_path}.rbs",
        "newgem.gemspec.tt" => "#{name}.gemspec",
        "Rakefile.tt" => "Rakefile",
        "README.md.tt" => "README.md",
        "bin/console.tt" => "bin/console",
        "bin/setup.tt" => "bin/setup",
      }

      executables = %w[
        bin/console
        bin/setup
      ]

      templates.merge!("gitignore.tt" => ".gitignore") if use_git

      if test_framework = ask_and_set_test_framework
        config[:test] = test_framework
        config[:test_framework_version] = TEST_FRAMEWORK_VERSIONS[test_framework]

        case test_framework
        when "rspec"
          templates.merge!(
            "rspec.tt" => ".rspec",
            "spec/spec_helper.rb.tt" => "spec/spec_helper.rb",
            "spec/newgem_spec.rb.tt" => "spec/#{namespaced_path}_spec.rb"
          )
          config[:test_task] = :spec
        when "minitest"
          templates.merge!(
            "test/minitest/test_helper.rb.tt" => "test/test_helper.rb",
            "test/minitest/newgem_test.rb.tt" => "test/#{namespaced_path}_test.rb"
          )
          config[:test_task] = :test
        when "test-unit"
          templates.merge!(
            "test/test-unit/test_helper.rb.tt" => "test/test_helper.rb",
            "test/test-unit/newgem_test.rb.tt" => "test/#{namespaced_path}_test.rb"
          )
          config[:test_task] = :test
        end
      end

      config[:ci] = ask_and_set_ci
      case config[:ci]
      when "github"
        templates.merge!("github/workflows/main.yml.tt" => ".github/workflows/main.yml")
      when "travis"
        templates.merge!("travis.yml.tt" => ".travis.yml")
      when "gitlab"
        templates.merge!("gitlab-ci.yml.tt" => ".gitlab-ci.yml")
      when "circle"
        templates.merge!("circleci/config.yml.tt" => ".circleci/config.yml")
      end

      if ask_and_set(:mit, "Do you want to license your code permissively under the MIT license?",
        "This means that any other developer or company will be legally allowed to use your code " \
        "for free as long as they admit you created it. You can read more about the MIT license " \
        "at https://choosealicense.com/licenses/mit.")
        config[:mit] = true
        Bundler.ui.info "MIT License enabled in config"
        templates.merge!("LICENSE.txt.tt" => "LICENSE.txt")
      end

      if ask_and_set(:coc, "Do you want to include a code of conduct in gems you generate?",
        "Codes of conduct can increase contributions to your project by contributors who " \
        "prefer collaborative, safe spaces. You can read more about the code of conduct at " \
        "contributor-covenant.org. Having a code of conduct means agreeing to the responsibility " \
        "of enforcing it, so be sure that you are prepared to do that. Be sure that your email " \
        "address is specified as a contact in the generated code of conduct so that people know " \
        "who to contact in case of a violation. For suggestions about " \
        "how to enforce codes of conduct, see https://bit.ly/coc-enforcement.")
        config[:coc] = true
        Bundler.ui.info "Code of conduct enabled in config"
        templates.merge!("CODE_OF_CONDUCT.md.tt" => "CODE_OF_CONDUCT.md")
      end

      if ask_and_set(:changelog, "Do you want to include a changelog?",
        "A changelog is a file which contains a curated, chronologically ordered list of notable " \
        "changes for each version of a project. To make it easier for users and contributors to" \
        " see precisely what notable changes have been made between each release (or version) of" \
        " the project. Whether consumers or developers, the end users of software are" \
        " human beings who care about what's in the software. When the software changes, people " \
        "want to know why and how. see https://keepachangelog.com")
        config[:changelog] = true
        Bundler.ui.info "Changelog enabled in config"
        templates.merge!("CHANGELOG.md.tt" => "CHANGELOG.md")
      end

      config[:linter] = ask_and_set_linter
      case config[:linter]
      when "rubocop"
        config[:linter_version] = rubocop_version
        Bundler.ui.info "RuboCop enabled in config"
        templates.merge!("rubocop.yml.tt" => ".rubocop.yml")
      when "standard"
        config[:linter_version] = standard_version
        Bundler.ui.info "Standard enabled in config"
        templates.merge!("standard.yml.tt" => ".standard.yml")
      end

      templates.merge!("exe/newgem.tt" => "exe/#{name}") if config[:exe]

      if options[:ext]
        templates.merge!(
          "ext/newgem/extconf.rb.tt" => "ext/#{name}/extconf.rb",
          "ext/newgem/newgem.h.tt" => "ext/#{name}/#{underscored_name}.h",
          "ext/newgem/newgem.c.tt" => "ext/#{name}/#{underscored_name}.c"
        )
      end

      if target.exist? && !target.directory?
        Bundler.ui.error "Couldn't create a new gem named `#{gem_name}` because there's an existing file named `#{gem_name}`."
        exit Bundler::BundlerError.all_errors[Bundler::GenericSystemCallError]
      end

      if use_git
        Bundler.ui.info "Initializing git repo in #{target}"
        require "shellwords"
        `git init #{target.to_s.shellescape}`

        config[:git_default_branch] = File.read("#{target}/.git/HEAD").split("/").last.chomp
      end

      templates.each do |src, dst|
        destination = target.join(dst)
        thor.template("newgem/#{src}", destination, config)
      end

      executables.each do |file|
        path = target.join(file)
        executable = (path.stat.mode | 0o111)
        path.chmod(executable)
      end

      if use_git
        Dir.chdir(target) do
          `git add .`
        end
      end

      # Open gemspec in editor
      open_editor(options["edit"], target.join("#{name}.gemspec")) if options[:edit]

      Bundler.ui.info "Gem '#{name}' was successfully created. " \
        "For more information on making a RubyGem visit https://bundler.io/guides/creating_gem.html"
    end

    private

    def resolve_name(name)
      SharedHelpers.pwd.join(name).basename.to_s
    end

    def ask_and_set(key, header, message)
      choice = options[key]
      choice = Bundler.settings["gem.#{key}"] if choice.nil?

      if choice.nil?
        Bundler.ui.confirm header
        choice = Bundler.ui.yes? "#{message} y/(n):"
        Bundler.settings.set_global("gem.#{key}", choice)
      end

      choice
    end

    def validate_ext_name
      return unless gem_name.index("-")

      Bundler.ui.error "You have specified a gem name which does not conform to the \n" \
                       "naming guidelines for C extensions. For more information, \n" \
                       "see the 'Extension Naming' section at the following URL:\n" \
                       "https://guides.rubygems.org/gems-with-extensions/\n"
      exit 1
    end

    def ask_and_set_test_framework
      test_framework = options[:test] || Bundler.settings["gem.test"]

      if test_framework.to_s.empty?
        Bundler.ui.confirm "Do you want to generate tests with your gem?"
        Bundler.ui.info hint_text("test")

        result = Bundler.ui.ask "Enter a test framework. rspec/minitest/test-unit/(none):"
        if result =~ /rspec|minitest|test-unit/
          test_framework = result
        else
          test_framework = false
        end
      end

      if Bundler.settings["gem.test"].nil?
        Bundler.settings.set_global("gem.test", test_framework)
      end

      if options[:test] == Bundler.settings["gem.test"]
        Bundler.ui.info "#{options[:test]} is already configured, ignoring --test flag."
      end

      test_framework
    end

    def hint_text(setting)
      if Bundler.settings["gem.#{setting}"] == false
        "Your choice will only be applied to this gem."
      else
        "Future `bundle gem` calls will use your choice. " \
        "This setting can be changed anytime with `bundle config gem.#{setting}`."
      end
    end

    def ask_and_set_ci
      ci_template = options[:ci] || Bundler.settings["gem.ci"]

      if ci_template.to_s.empty?
        Bundler.ui.confirm "Do you want to set up continuous integration for your gem? " \
          "Supported services:\n" \
          "* CircleCI:       https://circleci.com/\n" \
          "* GitHub Actions: https://github.com/features/actions\n" \
          "* GitLab CI:      https://docs.gitlab.com/ee/ci/\n" \
          "* Travis CI:      https://travis-ci.org/\n" \
          "\n"
        Bundler.ui.info hint_text("ci")

        result = Bundler.ui.ask "Enter a CI service. github/travis/gitlab/circle/(none):"
        if result =~ /github|travis|gitlab|circle/
          ci_template = result
        else
          ci_template = false
        end
      end

      if Bundler.settings["gem.ci"].nil?
        Bundler.settings.set_global("gem.ci", ci_template)
      end

      if options[:ci] == Bundler.settings["gem.ci"]
        Bundler.ui.info "#{options[:ci]} is already configured, ignoring --ci flag."
      end

      ci_template
    end

    def ask_and_set_linter
      linter_template = options[:linter] || Bundler.settings["gem.linter"]
      linter_template = deprecated_rubocop_option if linter_template.nil?

      if linter_template.to_s.empty?
        Bundler.ui.confirm "Do you want to add a code linter and formatter to your gem? " \
          "Supported Linters:\n" \
          "* RuboCop:       https://rubocop.org\n" \
          "* Standard:      https://github.com/testdouble/standard\n" \
          "\n"
        Bundler.ui.info hint_text("linter")

        result = Bundler.ui.ask "Enter a linter. rubocop/standard/(none):"
        if result =~ /rubocop|standard/
          linter_template = result
        else
          linter_template = false
        end
      end

      if Bundler.settings["gem.linter"].nil?
        Bundler.settings.set_global("gem.linter", linter_template)
      end

      # Once gem.linter safely set, unset the deprecated gem.rubocop
      unless Bundler.settings["gem.rubocop"].nil?
        Bundler.settings.set_global("gem.rubocop", nil)
      end

      if options[:linter] == Bundler.settings["gem.linter"]
        Bundler.ui.info "#{options[:linter]} is already configured, ignoring --linter flag."
      end

      linter_template
    end

    def deprecated_rubocop_option
      if !options[:rubocop].nil?
        if options[:rubocop]
          Bundler::SharedHelpers.major_deprecation 2, "--rubocop is deprecated, use --linter=rubocop"
          "rubocop"
        else
          Bundler::SharedHelpers.major_deprecation 2, "--no-rubocop is deprecated, use --linter"
          false
        end
      elsif !Bundler.settings["gem.rubocop"].nil?
        Bundler::SharedHelpers.major_deprecation 2,
          "config gem.rubocop is deprecated; we've updated your config to use gem.linter instead"
        Bundler.settings["gem.rubocop"] ? "rubocop" : false
      end
    end

    def bundler_dependency_version
      v = Gem::Version.new(Bundler::VERSION)
      req = v.segments[0..1]
      req << "a" if v.prerelease?
      req.join(".")
    end

    def ensure_safe_gem_name(name, constant_array)
      if name =~ /^\d/
        Bundler.ui.error "Invalid gem name #{name} Please give a name which does not start with numbers."
        exit 1
      end

      constant_name = constant_array.join("::")

      existing_constant = constant_array.inject(Object) do |c, s|
        defined = begin
          c.const_defined?(s)
        rescue NameError
          Bundler.ui.error "Invalid gem name #{name} -- `#{constant_name}` is an invalid constant name"
          exit 1
        end
        (defined && c.const_get(s)) || break
      end

      return unless existing_constant
      Bundler.ui.error "Invalid gem name #{name} constant #{constant_name} is already in use. Please choose another gem name."
      exit 1
    end

    def open_editor(editor, file)
      thor.run(%(#{editor} "#{file}"))
    end

    def required_ruby_version
      if Gem.ruby_version < Gem::Version.new("2.4.a") then "2.3.0"
      elsif Gem.ruby_version < Gem::Version.new("2.5.a") then "2.4.0"
      elsif Gem.ruby_version < Gem::Version.new("2.6.a") then "2.5.0"
      else
        "2.6.0"
      end
    end

    def rubocop_version
      if Gem.ruby_version < Gem::Version.new("2.4.a") then "0.81.0"
      elsif Gem.ruby_version < Gem::Version.new("2.5.a") then "1.12"
      else
        "1.21"
      end
    end

    def standard_version
      if Gem.ruby_version < Gem::Version.new("2.4.a") then "0.2.5"
      elsif Gem.ruby_version < Gem::Version.new("2.5.a") then "1.0"
      else
        "1.3"
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Binstubs
    attr_reader :options, :gems
    def initialize(options, gems)
      @options = options
      @gems = gems
    end

    def run
      Bundler.definition.validate_runtime!
      path_option = options["path"]
      path_option = nil if path_option && path_option.empty?
      Bundler.settings.set_command_option :bin, path_option if options["path"]
      Bundler.settings.set_command_option_if_given :shebang, options["shebang"]
      installer = Installer.new(Bundler.root, Bundler.definition)

      installer_opts = {
        :force => options[:force],
        :binstubs_cmd => true,
        :all_platforms => options["all-platforms"],
      }

      if options[:all]
        raise InvalidOption, "Cannot specify --all with specific gems" unless gems.empty?
        @gems = Bundler.definition.specs.map(&:name)
        installer_opts.delete(:binstubs_cmd)
      elsif gems.empty?
        Bundler.ui.error "`bundle binstubs` needs at least one gem to run."
        exit 1
      end

      gems.each do |gem_name|
        spec = Bundler.definition.specs.find {|s| s.name == gem_name }
        unless spec
          raise GemNotFound, Bundler::CLI::Common.gem_not_found_message(
            gem_name, Bundler.definition.specs
          )
        end

        if options[:standalone]
          next Bundler.ui.warn("Sorry, Bundler can only be run via RubyGems.") if gem_name == "bundler"
          Bundler.settings.temporary(:path => (Bundler.settings[:path] || Bundler.root)) do
            installer.generate_standalone_bundler_executable_stubs(spec, installer_opts)
          end
        else
          installer.generate_bundler_executable_stubs(spec, installer_opts)
        end
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Show
    attr_reader :options, :gem_name, :latest_specs
    def initialize(options, gem_name)
      @options = options
      @gem_name = gem_name
      @verbose = options[:verbose] || options[:outdated]
      @latest_specs = fetch_latest_specs if @verbose
    end

    def run
      Bundler.ui.silence do
        Bundler.definition.validate_runtime!
        Bundler.load.lock
      end

      if gem_name
        if gem_name == "bundler"
          path = File.expand_path("../../../..", __FILE__)
        else
          spec = Bundler::CLI::Common.select_spec(gem_name, :regex_match)
          return unless spec
          path = spec.full_gem_path
          unless File.directory?(path)
            return Bundler.ui.warn "The gem #{gem_name} has been deleted. It was installed at: #{path}"
          end
        end
        return Bundler.ui.info(path)
      end

      if options[:paths]
        Bundler.load.specs.sort_by(&:name).map do |s|
          Bundler.ui.info s.full_gem_path
        end
      else
        Bundler.ui.info "Gems included by the bundle:"
        Bundler.load.specs.sort_by(&:name).each do |s|
          desc = "  * #{s.name} (#{s.version}#{s.git_version})"
          if @verbose
            latest = latest_specs.find {|l| l.name == s.name }
            Bundler.ui.info <<-END.gsub(/^ +/, "")
              #{desc}
              \tSummary:  #{s.summary || "No description available."}
              \tHomepage: #{s.homepage || "No website available."}
              \tStatus:   #{outdated?(s, latest) ? "Outdated - #{s.version} < #{latest.version}" : "Up to date"}
            END
          else
            Bundler.ui.info desc
          end
        end
      end
    end

    private

    def fetch_latest_specs
      definition = Bundler.definition(true)
      if options[:outdated]
        Bundler.ui.info "Fetching remote specs for outdated check...\n\n"
        Bundler.ui.silence { definition.resolve_remotely! }
      else
        definition.resolve_with_cache!
      end
      Bundler.reset!
      definition.specs
    end

    def outdated?(current, latest)
      return false unless latest
      Gem::Version.new(current.version) < Gem::Version.new(latest.version)
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Add
    attr_reader :gems, :options, :version

    def initialize(options, gems)
      @gems = gems
      @options = options
      @options[:group] = options[:group].split(",").map(&:strip) unless options[:group].nil?
      @version = options[:version].split(",").map(&:strip) unless options[:version].nil?
    end

    def run
      validate_options!
      inject_dependencies
      perform_bundle_install unless options["skip-install"]
    end

    private

    def perform_bundle_install
      Installer.install(Bundler.root, Bundler.definition)
      Bundler.load.cache if Bundler.app_cache.exist?
    end

    def inject_dependencies
      dependencies = gems.map {|g| Bundler::Dependency.new(g, version, options) }

      Injector.inject(dependencies,
        :conservative_versioning => options[:version].nil?, # Perform conservative versioning only when version is not specified
        :optimistic => options[:optimistic],
        :strict => options[:strict])
    end

    def validate_options!
      raise InvalidOption, "You can not specify `--strict` and `--optimistic` at the same time." if options[:strict] && options[:optimistic]

      # raise error when no gems are specified
      raise InvalidOption, "Please specify gems to add." if gems.empty?

      version.to_a.each do |v|
        raise InvalidOption, "Invalid gem requirement pattern '#{v}'" unless Gem::Requirement::PATTERN =~ v.to_s
      end
    end
  end
end
# frozen_string_literal: true

module Bundler
  class CLI::Platform
    attr_reader :options
    def initialize(options)
      @options = options
    end

    def run
      platforms, ruby_version = Bundler.ui.silence do
        locked_ruby_version = Bundler.locked_gems && Bundler.locked_gems.ruby_version
        gemfile_ruby_version = Bundler.definition.ruby_version && Bundler.definition.ruby_version.single_version_string
        [Bundler.definition.platforms.map {|p| "* #{p}" },
         locked_ruby_version || gemfile_ruby_version]
      end
      output = []

      if options[:ruby]
        if ruby_version
          output << ruby_version
        else
          output << "No ruby version specified"
        end
      else
        output << "Your platform is: #{RUBY_PLATFORM}"
        output << "Your app has gems that work on these platforms:\n#{platforms.join("\n")}"

        if ruby_version
          output << "Your Gemfile specifies a Ruby version requirement:\n* #{ruby_version}"

          begin
            Bundler.definition.validate_runtime!
            output << "Your current platform satisfies the Ruby version requirement."
          rescue RubyVersionMismatch => e
            output << e.message
          end
        else
          output << "Your Gemfile does not specify a Ruby version requirement."
        end
      end

      Bundler.ui.info output.join("\n\n")
    end
  end
end
# frozen_string_literal: true

module Bundler
  class SimilarityDetector
    SimilarityScore = Struct.new(:string, :distance)

    # initialize with an array of words to be matched against
    def initialize(corpus)
      @corpus = corpus
    end

    # return an array of words similar to 'word' from the corpus
    def similar_words(word, limit = 3)
      words_by_similarity = @corpus.map {|w| SimilarityScore.new(w, levenshtein_distance(word, w)) }
      words_by_similarity.select {|s| s.distance <= limit }.sort_by(&:distance).map(&:string)
    end

    # return the result of 'similar_words', concatenated into a list
    # (eg "a, b, or c")
    def similar_word_list(word, limit = 3)
      words = similar_words(word, limit)
      if words.length == 1
        words[0]
      elsif words.length > 1
        [words[0..-2].join(", "), words[-1]].join(" or ")
      end
    end

    protected

    # https://www.informit.com/articles/article.aspx?p=683059&seqNum=36
    def levenshtein_distance(this, that, ins = 2, del = 2, sub = 1)
      # ins, del, sub are weighted costs
      return nil if this.nil?
      return nil if that.nil?
      dm = [] # distance matrix

      # Initialize first row values
      dm[0] = (0..this.length).collect {|i| i * ins }
      fill = [0] * (this.length - 1)

      # Initialize first column values
      (1..that.length).each do |i|
        dm[i] = [i * del, fill.flatten]
      end

      # populate matrix
      (1..that.length).each do |i|
        (1..this.length).each do |j|
          # critical comparison
          dm[i][j] = [
            dm[i - 1][j - 1] + (this[j - 1] == that[i - 1] ? 0 : sub),
            dm[i][j - 1] + ins,
            dm[i - 1][j] + del,
          ].min
        end
      end

      # The last value in matrix is the Levenshtein distance between the strings
      dm[that.length][this.length]
    end
  end
end
# frozen_string_literal: true

require "set"
module Bundler
  class Graph
    GRAPH_NAME = :Gemfile

    def initialize(env, output_file, show_version = false, show_requirements = false, output_format = "png", without = [])
      @env               = env
      @output_file       = output_file
      @show_version      = show_version
      @show_requirements = show_requirements
      @output_format     = output_format
      @without_groups    = without.map(&:to_sym)

      @groups            = []
      @relations         = Hash.new {|h, k| h[k] = Set.new }
      @node_options      = {}
      @edge_options      = {}

      _populate_relations
    end

    attr_reader :groups, :relations, :node_options, :edge_options, :output_file, :output_format

    def viz
      GraphVizClient.new(self).run
    end

    private

    def _populate_relations
      parent_dependencies = _groups.values.to_set.flatten
      loop do
        break if parent_dependencies.empty?

        tmp = Set.new
        parent_dependencies.each do |dependency|
          child_dependencies = spec_for_dependency(dependency).runtime_dependencies.to_set
          @relations[dependency.name] += child_dependencies.map(&:name).to_set
          tmp += child_dependencies

          @node_options[dependency.name] = _make_label(dependency, :node)
          child_dependencies.each do |c_dependency|
            @edge_options["#{dependency.name}_#{c_dependency.name}"] = _make_label(c_dependency, :edge)
          end
        end
        parent_dependencies = tmp
      end
    end

    def _groups
      relations = Hash.new {|h, k| h[k] = Set.new }
      @env.current_dependencies.each do |dependency|
        dependency.groups.each do |group|
          next if @without_groups.include?(group)

          relations[group.to_s].add(dependency)
          @relations[group.to_s].add(dependency.name)

          @node_options[group.to_s] ||= _make_label(group, :node)
          @edge_options["#{group}_#{dependency.name}"] = _make_label(dependency, :edge)
        end
      end
      @groups = relations.keys
      relations
    end

    def _make_label(symbol_or_string_or_dependency, element_type)
      case element_type.to_sym
      when :node
        if symbol_or_string_or_dependency.is_a?(Gem::Dependency)
          label = symbol_or_string_or_dependency.name.dup
          label << "\n#{spec_for_dependency(symbol_or_string_or_dependency).version}" if @show_version
        else
          label = symbol_or_string_or_dependency.to_s
        end
      when :edge
        label = nil
        if symbol_or_string_or_dependency.respond_to?(:requirements_list) && @show_requirements
          tmp = symbol_or_string_or_dependency.requirements_list.join(", ")
          label = tmp if tmp != ">= 0"
        end
      else
        raise ArgumentError, "2nd argument is invalid"
      end
      label.nil? ? {} : { :label => label }
    end

    def spec_for_dependency(dependency)
      @env.requested_specs.find {|s| s.name == dependency.name }
    end

    class GraphVizClient
      def initialize(graph_instance)
        @graph_name    = graph_instance.class::GRAPH_NAME
        @groups        = graph_instance.groups
        @relations     = graph_instance.relations
        @node_options  = graph_instance.node_options
        @edge_options  = graph_instance.edge_options
        @output_file   = graph_instance.output_file
        @output_format = graph_instance.output_format
      end

      def g
        @g ||= ::GraphViz.digraph(@graph_name, :concentrate => true, :normalize => true, :nodesep => 0.55) do |g|
          g.edge[:weight]   = 2
          g.edge[:fontname] = g.node[:fontname] = "Arial, Helvetica, SansSerif"
          g.edge[:fontsize] = 12
        end
      end

      def run
        @groups.each do |group|
          g.add_nodes(
            group, {
              :style     => "filled",
              :fillcolor => "#B9B9D5",
              :shape     => "box3d",
              :fontsize  => 16,
            }.merge(@node_options[group])
          )
        end

        @relations.each do |parent, children|
          children.each do |child|
            if @groups.include?(parent)
              g.add_nodes(child, { :style => "filled", :fillcolor => "#B9B9D5" }.merge(@node_options[child]))
              g.add_edges(parent, child, { :constraint => false }.merge(@edge_options["#{parent}_#{child}"]))
            else
              g.add_nodes(child, @node_options[child])
              g.add_edges(parent, child, @edge_options["#{parent}_#{child}"])
            end
          end
        end

        if @output_format.to_s == "debug"
          $stdout.puts g.output :none => String
          Bundler.ui.info "debugging bundle viz..."
        else
          begin
            g.output @output_format.to_sym => "#{@output_file}.#{@output_format}"
            Bundler.ui.info "#{@output_file}.#{@output_format}"
          rescue ArgumentError => e
            warn "Unsupported output format. See Ruby-Graphviz/lib/graphviz/constants.rb"
            raise e
          end
        end
      end
    end
  end
end
# frozen_string_literal: false

module Bundler
  VERSION = "2.2.33".freeze

  def self.bundler_major_version
    @bundler_major_version ||= VERSION.split(".").first.to_i
  end
end
# frozen_string_literal: true

module Bundler
  class SourceMap
    attr_reader :sources, :dependencies

    def initialize(sources, dependencies)
      @sources = sources
      @dependencies = dependencies
    end

    def pinned_spec_names(skip = nil)
      direct_requirements.reject {|_, source| source == skip }.keys
    end

    def all_requirements
      requirements = direct_requirements.dup

      unmet_deps = sources.non_default_explicit_sources.map do |source|
        (source.spec_names - pinned_spec_names).each do |indirect_dependency_name|
          previous_source = requirements[indirect_dependency_name]
          if previous_source.nil?
            requirements[indirect_dependency_name] = source
          else
            no_ambiguous_sources = Bundler.feature_flag.bundler_3_mode?

            msg = ["The gem '#{indirect_dependency_name}' was found in multiple relevant sources."]
            msg.concat [previous_source, source].map {|s| "  * #{s}" }.sort
            msg << "You #{no_ambiguous_sources ? :must : :should} add this gem to the source block for the source you wish it to be installed from."
            msg = msg.join("\n")

            raise SecurityError, msg if no_ambiguous_sources
            Bundler.ui.warn "Warning: #{msg}"
          end
        end

        source.unmet_deps
      end

      sources.default_source.add_dependency_names(unmet_deps.flatten - requirements.keys)

      requirements
    end

    def direct_requirements
      @direct_requirements ||= begin
        requirements = {}
        default = sources.default_source
        dependencies.each do |dep|
          dep_source = dep.source || default
          dep_source.add_dependency_names(dep.name)
          requirements[dep.name] = dep_source
        end
        requirements
      end
    end
  end
end
# frozen_string_literal: true

require "rubygems" unless defined?(Gem)

module Bundler
  class RubygemsIntegration
    if defined?(Gem::Ext::Builder::CHDIR_MONITOR)
      EXT_LOCK = Gem::Ext::Builder::CHDIR_MONITOR
    else
      require "monitor"

      EXT_LOCK = Monitor.new
    end

    def self.version
      @version ||= Gem::Version.new(Gem::VERSION)
    end

    def self.provides?(req_str)
      Gem::Requirement.new(req_str).satisfied_by?(version)
    end

    def initialize
      @replaced_methods = {}
      backport_ext_builder_monitor
    end

    def version
      self.class.version
    end

    def provides?(req_str)
      self.class.provides?(req_str)
    end

    def build_args
      require "rubygems/command"
      Gem::Command.build_args
    end

    def build_args=(args)
      require "rubygems/command"
      Gem::Command.build_args = args
    end

    def loaded_specs(name)
      Gem.loaded_specs[name]
    end

    def add_to_load_path(paths)
      return Gem.add_to_load_path(*paths) if Gem.respond_to?(:add_to_load_path)

      if insert_index = Gem.load_path_insert_index
        # Gem directories must come after -I and ENV['RUBYLIB']
        $LOAD_PATH.insert(insert_index, *paths)
      else
        # We are probably testing in core, -I and RUBYLIB don't apply
        $LOAD_PATH.unshift(*paths)
      end
    end

    def mark_loaded(spec)
      if spec.respond_to?(:activated=)
        current = Gem.loaded_specs[spec.name]
        current.activated = false if current
        spec.activated = true
      end
      Gem.loaded_specs[spec.name] = spec
    end

    def validate(spec)
      Bundler.ui.silence { spec.validate(false) }
    rescue Gem::InvalidSpecificationException => e
      error_message = "The gemspec at #{spec.loaded_from} is not valid. Please fix this gemspec.\n" \
        "The validation error was '#{e.message}'\n"
      raise Gem::InvalidSpecificationException.new(error_message)
    rescue Errno::ENOENT
      nil
    end

    def set_installed_by_version(spec, installed_by_version = Gem::VERSION)
      return unless spec.respond_to?(:installed_by_version=)
      spec.installed_by_version = Gem::Version.create(installed_by_version)
    end

    def spec_missing_extensions?(spec, default = true)
      return spec.missing_extensions? if spec.respond_to?(:missing_extensions?)

      return false if spec.default_gem?
      return false if spec.extensions.empty?

      default
    end

    def spec_matches_for_glob(spec, glob)
      return spec.matches_for_glob(glob) if spec.respond_to?(:matches_for_glob)

      spec.load_paths.map do |lp|
        Dir["#{lp}/#{glob}#{suffix_pattern}"]
      end.flatten(1)
    end

    def stub_set_spec(stub, spec)
      stub.instance_variable_set(:@spec, spec)
    end

    def path(obj)
      obj.to_s
    end

    def configuration
      require_relative "psyched_yaml"
      Gem.configuration
    rescue Gem::SystemExitException, LoadError => e
      Bundler.ui.error "#{e.class}: #{e.message}"
      Bundler.ui.trace e
      raise
    rescue YamlLibrarySyntaxError => e
      raise YamlSyntaxError.new(e, "Your RubyGems configuration, which is " \
        "usually located in ~/.gemrc, contains invalid YAML syntax.")
    end

    def ruby_engine
      Gem.ruby_engine
    end

    def read_binary(path)
      Gem.read_binary(path)
    end

    def inflate(obj)
      Gem::Util.inflate(obj)
    end

    def correct_for_windows_path(path)
      if Gem::Util.respond_to?(:correct_for_windows_path)
        Gem::Util.correct_for_windows_path(path)
      elsif path[0].chr == "/" && path[1].chr =~ /[a-z]/i && path[2].chr == ":"
        path[1..-1]
      else
        path
      end
    end

    def sources=(val)
      # Gem.configuration creates a new Gem::ConfigFile, which by default will read ~/.gemrc
      # If that file exists, its settings (including sources) will overwrite the values we
      # are about to set here. In order to avoid that, we force memoizing the config file now.
      configuration

      Gem.sources = val
    end

    def sources
      Gem.sources
    end

    def gem_dir
      Gem.dir
    end

    def gem_bindir
      Gem.bindir
    end

    def user_home
      Gem.user_home
    end

    def gem_path
      Gem.path
    end

    def reset
      Gem::Specification.reset
    end

    def post_reset_hooks
      Gem.post_reset_hooks
    end

    def suffix_pattern
      Gem.suffix_pattern
    end

    def gem_cache
      gem_path.map {|p| File.expand_path("cache", p) }
    end

    def spec_cache_dirs
      @spec_cache_dirs ||= begin
        dirs = gem_path.map {|dir| File.join(dir, "specifications") }
        dirs << Gem.spec_cache_dir if Gem.respond_to?(:spec_cache_dir) # Not in RubyGems 2.0.3 or earlier
        dirs.uniq.select {|dir| File.directory? dir }
      end
    end

    def marshal_spec_dir
      Gem::MARSHAL_SPEC_DIR
    end

    def clear_paths
      Gem.clear_paths
    end

    def bin_path(gem, bin, ver)
      Gem.bin_path(gem, bin, ver)
    end

    def loaded_gem_paths
      loaded_gem_paths = Gem.loaded_specs.map {|_, s| s.full_require_paths }
      loaded_gem_paths.flatten
    end

    def load_plugins
      Gem.load_plugins if Gem.respond_to?(:load_plugins)
    end

    def load_plugin_files(files)
      Gem.load_plugin_files(files) if Gem.respond_to?(:load_plugin_files)
    end

    def load_env_plugins
      Gem.load_env_plugins if Gem.respond_to?(:load_env_plugins)
    end

    def ui=(obj)
      Gem::DefaultUserInteraction.ui = obj
    end

    def ext_lock
      EXT_LOCK
    end

    def with_build_args(args)
      ext_lock.synchronize do
        old_args = build_args
        begin
          self.build_args = args
          yield
        ensure
          self.build_args = old_args
        end
      end
    end

    def spec_from_gem(path, policy = nil)
      require "rubygems/security"
      require_relative "psyched_yaml"
      gem_from_path(path, security_policies[policy]).spec
    rescue Exception, Gem::Exception, Gem::Security::Exception => e # rubocop:disable Lint/RescueException
      if e.is_a?(Gem::Security::Exception) ||
          e.message =~ /unknown trust policy|unsigned gem/i ||
          e.message =~ /couldn't verify (meta)?data signature/i
        raise SecurityError,
          "The gem #{File.basename(path, ".gem")} can't be installed because " \
          "the security policy didn't allow it, with the message: #{e.message}"
      else
        raise e
      end
    end

    def build_gem(gem_dir, spec)
      build(spec)
    end

    def security_policy_keys
      %w[High Medium Low AlmostNo No].map {|level| "#{level}Security" }
    end

    def security_policies
      @security_policies ||= begin
        require "rubygems/security"
        Gem::Security::Policies
      rescue LoadError, NameError
        {}
      end
    end

    def reverse_rubygems_kernel_mixin
      # Disable rubygems' gem activation system
      kernel = (class << ::Kernel; self; end)
      [kernel, ::Kernel].each do |k|
        if k.private_method_defined?(:gem_original_require)
          redefine_method(k, :require, k.instance_method(:gem_original_require))
        end
      end
    end

    def replace_gem(specs, specs_by_name)
      reverse_rubygems_kernel_mixin

      executables = nil

      kernel = (class << ::Kernel; self; end)
      [kernel, ::Kernel].each do |kernel_class|
        redefine_method(kernel_class, :gem) do |dep, *reqs|
          if executables && executables.include?(File.basename(caller.first.split(":").first))
            break
          end

          reqs.pop if reqs.last.is_a?(Hash)

          unless dep.respond_to?(:name) && dep.respond_to?(:requirement)
            dep = Gem::Dependency.new(dep, reqs)
          end

          if spec = specs_by_name[dep.name]
            return true if dep.matches_spec?(spec)
          end

          message = if spec.nil?
            target_file = begin
                            Bundler.default_gemfile.basename
                          rescue GemfileNotFound
                            "inline Gemfile"
                          end
            "#{dep.name} is not part of the bundle." \
            " Add it to your #{target_file}."
          else
            "can't activate #{dep}, already activated #{spec.full_name}. " \
            "Make sure all dependencies are added to Gemfile."
          end

          e = Gem::LoadError.new(message)
          e.name = dep.name
          if e.respond_to?(:requirement=)
            e.requirement = dep.requirement
          elsif e.respond_to?(:version_requirement=)
            e.version_requirement = dep.requirement
          end
          raise e
        end

        # backwards compatibility shim, see https://github.com/rubygems/bundler/issues/5102
        kernel_class.send(:public, :gem) if Bundler.feature_flag.setup_makes_kernel_gem_public?
      end
    end

    # Used to make bin stubs that are not created by bundler work
    # under bundler. The new Gem.bin_path only considers gems in
    # +specs+
    def replace_bin_path(specs_by_name)
      gem_class = (class << Gem; self; end)

      redefine_method(gem_class, :find_spec_for_exe) do |gem_name, *args|
        exec_name = args.first
        raise ArgumentError, "you must supply exec_name" unless exec_name

        spec_with_name = specs_by_name[gem_name]
        matching_specs_by_exec_name = specs_by_name.values.select {|s| s.executables.include?(exec_name) }
        spec = matching_specs_by_exec_name.delete(spec_with_name)

        unless spec || !matching_specs_by_exec_name.empty?
          message = "can't find executable #{exec_name} for gem #{gem_name}"
          if spec_with_name.nil?
            message += ". #{gem_name} is not currently included in the bundle, " \
                       "perhaps you meant to add it to your #{Bundler.default_gemfile.basename}?"
          end
          raise Gem::Exception, message
        end

        unless spec
          spec = matching_specs_by_exec_name.shift
          warn \
            "Bundler is using a binstub that was created for a different gem (#{spec.name}).\n" \
            "You should run `bundle binstub #{gem_name}` " \
            "to work around a system/bundle conflict."
        end

        unless matching_specs_by_exec_name.empty?
          conflicting_names = matching_specs_by_exec_name.map(&:name).join(", ")
          warn \
            "The `#{exec_name}` executable in the `#{spec.name}` gem is being loaded, but it's also present in other gems (#{conflicting_names}).\n" \
            "If you meant to run the executable for another gem, make sure you use a project specific binstub (`bundle binstub <gem_name>`).\n" \
            "If you plan to use multiple conflicting executables, generate binstubs for them and disambiguate their names."
        end

        spec
      end

      redefine_method(gem_class, :activate_bin_path) do |name, *args|
        exec_name = args.first
        return ENV["BUNDLE_BIN_PATH"] if exec_name == "bundle"

        # Copy of Rubygems activate_bin_path impl
        requirement = args.last
        spec = find_spec_for_exe name, exec_name, [requirement]

        gem_bin = File.join(spec.full_gem_path, spec.bindir, exec_name)
        gem_from_path_bin = File.join(File.dirname(spec.loaded_from), spec.bindir, exec_name)
        File.exist?(gem_bin) ? gem_bin : gem_from_path_bin
      end

      redefine_method(gem_class, :bin_path) do |name, *args|
        exec_name = args.first
        return ENV["BUNDLE_BIN_PATH"] if exec_name == "bundle"

        spec = find_spec_for_exe(name, *args)
        exec_name ||= spec.default_executable

        gem_bin = File.join(spec.full_gem_path, spec.bindir, exec_name)
        gem_from_path_bin = File.join(File.dirname(spec.loaded_from), spec.bindir, exec_name)
        File.exist?(gem_bin) ? gem_bin : gem_from_path_bin
      end
    end

    # Replace or hook into RubyGems to provide a bundlerized view
    # of the world.
    def replace_entrypoints(specs)
      specs_by_name = add_default_gems_to(specs)

      replace_gem(specs, specs_by_name)
      stub_rubygems(specs)
      replace_bin_path(specs_by_name)

      Gem.clear_paths
    end

    # Add default gems not already present in specs, and return them as a hash.
    def add_default_gems_to(specs)
      specs_by_name = specs.reduce({}) do |h, s|
        h[s.name] = s
        h
      end

      Bundler.rubygems.default_stubs.each do |stub|
        default_spec = stub.to_spec
        default_spec_name = default_spec.name
        next if specs_by_name.key?(default_spec_name)

        specs << default_spec
        specs_by_name[default_spec_name] = default_spec
      end

      specs_by_name
    end

    def undo_replacements
      @replaced_methods.each do |(sym, klass), method|
        redefine_method(klass, sym, method)
      end
      if Binding.public_method_defined?(:source_location)
        post_reset_hooks.reject! {|proc| proc.binding.source_location[0] == __FILE__ }
      else
        post_reset_hooks.reject! {|proc| proc.binding.eval("__FILE__") == __FILE__ }
      end
      @replaced_methods.clear
    end

    def redefine_method(klass, method, unbound_method = nil, &block)
      visibility = method_visibility(klass, method)
      begin
        if (instance_method = klass.instance_method(method)) && method != :initialize
          # doing this to ensure we also get private methods
          klass.send(:remove_method, method)
        end
      rescue NameError
        # method isn't defined
        nil
      end
      @replaced_methods[[method, klass]] = instance_method
      if unbound_method
        klass.send(:define_method, method, unbound_method)
        klass.send(visibility, method)
      elsif block
        klass.send(:define_method, method, &block)
        klass.send(visibility, method)
      end
    end

    def method_visibility(klass, method)
      if klass.private_method_defined?(method)
        :private
      elsif klass.protected_method_defined?(method)
        :protected
      else
        :public
      end
    end

    def stub_rubygems(specs)
      Gem::Specification.all = specs

      Gem.post_reset do
        Gem::Specification.all = specs
      end

      redefine_method((class << Gem; self; end), :finish_resolve) do |*|
        []
      end
    end

    def plain_specs
      Gem::Specification._all
    end

    def plain_specs=(specs)
      Gem::Specification.all = specs
    end

    def fetch_specs(remote, name)
      require "rubygems/remote_fetcher"
      path = remote.uri.to_s + "#{name}.#{Gem.marshal_version}.gz"
      fetcher = gem_remote_fetcher
      fetcher.headers = { "X-Gemfile-Source" => remote.original_uri.to_s } if remote.original_uri
      string = fetcher.fetch_path(path)
      Bundler.load_marshal(string)
    rescue Gem::RemoteFetcher::FetchError
      # it's okay for prerelease to fail
      raise unless name == "prerelease_specs"
    end

    def fetch_all_remote_specs(remote)
      specs = fetch_specs(remote, "specs")
      pres = fetch_specs(remote, "prerelease_specs") || []

      specs.concat(pres)
    end

    def download_gem(spec, uri, cache_dir)
      require "rubygems/remote_fetcher"
      uri = Bundler.settings.mirror_for(uri)
      fetcher = gem_remote_fetcher
      fetcher.headers = { "X-Gemfile-Source" => spec.remote.original_uri.to_s } if spec.remote.original_uri
      Bundler::Retry.new("download gem from #{uri}").attempts do
        gem_file_name = spec.file_name
        local_gem_path = File.join cache_dir, gem_file_name
        return if File.exist? local_gem_path

        begin
          remote_gem_path = uri + "gems/#{gem_file_name}"
          remote_gem_path = remote_gem_path.to_s if provides?("< 3.2.0.rc.1")

          SharedHelpers.filesystem_access(local_gem_path) do
            fetcher.cache_update_path remote_gem_path, local_gem_path
          end
        rescue Gem::RemoteFetcher::FetchError
          raise if spec.original_platform == spec.platform

          original_gem_file_name = "#{spec.original_name}.gem"
          raise if gem_file_name == original_gem_file_name

          gem_file_name = original_gem_file_name
          retry
        end
      end
    rescue Gem::RemoteFetcher::FetchError => e
      raise Bundler::HTTPError, "Could not download gem from #{uri} due to underlying error <#{e.message}>"
    end

    def gem_remote_fetcher
      require "rubygems/remote_fetcher"
      proxy = configuration[:http_proxy]
      Gem::RemoteFetcher.new(proxy)
    end

    def gem_from_path(path, policy = nil)
      require "rubygems/package"
      p = Gem::Package.new(path)
      p.security_policy = policy if policy
      p
    end

    def build(spec, skip_validation = false)
      require "rubygems/package"
      Gem::Package.build(spec, skip_validation)
    end

    def repository_subdirectories
      Gem::REPOSITORY_SUBDIRECTORIES
    end

    def install_with_build_args(args)
      yield
    end

    def path_separator
      Gem.path_separator
    end

    def all_specs
      Gem::Specification.stubs.map do |stub|
        StubSpecification.from_stub(stub)
      end
    end

    def backport_ext_builder_monitor
      # So we can avoid requiring "rubygems/ext" in its entirety
      Gem.module_eval <<-RUBY, __FILE__, __LINE__ + 1
        module Ext
        end
      RUBY

      require "rubygems/ext/builder"

      Gem::Ext::Builder.class_eval do
        unless const_defined?(:CHDIR_MONITOR)
          const_set(:CHDIR_MONITOR, EXT_LOCK)
        end

        remove_const(:CHDIR_MUTEX) if const_defined?(:CHDIR_MUTEX)
        const_set(:CHDIR_MUTEX, const_get(:CHDIR_MONITOR))
      end
    end

    def find_name(name)
      Gem::Specification.stubs_for(name).map(&:to_spec)
    end

    if Gem::Specification.respond_to?(:default_stubs)
      def default_stubs
        Gem::Specification.default_stubs("*.gemspec")
      end
    else
      def default_stubs
        Gem::Specification.send(:default_stubs, "*.gemspec")
      end
    end

    def use_gemdeps(gemfile)
      ENV["BUNDLE_GEMFILE"] ||= File.expand_path(gemfile)
      require_relative "gemdeps"
      runtime = Bundler.setup
      activated_spec_names = runtime.requested_specs.map(&:to_spec).sort_by(&:name)
      [Gemdeps.new(runtime), activated_spec_names]
    end
  end

  def self.rubygems
    @rubygems ||= RubygemsIntegration.new
  end
end
# frozen_string_literal: true

require_relative "match_platform"

module Bundler
  class LazySpecification
    include MatchPlatform

    attr_reader :name, :version, :dependencies, :platform
    attr_accessor :source, :remote

    def initialize(name, version, platform, source = nil)
      @name          = name
      @version       = version
      @dependencies  = []
      @platform      = platform || Gem::Platform::RUBY
      @source        = source
      @specification = nil
    end

    def full_name
      if platform == Gem::Platform::RUBY || platform.nil?
        "#{@name}-#{@version}"
      else
        "#{@name}-#{@version}-#{platform}"
      end
    end

    def ==(other)
      identifier == other.identifier
    end

    def eql?(other)
      identifier.eql?(other.identifier)
    end

    def hash
      identifier.hash
    end

    ##
    # Does this locked specification satisfy +dependency+?
    #
    # NOTE: Rubygems default requirement is ">= 0", which doesn't match
    # prereleases of 0 versions, like "0.0.0.dev" or "0.0.0.SNAPSHOT". However,
    # bundler users expect those to work. We need to make sure that Gemfile
    # dependencies without explicit requirements (which use ">= 0" under the
    # hood by default) are still valid for locked specs using this kind of
    # versions. The method implements an ad-hoc fix for that. A better solution
    # might be to change default rubygems requirement of dependencies to be ">=
    # 0.A" but that's a major refactoring likely to break things. Hopefully we
    # can attempt it in the future.
    #

    def satisfies?(dependency)
      effective_requirement = dependency.requirement == Gem::Requirement.default ? Gem::Requirement.new(">= 0.A") : dependency.requirement

      @name == dependency.name && effective_requirement.satisfied_by?(Gem::Version.new(@version))
    end

    def to_lock
      out = String.new

      if platform == Gem::Platform::RUBY || platform.nil?
        out << "    #{name} (#{version})\n"
      else
        out << "    #{name} (#{version}-#{platform})\n"
      end

      dependencies.sort_by(&:to_s).uniq.each do |dep|
        next if dep.type == :development
        out << "    #{dep.to_lock}\n"
      end

      out
    end

    def __materialize__
      @specification = if source.is_a?(Source::Gemspec) && source.gemspec.name == name
        source.gemspec.tap {|s| s.source = source }
      else
        search_object = if source.is_a?(Source::Path)
          Dependency.new(name, version)
        else
          ruby_platform_materializes_to_ruby_platform? ? self : Dependency.new(name, version)
        end
        platform_object = Gem::Platform.new(platform)
        candidates = source.specs.search(search_object)
        same_platform_candidates = candidates.select do |spec|
          MatchPlatform.platforms_match?(spec.platform, platform_object)
        end
        installable_candidates = same_platform_candidates.select do |spec|
          !spec.is_a?(EndpointSpecification) ||
            (spec.required_ruby_version.satisfied_by?(Gem.ruby_version) &&
              spec.required_rubygems_version.satisfied_by?(Gem.rubygems_version))
        end
        search = installable_candidates.last || same_platform_candidates.last
        search.dependencies = dependencies if search && (search.is_a?(RemoteSpecification) || search.is_a?(EndpointSpecification))
        search
      end
    end

    def respond_to?(*args)
      super || @specification ? @specification.respond_to?(*args) : nil
    end

    def to_s
      @__to_s ||= if platform == Gem::Platform::RUBY || platform.nil?
        "#{name} (#{version})"
      else
        "#{name} (#{version}-#{platform})"
      end
    end

    def identifier
      @__identifier ||= [name, version, platform_string]
    end

    def git_version
      return unless source.is_a?(Bundler::Source::Git)
      " #{source.revision[0..6]}"
    end

    protected

    def platform_string
      platform_string = platform.to_s
      platform_string == Index::RUBY ? Index::NULL : platform_string
    end

    private

    def to_ary
      nil
    end

    def method_missing(method, *args, &blk)
      raise "LazySpecification has not been materialized yet (calling :#{method} #{args.inspect})" unless @specification

      return super unless respond_to?(method)

      @specification.send(method, *args, &blk)
    end

    #
    # For backwards compatibility with existing lockfiles, if the most specific
    # locked platform is RUBY, we keep the previous behaviour of resolving the
    # best platform variant at materiliazation time. For previous bundler
    # versions (before 2.2.0) this was always the case (except when the lockfile
    # only included non-ruby platforms), but we're also keeping this behaviour
    # on newer bundlers unless users generate the lockfile from scratch or
    # explicitly add a more specific platform.
    #
    def ruby_platform_materializes_to_ruby_platform?
      !Bundler.most_specific_locked_platform?(Gem::Platform::RUBY) || Bundler.settings[:force_ruby_platform]
    end
  end
end
# frozen_string_literal: true

module Bundler
  module RubyDsl
    def ruby(*ruby_version)
      options = ruby_version.last.is_a?(Hash) ? ruby_version.pop : {}
      ruby_version.flatten!
      raise GemfileError, "Please define :engine_version" if options[:engine] && options[:engine_version].nil?
      raise GemfileError, "Please define :engine" if options[:engine_version] && options[:engine].nil?

      if options[:engine] == "ruby" && options[:engine_version] &&
          ruby_version != Array(options[:engine_version])
        raise GemfileEvalError, "ruby_version must match the :engine_version for MRI"
      end
      @ruby_version = RubyVersion.new(ruby_version, options[:patchlevel], options[:engine], options[:engine_version])
    end
  end
end
# frozen_string_literal: true

require_relative "bundler/vendored_fileutils"
require "pathname"
require "rbconfig"

require_relative "bundler/errors"
require_relative "bundler/environment_preserver"
require_relative "bundler/plugin"
require_relative "bundler/rubygems_ext"
require_relative "bundler/rubygems_integration"
require_relative "bundler/version"
require_relative "bundler/constants"
require_relative "bundler/current_ruby"
require_relative "bundler/build_metadata"

# Bundler provides a consistent environment for Ruby projects by
# tracking and installing the exact gems and versions that are needed.
#
# Since Ruby 2.6, Bundler is a part of Ruby's standard library.
#
# Bunder is used by creating _gemfiles_ listing all the project dependencies
# and (optionally) their versions and then using
#
#   require 'bundler/setup'
#
# or Bundler.setup to setup environment where only specified gems and their
# specified versions could be used.
#
# See {Bundler website}[https://bundler.io/docs.html] for extensive documentation
# on gemfiles creation and Bundler usage.
#
# As a standard library inside project, Bundler could be used for introspection
# of loaded and required modules.
#
module Bundler
  environment_preserver = EnvironmentPreserver.from_env
  ORIGINAL_ENV = environment_preserver.restore
  environment_preserver.replace_with_backup
  SUDO_MUTEX = Thread::Mutex.new

  autoload :Definition,             File.expand_path("bundler/definition", __dir__)
  autoload :Dependency,             File.expand_path("bundler/dependency", __dir__)
  autoload :DepProxy,               File.expand_path("bundler/dep_proxy", __dir__)
  autoload :Deprecate,              File.expand_path("bundler/deprecate", __dir__)
  autoload :Digest,                 File.expand_path("bundler/digest", __dir__)
  autoload :Dsl,                    File.expand_path("bundler/dsl", __dir__)
  autoload :EndpointSpecification,  File.expand_path("bundler/endpoint_specification", __dir__)
  autoload :Env,                    File.expand_path("bundler/env", __dir__)
  autoload :Fetcher,                File.expand_path("bundler/fetcher", __dir__)
  autoload :FeatureFlag,            File.expand_path("bundler/feature_flag", __dir__)
  autoload :GemHelper,              File.expand_path("bundler/gem_helper", __dir__)
  autoload :GemHelpers,             File.expand_path("bundler/gem_helpers", __dir__)
  autoload :GemVersionPromoter,     File.expand_path("bundler/gem_version_promoter", __dir__)
  autoload :Graph,                  File.expand_path("bundler/graph", __dir__)
  autoload :Index,                  File.expand_path("bundler/index", __dir__)
  autoload :Injector,               File.expand_path("bundler/injector", __dir__)
  autoload :Installer,              File.expand_path("bundler/installer", __dir__)
  autoload :LazySpecification,      File.expand_path("bundler/lazy_specification", __dir__)
  autoload :LockfileParser,         File.expand_path("bundler/lockfile_parser", __dir__)
  autoload :MatchPlatform,          File.expand_path("bundler/match_platform", __dir__)
  autoload :ProcessLock,            File.expand_path("bundler/process_lock", __dir__)
  autoload :RemoteSpecification,    File.expand_path("bundler/remote_specification", __dir__)
  autoload :Resolver,               File.expand_path("bundler/resolver", __dir__)
  autoload :Retry,                  File.expand_path("bundler/retry", __dir__)
  autoload :RubyDsl,                File.expand_path("bundler/ruby_dsl", __dir__)
  autoload :RubyVersion,            File.expand_path("bundler/ruby_version", __dir__)
  autoload :Runtime,                File.expand_path("bundler/runtime", __dir__)
  autoload :Settings,               File.expand_path("bundler/settings", __dir__)
  autoload :SharedHelpers,          File.expand_path("bundler/shared_helpers", __dir__)
  autoload :Source,                 File.expand_path("bundler/source", __dir__)
  autoload :SourceList,             File.expand_path("bundler/source_list", __dir__)
  autoload :SourceMap,              File.expand_path("bundler/source_map", __dir__)
  autoload :SpecSet,                File.expand_path("bundler/spec_set", __dir__)
  autoload :StubSpecification,      File.expand_path("bundler/stub_specification", __dir__)
  autoload :UI,                     File.expand_path("bundler/ui", __dir__)
  autoload :URICredentialsFilter,   File.expand_path("bundler/uri_credentials_filter", __dir__)
  autoload :VersionRanges,          File.expand_path("bundler/version_ranges", __dir__)

  class << self
    def configure
      @configured ||= configure_gem_home_and_path
    end

    def ui
      (defined?(@ui) && @ui) || (self.ui = UI::Shell.new)
    end

    def ui=(ui)
      Bundler.rubygems.ui = UI::RGProxy.new(ui)
      @ui = ui
    end

    # Returns absolute path of where gems are installed on the filesystem.
    def bundle_path
      @bundle_path ||= Pathname.new(configured_bundle_path.path).expand_path(root)
    end

    def configured_bundle_path
      @configured_bundle_path ||= settings.path.tap(&:validate!)
    end

    # Returns absolute location of where binstubs are installed to.
    def bin_path
      @bin_path ||= begin
        path = settings[:bin] || "bin"
        path = Pathname.new(path).expand_path(root).expand_path
        SharedHelpers.filesystem_access(path) {|p| FileUtils.mkdir_p(p) }
        path
      end
    end

    # Turns on the Bundler runtime. After +Bundler.setup+ call, all +load+ or
    # +require+ of the gems would be allowed only if they are part of
    # the Gemfile or Ruby's standard library. If the versions specified
    # in Gemfile, only those versions would be loaded.
    #
    # Assuming Gemfile
    #
    #    gem 'first_gem', '= 1.0'
    #    group :test do
    #      gem 'second_gem', '= 1.0'
    #    end
    #
    # The code using Bundler.setup works as follows:
    #
    #    require 'third_gem' # allowed, required from global gems
    #    require 'first_gem' # allowed, loads the last installed version
    #    Bundler.setup
    #    require 'fourth_gem' # fails with LoadError
    #    require 'second_gem' # loads exactly version 1.0
    #
    # +Bundler.setup+ can be called only once, all subsequent calls are no-op.
    #
    # If _groups_ list is provided, only gems from specified groups would
    # be allowed (gems specified outside groups belong to special +:default+ group).
    #
    # To require all gems from Gemfile (or only some groups), see Bundler.require.
    #
    def setup(*groups)
      # Return if all groups are already loaded
      return @setup if defined?(@setup) && @setup

      definition.validate_runtime!

      SharedHelpers.print_major_deprecations!

      if groups.empty?
        # Load all groups, but only once
        @setup = load.setup
      else
        load.setup(*groups)
      end
    end

    # Setups Bundler environment (see Bundler.setup) if it is not already set,
    # and loads all gems from groups specified. Unlike ::setup, can be called
    # multiple times with different groups (if they were allowed by setup).
    #
    # Assuming Gemfile
    #
    #    gem 'first_gem', '= 1.0'
    #    group :test do
    #      gem 'second_gem', '= 1.0'
    #    end
    #
    # The code will work as follows:
    #
    #    Bundler.setup # allow all groups
    #    Bundler.require(:default) # requires only first_gem
    #    # ...later
    #    Bundler.require(:test)   # requires second_gem
    #
    def require(*groups)
      setup(*groups).require(*groups)
    end

    def load
      @load ||= Runtime.new(root, definition)
    end

    def environment
      SharedHelpers.major_deprecation 2, "Bundler.environment has been removed in favor of Bundler.load", :print_caller_location => true
      load
    end

    # Returns an instance of Bundler::Definition for given Gemfile and lockfile
    #
    # @param unlock [Hash, Boolean, nil] Gems that have been requested
    #   to be updated or true if all gems should be updated
    # @return [Bundler::Definition]
    def definition(unlock = nil)
      @definition = nil if unlock
      @definition ||= begin
        configure
        Definition.build(default_gemfile, default_lockfile, unlock)
      end
    end

    def frozen_bundle?
      frozen = settings[:deployment]
      frozen ||= settings[:frozen]
      frozen
    end

    def locked_gems
      @locked_gems ||=
        if defined?(@definition) && @definition
          definition.locked_gems
        elsif Bundler.default_lockfile.file?
          lock = Bundler.read_file(Bundler.default_lockfile)
          LockfileParser.new(lock)
        end
    end

    def most_specific_locked_platform?(platform)
      return false unless defined?(@definition) && @definition

      definition.most_specific_locked_platform == platform
    end

    def ruby_scope
      "#{Bundler.rubygems.ruby_engine}/#{RbConfig::CONFIG["ruby_version"]}"
    end

    def user_home
      @user_home ||= begin
        home = Bundler.rubygems.user_home
        bundle_home = home ? File.join(home, ".bundle") : nil

        warning = if home.nil?
          "Your home directory is not set."
        elsif !File.directory?(home)
          "`#{home}` is not a directory."
        elsif !File.writable?(home) && (!File.directory?(bundle_home) || !File.writable?(bundle_home))
          "`#{home}` is not writable."
        end

        if warning
          Bundler.ui.warn "#{warning}\n"
          user_home = tmp_home_path
          Bundler.ui.warn "Bundler will use `#{user_home}' as your home directory temporarily.\n"
          user_home
        else
          Pathname.new(home)
        end
      end
    end

    def user_bundle_path(dir = "home")
      env_var, fallback = case dir
                          when "home"
                            ["BUNDLE_USER_HOME", proc { Pathname.new(user_home).join(".bundle") }]
                          when "cache"
                            ["BUNDLE_USER_CACHE", proc { user_bundle_path.join("cache") }]
                          when "config"
                            ["BUNDLE_USER_CONFIG", proc { user_bundle_path.join("config") }]
                          when "plugin"
                            ["BUNDLE_USER_PLUGIN", proc { user_bundle_path.join("plugin") }]
                          else
                            raise BundlerError, "Unknown user path requested: #{dir}"
      end
      # `fallback` will already be a Pathname, but Pathname.new() is
      # idempotent so it's OK
      Pathname.new(ENV.fetch(env_var, &fallback))
    end

    def user_cache
      user_bundle_path("cache")
    end

    def home
      bundle_path.join("bundler")
    end

    def install_path
      home.join("gems")
    end

    def specs_path
      bundle_path.join("specifications")
    end

    def root
      @root ||= begin
                  SharedHelpers.root
                rescue GemfileNotFound
                  bundle_dir = default_bundle_dir
                  raise GemfileNotFound, "Could not locate Gemfile or .bundle/ directory" unless bundle_dir
                  Pathname.new(File.expand_path("..", bundle_dir))
                end
    end

    def app_config_path
      if app_config = ENV["BUNDLE_APP_CONFIG"]
        app_config_pathname = Pathname.new(app_config)

        if app_config_pathname.absolute?
          app_config_pathname
        else
          app_config_pathname.expand_path(root)
        end
      else
        root.join(".bundle")
      end
    end

    def app_cache(custom_path = nil)
      path = custom_path || root
      Pathname.new(path).join(settings.app_cache_path)
    end

    def tmp(name = Process.pid.to_s)
      Kernel.send(:require, "tmpdir")
      Pathname.new(Dir.mktmpdir(["bundler", name]))
    end

    def rm_rf(path)
      FileUtils.remove_entry_secure(path) if path && File.exist?(path)
    rescue ArgumentError
      message = <<EOF
It is a security vulnerability to allow your home directory to be world-writable, and bundler can not continue.
You should probably consider fixing this issue by running `chmod o-w ~` on *nix.
Please refer to https://ruby-doc.org/stdlib-2.1.2/libdoc/fileutils/rdoc/FileUtils.html#method-c-remove_entry_secure for details.
EOF
      File.world_writable?(path) ? Bundler.ui.warn(message) : raise
      raise PathError, "Please fix the world-writable issue with your #{path} directory"
    end

    def settings
      @settings ||= Settings.new(app_config_path)
    rescue GemfileNotFound
      @settings = Settings.new(Pathname.new(".bundle").expand_path)
    end

    # @return [Hash] Environment present before Bundler was activated
    def original_env
      ORIGINAL_ENV.clone
    end

    # @deprecated Use `unbundled_env` instead
    def clean_env
      Bundler::SharedHelpers.major_deprecation(
        2,
        "`Bundler.clean_env` has been deprecated in favor of `Bundler.unbundled_env`. " \
        "If you instead want the environment before bundler was originally loaded, use `Bundler.original_env`",
        :print_caller_location => true
      )

      unbundled_env
    end

    # @return [Hash] Environment with all bundler-related variables removed
    def unbundled_env
      env = original_env

      if env.key?("BUNDLER_ORIG_MANPATH")
        env["MANPATH"] = env["BUNDLER_ORIG_MANPATH"]
      end

      env.delete_if {|k, _| k[0, 7] == "BUNDLE_" }

      if env.key?("RUBYOPT")
        rubyopt = env["RUBYOPT"].split(" ")
        rubyopt.delete("-r#{File.expand_path("bundler/setup", __dir__)}")
        rubyopt.delete("-rbundler/setup")
        env["RUBYOPT"] = rubyopt.join(" ")
      end

      if env.key?("RUBYLIB")
        rubylib = env["RUBYLIB"].split(File::PATH_SEPARATOR)
        rubylib.delete(File.expand_path("..", __FILE__))
        env["RUBYLIB"] = rubylib.join(File::PATH_SEPARATOR)
      end

      env
    end

    # Run block with environment present before Bundler was activated
    def with_original_env
      with_env(original_env) { yield }
    end

    # @deprecated Use `with_unbundled_env` instead
    def with_clean_env
      Bundler::SharedHelpers.major_deprecation(
        2,
        "`Bundler.with_clean_env` has been deprecated in favor of `Bundler.with_unbundled_env`. " \
        "If you instead want the environment before bundler was originally loaded, use `Bundler.with_original_env`",
        :print_caller_location => true
      )

      with_env(unbundled_env) { yield }
    end

    # Run block with all bundler-related variables removed
    def with_unbundled_env
      with_env(unbundled_env) { yield }
    end

    # Run subcommand with the environment present before Bundler was activated
    def original_system(*args)
      with_original_env { Kernel.system(*args) }
    end

    # @deprecated Use `unbundled_system` instead
    def clean_system(*args)
      Bundler::SharedHelpers.major_deprecation(
        2,
        "`Bundler.clean_system` has been deprecated in favor of `Bundler.unbundled_system`. " \
        "If you instead want to run the command in the environment before bundler was originally loaded, use `Bundler.original_system`",
        :print_caller_location => true
      )

      with_env(unbundled_env) { Kernel.system(*args) }
    end

    # Run subcommand in an environment with all bundler related variables removed
    def unbundled_system(*args)
      with_unbundled_env { Kernel.system(*args) }
    end

    # Run a `Kernel.exec` to a subcommand with the environment present before Bundler was activated
    def original_exec(*args)
      with_original_env { Kernel.exec(*args) }
    end

    # @deprecated Use `unbundled_exec` instead
    def clean_exec(*args)
      Bundler::SharedHelpers.major_deprecation(
        2,
        "`Bundler.clean_exec` has been deprecated in favor of `Bundler.unbundled_exec`. " \
        "If you instead want to exec to a command in the environment before bundler was originally loaded, use `Bundler.original_exec`",
        :print_caller_location => true
      )

      with_env(unbundled_env) { Kernel.exec(*args) }
    end

    # Run a `Kernel.exec` to a subcommand in an environment with all bundler related variables removed
    def unbundled_exec(*args)
      with_env(unbundled_env) { Kernel.exec(*args) }
    end

    def local_platform
      return Gem::Platform::RUBY if settings[:force_ruby_platform] || Gem.platforms == [Gem::Platform::RUBY]
      Gem::Platform.local
    end

    def default_gemfile
      SharedHelpers.default_gemfile
    end

    def default_lockfile
      SharedHelpers.default_lockfile
    end

    def default_bundle_dir
      SharedHelpers.default_bundle_dir
    end

    def system_bindir
      # Gem.bindir doesn't always return the location that RubyGems will install
      # system binaries. If you put '-n foo' in your .gemrc, RubyGems will
      # install binstubs there instead. Unfortunately, RubyGems doesn't expose
      # that directory at all, so rather than parse .gemrc ourselves, we allow
      # the directory to be set as well, via `bundle config set --local bindir foo`.
      Bundler.settings[:system_bindir] || Bundler.rubygems.gem_bindir
    end

    def preferred_gemfile_name
      Bundler.settings[:init_gems_rb] ? "gems.rb" : "Gemfile"
    end

    def use_system_gems?
      configured_bundle_path.use_system_gems?
    end

    def requires_sudo?
      return @requires_sudo if defined?(@requires_sudo_ran)

      sudo_present = which "sudo" if settings.allow_sudo?

      if sudo_present
        # the bundle path and subdirectories need to be writable for RubyGems
        # to be able to unpack and install gems without exploding
        path = bundle_path
        path = path.parent until path.exist?

        # bins are written to a different location on OS X
        bin_dir = Pathname.new(Bundler.system_bindir)
        bin_dir = bin_dir.parent until bin_dir.exist?

        # if any directory is not writable, we need sudo
        files = [path, bin_dir] | Dir[bundle_path.join("build_info/*").to_s] | Dir[bundle_path.join("*").to_s]
        unwritable_files = files.reject {|f| File.writable?(f) }
        sudo_needed = !unwritable_files.empty?
        if sudo_needed
          Bundler.ui.warn "Following files may not be writable, so sudo is needed:\n  #{unwritable_files.map(&:to_s).sort.join("\n  ")}"
        end
      end

      @requires_sudo_ran = true
      @requires_sudo = settings.allow_sudo? && sudo_present && sudo_needed
    end

    def mkdir_p(path, options = {})
      if requires_sudo? && !options[:no_sudo]
        sudo "mkdir -p '#{path}'" unless File.exist?(path)
      else
        SharedHelpers.filesystem_access(path, :write) do |p|
          FileUtils.mkdir_p(p)
        end
      end
    end

    def which(executable)
      if File.file?(executable) && File.executable?(executable)
        executable
      elsif paths = ENV["PATH"]
        quote = '"'.freeze
        paths.split(File::PATH_SEPARATOR).find do |path|
          path = path[1..-2] if path.start_with?(quote) && path.end_with?(quote)
          executable_path = File.expand_path(executable, path)
          return executable_path if File.file?(executable_path) && File.executable?(executable_path)
        end
      end
    end

    def sudo(str)
      SUDO_MUTEX.synchronize do
        prompt = "\n\n" + <<-PROMPT.gsub(/^ {6}/, "").strip + " "
        Your user account isn't allowed to install to the system RubyGems.
        You can cancel this installation and run:

            bundle config set --local path 'vendor/bundle'
            bundle install

        to install the gems into ./vendor/bundle/, or you can enter your password
        and install the bundled gems to RubyGems using sudo.

        Password:
        PROMPT

        unless @prompted_for_sudo ||= system(%(sudo -k -p "#{prompt}" true))
          raise SudoNotPermittedError,
            "Bundler requires sudo access to install at the moment. " \
            "Try installing again, granting Bundler sudo access when prompted, or installing into a different path."
        end

        `sudo -p "#{prompt}" #{str}`
      end
    end

    def read_file(file)
      SharedHelpers.filesystem_access(file, :read) do
        File.open(file, "r:UTF-8", &:read)
      end
    end

    def load_marshal(data)
      Marshal.load(data)
    rescue StandardError => e
      raise MarshalError, "#{e.class}: #{e.message}"
    end

    def load_gemspec(file, validate = false)
      @gemspec_cache ||= {}
      key = File.expand_path(file)
      @gemspec_cache[key] ||= load_gemspec_uncached(file, validate)
      # Protect against caching side-effected gemspecs by returning a
      # new instance each time.
      @gemspec_cache[key].dup if @gemspec_cache[key]
    end

    def load_gemspec_uncached(file, validate = false)
      path = Pathname.new(file)
      contents = read_file(file)
      spec = if contents.start_with?("---") # YAML header
        eval_yaml_gemspec(path, contents)
      else
        # Eval the gemspec from its parent directory, because some gemspecs
        # depend on "./" relative paths.
        SharedHelpers.chdir(path.dirname.to_s) do
          eval_gemspec(path, contents)
        end
      end
      return unless spec
      spec.loaded_from = path.expand_path.to_s
      Bundler.rubygems.validate(spec) if validate
      spec
    end

    def clear_gemspec_cache
      @gemspec_cache = {}
    end

    def git_present?
      return @git_present if defined?(@git_present)
      @git_present = Bundler.which("git") || Bundler.which("git.exe")
    end

    def feature_flag
      @feature_flag ||= FeatureFlag.new(VERSION)
    end

    def reset!
      reset_paths!
      Plugin.reset!
      reset_rubygems!
    end

    def reset_settings_and_root!
      @settings = nil
      @root = nil
    end

    def reset_paths!
      @bin_path = nil
      @bundler_major_version = nil
      @bundle_path = nil
      @configured = nil
      @configured_bundle_path = nil
      @definition = nil
      @load = nil
      @locked_gems = nil
      @root = nil
      @settings = nil
      @setup = nil
      @user_home = nil
    end

    def reset_rubygems!
      return unless defined?(@rubygems) && @rubygems
      rubygems.undo_replacements
      rubygems.reset
      @rubygems = nil
    end

    def configure_gem_home_and_path(path = bundle_path)
      configure_gem_path
      configure_gem_home(path)
      Bundler.rubygems.clear_paths
    end

    private

    def eval_yaml_gemspec(path, contents)
      require_relative "bundler/psyched_yaml"

      # If the YAML is invalid, Syck raises an ArgumentError, and Psych
      # raises a Psych::SyntaxError. See psyched_yaml.rb for more info.
      Gem::Specification.from_yaml(contents)
    rescue YamlLibrarySyntaxError, ArgumentError, Gem::EndOfYAMLException, Gem::Exception
      eval_gemspec(path, contents)
    end

    def eval_gemspec(path, contents)
      eval(contents, TOPLEVEL_BINDING.dup, path.expand_path.to_s)
    rescue ScriptError, StandardError => e
      msg = "There was an error while loading `#{path.basename}`: #{e.message}"

      raise GemspecError, Dsl::DSLError.new(msg, path, e.backtrace, contents)
    end

    def configure_gem_path
      unless use_system_gems?
        # this needs to be empty string to cause
        # PathSupport.split_gem_path to only load up the
        # Bundler --path setting as the GEM_PATH.
        Bundler::SharedHelpers.set_env "GEM_PATH", ""
      end
    end

    def configure_gem_home(path)
      Bundler::SharedHelpers.set_env "GEM_HOME", path.to_s
    end

    def tmp_home_path
      Kernel.send(:require, "tmpdir")
      SharedHelpers.filesystem_access(Dir.tmpdir) do
        path = Bundler.tmp
        at_exit { Bundler.rm_rf(path) }
        path
      end
    end

    # @param env [Hash]
    def with_env(env)
      backup = ENV.to_hash
      ENV.replace(env)
      yield
    ensure
      ENV.replace(backup)
    end
  end
end
#!/opt/alt/ruby30/bin/ruby
# frozen_string_literal: true

# Exit cleanly from an early interrupt
Signal.trap("INT") do
  Bundler.ui.debug("\n#{caller.join("\n")}") if defined?(Bundler)
  exit 1
end

base_path = File.expand_path("../lib", __dir__)

if File.exist?(base_path)
  require_relative "../lib/bundler"
else
  require "bundler"
end

# Workaround for non-activated bundler spec due to missing https://github.com/rubygems/rubygems/commit/4e306d7bcdee924b8d80ca9db6125aa59ee4e5a3
gem "bundler", Bundler::VERSION if Gem.rubygems_version < Gem::Version.new("2.6.2")

# Check if an older version of bundler is installed
$LOAD_PATH.each do |path|
  next unless path =~ %r{/bundler-0\.(\d+)} && $1.to_i < 9
  err = String.new
  err << "Looks like you have a version of bundler that's older than 0.9.\n"
  err << "Please remove your old versions.\n"
  err << "An easy way to do this is by running `gem cleanup bundler`."
  abort(err)
end

if File.exist?(base_path)
  require_relative "../lib/bundler/friendly_errors"
else
  require "bundler/friendly_errors"
end

Bundler.with_friendly_errors do
  if File.exist?(base_path)
    require_relative "../lib/bundler/cli"
  else
    require "bundler/cli"
  end

  # Allow any command to use --help flag to show help for that command
  help_flags = %w[--help -h]
  help_flag_used = ARGV.any? {|a| help_flags.include? a }
  args = help_flag_used ? Bundler::CLI.reformatted_help_args(ARGV) : ARGV

  Bundler::CLI.start(args, :debug => true)
end
#!/opt/alt/ruby30/bin/ruby
# frozen_string_literal: true

load File.expand_path("../bundle", __FILE__)
#!/opt/alt/ruby30/bin/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
#!/opt/alt/ruby30/bin/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

# 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 <tt>rdoc --help</tt> 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 <tt>rake</tt> 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 <drbrain@segment7.net>.
#
# Dave Thomas <dave@pragmaticprogrammer.com> 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
# frozen_string_literal: true
##
# A Mixin adds features from a module into another context.  RDoc::Include and
# RDoc::Extend are both mixins.

class RDoc::Mixin < RDoc::CodeObject

  ##
  # Name of included module

  attr_accessor :name

  ##
  # Creates a new Mixin for +name+ with +comment+

  def initialize(name, comment)
    super()
    @name = name
    self.comment = comment
    @module = nil # cache for module if found
  end

  ##
  # Mixins are sorted by name

  def <=> other
    return unless self.class === other

    name <=> other.name
  end

  def == other # :nodoc:
    self.class === other and @name == other.name
  end

  alias eql? == # :nodoc:

  ##
  # Full name based on #module

  def full_name
    m = self.module
    RDoc::ClassModule === m ? m.full_name : @name
  end

  def hash # :nodoc:
    [@name, self.module].hash
  end

  def inspect # :nodoc:
    "#<%s:0x%x %s.%s %s>" % [
      self.class,
      object_id,
      parent_name, self.class.name.downcase, @name,
    ]
  end

  ##
  # Attempts to locate the included module object.  Returns the name if not
  # known.
  #
  # The scoping rules of Ruby to resolve the name of an included module are:
  # - first look into the children of the current context;
  # - if not found, look into the children of included modules,
  #   in reverse inclusion order;
  # - if still not found, go up the hierarchy of names.
  #
  # This method has <code>O(n!)</code> behavior when the module calling
  # include is referencing nonexistent modules.  Avoid calling #module until
  # after all the files are parsed.  This behavior is due to ruby's constant
  # lookup behavior.
  #
  # As of the beginning of October, 2011, no gem includes nonexistent modules.

  def module
    return @module if @module

    # search the current context
    return @name unless parent
    full_name = parent.child_name(@name)
    @module = @store.modules_hash[full_name]
    return @module if @module
    return @name if @name =~ /^::/

    # search the includes before this one, in reverse order
    searched = parent.includes.take_while { |i| i != self }.reverse
    searched.each do |i|
      inc = i.module
      next if String === inc
      full_name = inc.child_name(@name)
      @module = @store.modules_hash[full_name]
      return @module if @module
    end

    # go up the hierarchy of names
    up = parent.parent
    while up
      full_name = up.child_name(@name)
      @module = @store.modules_hash[full_name]
      return @module if @module
      up = up.parent
    end

    @name
  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:
    "#{self.class.name.downcase} #@name in: #{parent}"
  end

end

# 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
# frozen_string_literal: true
require 'rdoc'
require 'erb'
require 'time'
require 'json'

begin
  require 'webrick'
rescue LoadError
  abort "webrick is not found. You may need to `gem install webrick` to install webrick."
end

##
# This is a WEBrick servlet that allows you to browse ri documentation.
#
# You can show documentation through either `ri --server` or, with RubyGems
# 2.0 or newer, `gem server`.  For ri, the server runs on port 8214 by
# default.  For RubyGems the server runs on port 8808 by default.
#
# You can use this servlet in your own project by mounting it on a WEBrick
# server:
#
#   require 'webrick'
#
#   server = WEBrick::HTTPServer.new Port: 8000
#
#   server.mount '/', RDoc::Servlet
#
# If you want to mount the servlet some other place than the root, provide the
# base path when mounting:
#
#   server.mount '/rdoc', RDoc::Servlet, '/rdoc'

class RDoc::Servlet < WEBrick::HTTPServlet::AbstractServlet

  @server_stores = Hash.new { |hash, server| hash[server] = {} }
  @cache         = Hash.new { |hash, store|  hash[store]  = {} }

  ##
  # Maps an asset type to its path on the filesystem

  attr_reader :asset_dirs

  ##
  # An RDoc::Options instance used for rendering options

  attr_reader :options

  ##
  # Creates an instance of this servlet that shares cached data between
  # requests.

  def self.get_instance server, *options # :nodoc:
    stores = @server_stores[server]

    new server, stores, @cache, *options
  end

  ##
  # Creates a new WEBrick servlet.
  #
  # Use +mount_path+ when mounting the servlet somewhere other than /.
  #
  # Use +extra_doc_dirs+ for additional documentation directories.
  #
  # +server+ is provided automatically by WEBrick when mounting.  +stores+ and
  # +cache+ are provided automatically by the servlet.

  def initialize server, stores, cache, mount_path = nil, extra_doc_dirs = []
    super server

    @cache      = cache
    @mount_path = mount_path
    @extra_doc_dirs = extra_doc_dirs
    @stores     = stores

    @options = RDoc::Options.new
    @options.op_dir = '.'

    darkfish_dir = nil

    # HACK dup
    $LOAD_PATH.each do |path|
      darkfish_dir = File.join path, 'rdoc/generator/template/darkfish/'
      next unless File.directory? darkfish_dir
      @options.template_dir = darkfish_dir
      break
    end

    @asset_dirs = {
      :darkfish   => darkfish_dir,
      :json_index =>
        File.expand_path('../generator/template/json_index/', __FILE__),
    }
  end

  ##
  # Serves the asset at the path in +req+ for +generator_name+ via +res+.

  def asset generator_name, req, res
    asset_dir = @asset_dirs[generator_name]

    asset_path = File.join asset_dir, req.path

    if_modified_since req, res, asset_path

    res.body = File.read asset_path

    res.content_type = case req.path
                       when /\.css\z/ then 'text/css'
                       when /\.js\z/  then 'application/javascript'
                       else                'application/octet-stream'
                       end
  end

  ##
  # GET request entry point.  Fills in +res+ for the path, etc. in +req+.

  def do_GET req, res
    req.path.sub!(/\A#{Regexp.escape @mount_path}/, '') if @mount_path

    case req.path
    when '/' then
      root req, res
    when '/js/darkfish.js', '/js/jquery.js', '/js/search.js',
         %r%^/css/%, %r%^/images/%, %r%^/fonts/% then
      asset :darkfish, req, res
    when '/js/navigation.js', '/js/searcher.js' then
      asset :json_index, req, res
    when '/js/search_index.js' then
      root_search req, res
    else
      show_documentation req, res
    end
  rescue WEBrick::HTTPStatus::NotFound => e
    generator = generator_for RDoc::Store.new

    not_found generator, req, res, e.message
  rescue WEBrick::HTTPStatus::Status
    raise
  rescue => e
    error e, req, res
  end

  ##
  # Fills in +res+ with the class, module or page for +req+ from +store+.
  #
  # +path+ is relative to the mount_path and is used to determine the class,
  # module or page name (/RDoc/Servlet.html becomes RDoc::Servlet).
  # +generator+ is used to create the page.

  def documentation_page store, generator, path, req, res
    text_name = path.chomp '.html'
    name = text_name.gsub '/', '::'

    if klass = store.find_class_or_module(name) then
      res.body = generator.generate_class klass
    elsif page = store.find_text_page(name.sub(/_([^_]*)\z/, '.\1')) then
      res.body = generator.generate_page page
    elsif page = store.find_text_page(text_name.sub(/_([^_]*)\z/, '.\1')) then
      res.body = generator.generate_page page
    else
      not_found generator, req, res
    end
  end

  ##
  # Creates the JSON search index on +res+ for the given +store+.  +generator+
  # must respond to \#json_index to build.  +req+ is ignored.

  def documentation_search store, generator, req, res
    json_index = @cache[store].fetch :json_index do
      @cache[store][:json_index] =
        JSON.dump generator.json_index.build_index
    end

    res.content_type = 'application/javascript'
    res.body = "var search_data = #{json_index}"
  end

  ##
  # Returns the RDoc::Store and path relative to +mount_path+ for
  # documentation at +path+.

  def documentation_source path
    _, source_name, path = path.split '/', 3

    store = @stores[source_name]
    return store, path if store

    store = store_for source_name

    store.load_all

    @stores[source_name] = store

    return store, path
  end

  ##
  # Generates an error page for the +exception+ while handling +req+ on +res+.

  def error exception, req, res
    backtrace = exception.backtrace.join "\n"

    res.content_type = 'text/html'
    res.status = 500
    res.body = <<-BODY
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">

<title>Error - #{ERB::Util.html_escape exception.class}</title>

<link type="text/css" media="screen" href="#{@mount_path}/css/rdoc.css" rel="stylesheet">
</head>
<body>
<h1>Error</h1>

<p>While processing <code>#{ERB::Util.html_escape req.request_uri}</code> the
RDoc (#{ERB::Util.html_escape RDoc::VERSION}) server has encountered a
<code>#{ERB::Util.html_escape exception.class}</code>
exception:

<pre>#{ERB::Util.html_escape exception.message}</pre>

<p>Please report this to the
<a href="https://github.com/ruby/rdoc/issues">RDoc issues tracker</a>.  Please
include the RDoc version, the URI above and exception class, message and
backtrace.  If you're viewing a gem's documentation, include the gem name and
version.  If you're viewing Ruby's documentation, include the version of ruby.

<p>Backtrace:

<pre>#{ERB::Util.html_escape backtrace}</pre>

</body>
</html>
    BODY
  end

  ##
  # Instantiates a Darkfish generator for +store+

  def generator_for store
    generator = RDoc::Generator::Darkfish.new store, @options
    generator.file_output = false
    generator.asset_rel_path = '..'

    rdoc = RDoc::RDoc.new
    rdoc.store     = store
    rdoc.generator = generator
    rdoc.options   = @options

    @options.main_page = store.main
    @options.title     = store.title

    generator
  end

  ##
  # Handles the If-Modified-Since HTTP header on +req+ for +path+.  If the
  # file has not been modified a Not Modified response is returned.  If the
  # file has been modified a Last-Modified header is added to +res+.

  def if_modified_since req, res, path = nil
    last_modified = File.stat(path).mtime if path

    res['last-modified'] = last_modified.httpdate

    return unless ims = req['if-modified-since']

    ims = Time.parse ims

    unless ims < last_modified then
      res.body = ''
      raise WEBrick::HTTPStatus::NotModified
    end
  end

  ##
  # Returns an Array of installed documentation.
  #
  # Each entry contains the documentation name (gem name, 'Ruby
  # Documentation', etc.), the path relative to the mount point, whether the
  # documentation exists, the type of documentation (See RDoc::RI::Paths#each)
  # and the filesystem to the RDoc::Store for the documentation.

  def installed_docs
    extra_counter = 0
    ri_paths.map do |path, type|
      store = RDoc::Store.new path, type
      exists = File.exist? store.cache_path

      case type
      when :gem then
        gem_path = path[%r%/([^/]*)/ri$%, 1]
        [gem_path, "#{gem_path}/", exists, type, path]
      when :system then
        ['Ruby Documentation', 'ruby/', exists, type, path]
      when :site then
        ['Site Documentation', 'site/', exists, type, path]
      when :home then
        ['Home Documentation', 'home/', exists, type, path]
      when :extra then
        extra_counter += 1
        store.load_cache if exists
        title = store.title || "Extra Documentation"
        [title, "extra-#{extra_counter}/", exists, type, path]
      end
    end
  end

  ##
  # Returns a 404 page built by +generator+ for +req+ on +res+.

  def not_found generator, req, res, message = nil
    message ||= "The page <kbd>#{ERB::Util.h req.path}</kbd> was not found"
    res.body = generator.generate_servlet_not_found message
    res.status = 404
  end

  ##
  # Enumerates the ri paths.  See RDoc::RI::Paths#each

  def ri_paths &block
    RDoc::RI::Paths.each true, true, true, :all, *@extra_doc_dirs, &block #TODO: pass extra_dirs
  end

  ##
  # Generates the root page on +res+.  +req+ is ignored.

  def root req, res
    generator = RDoc::Generator::Darkfish.new nil, @options

    res.body = generator.generate_servlet_root installed_docs

    res.content_type = 'text/html'
  end

  ##
  # Generates a search index for the root page on +res+.  +req+ is ignored.

  def root_search req, res
    search_index = []
    info         = []

    installed_docs.map do |name, href, exists, type, path|
      next unless exists

      search_index << name

      case type
      when :gem
        gemspec = path.gsub(%r%/doc/([^/]*?)/ri$%,
                            '/specifications/\1.gemspec')

        spec = Gem::Specification.load gemspec

        path    = spec.full_name
        comment = spec.summary
      when :system then
        path    = 'ruby'
        comment = 'Documentation for the Ruby standard library'
      when :site then
        path    = 'site'
        comment = 'Documentation for non-gem libraries'
      when :home then
        path    = 'home'
        comment = 'Documentation from your home directory'
      when :extra
        comment = name
      end

      info << [name, '', path, '', comment]
    end

    index = {
      :index => {
        :searchIndex     => search_index,
        :longSearchIndex => search_index,
        :info            => info,
      }
    }

    res.body = "var search_data = #{JSON.dump index};"
    res.content_type = 'application/javascript'
  end

  ##
  # Displays documentation for +req+ on +res+, whether that be HTML or some
  # asset.

  def show_documentation req, res
    store, path = documentation_source req.path

    if_modified_since req, res, store.cache_path

    generator = generator_for store

    case path
    when nil, '', 'index.html' then
      res.body = generator.generate_index
    when 'table_of_contents.html' then
      res.body = generator.generate_table_of_contents
    when 'js/search_index.js' then
      documentation_search store, generator, req, res
    else
      documentation_page store, generator, path, req, res
    end
  ensure
    res.content_type ||= 'text/html'
  end

  ##
  # Returns an RDoc::Store for the given +source_name+ ('ruby' or a gem name).

  def store_for source_name
    case source_name
    when 'home' then
      RDoc::Store.new RDoc::RI::Paths.home_dir, :home
    when 'ruby' then
      RDoc::Store.new RDoc::RI::Paths.system_dir, :system
    when 'site' then
      RDoc::Store.new RDoc::RI::Paths.site_dir, :site
    when /\Aextra-(\d+)\z/ then
      index = $1.to_i - 1
      ri_dir = installed_docs[index][4]
      RDoc::Store.new ri_dir, :extra
    else
      ri_dir, type = ri_paths.find do |dir, dir_type|
        next unless dir_type == :gem

        source_name == dir[%r%/([^/]*)/ri$%, 1]
      end

      raise WEBrick::HTTPStatus::NotFound,
            "Could not find gem \"#{ERB::Util.html_escape(source_name)}\". Are you sure you installed it?" unless ri_dir

      store = RDoc::Store.new ri_dir, type

      return store if File.exist? store.cache_path

      raise WEBrick::HTTPStatus::NotFound,
            "Could not find documentation for \"#{ERB::Util.html_escape(source_name)}\". Please run `gem rdoc --ri gem_name`"

    end
  end

end
# 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

# 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

# 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 <tt>--</tt> and end with <tt>++</tt>.
  # 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
# frozen_string_literal: true
##
# A singleton class

class RDoc::SingleClass < RDoc::ClassModule

  ##
  # Adds the superclass to the included modules.

  def ancestors
    superclass ? super + [superclass] : super
  end

  def aref_prefix # :nodoc:
    'sclass'
  end

  ##
  # The definition of this singleton class, <tt>class << MyClassName</tt>

  def definition
    "class << #{full_name}"
  end

end

# frozen_string_literal: true
##
# Collection of methods for writing parsers

module RDoc::Parser::RubyTools

  ##
  # Adds a token listener +obj+, but you should probably use token_listener

  def add_token_listener(obj)
    @token_listeners ||= []
    @token_listeners << obj
  end

  ##
  # Fetches the next token from the scanner

  def get_tk
    tk = nil

    if @tokens.empty? then
      if @scanner_point >= @scanner.size
        return nil
      else
        tk = @scanner[@scanner_point]
        @scanner_point += 1
        @read.push tk[:text]
      end
    else
      @read.push @unget_read.shift
      tk = @tokens.shift
    end

    if tk == nil || :on___end__ == tk[:kind]
      tk = nil
    end

    return nil unless tk

    # inform any listeners of our shiny new token
    @token_listeners.each do |obj|
      obj.add_token(tk)
    end if @token_listeners

    tk
  end

  ##
  # Reads and returns all tokens up to one of +tokens+.  Leaves the matched
  # token in the token list.

  def get_tk_until(*tokens)
    read = []

    loop do
      tk = get_tk

      case tk
      when *tokens then
        unget_tk tk
        break
      end

      read << tk
    end

    read
  end

  ##
  # Retrieves a String representation of the read tokens

  def get_tkread
    read = @read.join("")
    @read = []
    read
  end

  ##
  # Peek equivalent for get_tkread

  def peek_read
    @read.join('')
  end

  ##
  # Peek at the next token, but don't remove it from the stream

  def peek_tk
    unget_tk(tk = get_tk)
    tk
  end

  ##
  # Removes the token listener +obj+

  def remove_token_listener(obj)
    @token_listeners.delete(obj)
  end

  ##
  # Resets the tools

  def reset
    @read       = []
    @tokens     = []
    @unget_read = []
    @nest = 0
    @scanner_point = 0
  end

  ##
  # Skips whitespace tokens including newlines

  def skip_tkspace
    tokens = []

    while (tk = get_tk) and (:on_sp == tk[:kind] or :on_nl == tk[:kind] or :on_ignored_nl == tk[:kind]) do
      tokens.push(tk)
    end

    unget_tk(tk)
    tokens
  end

  ##
  # Skips whitespace tokens excluding newlines

  def skip_tkspace_without_nl
    tokens = []

    while (tk = get_tk) and :on_sp == tk[:kind] do
      tokens.push(tk)
    end

    unget_tk(tk)
    tokens
  end

  ##
  # Has +obj+ listen to tokens

  def token_listener(obj)
    add_token_listener obj
    yield
  ensure
    remove_token_listener obj
  end

  ##
  # Returns +tk+ to the scanner

  def unget_tk(tk)
    @tokens.unshift tk
    @unget_read.unshift @read.pop

    # Remove this token from any listeners
    @token_listeners.each do |obj|
      obj.pop_token
    end if @token_listeners

    nil
  end

end


# frozen_string_literal: true
##
# This file contains stuff stolen outright from:
#
#   rtags.rb -
#   ruby-lex.rb - ruby lexcal analyzer
#   ruby-token.rb - ruby tokens
#       by Keiju ISHITSUKA (Nippon Rational Inc.)
#

##
# Extracts code elements from a source file returning a TopLevel object
# containing the constituent file elements.
#
# This file is based on rtags
#
# RubyParser understands how to document:
# * classes
# * modules
# * methods
# * constants
# * aliases
# * private, public, protected
# * private_class_function, public_class_function
# * private_constant, public_constant
# * module_function
# * attr, attr_reader, attr_writer, attr_accessor
# * extra accessors given on the command line
# * metaprogrammed methods
# * require
# * include
#
# == Method Arguments
#
#--
# NOTE: I don't think this works, needs tests, remove the paragraph following
# this block when known to work
#
# The parser extracts the arguments from the method definition.  You can
# override this with a custom argument definition using the :args: directive:
#
#   ##
#   # This method tries over and over until it is tired
#
#   def go_go_go(thing_to_try, tries = 10) # :args: thing_to_try
#     puts thing_to_try
#     go_go_go thing_to_try, tries - 1
#   end
#
# If you have a more-complex set of overrides you can use the :call-seq:
# directive:
#++
#
# The parser extracts the arguments from the method definition.  You can
# override this with a custom argument definition using the :call-seq:
# directive:
#
#   ##
#   # This method can be called with a range or an offset and length
#   #
#   # :call-seq:
#   #   my_method(Range)
#   #   my_method(offset, length)
#
#   def my_method(*args)
#   end
#
# The parser extracts +yield+ expressions from method bodies to gather the
# yielded argument names.  If your method manually calls a block instead of
# yielding or you want to override the discovered argument names use
# the :yields: directive:
#
#   ##
#   # My method is awesome
#
#   def my_method(&block) # :yields: happy, times
#     block.call 1, 2
#   end
#
# == Metaprogrammed Methods
#
# To pick up a metaprogrammed method, the parser looks for a comment starting
# with '##' before an identifier:
#
#   ##
#   # This is a meta-programmed method!
#
#   add_my_method :meta_method, :arg1, :arg2
#
# The parser looks at the token after the identifier to determine the name, in
# this example, :meta_method.  If a name cannot be found, a warning is printed
# and 'unknown is used.
#
# You can force the name of a method using the :method: directive:
#
#   ##
#   # :method: some_method!
#
# By default, meta-methods are instance methods.  To indicate that a method is
# a singleton method instead use the :singleton-method: directive:
#
#   ##
#   # :singleton-method:
#
# You can also use the :singleton-method: directive with a name:
#
#   ##
#   # :singleton-method: some_method!
#
# You can define arguments for metaprogrammed methods via either the
# :call-seq:, :arg: or :args: directives.
#
# Additionally you can mark a method as an attribute by
# using :attr:, :attr_reader:, :attr_writer: or :attr_accessor:.  Just like
# for :method:, the name is optional.
#
#   ##
#   # :attr_reader: my_attr_name
#
# == Hidden methods and attributes
#
# You can provide documentation for methods that don't appear using
# the :method:, :singleton-method: and :attr: directives:
#
#   ##
#   # :attr_writer: ghost_writer
#   # There is an attribute here, but you can't see it!
#
#   ##
#   # :method: ghost_method
#   # There is a method here, but you can't see it!
#
#   ##
#   # this is a comment for a regular method
#
#   def regular_method() end
#
# Note that by default, the :method: directive will be ignored if there is a
# standard rdocable item following it.

require 'ripper'
require_relative 'ripper_state_lex'

class RDoc::Parser::Ruby < RDoc::Parser

  parse_files_matching(/\.rbw?$/)

  include RDoc::TokenStream
  include RDoc::Parser::RubyTools

  ##
  # RDoc::NormalClass type

  NORMAL = "::"

  ##
  # RDoc::SingleClass type

  SINGLE = "<<"

  ##
  # Creates a new Ruby parser.

  def initialize(top_level, file_name, content, options, stats)
    super

    if /\t/ =~ content then
      tab_width = @options.tab_width
      content = content.split(/\n/).map do |line|
        1 while line.gsub!(/\t+/) {
          ' ' * (tab_width*$&.length - $`.length % tab_width)
        }  && $~
        line
      end.join("\n")
    end

    @size = 0
    @token_listeners = nil
    content = RDoc::Encoding.remove_magic_comment content
    @scanner = RDoc::Parser::RipperStateLex.parse(content)
    @content = content
    @scanner_point = 0
    @prev_seek = nil
    @markup = @options.markup
    @track_visibility = :nodoc != @options.visibility
    @encoding = @options.encoding

    reset
  end

  def tk_nl?(tk)
    :on_nl == tk[:kind] or :on_ignored_nl == tk[:kind]
  end

  ##
  # Retrieves the read token stream and replaces +pattern+ with +replacement+
  # using gsub.  If the result is only a ";" returns an empty string.

  def get_tkread_clean pattern, replacement # :nodoc:
    read = get_tkread.gsub(pattern, replacement).strip
    return '' if read == ';'
    read
  end

  ##
  # Extracts the visibility information for the visibility token +tk+
  # and +single+ class type identifier.
  #
  # Returns the visibility type (a string), the visibility (a symbol) and
  # +singleton+ if the methods following should be converted to singleton
  # methods.

  def get_visibility_information tk, single # :nodoc:
    vis_type  = tk[:text]
    singleton = single == SINGLE

    vis =
      case vis_type
      when 'private'   then :private
      when 'protected' then :protected
      when 'public'    then :public
      when 'private_class_method' then
        singleton = true
        :private
      when 'public_class_method' then
        singleton = true
        :public
      when 'module_function' then
        singleton = true
        :public
      else
        raise RDoc::Error, "Invalid visibility: #{tk.name}"
      end

    return vis_type, vis, singleton
  end

  ##
  # Look for the first comment in a file that isn't a shebang line.

  def collect_first_comment
    skip_tkspace
    comment = ''.dup
    comment = RDoc::Encoding.change_encoding comment, @encoding if @encoding
    first_line = true
    first_comment_tk_kind = nil
    line_no = nil

    tk = get_tk

    while tk && (:on_comment == tk[:kind] or :on_embdoc == tk[:kind])
      comment_body = retrieve_comment_body(tk)
      if first_line and comment_body =~ /\A#!/ then
        skip_tkspace
        tk = get_tk
      elsif first_line and comment_body =~ /\A#\s*-\*-/ then
        first_line = false
        skip_tkspace
        tk = get_tk
      else
        break if first_comment_tk_kind and not first_comment_tk_kind === tk[:kind]
        first_comment_tk_kind = tk[:kind]

        line_no = tk[:line_no] if first_line
        first_line = false
        comment << comment_body
        tk = get_tk

        if :on_nl === tk then
          skip_tkspace_without_nl
          tk = get_tk
        end
      end
    end

    unget_tk tk

    new_comment comment, line_no
  end

  ##
  # Consumes trailing whitespace from the token stream

  def consume_trailing_spaces # :nodoc:
    skip_tkspace_without_nl
  end

  ##
  # Creates a new attribute in +container+ with +name+.

  def create_attr container, single, name, rw, comment # :nodoc:
    att = RDoc::Attr.new get_tkread, name, rw, comment, single == SINGLE
    record_location att

    container.add_attribute att
    @stats.add_attribute att

    att
  end

  ##
  # Creates a module alias in +container+ at +rhs_name+ (or at the top-level
  # for "::") with the name from +constant+.

  def create_module_alias container, constant, rhs_name # :nodoc:
    mod = if rhs_name =~ /^::/ then
            @store.find_class_or_module rhs_name
          else
            container.find_module_named rhs_name
          end

    container.add_module_alias mod, rhs_name, constant, @top_level
  end

  ##
  # Aborts with +msg+

  def error(msg)
    msg = make_message msg

    abort msg
  end

  ##
  # Looks for a true or false token.

  def get_bool
    skip_tkspace
    tk = get_tk
    if :on_kw == tk[:kind] && 'true' == tk[:text]
      true
    elsif :on_kw == tk[:kind] && ('false' == tk[:text] || 'nil' == tk[:text])
      false
    else
      unget_tk tk
      true
    end
  end

  ##
  # Look for the name of a class of module (optionally with a leading :: or
  # with :: separated named) and return the ultimate name, the associated
  # container, and the given name (with the ::).

  def get_class_or_module container, ignore_constants = false
    skip_tkspace
    name_t = get_tk
    given_name = ''.dup

    # class ::A -> A is in the top level
    if :on_op == name_t[:kind] and '::' == name_t[:text] then # bug
      name_t = get_tk
      container = @top_level
      given_name << '::'
    end

    skip_tkspace_without_nl
    given_name << name_t[:text]

    is_self = name_t[:kind] == :on_op && name_t[:text] == '<<'
    new_modules = []
    while !is_self && (tk = peek_tk) and :on_op == tk[:kind] and '::' == tk[:text] do
      prev_container = container
      container = container.find_module_named name_t[:text]
      container ||=
        if ignore_constants then
          c = RDoc::NormalModule.new name_t[:text]
          c.store = @store
          new_modules << [prev_container, c]
          c
        else
          c = prev_container.add_module RDoc::NormalModule, name_t[:text]
          c.ignore unless prev_container.document_children
          @top_level.add_to_classes_or_modules c
          c
        end

      record_location container

      get_tk
      skip_tkspace
      if :on_lparen == peek_tk[:kind] # ProcObjectInConstant::()
        parse_method_or_yield_parameters
        break
      end
      name_t = get_tk
      unless :on_const == name_t[:kind] || :on_ident == name_t[:kind]
        raise RDoc::Error, "Invalid class or module definition: #{given_name}"
      end
      if prev_container == container and !ignore_constants
        given_name = name_t[:text]
      else
        given_name << '::' + name_t[:text]
      end
    end

    skip_tkspace_without_nl

    return [container, name_t, given_name, new_modules]
  end

  ##
  # Return a superclass, which can be either a constant of an expression

  def get_class_specification
    tk = peek_tk
    if tk.nil?
      return ''
    elsif :on_kw == tk[:kind] && 'self' == tk[:text]
      return 'self'
    elsif :on_gvar == tk[:kind]
      return ''
    end

    res = get_constant

    skip_tkspace_without_nl

    get_tkread # empty out read buffer

    tk = get_tk
    return res unless tk

    case tk[:kind]
    when :on_nl, :on_comment, :on_embdoc, :on_semicolon then
      unget_tk(tk)
      return res
    end

    res += parse_call_parameters(tk)
    res
  end

  ##
  # Parse a constant, which might be qualified by one or more class or module
  # names

  def get_constant
    res = ""
    skip_tkspace_without_nl
    tk = get_tk

    while tk && ((:on_op == tk[:kind] && '::' == tk[:text]) || :on_const == tk[:kind]) do
      res += tk[:text]
      tk = get_tk
    end

    unget_tk(tk)
    res
  end

  ##
  # Get an included module that may be surrounded by parens

  def get_included_module_with_optional_parens
    skip_tkspace_without_nl
    get_tkread
    tk = get_tk
    end_token = get_end_token tk
    return '' unless end_token

    nest = 0
    continue = false
    only_constant = true

    while tk != nil do
      is_element_of_constant = false
      case tk[:kind]
      when :on_semicolon then
        break if nest == 0
      when :on_lbracket then
        nest += 1
      when :on_rbracket then
        nest -= 1
      when :on_lbrace then
        nest += 1
      when :on_rbrace then
        nest -= 1
        if nest <= 0
          # we might have a.each { |i| yield i }
          unget_tk(tk) if nest < 0
          break
        end
      when :on_lparen then
        nest += 1
      when end_token[:kind] then
        if end_token[:kind] == :on_rparen
          nest -= 1
          break if nest <= 0
        else
          break if nest <= 0
        end
      when :on_rparen then
        nest -= 1
      when :on_comment, :on_embdoc then
        @read.pop
        if :on_nl == end_token[:kind] and "\n" == tk[:text][-1] and
          (!continue or (tk[:state] & RDoc::Parser::RipperStateLex::EXPR_LABEL) != 0) then
          break if !continue and nest <= 0
        end
      when :on_comma then
        continue = true
      when :on_ident then
        continue = false if continue
      when :on_kw then
        case tk[:text]
        when 'def', 'do', 'case', 'for', 'begin', 'class', 'module'
          nest += 1
        when 'if', 'unless', 'while', 'until', 'rescue'
          # postfix if/unless/while/until/rescue must be EXPR_LABEL
          nest += 1 unless (tk[:state] & RDoc::Parser::RipperStateLex::EXPR_LABEL) != 0
        when 'end'
          nest -= 1
          break if nest == 0
        end
      when :on_const then
        is_element_of_constant = true
      when :on_op then
        is_element_of_constant = true if '::' == tk[:text]
      end
      only_constant = false unless is_element_of_constant
      tk = get_tk
    end

    if only_constant
      get_tkread_clean(/\s+/, ' ')
    else
      ''
    end
  end

  ##
  # Little hack going on here. In the statement:
  #
  #   f = 2*(1+yield)
  #
  # We see the RPAREN as the next token, so we need to exit early.  This still
  # won't catch all cases (such as "a = yield + 1"

  def get_end_token tk # :nodoc:
    case tk[:kind]
    when :on_lparen
      token = RDoc::Parser::RipperStateLex::Token.new
      token[:kind] = :on_rparen
      token[:text] = ')'
      token
    when :on_rparen
      nil
    else
      token = RDoc::Parser::RipperStateLex::Token.new
      token[:kind] = :on_nl
      token[:text] = "\n"
      token
    end
  end

  ##
  # Retrieves the method container for a singleton method.

  def get_method_container container, name_t # :nodoc:
    prev_container = container
    container = container.find_module_named(name_t[:text])

    unless container then
      constant = prev_container.constants.find do |const|
        const.name == name_t[:text]
      end

      if constant then
        parse_method_dummy prev_container
        return
      end
    end

    unless container then
      # TODO seems broken, should starting at Object in @store
      obj = name_t[:text].split("::").inject(Object) do |state, item|
        state.const_get(item)
      end rescue nil

      type = obj.class == Class ? RDoc::NormalClass : RDoc::NormalModule

      unless [Class, Module].include?(obj.class) then
        warn("Couldn't find #{name_t[:text]}. Assuming it's a module")
      end

      if type == RDoc::NormalClass then
        sclass = obj.superclass ? obj.superclass.name : nil
        container = prev_container.add_class type, name_t[:text], sclass
      else
        container = prev_container.add_module type, name_t[:text]
      end

      record_location container
    end

    container
  end

  ##
  # Extracts a name or symbol from the token stream.

  def get_symbol_or_name
    tk = get_tk
    case tk[:kind]
    when :on_symbol then
      text = tk[:text].sub(/^:/, '')

      next_tk = peek_tk
      if next_tk && :on_op == next_tk[:kind] && '=' == next_tk[:text] then
        get_tk
        text << '='
      end

      text
    when :on_ident, :on_const, :on_gvar, :on_cvar, :on_ivar, :on_op, :on_kw then
      tk[:text]
    when :on_tstring, :on_dstring then
      tk[:text][1..-2]
    else
      raise RDoc::Error, "Name or symbol expected (got #{tk})"
    end
  end

  ##
  # Marks containers between +container+ and +ancestor+ as ignored

  def suppress_parents container, ancestor # :nodoc:
    while container and container != ancestor do
      container.suppress unless container.documented?
      container = container.parent
    end
  end

  ##
  # Look for directives in a normal comment block:
  #
  #   # :stopdoc:
  #   # Don't display comment from this point forward
  #
  # This routine modifies its +comment+ parameter.

  def look_for_directives_in container, comment
    @preprocess.handle comment, container do |directive, param|
      case directive
      when 'method', 'singleton-method',
           'attr', 'attr_accessor', 'attr_reader', 'attr_writer' then
        false # handled elsewhere
      when 'section' then
        break unless container.kind_of?(RDoc::Context)
        container.set_current_section param, comment.dup
        comment.text = ''
        break
      end
    end

    comment.remove_private
  end

  ##
  # Adds useful info about the parser to +message+

  def make_message message
    prefix = "#{@file_name}:".dup

    tk = peek_tk
    prefix << "#{tk[:line_no]}:#{tk[:char_no]}:" if tk

    "#{prefix} #{message}"
  end

  ##
  # Creates a comment with the correct format

  def new_comment comment, line_no = nil
    c = RDoc::Comment.new comment, @top_level, :ruby
    c.line = line_no
    c.format = @markup
    c
  end

  ##
  # Creates an RDoc::Attr for the name following +tk+, setting the comment to
  # +comment+.

  def parse_attr(context, single, tk, comment)
    line_no = tk[:line_no]

    args = parse_symbol_arg 1
    if args.size > 0 then
      name = args[0]
      rw = "R"
      skip_tkspace_without_nl
      tk = get_tk

      if :on_comma == tk[:kind] then
        rw = "RW" if get_bool
      else
        unget_tk tk
      end

      att = create_attr context, single, name, rw, comment
      att.line   = line_no

      read_documentation_modifiers att, RDoc::ATTR_MODIFIERS
    else
      warn "'attr' ignored - looks like a variable"
    end
  end

  ##
  # Creates an RDoc::Attr for each attribute listed after +tk+, setting the
  # comment for each to +comment+.

  def parse_attr_accessor(context, single, tk, comment)
    line_no = tk[:line_no]

    args = parse_symbol_arg
    rw = "?"

    tmp = RDoc::CodeObject.new
    read_documentation_modifiers tmp, RDoc::ATTR_MODIFIERS
    # TODO In most other places we let the context keep track of document_self
    # and add found items appropriately but here we do not.  I'm not sure why.
    return if @track_visibility and not tmp.document_self

    case tk[:text]
    when "attr_reader"   then rw = "R"
    when "attr_writer"   then rw = "W"
    when "attr_accessor" then rw = "RW"
    else
      rw = '?'
    end

    for name in args
      att = create_attr context, single, name, rw, comment
      att.line   = line_no
    end
  end

  ##
  # Parses an +alias+ in +context+ with +comment+

  def parse_alias(context, single, tk, comment)
    line_no = tk[:line_no]

    skip_tkspace

    if :on_lparen === peek_tk[:kind] then
      get_tk
      skip_tkspace
    end

    new_name = get_symbol_or_name

    skip_tkspace
    if :on_comma === peek_tk[:kind] then
      get_tk
      skip_tkspace
    end

    begin
      old_name = get_symbol_or_name
    rescue RDoc::Error
      return
    end

    al = RDoc::Alias.new(get_tkread, old_name, new_name, comment,
                         single == SINGLE)
    record_location al
    al.line   = line_no

    read_documentation_modifiers al, RDoc::ATTR_MODIFIERS
    context.add_alias al
    @stats.add_alias al

    al
  end

  ##
  # Extracts call parameters from the token stream.

  def parse_call_parameters(tk)
    end_token = case tk[:kind]
                when :on_lparen
                  :on_rparen
                when :on_rparen
                  return ""
                else
                  :on_nl
                end
    nest = 0

    loop do
      break if tk.nil?
      case tk[:kind]
      when :on_semicolon
        break
      when :on_lparen
        nest += 1
      when end_token
        if end_token == :on_rparen
          nest -= 1
          break if RDoc::Parser::RipperStateLex.end?(tk) and nest <= 0
        else
          break if RDoc::Parser::RipperStateLex.end?(tk)
        end
      when :on_comment, :on_embdoc
        unget_tk(tk)
        break
      when :on_op
        if tk[:text] =~ /^(.{1,2})?=$/
          unget_tk(tk)
          break
        end
      end
      tk = get_tk
    end

    get_tkread_clean "\n", " "
  end

  ##
  # Parses a class in +context+ with +comment+

  def parse_class container, single, tk, comment
    line_no = tk[:line_no]

    declaration_context = container
    container, name_t, given_name, = get_class_or_module container

    if name_t[:kind] == :on_const
      cls = parse_class_regular container, declaration_context, single,
        name_t, given_name, comment
    elsif name_t[:kind] == :on_op && name_t[:text] == '<<'
      case name = get_class_specification
      when 'self', container.name
        read_documentation_modifiers cls, RDoc::CLASS_MODIFIERS
        parse_statements container, SINGLE
        return # don't update line
      else
        cls = parse_class_singleton container, name, comment
      end
    else
      warn "Expected class name or '<<'. Got #{name_t[:kind]}: #{name_t[:text].inspect}"
      return
    end

    cls.line   = line_no

    # after end modifiers
    read_documentation_modifiers cls, RDoc::CLASS_MODIFIERS

    cls
  end

  ##
  # Parses and creates a regular class

  def parse_class_regular container, declaration_context, single, # :nodoc:
                          name_t, given_name, comment
    superclass = '::Object'

    if given_name =~ /^::/ then
      declaration_context = @top_level
      given_name = $'
    end

    tk = peek_tk
    if tk[:kind] == :on_op && tk[:text] == '<' then
      get_tk
      skip_tkspace
      superclass = get_class_specification
      superclass = '(unknown)' if superclass.empty?
    end

    cls_type = single == SINGLE ? RDoc::SingleClass : RDoc::NormalClass
    cls = declaration_context.add_class cls_type, given_name, superclass
    cls.ignore unless container.document_children

    read_documentation_modifiers cls, RDoc::CLASS_MODIFIERS
    record_location cls

    cls.add_comment comment, @top_level

    @top_level.add_to_classes_or_modules cls
    @stats.add_class cls

    suppress_parents container, declaration_context unless cls.document_self

    parse_statements cls

    cls
  end

  ##
  # Parses a singleton class in +container+ with the given +name+ and
  # +comment+.

  def parse_class_singleton container, name, comment # :nodoc:
    other = @store.find_class_named name

    unless other then
      if name =~ /^::/ then
        name = $'
        container = @top_level
      end

      other = container.add_module RDoc::NormalModule, name
      record_location other

      # class << $gvar
      other.ignore if name.empty?

      other.add_comment comment, @top_level
    end

    # notify :nodoc: all if not a constant-named class/module
    # (and remove any comment)
    unless name =~ /\A(::)?[A-Z]/ then
      other.document_self = nil
      other.document_children = false
      other.clear_comment
    end

    @top_level.add_to_classes_or_modules other
    @stats.add_class other

    read_documentation_modifiers other, RDoc::CLASS_MODIFIERS
    parse_statements(other, SINGLE)

    other
  end

  ##
  # Parses a constant in +context+ with +comment+.  If +ignore_constants+ is
  # true, no found constants will be added to RDoc.

  def parse_constant container, tk, comment, ignore_constants = false
    line_no = tk[:line_no]

    name = tk[:text]
    skip_tkspace_without_nl

    return unless name =~ /^\w+$/

    new_modules = []
    if :on_op == peek_tk[:kind] && '::' == peek_tk[:text] then
      unget_tk tk

      container, name_t, _, new_modules = get_class_or_module container, true

      name = name_t[:text]
    end

    is_array_or_hash = false
    if peek_tk && :on_lbracket == peek_tk[:kind]
      get_tk
      nest = 1
      while bracket_tk = get_tk
        case bracket_tk[:kind]
        when :on_lbracket
          nest += 1
        when :on_rbracket
          nest -= 1
          break if nest == 0
        end
      end
      skip_tkspace_without_nl
      is_array_or_hash = true
    end

    unless peek_tk && :on_op == peek_tk[:kind] && '=' == peek_tk[:text] then
      return false
    end
    get_tk

    unless ignore_constants
      new_modules.each do |prev_c, new_module|
        prev_c.add_module_by_normal_module new_module
        new_module.ignore unless prev_c.document_children
        @top_level.add_to_classes_or_modules new_module
      end
    end

    value = ''
    con = RDoc::Constant.new name, value, comment

    body = parse_constant_body container, con, is_array_or_hash

    return unless body

    con.value = body
    record_location con
    con.line   = line_no
    read_documentation_modifiers con, RDoc::CONSTANT_MODIFIERS

    return if is_array_or_hash

    @stats.add_constant con
    container.add_constant con

    true
  end

  def parse_constant_body container, constant, is_array_or_hash # :nodoc:
    nest     = 0
    rhs_name = ''.dup

    get_tkread

    tk = get_tk

    body = nil
    loop do
      break if tk.nil?
      if :on_semicolon == tk[:kind] then
        break if nest <= 0
      elsif [:on_tlambeg, :on_lparen, :on_lbrace, :on_lbracket].include?(tk[:kind]) then
        nest += 1
      elsif (:on_kw == tk[:kind] && 'def' == tk[:text]) then
        nest += 1
      elsif (:on_kw == tk[:kind] && %w{do if unless case begin}.include?(tk[:text])) then
        if (tk[:state] & RDoc::Parser::RipperStateLex::EXPR_LABEL) == 0
          nest += 1
        end
      elsif [:on_rparen, :on_rbrace, :on_rbracket].include?(tk[:kind]) ||
            (:on_kw == tk[:kind] && 'end' == tk[:text]) then
        nest -= 1
      elsif (:on_comment == tk[:kind] or :on_embdoc == tk[:kind]) then
        unget_tk tk
        if nest <= 0 and RDoc::Parser::RipperStateLex.end?(tk) then
          body = get_tkread_clean(/^[ \t]+/, '')
          read_documentation_modifiers constant, RDoc::CONSTANT_MODIFIERS
          break
        else
          read_documentation_modifiers constant, RDoc::CONSTANT_MODIFIERS
        end
      elsif :on_const == tk[:kind] then
        rhs_name << tk[:text]

        next_tk = peek_tk
        if nest <= 0 and (next_tk.nil? || :on_nl == next_tk[:kind]) then
          create_module_alias container, constant, rhs_name unless is_array_or_hash
          break
        end
      elsif :on_nl == tk[:kind] then
        if nest <= 0 and RDoc::Parser::RipperStateLex.end?(tk) then
          unget_tk tk
          break
        end
      elsif :on_op == tk[:kind] && '::' == tk[:text]
        rhs_name << '::'
      end
      tk = get_tk
    end

    body ? body : get_tkread_clean(/^[ \t]+/, '')
  end

  ##
  # Generates an RDoc::Method or RDoc::Attr from +comment+ by looking for
  # :method: or :attr: directives in +comment+.

  def parse_comment container, tk, comment
    return parse_comment_tomdoc container, tk, comment if @markup == 'tomdoc'
    column  = tk[:char_no]
    line_no = comment.line.nil? ? tk[:line_no] : comment.line

    comment.text = comment.text.sub(/(^# +:?)(singleton-)(method:)/, '\1\3')
    singleton = !!$~

    co =
      if (comment.text = comment.text.sub(/^# +:?method: *(\S*).*?\n/i, '')) && !!$~ then
        line_no += $`.count("\n")
        parse_comment_ghost container, comment.text, $1, column, line_no, comment
      elsif (comment.text = comment.text.sub(/# +:?(attr(_reader|_writer|_accessor)?): *(\S*).*?\n/i, '')) && !!$~ then
        parse_comment_attr container, $1, $3, comment
      end

    if co then
      co.singleton = singleton
      co.line      = line_no
    end

    true
  end

  ##
  # Parse a comment that is describing an attribute in +container+ with the
  # given +name+ and +comment+.

  def parse_comment_attr container, type, name, comment # :nodoc:
    return if name.empty?

    rw = case type
         when 'attr_reader' then 'R'
         when 'attr_writer' then 'W'
         else 'RW'
         end

    create_attr container, NORMAL, name, rw, comment
  end

  def parse_comment_ghost container, text, name, column, line_no, # :nodoc:
                          comment
    name = nil if name.empty?

    meth = RDoc::GhostMethod.new get_tkread, name
    record_location meth

    meth.start_collecting_tokens
    indent = RDoc::Parser::RipperStateLex::Token.new(1, 1, :on_sp, ' ' * column)
    position_comment = RDoc::Parser::RipperStateLex::Token.new(line_no, 1, :on_comment)
    position_comment[:text] = "# File #{@top_level.relative_name}, line #{line_no}"
    newline = RDoc::Parser::RipperStateLex::Token.new(0, 0, :on_nl, "\n")
    meth.add_tokens [position_comment, newline, indent]

    meth.params =
      if text.sub!(/^#\s+:?args?:\s*(.*?)\s*$/i, '') then
        $1
      else
        ''
      end

    comment.normalize
    comment.extract_call_seq meth

    return unless meth.name

    container.add_method meth

    meth.comment = comment

    @stats.add_method meth

    meth
  end

  ##
  # Creates an RDoc::Method on +container+ from +comment+ if there is a
  # Signature section in the comment

  def parse_comment_tomdoc container, tk, comment
    return unless signature = RDoc::TomDoc.signature(comment)
    column  = tk[:char_no]
    line_no = tk[:line_no]

    name, = signature.split %r%[ \(]%, 2

    meth = RDoc::GhostMethod.new get_tkread, name
    record_location meth
    meth.line      = line_no

    meth.start_collecting_tokens
    indent = RDoc::Parser::RipperStateLex::Token.new(1, 1, :on_sp, ' ' * column)
    position_comment = RDoc::Parser::RipperStateLex::Token.new(line_no, 1, :on_comment)
    position_comment[:text] = "# File #{@top_level.relative_name}, line #{line_no}"
    newline = RDoc::Parser::RipperStateLex::Token.new(0, 0, :on_nl, "\n")
    meth.add_tokens [position_comment, newline, indent]

    meth.call_seq = signature

    comment.normalize

    return unless meth.name

    container.add_method meth

    meth.comment = comment

    @stats.add_method meth
  end

  ##
  # Parses an +include+ or +extend+, indicated by the +klass+ and adds it to
  # +container+ # with +comment+

  def parse_extend_or_include klass, container, comment # :nodoc:
    loop do
      skip_tkspace_comment

      name = get_included_module_with_optional_parens

      unless name.empty? then
        obj = container.add klass, name, comment
        record_location obj
      end

      return if peek_tk.nil? || :on_comma != peek_tk[:kind]

      get_tk
    end
  end

  ##
  # Parses identifiers that can create new methods or change visibility.
  #
  # Returns true if the comment was not consumed.

  def parse_identifier container, single, tk, comment # :nodoc:
    case tk[:text]
    when 'private', 'protected', 'public', 'private_class_method',
         'public_class_method', 'module_function' then
      parse_visibility container, single, tk
      return true
    when 'private_constant', 'public_constant'
      parse_constant_visibility container, single, tk
      return true
    when 'attr' then
      parse_attr container, single, tk, comment
    when /^attr_(reader|writer|accessor)$/ then
      parse_attr_accessor container, single, tk, comment
    when 'alias_method' then
      parse_alias container, single, tk, comment
    when 'require', 'include' then
      # ignore
    else
      if comment.text =~ /\A#\#$/ then
        case comment.text
        when /^# +:?attr(_reader|_writer|_accessor)?:/ then
          parse_meta_attr container, single, tk, comment
        else
          method = parse_meta_method container, single, tk, comment
          method.params = container.params if
            container.params
          method.block_params = container.block_params if
            container.block_params
        end
      end
    end

    false
  end

  ##
  # Parses a meta-programmed attribute and creates an RDoc::Attr.
  #
  # To create foo and bar attributes on class C with comment "My attributes":
  #
  #   class C
  #
  #     ##
  #     # :attr:
  #     #
  #     # My attributes
  #
  #     my_attr :foo, :bar
  #
  #   end
  #
  # To create a foo attribute on class C with comment "My attribute":
  #
  #   class C
  #
  #     ##
  #     # :attr: foo
  #     #
  #     # My attribute
  #
  #     my_attr :foo, :bar
  #
  #   end

  def parse_meta_attr(context, single, tk, comment)
    args = parse_symbol_arg
    rw = "?"

    # If nodoc is given, don't document any of them

    tmp = RDoc::CodeObject.new
    read_documentation_modifiers tmp, RDoc::ATTR_MODIFIERS

    regexp = /^# +:?(attr(_reader|_writer|_accessor)?): *(\S*).*?\n/i
    if regexp =~ comment.text then
      comment.text = comment.text.sub(regexp, '')
      rw = case $1
           when 'attr_reader' then 'R'
           when 'attr_writer' then 'W'
           else 'RW'
           end
      name = $3 unless $3.empty?
    end

    if name then
      att = create_attr context, single, name, rw, comment
    else
      args.each do |attr_name|
        att = create_attr context, single, attr_name, rw, comment
      end
    end

    att
  end

  ##
  # Parses a meta-programmed method

  def parse_meta_method(container, single, tk, comment)
    column  = tk[:char_no]
    line_no = tk[:line_no]

    start_collecting_tokens
    add_token tk
    add_token_listener self

    skip_tkspace_without_nl

    comment.text = comment.text.sub(/(^# +:?)(singleton-)(method:)/, '\1\3')
    singleton = !!$~

    name = parse_meta_method_name comment, tk

    return unless name

    meth = RDoc::MetaMethod.new get_tkread, name
    record_location meth
    meth.line   = line_no
    meth.singleton = singleton

    remove_token_listener self

    meth.start_collecting_tokens
    indent = RDoc::Parser::RipperStateLex::Token.new(1, 1, :on_sp, ' ' * column)
    position_comment = RDoc::Parser::RipperStateLex::Token.new(line_no, 1, :on_comment)
    position_comment[:text] = "# File #{@top_level.relative_name}, line #{line_no}"
    newline = RDoc::Parser::RipperStateLex::Token.new(0, 0, :on_nl, "\n")
    meth.add_tokens [position_comment, newline, indent]
    meth.add_tokens @token_stream

    parse_meta_method_params container, single, meth, tk, comment

    meth.comment = comment

    @stats.add_method meth

    meth
  end

  ##
  # Parses the name of a metaprogrammed method.  +comment+ is used to
  # determine the name while +tk+ is used in an error message if the name
  # cannot be determined.

  def parse_meta_method_name comment, tk # :nodoc:
    if comment.text.sub!(/^# +:?method: *(\S*).*?\n/i, '') then
      return $1 unless $1.empty?
    end

    name_t = get_tk

    if :on_symbol == name_t[:kind] then
      name_t[:text][1..-1]
    elsif :on_tstring == name_t[:kind] then
      name_t[:text][1..-2]
    elsif :on_op == name_t[:kind] && '=' == name_t[:text] then # ignore
      remove_token_listener self

      nil
    else
      warn "unknown name token #{name_t.inspect} for meta-method '#{tk[:text]}'"
      'unknown'
    end
  end

  ##
  # Parses the parameters and block for a meta-programmed method.

  def parse_meta_method_params container, single, meth, tk, comment # :nodoc:
    token_listener meth do
      meth.params = ''

      look_for_directives_in meth, comment
      comment.normalize
      comment.extract_call_seq meth

      container.add_method meth

      last_tk = tk

      while tk = get_tk do
        if :on_semicolon == tk[:kind] then
          break
        elsif :on_nl == tk[:kind] then
          break unless last_tk and :on_comma == last_tk[:kind]
        elsif :on_sp == tk[:kind] then
          # expression continues
        elsif :on_kw == tk[:kind] && 'do' == tk[:text] then
          parse_statements container, single, meth
          break
        else
          last_tk = tk
        end
      end
    end
  end

  ##
  # Parses a normal method defined by +def+

  def parse_method(container, single, tk, comment)
    singleton = nil
    added_container = false
    name = nil
    column  = tk[:char_no]
    line_no = tk[:line_no]

    start_collecting_tokens
    add_token tk

    token_listener self do
      prev_container = container
      name, container, singleton = parse_method_name container
      added_container = container != prev_container
    end

    return unless name

    meth = RDoc::AnyMethod.new get_tkread, name
    look_for_directives_in meth, comment
    meth.singleton = single == SINGLE ? true : singleton

    record_location meth
    meth.line   = line_no

    meth.start_collecting_tokens
    indent = RDoc::Parser::RipperStateLex::Token.new(1, 1, :on_sp, ' ' * column)
    token = RDoc::Parser::RipperStateLex::Token.new(line_no, 1, :on_comment)
    token[:text] = "# File #{@top_level.relative_name}, line #{line_no}"
    newline = RDoc::Parser::RipperStateLex::Token.new(0, 0, :on_nl, "\n")
    meth.add_tokens [token, newline, indent]
    meth.add_tokens @token_stream

    parse_method_params_and_body container, single, meth, added_container

    comment.normalize
    comment.extract_call_seq meth

    meth.comment = comment

    # after end modifiers
    read_documentation_modifiers meth, RDoc::METHOD_MODIFIERS

    @stats.add_method meth
  end

  ##
  # Parses the parameters and body of +meth+

  def parse_method_params_and_body container, single, meth, added_container
    token_listener meth do
      parse_method_parameters meth

      if meth.document_self or not @track_visibility then
        container.add_method meth
      elsif added_container then
        container.document_self = false
      end

      # Having now read the method parameters and documentation modifiers, we
      # now know whether we have to rename #initialize to ::new

      if meth.name == "initialize" && !meth.singleton then
        if meth.dont_rename_initialize then
          meth.visibility = :protected
        else
          meth.singleton = true
          meth.name = "new"
          meth.visibility = :public
        end
      end

      parse_statements container, single, meth
    end
  end

  ##
  # Parses a method that needs to be ignored.

  def parse_method_dummy container
    dummy = RDoc::Context.new
    dummy.parent = container
    dummy.store  = container.store
    skip_method dummy
  end

  ##
  # Parses the name of a method in +container+.
  #
  # Returns the method name, the container it is in (for def Foo.name) and if
  # it is a singleton or regular method.

  def parse_method_name container # :nodoc:
    skip_tkspace
    name_t = get_tk
    back_tk = skip_tkspace_without_nl
    singleton = false

    dot = get_tk
    if dot[:kind] == :on_period || (dot[:kind] == :on_op && dot[:text] == '::') then
      singleton = true

      name, container = parse_method_name_singleton container, name_t
    else
      unget_tk dot
      back_tk.reverse_each do |token|
        unget_tk token
      end

      name = parse_method_name_regular container, name_t
    end

    return name, container, singleton
  end

  ##
  # For the given +container+ and initial name token +name_t+ the method name
  # is parsed from the token stream for a regular method.

  def parse_method_name_regular container, name_t # :nodoc:
    if :on_op == name_t[:kind] && (%w{* & [] []= <<}.include?(name_t[:text])) then
      name_t[:text]
    else
      unless [:on_kw, :on_const, :on_ident].include?(name_t[:kind]) then
        warn "expected method name token, . or ::, got #{name_t.inspect}"
        skip_method container
        return
      end
      name_t[:text]
    end
  end

  ##
  # For the given +container+ and initial name token +name_t+ the method name
  # and the new +container+ (if necessary) are parsed from the token stream
  # for a singleton method.

  def parse_method_name_singleton container, name_t # :nodoc:
    skip_tkspace
    name_t2 = get_tk

    if (:on_kw == name_t[:kind] && 'self' == name_t[:text]) || (:on_op == name_t[:kind] && '%' == name_t[:text]) then
      # NOTE: work around '[' being consumed early
      if :on_lbracket == name_t2[:kind]
        get_tk
        name = '[]'
      else
        name = name_t2[:text]
      end
    elsif :on_const == name_t[:kind] then
      name = name_t2[:text]

      container = get_method_container container, name_t

      return unless container

      name
    elsif :on_ident == name_t[:kind] || :on_ivar == name_t[:kind] || :on_gvar == name_t[:kind] then
      parse_method_dummy container

      name = nil
    elsif (:on_kw == name_t[:kind]) && ('true' == name_t[:text] || 'false' == name_t[:text] || 'nil' == name_t[:text]) then
      klass_name = "#{name_t[:text].capitalize}Class"
      container = @store.find_class_named klass_name
      container ||= @top_level.add_class RDoc::NormalClass, klass_name

      name = name_t2[:text]
    else
      warn "unexpected method name token #{name_t.inspect}"
      # break
      skip_method container

      name = nil
    end

    return name, container
  end

  ##
  # Extracts +yield+ parameters from +method+

  def parse_method_or_yield_parameters(method = nil,
                                       modifiers = RDoc::METHOD_MODIFIERS)
    skip_tkspace_without_nl
    tk = get_tk
    end_token = get_end_token tk
    return '' unless end_token

    nest = 0
    continue = false

    while tk != nil do
      case tk[:kind]
      when :on_semicolon then
        break if nest == 0
      when :on_lbracket then
        nest += 1
      when :on_rbracket then
        nest -= 1
      when :on_lbrace then
        nest += 1
      when :on_rbrace then
        nest -= 1
        if nest <= 0
          # we might have a.each { |i| yield i }
          unget_tk(tk) if nest < 0
          break
        end
      when :on_lparen then
        nest += 1
      when end_token[:kind] then
        if end_token[:kind] == :on_rparen
          nest -= 1
          break if nest <= 0
        else
          break
        end
      when :on_rparen then
        nest -= 1
      when :on_comment, :on_embdoc then
        @read.pop
        if :on_nl == end_token[:kind] and "\n" == tk[:text][-1] and
          (!continue or (tk[:state] & RDoc::Parser::RipperStateLex::EXPR_LABEL) != 0) then
          if method && method.block_params.nil? then
            unget_tk tk
            read_documentation_modifiers method, modifiers
          end
          break if !continue and nest <= 0
        end
      when :on_comma then
        continue = true
      when :on_ident then
        continue = false if continue
      end
      tk = get_tk
    end

    get_tkread_clean(/\s+/, ' ')
  end

  ##
  # Capture the method's parameters. Along the way, look for a comment
  # containing:
  #
  #    # yields: ....
  #
  # and add this as the block_params for the method

  def parse_method_parameters method
    res = parse_method_or_yield_parameters method

    res = "(#{res})" unless res =~ /\A\(/
    method.params = res unless method.params

    return if  method.block_params

    skip_tkspace_without_nl
    read_documentation_modifiers method, RDoc::METHOD_MODIFIERS
  end

  ##
  # Parses an RDoc::NormalModule in +container+ with +comment+

  def parse_module container, single, tk, comment
    container, name_t, = get_class_or_module container

    name = name_t[:text]

    mod = container.add_module RDoc::NormalModule, name
    mod.ignore unless container.document_children
    record_location mod

    read_documentation_modifiers mod, RDoc::CLASS_MODIFIERS
    mod.add_comment comment, @top_level
    parse_statements mod

    # after end modifiers
    read_documentation_modifiers mod, RDoc::CLASS_MODIFIERS

    @stats.add_module mod
  end

  ##
  # Parses an RDoc::Require in +context+ containing +comment+

  def parse_require(context, comment)
    skip_tkspace_comment
    tk = get_tk

    if :on_lparen == tk[:kind] then
      skip_tkspace_comment
      tk = get_tk
    end

    name = tk[:text][1..-2] if :on_tstring == tk[:kind]

    if name then
      @top_level.add_require RDoc::Require.new(name, comment)
    else
      unget_tk tk
    end
  end

  ##
  # Parses a rescue

  def parse_rescue
    skip_tkspace_without_nl

    while tk = get_tk
      case tk[:kind]
      when :on_nl, :on_semicolon, :on_comment then
        break
      when :on_comma then
        skip_tkspace_without_nl

        get_tk if :on_nl == peek_tk[:kind]
      end

      skip_tkspace_without_nl
    end
  end

  ##
  # Retrieve comment body without =begin/=end

  def retrieve_comment_body(tk)
    if :on_embdoc == tk[:kind]
      tk[:text].gsub(/\A=begin.*\n/, '').gsub(/=end\n?\z/, '')
    else
      tk[:text]
    end
  end

  ##
  # The core of the Ruby parser.

  def parse_statements(container, single = NORMAL, current_method = nil,
                       comment = new_comment(''))
    raise 'no' unless RDoc::Comment === comment
    comment = RDoc::Encoding.change_encoding comment, @encoding if @encoding

    nest = 1
    save_visibility = container.visibility

    non_comment_seen = true

    while tk = get_tk do
      keep_comment = false
      try_parse_comment = false

      non_comment_seen = true unless (:on_comment == tk[:kind] or :on_embdoc == tk[:kind])

      case tk[:kind]
      when :on_nl, :on_ignored_nl, :on_comment, :on_embdoc then
        if :on_nl == tk[:kind] or :on_ignored_nl == tk[:kind]
          skip_tkspace
          tk = get_tk
        else
          past_tokens = @read.size > 1 ? @read[0..-2] : []
          nl_position = 0
          past_tokens.reverse.each_with_index do |read_tk, i|
            if read_tk =~ /^\n$/ then
              nl_position = (past_tokens.size - 1) - i
              break
            elsif read_tk =~ /^#.*\n$/ then
              nl_position = ((past_tokens.size - 1) - i) + 1
              break
            end
          end
          comment_only_line = past_tokens[nl_position..-1].all?{ |c| c =~ /^\s+$/ }
          unless comment_only_line then
            tk = get_tk
          end
        end

        if tk and (:on_comment == tk[:kind] or :on_embdoc == tk[:kind]) then
          if non_comment_seen then
            # Look for RDoc in a comment about to be thrown away
            non_comment_seen = parse_comment container, tk, comment unless
              comment.empty?

            comment = ''
            comment = RDoc::Encoding.change_encoding comment, @encoding if @encoding
          end

          line_no = nil
          while tk and (:on_comment == tk[:kind] or :on_embdoc == tk[:kind]) do
            comment_body = retrieve_comment_body(tk)
            line_no = tk[:line_no] if comment.empty?
            comment += comment_body
            comment << "\n" unless comment_body =~ /\n\z/

            if comment_body.size > 1 && comment_body =~ /\n\z/ then
              skip_tkspace_without_nl # leading spaces
            end
            tk = get_tk
          end

          comment = new_comment comment, line_no

          unless comment.empty? then
            look_for_directives_in container, comment

            if container.done_documenting then
              throw :eof if RDoc::TopLevel === container
              container.ongoing_visibility = save_visibility
            end
          end

          keep_comment = true
        else
          non_comment_seen = true
        end

        unget_tk tk
        keep_comment = true
        container.current_line_visibility = nil

      when :on_kw then
        case tk[:text]
        when 'class' then
          parse_class container, single, tk, comment

        when 'module' then
          parse_module container, single, tk, comment

        when 'def' then
          parse_method container, single, tk, comment

        when 'alias' then
          parse_alias container, single, tk, comment unless current_method

        when 'yield' then
          if current_method.nil? then
            warn "Warning: yield outside of method" if container.document_self
          else
            parse_yield container, single, tk, current_method
          end

        when 'until', 'while' then
          if (tk[:state] & RDoc::Parser::RipperStateLex::EXPR_LABEL) == 0
            nest += 1
            skip_optional_do_after_expression
          end

        # Until and While can have a 'do', which shouldn't increase the nesting.
        # We can't solve the general case, but we can handle most occurrences by
        # ignoring a do at the end of a line.

        # 'for' is trickier
        when 'for' then
          nest += 1
          skip_for_variable
          skip_optional_do_after_expression

        when 'case', 'do', 'if', 'unless', 'begin' then
          if (tk[:state] & RDoc::Parser::RipperStateLex::EXPR_LABEL) == 0
            nest += 1
          end

        when 'super' then
          current_method.calls_super = true if current_method

        when 'rescue' then
          parse_rescue

        when 'end' then
          nest -= 1
          if nest == 0 then
            container.ongoing_visibility = save_visibility

            parse_comment container, tk, comment unless comment.empty?

            return
          end
        end

      when :on_const then
        unless parse_constant container, tk, comment, current_method then
          try_parse_comment = true
        end

      when :on_ident then
        if nest == 1 and current_method.nil? then
          keep_comment = parse_identifier container, single, tk, comment
        end

        case tk[:text]
        when "require" then
          parse_require container, comment
        when "include" then
          parse_extend_or_include RDoc::Include, container, comment
        when "extend" then
          parse_extend_or_include RDoc::Extend, container, comment
        end

      else
        try_parse_comment = nest == 1
      end

      if try_parse_comment then
        non_comment_seen = parse_comment container, tk, comment unless
          comment.empty?

        keep_comment = false
      end

      unless keep_comment then
        comment = new_comment ''
        comment = RDoc::Encoding.change_encoding comment, @encoding if @encoding
        container.params = nil
        container.block_params = nil
      end

      consume_trailing_spaces
    end

    container.params = nil
    container.block_params = nil
  end

  ##
  # Parse up to +no+ symbol arguments

  def parse_symbol_arg(no = nil)
    skip_tkspace_comment

    tk = get_tk
    if tk[:kind] == :on_lparen
      parse_symbol_arg_paren no
    else
      parse_symbol_arg_space no, tk
    end
  end

  ##
  # Parses up to +no+ symbol arguments surrounded by () and places them in
  # +args+.

  def parse_symbol_arg_paren no # :nodoc:
    args = []

    loop do
      skip_tkspace_comment
      if tk1 = parse_symbol_in_arg
        args.push tk1
        break if no and args.size >= no
      end

      skip_tkspace_comment
      case (tk2 = get_tk)[:kind]
      when :on_rparen
        break
      when :on_comma
      else
        warn("unexpected token: '#{tk2.inspect}'") if $DEBUG_RDOC
        break
      end
    end

    args
  end

  ##
  # Parses up to +no+ symbol arguments separated by spaces and places them in
  # +args+.

  def parse_symbol_arg_space no, tk # :nodoc:
    args = []

    unget_tk tk
    if tk = parse_symbol_in_arg
      args.push tk
      return args if no and args.size >= no
    end

    loop do
      skip_tkspace_without_nl

      tk1 = get_tk
      if tk1.nil? || :on_comma != tk1[:kind] then
        unget_tk tk1
        break
      end

      skip_tkspace_comment
      if tk = parse_symbol_in_arg
        args.push tk
        break if no and args.size >= no
      end
    end

    args
  end

  ##
  # Returns symbol text from the next token

  def parse_symbol_in_arg
    tk = get_tk
    if :on_symbol == tk[:kind] then
      tk[:text].sub(/^:/, '')
    elsif :on_tstring == tk[:kind] then
      tk[:text][1..-2]
    elsif :on_dstring == tk[:kind] or :on_ident == tk[:kind] then
      nil # ignore
    else
      warn("Expected symbol or string, got #{tk.inspect}") if $DEBUG_RDOC
      nil
    end
  end

  ##
  # Parses statements in the top-level +container+

  def parse_top_level_statements container
    comment = collect_first_comment

    look_for_directives_in container, comment

    throw :eof if container.done_documenting

    @markup = comment.format

    # HACK move if to RDoc::Context#comment=
    container.comment = comment if container.document_self unless comment.empty?

    parse_statements container, NORMAL, nil, comment
  end

  ##
  # Determines the visibility in +container+ from +tk+

  def parse_visibility(container, single, tk)
    vis_type, vis, singleton = get_visibility_information tk, single

    skip_tkspace_comment false

    ptk = peek_tk
    # Ryan Davis suggested the extension to ignore modifiers, because he
    # often writes
    #
    #   protected unless $TESTING
    #
    if [:on_nl, :on_semicolon].include?(ptk[:kind]) || (:on_kw == ptk[:kind] && (['if', 'unless'].include?(ptk[:text]))) then
      container.ongoing_visibility = vis
    elsif :on_kw == ptk[:kind] && 'def' == ptk[:text]
      container.current_line_visibility = vis
    else
      update_visibility container, vis_type, vis, singleton
    end
  end

  ##
  # Parses a Module#private_constant or Module#public_constant call from +tk+.

  def parse_constant_visibility(container, single, tk)
    args = parse_symbol_arg
    case tk[:text]
    when 'private_constant'
      vis = :private
    when 'public_constant'
      vis = :public
    else
      raise RDoc::Error, 'Unreachable'
    end
    container.set_constant_visibility_for args, vis
  end

  ##
  # Determines the block parameter for +context+

  def parse_yield(context, single, tk, method)
    return if method.block_params

    get_tkread
    method.block_params = parse_method_or_yield_parameters
  end

  ##
  # Directives are modifier comments that can appear after class, module, or
  # method names. For example:
  #
  #   def fred # :yields: a, b
  #
  # or:
  #
  #   class MyClass # :nodoc:
  #
  # We return the directive name and any parameters as a two element array if
  # the name is in +allowed+.  A directive can be found anywhere up to the end
  # of the current line.

  def read_directive allowed
    tokens = []

    while tk = get_tk do
      tokens << tk

      if :on_nl == tk[:kind] or (:on_kw == tk[:kind] && 'def' == tk[:text]) then
        return
      elsif :on_comment == tk[:kind] or :on_embdoc == tk[:kind] then
        return unless tk[:text] =~ /\s*:?([\w-]+):\s*(.*)/

        directive = $1.downcase

        return [directive, $2] if allowed.include? directive

        return
      end
    end
  ensure
    unless tokens.length == 1 and (:on_comment == tokens.first[:kind] or :on_embdoc == tokens.first[:kind]) then
      tokens.reverse_each do |token|
        unget_tk token
      end
    end
  end

  ##
  # Handles directives following the definition for +context+ (any
  # RDoc::CodeObject) if the directives are +allowed+ at this point.
  #
  # See also RDoc::Markup::PreProcess#handle_directive

  def read_documentation_modifiers context, allowed
    skip_tkspace_without_nl
    directive, value = read_directive allowed

    return unless directive

    @preprocess.handle_directive '', directive, value, context do |dir, param|
      if %w[notnew not_new not-new].include? dir then
        context.dont_rename_initialize = true

        true
      end
    end
  end

  ##
  # Records the location of this +container+ in the file for this parser and
  # adds it to the list of classes and modules in the file.

  def record_location container # :nodoc:
    case container
    when RDoc::ClassModule then
      @top_level.add_to_classes_or_modules container
    end

    container.record_location @top_level
  end

  ##
  # Scans this Ruby file for Ruby constructs

  def scan
    reset

    catch :eof do
      begin
        parse_top_level_statements @top_level

      rescue StandardError => e
        if @content.include?('<%') and @content.include?('%>') then
          # Maybe, this is ERB.
          $stderr.puts "\033[2KRDoc detects ERB file. Skips it for compatibility:"
          $stderr.puts @file_name
          return
        end

        if @scanner_point >= @scanner.size
          now_line_no = @scanner[@scanner.size - 1][:line_no]
        else
          now_line_no = peek_tk[:line_no]
        end
        first_tk_index = @scanner.find_index { |tk| tk[:line_no] == now_line_no }
        last_tk_index = @scanner.find_index { |tk| tk[:line_no] == now_line_no + 1 }
        last_tk_index = last_tk_index ? last_tk_index - 1 : @scanner.size - 1
        code = @scanner[first_tk_index..last_tk_index].map{ |t| t[:text] }.join

        $stderr.puts <<-EOF

#{self.class} failure around line #{now_line_no} of
#{@file_name}

        EOF

        unless code.empty? then
          $stderr.puts code
          $stderr.puts
        end

        raise e
      end
    end

    @top_level
  end

  ##
  # while, until, and for have an optional do

  def skip_optional_do_after_expression
    skip_tkspace_without_nl
    tk = get_tk

    b_nest = 0
    nest = 0

    loop do
      break unless tk
      case tk[:kind]
      when :on_semicolon, :on_nl, :on_ignored_nl then
        break if b_nest.zero?
      when :on_lparen then
        nest += 1
      when :on_rparen then
        nest -= 1
      when :on_kw then
        case tk[:text]
        when 'begin'
          b_nest += 1
        when 'end'
          b_nest -= 1
        when 'do'
          break if nest.zero?
        end
      when :on_comment, :on_embdoc then
        if b_nest.zero? and "\n" == tk[:text][-1] then
          break
        end
      end
      tk = get_tk
    end

    skip_tkspace_without_nl

    get_tk if peek_tk && :on_kw == peek_tk[:kind] && 'do' == peek_tk[:text]
  end

  ##
  # skip the var [in] part of a 'for' statement

  def skip_for_variable
    skip_tkspace_without_nl
    get_tk
    skip_tkspace_without_nl
    tk = get_tk
    unget_tk(tk) unless :on_kw == tk[:kind] and 'in' == tk[:text]
  end

  ##
  # Skips the next method in +container+

  def skip_method container
    meth = RDoc::AnyMethod.new "", "anon"
    parse_method_parameters meth
    parse_statements container, false, meth
  end

  ##
  # Skip spaces until a comment is found

  def skip_tkspace_comment(skip_nl = true)
    loop do
      skip_nl ? skip_tkspace : skip_tkspace_without_nl
      next_tk = peek_tk
      return if next_tk.nil? || (:on_comment != next_tk[:kind] and :on_embdoc != next_tk[:kind])
      get_tk
    end
  end

  ##
  # Updates visibility in +container+ from +vis_type+ and +vis+.

  def update_visibility container, vis_type, vis, singleton # :nodoc:
    new_methods = []

    case vis_type
    when 'module_function' then
      args = parse_symbol_arg
      container.set_visibility_for args, :private, false

      container.methods_matching args do |m|
        s_m = m.dup
        record_location s_m
        s_m.singleton = true
        new_methods << s_m
      end
    when 'public_class_method', 'private_class_method' then
      args = parse_symbol_arg

      container.methods_matching args, true do |m|
        if m.parent != container then
          m = m.dup
          record_location m
          new_methods << m
        end

        m.visibility = vis
      end
    else
      args = parse_symbol_arg
      container.set_visibility_for args, vis, singleton
    end

    new_methods.each do |method|
      case method
      when RDoc::AnyMethod then
        container.add_method method
      when RDoc::Attr then
        container.add_attribute method
      end
      method.visibility = vis
    end
  end

  ##
  # Prints +message+ to +$stderr+ unless we're being quiet

  def warn message
    @options.warn make_message message
  end

end
# frozen_string_literal: true
##
# Indicates this parser is text and doesn't contain code constructs.
#
# Include this module in a RDoc::Parser subclass to make it show up as a file,
# not as part of a class or module.
#--
# This is not named File to avoid overriding ::File

module RDoc::Parser::Text
end

# frozen_string_literal: true
##
# Parse a non-source file. We basically take the whole thing as one big
# comment.

class RDoc::Parser::Simple < RDoc::Parser

  include RDoc::Parser::Text

  parse_files_matching(//)

  attr_reader :content # :nodoc:

  ##
  # Prepare to parse a plain file

  def initialize(top_level, file_name, content, options, stats)
    super

    preprocess = RDoc::Markup::PreProcess.new @file_name, @options.rdoc_include

    @content = preprocess.handle @content, @top_level
  end

  ##
  # Extract the file contents and attach them to the TopLevel as a comment

  def scan
    comment = remove_coding_comment @content
    comment = remove_private_comment comment

    comment = RDoc::Comment.new comment, @top_level

    @top_level.comment = comment
    @top_level
  end

  ##
  # Removes the encoding magic comment from +text+

  def remove_coding_comment text
    text.sub(/\A# .*coding[=:].*$/, '')
  end

  ##
  # Removes private comments.
  #
  # Unlike RDoc::Comment#remove_private this implementation only looks for two
  # dashes at the beginning of the line.  Three or more dashes are considered
  # to be a rule and ignored.

  def remove_private_comment comment
    # Workaround for gsub encoding for Ruby 1.9.2 and earlier
    empty = ''
    empty = RDoc::Encoding.change_encoding empty, comment.encoding

    comment = comment.gsub(%r%^--\n.*?^\+\+\n?%m, empty)
    comment.sub(%r%^--\n.*%m, empty)
  end

end
# frozen_string_literal: true
##
# Parse a RD format file.  The parsed RDoc::Markup::Document is attached as a
# file comment.

class RDoc::Parser::RD < RDoc::Parser

  include RDoc::Parser::Text

  parse_files_matching(/\.rd(?:\.[^.]+)?$/)

  ##
  # Creates an rd-format TopLevel for the given file.

  def scan
    comment = RDoc::Comment.new @content, @top_level
    comment.format = 'rd'

    @top_level.comment = comment
  end

end

# frozen_string_literal: true
##
# Parse a Markdown format file.  The parsed RDoc::Markup::Document is attached
# as a file comment.

class RDoc::Parser::Markdown < RDoc::Parser

  include RDoc::Parser::Text

  parse_files_matching(/\.(md|markdown)(?:\.[^.]+)?$/)

  ##
  # Creates an Markdown-format TopLevel for the given file.

  def scan
    comment = RDoc::Comment.new @content, @top_level
    comment.format = 'markdown'

    @top_level.comment = comment
  end

end


# frozen_string_literal: true

##
# A ChangeLog file parser.
#
# This parser converts a ChangeLog into an RDoc::Markup::Document.  When
# viewed as HTML a ChangeLog page will have an entry for each day's entries in
# the sidebar table of contents.
#
# This parser is meant to parse the MRI ChangeLog, but can be used to parse any
# {GNU style Change
# Log}[http://www.gnu.org/prep/standards/html_node/Style-of-Change-Logs.html].

class RDoc::Parser::ChangeLog < RDoc::Parser

  include RDoc::Parser::Text

  parse_files_matching(/(\/|\\|\A)ChangeLog[^\/\\]*\z/)

  ##
  # Attaches the +continuation+ of the previous line to the +entry_body+.
  #
  # Continued function listings are joined together as a single entry.
  # Continued descriptions are joined to make a single paragraph.

  def continue_entry_body entry_body, continuation
    return unless last = entry_body.last

    if last =~ /\)\s*\z/ and continuation =~ /\A\(/ then
      last.sub!(/\)\s*\z/, ',')
      continuation = continuation.sub(/\A\(/, '')
    end

    if last =~ /\s\z/ then
      last << continuation
    else
      last << ' ' + continuation
    end
  end

  ##
  # Creates an RDoc::Markup::Document given the +groups+ of ChangeLog entries.

  def create_document groups
    doc = RDoc::Markup::Document.new
    doc.omit_headings_below = 2
    doc.file = @top_level

    doc << RDoc::Markup::Heading.new(1, File.basename(@file_name))
    doc << RDoc::Markup::BlankLine.new

    groups.sort_by do |day,| day end.reverse_each do |day, entries|
      doc << RDoc::Markup::Heading.new(2, day.dup)
      doc << RDoc::Markup::BlankLine.new

      doc.concat create_entries entries
    end

    doc
  end

  ##
  # Returns a list of ChangeLog entries an RDoc::Markup nodes for the given
  # +entries+.

  def create_entries entries
    out = []

    entries.each do |entry, items|
      out << RDoc::Markup::Heading.new(3, entry)
      out << RDoc::Markup::BlankLine.new

      out << create_items(items)
    end

    out
  end

  ##
  # Returns an RDoc::Markup::List containing the given +items+ in the
  # ChangeLog

  def create_items items
    list = RDoc::Markup::List.new :NOTE

    items.each do |item|
      item =~ /\A(.*?(?:\([^)]+\))?):\s*/

      title = $1
      body = $'

      paragraph = RDoc::Markup::Paragraph.new body
      list_item = RDoc::Markup::ListItem.new title, paragraph
      list << list_item
    end

    list
  end

  ##
  # Groups +entries+ by date.

  def group_entries entries
    @time_cache ||= {}
    entries.group_by do |title, _|
      begin
        time = @time_cache[title]
        (time || parse_date(title)).strftime '%Y-%m-%d'
      rescue NoMethodError, ArgumentError
        time, = title.split '  ', 2
        parse_date(time).strftime '%Y-%m-%d'
      end
    end
  end

  ##
  # Parse date in ISO-8601, RFC-2822, or default of Git

  def parse_date(date)
    case date
    when /\A\s*(\d+)-(\d+)-(\d+)(?:[ T](\d+):(\d+):(\d+) *([-+]\d\d):?(\d\d))?\b/
      Time.new($1, $2, $3, $4, $5, $6, ("#{$7}:#{$8}" if $7))
    when /\A\s*\w{3}, +(\d+) (\w{3}) (\d+) (\d+):(\d+):(\d+) *(?:([-+]\d\d):?(\d\d))\b/
      Time.new($3, $2, $1, $4, $5, $6, ("#{$7}:#{$8}" if $7))
    when /\A\s*\w{3} (\w{3}) +(\d+) (\d+) (\d+):(\d+):(\d+) *(?:([-+]\d\d):?(\d\d))\b/
      Time.new($3, $1, $2, $4, $5, $6, ("#{$7}:#{$8}" if $7))
    when /\A\s*\w{3} (\w{3}) +(\d+) (\d+):(\d+):(\d+) (\d+)\b/
      Time.new($6, $1, $2, $3, $4, $5)
    else
      raise ArgumentError, "bad date: #{date}"
    end
  end

  ##
  # Parses the entries in the ChangeLog.
  #
  # Returns an Array of each ChangeLog entry in order of parsing.
  #
  # A ChangeLog entry is an Array containing the ChangeLog title (date and
  # committer) and an Array of ChangeLog items (file and function changed with
  # description).
  #
  # An example result would be:
  #
  #    [ 'Tue Dec  4 08:33:46 2012  Eric Hodel  <drbrain@segment7.net>',
  #      [ 'README.EXT:  Converted to RDoc format',
  #        'README.EXT.ja:  ditto']]

  def parse_entries
    @time_cache ||= {}

    if /\A((?:.*\n){,3})commit\s/ =~ @content
      class << self; prepend Git; end
      parse_info($1)
      return parse_entries
    end

    entries = []
    entry_name = nil
    entry_body = []

    @content.each_line do |line|
      case line
      when /^\s*$/ then
        next
      when /^\w.*/ then
        entries << [entry_name, entry_body] if entry_name

        entry_name = $&

        begin
          time = parse_date entry_name
          @time_cache[entry_name] = time
        rescue ArgumentError
          entry_name = nil
        end

        entry_body = []
      when /^(\t| {8})?\*\s*(.*)/ then # "\t* file.c (func): ..."
        entry_body << $2.dup
      when /^(\t| {8})?\s*(\(.*)/ then # "\t(func): ..."
        entry = $2

        if entry_body.last =~ /:/ then
          entry_body << entry.dup
        else
          continue_entry_body entry_body, entry
        end
      when /^(\t| {8})?\s*(.*)/ then
        continue_entry_body entry_body, $2
      end
    end

    entries << [entry_name, entry_body] if entry_name

    entries.reject! do |(entry,_)|
      entry == nil
    end

    entries
  end

  ##
  # Converts the ChangeLog into an RDoc::Markup::Document

  def scan
    @time_cache = {}

    entries = parse_entries
    grouped_entries = group_entries entries

    doc = create_document grouped_entries

    @top_level.comment = doc

    @top_level
  end

  module Git
    def parse_info(info)
      /^\s*base-url\s*=\s*(.*\S)/ =~ info
      @base_url = $1
    end

    def parse_entries
      entries = []

      @content.scan(/^commit\s+(\h{20})\h*\n((?:.+\n)*)\n((?: {4}.*\n+)*)/) do
        entry_name, header, entry_body = $1, $2, $3.gsub(/^ {4}/, '')
        # header = header.scan(/^ *(\S+?): +(.*)/).to_h
        # date = header["CommitDate"] || header["Date"]
        date = header[/^ *(?:Author)?Date: +(.*)/, 1]
        author = header[/^ *Author: +(.*)/, 1]
        begin
          time = parse_date(header[/^ *CommitDate: +(.*)/, 1] || date)
          @time_cache[entry_name] = time
          author.sub!(/\s*<(.*)>/, '')
          email = $1
          entries << [entry_name, [author, email, date, entry_body]]
        rescue ArgumentError
        end
      end

      entries
    end

    def create_entries entries
      # git log entries have no strictly itemized style like the old
      # style, just assume Markdown.
      entries.map do |commit, entry|
        LogEntry.new(@base_url, commit, *entry)
      end
    end

    LogEntry = Struct.new(:base, :commit, :author, :email, :date, :contents) do
      HEADING_LEVEL = 3

      def initialize(base, commit, author, email, date, contents)
        case contents
        when String
          contents = RDoc::Markdown.parse(contents).parts.each do |body|
            case body
            when RDoc::Markup::Heading
              body.level += HEADING_LEVEL + 1
            end
          end
          case first = contents[0]
          when RDoc::Markup::Paragraph
            contents[0] = RDoc::Markup::Heading.new(HEADING_LEVEL + 1, first.text)
          end
        end
        super
      end

      def level
        HEADING_LEVEL
      end

      def aref
        "label-#{commit}"
      end

      def label context = nil
        aref
      end

      def text
        case base
        when nil
          "#{date}"
        when /%s/
          "{#{date}}[#{base % commit}]"
        else
          "{#{date}}[#{base}#{commit}]"
        end + " {#{author}}[mailto:#{email}]"
      end

      def accept visitor
        visitor.accept_heading self
        begin
          if visitor.respond_to?(:code_object=)
            code_object = visitor.code_object
            visitor.code_object = self
          end
          contents.each do |body|
            body.accept visitor
          end
        ensure
          if visitor.respond_to?(:code_object)
            visitor.code_object = code_object
          end
        end
      end

      def pretty_print q # :nodoc:
        q.group(2, '[log_entry: ', ']') do
          q.text commit
          q.text ','
          q.breakable
          q.group(2, '[date: ', ']') { q.text date }
          q.text ','
          q.breakable
          q.group(2, '[author: ', ']') { q.text author }
          q.text ','
          q.breakable
          q.group(2, '[email: ', ']') { q.text email }
          q.text ','
          q.breakable
          q.pp contents
        end
      end
    end
  end
end

# frozen_string_literal: true
require 'tsort'

##
# RDoc::Parser::C attempts to parse C extension files.  It looks for
# the standard patterns that you find in extensions: +rb_define_class+,
# +rb_define_method+ and so on.  It tries to find the corresponding
# C source for the methods and extract comments, but if we fail
# we don't worry too much.
#
# The comments associated with a Ruby method are extracted from the C
# comment block associated with the routine that _implements_ that
# method, that is to say the method whose name is given in the
# +rb_define_method+ call. For example, you might write:
#
#   /*
#    * Returns a new array that is a one-dimensional flattening of this
#    * array (recursively). That is, for every element that is an array,
#    * extract its elements into the new array.
#    *
#    *    s = [ 1, 2, 3 ]           #=> [1, 2, 3]
#    *    t = [ 4, 5, 6, [7, 8] ]   #=> [4, 5, 6, [7, 8]]
#    *    a = [ s, t, 9, 10 ]       #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
#    *    a.flatten                 #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#    */
#    static VALUE
#    rb_ary_flatten(VALUE ary)
#    {
#        ary = rb_obj_dup(ary);
#        rb_ary_flatten_bang(ary);
#        return ary;
#    }
#
#    ...
#
#    void
#    Init_Array(void)
#    {
#      ...
#      rb_define_method(rb_cArray, "flatten", rb_ary_flatten, 0);
#
# Here RDoc will determine from the +rb_define_method+ line that there's a
# method called "flatten" in class Array, and will look for the implementation
# in the method +rb_ary_flatten+. It will then use the comment from that
# method in the HTML output. This method must be in the same source file
# as the +rb_define_method+.
#
# The comment blocks may include special directives:
#
# [Document-class: +name+]
#   Documentation for the named class.
#
# [Document-module: +name+]
#   Documentation for the named module.
#
# [Document-const: +name+]
#   Documentation for the named +rb_define_const+.
#
#   Constant values can be supplied on the first line of the comment like so:
#
#     /* 300: The highest possible score in bowling */
#     rb_define_const(cFoo, "PERFECT", INT2FIX(300));
#
#   The value can contain internal colons so long as they are escaped with a \
#
# [Document-global: +name+]
#   Documentation for the named +rb_define_global_const+
#
# [Document-variable: +name+]
#   Documentation for the named +rb_define_variable+
#
# [Document-method\: +method_name+]
#   Documentation for the named method.  Use this when the method name is
#   unambiguous.
#
# [Document-method\: <tt>ClassName::method_name</tt>]
#   Documentation for a singleton method in the given class.  Use this when
#   the method name alone is ambiguous.
#
# [Document-method\: <tt>ClassName#method_name</tt>]
#   Documentation for a instance method in the given class.  Use this when the
#   method name alone is ambiguous.
#
# [Document-attr: +name+]
#   Documentation for the named attribute.
#
# [call-seq:  <i>text up to an empty line</i>]
#   Because C source doesn't give descriptive names to Ruby-level parameters,
#   you need to document the calling sequence explicitly
#
# In addition, RDoc assumes by default that the C method implementing a
# Ruby function is in the same source file as the rb_define_method call.
# If this isn't the case, add the comment:
#
#   rb_define_method(....);  // in filename
#
# As an example, we might have an extension that defines multiple classes
# in its Init_xxx method. We could document them using
#
#   /*
#    * Document-class:  MyClass
#    *
#    * Encapsulate the writing and reading of the configuration
#    * file. ...
#    */
#
#   /*
#    * Document-method: read_value
#    *
#    * call-seq:
#    *   cfg.read_value(key)            -> value
#    *   cfg.read_value(key} { |key| }  -> value
#    *
#    * Return the value corresponding to +key+ from the configuration.
#    * In the second form, if the key isn't found, invoke the
#    * block and return its value.
#    */

class RDoc::Parser::C < RDoc::Parser

  parse_files_matching(/\.(?:([CcHh])\1?|c([+xp])\2|y)\z/)

  include RDoc::Text

  ##
  # Maps C variable names to names of Ruby classes or modules

  attr_reader :classes

  ##
  # C file the parser is parsing

  attr_accessor :content

  ##
  # Dependencies from a missing enclosing class to the classes in
  # missing_dependencies that depend upon it.

  attr_reader :enclosure_dependencies

  ##
  # Maps C variable names to names of Ruby classes (and singleton classes)

  attr_reader :known_classes

  ##
  # Classes found while parsing the C file that were not yet registered due to
  # a missing enclosing class.  These are processed by do_missing

  attr_reader :missing_dependencies

  ##
  # Maps C variable names to names of Ruby singleton classes

  attr_reader :singleton_classes

  ##
  # The TopLevel items in the parsed file belong to

  attr_reader :top_level

  ##
  # Prepares for parsing a C file.  See RDoc::Parser#initialize for details on
  # the arguments.

  def initialize top_level, file_name, content, options, stats
    super

    @known_classes = RDoc::KNOWN_CLASSES.dup
    @content = handle_tab_width handle_ifdefs_in @content
    @file_dir = File.dirname @file_name

    @classes           = load_variable_map :c_class_variables
    @singleton_classes = load_variable_map :c_singleton_class_variables

    # class_variable => { function => [method, ...] }
    @methods = Hash.new { |h, f| h[f] = Hash.new { |i, m| i[m] = [] } }

    # missing variable => [handle_class_module arguments]
    @missing_dependencies = {}

    # missing enclosure variable => [dependent handle_class_module arguments]
    @enclosure_dependencies = Hash.new { |h, k| h[k] = [] }
    @enclosure_dependencies.instance_variable_set :@missing_dependencies,
                                                  @missing_dependencies

    @enclosure_dependencies.extend TSort

    def @enclosure_dependencies.tsort_each_node &block
      each_key(&block)
    rescue TSort::Cyclic => e
      cycle_vars = e.message.scan(/"(.*?)"/).flatten

      cycle = cycle_vars.sort.map do |var_name|
        delete var_name

        var_name, type, mod_name, = @missing_dependencies[var_name]

        "#{type} #{mod_name} (#{var_name})"
      end.join ', '

      warn "Unable to create #{cycle} due to a cyclic class or module creation"

      retry
    end

    def @enclosure_dependencies.tsort_each_child node, &block
      fetch(node, []).each(&block)
    end
  end

  ##
  # Scans #content for rb_define_alias

  def do_aliases
    @content.scan(/rb_define_alias\s*\(
                   \s*(\w+),
                   \s*"(.+?)",
                   \s*"(.+?)"
                   \s*\)/xm) do |var_name, new_name, old_name|
      class_name = @known_classes[var_name]

      unless class_name then
        @options.warn "Enclosing class or module %p for alias %s %s is not known" % [
          var_name, new_name, old_name]
        next
      end

      class_obj = find_class var_name, class_name
      comment = find_alias_comment var_name, new_name, old_name
      comment.normalize
      if comment.to_s.empty? and existing_method = class_obj.method_list.find { |m| m.name == old_name}
        comment = existing_method.comment
      end
      add_alias(var_name, class_obj, old_name, new_name, comment)
    end
  end

  ##
  # Add alias, either from a direct alias definition, or from two
  # method that reference the same function.

  def add_alias(var_name, class_obj, old_name, new_name, comment)
    al = RDoc::Alias.new '', old_name, new_name, ''
    al.singleton = @singleton_classes.key? var_name
    al.comment = comment
    al.record_location @top_level
    class_obj.add_alias al
    @stats.add_alias al
    al
  end

  ##
  # Scans #content for rb_attr and rb_define_attr

  def do_attrs
    @content.scan(/rb_attr\s*\(
                   \s*(\w+),
                   \s*([\w"()]+),
                   \s*([01]),
                   \s*([01]),
                   \s*\w+\);/xm) do |var_name, attr_name, read, write|
      handle_attr var_name, attr_name, read, write
    end

    @content.scan(%r%rb_define_attr\(
                             \s*([\w\.]+),
                             \s*"([^"]+)",
                             \s*(\d+),
                             \s*(\d+)\s*\);
                %xm) do |var_name, attr_name, read, write|
      handle_attr var_name, attr_name, read, write
    end
  end

  ##
  # Scans #content for boot_defclass

  def do_boot_defclass
    @content.scan(/(\w+)\s*=\s*boot_defclass\s*\(\s*"(\w+?)",\s*(\w+?)\s*\)/) do
      |var_name, class_name, parent|
      parent = nil if parent == "0"
      handle_class_module(var_name, :class, class_name, parent, nil)
    end
  end

  ##
  # Scans #content for rb_define_class, boot_defclass, rb_define_class_under
  # and rb_singleton_class

  def do_classes_and_modules
    do_boot_defclass if @file_name == "class.c"

    @content.scan(
      %r(
        (?<var_name>[\w\.]+)\s* =
        \s*rb_(?:
          define_(?:
            class(?: # rb_define_class(class_name_1, parent_name_1)
              \s*\(
                \s*"(?<class_name_1>\w+)",
                \s*(?<parent_name_1>\w+)\s*
              \)
            |
              _under\s*\( # rb_define_class_under(class_under, class_name2, parent_name2...)
                \s* (?<class_under>\w+),
                \s* "(?<class_name_2>\w+)",
                \s*
                (?:
                  (?<parent_name_2>[\w\*\s\(\)\.\->]+) |
                  rb_path2class\("(?<path>[\w:]+)"\)
                )
              \s*\)
            )
          |
            module(?: # rb_define_module(module_name_1)
              \s*\(
                \s*"(?<module_name_1>\w+)"\s*
              \)
            |
              _under\s*\( # rb_define_module_under(module_under, module_name_2)
                \s*(?<module_under>\w+),
                \s*"(?<module_name_2>\w+)"
              \s*\)
            )
          )
      |
        struct_define_without_accessor\s*\( # rb_struct_define_without_accessor(class_name_3, parent_name_3, ...)
          \s*"(?<class_name_3>\w+)",
          \s*(?<parent_name_3>\w+),
          \s*\w+,        # Allocation function
          (?:\s*"\w+",)* # Attributes
          \s*NULL
        \)
      |
        singleton_class\s*\( # rb_singleton_class(target_class_name)
          \s*(?<target_class_name>\w+)
        \)
        )
      )mx
    ) do
      class_name = $~[:class_name_1]
      type = :class
      if class_name
        # rb_define_class(class_name_1, parent_name_1)
        parent_name = $~[:parent_name_1]
        #under = nil
      else
        class_name = $~[:class_name_2]
        if class_name
          # rb_define_class_under(class_under, class_name2, parent_name2...)
          parent_name = $~[:parent_name_2] || $~[:path]
          under = $~[:class_under]
        else
          class_name = $~[:class_name_3]
          if class_name
            # rb_struct_define_without_accessor(class_name_3, parent_name_3, ...)
            parent_name = $~[:parent_name_3]
            #under = nil
          else
            type = :module
            class_name = $~[:module_name_1]
            #parent_name = nil
            if class_name
              # rb_define_module(module_name_1)
              #under = nil
            else
              class_name = $~[:module_name_2]
              if class_name
                # rb_define_module_under(module_under, module_name_1)
                under = $~[:module_under]
              else
                # rb_singleton_class(target_class_name)
                target_class_name = $~[:target_class_name]
                handle_singleton $~[:var_name], target_class_name
                next
              end
            end
          end
        end
      end

      handle_class_module($~[:var_name], type, class_name, parent_name, under)
    end
  end

  ##
  # Scans #content for rb_define_variable, rb_define_readonly_variable,
  # rb_define_const and rb_define_global_const

  def do_constants
    @content.scan(%r%\Wrb_define_
                   ( variable          |
                     readonly_variable |
                     const             |
                     global_const        )
               \s*\(
                 (?:\s*(\w+),)?
                 \s*"(\w+)",
                 \s*(.*?)\s*\)\s*;
                 %xm) do |type, var_name, const_name, definition|
      var_name = "rb_cObject" if !var_name or var_name == "rb_mKernel"
      handle_constants type, var_name, const_name, definition
    end

    @content.scan(%r%
                  \Wrb_curses_define_const
                  \s*\(
                    \s*
                    (\w+)
                    \s*
                  \)
                  \s*;%xm) do |consts|
      const = consts.first

      handle_constants 'const', 'mCurses', const, "UINT2NUM(#{const})"
    end

    @content.scan(%r%
                  \Wrb_file_const
                  \s*\(
                    \s*
                    "([^"]+)",
                    \s*
                    (.*?)
                    \s*
                  \)
                  \s*;%xm) do |name, value|
      handle_constants 'const', 'rb_mFConst', name, value
    end
  end


  ##
  # Scans #content for rb_include_module

  def do_includes
    @content.scan(/rb_include_module\s*\(\s*(\w+?),\s*(\w+?)\s*\)/) do |c,m|
      next unless cls = @classes[c]
      m = @known_classes[m] || m

      comment = RDoc::Comment.new '', @top_level, :c
      incl = cls.add_include RDoc::Include.new(m, comment)
      incl.record_location @top_level
    end
  end

  ##
  # Scans #content for rb_define_method, rb_define_singleton_method,
  # rb_define_module_function, rb_define_private_method,
  # rb_define_global_function and define_filetest_function

  def do_methods
    @content.scan(%r%rb_define_
                   (
                      singleton_method |
                      method           |
                      module_function  |
                      private_method
                   )
                   \s*\(\s*([\w\.]+),
                     \s*"([^"]+)",
                     \s*(?:RUBY_METHOD_FUNC\(|VALUEFUNC\(|\(METHOD\))?(\w+)\)?,
                     \s*(-?\w+)\s*\)
                   (?:;\s*/[*/]\s+in\s+(\w+?\.(?:cpp|c|y)))?
                 %xm) do |type, var_name, meth_name, function, param_count, source_file|

      # Ignore top-object and weird struct.c dynamic stuff
      next if var_name == "ruby_top_self"
      next if var_name == "nstr"

      var_name = "rb_cObject" if var_name == "rb_mKernel"
      handle_method(type, var_name, meth_name, function, param_count,
                    source_file)
    end

    @content.scan(%r%rb_define_global_function\s*\(
                             \s*"([^"]+)",
                             \s*(?:RUBY_METHOD_FUNC\(|VALUEFUNC\()?(\w+)\)?,
                             \s*(-?\w+)\s*\)
                (?:;\s*/[*/]\s+in\s+(\w+?\.[cy]))?
                %xm) do |meth_name, function, param_count, source_file|
      handle_method("method", "rb_mKernel", meth_name, function, param_count,
                    source_file)
    end

    @content.scan(/define_filetest_function\s*\(
                     \s*"([^"]+)",
                     \s*(?:RUBY_METHOD_FUNC\(|VALUEFUNC\()?(\w+)\)?,
                     \s*(-?\w+)\s*\)/xm) do |meth_name, function, param_count|

      handle_method("method", "rb_mFileTest", meth_name, function, param_count)
      handle_method("singleton_method", "rb_cFile", meth_name, function,
                    param_count)
    end
  end

  ##
  # Creates classes and module that were missing were defined due to the file
  # order being different than the declaration order.

  def do_missing
    return if @missing_dependencies.empty?

    @enclosure_dependencies.tsort.each do |in_module|
      arguments = @missing_dependencies.delete in_module

      next unless arguments # dependency on existing class

      handle_class_module(*arguments)
    end
  end

  ##
  # Finds the comment for an alias on +class_name+ from +new_name+ to
  # +old_name+

  def find_alias_comment class_name, new_name, old_name
    content =~ %r%((?>/\*.*?\*/\s+))
                  rb_define_alias\(\s*#{Regexp.escape class_name}\s*,
                                   \s*"#{Regexp.escape new_name}"\s*,
                                   \s*"#{Regexp.escape old_name}"\s*\);%xm

    RDoc::Comment.new($1 || '', @top_level, :c)
  end

  ##
  # Finds a comment for rb_define_attr, rb_attr or Document-attr.
  #
  # +var_name+ is the C class variable the attribute is defined on.
  # +attr_name+ is the attribute's name.
  #
  # +read+ and +write+ are the read/write flags ('1' or '0').  Either both or
  # neither must be provided.

  def find_attr_comment var_name, attr_name, read = nil, write = nil
    attr_name = Regexp.escape attr_name

    rw = if read and write then
           /\s*#{read}\s*,\s*#{write}\s*/xm
         else
           /.*?/m
         end

    comment = if @content =~ %r%((?>/\*.*?\*/\s+))
                                rb_define_attr\((?:\s*#{var_name},)?\s*
                                                "#{attr_name}"\s*,
                                                #{rw}\)\s*;%xm then
                $1
              elsif @content =~ %r%((?>/\*.*?\*/\s+))
                                   rb_attr\(\s*#{var_name}\s*,
                                            \s*#{attr_name}\s*,
                                            #{rw},.*?\)\s*;%xm then
                $1
              elsif @content =~ %r%(/\*.*?(?:\s*\*\s*)?)
                                   Document-attr:\s#{attr_name}\s*?\n
                                   ((?>(.|\n)*?\*/))%x then
                "#{$1}\n#{$2}"
              else
                ''
              end

    RDoc::Comment.new comment, @top_level, :c
  end

  ##
  # Generate a Ruby-method table

  def gen_body_table file_content
    table = {}
    file_content.scan(%r{
      ((?>/\*.*?\*/\s*)?)
      ((?:(?:\w+)\s+)?
        (?:intern\s+)?VALUE\s+(\w+)
        \s*(?:\([^)]*\))(?:[^\);]|$))
    | ((?>/\*.*?\*/\s*))^\s*(\#\s*define\s+(\w+)\s+(\w+))
    | ^\s*\#\s*define\s+(\w+)\s+(\w+)
    }xm) do
      case
      when $1
        table[$3] = [:func_def, $1, $2, $~.offset(2)] if !table[$3] || table[$3][0] != :func_def
      when $4
        table[$6] = [:macro_def, $4, $5, $~.offset(5), $7] if !table[$6] || table[$6][0] == :macro_alias
      when $8
        table[$8] ||= [:macro_alias, $9]
      end
    end
    table
  end

  ##
  # Find the C code corresponding to a Ruby method

  def find_body class_name, meth_name, meth_obj, file_content, quiet = false
    if file_content
      @body_table ||= {}
      @body_table[file_content] ||= gen_body_table file_content
      type, *args = @body_table[file_content][meth_name]
    end

    case type
    when :func_def
      comment = RDoc::Comment.new args[0], @top_level, :c
      body = args[1]
      offset, = args[2]

      comment.remove_private if comment

      # try to find the whole body
      body = $& if /#{Regexp.escape body}[^(]*?\{.*?^\}/m =~ file_content

      # The comment block may have been overridden with a 'Document-method'
      # block. This happens in the interpreter when multiple methods are
      # vectored through to the same C method but those methods are logically
      # distinct (for example Kernel.hash and Kernel.object_id share the same
      # implementation

      override_comment = find_override_comment class_name, meth_obj
      comment = override_comment if override_comment

      comment.normalize
      find_modifiers comment, meth_obj if comment

      #meth_obj.params = params
      meth_obj.start_collecting_tokens
      tk = { :line_no => 1, :char_no => 1, :text => body }
      meth_obj.add_token tk
      meth_obj.comment = comment
      meth_obj.line    = file_content[0, offset].count("\n") + 1

      body
    when :macro_def
      comment = RDoc::Comment.new args[0], @top_level, :c
      body = args[1]
      offset, = args[2]

      find_body class_name, args[3], meth_obj, file_content, true

      comment.normalize
      find_modifiers comment, meth_obj

      meth_obj.start_collecting_tokens
      tk = { :line_no => 1, :char_no => 1, :text => body }
      meth_obj.add_token tk
      meth_obj.comment = comment
      meth_obj.line    = file_content[0, offset].count("\n") + 1

      body
    when :macro_alias
      # with no comment we hope the aliased definition has it and use it's
      # definition

      body = find_body(class_name, args[0], meth_obj, file_content, true)

      return body if body

      @options.warn "No definition for #{meth_name}"
      false
    else # No body, but might still have an override comment
      comment = find_override_comment class_name, meth_obj

      if comment then
        comment.normalize
        find_modifiers comment, meth_obj
        meth_obj.comment = comment

        ''
      else
        @options.warn "No definition for #{meth_name}"
        false
      end
    end
  end

  ##
  # Finds a RDoc::NormalClass or RDoc::NormalModule for +raw_name+

  def find_class(raw_name, name)
    unless @classes[raw_name]
      if raw_name =~ /^rb_m/
        container = @top_level.add_module RDoc::NormalModule, name
      else
        container = @top_level.add_class RDoc::NormalClass, name
      end

      container.record_location @top_level
      @classes[raw_name] = container
    end
    @classes[raw_name]
  end

  ##
  # Look for class or module documentation above Init_+class_name+(void),
  # in a Document-class +class_name+ (or module) comment or above an
  # rb_define_class (or module).  If a comment is supplied above a matching
  # Init_ and a rb_define_class the Init_ comment is used.
  #
  #   /*
  #    * This is a comment for Foo
  #    */
  #   Init_Foo(void) {
  #       VALUE cFoo = rb_define_class("Foo", rb_cObject);
  #   }
  #
  #   /*
  #    * Document-class: Foo
  #    * This is a comment for Foo
  #    */
  #   Init_foo(void) {
  #       VALUE cFoo = rb_define_class("Foo", rb_cObject);
  #   }
  #
  #   /*
  #    * This is a comment for Foo
  #    */
  #   VALUE cFoo = rb_define_class("Foo", rb_cObject);

  def find_class_comment class_name, class_mod
    comment = nil

    if @content =~ %r%
        ((?>/\*.*?\*/\s+))
        (static\s+)?
        void\s+
        Init_#{class_name}\s*(?:_\(\s*)?\(\s*(?:void\s*)?\)%xmi then
      comment = $1.sub(%r%Document-(?:class|module):\s+#{class_name}%, '')
    elsif @content =~ %r%Document-(?:class|module):\s+#{class_name}\s*?
                         (?:<\s+[:,\w]+)?\n((?>.*?\*/))%xm then
      comment = "/*\n#{$1}"
    elsif @content =~ %r%((?>/\*.*?\*/\s+))
                         ([\w\.\s]+\s* = \s+)?rb_define_(class|module)[\t (]*?"(#{class_name})"%xm then
      comment = $1
    elsif @content =~ %r%((?>/\*.*?\*/\s+))
                         ([\w\. \t]+ = \s+)?rb_define_(class|module)_under[\t\w, (]*?"(#{class_name.split('::').last})"%xm then
      comment = $1
    else
      comment = ''
    end

    comment = RDoc::Comment.new comment, @top_level, :c
    comment.normalize

    look_for_directives_in class_mod, comment

    class_mod.add_comment comment, @top_level
  end

  ##
  # Generate a const table

  def gen_const_table file_content
    table = {}
    @content.scan(%r{
      ((?>^\s*/\*.*?\*/\s+))
        rb_define_(\w+)\((?:\s*(?:\w+),)?\s*
                           "(\w+)"\s*,
                           .*?\)\s*;
    | Document-(?:const|global|variable):\s
        ((?:\w+::)*\w+)
        \s*?\n((?>.*?\*/))
    }mxi) do
      case
      when $1 then table[[$2, $3]] = $1
      when $4 then table[$4] = "/*\n" + $5
      end
    end
    table
  end

  ##
  # Finds a comment matching +type+ and +const_name+ either above the
  # comment or in the matching Document- section.

  def find_const_comment(type, const_name, class_name = nil)
    @const_table ||= {}
    @const_table[@content] ||= gen_const_table @content
    table = @const_table[@content]

    comment =
      table[[type, const_name]] ||
      (class_name && table[class_name + "::" + const_name]) ||
      table[const_name] ||
      ''

    RDoc::Comment.new comment, @top_level, :c
  end

  ##
  # Handles modifiers in +comment+ and updates +meth_obj+ as appropriate.

  def find_modifiers comment, meth_obj
    comment.normalize
    comment.extract_call_seq meth_obj

    look_for_directives_in meth_obj, comment
  end

  ##
  # Finds a <tt>Document-method</tt> override for +meth_obj+ on +class_name+

  def find_override_comment class_name, meth_obj
    name = Regexp.escape meth_obj.name
    prefix = Regexp.escape meth_obj.name_prefix

    comment = if @content =~ %r%Document-method:
                                \s+#{class_name}#{prefix}#{name}
                                \s*?\n((?>.*?\*/))%xm then
                "/*#{$1}"
              elsif @content =~ %r%Document-method:
                                   \s#{name}\s*?\n((?>.*?\*/))%xm then
                "/*#{$1}"
              end

    return unless comment

    RDoc::Comment.new comment, @top_level, :c
  end

  ##
  # Creates a new RDoc::Attr +attr_name+ on class +var_name+ that is either
  # +read+, +write+ or both

  def handle_attr(var_name, attr_name, read, write)
    rw = ''
    rw += 'R' if '1' == read
    rw += 'W' if '1' == write

    class_name = @known_classes[var_name]

    return unless class_name

    class_obj = find_class var_name, class_name

    return unless class_obj

    comment = find_attr_comment var_name, attr_name
    comment.normalize

    name = attr_name.gsub(/rb_intern(?:_const)?\("([^"]+)"\)/, '\1')

    attr = RDoc::Attr.new '', name, rw, comment

    attr.record_location @top_level
    class_obj.add_attribute attr
    @stats.add_attribute attr
  end

  ##
  # Creates a new RDoc::NormalClass or RDoc::NormalModule based on +type+
  # named +class_name+ in +parent+ which was assigned to the C +var_name+.

  def handle_class_module(var_name, type, class_name, parent, in_module)
    parent_name = @known_classes[parent] || parent

    if in_module then
      enclosure = @classes[in_module] || @store.find_c_enclosure(in_module)

      if enclosure.nil? and enclosure = @known_classes[in_module] then
        enc_type = /^rb_m/ =~ in_module ? :module : :class
        handle_class_module in_module, enc_type, enclosure, nil, nil
        enclosure = @classes[in_module]
      end

      unless enclosure then
        @enclosure_dependencies[in_module] << var_name
        @missing_dependencies[var_name] =
          [var_name, type, class_name, parent, in_module]

        return
      end
    else
      enclosure = @top_level
    end

    if type == :class then
      full_name = if RDoc::ClassModule === enclosure then
                    enclosure.full_name + "::#{class_name}"
                  else
                    class_name
                  end

      if @content =~ %r%Document-class:\s+#{full_name}\s*<\s+([:,\w]+)% then
        parent_name = $1
      end

      cm = enclosure.add_class RDoc::NormalClass, class_name, parent_name
    else
      cm = enclosure.add_module RDoc::NormalModule, class_name
    end

    cm.record_location enclosure.top_level

    find_class_comment cm.full_name, cm

    case cm
    when RDoc::NormalClass
      @stats.add_class cm
    when RDoc::NormalModule
      @stats.add_module cm
    end

    @classes[var_name] = cm
    @known_classes[var_name] = cm.full_name
    @store.add_c_enclosure var_name, cm
  end

  ##
  # Adds constants.  By providing some_value: at the start of the comment you
  # can override the C value of the comment to give a friendly definition.
  #
  #   /* 300: The perfect score in bowling */
  #   rb_define_const(cFoo, "PERFECT", INT2FIX(300));
  #
  # Will override <tt>INT2FIX(300)</tt> with the value +300+ in the output
  # RDoc.  Values may include quotes and escaped colons (\:).

  def handle_constants(type, var_name, const_name, definition)
    class_name = @known_classes[var_name]

    return unless class_name

    class_obj = find_class var_name, class_name

    unless class_obj then
      @options.warn 'Enclosing class or module %p is not known' % [const_name]
      return
    end

    comment = find_const_comment type, const_name, class_name
    comment.normalize

    # In the case of rb_define_const, the definition and comment are in
    # "/* definition: comment */" form.  The literal ':' and '\' characters
    # can be escaped with a backslash.
    if type.downcase == 'const' then
      no_match, new_definition, new_comment = comment.text.split(/(\A.*):/)

      if no_match and no_match.empty? then
        if new_definition.empty? then # Default to literal C definition
          new_definition = definition
        else
          new_definition = new_definition.gsub("\:", ":")
          new_definition = new_definition.gsub("\\", '\\')
        end

        new_definition.sub!(/\A(\s+)/, '')

        new_comment = "#{$1}#{new_comment.lstrip}"

        new_comment = RDoc::Comment.new new_comment, @top_level, :c

        con = RDoc::Constant.new const_name, new_definition, new_comment
      else
        con = RDoc::Constant.new const_name, definition, comment
      end
    else
      con = RDoc::Constant.new const_name, definition, comment
    end

    con.record_location @top_level
    @stats.add_constant con
    class_obj.add_constant con
  end

  ##
  # Removes #ifdefs that would otherwise confuse us

  def handle_ifdefs_in(body)
    body.gsub(/^#ifdef HAVE_PROTOTYPES.*?#else.*?\n(.*?)#endif.*?\n/m, '\1')
  end

  ##
  # Adds an RDoc::AnyMethod +meth_name+ defined on a class or module assigned
  # to +var_name+.  +type+ is the type of method definition function used.
  # +singleton_method+ and +module_function+ create a singleton method.

  def handle_method(type, var_name, meth_name, function, param_count,
                    source_file = nil)
    class_name = @known_classes[var_name]
    singleton  = @singleton_classes.key? var_name

    @methods[var_name][function] << meth_name

    return unless class_name

    class_obj = find_class var_name, class_name

    if existing_method = class_obj.method_list.find { |m| m.c_function == function }
      add_alias(var_name, class_obj, existing_method.name, meth_name, existing_method.comment)
    end

    if class_obj then
      if meth_name == 'initialize' then
        meth_name = 'new'
        singleton = true
        type = 'method' # force public
      end

      meth_obj = RDoc::AnyMethod.new '', meth_name
      meth_obj.c_function = function
      meth_obj.singleton =
        singleton || %w[singleton_method module_function].include?(type)

      p_count = Integer(param_count) rescue -1

      if source_file then
        file_name = File.join @file_dir, source_file

        if File.exist? file_name then
          file_content = File.read file_name
        else
          @options.warn "unknown source #{source_file} for #{meth_name} in #{@file_name}"
        end
      else
        file_content = @content
      end

      body = find_body class_name, function, meth_obj, file_content

      if body and meth_obj.document_self then
        meth_obj.params = if p_count < -1 then # -2 is Array
                            '(*args)'
                          elsif p_count == -1 then # argc, argv
                            rb_scan_args body
                          else
                            "(#{(1..p_count).map { |i| "p#{i}" }.join ', '})"
                          end


        meth_obj.record_location @top_level
        class_obj.add_method meth_obj
        @stats.add_method meth_obj
        meth_obj.visibility = :private if 'private_method' == type
      end
    end
  end

  ##
  # Registers a singleton class +sclass_var+ as a singleton of +class_var+

  def handle_singleton sclass_var, class_var
    class_name = @known_classes[class_var]

    @known_classes[sclass_var]     = class_name
    @singleton_classes[sclass_var] = class_name
  end

  ##
  # Normalizes tabs in +body+

  def handle_tab_width(body)
    if /\t/ =~ body
      tab_width = @options.tab_width
      body.split(/\n/).map do |line|
        1 while line.gsub!(/\t+/) do
          ' ' * (tab_width * $&.length - $`.length % tab_width)
        end && $~
        line
      end.join "\n"
    else
      body
    end
  end

  ##
  # Loads the variable map with the given +name+ from the RDoc::Store, if
  # present.

  def load_variable_map map_name
    return {} unless files = @store.cache[map_name]
    return {} unless name_map = files[@file_name]

    class_map = {}

    name_map.each do |variable, name|
      next unless mod = @store.find_class_or_module(name)

      class_map[variable] = if map_name == :c_class_variables then
                              mod
                            else
                              name
                            end
      @known_classes[variable] = name
    end

    class_map
  end

  ##
  # Look for directives in a normal comment block:
  #
  #   /*
  #    * :title: My Awesome Project
  #    */
  #
  # This method modifies the +comment+

  def look_for_directives_in context, comment
    @preprocess.handle comment, context do |directive, param|
      case directive
      when 'main' then
        @options.main_page = param
        ''
      when 'title' then
        @options.default_title = param if @options.respond_to? :default_title=
        ''
      end
    end

    comment
  end

  ##
  # Extracts parameters from the +method_body+ and returns a method
  # parameter string.  Follows 1.9.3dev's scan-arg-spec, see README.EXT

  def rb_scan_args method_body
    method_body =~ /rb_scan_args\((.*?)\)/m
    return '(*args)' unless $1

    $1.split(/,/)[2] =~ /"(.*?)"/ # format argument
    format = $1.split(//)

    lead = opt = trail = 0

    if format.first =~ /\d/ then
      lead = $&.to_i
      format.shift
      if format.first =~ /\d/ then
        opt = $&.to_i
        format.shift
        if format.first =~ /\d/ then
          trail = $&.to_i
          format.shift
          block_arg = true
        end
      end
    end

    if format.first == '*' and not block_arg then
      var = true
      format.shift
      if format.first =~ /\d/ then
        trail = $&.to_i
        format.shift
      end
    end

    if format.first == ':' then
      hash = true
      format.shift
    end

    if format.first == '&' then
      block = true
      format.shift
    end

    # if the format string is not empty there's a bug in the C code, ignore it

    args = []
    position = 1

    (1...(position + lead)).each do |index|
      args << "p#{index}"
    end

    position += lead

    (position...(position + opt)).each do |index|
      args << "p#{index} = v#{index}"
    end

    position += opt

    if var then
      args << '*args'
      position += 1
    end

    (position...(position + trail)).each do |index|
      args << "p#{index}"
    end

    position += trail

    if hash then
      args << "p#{position} = {}"
    end

    args << '&block' if block

    "(#{args.join ', '})"
  end

  ##
  # Removes lines that are commented out that might otherwise get picked up
  # when scanning for classes and methods

  def remove_commented_out_lines
    @content = @content.gsub(%r%//.*rb_define_%, '//')
  end

  ##
  # Extracts the classes, modules, methods, attributes, constants and aliases
  # from a C file and returns an RDoc::TopLevel for this file

  def scan
    remove_commented_out_lines

    do_classes_and_modules
    do_missing

    do_constants
    do_methods
    do_includes
    do_aliases
    do_attrs

    @store.add_c_variables self

    @top_level
  end

end
# frozen_string_literal: true
require 'ripper'

class RDoc::Parser::RipperStateLex
  # TODO: Remove this constants after Ruby 2.4 EOL
  RIPPER_HAS_LEX_STATE = Ripper::Filter.method_defined?(:state)

  Token = Struct.new(:line_no, :char_no, :kind, :text, :state)

  EXPR_NONE = 0
  EXPR_BEG = 1
  EXPR_END = 2
  EXPR_ENDARG = 4
  EXPR_ENDFN = 8
  EXPR_ARG = 16
  EXPR_CMDARG = 32
  EXPR_MID = 64
  EXPR_FNAME = 128
  EXPR_DOT = 256
  EXPR_CLASS = 512
  EXPR_LABEL = 1024
  EXPR_LABELED = 2048
  EXPR_FITEM = 4096
  EXPR_VALUE = EXPR_BEG
  EXPR_BEG_ANY  =  (EXPR_BEG | EXPR_MID | EXPR_CLASS)
  EXPR_ARG_ANY  =  (EXPR_ARG | EXPR_CMDARG)
  EXPR_END_ANY  =  (EXPR_END | EXPR_ENDARG | EXPR_ENDFN)

  class InnerStateLex < Ripper::Filter
    attr_accessor :lex_state

    def initialize(code)
      @lex_state = EXPR_BEG
      @in_fname = false
      @continue = false
      reset
      super(code)
    end

    def reset
      @command_start = false
      @cmd_state = @command_start
    end

    def on_nl(tok, data)
      case @lex_state
      when EXPR_FNAME, EXPR_DOT
        @continue = true
      else
        @continue = false
        @lex_state = EXPR_BEG unless (EXPR_LABEL & @lex_state) != 0
      end
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_ignored_nl(tok, data)
      case @lex_state
      when EXPR_FNAME, EXPR_DOT
        @continue = true
      else
        @continue = false
        @lex_state = EXPR_BEG unless (EXPR_LABEL & @lex_state) != 0
      end
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_op(tok, data)
      case tok
      when '&', '|', '!', '!=', '!~'
        case @lex_state
        when EXPR_FNAME, EXPR_DOT
          @lex_state = EXPR_ARG
        else
          @lex_state = EXPR_BEG
        end
      when '<<'
        # TODO next token?
        case @lex_state
        when EXPR_FNAME, EXPR_DOT
          @lex_state = EXPR_ARG
        else
          @lex_state = EXPR_BEG
        end
      when '?'
        @lex_state = EXPR_BEG
      when '&&', '||', '+=', '-=', '*=', '**=',
           '&=', '|=', '^=', '<<=', '>>=', '||=', '&&='
        @lex_state = EXPR_BEG
      when '::'
        case @lex_state
        when EXPR_ARG, EXPR_CMDARG
          @lex_state = EXPR_DOT
        when EXPR_FNAME, EXPR_DOT
          @lex_state = EXPR_ARG
        else
          @lex_state = EXPR_BEG
        end
      else
        case @lex_state
        when EXPR_FNAME, EXPR_DOT
          @lex_state = EXPR_ARG
        else
          @lex_state = EXPR_BEG
        end
      end
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_kw(tok, data)
      case tok
      when 'class'
        @lex_state = EXPR_CLASS
        @in_fname = true
      when 'def'
        @lex_state = EXPR_FNAME
        @continue = true
        @in_fname = true
      when 'if', 'unless', 'while', 'until'
        if ((EXPR_MID | EXPR_END | EXPR_ENDARG | EXPR_ENDFN | EXPR_ARG | EXPR_CMDARG) & @lex_state) != 0 # postfix if
          @lex_state = EXPR_BEG | EXPR_LABEL
        else
          @lex_state = EXPR_BEG
        end
      when 'begin', 'case', 'when'
        @lex_state = EXPR_BEG
      when 'return', 'break'
        @lex_state = EXPR_MID
      else
        if @lex_state == EXPR_FNAME
          @lex_state = EXPR_END
        else
          @lex_state = EXPR_END
        end
      end
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_tstring_beg(tok, data)
      @lex_state = EXPR_BEG
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_tstring_end(tok, data)
      @lex_state = EXPR_END | EXPR_ENDARG
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_CHAR(tok, data)
      @lex_state = EXPR_END
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_period(tok, data)
      @lex_state = EXPR_DOT
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_int(tok, data)
      @lex_state = EXPR_END | EXPR_ENDARG
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_float(tok, data)
      @lex_state = EXPR_END | EXPR_ENDARG
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_rational(tok, data)
      @lex_state = EXPR_END | EXPR_ENDARG
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_imaginary(tok, data)
      @lex_state = EXPR_END | EXPR_ENDARG
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_symbeg(tok, data)
      @lex_state = EXPR_FNAME
      @continue = true
      @in_fname = true
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    private def on_variables(event, tok, data)
      if @in_fname
        @lex_state = EXPR_ENDFN
        @in_fname = false
        @continue = false
      elsif @continue
        case @lex_state
        when EXPR_DOT
          @lex_state = EXPR_ARG
        else
          @lex_state = EXPR_ENDFN
          @continue = false
        end
      else
        @lex_state = EXPR_CMDARG
      end
      data << Token.new(lineno, column, event, tok, @lex_state)
    end

    def on_ident(tok, data)
      on_variables(__method__, tok, data)
    end

    def on_ivar(tok, data)
      @lex_state = EXPR_END
      on_variables(__method__, tok, data)
    end

    def on_cvar(tok, data)
      @lex_state = EXPR_END
      on_variables(__method__, tok, data)
    end

    def on_gvar(tok, data)
      @lex_state = EXPR_END
      on_variables(__method__, tok, data)
    end

    def on_backref(tok, data)
      @lex_state = EXPR_END
      on_variables(__method__, tok, data)
    end

    def on_lparen(tok, data)
      @lex_state = EXPR_LABEL | EXPR_BEG
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_rparen(tok, data)
      @lex_state = EXPR_ENDFN
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_lbrace(tok, data)
      @lex_state = EXPR_LABEL | EXPR_BEG
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_rbrace(tok, data)
      @lex_state = EXPR_ENDARG
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_lbracket(tok, data)
      @lex_state = EXPR_LABEL | EXPR_BEG
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_rbracket(tok, data)
      @lex_state = EXPR_ENDARG
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_const(tok, data)
      case @lex_state
      when EXPR_FNAME
        @lex_state = EXPR_ENDFN
      when EXPR_CLASS, EXPR_CMDARG, EXPR_MID
        @lex_state = EXPR_ARG
      else
        @lex_state = EXPR_CMDARG
      end
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_sp(tok, data)
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_comma(tok, data)
      @lex_state = EXPR_BEG | EXPR_LABEL if (EXPR_ARG_ANY & @lex_state) != 0
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_comment(tok, data)
      @lex_state = EXPR_BEG unless (EXPR_LABEL & @lex_state) != 0
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_ignored_sp(tok, data)
      @lex_state = EXPR_BEG unless (EXPR_LABEL & @lex_state) != 0
      data << Token.new(lineno, column, __method__, tok, @lex_state)
    end

    def on_heredoc_beg(tok, data)
      data << Token.new(lineno, column, __method__, tok, @lex_state)
      @lex_state = EXPR_END
      data
    end

    def on_heredoc_end(tok, data)
      data << Token.new(lineno, column, __method__, tok, @lex_state)
      @lex_state = EXPR_BEG
      data
    end

    def on_default(event, tok, data)
      reset
      data << Token.new(lineno, column, event, tok, @lex_state)
    end
  end unless RIPPER_HAS_LEX_STATE

  class InnerStateLex < Ripper::Filter
    def initialize(code)
      super(code)
    end

    def on_default(event, tok, data)
      data << Token.new(lineno, column, event, tok, state)
    end
  end if RIPPER_HAS_LEX_STATE

  def get_squashed_tk
    if @buf.empty?
      tk = @tokens.shift
    else
      tk = @buf.shift
    end
    return nil if tk.nil?
    case tk[:kind]
    when :on_symbeg then
      tk = get_symbol_tk(tk)
    when :on_tstring_beg then
      tk = get_string_tk(tk)
    when :on_backtick then
      if (tk[:state] & (EXPR_FNAME | EXPR_ENDFN)) != 0
        @inner_lex.lex_state = EXPR_ARG unless RIPPER_HAS_LEX_STATE
        tk[:kind] = :on_ident
        tk[:state] = Ripper::Lexer.const_defined?(:State) ? Ripper::Lexer::State.new(EXPR_ARG) : EXPR_ARG
      else
        tk = get_string_tk(tk)
      end
    when :on_regexp_beg then
      tk = get_regexp_tk(tk)
    when :on_embdoc_beg then
      tk = get_embdoc_tk(tk)
    when :on_heredoc_beg then
      @heredoc_queue << retrieve_heredoc_info(tk)
      @inner_lex.lex_state = EXPR_END unless RIPPER_HAS_LEX_STATE
    when :on_nl, :on_ignored_nl, :on_comment, :on_heredoc_end then
      if !@heredoc_queue.empty?
        get_heredoc_tk(*@heredoc_queue.shift)
      elsif tk[:text].nil? # :on_ignored_nl sometimes gives nil
        tk[:text] = ''
      end
    when :on_words_beg then
      tk = get_words_tk(tk)
    when :on_qwords_beg then
      tk = get_words_tk(tk)
    when :on_symbols_beg then
      tk = get_words_tk(tk)
    when :on_qsymbols_beg then
      tk = get_words_tk(tk)
    when :on_op then
      if '&.' == tk[:text]
        tk[:kind] = :on_period
      else
        tk = get_op_tk(tk)
      end
    end
    tk
  end

  private def get_symbol_tk(tk)
    is_symbol = true
    symbol_tk = Token.new(tk.line_no, tk.char_no, :on_symbol)
    if ":'" == tk[:text] or ':"' == tk[:text]
      tk1 = get_string_tk(tk)
      symbol_tk[:text] = tk1[:text]
      symbol_tk[:state] = tk1[:state]
    else
      case (tk1 = get_squashed_tk)[:kind]
      when :on_ident
        symbol_tk[:text] = ":#{tk1[:text]}"
        symbol_tk[:state] = tk1[:state]
      when :on_tstring_content
        symbol_tk[:text] = ":#{tk1[:text]}"
        symbol_tk[:state] = get_squashed_tk[:state] # skip :on_tstring_end
      when :on_tstring_end
        symbol_tk[:text] = ":#{tk1[:text]}"
        symbol_tk[:state] = tk1[:state]
      when :on_op
        symbol_tk[:text] = ":#{tk1[:text]}"
        symbol_tk[:state] = tk1[:state]
      when :on_ivar
        symbol_tk[:text] = ":#{tk1[:text]}"
        symbol_tk[:state] = tk1[:state]
      when :on_cvar
        symbol_tk[:text] = ":#{tk1[:text]}"
        symbol_tk[:state] = tk1[:state]
      when :on_gvar
        symbol_tk[:text] = ":#{tk1[:text]}"
        symbol_tk[:state] = tk1[:state]
      when :on_const
        symbol_tk[:text] = ":#{tk1[:text]}"
        symbol_tk[:state] = tk1[:state]
      when :on_kw
        symbol_tk[:text] = ":#{tk1[:text]}"
        symbol_tk[:state] = tk1[:state]
      else
        is_symbol = false
        tk = tk1
      end
    end
    if is_symbol
      tk = symbol_tk
    end
    tk
  end

  private def get_string_tk(tk)
    string = tk[:text]
    state = nil
    kind = :on_tstring
    loop do
      inner_str_tk = get_squashed_tk
      if inner_str_tk.nil?
        break
      elsif :on_tstring_end == inner_str_tk[:kind]
        string = string + inner_str_tk[:text]
        state = inner_str_tk[:state]
        break
      elsif :on_label_end == inner_str_tk[:kind]
        string = string + inner_str_tk[:text]
        state = inner_str_tk[:state]
        kind = :on_symbol
        break
      else
        string = string + inner_str_tk[:text]
        if :on_embexpr_beg == inner_str_tk[:kind] then
          kind = :on_dstring if :on_tstring == kind
        end
      end
    end
    Token.new(tk.line_no, tk.char_no, kind, string, state)
  end

  private def get_regexp_tk(tk)
    string = tk[:text]
    state = nil
    loop do
      inner_str_tk = get_squashed_tk
      if inner_str_tk.nil?
        break
      elsif :on_regexp_end == inner_str_tk[:kind]
        string = string + inner_str_tk[:text]
        state = inner_str_tk[:state]
        break
      else
        string = string + inner_str_tk[:text]
      end
    end
    Token.new(tk.line_no, tk.char_no, :on_regexp, string, state)
  end

  private def get_embdoc_tk(tk)
    string = tk[:text]
    until :on_embdoc_end == (embdoc_tk = get_squashed_tk)[:kind] do
      string = string + embdoc_tk[:text]
    end
    string = string + embdoc_tk[:text]
    Token.new(tk.line_no, tk.char_no, :on_embdoc, string, embdoc_tk.state)
  end

  private def get_heredoc_tk(heredoc_name, indent)
    string = ''
    start_tk = nil
    prev_tk = nil
    until heredoc_end?(heredoc_name, indent, tk = @tokens.shift) do
      start_tk = tk unless start_tk
      if (prev_tk.nil? or "\n" == prev_tk[:text][-1]) and 0 != tk[:char_no]
        string = string + (' ' * tk[:char_no])
      end
      string = string + tk[:text]
      prev_tk = tk
    end
    start_tk = tk unless start_tk
    prev_tk = tk unless prev_tk
    @buf.unshift tk # closing heredoc
    heredoc_tk = Token.new(start_tk.line_no, start_tk.char_no, :on_heredoc, string, prev_tk.state)
    @buf.unshift heredoc_tk
  end

  private def retrieve_heredoc_info(tk)
    name = tk[:text].gsub(/\A<<[-~]?(['"`]?)(.+)\1\z/, '\2')
    indent = tk[:text] =~ /\A<<[-~]/
    [name, indent]
  end

  private def heredoc_end?(name, indent, tk)
    result = false
    if :on_heredoc_end == tk[:kind] then
      tk_name = tk[:text].chomp
      tk_name.lstrip! if indent
      if name == tk_name
        result = true
      end
    end
    result
  end

  private def get_words_tk(tk)
    string = ''
    start_token = tk[:text]
    start_quote = tk[:text].rstrip[-1]
    line_no = tk[:line_no]
    char_no = tk[:char_no]
    state = tk[:state]
    end_quote =
      case start_quote
      when ?( then ?)
      when ?[ then ?]
      when ?{ then ?}
      when ?< then ?>
      else start_quote
      end
    end_token = nil
    loop do
      tk = get_squashed_tk
      if tk.nil?
        end_token = end_quote
        break
      elsif :on_tstring_content == tk[:kind] then
        string += tk[:text]
      elsif :on_words_sep == tk[:kind] or :on_tstring_end == tk[:kind] then
        if end_quote == tk[:text].strip then
          end_token = tk[:text]
          break
        else
          string += tk[:text]
        end
      else
        string += tk[:text]
      end
    end
    text = "#{start_token}#{string}#{end_token}"
    Token.new(line_no, char_no, :on_dstring, text, state)
  end

  private def get_op_tk(tk)
    redefinable_operators = %w[! != !~ % & * ** + +@ - -@ / < << <= <=> == === =~ > >= >> [] []= ^ ` | ~]
    if redefinable_operators.include?(tk[:text]) and tk[:state] == EXPR_ARG then
      @inner_lex.lex_state = EXPR_ARG unless RIPPER_HAS_LEX_STATE
      tk[:state] = Ripper::Lexer.const_defined?(:State) ? Ripper::Lexer::State.new(EXPR_ARG) : EXPR_ARG
      tk[:kind] = :on_ident
    elsif tk[:text] =~ /^[-+]$/ then
      tk_ahead = get_squashed_tk
      case tk_ahead[:kind]
      when :on_int, :on_float, :on_rational, :on_imaginary then
        tk[:text] += tk_ahead[:text]
        tk[:kind] = tk_ahead[:kind]
        tk[:state] = tk_ahead[:state]
      when :on_heredoc_beg, :on_tstring, :on_dstring # frozen/non-frozen string literal
        tk[:text] += tk_ahead[:text]
        tk[:kind] = tk_ahead[:kind]
        tk[:state] = tk_ahead[:state]
      else
        @buf.unshift tk_ahead
      end
    end
    tk
  end

  def initialize(code)
    @buf = []
    @heredoc_queue = []
    @inner_lex = InnerStateLex.new(code)
    @tokens = @inner_lex.parse([])
  end

  def self.parse(code)
    lex = self.new(code)
    tokens = []
    begin
      while tk = lex.get_squashed_tk
        tokens.push tk
      end
    rescue StopIteration
    end
    tokens
  end

  def self.end?(token)
    (token[:state] & EXPR_END)
  end
end
# frozen_string_literal: true
module RDoc

  ##
  # Ruby's built-in classes, modules and exceptions

  KNOWN_CLASSES = {
    "rb_cArray"            => "Array",
    "rb_cBasicObject"      => "BasicObject",
    "rb_cBignum"           => "Bignum",
    "rb_cClass"            => "Class",
    "rb_cData"             => "Data",
    "rb_cDir"              => "Dir",
    "rb_cEncoding"         => "Encoding",
    "rb_cFalseClass"       => "FalseClass",
    "rb_cFile"             => "File",
    "rb_cFixnum"           => "Fixnum",
    "rb_cFloat"            => "Float",
    "rb_cHash"             => "Hash",
    "rb_cIO"               => "IO",
    "rb_cInteger"          => "Integer",
    "rb_cModule"           => "Module",
    "rb_cNilClass"         => "NilClass",
    "rb_cNumeric"          => "Numeric",
    "rb_cObject"           => "Object",
    "rb_cProc"             => "Proc",
    "rb_cRange"            => "Range",
    "rb_cRegexp"           => "Regexp",
    "rb_cRubyVM"           => "RubyVM",
    "rb_cSocket"           => "Socket",
    "rb_cString"           => "String",
    "rb_cStruct"           => "Struct",
    "rb_cSymbol"           => "Symbol",
    "rb_cThread"           => "Thread",
    "rb_cTime"             => "Time",
    "rb_cTrueClass"        => "TrueClass",

    "rb_eArgError"         => "ArgError",
    "rb_eEOFError"         => "EOFError",
    "rb_eException"        => "Exception",
    "rb_eFatal"            => "fatal",
    "rb_eFloatDomainError" => "FloatDomainError",
    "rb_eIOError"          => "IOError",
    "rb_eIndexError"       => "IndexError",
    "rb_eInterrupt"        => "Interrupt",
    "rb_eLoadError"        => "LoadError",
    "rb_eNameError"        => "NameError",
    "rb_eNoMemError"       => "NoMemError",
    "rb_eNotImpError"      => "NotImpError",
    "rb_eRangeError"       => "RangeError",
    "rb_eRuntimeError"     => "RuntimeError",
    "rb_eScriptError"      => "ScriptError",
    "rb_eSecurityError"    => "SecurityError",
    "rb_eSignal"           => "SignalException",
    "rb_eStandardError"    => "StandardError",
    "rb_eSyntaxError"      => "SyntaxError",
    "rb_eSystemCallError"  => "SystemCallError",
    "rb_eSystemExit"       => "SystemExit",
    "rb_eTypeError"        => "TypeError",
    "rb_eZeroDivError"     => "ZeroDivError",

    "rb_mComparable"       => "Comparable",
    "rb_mEnumerable"       => "Enumerable",
    "rb_mErrno"            => "Errno",
    "rb_mFConst"           => "File::Constants",
    "rb_mFileTest"         => "FileTest",
    "rb_mGC"               => "GC",
    "rb_mKernel"           => "Kernel",
    "rb_mMath"             => "Math",
    "rb_mProcess"          => "Process"
  }

end
# frozen_string_literal: true
##
# A file loaded by \#require

class RDoc::Require < RDoc::CodeObject

  ##
  # Name of the required file

  attr_accessor :name

  ##
  # Creates a new Require that loads +name+ with +comment+

  def initialize(name, comment)
    super()
    @name = name.gsub(/'|"/, "") #'
    @top_level = nil
    self.comment = comment
  end

  def inspect # :nodoc:
    "#<%s:0x%x require '%s' in %s>" % [
      self.class,
      object_id,
      @name,
      parent_file_name,
    ]
  end

  def to_s # :nodoc:
    "require #{name} in: #{parent}"
  end

  ##
  # The RDoc::TopLevel corresponding to this require, or +nil+ if not found.

  def top_level
    @top_level ||= begin
      tl = RDoc::TopLevel.all_files_hash[name + '.rb']

      if tl.nil? and RDoc::TopLevel.all_files.first.full_name =~ %r(^lib/) then
        # second chance
        tl = RDoc::TopLevel.all_files_hash['lib/' + name + '.rb']
      end

      tl
    end
  end

end

# frozen_string_literal: true
# This file was used to load all the RDoc::CodeObject subclasses at once.  Now
# autoload handles this.

require 'rdoc'

# frozen_string_literal: true
##
# A normal module, like NormalClass

class RDoc::NormalModule < RDoc::ClassModule

  def aref_prefix # :nodoc:
    'module'
  end

  def inspect # :nodoc:
    "#<%s:0x%x module %s includes: %p extends: %p attributes: %p methods: %p aliases: %p>" % [
      self.class, object_id,
      full_name, @includes, @extends, @attributes, @method_list, @aliases
    ]
  end

  ##
  # The definition of this module, <tt>module MyModuleName</tt>

  def definition
    "module #{full_name}"
  end

  ##
  # This is a module, returns true

  def module?
    true
  end

  def pretty_print q # :nodoc:
    q.group 2, "[module #{full_name}: ", "]" do
      q.breakable
      q.text "includes:"
      q.breakable
      q.seplist @includes do |inc| q.pp inc end
      q.breakable

      q.breakable
      q.text "constants:"
      q.breakable
      q.seplist @constants do |const| q.pp const end

      q.text "attributes:"
      q.breakable
      q.seplist @attributes do |attr| q.pp attr end
      q.breakable

      q.text "methods:"
      q.breakable
      q.seplist @method_list do |meth| q.pp meth end
      q.breakable

      q.text "aliases:"
      q.breakable
      q.seplist @aliases do |aliaz| q.pp aliaz end
      q.breakable

      q.text "comment:"
      q.breakable
      q.pp comment
    end
  end

  ##
  # Modules don't have one, raises NoMethodError

  def superclass
    raise NoMethodError, "#{full_name} is a module"
  end

end

# 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

# frozen_string_literal: true
##
# An i18n supported text.
#
# This object provides the following two features:
#
#   * Extracts translation messages from wrapped raw text.
#   * Translates wrapped raw text in specified locale.
#
# Wrapped raw text is one of String, RDoc::Comment or Array of them.

class RDoc::I18n::Text

  ##
  # Creates a new i18n supported text for +raw+ text.

  def initialize(raw)
    @raw = raw
  end

  ##
  # Extracts translation target messages and yields each message.
  #
  # Each yielded message is a Hash. It consists of the followings:
  #
  # :type      :: :paragraph
  # :paragraph :: String (The translation target message itself.)
  # :line_no   :: Integer (The line number of the :paragraph is started.)
  #
  # The above content may be added in the future.

  def extract_messages
    parse do |part|
      case part[:type]
      when :empty_line
        # ignore
      when :paragraph
        yield(part)
      end
    end
  end

  # Translates raw text into +locale+.
  def translate(locale)
    translated_text = ''
    parse do |part|
      case part[:type]
      when :paragraph
        translated_text += locale.translate(part[:paragraph])
      when :empty_line
        translated_text += part[:line]
      else
        raise "should not reach here: unexpected type: #{type}"
      end
    end
    translated_text
  end

  private
  def parse(&block)
    paragraph = ''
    paragraph_start_line = 0
    line_no = 0

    each_line(@raw) do |line|
      line_no += 1
      case line
      when /\A\s*\z/
        if paragraph.empty?
          emit_empty_line_event(line, line_no, &block)
        else
          paragraph += line
          emit_paragraph_event(paragraph, paragraph_start_line, line_no,
                               &block)
          paragraph = ''
        end
      else
        paragraph_start_line = line_no if paragraph.empty?
        paragraph += line
      end
    end

    unless paragraph.empty?
      emit_paragraph_event(paragraph, paragraph_start_line, line_no, &block)
    end
  end

  def each_line(raw, &block)
    case raw
    when RDoc::Comment
      raw.text.each_line(&block)
    when Array
      raw.each do |comment, location|
        each_line(comment, &block)
      end
    else
      raw.each_line(&block)
    end
  end

  def emit_empty_line_event(line, line_no)
    part = {
      :type => :empty_line,
      :line => line,
      :line_no => line_no,
    }
    yield(part)
  end

  def emit_paragraph_event(paragraph, paragraph_start_line, line_no, &block)
    paragraph_part = {
      :type => :paragraph,
      :line_no => paragraph_start_line,
    }
    match_data = /(\s*)\z/.match(paragraph)
    if match_data
      paragraph_part[:paragraph] = match_data.pre_match
      yield(paragraph_part)
      emit_empty_line_event(match_data[1], line_no, &block)
    else
      paragraph_part[:paragraph] = paragraph
      yield(paragraph_part)
    end
  end

end
# frozen_string_literal: true
##
# A message container for a locale.
#
# This object provides the following two features:
#
#   * Loads translated messages from .po file.
#   * Translates a message into the locale.

class RDoc::I18n::Locale

  @@locales = {} # :nodoc:

  class << self

    ##
    # Returns the locale object for +locale_name+.

    def [](locale_name)
      @@locales[locale_name] ||= new(locale_name)
    end

    ##
    # Sets the locale object for +locale_name+.
    #
    # Normally, this method is not used. This method is useful for
    # testing.

    def []=(locale_name, locale)
      @@locales[locale_name] = locale
    end

  end

  ##
  # The name of the locale. It uses IETF language tag format
  # +[language[_territory][.codeset][@modifier]]+.
  #
  # See also {BCP 47 - Tags for Identifying
  # Languages}[http://tools.ietf.org/rfc/bcp/bcp47.txt].

  attr_reader :name

  ##
  # Creates a new locale object for +name+ locale. +name+ must
  # follow IETF language tag format.

  def initialize(name)
    @name = name
    @messages = {}
  end

  ##
  # Loads translation messages from +locale_directory+/+@name+/rdoc.po
  # or +locale_directory+/+@name+.po. The former has high priority.
  #
  # This method requires gettext gem for parsing .po file. If you
  # don't have gettext gem, this method doesn't load .po file. This
  # method warns and returns +false+.
  #
  # Returns +true+ if succeeded, +false+ otherwise.

  def load(locale_directory)
    return false if @name.nil?

    po_file_candidates = [
      File.join(locale_directory, @name, 'rdoc.po'),
      File.join(locale_directory, "#{@name}.po"),
    ]
    po_file = po_file_candidates.find do |po_file_candidate|
      File.exist?(po_file_candidate)
    end
    return false unless po_file

    begin
      require 'gettext/po_parser'
      require 'gettext/mo'
    rescue LoadError
      warn('Need gettext gem for i18n feature:')
      warn('  gem install gettext')
      return false
    end

    po_parser = GetText::POParser.new
    messages = GetText::MO.new
    po_parser.report_warning = false
    po_parser.parse_file(po_file, messages)

    @messages.merge!(messages)

    true
  end

  ##
  # Translates the +message+ into locale. If there is no translation
  # messages for +message+ in locale, +message+ itself is returned.

  def translate(message)
    @messages[message] || message
  end

end
# frozen_string_literal: true

##
# For RDoc::Text#to_html

require 'strscan'

##
# Methods for manipulating comment text

module RDoc::Text

  attr_accessor :language

  ##
  # Maps markup formats to classes that can parse them.  If the format is
  # unknown, "rdoc" format is used.

  MARKUP_FORMAT = {
    'markdown' => RDoc::Markdown,
    'rdoc'     => RDoc::Markup,
    'rd'       => RDoc::RD,
    'tomdoc'   => RDoc::TomDoc,
  }

  MARKUP_FORMAT.default = RDoc::Markup

  ##
  # Maps an encoding to a Hash of characters properly transcoded for that
  # encoding.
  #
  # See also encode_fallback.

  TO_HTML_CHARACTERS = Hash.new do |h, encoding|
    h[encoding] = {
      :close_dquote => encode_fallback('”', encoding, '"'),
      :close_squote => encode_fallback('’', encoding, '\''),
      :copyright    => encode_fallback('©', encoding, '(c)'),
      :ellipsis     => encode_fallback('…', encoding, '...'),
      :em_dash      => encode_fallback('—', encoding, '---'),
      :en_dash      => encode_fallback('–', encoding, '--'),
      :open_dquote  => encode_fallback('“', encoding, '"'),
      :open_squote  => encode_fallback('‘', encoding, '\''),
      :trademark    => encode_fallback('®', encoding, '(r)'),
    }
  end

  ##
  # Transcodes +character+ to +encoding+ with a +fallback+ character.

  def self.encode_fallback character, encoding, fallback
    character.encode(encoding, :fallback => { character => fallback },
                     :undef => :replace, :replace => fallback)
  end

  ##
  # Expands tab characters in +text+ to eight spaces

  def expand_tabs text
    expanded = []

    text.each_line do |line|
      nil while line.gsub!(/(?:\G|\r)((?:.{8})*?)([^\t\r\n]{0,7})\t/) do
        r = "#{$1}#{$2}#{' ' * (8 - $2.size)}"
        r = RDoc::Encoding.change_encoding r, text.encoding
        r
      end

      expanded << line
    end

    expanded.join
  end

  ##
  # Flush +text+ left based on the shortest line

  def flush_left text
    indent = 9999

    text.each_line do |line|
      line_indent = line =~ /\S/ || 9999
      indent = line_indent if indent > line_indent
    end

    empty = ''
    empty = RDoc::Encoding.change_encoding empty, text.encoding

    text.gsub(/^ {0,#{indent}}/, empty)
  end

  ##
  # Convert a string in markup format into HTML.
  #
  # Requires the including class to implement #formatter

  def markup text
    if @store.rdoc.options
      locale = @store.rdoc.options.locale
    else
      locale = nil
    end
    if locale
      i18n_text = RDoc::I18n::Text.new(text)
      text = i18n_text.translate(locale)
    end
    parse(text).accept formatter
  end

  ##
  # Strips hashes, expands tabs then flushes +text+ to the left

  def normalize_comment text
    return text if text.empty?

    case language
    when :ruby
      text = strip_hashes text
    when :c
      text = strip_stars text
    end
    text = expand_tabs    text
    text = flush_left     text
    text = strip_newlines text
    text
  end

  ##
  # Normalizes +text+ then builds a RDoc::Markup::Document from it

  def parse text, format = 'rdoc'
    return text if RDoc::Markup::Document === text
    return text.parse if RDoc::Comment === text

    text = normalize_comment text # TODO remove, should not be necessary

    return RDoc::Markup::Document.new if text =~ /\A\n*\z/

    MARKUP_FORMAT[format].parse text
  end

  ##
  # The first +limit+ characters of +text+ as HTML

  def snippet text, limit = 100
    document = parse text

    RDoc::Markup::ToHtmlSnippet.new(options, limit).convert document
  end

  ##
  # Strips leading # characters from +text+

  def strip_hashes text
    return text if text =~ /^(?>\s*)[^\#]/

    empty = ''
    empty = RDoc::Encoding.change_encoding empty, text.encoding

    text.gsub(/^\s*(#+)/) { $1.tr '#', ' ' }.gsub(/^\s+$/, empty)
  end

  ##
  # Strips leading and trailing \n characters from +text+

  def strip_newlines text
    text.gsub(/\A\n*(.*?)\n*\z/m) do $1 end # block preserves String encoding
  end

  ##
  # Strips /* */ style comments

  def strip_stars text
    return text unless text =~ %r%/\*.*\*/%m

    encoding = text.encoding

    text = text.gsub %r%Document-method:\s+[\w:.#=!?|^&<>~+\-/*\%@`\[\]]+%, ''

    space = ' '
    space = RDoc::Encoding.change_encoding space, encoding if encoding

    text.sub!  %r%/\*+%       do space * $&.length end
    text.sub!  %r%\*+/%       do space * $&.length end
    text.gsub! %r%^[ \t]*\*%m do space * $&.length end

    empty = ''
    empty = RDoc::Encoding.change_encoding empty, encoding if encoding
    text.gsub(/^\s+$/, empty)
  end

  ##
  # Converts ampersand, dashes, ellipsis, quotes, copyright and registered
  # trademark symbols in +text+ to properly encoded characters.

  def to_html text
    html = (''.encode text.encoding).dup

    encoded = RDoc::Text::TO_HTML_CHARACTERS[text.encoding]

    s = StringScanner.new text
    insquotes = false
    indquotes = false
    after_word = nil

    until s.eos? do
      case
      when s.scan(/<(tt|code)>.*?<\/\1>/) then # skip contents of tt
        html << s.matched.gsub('\\\\', '\\')
      when s.scan(/<(tt|code)>.*?/) then
        warn "mismatched <#{s[1]}> tag" # TODO signal file/line
        html << s.matched
      when s.scan(/<[^>]+\/?s*>/) then # skip HTML tags
        html << s.matched
      when s.scan(/\\(\S)/) then # unhandled suppressed crossref
        html << s[1]
        after_word = nil
      when s.scan(/\.\.\.(\.?)/) then
        html << s[1] << encoded[:ellipsis]
        after_word = nil
      when s.scan(/\(c\)/) then
        html << encoded[:copyright]
        after_word = nil
      when s.scan(/\(r\)/) then
        html << encoded[:trademark]
        after_word = nil
      when s.scan(/---/) then
        html << encoded[:em_dash]
        after_word = nil
      when s.scan(/--/) then
        html << encoded[:en_dash]
        after_word = nil
      when s.scan(/&quot;|"/) then
        html << encoded[indquotes ? :close_dquote : :open_dquote]
        indquotes = !indquotes
        after_word = nil
      when s.scan(/``/) then # backtick double quote
        html << encoded[:open_dquote]
        after_word = nil
      when s.scan(/''/) then # tick double quote
        html << encoded[:close_dquote]
        after_word = nil
      when s.scan(/'/) then # single quote
        if insquotes
          html << encoded[:close_squote]
          insquotes = false
        elsif after_word
          # Mary's dog, my parents' house: do not start paired quotes
          html << encoded[:close_squote]
        else
          html << encoded[:open_squote]
          insquotes = true
        end

        after_word = nil
      else # advance to the next potentially significant character
        match = s.scan(/.+?(?=[<\\.("'`&-])/) #"

        if match then
          html << match
          after_word = match =~ /\w$/
        else
          html << s.rest
          break
        end
      end
    end

    html
  end

  ##
  # Wraps +txt+ to +line_len+

  def wrap(txt, line_len = 76)
    res = []
    sp = 0
    ep = txt.length

    while sp < ep
      # scan back for a space
      p = sp + line_len - 1
      if p >= ep
        p = ep
      else
        while p > sp and txt[p] != ?\s
          p -= 1
        end
        if p <= sp
          p = sp + line_len
          while p < ep and txt[p] != ?\s
            p += 1
          end
        end
      end
      res << txt[sp...p] << "\n"
      sp = p
      sp += 1 while sp < ep and txt[sp] == ?\s
    end

    res.join.strip
  end

end
# frozen_string_literal: true
require 'rdoc'

require 'find'
require 'fileutils'
require 'pathname'
require 'time'

##
# This is the driver for generating RDoc output.  It handles file parsing and
# generation of output.
#
# To use this class to generate RDoc output via the API, the recommended way
# is:
#
#   rdoc = RDoc::RDoc.new
#   options = rdoc.load_options # returns an RDoc::Options instance
#   # set extra options
#   rdoc.document options
#
# You can also generate output like the +rdoc+ executable:
#
#   rdoc = RDoc::RDoc.new
#   rdoc.document argv
#
# Where +argv+ is an array of strings, each corresponding to an argument you'd
# give rdoc on the command line.  See <tt>rdoc --help</tt> for details.

class RDoc::RDoc

  @current = nil

  ##
  # This is the list of supported output generators

  GENERATORS = {}

  ##
  # Generator instance used for creating output

  attr_accessor :generator

  ##
  # Hash of files and their last modified times.

  attr_reader :last_modified

  ##
  # RDoc options

  attr_accessor :options

  ##
  # Accessor for statistics.  Available after each call to parse_files

  attr_reader :stats

  ##
  # The current documentation store

  attr_reader :store

  ##
  # Add +klass+ that can generate output after parsing

  def self.add_generator(klass)
    name = klass.name.sub(/^RDoc::Generator::/, '').downcase
    GENERATORS[name] = klass
  end

  ##
  # Active RDoc::RDoc instance

  def self.current
    @current
  end

  ##
  # Sets the active RDoc::RDoc instance

  def self.current= rdoc
    @current = rdoc
  end

  ##
  # Creates a new RDoc::RDoc instance.  Call #document to parse files and
  # generate documentation.

  def initialize
    @current       = nil
    @generator     = nil
    @last_modified = {}
    @old_siginfo   = nil
    @options       = nil
    @stats         = nil
    @store         = nil
  end

  ##
  # Report an error message and exit

  def error(msg)
    raise RDoc::Error, msg
  end

  ##
  # Gathers a set of parseable files from the files and directories listed in
  # +files+.

  def gather_files files
    files = ["."] if files.empty?

    file_list = normalized_file_list files, true, @options.exclude

    file_list = remove_unparseable(file_list)

    if file_list.count {|name, mtime|
         file_list[name] = @last_modified[name] unless mtime
         mtime
       } > 0
      @last_modified.replace file_list
      file_list.keys.sort
    else
      []
    end
  end

  ##
  # Turns RDoc from stdin into HTML

  def handle_pipe
    @html = RDoc::Markup::ToHtml.new @options

    parser = RDoc::Text::MARKUP_FORMAT[@options.markup]

    document = parser.parse $stdin.read

    out = @html.convert document

    $stdout.write out
  end

  ##
  # Installs a siginfo handler that prints the current filename.

  def install_siginfo_handler
    return unless Signal.list.include? 'INFO'

    @old_siginfo = trap 'INFO' do
      puts @current if @current
    end
  end

  ##
  # Loads options from .rdoc_options if the file exists, otherwise creates a
  # new RDoc::Options instance.

  def load_options
    options_file = File.expand_path '.rdoc_options'
    return RDoc::Options.new unless File.exist? options_file

    RDoc.load_yaml

    begin
      options = YAML.safe_load_file '.rdoc_options', permitted_classes: [RDoc::Options, Symbol]
    rescue Psych::SyntaxError
      raise RDoc::Error, "#{options_file} is not a valid rdoc options file"
    end

    return RDoc::Options.new unless options # Allow empty file.

    raise RDoc::Error, "#{options_file} is not a valid rdoc options file" unless
      RDoc::Options === options or Hash === options

    if Hash === options
      # Override the default values with the contents of YAML file.
      options = RDoc::Options.new options
    end

    options
  end

  ##
  # Create an output dir if it doesn't exist. If it does exist, but doesn't
  # contain the flag file <tt>created.rid</tt> then we refuse to use it, as
  # we may clobber some manually generated documentation

  def setup_output_dir(dir, force)
    flag_file = output_flag_file dir

    last = {}

    if @options.dry_run then
      # do nothing
    elsif File.exist? dir then
      error "#{dir} exists and is not a directory" unless File.directory? dir

      begin
        File.open flag_file do |io|
          unless force then
            Time.parse io.gets

            io.each do |line|
              file, time = line.split "\t", 2
              time = Time.parse(time) rescue next
              last[file] = time
            end
          end
        end
      rescue SystemCallError, TypeError
        error <<-ERROR

Directory #{dir} already exists, but it looks like it isn't an RDoc directory.

Because RDoc doesn't want to risk destroying any of your existing files,
you'll need to specify a different output directory name (using the --op <dir>
option)

        ERROR
      end unless @options.force_output
    else
      FileUtils.mkdir_p dir
      FileUtils.touch flag_file
    end

    last
  end

  ##
  # Sets the current documentation tree to +store+ and sets the store's rdoc
  # driver to this instance.

  def store= store
    @store = store
    @store.rdoc = self
  end

  ##
  # Update the flag file in an output directory.

  def update_output_dir(op_dir, time, last = {})
    return if @options.dry_run or not @options.update_output_dir
    unless ENV['SOURCE_DATE_EPOCH'].nil?
      time = Time.at(ENV['SOURCE_DATE_EPOCH'].to_i).gmtime
    end

    File.open output_flag_file(op_dir), "w" do |f|
      f.puts time.rfc2822
      last.each do |n, t|
        f.puts "#{n}\t#{t.rfc2822}"
      end
    end
  end

  ##
  # Return the path name of the flag file in an output directory.

  def output_flag_file(op_dir)
    File.join op_dir, "created.rid"
  end

  ##
  # The .document file contains a list of file and directory name patterns,
  # representing candidates for documentation. It may also contain comments
  # (starting with '#')

  def parse_dot_doc_file in_dir, filename
    # read and strip comments
    patterns = File.read(filename).gsub(/#.*/, '')

    result = {}

    patterns.split(' ').each do |patt|
      candidates = Dir.glob(File.join(in_dir, patt))
      result.update normalized_file_list(candidates, false, @options.exclude)
    end

    result
  end

  ##
  # Given a list of files and directories, create a list of all the Ruby
  # files they contain.
  #
  # If +force_doc+ is true we always add the given files, if false, only
  # add files that we guarantee we can parse.  It is true when looking at
  # files given on the command line, false when recursing through
  # subdirectories.
  #
  # The effect of this is that if you want a file with a non-standard
  # extension parsed, you must name it explicitly.

  def normalized_file_list(relative_files, force_doc = false,
                           exclude_pattern = nil)
    file_list = {}

    relative_files.each do |rel_file_name|
      rel_file_name = rel_file_name.sub(/^\.\//, '')
      next if rel_file_name.end_with? 'created.rid'
      next if exclude_pattern && exclude_pattern =~ rel_file_name
      stat = File.stat rel_file_name rescue next

      case type = stat.ftype
      when "file" then
        mtime = (stat.mtime unless (last_modified = @last_modified[rel_file_name] and
                                    stat.mtime.to_i <= last_modified.to_i))

        if force_doc or RDoc::Parser.can_parse(rel_file_name) then
          file_list[rel_file_name] = mtime
        end
      when "directory" then
        next if rel_file_name == "CVS" || rel_file_name == ".svn"

        created_rid = File.join rel_file_name, "created.rid"
        next if File.file? created_rid

        dot_doc = File.join rel_file_name, RDoc::DOT_DOC_FILENAME

        if File.file? dot_doc then
          file_list.update(parse_dot_doc_file(rel_file_name, dot_doc))
        else
          file_list.update(list_files_in_directory(rel_file_name))
        end
      else
        warn "rdoc can't parse the #{type} #{rel_file_name}"
      end
    end

    file_list
  end

  ##
  # Return a list of the files to be processed in a directory. We know that
  # this directory doesn't have a .document file, so we're looking for real
  # files. However we may well contain subdirectories which must be tested
  # for .document files.

  def list_files_in_directory dir
    files = Dir.glob File.join(dir, "*")

    normalized_file_list files, false, @options.exclude
  end

  ##
  # Parses +filename+ and returns an RDoc::TopLevel

  def parse_file filename
    encoding = @options.encoding
    filename = filename.encode encoding

    @stats.add_file filename

    return if RDoc::Parser.binary? filename

    content = RDoc::Encoding.read_file filename, encoding

    return unless content

    filename_path = Pathname(filename).expand_path
    begin
      relative_path = filename_path.relative_path_from @options.root
    rescue ArgumentError
      relative_path = filename_path
    end

    if @options.page_dir and
       relative_path.to_s.start_with? @options.page_dir.to_s then
      relative_path =
        relative_path.relative_path_from @options.page_dir
    end

    top_level = @store.add_file filename, relative_name: relative_path.to_s

    parser = RDoc::Parser.for top_level, filename, content, @options, @stats

    return unless parser

    parser.scan

    # restart documentation for the classes & modules found
    top_level.classes_or_modules.each do |cm|
      cm.done_documenting = false
    end

    top_level

  rescue Errno::EACCES => e
    $stderr.puts <<-EOF
Unable to read #{filename}, #{e.message}

Please check the permissions for this file.  Perhaps you do not have access to
it or perhaps the original author's permissions are to restrictive.  If the
this is not your library please report a bug to the author.
    EOF
  rescue => e
    $stderr.puts <<-EOF
Before reporting this, could you check that the file you're documenting
has proper syntax:

  #{Gem.ruby} -c #{filename}

RDoc is not a full Ruby parser and will fail when fed invalid ruby programs.

The internal error was:

\t(#{e.class}) #{e.message}

    EOF

    $stderr.puts e.backtrace.join("\n\t") if $DEBUG_RDOC

    raise e
    nil
  end

  ##
  # Parse each file on the command line, recursively entering directories.

  def parse_files files
    file_list = gather_files files
    @stats = RDoc::Stats.new @store, file_list.length, @options.verbosity

    return [] if file_list.empty?

    original_options = @options.dup
    @stats.begin_adding

    file_info = file_list.map do |filename|
      @current = filename
      parse_file filename
    end.compact

    @stats.done_adding
    @options = original_options

    file_info
  end

  ##
  # Removes file extensions known to be unparseable from +files+ and TAGS
  # files for emacs and vim.

  def remove_unparseable files
    files.reject do |file, *|
      file =~ /\.(?:class|eps|erb|scpt\.txt|svg|ttf|yml)$/i or
        (file =~ /tags$/i and
         File.open(file, 'rb') { |io|
           io.read(100) =~ /\A(\f\n[^,]+,\d+$|!_TAG_)/
         })
    end
  end

  ##
  # Generates documentation or a coverage report depending upon the settings
  # in +options+.
  #
  # +options+ can be either an RDoc::Options instance or an array of strings
  # equivalent to the strings that would be passed on the command line like
  # <tt>%w[-q -o doc -t My\ Doc\ Title]</tt>.  #document will automatically
  # call RDoc::Options#finish if an options instance was given.
  #
  # For a list of options, see either RDoc::Options or <tt>rdoc --help</tt>.
  #
  # By default, output will be stored in a directory called "doc" below the
  # current directory, so make sure you're somewhere writable before invoking.

  def document options
    self.store = RDoc::Store.new

    if RDoc::Options === options then
      @options = options
      @options.finish
    else
      @options = load_options
      @options.parse options
    end

    if @options.pipe then
      handle_pipe
      exit
    end

    unless @options.coverage_report then
      @last_modified = setup_output_dir @options.op_dir, @options.force_update
    end

    @store.encoding = @options.encoding
    @store.dry_run  = @options.dry_run
    @store.main     = @options.main_page
    @store.title    = @options.title
    @store.path     = @options.op_dir

    @start_time = Time.now

    @store.load_cache

    file_info = parse_files @options.files

    @options.default_title = "RDoc Documentation"

    @store.complete @options.visibility

    @stats.coverage_level = @options.coverage_report

    if @options.coverage_report then
      puts

      puts @stats.report.accept RDoc::Markup::ToRdoc.new
    elsif file_info.empty? then
      $stderr.puts "\nNo newer files." unless @options.quiet
    else
      gen_klass = @options.generator

      @generator = gen_klass.new @store, @options

      generate
    end

    if @stats and (@options.coverage_report or not @options.quiet) then
      puts
      puts @stats.summary.accept RDoc::Markup::ToRdoc.new
    end

    exit @stats.fully_documented? if @options.coverage_report
  end

  ##
  # Generates documentation for +file_info+ (from #parse_files) into the
  # output dir using the generator selected
  # by the RDoc options

  def generate
    if @options.dry_run then
      # do nothing
      @generator.generate
    else
      Dir.chdir @options.op_dir do
        unless @options.quiet then
          $stderr.puts "\nGenerating #{@generator.class.name.sub(/^.*::/, '')} format into #{Dir.pwd}..."
        end

        @generator.generate
        update_output_dir '.', @start_time, @last_modified
      end
    end
  end

  ##
  # Removes a siginfo handler and replaces the previous

  def remove_siginfo_handler
    return unless Signal.list.key? 'INFO'

    handler = @old_siginfo || 'DEFAULT'

    trap 'INFO', handler
  end

end

begin
  require 'rubygems'

  rdoc_extensions = Gem.find_files 'rdoc/discover'

  rdoc_extensions.each do |extension|
    begin
      load extension
    rescue => e
      warn "error loading #{extension.inspect}: #{e.message} (#{e.class})"
      warn "\t#{e.backtrace.join "\n\t"}" if $DEBUG
    end
  end
rescue LoadError
end

# require built-in generators after discovery in case they've been replaced
require_relative 'generator/darkfish'
require_relative 'generator/ri'
require_relative 'generator/pot'
# -*- coding: us-ascii -*-
# frozen_string_literal: true

##
# A parser is simple a class that subclasses RDoc::Parser and implements #scan
# to fill in an RDoc::TopLevel with parsed data.
#
# The initialize method takes an RDoc::TopLevel to fill with parsed content,
# the name of the file to be parsed, the content of the file, an RDoc::Options
# object and an RDoc::Stats object to inform the user of parsed items.  The
# scan method is then called to parse the file and must return the
# RDoc::TopLevel object.  By calling super these items will be set for you.
#
# In order to be used by RDoc the parser needs to register the file extensions
# it can parse.  Use ::parse_files_matching to register extensions.
#
#   require 'rdoc'
#
#   class RDoc::Parser::Xyz < RDoc::Parser
#     parse_files_matching /\.xyz$/
#
#     def initialize top_level, file_name, content, options, stats
#       super
#
#       # extra initialization if needed
#     end
#
#     def scan
#       # parse file and fill in @top_level
#     end
#   end

class RDoc::Parser

  @parsers = []

  class << self

    ##
    # An Array of arrays that maps file extension (or name) regular
    # expressions to parser classes that will parse matching filenames.
    #
    # Use parse_files_matching to register a parser's file extensions.

    attr_reader :parsers

  end

  ##
  # The name of the file being parsed

  attr_reader :file_name

  ##
  # Alias an extension to another extension. After this call, files ending
  # "new_ext" will be parsed using the same parser as "old_ext"

  def self.alias_extension(old_ext, new_ext)
    old_ext = old_ext.sub(/^\.(.*)/, '\1')
    new_ext = new_ext.sub(/^\.(.*)/, '\1')

    parser = can_parse_by_name "xxx.#{old_ext}"
    return false unless parser

    RDoc::Parser.parsers.unshift [/\.#{new_ext}$/, parser]

    true
  end

  ##
  # Determines if the file is a "binary" file which basically means it has
  # content that an RDoc parser shouldn't try to consume.

  def self.binary?(file)
    return false if file =~ /\.(rdoc|txt)$/

    s = File.read(file, 1024) or return false

    return true if s[0, 2] == Marshal.dump('')[0, 2] or s.index("\x00")

    mode = 'r:utf-8' # default source encoding has been changed to utf-8
    s.sub!(/\A#!.*\n/, '')     # assume shebang line isn't longer than 1024.
    encoding = s[/^\s*\#\s*(?:-\*-\s*)?(?:en)?coding:\s*([^\s;]+?)(?:-\*-|[\s;])/, 1]
    mode = "rb:#{encoding}" if encoding
    s = File.open(file, mode) {|f| f.gets(nil, 1024)}

    not s.valid_encoding?
  end

  ##
  # Checks if +file+ is a zip file in disguise.  Signatures from
  # http://www.garykessler.net/library/file_sigs.html

  def self.zip? file
    zip_signature = File.read file, 4

    zip_signature == "PK\x03\x04" or
      zip_signature == "PK\x05\x06" or
      zip_signature == "PK\x07\x08"
  rescue
    false
  end

  ##
  # Return a parser that can handle a particular extension

  def self.can_parse file_name
    parser = can_parse_by_name file_name

    # HACK Selenium hides a jar file using a .txt extension
    return if parser == RDoc::Parser::Simple and zip? file_name

    parser
  end

  ##
  # Returns a parser that can handle the extension for +file_name+.  This does
  # not depend upon the file being readable.

  def self.can_parse_by_name file_name
    _, parser = RDoc::Parser.parsers.find { |regexp,| regexp =~ file_name }

    # The default parser must not parse binary files
    ext_name = File.extname file_name
    return parser if ext_name.empty?

    if parser == RDoc::Parser::Simple and ext_name !~ /txt|rdoc/ then
      case check_modeline file_name
      when nil, 'rdoc' then # continue
      else return nil
      end
    end

    parser
  rescue Errno::EACCES
  end

  ##
  # Returns the file type from the modeline in +file_name+

  def self.check_modeline file_name
    line = File.open file_name do |io|
      io.gets
    end

    /-\*-\s*(.*?\S)\s*-\*-/ =~ line

    return nil unless type = $1

    if /;/ =~ type then
      return nil unless /(?:\s|\A)mode:\s*([^\s;]+)/i =~ type
      type = $1
    end

    return nil if /coding:/i =~ type

    type.downcase
  rescue ArgumentError
  rescue Encoding::InvalidByteSequenceError # invalid byte sequence

  end

  ##
  # Finds and instantiates the correct parser for the given +file_name+ and
  # +content+.

  def self.for top_level, file_name, content, options, stats
    return if binary? file_name

    parser = use_markup content

    unless parser then
      parse_name = file_name

      # If no extension, look for shebang
      if file_name !~ /\.\w+$/ && content =~ %r{\A#!(.+)} then
        shebang = $1
        case shebang
        when %r{env\s+ruby}, %r{/ruby}
          parse_name = 'dummy.rb'
        end
      end

      parser = can_parse parse_name
    end

    return unless parser

    content = remove_modeline content

    parser.new top_level, file_name, content, options, stats
  rescue SystemCallError
    nil
  end

  ##
  # Record which file types this parser can understand.
  #
  # It is ok to call this multiple times.

  def self.parse_files_matching(regexp)
    RDoc::Parser.parsers.unshift [regexp, self]
  end

  ##
  # Removes an emacs-style modeline from the first line of the document

  def self.remove_modeline content
    content.sub(/\A.*-\*-\s*(.*?\S)\s*-\*-.*\r?\n/, '')
  end

  ##
  # If there is a <tt>markup: parser_name</tt> comment at the front of the
  # file, use it to determine the parser.  For example:
  #
  #   # markup: rdoc
  #   # Class comment can go here
  #
  #   class C
  #   end
  #
  # The comment should appear as the first line of the +content+.
  #
  # If the content contains a shebang or editor modeline the comment may
  # appear on the second or third line.
  #
  # Any comment style may be used to hide the markup comment.

  def self.use_markup content
    markup = content.lines.first(3).grep(/markup:\s+(\w+)/) { $1 }.first

    return unless markup

    # TODO Ruby should be returned only when the filename is correct
    return RDoc::Parser::Ruby if %w[tomdoc markdown].include? markup

    markup = Regexp.escape markup

    _, selected = RDoc::Parser.parsers.find do |_, parser|
      /^#{markup}$/i =~ parser.name.sub(/.*:/, '')
    end

    selected
  end

  ##
  # Creates a new Parser storing +top_level+, +file_name+, +content+,
  # +options+ and +stats+ in instance variables.  In +@preprocess+ an
  # RDoc::Markup::PreProcess object is created which allows processing of
  # directives.

  def initialize top_level, file_name, content, options, stats
    @top_level = top_level
    @top_level.parser = self.class
    @store = @top_level.store

    @file_name = file_name
    @content = content
    @options = options
    @stats = stats

    @preprocess = RDoc::Markup::PreProcess.new @file_name, @options.rdoc_include
    @preprocess.options = @options
  end

  autoload :RubyTools, 'rdoc/parser/ruby_tools'
  autoload :Text,      'rdoc/parser/text'

end

# simple must come first in order to show up last in the parsers list
require_relative 'parser/simple'
require_relative 'parser/c'
require_relative 'parser/changelog'
require_relative 'parser/markdown'
require_relative 'parser/rd'
require_relative 'parser/ruby'
# 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

# 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 <tt>+=</tt>.

  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 <tt>parent.modules_hash</tt> or
  # <tt>parent.classes_hash</tt> 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 <tt>RDoc::ClassModule#is_alias_for</tt> set to
  # the aliased module/class, and this copy is added to <tt>#aliases</tt>
  # 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

# frozen_string_literal: true
##
# Abstract class representing either a method or an attribute.

class RDoc::MethodAttr < RDoc::CodeObject

  include Comparable

  ##
  # Name of this method/attribute.

  attr_accessor :name

  ##
  # public, protected, private

  attr_accessor :visibility

  ##
  # Is this a singleton method/attribute?

  attr_accessor :singleton

  ##
  # Source file token stream

  attr_reader :text

  ##
  # Array of other names for this method/attribute

  attr_reader :aliases

  ##
  # The method/attribute we're aliasing

  attr_accessor :is_alias_for

  #--
  # The attributes below are for AnyMethod only.
  # They are left here for the time being to
  # allow ri to operate.
  # TODO modify ri to avoid calling these on attributes.
  #++

  ##
  # Parameters yielded by the called block

  attr_reader :block_params

  ##
  # Parameters for this method

  attr_accessor :params

  ##
  # Different ways to call this method

  attr_accessor :call_seq

  ##
  # The call_seq or the param_seq with method name, if there is no call_seq.

  attr_reader :arglists

  ##
  # Pretty parameter list for this method

  attr_reader :param_seq


  ##
  # Creates a new MethodAttr from token stream +text+ and method or attribute
  # name +name+.
  #
  # Usually this is called by super from a subclass.

  def initialize text, name
    super()

    @text = text
    @name = name

    @aliases      = []
    @is_alias_for = nil
    @parent_name  = nil
    @singleton    = nil
    @visibility   = :public
    @see = false

    @arglists     = nil
    @block_params = nil
    @call_seq     = nil
    @param_seq    = nil
    @params       = nil
  end

  ##
  # Resets cached data for the object so it can be rebuilt by accessor methods

  def initialize_copy other # :nodoc:
    @full_name = nil
  end

  def initialize_visibility # :nodoc:
    super
    @see = nil
  end

  ##
  # Order by #singleton then #name

  def <=>(other)
    return unless other.respond_to?(:singleton) &&
                  other.respond_to?(:name)

    [     @singleton ? 0 : 1,       name] <=>
    [other.singleton ? 0 : 1, other.name]
  end

  def == other # :nodoc:
    equal?(other) or self.class == other.class and full_name == other.full_name
  end

  ##
  # A method/attribute is documented if any of the following is true:
  # - it was marked with :nodoc:;
  # - it has a comment;
  # - it is an alias for a documented method;
  # - it has a +#see+ method that is documented.

  def documented?
    super or
      (is_alias_for and is_alias_for.documented?) or
      (see and see.documented?)
  end

  ##
  # A method/attribute to look at,
  # in particular if this method/attribute has no documentation.
  #
  # It can be a method/attribute of the superclass or of an included module,
  # including the Kernel module, which is always appended to the included
  # modules.
  #
  # Returns +nil+ if there is no such method/attribute.
  # The +#is_alias_for+ method/attribute, if any, is not included.
  #
  # Templates may generate a "see also ..." if this method/attribute
  # has documentation, and "see ..." if it does not.

  def see
    @see = find_see if @see == false
    @see
  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 find_see # :nodoc:
    return nil if singleton || is_alias_for

    # look for the method
    other = find_method_or_attribute name
    return other if other

    # if it is a setter, look for a getter
    return nil unless name =~ /[a-z_]=$/i   # avoid == or ===
    return find_method_or_attribute name[0..-2]
  end

  def find_method_or_attribute name # :nodoc:
    return nil unless parent.respond_to? :ancestors

    searched = parent.ancestors
    kernel = @store.modules_hash['Kernel']

    searched << kernel if kernel &&
      parent != kernel && !searched.include?(kernel)

    searched.each do |ancestor|
      next if String === ancestor
      next if parent == ancestor

      other = ancestor.find_method_named('#' + name) ||
              ancestor.find_attribute_named(name)

      return other if other
    end

    nil
  end

  ##
  # Abstract method. Contexts in their building phase call this
  # to register a new alias for this known method/attribute.
  #
  # - creates a new AnyMethod/Attribute named <tt>an_alias.new_name</tt>;
  # - adds +self+ as an alias for the new method or attribute
  # - adds the method or attribute to #aliases
  # - adds the method or attribute to +context+.

  def add_alias(an_alias, context)
    raise NotImplementedError
  end

  ##
  # HTML fragment reference for this method

  def aref
    type = singleton ? 'c' : 'i'
    # % characters are not allowed in html names => dash instead
    "#{aref_prefix}-#{type}-#{html_name}"
  end

  ##
  # Prefix for +aref+, defined by subclasses.

  def aref_prefix
    raise NotImplementedError
  end

  ##
  # Attempts to sanitize the content passed by the Ruby parser:
  # remove outer parentheses, etc.

  def block_params=(value)
    # 'yield.to_s' or 'assert yield, msg'
    return @block_params = '' if value =~ /^[\.,]/

    # remove trailing 'if/unless ...'
    return @block_params = '' if value =~ /^(if|unless)\s/

    value = $1.strip if value =~ /^(.+)\s(if|unless)\s/

    # outer parentheses
    value = $1 if value =~ /^\s*\((.*)\)\s*$/
    value = value.strip

    # proc/lambda
    return @block_params = $1 if value =~ /^(proc|lambda)(\s*\{|\sdo)/

    # surrounding +...+ or [...]
    value = $1.strip if value =~ /^\+(.*)\+$/
    value = $1.strip if value =~ /^\[(.*)\]$/

    return @block_params = '' if value.empty?

    # global variable
    return @block_params = 'str' if value =~ /^\$[&0-9]$/

    # wipe out array/hash indices
    value.gsub!(/(\w)\[[^\[]+\]/, '\1')

    # remove @ from class/instance variables
    value.gsub!(/@@?([a-z0-9_]+)/, '\1')

    # method calls => method name
    value.gsub!(/([A-Z:a-z0-9_]+)\.([a-z0-9_]+)(\s*\(\s*[a-z0-9_.,\s]*\s*\)\s*)?/) do
      case $2
      when 'to_s'      then $1
      when 'const_get' then 'const'
      when 'new' then
        $1.split('::').last.  # ClassName => class_name
          gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
          gsub(/([a-z\d])([A-Z])/,'\1_\2').
          downcase
      else
        $2
      end
    end

    # class prefixes
    value.gsub!(/[A-Za-z0-9_:]+::/, '')

    # simple expressions
    value = $1 if value =~ /^([a-z0-9_]+)\s*[-*+\/]/

    @block_params = value.strip
  end

  ##
  # HTML id-friendly method/attribute name

  def html_name
    require 'cgi'

    CGI.escape(@name.gsub('-', '-2D')).gsub('%','-').sub(/^-/, '')
  end

  ##
  # Full method/attribute name including namespace

  def full_name
    @full_name ||= "#{parent_name}#{pretty_name}"
  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>" % [
      self.class, object_id,
      full_name,
      visibility,
      alias_for,
    ]
  end

  ##
  # '::' for a class method/attribute, '#' for an instance method.

  def name_prefix
    @singleton ? '::' : '#'
  end

  ##
  # Name for output to HTML.  For class methods the full name with a "." is
  # used like +SomeClass.method_name+.  For instance methods the class name is
  # used if +context+ does not match the parent.
  #
  # This is to help prevent people from using :: to call class methods.

  def output_name context
    return "#{name_prefix}#{@name}" if context == parent

    "#{parent_name}#{@singleton ? '.' : '#'}#{@name}"
  end

  ##
  # Method/attribute name with class/instance indicator

  def pretty_name
    "#{name_prefix}#{@name}"
  end

  ##
  # Type of method/attribute (class or instance)

  def type
    singleton ? 'class' : 'instance'
  end

  ##
  # Path to this method for use with HTML generator output.

  def path
    "#{@parent.path}##{aref}"
  end

  ##
  # Name of our parent with special handling for un-marshaled methods

  def parent_name
    @parent_name || super
  end

  def pretty_print q # :nodoc:
    alias_for =
      if @is_alias_for.respond_to? :name then
        "alias for #{@is_alias_for.name}"
      elsif Array === @is_alias_for then
        "alias for #{@is_alias_for.last}"
      end

    q.group 2, "[#{self.class.name} #{full_name} #{visibility}", "]" do
      if alias_for then
        q.breakable
        q.text alias_for
      end

      if text then
        q.breakable
        q.text "text:"
        q.breakable
        q.pp @text
      end

      unless comment.empty? then
        q.breakable
        q.text "comment:"
        q.breakable
        q.pp @comment
      end
    end
  end

  ##
  # Used by RDoc::Generator::JsonIndex to create a record for the search
  # engine.

  def search_record
    [
      @name,
      full_name,
      @name,
      @parent.full_name,
      path,
      params,
      snippet(@comment),
    ]
  end

  def to_s # :nodoc:
    if @is_alias_for
      "#{self.class.name}: #{full_name} -> #{is_alias_for}"
    else
      "#{self.class.name}: #{full_name}"
    end
  end

end

Searcher = function(data) {
  this.data = data;
  this.handlers = [];
}

Searcher.prototype = new function() {
  // search is performed in chunks of 1000 for non-blocking user input
  var CHUNK_SIZE = 1000;
  // do not try to find more than 100 results
  var MAX_RESULTS = 100;
  var huid = 1;
  var suid = 1;
  var runs = 0;

  this.find = function(query) {
    var queries = splitQuery(query);
    var regexps = buildRegexps(queries);
    var highlighters = buildHilighters(queries);
    var state = { from: 0, pass: 0, limit: MAX_RESULTS, n: suid++};
    var _this = this;

    this.currentSuid = state.n;

    if (!query) return;

    var run = function() {
      // stop current search thread if new search started
      if (state.n != _this.currentSuid) return;

      var results =
        performSearch(_this.data, regexps, queries, highlighters, state);
      var hasMore = (state.limit > 0 && state.pass < 4);

      triggerResults.call(_this, results, !hasMore);
      if (hasMore) {
        setTimeout(run, 2);
      }
      runs++;
    };
    runs = 0;

    // start search thread
    run();
  }

  /*  ----- Events ------  */
  this.ready = function(fn) {
    fn.huid = huid;
    this.handlers.push(fn);
  }

  /*  ----- Utilities ------  */
  function splitQuery(query) {
    return query.split(/(\s+|::?|\(\)?)/).filter(function(string) {
      return string.match(/\S/);
    });
  }

  function buildRegexps(queries) {
    return queries.map(function(query) {
      return new RegExp(query.replace(/(.)/g, '([$1])([^$1]*?)'), 'i');
    });
  }

  function buildHilighters(queries) {
    return queries.map(function(query) {
      return query.split('').map(function(l, i) {
        return '\u0001$' + (i*2+1) + '\u0002$' + (i*2+2);
      }).join('');
    });
  }

  // function longMatchRegexp(index, longIndex, regexps) {
  //     for (var i = regexps.length - 1; i >= 0; i--){
  //         if (!index.match(regexps[i]) && !longIndex.match(regexps[i])) return false;
  //     };
  //     return true;
  // }


  /*  ----- Mathchers ------  */

  /*
   * This record matches if the index starts with queries[0] and the record
   * matches all of the regexps
   */
  function matchPassBeginning(index, longIndex, queries, regexps) {
    if (index.indexOf(queries[0]) != 0) return false;
    for (var i=1, l = regexps.length; i < l; i++) {
      if (!index.match(regexps[i]) && !longIndex.match(regexps[i]))
        return false;
    };
    return true;
  }

  /*
   * This record matches if the longIndex starts with queries[0] and the
   * longIndex matches all of the regexps
   */
  function matchPassLongIndex(index, longIndex, queries, regexps) {
    if (longIndex.indexOf(queries[0]) != 0) return false;
    for (var i=1, l = regexps.length; i < l; i++) {
      if (!longIndex.match(regexps[i]))
        return false;
    };
    return true;
  }

  /*
   * This record matches if the index contains queries[0] and the record
   * matches all of the regexps
   */
  function matchPassContains(index, longIndex, queries, regexps) {
    if (index.indexOf(queries[0]) == -1) return false;
    for (var i=1, l = regexps.length; i < l; i++) {
      if (!index.match(regexps[i]) && !longIndex.match(regexps[i]))
        return false;
    };
    return true;
  }

  /*
   * This record matches if regexps[0] matches the index and the record
   * matches all of the regexps
   */
  function matchPassRegexp(index, longIndex, queries, regexps) {
    if (!index.match(regexps[0])) return false;
    for (var i=1, l = regexps.length; i < l; i++) {
      if (!index.match(regexps[i]) && !longIndex.match(regexps[i]))
        return false;
    };
    return true;
  }


  /*  ----- Highlighters ------  */
  function highlightRegexp(info, queries, regexps, highlighters) {
    var result = createResult(info);
    for (var i=0, l = regexps.length; i < l; i++) {
      result.title = result.title.replace(regexps[i], highlighters[i]);
      result.namespace = result.namespace.replace(regexps[i], highlighters[i]);
    };
    return result;
  }

  function hltSubstring(string, pos, length) {
    return string.substring(0, pos) + '\u0001' + string.substring(pos, pos + length) + '\u0002' + string.substring(pos + length);
  }

  function highlightQuery(info, queries, regexps, highlighters) {
    var result = createResult(info);
    var pos = 0;
    var lcTitle = result.title.toLowerCase();

    pos = lcTitle.indexOf(queries[0]);
    if (pos != -1) {
      result.title = hltSubstring(result.title, pos, queries[0].length);
    }

    result.namespace = result.namespace.replace(regexps[0], highlighters[0]);
    for (var i=1, l = regexps.length; i < l; i++) {
      result.title = result.title.replace(regexps[i], highlighters[i]);
      result.namespace = result.namespace.replace(regexps[i], highlighters[i]);
    };
    return result;
  }

  function createResult(info) {
    var result = {};
    result.title = info[0];
    result.namespace = info[1];
    result.path = info[2];
    result.params = info[3];
    result.snippet = info[4];
    result.badge = info[6];
    return result;
  }

  /*  ----- Searching ------  */
  function performSearch(data, regexps, queries, highlighters, state) {
    var searchIndex = data.searchIndex;
    var longSearchIndex = data.longSearchIndex;
    var info = data.info;
    var result = [];
    var i = state.from;
    var l = searchIndex.length;
    var togo = CHUNK_SIZE;
    var matchFunc, hltFunc;

    while (state.pass < 4 && state.limit > 0 && togo > 0) {
      if (state.pass == 0) {
        matchFunc = matchPassBeginning;
        hltFunc = highlightQuery;
      } else if (state.pass == 1) {
        matchFunc = matchPassLongIndex;
        hltFunc = highlightQuery;
      } else if (state.pass == 2) {
        matchFunc = matchPassContains;
        hltFunc = highlightQuery;
      } else if (state.pass == 3) {
        matchFunc = matchPassRegexp;
        hltFunc = highlightRegexp;
      }

      for (; togo > 0 && i < l && state.limit > 0; i++, togo--) {
        if (info[i].n == state.n) continue;
        if (matchFunc(searchIndex[i], longSearchIndex[i], queries, regexps)) {
          info[i].n = state.n;
          result.push(hltFunc(info[i], queries, regexps, highlighters));
          state.limit--;
        }
      };
      if (searchIndex.length <= i) {
        state.pass++;
        i = state.from = 0;
      } else {
        state.from = i;
      }
    }
    return result;
  }

  function triggerResults(results, isLast) {
    this.handlers.forEach(function(fn) {
      fn.call(this, results, isLast)
    });
  }
}

/*
 * Navigation allows movement using the arrow keys through the search results.
 *
 * When using this library you will need to set scrollIntoView to the
 * appropriate function for your layout.  Use scrollInWindow if the container
 * is not scrollable and scrollInElement if the container is a separate
 * scrolling region.
 */
Navigation = new function() {
  this.initNavigation = function() {
    var _this = this;

    document.addEventListener('keydown', function(e) {
      _this.onkeydown(e);
    });

    this.navigationActive = true;
  }

  this.setNavigationActive = function(state) {
    this.navigationActive = state;
  }

  this.onkeydown = function(e) {
    if (!this.navigationActive) return;
    switch(e.keyCode) {
      case 37: //Event.KEY_LEFT:
        if (this.moveLeft()) e.preventDefault();
        break;
      case 38: //Event.KEY_UP:
        if (e.keyCode == 38 || e.ctrlKey) {
          if (this.moveUp()) e.preventDefault();
        }
        break;
      case 39: //Event.KEY_RIGHT:
        if (this.moveRight()) e.preventDefault();
        break;
      case 40: //Event.KEY_DOWN:
        if (e.keyCode == 40 || e.ctrlKey) {
          if (this.moveDown()) e.preventDefault();
        }
        break;
      case 13: //Event.KEY_RETURN:
        if (this.current) e.preventDefault();
        this.select(this.current);
        break;
    }
    if (e.ctrlKey && e.shiftKey) this.select(this.current);
  }

  this.moveRight = function() {
  }

  this.moveLeft = function() {
  }

  this.move = function(isDown) {
  }

  this.moveUp = function() {
    return this.move(false);
  }

  this.moveDown = function() {
    return this.move(true);
  }

  /*
   * Scrolls to the given element in the scrollable element view.
   */
  this.scrollInElement = function(element, view) {
    var offset, viewHeight, viewScroll, height;
    offset = element.offsetTop;
    height = element.offsetHeight;
    viewHeight = view.offsetHeight;
    viewScroll = view.scrollTop;

    if (offset - viewScroll + height > viewHeight) {
      view.scrollTop = offset - viewHeight + height;
    }
    if (offset < viewScroll) {
      view.scrollTop = offset;
    }
  }

  /*
   * Scrolls to the given element in the window.  The second argument is
   * ignored
   */
  this.scrollInWindow = function(element, ignored) {
    var offset, viewHeight, viewScroll, height;
    offset = element.offsetTop;
    height = element.offsetHeight;
    viewHeight = window.innerHeight;
    viewScroll = window.scrollY;

    if (offset - viewScroll + height > viewHeight) {
      window.scrollTo(window.scrollX, offset - viewHeight + height);
    }
    if (offset < viewScroll) {
      window.scrollTo(window.scrollX, offset);
    }
  }
}

/**
 *
 * Darkfish Page Functions
 * $Id: darkfish.js 53 2009-01-07 02:52:03Z deveiant $
 *
 * Author: Michael Granger <mgranger@laika.com>
 *
 */

/* 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 <script> per-page
    html += '<p class="search-match"><a href="' + index_rel_prefix + result.path + '">' + this.hlt(result.title);
    if (result.params)
      html += '<span class="params">' + result.params + '</span>';
    html += '</a>';


    if (result.namespace)
      html += '<p class="search-namespace">' + this.hlt(result.namespace);

    if (result.snippet)
      html += '<div class="search-snippet">' + result.snippet + '</div>';

    li.innerHTML = html;

    return li;
  }

  search.select = function(result) {
    window.location.href = result.firstChild.firstChild.href;
  }

  search.scrollIntoView = search.scrollInWindow;
};

document.addEventListener('DOMContentLoaded', function() {
  hookSourceViews();
  hookSearch();
});
Search = function(data, input, result) {
  this.data = data;
  this.input = input;
  this.result = result;

  this.current = null;
  this.view = this.result.parentNode;
  this.searcher = new Searcher(data.index);
  this.init();
}

Search.prototype = Object.assign({}, Navigation, new function() {
  var suid = 1;

  this.init = function() {
    var _this = this;
    var observer = function(e) {
      switch(e.keyCode) {
        case 38: // Event.KEY_UP
        case 40: // Event.KEY_DOWN
          return;
      }
      _this.search(_this.input.value);
    };
    this.input.addEventListener('keyup', observer);
    this.input.addEventListener('click', observer); // mac's clear field

    this.searcher.ready(function(results, isLast) {
      _this.addResults(results, isLast);
    })

    this.initNavigation();
    this.setNavigationActive(false);
  }

  this.search = function(value, selectFirstMatch) {
    value = value.trim().toLowerCase();
    if (value) {
      this.setNavigationActive(true);
    } else {
      this.setNavigationActive(false);
    }

    if (value == '') {
      this.lastQuery = value;
      this.result.innerHTML = '';
      this.result.setAttribute('aria-expanded', 'false');
      this.setNavigationActive(false);
    } else if (value != this.lastQuery) {
      this.lastQuery = value;
      this.result.setAttribute('aria-busy',     'true');
      this.result.setAttribute('aria-expanded', 'true');
      this.firstRun = true;
      this.searcher.find(value);
    }
  }

  this.addResults = function(results, isLast) {
    var target = this.result;
    if (this.firstRun && (results.length > 0 || isLast)) {
      this.current = null;
      this.result.innerHTML = '';
    }

    for (var i=0, l = results.length; i < l; i++) {
      var item = this.renderItem.call(this, results[i]);
      item.setAttribute('id', 'search-result-' + target.childElementCount);
      target.appendChild(item);
    };

    if (this.firstRun && results.length > 0) {
      this.firstRun = false;
      this.current = target.firstChild;
      this.current.classList.add('search-selected');
    }
    //TODO: ECMAScript
    //if (jQuery.browser.msie) this.$element[0].className += '';

    if (isLast) this.result.setAttribute('aria-busy', 'false');
  }

  this.move = function(isDown) {
    if (!this.current) return;
    var next = isDown ? this.current.nextElementSibling : this.current.previousElementSibling;
    if (next) {
      this.current.classList.remove('search-selected');
      next.classList.add('search-selected');
      this.input.setAttribute('aria-activedescendant', next.getAttribute('id'));
      this.scrollIntoView(next, this.view);
      this.current = next;
      this.input.value = next.firstChild.firstChild.text;
      this.input.select();
    }
    return true;
  }

  this.hlt = function(html) {
    return this.escapeHTML(html).
      replace(/\u0001/g, '<em>').
      replace(/\u0002/g, '</em>');
  }

  this.escapeHTML = function(html) {
    return html.replace(/[&<>]/g, function(c) {
      return '&#' + c.charCodeAt(0) + ';';
    });
  }

});

       GPOS'    HPGSUBV.T  Il  OS/28  J|   `cmapRԟ  J  cvt &6 e   8fpgmzA e  	gasp    e   glyf^  O  headd     6hhea1     $hmtx?k    TkernOQ  @  gloca) N4  ,maxp>
 P`    nameBbd P  }post:\ b   prepx9 op       
 0 J DFLT latn                 kern kern                   G    r Tv		

V8,^$^0
DJJJL F !z"##P#$4$~%x&&'()*++,J,-n. ./$/V///1242n2233V3344J4445567778~88:;";;<=2>,?&?@ABC8CDE.F( > 	[ j y j [ $[ 9 > : A < / ? > D F G H R T my oy yy }y [ [ [ [ [ [ [  /                    [      / y y j j y j y y [ > 	[ j y j [ $[ 9 > : A < / ? > D F G H R T my oy yy }y [ [ [ [ [ [ [  /                    [      / y y j j y j y y [ - # & * 2 4 D F G H R T k p                                 > 	[ j y j [ $[ 9 > : A < / ? > D F G H R T my oy yy }y [ [ [ [ [ [ [  /                    [      / y y j j y j y y [ 0 = 
= = I # & * 2 4 7A 9= :m <d ?= Y~ Z \ k l= mI oI p r= yI |= }I        d ~ ~   d I I = = = = I I I & y 	 
y y j j  $ 7G 9 ; <Q = ? ly ry |y        Q  Q    y y j y y j j  0 = 
= = I # & * 2 4 7A 9= :m <d ?= Y~ Z \ k l= mI oI p r= yI |= }I        d ~ ~   d I I = = = = I I I q  > 	 
 >  > G  G    " F # $ & * -o 2 4 D F G H P Q R S T U V X Y Z \ ] k l > m o p r > t P u P w y { P | > }                                                         >  > G  >  > G  G    $  	 
    $ 7 9 ; < = ? @ ` l r |                   : V 
V V  # & * - 2 2 4 7 8 9 : <y ? W Y Z \ k lV m o p rV t` u` y {` |V }            y     y   V V V V    
 o mo oo yo }o o o o o o $  	 
    $ 7 9 ; < = ? @ ` l r |                   > 	 L L    "  $ -. D F G H P Q R S T U X w                                      L L L   	  $          +   
     # & * 2 4 I W Y Z \ k l  m o p r  y |  }                         3  
  $ # & * 2 4 78 9V :y <= ?V Yz Z \z k l m$ o$ p r t= u= y$ {= | }$        = z z   = $ $     $ $ $ $  	 
    $ 7 9 ; < = ? @ ` l r |                   / 	 = =  $ -V D F G H R T                                = = =  $  	 
    $ 7 9 ; < = ? @ ` l r |                    # & * 2 4 7 8 k p              f 	 L L L  ] ] " - # $ & * -8 2 4 D) F) G) H) JA P] Q] R) S] T) U] VF X] YQ Zy [b \L ]e k mL oL p w] yL }L               ) ) ) ) ) ) ) ) ) ) ) ) ) ] ) ) ) ) ) ) ] ] ] ] Q Q  )  ) ) ]  ) F F e e e L L L L L L L L   	  $          q  > 	 
 >  > G  G    " F # $ & * -o 2 4 D F G H P Q R S T U V X Y Z \ ] k l > m o p r > t P u P w y { P | > }                                                         >  > G  >  > G  G    N  F 	 
 F  F      $ - D F G H J P Q R S T U V X l F r F t < u < w { < | F                                         F  F   F  F    +   
     # & * 2 4 I W Y Z \ k l  m o p r  y |  }                         m  4 	~ 
 4  4 [ V [ ~   " 2 # $~ & * -8 2 4 DG FG GG HG J_ P Q RG S TG U VG X ] k l 4 mV oV p r 4 t 2 u 2 w yV { 2 | 4 }V ~ ~ ~ ~ ~ ~ ~        G G G G G G G G G G G G G  G G G G G G     ~ G  G G   G G G    V V  4  4 [  4  4 [ V [ V V ~   "   # & * 2 4 k m o p y }               - # & * 2 4 D F G H R T k p                                 : V 
V V  # & * - 2 2 4 7 8 9 : <y ? W Y Z \ k lV m o p rV t` u` y {` |V }            y     y   V V V V      
   @ [ ` l r |       
   @ [ ` l r |       K 
 K  K y y l K r K t d u d { d | K  K  K y  K  K y y   
  Y \ l r t u { |        D F G H R T                          
  Y \ l r t u { |         
  Y \ l r t u { |         
   @ [ ` l r |       
   @ [ ` l r |     " y y D F G H R T                        y y y . 	 ~ ~  $ D F G H R T                                ~ ~ ~   	    $              D F G H R T                        . 	 y y  $ D F G H R T                                y y y  - # & * 2 4 D F G H R T k p                                 $  	 
    $ 7 9 ; < = ? @ ` l r |                   > 	[ j y j [ $[ 9 > : A < / ? > D F G H R T my oy yy }y [ [ [ [ [ [ [  /                    [      / y y j j y j y y [ & y 	 
y y j j  $ 7G 9 ; <Q = ? ly ry |y        Q  Q    y y j y y j j  & y 	 
y y j j  $ 7G 9 ; <Q = ? ly ry |y        Q  Q    y y j y y j j  $  	 
    $ 7 9 ; < = ? @ ` l r |                   > 	[ j y j [ $[ 9 > : A < / ? > D F G H R T my oy yy }y [ [ [ [ [ [ [  /                    [      / y y j j y j y y [  	e e $e 9 F : F < ( ? F e e e e e e e  ( e  ( e  	e e $e 9 F : F < ( ? F e e e e e e e  ( e  ( e & y 	 
y y j j  $ 7G 9 ; <Q = ? ly ry |y        Q  Q    y y j y y j j   	e e $e 9 F : F < ( ? F e e e e e e e  ( e  ( e > 	[ j y j [ $[ 9 > : A < / ? > D F G H R T my oy yy }y [ [ [ [ [ [ [  /                    [      / y y j j y j y y [ & y 	 
y y j j  $ 7G 9 ; <Q = ? ly ry |y        Q  Q    y y j y y j j  : V 
V V  # & * - 2 2 4 7 8 9 : <y ? W Y Z \ k lV m o p rV t` u` y {` |V }            y     y   V V V V    : V 
V V  # & * - 2 2 4 7 8 9 : <y ? W Y Z \ k lV m o p rV t` u` y {` |V }            y     y   V V V V    : V 
V V  # & * - 2 2 4 7 8 9 : <y ? W Y Z \ k lV m o p rV t` u` y {` |V }            y     y   V V V V    : V 
V V  # & * - 2 2 4 7 8 9 : <y ? W Y Z \ k lV m o p rV t` u` y {` |V }            y     y   V V V V    : V 
V V  # & * - 2 2 4 7 8 9 : <y ? W Y Z \ k lV m o p rV t` u` y {` |V }            y     y   V V V V    : V 
V V  # & * - 2 2 4 7 8 9 : <y ? W Y Z \ k lV m o p rV t` u` y {` |V }            y     y   V V V V    
 o mo oo yo }o o o o o o $  	 
    $ 7 9 ; < = ? @ ` l r |                   $  	 
    $ 7 9 ; < = ? @ ` l r |                   $  	 
    $ 7 9 ; < = ? @ ` l r |                   $  	 
    $ 7 9 ; < = ? @ ` l r |                   $  	 
    $ 7 9 ; < = ? @ ` l r |                   $  	 
    $ 7 9 ; < = ? @ ` l r |                    	  $           	  $           	  $           	  $          m  4 	~ 
 4  4 [ V [ ~   " 2 # $~ & * -8 2 4 DG FG GG HG J_ P Q RG S TG U VG X ] k l 4 mV oV p r 4 t 2 u 2 w yV { 2 | 4 }V ~ ~ ~ ~ ~ ~ ~        G G G G G G G G G G G G G  G G G G G G     ~ G  G G   G G G    V V  4  4 [  4  4 [ V [ V V ~ $  	 
    $ 7 9 ; < = ? @ ` l r |                     
   @ [ ` l r |       
   @ [ ` l r |       
   @ [ ` l r |       
   @ [ ` l r |       
   @ [ ` l r |       
  Y \ l r t u { |         
   @ [ ` l r |       
   @ [ ` l r |       
   @ [ ` l r |       
   @ [ ` l r |       
   @ [ ` l r |       
   @ [ ` l r |     . 	 ~ ~  $ D F G H R T                                ~ ~ ~    
   @ [ ` l r |     . 	 ~ ~  $ D F G H R T                                ~ ~ ~  : V 
V V  # & * - 2 2 4 7 8 9 : <y ? W Y Z \ k lV m o p rV t` u` y {` |V }            y     y   V V V V    
 o mo oo yo }o o o o o o   
   @ [ ` l r |     " o 
o o t 9j : <y ?j Y Z \ lo mt ot ro t u yt { |o }t y   y t t o o o o t t t   
  Y \ l r t u { |         
   @ [ ` l r |     m  4 	~ 
 4  4 [ V [ ~   " 2 # $~ & * -8 2 4 DG FG GG HG J_ P Q RG S TG U VG X ] k l 4 mV oV p r 4 t 2 u 2 w yV { 2 | 4 }V ~ ~ ~ ~ ~ ~ ~        G G G G G G G G G G G G G  G G G G G G     ~ G  G G   G G G    V V  4  4 [  4  4 [ V [ V V ~   "   # & * 2 4 k m o p y }                 "   # & * 2 4 k m o p y }                 "   # & * 2 4 k m o p y }               & y 	 
y y j j  $ 7G 9 ; <Q = ? ly ry |y        Q  Q    y y j y y j j  & y 	 
y y j j  $ 7G 9 ; <Q = ? ly ry |y        Q  Q    y y j y y j j  > 	[ j y j [ $[ 9 > : A < / ? > D F G H R T my oy yy }y [ [ [ [ [ [ [  /                    [      / y y j j y j y y [ > 	[ j y j [ $[ 9 > : A < / ? > D F G H R T my oy yy }y [ [ [ [ [ [ [  /                    [      / y y j j y j y y [ 0 = 
= = I # & * 2 4 7A 9= :m <d ?= Y~ Z \ k l= mI oI p r= yI |= }I        d ~ ~   d I I = = = = I I I > 	[ j y j [ $[ 9 > : A < / ? > D F G H R T my oy yy }y [ [ [ [ [ [ [  /                    [      / y y j j y j y y [ > 	[ j y j [ $[ 9 > : A < / ? > D F G H R T my oy yy }y [ [ [ [ [ [ [  /                    [      / y y j j y j y y [ 0 = 
= = I # & * 2 4 7A 9= :m <d ?= Y~ Z \ k l= mI oI p r= yI |= }I        d ~ ~   d I I = = = = I I I & y 	 
y y j j  $ 7G 9 ; <Q = ? ly ry |y        Q  Q    y y j y y j j  0 = 
= = I # & * 2 4 7A 9= :m <d ?= Y~ Z \ k l= mI oI p r= yI |= }I        d ~ ~   d I I = = = = I I I & y 	 
y y j j  $ 7G 9 ; <Q = ? ly ry |y        Q  Q    y y j y y j j  & y 	 
y y j j  $ 7G 9 ; <Q = ? ly ry |y        Q  Q    y y j y y j j  > 	[ j y j [ $[ 9 > : A < / ? > D F G H R T my oy yy }y [ [ [ [ [ [ [  /                    [      / y y j j y j y y [ : V 
V V  # & * - 2 2 4 7 8 9 : <y ? W Y Z \ k lV m o p rV t` u` y {` |V }            y     y   V V V V     r  
       # $ & ' ) - . / 2 3 4 5 7 8 9 : ; < = > ? E H I K N P Q R S U Y Z [ \ ^ k l m o p r t u y { | }                                                              
 8  DFLT latn                     case &case ,liga 2liga 8sups >sups D                                        ,     >  B 	
  @       L  O  ,  { t u   C j q v          I         ,   x  x   A  P `K        tyPL   Jz                              & 
                                                                          	 
                        ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ 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                                    r d e i  x  p k  v j    s g w      l |     c n     m }  b                    y                        q    z    `   T @      ~ 1DS[a~    " & 0 : D !"!&"""""""+"H"`"e%&i        1ARZ`x      & 0 9 D !"!&"""""""+"H"`"d%&i {uq[H$I޸ޡޞ:ڜ                                                                                      `   T @      ~ 1DS[a~    " & 0 : D !"!&"""""""+"H"`"e%&i        1ARZ`x      & 0 9 D !"!&"""""""+"H"`"d%&i {uq[H$I޸ޡޞ:ڜ                                                                                         /   , 8 < @  BK	PX@3 	` f    [  [ 		Q C Q D@4 h f    [  [ 		Q C Q DY@@?>=<;:9751/+)&$$
+>32#'.<54>54.#"#"'4632#"&!!7!!3<G*6]E'!1;3$
A!1:1!/?#.B.{,! ,, !,]#[n$;S47O;-('rT.)*4C.$8' ..  ..y$?      )@&   hC S D    +#>74>32#"&F
>F!""'5-PS\88\SP-<""!5   t 
  ,@)	 B  kD   
 
$+#"&'7!#"&'7e$
&]$
&ܚ$ܚ$  P  r : > yK)PX@( Y	CQ
C   D@&
Z Y	C   DY@  >=<; : :5320-,'%#"!#!+#"&547!+#"546?3#76;>;!323+32%!!'Ԇ)ۂ
)։(+)	,E	l%D	m$yE  rB[ 9 D O @!
*BKPX@2 j 

h 
f   _ 

SC	 S   D@1 j 

h 
f  k 

SC	 S   DY@LKA@#$#$+.'7632.54>?>;#".'+4.'>ေ>	"/AU8o<rY6=rg#"d7#;XAc@|c=D~p$#-Lb6kYb4'DX2`TV,bP&!(#/HhLNpEJ@!!)%0GhN\N:P9)>c6M9*,6Tl    }8  ' 0 D X uKPX@+    [  	[ SC C 		S D@/    [  	[ C S C C 		S DY@US((%"&((($
+#".54>324.#"32>>;+#".54>324.#"32>7Zt>3W?#4XvA3V?$J.>$0XC'-?$0WC(XAB7Zt>3W>#4XuA3V?$J.=$0XC(.?$0WB(qgh4&ImGgi5&JmI<W9)W]<V8(Vb
gh5&JlGgi5&KmH<W9)W];V8(V    M ? O T@QK8J)#Bh  S  C S C S D FD/-&$ 
 ??	+2"#"'.#">7>;#"&/#".54>7.54>32>7>hJ)40K6=eI(>;a2A<TDM/lzGG|\6:cM106b0.J_2>si^(GrP,)Kh?	 E:%,Mi>EINHG^[3V>#-U|NRy\FFPd8BeD"!:P/Viz    e 
 @	 B   kD   
 
$+#"&'7e$
&ܚ$  H   (+.54>7!2!	++<'
4UxR&	S~T+OH		XPVr	w      (+4.'&546?'&547>\!1!	++<'
4UxR&	S~T++OH		YPVr	w	   ; *@'40/+'&"	 B   ja   ; ;+7>7'7>7./7.5<?3>?'.'x	2	

n+n		n,n		n,n	
	n+n	    3  .@+ j k  M  R F    +!!#!7!7O7L8Q	8=G;G     ?    @ B?   S D"+74632'.54>7#"&?0'+/(8"'$	%/U#2;0)URL 	%9J,2    c*x  @   M   Q  E+!!n	RxN    :    @   S D&$+74>32#"&:!#7''5M""'55    @   k D""++6;	!&''/$     Z`  ' ,@)  S  CS D ''	 +2#".54>2>54.#"\r@by\r@b.cQ5\}GcQ5]}HّjHّGj_)ʂz;_Ƀ{;         )@&B   h C  R D$+%!7#"/3!!FI5(HE	'iH   F  5 1 <@9-B h  S  C Q D +)#! 11+2>3!2!7>7>54.#"#"/>Kc9;eK	 G#hq	!K}Z2-Mf9Du_F.\~*S}R[D8!5!C{|NCcA 'Ig?Zb4    q< H U@RD
B h h  [  S  C S D B@:80/.-%# HH	+2#".'763232>54.#7>54.#"#"/>K`73XwCEgF#Qhaf<)	
2OpNag6$Vm	ak8,Kd9Dv`F.[~)OvLP~^?7Oe:`xD.\Y
GhF"Ci@7aG)B2X|L@_?'Hg@Zb4  >  ^   +@(  B  \ C D!#+!+#!"&/367!Z1T2g;Tk5b2i- '  g8 - @@=+*B h  [   Q C S D(#&(""+#!632#".'763232>54.#"'!2kgg3[m:hXI -HgF[yF(TXn8{_$6aP}ǊJ#-'%=riBmN,%r     3 2@/B   [ C S D 0.&$	 +2#".54>7>;>32>54.#"Tb6QoYf7:Z>	Q&>B*PsJ^p=,QtG_o=M5`RlJ7h\:qwH	
*K#?G-DtU0=lWFrP+Do        $@!B QC    D    $'++>7!"&57	H.
#	
>     f& % ; O D@A
B [ S C S   D=<'& GE<O=O1/&;'; %%	+".54>7.54>32'2>54.#"2>54.#"^m<6`MmpBxfW_1)MpH<cG'NeYl==`u7,]ZQ=$.Ty[Y+%HjES\2!Fk1ZNYfA!hTl?3WuCDw`F5NiBfq<J3_SOkA"8PkE?fJ(9]v>6]E'2XwE2^H+       Z  2 2@/B   [ S C D /-%#	 +".54>32+>74.#"32>MP^3OiUc5:V7H T >BV+NnBVl=)MnD]i8Z3\OfI8fVDrosEI&L)BHCqQ-9gVClK(Ai   :Z   ;K#PX@ S C   S D@   [   S DY&&&$+74>32#"&4>32#"&:!#7''5f!#7''5M""'55D""'55    <e  ) K@
 B?K#PX@ S C   S D@   [   S DY@	(& "+74632'.54>7#"&4>32#"&<0'+/(8"'$	%/o!#7''5U#2;0)URL 	%9J,2<""'55    	5  (+%(BA
    	c   !@   Y   M   Q  E+!!!!;	/:+GG   	5  (+	767>7&'&5<>7L%(A
~    ' 9 5@2 B h f  S   C S D(&#,$+>32#7>54.#"#"'4>32#"&EQ\4=gK*1LYQ< @9NZL2 9M,>\@(
"!""'5
3'&Fa;SvXA<>(,E>?PhH/K5#*#g""!5  a2 W l f@c
^
?B   h  [  

[	  [ O S GYX b`XlYlOMCA=;86,*" 
 WW+%"&5<7#".54>3232>54.#"3267632#".54>32%2>7.#"IG?L-B*!>ZqN1T!';sZ7Lg\a7Vz_	o^<jhpɘXDq%!HHFp.;l\K5/NH\S 9L,;|tfL,=Z !*	Iv||?7fzPD>JP[ǡq=I҉ՙTD?lT7%AXck4!9*    X   $@!B   Z C   D# +!#"&'!+3!.'XLeLb>E	
bz*     5   * =@:B [  S   C SD  *("   !+3!2#!2654.#%!2>54&#!yfb/,QtICsJD)OsJa\,*OrHD|eIybp<:]B$H:_zAw~   / D@A
 B h   f S C  S D '%"  //+%2>32#".546$32#".#"ItZA.	#.ixPzŋKpItaQ&)N}`aBvE%+%*/K5X⊹3y,B*(,5,h|ǋJ      -   @ S C  S    D!(!&+#!!24.#!!2>-1[g$}ʍLg?uhxޢZ/}ڵb3UދyHc    ?  (@%  Y   Q C Q D+!!!!!!4WG7I5PR     ? 	 "@  Y   Q C D+!!!#!4WJOPd5Su     9 G@D$	B h   [ S C  S D 1/(&  99+%2>7#"504>7!#".546$32#"'.#"CobZ-0k?5o}R͐MnM~hV&	'7Kb?]BzA*
%:'Y㊻3w,@)'!h|ǌK    !   @   ZC   D+!#!#3!3sdSSddR(RdYk       @ C    D+!#3	dd     '@$ B h C  S    D#%$+#"&'7>3232>73}HnW6Y+

#1#;lW=xduq76%Wi       &@# B    \CD'(% +3267>;#"&'.+#3^M"(PQ~P	*	TTcdLXfU     X  @ C   R D+7!!3h6cUU    < ! '@$  B   h  CD!6(+67>;#>7+"'#32-
~EW	nWDy#F     !  @ B  CD!+2>73#"'#3bW.QW10y-G     q  ' @ S C  S    D((($+#".546$324.#"32>qm|ȍLn}ɍLg?vgޣ\@vgޢ[0xY≺3xY{ŋKh{ŊKg    ?   /@,  [S C    D    !+#!2#32>54&#GFcTJvT^k:;lHS<jV     q  / T@
BKPX@ S C S C    D@   k S C S DY((($&+#"&'#".546$324.#"32>q5aU#N
||ȍLn}ɍLg?vgޣ\@vgޢ[0⼓1{
C2Y≺3xY{ŋKh{ŊKg    3  ! 7@4B  [S C   D  !   *!+#!2#"'.#32>54&#POcP<n^qU!%SM_j8\sH@4`S~     ' = =@:= B   h f S C S D;9(&!#!+#".#"#"&'763232>54.54>32";]FLwS,2QgmgQ2B{m<!	!-@U8T`32QglhQ1:mef8&-&1Uq@=S;+)1FdI`LcV+#)#9dN>S:((0GgKQsDKH          @  QC D    +!#!7
8c6
T3T       #@ C  S D  +%2>73#".5473o]uLkdl]sgo:kdl-WFH~clu˖VG|e,-l(Th;       
  @ B  C D, +32>7>;#O&
	GN:Yc00y     ~ (  @# B  CD+; +32>7>;2>7>;#.'#NMY	Yh))h))y/     @  B  CD)"'!+	32676;	#"&'+Y-c Y	b
4rp       @ BC    D,"+#32>7>;gIcIX+SGH?d!      ,    $@! QC   Q D    +!!7>7!728A	!	R!R  DD  '@$    [ O QE    !#+!+32D&̼#    qH  @  k    D" +32#"&'q''	%$+      '@$ B    [ O Q E!#+!!7>;#"5(˻#v      @	 B k    D+!+3#"&'&'+\;UC
F
L  1  @  M Q   E    +!7	+AA     ~  @  k   D  +2#"/s5  <s  + ^@  BK%PX@ S C S   D@ S C   CS DY@#!++*' +!#"&5#".54>322>7&#".!&[gr=?^? ,QpR<h39odY#2;EC~o]D%[9P^41ZPW~\4@ud-PnL    f  0 h"BK%PX@   CS C SD@!   CS CC S DY@  (&00  *%+33>32#"&'#"32>54&f]a'`ju<AbB" ;UlHU* 9sk]$#7?C#?mYE/fO\32[PMb9MLl@td'7"3XuA    HF 2 5@2B h f S C  S    D%(#&*$+%#".54>32#".#"32>325_[^5VT*!>XnI1OB6	
1N;Tk=AbC5TA1&
;L,;jVOvV1#2! % ZlEvV0")"
  @  . p@" BK%PX@ C S C S   D@! C S C  CS DY@ &$..
 +!"&5#".54>323%2>7.#"!'alv=AbB" ;UlIQ,I\I9rk]$#+E?mYE/f=Q_42\QLb9GGKQ@?tc N@3Xt@    FF , = 7@42 B   hS C   S D.--=.=*&%,+32>32#".54>32%">54.F8`Ќ5UC3(	1]_f:SX.;WpOIe?PcCO,,G%)JB;1')$($
4K07eZKzZ4)=GgDqQ%)0361(     B % ^BK!PX@   kS CQD@   k YS DY@   % %!$%$	++'&546737>32#"&#"!2j*#~
:Wn?8
(-Q?-	
~w~UV+
0AhK{F  > T d @<& CBBKPX@+	 [  [ C S C  S    D@. h	 [  [ S C  S    DY@VU^\UdVdQOGD7642*(
+#".54>32.5467#".54>32!4&'.#"32>2>54&#"(/(#*#@tdO_4Kb"D#")[69bG(1]W3Z#l 1X)ca1'Hf>N[2@eF$n]@dE$l7ZKA>@$3016@'?uZ6 =X8HoL(4 #H3$GgDEh? 
L1F%?T.+C-*FZ6Wo8hi3Tm9jn  f    ,@)B   C S CD    %%+33>32#654&#"f^\(akp9po
^KMS6pi^$AKuQ*2]|.)fj7gZ     x     &@# S CC    D  
  +##".54>32Ny]yW !  m  ( 4@1	 B S CC S    D  %#  !%%+#"&'7>323267#".54>32J(?W5)JR
4XA%
XQbW !     c    0@- B    \C CD    %(%!+3267>;#"&'.+#rm%R9	lP	$=]	{_



   u    @   CD    +33u]Q    ^   5 Z@ BK)PX@ S  CD@   CSCDY@   5 5%&($!	+332>32>32#>54&#"#654&#"^x+#NqdU']gl5k^
]K>M1eaW#C]K	:JrI?$ꛫ~v"'PwO'}
6_|7Z]-Z\|E6TWо  ^   ! P@
 BK)PX@  S  CD@   C S CDY@   ! !%&!+332>32#654&#"^x+")cnt;op
^KMS8rk^$=$O}W-	2[|.)ej9i]     G  % ,@) S C  SD %%	 +%2>54&#"".54>32Wf7~:fVE/wP]3HlP]3I>[g)JexFK8j`yߪe9i^yޫf     2  - m@ !BK)PX@ S  C S CD@!   CS C S CDY@  %#--  *&!+32>32#"&'"32>54&2+# 'amv=AbB" ;UlHQ+;9sj^$#,E?mYE/fF$Q_42[PMb9HF?tdO@3XuA    <s  . 6@3#B S CS C    D&$..*) +#"&547#".54>322>?&#"6O&Yeo<?^? ,QpR<h39mdX#4;EC~o]D%[sM}Z11ZPW~\4?tc-PnL  ^    ,@)
 B  S  CD    #$!+332>32&#"^x+#Dc)+.(k=<$أY   ! < =@:< B   h f S C S D:8'%" #!+#".#"#"&'7>3232>54.54>32
2J73[C'&?OTO?&3^Ra/	
5R>;aE&&>PSP>&2Z|JT|0i"9K*)8)%4K5@x]8C6" ' 'DY2,<+#2H4:kS144  l@ + g@
	 &BK!PX@# j   h  Q C S D@! j   h   \ S DY@	%#(&&+74>7#"5?>;!!32>32#"&DB
./ E=0!3&(r9R]$9,5)d	G)4!A:**3Z   r " P@
  BK%PX@C   TD@C C   T DY@   " "'!%+32>73#"&5#"&54>7!KMS7pj^$@^x,)cmt:oo
/(fk8i\O|U-	3Z   S    @ B  C D+ +3267>;#SIGN	,*0   V  x )  @# B  CD(!+: +32>76;2>7>;#"'&5+VC	V$
FBVDB))**(    V  @  B  CD("(!+3267>;	#"&'+sP	 	TP	Prq	0Q  V  @ BC    D,"!++32>7>;CJ	I	
  	  <  @ Q C   Q D+!!7>7!7!6a/	^

K&	MK   GF D 7@4" 5B  [    [ O S G<:303)+4&#72654&54>;+";20#".54>D9J\+NoE3:P1	'?.*")"'8#38U:#*#9I;tw<<U_3(3Vn:B>-TF3)5 =vw{A)B0

	%BY4D{ut       @   Q D+3#KK    D 7@45" B   [    [ O S G<:303)+3"+7>;2>54&54>7.54>54.+"&504>732D9J\+NoE3:P1	'>/*")"'9"37V:#*#9I;tw<<U_3(3Vm;B>-TF3(6 =vw{A(C0

	%BY4D{ut    P  9@6 j k   [  O  S  G 
 +2>53#".#"#4>32%=*N <X83kib+&;*M <W84khb70B'7^F('0'0B'7^F('0'      )@&   h S CD    +>734632#"&D
)			C 5'#7''5&-PS\88\SP-'7#'55   / : K@H%B j h f  k S C  S   D##'#	+.54>?>;#".'>32+Vb4Lˀ##)V.
	4N8KlI*J]l:$#)LmEir=@o`לX;- "' 	1%Q]7lJ      i = C@@+  
B h  [ S C S D%&%##("	+#!>3!#!7>7#7>;>32#"'.#"!a%'#/)5$=/*$LzfPuQ4(	&;XAN`=	$,F9/'@#4I5W%)]uC%?V0 <.4_O$    D # 7 9@6!B @ ?  W  S   D42*((+467'7>327'#"&''7.732>54.#"(#2-n?>n-1%))#1-n?>m,1$)H+Ib89cJ++Jc98bI+>m-2%*)$2-n?>m-2$)($2-m?8bI++Ib88cJ++Jc        ! 8@5	 B 
 Z	YC D! +!+!32>7>;!!!!#!7!7![M	
N[o/]/nhd##9v88v       @    Y Q D+3#3#KKKK     X}b E Y A@>E WM: #B   h f  W S DCA,*'%!#!+#".#"#"&'763232>54.5467.54>32>54.'K	1I76[B%(BUXUB(^](22]Ta0
4P>>bD$ImmIdq*42Z}LS{0!8IPR$NC2CJL#`M#:N*)>3,-3AR7^&"U;Dy\5B6" % 'CY2=S@:GaGU)!V>;lR145&<2+(+&kE(?3*&&+g  vqm  % 3K'PX@  S D@  O S  GY&(($+#".54>32#".54632V0""1   k / K a @
 BKPX@4   h   f  [  [ 		S C S DKPX@4   h   f  [  [ 		S C S D@4   h   f  [  [ 		S C S DYY@^\*,*(#&(%"
+>32#".54>32#".#"32>4>32#".732>54.#"Y";t`s@Cwc4WJA	!;[DSa55_L<V?-%4^dc^44^cc^4<g\yW/hg#;FAvfdwB)!5bWZa3,c^44^cd^44^dh/Wy]ii     >d 0 : L@I!B h  [	  W S D21 651:2:%# 00
+"&=#".54>7>454#"#"&/>32'26?4cB2&)[go'8)

	1i?*>)=[+9GD.11!*H7!w/-1A$	4Ya*5)KB.)       % %(+77			 =			 z	{z	  T  =K	PX@ _   M   Q  E@ k   M   Q  EY+!#!<.O$'   c*x  @   M   Q  E+!!n	RxN    q  1 G P <BKPX@/h  		[ 
[  S   C S DKPX@/h  		[ 
[  S   C S D@/h  		[ 
[  S   C S DYY@22PNJH2G2F)!**,&+4>32#".732>54.#"#32#"'.#'32654&+q4^dd^44^cc^4<g\yW/hgUv
Onywkwc^44^cd^44^dh/Wy]iiyusvd_@a[\T     rq$  @   M   Q  E+!!y	$@    D  ' @  W  S   D((($+4>32#".732>54.#"0Qm>?nQ//Qn?>mQ0E$>U00T=$$=T00U>$n>mQ..Qm>>lQ//Ql>0T>$$>T00T?$$?T    < P8   <@9 j h  Z M Q E    	+!!#!7!!!2	O1L1S2VjGlGG   V / g@
-BK!PX@ h   [ S D@! h   [ O Q EY@ +)%# //+2>3!2!767%>54.#"#"/>(E33C%('
"=,#/9Z$V,?*-LD?!;>@$-B=`e    |V > @:BKPX@, h h   [  [ S D@1 h h   [  [ O S GY@ 8631+*)(  >>	+2#".'763232>54.#7>54.#"#"/>(D2UE@A+H^3<N1 	 9.,E/+D0ae".?T	$1BPV)<&K_K95U>!3C$('0;-!2RH+B;0I2 T  @   kD    "++7>3T7   $ 7@4  #BC   SC D   $ $&(!&+32673#"50>7#"&'#"&5RcjXH][z3K]Xn(.cmybX	;3X[JD*R#    yB4  *@'   hi  S D    +##!#".54>34	UVm\h8EnRy-SwKVi;       @   O   S  G($+4>32#".$&&$P&&%%   T   V@ BK	PX@  ^  j T D@  j  j T DY@  +232654.'73#"&'764#3:(8"8:'JN2E(&D2*a73!5%    lQ  N	BKPX@ j  j  Q  D@ j  j  M  R  FY$+37#"/733!C9R%h5    ;  # )@& W  S  D ##	 +2#".54>2>54&#"7U;+OpE8V;+Oq7T8RR:U8R$C]9O[2$B]9O\2*MlBYk+NlAYj     % # (+7'&54767&'&54?'&54767&'&54?				'	'
'	'
       `   ( . Q@N" B h h
  Z  \	CD.-('&%$#%"#!"+%3+#7!"5'3+6;37#"/733!>7!n=A&$(C9R'"Ud#k%w
h5t|    H  9 J b@_D=7 B h h
 Z [	C  T   D
	JIHGFEB@;:52/-	9
9""+%+6;2>3!2!7>7%>54.#"#*/>%37#"/733!w&$(y(E33C%('
"=,#/>XC9Rd#K,?*-LD?! ;>@$-F9`e %w
h5    r   Y _ y@vU!.
	 B h 	
	
h 

h  	[ 
  
[  \ SCD_^SPMKEDCB:820*(YY"#!#+%3+#7!"5'3+6;%2#".'763232>54.#7>54.#"#*/>>7!		n=A&$((D2UE@A+H^3<N1 	"6*,E/+D0ae".?V		1BP+'"Ud#)<&K_K95U>!3C$-%0;-!2RH+E80I2|  ; ( : 5@2 B h f S C  S    D('#,$+#".54>?332>324>32#"&;DP\4;gL+1KZP; >6MXK1!8K)=]B'!""'53'%Db>RtS=68%+?99KeG0L5$*$P""!5   X& $   	@    X& $   H    X& $   @    X& $   @    X& $   
@    X& $   @        :@7 B  Y  Y   Q C SD#	+!!!!!!+!!6WXMwz
5PRbz5+    L h@e9? J	B h f
  h S C SC 	S 			D HF>=750.&$! LL+232654.'7.546$32#".#"32>32#"&'76#3:(8"/rFpItaQ&)N}`aBvbItZA.	#-dsLJN2E(&D2*r^܅3y,B*(,5,h|ǋJ%+%*-I5L73!5%     ?& (   	G     ?& (   G     ?& (   G     ?& (   
G     & ,   	      & ,         & ,         & ,   
     E  `  ! ,@)  Y S C S D!%(!+3!2#!#%4.#!!!!2>MR}ɍLl$T?ugHsJxݡZUމryH>c   !& 1      q& 2   	   q& 2      q& 2      q& 2      q& 2   
     )C  	(+		'	7	)cF6Z,9C3u3wp4p     O ! - 9 b@21&%BKPX@  k C S C  S    D@ j  k S C  S    DY**%(%$+#"&'+7.546$327>;.#"%4&'32>qmhC")JNnmEz4DHw:6%:`ޣ\"409Zޢ[0x>9Q卺3xE?QvE<@h(oE67g & 8   	   & 8      & 8      & 8   
     & <   &      Y   ,@)   \  [ C D"& +32+#332>54&#Ju#cd-T^k:ilHT<jV     ; P @
JBKPX@- h k  S  C Q C S D@+ h k  [  S  C S DY@ LKIGFD<:$" PP	+2#"&'763232>54.54>54.#"+'&573>InJ%4MZM4.EQE.6_M]~03L::^B$/HRH/5O]O54T=A{cEp*#W|-I\.FdL<:A+)3'&7TBL\3C6! % (E]58F0#-B58RC=GZ?D9&Bv^zv	(_K <s& D    CT   <& D    v-   <s& D       <h& D       <m& D    j   <s& D    2    2j G W d @?E!BK)PX@5 h h
[ S	  CSD@? h h
[ S	  C SC SDY@&YX ^]XdYdSQIHCA=;860/'%
	 GG+232>32#"&'#".54>?>54&#"#"/>32>32>7">54&Z7]D&>y5UD3(	0\`g:t[jo08]C%F\[BaF.Qcrt9=0B'=oY<
GtY;{4b ;Q0:hN0))$($
3K1MjA8W<K}[6U#in(/(NPxkjx'Eb?.B+-U|P+6cV'<N-HQ    HF N h@e;A L	B h f
  h S C SC 	S 			D JH@?9720(&#! NN+232654.'7.54>32#".#"32>32#"&'76#3:(8"1OtM&!>XnI1OB6	
1N;Tk=AbC5TA1&2XVV/ JN2E(&D2*u?iSOvV1#2! % ZlEvV0")"
7I,P73!5%    FF& H    C    FF& H    v    FF& H        FQm& H    j    a  `&     C    x  '&     v    B  %&         I  Dm&     j     Iy 7 I 5@20B76@  [ S    D98A?8I9I,*" +&54?.'&54?7#".54>324654&'267.#"3vDQC
+H4@~L^5Ayi1`TE\UI!	+GeDZ`2*Hc.	y#0	=3
	o(f~Yn9h[mU9X=K,3dO1H|^M{V. ^  j& Q     ++   G& R   C   ++   G& R   v   ++   G& R      ++   Gj& R      ++   Go& R   j   ++     3^   # +@(   [    Y O S G&&&%+!!4>32#"&4>32#"&U%$.&$,X%$.%#-G{&1#%/Y&1#%/       * 5 u@43$#BKPX@!  k C S C S   D@! j  k S C S   DY@,+ +5,5'%   +"'+7.54>327>;&#"2>54&'YF!&+-HlDq-=2u),I7GnWh9Wg9GK`5[yߪe(&S5XyޫfWGYAZkBn*GB    r& X   C   ++   r& X   v   ++   r& X      ++   ro& X   j   ++   V& \   v   ++    ;  0 ?@<"B   CS C S CD  (&00  *%+3>32#"&'#"32>54&;]b'`kt<AbB" ;UlHQ+6$9sk]$#7>C#?mYF/gN\32[PMb9HGE@ud'6"3XuA Vo& \   j   ++    ' 0 L@I-BA  h  Z C C S D )($" ''+2#"&54>7.'!+332>!.'	
Q+BK*6eLbg7.3*$E		!B:">6.by$0<")0+,     <s 4 F K%PX@&;B@&;BYK%PX@*  h S C	SC S D@.  h S C C	S C S DY@65 ><5F6F1/('$" 44
+2#"&54>7.5#".54>32#32>2>7&#",	
Q+BK-8!&[gr=?^? ,QpR<h3u3+3*$09odY#2;EC~o]D%[!B:#@7/
4P^41ZPW~\4?$0<")06@ud-PnL    & &      HF& F   v   ++    ? ' T@Q	B
 	 	h  Y Q C QC 		S D $" ''+2#"&54>7!!!!!!#32>X	
Q+BK*6WG7Ip3+3*$!B:">6.RPR$0<")0  FF L ] e@bR9@?B h	  h
S C SC S DNM M]N]IG>=750. LL+2#"&54>7"#".54>3232>32732>">54.C	
Q+BK$/SX.;WpOIe?8`Ќ5UC3(	/XZ_6)-3+3*$PcCO,,G!B:93-7eZKzZ4)=G)JB;1')$($
1H0$0<")0DqQ%)0361(   x  N  @C    D    +#Ny]y     0    !@  B C   R D+%!!7>?3g~Dh6H	
[c=
UMf@^     S  8  @ B   C D+46?37#SL]H_\ZTvW2VV    !& 1      ^  & Q   v  ++        46@
 BKPX@*  Y S C   Q
C	SDKPX@4  Y S C   Q
C SC 		SDK#PX@*  Y S C   Q
C	SDK%PX@4  Y S C   Q
C SC 		SD@2  Y S C   Q
C Q C 		S DYYYY@  1/'%    (%+!!!!!#".54>324.#"32> 	ZG2	H'+qVo}CeWrQ,]7g]w̕U8h\x̔TRPR>N{U-Wއ6z5aVgxKkxIj  6 8 N ] S@PT6$B h S	  C
SDPO:9 O]P]FD9N:N42*("  88+232>32#"&'#".54>32>2>54.#"">54.=aD#8^ƃy5UD3(	0\`g:yUi~GOtK$Mix:8GrW>(:W;Zh88Z~H{_?{-0J 9O0%F@80'$($
3K1EnL):aEZuvI2Vs?CoO+Tۈ6fP0q:k_:EN'6)   '& 6      !& V   v   ++   '& 6   
   !& V      ++     & <   
&   ,  & =   F   	  <& ]   v   ++   ,  & =   F   	  <& ]      ++   ,  & =   F   	  <& ]      ++    U %SKPX@ Y S C  S    DKPX@ Y S C  S    DKPX@ Y S C  S    DKPX@ Y S C  S    DKPX@ Y S C  S    DKPX@ Y S C  S    DKPX@ Y S C  S    D@ Y S C  S    DYYYYYYY@   % %""	+#763>7'&546737>3#"!VwW%3eWE//"5dWE1f	b\+/FqS
1 FqRE    oR  @ B  k D' +#"/+73R=	{AS    r  @ B  k   D' +32?6;#A{?S    rq$ q    a   @   WD  +".547332>73e5K.C 3&,?+C#=Y5H*4%3B&2ZD' 2  @   S  D($+#".54>32    F!!   s   =K'PX@  W  S   D@    [ O S GY$&($+4>32#".732654&#"/?##?//?##?/:@32@@23@$<++<$$;,,;$2@@22@@  7\   +@(B @  j S D  +2#"&54>732>F	
Q+BK1>-3+3*$!B:%C:/$0<")0     |nh  QKPX@  W SD@  [  O  S GY@ 
 +2673#".#"#>32(.9(6 1-+&0:)5 2,*7/$>.!(!:-$?-!'!     	  #@   S D

  

 	 #++7>3!+7>3)=- Y  \BK1PX@  SCSD@  SC CS DY@    !$##	++#!#"&'7632327#7>3Yq]qVVsb0	V$d;ns	&!    ld  @   M   Q  E+!!+dE    Bd  @   M   Q  E+!!	VdE    #   (+&5467\H):#7;XB
1v?/*  \   (+'&5467>54&'&547E\H*8
7;XA		1v?,       (+7'&5467>54&'&547\H*8
7;XA		1v?,    #  )  (+&5467&5467\H):\H):#7;XB
1v?/*7;XB
1v?/*   e  +  (+'&5467>54&'&547%'&5467>54&'&547T\H*8
8\H*8
7;XA		1v?,7;XA		1v?,     +  (+7'&5467>54&'&547%'&5467>54&'&547|\H*8
8\H*8
7;XA		1v?,7;XA		1v?,      " YKPX@# C S  CSC D@O C S  C DY@
$!#"+>3>32>72!#"'!FK/	GLF=Oh=&
   f 6 *
BKPX@6		`
[ C  SC  SC 


D@1		`  O
[ C  SC 


DY@   6 61.,+)'$##!##+%!7>3>32>72!!#.'#"'"&5467XFK/	GLFZ_FK,G&OOM$ &
+'
    91|  @   O   S  G($+4>32#".9.Pi<=lP..Pl=<iP.T=lQ..Ql=<iP..Pi  :   ! 1 @  SD&&(&&$+74>32#"&%4>32#"&%4>32#"&:!#7''5!""'5!#7''5M""'55'""!5'""'55  }  ' 0 D X l  KPX@/    [	[ SC C		S
D@3    [	[ C S C C		S
DY@}{sqig_]US((%"&((($+#".54>324.#"32>>;+#".54>324.#"32>%#".54>324.#"32>7Zt>3W?#4XvA3V?$J.>$0XC'-?$0WC(XAB7Zt>3W>#4XuA3V?$J.=$0XC(.?$0WB(6Zt?3W>#4XuA3V?$J.=$0WC'->$0WC'qgh4&ImGgi5&JmI<W9)W]<V8(Vb
gh5&JlGgi5&KmH<W9)W];V8(V]gh5&JlGgi5&KmH<W9)W];V8(V        (+7			 z	        (+7'&54767&'&54?		'	'
     @ C    D""+'+6;&$(d#     ) J [@X9	B   h 		h  [	[ S C 
S 


DJIFEDC?=75$##%'$+3>32#".#"!#!!#!32>32#".5#73>7#Lqr@jWI %,@W:_`e	4aY>cM:)	 )^l|Fnu<^ғN,A*$$@}u*X0zC%+%	!.K5Qه9/Y*     H  & 9@6B hi S	  D&&!4)
+>7>;#7+"'#32'###7

6E<6		
7<F7

?E?n'|)B?::  (  ; : 3@0  B   S CSD   : :***+!>54.#"!"504>7!7.54>32!,dyDCv]p˛[0Y|L+3N]4lrÍPKghYyjn7I׎VhF
Rw\YFv}͛h3     W / A C@@ 5"B h  [  S   CS D10;90A1A#)**$+>32#".54>32>54&#"#"'2>7.#"%BBD&EjH&	kԂClM)&EawK1WG4ol-G6%
NKv_!7V?fr=t=#5d^AI,SvKRtT/7T:NV&Fx4dN0``y    i   @	B C  R    D+)3!.'ijYj%&    w  $@!  QCD    +##!##7w	__	PiiP   *@' B   QC Q D    +!!!767	&5467	IR
RR$2-     {  @   M   Q  E+!!<	G    E  S  "@ B j   [    D+%!+!##"&5467!267>;RM9
7	)#(   L ' ; O L@IK-B[
	  O
	 S  G=<)( GE<O=O31(;);	 ''+".'#".54>32>32%2>7.#"!2>54.#"3O?3"HPX30T>$3Un<3O?3"GPX31U?$2Up(IDA -4@(-P=$-<m0Q;"-<$(ICA!,5?'BV..VB'$C`<N_5'BV..VB'$C`<L`7N&?T--T@&'Ge=.F0*Id:-F0&@S--T@& e ' *@' B  S   CS D!%'U$+>32#"&#"#"&'7>3232>7EZl;$4
	`"Kas@;
 6[J7>WU+,
dZ)	' GrQ      7 d@a  !0"/B   [   [  [	O	S G 42+)&$77
 
+2>7#".#"'>322>7#".#"'>3243-%#i83a]\.3,%#h<4a][2-&#h84a]\/3,$$h<5a]Z(8+.$,$6-/$,$8*/$,$6-0%+%      	p  kK	PX@)   ^ _ 	 ZMQE@'  j k 	 ZMQEY@
+!3!!!!#!7!7!F͇	FEZ>cGGG  g PO   @ @   M   Q  E+!!&)$@A
v>	xI  u PQ   @@   M  Q   E+%!7!7>767.'&5<>7c	AG&)$PI>	    f   "@
  B   M   Q  E+3	#	>7	.'BnBL		M		@@S     ~  @   ja    +3v0    @T % k@ BK!PX@" kS C Q  C D@  k  [S C DY@!&%$	+!#!+'&5737>32#"&#"8w^nFl*"~DlX%$ 	,"<}v	*U\e6.   @ $ @

BK!PX@$   kSC
	QC DK%PX@"   k
	[SC DK)PX@&   k
	[ CS C D@- h   k
	[ C S C DYYY@   $ $!!%$++'&5737>32;#.#"!3l*"~BjYE94]/h0EqU7	~v	*BXm>nL/X~NBF   S   -K1PX@ j    D@
 j   aY@	    +#n;N[  { 	 @  j a  		+2#"&/I		     6   @  O S  G$$$"+#"&54632#"&546324/../O.--.,, -- ,, --     6p  @   M   Q  E+!!	p:   , 	 @ j   a   	 #++7>3I	      @ B  j  a+ +#"&/.'+73GGW       @ B  j a+ +326?>;#GGW    (@%j   O  S  G  +"&547332673gc>DNXU?{XT9AQHcr @8  @   O  S   G($+#".54>32    1   !@    [ O S G$&($+4>32#".732654&#"-<"">-->""<-5?32@@23?^";**;"#:**:#2@@22@@    1@.  [  O  S G 
 +2673#".#"#>32&/4&4 3/-&/7'4 4.-O7+"<, & 9*"<, %      	  +@(  O S  G

  

 	 #++7>3!+7>3-Z3   @  k   D 	 +2+	$U
!;XB
-     M_< 	    ʓ^p    ӡ   	          V                  /          T   P r } M ( (    ?d c : Z  F q > g   f  : <+  +   a  v ?  ` p & B    n  F    '5 E   TS  ,( D q(   < f] H @ F8 Bq f xmx c u ^  ^ G 2 < ^ ! l r SS VV VF 	( GX (  P  T     X  X vM kk 2  d cM q r  <    y    2     ? ? ? ? & & & &  En        OE E E E S F   ; < < < < < < 2] H F F F F a x B I I  ^ G G G G G    r r r r V ; V < ] H?  F x 02 Sn   ^   6 ' ! ' !S  ,F 	 ,F 	 ,F 	  o  r 2  7 | <  n n  g g g, , f9` :  }E E  )! l (+ WT  b E Le  + g+ u    @ @ S {  ,   @        g P`    	[  j  y  j  [  $[  9 >  : A  < /  ? >  D  F  G  H  R  T  my  oy  yy  }y  [  [  [  [  [  [  [   /                                        [           /  y  y  j  j  y  j  y  y  [ 
 	[ 
 j 
 y 
 j 
 [ 
 $[ 
 9 > 
 : A 
 < / 
 ? > 
 D 
 F 
 G 
 H 
 R 
 T 
 my 
 oy 
 yy 
 }y 
 [ 
 [ 
 [ 
 [ 
 [ 
 [ 
 [ 
  / 
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
 [ 
  
  
  
  
  / 
 y 
 y 
 j 
 j 
 y 
 j 
 y 
 y 
 [  #  &  *  2  4  D  F  G  H  R  T  k  p                                                                  	[  j  y  j  [  $[  9 >  : A  < /  ? >  D  F  G  H  R  T  my  oy  yy  }y  [  [  [  [  [  [  [   /                                        [           /  y  y  j  j  y  j  y  y  [  =  
=  =  I  #  &  *  2  4  7A  9=  :m  <d  ?=  Y~  Z  \  k  l=  mI  oI  p  r=  yI  |=  }I                d  ~  ~      d  I  I  =  =  =  =  I  I  I  y  	  
y  y  j  j    $  7G  9  ;  <Q  =  ?  ly  ry  |y                Q    Q        y  y  j  y  y  j  j    =  
=  =  I  #  &  *  2  4  7A  9=  :m  <d  ?=  Y~  Z  \  k  l=  mI  oI  p  r=  yI  |=  }I                d  ~  ~      d  I  I  =  =  =  =  I  I  I   >  	  
 >   >  G    G        " F  #  $  &  *  -o  2  4  D  F  G  H  P  Q  R  S  T  U  V  X  Y  Z  \  ]  k  l >  m  o  p  r >  t P  u P  w  y  { P  | >  }                                                                                                                 >   >  G   >   >  G    G       #  # 	 # 
 #  #  #  # $ # 7 # 9 # ; # < # = # ? # @ # ` # l # r # | #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  $ V $ 
V $ V $  $ # $ & $ * $ - 2 $ 2 $ 4 $ 7 $ 8 $ 9 $ : $ <y $ ? $ W $ Y $ Z $ \ $ k $ lV $ m $ o $ p $ rV $ t` $ u` $ y $ {` $ |V $ } $  $  $  $  $  $  $  $  $  $  $  $ y $  $  $  $  $ y $  $  $ V $ V $ V $ V $  $  $  & o & mo & oo & yo & }o & o & o & o & o & o '  ' 	 ' 
 '  '  '  ' $ ' 7 ' 9 ' ; ' < ' = ' ? ' @ ' ` ' l ' r ' | '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  ) 	 ) L ) L )  )  )  ) "  ) $ ) -. ) D ) F ) G ) H ) P ) Q ) R ) S ) T ) U ) X ) w )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  ) L ) L ) L )  - 	 -  - $ -  -  -  -  -  -  -  -  -  .   . 
  .   .  . # . & . * . 2 . 4 . I . W . Y . Z . \ . k . l  . m . o . p . r  . y . |  . } .  .  .  .  .  .  .  .  .  .  .  .  .  .   .   .   .   .  .  .  /  / 
 /  / $ / # / & / * / 2 / 4 / 78 / 9V / :y / <= / ?V / Yz / Z / \z / k / l / m$ / o$ / p / r / t= / u= / y$ / {= / | / }$ /  /  /  /  /  /  /  / = / z / z /  /  / = / $ / $ /  /  /  /  / $ / $ / $ 2  2 	 2 
 2  2  2  2 $ 2 7 2 9 2 ; 2 < 2 = 2 ? 2 @ 2 ` 2 l 2 r 2 | 2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  3 	 3 = 3 = 3  3 $ 3 -V 3 D 3 F 3 G 3 H 3 R 3 T 3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3 = 3 = 3 = 3  4  4 	 4 
 4  4  4  4 $ 4 7 4 9 4 ; 4 < 4 = 4 ? 4 @ 4 ` 4 l 4 r 4 | 4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  5 # 5 & 5 * 5 2 5 4 5 7 5 8 5 k 5 p 5  5  5  5  5  5  5  5  5  5  5  5  5  7 	 7 L 7 L 7 L 7  7 ] 7 ] 7 " - 7 # 7 $ 7 & 7 * 7 -8 7 2 7 4 7 D) 7 F) 7 G) 7 H) 7 JA 7 P] 7 Q] 7 R) 7 S] 7 T) 7 U] 7 VF 7 X] 7 YQ 7 Zy 7 [b 7 \L 7 ]e 7 k 7 mL 7 oL 7 p 7 w] 7 yL 7 }L 7  7  7  7  7  7  7  7  7  7  7  7  7  7  7 ) 7 ) 7 ) 7 ) 7 ) 7 ) 7 ) 7 ) 7 ) 7 ) 7 ) 7 ) 7 ) 7 ] 7 ) 7 ) 7 ) 7 ) 7 ) 7 ) 7 ] 7 ] 7 ] 7 ] 7 Q 7 Q 7  7 ) 7  7 ) 7 ) 7 ] 7  7 ) 7 F 7 F 7 e 7 e 7 e 7 L 7 L 7 L 7 L 7 L 7 L 7 L 7 L 7  8 	 8  8 $ 8  8  8  8  8  8  8  8  8  9  > 9 	 9 
 > 9  > 9 G 9  9 G 9  9  9  9 " F 9 # 9 $ 9 & 9 * 9 -o 9 2 9 4 9 D 9 F 9 G 9 H 9 P 9 Q 9 R 9 S 9 T 9 U 9 V 9 X 9 Y 9 Z 9 \ 9 ] 9 k 9 l > 9 m 9 o 9 p 9 r > 9 t P 9 u P 9 w 9 y 9 { P 9 | > 9 } 9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  > 9  > 9 G 9  > 9  > 9 G 9  9 G 9  9  9  :  F : 	 : 
 F :  F :  :  :  :  :  : $ : - : D : F : G : H : J : P : Q : R : S : T : U : V : X : l F : r F : t < : u < : w : { < : | F :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  F :  F :  :  F :  F :  :  :  ;   ; 
  ;   ;  ; # ; & ; * ; 2 ; 4 ; I ; W ; Y ; Z ; \ ; k ; l  ; m ; o ; p ; r  ; y ; |  ; } ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;   ;   ;   ;   ;  ;  ;  <  4 < 	~ < 
 4 <  4 < [ < V < [ < ~ <  <  < " 2 < # < $~ < & < * < -8 < 2 < 4 < DG < FG < GG < HG < J_ < P < Q < RG < S < TG < U < VG < X < ] < k < l 4 < mV < oV < p < r 4 < t 2 < u 2 < w < yV < { 2 < | 4 < }V < ~ < ~ < ~ < ~ < ~ < ~ < ~ <  <  <  <  <  <  <  < G < G < G < G < G < G < G < G < G < G < G < G < G <  < G < G < G < G < G < G <  <  <  <  < ~ < G <  < G < G <  <  < G < G < G <  <  <  < V < V <  4 <  4 < [ <  4 <  4 < [ < V < [ < V < V < ~ =  = "   = # = & = * = 2 = 4 = k = m = o = p = y = } =  =  =  =  =  =  =  =  =  =  =  =  =  =  > # > & > * > 2 > 4 > D > F > G > H > R > T > k > p >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  ? V ? 
V ? V ?  ? # ? & ? * ? - 2 ? 2 ? 4 ? 7 ? 8 ? 9 ? : ? <y ? ? ? W ? Y ? Z ? \ ? k ? lV ? m ? o ? p ? rV ? t` ? u` ? y ? {` ? |V ? } ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ? y ?  ?  ?  ?  ? y ?  ?  ? V ? V ? V ? V ?  ?  ?  E  E 
 E  E  E @ E [ E ` E l E r E | E  E  E  E  H  H 
 H  H  H @ H [ H ` H l H r H | H  H  H  H  I  K I 
 K I  K I y I y I l K I r K I t d I u d I { d I | K I  K I  K I y I  K I  K I y I y K  K 
 K  K Y K \ K l K r K t K u K { K | K  K  K  K  K  K  N D N F N G N H N R N T N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  P  P 
 P  P Y P \ P l P r P t P u P { P | P  P  P  P  P  P  Q  Q 
 Q  Q Y Q \ Q l Q r Q t Q u Q { Q | Q  Q  Q  Q  Q  Q  R  R 
 R  R  R @ R [ R ` R l R r R | R  R  R  R  S  S 
 S  S  S @ S [ S ` S l S r S | S  S  S  S  U y U y U D U F U G U H U R U T U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U y U y U y Y 	 Y ~ Y ~ Y  Y $ Y D Y F Y G Y H Y R Y T Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y ~ Y ~ Y ~ Y  Z 	 Z  Z  Z  Z $ Z  Z  Z  Z  Z  Z  Z  Z  Z  Z  Z  Z  [ D [ F [ G [ H [ R [ T [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  \ 	 \ y \ y \  \ $ \ D \ F \ G \ H \ R \ T \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \ y \ y \ y \  ^ # ^ & ^ * ^ 2 ^ 4 ^ D ^ F ^ G ^ H ^ R ^ T ^ k ^ p ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  k  k 	 k 
 k  k  k  k $ k 7 k 9 k ; k < k = k ? k @ k ` k l k r k | k  k  k  k  k  k  k  k  k  k  k  k  k  k  k  k  k  k  l 	[ l j l y l j l [ l $[ l 9 > l : A l < / l ? > l D l F l G l H l R l T l my l oy l yy l }y l [ l [ l [ l [ l [ l [ l [ l  / l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l [ l  l  l  l  l  / l y l y l j l j l y l j l y l y l [ m y m 	 m 
y m y m j m j m  m $ m 7G m 9 m ; m <Q m = m ? m ly m ry m |y m  m  m  m  m  m  m  m Q m  m Q m  m  m  m y m y m j m y m y m j m j m  o y o 	 o 
y o y o j o j o  o $ o 7G o 9 o ; o <Q o = o ? o ly o ry o |y o  o  o  o  o  o  o  o Q o  o Q o  o  o  o y o y o j o y o y o j o j o  p  p 	 p 
 p  p  p  p $ p 7 p 9 p ; p < p = p ? p @ p ` p l p r p | p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  r 	[ r j r y r j r [ r $[ r 9 > r : A r < / r ? > r D r F r G r H r R r T r my r oy r yy r }y r [ r [ r [ r [ r [ r [ r [ r  / r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r [ r  r  r  r  r  / r y r y r j r j r y r j r y r y r [ t 	e t e t $e t 9 F t : F t < ( t ? F t e t e t e t e t e t e t e t  ( t e t  ( t e u 	e u e u $e u 9 F u : F u < ( u ? F u e u e u e u e u e u e u e u  ( u e u  ( u e y y y 	 y 
y y y y j y j y  y $ y 7G y 9 y ; y <Q y = y ? y ly y ry y |y y  y  y  y  y  y  y  y Q y  y Q y  y  y  y y y y y j y y y y y j y j y  { 	e { e { $e { 9 F { : F { < ( { ? F { e { e { e { e { e { e { e {  ( { e {  ( { e | 	[ | j | y | j | [ | $[ | 9 > | : A | < / | ? > | D | F | G | H | R | T | my | oy | yy | }y | [ | [ | [ | [ | [ | [ | [ |  / |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | [ |  |  |  |  |  / | y | y | j | j | y | j | y | y | [ } y } 	 } 
y } y } j } j }  } $ } 7G } 9 } ; } <Q } = } ? } ly } ry } |y }  }  }  }  }  }  }  } Q }  } Q }  }  }  } y } y } j } y } y } j } j }   V  
V  V    #  &  *  - 2  2  4  7  8  9  :  <y  ?  W  Y  Z  \  k  lV  m  o  p  rV  t`  u`  y  {`  |V  }                        y          y      V  V  V  V        V  
V  V    #  &  *  - 2  2  4  7  8  9  :  <y  ?  W  Y  Z  \  k  lV  m  o  p  rV  t`  u`  y  {`  |V  }                        y          y      V  V  V  V        V  
V  V    #  &  *  - 2  2  4  7  8  9  :  <y  ?  W  Y  Z  \  k  lV  m  o  p  rV  t`  u`  y  {`  |V  }                        y          y      V  V  V  V        V  
V  V    #  &  *  - 2  2  4  7  8  9  :  <y  ?  W  Y  Z  \  k  lV  m  o  p  rV  t`  u`  y  {`  |V  }                        y          y      V  V  V  V        V  
V  V    #  &  *  - 2  2  4  7  8  9  :  <y  ?  W  Y  Z  \  k  lV  m  o  p  rV  t`  u`  y  {`  |V  }                        y          y      V  V  V  V        V  
V  V    #  &  *  - 2  2  4  7  8  9  :  <y  ?  W  Y  Z  \  k  lV  m  o  p  rV  t`  u`  y  {`  |V  }                        y          y      V  V  V  V        o  mo  oo  yo  }o  o  o  o  o  o    	  
        $  7  9  ;  <  =  ?  @  `  l  r  |                                        	  
        $  7  9  ;  <  =  ?  @  `  l  r  |                                        	  
        $  7  9  ;  <  =  ?  @  `  l  r  |                                        	  
        $  7  9  ;  <  =  ?  @  `  l  r  |                                        	  
        $  7  9  ;  <  =  ?  @  `  l  r  |                                        	  
        $  7  9  ;  <  =  ?  @  `  l  r  |                                      	    $                    	    $                    	    $                    	    $                     4  	~  
 4   4  [  V  [  ~      " 2  #  $~  &  *  -8  2  4  DG  FG  GG  HG  J_  P  Q  RG  S  TG  U  VG  X  ]  k  l 4  mV  oV  p  r 4  t 2  u 2  w  yV  { 2  | 4  }V  ~  ~  ~  ~  ~  ~  ~                G  G  G  G  G  G  G  G  G  G  G  G  G    G  G  G  G  G  G          ~  G    G  G      G  G  G        V  V   4   4  [   4   4  [  V  [  V  V  ~    	  
        $  7  9  ;  <  =  ?  @  `  l  r  |                                        
      @  [  `  l  r  |            
      @  [  `  l  r  |            
      @  [  `  l  r  |            
      @  [  `  l  r  |            
      @  [  `  l  r  |            
    Y  \  l  r  t  u  {  |                
      @  [  `  l  r  |            
      @  [  `  l  r  |            
      @  [  `  l  r  |            
      @  [  `  l  r  |            
      @  [  `  l  r  |            
      @  [  `  l  r  |          	  ~  ~    $  D  F  G  H  R  T                                                                ~  ~  ~      
      @  [  `  l  r  |          	  ~  ~    $  D  F  G  H  R  T                                                                ~  ~  ~    V  
V  V    #  &  *  - 2  2  4  7  8  9  :  <y  ?  W  Y  Z  \  k  lV  m  o  p  rV  t`  u`  y  {`  |V  }                        y          y      V  V  V  V        o  mo  oo  yo  }o  o  o  o  o  o    
      @  [  `  l  r  |          o  
o  o  t  9j  :  <y  ?j  Y  Z  \  lo  mt  ot  ro  t  u  yt  {  |o  }t  y      y  t  t  o  o  o  o  t  t  t    
    Y  \  l  r  t  u  {  |                
      @  [  `  l  r  |           4  	~  
 4   4  [  V  [  ~      " 2  #  $~  &  *  -8  2  4  DG  FG  GG  HG  J_  P  Q  RG  S  TG  U  VG  X  ]  k  l 4  mV  oV  p  r 4  t 2  u 2  w  yV  { 2  | 4  }V  ~  ~  ~  ~  ~  ~  ~                G  G  G  G  G  G  G  G  G  G  G  G  G    G  G  G  G  G  G          ~  G    G  G      G  G  G        V  V   4   4  [   4   4  [  V  [  V  V  ~    "    #  &  *  2  4  k  m  o  p  y  }                                "    #  &  *  2  4  k  m  o  p  y  }                                "    #  &  *  2  4  k  m  o  p  y  }                              y  	  
y  y  j  j    $  7G  9  ;  <Q  =  ?  ly  ry  |y                Q    Q        y  y  j  y  y  j  j    y  	  
y  y  j  j    $  7G  9  ;  <Q  =  ?  ly  ry  |y                Q    Q        y  y  j  y  y  j  j    	[  j  y  j  [  $[  9 >  : A  < /  ? >  D  F  G  H  R  T  my  oy  yy  }y  [  [  [  [  [  [  [   /                                        [           /  y  y  j  j  y  j  y  y  [  	[  j  y  j  [  $[  9 >  : A  < /  ? >  D  F  G  H  R  T  my  oy  yy  }y  [  [  [  [  [  [  [   /                                        [           /  y  y  j  j  y  j  y  y  [  =  
=  =  I  #  &  *  2  4  7A  9=  :m  <d  ?=  Y~  Z  \  k  l=  mI  oI  p  r=  yI  |=  }I                d  ~  ~      d  I  I  =  =  =  =  I  I  I  	[  j  y  j  [  $[  9 >  : A  < /  ? >  D  F  G  H  R  T  my  oy  yy  }y  [  [  [  [  [  [  [   /                                        [           /  y  y  j  j  y  j  y  y  [  	[  j  y  j  [  $[  9 >  : A  < /  ? >  D  F  G  H  R  T  my  oy  yy  }y  [  [  [  [  [  [  [   /                                        [           /  y  y  j  j  y  j  y  y  [  =  
=  =  I  #  &  *  2  4  7A  9=  :m  <d  ?=  Y~  Z  \  k  l=  mI  oI  p  r=  yI  |=  }I                d  ~  ~      d  I  I  =  =  =  =  I  I  I  y  	  
y  y  j  j    $  7G  9  ;  <Q  =  ?  ly  ry  |y                Q    Q        y  y  j  y  y  j  j    =  
=  =  I  #  &  *  2  4  7A  9=  :m  <d  ?=  Y~  Z  \  k  l=  mI  oI  p  r=  yI  |=  }I                d  ~  ~      d  I  I  =  =  =  =  I  I  I  y  	  
y  y  j  j    $  7G  9  ;  <Q  =  ?  ly  ry  |y                Q    Q        y  y  j  y  y  j  j    y  	  
y  y  j  j    $  7G  9  ;  <Q  =  ?  ly  ry  |y                Q    Q        y  y  j  y  y  j  j    	[  j  y  j  [  $[  9 >  : A  < /  ? >  D  F  G  H  R  T  my  oy  yy  }y  [  [  [  [  [  [  [   /                                        [           /  y  y  j  j  y  j  y  y  [  V  
V  V    #  &  *  - 2  2  4  7  8  9  :  <y  ?  W  Y  Z  \  k  lV  m  o  p  rV  t`  u`  y  {`  |V  }                        y          y      V  V  V  V               .B>tTn<4t@x		n	
 
L
r
lBl"^NR@P:jrN"j Pj@
jjdd$  n !*!|"f"#&#V#p$@$Z$$%`& & &v&&'6'|'(()$)*X*d*p*|****+++++++++,>,J,V,b,n,z,,-<-H-T-`-l-x-.j.v...../0<0H0T0`0l0x0001 121D1V1h1z112j2|22223,3>34r4~445556.6:6L7:77888 8,888J8V8h8t89l9999:&:t:;
;>;;;;<"<J<<==>(>T>???@@@AjABBBBBBCjCDBDDEE`EzEFFFGG(GJGxGGHHDHHH      d   " / n   	                       
                /                (               0       B      	 B      
Q       -       2E       w       9  	  S  	  g  	  {  	  ^  	     	  P  	     	  `U  	    	 	   	 
  	  0  	  d  	   	  4  	    	  Copyright (c) 2010-2013 by tyPoland Lukasz Dziedzic with Reserved Font Name "Lato". Licensed under the SIL Open Font License, Version 1.1.Lato LightItalictyPolandLukaszDziedzic: Lato Light Italic: 2013Lato Light ItalicVersion 1.105; Western+Polish opensourceLato-LightItalicLato is a trademark of tyPoland Lukasz Dziedzic.Lukasz DziedzicLato is a sanserif typeface family designed in the Summer 2010 by Warsaw-based designer Lukasz Dziedzic ("Lato" means "Summer" in Polish). It tries to carefully balance some potentially conflicting priorities: it should seem quite "transparent" when used in body text but would display some original traits when used in larger sizes. The classical proportions, particularly visible in the uppercase, give the letterforms familiar harmony and elegance. At the same time, its sleek sanserif look makes evident the fact that Lato was designed in 2010, even though it does not follow any current trend. The semi-rounded details of the letters give Lato a feeling of warmth, while the strong structure provides stability and seriousness.http://www.typoland.com/http://www.typoland.com/designers/Lukasz_Dziedzic/Copyright (c) 2013-2013 by tyPoland Lukasz Dziedzic (http://www.typoland.com/) with Reserved Font Name "Lato". Licensed under the SIL Open Font License, Version 1.1 (http://scripts.sil.org/OFL).http://scripts.sil.org/OFL C o p y r i g h t   ( c )   2 0 1 0 - 2 0 1 3   b y   t y P o l a n d   L u k a s z   D z i e d z i c   w i t h   R e s e r v e d   F o n t   N a m e   " L a t o " .   L i c e n s e d   u n d e r   t h e   S I L   O p e n   F o n t   L i c e n s e ,   V e r s i o n   1 . 1 . L a t o   L i g h t I t a l i c t y P o l a n d L u k a s z D z i e d z i c :   L a t o   L i g h t   I t a l i c :   2 0 1 3 L a t o - L i g h t I t a l i c V e r s i o n   1 . 1 0 5 ;   W e s t e r n + P o l i s h   o p e n s o u r c e L a t o   i s   a   t r a d e m a r k   o f   t y P o l a n d   L u k a s z   D z i e d z i c . L u k a s z   D z i e d z i c L a t o   i s   a   s a n s e r i f   t y p e f a c e   f a m i l y   d e s i g n e d   i n   t h e   S u m m e r   2 0 1 0   b y   W a r s a w - b a s e d   d e s i g n e r   L u k a s z   D z i e d z i c   ( " L a t o "   m e a n s   " S u m m e r "   i n   P o l i s h ) .   I t   t r i e s   t o   c a r e f u l l y   b a l a n c e   s o m e   p o t e n t i a l l y   c o n f l i c t i n g   p r i o r i t i e s :   i t   s h o u l d   s e e m   q u i t e   " t r a n s p a r e n t "   w h e n   u s e d   i n   b o d y   t e x t   b u t   w o u l d   d i s p l a y   s o m e   o r i g i n a l   t r a i t s   w h e n   u s e d   i n   l a r g e r   s i z e s .   T h e   c l a s s i c a l   p r o p o r t i o n s ,   p a r t i c u l a r l y   v i s i b l e   i n   t h e   u p p e r c a s e ,   g i v e   t h e   l e t t e r f o r m s   f a m i l i a r   h a r m o n y   a n d   e l e g a n c e .   A t   t h e   s a m e   t i m e ,   i t s   s l e e k   s a n s e r i f   l o o k   m a k e s   e v i d e n t   t h e   f a c t   t h a t   L a t o   w a s   d e s i g n e d   i n   2 0 1 0 ,   e v e n   t h o u g h   i t   d o e s   n o t   f o l l o w   a n y   c u r r e n t   t r e n d .   T h e   s e m i - r o u n d e d   d e t a i l s   o f   t h e   l e t t e r s   g i v e   L a t o   a   f e e l i n g   o f   w a r m t h ,   w h i l e   t h e   s t r o n g   s t r u c t u r e   p r o v i d e s   s t a b i l i t y   a n d   s e r i o u s n e s s . h t t p : / / w w w . t y p o l a n d . c o m / h t t p : / / w w w . t y p o l a n d . c o m / d e s i g n e r s / L u k a s z _ D z i e d z i c / C o p y r i g h t   ( c )   2 0 1 3 - 2 0 1 3   b y   t y P o l a n d   L u k a s z   D z i e d z i c   ( h t t p : / / w w w . t y p o l a n d . c o m / )   w i t h   R e s e r v e d   F o n t   N a m e   " L a t o " .   L i c e n s e d   u n d e r   t h e   S I L   O p e n   F o n t   L i c e n s e ,   V e r s i o n   1 . 1   ( h t t p : / / s c r i p t s . s i l . o r g / O F L ) . h t t p : / / s c r i p t s . s i l . o r g / O F L L a t o L i g h t   I t a l i c        X A                              	 
                        ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ 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    j i k m l n  o q p r s u t v w  x z y { } |    ~       	
                                                     !"#NULLuni00A0uni00ADmacronperiodcenteredAogonekaogonekEogonekeogonekNacutenacuteSacutesacuteZacutezacute
Zdotaccent
zdotaccentuni02C9EuroDeltauni2669undercommaaccent
grave.casedieresis.casemacron.case
acute.casecircumflex.case
caron.case
breve.casedotaccent.case	ring.case
tilde.casehungarumlaut.case
caron.salt                      _ K _ K    VV , `f-, d P&ZE[X!#!X PPX!@Y 8PX!8YY Ead(PX!E 0PX!0Y PX f a 
PX`  PX!
` 6PX!6``YYY +YY# PXeYY-, E %ad CPX#B#B!!Y`-,#!#! dbB #B*! C   +0%QX`PaRYX#Y! @SX +!@Y# PXeY-,C+  C`B-,#B#  #Bab`*-,  E EcEb`D`-,  E  +#%` E#a d  PX! 0PX @YY# PXeY%#aDD`-,EaD-	,`  	CJ PX 	#BY
CJ RX 
#BY-
,  b  c#aC` ` #B#-,KTXDY$e#x-,KQXKSXDY!Y$e#x-, CUXCaB
+Y C%B	%B
%B# %PX C`%B #a	*!#a #a	*! C`%B%a	*!Y	CG
CG`b EcEb`  #DC >C`B-, ETX #B `a  BB`+m+"Y-, +-,+-,+-,+-,+-,+-,+-,+-,+-,	+-,+ ETX #B `a  BB`+m+"Y-, +-,+-,+-,+-,+-,+- ,+-!,+-",+-#,	+-$, <`-%, `` C#`C%a`$*!-&,%+%*-',  G  EcEb`#a8# UX G  EcEb`#a8!Y-(, ETX '*0"Y-),+ ETX '*0"Y-*, 5`-+, EcEb +EcEb +      D>#8**-,, < G EcEb` Ca8--,.<-., < G EcEb` CaCc8-/, % . G #B%IG#G#a Xb!Y#B.*-0, %%G#G#aE+e.#  <8-1, %% .G#G#a #BE+ `PX @QX  &YBB# C #G#G#a#F`Cb`  + a C`d#CadPXCaC`Y%ba#  &#Fa8#CF%CG#G#a` Cb`#  +#C` +%a%b&a %`d#%`dPX!#!Y#  &#Fa8Y-2,    & .G#G#a#<8-3,  #B   F#G +#a8-4, %%G#G#a TX. <#!%%G#G#a %%G#G#a%%I%aEc# Xb!YcEb`#.#  <8#!Y-5,  C .G#G#a ` `fb#  <8-6,# .F%FRX <Y.&+-7,# .F%FPX <Y.&+-8,# .F%FRX <Y# .F%FPX <Y.&+-9,0+# .F%FRX <Y.&+-:,1+  <#B8# .F%FRX <Y.&+C.&+-;, %& .G#G#aE+# < .#8&+-<,%B %% .G#G#a #BE+ `PX @QX  &YBB# GCb`  + a C`d#CadPXCaC`Y%ba%Fa8# <#8!  F#G +#a8!Y&+-=,0+.&+->,1+!#  <#B#8&+C.&+-?,  G #B .,*-@,  G #B .,*-A, -*-B,/*-C, E# . F#a8&+-D,#BC+-E,  <+-F, <+-G, <+-H,<+-I,  =+-J, =+-K, =+-L,=+-M,  9+-N, 9+-O, 9+-P,9+-Q,  ;+-R, ;+-S, ;+-T,;+-U,  >+-V, >+-W, >+-X,>+-Y,  :+-Z, :+-[, :+-\,:+-],2+.&+-^,2+6+-_,2+7+-`, 2+8+-a,3+.&+-b,3+6+-c,3+7+-d,3+8+-e,4+.&+-f,4+6+-g,4+7+-h,4+8+-i,5+.&+-j,5+6+-k,5+7+-l,5+8+-m,+e$Px0-   K KRXY  c #D#pE  (`f UX%aEc#b#D***Y(	ERD*D$QX@XD&QX XDYYYY D          GPOSjN    KGSUBV.T  L  OS/28  M   `cmapRԟ  N@  cvt &7 g|   8fpgmzA g  	gasp    gt   glyfi  S(  headDeJ  ޼   6hheaix     $hmtxESvJ    Tkern2  l  llocaKp PP  ,maxp>
 R|    nameU R  :post:\ c  prepx9 qH       
 0 J DFLT latn                 kern kern                   Jn    v $R
^	h
B
l&rjZjL*|DV: !.!##L#$4$~%&J'$'()*+f+,6,-.(./t//0:0|2"233T334&4l455b566L667B778889d99:&::;@<=>j?,?@hABCzDEFG*GHfI K 	V  B  V # $V & * 2 4 9 7 : 7 <  ? 7 D F G H R T mB oB yB }B V V V V V V V                             V         B B   B B B V K 	V  B  V # $V & * 2 4 9 7 : 7 <  ? 7 D F G H R T mB oB yB }B V V V V V V V                             V         B B   B B B V " # & * 2 4 F G H R T                         K 	V  B  V # $V & * 2 4 9 7 : 7 <  ? 7 D F G H R T mB oB yB }B V V V V V V V                             V         B B   B B B V -  
  v # & * 2 4 7L 9L : <y ?L Y Z \ l mv ov r yv | }v        y   y v v     v v v  ' B 	 
B B v v  $ 7L 9 : ; <` = ? lB rB |B        `  `    B B v B B v B  -  
  v # & * 2 4 7L 9L : <y ?L Y Z \ l mv ov r yv | }v        y   y v v     v v v  k  7 	 
 7  7 G  G    " < # $ & * -o 2 4 D F G H I J{ P Q R S T U V W X Y [ \ ] l 7 m o r 7 t F u F w y { F | 7 }                                                  7  7 G  7  7 G     7  )  	 
      $ 7 9 ; < = ? @ ` l r |                      6 V 
V V  " # & * - - 2 4 7 8 9 : <t ? Y \ lV m o rV t` u` y {` |V }            t   t   V V V V    V 
 e me oe ye }e e e e e e )  	 
      $ 7 9 ; < = ? @ ` l r |                      4 	 L L    "  $ -. F G H P Q R S T U X w                              L L   	    $            1  # & * 2 4 F G H I R T W Y Z \ m o y }                              I  
   4 $  4 " # & * 2 4 7[ 9V :y <= ?V F G H R T Y Z \ l m$ o$ r tB uB y$ {B | }$        =                  = $ $    4    4 $ $ $  )  	 
      $ 7 9 ; < = ? @ ` l r |                      . 	    $ -V D F G H R T                                   )  	 
      $ 7 9 ; < = ? @ ` l r |                       # & * 2 4 7 8              [ 	 L L L  ` ` # $ & * -8 2 4 D F) G) H) J> P` Q` R) S` T) U` VD X` YL Zt [g \L ] mL oL w` yL }L                      ) ) ) ) ) ) ` ) ) ) ) ) ) ` ` ` `    ) ) `  ) L L L L L L L   	    $            k  7 	 
 7  7 G  G    " < # $ & * -o 2 4 D F G H I J{ P Q R S T U V W X Y [ \ ] l 7 m o r 7 t F u F w y { F | 7 }                                                  7  7 G  7  7 G     7  I  7 	 
 7  7     " % $ - D F G H J R T V l 7 m o r 7 t 7 u 7 y { 7 | 7 }                                   7  7   7  7      7  1  # & * 2 4 F G H I R T W Y Z \ m o y }                              i   	t 
    y ` y t   " % # $t & * -8 2 4 D F` G` H` J[ P Q R` S T` U V X Y Z [ \ l  m` o` r  t - u - w y` { - |  }` t t t t t t t               ` ` ` ` ` `  ` ` ` ` ` `     t   ` `   ` ` `     y     y ` ` `   t 0  " % # & * 2 4 F G H R T V Y \ m o y }                              " # & * 2 4 F G H R T                         6 V 
V V  " # & * - - 2 4 7 8 9 : <t ? Y \ lV m o rV t` u` y {` |V }            t   t   V V V V    V   
  Y Z \ l r t u { |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        K 
 K  K y y l K r K t d u d { d | K  K  K y  K  K y  K   
  Y Z \ l r t u { |       F G H R T                  
  Y Z \ l r t u { |        
  Y Z \ l r t u { |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |         D           $ 	    $ F G H R T                                 F G H R T                $ 	    $ F G H R T                           " # & * 2 4 F G H R T                         K 	V  B  V # $V & * 2 4 9 7 : 7 <  ? 7 D F G H R T mB oB yB }B V V V V V V V                             V         B B   B B B V ' B 	 
B B v v  $ 7L 9 : ; <` = ? lB rB |B        `  `    B B v B B v B  ' B 	 
B B v v  $ 7L 9 : ; <` = ? lB rB |B        `  `    B B v B B v B  )  	 
      $ 7 9 ; < = ? @ ` l r |                      K 	V  B  V # $V & * 2 4 9 7 : 7 <  ? 7 D F G H R T mB oB yB }B V V V V V V V                             V         B B   B B B V  	` ` $` 9 F : F < ( ? F ` ` ` ` ` ` `  ( `  ( `  	` ` $` 9 F : F < ( ? F ` ` ` ` ` ` `  ( `  ( ` ' B 	 
B B v v  $ 7L 9 : ; <` = ? lB rB |B        `  `    B B v B B v B   	` ` $` 9 F : F < ( ? F ` ` ` ` ` ` `  ( `  ( ` K 	V  B  V # $V & * 2 4 9 7 : 7 <  ? 7 D F G H R T mB oB yB }B V V V V V V V                             V         B B   B B B V ' B 	 
B B v v  $ 7L 9 : ; <` = ? lB rB |B        `  `    B B v B B v B  6 V 
V V  " # & * - - 2 4 7 8 9 : <t ? Y \ lV m o rV t` u` y {` |V }            t   t   V V V V    V 6 V 
V V  " # & * - - 2 4 7 8 9 : <t ? Y \ lV m o rV t` u` y {` |V }            t   t   V V V V    V 6 V 
V V  " # & * - - 2 4 7 8 9 : <t ? Y \ lV m o rV t` u` y {` |V }            t   t   V V V V    V 6 V 
V V  " # & * - - 2 4 7 8 9 : <t ? Y \ lV m o rV t` u` y {` |V }            t   t   V V V V    V 6 V 
V V  " # & * - - 2 4 7 8 9 : <t ? Y \ lV m o rV t` u` y {` |V }            t   t   V V V V    V 6 V 
V V  " # & * - - 2 4 7 8 9 : <t ? Y \ lV m o rV t` u` y {` |V }            t   t   V V V V    V 
 e me oe ye }e e e e e e )  	 
      $ 7 9 ; < = ? @ ` l r |                      )  	 
      $ 7 9 ; < = ? @ ` l r |                      )  	 
      $ 7 9 ; < = ? @ ` l r |                      )  	 
      $ 7 9 ; < = ? @ ` l r |                      )  	 
      $ 7 9 ; < = ? @ ` l r |                      )  	 
      $ 7 9 ; < = ? @ ` l r |                       	    $             	    $             	    $             	    $            i   	t 
    y ` y t   " % # $t & * -8 2 4 D F` G` H` J[ P Q R` S T` U V X Y Z [ \ l  m` o` r  t - u - w y` { - |  }` t t t t t t t               ` ` ` ` ` `  ` ` ` ` ` `     t   ` `   ` ` `     y     y ` ` `   t )  	 
      $ 7 9 ; < = ? @ ` l r |                        
  Y Z \ l r t u { |        
  Y Z \ l r t u { |        
  Y Z \ l r t u { |        
  Y Z \ l r t u { |        
  Y Z \ l r t u { |        
  Y Z \ l r t u { |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
  Y Z \ l r t u { |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |      6 V 
V V  " # & * - - 2 4 7 8 9 : <t ? Y \ lV m o rV t` u` y {` |V }            t   t   V V V V    V   
  Y Z \ l r t u { |      
 e me oe ye }e e e e e e   
   9 : ? @ Y [ \ ` l r |        t 
t t o 9j : <y ?j Y \ lt mo oo rt t u yo { |t }o y y o o t t t t o o o t   
  Y Z \ l r t u { |        
   9 : ? @ Y [ \ ` l r |      i   	t 
    y ` y t   " % # $t & * -8 2 4 D F` G` H` J[ P Q R` S T` U V X Y Z [ \ l  m` o` r  t - u - w y` { - |  }` t t t t t t t               ` ` ` ` ` `  ` ` ` ` ` `     t   ` `   ` ` `     y     y ` ` `   t 0  " % # & * 2 4 F G H R T V Y \ m o y }                              0  " % # & * 2 4 F G H R T V Y \ m o y }                              0  " % # & * 2 4 F G H R T V Y \ m o y }                              ' B 	 
B B v v  $ 7L 9 : ; <` = ? lB rB |B        `  `    B B v B B v B  ' B 	 
B B v v  $ 7L 9 : ; <` = ? lB rB |B        `  `    B B v B B v B  K 	V  B  V # $V & * 2 4 9 7 : 7 <  ? 7 D F G H R T mB oB yB }B V V V V V V V                             V         B B   B B B V K 	V  B  V # $V & * 2 4 9 7 : 7 <  ? 7 D F G H R T mB oB yB }B V V V V V V V                             V         B B   B B B V -  
  v # & * 2 4 7L 9L : <y ?L Y Z \ l mv ov r yv | }v        y   y v v     v v v  K 	V  B  V # $V & * 2 4 9 7 : 7 <  ? 7 D F G H R T mB oB yB }B V V V V V V V                             V         B B   B B B V K 	V  B  V # $V & * 2 4 9 7 : 7 <  ? 7 D F G H R T mB oB yB }B V V V V V V V                             V         B B   B B B V -  
  v # & * 2 4 7L 9L : <y ?L Y Z \ l mv ov r yv | }v        y   y v v     v v v  ' B 	 
B B v v  $ 7L 9 : ; <` = ? lB rB |B        `  `    B B v B B v B  ' B 	 
B B v v  $ 7L 9 : ; <` = ? lB rB |B        `  `    B B v B B v B  ' B 	 
B B v v  $ 7L 9 : ; <` = ? lB rB |B        `  `    B B v B B v B  K 	V  B  V # $V & * 2 4 9 7 : 7 <  ? 7 D F G H R T mB oB yB }B V V V V V V V                             V         B B   B B B V 6 V 
V V  " # & * - - 2 4 7 8 9 : <t ? Y \ lV m o rV t` u` y {` |V }            t   t   V V V V    V  v  
       # $ & ' ) - . / 2 3 4 5 7 8 9 : ; < = > ? D E H I K N P Q R S U Y Z [ \ ^ l m o p r t u y { | }                                                                  
 8  DFLT latn                     case &case ,liga 2liga 8sups >sups D                                        ,     >  B 	
  @       L  O  ,  { t u   C j q v          I         ,   x  x   D  P `K        tyPL @  Jz                              & 
                                                                          	 
                        ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ 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                                    r d e i  x  p k  v j    s g w      l |     c n     m }  b                    y                        q    z    `   T @      ~ 1DS[a~    " & 0 : D !"!&"""""""+"H"`"e%&i        1ARZ`x      & 0 9 D !"!&"""""""+"H"`"d%&i {uq[H$I޸ޡޞ:ڜ                                                                                      `   T @      ~ 1DS[a~    " & 0 : D !"!&"""""""+"H"`"e%&i        1ARZ`x      & 0 9 D !"!&"""""""+"H"`"d%&i {uq[H$I޸ޡޞ:ڜ                                                                                         /   ' 3 7 ;  BK	PX@3 	` f    [  [ 		Q C Q D@4 h f    [  [ 		Q C Q DY@;:$$#,$
+>32#'&>54.#"#"'4632#"&!!7!!3<G*6]E'!1:3%
A 1;2"/?#.B.{,! ,, !,]#[n$;S47O;-('rz/**5C/$8' ..  ..y$?        &@#   QC S D    +#.54>32#"&tA1!""'5-PS\88\SP-<""!5     ) 
  ,@) B  Q D   
 
$+#"&/!#"&/		u		ܙ$ܙ$  V  < 6 : 5BK-PX@( Y	CQ
C   D@&
Z Y	C   DY@  :987 6 6421/-,(&#"!#!+#"&547!+#"&5<?3#76;>;!323+32%!!^)VV*^R(W*_*_*W(R*REm	
&!Fp&!{,F  
\ ; F Q @)
!
LA*7 BKPX@2 j 

h 
f   _ 

SC	 T   D@1 j 

h 
f  k 

SC	 T   DY@NMCB;965$#$+.'7632.54>?>;#".'+4.'>H	&4EX8 De>4e_	$e?
'?]A/_WJ7:mf$2Tm<P}U,,Lc8LqL&bP'!'#|4QwZEe>K?"!(% (4G[<VsFB\@+7Yu>X?-(0K`    W  ' 0 D X ?@<    [  	[ C S C C 		S DUS((%"&((($
+#".54>324.#"32>>;+#".54>324.#"32>0Rl<>mP..Pm>>lQ/L#=Q--P<##<P--Q=#eCD0Ql<>mP..Pm>>lQ.L#<Q--Q<##<Q--Q<#3WX--XWXY--YXMnG!!GnMMmF!!Fm
PWX--XWXY--YXMoG!!GoMMmF  Fm  jT @ R S@PN9K*$B h f  S  C C S D GE0.'%!
 @@+2#"&'.#">7>;#"&/#".54>7.54>32>7&'CxY5":W;<bF'TX-57C>*Y-l~OKsG4Z|HGG3^;^s8F}m[&5BkJ(.Ng8D<*%C\7RVHHI^[4X?$2aZHmVPVFwX2MrM& 9N/N_n      
 @ B   Q D   
 
$+#"&/		ܙ$      (+.54>7yx*Mi@@iM*wyve
vuuv
e   b  (+4'&54?'&5476Zyw*Lj@@jL*xyv
vuuv
  { 5 1@.1-,($#	 B   M   Q E   5 5+5467'7>7./7.=3>?'.'t4	m,n
n-n
	m-m	
n-n	    m   ,@) M  YQ E    +!!#!5!iQNR=I;I     n   @ B?   S D"+74632'&5467>7#"&n0'+/(8"
	%/U#2;0)URL 	

'5@$2   d)5z  @   M   Q  E+!!d/zQ     i"   @   S D($+74>32#"&i!""'5M""!5   @   k D""++6;[ 'n')-%     I?  ' @ S C  S    D((($+#".54>324.#"32>?PiiOOiiPdBoRRpBBpRRoBĺWWWWHHGG        *@'
B   h C  R D%+%!47#"/3!!5E
	J5'J|"&	(iJ      2 >@;.Bh  S  C Q D -,+)$" 22+2>3!2!5467>54.#"#"&#'>ZQpB1To=E E#co<fK+4Wq>CqW9
0Kr/_`P~w><8"=rtzENsJ$)Ie<#[b3    H U@RD
B h h  [  S  C S D B@;910/.&$ HH	+2#".'763232>54.#5>54.#"#"/>eQm?+Kf<Fzayh:&#4KeBZ[-)`s\^02Tp=CpV:1Jr-ZXEoT9Wl=Ah@
599-<]s6ApQ/E-NlAKnH"(He>#[b3   ?  ^    @  [ C D!#+!+#!"&/3467![Ve	UV^4j/&    / @@=-,B h  [   Q C S D(#&(#"+#!>32#".'763232>54.#"'! UCx7nq:Nd;j^N
1MiFRi;-[^9H>o|^(?q\p|B#.'$5d]L[3s    0 2@/B   [ C S D -+#!	 +2#".54676;>32>54.#"t[o?E{gcu@T`"TZ4;1ZQVa43]NX`2N<m``vB@xmSт)H#=E]Oa66_MQ[1=a|      /  @ QC    D    #'++67!"&=/wA+	 =     x ' ; O D@A
B [ S C S   D=<)( GE<O=O31(;); ''	+".54>7.54>32'2>54.#"2>54.#"DfyD-RqD>`A"9j_^k9"B`>DqR.DyfQ`4Dj<<jD4_QQwN%*QuKKvQ*%Nw6fZNzZ<>Vi<Kb88bK<iV><ZzNZf6L-StG]|JJ|]GtS-1Sj9=iN,,Ni=9jS1         2 2@/B   [ S C D /-%#	 +".54>32+>74.#"32>=Wk<Cxb^q?-@)"V3:"2Z{IN]40W{KU\/Z9j\[rA@ud7ddi<H*K#@FM[32Z}KN}W.:^u   J  # ;K#PX@ S C   S D@   [   S DY(&($+74>32#"&4>32#"&!""'5!""'5M""!5D""!5   J  - H@
(B?K#PX@  S   C S D@    [ S DY,*$($+4>32#"&4632'&5467>7#"&!""'50'+/(8"
	%/j""!5#2;0)URL 	

'5@$2    	5  (+!'*)A		A  e   !@   Y   M   Q  E+!!!!;;,JJ  	5   (+546767.'&=*("	A	A)     ! ( : 9@6 B h f  S   C S D(&#-$+>32#'54>54.#"#"'4>32#"&!DQ`8F|]7/HTI3A0GSG0*H^3BaB&!""'52'*NqFLnS?78")>:<KbC6U;#+#i""!5    l3 N a f@c
U
8B   h  [  

[	  [ O S GPO YWOaPaFD<:641/'% NN+%"&'#".54>3232>54.#"3267632#"$&546$32%2>7.#"XY8R8R6A}t5]%[%09hP/a}mqd
pzvq:e$MG>P3"Zg9(;]W]S'D\5UV.I,7 <obݒHj]DA%JPi%wSmHF?kS6IvK(E2       $@!B   Z C   D# +!#"&'!+3!.'OINCfze{++    z   * =@:B [  S   C SD  *("   !+3!2#!2654.#%!2>54&#!yt9'JkE@zqc3`Y3bY*0]U8hXAZd5CkK(K2Rh7   | 2 D@A B   h  f S C S D ,*" 	 22+%2#".54>32#".#"32>7>
(,h{XbeMob/	+=TnF؜WVyLwdV*	+/K5g
i+@*-%Y뒖W(:'      y   @ S C  S    D!(!$+#!!24.#!!2>ybbjRҀcҕRĤbbTT    "  .@+  Y   QC Q D    +!!!!!"lUSU     " 	 (@%  Y   QC D   	 	+!!!#"{gUUv   |C 4 H@E! B h   [ S C  S D ,*%# 44+%2>7!"&=!#".546$32#"'.#"2Ixg]/5rYddQvf/		9ahޝUVC+}	8	%:'gg+?),,0&X쓖X          @   YC   D+!#!#3!3gggvgZl      ^  @ C    D+!#3^gg    Y  '@$ B h C  S    D#'$+#"&'>7>3232>53;mb-\1	#-LzV-gw|?	0cf     " &@# B    [CD'(' +32>7>;#"&'.+#3VT;S!S [ff	KXdV        @ C   R D+%!!38fWW     H   %@" B   h  CD!5(+>7>;#47+"'#32z,GZYF; y#J(         @  CD!+2&53#"'#3	Z1hY26yY  {  ' @ S C  S    D((($+#".54>324.#"32>bccbjRҀ~їSS~ҕRĤgghgWW씕VV      S   *@'  [ S C    D    !+#!2#%!2>54&#!VfmEu^g7:]q?R4\}J    {  0 T@
BKPX@ S C S C    D@   k S C S DY(((%&+#"&'#".54>324.#"32>+PsHpV ?NccbjRҀ~їSS~ҕRk~-vFghgWW씕VV       " 2@/B  [ S C   D  "   *!+#!2#"&'.#'32>54&#!Vfi8i]Y;')^g6ƽQeA
>L-TvJ   W = =@:= B   h f S C S D;9(&!#!+#".#"#"&'763232>54.54>32~	)FiMMuO)=dd==tlL	(8J`=T[0=dd=6hbnH%-&,Ld7H^B-,5PuWYtCcV,#)#3XyEKaA,*4Qy[Ge=FH     #  n   @  QC D    +!#!5nfW0W       #@ C  S D  +%2>53#".53fp;fJ||ǋJg;oIG~cku˗VVukc~H       @ B  C D* +3267>;#QP[j.46,y        '  @# B  CD,; +32>7>;2>7>;#&'#Ue	
eNC\^][u..u,-y4      @  B  CD(")!+	32>7>;	#"&'+e
beB
J]LT%	        @  BC    D,"+#32>7>;gYZHH?v++  s    $@! QC   Q D    +!!547!5~#U%U    '@$    [ O QE    !#+!+32>$$   @  k    D" +32#"&')'n' %"    k  !@   [   O   Q  E!"+46;#"&=!!k=s$       @
 B k    D,!+3#"&'.'+ <UD		G
L     3  @  M Q   E    +!5DD   V 	 @  k   D  		+2#"&/6
   kC ' 7 T@Q-B h  [ S C  C	S D)( /.(7)7" 	 ''
+!"/#".54>754&#"#"/>32%2>7)QXf=3`J-HwuHeF,
NmPxO(J:aSH#ͅ?!6H(@,>aD?lP0h(0(NP3_Sx5->$#<S52I/      # K%PX@B@BYK%PX@   CS C SD@!   CS CC S DY@  ##  &#+33>32#"&'#"32>54&`Bm9oih6hc?9ZXY-XfmPQOzf[VE@ub    XX , 9@6, B   h f S C S D(&#(#"+#".#"32>32#".54>321	
#:W>V[01ZNHa?%FXg8_q?<sla8^ =reio:"("
 4&EyrK>5  W  # q@ BK%PX@ C S C S   D@! C S C  CS DY@ ## +!"/#"&54>323%267.#"c
Bn9oie6`^c?:XXY-ZjmPKHNQ@f[UF@ub   X % 0 H@EB h  [ S  C S D'& ,+&0'0	 %%	+2#!32>32#".54>"!4.Ti;14`TKnK,
Oao8fxA=skMzY7	,Pp:oips:!)!
 4%GkJG0Z~NPX/    n  _BK!PX@S C  QCD@  [S CDY@    !$%!	+3'&=354>32#"&#"!!ǌ,PqD?)1S<!C{	'~UV+
.@gK{G  K : P d @3B+BKPX@,
 [  [ C  S	  C S D@/   h
 [  [  S	  C S DY@RQ \ZQdRdMKA?$" ::+23#"'#".5467.54>7.54>4.'32>2>54.#"Ao,4]OVF*0<cc<>ugik6h[2; -GO3]1Rkuv3&A.-W~RLa7@dD#$Ec??dE$$Ed !&_6HuS.B+.-QC>rX5+I`6Or@9.-()[HuT./9 	'1;#,K7 ">V.%B\88]B$$B]88\B%         -@*B   C S CD    ##+33>32#4&#"_EnR}R*_bBUe4bW|eX     G   &@# S CC    D  
  +##".54>32_    W!!    G  ' 4@1	 B S CC S    D  $"  !$%+#"&'76323265#".54>32;Y<.QN    4XA%
0XQbW!!       0@- B    [C CD    %(%!+3267>;#"&'.+#.TI
S^-`{_


      @C    D    +#_Q      , 8@5 +B   CSCD   , ,##&&!	+332>32>32#4&#"#4&#"4	BKU/mATc4JvS,`~u4_I+_toQ6)D1q>Z;1`Z|&KpJ|aV        1@. B   C S CD    #$!+332>32#4&#"4	DoR}R*_bBVi4bW|eX  W  ' ,@)  S  CS D ''	 +2#".54>2>54.#"kt==tkku==ukYY,,YYYY--YIuuHHuuIK=rdcs>>scdr=       $ D@A B   CS C S CD  $$  &%!+32>32#"&'"32>54&4	Bn9nif6Bc>9YXY-CZjmPJIg\VF@ub   W  # D@ABC S CS C    D  ##  &#+##"&54>32763267.#"`Bl9oig6	c?6YXY-XfmPNLp]f[RH@ub         8@5 B h   C S CD    #$%!+332>32#".#"20u-L"!0q-yB
y   Y < =@:< B   h f S C S D:8'%" #!+#".#"#"&'7>3232>54.54>32#9S<6Y?#0NchcN0/YSi<&=[C?`@!0NcicN0.UzL[;h4E&/>,  ':T<ApR0C6" % #<Q-2B.  &:S>5bJ,46  4@ # x@
!BKPX@% j hQC  S   D@# j h[  S   DY@ 
	 ##	+"&5#"&=7>;!!32>32eq-9%2$4&&upu%d	G]);&
**3    -@* BC C   S D    $!#+32673#"/#".5逃aC`5	EoS|R*cXVh4bW|        @
 BC    D,!+!#32>7>;T\KH

	JH	*+       *  @# B  CD*!); +32>76;2>76;#"'.'+I'		FFC	**-*+(     #  v  @  B  CD("(!+	3267>;	#"&'+[$
Xj[
UZ	h	     @ BC    D,""++32>7>;{D[OO	KI	     J  :  @ Q C   Q D+!!547!5!:d)qK&MK   ? H 3@0* B  [    [ O S G@>;83-+4.#52>54.54>;+";2#".54>):##:)&HiB7!+G3)55)3G+!7BiH&!7)=)7!7hhi8=hM+*8P19lii5%>./=%5ijl81P8*+Mh=8ihh Q  @   Q D+3#KK  i H 5@2B  [  [   O  S   GEDCB530-3)++546;2>54.54>7.54>54.+"&=323"}&HiB7	!+G3)55)3G+!	7BiH&)9##9)7hhi8=hM+*8P18lji5%=/.>%5iil91P8*+Mh=8ihh7!7)=)7     9@6 j k   [  O  S  G 
 +2>53#".#"#4>32%=*N <X83kib+&;*M <W84khb70B'7^F('0'0B'7^F('0'      &@# S C   QD    +4>734632#"&A5'""'5&-PS\88\SP-'5""7   0 ; U@R6&, B j h f  k S C  T   D##'#	+.54>?>;#".'>32+M`r>@{s
$W5		!7P8+KfC'EXh:
$/Y}N,\a3JtpM:.!"' 1%bo@i?q  C  Q : @@=3)B   h  [ S C S D#&#%&%"	+46;4>32#"'.#"!#!>3!#!5>5#C4gfLtW>&	->V<NuP(?H?+6"@2&]uC%@V0;.4]O'Yy+(A(:N4F    D # 7 9@6!B @ ?  W  S   D42*((+467'7>327'#"&''7.732>54.#"($1-n?>m-1$*)$2-n>>m-1$)H+Ic88cJ++Jc88cI+>m-2$*)$2-n?>m-2$)($2-n?8bI++Ib88cJ++Jc  U  (   8@5	 B 
 Z	YC D *!+!3267>;!!!!#!5!5!ZZOZ	YPY[n_nhg#!':v:~:v Q   @    Y Q D+3#3#KKKK    }k H \ A@>H ZP= #B   h f  W S DFD-+(&!#!+#".#"#"&'7>3232>54.5467.54>32>54.'(#9S<8[@#2RhmhR2TR6C/YSi<&>\D>`B"4VmqmV4[g7E.UzL[;'CX`c-G>$=QZ]+YJ5F'.D7.07F]>S{#&bEApR0C6" % "<Q/3L;004EY=M{%%cJ6aK,55)A5-*+ `=-F7,)'&^   '"W  ' 3KPX@  S D@  O S  GY((($+#".54>32#".54>32W   U , H \ @
 BKPX@4   h   f  [  [ 		S C S DKPX@4   h   f  [  [ 		S C S D@4   h   f  [  [ 		S C S DYY@YW*,((#&(%!
+632#".54>32#".#"3264>32#".732>54.#"8;t`s@Cxc4WJ@
!:[DSa55^MU{S4]dd]44]dc]4;ghhg
;FAvfdwB)!5bWZa3)Pc^44^cd^44^dhhii     j>5 & 4 B@? ,B h  [  W S D('.-'4(4$##' 	+#"&/#".54>754&#"#"/>322>755 

15=$!<.*]iDI+;(0jCeh!81+!*GD$%9'$A13LO0-ub"D8'      % %(+55	
	
z
	
{z
	
  S  =K	PX@ _   M   Q  E@ k   M   Q  EY+!#!=R'     d)5z  @   M   Q  E+!!d/zQ     U  / F O :BKPX@/h  		[ 
[  S   C S DKPX@/h  		[ 
[  S   C S D@/h  		[ 
[  S   C S DYY@00OMIG0F0E)!(*,&+4>32#".732>54.#"#32#"&'.#'32654&+U4]dd]44]dc]4;ghhgUu	P
nywlvc^44^cd^44^dhhiiyusvd
_@a[\T  5%  @   M   Q  E+!!!%A     [D  ' @  W  S   D((($+4>32#".732>54.#"[/Qn??nQ//Qn??nQ/G$>T00T=$$=T00T>$n>mQ..Qm>>lQ//Ql>0T>$$>T00T?$$?T    m P   7@4  Y Y M Q E    	+!!#!5!!!iQNRRUjInII   a;W - g@
+BK#PX@ h   [ S D@! h   [ O Q EY@ (&#! --+2>3!2!546?>54.#"#"&/>V,N9!*8'&1%'4>H|W1I0(E?;*89< #4"G7`f     b|=W ? @=BKPX@, h h   [  [ S D@1 h h   [  [ O S GY@ ;964.-,+#! ??	+2#".'7>3232>54.#5>54.#"#"/>\,L7 H<IM%@V0<Q7!$;-)>).J5[Y'3?I{W/C+BWTB0M73C$(%*4!4%1K?"2!A;`f   	 @   kD   	 #++7>39
     0@- BC   SC D    &$!#+32673#"/#"&'#"&5逃aC`5	Ffb%0cXX\MH+X$     6B  *@'   hi  S D    +##!#".54>3UVgr==rgRy8bMP\2  o  @   O   S  G($+4>32#".$&&$P&&%%      V@ BK	PX@  ^  j T D@  j  j T DY@  +232654.'73#"&'76(390A'*=Y]1D()N
,&!`<;0!    5R  O	BKPX@ j  j  Q  D@ j  j  M  R  FY$+37#"/733!:%~	c1  W;   )@& W  S  D 	 +2#".54>2654&#"wBjJ''JjBDjK''KjDhiihkii*OoEEoO**OoEEoO*rqqr       ) ' (+7'&547>7.'&54?'&547>7.'&54?	&%		&%	     q   # - O@L! 	B h 	 	Z
  [C SD-+(&#"$!"+%3+#5!"/3%37#"/733!47!+>;~m?`C:( 
*$ #%~	c1w}d      K - = G e@b710+B h h 		Z   [C S
D GEB@=<;:9853/.(&#! --+2>3!2!546?>54.#"#"&/>%37#"/733!+>;f,N9!*8'&1%'4>I|:( 
*1I0(E?;*89< #4"@>`f%~	c1bd   S  q  P U _]@N	
$S BK	PX@B 

h 		h 
 	
	[   [  \ SC SDKPX@B 

h 		h 
 	
	[   [  \ SC SDKPX@B 

h 		h 
 	
	[   [  \ SC SD@B 

h 		h 
 	
	[   [  \ SC SDYYY@!_]ZXUTKHEC=<;:20)' PP!"+%3+#5!"/32#".'7>3232>54.#5>54.#"#*.'>47!+>;~m?`CZ,L7 H<IM%@V0<Q7!$;-)>).J5[Y'3>J	{( 
*$ /C+BWTB0M73C$(%*4!4%1K?"2!G5`f}d  * ) ; 5@2 B h f S C  T    D('#-$+#".54>?332>324>32#"&DQ`8E}]70GTJ3A0GTG0*H^3E_@$
		!""'52')MoGLkM924#*<45E]B6U;#+#O""!5     & $   	[     & $   [     & $   `     & $   `     & $   
`     & $   `        4@1  Y  Y  Q   C SD"	+!!!!!!!+!HjK8O iUSUc7.  | O h@e<B M	B h f
  h S C SC 	S 			D KIA@:820(&! OO+232654.'7.54>32#".#"32>7>32#"&'76(390A'$ZeMob/	+=TnF؜WVyLwdV*	
(,eyUY]1D()N
,&!sn
i+@*-%Y뒖W(:'+.J5K<;0!     "& (   	Z     "& (   Z     "& (   _     "& (   
_     & ,   	      N& ,         E& ,   	      N& ,   
	     1    ! ,@)  Y S C S D!%(!+3!2#!#%4.#!!!!2>1bbRҀclҕRbbT@T     & 1      {& 2   	   {& 2      {& 2      {& 2      {& 2   
     D  	(+		'	7	t34u5pn4t4vp6o     { ! - 9 b@21&%BKPX@  k C S C  S    D@ j  k S C  S    DY**%(%$+#"&'+7&54>327>;.#"4&'32>bsQ ,lwcySo7eo$^UGj~їSrVNEdҕRĤg=9`hC?`갠R9<W씘R35V  & 8   	   & 8      & 8      & 8   
     & <   /      S   .@+  [  [ C    D    !+#3!2#%!2>54&#!VffEu^g7]q?R4\}J   ' J >@;B h  S  C C S D ED?='%"  JJ+2#"&'7>3232>54.54>54.#"#4>UZ./GRG/!7EIE7!2Z~Me<%<Y?;\?!;XfX;0ITI0?fIG}^6_Bu3Qd2>\G87:%$1$!)<S;DrR-C6" % #=R/CQ4&1K?1H>:DS8I?*+X^eo;   kC& D    C    kC& D    v    kC& D        kCi& D        kCW& D    j    kC& D         k B R ] @:@BK1PX@5 h h
[ S	  CSD@? h h
[ S	  C SC SDY@&TS YXS]T]NLDC><7520-,$"	 BB+2#!32>32#"&'#".54>754&#"#"&/>32>32>5"!4.K`7
l0X|LGdD&
JZe4/Uly7?lP.HwuHeF,Mk~/ͅ?!<R1BtW2HsR1V(He<sopr:!'!
4%MjBBhI@qV6E)0)
NPpo(BY58O2,U|O+4^RU]1  XX G h@e6: E	B h f
  h S C SC 	S 			D CA9842/-%#  GG+232654.'7.54>32#".#"32>32#"&'76(390A'%Wg8<sla8	
#:W>V[01ZNHa?%-jY]1D()N
,&!vKsrK>5" =reio:"("
 :NO<;0!  X& H    C    X& H    v    X& H        XW& H    j    "  V&     C      &     v     &          W&     j     Y} 6 J 6@3<2B65@  [ S    D87B@7J8J.,$"+&54?.'.546?7#".54>32.'2>7.#"~<J
ZNr?iM*9rs[wD:og5kcV n9X\2;XvLXY-7_}.

m!/<0d/zuWAyl`I9X<K-Et3fP2<jR]d5   i& Q       W& R    C    W& R    v    W& R        Wi& R        WW& R    j     m _   # +@(   [    Y O S G($(#+!!4632#"&4632#"&mUy5'""'55'""'5I'7#!5_'7#!5     W&   , 6 =@:54%$
 B j  k S C S    D.--6.6'%($'+#"'+7.54>327>;.#"2>54'h<>=tklQ!&DF=ukX7W2/0-vKY[.iYZ.P
WiCvuHOmCuI1-th9*,?s>rds]E & X    C    & X    v    & X        W& X    j    & \    v       ! @@=B   CS C S CD  !!  &#+3>32#"&'"32>54&_Bm9nif6Bc>9YXY-XgmPNLg\VF@ub  W& \    j     c & / O@L,BA  h  Z CC S D ('#! &&	+2#"&54>7&'!+3"32>!.'F
T/L^'1INCfC23&@2&z"KB92*ey/A'05++    k B R n@k-H	6B h
  h  		[ S CS C S DDC JICRDR?=1/*(%#  BB+2#"&54>7&/#".54>754&#"#"&/>3232>2>7
T/L^)4
)QXf=3`J-HwuHeF,NmPxO(.(@2&:aSH#ͅ?!6H"KB ;3+	(@,>aD?lP0h(0(
NP3_Sx"-705(->$#<S52I/  |& &      XX& F    v     A ' T@Q	B
 	 	h  Y Q C QC 		S D $" ''+2#"&54>7!!!!!!#32>$
T/L^&1RPl[.(@2&"KB82+USU"-705    X C N g@d2B h  h 
 
[		S C SC S DED JIDNEN@>0.+)$" CC+2#"&54>7"#".54>32#!32>3232>"!4.
T/L^!+
fxA=sjTi;14`TKnK,
7EP*,&@2&MzY7	,Pp"KB4/)GkJ:oips:!)!
 *"",5050Z~NPX/        @C    D    +#_   :    #@   B C   R D+%!!54?3crf?WKeB
]  9    #@ 
 BC    D    +7#54?[_Y2TZ4Tv      & 1        & Q    v    {7   4 @
 
BKPX@+  Y  S C  Q C	SDK%PX@)  Y S C   Q C	SDK)PX@3  Y S C   Q C	Q C	S D@1  Y S C   Q C Q C 		S DYYY@1/%(%
+!!!!!#".54>32!4.#"32>7l%k]ߠYY߇]k%EJsrKKrsJ2SUNRY/f
h0ZRM=XX씕WW  WW 2 F Q a@^.
B h 
 
[	 S  CSDHG43 MLGQHQ><3F4F,*" 	 22+2#!32>32#"&'#".54>32>2>54.#""!4.K`7l0Y|LCcE)JZe4,*Ĕbm::mc*E^xZR{R))R{RS|S))S|?HsR1W(Ie<sopr:!)!
 4%HuuIBjL)K=rdcs>>scdr=n4^RU]1   W & 6      Y& V    v    W& 6      Y& V          & <   
4   s  & =   h   J  :& ]    v    s  & =   k   J  :& ]        s  & =   k   J  :& ]         v # 2@/Y S C  S    D   # #""	+#543>7'&=37>3#"!{`DlX$3`N7
_ض$5`N7
eb\+0 FpR

'3FpRG     (  @ B  k D* +#"/&'+73(ACU   (  @ B  k   D' +32?>;# CAU    5% q    5   @   WD 
 +".5332>53$B[9E(A00A)E9['DZ2%B22B%2ZD'     }  @   S  D($+#".54>32}    F!!   xs   =K'PX@  W  S   D@    [ O S GY$&($+4>32#".732654&#"x/?##?//?##?/:@32@@23@$<++<$$;,,;$2@@22@@     +@(B @  j S D  +2#"&54>732>
T/L^-81.(@2&"KB"=6,"-705     &*i  QKPX@  W SD@  [  O  S GY@ 
 +2673#".#"#4>32+,;%6"!;63*,=&6"";53 7/$?.!'!9-$?.!'!    | 	  #@   S D

  

 	 #++7>3!+7>3*R/

   .s  \BK1PX@  SCSD@  SC CS DY@    !$##	++#!#"&'7632325#5463s_,mi4	$e=nt	'"  f  @   M   Q  E+!!fG     f  @   M   Q  E+!!fG     !.   (+.5467L=&2#!&K&N;3d6;=  n   (+'&547>54'&547L=&2#&K&N;2e6:=  n     (+7'&547>54'&547L=&2#&K&N;2e6:=   !;  )  (+.5467.5467L=&2#L=&2#!&K&N;3d6;=&K&N;3d6;=   n'  )  (+'&547>54'&547%'&547>54'&547L=&2#JL=&2#&K&N;2e6:=&K&N;2e6:=  n '   )  (+7'&547>54'&547%'&547>54'&547L=&2#JL=&2#&K&N;2e6:=&K&N;2e6:=     @ BKPX@ C  CSC DK%PX@Z C  C D@  `Z C DYY@
#!""+463632>72!#"'!MSRN    - @&"	BKPX@/	

	` 
	 
[ CCSC DK%PX@-	

	` Z 
	 
[ CC D@/`	

	` Z 
	 
[ C DYY@+)('%#! !"#+7!!5463632>72!!#.'#"'"&5|MSRN}NRSM  B    1i|  @   O   S  G($+4>32#"..Pj<=lP..Pl=<jP.T=lQ..Ql=<iP..Pi  i   # 5 @  SD(&(&($+74>32#"&%4>32#"&%4>32#"&i!""'5!""'5!""'5M""!5'""!5'""!5    Wz  ' 0 D X l  K@H    [	[ C S C C		S
D}{sqig_]US((%"&((($+#".54>324.#"32>>;+#".54>324.#"32>%#".54>324.#"32>0Rl<>mP..Pm>>lQ/L#=Q--P<##<P--Q=#eCD0Ql<>mP..Pm>>lQ.L#<Q--Q<##<Q--Q<# 0Ql<>mP..Pm>>lQ.L#<Q--Q<##<Q--Q<#3WX--XWXY--YXMnG!!GnMMmF!!Fm
PWX--XWXY--YXMoG!!GoMMmF  FmMWX--XWXY--YXMoG!!GoMMmF  Fm      (+5	
z
	
      (+7'&547>7.'&54?	&%	    6   	 @ C    D#"+'+>;k( 
*d  o N [@X;	B   h 		h  [	[ S C 
S 


DNMHGFEA?97$##%'$+3>32#".#"!#!!#!32>32#".'#53.547#Zn@m]Q%
"1CY:ZqJZHpZ>_H4$	
	%$TfxFqT_ҒN,A+#%?zv/2'|~@%+%	#.K5Nً;'10     HH  # C@@
 B h S	  C S	  D##!4%
+67>;#7+"'#32###5	
9>?9
	WGl,z*E?x;;     h  } 7 1@.1 B   S CSD   7 6***+!>54.#"!"&=!5.54>32!#c`r>VooŔV>q`byDe뇇eDxbkOwg~~??~~gwO4\mؖOO؉m\4     { . B C@@ 4B h  [  S   CS D0/:8/B0B#+(($+>32#".54>32>54&#"#"&'2>7.#"$CCG(W_2GԌQ`5Iq5cVD1K8%
MRoO
+GeEbk9(If=#H~6f[rɖV9W;;5-
&Gy3cN/IdKvR+          @ B   C R D+3!7!&'^\M
*ySz!+&   M  $@!  QCD    +##!##5bbRkkR    W  &@#B  Q   C Q D+!!!!547	&5W{[`RR$1.    z  @   M   Q  E+!!=I     (    "@ B j    [ D*# +#"&=!267>;#5:
:O
.)%'I     J ' ; O L@IK-B[
	  O
	 S  G=<)( GE<O=O31(;);	 ''+".'#".54>32>32%2>7.#"!2>54.#"7\NCCN[79hO//Oh97[NCCN\79hO//OhF,KB;;BK,,M:!!:M+M9!!9M+-KB;;BK(BW//VC(+PsGGrP+(CW..WC(+PrGGsP+N&@S--T@&:V78V::V87V:&@T--S@& K ) *@' B  S   CS D!%)U$+>32#"&#"#"&'7>3232>7
:Vo@'94XC-	?]xE!A

"<`G/
>WU++
 DgHcZ*	'	 GqQ     / d@a  ('B   [   [  [	O	S G ,*%# // 
+267#".#"'>32267#".#"'>324Xd84ec`.7Wc<4fc_.4Xd84ec`.7Wc<4fc_*-:+/$,$-8-0$,$-:+.$,$-8-/$,$      p  kK	PX@)   ^ _ 	 ZMQE@'  j k 	 ZMQEY@
+!3!!!!#!5!7!uGth@vHvThDeJJJ      PO   !@	  @   M   Q  E+!!''%v>	?xI     PO   !@
 @   M  Q   E+5467>7.'.=!5!&&&(?>I    f   "@
  B   M   Q  E+3	#	>7	.'BnBL		N	
@@S       @   C D+3#     k  aBK!PX@S C  QC	D@  [S C	DY@    !$%!
+3'&=354>32#"&#"!#!ǌ6g_!G+!G`{	'U\g7
0
R<}      " K!PX@ SC  QC	DK1PX@  [ SC	D@!  [ C S C	DYY@   " "A15!
+3'&=354>32;#.#"!!ǌ4d`"IE<H_6w0KvQ+ {	'AXn>nO/Y~NAG  R  @  j D 
 +2+:	 0["6M6      	 @  j a  		+2#"&'%tG
	    2E  % @  O S  G&(($+#".54>32#".546320!!1   U5q  @   M   Q  E+!!Uaq<     J 	 @ j   a   	 #++7>3J
F	    <  @ B  j  a, +#"&/.'+73<IJZ{{  <  @ B  j a, +32>?>;#J	IZ{{   2  (@%j   O  S  G 
 +"&5332653$|v@R``R@vpfGQQGbt     8{  @   O  S   G($+#".54>32{    }   !@    [ O S G$&($+4>32#".732654&#"}-="">-->""=-5@32@@23@^";**;"#:**:#2@@22@@  *)  1@.  [  O  S G 
 +2673#".#"#4>32*,6"5"!<85*+8$4""<84P7+#;- % 8*"<- %     j 	  +@(  O S  G

  

 	 #++7>3!+7>3/q4		   m  @  k   D 
 +2+U	 3#;U<.      U_<     ʓ^p    ӡ6z   	          V  6:z                /             V  Wg j X X b  { m n d i I    ?    x       !k l	   |  x  | V  Y(    ; { ; {  W # 	     sX X k   I V kD  XD W X  K:    7 : : W. D W \ Y 4:    #  JX ?XX i      C  UX I 'M U jj   dM UI  [ m a bI :  6 I   Wj    S *	 	 	 	 	 	 7 |    V V V V ' 1 ; {; {; {; {; { ; {        k k k k k kI k X X X X X " 0 Y: : W: W: W: W: W m: W: : : :  .  	  k | X  X * :X 9 :  { W: W\ Y W\ Y  s J s J s J vI  I  I I 5I I xI I &I | .: 7   n n  n n  ` i Wk k 6  H h { T MT W c (T J       * l I I I I UI I I I 2I I }I *I jI      l #`    	V    B    V  #  $V  &  *  2  4  9 7  : 7  <   ? 7  D  F  G  H  R  T  mB  oB  yB  }B  V  V  V  V  V  V  V                                                         V                 B  B      B  B  B  V 
 	V 
  
 B 
  
 V 
 # 
 $V 
 & 
 * 
 2 
 4 
 9 7 
 : 7 
 <  
 ? 7 
 D 
 F 
 G 
 H 
 R 
 T 
 mB 
 oB 
 yB 
 }B 
 V 
 V 
 V 
 V 
 V 
 V 
 V 
  
  
  
  
  
  
  
   
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
 V 
  
  
  
  
  
  
   
 B 
 B 
  
  
 B 
 B 
 B 
 V  #  &  *  2  4  F  G  H  R  T                                                  	V    B    V  #  $V  &  *  2  4  9 7  : 7  <   ? 7  D  F  G  H  R  T  mB  oB  yB  }B  V  V  V  V  V  V  V                                                         V                 B  B      B  B  B  V    
    v  #  &  *  2  4  7L  9L  :  <y  ?L  Y  Z  \  l  mv  ov  r  yv  |  }v                y      y  v  v          v  v  v    B  	  
B  B  v  v    $  7L  9  :  ;  <`  =  ?  lB  rB  |B                `    `        B  B  v  B  B  v  B      
    v  #  &  *  2  4  7L  9L  :  <y  ?L  Y  Z  \  l  mv  ov  r  yv  |  }v                y      y  v  v          v  v  v     7  	  
 7   7  G    G        " <  #  $  &  *  -o  2  4  D  F  G  H  I  J{  P  Q  R  S  T  U  V  W  X  Y  [  \  ]  l 7  m  o  r 7  t F  u F  w  y  { F  | 7  }                                                                                                   7   7  G   7   7  G         7   #  # 	 # 
 #  #  #  #  #  # $ # 7 # 9 # ; # < # = # ? # @ # ` # l # r # | #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  $ V $ 
V $ V $  $ " $ # $ & $ * $ - - $ 2 $ 4 $ 7 $ 8 $ 9 $ : $ <t $ ? $ Y $ \ $ lV $ m $ o $ rV $ t` $ u` $ y $ {` $ |V $ } $  $  $  $  $  $  $  $  $  $  $  $ t $  $  $ t $  $  $ V $ V $ V $ V $  $  $  $ V & e & me & oe & ye & }e & e & e & e & e & e '  ' 	 ' 
 '  '  '  '  '  ' $ ' 7 ' 9 ' ; ' < ' = ' ? ' @ ' ` ' l ' r ' | '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  ) 	 ) L ) L )  )  )  ) "  ) $ ) -. ) F ) G ) H ) P ) Q ) R ) S ) T ) U ) X ) w )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  ) L ) L )  - 	 -  -  -  - $ -  -  -  -  -  -  -  -  -  -  -  .  . # . & . * . 2 . 4 . F . G . H . I . R . T . W . Y . Z . \ . m . o . y . } .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  /  / 
 /  /  4 / $ /  4 / " / # / & / * / 2 / 4 / 7[ / 9V / :y / <= / ?V / F / G / H / R / T / Y / Z / \ / l / m$ / o$ / r / tB / uB / y$ / {B / | / }$ /  /  /  /  /  /  /  / = /  /  /  /  /  /  /  /  /  /  /  /  /  /  /  /  /  / = / $ / $ /  /  /  4 /  /  /  4 / $ / $ / $ /  2  2 	 2 
 2  2  2  2  2  2 $ 2 7 2 9 2 ; 2 < 2 = 2 ? 2 @ 2 ` 2 l 2 r 2 | 2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  3 	 3  3  3  3 $ 3 -V 3 D 3 F 3 G 3 H 3 R 3 T 3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  4  4 	 4 
 4  4  4  4  4  4 $ 4 7 4 9 4 ; 4 < 4 = 4 ? 4 @ 4 ` 4 l 4 r 4 | 4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  5 # 5 & 5 * 5 2 5 4 5 7 5 8 5  5  5  5  5  5  5  5  5  5  5  5  5  7 	 7 L 7 L 7 L 7  7 ` 7 ` 7 # 7 $ 7 & 7 * 7 -8 7 2 7 4 7 D 7 F) 7 G) 7 H) 7 J> 7 P` 7 Q` 7 R) 7 S` 7 T) 7 U` 7 VD 7 X` 7 YL 7 Zt 7 [g 7 \L 7 ] 7 mL 7 oL 7 w` 7 yL 7 }L 7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7  7 ) 7 ) 7 ) 7 ) 7 ) 7 ) 7 ` 7 ) 7 ) 7 ) 7 ) 7 ) 7 ) 7 ` 7 ` 7 ` 7 ` 7  7  7  7 ) 7 ) 7 ` 7  7 ) 7 L 7 L 7 L 7 L 7 L 7 L 7 L 7  8 	 8  8  8  8 $ 8  8  8  8  8  8  8  8  8  8  8  9  7 9 	 9 
 7 9  7 9 G 9  9 G 9  9  9  9 " < 9 # 9 $ 9 & 9 * 9 -o 9 2 9 4 9 D 9 F 9 G 9 H 9 I 9 J{ 9 P 9 Q 9 R 9 S 9 T 9 U 9 V 9 W 9 X 9 Y 9 [ 9 \ 9 ] 9 l 7 9 m 9 o 9 r 7 9 t F 9 u F 9 w 9 y 9 { F 9 | 7 9 } 9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  7 9  7 9 G 9  7 9  7 9 G 9  9  9  9  7 9  :  7 : 	 : 
 7 :  7 :  :  :  :  : " % : $ : - : D : F : G : H : J : R : T : V : l 7 : m : o : r 7 : t 7 : u 7 : y : { 7 : | 7 : } :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  7 :  7 :  :  7 :  7 :  :  :  :  :  7 :  ;  ; # ; & ; * ; 2 ; 4 ; F ; G ; H ; I ; R ; T ; W ; Y ; Z ; \ ; m ; o ; y ; } ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  <   < 	t < 
  <   < y < ` < y < t <  <  < " % < # < $t < & < * < -8 < 2 < 4 < D < F` < G` < H` < J[ < P < Q < R` < S < T` < U < V < X < Y < Z < [ < \ < l  < m` < o` < r  < t - < u - < w < y` < { - < |  < }` < t < t < t < t < t < t < t <  <  <  <  <  <  <  <  <  <  <  <  <  <  < ` < ` < ` < ` < ` < ` <  < ` < ` < ` < ` < ` < ` <  <  <  <  < t <  <  < ` < ` <  <  < ` < ` < ` <   <   < y <   <   < y < ` < ` < ` <   < t =  = " % = # = & = * = 2 = 4 = F = G = H = R = T = V = Y = \ = m = o = y = } =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  > # > & > * > 2 > 4 > F > G > H > R > T >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  ? V ? 
V ? V ?  ? " ? # ? & ? * ? - - ? 2 ? 4 ? 7 ? 8 ? 9 ? : ? <t ? ? ? Y ? \ ? lV ? m ? o ? rV ? t` ? u` ? y ? {` ? |V ? } ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ? t ?  ?  ? t ?  ?  ? V ? V ? V ? V ?  ?  ?  ? V D  D 
 D  D Y D Z D \ D l D r D t D u D { D | D  D  D  D  D  E  E 
 E  E  E 9 E : E ? E @ E Y E [ E \ E ` E l E r E | E  E  E  E  E  H  H 
 H  H  H 9 H : H ? H @ H Y H [ H \ H ` H l H r H | H  H  H  H  H  I  K I 
 K I  K I y I y I l K I r K I t d I u d I { d I | K I  K I  K I y I  K I  K I y I  K K  K 
 K  K Y K Z K \ K l K r K t K u K { K | K  K  K  K  K  N F N G N H N R N T N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  P  P 
 P  P Y P Z P \ P l P r P t P u P { P | P  P  P  P  P  Q  Q 
 Q  Q Y Q Z Q \ Q l Q r Q t Q u Q { Q | Q  Q  Q  Q  Q  R  R 
 R  R  R 9 R : R ? R @ R Y R [ R \ R ` R l R r R | R  R  R  R  R  S  S 
 S  S  S 9 S : S ? S @ S Y S [ S \ S ` S l S r S | S  S  S  S  S  U  U  U D U  U  U  U  U  U  U  U  U  U  Y 	 Y  Y  Y  Y $ Y F Y G Y H Y R Y T Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Z  Z  Z  Z  [ F [ G [ H [ R [ T [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  \ 	 \  \  \  \ $ \ F \ G \ H \ R \ T \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  ^ # ^ & ^ * ^ 2 ^ 4 ^ F ^ G ^ H ^ R ^ T ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  l 	V l  l B l  l V l # l $V l & l * l 2 l 4 l 9 7 l : 7 l <  l ? 7 l D l F l G l H l R l T l mB l oB l yB l }B l V l V l V l V l V l V l V l  l  l  l  l  l  l  l   l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l V l  l  l  l  l  l  l   l B l B l  l  l B l B l B l V m B m 	 m 
B m B m v m v m  m $ m 7L m 9 m : m ; m <` m = m ? m lB m rB m |B m  m  m  m  m  m  m  m ` m  m ` m  m  m  m B m B m v m B m B m v m B m  o B o 	 o 
B o B o v o v o  o $ o 7L o 9 o : o ; o <` o = o ? o lB o rB o |B o  o  o  o  o  o  o  o ` o  o ` o  o  o  o B o B o v o B o B o v o B o  p  p 	 p 
 p  p  p  p  p  p $ p 7 p 9 p ; p < p = p ? p @ p ` p l p r p | p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  r 	V r  r B r  r V r # r $V r & r * r 2 r 4 r 9 7 r : 7 r <  r ? 7 r D r F r G r H r R r T r mB r oB r yB r }B r V r V r V r V r V r V r V r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r V r  r  r  r  r  r  r   r B r B r  r  r B r B r B r V t 	` t ` t $` t 9 F t : F t < ( t ? F t ` t ` t ` t ` t ` t ` t ` t  ( t ` t  ( t ` u 	` u ` u $` u 9 F u : F u < ( u ? F u ` u ` u ` u ` u ` u ` u ` u  ( u ` u  ( u ` y B y 	 y 
B y B y v y v y  y $ y 7L y 9 y : y ; y <` y = y ? y lB y rB y |B y  y  y  y  y  y  y  y ` y  y ` y  y  y  y B y B y v y B y B y v y B y  { 	` { ` { $` { 9 F { : F { < ( { ? F { ` { ` { ` { ` { ` { ` { ` {  ( { ` {  ( { ` | 	V |  | B |  | V | # | $V | & | * | 2 | 4 | 9 7 | : 7 | <  | ? 7 | D | F | G | H | R | T | mB | oB | yB | }B | V | V | V | V | V | V | V |  |  |  |  |  |  |  |   |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | V |  |  |  |  |  |  |   | B | B |  |  | B | B | B | V } B } 	 } 
B } B } v } v }  } $ } 7L } 9 } : } ; } <` } = } ? } lB } rB } |B }  }  }  }  }  }  }  } ` }  } ` }  }  }  } B } B } v } B } B } v } B }   V  
V  V    "  #  &  *  - -  2  4  7  8  9  :  <t  ?  Y  \  lV  m  o  rV  t`  u`  y  {`  |V  }                        t      t      V  V  V  V        V  V  
V  V    "  #  &  *  - -  2  4  7  8  9  :  <t  ?  Y  \  lV  m  o  rV  t`  u`  y  {`  |V  }                        t      t      V  V  V  V        V  V  
V  V    "  #  &  *  - -  2  4  7  8  9  :  <t  ?  Y  \  lV  m  o  rV  t`  u`  y  {`  |V  }                        t      t      V  V  V  V        V  V  
V  V    "  #  &  *  - -  2  4  7  8  9  :  <t  ?  Y  \  lV  m  o  rV  t`  u`  y  {`  |V  }                        t      t      V  V  V  V        V  V  
V  V    "  #  &  *  - -  2  4  7  8  9  :  <t  ?  Y  \  lV  m  o  rV  t`  u`  y  {`  |V  }                        t      t      V  V  V  V        V  V  
V  V    "  #  &  *  - -  2  4  7  8  9  :  <t  ?  Y  \  lV  m  o  rV  t`  u`  y  {`  |V  }                        t      t      V  V  V  V        V  e  me  oe  ye  }e  e  e  e  e  e    	  
            $  7  9  ;  <  =  ?  @  `  l  r  |                                              	  
            $  7  9  ;  <  =  ?  @  `  l  r  |                                              	  
            $  7  9  ;  <  =  ?  @  `  l  r  |                                              	  
            $  7  9  ;  <  =  ?  @  `  l  r  |                                              	  
            $  7  9  ;  <  =  ?  @  `  l  r  |                                              	  
            $  7  9  ;  <  =  ?  @  `  l  r  |                                            	        $                        	        $                        	        $                        	        $                           	t  
      y  `  y  t      " %  #  $t  &  *  -8  2  4  D  F`  G`  H`  J[  P  Q  R`  S  T`  U  V  X  Y  Z  [  \  l   m`  o`  r   t -  u -  w  y`  { -  |   }`  t  t  t  t  t  t  t                              `  `  `  `  `  `    `  `  `  `  `  `          t      `  `      `  `  `        y        y  `  `  `     t    	  
            $  7  9  ;  <  =  ?  @  `  l  r  |                                              
    Y  Z  \  l  r  t  u  {  |              
    Y  Z  \  l  r  t  u  {  |              
    Y  Z  \  l  r  t  u  {  |              
    Y  Z  \  l  r  t  u  {  |              
    Y  Z  \  l  r  t  u  {  |              
    Y  Z  \  l  r  t  u  {  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
    Y  Z  \  l  r  t  u  {  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |            V  
V  V    "  #  &  *  - -  2  4  7  8  9  :  <t  ?  Y  \  lV  m  o  rV  t`  u`  y  {`  |V  }                        t      t      V  V  V  V        V    
    Y  Z  \  l  r  t  u  {  |            e  me  oe  ye  }e  e  e  e  e  e    
      9  :  ?  @  Y  [  \  `  l  r  |            t  
t  t  o  9j  :  <y  ?j  Y  \  lt  mo  oo  rt  t  u  yo  {  |t  }o  y  y  o  o  t  t  t  t  o  o  o  t    
    Y  Z  \  l  r  t  u  {  |              
      9  :  ?  @  Y  [  \  `  l  r  |               	t  
      y  `  y  t      " %  #  $t  &  *  -8  2  4  D  F`  G`  H`  J[  P  Q  R`  S  T`  U  V  X  Y  Z  [  \  l   m`  o`  r   t -  u -  w  y`  { -  |   }`  t  t  t  t  t  t  t                              `  `  `  `  `  `    `  `  `  `  `  `          t      `  `      `  `  `        y        y  `  `  `     t    " %  #  &  *  2  4  F  G  H  R  T  V  Y  \  m  o  y  }                                                              " %  #  &  *  2  4  F  G  H  R  T  V  Y  \  m  o  y  }                                                              " %  #  &  *  2  4  F  G  H  R  T  V  Y  \  m  o  y  }                                                            B  	  
B  B  v  v    $  7L  9  :  ;  <`  =  ?  lB  rB  |B                `    `        B  B  v  B  B  v  B    B  	  
B  B  v  v    $  7L  9  :  ;  <`  =  ?  lB  rB  |B                `    `        B  B  v  B  B  v  B    	V    B    V  #  $V  &  *  2  4  9 7  : 7  <   ? 7  D  F  G  H  R  T  mB  oB  yB  }B  V  V  V  V  V  V  V                                                         V                 B  B      B  B  B  V  	V    B    V  #  $V  &  *  2  4  9 7  : 7  <   ? 7  D  F  G  H  R  T  mB  oB  yB  }B  V  V  V  V  V  V  V                                                         V                 B  B      B  B  B  V    
    v  #  &  *  2  4  7L  9L  :  <y  ?L  Y  Z  \  l  mv  ov  r  yv  |  }v                y      y  v  v          v  v  v    	V    B    V  #  $V  &  *  2  4  9 7  : 7  <   ? 7  D  F  G  H  R  T  mB  oB  yB  }B  V  V  V  V  V  V  V                                                         V                 B  B      B  B  B  V  	V    B    V  #  $V  &  *  2  4  9 7  : 7  <   ? 7  D  F  G  H  R  T  mB  oB  yB  }B  V  V  V  V  V  V  V                                                         V                 B  B      B  B  B  V    
    v  #  &  *  2  4  7L  9L  :  <y  ?L  Y  Z  \  l  mv  ov  r  yv  |  }v                y      y  v  v          v  v  v    B  	  
B  B  v  v    $  7L  9  :  ;  <`  =  ?  lB  rB  |B                `    `        B  B  v  B  B  v  B    B  	  
B  B  v  v    $  7L  9  :  ;  <`  =  ?  lB  rB  |B                `    `        B  B  v  B  B  v  B    B  	  
B  B  v  v    $  7L  9  :  ;  <`  =  ?  lB  rB  |B                `    `        B  B  v  B  B  v  B    	V    B    V  #  $V  &  *  2  4  9 7  : 7  <   ? 7  D  F  G  H  R  T  mB  oB  yB  }B  V  V  V  V  V  V  V                                                         V                 B  B      B  B  B  V  V  
V  V    "  #  &  *  - -  2  4  7  8  9  :  <t  ?  Y  \  lV  m  o  rV  t`  u`  y  {`  |V  }                        t      t      V  V  V  V        V       ""J"<bn6 2	(	z	

,
R
~Zv@~FFFr*zTTV`PrNNJl 
 ^!B!!"$">##&#n#$"$$%.%d%%&.&t&'0'))r)~)))))*********++T+`+l+x++++,P,\,h,t,,,-P-\-h-t---.x///(/4/@/L/X/d/p/0000&020>01 111$101<1122223<334*4\4h4t5<5556666(646@6L6X6d66777D7n778R88899>9d99::V:;t;;<<= =>=>4>??F?p???@@A^AAB6BxBBCbCCCDD.D\DDDE$EhEE      `   " / n   	                       
                (        
        (        
        0        %      	 %      
4              2(       Z         	  6  	  J  	  ^  	  Pl  	    	  P  	    	  `   	    	 	   	 
  	  0V  	  d  	   	  4n  	    	  
Copyright (c) 2010-2013 by tyPoland Lukasz Dziedzic with Reserved Font Name "Lato". Licensed under the SIL Open Font License, Version 1.1.Lato LightRegulartyPolandLukaszDziedzic: Lato Light: 2013Version 1.105; Western+Polish opensourceLato-LightLato is a trademark of tyPoland Lukasz Dziedzic.Lukasz DziedzicLato is a sanserif typeface family designed in the Summer 2010 by Warsaw-based designer Lukasz Dziedzic ("Lato" means "Summer" in Polish). It tries to carefully balance some potentially conflicting priorities: it should seem quite "transparent" when used in body text but would display some original traits when used in larger sizes. The classical proportions, particularly visible in the uppercase, give the letterforms familiar harmony and elegance. At the same time, its sleek sanserif look makes evident the fact that Lato was designed in 2010, even though it does not follow any current trend. The semi-rounded details of the letters give Lato a feeling of warmth, while the strong structure provides stability and seriousness.http://www.typoland.com/http://www.typoland.com/designers/Lukasz_Dziedzic/Copyright (c) 2013-2013 by tyPoland Lukasz Dziedzic (http://www.typoland.com/) with Reserved Font Name "Lato". Licensed under the SIL Open Font License, Version 1.1 (http://scripts.sil.org/OFL).http://scripts.sil.org/OFL C o p y r i g h t   ( c )   2 0 1 0 - 2 0 1 3   b y   t y P o l a n d   L u k a s z   D z i e d z i c   w i t h   R e s e r v e d   F o n t   N a m e   " L a t o " .   L i c e n s e d   u n d e r   t h e   S I L   O p e n   F o n t   L i c e n s e ,   V e r s i o n   1 . 1 . L a t o   L i g h t R e g u l a r t y P o l a n d L u k a s z D z i e d z i c :   L a t o   L i g h t :   2 0 1 3 L a t o - L i g h t V e r s i o n   1 . 1 0 5 ;   W e s t e r n + P o l i s h   o p e n s o u r c e L a t o   i s   a   t r a d e m a r k   o f   t y P o l a n d   L u k a s z   D z i e d z i c . L u k a s z   D z i e d z i c L a t o   i s   a   s a n s e r i f   t y p e f a c e   f a m i l y   d e s i g n e d   i n   t h e   S u m m e r   2 0 1 0   b y   W a r s a w - b a s e d   d e s i g n e r   L u k a s z   D z i e d z i c   ( " L a t o "   m e a n s   " S u m m e r "   i n   P o l i s h ) .   I t   t r i e s   t o   c a r e f u l l y   b a l a n c e   s o m e   p o t e n t i a l l y   c o n f l i c t i n g   p r i o r i t i e s :   i t   s h o u l d   s e e m   q u i t e   " t r a n s p a r e n t "   w h e n   u s e d   i n   b o d y   t e x t   b u t   w o u l d   d i s p l a y   s o m e   o r i g i n a l   t r a i t s   w h e n   u s e d   i n   l a r g e r   s i z e s .   T h e   c l a s s i c a l   p r o p o r t i o n s ,   p a r t i c u l a r l y   v i s i b l e   i n   t h e   u p p e r c a s e ,   g i v e   t h e   l e t t e r f o r m s   f a m i l i a r   h a r m o n y   a n d   e l e g a n c e .   A t   t h e   s a m e   t i m e ,   i t s   s l e e k   s a n s e r i f   l o o k   m a k e s   e v i d e n t   t h e   f a c t   t h a t   L a t o   w a s   d e s i g n e d   i n   2 0 1 0 ,   e v e n   t h o u g h   i t   d o e s   n o t   f o l l o w   a n y   c u r r e n t   t r e n d .   T h e   s e m i - r o u n d e d   d e t a i l s   o f   t h e   l e t t e r s   g i v e   L a t o   a   f e e l i n g   o f   w a r m t h ,   w h i l e   t h e   s t r o n g   s t r u c t u r e   p r o v i d e s   s t a b i l i t y   a n d   s e r i o u s n e s s . h t t p : / / w w w . t y p o l a n d . c o m / h t t p : / / w w w . t y p o l a n d . c o m / d e s i g n e r s / L u k a s z _ D z i e d z i c / C o p y r i g h t   ( c )   2 0 1 3 - 2 0 1 3   b y   t y P o l a n d   L u k a s z   D z i e d z i c   ( h t t p : / / w w w . t y p o l a n d . c o m / )   w i t h   R e s e r v e d   F o n t   N a m e   " L a t o " .   L i c e n s e d   u n d e r   t h e   S I L   O p e n   F o n t   L i c e n s e ,   V e r s i o n   1 . 1   ( h t t p : / / s c r i p t s . s i l . o r g / O F L ) . h t t p : / / s c r i p t s . s i l . o r g / O F L L a t o L i g h t         Z D                              	 
                        ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ 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    j i k m l n  o q p r s u t v w  x z y { } |    ~       	
                                                     !"#NULLuni00A0uni00ADmacronperiodcenteredAogonekaogonekEogonekeogonekNacutenacuteSacutesacuteZacutezacute
Zdotaccent
zdotaccentuni02C9EuroDeltauni2669undercommaaccent
grave.casedieresis.casemacron.case
acute.casecircumflex.case
caron.case
breve.casedotaccent.case	ring.case
tilde.casehungarumlaut.case
caron.salt                      b K b K    VV , `f-, d P&ZE[X!#!X PPX!@Y 8PX!8YY Ead(PX!E 0PX!0Y PX f a 
PX`  PX!
` 6PX!6``YYY +YY# PXeYY-, E %ad CPX#B#B!!Y`-,#!#! dbB #B*! C   +0%QX`PaRYX#Y! @SX +!@Y# PXeY-,C+  C`B-,#B#  #Bab`*-,  E EcEb`D`-,  E  +#%` E#a d  PX! 0PX @YY# PXeY%#aDD`-,EaD-	,`  	CJ PX 	#BY
CJ RX 
#BY-
,  b  c#aC` ` #B#-,KTXDY$e#x-,KQXKSXDY!Y$e#x-, CUXCaB
+Y C%B	%B
%B# %PX C`%B #a	*!#a #a	*! C`%B%a	*!Y	CG
CG`b EcEb`  #DC >C`B-, ETX #B `a  BB`+m+"Y-, +-,+-,+-,+-,+-,+-,+-,+-,+-,	+-,+ ETX #B `a  BB`+m+"Y-, +-,+-,+-,+-,+-,+- ,+-!,+-",+-#,	+-$, <`-%, `` C#`C%a`$*!-&,%+%*-',  G  EcEb`#a8# UX G  EcEb`#a8!Y-(, ETX '*0"Y-),+ ETX '*0"Y-*, 5`-+, EcEb +EcEb +      D>#8**-,, < G EcEb` Ca8--,.<-., < G EcEb` CaCc8-/, % . G #B%IG#G#a Xb!Y#B.*-0, %%G#G#aE+e.#  <8-1, %% .G#G#a #BE+ `PX @QX  &YBB# C #G#G#a#F`Cb`  + a C`d#CadPXCaC`Y%ba#  &#Fa8#CF%CG#G#a` Cb`#  +#C` +%a%b&a %`d#%`dPX!#!Y#  &#Fa8Y-2,    & .G#G#a#<8-3,  #B   F#G +#a8-4, %%G#G#a TX. <#!%%G#G#a %%G#G#a%%I%aEc# Xb!YcEb`#.#  <8#!Y-5,  C .G#G#a ` `fb#  <8-6,# .F%FRX <Y.&+-7,# .F%FPX <Y.&+-8,# .F%FRX <Y# .F%FPX <Y.&+-9,0+# .F%FRX <Y.&+-:,1+  <#B8# .F%FRX <Y.&+C.&+-;, %& .G#G#aE+# < .#8&+-<,%B %% .G#G#a #BE+ `PX @QX  &YBB# GCb`  + a C`d#CadPXCaC`Y%ba%Fa8# <#8!  F#G +#a8!Y&+-=,0+.&+->,1+!#  <#B#8&+C.&+-?,  G #B .,*-@,  G #B .,*-A, -*-B,/*-C, E# . F#a8&+-D,#BC+-E,  <+-F, <+-G, <+-H,<+-I,  =+-J, =+-K, =+-L,=+-M,  9+-N, 9+-O, 9+-P,9+-Q,  ;+-R, ;+-S, ;+-T,;+-U,  >+-V, >+-W, >+-X,>+-Y,  :+-Z, :+-[, :+-\,:+-],2+.&+-^,2+6+-_,2+7+-`, 2+8+-a,3+.&+-b,3+6+-c,3+7+-d,3+8+-e,4+.&+-f,4+6+-g,4+7+-h,4+8+-i,5+.&+-j,5+6+-k,5+7+-l,5+8+-m,+e$Px0-   K KRXY  c #D#pE  (`f UX%aEc#b#D***Y(	ERD*D$QX@XD&QX XDYYYY D          pFFTMfh    OS/2r  x   `cmap_ce  X  cvt  q     "fpgmY7  `  sgasp     glyf'b    headu      6hhea;  4   $hmtxzpF    ~loca  <  vmaxpS  X    nameqB  P  ;dpost6z   3prep&#     A    Z½jV_<         v               v                   : V  j       
       X   X   KX  ^ 2   	             ADBE @ "  `                M      X       W U  *   z T U  U  c G b E 9 ' 8 M F D C   x U k m 1   g B U s  5 O _ Q b  Q S 0 f 1 d C * O + 
 6 & A  c c o <  Q ] P < E g H ] Z 7 j Q < ] < ] <  H E M 3  @ 1 G x c L    q M : 5 [    S U U p   U    M H     a   ' {             B s s s s _ _ _ _  S 0 0 0 0 0 f - O O O O & e X Q Q Q Q Q Q  P E E E E Z Z Z Z < ] < < < < < U < M M M M 1 ] 1   Q   Q   Q B P B P B P B P U 3  < s E s E s E s E s E 5 H 5 H 5 H 5 H O 
 
  _ Z _ Z _ Z _ Z _ Z Q 7 b j j  Q  Q  Q  + 5 Q S ] S ] S ] 0 < 0 < 0 < !  d  d t d  C H C H C H C H * E * E O M O M O M O M O M O M 
  & 1 & A G A G A G  > 1 0 < O M   Q _ Z 0 < O M O M O M O M O M 5 H 0 < C H * E 7  ^ < ] = ? E < M . ? 6 3  1     R                                  l  #                       U < U < 5 H O ] O ]  Q C Q  Q Q < S ] S ] S ] d  d  d M C H C H * E * E 
  
  
  & 1 A G E O & 1 & 1 & 1 & 1 P     _ g g                             ` N / + m : + T ` l 8 U                                                               4    ~1Ie~7CRTYaeoy$(.1CIMPRX[!%+;Ico    " : D q y          ""        4Lh7CPTXaeoy #&.1CGMORV[ $*6BZl    " 9 D p t }         "" wnl@%
 zsrmkZWTSROM
zjbRJHE?}zuigfc_]Z                                                                                                                                                                                      
                                                                     	 
                        ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ 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                                     t f g k z  r m   x l       u     i y           n ~      e p  ?     o    d       6       {                    v s}~ |w    ,K 	PXY D 	 _^- ,  EiD`- , *!- , F%FRX#Y  Id F had%F hadRX#eY/  SXi  TX!@Yi  TX!@eYY:- , F%FRX#Y F jad%F jadRX#Y/- ,K &PXQXD@DY!! EPXD!YY- ,  EiD`  E}iD`- , *- ,K &SX@ Y &SX#!#Y &SX#! #Y &SX#! #Y &SX#!@#Y  &SX%EPX#!#!%E#!#!Y!YD- 	,KSXED!!Y-  + ++@6*! + M@2$ + +  E}iDK`RX Y     D V   3  > ~                    8 D $4>td`HDP		B		

R

:4~D XR$&vLj Vb LV`Vj

8
dpx *2,6@H      0 @ P       !B!N!Z!f!r!~!!!!!"
"""".":"F"t"### #,#8#|#$$$$($4$@$%%%%(%4%@%L%X%d%%&&& &,&8&x' '''$'0'<''''''(b))))&)2)>)J)V)b)n)z)**"*.*:*F*R*^*+H+T+`+l+x++++++++,@,,,,,,,-X---....*.|........//l/x/////0&020>0J0V0b0n01h1t111111111112222(242@2L2X2d2p2|222223 333333333444 45
5h56H6777*767B7N7Z7f7r7~7777777778`888999T9:H:;8;;<<<===>4>p>?8??@@F@@AA
A0AVA^AfAAAAAAAAAAABBhBBBC C8CLCzCCCD(DJDhDDDE EERE~EEFFFjFG"GfHHDHHI2I|IIJ.JpJJJJJJJJJK
KK"K.K<KLKXKdKpK|KKKKKKKKKKLLLL(L4L@LLLXLdLpL|LLLLLLLLLLMhMtMMMMMMMMMNN:NDNPN\NjNNNNNOO$O.O8OBOLOVO`OjOOOOOOOOOPPPP PbQQRLRS$ST4TU&UUVVVJVlVVW8WWXXXXY Y2YFYfYYYZ Z4Z^ZZZ[ [@[[[\D\\]
] ]N    u   -   EX /  >Y  EX /  >Y 	ܸ 01'3#4632#"&P
8-++++@^^#))#$**    `&   s     W        EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y    +    +  
и и  и и  и и  и 017#537#53733733#3##7##7#OVU[55QWV]669::9     U  1 G  / ,/ +ܹ    ܺ   +9 и    ! + 9 + .01.#"#5.'732654.546753"(3;/GRG//A'<8d#'&[9<=/FSF/YI<7J-&$*<. 7),9)1&) )9,?P*   ='{M&       *A   G    EX 3/ 3 >Y  EX !/ ! >Y  EX /  >Y !    ! 39  3 !9  +и и 3    и  ;   Eи >и  G0173267.'>54&#"&'#".54>7.54>32>73z".:0U" *F%!#&jAH$W8,H3#,%5!=B(2 S-)L4$<5- *d6=-:!%+67#(0C( 6-')O#!8*H: 4/)3^'(_9Av4.   `c      +01'3#n8Ann    P       +01.5467hyyh-e__e-Q䑑Q*UU*   zP      +01>54&'7ze__e-hyyhUU*Q䑑Q   T o,  /  /   9    и  
и  01?'7737'l	0	l*xxF.77.F     U h,       +  и  	01#53533##BB+>>    +       +01>7#"&54632>>	 .0 --]SO<%&%'E;Xy   U+i    }      EX 	/ 	 >Y 0174632#"&/""//""/H&//&&..   c`     EX /  >Y  01#3JHJf    G   ' K   EX /  >Y  EX  /   >Y          9 / "01"&54632"32654."&54632,kzzkkzzk!8)UCCU)8!%%%%TAcEEcA# ## #     b  ~  =   EX 
/ 
 >Y  EX /  >Y    и 
 й  01%!53#5>73R3L=DDD5     E  
  C   EX /  >Y  EX /  >Y    к   9   017>54&#"'>32>;!IQ}U,DG-M/+cD0M6+NlA=?1HtaT(7F- /,51F*-[ai;G    9 3 S   EX /  >Y  EX 0/ 0 >Y     09 /      &  901732>54.#52>54&#"'>32#"&'c Y>!8)8X?9O2G;-P ,(f>-M9 L< 9,$?T0Sp#.+/"? ,/6$4#-)<':J)6!*D/7#    '  !~ 	  Y   EX /  >Y  EX /  >Y     +      	и  и 	 и   01%5>7###5!533p"cN?Xc=/B7t   8
~ ( U   EX /  >Y  EX #/ # >Y    + #    # 9  и   01732>54&#"'!!>32#".'a$+5 ";,UH(8",i5%.P;"'BU.+E7-&6!BJ3G1K44P7  M  0 W   EX -/ - >Y  EX #/ # >Y    + #     # -9    -  01%2>54&#".#">32#".54>32A2$FB&T)	UB$&F5!&_0,I5#:M+4YB%,Ja4;W 5%3 BE'/]`@iM&-1J1.K6&MsM`U''     F  ~  3   EX /  >Y  EX  /   >Y    	013>7!5!#2M7?R2V[~CG3H^     D   @ W   EX )/ ) >Y  EX </ < >Y   )     9 / 1и 1/ ܸ   01732654.'7654&#"4>75.54>32#".WJHL6I*/>PB?6B.=&1(95H+/I39(.":U76W<!6D>2!- A:F0A8/) !4*I3%<+-?%-O&3"$>./@   C  0 W   EX #/ # >Y  EX -/ - >Y     +  - #9    #   -  01267.#"32>7#".54>32#"&'%T*
SG1$EYB%&E5 ']1,I4";M*4ZB%-J`4;W 6'.^`%4BEAhM&,1J1.K6&MsM`U'&    }'   f    +'   f     x 0h  ;      +   и /      9  и /  01%%xu-kOO  U & k     k 0h  ;      +   и /      9  и /  015%5%5-u-OO  m  ) *   EX '/ ' >Y   
 + ' !ܸ  017&>54&#"'>324632#"&#,'77&A1"\:*D1'-%f++++$8.('**7-#.)9$!3+(,3 #))#$**    1p"{ 4 = ?    % + /   + 8   + ;   +   /9  : 01%#'##".546754.#"3267#".54>323275"2G'/#$9'-R?%$>T1-C'R2;jP/-Pk>4L2 +%88hXd:*"1MN$@0*S}SP}V--3c```1$@W3#(@~7      8 	  A   EX /  >Y  EX /  >Y 
  	 +     01'.'###3#  ?U^Xd7m99m7dCp    g  !   % W   EX  /   >Y  EX /  >Y $   9 $/   
 $ 9      % 0132+2654&+2654&+g2S;!9:HP$A[7æTIMLVcU\ZWc&=+1OND0H0x:76/?C=9   B* ! 9   EX /  >Y  EX /  >Y      014>32.#"3267#".B+Nl@<Z/@*/M66M/-F 0'b?>iM,HO~X/0 5!%Eb=>cF&&#3-2.W   U  % 
  9   EX  /   >Y  EX 
/ 
 >Y     
  0132+72654&+U'LpIpoopHN{U-D}}    s    M   EX  /   >Y  EX /  >Y        9 /     01!!!!!!sKaFGG      	 C   EX  /   >Y  EX 	/ 	 >Y      	  9 /  01!!!!#SFF  5 ' M   EX /  >Y  EX #/ # >Y    #    # 9 /  014>32.#"32675#53#".5+Mk@!6-#/>0.K63L0#< d@>hL*HOW/5"%Eb=>cF&E ,.W  O  	  I   EX  /   >Y  EX /  >Y 	   9 	/     и  013!3#!#OTTTTp5  _    A   EX /  >Y  EX /  >Y       и   	0173#5!#3!_fGFFG  Q  5   EX 	/ 	 >Y  EX /  >Y   	  0173265!5!#"&'H&GAf3S=8i",*KQrFA.Q<#49   b  C  k   EX  /   >Y  EX /  >Y  EX /  >Y  EX /  >Y    9 	   9 	 и  
01333##bT^]rTIjU       +   EX  /   >Y  EX /  >Y  013!!REiG    Q    M   EX  /   >Y  EX /  >Y    +   и  	и     013373#4>7##/##Q\]! \\G+Z-Z,Fjjpq675576   S    Y   EX /  >Y  EX /  >Y   9    к   9     0133.53#'##SUB	OUB	Ob1k4Tp3g3    0(  ' 5   EX 
/ 
 >Y  EX  /   >Y   
  01".54>32'2>54.#",8\C%%C\87]C%%C]7%>++>%&=++=0YOO}W./W}NOY0I&Gc>=bD%%Db=>cG&  f  !   G   EX  /   >Y  EX /  >Y    9 /       0132+#2654&+f6Z?##@Y6vSWSUUk-J64L2HAFG7   1])  4 K   EX $/ $ >Y  EX /  >Y 1   +    $    .0132>54.#"#"&'.54>323267+=&%=++=%&=+$Wm/M7$B\87\B$4K-J3	K=dG''Gd==cE%%EcXC7WvGO}W//W~NFtW8	*+   d  )   S   EX /  >Y  EX /  >Y   9 /        	и  0132654&+##32mMQQMmuS2T="PCY?@A4,F3M\    C 3 I   EX /  >Y  EX 0/ 0 >Y    0 9       0901732654./.54>32.#"#"&'u%b6FL +^2) 9O/>h$, M1<F!*\5' <V6Hy-%-;0#)
(7$%@/-$6!3-!	()7$'D34-   *  .  3   EX /  >Y  EX /  >Y    01#5!##TJFF    O	  3   EX  /   >Y  EX /  >Y     01332>53#".5OT%22&Q!:Q00R;!f3G++G3hGb??bG    +  -  3   EX  /   >Y  EX /  >Y     0133>73#+Xj	iUa;d:546bp   
  N ! M   EX /  >Y  EX  /   >Y   
 +     и  и   0133>?33>73#.'##
S5	
E;E	2Oa\KHZd*O))P)(Q))P)o<<   6  "  ]   EX /  >Y  EX /  >Y    9   9  к   9  к   90133>?3#'.'##\\ZX\cbXS=++33   &  2  @   EX /  >Y  EX /  >Y  EX /  >Y   901%33>?3#Xc$&_VT&K((L&Z  A   	 =   EX /  >Y  EX /  >Y    и    017!5!!!Aou&2F2G    h       +    +01!#3!00    c`     EX  /   >Y 013#cJHJ   chw        +    +01#5!!55h00   o 	 &   EX  /   >Y ܺ    9 	013#/##HHB11BH~     <t        +01!5 EGG   =m    Q ! /    EX /  >Y  EX /  >Y  EX /  >Y   9 /  
   '   
 '9   9  *   + 0174>7.#"'>32#'##".732675Q'U^1#0X" 17> daC)c4"<-P'*Q*Ni?~)=,,!%8m[B .#3'	%#'     ]  '    EX /  >Y  EX  /   >Y  EX /  >Y  EX /  >Y   9   9        $   ' 013>32#"&'##732>54.#"]R#W+1L3$=P+#Q#BR#G 6(!4$ I&^"(#A[8>bD##6r1H-(B/#&  P ! 9   EX /  >Y  EX /  >Y      0174>32.#"3267#".P+Jc7<W)A&*F11E*-K$(c69aH(=_B"*52E**D1#5$("A_    <  $    EX /  >Y  EX 
/ 
 >Y  EX /  >Y  EX /  >Y   9   9             0174>32'53#'##".73275.#"<%=P+-D"RDS-0M8UKDHA!?  7);_B$"Z8@-"A^>XbI1D  E  ' C   EX /  >Y  EX /  >Y '   +     " 0174>32!3267#".%4&#"E*EY/4R91C(+G"$\;6_G)LD7,<_B#!<T3	'>,6"#A^dIN'8$    g  B  V   EX /  >Y  EX /  >Y  EX /  >Y     и    
01.#"3###5754632/3 B9Q_eHDz	C<,C]>)Yl     H 6  E U    EX %/ % >Y  EX (/ ( >Y  EX '/ ' >Y  EX C/ C >Y  EX /  >Y C    и и  :  2ܹ F  5 F 29 5 и ( )  ' *  % N 0132>54&+"&'4675.54675.54>323##"&';2#"&2654.#"QN*D078_%#G)'#4E'( ɂ3E'+&50m^[&Fd>ku/A))BQ&0$#)8&1?,(@-?4 '>+		 4>">.Fk>5**5>     ]    e   EX  /   >Y  EX /  >Y  EX /  >Y  EX /  >Y   9      013>32#4&#"#]R'X9WQR4<%$&Rs)6ca#EC!    Z     ;   EX  /   >Y  EX /  >Y       ܸ 01!##%"&54632Z4R%%&&"##"    7'  ! A   EX  /   >Y  EX /  >Y         ܸ 01!#"&'732>5#%"&54632Z4/N;&H9$0%%&&-K7="1"##"     j  >  m   EX /  >Y  EX  /   >Y  EX /  >Y  EX /  >Y    9 	   9 	 и  
 01333#'#jR^\sR o  Q  5   EX  /   >Y  EX /  >Y      013327#"&5#Q3,(4!:(NQ6/>XW   <  ,      EX /  >Y  EX /  >Y  EX  /   >Y  EX  /   >Y  EX /  >Y  EX /  >Y     9  и            0133>32>32#4#"#4#"#<@1*J4)37O5&B7$O@"*T&.MIUV%&UV%&     ]    e   EX /  >Y  EX  /   >Y  EX /  >Y  EX /  >Y   9      0133>32#4&#"#]D&X9WQR4<%$&RS)6ca#EC!    <  ' 5   EX /  >Y  EX /  >Y    # 0174>32#".732>54.#"<'BW00WB''BW00WB'U)9##9))9##9)=_B""B_=<_A""A_<*D11D**E22E   ]3  %    EX 	/ 	 >Y  EX /  >Y  EX /  >Y  EX /  >Y  	 9   	9       	 "   % 01#33>32#"&'732654.#"RD"Y-1K3$=P,"O!#FBT!4$ I&)> *#A[9>aD#!?f[(B/#&    <3  $    EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y   9   9             0174>32373#57#".73275.#"<%=P+-F#BR Q-0M8UKDHA!?  7);_B$" 6MX+"A^>XbI1D      T   EX  /   >Y  EX /  >Y  EX /  >Y    9      0133>32.#"#D&oD.#7e,Rs;D	G	?L     H - I   EX /  >Y  EX */ * >Y    * 9      *901732654&'.54>32.#"#"&'p)^BB@EY&C23M27h$( N-".RBc_7Q4Hy-v$, ,	#*3%%5'@84(-  E"n  M  /  EX /  >Y  EX /  >Y     и  и   01#5?33#3267#".5ΉD0##8!P(5H+>C!1"
<5J-  M  e   EX 
/ 
 >Y  EX /  >Y  EX /  >Y  EX  /   >Y   9      01!#'##"&5332673C%W9XQS3=*D)RU+6ca.EC+/Q  3  %  <   EX  /   >Y  EX 
/ 
 >Y  EX /  >Y  0133>73#3SppO\%G##G%    P ! t   EX  /   >Y  EX 
/ 
 >Y  EX /  >Y  EX !/ ! >Y  EX /  >Y    !9  к    90133>?33>73#'.'##T;;F<;Njc:	8b#B""C"#B""B##E% D*  @    e   EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y   9   и  и 017'33>?3#'.'##[MIWZU!PXk*,ip.+p   1/'  [   EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y      901326?33>73#"'7T
3@SwjN$2A)$;-$ J##I!$>-
A   G   	 =   EX /  >Y  EX /  >Y    и    017!5!!!GMX3,wC,C    xh 9 +  3  4 +    +   
 + ' 
 9014>54.#52>54&54>;#";#".  9,,9 	.F/=4&1
'44'
1&4=/F.1..40]4'30
#+[/13		313T.#
03 Q      +013#JJ     ch 9 +     7 +    + '  ( +  ( '9012>54&54675.54654.+5323"+5&1
&44&
1&3=/E.	 9,,9 .E/=h
#.T313		31/[+#
03'4]04..1'30   L   '     +    +  и  01>3232>7#".#"LH&/)'	5H&/)')F7 "F6 "4     Hu      EX /  >Y 	ܸ 01#737#"&54632RP
8-++++Z^^X$))$#**   q  % \   EX /  >Y "  
 +   ! + !  и  / " и / 
 и / ܸ  и /01#5.54>753.'>7:8@?9H'3-J56J*3,@(- 4XBCX	"gh$=T54S<$jg"4   M   ) W   EX /  >Y  EX /  >Y    +     и      и  #01%!5>54'#57.54>32.#"3#;?=uc7M0>U0;*BE%&GG2_94 = *D0+ /A4 ; 85F   : SA   4   &   +   0 +01?.5467'76327'#"'732>54.#":TS,W0?>1W,TT,X9>1WP ++  ++ U:##;V-Z%%Z-V;##:U-Y&Y1$$11$$1   5  #~  l   EX  /   >Y  EX 	/ 	 >Y  EX /  >Y   	9  й   и ܸ й   и  013>?33#3##5#535#53\!"\RR~!C##C!/A00A/@ Q       +   +013##JJJJ5M0    [  G O  /  ( + D   + 2 ( 9  D /9   2 9    к <  29 < 01%>54.'.#"#"&'732654.5467.54>32s #)>I %)?IT8#*&*?I?*1)*;$7\ 2=*)-*>J>*3(&8&2Q&"",!)!+!k%$+=.0<'2$&!-(&*=.-@'/$"  L    :  ' E M   EX /  >Y  EX /  >Y    #  -й 4   Aй : 014>32#".732>54.#"4>32.#"3267#".)Ic99cI))Ic99cI). ;S22S;  ;S22S; F.;!#1".85-&4&";,CL{U..U{LM{W//W{MBkM**MkBBjL))LjB+F2'K;BM*3I   N   S 4& s     U hi       +01!#5!UBi U+i    p?  ' 5 > =      + 
   + 6  2 +  )и 2 /и  4и 101".54>32'2>54.#"32#'##72654&+,'E33E''D33D'7''7 6((6)L /..#))C?4H,,H44H,,H4%*;$#;++;#$;*$SFFfC    Y         
   +     +01".54>32'2654&#",-##-.""."**"!**!//""//!..#%..%#.   U  ,   D   EX /  >Y     +  ܸ  и   и    01#53533##!!BBR0>>A>            =    ME. ( s  (/  EX  /   >Y  EX /  >Y  EX /  >Y  EX /  >Y      9  
    01332>733:7#"&'##"&'#MS49&&'S&$ Q/#;SCE	+#<cX>5:85 &;43    H   %   EX  /   >Y  EX /  >Y013##".54>;QQ6 5ZB%$?V2+ 25R9;Q3    }      +v   a      N   a 4& s      ?~'{M&        <~'{M&      '  U'{M&      {<  ' *   EX %/ % >Y 
   + % ܸ 01%3267#"&54>'7#"&54632g#,'87&A0!]:Te'-$g,++,$8.('+*6-#.TH!3+(,2!$))$#**      82& &  #        82& &  $        82& &  %        83& &  &        8-& &  *        8k& &  ,       O   f   EX /  >Y  EX /  >Y  EX /  >Y    
 +    +        01#!5##!#3#=+.IWCL6i6wGFG B+*& (  //    s  2& *  #    s  2& *  $    s  2& *  %    s  -& *  *    _  2& .  #     _  2& .  $     _  2& .  %     _  -& .  *        +   S   EX /  >Y  EX /  >Y     +        и   01#5732+72654&+3#[KKpoopHA* D}}/ S  3& 3  &    0(2& 4  #     0(2& 4  $     0(2& 4  %     0(3& 4  &     0(-& 4  *      f ~  )   	 + 
 	 9 
 и 
 и 01?'77'f,,,---   -, 
  / }   EX +/ + >Y  EX /  >Y   +9   и    
  +9 
 и +   
 и    и  #и  -01732>54/.#"#"''7.54>3277 %>+8!&=+L%C]7Z@50?%C\8\?6/t&Gc>Y@8%Db=_@+sHOY0=O ]-vIO}W.=O     O	2& :  #     O	2& :  $     O	2& :  %     O	-& :  *     &  22& >  $      e  !   9   EX  /   >Y  EX /  >Y    +    +01332+#72654&+eTv6Z?##@Y6vTWSUUkn.I64M2@GG6   X4 9 Z   EX /  >Y  EX 9/ 9 >Y  EX /  >Y "    "9  4  %  49014>32#"&'732654.54>54&#"#X4J/(=*",5,+<%*F !4*--4-",*7?R.L6)5&5,) $5' 6(:/&!-#"1-/ %1KK    Q& F      Q& F      Q& F      Q& F      Q& F      Q& F       U . 7 D    EX /  >Y  EX /  >Y  EX &/ & >Y  EX ,/ , >Y /   +   ,9 /     & 9 &   ) & 9  4  , ;   B 017467.#"'>32>32!3267#"&'#"&%4.#"3267./||'/AP-0;E0%7%<;/A&5H)O&<F!/9(">\OIW6E8 8*/3$=P-L]60+-.K8+RI'($#5: P+& H  *    E& J      E& J      E& J      E& J      Z  &   0    Z  &   0    Z  &   0    Z  &   0     <  9 k   EX 4/ 4 >Y  EX /  >Y '   +     * 4 9 *    4 9  -и  7и 001%2>5<'.#"#".54>32.''7.'77,(;'#R'(=),<{BP!>X7/VB'"=S2/T=.<"&(J"85H,/&,;"&=+*=y<cG' =W63S; *&Ee(M)D!4*E)    ]  & S      <& T       <& T       <& T       <& T       <& T        U `3    %     +   ܸ ܸ  ܸ 01"&546324632#"&'!!,MR>   < 
  0 }   EX ,/ , >Y  EX /  >Y   ,9   и    
 , 9 
 и ,   
 и   !и  $и  .01732>54&/.#"#"''7.54>327):#9)2#9)5 'BW0S?3%5 'BW0S?3%\&1E*!:&2F*!8  Y7<_A"0;> X6=_B"0; M& Z      M& Z      M& Z      M& Z      1/'& ^       ]3  %    EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y   9   9        "   % 01#3>32#"&'532>54&#"RR#V+1L3%=P+$L!#E 7(AI H&W"(#A[9>aD#"\1H-Pc#&   1/'& ^         8& &  '     Q& F         82& &  (     Q& F        ,W 	 % e   EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y #   +     +   01'.'##"&54>7#'##3327  .(7>?U^#-d7m99m7d=,+& 	p=    Q2 4 B    EX /  >Y  EX 0/ 0 >Y  EX /  >Y  EX #/ # >Y   09 /  
  #    +и 0 :   > 0174>7.#"'>32327#"&54>7'##".732675Q'U^1#0X" 17> da*,.&4)c4"<-P'*Q*Ni?~)=,,!%8m[;)+*% 	> .#3'	%#'  B*2& (  $/    P& H  +    B*2& (  %/    P& H  +    B*5& (  )/    P& H  +    B*2& (  ./    P& H  +    U  %2& )  .     3T& I 8     +     <C  ,    EX  /   >Y  EX )/ ) >Y  EX /  >Y  EX /  >Y   + + #   9 #              9     и  &и + '01.#"327#'##".54>32'5#53533!? 8)KDHAHDS-0M8%=P+-D"RH`.A'S]I@- ?Z;9[@""ZB0]]   s  & *  '    E& J      s  2& *  (    E& J      s  5& *  )    E& J       s,! ! ^   EX  /   >Y  EX 
/ 
 >Y  EX  /   >Y    +    +        01!!!!!#3267#"&5467!sK!
.'8/FGG%-,+*A   E2 5 > ^   EX $/ $ >Y  EX /  >Y  EX /  >Y >  , +     2  $ 9 01%3267#"&54>7#".54>32!3267'4&#""-
-&4"6_G)*EY/4R91C(+G"LD7,-)$!)+*$ 	#A^<<_B#!<T3	'>,IN'8$   s  2& *  .    E& J      52& ,  %    H 6& L      52& ,  (    H 6& L      55& ,  )    H 6& L      5(& ,  #    H 6& L  9    O  	2& -  %     
  \& M  %f *  
  N      EX /  >Y  EX /  >Y  EX /  >Y  EX 
/ 
 >Y  ܹ    ܸ   и      и  и  01!!7##!##5753!533ETTEETTEoo5*uuuu         EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y    +    9         и  и  01>32#4&#"##57533#'X9WQR4<%$&RIIR)6caEC!;+]]0I    _  3& .  &     Z  &   0    _  & .  '     Z  &   0    _  2& .  (     Z  &   0     _,  `   EX /  >Y  EX 
/ 
 >Y  EX /  >Y    +        и   0173#5!#3#327#"&5467#_ ".(7*GFFG4-,++<    Z2  & g   EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y      
   ܸ !01#5!3267#"&54>7#"&54632<4#
-&5
 %%&&C6)+*#J"##" _  5& .  )      Z    /   EX  /   >Y  EX /  >Y    01!##Z4R   Q2& /  %    7'&\  0    b(C& 0  &    j(>& P  #     j  >  m   EX  /   >Y  EX /  >Y  EX /  >Y  EX /  >Y    9 	   9 	 и  
 01373#'#jR^\sR  n      2& 1  $    Qf& Q  $4   (& 1  .    Q(& Q  G      & 1  8|   Q& Q  8      & 1    +& Q    5    I   EX /  >Y  EX /  >Y      9  и  и 	01%!55737iQQRGG+C,ixDx  Q  W   EX /  >Y  EX /  >Y   9  
и     и и   01%#"&=575#537327!:(NQ||3,(4XWGFGC[G[6/  S  2& 3  $    ]  & S      S(& 3       ](& S      S  2& 3  .    ]  & S        V  & m   EX /  >Y  EX $/ $ >Y  EX #/ # >Y  EX /  >Y   +    &  #9 & ! 01>7#"&54632%>32#4&#"#305 '* (2LC#P5OLS.4'='RDO5' #+@9Kv#<%3`^)B@)(L  0(& 4  '     <& T       0(2& 4  (     <& T       0(2& 4  -     <& T        !  O   O   EX /  >Y  EX /  >Y   	 +       и  01463!#3#3!".7;#"!}>aD$VTVVTKFGG-U{N~    T  ; D    EX /  >Y  EX /  >Y  EX 2/ 2 >Y  EX 7/ 7 >Y <  ' + 7       2 9 2 +  5 2 9  A 01732>54.#"4>32>32#3267#"&'#".%4.#"X&%%&M0@%/EA0"5#:6';#0H+]&@/-0*E11E**D22D*=_A"=87>$<Q-L]697p"A_`8+SH  d  )2& 7  $      & W  *    d()& 7      t(& W      d  )2& 7  .      & W  *    C2& 8  $    H& X      C2& 8  %    H& X      C+& 8  /    H+& X      C2& 8  .    H& X      *+.& 9  /     E+"n& Y  L    *  .2& 9  .     E"& Y  8    O	3& :  &     M& Z      O	& :  '     M& Z      O	2& :  (     M& Z      O	k& :  ,     M& Z      O	2& :  -     M& Z       O,	 * R   EX  /   >Y  EX /  >Y  EX '/ ' >Y    + '   ' 01332>533267#"&54>7.5OT$23%QE750
-(8	nkf3G++G3hft=-,+!	}   M2 %    EX /  >Y  EX $/ $ >Y  EX /  >Y  EX /  >Y  EX  /   >Y      к   9      # 01!327#"&5467'##"&5332673-).&40 %W9XQS3=*D)R6)+*)=Q+6ca.EC+/Q  
  N2& <  %       P& \       &  22& >  %     1/'& ^      &  2-& >  *     A  2& ?  $    G  & _      A  5& ?  )    G  & _      A  2& ?  .    G  & _         +    EX /  >Y  EX %/ % >Y  EX  /   >Y  EX /  >Y !  $ +   9         	    9    $ #и $ (и ! )01732654&#"'>32#"&'###57533##G@T@I I&#W+1L3$=P+#Q#BIIRraVL]#&D"("=X6<^A"#6;+]]0I  >&  # C   EX 
/ 
 >Y  EX /  >Y    +    
   013267>32#".5467!.#"RBDWV:9Z?"$A\77Y>"TP)Ajvxi7 )/W}OO~Y00Y|Lv!   1 ( B   EX %/ % >Y    + 
   + %    и 
 !01.#"3##"&'7326?#5737>32#(>,*4-
hF)PT0J$/??.K6>OM;8dh  02  4 G   EX ,/ , >Y  EX "/ " >Y    , 
   " ,9  .01%2>54.#"#".54>32>54&',%>++>%&=++=9-,0%C]78\C%%C\8?5'(=&Gc>=bD%%Db=>cG& -2+[OY00YOO}W.
   <,e  4 G   EX ,/ , >Y  EX "/ " >Y    , 
   " ,9  .01%2>54.#"#".54>32>54&',#9))9##9))98,&.'BW00WB''BW061,)81D**E22E**D1- ,2!eC<_A""A_<=_B"
   Ov ( J   EX /  >Y  EX !/ ! >Y  EX /  >Y !     01#".5332>53>54&'_'!:Q00R;!T%22&#(0 $Gb??bGf3G++G3#
    MVo # a   EX /  >Y  EX /  >Y  EX 	/ 	 >Y  EX /  >Y   9     01#'##"&5332673>54&'?
"C%W9XQS3=*D)#0o #:U+6ca.EC+/Q"
      82& &  .     Q& F      _  2& .  .     Z  &   0    0(2& 4  .     <& T       O	2& :  .     M& Z      O	& :  1     M& Z  0    O	& :  3     M7& Z  2    O	& :  5     M7& Z  4    O	& :  7     M7& Z  6    52& ,  .    H 6& L       0,( % 9 K   EX /  >Y  EX 	/ 	 >Y #   + 	 и 	 &   0 01#"&5467.54>32327'2>54.#"-(8$A]=%C\87]C%`O	W%>++>%&=++=,+!;:_zAO}W./W}N"	&Gc>=bD%%Db=>cG&   <2 ( < \   EX /  >Y  EX /  >Y  EX &/ & >Y  и &    .   8 014>7.54>323267#"&32>54.#"/T>$'BW00WB'-@(#$	.&4Y)9##9))9##9)y!$A\:=_B""B_=3M;+8)+*D11D**E22E   C(& 8  
    H(& X  
    *(.& 9      E("n& Y  O     7'  5   EX  /   >Y  EX /  >Y      01!#"&'732>5#Z4/N;&H9$0-K7="1       )   - c   EX %/ % >Y  EX /  >Y    и и и и %     9  !и  #и "01%2654&+3#32654&++5#5732&U^\WkZTJNL^HP$A[7MM2S;!8;?CFA<e/r=8860PE2I1*&<*0K   ^ ! / v   EX /  >Y  EX /  >Y  EX /  >Y   9 /  
    9  '   *   + 013267#"&533>324.#">(U^0#0Y" 17> dbD(d3"=-P'*Q*Nh?h)=,-!%8m[*B .$3'	%#'     <  $    EX /  >Y  EX /  >Y  EX /  >Y  EX  /   >Y      9       9     	 0173275.#"4>32373#'##".KDHA!?  7)U$>P,+H"BDT./M8XbI1D+;_B$" 6@-"A^  ]  %    EX /  >Y  EX !/ ! >Y  EX /  >Y  EX /  >Y !    ! 9      !9     
 01%4&#"32>7#"&'##33>32AI$J #E 6(U$=P+$P#BDZ11K3Sc%$ 2F0>bD##6@-#A[  = ! 5   EX /  >Y  EX /  >Y     01%#"&'732>54.#"'>32)Fa79d'%M-)E1.B',F*_B5]F)<_A"($5#1D**E25*"B_   ?  ' C   EX /  >Y  EX /  >Y    +     " 01%#"&'732>7!.54>32.#")G_6;\$"G+(B0">U31V@%T
PB7*<^A#"6+?'	3T<!#B_HO&9$   E  # C   EX /  >Y  EX /  >Y #   +       017467!.#"'>32#".73267E{UT*J!$^99\A$$AY53S; LQBHR	JY8"B^<<_B# =W+ONRK  <' ! /    EX /  >Y  EX /  >Y  EX /  >Y  EX 
/ 
 >Y      9   9 
 "   $   %   ( 01326?#".54>32373#"&'7275.#"}&P%FKT-/M8$=Q,+J Bvm0a(FC!@ 7*MjF;b*"?[99\@##6\jI0A'R`   M3  a   EX 
/ 
 >Y  EX /  >Y  EX  /   >Y  EX /  >Y  
 9     01#57#"&5332>73R'X9WQR4<%$&Rͮr(7ca.EC!S    .      EX /  >Y  EX /  >Y  EX /  >Y  EX  /   >Y  EX /  >Y  EX /  >Y    9   9            01!#'##"'#"&533267332673@1*J4)38O5&C6%N@"*T&.MI\V%&`V%&`    ?  T   EX /  >Y  EX /  >Y  EX  /   >Y   9      01!#'##"&'732673D&oD.#7e,Rs;D	G	?L  6x  A   EX /  >Y  EX /  >Y    и  и   01%3##5#5354&#"'>32D5F#8!P(5H+CCCAD
=5J-    3  %  @   EX /  >Y  EX  /   >Y  EX 
/ 
 >Y    901!#.'##3%SppO\%H##H%     P ! i  /  EX /  >Y  EX  /   >Y  EX /  >Y  EX /  >Y    9   9   901!#.'##'.'##33>?3PT;;F<;Njc:	8b#B""C"#B""B##E% D*  1  '  R   EX /  >Y  EX /  >Y  EX /  >Y      9  01.#"#.'##>32	0=SwjN$0>'!<.? J##I!*$>.A   3  c   EX /  >Y  EX /  >Y  EX  /   >Y  EX /  >Y    9 	   9 	 01###73753R^\sR%n       :  / /  EX  /   >Y    +   9   013>32#54&#"#@8$94@$'@}E!A>*'    w   4   EX  /   	>Y    +       ܸ 013#"&'73265#7"&54632 6(-" / F2&
.+(r    N  6  /  EX /  	>Y    +   9   0133>32.#"#6B'#=@FK',6(2   RF ! Z  /  EX  /   	>Y  EX 
/ 
 	>Y  EX /  	>Y    и 
     0133>?33>?3#'.'##R@%	$3%$<CM#"JF-----,   |F  A   EX /  	>Y  EX 	/ 	 	>Y    +   9  017326?33>?3#"&'7%@E	<><5	#@//3@1   ^|   ^            +    +012654&#56'3,,3EHHE*#"*$>45>     h       +     +01"3&546h3++3EHHE*"#*$>54>   =   =    _     EX  /   >Y 013#f8   Y   =   =m    _ B       +01#3_f8@    ?   Jn      2    C   ;       (   EX  /   >Y    +    0133267#"&5#đ"62Q 2<86      N - +    * +    +  * 9   90132654.'.54632.#"#"&'7%(& +"G@$?-&!,#IF+LS
(5(
)9    F  K  / /  EX /  	>Y  EX /  	>Y   9   и  и 01'33>?3#'.'##fD+&DhoE/
	+CBBFF   =m      +013#ZZ?є  =       +01#73*?ZZ=     =       +  ܸ 013#'##	Fa?CC?єcc     C  '     +  ܹ   
и  01>323273#".#"#+(	/+(	/C0=6/>7   Y       +013#9     ?    	    + 	 ܸ 01".'332>73,!/ 3&%3 /?'/ 3/'  Jn        +01"&54632,&&&&J"##"    L         +   и  01"&546323"&54632L           )        +   ܹ  01>54'7 S	BH(O'0)&           +  ܸ 01"&54632'2654&#",)44))44)3**22**3%   ;         +   и  013#73#IX7HX7ʏ   =       +  ܸ 013373#?CC?aFcc  l;        +  и  01#'3#'37XIM7XH;   !Z       +  01632#"5467Z3&+#E#?   _    
   +  0167#"&5463262&+@.E#> #e        +   01>54&'7#**;
'4
 (  n        +01"&54632,&&&&"##"     7         +   и  01"&546323"&54632    (p        +  	ܹ  01'>54&'73.(5(10#" (&  +p       +  и ܹ 
 01%3'>54&'5#(5(1!5  )  2      EX /  >Y 
   +014673327#"&.: $.&4y)@7)+     2    	    +01".'332673, /3$##$3/%-//-%    U        +01#53:      N  # 9  /    +    +   ! +   9    01467.#"'>32#'##"&732675fm'4H(?=49 +<?"+QCY58,+H?%2/R	%        T  /  EX /  >Y    +    +   9   9       013>32#"&'##732654&#"@5BD(522@((4'.),}8YK)A- K?93=(        T  /  EX 
/ 
 >Y    +    +   9   9      014>32'53#'##"&73275.#"(5+@55?LB.*+(&'5'?,6y,%XQ7=(>   N    !     +    + 
   +014>32#3267#".74&#"+9DH=/*;##<-+(#7'?,SE17)+?B-00-     rN  A M d   EX %/ % 	>Y   ? + "  H + 7  	 + B  0 +  	 79  и 0 2и и % ( 01732654&+"&'475.54675.54>323##"';2#"&72654&#"326?%#;65#/R".?G@>0D*FO((((%( )+0)"$))-&  ((  &       S  / /  EX  /   >Y  EX /  	>Y 
   9 
   	  9 	 013373#'#@G|GkF@ΠCU   N  T  / / /  EX /  	>Y    +    +   9  и    0133>32>32#54#"#54#"#2!1$"%=5 =F*7403.3     N        +    +014>32#".732654&#"+9  9,,9  9+B1++11++1(?++?((?++?(5@@54AA     N   T  /  EX /  	>Y 	   +    +  	 9   	9      017#33>32#"'732654&#"@46AD(5/.((4'.'.k$YK)A-%.?93=(      I   EX /  	>Y  EX /  >Y    +      и   	01#5?33#3267#"&5MP5"-0H80ZZ3**.J=     F  A   EX /  	>Y  EX /  	>Y    +   9  01#'##"&=332675349%74@#)@3!A>*&   F  3  /  EX 
/ 
 	>Y  EX /  	>Y   0133>?3#B=	>=vJF00      N       +    +014>32.#"3267#"./="#2 !0<:0(; #=,(?+)A45@)+?     8  /  EX /  	>Y    +  	  и  01.#"3###5754632"*$?OOAE-*#30:G    F 	 4  	/  EX /  	>Y 	    и    017#5!3!ս&3"3 U%& )      <& I      UU%& )      <U& I      5& ,  '    H 6& L      O	& -       ]& M      O2	& -       ]2& M      & 1  .    Q& Q  G    C& 1  &' .  Qp& Q  ' G    U& 1  .    QU& Q  G    Q& 2       <,& R      S  5& 3  )    ]  & S      S& 3       ]& S      SU& 3       ]U& S      d)& 7      & W      d)& 7  &'   & W  &*   dU)& 7      MU& W      C5& 8  )    H& X      C& 8  
    H& X  
    *.& 9      E"n& Y  O    *U.& 9      EU"n& Y  O    
  N2& <  #       P& \       
  N2& <  $       P& \       
  N-& <  *       P& \       &  25& >  )     1/'& ^      A& ?      G& _      E"@& Y     O3 * h   EX /  >Y  EX )/ ) >Y  EX /  >Y !    + 	 !  9     %   % 9014>32#"&'732654./7.#"#O9X;NbuXR-?(4S03,0&?1v9,DLU2W?$TFbH'C1(!5?2*$
6"0Y^`   &  22& >  #     1/'& ^      &2& >       1"'& ^     &  2h& >  +     1/'& ^  	    &  23& >  &     1/'& ^       P         +01!!PH H    D        +01!!0 H   ^|      +01632#"&5467|/5'* '3LDO4( #*?9Kw#     ^      +01>7#"&5463205 '* (2LCO5' #+@9Kv#  |     _^& s    g^& s    g |' s     s    
   +01%".54>32,6))66))6s'6!!6''6!!6'    4      +01757ř''P#"      4      +01%'7'R''#P"      <p       +01?'7!!M#             *  /  EX  /   	>Y     ܸ 013##7"&54632@Fr                                 lC!     llC"      N  :  / /  EX /  	>Y    +   9   0133>32#54&#"#57%85@$'@F0!A>*'  K   W   Wa   W   W  W   K   W   W   W   K   W   K   W   W   W   K   W   K    W    !  W   l "  W     N   !     +    +    +014673.#"'>32#"&732673/*;#GV)7 CM9-)'/	/5)XQ'?+T>001/  `" 	  7    EX &/ & >Y  EX /  >Y й       & 	  и 	 
и   и  и  ܸ и  и & #и & %ܸ  )  % *и ) ,и  3и  4и 4/01%.#*#7.'#7.546?33273.'>7!>
'>A$#&#T6&&DNvg&&-1<#7GdLs!(0ccm|#qgbgr /#    N   4    EX /  >Y  EX /  >Y    +     и       	и  и      'и  (и  -и  .01%!5>=#573.'#57.54>32.#"3#3#;?=|WaP7M0>U0;*BEξ	%&GG2_9,-%*D0+ /A4#115F    /  '~  	   /    EX '/ ' >Y  EX +/ + >Y  EX /  >Y  EX /  >Y ' ܹ   и  и и    и    '    и  и  и  и  "и  #и  &и  )и -015#3#3/5#'3'#3##'##5#575#57533533ZD7>H;C5HHTapAJJJJTfkAH=.+;&f<+&<%*   +  *~   ! c   EX /  >Y  EX /  >Y    +    +     и  и  и   01267#3.##+##575323 ENNE*@%<M-EOKK-N;%@.:9sl;1,A*3'?-    m  "   / V   EX /  >Y $   +         $ ܸ )и  /  +и / .017!!.#"3267#'##"&54>32'5#5353yz-)944N:>'L[1?!'5G11y +>Ex,S+a\)B/S"1CC    :6 1 m   EX /  >Y  EX /  >Y ( " + ( +  и ( 	и " и "   и     . 01%#"&'#57&45<7#57>32.#"!!!#32676&\>b@;;@j3X1;&JZ&XE+AQ,1v+		,v-!/!bW1
	0U`$#   +  *~    4    EX // / >Y  EX %/ % >Y 	  # + /   й    ܹ    и   и  и  'и   *и  +и  .и  301>54&'#27#3.##3#+##575#575323;p!G6*A@H
)8F'EOKKKKNsJ	;tKK?"h	)"1!y$;%x7A   T * u   EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y *  ' +  ܸ  ܸ     # 01%#5.54>753.#"32675#53CX<2T<! ;T4<.O1;&,C/-A* :t=>	dd2TtHFsU3ec,.!%Db<>bD%E    `"  % {   EX /  >Y  EX /  >Y  EX 
/ 
 >Y  EX /  >Y         ܸ  ܸ   !и  "017#5.54>753.'>7JHMMH!O354V>"!=W55/O12 "6Elp&0dc1TvIGtT4a`+/#    l  ~  p   EX /  >Y  EX /  >Y  EX /  >Y    и и и    и  й   
и 
/01#3##'#53267!573.+5!!+IG]I^YOS`L]LOM5#1LXC:<,.&D     8~ $ ]   EX /  >Y  EX /  >Y       9   #и и   и и и  и 017>54&'7'575575377%NA)E:fOhhhhTB)='?^>050H041ǞV5VHV4W     U+i       +01!!URi>    <p    =   (   EX  /   >Y    +    01"&54632'2654&#",=NN==NN= ..  ..XONTTNOX29<<55<<9     a1     EX /  >Y     +01%#5>73#"R!)2?*    =  ,   EX /  >Y    +     017>54&#"'>323#NS&';$6>!,$;N! !#52'')5     = $ <   EX !/ ! >Y    + 	   + !     	901732654#52654&#"'>32#"&'1#`*'(=#/;8 'F3#CQ3&&,(7&-0      1   8   EX 	/ 	 >Y    +    +   и  
01%57###5#5733N-629G2t8RAI+IIɽ     1  D   EX /  >Y    +   	 +     	 9  01732654&#"'73#632#"&'-%$
 2>F6*<Q6F300:     =  & F   EX /  >Y #   +    +       #9  	 01%2654&#"7.#">32#"&546328#,o+4-34+;NUE,&&";95*&QGV[      1  &   EX  /   >Y    +  	013>7#53#$ (
A'A;:5$#??D(    =   8 <   EX 4/ 4 >Y %   + 4    4 9  % 901732654.'7>54&#"4675.54>32#".')/W,r'*2A!%"-.!P
<n %/%!%!       =  $ F   EX !/ ! >Y   	 +    +   !9    !  0173267.#"3267#"&54632#"&'#,*2-33@3;NUE-&$995*,<QGV[        +017467.72.-((-.27Ko2!-c;;c- 1o  l      +01%'>54&'7l72.-((-.27Ko1 -c;;c-!2o     _2      +013#^XE2p  2       +01#73>EX^p     2       +  ܸ 0173#'#`P`CCCppDD     3  +      +   ܸ   и    01".#"#>3232673h .,$ .,/=.>         +013#9     2    	    + 	 ܸ 01".'332673,,2""""2,(''(   e5        +01"&54632,!!!!    -         +   и  01"&546323"&54632   h       +   ܹ  01>54'7 S	BH('0)&     k        +  ܸ 01"&54632'2654&#",)44)(55(/)(00()/$   2        +  и  017373#BMSMT;pppp   2       +  ܸ 01#'337`P`CCC2ppDD    +k       +  и ܹ 
 01%3'>54&'6#(5(1!5  )  L    +      +   и  и  ܹ  01"&546323"&54632'3#L/      +  
   + 
 ܹ    и 
 013#"&546323"&54632&.  L7    %     +   
 +  и 
 013#"&546323"&54632IOg:!7g      )  
   + 
 ܸ  ܸ  и 
 013#"&546323"&54632R[pD#o|  L7    +     +  ܹ    и  013373#"&546323"&54632=??=[F37@@g       +      +   и  и  ܹ  01"&546323"&546327#'337`P`CCCooDD  L7    )    
 + 
 ܸ ܸ  и 
 01#'3"&54632#"&54632a:gOsg      )  
   + 
  ܸ ܸ  и 
 01#'3"&54632#"&54632_Dp[|Go $A       +01'3
;$9             +  	ܹ  01.54>7H3.(4'1$! )&      >         .        e               &        "       A       $       `             	        	      '       $:  	   ,    	   E  	   u  	  L   	    	  2  	  *  	  :  	  4]  	 	   	  2  	 ##  	  H9 T y p o g r a p h i c   a l t e r n a t e s  Typographic alternates  S o u r c e   C o d e   P r o  Source Code Pro  R e g u l a r  Regular  1 . 0 1 7 ; A D B E ; S o u r c e C o d e P r o - R e g u l a r ; A D O B E  1.017;ADBE;SourceCodePro-Regular;ADOBE  S o u r c e   C o d e   P r o  Source Code Pro  V e r s i o n   1 . 0 1 7 ; P S   V e r s i o n   1 . 0 0 0 ; h o t c o n v   1 . 0 . 7 0 ; m a k e o t f . l i b 2 . 5 . 5 9 0 0  Version 1.017;PS Version 1.000;hotconv 1.0.70;makeotf.lib2.5.5900  S o u r c e C o d e P r o - R e g u l a r  SourceCodePro-Regular  S o u r c e   i s   a   t r a d e m a r k   o f   A d o b e   S y s t e m s   I n c o r p o r a t e d   i n   t h e   U n i t e d   S t a t e s   a n d / o r   o t h e r   c o u n t r i e s .  Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries.  A d o b e   S y s t e m s   I n c o r p o r a t e d  Adobe Systems Incorporated  P a u l   D .   H u n t  Paul D. Hunt  h t t p : / / w w w . a d o b e . c o m / t y p e  http://www.adobe.com/type  C o p y r i g h t   2 0 1 0 ,   2 0 1 2   A d o b e   S y s t e m s   I n c o r p o r a t e d   ( h t t p : / / w w w . a d o b e . c o m / ) ,   w i t h   R e s e r v e d   F o n t   N a m e   ' S o u r c e ' .   A l l   R i g h t s   R e s e r v e d .   S o u r c e   i s   a   t r a d e m a r k   o f   A d o b e   S y s t e m s   I n c o r p o r a t e d   i n   t h e   U n i t e d   S t a t e s   a n d / o r   o t h e r   c o u n t r i e s .  
  
 T h i s   F o n t   S o f t w a r e   i s   l i c e n s e d   u n d e r   t h e   S I L   O p e n   F o n t   L i c e n s e ,   V e r s i o n   1 . 1 .  
  
 T h i s   l i c e n s e   i s   c o p i e d   b e l o w ,   a n d   i s   a l s o   a v a i l a b l e   w i t h   a   F A Q   a t :   h t t p : / / s c r i p t s . s i l . o r g / O F L  
  
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  
 S I L   O P E N   F O N T   L I C E N S E   V e r s i o n   1 . 1   -   2 6   F e b r u a r y   2 0 0 7  
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  
  
 P R E A M B L E  
 T h e   g o a l s   o f   t h e   O p e n   F o n t   L i c e n s e   ( O F L )   a r e   t o   s t i m u l a t e   w o r l d w i d e   d e v e l o p m e n t   o f   c o l l a b o r a t i v e   f o n t   p r o j e c t s ,   t o   s u p p o r t   t h e   f o n t   c r e a t i o n   e f f o r t s   o f   a c a d e m i c   a n d   l i n g u i s t i c   c o m m u n i t i e s ,   a n d   t o   p r o v i d e   a   f r e e   a n d   o p e n   f r a m e w o r k   i n   w h i c h   f o n t s   m a y   b e   s h a r e d   a n d   i m p r o v e d   i n   p a r t n e r s h i p   w i t h   o t h e r s .  
  
 T h e   O F L   a l l o w s   t h e   l i c e n s e d   f o n t s   t o   b e   u s e d ,   s t u d i e d ,   m o d i f i e d   a n d   r e d i s t r i b u t e d   f r e e l y   a s   l o n g   a s   t h e y   a r e   n o t   s o l d   b y   t h e m s e l v e s .   T h e   f o n t s ,   i n c l u d i n g   a n y   d e r i v a t i v e   w o r k s ,   c a n   b e   b u n d l e d ,   e m b e d d e d ,   r e d i s t r i b u t e d   a n d / o r   s o l d   w i t h   a n y   s o f t w a r e   p r o v i d e d   t h a t   a n y   r e s e r v e d   n a m e s   a r e   n o t   u s e d   b y   d e r i v a t i v e   w o r k s .   T h e   f o n t s   a n d   d e r i v a t i v e s ,   h o w e v e r ,   c a n n o t   b e   r e l e a s e d   u n d e r   a n y   o t h e r   t y p e   o f   l i c e n s e .   T h e   r e q u i r e m e n t   f o r   f o n t s   t o   r e m a i n   u n d e r   t h i s   l i c e n s e   d o e s   n o t   a p p l y   t o   a n y   d o c u m e n t   c r e a t e d   u s i n g   t h e   f o n t s   o r   t h e i r   d e r i v a t i v e s .  
  
 D E F I N I T I O N S  
 " F o n t   S o f t w a r e "   r e f e r s   t o   t h e   s e t   o f   f i l e s   r e l e a s e d   b y   t h e   C o p y r i g h t   H o l d e r ( s )   u n d e r   t h i s   l i c e n s e   a n d   c l e a r l y   m a r k e d   a s   s u c h .   T h i s   m a y   i n c l u d e   s o u r c e   f i l e s ,   b u i l d   s c r i p t s   a n d   d o c u m e n t a t i o n .  
  
 " R e s e r v e d   F o n t   N a m e "   r e f e r s   t o   a n y   n a m e s   s p e c i f i e d   a s   s u c h   a f t e r   t h e   c o p y r i g h t   s t a t e m e n t ( s ) .  
  
 " O r i g i n a l   V e r s i o n "   r e f e r s   t o   t h e   c o l l e c t i o n   o f   F o n t   S o f t w a r e   c o m p o n e n t s   a s   d i s t r i b u t e d   b y   t h e   C o p y r i g h t   H o l d e r ( s ) .  
  
 " M o d i f i e d   V e r s i o n "   r e f e r s   t o   a n y   d e r i v a t i v e   m a d e   b y   a d d i n g   t o ,   d e l e t i n g ,   o r   s u b s t i t u t i n g   - -   i n   p a r t   o r   i n   w h o l e   - -   a n y   o f   t h e   c o m p o n e n t s   o f   t h e   O r i g i n a l   V e r s i o n ,   b y   c h a n g i n g   f o r m a t s   o r   b y   p o r t i n g   t h e   F o n t   S o f t w a r e   t o   a   n e w   e n v i r o n m e n t .  
  
 " A u t h o r "   r e f e r s   t o   a n y   d e s i g n e r ,   e n g i n e e r ,   p r o g r a m m e r ,   t e c h n i c a l   w r i t e r   o r   o t h e r   p e r s o n   w h o   c o n t r i b u t e d   t o   t h e   F o n t   S o f t w a r e .  
  
 P E R M I S S I O N   &   C O N D I T I O N S  
 P e r m i s s i o n   i s   h e r e b y   g r a n t e d ,   f r e e   o f   c h a r g e ,   t o   a n y   p e r s o n   o b t a i n i n g   a   c o p y   o f   t h e   F o n t   S o f t w a r e ,   t o   u s e ,   s t u d y ,   c o p y ,   m e r g e ,   e m b e d ,   m o d i f y ,   r e d i s t r i b u t e ,   a n d   s e l l   m o d i f i e d   a n d   u n m o d i f i e d   c o p i e s   o f   t h e   F o n t   S o f t w a r e ,   s u b j e c t   t o   t h e   f o l l o w i n g   c o n d i t i o n s :  
  
 1 )   N e i t h e r   t h e   F o n t   S o f t w a r e   n o r   a n y   o f   i t s   i n d i v i d u a l   c o m p o n e n t s ,   i n   O r i g i n a l   o r   M o d i f i e d   V e r s i o n s ,   m a y   b e   s o l d   b y   i t s e l f .  
  
 2 )   O r i g i n a l   o r   M o d i f i e d   V e r s i o n s   o f   t h e   F o n t   S o f t w a r e   m a y   b e   b u n d l e d ,   r e d i s t r i b u t e d   a n d / o r   s o l d   w i t h   a n y   s o f t w a r e ,   p r o v i d e d   t h a t   e a c h   c o p y   c o n t a i n s   t h e   a b o v e   c o p y r i g h t   n o t i c e   a n d   t h i s   l i c e n s e .   T h e s e   c a n   b e   i n c l u d e d   e i t h e r   a s   s t a n d - a l o n e   t e x t   f i l e s ,   h u m a n - r e a d a b l e   h e a d e r s   o r   i n   t h e   a p p r o p r i a t e   m a c h i n e - r e a d a b l e   m e t a d a t a   f i e l d s   w i t h i n   t e x t   o r   b i n a r y   f i l e s   a s   l o n g   a s   t h o s e   f i e l d s   c a n   b e   e a s i l y   v i e w e d   b y   t h e   u s e r .  
  
 3 )   N o   M o d i f i e d   V e r s i o n   o f   t h e   F o n t   S o f t w a r e   m a y   u s e   t h e   R e s e r v e d   F o n t   N a m e ( s )   u n l e s s   e x p l i c i t   w r i t t e n   p e r m i s s i o n   i s   g r a n t e d   b y   t h e   c o r r e s p o n d i n g   C o p y r i g h t   H o l d e r .   T h i s   r e s t r i c t i o n   o n l y   a p p l i e s   t o   t h e   p r i m a r y   f o n t   n a m e   a s   p r e s e n t e d   t o   t h e   u s e r s .  
  
 4 )   T h e   n a m e ( s )   o f   t h e   C o p y r i g h t   H o l d e r ( s )   o r   t h e   A u t h o r ( s )   o f   t h e   F o n t   S o f t w a r e   s h a l l   n o t   b e   u s e d   t o   p r o m o t e ,   e n d o r s e   o r   a d v e r t i s e   a n y   M o d i f i e d   V e r s i o n ,   e x c e p t   t o   a c k n o w l e d g e   t h e   c o n t r i b u t i o n ( s )   o f   t h e   C o p y r i g h t   H o l d e r ( s )   a n d   t h e   A u t h o r ( s )   o r   w i t h   t h e i r   e x p l i c i t   w r i t t e n   p e r m i s s i o n .  
  
 5 )   T h e   F o n t   S o f t w a r e ,   m o d i f i e d   o r   u n m o d i f i e d ,   i n   p a r t   o r   i n   w h o l e ,   m u s t   b e   d i s t r i b u t e d   e n t i r e l y   u n d e r   t h i s   l i c e n s e ,   a n d   m u s t   n o t   b e   d i s t r i b u t e d   u n d e r   a n y   o t h e r   l i c e n s e .   T h e   r e q u i r e m e n t   f o r   f o n t s   t o   r e m a i n   u n d e r   t h i s   l i c e n s e   d o e s   n o t   a p p l y   t o   a n y   d o c u m e n t   c r e a t e d   u s i n g   t h e   F o n t   S o f t w a r e .  
  
 T E R M I N A T I O N  
 T h i s   l i c e n s e   b e c o m e s   n u l l   a n d   v o i d   i f   a n y   o f   t h e   a b o v e   c o n d i t i o n s   a r e   n o t   m e t .  
  
 D I S C L A I M E R  
 T H E   F O N T   S O F T W A R E   I S   P R O V I D E D   " A S   I S " ,   W I T H O U T   W A R R A N T Y   O F   A N Y   K I N D ,   E X P R E S S   O R   I M P L I E D ,   I N C L U D I N G   B U T   N O T   L I M I T E D   T O   A N Y   W A R R A N T I E S   O F   M E R C H A N T A B I L I T Y ,   F I T N E S S   F O R   A   P A R T I C U L A R   P U R P O S E   A N D   N O N I N F R I N G E M E N T   O F   C O P Y R I G H T ,   P A T E N T ,   T R A D E M A R K ,   O R   O T H E R   R I G H T .   I N   N O   E V E N T   S H A L L   T H E   C O P Y R I G H T   H O L D E R   B E   L I A B L E   F O R   A N Y   C L A I M ,   D A M A G E S   O R   O T H E R   L I A B I L I T Y ,   I N C L U D I N G   A N Y   G E N E R A L ,   S P E C I A L ,   I N D I R E C T ,   I N C I D E N T A L ,   O R   C O N S E Q U E N T I A L   D A M A G E S ,   W H E T H E R   I N   A N   A C T I O N   O F   C O N T R A C T ,   T O R T   O R   O T H E R W I S E ,   A R I S I N G   F R O M ,   O U T   O F   T H E   U S E   O R   I N A B I L I T Y   T O   U S E   T H E   F O N T   S O F T W A R E   O R   F R O M   O T H E R   D E A L I N G S   I N   T H E   F O N T   S O F T W A R E .  
  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

-----------------------------------------------------------
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.
  h t t p : / / w w w . a d o b e . c o m / t y p e / l e g a l . h t m l  http://www.adobe.com/type/legal.html         2                    :           	 
                        ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ 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    j i k m l n  o q p r s u t v w  x z y { } |    ~     
     !"  #$%&'()*+,-./012  3456789:;<=>?  @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:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXNULLCRuni00A0uni00ADtwo.sups
three.supsuni00B5one.supsAmacronamacronAbreveabreveAogonekaogonekCcircumflexccircumflex
Cdotaccent
cdotaccentDcarondcaronDcroatEmacronemacronEbreveebreve
Edotaccent
edotaccentEogonekeogonekEcaronecaronGcircumflexgcircumflex
Gdotaccent
gdotaccentuni0122uni0123HcircumflexhcircumflexHbarhbarItildeitildeImacronimacronuni012Cuni012DIogonekiogonekJcircumflexjcircumflexuni0136uni0137kgreenlandicLacutelacuteuni013Buni013CLcaronlcaronLdotldotNacutenacuteuni0145uni0146NcaronncaronnapostropheOmacronomacronuni014Euni014FOhungarumlautohungarumlautRacuteracuteuni0156uni0157RcaronrcaronSacutesacuteScircumflexscircumflexuni015Euni015Funi0162uni0163TcarontcaronUtildeutildeUmacronumacronUbreveubreveUringuringUhungarumlautuhungarumlautUogonekuogonekWcircumflexwcircumflexYcircumflexycircumflexZacutezacute
Zdotaccent
zdotaccentuni0180uni018Funi0192OhornohornUhornuhornuni01CDuni01CEuni01CFuni01D0uni01D1uni01D2uni01D3uni01D4uni01D5uni01D6uni01D7uni01D8uni01D9uni01DAuni01DBuni01DCGcarongcaronuni01EAuni01EBuni0218uni0219uni021Auni021Buni0237uni0243uni0250uni0251uni0252uni0254uni0258uni0259uni0261uni0265uni026Funi0279uni0287uni028Cuni028Duni028Euni029Eh.supsj.supsr.supsw.supsy.supsuni02BBuni02BCuni02BEuni02BFuni02C8uni02C9uni02CAuni02CBuni02CCl.supss.supsx.supsuni0300uni0301uni0302uni0303uni0304uni0306uni0307uni0308uni0309uni030Auni030Buni030Cuni030Funi0312uni0313uni031Buni0323uni0324uni0326uni0327uni0328uni032Euni0331a.supsb.supsd.supse.supsg.supsk.supsm.supso.supsp.supst.supsu.supsv.supsc.supsf.supsz.supsuni1E0Cuni1E0Duni1E0Euni1E0Funi1E20uni1E21uni1E24uni1E25uni1E2Auni1E2Buni1E36uni1E37uni1E38uni1E39uni1E3Auni1E3Buni1E42uni1E43uni1E44uni1E45uni1E46uni1E47uni1E48uni1E49uni1E5Auni1E5Buni1E5Cuni1E5Duni1E5Euni1E5Funi1E60uni1E61uni1E62uni1E63uni1E6Cuni1E6Duni1E6Euni1E6FWgravewgraveWacutewacute	Wdieresis	wdieresisuni1E8Euni1E8Funi1E92uni1E93uni1E97uni1E9EYgraveygraveuni1EF4uni1EF5uni1EF6uni1EF7uni1EF8uni1EF9	zero.supsi.sups	four.sups	five.supssix.sups
seven.sups
eight.sups	nine.supsparenleft.supsparenright.supsn.sups	zero.subsone.substwo.subs
three.subs	four.subs	five.subssix.subs
seven.subs
eight.subs	nine.subsparenleft.subsparenright.subsuni0259.supscolonmonetarylirauni20A6pesetadongEurouni20B1uni20B2uni20B5uni20B9uni20BAuni2215	zero.dnomone.dnomtwo.dnom
three.dnom	four.dnom	five.dnomsix.dnom
seven.dnom
eight.dnom	nine.dnomparenleft.dnomparenright.dnomuni0300.capuni0301.capuni0302.capuni0303.capuni0304.capuni0306.capuni0307.capuni0308.capuni0309.capuni030A.capuni030B.capuni030C.capuni0327.capuni03080304uni03080304.capuni03080301uni03080301.capuni0308030Cuni0308030C.capuni03080300uni03080300.cap	uni030C.a	uni0326.a            mU               pFFTMfh    OS/2s  x   `cmap_ce  X  cvt       "fpgmY7  `  sgasp     glyfpe    headu      6hheaA  4   $hmtxf]    ~locabk3  <  vmaxpS  X    nameD  p  ;Xpost6z   3prep~     A    ZR_<                                          : Q  c       
       X   X   KX  ^ 2   	             ADBE   "  `                M      X      S F @     ~ @ F  F  J 8 R 3 * # . < > = 5   t F b b  	 T 7 A ^ l , @ J ; D k A B & J $ F 2  @     8  J i V <  = H C / 7 R 4 H O * L > $ H / H / t 5 1 >   %  F j  i 4    ` C $   G p   + F F e   F    > 0     <    g 	 	 	 	 	 	 7 ^ ^ ^ ^ J J J J  B & & & & & T  @ @ @ @  I = = = = = = =  C 7 7 7 7 O O O O / H / / / / / F / > > > >  H  	 = 	 = 	 = 7 C 7 C 7 C 7 C A   / ^ 7 ^ 7 ^ 7 ^ 7 ^ 7 , 4 , 4 , 4 , 4 @   J O J O J O J O J O ; * D L L k > k > k > k  ! > B H B H B H & / & / & /   F t F e F t 2 5 2 5 2 5 2 5  1  1 @ > @ > @ > @ > @ > @ >      8 F 8 F 8 F  : . & / @ > 	 = J O & / @ > @ > @ > @ > @ > , 4 & / 2 5  1 * 	 H / H 4 6 7 / <   4 2        S                     |        p     E  "              s     v    A / A / , 4 @ H @ H k > 7 > k > A $ B H B H B H F j F j F B 2 5 2 5  1  1         8 F 1 @         P     4 F F                             O C   [ -  C O X $ F                                                                4    ~1Ie~7CRTYaeoy$(.1CIMPRX[!%+;Ico    " : D q y          ""        4Lh7CPTXaeoy #&.1CGMORV[ $*6BZl    " 9 D p t }         "" wnl@%
 zsrmkZWTSROM
zjbRJHE?}zuigfc_]Z                                                                                                                                                                                      
                                                                     	 
                        ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ 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                                     t f g k z  r m   x l       u     i y           n ~      e p  ?     o    d       6       {                    v s}~ |w    ,K 	PXY D 	 _^- ,  EiD`- , *!- , F%FRX#Y  Id F had%F hadRX#eY/  SXi  TX!@Yi  TX!@eYY:- , F%FRX#Y F jad%F jadRX#Y/- ,K &PXQXD@DY!! EPXD!YY- ,  EiD`  E}iD`- , *- ,K &SX@ Y &SX#!#Y &SX#! #Y &SX#! #Y &SX#!@#Y  &SX%EPX#!#!%E#!#!Y!YD- 	,KSXED!!Y-  + ++% + .&  + +  E}iDK`RX Y     s    H  B {                    6 D .4jlbFDT		L		

V

>*r(,&\zt2VtTl(T0 ^f6Pn,4p>pz $ 0 < H T ` l     !!!!&!2!!!!!!!"""""""# #|######$~$$$$$$$$$%n%z%%%%%%&v&&&&&'*'6'B'N'Z'f'(v((((((((((()))))))*4*******+++ +,+8+D+,,&,2,>,J,V,b,-4-@-h-t-----. ...$.0.<.H....////&///////0:00001
11"1.1:1F1R1^1j1v111111111112222*2333(343@3L3X3d3p3|334"4z45B566l6x66666666666777 7,787D78*868B8N8Z8999:l:;;h;<H<==^=>>`>>?2?n?@$@,@4@X@|@@@@@@@@@@@@@A.AAAABBPBdBBBCC@CbCCCCDD6DjDDDEE0EEF:FGG^GGHJHHIIDIIIIIIIIJJJ J,J8JDJRJbJnJzJJJJJJJJJJK KKK&K2K>KJKVKbKnKzKKKKKKKKKKKL
L~LLLLLLLLLMM,MPMZMhMvMMMMMN N4N>NHNRN\NfNpNzNNNNNNNNOOOO&O0O:OP.PQdQR:RSJST$TTU UULUpUVV@VVW WWX
X,X>XRXrXXXYY<YfYYYZZJZZ[
[P[[\\2\^       -   EX /  >Y  EX /  >Y 	ܸ 01'3#4632#"&`49++99++9-77--99 S/' |          F        EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y    +    +  
и и  и и  и и  и 017#537#53733733#3##7##7#JUO[ThTO[T_UgUh^n^^n^nn     @ , G  / '/ &ܹ    ܺ   &9 и     & 9 & )01.#"#5.'732654.546753#?)E+AKA+VTb1h&@0U0$&+ALA+XLb4M.+>-?])!d!*>.AV+    H'D&      J 
  A    EX 3/ 3 >Y  EX !/ ! >Y  EX /  >Y !    3 !9  ! 39  +и и 3 ܸ  и и     ;   >017327.'>54&#"&'#".54>7.54>32>71(  #?-%{, 3(#DF%Y73N5&*<%JS#,= 	%.C$$#").'<m3 	w/"3C& 5+$&G#>/PD3,&; J,  /      +01'3##Z    M       +01.5467bqqbRYQ)@-RW䎎WAWv;i`Y+A  ~M    	  +01>54&'7~-@)QYRbqqbr+Y`i;vWAW䎎W   @ [6  /  /   9    и  
и  01?'7737'xaNa@ttDG++GD,     F ^6       +  и  	01#53533##llhh     '       +0165#".54632'A/>>jh-a&/8[Q`  F~          EX /  >Y 0174>32#"&++@44@i+  +2CC     J`     EX /  >Y  01#3{I{f    8   ' 3 K   EX 
/ 
 >Y  EX  /   >Y 
       (  9 (/ .01".54>32"32>54."&54632,7Z@##@Z77Z@##@Z7)))) ++  +++T|QQzS))SzQQ|T+!1R>>S33S>>R1)##))##)   R  {  =   EX 
/ 
 >Y  EX /  >Y    и 
 й  01%!53#5>7398O#lwwwo[
     3   ! C   EX /  >Y  EX  /   >Y    к    9   017>54&#"'>32>;!:DpP,62&?O17=%2R;!&AT.?#T9cVL"/1'O&5J.(SSS(|    * - S   EX /  >Y  EX */ * >Y     *9 /      "  901732654.#52654&#"'>32#"&'n O,4C,J8^M2,&@!J/k>4V>"@9<R)E\2Rv%$'$"h/&!%Z&+-@*2EM>,E/1)  #  .{ 	  Y   EX /  >Y  EX /  >Y     +      	и  и 	 и   015467###5!533U$`}P	PkO6pe~   .{ $ U   EX /  >Y  EX !/ ! >Y   	 + !    ! 9  и   01732654&#"'!!>32#"&'p I-6EA3A&,O<#)EZ1Ss'%2102	*A|w0J35R93&   <!  2 W   EX // / >Y  EX %/ % >Y    + %     % /9    /  01%2>54&#".#">32#".54>32:#4*<$< 5)"S$*G5%?R.1\H,.Mb5Df b'1+"&3/L8!$0J22N8$LwTYT)-     >  {  3   EX /  >Y  EX  /   >Y    	013>7!5!#+D2<J*Oys?|ZCu}]     =   > W   EX '/ ' >Y  EX :/ : >Y   '     9 / /и // ܸ  01732654.'7654&#"4>75.54>32#".B1-7)8"#0.,#1F!+(5 9P/0M65&,  =Z:7X>!*/'(2+2%-$%',/&G3(A.-A'-F(3 &@/.@    5  2 W   EX %/ % >Y  EX // / >Y     +  / %9    %   /  01267.#"32>7#".54>32#"&'<$#4c< 5)#S#*H5%?R.1]H+.Lc4Df!V#%3'1+/M8!%0J21O8$LwTYT).    "'   C    '"'   C     t y  ;      +   и /      9  и /  01%%t	~  F & t     b y  ;      +   и /      9  и /  015%5%5~	  b  ) *   EX '/ ' >Y   
 + ' !ܸ  01&>54&#"'>324632#"&'"* 0R$b<+K7 $("9++99++9 !5*"   K(2)=)!0("%+-77--99   m& 6 @ ?     ' + 1   + :   + >   +   19  = 01%#'##".54>754.#"3267#".54>3232675&N<)/"#A\9 2!#F8#$;L)-;**T6<oV30Rm=9S5#F9d3#&3(;)2'"JuRNsM%I0cff`.&BY4\$    	  O 	  A   EX /  >Y  EX /  >Y 
  	 +     01'.'###3#n(˰˜<1n34m1<st    T  -   & W   EX  /   >Y  EX /  >Y %   9 %/    % 9      & 0132+2654&+254&+T3W@%*FH&D[560143@v9=@&>/,&JB2H/+%% Y+'     79  9   EX /  >Y  EX /  >Y      014>32.#"3267#".70TrA?a!Q6##:+\J#9QR|?pT1BQX.3 [6N1eo Y`+T}   A  ,   9   EX  /   >Y  EX /  >Y       0132+72>54.+AGtR--QpD&?--?&&OzTT|Q(w1P;:O/b     ^    M   EX  /   >Y  EX /  >Y        9 /     01!!3#!!^%H|{|     l   	 C   EX  /   >Y  EX 	/ 	 >Y      	  9 /  01!!3##l||     ,# # M   EX /  >Y  EX /  >Y         9 /  014>32.#"32675#53#".,/Qn?B] Q2' 6(MN"_!l??mQ.BRW.3 [6N1eo

px0+T}    @    I   EX  /   >Y  EX /  >Y 	   9 	/     и  013353###@t  J    A   EX /  >Y  EX /  >Y       и   	0173#5!#3!JĘ<|||l|  ;  5   EX /  >Y  EX /  >Y     0173265#5!#".':B32:]C:84H3D'{R0U@%)  D  R  k   EX  /   >Y  EX /  >Y  EX /  >Y  EX /  >Y    9 	   9 	 и  
01333##D֣Lxd   k     +   EX  /   >Y  EX /  >Y  013!!k"K|    A    M   EX  /   >Y  EX /  >Y    +   и  	и     0133?3#54>7##/##AB?w32A21uZZtOTOOTO   B    Y   EX /  >Y  EX /  >Y   9    к   9     0133.=3#'##B8849tE6|:  &2   5   EX 
/ 
 >Y  EX  /   >Y   
  01".54>32'2654&#",:aE&&Ea::aE&&Ea:3<<33<</X~PP}U--V}OP~X/scbnnbcs  J  7   G   EX  /   >Y  EX /  >Y    9 /       0132+#254&+J5]E()F\4[w<;R1Q;9T6Rh3*    $ND  * K   EX /  >Y  EX /  >Y '   +         $01"32654&#".'.54>323267)4::43;;00PA0Xh&D`;:`D&^QC#nbcsscbnJ	.A&P}U--V}O#   F  H   S   EX /  >Y  EX /  >Y 
  9 
/        и 
 013254&+'##32Hw<;H}M4[E(@4`a0&/N:H]  2' / I   EX /  >Y  EX ,/ , >Y    , 9       ,901732654./.54>32.#"#"&'%W+3/%T3&#?X5<p-K"B*+/</OAK"@^=B5&"	$
 +9$(G5,*]"TE)I7!//      9  3   EX /  >Y  EX /  >Y    01#5!##Ô||     @  3   EX  /   >Y  EX /  >Y     	01332653#"&5@,//-swxv`;>>;o      I  3   EX  /   >Y  EX /  >Y     
0133>73#NMı6e66e60t     T ! M   EX /  >Y  EX  /   >Y   
 +     и  и   0133>?33>73#'.'##-Y+Q)
	'*R**R*(T**S)[tAA       F  ]   EX /  >Y  EX /  >Y    9   9  к   9  к   90133>?3#'.'##г?:GDO={33{33     H  @   EX /  >Y  EX /  >Y  EX /  >Y   901733>?3#ҞBBҔ&H''H&P   8  # 	 =   EX /  >Y  EX /  >Y    и    017!5!!!825Y{YI|    h       +    +01!#3!'N@N    J`     EX  /   >Y 013#J{I{   ih        +    +01#5!!5'JNN   V 	 &   EX  /   >Y ܺ    9 	013#/##vy.--.yt  <\        +01!5 6nn   >~    =  )    EX /  >Y  EX /  >Y  EX /  >Y   9 /     !    !9   9  $   % 0174>7.#"'>32#'##".732675=$O|X33$I*43u@hxx&Z0&<*% !:7H**?,"&`&nr8')6+R  H)  !    EX /  >Y  EX  /   >Y  EX /  >Y  EX /  >Y   9   9           ! 013>32#"&'##732654#"HI$.K3$<M*#Es-)8[/-N$A]9@dE$" 6EM.  C$  9   EX /  >Y  EX /  >Y      0174>32&#"3267#".C/Oh9;_ D77@PM>'B<-m3;dK*>aB#&['LAAL]&##Ba     /  #    EX /  >Y  EX 
/ 
 >Y  EX /  >Y  EX /  >Y   9   9           ! 0174>32'53#'##".732675.#"/$;L)+:xH&/M72.*));=`C$MC3$$C`?JDD    7"  # C   EX /  >Y  EX /  >Y #   +       0174>32!3267#".%4&#"7+H]29X:Q7"=!0*h2:dJ+f.3(>
=`C$$@W3$	81X#C`t*4.0     R  I  V   EX /  >Y  EX /  >Y  EX /  >Y     и    	01&#"3###5754>32-170-6T:+K B*-s}m+J7     4-<  D P    EX "/ " >Y  EX %/ % >Y  EX $/ $ >Y  EX @/ @ >Y  EX 
/ 
 >Y @   
 и и 
 7  /ܹ E  1 E /9 1 и % &  $ '  " K 0132654&+"&'475.54675.54>323##"';2#".2654&#"C;<J,+>#xM!&#:M*.$e	 7K+ $(,\bg*LnC0S<"--++>#$=&( 2A,-C-k#+>)
:C'B/0k))())())  H    e   EX  /   >Y  EX /  >Y  EX /  >Y  EX /  >Y   9      013>32#4&#"#H#)1TM )-_l^2.     O     ;   EX  /   >Y  EX /  >Y       ܸ 01!##%"&54632OZ
+77++77}0))33))0    *<   A   EX  /   >Y  EX /  >Y         ܸ 01!#"&'73265#%"&54632OZ5YC.K +15'
+77++77.-R>%i
36e0))33))0  L  I  m   EX /  >Y  EX  /   >Y  EX /  >Y  EX /  >Y    9 	   9 	 и  
 013373#'#L˟IkM}    >   5   EX  /   >Y  EX /  >Y      01!3267#"&5#>#&!""&^_	l
o_  $  =      EX /  >Y  EX /  >Y  EX  /   >Y  EX  /   >Y  EX /  >Y  EX /  >Y     9  	и    	        0133>32>32#4#"#4#"#$n1+!-	5*4:q>+)("/UKQ.0Q.     H    e   EX /  >Y  EX  /   >Y  EX /  >Y  EX /  >Y   9      0133>32#4&#"#Hx S8TN )-B .l^2.     /)   5   EX /  >Y  EX /  >Y     0174>32#".732654&#"/*G[11[G**G[11[G*33333333>aB##Ba>>aB##Ba>ALLAALL   HH)       EX 	/ 	 >Y  EX /  >Y  EX /  >Y  EX /  >Y  	 9   	9       	      01#33>32#"'732654#"ۓxN(.J4$<M*D8-*8[/-'2#$B]9@cE$6cEM.  /H  #    EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y   9   9           ! 0174>32373#57#".732675.#"/$;L)*AsF#/M72.*));=`C$!3XL $C`?JDD    t  $  T   EX  /   >Y  EX /  >Y  EX /  >Y    9      0133>32.#"#tx%h<!)%.Y l=;

{6C     5 / I   EX /  >Y  EX ,/ , >Y    , 9      ,901732654&'.54>32.#"#"&'w+W23,I<!?2 ;U5Bm'B"H'/'"/%B2 =[<C0 	#.":(+X
"0 ":+,   1&t  M  /  EX /  >Y  EX /  >Y     и  и   01#5?33#3267#".5}y260!Q0;R3}ms9/
j
 9P1   >  e   EX 
/ 
 >Y  EX /  >Y  EX /  >Y  EX  /   >Y   9      01!#'##"&5332673x!P6UL*+G&-l^22.!F    9  <   EX  /   >Y  EX 
/ 
 >Y  EX /  >Y  0133>?3#NN&L''L&      T ! t   EX  /   >Y  EX 
/ 
 >Y  EX /  >Y  EX !/ ! >Y  EX /  >Y    !9  к    90133>?33>?3#'.'##
g!M	%H&&J#%H&&H%#G(D3    %  2  e   EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y   9   и  и 01'33>?3#'.'##ѡ3

,91P+,PR,+R  >;  [   EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y      901326?33>?3#"&'7]+1
גS
I*6G/&H$#K'%K%/G/p     F   	 =   EX /  >Y  EX /  >Y    и    017#5!!!F)O.sNs     jh 7 +  3  4 +    +   
 + ' 
 9014>54.'5>54.546;#";#"& 5((5 Z`M)(	.66.	()M`Z
*''V('+Q=N(N-93		39.L)N=   m      +013#낂  ih 7 +     5 +    + '  ( +  ( '9012>54&54675.54654.+532+5'	.66.	')M`Z 5))5 Z`MJ)L.93		39-N(N=Q+'(V''*Q=N   4 $  '     +    +  и  01>323267#".#"4 T/.'#&X T/.'#'NC(*)NC(*  R      EX /  >Y 	ܸ 01#737#"&54632p`49++99++9)-77--99   `  $ \   EX /  >Y !  
 +     +    и  / ! и / 
 и / ܸ  и /01#5.54>753&'>77$$%#D"Q1O8 :N/Q'?C$@--AE__(AX65V?)a]Z  C  & * W   EX /  >Y  EX /  >Y    +     и      и  #01%!5>54'#57.54>32.#"3#&4BpT"<T2>Y#O,07||[O6V(/L5*'P.0$[$4    $ ?4S  *   "   +   ( +01?&5467'76327'#"'32654&#"$Q"PIY0642YIQ"RIZ47.Zi2$$22$$2R.A 7RJZZJR-@!7RJ[[-55--55      9{  l   EX  /   >Y  EX 	/ 	 >Y  EX /  >Y   	9  й   и ܸ й   и  013>?33#3##5#535#53=={!B !B F7FF7F%  m       +   +013##낂Jl:     G  A O  +  % + >   + . % 9  > +9  . 9   к 8  .9 8 01654.'7.#"#"&'732654.5467.54632 3>$ 2=%86(=G=(+)0H/7j"T3<';E;',&]U:\ Q!&!' -@-,A&":*)+K3-@/&C(DU)   p;    E  ' E M   EX /  >Y  EX /  >Y    #  -й 4   Aй : 014>32#".732>54.#"4>32.#"3267#".-Mf99fM--Mf99fM-@9P11P99P11P980?"'57%'&!/7!&?.ENzU--UzNN{W..W{N>dH''Hd>=dG&&Gd>,G2==-3<D3I   U   + '|         F ^~       +01!#5!Fl~ F~    e7  ' 5 > =      + 
   + 6  2 +  )и 2 /и  4и 101".54>32'2>54.#"'32#'##72654&++)H66H))H66H)5''5 4''41Y#.*<:N76J,,J66J,,J61(8##8((8##8( "M<<d6 P         
   +     +01".54>32'2654&#"-5''55''5%%%%'4 5''5 4'F)! )) !)   F  6   D   EX /  >Y     +  ܸ  и   и    01#53533##!!ll4&hh6h             >    ><K ' s  '/  EX  /   >Y  EX 	/ 	 >Y  EX  /   >Y  EX /  >Y      	  9      013326733:7#"&'##"&'#>#"0%19>%%6*"+2,`]Tm0.,-	<c7  0   %   EX  /   >Y  EX /  >Y013##".54>;|4(1WB&&AV1*$;W9?U5            #         U   < .'|          Q|'D&        G|'D&        R'D&      gF  ) *   EX '/ ' >Y 
   + ' !ܸ 01%3267#".54>'7#"&54632'"*  0Q$b<+K7 $("8,+88+,8"4*" ! J)2(>)!0("%+-77--99  	  O6& &  #     	  O6& &  $     	  O6& &  %     	  OG& &  &     	  OH& &  *     	  O}& &  ,       S   f   EX /  >Y  EX /  >Y  EX /  >Y    
 +    +        01#!5##!#3#7pv-|vv1]+]|||  7#9& (  /0    ^  6& *  #    ^  6& *  $    ^  6& *  %    ^  H& *  *    J  6& .  #     J  6& .  $     J  6& .  %     J  H& .  *        2  ! S   EX /  >Y  EX /  >Y     +        и   01#5732+72>54.+3#GEEFtR--PqC&?--?&kk-B&OzTT|Q(w1P;:O/G B  G& 3  &    &26& 4  #     &26& 4  $     &26& 4  %     &2G& 4  &     &2H& 4  *      T p#  )   	 + 
 	 9 
 и 
 и 01?'77'TIIIJJJ   C   * }   EX &/ & >Y  EX /  >Y   &9   и      &9  	и &    и   и  и 	 (01732654&/&#"#"''7.54>327%3<&)3<<&Ea:R;3N@&Ea:U?5Nsc!l$nb,$'*kBP~X/,I2]+rFP}U-0M2 @6& :  #     @6& :  $     @6& :  %     @H& :  *       H6& >  $      I  6   9   EX  /   >Y  EX /  >Y    +    +01332+#7254&+I[5]E()F\4[w<;Rc1P;:S6{h3)   =; 9 Z   EX /  >Y  EX 9/ 9 >Y  EX /  >Y "    "9  4  %  49014>32#"&'732654.54>54&#"#=8V90H.")",A+*?"1*")")&.P;!/= $1'!%3$"<,d".!,(+#<3    =& F      =& F      =& F      =& F      =& F      =& F       Q 0 9 E    EX /  >Y  EX /  >Y  EX &/ & >Y  EX ,/ , >Y 1   +   ,9 /     & 9 &   ) & 9  6  , <   C 017467.#"'>32>32#3267#"&'#".%4.#"3267./or94*P+,7:,&:'0#%2H 6G'C""3#%.!1+MS#$`(!%$&AW1"
33^*#)$(7$140')    C#$& H  )    7"& J      7"& J      7"& J      7"& J      O  &   -    O  &   -    O  &   -    O  &   -     /&  4 k   EX // / >Y  EX /  >Y #  	 +     & / 9 &    / 9  )и  2и ,01%265<'.#"#".54>32.''7&'77,4=8 6? ,@O#A_<3ZC($>O,$B1#&x+3@&I"&kLK	:<-<r<fJ*">Y76T:-I KA<Y)EA H  & S      /)& T       /)& T       /)& T       /)& T       /)& T        F IK    %     +   ܸ ܸ  ܸ 01"&546324632#"&!!,#..##..t.##..##.4+""++""+"++""++
h  /)   * }   EX &/ & >Y  EX /  >Y   &9   и     & 9  	и &    и   и  и 	 (01732654&/&#"%#"''7.54>327"33$"33!*G[1L?,7.!*G[1L>-7{QAAQA#!X7>aB#(5*8 X7>aB#'6+  >& Z      >& Z      >& Z      >& Z      >;& ^       HH)  $    EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y   9   9        "   $ 01#3>32#"&'532>54&#"ۓG&.J3%<M(%<.#,0.-uL$B]9@cE$Q$7&CC.  >;& ^      	  O-& &  '     =& F      	  O6& &  (     =& F       	!e 	 ( e   EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y %   +     +   01'.'##"&54>7#'##33267n;0B('(˰!<1n34m1<61-)!t	    =.+ 1 =    EX /  >Y  EX -/ - >Y  EX /  >Y  EX  /   >Y   -9 /         (и - 5   9 0174>7.#"'>323267#"&54>7'##".732675=$O|X33$I*43u@hx1'
:-=	&Z0&<*% !:7H**?,"&`&nr0B.-%:')6+R    796& (  $6    C$& H  )    796& (  %6    C$& H  )    79W& (  )6    C$& H  )    796& (  .6    C$& H  )    A  ,6& )  .    x& I 8     2     /R  *    EX /  >Y  EX '/ ' >Y  EX /  >Y  EX /  >Y   ) + !  9 !            9     и  $и ) %01&#"3267#'##".54>32'5#53533}'**<2.*BxH&/M7$;L)+:BO!>BE?3$"A\;:]A"M,GJJ    ^  -& *  '    7"& J      ^  6& *  (    7"& J      ^  W& *  )    7"& J       ^!* # ^   EX  /   >Y  EX 
/ 
 >Y  EX "/ " >Y    +    +     "  01!!3#!#3267#"&54>7!^%
!;0C|{| 	J1-(!    7." 1 8 ^   EX "/ " >Y  EX /  >Y  EX /  >Y 8  * +     .  " 5 01%3267#"&5467#".54>32!3267'4&#"!+	
:-;%:dJ++H]29X:Q7"=!A.3(>
.$B.-%:#C`>=`C$$@W3$	81*4.0 ^  6& *  .    7"& J      ,#6& ,  %    4-<& L      ,#6& ,  (    4-<& L      ,#W& ,  )    4-<& L      ,#& ,  "    4-<& L  9    @  6& -  %      f& M  %j 0    U      EX /  >Y  EX /  >Y  EX /  >Y  EX 
/ 
 >Y  ܹ    ܸ   и      и  и  01#37#####57533533====UUA`___         EX /  >Y  EX /  >Y  EX /  >Y  EX 
/ 
 >Y    +    9         и  и  01>32#4&#"##57533##)1TM )-BBl^2.,AKJG/ J  G& .  &     O  &   -    J  -& .  '     O  &   -    J  6& .  (     O  &   -     J! # `   EX /  >Y  EX 
/ 
 >Y  EX "/ " >Y    + "       и   0173#5!#3#3267#".54>7#JĘ)"";)|||l|/	J#(!   O.  & g   EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y      
   ܸ !01#5!3267#"&54>7#"&54632Z(
:-=	*C+77++77}s/B.-%90))33))0 J  W& .  )      O    /   EX  /   >Y  EX /  >Y    01!##OZ}   ;6& /  %    *<&\  -    DR& 0      LI& P       L  I  m   EX  /   >Y  EX /  >Y  EX /  >Y  EX /  >Y    9 	   9 	 и  
 013?3#'#L˟JH{   k   6& 1  $    > m& Q  $7   k & 1       > & Q  >    k   & 1  8  > & Q  8    k  '& 1    9& Q    !     I   EX /  >Y  EX /  >Y      9  и  и 	01%!55737 KJJ||)r)Tqrq  >   W   EX /  >Y  EX /  >Y 	  9 	 и    	 и и   01%#"&=575#5!73267 ""&^_qq#&
o_R?u@tPuQ	  B  6& 3  $    H  & S      B& 3       H& S      B  6& 3  .    H  & S          & m   EX /  >Y  EX $/ $ >Y  EX #/ # >Y  EX /  >Y   +    &  #9 & ! 0167#"&54632%>32#4&#"#3.i
)25*9=WXfG2JE!xp/[2*.7UKR}(-k]!1-@  &2-& 4  '     /)& T       &26& 4  (     /)& T       &26& 4  -     /)& T          S  ! O   EX /  >Y  EX /  >Y 
   +       и  014>3!#3#3!".7;#"*Je;"yy:bH(((ITzO&{{|(Q|T;Q1/N     P  4 =    EX /  >Y  EX /  >Y  EX */ * >Y  EX 0/ 0 >Y 5   + 0    	   * 9 * #  - * 9  : 01732654&#"4>32>32#3267#"&'#".%4.#"  3D&+<>%%:'/#"2F'C:-&C2"AMMAAMMA>aB#/'*,&AW133^(%&'#Bam$14   F  H6& 7  $    t  $& W  '    FH& 7      e$& W      F  H6& 7  .    t  $& W  '    2'6& 8  $    5& X      2'6& 8  %    5& X      2#'& 8  /    5#& X      2'6& 8  .    5& X      #9& 9  /     1#&t& Y  I      96& 9  .     1&& Y  8    @G& :  &     >& Z      @-& :  '     >& Z      @6& :  (     >& Z      @}& :  ,     >& Z      @6& :  -     >& Z       @! ( R   EX  /   >Y  EX 	/ 	 >Y  EX %/ % >Y    + %   % 013326533267#"&54>7.5@,./.>>$
";0Cjh`;>>;o^w
	J1-&v     >.! (    EX /  >Y  EX '/ ' >Y  EX /  >Y  EX /  >Y  EX  /   >Y      к   9  #   & 01!3267#"&54>7'##"&53326732&
:-=
!P6UL*+/B.-%I&-l^22.!F    T6& <  %       T& \        H6& >  %     >;& ^        HH& >  *     8  #6& ?  $    F  & _      8  #W& ?  )    F  & _      8  #6& ?  .    F  & _       ) 
 )    EX /  >Y  EX #/ # >Y  EX /  >Y  EX /  >Y   " +   9             9  
  " !и " &и  '01732654#"'>32#"&'###57533#-)8[/-I$.K3$<M*#EsBB@H|.m"?Y7>`B#" 6,AKJG/    :0  " C   EX 
/ 
 >Y  EX /  >Y    +    
  013267>32#".547!.#"5*'7	"[?7[B$%B]88\B$`;6#2KKLKG )-W}PP~W.-V}OSU  .& + B   EX &/ & >Y    +   	 + &   	 и   01.#"3##"&'7>?#5737>32
&'s-G6!2WK2I4
+#7k-N:!	l 6+e+7N2   &S  , G   EX $/ $ >Y  EX /  >Y    $     $9  &01%2654&#"#".54>32>54&',3<<33<<=>0$)&Ea::aE&&Ea:B8 
sscbnnbcs)3<+RP~X//X~PP}U-	   /I~  - G   EX $/ $ >Y  EX /  >Y    $     $9  '01%2654&#"#".54>32>54&',33333332<."(*G[11[G**G[15$
kLAALLAAL)3:!_=>aB##Ba>>aB#    @$ " J   EX /  >Y  EX /  >Y  EX /  >Y      01#"&5332653>54&'w!.swxv,//-F
$)+`;>>;	    >n # a   EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y 	  9   	  01#'##"&5332673>54&'Q8)x!P6UL*+1
)19>G&-l^22.!F    	  O6& &  .     =& F      J  6& .  .     O  &   -    &26& 4  .     /)& T       @6& :  .     >& Z      @& :  1     >9& Z  0    @& :  3     >P& Z  2    @& :  5     >P& Z  4    @& :  7     >P& Z  6    ,#6& ,  .    4-<& L       &!2 & 2 K   EX /  >Y  EX 	/ 	 >Y #   + 	 и 	 '   - 01#"&5467.54>323267'2654&#";0C(<Y;&Ea::aE&.@'& 
`3<<33<<1-'<;\uAP}U--V}OCiQ85	scbnnbcs   /.) & 2 \   EX /  >Y  EX /  >Y  EX $/ $ >Y  и $    *   0 01467.54>323267#"&32654&#"%-Q<$*F[21\F*.@'$
:-=33333333w&8(BZ9>aB##Ba>2L<-.B.ALLAALL    2'& 8  
    5& X      9& 9       1&t& Y  D     *<  5   EX  /   >Y  EX /  >Y      01!#"&'73265#OZ5YC.K +15'.-R>%i
36e  	  0   , c   EX $/ $ >Y  EX /  >Y    и и и и $     9   и  "и !01%2654&+3#3254&++5#5732)<>==Bjj5g336FH'C\5KK3W?$49i644/@GF$Q$ OE4K1A%<,)J  H"  ) v   EX /  >Y  EX /  >Y  EX /  >Y   9 /      9  !   $   % 013267#"&533>324&#">"$O|X33$I*43u@hxx&Z0%=*% !:7H*g*?-"&a&nr8')6+R  /  #    EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y     9      9     
 01732675.#"4>32373#'##".2.*));$;N*&CsxK$/M7JDDH=`C$!33$$C`    H)  "    EX /  >Y  EX /  >Y  EX /  >Y  EX /  >Y      9      9     	 01%4#"3267#"&'##33>32^+,):$<N*"FsxN+.J3DRAdE$" 63$$A\  4  5   EX /  >Y  EX /  >Y     01%#"&'732654&#"'>32,Kg:5i+<=%AQI< :D h?9cK+>aB##&]LAAL[&#Ba     6!  # C   EX /  >Y  EX /  >Y    +       01%#"&'73267!.54>32.#"!+Jd:2h*0!="7N >[;0ZD)	7*25>`C#X18	$3W@$$C`0.4*     7"  # C   EX /  >Y  EX /  >Y #   +       017467!.#"'>32#".732677O
A6"B1+g2;aE&)F]3:X<12+;$	61\$C`=<aC$$AX+5-3  /<   /    EX /  >Y  EX /  >Y  EX /  >Y  EX 
/ 
 >Y      9   9 
 !   $   %   ( 01326?#".54>32373#"&'2675.#"#M79I#/M7#;N+N9s*j,+*$6,/#@$AY69]A$?3 eo!0>B  <H  a   EX 
/ 
 >Y  EX /  >Y  EX  /   >Y  EX /  >Y  
 9     01#57#"&5332673S8TM )-_-l^22.K      9      EX /  >Y  EX /  >Y  EX /  >Y  EX  /   >Y  EX /  >Y  EX /  >Y    9 	  9    	        01!#'##"&'#"&533273326739n1, -	5*4:q>+)(!0UK\.0O.O    4  T   EX /  >Y  EX /  >Y  EX  /   >Y   9      01!#'##"&'732673x%h<!)%.Y l<<

|6C  2|'  A   EX /  >Y  EX /  >Y    и  и   01%3##5#5354&#"'>32}y260!Q0;R3sss9/
j
9Q1      9  @   EX /  >Y  EX  /   >Y  EX 
/ 
 >Y    901!#'.'##39NN&L''L&       T ! i  /  EX /  >Y  EX  /   >Y  EX /  >Y  EX /  >Y    9   9   901!#'.'##'.'##33>?3T
g!M	%H&&J#%H&&H%#G(D3      9  R   EX /  >Y  EX /  >Y  EX /  >Y      9  01&#"#'.'##>32).גS
I)5E.$O(-#K'%K%	.H1p    H  c   EX /  >Y  EX /  >Y  EX  /   >Y  EX /  >Y    9 	   9 	 01###73753˟J}$H{    :  / /  EX  /   >Y    +   9   013>32#54&#"#h5$92hhp<H>˾       4   EX  /   	>Y    +       ܸ 013#"&'7326=#7"&54632$<.0"~&&''M7)
I	#~!##!  U  6  /  EX /  	>Y    +   9   0133>32.#"#V@#5hMH)'V",    SM ! Z  /  EX  /   	>Y  EX 
/ 
 	>Y  EX /  	>Y    и 
     0133>?33>?3#'.'##SfG^1xwM02dd00f/,#f   M  A   EX /  	>Y  EX 	/ 	 	>Y    +   9  017326?33>?3#"&'7h/(ct".?./ 0N   "   "           +   +012654&#56'2$$2QNNQ2&&6E88E     p      +    +01"3&546p2%%2QNNQ&&6E88E   >   >    yx      +013#Z    P   >   >~    x b       +01#3xZk   >   9   $   .    ?   =       (   EX  /   >Y    +    0133267#"&=#
%D<DPK?   U ) +    & +    +  & 9   90132654&'.54632.#"#"&'50'!PF+D/,-)!RN*Sk	.:=!->  |M  K  / /  EX /  	>Y  EX /  	>Y   9   и  и 01'33>?3#'&'##holioo"l3333   >~      +013#Yk  >       +01#73EkY>     >       +  ܸ 013#'##|dk55k__  ?  '     +  ܹ   и  01>3232673#".#"#	>.K	>.
K?IFHG     P       +01!!]   >    	    + 	 ܸ 01".'332673,%7$RR$7>+9 ++ 9+   9        +01"&54632,+77++7790))33))0    p;         +   и  01"&546323"&54632#,,##++#++##,,;-"!--!"--"!--!"-   -        +   ܹ  01>54&'7$+\L&3gJ1(%     $        +  ܸ 01"&54632'2654&#",3>>33>>3$7//77//77   =         +   и  013#73#u_Zu_[ԗ    >       +  ܸ 013373#k55kd|``  E=        +  и  01#'3#'3Z_uf[_u=    a      
 +  01632#"5467a8 B03'S*C     m    
   +  0167#"&546328B03J'S*C "~        +   01>54&'7"%
e.># ,)!0          +01"&54632,+77++770))33))0     (         +   и  01"&546323"&54632''''''''())(())(            +  	ܹ  01'>54&'7D50@$$/*'&%;6  #       +  и ܹ 
 01%3'>54&'V 0@$$/"/#%;  .      EX /  >Y    +014>733267#"&
S6
:-=w&*-B.    .    	    +01".'332673,#3"RR"3&3""3&    C        +01!5!^    U  " 9  /    +    +     +   9   01467&#"'>32#'##"&732675\g5.%!L(AJU309d6)_5:
+CIN!:25      T  /  EX /  >Y    +    +   9   9      013>32#"'##732654#"h/?G(30)	Qh#8p1\K*C-+#_*2U        ! T  /  EX 
/ 
 >Y    +    +   9   9      014>32'53#'##"&732675.#"(3%gT0@Lk$(A,1o2 [R/*	*    U  " !     +    +    +014>32#327#".74&#"/; &9%2"&'#D&@0 '(@-+:!#=,@L!     zU  B N d   EX #/ # 	>Y   > + !  I + 8  	 + C  . +  	 89  и . 1и и # & 01732654&+"&'475.54675.54>323##"&';2#".72654&#",%&1(	U4'4A&2
<BGl\ 8(	 '!+-K*	&-5B	     S  / /  EX  /   >Y  EX /  	>Y 
   9 
   	  9 	 013373#'#hrq|pQ-h}},Q   sU  T  / / /  EX /  	>Y    +    +   9  и    0133>32>32#54#"#54#"#sN
 .$#'cPbM)6 :1    U        +    +014>32#".732654&#"/<!!<//<!!</j    )@--@))@,,@))11)*00     U   T  /  EX /  	>Y 	   +    +  	 9   	9      01%#33>32#"&'732654#"hU3?F(3'#8_ \K*C-E*2U     I   EX /  	>Y  EX /  >Y    +      и   	01#5?33#327#".5EJW #3(8"MVVQn$J&5!   M  A   EX /  	>Y  EX /  	>Y    +   9  01#'##"&=3326753U5#92hh-H=̿   vM  3  /  EX 
/ 
 	>Y  EX /  	>Y   0133>?3#vh00cuxM22      U       +    +014>32&#"3267#".3C%"50'//$ )@&@0)@-@0*)1	A,@    8  
/  EX /  	>Y    +    и  01.#"3##5#5754>32#<oogJJ%9'3}3	QM	0$    M 	 4  	/  EX /  	>Y 	    и    017#5!3!#;Q7Q A,& )      /& I  	    AC,& )      /C& I  	    ,#-& ,  '    4-<& L      @& -       H& M      @.& -       H.& M      k & 1       > & Q  >    7 -& 1  &'    > & Q  ' >    kC & 1       >C & Q  >    A& 2       $=& R      B  W& 3  )    H  & S      B& 3       H& S      BC& 3       HC& S      FH& 7      j$& W      FH-& 7  &'   j$& W  &'   FCH& 7      BC$& W      2'W& 8  )    5& X      2'& 8  
    5& X      9& 9       1&t& Y  D    C9& 9       1C&t& Y  D      T6& <  #       T& \        T6& <  $       T& \        TH& <  *       T& \        HW& >  )     >;& ^      8#& ?  
    F& _      1&d& Y     @5 * h   EX /  >Y  EX )/ ) >Y  EX /  >Y !    + 	 !  9     %   % 9014>32#"&'732654&/7.#"#@:[@WqH*!+@+8LL33
K%-(.Q<#eRz +9%(F3&Y( 3V}$=>Z      H6& >  #     >;& ^      H& >       H& ^       Hv& >  +     >;& ^        HG& >  &     >;& ^       P 6       +01!!PH6o    D6       +01!!06o   "      +01632#"&546757
(36*8=WXkD01*.7TLR}(     "     
 +0167#"&54632i	)36*9<VXp/\2*.7UKR}(          4"'|        F"$'|        F$ '|      e    
   +01%".54>32,#<,,<##<,,<e,:#";,,;"#:,          +01757>>77            +01%'7'?>>77     Gp       +01?'733e/0             *  /  EX  /   	>Y     ܸ 013#5#7"&54632h}&&''M~!##!                                  _\!     _\"      U  :  / /  EX /  	>Y    +   9   0133>32#54&#"#U5%83hhM*H>˾  K   W   W   W   W  W   K   W   W   W   K   W   K   W   W   W   K   W   K    W    !  W    "  W     U  ! !     +    +    +014673.#"'>32#".73267)!&#@ L]-; &9&X %#?\Q(?-+:!      O3   4    EX $/ $ >Y  EX /  >Y й       $   и  и   и  и  ܸ и  и $ !и $ #ܸ  (  # )и ( +и  1и  2и 2/01%&+#7&'#7.54>?33273&'672	24&($-&Z622KY"?X7222Q02%veKf7R).cciy vFqT4	gbdq
Oh	+     C  & 1 }   EX /  >Y  EX /  >Y 
   + $  ' +     
 и / ' и $ и /    
 *и  ,01%!5>7#573.'#57&54>32.#"3#3#&-?pO[C"<T2>Y#O,07||[A,EE/L5*'P.0
KJ)      <{     +    EX #/ # >Y  EX '/ ' >Y  EX /  >Y  EX /  >Y    + &    +     к 	  #9   
и & и #     и  и  и  и  и  и /   и & !и !/ & )01#3#3'3'#'3'#3##'##5#575#57533533;/!*;/!*GEEYKjFFFFYKjEV0:0:~0:404:     ;{   ! c   EX /  >Y  EX /  >Y    +    +     и  и  и   01267#53.##+##575323,6
6,5=+?P,,DD,P?*>3&#IH&"+>)|U'?-     [  2   - V   EX /  >Y "   +         " ܸ 'и  -  )и - ,017!!.#"3267#'##"&54>32'5#5353h]	"2*##Hd	;#N]2? %/yJJh+&0,aDn$b\*B/CJ11     -G 1 m   EX /  >Y  EX /  >Y ( $ + ( +  и ( и $ и $ !  и     . 01%#".'#57&45<7#57>32.#"3!3#3267G)d=3XG2@77@l3_%Q4 3BB1#6P-/9U8EDpz(&O>9JK7:       ;{    5    EX ./ . >Y  EX $/ $ >Y 	  " + .   й    ܹ    и   и  и  &и   )и  *и  -и  4016454&'#27#53&##3#+##575#575323w">~}@5;;F.<H',CCCC(H;-G-a''$$^:"1 Z4.41#    C & S   EX /  >Y  EX /  >Y    & +  и  и     " 013#5.54>753.#"3275#KI)b2S<"!<S3b*KQ4 BFJA"Lj$ff1QqGEoT5
he(Pqehlz  O3  $ {   EX /  >Y  EX /  >Y  EX 
/ 
 >Y  EX /  >Y         ܸ  ܸ   !и  "01#5.54>753.'67C012/!O/Q5ZA$#@Z7Q*NQ"+#jTUj$-ed0RrJGrT4][' OZ
(   X  {  p   EX /  >Y  EX /  >Y  EX /  >Y    и и и    и  й   
и 
/01#3##'#5327#573.+5!%LJI6VJtQE8J12J@QuGDu  $'{ # ]   EX /  >Y  EX /  >Y      9  "и и  и и и  и 01%>54&'7'55755753779,y;odUUUU}", DiE")Q)7)Q)~MQM7MQM    F~       +01!!F4~h   Gp    D   (   EX  /   >Y 
   +    01".54>32'2654&#", 6((6  6((6 ,?''=++=''?,O(33$$33(     8 
    EX 
/ 
 >Y     +01%#5>73#QSk@    D  ,   EX /  >Y    +     017>54&#"'>323!5'>@)<F2\7(% #8$:3#@W    D * :   EX '/ ' >Y    + 
 	 + '    	 
901732654&#52654&#"'>32#"&'-#& "*D)+ #$1F#`7	>!!
&%    8   8   EX 	/ 	 >Y    +    +   и  
01%57###5#5733A"!3^x3c>;B==3ȹ     8   D   EX /  >Y    +   	 +     	 9  01732654&#"'73#>32#"&'++Յ2;$1"D#`X#3.(     D 	 & F   EX /  >Y #   +    +       #9   01%2654#"7.#">32#"&54>323&d&"'.6!.HN)=) 6C."0.)]J"=.       8  &   EX  /   >Y    +  	013>7#5!# #	p"854W8 ;<B'   D   6 <   EX 4/ 4 >Y #   + 4    4 9  # 901%32654&'7654&#"4675.54>32#"&5&"-6H	#1<JW`z"!1*!5  D 	 ' F   EX $/ $ >Y    +    +   $9    $  01%3267.#"3267#"&54>32#"&'%#3&!!.-6!.#8'*=(!6
-!//),>%!=/         +017467.93O)**)O39Ow800g78g008w        +01%'>54&'793O)**)O39Pw800g87g008w     w6      +013#Qu6x  6       +01#73VuQx     6       +  ܸ 0173#'#``q55xx==     G  +      +   ܸ   и    01".#"#>3232673k"K<'"K<ECEC  -       +01!!-]   6        +  ܸ 
01"&'332673,BAQQAB66B    W        +01"&54632,%00%%00+""++""+    H         +   и  01"&546323"&54632''''''''((((((((   v       +   ܹ  01>54&'7$+\L&3I1(%   }        +  ܸ 01"&54632'2654&#",3>>33>>35--55--57   6        +  и  017373#?}Y}Zcxxxx   6       +  ܸ 01#'337``q556xx==    #       +  и ܹ 
 01%3'>54&'V!1@##/"/#%;  ;9    +      +   и  и  ܹ  01"&546323"&54632%!!########;#$$##$$#E       +  
   + 
 ܹ    и 
 01!!"&546323"&54632*########E$##$$##$    ;P    %     +   
 +  и 
 013#"&546323"&54632;~s^########Po#$$##$$#      )  
   + 
 ܸ  ܸ  и 
 013#"&546323"&546322vu########x$##$$##$  ;P    +     +  ܹ    и  013373#"&546323"&54632d..dV|%########P::o#$$##$$#       +      +   и  и  ܹ  01"&546323"&54632#'337########*``q55$##$$##$xx<<     ;P    )    
 + 
 ܸ ܸ  и 
 01#'3"&54632#"&54632p^s~r########o#$$##$$#         )  
   + 
  ܸ ܸ  и 
 01#'3"&54632#"&54632wuvi########Vx$##$$##$     $[        +01'3^$E   !        +  	ܹ  01.54>7OC61@$$/+!'&&;
6     >         .        e               #               A              `             	              '       $9  	   ,    	   E  	   u  	  F   	  (   	  /  	  $  	  .  	  4Q  	 	   	  2  	 #  	  H9 T y p o g r a p h i c   a l t e r n a t e s  Typographic alternates  S o u r c e   C o d e   P r o  Source Code Pro  B o l d  Bold  1 . 0 1 7 ; A D B E ; S o u r c e C o d e P r o - B o l d ; A D O B E  1.017;ADBE;SourceCodePro-Bold;ADOBE  S o u r c e   C o d e   P r o   B o l d  Source Code Pro Bold  V e r s i o n   1 . 0 1 7 ; P S   V e r s i o n   1 . 0 0 0 ; h o t c o n v   1 . 0 . 7 0 ; m a k e o t f . l i b 2 . 5 . 5 9 0 0  Version 1.017;PS Version 1.000;hotconv 1.0.70;makeotf.lib2.5.5900  S o u r c e C o d e P r o - B o l d  SourceCodePro-Bold  S o u r c e   i s   a   t r a d e m a r k   o f   A d o b e   S y s t e m s   I n c o r p o r a t e d   i n   t h e   U n i t e d   S t a t e s   a n d / o r   o t h e r   c o u n t r i e s .  Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries.  A d o b e   S y s t e m s   I n c o r p o r a t e d  Adobe Systems Incorporated  P a u l   D .   H u n t  Paul D. Hunt  h t t p : / / w w w . a d o b e . c o m / t y p e  http://www.adobe.com/type  C o p y r i g h t   2 0 1 0 ,   2 0 1 2   A d o b e   S y s t e m s   I n c o r p o r a t e d   ( h t t p : / / w w w . a d o b e . c o m / ) ,   w i t h   R e s e r v e d   F o n t   N a m e   ' S o u r c e ' .   A l l   R i g h t s   R e s e r v e d .   S o u r c e   i s   a   t r a d e m a r k   o f   A d o b e   S y s t e m s   I n c o r p o r a t e d   i n   t h e   U n i t e d   S t a t e s   a n d / o r   o t h e r   c o u n t r i e s .  
  
 T h i s   F o n t   S o f t w a r e   i s   l i c e n s e d   u n d e r   t h e   S I L   O p e n   F o n t   L i c e n s e ,   V e r s i o n   1 . 1 .  
  
 T h i s   l i c e n s e   i s   c o p i e d   b e l o w ,   a n d   i s   a l s o   a v a i l a b l e   w i t h   a   F A Q   a t :   h t t p : / / s c r i p t s . s i l . o r g / O F L  
  
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  
 S I L   O P E N   F O N T   L I C E N S E   V e r s i o n   1 . 1   -   2 6   F e b r u a r y   2 0 0 7  
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  
  
 P R E A M B L E  
 T h e   g o a l s   o f   t h e   O p e n   F o n t   L i c e n s e   ( O F L )   a r e   t o   s t i m u l a t e   w o r l d w i d e   d e v e l o p m e n t   o f   c o l l a b o r a t i v e   f o n t   p r o j e c t s ,   t o   s u p p o r t   t h e   f o n t   c r e a t i o n   e f f o r t s   o f   a c a d e m i c   a n d   l i n g u i s t i c   c o m m u n i t i e s ,   a n d   t o   p r o v i d e   a   f r e e   a n d   o p e n   f r a m e w o r k   i n   w h i c h   f o n t s   m a y   b e   s h a r e d   a n d   i m p r o v e d   i n   p a r t n e r s h i p   w i t h   o t h e r s .  
  
 T h e   O F L   a l l o w s   t h e   l i c e n s e d   f o n t s   t o   b e   u s e d ,   s t u d i e d ,   m o d i f i e d   a n d   r e d i s t r i b u t e d   f r e e l y   a s   l o n g   a s   t h e y   a r e   n o t   s o l d   b y   t h e m s e l v e s .   T h e   f o n t s ,   i n c l u d i n g   a n y   d e r i v a t i v e   w o r k s ,   c a n   b e   b u n d l e d ,   e m b e d d e d ,   r e d i s t r i b u t e d   a n d / o r   s o l d   w i t h   a n y   s o f t w a r e   p r o v i d e d   t h a t   a n y   r e s e r v e d   n a m e s   a r e   n o t   u s e d   b y   d e r i v a t i v e   w o r k s .   T h e   f o n t s   a n d   d e r i v a t i v e s ,   h o w e v e r ,   c a n n o t   b e   r e l e a s e d   u n d e r   a n y   o t h e r   t y p e   o f   l i c e n s e .   T h e   r e q u i r e m e n t   f o r   f o n t s   t o   r e m a i n   u n d e r   t h i s   l i c e n s e   d o e s   n o t   a p p l y   t o   a n y   d o c u m e n t   c r e a t e d   u s i n g   t h e   f o n t s   o r   t h e i r   d e r i v a t i v e s .  
  
 D E F I N I T I O N S  
 " F o n t   S o f t w a r e "   r e f e r s   t o   t h e   s e t   o f   f i l e s   r e l e a s e d   b y   t h e   C o p y r i g h t   H o l d e r ( s )   u n d e r   t h i s   l i c e n s e   a n d   c l e a r l y   m a r k e d   a s   s u c h .   T h i s   m a y   i n c l u d e   s o u r c e   f i l e s ,   b u i l d   s c r i p t s   a n d   d o c u m e n t a t i o n .  
  
 " R e s e r v e d   F o n t   N a m e "   r e f e r s   t o   a n y   n a m e s   s p e c i f i e d   a s   s u c h   a f t e r   t h e   c o p y r i g h t   s t a t e m e n t ( s ) .  
  
 " O r i g i n a l   V e r s i o n "   r e f e r s   t o   t h e   c o l l e c t i o n   o f   F o n t   S o f t w a r e   c o m p o n e n t s   a s   d i s t r i b u t e d   b y   t h e   C o p y r i g h t   H o l d e r ( s ) .  
  
 " M o d i f i e d   V e r s i o n "   r e f e r s   t o   a n y   d e r i v a t i v e   m a d e   b y   a d d i n g   t o ,   d e l e t i n g ,   o r   s u b s t i t u t i n g   - -   i n   p a r t   o r   i n   w h o l e   - -   a n y   o f   t h e   c o m p o n e n t s   o f   t h e   O r i g i n a l   V e r s i o n ,   b y   c h a n g i n g   f o r m a t s   o r   b y   p o r t i n g   t h e   F o n t   S o f t w a r e   t o   a   n e w   e n v i r o n m e n t .  
  
 " A u t h o r "   r e f e r s   t o   a n y   d e s i g n e r ,   e n g i n e e r ,   p r o g r a m m e r ,   t e c h n i c a l   w r i t e r   o r   o t h e r   p e r s o n   w h o   c o n t r i b u t e d   t o   t h e   F o n t   S o f t w a r e .  
  
 P E R M I S S I O N   &   C O N D I T I O N S  
 P e r m i s s i o n   i s   h e r e b y   g r a n t e d ,   f r e e   o f   c h a r g e ,   t o   a n y   p e r s o n   o b t a i n i n g   a   c o p y   o f   t h e   F o n t   S o f t w a r e ,   t o   u s e ,   s t u d y ,   c o p y ,   m e r g e ,   e m b e d ,   m o d i f y ,   r e d i s t r i b u t e ,   a n d   s e l l   m o d i f i e d   a n d   u n m o d i f i e d   c o p i e s   o f   t h e   F o n t   S o f t w a r e ,   s u b j e c t   t o   t h e   f o l l o w i n g   c o n d i t i o n s :  
  
 1 )   N e i t h e r   t h e   F o n t   S o f t w a r e   n o r   a n y   o f   i t s   i n d i v i d u a l   c o m p o n e n t s ,   i n   O r i g i n a l   o r   M o d i f i e d   V e r s i o n s ,   m a y   b e   s o l d   b y   i t s e l f .  
  
 2 )   O r i g i n a l   o r   M o d i f i e d   V e r s i o n s   o f   t h e   F o n t   S o f t w a r e   m a y   b e   b u n d l e d ,   r e d i s t r i b u t e d   a n d / o r   s o l d   w i t h   a n y   s o f t w a r e ,   p r o v i d e d   t h a t   e a c h   c o p y   c o n t a i n s   t h e   a b o v e   c o p y r i g h t   n o t i c e   a n d   t h i s   l i c e n s e .   T h e s e   c a n   b e   i n c l u d e d   e i t h e r   a s   s t a n d - a l o n e   t e x t   f i l e s ,   h u m a n - r e a d a b l e   h e a d e r s   o r   i n   t h e   a p p r o p r i a t e   m a c h i n e - r e a d a b l e   m e t a d a t a   f i e l d s   w i t h i n   t e x t   o r   b i n a r y   f i l e s   a s   l o n g   a s   t h o s e   f i e l d s   c a n   b e   e a s i l y   v i e w e d   b y   t h e   u s e r .  
  
 3 )   N o   M o d i f i e d   V e r s i o n   o f   t h e   F o n t   S o f t w a r e   m a y   u s e   t h e   R e s e r v e d   F o n t   N a m e ( s )   u n l e s s   e x p l i c i t   w r i t t e n   p e r m i s s i o n   i s   g r a n t e d   b y   t h e   c o r r e s p o n d i n g   C o p y r i g h t   H o l d e r .   T h i s   r e s t r i c t i o n   o n l y   a p p l i e s   t o   t h e   p r i m a r y   f o n t   n a m e   a s   p r e s e n t e d   t o   t h e   u s e r s .  
  
 4 )   T h e   n a m e ( s )   o f   t h e   C o p y r i g h t   H o l d e r ( s )   o r   t h e   A u t h o r ( s )   o f   t h e   F o n t   S o f t w a r e   s h a l l   n o t   b e   u s e d   t o   p r o m o t e ,   e n d o r s e   o r   a d v e r t i s e   a n y   M o d i f i e d   V e r s i o n ,   e x c e p t   t o   a c k n o w l e d g e   t h e   c o n t r i b u t i o n ( s )   o f   t h e   C o p y r i g h t   H o l d e r ( s )   a n d   t h e   A u t h o r ( s )   o r   w i t h   t h e i r   e x p l i c i t   w r i t t e n   p e r m i s s i o n .  
  
 5 )   T h e   F o n t   S o f t w a r e ,   m o d i f i e d   o r   u n m o d i f i e d ,   i n   p a r t   o r   i n   w h o l e ,   m u s t   b e   d i s t r i b u t e d   e n t i r e l y   u n d e r   t h i s   l i c e n s e ,   a n d   m u s t   n o t   b e   d i s t r i b u t e d   u n d e r   a n y   o t h e r   l i c e n s e .   T h e   r e q u i r e m e n t   f o r   f o n t s   t o   r e m a i n   u n d e r   t h i s   l i c e n s e   d o e s   n o t   a p p l y   t o   a n y   d o c u m e n t   c r e a t e d   u s i n g   t h e   F o n t   S o f t w a r e .  
  
 T E R M I N A T I O N  
 T h i s   l i c e n s e   b e c o m e s   n u l l   a n d   v o i d   i f   a n y   o f   t h e   a b o v e   c o n d i t i o n s   a r e   n o t   m e t .  
  
 D I S C L A I M E R  
 T H E   F O N T   S O F T W A R E   I S   P R O V I D E D   " A S   I S " ,   W I T H O U T   W A R R A N T Y   O F   A N Y   K I N D ,   E X P R E S S   O R   I M P L I E D ,   I N C L U D I N G   B U T   N O T   L I M I T E D   T O   A N Y   W A R R A N T I E S   O F   M E R C H A N T A B I L I T Y ,   F I T N E S S   F O R   A   P A R T I C U L A R   P U R P O S E   A N D   N O N I N F R I N G E M E N T   O F   C O P Y R I G H T ,   P A T E N T ,   T R A D E M A R K ,   O R   O T H E R   R I G H T .   I N   N O   E V E N T   S H A L L   T H E   C O P Y R I G H T   H O L D E R   B E   L I A B L E   F O R   A N Y   C L A I M ,   D A M A G E S   O R   O T H E R   L I A B I L I T Y ,   I N C L U D I N G   A N Y   G E N E R A L ,   S P E C I A L ,   I N D I R E C T ,   I N C I D E N T A L ,   O R   C O N S E Q U E N T I A L   D A M A G E S ,   W H E T H E R   I N   A N   A C T I O N   O F   C O N T R A C T ,   T O R T   O R   O T H E R W I S E ,   A R I S I N G   F R O M ,   O U T   O F   T H E   U S E   O R   I N A B I L I T Y   T O   U S E   T H E   F O N T   S O F T W A R E   O R   F R O M   O T H E R   D E A L I N G S   I N   T H E   F O N T   S O F T W A R E .  
  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

-----------------------------------------------------------
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.
  h t t p : / / w w w . a d o b e . c o m / t y p e / l e g a l . h t m l  http://www.adobe.com/type/legal.html         2                    :           	 
                        ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ 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    j i k m l n  o q p r s u t v w  x z y { } |    ~     
     !"  #$%&'()*+,-./012  3456789:;<=>?  @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:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXNULLCRuni00A0uni00ADtwo.sups
three.supsuni00B5one.supsAmacronamacronAbreveabreveAogonekaogonekCcircumflexccircumflex
Cdotaccent
cdotaccentDcarondcaronDcroatEmacronemacronEbreveebreve
Edotaccent
edotaccentEogonekeogonekEcaronecaronGcircumflexgcircumflex
Gdotaccent
gdotaccentuni0122uni0123HcircumflexhcircumflexHbarhbarItildeitildeImacronimacronuni012Cuni012DIogonekiogonekJcircumflexjcircumflexuni0136uni0137kgreenlandicLacutelacuteuni013Buni013CLcaronlcaronLdotldotNacutenacuteuni0145uni0146NcaronncaronnapostropheOmacronomacronuni014Euni014FOhungarumlautohungarumlautRacuteracuteuni0156uni0157RcaronrcaronSacutesacuteScircumflexscircumflexuni015Euni015Funi0162uni0163TcarontcaronUtildeutildeUmacronumacronUbreveubreveUringuringUhungarumlautuhungarumlautUogonekuogonekWcircumflexwcircumflexYcircumflexycircumflexZacutezacute
Zdotaccent
zdotaccentuni0180uni018Funi0192OhornohornUhornuhornuni01CDuni01CEuni01CFuni01D0uni01D1uni01D2uni01D3uni01D4uni01D5uni01D6uni01D7uni01D8uni01D9uni01DAuni01DBuni01DCGcarongcaronuni01EAuni01EBuni0218uni0219uni021Auni021Buni0237uni0243uni0250uni0251uni0252uni0254uni0258uni0259uni0261uni0265uni026Funi0279uni0287uni028Cuni028Duni028Euni029Eh.supsj.supsr.supsw.supsy.supsuni02BBuni02BCuni02BEuni02BFuni02C8uni02C9uni02CAuni02CBuni02CCl.supss.supsx.supsuni0300uni0301uni0302uni0303uni0304uni0306uni0307uni0308uni0309uni030Auni030Buni030Cuni030Funi0312uni0313uni031Buni0323uni0324uni0326uni0327uni0328uni032Euni0331a.supsb.supsd.supse.supsg.supsk.supsm.supso.supsp.supst.supsu.supsv.supsc.supsf.supsz.supsuni1E0Cuni1E0Duni1E0Euni1E0Funi1E20uni1E21uni1E24uni1E25uni1E2Auni1E2Buni1E36uni1E37uni1E38uni1E39uni1E3Auni1E3Buni1E42uni1E43uni1E44uni1E45uni1E46uni1E47uni1E48uni1E49uni1E5Auni1E5Buni1E5Cuni1E5Duni1E5Euni1E5Funi1E60uni1E61uni1E62uni1E63uni1E6Cuni1E6Duni1E6Euni1E6FWgravewgraveWacutewacute	Wdieresis	wdieresisuni1E8Euni1E8Funi1E92uni1E93uni1E97uni1E9EYgraveygraveuni1EF4uni1EF5uni1EF6uni1EF7uni1EF8uni1EF9	zero.supsi.sups	four.sups	five.supssix.sups
seven.sups
eight.sups	nine.supsparenleft.supsparenright.supsn.sups	zero.subsone.substwo.subs
three.subs	four.subs	five.subssix.subs
seven.subs
eight.subs	nine.subsparenleft.subsparenright.subsuni0259.supscolonmonetarylirauni20A6pesetadongEurouni20B1uni20B2uni20B5uni20B9uni20BAuni2215	zero.dnomone.dnomtwo.dnom
three.dnom	four.dnom	five.dnomsix.dnom
seven.dnom
eight.dnom	nine.dnomparenleft.dnomparenright.dnomuni0300.capuni0301.capuni0302.capuni0303.capuni0304.capuni0306.capuni0307.capuni0308.capuni0309.capuni030A.capuni030B.capuni030C.capuni0327.capuni03080304uni03080304.capuni03080301uni03080301.capuni0308030Cuni0308030C.capuni03080300uni03080300.cap	uni030C.a	uni0326.a            mU    w            DSIG    w   GPOS  ,  KGSUBV.T  L  OS/2ٮi  M   `cmapRԟ  NP  cvt ' m`   8fpgmzA m  	gasp    mX   glyf*~ʙ  S8  Bheade  |   6hhea     $hmtx[`    TkernlBjT  ,  lloca. V  ,maxp<
 X<    name$ X\  ^post:] i  prepx9 w,       
 0 J DFLT latn                 kern kern                   Jn    v $R
^	h
B
l&rjZjL*|DV: !.!##L#$4$~%&J'$'()*+f+,6,-.(./t//0:0|2"233T334&4l455b566L667B778889d99:&::;@<=>j?,?@hABCzDEFG*GHfI K 	J  N  J # $J & * 2 4 9 0 : 0 <  ? 0 D F G H R T mN oN yN }N J J J J J J J                             J         N N   N N N J K 	J  N  J # $J & * 2 4 9 0 : 0 <  ? 0 D F G H R T mN oN yN }N J J J J J J J                             J         N N   N N N J " # & * 2 4 F G H R T                         K 	J  N  J # $J & * 2 4 9 0 : 0 <  ? 0 D F G H R T mN oN yN }N J J J J J J J                             J         N N   N N N J -  
  x # & * 2 4 7L 9L : <h ?L Y| Z \| l mx ox r yx | }x        h   h x x     x x x  ' N 	 
N N x x  $ 7L 9 : ; <` = ? lN rN |N        `  `    N N x N N x N  -  
  x # & * 2 4 7L 9L : <h ?L Y| Z \| l mx ox r yx | }x        h   h x x     x x x  k  0 	x 
 0  0 @  @ x   " 0 # $x & * -h 2 4 D F G H I Jx P Q R S T U V W X Y [ \ ] l 0 m o r 0 t : u : w y { : | 0 } x x x x x x x                                x           0  0 @  0  0 @     0 x )  	 
      $ 7 9 ; < = ? @ ` l r |                      6 J 
J J  " # & * - 2 2 4 7| 8 9x : <\ ?x Y \ lJ m o rJ tH uH y {H |J }            \   \   J J J J    J 
 j mj oj yj }j j j j j j )  	 
      $ 7 9 ; < = ? @ ` l r |                      4 	| L L |   "  $| -: F G H P Q R S T U X w | | | | | | |                  |     L L |  	    $            1  # & * 2 4 F G H I R T W Y Z \ m o y }                              I  
   6 :  6 " # & * 2 4 7T 9J :h <, ?J F G H R T Y Z \ l m: o: r t6 u6 y: {6 | }:        ,                  , : :    6    6 : : :  )  	 
      $ 7 9 ; < = ? @ ` l r |                      . 	v   v $v -J D F G H R T v v v v v v v                    v       v )  	 
      $ 7 9 ; < = ? @ ` l r |                       # & * 2 4 7 8              [ 	| L L L | ` ` # $| & * -8 2 4 D F. G. H. JD P` Q` R. S` T. U` V^ X` YL Zt [p \L ] mL oL w` yL }L | | | | | | |               . . . . . . ` . . . . . . ` ` ` ` |   . . `  . L L L L L L L |  	    $            k  0 	x 
 0  0 @  @ x   " 0 # $x & * -h 2 4 D F G H I Jx P Q R S T U V W X Y [ \ ] l 0 m o r 0 t : u : w y { : | 0 } x x x x x x x                                x           0  0 @  0  0 @     0 x I  0 	 
 0  0     " " $ - D F G H J R T V l 0 m o r 0 t 0 u 0 y { 0 | 0 }                                   0  0   0  0      0  1  # & * 2 4 F G H I R T W Y Z \ m o y }                              i   	\ 
    h ` h \   " " # $\ & * -8 2 4 D F` G` H` JT P Q R` S T` U V X Y Z [| \ l  m` o` r  t 2 u 2 w y` { 2 |  }` \ \ \ \ \ \ \               ` ` ` ` ` `  ` ` ` ` ` `     \   ` `   ` ` `     h     h ` ` `   \ 0  " " # & * 2 4 F G H R T V Y \ m o y }                              " # & * 2 4 F G H R T                         6 J 
J J  " # & * - 2 2 4 7| 8 9x : <\ ?x Y \ lJ m o rJ tH uH y {H |J }            \   \   J J J J    J   
  Y Z \ l r t u { |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        D 
 D  D ~ ~ l D r D t d u d { d | D  D  D ~  D  D ~  D   
  Y Z \ l r t u { |       F G H R T                  
  Y Z \ l r t u { |        
  Y Z \ l r t u { |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |       | | D         | | $ 	 | |  $ F G H R T                        | |        F G H R T                $ 	 | |  $ F G H R T                        | |  " # & * 2 4 F G H R T                         K 	J  N  J # $J & * 2 4 9 0 : 0 <  ? 0 D F G H R T mN oN yN }N J J J J J J J                             J         N N   N N N J ' N 	 
N N x x  $ 7L 9 : ; <` = ? lN rN |N        `  `    N N x N N x N  ' N 	 
N N x x  $ 7L 9 : ; <` = ? lN rN |N        `  `    N N x N N x N  )  	 
      $ 7 9 ; < = ? @ ` l r |                      K 	J  N  J # $J & * 2 4 9 0 : 0 <  ? 0 D F G H R T mN oN yN }N J J J J J J J                             J         N N   N N N J  	H H $H 9 : : : < ( ? : H H H H H H H  ( H  ( H  	H H $H 9 : : : < ( ? : H H H H H H H  ( H  ( H ' N 	 
N N x x  $ 7L 9 : ; <` = ? lN rN |N        `  `    N N x N N x N   	H H $H 9 : : : < ( ? : H H H H H H H  ( H  ( H K 	J  N  J # $J & * 2 4 9 0 : 0 <  ? 0 D F G H R T mN oN yN }N J J J J J J J                             J         N N   N N N J ' N 	 
N N x x  $ 7L 9 : ; <` = ? lN rN |N        `  `    N N x N N x N  6 J 
J J  " # & * - 2 2 4 7| 8 9x : <\ ?x Y \ lJ m o rJ tH uH y {H |J }            \   \   J J J J    J 6 J 
J J  " # & * - 2 2 4 7| 8 9x : <\ ?x Y \ lJ m o rJ tH uH y {H |J }            \   \   J J J J    J 6 J 
J J  " # & * - 2 2 4 7| 8 9x : <\ ?x Y \ lJ m o rJ tH uH y {H |J }            \   \   J J J J    J 6 J 
J J  " # & * - 2 2 4 7| 8 9x : <\ ?x Y \ lJ m o rJ tH uH y {H |J }            \   \   J J J J    J 6 J 
J J  " # & * - 2 2 4 7| 8 9x : <\ ?x Y \ lJ m o rJ tH uH y {H |J }            \   \   J J J J    J 6 J 
J J  " # & * - 2 2 4 7| 8 9x : <\ ?x Y \ lJ m o rJ tH uH y {H |J }            \   \   J J J J    J 
 j mj oj yj }j j j j j j )  	 
      $ 7 9 ; < = ? @ ` l r |                      )  	 
      $ 7 9 ; < = ? @ ` l r |                      )  	 
      $ 7 9 ; < = ? @ ` l r |                      )  	 
      $ 7 9 ; < = ? @ ` l r |                      )  	 
      $ 7 9 ; < = ? @ ` l r |                      )  	 
      $ 7 9 ; < = ? @ ` l r |                       	    $             	    $             	    $             	    $            i   	\ 
    h ` h \   " " # $\ & * -8 2 4 D F` G` H` JT P Q R` S T` U V X Y Z [| \ l  m` o` r  t 2 u 2 w y` { 2 |  }` \ \ \ \ \ \ \               ` ` ` ` ` `  ` ` ` ` ` `     \   ` `   ` ` `     h     h ` ` `   \ )  	 
      $ 7 9 ; < = ? @ ` l r |                        
  Y Z \ l r t u { |        
  Y Z \ l r t u { |        
  Y Z \ l r t u { |        
  Y Z \ l r t u { |        
  Y Z \ l r t u { |        
  Y Z \ l r t u { |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
  Y Z \ l r t u { |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |        
   9 : ? @ Y [ \ ` l r |      6 J 
J J  " # & * - 2 2 4 7| 8 9x : <\ ?x Y \ lJ m o rJ tH uH y {H |J }            \   \   J J J J    J   
  Y Z \ l r t u { |      
 j mj oj yj }j j j j j j   
   9 : ? @ Y [ \ ` l r |        t 
t t  9^ : <h ?^ Y \ lt m o rt t| u| y {| |t } h h   t t t t    t   
  Y Z \ l r t u { |        
   9 : ? @ Y [ \ ` l r |      i   	\ 
    h ` h \   " " # $\ & * -8 2 4 D F` G` H` JT P Q R` S T` U V X Y Z [| \ l  m` o` r  t 2 u 2 w y` { 2 |  }` \ \ \ \ \ \ \               ` ` ` ` ` `  ` ` ` ` ` `     \   ` `   ` ` `     h     h ` ` `   \ 0  " " # & * 2 4 F G H R T V Y \ m o y }                              0  " " # & * 2 4 F G H R T V Y \ m o y }                              0  " " # & * 2 4 F G H R T V Y \ m o y }                              ' N 	 
N N x x  $ 7L 9 : ; <` = ? lN rN |N        `  `    N N x N N x N  ' N 	 
N N x x  $ 7L 9 : ; <` = ? lN rN |N        `  `    N N x N N x N  K 	J  N  J # $J & * 2 4 9 0 : 0 <  ? 0 D F G H R T mN oN yN }N J J J J J J J                             J         N N   N N N J K 	J  N  J # $J & * 2 4 9 0 : 0 <  ? 0 D F G H R T mN oN yN }N J J J J J J J                             J         N N   N N N J -  
  x # & * 2 4 7L 9L : <h ?L Y| Z \| l mx ox r yx | }x        h   h x x     x x x  K 	J  N  J # $J & * 2 4 9 0 : 0 <  ? 0 D F G H R T mN oN yN }N J J J J J J J                             J         N N   N N N J K 	J  N  J # $J & * 2 4 9 0 : 0 <  ? 0 D F G H R T mN oN yN }N J J J J J J J                             J         N N   N N N J -  
  x # & * 2 4 7L 9L : <h ?L Y| Z \| l mx ox r yx | }x        h   h x x     x x x  ' N 	 
N N x x  $ 7L 9 : ; <` = ? lN rN |N        `  `    N N x N N x N  ' N 	 
N N x x  $ 7L 9 : ; <` = ? lN rN |N        `  `    N N x N N x N  ' N 	 
N N x x  $ 7L 9 : ; <` = ? lN rN |N        `  `    N N x N N x N  K 	J  N  J # $J & * 2 4 9 0 : 0 <  ? 0 D F G H R T mN oN yN }N J J J J J J J                             J         N N   N N N J 6 J 
J J  " # & * - 2 2 4 7| 8 9x : <\ ?x Y \ lJ m o rJ tH uH y {H |J }            \   \   J J J J    J  v  
       # $ & ' ) - . / 2 3 4 5 7 8 9 : ; < = > ? D E H I K N P Q R S U Y Z [ \ ^ l m o p r t u y { | }                                                                  
 8  DFLT latn                     case &case ,liga 2liga 8sups >sups D                                        ,     >  B 	
  @       L  O  ,  { t u   C j q v          I            x  x   x  P `K        tyPL @  Jz                              & 
                                                                          	 
                        ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ 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                                    r d e i  x  p k  v j    s g w      l |     c n     m }  b                    y                        q    z    `   T @      ~ 1DS[a~    " & 0 : D !"!&"""""""+"H"`"e%&i        1ARZ`x      & 0 9 D !"!&"""""""+"H"`"d%&i {uq[H$I޸ޡޞ:ڜ                                                                                      `   T @      ~ 1DS[a~    " & 0 : D !"!&"""""""+"H"`"e%&i        1ARZ`x      & 0 9 D !"!&"""""""+"H"`"d%&i {uq[H$I޸ޡޞ:ڜ                                                                                         -   % 5 9 = J@G  B h f    [  [ 		Q C Q D=<($#*$
+>32#'&>54&#"#"'4632#"&!!7!!9DO.?gI)-60#z-70 I9)8(c>0((0>22cu&#@[87P;+&%iu"3+(.:(3</@)(?g6,      ! &@#   QC S D    +#.54>32#".	y	+!..""..!-VW[44[WV-<."".-""-     
  ,@)	 B  Q D   
 
$+#"&/!#"&/3ޛ ## "ޛ ## "  6  Q > B H@E Y	CQ
C   D  BA@? > >86530/*(##!#!+#"&5467#+#"&546?3#7>;>;3323+32%3#TQ GG-OUA$'H+PTTO!I%&A	AY"Z%9FJf"ZK9F  j$g 8 C N ~@J( I>) ? 4 BK	PX@$   h   f S C S D@$   h   f S C S DY#&#&+.'7>32.54>?>;#".'+4.'>yH50FaD%FkA9mh
Bi<+):L1!HpE<skB%@V1"AeE#"<P/A_=aKR&1.5UaIlER:B!!4R{\ZxK2H4&-F]0G6((<K    H  ' 1 E Y KPX@'    [  	[ SC 		SDK"PX@+    [  	[ SC C 		S D@/    [  	[ C S C C 		S DYY@VT((%#&((($
+#".54>324.#"32>>;+#".54>324.#"32>4Wt?DsV00VsDCuU11A%%A00A%%A1
54Ws?DsV00VsDCtV01A%%A00A%%A1?T[00[TV\00\VB\;;\BA[99[wRT[00[TV\00\VB]::]BAZ99Z     Rx ? K @8IH+%BKPX@* h  S  C SC SD@( h  S  C S C S DY@ FD/-(&" 	 ??+2#"&'.#">7>;#"&/#".54>7.54>3267O_7o1E.2P9"6&&-nFB,$^PyJ/SrD=:5d0Nd4pDYjk3To<8. 9M-#@AE&]CJsa[j6g]F}jTMNI_7AcD#RD9     3 
 @	 B   Q D   
 
$+#"&/3ޛ ## "      
(+.54>7!nhOKiAAiKO
imum0szyt1l     J  	(+4'&546?'.54676*mi
OKiAAiKOhnu1tyzs0     `_ 0 J@-)($  BKPX@ Q   D@   M   Q EY@
   0 0+5467'767./7.=3>?'.'b!,$%#,#	X,!!,_"cKdeKd %)cKdeKd!'  d "  ,@) M  YQ E    +!!#!5!ikUR     ^P   @?   S D$+74>32'&547>7#".^,/0G-
 *{)'3-a_Z&%0:!!-   dR  @   M   Q  E+!!d     XQ   @   S D($+74>32#".X!..""..!n."".-""-     	 @   k D#"++>;7KY0!K#" "  <L  ' @ S C  S    D((($+#".54>324.#"32>LQmnPPnmQ7]zBBz\77\zBBz]7̼XXXX켤߈;;ߤވ;;        *@'B   h C  R D&+%!47#"&/3!!4 
	8 ,-	Mq  h  $ 3 ;@8/B h  S  C Q D ,*$" 33+2>3!2!5467>54.#"#"&/>Y[sB0Rk<(R&"D9^C$(F^66\G1
 ]P{6g^P}u=~"l=(:klo??_> 9N/bf5  l. J U@RF
B h h  [  S  C S D CA;910/.&$ JJ	+2#".'763232>54.#5>54.#"#"&/>l[o>#A\9KcrpHL(DeKKqK&Qp[R%'D]66\G0 ]P{4`SDkQ8%co;9dP 		I@,1N`/:`F(&B\8>\< 9O.bf5   (  `   &@# B  [ C D!#+3+#!"&/3467!fy[< ;     l . @@=,+B h  [   Q C S D(#&(""+#!632#".'763232>54.#"'!09>Bp_pt;Pm?tdV!63HaCKxU.'OvO6t>ptK&1Bt]rF*6L&0Y|MClL*!     l2  . 2@/ B   [ C S D +)!	 +2#".5467>;>32>54.#"VtDHml|CT[k2 3|(MoGHtS-,PpCHtQ+n9mfc~HEp^z#'LErR-.RpBFqO*1Sm  n  <  @ QC    D    $'++>7!"&=<.'ZP",S%*y  `&  3 G D@AB [ S C S   D54!  ?=4G5G+) 3!3 	+".5467.54>32'2>54.#"2>54.#"CkFqs>rbar>tpGkFoM)1Sl;;lS1)MoFFc>!Aa@@aA!>c9j^&*tOf::fOt*&^j9'Gc<JiBBiJ<cG'+G\12XB&&BX21\G+     6  3 2@/ B   [ S C D 0.&$	 +".54>32+>74.#"32>%QnAF~hgxA,='0&7+Li?BmM*'IiAHoL(L6ic^zFDzg>oji8;4,.CmL)+Lj?DkJ&/Nf    y  ' ;K$PX@ S C   S D@   [   S DY((($+74>32#".4>32#".!..""..!!..""..!n."".-""-	."".-""-     y  2 D?K$PX@ S C   S D@   [   S DY@	/-%#$+74>32'&547>7#".4>32#".,/0G-
 *!..""..!{)'3-a_Z&%0:!!-."".-""-   W  (+?--


     !@   Y   M   Q  E+!!!![[>և   W   (+75467%>7.'%.=++?


oJ  " ( < 9@6  B h f  S   C S D(&#-$+>32#'54>54.#"#"'4>32#"."KYg<Ob8-ERG3z-EOE-":O-=W<%!..""..!4(.TxKLnS=66!*A99EX<+F1$."".-""-   VO Q a f@c
X
7B   h  [  

[	  [ O S GSR [YRaSaGE;9530.&$ QQ+%"&'#".54>3232>54.#"3267632#"$&54>32%2>7&#"Nb:N<X;A}Ce-])1XC'YzdkU
kﭭ}7dl\_5=k?;1L'.K}Z3BKNQF)Id:UXK1$/
8fWЋEfXB3	BHRn,mʯg9(NsklLx2VA'	?fEHW   
  I   $@!B   Z C   D# +!#"&'!+3!&'I }"=
Z{G6Q)E       * =@:B [  S   C SD  *("   !+3!2#!2>54&#%!2>54&#!Ʉ{;!CeDCx6SwM$ RxO&4`W5bTB[l;&E_9o$@[6~v   Z	 . D@A B   h  f S C S D )' ..+2#".546$32#".#"32>76LXbi	Y?(6Jb@sMMi@fWK&(SfrkkbTY
 O҂ґL 1"        @ S C  S    D!(!$+#!!24.#!!2>ffHsUsH̡ggАLL      !  .@+  Y   QC Q D    +!!!!!!P-$     ! 	 (@%  Y   QC D   	 	+!!!#!PL   Z@ 4 K@H!  B h   [ S C  S D ,*%# 44+%2>7#"&=!#"$&546$32#"'.#"-:aVL&6uYigU}j.7>YySyĊJM<n':'kj/C*X(%OтՔN    8   @   YC   D+!#!#3!38t        @ C    D+!#3    <  QKPX B BYKPX@ C S    D@ h C  S    DY!&$+#"'>7>3232>53;smai<2BgG%xF9(TZ      : " &@# B    [CD)(% +3267>;#".'.+#3I&-) %*:!X% 
	$Y
	9p        @ C   R D+%!!3pl£      # %@" B   h  CD!6)+>7>;#467+"'#32o

--
53q
g0--2
      8  @  CD!+2.53#"&'#3>bd1g70     \  ' @ S C  S    D((($+#"$&546$324.#"32>ffffHtsHHstH̡kkllґNN҄ёMM         *@'  [ S C    D    !+#!2#'32>54&+ɄAFȁSV,?tedxC,OnB  \$  0 sBK	PX@   k S C S DKPX@ S C S C    D@   k S C S DYY(((%&+#"&'#"$&546$324.#"32>)NpFp$89{CfffHtsHHstHe/skllґNN҄ёMM      # 2@/B  [ S C   D  #!  ,!+#!2#"'.#'32>54&+Ɓ>0[S$5((UW,V7h[LiJ() )Kh?  : = =@:=B   h f S C S D;9(&#!#"+#".#"#"&'7>3232>54.54>32	-EaEAdC";a{{a;@{rQ86QsSElK(;`{{`;;pkxJ")"#<Q/<O8),7TzY^zFeV\-6-&E`;AS8')6V_LnBLH     ~   @  QC D    +!#!5~1/
       #@ C  S D  +%2>53#".53Ya3OԄԔO3a<lZg|ԛXX|gZl=     G  @ B  C D, +32>7>;# 	""P++P"g      (  @# B  CD+< +32>7>;2>7>;#&'#"(	Q#8!O
)#A		>""?4C!<gE)%       @  B  CD("(!+	3267>;	#"&'+'va	%	PY       @  BC    D,"+#32>7>;HG	::_#>>"-  V    $@! QC   Q D    +!!547!52,H"Lv    '@$    [ O QE    !#+!+32pFF  	 @  k    D# +32#"&'L!0YK8" '"#     Z  !@   [   O   Q  E!"+46;#"&=!!Zp3F      @
 B k    D+!+3#"&'.'+sfz`+,+    [  @  M Q   E    +!5xx   & 	 @  k   D  		+2#"&'! f  \z ) 9 }@!/BKPX@' h  [ S C S   D@+ h  [ S C   CS DY@+*10*9+9%##' 	+!#"&/#".54>754&#"#"&/>322>75zO (LT_:;gL-BecAYA/ TvUZ.2/NE?{l1,<^$9'!BeE<oV7Ovy!)!9QP8dU#2 2D*(:%    % @	BK	PX@   CS C SDK"PX@   CS C SD@!   CS CC S DYY@  %%  (#+33>32#"&'#"32654.?iXd6<qfb3	&QW70uH#B`IYB~pQLD\&wPIB6ʻc[*   J * i@
*BK	PX@$   h f S C S D@$   h f S C S DY($#(#"+#".#"32>32#".54>32E#6M8JrM'*LmDAT8$2Bn_xE?ysj?A5dX\a3&AQKF|qNE?  H  % p@BK"PX@ C S C S   D@! C S C  CS DY@ %% +!"/#".54>323%267.#"[&
AlWd6<qg]4=W71uG"B`%{O_C~pQ?92?PIB5ʻc[*   J $ - {BK	PX@' h  [ S  C S D@' h  [ S  C S DY@&% )(%-&-	 $$	+2#!32>32#".54>"!4.#[p?^0TtHCaF/2!\ip7iHAzr'"B_=sl*`_/$A(;&GʃjM>gK)      ]@
BK2PX@ S C  Q  CD@   Y S CDY@    4%+3'.=354>32+"!!p1[PD: .K6%]IbW]0Y6XA]  2 9 M ] @2A*BKPX@,
 [  [ C  S	  C S D@/   h
 [  [  S	  C S DY@ON WUN]O]JH@>#! 99+2!#"'#".5467.54>7.54>4.'32>2>54&#"Bs/*s"9eSG? !:`zz`:Azoon7_S+3!0 KU9f*H^hl19G#HmJHrO*6S8qlkq8RB!	APJyV..$%	2XFAz_9,Ja5KiC8/.**]JyU.&.N6";+0BN6K-]nn]-K6         -@*B   C S CD    ##+33>32#4&#"AgSU,ilO:ES7eV{sLA        GK	PX@ S CC    D@ S CC    DY@  
  +##".54>32X#.-##-.#>-##-/##/     ( Y	 BK	PX@ S CC  S    D@ S CC  S    DY@  %#  U%+#"&'7>323265#".54>32X EmL!6NB#.-##-.#=iN-

`IQ@>-##-/##/       0@- B    [C CD    %(%!+3267>;#"&'.+#K.@2Ws
    X  @C    D    +#X?      * V)BKPX@ S  CD@   CSCDY@   * *##&$!	+332>32>32#4&#"#4&#"j&
8\gEVa2P}W.hc,O<#b^Bq/%hEXra7P43b\{w{<[<{zxG=      LBKPX@  S  CD@   C S CDY@    #$!+332>32#4&#"j&
BkSU,ilO:%nIZ7eV{sLA   H  # NK	PX@  S  CS D@  S  CS DY@ ##	 +2#".54>2654&#",o}CC}oo~DD~oLpK%%KpJwxIIxwJxɴ4bZZa4       % @BK	PX@ S  C S CDKPX@ S  C S CD@!   CS C S CDYY@  %%  ($!+32>32#"&'"32654.j&
AmWd6<pf^3W71uH#B`L%xO`C~pQ>9@PIB6ʻc[*  H  % KPX@B@BYK	PX@ SCS C    DKPX@ SCS C    D@!C S CS C    DYY@  %%  (#+##".54>32763267.#"Ų@iWd6<qgb6
&W70vG"B`JZC~pQF@O%PI@7ʻc[*        lKPX@ B@ BYKPX@ S  CD@ h   C S CDY@    !$%!+332>32#"&#"f4g*D:4]}*jwlg{    > < =@:<B   h f S C S D:8'%" #!+#".#"#"&'7>3232>54.54>32&7L4-H3-J^c^J-2b]j<*(9Q=4N4-J_c_J-0\Vd:N(5'4&!(<W=FwW2E6D".<"*7' )>[A:kQ0?7  ,> ! t@
	 BK2PX@$ j hQ C  T   D@" j h [  T   DY@  !!+"&5#"&=7>;!!32>32xz)Z">1)4.~lG9@>U+1   z  L BKPX@C   SD@C C   S DY@    $!#+32673#"/#".5,jkN:j&
BjSV+zs~JB%mIY7dV        @ B  C D, +32>7>;#ct$H##H$      .  @' B  CD*!,< +32>7>;2>7>;#"'.'+M	


t$C""C$p#D!!H"/0R"         @  B  CD("(!+	3267>;	#"&'+	
c
@       @ BC    D,""++32>7>;	^		,,}     F  U  @ Q C   Q D+!!5467!5!U)'#&J#ߌ     ,  @ 3@0$ B  [    [ O S G86303++4&#52654.54>;+";2#".54>FCCF)S{R5MY)7!!7)YM5R{S)?QkP@2bbd4EtT.OeV8hcb2&A3%		%4@%2bch8WdP/TtE4ccb  p  @   Q D+3#把   X, @ 5@2B  [  [   O  S   G?>=<1/,)3)++546;2654.54>7.54>54&+"&=323"*R{R5MY)7!!7)YM5R{R*FCCF2bcc4EtT/PdW8hcb2%@4%		%3A&2bch8VeO.TtE4dbb2@PkQ   t   9@6 j k  O  [  S  G 
 +2673#".#"#4>32AI%Ef@4f_V$AI%EeA4f_VeUFCpP, '!TGCpP-!'!      ! &@# S C   QD    +4>734>32#".	y	"--""--"-UW\44\WU--""-."".     . 7 @ 3 2&* BK	PX@)  j   h  f T C  S   DKPX@)  j   h  f T C  S   D@)  j   h  f T C  S   DYY@	##'#+.54>?>;#".'>32+1\q?B~wBR6.!-?*4?U;&0<kBy4LsN'
OroQ?1>"	?HJ9c     4  [ > @@=7+B   h  [ S C S D%&#&'%"	+46;4>32#"&'.#"!#!>3!#!5>5#4 6nnNy^EH

)3B-?`@ {929<">0$^{G'DZ4./#*NnDHKm-Ls
"3E.!      ` # 7 ?@< !B @ ?  W  S   D42*((+467'7>327'#"&''7.732>54.#"![,h:9f+Y"![,h99e,Y"#>Q//S=$$=S//Q>#9e,Z"![,g:9f+\"![,g:.Q=$$=Q./R>##>R    ,  S " 8@5
 B 
 Z	YC D"! ,!+!32>7>;!!!!#!5!5!2h
!g3TTq(#:;"6fig;gi    p   @    Y Q D+3#3#把     r H Z A@>HXN= #B   h f  W S DFD-+(&!#!+#".#"#"&'7>3232>54.5467.54>32>54.'1&7L40M51OfifO1NT1>2a\j<)(:U?2O62RhnhR2V]2?0\Vd:Fm>604FOT(B6*8&9/+.7G\=Q&%bEFwW2E6D#->&-B3*,3F]@N}#&iK:kP0>73G95K/$8.&##I   V{  ' 3K PX@  S D@  O S  GY((($+#".54>32#".54>32 )(() g))))	((**((**   D . J b @
 BK	PX@4   h   f  [  [ 		S C S D@4   h   f  [  [ 		S C S DY@_],,*(#%(%"
+>32#".54>32#".#"32>4>32#".732>54.#"=9tbs?Ezbl9.2L;FqO++Lj>0B0%R4_ee_44_ee_4d,RrXc-RsXb@BIDzdeyCD7A-TxKMyR+	e`44`ed`44`eYtS-dYvS.e    \?T ) 5 E@B!- B h  [  W S D+*/.*5+5%##' 	+#"&/#".54>754&#"#"&/>322675T<.28"&A0&Xk:9&2%4yI6T:3J$Fa<4H1 )<)"C5#%?<
*1."<T3&#i#*"     ) )(+55:
:/:
:  ;  =K	PX@ _   M   Q  E@ k   M   Q  EY+!#!\;X!     dR  @   M   Q  E+!!d     D  3 I V >BK	PX@/h  		[ 
[  S   C S D@/h  		[ 
[  S   C S DY@44VTLJ4I4H)!*,,&+4>32#".732>54.#"#!2#"'.#'32>54.+D4_ee_44_ee_4d,RrXc-RsXb kj!	Pt7M/+F4e`44`ed`44`eYtS-dYvS.e|}z^
.r(:&%8$    RD  @   M   Q  E+!!>Du     F'  ' @  W  S   D((($+4>32#".732>54.#"F2XwEEwX22XwEEwX26I**H66H**I6hCvW22WvCBuW33WuA*I66I**J77J    d P"   7@4  Y Y M Q E    	+!!#!5!!!ikkBpx%   RQe - 9@6+B h   [ S D (&"  --+2>;2!546?>54&#"#"&/>Z4U<!*6/
, <-.9	Ge6M/(E>:M+455370*jj   T|Re = S@P9B h h   [  [ S D 640.*)(' ==	+2#".'763232>54.#5>54&#"#"&/>b3R; wBE*E[09T=+7+ / 'A/WG:009	C,ATe3D(-N>7T91H/ (+W<424/(5O5   U 	 @   kD   	 #++7>3Uj!   z  3@0  BC   SC D    &$!#+32673#"/#"&'#"&5,liN:j&
CWJp'Y&)nmxJB%mHD3.*W&($      *7  *@'   hi  S D    +##!#".54>3۝hu??uh77]=iQVe8  |  @   O   S  G($+4>32#".|)68((86)Q8((86))6    
  KPX@  B@ BYK	PX@   ^  T DKPX@  j  T D@  j  j T DYY@  +232654.'73#"&'76 *+)<&+pZQ 9P0)J	!PE6 3$7  xD_  O	BK$PX@ j  j  Q  D@ j  j  M  R  FY$+37#"/733!k	'li+X	8zU  H<   )@& W  S  D 	 +2#".54>2654&#"~FqP,,PqFGrQ,,QrGTSSTWSS+PsGHtQ++QtHGsP+iddhhddi       % % (+7'&54767&'&54?%'&54767&'&54?:

:(:

:{{   f  |    & 0 O@L$ 	B h 	 	Z
  [C SD0.+)&% $!#+3+#5!"&/3%37#"/733!4673+>;mRm
V|k	'li,L2. MA9;+X	8zU,\     f  ] - = G e@b710+B h h 		Z   [C S
D GEB@=<;:9853/.(&"  --+2>;2!546?>54&#"#"&/>%37#"/733!+>;f4U<!*6/
, <-.9	Gk	'li,L2. M6M/(E>:M+455370*jj3+X	8zUv\    D  }  N T ^ x@uJ	
%R B 

h 		h 
 	
	[   [  \ SC SD^\YWTSGEA?;:980.)'!NN!#+3+#5!"&/32#".'763232>54.#5>54&#"#"&/>4673+>;mRm
V|B3R; wBE*E[09T=+7+ / 'A/WG:009	C,AT,L2. MA93D(-N>7T91H/ (+W<424/(5O5\,\    , ) = 9@6  B h f S C  T    D('#-$+#".54>?332>324>32#".KXh<Ob8-ERG3z-EOE-":O-=W<&q!..""..!4(,RvKLjL601!,>2/<P;,E1$."".-""-  
  I& $   	k   
  I& $   k   
  I& $   v   
  I& $   v   
  I& $   
v   
  I-& $   s        :@7 B  Y  Y  Q   C SD#	+!!!!!!!+!</=a1Գ%^$)E     Z	 K2KPX@:> I B@:> IBYK	PX@0 h f S C S C	  S DKPX@0 h f S C S C	  S DKPX@0 h f S C S C	  S D@7 h f	  h S C S C S DYYY@ GE=<861/'%  KK
+232654.'7.546$32#".#"32>7632#"&'76 *+)<&$Vi	Y?(6Jb@sMMi@fWK&LSZQ 9P0)J	!vu kbTY
 O҂ґL 1"Sap7E6 3$7    !& (   	7     !& (   7     !& (   B     !& (   
B    & ,   	      & ,        {& ,        x& ,   
     2    ! ,@)  Y S C S D!%(!+3!2#!#%4.#!!!!2>2ffHt}UtHgg2АLrL   8& 1      \& 2   	   \& 2      \& 2      \& 2      \& 2   
    ~ X  	(+		'	7	b__d_YX`b`dY`X     \ ! - 8 h@21&% BKPX@  k C S C  S    D@ j  k S C  S    DY)*%(%$+#"&'+&546$327>;.#"4&'32>flOd:Np{fsSR  dgpAKE<WsHA<qttH̡k10b l:6ob꫇I*+N҄~HFM    & 8   	   & 8      & 8      & 8   
     & <   9         .@+  [  [ C    D    !+#332#'32>54&+ɄAFȁSV,?tedxC,OnB  v H wKPXBBYKPX@ h  S  C SD@# h  S  C C S DY@ CB=;%#  HH+2#"&'7>3232>54.54>54.#"#4>gb/+@K@+5P]P59dOa<)(7K5,F18TbT8-CNC-8Y?DoO+E<]n3<VB203 '4-/FfNNzU-E6D".@%8F3*:SB5O?6<G0 A4!*T~T&hzB  \z& D    C    \z& D    v    \z& D        \z& D        \z{& D    j    \z& D         \ C Q \ @A;BK	PX@5 h h
[ S	  CSDKPX@5 h h
[ S	  CSD@? h h
[ S	  C SC SDYY@&SR XWR\S\MKED?=8631.-%#	 CC+2#!32>32#"&'#".54>754&#"#"&/>32>32>5"!4.Rg;.MiAE\=&/!Wcj4u7Wjw;ErS-BecAYA/ Tqx!6{l1dQ9cI*=`E)<W@zp)[Z,$	=(;&qt>X8#FjH<t\;2v~#*#9QPf[Xg#8H*WP$JnJ)NpFAoP-    J H KPX@7; F B@7; FBYKPX@- h f   f S C  T D@3 h f   f  f S C T DY@ DB42/-%#  HH	+232654.'7.54>32#".#"32>32#"&'76 *+)<&%Sf:?ysj?/#6M8JrM'*LmDAT8$2;aZQ 9P0)J	!yOqqNE?@5dX\a3&	AHJ:E6 3$7 J& H    C    J& H    v    J& H        J{& H    j     &     C      (&     v     6&          ){&     j     L 4 H 6@3:0B43@  [ S    D65@>5H6H.,$"+.54?.'.54?7#".54>32.'2>7.#"g-e9`Q#a<cF'>{xb}H>thdAu^_GsQ.4Kc>KqL'.Pi)H"><0z9C1|nVB{p^~JVW@6mo+Q?%2WwDQV-    & Q       H& R    C    H& R    v    H& R        H& R        H{& R    j     d "   + +@(   [    Y O S G(((%+!!4>32#".4>32#".dBb!--""--!!--""--!."".-""-S."".-""-     @-I ! + 5 t@43%$  BAK	PX@  j  k S C S    D@  j  k S C S    DY@-,,5-5%%(%'+#"&'+7.54>327>;&#"2>54'=BC}oL67;CBFD~oO8D  Z;IoLtO(7KsO(4OFtDvxI" JE|wJ&#[aN86d$5dZ`0 z& X    C    z& X    v    z& X        z{& X    j    & \    v       # q@BK	PX@!   CS C S CD@!   CS C S CDY@  ##  (#+3>32#"&'"32654.?iWd6<pf_3W71uH#B`JYB~pQE?3PIB6ʻc[*    {& \    j     
 ' / KPX@
, B@
,BYKPX@!  Z CC	  S D@(	  h  Z CC S DY@ )($" ''
+2#"&5467"&'!+3#32>!&'d	]3XeO< }"==%*"1*?
BOB:e&Zg'/&+	G6Q)E   \ C S @;I	  BKPX@1 h  		[ S C
S C  S D@8 h   h  		[ S C
S C   S DY@EDKJDSES%##.%#'+!32>32#"&54>7&/#".54>754&#"#"&/>322>75z*"1*	]3Xe'5
(LT_:;gL-BecAYA/	 TvUZ.2/NE?{l1,<'/&+	BOB83- ^$9'!BeE<oV7Ovy!)!9QP8dU#2 2D*(:% Z	& &      J& F    v     4 & KPX B	BYKPX@*  Y Q C QC	
  S D@1
 	 	h  Y Q C QC 		S DY@ #! &&+2#"&5467!!!!!!#32>	]3XeO<ZsP-[*"1*BOB:e&$'/&+	  J < E KPX@
- B@
-BYKPX@2 h 	 	[S C S C
  S D@9 h
  h 	 	[S C S C S DY@>= A@=E>E97+)&$  <<+2#"&5467.54>32#!32>3232>"!4.	]3XeB4g~FAzn[p?^0TtHCaF/22R'!1*'"B_BOB5]%HȁjM=sl*`_/$A<G&.&+	U>gK)       X  @C    D    +#X   ,    #@ 
  B C   R D+%!!54?3lһ%ā"*_V     6  K  #@ 
 BC    D    +7#54?MfCLiD      8& 1        & Q    v    \'  02@
 BKPX@"  Y  S
C	SDK"PX@,  Y  S C  Q
C	SDK,PX@6  Y  S C  Q
C	Q C	S DK0PX@4  Y S C   Q
C	Q C	S D@2  Y S C   Q
C Q C 		S DYYYY@  -+#!  (#+!!!!!5#".54>3254.#"32>'P-T\\ꎡT@whhxAAxhhw@$xkly3ӔOOӄӓNN  Hu 0 @ K @.
BK	PX@, h 
 
[	 S  CSD@, h 
 
[	 S  CSDY@$BA21 GFAKBK:81@2@,*" 	 00+2#!32>32#"&'#".54>32>2654.#""!4.Rg;.MiA=Y@-3!Wcj4w76du@@wf52"DhEGhE"e=`E*<W@zp)[Z,$A(;&swpzIxwJyni~xɴZb44bZ)NpFAoP-   : & 6      >& V    v    :& 6      >& V          & <   
D   V  & =   N   F  U& ]    v    V  & =   X   F  U& ]        V  & =   X   F  U& ]         j # 6@3BY S C  T    D   # ##"+#5432>7'.=37>3#"!Y<-Q?,Y.Q@-	B &͹^9:\DIƿb:]D   d  @ B  k D' +#"/+3dw{ߦ~~	    d  @ B  k   D+ +32>?>;#{wߦ
}	

}	   RD q     D   @   WD 
 +".5332>532MhA~"9++9"~Ai+Ib7!9((9!7bI+       @   S  D($+#".54>32#.-""-.#:-""-/##/   jk   =KPX@  W  S   D@    [ O S GY$&($+4>32#".732654&#"j 7H()I8  8I)(H7 d6/-77-/6#*D22D*)D00D),88,-88     YKPX@ B @@B @YKPX@  S D@  j S DY@  +2#"&54>732>	]3Xe+;"\*"1*BOB;6/'/&+	    Y  QK.PX@  W SD@  O [  S GY@ 
 +2673#".#"#4>32$'l/A(#=60Ho0B'#=6/-*,/O8"X0O9"   ^ 	  #@   S D

  

 	 #++7>3!+7>3J!!V!     0 ! YBK(PX@  SC SD@  SC C S DY@   !  6##++#!#"&'7>3265#54>3sy"BB9	H$rwK	>B|@       @   M   Q  E+!!        @   M   Q  E+!!2     :'   (+.5467rYP7
0a0ZE"
,16 D&
    ZF   (+'.547>54&'&547YO7
0`0[E"
-16 D&   ZF    (+%'.547>54&'&547YO7
0`0[E"
-16 D&    :W  1  (+.5467.5467rYP7
YP7
0a0ZE"
,16 D&
,0a0ZE"
,16 D&
   Zv  1  (+'.547>54&'&547%'.547>54&'&547YO7
YO7
0`0[E"
-16 D&,0`0[E"
-16 D&     Zv   1  (+%'.547>54&'&547%'.547>54&'&547YO7
YO7
0`0[E"
-16 D&,0`0[E"
-16 D&  v  3@0	  B C S  C D#$&"+4632632>72!#"'!v)+"LPP'(57&NE,(x&75(w0	
0<`	   v / G@D	  %$ B[ C	 S  C D/.$$#$&"
+4632632>72!!#.'#"'"&=!!v)+"LPP'(57&NE,(x(,EN&75(NE+)w0	
0<<00<X        ,KPX@  S   D@   O   S  GY($+4>32#".;dLMe;;eMLd;SMe;;eMMd;;d  XV   ' ; @  SD((((($+74>32#".%4>32#".%4>32#".X!..""..!!..""..!!..""..!n."".-""-."".-""-."".-""-     H  ' 1 E Y m  KPX@+    [	[ SC		S
DK"PX@/    [	[ SC C		S
D@3    [	[ C S C C		S
DYY@~|trjh`^VT((%#&((($+#".54>324.#"32>>;+#".54>324.#"32>%#".54>324.#"32>4Wt?DsV00VsDCuU11A%%A00A%%A1	
54Ws?DsV00VsDCtV01A%%A00A%%A1h4Wt?DsV00VsDCuU11A%%A00A%%A1?T[00[TV\00\VB\;;\BA[99[}RT[00[TV\00\VB]::]BAZ99ZAT[00[TV\00\VB]::]BAZ99Z     (+5:
:       (+'&54767&'&54?:

:{    D  # 	 @ C    D#"+'+>;,L2. M5\   "r G [@X	5	B   h 		h  [	[ S C 
S 


DGF@?>=9720"###%$+3>32#".#"!#!!#!32>32#".'#53&45467#"_lF=%>aK #j6R<+ KFЏtW~ˏLdXD	&.&7(8 % FfqOӃf)    @I)  & C@@B h S	  C S	  D&&!4)
+>7>;#7+"'#32'###5	jn	nj~U/mKMHPii   V  ~ 7 1@.1 B   S CSD   7 6***+!>54.#"!"&=!5.54>32!#DQc7E{dd{E7bQ$`l;cc;m`$Ag]km88mk]gAJ#d`e֚VVրe`d#     \2 * > C@@  0B h  [  S   CS D,+64+>,>#'(($+>32#".54>32>54&#"#"&'2>7.#"\'INV3Zh9IݔVh:Lph0|*G8*xBw`G
&>W:TX- <U9*Jʀ9k_sʔVYV%C7ps,S@&>mWAfF%    b   @	 B   C R D+3!%!.'`SM				g:"";   >  $@!  QCD    +##!##5WW    T  &@#B  Q   C Q D+!!!!5467	.5Te=Q	
u;4;A  \  @   M   Q  E+!!\     .    "@ B j    [ D,# +#"&=!2>7>;#)O	s֕!)9e D"8GP   :   ' ; O L@IK-B[
	  O
	 S  G=<)( GE<O=O31(;);	 ''+%".'#".54>32>32%2>7.#"!2>54.#"8[MAAL\7>qU22Uq>7\LAAM[8>pV22VpO$>7227>$$?00?$?//?$$>8228>";L**L;"0Y|LL|X1";L**L;"1X|LL|Y05E''E4/H00H//H00H/4E''E5  \ # (@% B  S   C S D6''"+>32#"#"&'7>32>7v&E doAcK#J
	 :W=%CV	
mvf_-L;]B    ~  7 @ 0!/"BK	PX@+  [   [	O  [	S GKPX@$   [  [	 W S D@+  [   [	O  [	S GYY@ 42+)&$77
 
+2>7#".#"'>322>7#".#"'>326."	#p=4ge_-8."	#qB5hd_-6."	#p=4ge_-8."	#qB5hd_Zr/.!(!m31!)!q0.!)!m31!(!   ~  kKPX@)   ^ _ 	 ZMQE@'  j k 	 ZMQEY@
+!733!!!#7!5!7!rr_2wwK_Vȇ   P   !@  @   M   Q  E+!!G.32yz
z{
      P   !@	 @   M  Q   E+5467%67.'%.=!5!)81GJz
z        "@
  B   M   Q  E+3	#>7	&'|z|	
54&&EF+#&       @   C D+3#      ! a@BK2PX@ S C  Q  CD@   Y S CDY@   ! !U%+3'.=354>32#"&#"!#!p:ts&OdT]I8]p>

]3`         BK&PX@ SC  Q  CDK2PX@" C S C  Q  CD@    Y C S CDYY@    A!%	+3'.=354>32;#.#"!!p4hhSHd6m(]I6TpBY*6      @  S D 
 +2+h
>1P
2H4    
 	 @  j a  		+2#"&'%  Ӌ   v  ' @  O S  G((($+#".54>32#".54>32)'')((((''))''))  D'"  @   M   Q  E+!!D"j     
  @ j   a    
#++7>3

   
x  @ B  j  a* +#"&/&'+73x		
__   
x  @
 B j   a,!+#'32>?>;		
^^  J  (@%j   O  S  G 
 +"&53326533sNVVNssr;==;i|       @   O  S   G($+#".54>32"-,!!,-",!!,,"",  v-   !@    [ O S G$&($+4>32#".732654&#"v3D&'E55E'&D3Y6/-77-/6{'B//B'&@..@&+99+-88  V  1@.  O [  S G 
 +2673#".#"#4>32#%b*>(#@;4"%d+?'#@:4)%+H5+$+I4    N
 	  +@(  O S  G

  

 	 #++7>3!+7>3V&!`(    |  @  S  D 
 +2+ 
>9
!;ZBG      C_<     ʓ^p    ӡD-   	          V  	DC               ' -             6 j$ H~ R X X J  ` d ^ d X <  h l ( l l n `       "l VP 
 Z Z  l  Z f x <R  0  < \ < \ $ :  P     VX X Z   f & \^  J^ H J  2X      j X X HP ^ H& d > ,X z       FX ,X X X t     4  ,X  rf < D \   d< Df  F d R Tf X z: *" |f  x H  f f D ,P 
P 
P 
P 
P 
P 
BZ Z    ff ff* 2 < \< \< \< \< \ ~< \        \ \ \ \ \ \` \ J J J J J     R LX X HX HX HX HX H dX @X zX zX zX z  P   P 
 \Z Z J  J  > , 6 X  \ HH :d >$ :d >  V F V F V F jf  f  f f  f f jf f f ^ 0X j  : Z Z : Z Z v v  X	 Hx x fD " @ V \p X >X T z .X :        t  f fff Df fff f f vf f Nf      l #`    	J    N    J  #  $J  &  *  2  4  9 0  : 0  <   ? 0  D  F  G  H  R  T  mN  oN  yN  }N  J  J  J  J  J  J  J                                                         J                 N  N      N  N  N  J 
 	J 
  
 N 
  
 J 
 # 
 $J 
 & 
 * 
 2 
 4 
 9 0 
 : 0 
 <  
 ? 0 
 D 
 F 
 G 
 H 
 R 
 T 
 mN 
 oN 
 yN 
 }N 
 J 
 J 
 J 
 J 
 J 
 J 
 J 
  
  
  
  
  
  
  
   
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
 J 
  
  
  
  
  
  
   
 N 
 N 
  
  
 N 
 N 
 N 
 J  #  &  *  2  4  F  G  H  R  T                                                  	J    N    J  #  $J  &  *  2  4  9 0  : 0  <   ? 0  D  F  G  H  R  T  mN  oN  yN  }N  J  J  J  J  J  J  J                                                         J                 N  N      N  N  N  J    
    x  #  &  *  2  4  7L  9L  :  <h  ?L  Y|  Z  \|  l  mx  ox  r  yx  |  }x                h      h  x  x          x  x  x    N  	  
N  N  x  x    $  7L  9  :  ;  <`  =  ?  lN  rN  |N                `    `        N  N  x  N  N  x  N      
    x  #  &  *  2  4  7L  9L  :  <h  ?L  Y|  Z  \|  l  mx  ox  r  yx  |  }x                h      h  x  x          x  x  x     0  	x  
 0   0  @    @  x      " 0  #  $x  &  *  -h  2  4  D  F  G  H  I  Jx  P  Q  R  S  T  U  V  W  X  Y  [  \  ]  l 0  m  o  r 0  t :  u :  w  y  { :  | 0  }  x  x  x  x  x  x  x                                                                x                     0   0  @   0   0  @         0  x #  # 	 # 
 #  #  #  #  #  # $ # 7 # 9 # ; # < # = # ? # @ # ` # l # r # | #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  $ J $ 
J $ J $  $ " $ # $ & $ * $ - 2 $ 2 $ 4 $ 7| $ 8 $ 9x $ : $ <\ $ ?x $ Y $ \ $ lJ $ m $ o $ rJ $ tH $ uH $ y $ {H $ |J $ } $  $  $  $  $  $  $  $  $  $  $  $ \ $  $  $ \ $  $  $ J $ J $ J $ J $  $  $  $ J & j & mj & oj & yj & }j & j & j & j & j & j '  ' 	 ' 
 '  '  '  '  '  ' $ ' 7 ' 9 ' ; ' < ' = ' ? ' @ ' ` ' l ' r ' | '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  ) 	| ) L ) L ) | )  )  ) "  ) $| ) -: ) F ) G ) H ) P ) Q ) R ) S ) T ) U ) X ) w ) | ) | ) | ) | ) | ) | ) | )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  ) | )  )  )  )  ) L ) L ) | - 	 -  -  -  - $ -  -  -  -  -  -  -  -  -  -  -  .  . # . & . * . 2 . 4 . F . G . H . I . R . T . W . Y . Z . \ . m . o . y . } .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  /  / 
 /  /  6 / : /  6 / " / # / & / * / 2 / 4 / 7T / 9J / :h / <, / ?J / F / G / H / R / T / Y / Z / \ / l / m: / o: / r / t6 / u6 / y: / {6 / | / }: /  /  /  /  /  /  /  / , /  /  /  /  /  /  /  /  /  /  /  /  /  /  /  /  /  / , / : / : /  /  /  6 /  /  /  6 / : / : / : /  2  2 	 2 
 2  2  2  2  2  2 $ 2 7 2 9 2 ; 2 < 2 = 2 ? 2 @ 2 ` 2 l 2 r 2 | 2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  3 	v 3  3  3 v 3 $v 3 -J 3 D 3 F 3 G 3 H 3 R 3 T 3 v 3 v 3 v 3 v 3 v 3 v 3 v 3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3 v 3  3  3  3  3  3  3 v 4  4 	 4 
 4  4  4  4  4  4 $ 4 7 4 9 4 ; 4 < 4 = 4 ? 4 @ 4 ` 4 l 4 r 4 | 4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  5 # 5 & 5 * 5 2 5 4 5 7 5 8 5  5  5  5  5  5  5  5  5  5  5  5  5  7 	| 7 L 7 L 7 L 7 | 7 ` 7 ` 7 # 7 $| 7 & 7 * 7 -8 7 2 7 4 7 D 7 F. 7 G. 7 H. 7 JD 7 P` 7 Q` 7 R. 7 S` 7 T. 7 U` 7 V^ 7 X` 7 YL 7 Zt 7 [p 7 \L 7 ] 7 mL 7 oL 7 w` 7 yL 7 }L 7 | 7 | 7 | 7 | 7 | 7 | 7 | 7  7  7  7  7  7  7  7  7  7  7  7  7  7  7 . 7 . 7 . 7 . 7 . 7 . 7 ` 7 . 7 . 7 . 7 . 7 . 7 . 7 ` 7 ` 7 ` 7 ` 7 | 7  7  7 . 7 . 7 ` 7  7 . 7 L 7 L 7 L 7 L 7 L 7 L 7 L 7 | 8 	 8  8  8  8 $ 8  8  8  8  8  8  8  8  8  8  8  9  0 9 	x 9 
 0 9  0 9 @ 9  9 @ 9 x 9  9  9 " 0 9 # 9 $x 9 & 9 * 9 -h 9 2 9 4 9 D 9 F 9 G 9 H 9 I 9 Jx 9 P 9 Q 9 R 9 S 9 T 9 U 9 V 9 W 9 X 9 Y 9 [ 9 \ 9 ] 9 l 0 9 m 9 o 9 r 0 9 t : 9 u : 9 w 9 y 9 { : 9 | 0 9 } 9 x 9 x 9 x 9 x 9 x 9 x 9 x 9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9 x 9  9  9  9  9  9  9  9  9  9  0 9  0 9 @ 9  0 9  0 9 @ 9  9  9  9  0 9 x :  0 : 	 : 
 0 :  0 :  :  :  :  : " " : $ : - : D : F : G : H : J : R : T : V : l 0 : m : o : r 0 : t 0 : u 0 : y : { 0 : | 0 : } :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  0 :  0 :  :  0 :  0 :  :  :  :  :  0 :  ;  ; # ; & ; * ; 2 ; 4 ; F ; G ; H ; I ; R ; T ; W ; Y ; Z ; \ ; m ; o ; y ; } ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  <   < 	\ < 
  <   < h < ` < h < \ <  <  < " " < # < $\ < & < * < -8 < 2 < 4 < D < F` < G` < H` < JT < P < Q < R` < S < T` < U < V < X < Y < Z < [| < \ < l  < m` < o` < r  < t 2 < u 2 < w < y` < { 2 < |  < }` < \ < \ < \ < \ < \ < \ < \ <  <  <  <  <  <  <  <  <  <  <  <  <  <  < ` < ` < ` < ` < ` < ` <  < ` < ` < ` < ` < ` < ` <  <  <  <  < \ <  <  < ` < ` <  <  < ` < ` < ` <   <   < h <   <   < h < ` < ` < ` <   < \ =  = " " = # = & = * = 2 = 4 = F = G = H = R = T = V = Y = \ = m = o = y = } =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  =  > # > & > * > 2 > 4 > F > G > H > R > T >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  ? J ? 
J ? J ?  ? " ? # ? & ? * ? - 2 ? 2 ? 4 ? 7| ? 8 ? 9x ? : ? <\ ? ?x ? Y ? \ ? lJ ? m ? o ? rJ ? tH ? uH ? y ? {H ? |J ? } ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ? \ ?  ?  ? \ ?  ?  ? J ? J ? J ? J ?  ?  ?  ? J D  D 
 D  D Y D Z D \ D l D r D t D u D { D | D  D  D  D  D  E  E 
 E  E  E 9 E : E ? E @ E Y E [ E \ E ` E l E r E | E  E  E  E  E  H  H 
 H  H  H 9 H : H ? H @ H Y H [ H \ H ` H l H r H | H  H  H  H  H  I  D I 
 D I  D I ~ I ~ I l D I r D I t d I u d I { d I | D I  D I  D I ~ I  D I  D I ~ I  D K  K 
 K  K Y K Z K \ K l K r K t K u K { K | K  K  K  K  K  N F N G N H N R N T N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  P  P 
 P  P Y P Z P \ P l P r P t P u P { P | P  P  P  P  P  Q  Q 
 Q  Q Y Q Z Q \ Q l Q r Q t Q u Q { Q | Q  Q  Q  Q  Q  R  R 
 R  R  R 9 R : R ? R @ R Y R [ R \ R ` R l R r R | R  R  R  R  R  S  S 
 S  S  S 9 S : S ? S @ S Y S [ S \ S ` S l S r S | S  S  S  S  S  U | U | U D U  U  U  U  U  U  U  U  U | U | Y 	 Y | Y | Y  Y $ Y F Y G Y H Y R Y T Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y | Y | Y  Z  Z  Z  Z  [ F [ G [ H [ R [ T [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  \ 	 \ | \ | \  \ $ \ F \ G \ H \ R \ T \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \ | \ | \  ^ # ^ & ^ * ^ 2 ^ 4 ^ F ^ G ^ H ^ R ^ T ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  l 	J l  l N l  l J l # l $J l & l * l 2 l 4 l 9 0 l : 0 l <  l ? 0 l D l F l G l H l R l T l mN l oN l yN l }N l J l J l J l J l J l J l J l  l  l  l  l  l  l  l   l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l J l  l  l  l  l  l  l   l N l N l  l  l N l N l N l J m N m 	 m 
N m N m x m x m  m $ m 7L m 9 m : m ; m <` m = m ? m lN m rN m |N m  m  m  m  m  m  m  m ` m  m ` m  m  m  m N m N m x m N m N m x m N m  o N o 	 o 
N o N o x o x o  o $ o 7L o 9 o : o ; o <` o = o ? o lN o rN o |N o  o  o  o  o  o  o  o ` o  o ` o  o  o  o N o N o x o N o N o x o N o  p  p 	 p 
 p  p  p  p  p  p $ p 7 p 9 p ; p < p = p ? p @ p ` p l p r p | p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  r 	J r  r N r  r J r # r $J r & r * r 2 r 4 r 9 0 r : 0 r <  r ? 0 r D r F r G r H r R r T r mN r oN r yN r }N r J r J r J r J r J r J r J r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r J r  r  r  r  r  r  r   r N r N r  r  r N r N r N r J t 	H t H t $H t 9 : t : : t < ( t ? : t H t H t H t H t H t H t H t  ( t H t  ( t H u 	H u H u $H u 9 : u : : u < ( u ? : u H u H u H u H u H u H u H u  ( u H u  ( u H y N y 	 y 
N y N y x y x y  y $ y 7L y 9 y : y ; y <` y = y ? y lN y rN y |N y  y  y  y  y  y  y  y ` y  y ` y  y  y  y N y N y x y N y N y x y N y  { 	H { H { $H { 9 : { : : { < ( { ? : { H { H { H { H { H { H { H {  ( { H {  ( { H | 	J |  | N |  | J | # | $J | & | * | 2 | 4 | 9 0 | : 0 | <  | ? 0 | D | F | G | H | R | T | mN | oN | yN | }N | J | J | J | J | J | J | J |  |  |  |  |  |  |  |   |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | J |  |  |  |  |  |  |   | N | N |  |  | N | N | N | J } N } 	 } 
N } N } x } x }  } $ } 7L } 9 } : } ; } <` } = } ? } lN } rN } |N }  }  }  }  }  }  }  } ` }  } ` }  }  }  } N } N } x } N } N } x } N }   J  
J  J    "  #  &  *  - 2  2  4  7|  8  9x  :  <\  ?x  Y  \  lJ  m  o  rJ  tH  uH  y  {H  |J  }                        \      \      J  J  J  J        J  J  
J  J    "  #  &  *  - 2  2  4  7|  8  9x  :  <\  ?x  Y  \  lJ  m  o  rJ  tH  uH  y  {H  |J  }                        \      \      J  J  J  J        J  J  
J  J    "  #  &  *  - 2  2  4  7|  8  9x  :  <\  ?x  Y  \  lJ  m  o  rJ  tH  uH  y  {H  |J  }                        \      \      J  J  J  J        J  J  
J  J    "  #  &  *  - 2  2  4  7|  8  9x  :  <\  ?x  Y  \  lJ  m  o  rJ  tH  uH  y  {H  |J  }                        \      \      J  J  J  J        J  J  
J  J    "  #  &  *  - 2  2  4  7|  8  9x  :  <\  ?x  Y  \  lJ  m  o  rJ  tH  uH  y  {H  |J  }                        \      \      J  J  J  J        J  J  
J  J    "  #  &  *  - 2  2  4  7|  8  9x  :  <\  ?x  Y  \  lJ  m  o  rJ  tH  uH  y  {H  |J  }                        \      \      J  J  J  J        J  j  mj  oj  yj  }j  j  j  j  j  j    	  
            $  7  9  ;  <  =  ?  @  `  l  r  |                                              	  
            $  7  9  ;  <  =  ?  @  `  l  r  |                                              	  
            $  7  9  ;  <  =  ?  @  `  l  r  |                                              	  
            $  7  9  ;  <  =  ?  @  `  l  r  |                                              	  
            $  7  9  ;  <  =  ?  @  `  l  r  |                                              	  
            $  7  9  ;  <  =  ?  @  `  l  r  |                                            	        $                        	        $                        	        $                        	        $                           	\  
      h  `  h  \      " "  #  $\  &  *  -8  2  4  D  F`  G`  H`  JT  P  Q  R`  S  T`  U  V  X  Y  Z  [|  \  l   m`  o`  r   t 2  u 2  w  y`  { 2  |   }`  \  \  \  \  \  \  \                              `  `  `  `  `  `    `  `  `  `  `  `          \      `  `      `  `  `        h        h  `  `  `     \    	  
            $  7  9  ;  <  =  ?  @  `  l  r  |                                              
    Y  Z  \  l  r  t  u  {  |              
    Y  Z  \  l  r  t  u  {  |              
    Y  Z  \  l  r  t  u  {  |              
    Y  Z  \  l  r  t  u  {  |              
    Y  Z  \  l  r  t  u  {  |              
    Y  Z  \  l  r  t  u  {  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
    Y  Z  \  l  r  t  u  {  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |              
      9  :  ?  @  Y  [  \  `  l  r  |            J  
J  J    "  #  &  *  - 2  2  4  7|  8  9x  :  <\  ?x  Y  \  lJ  m  o  rJ  tH  uH  y  {H  |J  }                        \      \      J  J  J  J        J    
    Y  Z  \  l  r  t  u  {  |            j  mj  oj  yj  }j  j  j  j  j  j    
      9  :  ?  @  Y  [  \  `  l  r  |            t  
t  t    9^  :  <h  ?^  Y  \  lt  m  o  rt  t|  u|  y  {|  |t  }  h  h      t  t  t  t        t    
    Y  Z  \  l  r  t  u  {  |              
      9  :  ?  @  Y  [  \  `  l  r  |               	\  
      h  `  h  \      " "  #  $\  &  *  -8  2  4  D  F`  G`  H`  JT  P  Q  R`  S  T`  U  V  X  Y  Z  [|  \  l   m`  o`  r   t 2  u 2  w  y`  { 2  |   }`  \  \  \  \  \  \  \                              `  `  `  `  `  `    `  `  `  `  `  `          \      `  `      `  `  `        h        h  `  `  `     \    " "  #  &  *  2  4  F  G  H  R  T  V  Y  \  m  o  y  }                                                              " "  #  &  *  2  4  F  G  H  R  T  V  Y  \  m  o  y  }                                                              " "  #  &  *  2  4  F  G  H  R  T  V  Y  \  m  o  y  }                                                            N  	  
N  N  x  x    $  7L  9  :  ;  <`  =  ?  lN  rN  |N                `    `        N  N  x  N  N  x  N    N  	  
N  N  x  x    $  7L  9  :  ;  <`  =  ?  lN  rN  |N                `    `        N  N  x  N  N  x  N    	J    N    J  #  $J  &  *  2  4  9 0  : 0  <   ? 0  D  F  G  H  R  T  mN  oN  yN  }N  J  J  J  J  J  J  J                                                         J                 N  N      N  N  N  J  	J    N    J  #  $J  &  *  2  4  9 0  : 0  <   ? 0  D  F  G  H  R  T  mN  oN  yN  }N  J  J  J  J  J  J  J                                                         J                 N  N      N  N  N  J    
    x  #  &  *  2  4  7L  9L  :  <h  ?L  Y|  Z  \|  l  mx  ox  r  yx  |  }x                h      h  x  x          x  x  x    	J    N    J  #  $J  &  *  2  4  9 0  : 0  <   ? 0  D  F  G  H  R  T  mN  oN  yN  }N  J  J  J  J  J  J  J                                                         J                 N  N      N  N  N  J  	J    N    J  #  $J  &  *  2  4  9 0  : 0  <   ? 0  D  F  G  H  R  T  mN  oN  yN  }N  J  J  J  J  J  J  J                                                         J                 N  N      N  N  N  J    
    x  #  &  *  2  4  7L  9L  :  <h  ?L  Y|  Z  \|  l  mx  ox  r  yx  |  }x                h      h  x  x          x  x  x    N  	  
N  N  x  x    $  7L  9  :  ;  <`  =  ?  lN  rN  |N                `    `        N  N  x  N  N  x  N    N  	  
N  N  x  x    $  7L  9  :  ;  <`  =  ?  lN  rN  |N                `    `        N  N  x  N  N  x  N    N  	  
N  N  x  x    $  7L  9  :  ;  <`  =  ?  lN  rN  |N                `    `        N  N  x  N  N  x  N    	J    N    J  #  $J  &  *  2  4  9 0  : 0  <   ? 0  D  F  G  H  R  T  mN  oN  yN  }N  J  J  J  J  J  J  J                                                         J                 N  N      N  N  N  J  J  
J  J    "  #  &  *  - 2  2  4  7|  8  9x  :  <\  ?x  Y  \  lJ  m  o  rJ  tH  uH  y  {H  |J  }                        \      \      J  J  J  J        J       D(\8R| Z R	@	

*
N
t
:::*z>&`.d8TvlHPTn"`N*ZN  z  !!"# #j##$n$$%%l%&&X&&'('l''(l))*>*J*V*b*n*z**++++,,, ,,,8,,,,,,,,------......../00000000111111112(2222223d3p44445d6"6<6p66678T8`8l8x888888889*9R9999:4::;;x;;;<<0<~<==j=>>p?~???@~@ADAABBNBhBC8CD8DDEEHE^EF8F`FFFGG4GbGGGH@HzH      b   " / n   	     n                                 *                (                0        /      	 G      
V       2       2J       |       >  	  X  	  l  	  t  	  T  	    	  P  	    	  `>  	  0  	 	   	 
  	  0  	  d  	 8  	  4Copyright (c) 2010-2013 by tyPoland Lukasz Dziedzic with Reserved Font Name "Lato". Licensed under the SIL Open Font License, Version 1.1.LatoRegulartyPolandLukaszDziedzic: Lato Regular: 2013Lato RegularVersion 1.105; Western+Polish opensourceLato-RegularLato is a trademark of tyPoland Lukasz Dziedzic.tyPoland Lukasz DziedzicLukasz DziedzicLato is a sanserif typeface family designed in the Summer 2010 by Warsaw-based designer Lukasz Dziedzic ("Lato" means "Summer" in Polish). It tries to carefully balance some potentially conflicting priorities: it should seem quite "transparent" when used in body text but would display some original traits when used in larger sizes. The classical proportions, particularly visible in the uppercase, give the letterforms familiar harmony and elegance. At the same time, its sleek sanserif look makes evident the fact that Lato was designed in 2010, even though it does not follow any current trend. The semi-rounded details of the letters give Lato a feeling of warmth, while the strong structure provides stability and seriousness.http://www.typoland.com/http://www.typoland.com/designers/Lukasz_Dziedzic/Copyright (c) 2010-2013 by tyPoland Lukasz Dziedzic (http://www.typoland.com/) with Reserved Font Name "Lato". Licensed under the SIL Open Font License, Version 1.1 (http://scripts.sil.org/OFL).http://scripts.sil.org/OFL C o p y r i g h t   ( c )   2 0 1 0 - 2 0 1 3   b y   t y P o l a n d   L u k a s z   D z i e d z i c   w i t h   R e s e r v e d   F o n t   N a m e   " L a t o " .   L i c e n s e d   u n d e r   t h e   S I L   O p e n   F o n t   L i c e n s e ,   V e r s i o n   1 . 1 . L a t o R e g u l a r t y P o l a n d L u k a s z D z i e d z i c :   L a t o   R e g u l a r :   2 0 1 3 L a t o - R e g u l a r V e r s i o n   1 . 1 0 5 ;   W e s t e r n + P o l i s h   o p e n s o u r c e L a t o   i s   a   t r a d e m a r k   o f   t y P o l a n d   L u k a s z   D z i e d z i c . t y P o l a n d   L u k a s z   D z i e d z i c L u k a s z   D z i e d z i c L a t o   i s   a   s a n s e r i f   t y p e f a c e   f a m i l y   d e s i g n e d   i n   t h e   S u m m e r   2 0 1 0   b y   W a r s a w - b a s e d   d e s i g n e r   L u k a s z   D z i e d z i c   ( " L a t o "   m e a n s   " S u m m e r "   i n   P o l i s h ) .   I t   t r i e s   t o   c a r e f u l l y   b a l a n c e   s o m e   p o t e n t i a l l y   c o n f l i c t i n g   p r i o r i t i e s :   i t   s h o u l d   s e e m   q u i t e   " t r a n s p a r e n t "   w h e n   u s e d   i n   b o d y   t e x t   b u t   w o u l d   d i s p l a y   s o m e   o r i g i n a l   t r a i t s   w h e n   u s e d   i n   l a r g e r   s i z e s .   T h e   c l a s s i c a l   p r o p o r t i o n s ,   p a r t i c u l a r l y   v i s i b l e   i n   t h e   u p p e r c a s e ,   g i v e   t h e   l e t t e r f o r m s   f a m i l i a r   h a r m o n y   a n d   e l e g a n c e .   A t   t h e   s a m e   t i m e ,   i t s   s l e e k   s a n s e r i f   l o o k   m a k e s   e v i d e n t   t h e   f a c t   t h a t   L a t o   w a s   d e s i g n e d   i n   2 0 1 0 ,   e v e n   t h o u g h   i t   d o e s   n o t   f o l l o w   a n y   c u r r e n t   t r e n d .   T h e   s e m i - r o u n d e d   d e t a i l s   o f   t h e   l e t t e r s   g i v e   L a t o   a   f e e l i n g   o f   w a r m t h ,   w h i l e   t h e   s t r o n g   s t r u c t u r e   p r o v i d e s   s t a b i l i t y   a n d   s e r i o u s n e s s . h t t p : / / w w w . t y p o l a n d . c o m / h t t p : / / w w w . t y p o l a n d . c o m / d e s i g n e r s / L u k a s z _ D z i e d z i c / C o p y r i g h t   ( c )   2 0 1 0 - 2 0 1 3   b y   t y P o l a n d   L u k a s z   D z i e d z i c   ( h t t p : / / w w w . t y p o l a n d . c o m / )   w i t h   R e s e r v e d   F o n t   N a m e   " L a t o " .   L i c e n s e d   u n d e r   t h e   S I L   O p e n   F o n t   L i c e n s e ,   V e r s i o n   1 . 1   ( h t t p : / / s c r i p t s . s i l . o r g / O F L ) . h t t p : / / s c r i p t s . s i l . o r g / O F L         t x                              	 
                        ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ 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    j i k m l n  o q p r s u t v w  x z y { } |    ~       	
                                                     !"#NULLuni00A0uni00ADmacronperiodcenteredAogonekaogonekEogonekeogonekNacutenacuteSacutesacuteZacutezacute
Zdotaccent
zdotaccentuni02C9EuroDeltauni2669undercommaaccent
grave.casedieresis.casemacron.case
acute.casecircumflex.case
caron.case
breve.casedotaccent.case	ring.case
tilde.casehungarumlaut.case
caron.salt                             VV , `f-, d P&ZE[X!#!X PPX!@Y 8PX!8YY Ead(PX!E 0PX!0Y PX f a 
PX`  PX!
` 6PX!6``YYY +YY# PXeYY-, E %ad CPX#B#B!!Y`-,#!#! dbB #B*! C   +0%QX`PaRYX#Y! @SX +!@Y# PXeY-,C+  C`B-,#B#  #Bab`*-,  E EcEb`D`-,  E  +#%` E#a d  PX! 0PX @YY# PXeY%#aDD`-,EaD-	,`  	CJ PX 	#BY
CJ RX 
#BY-
,  b  c#aC` ` #B#-,KTXDY$e#x-,KQXKSXDY!Y$e#x-, CUXCaB
+Y C%B	%B
%B# %PX C`%B #a	*!#a #a	*! C`%B%a	*!Y	CG
CG`b EcEb`  #DC >C`B-, ETX #B `a  BB`+m+"Y-, +-,+-,+-,+-,+-,+-,+-,+-,+-,	+-,+ ETX #B `a  BB`+m+"Y-, +-,+-,+-,+-,+-,+- ,+-!,+-",+-#,	+-$, <`-%, `` C#`C%a`$*!-&,%+%*-',  G  EcEb`#a8# UX G  EcEb`#a8!Y-(, ETX '*0"Y-),+ ETX '*0"Y-*, 5`-+, EcEb +EcEb +      D>#8**-,, < G EcEb` Ca8--,.<-., < G EcEb` CaCc8-/, % . G #B%IG#G#a Xb!Y#B.*-0, %%G#G#aE+e.#  <8-1, %% .G#G#a #BE+ `PX @QX  &YBB# C #G#G#a#F`Cb`  + a C`d#CadPXCaC`Y%ba#  &#Fa8#CF%CG#G#a` Cb`#  +#C` +%a%b&a %`d#%`dPX!#!Y#  &#Fa8Y-2,    & .G#G#a#<8-3,  #B   F#G +#a8-4, %%G#G#a TX. <#!%%G#G#a %%G#G#a%%I%aEc# Xb!YcEb`#.#  <8#!Y-5,  C .G#G#a ` `fb#  <8-6,# .F%FRX <Y.&+-7,# .F%FPX <Y.&+-8,# .F%FRX <Y# .F%FPX <Y.&+-9,0+# .F%FRX <Y.&+-:,1+  <#B8# .F%FRX <Y.&+C.&+-;, %& .G#G#aE+# < .#8&+-<,%B %% .G#G#a #BE+ `PX @QX  &YBB# GCb`  + a C`d#CadPXCaC`Y%ba%Fa8# <#8!  F#G +#a8!Y&+-=,0+.&+->,1+!#  <#B#8&+C.&+-?,  G #B .,*-@,  G #B .,*-A, -*-B,/*-C, E# . F#a8&+-D,#BC+-E,  <+-F, <+-G, <+-H,<+-I,  =+-J, =+-K, =+-L,=+-M,  9+-N, 9+-O, 9+-P,9+-Q,  ;+-R, ;+-S, ;+-T,;+-U,  >+-V, >+-W, >+-X,>+-Y,  :+-Z, :+-[, :+-\,:+-],2+.&+-^,2+6+-_,2+7+-`, 2+8+-a,3+.&+-b,3+6+-c,3+7+-d,3+8+-e,4+.&+-f,4+6+-g,4+7+-h,4+8+-i,5+.&+-j,5+6+-k,5+7+-l,5+8+-m,+e$Px0-   K KRXY  c #D#pE  (`f UX%aEc#b#D***Y(	ERD*D$QX@XD&QX XDYYYY D                  DSIG    tL   GPOS  ,  HPGSUBV.T  I|  OS/2ٮ  J   `cmapRԟ  J  cvt ' i   8fpgmzA j4  	gasp    i   glyfmr  O  >headd     6hhea`  L   $hmtx4W  p  Tkern@B    glocaE/ R  ,maxpC
 T    name U  Tpost:] fX  prepx9 s       
 0 J DFLT latn                 kern kern                   G    r Tv		

V8,^$^0
DJJJL F !z"##P#$4$~%x&&'()*++,J,-n. ./$/V///1242n2233V3344J4445567778~88:;";;<=2>,?&?@ABC8CDE.F( > 	U    U $U 9 6 : 0 < - ? 6 D F G H R T m o y } U U U U U U U  -                    U      -         U > 	U    U $U 9 6 : 0 < - ? 6 D F G H R T m o y } U U U U U U U  -                    U      -         U - # & * 2 4 D F G H R T k p                                 > 	U    U $U 9 6 : 0 < - ? 6 D F G H R T m o y } U U U U U U U  -                    U      -         U 0  
  ; # & * 2 4 75 9, :| <; ?, Yr Z \| k l m; o; p r y; | };        ; r r   ; ; ;     ; ; ; &  	 
  ^ ^  $ 7A 9 ; <@ = ? l r |        @  @      ^   ^ ^  0  
  ; # & * 2 4 75 9, :| <; ?, Yr Z \| k l m; o; p r y; | };        ; r r   ; ; ;     ; ; ; q  6 	 
 6  6 A  A    " : # $ & * -i 2 4 D F G H P Q R S T U V X Y Z \ ] k l 6 m o p r 6 t P u P w y { P | 6 }                                                         6  6 A  6  6 A  A    $  	 
    $ 7 9 ; < = ? @ ` l r |                   : J 
J J  # & * - > 2 4 7| 8 9 : <h ? W Y Z \ k lJ m o p rJ tI uI y {I |J }            h     h   J J J J    
  m o y }      $  	 
    $ 7 9 ; < = ? @ ` l r |                   > 	| L L |   "  $| -: D F G H P Q R S T U X w | | | | | | |                         |      L L L |  	  $          +   
     # & * 2 4 I W Y Z \ k l  m o p r  y |  }                         3  
  ; # & * 2 4 78 9J :h <, ?J Y| Z \| k l m; o; p r t, u, y; {, | };        , | |   , ; ;     ; ; ; $  	 
    $ 7 9 ; < = ? @ ` l r |                   / 	v C C v $v -J D F G H R T v v v v v v v                    v     C C C v $  	 
    $ 7 9 ; < = ? @ ` l r |                    # & * 2 4 7 8 k p              f 	| L L L | f f " ' # $| & * -8 2 4 D/ F/ G/ H/ JE Pf Qf R/ Sf T/ Uf VJ Xf YW Z [Z \L ]_ k mL oL p wf yL }L | | | | | | |        / / / / / / / / / / / / / f / / / / / / f f f f W W | /  / / f  / J J _ _ _ L L L L L L L L |  	  $          q  6 	 
 6  6 A  A    " : # $ & * -i 2 4 D F G H P Q R S T U V X Y Z \ ] k l 6 m o p r 6 t P u P w y { P | 6 }                                                         6  6 A  6  6 A  A    N  : 	 
 :  :      $ - D F G H J P Q R S T U V X l : r : t < u < w { < | :                                         :  :   :  :    +   
     # & * 2 4 I W Y Z \ k l  m o p r  y |  }                         m  7 	r 
 7  7 ' J ' r   " 2 # $r & * -8 2 4 DA FA GA HA JW P Q RA S TA U VA X ] k l 7 mJ oJ p r 7 t > u > w yJ { > | 7 }J r r r r r r r        A A A A A A A A A A A A A  A A A A A A     r A  A A   A A A    J J  7  7 '  7  7 ' J ' J J r   " # # & * 2 4 k m o p y }               - # & * 2 4 D F G H R T k p                                 : J 
J J  # & * - > 2 4 7| 8 9 : <h ? W Y Z \ k lJ m o p rJ tI uI y {I |J }            h     h   J J J J      
   @ [ ` l r |       
   @ [ ` l r |       E 
 E  E   l E r E t d u d { d | E  E  E   E  E     
  Y \ l r t u { |        D F G H R T                          
  Y \ l r t u { |         
  Y \ l r t u { |         
   @ [ ` l r |       
   @ [ ` l r |     " h h D F G H R T                        h h h . 	 r r  $ D F G H R T                                r r r   	    $              D F G H R T                        . 	 h h  $ D F G H R T                                h h h  - # & * 2 4 D F G H R T k p                                 $  	 
    $ 7 9 ; < = ? @ ` l r |                   > 	U    U $U 9 6 : 0 < - ? 6 D F G H R T m o y } U U U U U U U  -                    U      -         U &  	 
  ^ ^  $ 7A 9 ; <@ = ? l r |        @  @      ^   ^ ^  &  	 
  ^ ^  $ 7A 9 ; <@ = ? l r |        @  @      ^   ^ ^  $  	 
    $ 7 9 ; < = ? @ ` l r |                   > 	U    U $U 9 6 : 0 < - ? 6 D F G H R T m o y } U U U U U U U  -                    U      -         U  	T T $T 9 : : : < ( ? : T T T T T T T  ( T  ( T  	T T $T 9 : : : < ( ? : T T T T T T T  ( T  ( T &  	 
  ^ ^  $ 7A 9 ; <@ = ? l r |        @  @      ^   ^ ^   	T T $T 9 : : : < ( ? : T T T T T T T  ( T  ( T > 	U    U $U 9 6 : 0 < - ? 6 D F G H R T m o y } U U U U U U U  -                    U      -         U &  	 
  ^ ^  $ 7A 9 ; <@ = ? l r |        @  @      ^   ^ ^  : J 
J J  # & * - > 2 4 7| 8 9 : <h ? W Y Z \ k lJ m o p rJ tI uI y {I |J }            h     h   J J J J    : J 
J J  # & * - > 2 4 7| 8 9 : <h ? W Y Z \ k lJ m o p rJ tI uI y {I |J }            h     h   J J J J    : J 
J J  # & * - > 2 4 7| 8 9 : <h ? W Y Z \ k lJ m o p rJ tI uI y {I |J }            h     h   J J J J    : J 
J J  # & * - > 2 4 7| 8 9 : <h ? W Y Z \ k lJ m o p rJ tI uI y {I |J }            h     h   J J J J    : J 
J J  # & * - > 2 4 7| 8 9 : <h ? W Y Z \ k lJ m o p rJ tI uI y {I |J }            h     h   J J J J    : J 
J J  # & * - > 2 4 7| 8 9 : <h ? W Y Z \ k lJ m o p rJ tI uI y {I |J }            h     h   J J J J    
  m o y }      $  	 
    $ 7 9 ; < = ? @ ` l r |                   $  	 
    $ 7 9 ; < = ? @ ` l r |                   $  	 
    $ 7 9 ; < = ? @ ` l r |                   $  	 
    $ 7 9 ; < = ? @ ` l r |                   $  	 
    $ 7 9 ; < = ? @ ` l r |                   $  	 
    $ 7 9 ; < = ? @ ` l r |                    	  $           	  $           	  $           	  $          m  7 	r 
 7  7 ' J ' r   " 2 # $r & * -8 2 4 DA FA GA HA JW P Q RA S TA U VA X ] k l 7 mJ oJ p r 7 t > u > w yJ { > | 7 }J r r r r r r r        A A A A A A A A A A A A A  A A A A A A     r A  A A   A A A    J J  7  7 '  7  7 ' J ' J J r $  	 
    $ 7 9 ; < = ? @ ` l r |                     
   @ [ ` l r |       
   @ [ ` l r |       
   @ [ ` l r |       
   @ [ ` l r |       
   @ [ ` l r |       
  Y \ l r t u { |         
   @ [ ` l r |       
   @ [ ` l r |       
   @ [ ` l r |       
   @ [ ` l r |       
   @ [ ` l r |       
   @ [ ` l r |     . 	 r r  $ D F G H R T                                r r r    
   @ [ ` l r |     . 	 r r  $ D F G H R T                                r r r  : J 
J J  # & * - > 2 4 7| 8 9 : <h ? W Y Z \ k lJ m o p rJ tI uI y {I |J }            h     h   J J J J    
  m o y }        
   @ [ ` l r |     " i 
i i  9^ : <h ?^ Y Z \ li m o ri t} u} y {} |i } h   h   i i i i      
  Y \ l r t u { |         
   @ [ ` l r |     m  7 	r 
 7  7 ' J ' r   " 2 # $r & * -8 2 4 DA FA GA HA JW P Q RA S TA U VA X ] k l 7 mJ oJ p r 7 t > u > w yJ { > | 7 }J r r r r r r r        A A A A A A A A A A A A A  A A A A A A     r A  A A   A A A    J J  7  7 '  7  7 ' J ' J J r   " # # & * 2 4 k m o p y }                 " # # & * 2 4 k m o p y }                 " # # & * 2 4 k m o p y }               &  	 
  ^ ^  $ 7A 9 ; <@ = ? l r |        @  @      ^   ^ ^  &  	 
  ^ ^  $ 7A 9 ; <@ = ? l r |        @  @      ^   ^ ^  > 	U    U $U 9 6 : 0 < - ? 6 D F G H R T m o y } U U U U U U U  -                    U      -         U > 	U    U $U 9 6 : 0 < - ? 6 D F G H R T m o y } U U U U U U U  -                    U      -         U 0  
  ; # & * 2 4 75 9, :| <; ?, Yr Z \| k l m; o; p r y; | };        ; r r   ; ; ;     ; ; ; > 	U    U $U 9 6 : 0 < - ? 6 D F G H R T m o y } U U U U U U U  -                    U      -         U > 	U    U $U 9 6 : 0 < - ? 6 D F G H R T m o y } U U U U U U U  -                    U      -         U 0  
  ; # & * 2 4 75 9, :| <; ?, Yr Z \| k l m; o; p r y; | };        ; r r   ; ; ;     ; ; ; &  	 
  ^ ^  $ 7A 9 ; <@ = ? l r |        @  @      ^   ^ ^  0  
  ; # & * 2 4 75 9, :| <; ?, Yr Z \| k l m; o; p r y; | };        ; r r   ; ; ;     ; ; ; &  	 
  ^ ^  $ 7A 9 ; <@ = ? l r |        @  @      ^   ^ ^  &  	 
  ^ ^  $ 7A 9 ; <@ = ? l r |        @  @      ^   ^ ^  > 	U    U $U 9 6 : 0 < - ? 6 D F G H R T m o y } U U U U U U U  -                    U      -         U : J 
J J  # & * - > 2 4 7| 8 9 : <h ? W Y Z \ k lJ m o p rJ tI uI y {I |J }            h     h   J J J J     r  
       # $ & ' ) - . / 2 3 4 5 7 8 9 : ; < = > ? E H I K N P Q R S U Y Z [ \ ^ k l m o p r t u y { | }                                                              
 8  DFLT latn                     case &case ,liga 2liga 8sups >sups D                                        ,     >  B 	
  @       L  O  ,  { t u   C j q v          I            x  x   t  P `K        tyPL   Jz                              & 
                                                                          	 
                        ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ 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                                    r d e i  x  p k  v j    s g w      l |     c n     m }  b                    y                        q    z    `   T @      ~ 1DS[a~    " & 0 : D !"!&"""""""+"H"`"e%&i        1ARZ`x      & 0 9 D !"!&"""""""+"H"`"d%&i {uq[H$I޸ޡޞ:ڜ                                                                                      `   T @      ~ 1DS[a~    " & 0 : D !"!&"""""""+"H"`"e%&i        1ARZ`x      & 0 9 D !"!&"""""""+"H"`"d%&i {uq[H$I޸ޡޞ:ڜ                                                                                         -   ( 8 < @ J@G  B h f    [  [ 		Q C Q D@?($#-$
+>32#'.54>54&#"#"'4632#"&!!7!!9DO.?gI)-60#z
-5-I9)8(c>0((0>22cu&#@[87P;+&%ia/(&.8'3</@)(?g6,       ! &@#   QC S D    +#>74>32#".FuF!-."".-!-UV\44\VU->."".-""-      
  *@'	 B  Q D   
 
$+#"&=!#"&=$"%$"%ߛ""!ߛ""!    6   < @ H@E Y	CQ
C   D  @?>= < <6431.-(&##!#!+#"&547#+#"546?3#7>;>;3323+32%3#Nqt0M+j'&v
-NMv&%jjX]#(
7KGk X	G
7K    Gbf 8 C N @J) ? B AK	PX@$ j   h   f k C DKPX@$ j   h   f k C D@$ j   h   f k C DYY#'#%+.'7632.54>?>;#".'+4.'>w?=+A\Dg>w]9B|o@&g30%6I2]@~c>Fu"@":N,`JsP)5H)WHkG"aKN&1/1KoRSxLQ;@"!2IlO_S,A0#2Oh*?1%-DU   Z  ' 1 E Y KPX@'    [  	[ SC 		SDK PX@+    [  	[ SC C 		S D@/    [  	[ C S C C 		S DYY@VT((%#&((($
+#".54>324.#"32>>;+#".54>324.#"32>;`{A8^C%6]}F8^C&$1(G4$1'G5w|
~:`|A8]C%6]}F8]D%$1(G5$1'G6xcj7)MoFck8)NpH2H."JsQ1E-!GqUci7)MnFcl8)NpH2G."JrQ1F-!Hr     9 B N @;LK.&BKPX@* h  S  C SC SD@( h  S  C S C S DY@ IG20)'#! BB+2#"'.#">7>;#"./#".54>7.54>3267FrR-e)<)3R; /2B)6w[G`^Rb65]}H'%9iq#=T1_Fsr,Nj>!8-&C[49x?gBGs`zWf1[QOu\ B?Rj>8W<VF>     
 @	 B   Q D   
 
$+#"&=$"%ߛ""!     zS  (+.547*Q*;& UuGJrN)JC.VS	/r     (+4.'&546?
'.547>9)R);& TuFIsN)1IC/WT.r    a 6 C@0,+'$#	 BKPX@ k    D@
   jaY@
   6 6+7>7'767&/7&546?3>?'.'i!$$$3T
	 # 2a!
dIefIe!
dIefHd
   s A  .@+ j k  M  R F    +!!#!7!5f55i6SQ     2$   @?   S D"+74632'&54>7#"&2A6.1F- *'4A{/B'3-a_Z&&5E*E  a<  @   M   Q  E+!!s8    -'   @   S D($+74>32#".-"--""--"n."".-""-    . 	 @   k D#"++>;]:I4 I "!  Oj  ' ,@)  S  CS D ''	 +2#".54>2>54.#"_sAb~`sAb TqB-Le8TqB-LeIےkIۓJkYxj0Yxi0         *@'
B   h C  R D$+7!7#"&/3!!6{,֌MKq     /  J 4 ;@80B h  S  C Q D -+'% 44+2>3!2!7>7>54.#"#"&/>Sf99bJQ)R&HIrO)#>U2p%#Wc/ZR[~Cx
"5;)AusxE6R6ufbf4    ]X C U@R?
B h h  [  S  C S D <:64.-,+#! CC	+2#".'763232>54.#7>54.#"#"&/>Tb6*MmCz{VjdjBP,B\ARW.Nf">T2r&#Xc.UxIOyZ;#pl{B.\_:W:8Zr;0Q;"{5P5vebf4    -  f   '@$ B  \ C D!#+3+#!"&/3>7!./"+b{W79   DF . @@=,+B h  [   Q C S D(#&(""+#!632#".'763232>54.#"'!<379so\ii4]u?p_N=/C_CSd7$HnK2sDgM$/9dQ~͐O)6J%8eV9]C$    h0  2 2@/ B   [ C S D /-%#	 +2#".54>7>;>32>54.#"Oe:Tvbl99W<3.%7$Dd@Oa6'Ge>O^5l2`WoP<n_>wy}E3,$)!;cH(5^L=cE%8_~       $@!B QC    D    $'++>7!"&=7	'D-+)u   R>  3 G D@AB [ S C S   D54!  ?=4G5G+) 3!3 	+".5467.54>32'2>54.#"2>54.#"cr>aaHiZe6t|QcN~Z0-Lc5Bz_9$FdQqG :X;HoL'9Y3^Q)&bXq@4[{F-#uiw?.RtF@Z9$LwS5W?#4Sf3-N;"-Lh:+P=%     w  1 2@/ B   [ S C D .,&$	 +".54>32+>74.#"32>5K`7Rp^h8;T6c0.=P%D_:I{Z3xO~Y0M0\TiN;jXH}vvB<6-/:_D%2Y{Ju5Zv     -  ' ;K$PX@ S C   S D@   [   S DY((($+74>32#".4>32#".-"--""--"d"--""--"n."".-""-	."".-""-    .  , D?K$PX@ S C   S D@   [   S DY@	)'"+74632'&54>7#"&4>32#"..A6.1F- *'4Ai"--""--"{/B'3-a_Z&&5E*E."".-""-      W  (+6#/+-

'0        !@   Y   M   Q  E+!!!!Z:X=Ѓ   } X  (+	7>7%>7.'%.54>7/+Z|o

'0n     % 9 5@2 B h f  S   C S D(&#*$+>32#7>54&#"#"'4>32#".!KWc8FqP*/HWO=
%w5LWI1_Q8R;'
!-."".-!4(*Je;TvW?;@+0JA>H[=NZ$."".-""-  MM T d f@c
[
<B   h  [  

[	  [ O S GVU ^\UdVdLJ@>9731)' TT+%"&'#".54>3232>54.#"3267>32#".54>32%2>7&#"FR?H0G. ?[wT?[)!3aK.DzelPvLk_<kmuϛZEv1<:8k#)Ia92JMPE#<R0<~uhN-4L#Fitv<u્ړL>03HR_ɥu@O؊םYu3WC(	GrI9H         $@!B   Z C   D# +!#"&'!+3!.'N	%>^zQB&&C   a  e   * =@:B [  S   C SD  *("   !+3!2#!2>54&#%32>54&+aph2%JoJGy?OxP(QyQ(|-SwI@tbLpcxB*NnE_q+MlAgg    d / D@A B h   f S C  S D '%"  //+%2>32#".546$32#".#"BfN7)	A^̍KtL|fS$@(EmWtʔU:g ' Qfq\䉻6{2F+N
(/(]o{B    a  =   @ S C  S    D!(!$+#!!24.#!!2>=qՔP7g]Ό2xƎO1vZlyA[     a  A  (@%  Y   Q C Q D+!!!!!!.<=uϱ/    a  A 	 "@  Y   Q C D+!!!#!.?L/     d% : G@D&
B h   [ S C  S D 20+)"  ::+%2>7#"&50>17!#".546$32#"'.#"4ZOI$'	C6sRӖQsSnY%<
5KjK{͓R;lD

O':']芹3z2D(N
)%^q~C     a  E   @   ZC   D+!#!#3!3QEPOOr}       @ C    D+!#3=    QKPX B BYKPX@ C S    D@ h C  S    DY#%"+#"&'7>3232>736^0
!+4\J3um"N~\    r  %   &@# B    \CD'(% +3267>;#".'.+#3B#-,%#'+QQ" 	
#Y
	<n  a  f  @ C   R D+%!!3/7     a  v " &@# B   h  CD!6(+67>;#>7+"'#3243	/.['*'	g#.~++.	{    a  E  @ B  CD!+2>73#"&'#3rj^`)gH     d  ) @ S C  S    D(((&+#".546$324.#"32>4_kӕOrӕO8g]vƎP8g]xƎO2zڹh8^扷3|_m|D_m|C^     r  i   /@,  [S C    D    !+#!2#32>54.#nBrm6JυtJUX."DhE6dVqM4]L:\A#   d  0 PBKPX@ S C S C    D@   k S C S DY(((%&+#"&'#".546$324.#"32>3^R!"56q<ӕOrӕO8g]vƎP8g]xƎO2yظ4w^扷3|_m|D_m|C^   r  U  # 7@4B  [S C   D  #"  ,!+#!2#"'.#32>54&#vJyrm54bW 51"%/DUY-Y0YNWwS&(0WwGms     = =@:= B   h f S C S D;9(&#!#"+#".#"#"&'7>3232>54.54>32&;T?@dE$0NeheN0FtAB,DdKEoM*0NcicN0@xln9#)#(E\54G3')2JhJfPeVY-7-,NmB7I2%&0JlOX|JTI   {     @  QC D    +!#!7YW     $  #@ C  S D  +%2>73#".5473vPeAkjc{ow>jk'Ko>mZi{ӛXHj-/i&K|Z1     |  W  @ B  C D, +32>7>;#|%7  M**L! g       , !@'
 B  CD,> +32>7>;2>7>;#.'#
$+

'/
( <
:  :gO&&        @  B  CD'"(!+	3267>;	#"&'+ 	lz
Q$lq$  y    @ BC    D,"+#32>7>;GG
}!=;^44>      $@! QC   Q D    +!!7>7!7	"	l7<l;  !W  '@$    [ O QE    !#+!+32!WřC	    lq 	 @  k    D# +32#"&'lI +iH2"9"     )  '@$ B    [ O Q E!#+!!7>;#"&57X	ĘC80    @
 B k    D+!+3#"&'.'+>rgz`+,+  X  @  M Q   E    +!7+tt     M 	 @  k   D  		+2#"&'
kc  0  + ^@  BK"PX@ S C S   D@ S C   CS DY@$!++*' +!#"&57#".54>322>7.#"0\#$S]f7<bE&-StZA{<1^TI++<pbP9 $@hI(/[VZ]3=lY\'FatE     O  , K"PX@ B@ BYK	PX@   CS C TDK"PX@   CS C TD@!   CS CC T DYY@  $",,  (%+33>32#"&'#"32>54&OX&X`h6"?YmFQ*0b[P &j74\L<)V4=eF'R_6D?Au<jW6-,Kes{<w|   <b / dBK	PX@$ h f S C  S    D@$ h f S C  S    DY%(#%($+%#".54>32#".#"32>3234]^e:X[/Mrd38+A3E{\58Q6-F6)!,9L-<m\{hGDC
Kf>eG'!6     5  * s@  BK"PX@ C S C S   D@! C S C  CS DY@ $"**
 +!"&57#"&54>323%2>7.#"#&Zck7"?YmFJ{+E90a[O!&j6OY0V$AjK)R^6:6-?;iV5,^Yw}   ;q * 9 b@
0 BK	PX@   hS C   S D@   hS C   S DY@,++9,9*&%*+32>32#".54>32%">54.q6uv0K;-& ,3afo@W`4!?[uQMpH#?jR:d #8BoYB#75K2:k^NxW2,DRB4[{G19B$'    ? # g@
 BK2PX@" S CQC   Q D@ M   W S DY@   # #T%#++'.5737>32#"&#"3ve.KFdAcI>3	+I8&aKWNbW]0\8ZA]   ; K ^ @9$BKPX@+	 [  [ C S C  S    D@. h	 [  [ S C  S    DY@=<[YSQEC<K=K4320(&
+#".54>32.5467#".54>32!2>54&#"4&'.#"32>0"(")1)BzmWe7RY$G#	&^<:eL,5fbnQ~	
~6R9YN6R8W
6_*RxN&yoBmM+2PD<<?%*DHU:Gb9$B]8OrJ")B)&JoJHmB4;9/M`1XZ,J^3Z^-	0?"HL#:N    O    ,@)B   C S CD    &#+33>32#>54&#"OSOes|LL=B-_ZNATvy+{%RP1ZN   _     GK	PX@ S CC    D@ S CC    DY@  
  +##".54>32zz#,,!",,#>-##-.##/ g  ( Y	 BK	PX@ S CC  S    D@ S CC  S    DY@  %#  U%+#"&'7>323267#".54>32-LiC#2GE
#-+!"+,#=iN-

`IQ@>-##-.##/    N    0@- B    \C CD    %(%!+3267>;#"&'.+#jOy0";Ws
    X    @   CD    +33X?    G   0 Z@ BK"PX@ S  CD@   CSCDY@   0 0&%$$!	+332>32>32#654&#"#>54&#"GzY<KcgbLhpoLL2;+VPEAM/;0YOD?<~2{1(KG+S{P0GD0[R    G    P@
 BK"PX@  S  CD@   C S CDY@    &$!+332>32#>54&#"GyY<Qmq}LL=A0c\O:<Ć*{%RO4_S    7  # NK	PX@ S C  SD@ S C  SDY@ ##	 +%2>54&#"".54>32IxT.nhJwT.mYSd8PnSd8P}P_O_9ldb9lcc     + @ BK	PX@ S  C S CDK"PX@ S  C S CD@!   CS C S CDYY@  #!++  (&!+32>32#"&'"32>54&Y<&Zcl8"?YmFK|*60c\O &k74\L<)VM<BkL)R_6;7E<lW7-,Kes{<w|     0  0 b@%
	 BK	PX@ S CS C    D@ S CS C    DY@ )&0 0*, +#"&54>5#".54>322>7.#"p ;#PZb4<bE&-StZA{<0]TH-+<pbP9 %;^C$/[VZ]3<jWc'FatE  G    ,@)
 B  S  CD    #*!+332>32&#"GzY AY** /,a38*     
  9 9@69B   h f S C S D/#%/#"+#".#"#"&'7>3232>54.54>32!/D0-J6>^m^>7gZa/, 0I81O7>^l^>3`V[2S,;!/8)&:ZHFa:E6D#2C&3<(#7XI@w\7=4   _> 0 b+BK2PX@# j   h  Q C S D@! j   h   \ S DY@	%#(+&+74>7#"&54>?>;!!32>32#"&?qK^,
=/)(	%0}?ap$:/9)231	U+1j   ` # L BK"PX@C   TD@C C   T DY@   # #*!&+32>73#"&54>57#"&5467bL=B.a[N?zX"Qjq}L|$RP2\P"("Q*  K    @ B  C D, +32>7>;#K:t%J$$I&    Q   .  @' B  CD*!,< +32>7>;2>7>;#"'.'+Q]Jq
 W{
t#A  A#p#B! C#"! R"     @  B  CD(")!+32>7>;	#"&'+h

!/+   Q  @ BC    D,"!++32>7>;<)	@)*+       Y  @ Q C   Q D+!!7>7!7!P6	K#&J#ߌ    1Y E 7@4& :B  [    [ O S G=;303++4&#72654.54>;+";2#".54>85JI-YV1	
'B/"3;5@#C=
2EfC" & 4Bhw|575ai7MEoQ;?<MgA![?<rsu?FU%(Gb:Bxsq  5  @   Q D+3#   G 7@4<( B   [    [ O S G?=525++3"+7>;2>5<&454>7.54>54&+"&54>573285JI-YV1	
'B/"3;5@#C=
2EfC" & 4Bhw|575ai7M
	EoQ<?;LhA![?<rsu?FU%(Gb:Bxsq     9   9@6 j k  O  [  S  G 
 +2673#".#"#4>32AI%Ef@4f_V$AI%EeA4f_VeUFCpP, '!TGCpP-!'!      ! &@# S C   QD    +>734>32#".C
hB."--""--"-UW\45\VU-."".-""-  & / 8 @ % BK	PX@.  j h f k  S   C S D@.  j h f k  S   C S DY@
##'#+.54>?>;#".'>32+R`4Mф"@-R}04+=*@[?*	'!S`i6!@tjZ]0
	Dq`~מ\?1<	"<#6& Dv      > ?@<+B h  [ S C S D&&%#%&"	+#!>3!#!7>7#7>;>32#"&'.#"!zY	60<	;#9+$q!PmT{X9K#2H4AkQ3  Kj*Ip
/C..F	^zF&B[5,

0$+OpEF     +` # 7 ?@< !B @ ?  W  S   D42*((+467'7>327'#"&''7.732>54.#"![,h:9f+Y"![,h99e,Z!#>Q//S=$$=S//Q>#9e,Z"![,g:9f+\!![,g:.Q=$$=Q./R>##>R   ~   " 8@5
 B 
 Z	YC D"! ,!+!32>7>;!!!!#!7!7!6ʐ
	_"6V''Vp'!:; =cicAci  5   @    Y Q D+3#3#     ; F V A@>FTL; !B   h f  W S DDB+)&$#!+#".#"#"&'7>3232>54.5467.54>32>54.'R!/B0/K6DfvfDY_%-6f^a00	!0I:2O7)BUYUB)ag%.3aW[/:Zn3:26Ug1E9.>".A88JdH[)!U9J`7D6B"3E))<0(*0?R8Y'"X>AvZ5>6/B82V51D70#P   ^  ' @  S D((($+#".54>32#".54>32? )(() g))))((**((**   ] + G a @
 BK	PX@5   h
  f  [  [ 		S C S D@5   h
  f  [  [ 		S C S DY@ \ZPNB@42(& +++2#".54>32#".#"32>%4>32#".732>54.#";		<9tbs?Dzbm9.2M:GpP**Kg>?V9!.4`ee_44_ed`4e,QsXXsR-cXsQ,@BIDzdeyCC8A-TxKMyR+e`44`ed`44`eYtS--StYe.Sv  ? - 9 L@I! B h  [	  W S D/. 32.9/9%#
 --
+"&/#"&54>?6454&#"#"&/>32'26?.04AR%Vj(0"0$6xD,D//.G$B\9*H	1 ED(K;&&.6
(2.4G(P&#m*"      % %(+774
o ;]4
o ;
 
   >  =K	PX@ _   M   Q  E@ k   M   Q  EY+!#![4$9^    a<  @   M   Q  E+!!s8    ^  3 I V >BK	PX@/h  		[ 
[  S   C S D@/h  		[ 
[  S   C S DY@44VTLJ4I4H)!*,,&+4>32#".732>54.#"#!2#"'.#'32>54.+^4`ee`44`ee`4e,RrXXsR-c焄b kj!	Ps8M/+F4e`44`ed`44`eYtS--StYee|}z^
.r(:&%8$    pA  @   M   Q  E+!!~Aq    '  ' @  W  S   D((($+4>32#".732>54.#"3XvDEwX22XwEDvX3}6I**I66I**I6hCvW22WvCBuW33WuA*I66I**J77J    3 PK   <@9 j h  Z M Q E    	+!!#!7!!!/e--j/Dr{$   d - 9@6+	B h   [ S D (&#!
 --+26;2!7>?>54&#"#"&/>`m0?"2*6(6**A!CddS,HA<*89:-0+2ji    |d : S@P6B h h   [  [ S D 31.,('&% ::	+2#".'763232>54&#7>54&#"#"&/>.K5980Nd48Q7"	:+!"5%FV[S5,2=@5HWd->$-E7<]?!1G/!%011Y=>,-.+4P4  	 @   kD   	 #++7>3f"   % 2@/  BC   TC D   % %'%!&+32673#"&=#"&'#"&5<7\SVQF=]|gFPA^#U %Y
RYJBlHC/+$H      k7  *@'   hi  S D    +##!#".54>3ܵ붝j]i9Hq77]2Z~MZtC       @   O   S  G($+4>32#".)67((76)Q8((86))6   w 
  KPX@  B@ BYK	PX@   ^  T DKPX@  j  T D@  j  j T DYY@  +232654&'73#"&'76E(+GB:k JC!;Q0&B	(#	R?.$9'5   z^  N
BK2PX@ j  j  Q  D@ j  j  M  R  FY$+37#"&/733!6
y hNyu,\		6]     <  ! )@& W  S  D !!	 +2#".54>2654&#":]A"0UxH;^A#0Wy
ZYA?2E+@%Ea<R]2%Eb<Q]2uKU&C^8KT   w   % %(+'&54767&'&54?'&54767&'&54?5	p!;5	p!;{ |{       k   + 1 V@S%/  B h h
  Z  \	CD10+*)('&$##!#+3+#7!"&/3+>;37#"&/733!>73nUjw/F1!Gu6
y hNyuI>] [,\		6],     \ 	 7 H b@_B;5 B h h
 Z [	C  T   D
HGFEDC?=9820,*
77#"+%+>;26;2!7>?>54&#"#"&/>%37#"&/733!/F1!G`m3C$2*6(6*/=	+6
y hNyu5 [IdS-LC>!8*89:-04)ji<,\		6]     z   T Z ~@{P"/
	X  B h 	
	
h 

h  	[ 
  
[  \ SCDZYMKGEA@?>8631+)TT##!#+3+#7!"&/3+>;%2#".'763232>54&#7>54&#"#"&/>>73nUjw/F1!Gu.K5980Nd48Q7"	:46"5%FV[S5,2@15HWI>] [->$-E7<]?!1G/,2%011Y=>,-0%	4P4c,  u ' ; 5@2 B h f S C  S    D(&#,$+#".54>?332>324>32#".u!LWb8DoQ,/IWN:	$u	1HSF/-;!7S<'!-."".-!4''HgAQsS<56$-B:8CV;)?+$."".-""-    & $   	O    & $   _    & $   O    & $   O    & $   
O    -& $   P        9@6A  Y  Y  Q   C SD#	+!!!!!!!+!L *:&$@   d J KPX@9= H B@9= HBYK	PX@0 h f S C S C	  S DKPX@0 h f S C S C	  S D@7 h f	  h S C S C S DYY@ FD<;64/-%#  JJ
+232654&'7.546$32#".#"32>32#"&'76(+GB0r~BtL|fS$@(EmWtʔU:gUBfN7)	AWߒJC!;Q0&B	(#	vdڀ6{2F+N
(/(]o{B ' Q^o:?.$9'5    a  A& (   	$   a  A& (   $   a  A& (   $   a  A& (   
$   V  
& ,   	      & ,       g  & ,         & ,   
     E    ! ,@)  Y S C S D!%(!+3!2#!#%4.#!!!!2>SPԕOpQ{7f]>\?2xŎN	Z㈷vlyAn[   a  E& 1      d& 2   	   d& 2      d& 2      d& 2      d& 2   
    l 9W  	(+		'	7	9|8fnPg0]d]e[]Z     0 % 1 = g@5*)#
 BK PX@  k C S C  S    D@ j  k S C  S    DY**'(%&+#"&'+.546$327>;.#"%4&'32>4_kaCm=JMRrhEY`EJ+)2OvƎP$"<0wHxƎO2zڹh82/	T錷3|;6pTa<.1_*X;&'^  $& 8   	   $& 8      $& 8      $& 8   
   y  & <  < 	++        ,@)   \  [ C D"( +32+#332>54&#rn6J΅!3JUX.6cUqLa4]Lt    3& P }@JGBAK,PX@( h  S  C S C Q D@% h  W  S  C S DY@ LKFD=;%#  PP+2#"&'7>3232>54.54>54.#"+'&573>Y~Q&/FQF/+@K@+>iOY10	"-@0*G3.DQD.1JWJ1-I4>mU:
l.KFn(^6Se/D`H638&#/)+=XAV_3E6B"6I*0?.(4H8>XE:@P8;0CtUKW!M\K    0& D    Ci   0& D    v+   0& D    "   0& D    "   0& D    j"   0& D    6     G U bG@E?"BK	PX@5 h h
[ S	  CSDKPX@5 h h
[ S	  CSDK,PX@? h h
[ S	  C SC SD@J h h
[ S	  C  S	  C SC SDYYY@&WV \[VbWbQOIHCA<:75/.(& 
	 GG+232>32#"&'#"&54>7>54#"#"&/>32>32>7">54&]<fK*7zl1K;-&,3afo@i' Ydj1@<U?0Whlz<xg-NA4]K4	<bI2c(K%BY39lU7

#74L1rr>W8wxGc>(!)!7QP`UT^%<Q2HE%JoJ-TvH$3@$9D    <b I KPX@6< G B@6< GBYK	PX@0 h f S C S C	  S DKPX@0 h f S C S C	  S D@7 h f	  h S C S C S DYY@ EC;:42-+#! II
+232654&'7.54>32#".#"32>32#"&'76(+GB2JqL'Mrd38+A3E{\58Q6-F6)!,/TTW1JC!;Q0&B	(#	y
CkT{hGDC
Kf>eG'!63H-<?.$9'5 ;q& H    C    ;& H    v    ;q& H        ;& H    j    =  &     C    _  u&     v    "  ^&         /  w&     j     < 1 E 6@37-B10@  [ S    D32=;2E3E+)!+.54?.'&54?7#".54>32.'2>7.#")`7%XFqQ^FȂRe8E}ia0LL!AoX>	&<U9KwR+"=S)		^%7@3|9	STk9k_lU[\E3lv,Q?&<iQCjI'   G  & Q     ++   7& R   C   ++   7& R   v   ++   7& R      ++   7& R      ++   7& R   j   ++    s A~   ' +@(   [    Y O S G(&(%+!!4>32#"&4>32#"&B&2'&21;X&2'&20<2&(1$>f2&(1$>     %  ) 4 @32#" BK	PX@! C S C S  C DKPX@! C S C S  C DKPX@!  k C S C S   D@! j  k S C S   DYYY@+* *4+4&$ +"'+7.54>327>;&#"2>54&'|Z$:C(+Pn}["  Z'+P8NJzY1I{Y1F7=15Xb@.5WcYBZ-LsMg,K ,  `& X   C   ++   `& X   v   ++   `& X      ++   `& X   j   ++   Q& \   v   ++    %  , p@ BK	PX@!   CS C S CD@!   CS C S CDY@  $",,  (%+3>32#"&'#"32>54&%ݰY&X`h6"?YmFK{+.' 0b\O!&k74\L<)V4=eF'R_6;6&<jW6,,Kes{<w| Q& \   j   ++    ' 0 KPX@
- B@
-BYKPX@!  Z CC	  S D@(	  h  Z CC S DY@ )($" ''
+2#"&5467#"&'!+3#32>!.'Y0LRVBN	%_-&( @F:?n)^g!*3 '	QB&&C     0 4 F(KPX@&; BK"PX@&;B@&;BYYK	PX@# S C	SC  S DKPX@# S C	SC  S DK"PX@*  h S C	SC S D@.  h S C C	S C S DYYY@65 ?<5F6F1/('$" 44
+2#"&54>7.57#".54>32#32>2>7.#">Y0LR*:"$S]f7<bE&-StZA{<y-&( C1^TI++<pbP9 @F: =81@hI(/[VZ]3,!*3 '	\=lY\'FatE   d & &      <o& F   v   ++    aA % KPX B	BYKPX@*  Y Q C QC	
  S D@1
 	 	h  Y Q C QC 		S DY@ "  %%+2#"&5467!!!!!!#32>GY0LRVB/<=ui-&( @F:?n)!*3 '	   ;q A P KPX@G2 B@G2BYK	PX@* h	S C S C  S DKPX@* h	S C S C  S D@1 h  h	S C S C S DYY@CB BPCP><0.)' AA
+2#"&5467.54>3232>3232>">54.IY0LRI9U_2!?[uQMpH#6uv0K;-& ,MT+$( ?jR:d #8@F::f(<j]NxW2,DR%BoYB#7P]!)2 '	Y4[{G19B$'   _    @C    D    +#zz         !@
  B C   R D+%!!76?3m=7EY&}-`W   L  b  @ B   C D+4?37#LNF\TDJf!IE    a  E& 1      G  & Q   v  ++    d  2'@
 BKPX@"  Y  S
C	SDKPX@-  Y S
C   S
C	SDK PX@*  Y S C   Q
C	SDK"PX@4  Y S C   Q
C SC 		SD@2  Y S C   Q
C Q C 		S DYYYY@  /-%#  (#+!!!!!7#".54>324.#"32>;=qZuFhKkS h/ZSmI0[SmHr~\ㇹ6~&Ge?j|Dck|Cb  . 4 F U @L2"BK	PX@$ h S	  C
SD@$ h S	  C
SDY@ HG65 GUHU><5F6F0.&$  44+232>32#"&'#".54>32>2>54&#"">54.AhJ'8\~ym0K;-&,2afp@i'E΁QzQ)Ukk#?IQ}U+]aN|X/.JH;fP8h&'="?X5)LC;0&#74L1tsny;eHXe[ZfvNqsLy/VB(.YQ3:A!*!   & 6       
#& V   v ++ & 6       
,& V   ~ ++ y  & <  
< 	++    & =   8     Y& ]   v   ++     & =   8     Y& ]      ++     & =   8     Y& ]      ++    i ' 6@3BY S C  S    D   ' '#"+#763>7'.546767376$3#"!2:.UH8*0 /UI9+G!˹[7:^E	ſ_;^E}   Q  @ B  k D, +#"&/.'+3rdw	   q  @ B  k   D( +32?>;#qxds    pA q       @   WD 	 +".5467332>73r>V6y4B'6#z&Eg!:M-3?)9!6aI+     @   S  D($+#".54>32#.-""-.#:-""-/##/   kJ   =KPX@  W  S   D@    [ O S GY$&($+4>32#".732654&#" 7H()I8  8I)(H7 d6/-77-/6#*D22D*)D00D),88,-88  /t   YKPX@ B @@B @YKPX@  S D@  j S DY@  +2#"&54>732>RY0LR.@%W-&( @F:"@:2!*3 '	   h  QK*PX@  W SD@  O [  S GY@ 	 +273#".#"#>32Ai!2B% 5-) (j"3A%!4-()X/M7#-,.N8#   ) 	  #@   S D

  

 	 #++7>3!+7>3H" S     ! YBK(PX@  SC SD@  SC C S DY@   !  6##++#!#"&'7>3267#7>3"|lkOz=<;ND#u}wH	?C?
      @   M   Q  E+!!}    o  @   M   Q  E+!!7}       (+.5467j^/	!
%J%dL	09@"6       (+'&5467>54&'&547pj^0	!
%J%dL	08@#6       (+7'&5467>54&'&547j^0	!
%J%dL	08@#6       1  (+.5467.5467j^/	!
j^/	!
%J%dL	09@"6*%J%dL	09@"6     1  (+'&5467>54&'&547%'&5467>54&'&547yj^0	!
j^0	!
%J%dL	08@#6*%J%dL	08@#6       1  (+7'&5467>54&'&547%'&5467>54&'&547j^0	!
j^0	!
%J%dL	08@#6*%J%dL	08@#6    % ,@)  B C S  C D$&$"+>3632>32!#"&'!,*?G#)33#P$KIF &!6H0+u6/,
	)D   B 9 E@B  )!("B[ C	 S  C D98'%#&$"
+>3632>32!!#.'#"&'#"&5<>7!!,*?G#)33#P$KIF &"Pj.*?G!0+O$KIG&!kP/,
	'(v://
(        ,KPX@  S   D@   O   S  GY($+4>32#".:eLMe;;eMLe:SMe;;eMMd;;d  -,   ' ; @  SD((((($+74>32#".%4>32#".%4>32#".-"--""--""--""--"!..""..!n."".-""-."".-""-."".-""-     Z  ' 1 E Y m  KPX@+    [	[ SC		S
DK PX@/    [	[ SC C		S
D@3    [	[ C S C C		S
DYY@~|trjh`^VT((%#&((($+#".54>324.#"32>>;+#".54>324.#"32>%#".54>324.#"32>;`{A8^C%6]}F8^C&$1(G4$1'G5w|
~:`|A8]C%6]}F8]D%$1(G5$1'G6):`{A8^C%6]}F8]D%$1(F5#1'F6xcj7)MoFck8)NpH2H."JsQ1E-!GqUci7)MnFcl8)NpH2G."JrQ1F-!HrRci7)MnFcl8)NpH2G."JrQ1F-!Hr     (+74
o ;
     w   (+'&54767&'&54?5	p!;{     c 	 @ C    D#"+'+>;?/F1!G5 [  * B [@X	4	B   h 		h  [	[ S C 
S 


DBA?>=<861/"##%%$+3>32#".#"!#!!#!32>32#".'#7367#T!wp;C&6J3MoT0dRoI.ASގqv>̎LcWB 4f`7#H&6-6-DeqRҀcJG     I6  % B@?B h S	  C S	  D%%!4(
+>7>;#7+"'#32'###7	fGk.
}.iGg<x;P3rGRHNee      A = /@,! B   S CSD   = <,**+!>54.#"!"&546767!7.54>32!5Ti<5aReH*Lj@4/LxR,0X|`zȎNAwf~
(JxpZ_0BzMyY:O%TvTatQ+Lprěla     A 3 H B@?  "B h  [  S   CS D54?=4H5H#*++$+>32#".5467>32>7>54&#"#"&'2>7.#"'JMT0ItQ,n݉HwT._g^"	e\'C7):qdU .I5K{\:]9*8lc?!/X~P#sʔVRQ"=97or-S@'>mWgp         @	B C  R    D+)3!.'ԩ9 !9       $@!  QCD    +##!##7Ȳɱȼ]]   $@!B  Q   C Q D+!!!!7>7	&5<7RA!;4;A   ^  @   M   Q  E+!![    L  l  "@ B j   [    D,'!+!##"&5<>7!2>7>;p"Ne[n [ A 7Q    =  ' ; O L@IK-B[
	  O
	 S  G=<)( GE<O=O31(;);	 ''+%".'#".54>32>32%2>7.#"!2>54.#"{3P?1DNX35[C'7\xB3O@2DMX35\D'7]y!<86$,4!&A1$1S%B1$1!;86%+4!8K))K8!(KhARi=!9K))K9!(KiARi<5E''E4!<T4&:&!<T4'9&4E''E5  { ! (@% B  S   C S D6'%"+>32#"#"&'7>32>7)#A*\nOg}F D
6Q=,CWnuf_-L:^B      7 ^@[ 0!/"B  [   [	O  [	S G 42+)&$77
 
+2>7#".#"'>322>7#".#"'>32@80%(u=4c_\-90%
)wB4d^\81%
'v=4c_\-81%
)wB5c_[Wl0."("i31!)!m/-!(!h31!)!    }  kKPX@)   ^ _ 	 ZMQE@'  j k 	 ZMQEY@
+!733!!!#7!7!7!}w5}PwSʃ   Z P    @	 @   M   Q  E+!!3-2/*>yz
z{
   i P   @@   M  Q   E+%!7!7>7%>7.'%.54657n>2/aPz
z        "@
  B   M   Q  E+3	#>7	&'|y|	
54&&EF,#&     ~  -KPX@ k    D@
   jaY@	    +3v0     > ' s@
 BK2PX@( S C QC   C QD@  M W S C    DY@   ' 'W%#+#!+'&5737>32#"&#"yk}f.KFc(Izk''#SzU1	`KX#O8]n=Z$HnK5  > ! @	BK	PX@( SCQC C   Q DK&PX@( SCQC C   Q DK2PX@, C S CQC C   Q D@$M   W C S C DYYY@   ! !#!%#	++'&5737>32;#.#"3wg.KFb(
BnaG5w-_+uaKX!Q7TpAZ$
7   G2  5K0PX@ Q    D@  M Q   EY@	    +#2~mQR     U
	 	 @  j a  		+2#"&/      ' @  O S  G((($+#".54>32#".54>32P%##%X$$$$$$%%$$%%     (  @   M   Q  E+!!4f   
  @ j   a    
#++7>3
	    f
  @ B  j  a& +#"&/+73ǃr	
kk    
  @ B j   a    !+#'327>3r	kk       (@%j   O  S  G 
 +"&547332673syoNOp,Ie^^c><4T<     *  @   O  S   G($+#".54>32"-,!!,-",!!,,"",  V-   !@    [ O S G$&($+4>32#".732654&#"4D&'E44E'&D4Y6/-77-/6{'B//B'&@..@&+99+-88    1@.  O [  S G 
 +2673#".#"#>32)^.>% 82.'a.>%!82-|*%*G5 -%*H5     
b 	  +@(  O S  G

  

 	 #++7>3!+7>3(S'])  }  @  k   D 
 +2++$<]

9^ID      {_< 	    ʓ^p    ӡ-  	          V  O             ' -          {   6 G Z 9 ( z(  s 2 a - O  / ] - D h  R  - .+  + }  M a di a+ a aE dp a6 1 r a ao a dh r d r ? {?  |Z  y| ( ! l( 8 M 0 Ob < 5 ;] ?$ O _g N X G G 7  0 G
 
 _ ` K Q QZ ( 1X ( 9  {     ~X  ;8 ^= ]x k   a= ^8 p  3  8 ; k# 8   k w    d+ a+ a+ a+ a6 V6 6 g6  Eo a d d d d d l 0? ? ? ?  yh I 3 0 0 0 0 0 0 b < ; ; ; ; = _ " / < G 7 7 7 7 7 s  ` ` ` ` Q % Q 0 db <+ a ; _ Y Lo a G d . 
 
 
 
 y| Z | Z | Z  8 Q8 q8 p8 88 8 /8 h8 x       , , B  -O ZV V wA */ ] + AY  x L ={  + Z+ i    >G >8 G8 U8 8 88 f8 8 8*8 8 8 8     g P`    	U        U  $U  9 6  : 0  < -  ? 6  D  F  G  H  R  T  m  o  y  }  U  U  U  U  U  U  U   -                                        U           -                  U 
 	U 
  
  
  
 U 
 $U 
 9 6 
 : 0 
 < - 
 ? 6 
 D 
 F 
 G 
 H 
 R 
 T 
 m 
 o 
 y 
 } 
 U 
 U 
 U 
 U 
 U 
 U 
 U 
  - 
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
 U 
  
  
  
  
  - 
  
  
  
  
  
  
  
  
 U  #  &  *  2  4  D  F  G  H  R  T  k  p                                                                  	U        U  $U  9 6  : 0  < -  ? 6  D  F  G  H  R  T  m  o  y  }  U  U  U  U  U  U  U   -                                        U           -                  U    
    ;  #  &  *  2  4  75  9,  :|  <;  ?,  Yr  Z  \|  k  l  m;  o;  p  r  y;  |  };                ;  r  r      ;  ;  ;          ;  ;  ;    	  
    ^  ^    $  7A  9  ;  <@  =  ?  l  r  |                @    @            ^      ^  ^      
    ;  #  &  *  2  4  75  9,  :|  <;  ?,  Yr  Z  \|  k  l  m;  o;  p  r  y;  |  };                ;  r  r      ;  ;  ;          ;  ;  ;   6  	  
 6   6  A    A        " :  #  $  &  *  -i  2  4  D  F  G  H  P  Q  R  S  T  U  V  X  Y  Z  \  ]  k  l 6  m  o  p  r 6  t P  u P  w  y  { P  | 6  }                                                                                                                 6   6  A   6   6  A    A       #  # 	 # 
 #  #  #  # $ # 7 # 9 # ; # < # = # ? # @ # ` # l # r # | #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  $ J $ 
J $ J $  $ # $ & $ * $ - > $ 2 $ 4 $ 7| $ 8 $ 9 $ : $ <h $ ? $ W $ Y $ Z $ \ $ k $ lJ $ m $ o $ p $ rJ $ tI $ uI $ y $ {I $ |J $ } $  $  $  $  $  $  $  $  $  $  $  $ h $  $  $  $  $ h $  $  $ J $ J $ J $ J $  $  $  &  & m & o & y & } &  &  &  &  &  '  ' 	 ' 
 '  '  '  ' $ ' 7 ' 9 ' ; ' < ' = ' ? ' @ ' ` ' l ' r ' | '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  '  ) 	| ) L ) L ) | )  )  ) "  ) $| ) -: ) D ) F ) G ) H ) P ) Q ) R ) S ) T ) U ) X ) w ) | ) | ) | ) | ) | ) | ) | )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  )  ) | )  )  )  )  )  ) L ) L ) L ) | - 	 -  - $ -  -  -  -  -  -  -  -  -  .   . 
  .   .  . # . & . * . 2 . 4 . I . W . Y . Z . \ . k . l  . m . o . p . r  . y . |  . } .  .  .  .  .  .  .  .  .  .  .  .  .  .   .   .   .   .  .  .  /  / 
 /  / ; / # / & / * / 2 / 4 / 78 / 9J / :h / <, / ?J / Y| / Z / \| / k / l / m; / o; / p / r / t, / u, / y; / {, / | / }; /  /  /  /  /  /  /  / , / | / | /  /  / , / ; / ; /  /  /  /  / ; / ; / ; 2  2 	 2 
 2  2  2  2 $ 2 7 2 9 2 ; 2 < 2 = 2 ? 2 @ 2 ` 2 l 2 r 2 | 2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  3 	v 3 C 3 C 3 v 3 $v 3 -J 3 D 3 F 3 G 3 H 3 R 3 T 3 v 3 v 3 v 3 v 3 v 3 v 3 v 3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3 v 3  3  3  3  3 C 3 C 3 C 3 v 4  4 	 4 
 4  4  4  4 $ 4 7 4 9 4 ; 4 < 4 = 4 ? 4 @ 4 ` 4 l 4 r 4 | 4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  5 # 5 & 5 * 5 2 5 4 5 7 5 8 5 k 5 p 5  5  5  5  5  5  5  5  5  5  5  5  5  7 	| 7 L 7 L 7 L 7 | 7 f 7 f 7 " ' 7 # 7 $| 7 & 7 * 7 -8 7 2 7 4 7 D/ 7 F/ 7 G/ 7 H/ 7 JE 7 Pf 7 Qf 7 R/ 7 Sf 7 T/ 7 Uf 7 VJ 7 Xf 7 YW 7 Z 7 [Z 7 \L 7 ]_ 7 k 7 mL 7 oL 7 p 7 wf 7 yL 7 }L 7 | 7 | 7 | 7 | 7 | 7 | 7 | 7  7  7  7  7  7  7  7 / 7 / 7 / 7 / 7 / 7 / 7 / 7 / 7 / 7 / 7 / 7 / 7 / 7 f 7 / 7 / 7 / 7 / 7 / 7 / 7 f 7 f 7 f 7 f 7 W 7 W 7 | 7 / 7  7 / 7 / 7 f 7  7 / 7 J 7 J 7 _ 7 _ 7 _ 7 L 7 L 7 L 7 L 7 L 7 L 7 L 7 L 7 | 8 	 8  8 $ 8  8  8  8  8  8  8  8  8  9  6 9 	 9 
 6 9  6 9 A 9  9 A 9  9  9  9 " : 9 # 9 $ 9 & 9 * 9 -i 9 2 9 4 9 D 9 F 9 G 9 H 9 P 9 Q 9 R 9 S 9 T 9 U 9 V 9 X 9 Y 9 Z 9 \ 9 ] 9 k 9 l 6 9 m 9 o 9 p 9 r 6 9 t P 9 u P 9 w 9 y 9 { P 9 | 6 9 } 9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  9  6 9  6 9 A 9  6 9  6 9 A 9  9 A 9  9  9  :  : : 	 : 
 : :  : :  :  :  :  :  : $ : - : D : F : G : H : J : P : Q : R : S : T : U : V : X : l : : r : : t < : u < : w : { < : | : :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  :  : :  : :  :  : :  : :  :  :  ;   ; 
  ;   ;  ; # ; & ; * ; 2 ; 4 ; I ; W ; Y ; Z ; \ ; k ; l  ; m ; o ; p ; r  ; y ; |  ; } ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;  ;   ;   ;   ;   ;  ;  ;  <  7 < 	r < 
 7 <  7 < ' < J < ' < r <  <  < " 2 < # < $r < & < * < -8 < 2 < 4 < DA < FA < GA < HA < JW < P < Q < RA < S < TA < U < VA < X < ] < k < l 7 < mJ < oJ < p < r 7 < t > < u > < w < yJ < { > < | 7 < }J < r < r < r < r < r < r < r <  <  <  <  <  <  <  < A < A < A < A < A < A < A < A < A < A < A < A < A <  < A < A < A < A < A < A <  <  <  <  < r < A <  < A < A <  <  < A < A < A <  <  <  < J < J <  7 <  7 < ' <  7 <  7 < ' < J < ' < J < J < r =  = " # = # = & = * = 2 = 4 = k = m = o = p = y = } =  =  =  =  =  =  =  =  =  =  =  =  =  =  > # > & > * > 2 > 4 > D > F > G > H > R > T > k > p >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  ? J ? 
J ? J ?  ? # ? & ? * ? - > ? 2 ? 4 ? 7| ? 8 ? 9 ? : ? <h ? ? ? W ? Y ? Z ? \ ? k ? lJ ? m ? o ? p ? rJ ? tI ? uI ? y ? {I ? |J ? } ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ?  ? h ?  ?  ?  ?  ? h ?  ?  ? J ? J ? J ? J ?  ?  ?  E  E 
 E  E  E @ E [ E ` E l E r E | E  E  E  E  H  H 
 H  H  H @ H [ H ` H l H r H | H  H  H  H  I  E I 
 E I  E I  I  I l E I r E I t d I u d I { d I | E I  E I  E I  I  E I  E I  I  K  K 
 K  K Y K \ K l K r K t K u K { K | K  K  K  K  K  K  N D N F N G N H N R N T N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  N  P  P 
 P  P Y P \ P l P r P t P u P { P | P  P  P  P  P  P  Q  Q 
 Q  Q Y Q \ Q l Q r Q t Q u Q { Q | Q  Q  Q  Q  Q  Q  R  R 
 R  R  R @ R [ R ` R l R r R | R  R  R  R  S  S 
 S  S  S @ S [ S ` S l S r S | S  S  S  S  U h U h U D U F U G U H U R U T U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U  U h U h U h Y 	 Y r Y r Y  Y $ Y D Y F Y G Y H Y R Y T Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y  Y r Y r Y r Y  Z 	 Z  Z  Z  Z $ Z  Z  Z  Z  Z  Z  Z  Z  Z  Z  Z  Z  [ D [ F [ G [ H [ R [ T [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  [  \ 	 \ h \ h \  \ $ \ D \ F \ G \ H \ R \ T \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \  \ h \ h \ h \  ^ # ^ & ^ * ^ 2 ^ 4 ^ D ^ F ^ G ^ H ^ R ^ T ^ k ^ p ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  ^  k  k 	 k 
 k  k  k  k $ k 7 k 9 k ; k < k = k ? k @ k ` k l k r k | k  k  k  k  k  k  k  k  k  k  k  k  k  k  k  k  k  k  l 	U l  l  l  l U l $U l 9 6 l : 0 l < - l ? 6 l D l F l G l H l R l T l m l o l y l } l U l U l U l U l U l U l U l  - l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l  l U l  l  l  l  l  - l  l  l  l  l  l  l  l  l U m  m 	 m 
 m  m ^ m ^ m  m $ m 7A m 9 m ; m <@ m = m ? m l m r m | m  m  m  m  m  m  m  m @ m  m @ m  m  m  m  m  m ^ m  m  m ^ m ^ m  o  o 	 o 
 o  o ^ o ^ o  o $ o 7A o 9 o ; o <@ o = o ? o l o r o | o  o  o  o  o  o  o  o @ o  o @ o  o  o  o  o  o ^ o  o  o ^ o ^ o  p  p 	 p 
 p  p  p  p $ p 7 p 9 p ; p < p = p ? p @ p ` p l p r p | p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  p  r 	U r  r  r  r U r $U r 9 6 r : 0 r < - r ? 6 r D r F r G r H r R r T r m r o r y r } r U r U r U r U r U r U r U r  - r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r U r  r  r  r  r  - r  r  r  r  r  r  r  r  r U t 	T t T t $T t 9 : t : : t < ( t ? : t T t T t T t T t T t T t T t  ( t T t  ( t T u 	T u T u $T u 9 : u : : u < ( u ? : u T u T u T u T u T u T u T u  ( u T u  ( u T y  y 	 y 
 y  y ^ y ^ y  y $ y 7A y 9 y ; y <@ y = y ? y l y r y | y  y  y  y  y  y  y  y @ y  y @ y  y  y  y  y  y ^ y  y  y ^ y ^ y  { 	T { T { $T { 9 : { : : { < ( { ? : { T { T { T { T { T { T { T {  ( { T {  ( { T | 	U |  |  |  | U | $U | 9 6 | : 0 | < - | ? 6 | D | F | G | H | R | T | m | o | y | } | U | U | U | U | U | U | U |  - |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  | U |  |  |  |  |  - |  |  |  |  |  |  |  |  | U }  } 	 } 
 }  } ^ } ^ }  } $ } 7A } 9 } ; } <@ } = } ? } l } r } | }  }  }  }  }  }  }  } @ }  } @ }  }  }  }  }  } ^ }  }  } ^ } ^ }   J  
J  J    #  &  *  - >  2  4  7|  8  9  :  <h  ?  W  Y  Z  \  k  lJ  m  o  p  rJ  tI  uI  y  {I  |J  }                        h          h      J  J  J  J        J  
J  J    #  &  *  - >  2  4  7|  8  9  :  <h  ?  W  Y  Z  \  k  lJ  m  o  p  rJ  tI  uI  y  {I  |J  }                        h          h      J  J  J  J        J  
J  J    #  &  *  - >  2  4  7|  8  9  :  <h  ?  W  Y  Z  \  k  lJ  m  o  p  rJ  tI  uI  y  {I  |J  }                        h          h      J  J  J  J        J  
J  J    #  &  *  - >  2  4  7|  8  9  :  <h  ?  W  Y  Z  \  k  lJ  m  o  p  rJ  tI  uI  y  {I  |J  }                        h          h      J  J  J  J        J  
J  J    #  &  *  - >  2  4  7|  8  9  :  <h  ?  W  Y  Z  \  k  lJ  m  o  p  rJ  tI  uI  y  {I  |J  }                        h          h      J  J  J  J        J  
J  J    #  &  *  - >  2  4  7|  8  9  :  <h  ?  W  Y  Z  \  k  lJ  m  o  p  rJ  tI  uI  y  {I  |J  }                        h          h      J  J  J  J          m  o  y  }              	  
        $  7  9  ;  <  =  ?  @  `  l  r  |                                        	  
        $  7  9  ;  <  =  ?  @  `  l  r  |                                        	  
        $  7  9  ;  <  =  ?  @  `  l  r  |                                        	  
        $  7  9  ;  <  =  ?  @  `  l  r  |                                        	  
        $  7  9  ;  <  =  ?  @  `  l  r  |                                        	  
        $  7  9  ;  <  =  ?  @  `  l  r  |                                      	    $                    	    $                    	    $                    	    $                     7  	r  
 7   7  '  J  '  r      " 2  #  $r  &  *  -8  2  4  DA  FA  GA  HA  JW  P  Q  RA  S  TA  U  VA  X  ]  k  l 7  mJ  oJ  p  r 7  t >  u >  w  yJ  { >  | 7  }J  r  r  r  r  r  r  r                A  A  A  A  A  A  A  A  A  A  A  A  A    A  A  A  A  A  A          r  A    A  A      A  A  A        J  J   7   7  '   7   7  '  J  '  J  J  r    	  
        $  7  9  ;  <  =  ?  @  `  l  r  |                                        
      @  [  `  l  r  |            
      @  [  `  l  r  |            
      @  [  `  l  r  |            
      @  [  `  l  r  |            
      @  [  `  l  r  |            
    Y  \  l  r  t  u  {  |                
      @  [  `  l  r  |            
      @  [  `  l  r  |            
      @  [  `  l  r  |            
      @  [  `  l  r  |            
      @  [  `  l  r  |            
      @  [  `  l  r  |          	  r  r    $  D  F  G  H  R  T                                                                r  r  r      
      @  [  `  l  r  |          	  r  r    $  D  F  G  H  R  T                                                                r  r  r    J  
J  J    #  &  *  - >  2  4  7|  8  9  :  <h  ?  W  Y  Z  \  k  lJ  m  o  p  rJ  tI  uI  y  {I  |J  }                        h          h      J  J  J  J          m  o  y  }              
      @  [  `  l  r  |          i  
i  i    9^  :  <h  ?^  Y  Z  \  li  m  o  ri  t}  u}  y  {}  |i  }  h      h      i  i  i  i          
    Y  \  l  r  t  u  {  |                
      @  [  `  l  r  |           7  	r  
 7   7  '  J  '  r      " 2  #  $r  &  *  -8  2  4  DA  FA  GA  HA  JW  P  Q  RA  S  TA  U  VA  X  ]  k  l 7  mJ  oJ  p  r 7  t >  u >  w  yJ  { >  | 7  }J  r  r  r  r  r  r  r                A  A  A  A  A  A  A  A  A  A  A  A  A    A  A  A  A  A  A          r  A    A  A      A  A  A        J  J   7   7  '   7   7  '  J  '  J  J  r    " #  #  &  *  2  4  k  m  o  p  y  }                                " #  #  &  *  2  4  k  m  o  p  y  }                                " #  #  &  *  2  4  k  m  o  p  y  }                                	  
    ^  ^    $  7A  9  ;  <@  =  ?  l  r  |                @    @            ^      ^  ^      	  
    ^  ^    $  7A  9  ;  <@  =  ?  l  r  |                @    @            ^      ^  ^    	U        U  $U  9 6  : 0  < -  ? 6  D  F  G  H  R  T  m  o  y  }  U  U  U  U  U  U  U   -                                        U           -                  U  	U        U  $U  9 6  : 0  < -  ? 6  D  F  G  H  R  T  m  o  y  }  U  U  U  U  U  U  U   -                                        U           -                  U    
    ;  #  &  *  2  4  75  9,  :|  <;  ?,  Yr  Z  \|  k  l  m;  o;  p  r  y;  |  };                ;  r  r      ;  ;  ;          ;  ;  ;  	U        U  $U  9 6  : 0  < -  ? 6  D  F  G  H  R  T  m  o  y  }  U  U  U  U  U  U  U   -                                        U           -                  U  	U        U  $U  9 6  : 0  < -  ? 6  D  F  G  H  R  T  m  o  y  }  U  U  U  U  U  U  U   -                                        U           -                  U    
    ;  #  &  *  2  4  75  9,  :|  <;  ?,  Yr  Z  \|  k  l  m;  o;  p  r  y;  |  };                ;  r  r      ;  ;  ;          ;  ;  ;    	  
    ^  ^    $  7A  9  ;  <@  =  ?  l  r  |                @    @            ^      ^  ^      
    ;  #  &  *  2  4  75  9,  :|  <;  ?,  Yr  Z  \|  k  l  m;  o;  p  r  y;  |  };                ;  r  r      ;  ;  ;          ;  ;  ;    	  
    ^  ^    $  7A  9  ;  <@  =  ?  l  r  |                @    @            ^      ^  ^      	  
    ^  ^    $  7A  9  ;  <@  =  ?  l  r  |                @    @            ^      ^  ^    	U        U  $U  9 6  : 0  < -  ? 6  D  F  G  H  R  T  m  o  y  }  U  U  U  U  U  U  U   -                                        U           -                  U  J  
J  J    #  &  *  - >  2  4  7|  8  9  :  <h  ?  W  Y  Z  \  k  lJ  m  o  p  rJ  tI  uI  y  {I  |J  }                        h          h      J  J  J  J               Z,
Bz(ZtJBN		r	
.
^

z Pz2>|LrF(HxXd`(t(.lR@f|@@   !!l!"&"l#<##$,$F% %%b%&&&&'2'^'((Z()")**+ +++$+0+<+,n,z,,,,,,,--*-6-B-N-Z-f-. .,.8.D.P.b./R/^/j/v///0111111112
22222223L444*4<4N4`4456|667"788P8~889~:8:D:T:`:p:::::::;8;h;;;;<J<<=,====>>H>>?4?@@:@AAABBCCxDD0D\DDDEEFRFFG0GpGHHHI IJIdIIIJJ:JzJJK      b   " / n   	     n                                 )                (                0        +      	 C      
R       .       2F       x       :  	  T  	  h  	  p  	  R|  	    	  P  	    	  `4  	  0  	 	   	 
  	  0  	  d  	 .  	  4Copyright (c) 2010-2013 by tyPoland Lukasz Dziedzic with Reserved Font Name "Lato". Licensed under the SIL Open Font License, Version 1.1.LatoItalictyPolandLukaszDziedzic: Lato Italic: 2013Lato ItalicVersion 1.105; Western+Polish opensourceLato-ItalicLato is a trademark of tyPoland Lukasz Dziedzic.tyPoland Lukasz DziedzicLukasz DziedzicLato is a sanserif typeface family designed in the Summer 2010 by Warsaw-based designer Lukasz Dziedzic ("Lato" means "Summer" in Polish). It tries to carefully balance some potentially conflicting priorities: it should seem quite "transparent" when used in body text but would display some original traits when used in larger sizes. The classical proportions, particularly visible in the uppercase, give the letterforms familiar harmony and elegance. At the same time, its sleek sanserif look makes evident the fact that Lato was designed in 2010, even though it does not follow any current trend. The semi-rounded details of the letters give Lato a feeling of warmth, while the strong structure provides stability and seriousness.http://www.typoland.com/http://www.typoland.com/designers/Lukasz_Dziedzic/Copyright (c) 2010-2013 by tyPoland Lukasz Dziedzic (http://www.typoland.com/) with Reserved Font Name "Lato". Licensed under the SIL Open Font License, Version 1.1 (http://scripts.sil.org/OFL).http://scripts.sil.org/OFL C o p y r i g h t   ( c )   2 0 1 0 - 2 0 1 3   b y   t y P o l a n d   L u k a s z   D z i e d z i c   w i t h   R e s e r v e d   F o n t   N a m e   " L a t o " .   L i c e n s e d   u n d e r   t h e   S I L   O p e n   F o n t   L i c e n s e ,   V e r s i o n   1 . 1 . L a t o I t a l i c t y P o l a n d L u k a s z D z i e d z i c :   L a t o   I t a l i c :   2 0 1 3 L a t o - I t a l i c V e r s i o n   1 . 1 0 5 ;   W e s t e r n + P o l i s h   o p e n s o u r c e L a t o   i s   a   t r a d e m a r k   o f   t y P o l a n d   L u k a s z   D z i e d z i c . t y P o l a n d   L u k a s z   D z i e d z i c L u k a s z   D z i e d z i c L a t o   i s   a   s a n s e r i f   t y p e f a c e   f a m i l y   d e s i g n e d   i n   t h e   S u m m e r   2 0 1 0   b y   W a r s a w - b a s e d   d e s i g n e r   L u k a s z   D z i e d z i c   ( " L a t o "   m e a n s   " S u m m e r "   i n   P o l i s h ) .   I t   t r i e s   t o   c a r e f u l l y   b a l a n c e   s o m e   p o t e n t i a l l y   c o n f l i c t i n g   p r i o r i t i e s :   i t   s h o u l d   s e e m   q u i t e   " t r a n s p a r e n t "   w h e n   u s e d   i n   b o d y   t e x t   b u t   w o u l d   d i s p l a y   s o m e   o r i g i n a l   t r a i t s   w h e n   u s e d   i n   l a r g e r   s i z e s .   T h e   c l a s s i c a l   p r o p o r t i o n s ,   p a r t i c u l a r l y   v i s i b l e   i n   t h e   u p p e r c a s e ,   g i v e   t h e   l e t t e r f o r m s   f a m i l i a r   h a r m o n y   a n d   e l e g a n c e .   A t   t h e   s a m e   t i m e ,   i t s   s l e e k   s a n s e r i f   l o o k   m a k e s   e v i d e n t   t h e   f a c t   t h a t   L a t o   w a s   d e s i g n e d   i n   2 0 1 0 ,   e v e n   t h o u g h   i t   d o e s   n o t   f o l l o w   a n y   c u r r e n t   t r e n d .   T h e   s e m i - r o u n d e d   d e t a i l s   o f   t h e   l e t t e r s   g i v e   L a t o   a   f e e l i n g   o f   w a r m t h ,   w h i l e   t h e   s t r o n g   s t r u c t u r e   p r o v i d e s   s t a b i l i t y   a n d   s e r i o u s n e s s . h t t p : / / w w w . t y p o l a n d . c o m / h t t p : / / w w w . t y p o l a n d . c o m / d e s i g n e r s / L u k a s z _ D z i e d z i c / C o p y r i g h t   ( c )   2 0 1 0 - 2 0 1 3   b y   t y P o l a n d   L u k a s z   D z i e d z i c   ( h t t p : / / w w w . t y p o l a n d . c o m / )   w i t h   R e s e r v e d   F o n t   N a m e   " L a t o " .   L i c e n s e d   u n d e r   t h e   S I L   O p e n   F o n t   L i c e n s e ,   V e r s i o n   1 . 1   ( h t t p : / / s c r i p t s . s i l . o r g / O F L ) . h t t p : / / s c r i p t s . s i l . o r g / O F L     r t                              	 
                        ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ 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    j i k m l n  o q p r s u t v w  x z y { } |    ~       	
                                                     !"#NULLuni00A0uni00ADmacronperiodcenteredAogonekaogonekEogonekeogonekNacutenacuteSacutesacuteZacutezacute
Zdotaccent
zdotaccentuni02C9EuroDeltauni2669undercommaaccent
grave.casedieresis.casemacron.case
acute.casecircumflex.case
caron.case
breve.casedotaccent.case	ring.case
tilde.casehungarumlaut.case
caron.salt                             VV , `f-, d P&ZE[X!#!X PPX!@Y 8PX!8YY Ead(PX!E 0PX!0Y PX f a 
PX`  PX!
` 6PX!6``YYY +YY# PXeYY-, E %ad CPX#B#B!!Y`-,#!#! dbB #B*! C   +0%QX`PaRYX#Y! @SX +!@Y# PXeY-,C+  C`B-,#B#  #Bab`*-,  E EcEb`D`-,  E  +#%` E#a d  PX! 0PX @YY# PXeY%#aDD`-,EaD-	,`  	CJ PX 	#BY
CJ RX 
#BY-
,  b  c#aC` ` #B#-,KTXDY$e#x-,KQXKSXDY!Y$e#x-, CUXCaB
+Y C%B	%B
%B# %PX C`%B #a	*!#a #a	*! C`%B%a	*!Y	CG
CG`b EcEb`  #DC >C`B-, ETX #B `a  BB`+m+"Y-, +-,+-,+-,+-,+-,+-,+-,+-,+-,	+-,+ ETX #B `a  BB`+m+"Y-, +-,+-,+-,+-,+-,+- ,+-!,+-",+-#,	+-$, <`-%, `` C#`C%a`$*!-&,%+%*-',  G  EcEb`#a8# UX G  EcEb`#a8!Y-(, ETX '*0"Y-),+ ETX '*0"Y-*, 5`-+, EcEb +EcEb +      D>#8**-,, < G EcEb` Ca8--,.<-., < G EcEb` CaCc8-/, % . G #B%IG#G#a Xb!Y#B.*-0, %%G#G#aE+e.#  <8-1, %% .G#G#a #BE+ `PX @QX  &YBB# C #G#G#a#F`Cb`  + a C`d#CadPXCaC`Y%ba#  &#Fa8#CF%CG#G#a` Cb`#  +#C` +%a%b&a %`d#%`dPX!#!Y#  &#Fa8Y-2,    & .G#G#a#<8-3,  #B   F#G +#a8-4, %%G#G#a TX. <#!%%G#G#a %%G#G#a%%I%aEc# Xb!YcEb`#.#  <8#!Y-5,  C .G#G#a ` `fb#  <8-6,# .F%FRX <Y.&+-7,# .F%FPX <Y.&+-8,# .F%FRX <Y# .F%FPX <Y.&+-9,0+# .F%FRX <Y.&+-:,1+  <#B8# .F%FRX <Y.&+C.&+-;, %& .G#G#aE+# < .#8&+-<,%B %% .G#G#a #BE+ `PX @QX  &YBB# GCb`  + a C`d#CadPXCaC`Y%ba%Fa8# <#8!  F#G +#a8!Y&+-=,0+.&+->,1+!#  <#B#8&+C.&+-?,  G #B .,*-@,  G #B .,*-A, -*-B,/*-C, E# . F#a8&+-D,#BC+-E,  <+-F, <+-G, <+-H,<+-I,  =+-J, =+-K, =+-L,=+-M,  9+-N, 9+-O, 9+-P,9+-Q,  ;+-R, ;+-S, ;+-T,;+-U,  >+-V, >+-W, >+-X,>+-Y,  :+-Z, :+-[, :+-\,:+-],2+.&+-^,2+6+-_,2+7+-`, 2+8+-a,3+.&+-b,3+6+-c,3+7+-d,3+8+-e,4+.&+-f,4+6+-g,4+7+-h,4+8+-i,5+.&+-j,5+6+-k,5+7+-l,5+8+-m,+e$Px0-   K KRXY  c #D#pE  (`f UX%aEc#b#D***Y(	ERD*D$QX@XD&QX XDYYYY D          <%- if !svninfo.empty? then %>
<div id="file-svninfo-section" class="nav-section">
  <h3>VCS Info</h3>

  <div class="section-body">
    <dl class="svninfo">
      <dt>Rev
      <dd><%= svninfo[:rev] %>

      <dt>Last Checked In
      <dd><%= svninfo[:commitdate].strftime('%Y-%m-%d %H:%M:%S') %>
        (<%= svninfo[:commitdelta] %> ago)

      <dt>Checked in by
      <dd><%= svninfo[:committer] %>
    </dl>
  </div>
</div>
<%- end -%>
<%- 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 %>
<div class="nav-section">
  <h3>Table of Contents</h3>

  <ul class="link-list" role="directory">
<%-   table.each do |heading| -%>
    <li><a href="#<%= heading.label current %>"><%= heading.plain_html %></a>
<%-   end -%>
  </ul>
</div>
<%- end -%>
<div id="file-list-section" class="nav-section">
  <h3>Defined In</h3>

  <ul>
<%- klass.in_files.each do |tl| -%>
    <li><%= h tl.relative_name %>
<%- end -%>
  </ul>
</div>
<div id="search-section" role="search" class="project-section initially-hidden">
  <form action="#" method="get" accept-charset="utf-8">
    <div id="search-field-wrapper">
      <input id="search-field" role="combobox" aria-label="Search"
             aria-autocomplete="list" aria-controls="search-results"
             type="text" name="search" placeholder="Search" spellcheck="false"
             title="Type to search, Up and Down to navigate, Enter to load">
    </div>

    <ul id="search-results" aria-label="Search Results"
        aria-busy="false" aria-expanded="false"
        aria-atomic="false" class="initially-hidden"></ul>
  </form>
</div>
<%- unless klass.includes.empty? then %>
<div id="includes-section" class="nav-section">
  <h3>Included Modules</h3>

  <ul class="link-list">
  <%- klass.each_include do |inc| -%>
  <%- unless String === inc.module then -%>
    <li><a class="include" href="<%= klass.aref_to inc.module.path %>"><%= inc.module.full_name %></a>
  <%- else -%>
    <li><span class="include"><%= inc.name %></span>
  <%- end -%>
  <%- end -%>
  </ul>
</div>
<%- end -%>
<%- unless klass.extends.empty? then %>
<div id="extends-section" class="nav-section">
  <h3>Extended With Modules</h3>

  <ul class="link-list">
    <%- klass.each_extend do |ext| -%>
  <%- unless String === ext.module then -%>
    <li><a class="extend" href="<%= klass.aref_to ext.module.path %>"><%= ext.module.full_name %></a>
  <%- else -%>
    <li><span class="extend"><%= ext.name %></span>
  <%- end -%>
  <%- end -%>
  </ul>
</div>
<%- end -%>
<%- unless klass.sections.length == 1 then %>
<div id="sections-section" class="nav-section">
  <h3>Sections</h3>

  <ul class="link-list" role="directory">
    <%- klass.sort_sections.each do |section| -%>
      <li><a href="#<%= section.aref %>"><%= h section.title %></a></li>
    <%- end -%>
  </ul>
</div>
<%- end -%>
<body id="top" role="document" class="file">
<nav role="navigation">
  <div id="project-navigation">
    <%= render '_sidebar_navigation.rhtml' %>
    <%= render '_sidebar_search.rhtml' %>
  </div>

  <%= render '_sidebar_table_of_contents.rhtml' %>

  <div id="project-metadata">
    <%= render '_sidebar_pages.rhtml' %>
  </div>
</nav>

<main role="main" aria-label="Page <%=h file.full_name%>">
<%= file.description %>
</main>

<div id="home-section" role="region" title="Quick navigation" class="nav-section">
  <h2>
    <a href="<%= rel_prefix %>/index.html" rel="home">Home</a>
  </h2>

  <div id="table-of-contents-navigation">
    <a href="<%= rel_prefix %>/table_of_contents.html#pages">Pages</a>
    <a href="<%= rel_prefix %>/table_of_contents.html#classes">Classes</a>
    <a href="<%= rel_prefix %>/table_of_contents.html#methods">Methods</a>
  </div>
</div>
PNG

   IHDR         a   gAMA  7   tEXtSoftware Adobe ImageReadyqe<  IDAT8˝OSQ\^[تtz%l$***2:
iRp
c0ąKw&&`44(eKɽwwrOX\HiscUQz@;քIdTaˀ)jC'يKT8=ʯ9ނ^zΘ 1OFZ[W-Gz?&%*MGnN!aO>Nc[ɨX·0Nqg*1Sub|{g|fz)̾&\5\	0	3iD;`|0>A?Tx4^`oqs`>ʦ`fCv@mX[r\At.)G[Ì`N1)BWs+:NdsVa*DX.pB&B]H@T3@Pڏڠ	wVP63yp-4Ǽ$H'9{m@U$ZjCX:TgL::?[#{1P=.2F\iA-D77qXIפb4kaAj%
ͼj&Q˫H&s.
`jKLE3*ΫXw6_l=@hߊv,qq    IENDB`PNG

   IHDR         a   gAMA  7   tEXtSoftware Adobe ImageReadyqe<  IDAT8͓KQ&*z(	z24r!\e77V"x!bT7R*c<||:[WAD>9{Li'v%IID=z/;"\k޸)ku9x]2$W0=$QH>}F|`n6ϜϤkN7>9LL(,.}>ּ^OMM|%꿏:/T]F$6VW))t5FKòQq"rf y_Oa|	pHJ*MTX8[^Dr-||[v(33!.44Ǌebʡrטu͚d+@ S[Ko~TKrjkoraPDPy5@Y?i܅Sg@'˼Zj_M5̻w.;'5ڿ_    IENDB`PNG

   IHDR         a   gAMA  7   tEXtSoftware Adobe ImageReadyqe<  IDAT8˅IaOUÿ {bFcN4FMtn-=6c li4BH!(dX՗.U>BZERA\FTBXDP }!r^C2^@I`&tl$ɝ,S3MD.'	90NCӴY6)F?2m$	b@WH<Nt͐xjD"5v1of^gVfI.lfhě9<VOC|8i4>C8%JlGk8z#SmȉrXZ\@{x<.`^orŌBx<^'j}U1}QWhT]"kL|snێ#~ߢK\}bx'BQ'{i^oPȲz].c)weSL|iW(S    IENDB`PNG

   IHDR         7   gAMA  7   tEXtSoftware Adobe ImageReadyqe<   eIDAT(cπ2.RWe7JaWА\X]?XH^?
73`[*60HڐsV    IENDB`PNG

   IHDR         7   gAMA  7   tEXtSoftware Adobe ImageReadyqe<   aIDAT(cπ2Q+/ދEp,
 %ւ)XC۱)XdB=6PMu][z+_70!I ȓzS5    IENDB`PNG

   IHDR         c   sBIT|d   	pHYs    ~   tEXtSoftware Adobe Fireworks CS3F   tEXtCreation Time 7/16/07Z   (IDATHA 0 !U[
GϱJJJJJJJJJY     IENDB`GIF89a                                     !NETSCAPE2.0   !
  ,        @Rihlp,tm#6N+rrD4h@FCjz]Lj]﹬R3-H$wPy|KI\KQ\]PI~$
~	
J%:`@XP@AO	2|(D**HE}lF=$ Ƌ@\9LJ()?
``C=4RO@>}5TDU^=UQH~Xe֫:<! b`^Ovy':</%ƄEn`ʎ3AƊ~`۸Rf*4LE3DZ[FUպg*>|AoG4Q]V;ޙ<G)}SvO<}&py ]XgX
`"1A fJh!B 28'm
uљtbj)򖜊H	s6.7L;jԣJ?p6 l@k[-)PVXfQ9{fĥZ^v	&0lp)g9P !
  ,      EMbT5+ksly[J;w3iHʒ:QXR$Á511@eg;=(gڙn%pf"|w}zv[xE%`	+%		1"	
1Ʒ1++'i1֘~~%t"ݫ'$|dЉ'N7o%pDz:)DH$DEtl̑5żlP4	#y5SRzC> jUzҧ]$jQM
 ʆķ 7721@ܒDH;܋%ЅqۛXMgNάgMW  z!`dѥ]uja}aݸ6;5լDzTh,5~z~@y[:3M7gG]q=@c5

4u흃5_ _9_AMtB\Kⵘ}" @lDiQu+baq&{#'LHjz"$& $B !
  ,      EI@*PR*;ò[Ll7DҎ%GI0)mIԲ`I}>ă}-RwFu}y|O(p*"rt{RA>(^(		"4	
333..Чɞv.*o3uzz(	D.zHa рP*6=%8A%ϤH]JQ&2Lz녆Aɔ>50j(]T.s
*I@m:nTx^7}v(Hy!8/
4^ֹGi`zA" ?l8]'STҧX*3  @XMS<@蜮-./Ay5|Uv۬ϰVr4<A:\4bmdvi{˿ӛW'7naq{"8V_u_^2_[koTpbp:Mskx_"Vؓ !
  ,      %R4yԬԢ\K٩l'#Q<P:A*4 GZLnq,I\EoIUzqx#)_""
00+0##I"'20	q+t'k`n܀#|2aqVkoE f
NC})Tǐ`R8ć=5&D9ۦZ{@滗1M۴͇)TyN39]ƱAoVj>Z0ՠVTyïe]U4f!Pc0zkW+_^ў`v"Ŋa@x:@O,ȬtK5zsRtH5y3ʥ>yz= 3[/Z|&x@7nGdn B^|{ZCN3Z&$p{f;^C}Co % !
  ,      %$5,%:k.]#>	B"ZRp]2Shk9E-e<ͩkGj6-twsz|mOQtix41
)
U"			BQ
B)#B+u	)ێ#"pg߿=QǍPaQ*֑Xb<88l$Q,?	y2=0յT#rΗ59`jLmgTJ2MWy6jukիKy0 iP0J  Cg&(`oq]혗']u}C* ^\sxaGtKpeÈa  @jvlgVDz$ͣQ>mb16}4 @l`ѪzvsGt2y֐/V+SǊ=^"+Y 	09ڛ>0}ǈ`abqO
'8^Xd|5 [ahWY7֑W6!i!qHX&(@3&B !
  ,      Q$@RS"	k;	S]3X'+ζS
tUik`m0c]wldt$v}k~zq,lryux?)B		
;	00;+	­G0-g+	.z%$z+l(jx9hNt <; 8O7yxH#|bH$ѼLipȅѐ 2"-A(P  $tj@{s(W$( =!u5(jmnwmĸoA@w/d1+: 'l1f#|,z20Hg@1}թٯ[3S+|7Uǃ.{P卵0ʶc=+PL03:~p'v{On<~)@uP6k(àK'vK
V`I9(ZLG!  !
  ,      PeRN*',Ԣv*o<bKs M3k>oRsAE1fm):kvvM{wlrtqPm|uF~?W	a3&
A66	-3-	.,6o3/h-o	'dzz&(CGo߉Oa9 ќD=kOOEuj(ǑLʏTIR&K.H=ttI£B0E:qjԪPhY 	ʾBFdÎT0@ ܝK!Aݽ_aw9h P(!Ѣ,fʓmZ,rƝ[|.1鑣wZh%.:^mRi綽7V޿}c\u;o>oüu+],Ebd]/\.*h3;߯~|HoXg6]	!  !
  ,      E9$#%5(,Ԓr(i0.݊`lXtD%ydJ6H^.pl[k=.˿(>Sx~gypv}lNtjx{e>	(	~~	
--,-(Ĺ'e-/p(u'"	uGN
šL1:I<9uG '9cɕ-Q$L'lD7UTT ׄ tѦBU@%JJŪ)W?  LSY	bZvmމ Б]xF0I{VXg|-BfE#|.@4OP4 u8Sg֥_n;Ө՞(բQ)wǮ<.(ʳ2?eG|LՅ"x/-/y+,p=E1 dQٷ~  2Kꔛ$r
` m*YsCzFn ak}nnI#Q !
  ,      %R4Ԝ"CA,(~ں8׼دDA֐2hs݌+p]ˤObKw8^>uz`H~htkv"xm|1Z,
-#51"1''[#,
,},'	p#h1wa"w#p"b1V-akcB)P@;]XqČ#N-A"߲SyrL4eMʚph\@eq/o	D2(𯘳qs:gu@Fu+QAUӯZ#xbR4vG1
Mɻ ;8FP`B۩3he11O~	˟>z(C3A=\Z-ڇA a-qiSRYmG(1;Ž=dtqB[ !	
  ,        %dihlp,40T:Ԕn琘9␄\<
P)JZ+^f(-N	Ǥ4ant#o~$z|u#Svx@"'%	#m#	S%
	$%§	#ְͽ$&	A"%$#H݃'/9BHE dOC)Lq#Fo	gBbDIʤC'CRg̙G	4^M=<iEj0ћM-0R=jB+î{u,HYÖ$+vhPzz$W-] &=->F\dd3 X堙Kl٣̊@@T?}IVUT+ol|gr
TeluӭޒvG]l<ݑsg_D
)4EQ_i)Pi#!h Da
%.@qMOQ	`pnyHWC"$s*
]hp$V8<c!  ;PNG

   IHDR         a   gAMA  7  iCCPICC Profile  xTkPe:g	>hndStCkWZ6!Hm\$~ًo:w>كo{a"L"4M'S9'^qZ/USO^C+hMJ&G@Ӳylto߫c՚ 5"Yi\t։15LsX	g8ocግ#f45@	B:K@8i΁'&.<ER/dEs_雭mN|9}p ?_ApX65~B$&tieY)%$bT3liP443YP1KFۑ5>)@ry[:Vͦ#wQ?HBd(BacĪL"JitTy8;(Gx_^[%׎ŷQ麲uan7mQH^eOQu6Su2%vX^*l
Oޭˀq,>S%LdB1CZ$M9P'w\/].r#E|!3>_oa۾d1Zӑz'=~V+cjJtO %mN|-bWO+
o^IH.;S]i_s9*p.7U^s.3u	|^,<;c=ma>Vt.[՟Ϫx#
¡_2   	pHYs       diTXtXML:com.adobe.xmp     <x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="XMP Core 4.4.0">
   <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
      <rdf:Description rdf:about=""
            xmlns:xmp="http://ns.adobe.com/xap/1.0/">
         <xmp:CreatorTool>Adobe ImageReady</xmp:CreatorTool>
      </rdf:Description>
   </rdf:RDF>
</x:xmpmeta>
z  `IDAT8}RMka~vW#j-įV&ZjR
B"Q!zR!JA"T	~zi*U̶G_ݝ}gyEQp:::+z2t~&΍o*Lo$d2ee
 'V @43H6DX0O@(RmFٍodFɾ͇xUp:<"NTd}\3,@AZrr7! tZWwF_Z>lhRlޢ lk1<\ؼ
*q:ZUB:{ےܡP@Melۀ^z>:D"1iXZ{e<)iJl
En)ev`POydb=;;CX.ck1k&8jר_d{~?jcfiRԡsbOA9&ydV;8$p.r=XLv}@!OaX,*C;zJnYTaB!^L{n7k    IENDB`PNG

   IHDR         a   gAMA  7   tEXtSoftware Adobe ImageReadyqe<  oIDAT8˥Ka[/Y()%X(olNۖskn.-h;8fEP"jïMGˈ}yພ羹$ I.tulu	AX:𼂒ZHh1DnZJOJB{Z?`2`S=N$ő=;a&jwqJG#<"N2h8޵`6xցn_+~Zto}`x%XЛ͈	hXѿƻ/}BJ_G&|Qr-6AރEL⬡\U3:WUh[C6+	6.f *K͸ܝFqou4܄?d|XҥMvD`*_[#A20liR|xq`4w=\uQ	m+G|%$5Թ5RO*YGMUOGqj4ְ(X&
s1c˭(LVfRdjQ	'-1ATA>U	j4,pV"4L$e@.ArBY a~my Y])Q8tNLܞt2"I	o=CSd)__AF (    IENDB`PNG

   IHDR         a   gAMA  7   tEXtSoftware Adobe ImageReadyqe<  IDAT8˕kSQ8H)N]uA,wjazcbb6&	Qcn^b4b2e	l xW
}$9Xt:$n"0T8J)N!h4ʉF|p8|2X,f[͵`0S~OZ%
}
iz=nHXt:4"BrLRtv_T'-lu&f_uRl6 u]e
5~lޢnz{ejjUiw|}?$&x
r|TN%*4Ç l;'T^ٗG<"pFୌw!yhݔeE6	
ܙצPJ:C\DW^,<<4A	ѹ]s6ޑ    IENDB`PNG

   IHDR         7   gAMA  7   tEXtSoftware Adobe ImageReadyqe<   cIDAT(cπ2Q+/ދEp,
 %ćO`PoǦ`1	BrC6uo_?$
 }J Ʀg    IENDB`PNG

   IHDR         7   gAMA  7   tEXtSoftware Adobe ImageReadyqe<  VIDAT?HT ݝ^ٟ
juɥpOhi/8ԩ!p*0Ў;}E ,tnM2|13 "byK$i^NFDЙ;4eZ|Uj|jf^$ig)kYbIuKWPcJ'U>4MKB݆eSJtO9iԄʆn#2u`  *_
R4+*BuϘMYU׷oAaLG۽kE|"2w9m[yGwSB3{er~㫹<{@   %@    IENDB`PNG

   IHDR         a   gAMA  7   tEXtSoftware Adobe ImageReadyqe<  IDAT8mRKQ	-f=?IZTvrpmEDR-*"+RJ,+"ZLR.JŢ>DÔ?R;c}s}Wb{{Jlff`[%nJs.Û/ZA 8>>FP@>5}q$	{_Kx<B!y+qIEauuNS1stppp LMM;99G T/=/LNNaOd2H$8;;9pzzZtxggp^W"bbbBU$A:-"WU9D6nnnJJUUqssd2X,&U]HtF'$fS4x\>CvXZZdjr*^GQR)גct]l6GMr8d0e\SS$immMWp544zzzIpuu^u90_9>^WTT|	P]]:	$AWÃw{5nZZZ&c]5}EP^^`0,˃cccW/"֘kXYj    IENDB`PNG

   IHDR         a   gAMA  7   tEXtSoftware Adobe ImageReadyqe<  IDAT8˕oQ_[c+W.]хi5 gmJ[Fq#_)qո;,@{;u pLTʙH$(Z XMɤni"\nt:}yD	<ou]q},5QXjP*DޅB!5ɠlX2|XPVQ( IEAXk
ί:lU*h{-PU,n	Y>0\ږIU4(r
HMk̈_4_ziy'"[n1rM_A`b =$Ik_p-qS~=li~3Bv"qZAԧ̸r[G]<&e!'ڸ67	yq$OX!=_~1Gs~EZQx&qWK3!ޤunkzGrjQn    IENDB`PNG

   IHDR         %=m"   PLTE   tRNS @f   IDATc`    0 z    IENDB`PNG

   IHDR         a   gAMA  7   tEXtSoftware Adobe ImageReadyqe<  IDAT?s~~TI!!bF ,H8b1a5lNQB b`^8MA~y*޿\)(0kJiΆI H q~{СMкOgԪ(2X2s,}O>};x3o}~Wtܠ$SjbjLEMa8y޿ww>JҪ*m*u=g6=W|vjz:@B(%UZ4\1mfj"jAƚ6hT*J	VZJZ$@10PHZ(}
)Be @)zcԊe 02FHd#    W?9</;  C9Axy   轍y3t-;w^t'IWMeС*>Wi ! Gc{sގl6    IENDB`PNG

   IHDR         a   gAMA  7   tEXtSoftware Adobe ImageReadyqe<  %IDAT8c?%4ydÞ'/XfƦ"ʀGvi QTo@5 )%k;o4 7Y%uZbVTyE,Xݣo6ةm=x)k?"eKZ帹yLe?	'?e}KjmѹÓ.dfay6 \Vo]Z9մ6\K/ bĬ`
*YBc~Z:
ola_[S1qIbR/*.?##;L@	:
]_@$e;@1/x%|W4 |F=c 9WA1 2 5zaN?(8 SSQEQBZ(`?֎nx% P`_IU
 P,aj (X@K*п9} ce&R1 2hZ<u    IENDB`PNG

   IHDR         a   gAMA  7   tEXtSoftware Adobe ImageReadyqe<  IDAT8˥=Hqf~\?,yoX{KC7PcM54EkS$8V*wJB%{s^1㪋g99IDp8ラ%w%I=@]mvbS?|b~?GժilT70p,@ۙܘ^Y3$ՙO<oa x8A܉BW!!JBx8K?Y\z܃S<fRDKCPf' hafWãIn]BW)䎇p!GosAMNX	0eY[raBAmh=ڊI#͘061;Ū3Q@se
pk_;+?R15S_?q9*H3ɞ`!w2/L .\cIeصf|Ĕb`M ow=_m6EX    IENDB`PNG

   IHDR         a   gAMA  7   tEXtSoftware Adobe ImageReadyqe<  IDAT8˥?/Qϲhg5j%'F,[
LH	3(vw=fcoN{O~9VM4Q7ܿ)v/WQ=&bpSO^'&^:\˨6eND!& 9꒣_|?\srx,g*,(F#d[O aAA*Pp1O+C$`)*w`A#0$	*?b&NR    IENDB`PNG

   IHDR         7   gAMA  7   tEXtSoftware Adobe ImageReadyqe<   IDAT(υA0E֕n\xqob♼Rw(gIu2U5S6VXʲJ6YhlOe<Ƥj56S&5 n2 ,be%,r[;zֳ
X`<ƐdzB7|!A/n2=VYro vZd    IENDB`PNG

   IHDR         a   gAMA  7   tEXtSoftware Adobe ImageReadyqe<  IDAT8}Kh\u{g̝4L)B1>n\F)PADQTWf!"؍`HC0ijC1ͳLfw(v!g}69)wyc/T4"ԳX8ѫ̛vכ*WGU}[E>7&tJiG+*rQE>{	`=9 o/rorgaw=MЪUQVcƏ;}ź;qD>r7jT1aU&m86l7KVio{Ǥ9sVԨ,O"aWūmptk.h-V}֯K*R\M-Юޡ'O'CU0)79Ms&3P# V
'w 'ů 
N,op#LRi4Qjh ]GS\;QƤBH`1@<Ѐd^{9] ! "dlǁD	@|0mp
Qa+kK7
"$ h$?$BrN#&Cif
N7SV[6laL/HbF6tX=ֽɕد}GO|뻗zUC5rh8D>)4Vwͦ|"L\>2FΫ[^yjW?'q{gBio.ȧTctܲ^&    IENDB`PNG

   IHDR         7   gAMA  7   tEXtSoftware Adobe ImageReadyqe<   IDAT1nSAǞ4A(ISp.KPp"QA7%1Ӣ; +Z######DWk=C?|Xj9昇SekMs9NNVG@kD)4hn.Q@nJ)1]:; 1@T: ti: I$fM  -+g  ]^Lv    IENDB`PNG

   IHDR         a   gAMA  7   tEXtSoftware Adobe ImageReadyqe<  IDAT8˕RmkA~ԋK$5X% ǂ!#?P@PZ(*EA#ܹۙw:0;3ϼ@J	f?WoL`
OZ+M<ww
^IśKZRjFNV0+vE8q +bF"vs;4t >9cktyx	D7гm\PSt]Io@#/ د)[f^ѻ#dHkbG"uݿq\.Xc8YhH|r}/!FsRB(]jT5V?ZxYl6sd2QgwpdC2p8A厊*X,¢<}"W
8s"jR--tiM1eK
lT*=L/F#C7~-:MW1    IENDB`PNG

   IHDR         a   gAMA  7   tEXtSoftware Adobe ImageReadyqe<  ]IDAT8˥KSa[nQP2wܦγL[,biaA\Cv_2MlZFjסNMjmkʷ`&.#z<ϓ bVPT3%I{GqRivȅ
tz#E6EddJ`DR2<]N;4Ѿ;m>78ɀQe6LIt殷cq!z|vj/Xi@%1|hl !|!Y#uUNw]˼H3u	t]E>k%IfoRD:0`~|(r
on3oG0!$V*[W0_-+ dW&2ZfMFVJpiF&B>Rg- ~	CmڴERឫ p5ްy+21Kawh` #aZ񽞆TZoLѓ`"(?'ˎJvKކ|:G9[aw82Jwf'ymzsӘTsw__ιIr    IENDB`PNG

   IHDR         a   gAMA  7   tEXtSoftware Adobe ImageReadyqe<  FIDAT8ˍKHA̪-KC=CmfuP)DB"K$A
etJZyum0}f~3#s L|!!|g-V9Q鎺c`TC8*5bF'R!DЋkb^sP! Locgע≣.=^u֘[65޶FG ! P%wN5\q=(t@ȀѶ(t2)է"L?B2uXcYV$&a]ct<* Q1}E	)hYҁ갎6`DXr<:=UR̞O98*}V&b==hցqف+;˜JT< A!C:̼}nAH~0bM36+/痗sIĢ̾Ek J{v!=_MyKb] öa{6W03<U=c @_@,/fgkMq?)+H    IENDB`<%- if klass.type == 'class' then %>
<div id="parent-class-section" class="nav-section">
  <h3>Parent</h3>

  <%- if klass.superclass and not String === klass.superclass then -%>
  <p class="link"><a href="<%= klass.aref_to klass.superclass.path %>"><%= klass.superclass.full_name %></a>
  <%- else -%>
  <p class="link"><%= klass.superclass %>
  <%- end -%>
</div>
<%- end -%>
<body id="top" role="document" class="<%= klass.type %>">
<nav role="navigation">
  <div id="project-navigation">
    <%= render '_sidebar_navigation.rhtml' %>
    <%= render '_sidebar_search.rhtml' %>
  </div>

  <%= render '_sidebar_table_of_contents.rhtml' %>

  <div id="class-metadata">
    <%= render '_sidebar_sections.rhtml' %>
    <%= render '_sidebar_parent.rhtml' %>
    <%= render '_sidebar_includes.rhtml' %>
    <%= render '_sidebar_extends.rhtml' %>
    <%= render '_sidebar_methods.rhtml' %>
  </div>
</nav>

<main role="main" aria-labelledby="<%=h klass.aref %>">
  <h1 id="<%=h klass.aref %>" class="<%= klass.type %>">
    <%= klass.type %> <%= klass.full_name %>
  </h1>

  <section class="description">
    <%= klass.description %>
  </section>

  <%- klass.each_section do |section, constants, attributes| -%>
  <section id="<%= section.aref %>" class="documentation-section">
    <%- if section.title then -%>
    <header class="documentation-section-title">
      <h2>
        <%= section.title %>
      </h2>
      <span class="section-click-top">
        <a href="#top">&uarr; top</a>
      </span>
    </header>
    <%- end -%>

    <%- if section.comment then -%>
    <div>
      <%= section.description %>
    </div>
    <%- end -%>

    <%- unless constants.empty? then -%>
    <section class="constants-list">
      <header>
        <h3>Constants</h3>
      </header>
      <dl>
      <%- constants.each do |const| -%>
        <dt id="<%= const.name %>"><%= const.name %>
        <%- if const.comment then -%>
        <dd><%= const.description.strip %>
        <%- else -%>
        <dd class="missing-docs">(Not documented)
        <%- end -%>
      <%- end -%>
      </dl>
    </section>
    <%- end -%>

    <%- unless attributes.empty? then -%>
    <section class="attribute-method-details" class="method-section">
      <header>
        <h3>Attributes</h3>
      </header>

      <%- attributes.each do |attrib| -%>
      <div id="<%= attrib.aref %>" class="method-detail">
        <div class="method-heading attribute-method-heading">
          <span class="method-name"><%= h attrib.name %></span><span
            class="attribute-access-type">[<%= attrib.rw %>]</span>
        </div>

        <div class="method-description">
        <%- if attrib.comment then -%>
        <%= attrib.description.strip %>
        <%- else -%>
        <p class="missing-docs">(Not documented)
        <%- end -%>
        </div>
      </div>
      <%- end -%>
    </section>
    <%- end -%>

    <%- klass.methods_by_type(section).each do |type, visibilities|
       next if visibilities.empty?
       visibilities.each do |visibility, methods|
         next if methods.empty? %>
     <section id="<%= visibility %>-<%= type %>-<%= section.aref %>-method-details" class="method-section">
       <header>
         <h3><%= visibility.to_s.capitalize %> <%= type.capitalize %> Methods</h3>
       </header>

    <%- methods.each do |method| -%>
      <div id="<%= method.aref %>" class="method-detail <%= method.is_alias_for ? "method-alias" : '' %>">
        <%- if (call_seq = method.call_seq) then -%>
        <%-   call_seq.strip.split("\n").each_with_index do |call_seq, i| -%>
        <div class="method-heading">
          <span class="method-callseq">
            <%= h(call_seq.strip.
                  gsub( /^\w+\./m, '')).
                  gsub(/(.*)[-=]&gt;/, '\1&rarr;') %>
          </span>
          <%- if i == 0 and method.token_stream then -%>
          <span class="method-click-advice">click to toggle source</span>
          <%- end -%>
        </div>
        <%-   end -%>
        <%- else -%>
        <div class="method-heading">
          <span class="method-name"><%= h method.name %></span><span
            class="method-args"><%= h method.param_seq %></span>
          <%- if method.token_stream then -%>
          <span class="method-click-advice">click to toggle source</span>
          <%- end -%>
        </div>
        <%- end -%>

        <div class="method-description">
          <%- if method.comment then -%>
          <%= method.description.strip %>
          <%- else -%>
          <p class="missing-docs">(Not documented)
          <%- end -%>
          <%- if method.calls_super then -%>
            <div class="method-calls-super">
              Calls superclass method
              <%=
                  method.superclass_method ?
                  method.formatter.link(method.superclass_method.full_name, method.superclass_method.full_name) : nil
              %>
            </div>
          <%- end -%>

          <%- if method.token_stream then -%>
          <div class="method-source-code" id="<%= method.html_name %>-source">
            <pre><%= method.markup_code %></pre>
          </div>
          <%- end -%>
        </div>

        <%- unless method.aliases.empty? then -%>
        <div class="aliases">
          Also aliased as: <%= method.aliases.map do |aka|
            if aka.parent then # HACK lib/rexml/encodings
              %{<a href="#{klass.aref_to aka.path}">#{h aka.name}</a>}
            else
              h aka.name
            end
          end.join ", " %>
        </div>
        <%- end -%>

        <%- if method.is_alias_for then -%>
        <div class="aliases">
          Alias for: <a href="<%= klass.aref_to method.is_alias_for.path %>"><%= h method.is_alias_for.name %></a>
        </div>
        <%- end -%>
      </div>

    <%- end -%>
    </section>
  <%- end
     end %>
  </section>
<%- end -%>
</main>
<footer id="validator-badges" role="contentinfo">
  <p><a href="https://validator.w3.org/check/referer">Validate</a>
  <p>Generated by <a href="https://ruby.github.io/rdoc/">RDoc</a> <%= RDoc::VERSION %>.
  <p>Based on <a href="http://deveiate.org/projects/Darkfish-RDoc/">Darkfish</a> by <a href="http://deveiate.org">Michael Granger</a>.
</footer>
<div id="classindex-section" class="nav-section">
  <h3>Class and Module Index</h3>

  <ul class="link-list">
  <%- @modsort.each do |index_klass| -%>
    <li><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a>
  <%- end -%>
  </ul>
</div>
<body id="top" role="document" class="file">
<nav role="navigation">
  <div id="project-navigation">
    <%= render '_sidebar_navigation.rhtml' %>

    <%= render '_sidebar_search.rhtml' %>
  </div>

  <div id="project-metadata">
    <%= render '_sidebar_pages.rhtml' %>
    <%= render '_sidebar_classes.rhtml' %>
  </div>
</nav>

<main role="main">
<%- if @options.main_page and
      main_page = @files.find { |f| f.full_name == @options.main_page } then %>
<%= main_page.description %>
<%- else -%>
<p>This is the API documentation for <%= @title %>.
<%- end -%>
</main>
<%- simple_files = @files.select { |f| f.text? } %>
<%- unless simple_files.empty? then -%>
<div id="fileindex-section" class="nav-section">
  <h3>Pages</h3>

  <ul class="link-list">
  <%- simple_files.each do |f| -%>
    <li><a href="<%= rel_prefix %>/<%= f.path %>"><%= h f.page_name %></a>
  <%- end -%>
  </ul>
</div>
<%- end -%>
<body role="document">
<nav role="navigation">
  <div id="project-navigation">
    <div id="home-section" class="nav-section">
      <h2>
        <a href="<%= rel_prefix %>/" rel="home">Home</a>
      </h2>
    </div>

    <%= render '_sidebar_search.rhtml' %>
  </div>

<%= render '_sidebar_installed.rhtml' %>
</nav>

<main role="main">
  <h1>Local RDoc Documentation</h1>

  <p>Here you can browse local documentation from the ruby standard library and
  your installed gems.

<%- extra_dirs = installed.select { |_, _, _, type,| type == :extra } -%>
<%- unless extra_dirs.empty? -%>
  <h2>Extra Documentation Directories</h2>

  <p>The following additional documentation directories are available:</p>

  <ol>
  <%- extra_dirs.each do |name, href, exists, _, path| -%>
    <li>
    <%- if exists -%>
      <a href="<%= href %>"><%= h name %></a> (<%= h path %>)
    <%- else -%>
      <%= h name %> (<%= h path %>; <i>not available</i>)
    <%- end -%>
    </li>
  <%- end -%>
  </ol>
<%- end -%>

<%- gems = installed.select { |_, _, _, type,| type == :gem } -%>
<%- missing = gems.reject { |_, _, exists,| exists } -%>
<%- unless missing.empty? then -%>
  <h2>Missing Gem Documentation</h2>

  <p>You are missing documentation for some of your installed gems.
  You can install missing documentation for gems by running
  <kbd>gem rdoc --all</kbd>.  After installing the missing documentation you
  only need to reload this page.  The newly created documentation will
  automatically appear.

  <p>You can also install documentation for a specific gem by running one of
  the following commands.

  <ul>
  <%- names = missing.map { |name,| name.sub(/-([^-]*)$/, '') }.uniq -%>
  <%- names.each do |name| -%>
    <li><kbd>gem rdoc <%=h name %></kbd>
  <%- end -%>
  </ul>
<%- end -%>
</main>
/*
 * 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.
 */

/*
 * "Darkfish" Rdoc CSS
 * $Id: rdoc.css 54 2009-01-27 01:09:48Z deveiant $
 *
 * Author: Michael Granger <ged@FaerieMUD.org>
 *
 */

/* 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 */

<%- unless klass.method_list.empty? then %>
<!-- Method Quickref -->
<div id="method-list-section" class="nav-section">
  <h3>Methods</h3>

  <ul class="link-list" role="directory">
    <%- klass.each_method do |meth| -%>
    <li <%- if meth.calls_super %>class="calls-super" <%- end %>><a href="#<%= meth.aref %>"><%= meth.singleton ? '::' : '#' %><%= h meth.name -%></a>
    <%- end -%>
  </ul>
</div>
<%- end -%>
<meta charset="<%= @options.charset %>">

<title><%= h @title %></title>

<script type="text/javascript">
  var rdoc_rel_prefix = "<%= asset_rel_prefix %>/";
  var index_rel_prefix = "<%= rel_prefix %>/";
</script>

<script src="<%= asset_rel_prefix %>/js/navigation.js" defer></script>
<script src="<%= asset_rel_prefix %>/js/search.js" defer></script>
<script src="<%= asset_rel_prefix %>/js/search_index.js" defer></script>
<script src="<%= asset_rel_prefix %>/js/searcher.js" defer></script>
<script src="<%= asset_rel_prefix %>/js/darkfish.js" defer></script>

<link href="<%= asset_rel_prefix %>/css/fonts.css" rel="stylesheet">
<link href="<%= asset_rel_prefix %>/css/rdoc.css" rel="stylesheet">
<%- if @options.template_stylesheets.flatten.any? then -%>
<%-   @options.template_stylesheets.flatten.each do |stylesheet| -%>
<link href="<%= asset_rel_prefix %>/<%= File.basename stylesheet %>" rel="stylesheet">
<%-   end -%>
<%- end -%>
<div id="home-section" class="nav-section">
  <h3>Documentation</h3>

  <ul>
  <%- installed.each do |name, href, exists, type, _| -%>
    <%- next if type == :extra -%>
    <li class="folder">
    <%- if exists then -%>
      <a href="<%= href %>"><%= h name %></a>
    <%- else -%>
      <%= h name %>
    <%- end -%>
  <%- end -%>
  </ul>
</div>
<body id="top" class="table-of-contents">
<main role="main">
<h1 class="class"><%= h @title %></h1>

<%- simple_files = @files.select { |f| f.text? } -%>
<%- unless simple_files.empty? then -%>
<h2 id="pages">Pages</h2>
<ul>
<%- simple_files.sort.each do |file| -%>
  <li class="file">
    <a href="<%= file.path %>"><%= h file.page_name %></a>
<%
   # HACK table_of_contents should not exist on Document
   table = file.parse(file.comment).table_of_contents
   unless table.empty? then %>
    <ul>
<%- table.each do |heading| -%>
      <li><a href="<%= file.path %>#<%= heading.aref %>"><%= heading.plain_html %></a>
<%-   end -%>
    </ul>
<%- end -%>
  </li>
  <%- end -%>
</ul>
<%- end -%>

<h2 id="classes">Classes and Modules</h2>
<ul>
<%- @modsort.each do |klass| -%>
  <li class="<%= klass.type %>">
    <a href="<%= klass.path %>"><%= klass.full_name %></a>
<%- table = []
   table.concat klass.parse(klass.comment_location).table_of_contents
   table.concat klass.section_contents

   unless table.empty? then %>
    <ul>
<%- table.each do |item| -%>
      <li><a href="<%= klass.path %>#<%= item.aref %>"><%= item.plain_html %></a>
<%-   end -%>
    </ul>
<%- end -%>
  </li>
<%- end -%>
</ul>

<h2 id="methods">Methods</h2>
<ul>
<%- @store.all_classes_and_modules.map do |mod|
     mod.method_list
   end.flatten.sort.each do |method| %>
  <li class="method">
    <a href="<%= method.path %>"><%= h method.pretty_name %></a>
    &mdash;
    <span class="container"><%= method.parent.full_name %></span>
<%- end -%>
</ul>
</main>
<body role="document">
<nav role="navigation">
  <%= render '_sidebar_navigation.rhtml' %>

  <%= render '_sidebar_search.rhtml' %>

  <div id="project-metadata">
    <%= render '_sidebar_pages.rhtml' %>
    <%= render '_sidebar_classes.rhtml' %>
  </div>
</nav>

<main role="main">
  <h1>Not Found</h1>

  <p><%= message %>
</main>

# 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
# 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 <EMAIL@ADDRESS>, 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 <EMAIL@ADDRESS>
Language-Team: LANGUAGE <LL@li.org>
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
# 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
# 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
# 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 <tt>--op</tt> 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

    @options.template_stylesheets.each do |stylesheet|
      FileUtils.cp stylesheet, '.', 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 "<html" the body is
  # used directly.

  def assemble_template body_file
    body = body_file.read
    return body if body =~ /<html/

    head_file = @template_dir + '_head.rhtml'
    footer_file = @template_dir + '_footer.rhtml'

    <<-TEMPLATE
<!DOCTYPE html>

<html>
<head>
#{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
# 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 <tt>,
  # line dddd</tt> 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
              "<span class=\"line-num\">%2$*1$d</span> " % [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

# 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

# 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
# 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 <tt>old_name => [aliases]</tt>, 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, <tt>attr_reader :foo</tt> will not be registered
  # if method +foo+ exists, but <tt>attr_accessor :foo</tt> will be registered
  # if method +foo+ exists, but <tt>foo=</tt> 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 <tt>class Container::Item</tt> RDoc assumes +Container+ is a module
  # unless it later sees <tt>class Container</tt>.  +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
  # <tt>TopLevel::modules_hash</tt> or <tt>TopLevel::classes_hash</tt>),
  # 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 <tt>includes == false</tt>.

  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 =~ /<</
    path = [prefix] + path.split('::')

    File.join(*path.compact) + '.html'
  end

  ##
  # Instance attributes

  def instance_attributes
    @instance_attributes ||= attributes.reject { |a| a.singleton }
  end

  ##
  # Instance methods

  def instance_methods
    @instance_methods ||= method_list.reject { |a| a.singleton }
  end

  ##
  # Instance methods
  #--
  # TODO remove this later

  def instance_method_list
    warn '#instance_method_list is obsoleted, please use #instance_methods'
    @instance_methods ||= method_list.reject { |a| a.singleton }
  end

  ##
  # Breaks method_list into a nested hash by type (<tt>'class'</tt> or
  # <tt>'instance'</tt>) 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.
  # <tt>#full_name</tt> 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
  #   <tt>#remove_from_documentation? == true</tt>
  # * All classes and modules have <tt>#remove_from_documentation? == true</tt>

  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
# frozen_string_literal: true
##
# An anonymous class like:
#
#   c = Class.new do end
#
# AnonClass is currently not used.

class RDoc::AnonClass < RDoc::ClassModule
end

# frozen_string_literal: true
##
# Inline keeps track of markup and labels to create proper links.

class RDoc::RD::Inline

  ##
  # The text of the reference

  attr_reader :reference

  ##
  # The markup of this reference in RDoc format

  attr_reader :rdoc

  ##
  # Creates a new Inline for +rdoc+ and +reference+.
  #
  # +rdoc+ may be another Inline or a String.  If +reference+ is not given it
  # will use the text from +rdoc+.

  def self.new rdoc, reference = rdoc
    if self === rdoc and reference.equal? rdoc then
      rdoc
    else
      super
    end
  end

  ##
  # Initializes the Inline with +rdoc+ and +inline+

  def initialize rdoc, reference # :not-new:
    @reference = reference.equal?(rdoc) ? reference.dup : reference

    # unpack
    @reference = @reference.reference if self.class === @reference
    @rdoc      = rdoc
  end

  def == other # :nodoc:
    self.class === other and
      @reference == other.reference and @rdoc == other.rdoc
  end

  ##
  # Appends +more+ to this inline.  +more+ may be a String or another Inline.

  def append more
    case more
    when String then
      @reference += more
      @rdoc      += more
    when RDoc::RD::Inline then
      @reference += more.reference
      @rdoc      += more.rdoc
    else
      raise "unknown thingy #{more}"
    end

    self
  end

  def inspect # :nodoc:
    "(inline: #{self})"
  end

  alias to_s rdoc # :nodoc:

end

# frozen_string_literal: true
#
# DO NOT MODIFY!!!!
# This file is automatically generated by Racc 1.5.2
# from Racc grammar file "".
#

require 'racc/parser.rb'

require 'strscan'

class RDoc::RD

##
# RD format parser for inline markup such as emphasis, links, footnotes, etc.

class InlineParser < Racc::Parser


# :stopdoc:

EM_OPEN = '((*'
EM_OPEN_RE = /\A#{Regexp.quote(EM_OPEN)}/
EM_CLOSE = '*))'
EM_CLOSE_RE = /\A#{Regexp.quote(EM_CLOSE)}/
CODE_OPEN = '(({'
CODE_OPEN_RE = /\A#{Regexp.quote(CODE_OPEN)}/
CODE_CLOSE = '}))'
CODE_CLOSE_RE = /\A#{Regexp.quote(CODE_CLOSE)}/
VAR_OPEN = '((|'
VAR_OPEN_RE = /\A#{Regexp.quote(VAR_OPEN)}/
VAR_CLOSE = '|))'
VAR_CLOSE_RE = /\A#{Regexp.quote(VAR_CLOSE)}/
KBD_OPEN = '((%'
KBD_OPEN_RE = /\A#{Regexp.quote(KBD_OPEN)}/
KBD_CLOSE = '%))'
KBD_CLOSE_RE = /\A#{Regexp.quote(KBD_CLOSE)}/
INDEX_OPEN = '((:'
INDEX_OPEN_RE = /\A#{Regexp.quote(INDEX_OPEN)}/
INDEX_CLOSE = ':))'
INDEX_CLOSE_RE = /\A#{Regexp.quote(INDEX_CLOSE)}/
REF_OPEN = '((<'
REF_OPEN_RE = /\A#{Regexp.quote(REF_OPEN)}/
REF_CLOSE = '>))'
REF_CLOSE_RE = /\A#{Regexp.quote(REF_CLOSE)}/
FOOTNOTE_OPEN = '((-'
FOOTNOTE_OPEN_RE = /\A#{Regexp.quote(FOOTNOTE_OPEN)}/
FOOTNOTE_CLOSE = '-))'
FOOTNOTE_CLOSE_RE = /\A#{Regexp.quote(FOOTNOTE_CLOSE)}/
VERB_OPEN = "(('"
VERB_OPEN_RE = /\A#{Regexp.quote(VERB_OPEN)}/
VERB_CLOSE = "'))"
VERB_CLOSE_RE = /\A#{Regexp.quote(VERB_CLOSE)}/

BAR = "|"
BAR_RE = /\A#{Regexp.quote(BAR)}/
QUOTE = '"'
QUOTE_RE = /\A#{Regexp.quote(QUOTE)}/
SLASH = "/"
SLASH_RE = /\A#{Regexp.quote(SLASH)}/
BACK_SLASH = "\\"
BACK_SLASH_RE = /\A#{Regexp.quote(BACK_SLASH)}/
URL = "URL:"
URL_RE = /\A#{Regexp.quote(URL)}/

other_re_mode = Regexp::EXTENDED
other_re_mode |= Regexp::MULTILINE

OTHER_RE = Regexp.new(
  "\\A.+?(?=#{Regexp.quote(EM_OPEN)}|#{Regexp.quote(EM_CLOSE)}|
              #{Regexp.quote(CODE_OPEN)}|#{Regexp.quote(CODE_CLOSE)}|
              #{Regexp.quote(VAR_OPEN)}|#{Regexp.quote(VAR_CLOSE)}|
              #{Regexp.quote(KBD_OPEN)}|#{Regexp.quote(KBD_CLOSE)}|
              #{Regexp.quote(INDEX_OPEN)}|#{Regexp.quote(INDEX_CLOSE)}|
              #{Regexp.quote(REF_OPEN)}|#{Regexp.quote(REF_CLOSE)}|
            #{Regexp.quote(FOOTNOTE_OPEN)}|#{Regexp.quote(FOOTNOTE_CLOSE)}|
              #{Regexp.quote(VERB_OPEN)}|#{Regexp.quote(VERB_CLOSE)}|
              #{Regexp.quote(BAR)}|
              #{Regexp.quote(QUOTE)}|
              #{Regexp.quote(SLASH)}|
              #{Regexp.quote(BACK_SLASH)}|
              #{Regexp.quote(URL)})", other_re_mode)

# :startdoc:

##
# Creates a new parser for inline markup in the rd format.  The +block_parser+
# is used to for footnotes and labels in the inline text.

def initialize block_parser
  @block_parser = block_parser
end

##
# Parses the +inline+ text from RD format into RDoc format.

def parse inline
  @inline = inline
  @src = StringScanner.new inline
  @pre = "".dup
  @yydebug = true
  do_parse.to_s
end

##
# Returns the next token from the inline text

def next_token
  return [false, false] if @src.eos?
#  p @src.rest if @yydebug
  if ret = @src.scan(EM_OPEN_RE)
    @pre << ret
    [:EM_OPEN, ret]
  elsif ret = @src.scan(EM_CLOSE_RE)
    @pre << ret
    [:EM_CLOSE, ret]
  elsif ret = @src.scan(CODE_OPEN_RE)
    @pre << ret
    [:CODE_OPEN, ret]
  elsif ret = @src.scan(CODE_CLOSE_RE)
    @pre << ret
    [:CODE_CLOSE, ret]
  elsif ret = @src.scan(VAR_OPEN_RE)
    @pre << ret
    [:VAR_OPEN, ret]
  elsif ret = @src.scan(VAR_CLOSE_RE)
    @pre << ret
    [:VAR_CLOSE, ret]
  elsif ret = @src.scan(KBD_OPEN_RE)
    @pre << ret
    [:KBD_OPEN, ret]
  elsif ret = @src.scan(KBD_CLOSE_RE)
    @pre << ret
    [:KBD_CLOSE, ret]
  elsif ret = @src.scan(INDEX_OPEN_RE)
    @pre << ret
    [:INDEX_OPEN, ret]
  elsif ret = @src.scan(INDEX_CLOSE_RE)
    @pre << ret
    [:INDEX_CLOSE, ret]
  elsif ret = @src.scan(REF_OPEN_RE)
    @pre << ret
    [:REF_OPEN, ret]
  elsif ret = @src.scan(REF_CLOSE_RE)
    @pre << ret
    [:REF_CLOSE, ret]
  elsif ret = @src.scan(FOOTNOTE_OPEN_RE)
    @pre << ret
    [:FOOTNOTE_OPEN, ret]
  elsif ret = @src.scan(FOOTNOTE_CLOSE_RE)
    @pre << ret
    [:FOOTNOTE_CLOSE, ret]
  elsif ret = @src.scan(VERB_OPEN_RE)
    @pre << ret
    [:VERB_OPEN, ret]
  elsif ret = @src.scan(VERB_CLOSE_RE)
    @pre << ret
    [:VERB_CLOSE, ret]
  elsif ret = @src.scan(BAR_RE)
    @pre << ret
    [:BAR, ret]
  elsif ret = @src.scan(QUOTE_RE)
    @pre << ret
    [:QUOTE, ret]
  elsif ret = @src.scan(SLASH_RE)
    @pre << ret
    [:SLASH, ret]
  elsif ret = @src.scan(BACK_SLASH_RE)
    @pre << ret
    [:BACK_SLASH, ret]
  elsif ret = @src.scan(URL_RE)
    @pre << ret
    [:URL, ret]
  elsif ret = @src.scan(OTHER_RE)
    @pre << ret
    [:OTHER, ret]
  else
    ret = @src.rest
    @pre << ret
    @src.terminate
    [:OTHER, ret]
  end
end

##
# Raises a ParseError when invalid formatting is found

def on_error(et, ev, values)
  lines_of_rest = @src.rest.lines.to_a.length
  prev_words = prev_words_on_error(ev)
  at = 4 + prev_words.length

  message = <<-MSG
RD syntax error: line #{@block_parser.line_index - lines_of_rest}:
...#{prev_words} #{(ev||'')} #{next_words_on_error()} ...
  MSG

  message << " " * at + "^" * (ev ? ev.length : 0) + "\n"
  raise ParseError, message
end

##
# Returns words before the error

def prev_words_on_error(ev)
  pre = @pre
  if ev and /#{Regexp.quote(ev)}$/ =~ pre
    pre = $`
  end
  last_line(pre)
end

##
# Returns the last line of +src+

def last_line(src)
  if n = src.rindex("\n")
    src[(n+1) .. -1]
  else
    src
  end
end
private :last_line

##
# Returns words following an error

def next_words_on_error
  if n = @src.rest.index("\n")
    @src.rest[0 .. (n-1)]
  else
    @src.rest
  end
end

##
# Creates a new RDoc::RD::Inline for the +rdoc+ markup and the raw +reference+

def inline rdoc, reference = rdoc
  RDoc::RD::Inline.new rdoc, reference
end

# :stopdoc:
##### State transition tables begin ###

racc_action_table = [
   104,   103,   102,   100,   101,    99,   115,   116,   117,    29,
   105,   106,   107,   108,   109,   110,   111,   112,   113,   114,
    84,   118,   119,    63,    64,    65,    61,    81,    62,    76,
    78,    79,    85,    66,    67,    68,    69,    70,    71,    72,
    73,    74,    75,    77,    80,   149,    63,    64,    65,   153,
    81,    62,    76,    78,    79,    86,    66,    67,    68,    69,
    70,    71,    72,    73,    74,    75,    77,    80,   152,   104,
   103,   102,   100,   101,    99,   115,   116,   117,    87,   105,
   106,   107,   108,   109,   110,   111,   112,   113,   114,    88,
   118,   119,   104,   103,   102,   100,   101,    99,   115,   116,
   117,    89,   105,   106,   107,   108,   109,   110,   111,   112,
   113,   114,    96,   118,   119,   104,   103,   102,   100,   101,
    99,   115,   116,   117,   124,   105,   106,   107,   108,   109,
   110,   111,   112,   113,   114,   137,   118,   119,    22,    23,
    24,    25,    26,    21,    18,    19,   176,   177,    13,   148,
    14,   154,    15,   137,    16,   161,    17,   164,   173,    20,
    22,    23,    24,    25,    26,    21,    18,    19,   175,   177,
    13,   nil,    14,   nil,    15,   nil,    16,   nil,    17,   nil,
   nil,    20,    22,    23,    24,    25,    26,    21,    18,    19,
   nil,   nil,    13,   nil,    14,   nil,    15,   nil,    16,   nil,
    17,   nil,   nil,    20,    22,    23,    24,    25,    26,    21,
    18,    19,   nil,   nil,    13,   nil,    14,   nil,    15,   nil,
    16,   nil,    17,   nil,   nil,    20,    22,    23,    24,    25,
    26,    21,    18,    19,   nil,   nil,    13,   nil,    14,   nil,
    15,   nil,    16,   nil,    17,   nil,   nil,    20,    22,    23,
    24,    25,    26,    21,    18,    19,   nil,   nil,    13,   nil,
    14,   nil,    15,   nil,    16,   nil,    17,   nil,   nil,    20,
    22,    23,    24,    25,    26,    21,    18,    19,   nil,   nil,
    13,   nil,    14,   nil,    15,   nil,    16,   nil,    17,    42,
   nil,    20,    54,    38,    53,    55,    56,    57,   nil,    13,
   nil,    14,   nil,    15,   nil,    16,   nil,    17,   nil,   nil,
    20,    22,    23,    24,    25,    26,    21,    18,    19,   nil,
   nil,    13,   nil,    14,   nil,    15,   nil,    16,   nil,    17,
   nil,   nil,    20,    63,    64,    65,    61,    81,    62,    76,
    78,    79,   nil,    66,    67,    68,    69,    70,    71,    72,
    73,    74,    75,    77,    80,   122,   nil,   nil,    54,   nil,
    53,    55,    56,    57,   nil,    13,   nil,    14,   nil,    15,
   nil,    16,   nil,    17,   145,   nil,    20,    54,   133,    53,
    55,    56,    57,   nil,    13,   nil,    14,   nil,    15,   nil,
    16,   nil,    17,   145,   nil,    20,    54,   133,    53,    55,
    56,    57,   nil,    13,   nil,    14,   nil,    15,   nil,    16,
   nil,    17,   145,   nil,    20,    54,   133,    53,    55,    56,
    57,   nil,    13,   nil,    14,   nil,    15,   nil,    16,   nil,
    17,   145,   nil,    20,    54,   133,    53,    55,    56,    57,
   nil,    13,   nil,    14,   nil,    15,   nil,    16,   nil,    17,
   nil,   nil,    20,   135,   136,    54,   133,    53,    55,    56,
    57,   nil,    13,   nil,    14,   nil,    15,   nil,    16,   nil,
    17,   nil,   nil,    20,   135,   136,    54,   133,    53,    55,
    56,    57,   nil,    13,   nil,    14,   nil,    15,   nil,    16,
   nil,    17,   nil,   nil,    20,   135,   136,    54,   133,    53,
    55,    56,    57,   nil,    13,   nil,    14,   nil,    15,   nil,
    16,   nil,    17,    95,   nil,    20,    54,    91,    53,    55,
    56,    57,   145,   nil,   nil,    54,   133,    53,    55,    56,
    57,   158,   nil,   nil,    54,   nil,    53,    55,    56,    57,
   165,   135,   136,    54,   133,    53,    55,    56,    57,   145,
   nil,   nil,    54,   133,    53,    55,    56,    57,   172,   135,
   136,    54,   133,    53,    55,    56,    57,   174,   135,   136,
    54,   133,    53,    55,    56,    57,   178,   135,   136,    54,
   133,    53,    55,    56,    57,   135,   136,    54,   133,    53,
    55,    56,    57,   135,   136,    54,   133,    53,    55,    56,
    57,   135,   136,    54,   133,    53,    55,    56,    57,    22,
    23,    24,    25,    26,    21 ]

racc_action_check = [
    38,    38,    38,    38,    38,    38,    38,    38,    38,     1,
    38,    38,    38,    38,    38,    38,    38,    38,    38,    38,
    29,    38,    38,    59,    59,    59,    59,    59,    59,    59,
    59,    59,    31,    59,    59,    59,    59,    59,    59,    59,
    59,    59,    59,    59,    59,    59,    61,    61,    61,    61,
    61,    61,    61,    61,    61,    32,    61,    61,    61,    61,
    61,    61,    61,    61,    61,    61,    61,    61,    61,    91,
    91,    91,    91,    91,    91,    91,    91,    91,    33,    91,
    91,    91,    91,    91,    91,    91,    91,    91,    91,    34,
    91,    91,    97,    97,    97,    97,    97,    97,    97,    97,
    97,    35,    97,    97,    97,    97,    97,    97,    97,    97,
    97,    97,    37,    97,    97,   155,   155,   155,   155,   155,
   155,   155,   155,   155,    41,   155,   155,   155,   155,   155,
   155,   155,   155,   155,   155,    43,   155,   155,     0,     0,
     0,     0,     0,     0,     0,     0,   165,   165,     0,    58,
     0,    90,     0,    94,     0,   100,     0,   125,   162,     0,
     2,     2,     2,     2,     2,     2,     2,     2,   164,   172,
     2,   nil,     2,   nil,     2,   nil,     2,   nil,     2,   nil,
   nil,     2,    13,    13,    13,    13,    13,    13,    13,    13,
   nil,   nil,    13,   nil,    13,   nil,    13,   nil,    13,   nil,
    13,   nil,   nil,    13,    14,    14,    14,    14,    14,    14,
    14,    14,   nil,   nil,    14,   nil,    14,   nil,    14,   nil,
    14,   nil,    14,   nil,   nil,    14,    15,    15,    15,    15,
    15,    15,    15,    15,   nil,   nil,    15,   nil,    15,   nil,
    15,   nil,    15,   nil,    15,   nil,   nil,    15,    16,    16,
    16,    16,    16,    16,    16,    16,   nil,   nil,    16,   nil,
    16,   nil,    16,   nil,    16,   nil,    16,   nil,   nil,    16,
    17,    17,    17,    17,    17,    17,    17,    17,   nil,   nil,
    17,   nil,    17,   nil,    17,   nil,    17,   nil,    17,    18,
   nil,    17,    18,    18,    18,    18,    18,    18,   nil,    18,
   nil,    18,   nil,    18,   nil,    18,   nil,    18,   nil,   nil,
    18,    19,    19,    19,    19,    19,    19,    19,    19,   nil,
   nil,    19,   nil,    19,   nil,    19,   nil,    19,   nil,    19,
   nil,   nil,    19,    20,    20,    20,    20,    20,    20,    20,
    20,    20,   nil,    20,    20,    20,    20,    20,    20,    20,
    20,    20,    20,    20,    20,    39,   nil,   nil,    39,   nil,
    39,    39,    39,    39,   nil,    39,   nil,    39,   nil,    39,
   nil,    39,   nil,    39,    44,   nil,    39,    44,    44,    44,
    44,    44,    44,   nil,    44,   nil,    44,   nil,    44,   nil,
    44,   nil,    44,    45,   nil,    44,    45,    45,    45,    45,
    45,    45,   nil,    45,   nil,    45,   nil,    45,   nil,    45,
   nil,    45,   138,   nil,    45,   138,   138,   138,   138,   138,
   138,   nil,   138,   nil,   138,   nil,   138,   nil,   138,   nil,
   138,   146,   nil,   138,   146,   146,   146,   146,   146,   146,
   nil,   146,   nil,   146,   nil,   146,   nil,   146,   nil,   146,
   nil,   nil,   146,    42,    42,    42,    42,    42,    42,    42,
    42,   nil,    42,   nil,    42,   nil,    42,   nil,    42,   nil,
    42,   nil,   nil,    42,   122,   122,   122,   122,   122,   122,
   122,   122,   nil,   122,   nil,   122,   nil,   122,   nil,   122,
   nil,   122,   nil,   nil,   122,   127,   127,   127,   127,   127,
   127,   127,   127,   nil,   127,   nil,   127,   nil,   127,   nil,
   127,   nil,   127,    36,   nil,   127,    36,    36,    36,    36,
    36,    36,    52,   nil,   nil,    52,    52,    52,    52,    52,
    52,    92,   nil,   nil,    92,   nil,    92,    92,    92,    92,
   126,   126,   126,   126,   126,   126,   126,   126,   126,   142,
   nil,   nil,   142,   142,   142,   142,   142,   142,   159,   159,
   159,   159,   159,   159,   159,   159,   159,   163,   163,   163,
   163,   163,   163,   163,   163,   163,   171,   171,   171,   171,
   171,   171,   171,   171,   171,    95,    95,    95,    95,    95,
    95,    95,    95,   158,   158,   158,   158,   158,   158,   158,
   158,   168,   168,   168,   168,   168,   168,   168,   168,    27,
    27,    27,    27,    27,    27 ]

racc_action_pointer = [
   135,     9,   157,   nil,   nil,   nil,   nil,   nil,   nil,   nil,
   nil,   nil,   nil,   179,   201,   223,   245,   267,   286,   308,
   330,   nil,   nil,   nil,   nil,   nil,   nil,   606,   nil,    20,
   nil,    18,    39,    60,    69,    79,   510,    89,    -3,   352,
   nil,   120,   449,   130,   371,   390,   nil,   nil,   nil,   nil,
   nil,   nil,   519,   nil,   nil,   nil,   nil,   nil,   138,    20,
   nil,    43,   nil,   nil,   nil,   nil,   nil,   nil,   nil,   nil,
   nil,   nil,   nil,   nil,   nil,   nil,   nil,   nil,   nil,   nil,
   nil,   nil,   nil,   nil,   nil,   nil,   nil,   nil,   nil,   nil,
   128,    66,   528,   nil,   148,   581,   nil,    89,   nil,   nil,
   149,   nil,   nil,   nil,   nil,   nil,   nil,   nil,   nil,   nil,
   nil,   nil,   nil,   nil,   nil,   nil,   nil,   nil,   nil,   nil,
   nil,   nil,   470,   nil,   nil,   154,   537,   491,   nil,   nil,
   nil,   nil,   nil,   nil,   nil,   nil,   nil,   nil,   409,   nil,
   nil,   nil,   546,   nil,   nil,   nil,   428,   nil,   nil,   nil,
   nil,   nil,   nil,   nil,   nil,   112,   nil,   nil,   589,   555,
   nil,   nil,   155,   564,   164,   142,   nil,   nil,   597,   nil,
   nil,   573,   164,   nil,   nil,   nil,   nil,   nil,   nil ]

racc_action_default = [
  -138,  -138,    -1,    -3,    -4,    -5,    -6,    -7,    -8,    -9,
   -10,   -11,   -12,  -138,  -138,  -138,  -138,  -138,  -138,  -138,
  -138,  -103,  -104,  -105,  -106,  -107,  -108,  -111,  -110,  -138,
    -2,  -138,  -138,  -138,  -138,  -138,  -138,  -138,  -138,   -27,
   -26,   -35,  -138,   -58,   -41,   -40,   -47,   -48,   -49,   -50,
   -51,   -52,   -63,   -66,   -67,   -68,   -69,   -70,  -138,  -138,
  -112,  -138,  -116,  -117,  -118,  -119,  -120,  -121,  -122,  -123,
  -124,  -125,  -126,  -127,  -128,  -129,  -130,  -131,  -132,  -133,
  -134,  -135,  -137,  -109,   179,   -13,   -14,   -15,   -16,   -17,
  -138,  -138,   -23,   -22,   -33,  -138,   -19,   -24,   -79,   -80,
  -138,   -82,   -83,   -84,   -85,   -86,   -87,   -88,   -89,   -90,
   -91,   -92,   -93,   -94,   -95,   -96,   -97,   -98,   -99,  -100,
   -25,   -35,  -138,   -58,   -28,  -138,   -59,   -42,   -46,   -55,
   -56,   -65,   -71,   -72,   -75,   -76,   -77,   -31,   -38,   -44,
   -53,   -54,   -57,   -61,   -73,   -74,   -39,   -62,  -101,  -102,
  -136,  -113,  -114,  -115,   -18,   -20,   -21,   -33,  -138,  -138,
   -78,   -81,  -138,   -59,   -36,   -37,   -64,   -45,   -59,   -43,
   -60,  -138,   -34,   -36,   -37,   -29,   -30,   -32,   -34 ]

racc_goto_table = [
   126,    44,   125,    43,   144,   144,   160,    93,    97,    52,
   166,    82,   144,    40,    41,    39,   138,   146,   169,    30,
    36,    94,    44,     1,   123,   129,   169,    52,    90,    37,
    52,   167,   147,    92,   120,   121,    31,    32,    33,    34,
    35,   170,    58,   166,    59,    83,   170,   166,   151,   nil,
   150,   nil,   166,   159,     4,   166,     4,   nil,   nil,   nil,
   nil,   155,   nil,   156,   160,   nil,   nil,     4,     4,     4,
     4,     4,   nil,     4,     5,   nil,     5,   157,   nil,   nil,
   163,   nil,   162,    52,   nil,   168,   nil,     5,     5,     5,
     5,     5,   nil,     5,   nil,   nil,   nil,   nil,   144,   nil,
   nil,   nil,   144,   nil,   nil,   129,   144,   144,   nil,     6,
   129,     6,   nil,   nil,   nil,   nil,   171,     7,   nil,     7,
   nil,   nil,     6,     6,     6,     6,     6,     8,     6,     8,
     7,     7,     7,     7,     7,    11,     7,    11,   nil,   nil,
     8,     8,     8,     8,     8,   nil,     8,   nil,    11,    11,
    11,    11,    11,   nil,    11 ]

racc_goto_check = [
    22,    24,    21,    23,    36,    36,    37,    18,    16,    34,
    35,    41,    36,    19,    20,    17,    25,    25,    28,     3,
    13,    23,    24,     1,    23,    24,    28,    34,    14,    15,
    34,    29,    32,    17,    19,    20,     1,     1,     1,     1,
     1,    33,     1,    35,    38,    39,    33,    35,    42,   nil,
    41,   nil,    35,    22,     4,    35,     4,   nil,   nil,   nil,
   nil,    16,   nil,    18,    37,   nil,   nil,     4,     4,     4,
     4,     4,   nil,     4,     5,   nil,     5,    23,   nil,   nil,
    22,   nil,    21,    34,   nil,    22,   nil,     5,     5,     5,
     5,     5,   nil,     5,   nil,   nil,   nil,   nil,    36,   nil,
   nil,   nil,    36,   nil,   nil,    24,    36,    36,   nil,     6,
    24,     6,   nil,   nil,   nil,   nil,    22,     7,   nil,     7,
   nil,   nil,     6,     6,     6,     6,     6,     8,     6,     8,
     7,     7,     7,     7,     7,    11,     7,    11,   nil,   nil,
     8,     8,     8,     8,     8,   nil,     8,   nil,    11,    11,
    11,    11,    11,   nil,    11 ]

racc_goto_pointer = [
   nil,    23,   nil,    17,    54,    74,   109,   117,   127,   nil,
   nil,   135,   nil,     2,    -8,    11,   -30,    -3,   -29,    -5,
    -4,   -40,   -42,   -15,   -17,   -28,   nil,   nil,  -120,   -96,
   nil,   nil,   -20,  -101,    -9,  -116,   -40,   -91,    24,    18,
   nil,    -9,   -13 ]

racc_goto_default = [
   nil,   nil,     2,     3,    46,    47,    48,    49,    50,     9,
    10,    51,    12,   nil,   nil,   nil,   nil,   nil,   nil,   nil,
   nil,   nil,   nil,   nil,   140,   nil,    45,   127,   139,   128,
   141,   130,   142,   143,   132,   131,   134,    98,   nil,    28,
    27,   nil,    60 ]

racc_reduce_table = [
  0, 0, :racc_error,
  1, 27, :_reduce_none,
  2, 28, :_reduce_2,
  1, 28, :_reduce_3,
  1, 29, :_reduce_none,
  1, 29, :_reduce_none,
  1, 29, :_reduce_none,
  1, 29, :_reduce_none,
  1, 29, :_reduce_none,
  1, 29, :_reduce_none,
  1, 29, :_reduce_none,
  1, 29, :_reduce_none,
  1, 29, :_reduce_none,
  3, 30, :_reduce_13,
  3, 31, :_reduce_14,
  3, 32, :_reduce_15,
  3, 33, :_reduce_16,
  3, 34, :_reduce_17,
  4, 35, :_reduce_18,
  3, 35, :_reduce_19,
  2, 40, :_reduce_20,
  2, 40, :_reduce_21,
  1, 40, :_reduce_22,
  1, 40, :_reduce_23,
  2, 41, :_reduce_24,
  2, 41, :_reduce_25,
  1, 41, :_reduce_26,
  1, 41, :_reduce_27,
  2, 39, :_reduce_none,
  4, 39, :_reduce_29,
  4, 39, :_reduce_30,
  2, 43, :_reduce_31,
  4, 43, :_reduce_32,
  1, 44, :_reduce_33,
  3, 44, :_reduce_34,
  1, 45, :_reduce_none,
  3, 45, :_reduce_36,
  3, 45, :_reduce_37,
  2, 46, :_reduce_38,
  2, 46, :_reduce_39,
  1, 46, :_reduce_40,
  1, 46, :_reduce_41,
  1, 47, :_reduce_none,
  2, 51, :_reduce_43,
  1, 51, :_reduce_44,
  2, 53, :_reduce_45,
  1, 53, :_reduce_46,
  1, 50, :_reduce_none,
  1, 50, :_reduce_none,
  1, 50, :_reduce_none,
  1, 50, :_reduce_none,
  1, 50, :_reduce_none,
  1, 50, :_reduce_none,
  1, 54, :_reduce_none,
  1, 54, :_reduce_none,
  1, 55, :_reduce_none,
  1, 55, :_reduce_none,
  1, 56, :_reduce_57,
  1, 52, :_reduce_58,
  1, 57, :_reduce_59,
  2, 58, :_reduce_60,
  1, 58, :_reduce_none,
  2, 49, :_reduce_62,
  1, 49, :_reduce_none,
  2, 48, :_reduce_64,
  1, 48, :_reduce_none,
  1, 60, :_reduce_none,
  1, 60, :_reduce_none,
  1, 60, :_reduce_none,
  1, 60, :_reduce_none,
  1, 60, :_reduce_none,
  1, 62, :_reduce_none,
  1, 62, :_reduce_none,
  1, 59, :_reduce_none,
  1, 59, :_reduce_none,
  1, 61, :_reduce_none,
  1, 61, :_reduce_none,
  1, 61, :_reduce_none,
  2, 42, :_reduce_78,
  1, 42, :_reduce_none,
  1, 63, :_reduce_none,
  2, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  1, 63, :_reduce_none,
  3, 36, :_reduce_101,
  3, 37, :_reduce_102,
  1, 65, :_reduce_none,
  1, 65, :_reduce_none,
  1, 65, :_reduce_none,
  1, 65, :_reduce_none,
  1, 65, :_reduce_none,
  1, 65, :_reduce_none,
  2, 66, :_reduce_109,
  1, 66, :_reduce_none,
  1, 38, :_reduce_111,
  1, 67, :_reduce_none,
  2, 67, :_reduce_113,
  2, 67, :_reduce_114,
  2, 67, :_reduce_115,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  1, 68, :_reduce_none,
  2, 64, :_reduce_136,
  1, 64, :_reduce_none ]

racc_reduce_n = 138

racc_shift_n = 179

racc_token_table = {
  false => 0,
  :error => 1,
  :EX_LOW => 2,
  :QUOTE => 3,
  :BAR => 4,
  :SLASH => 5,
  :BACK_SLASH => 6,
  :URL => 7,
  :OTHER => 8,
  :REF_OPEN => 9,
  :FOOTNOTE_OPEN => 10,
  :FOOTNOTE_CLOSE => 11,
  :EX_HIGH => 12,
  :EM_OPEN => 13,
  :EM_CLOSE => 14,
  :CODE_OPEN => 15,
  :CODE_CLOSE => 16,
  :VAR_OPEN => 17,
  :VAR_CLOSE => 18,
  :KBD_OPEN => 19,
  :KBD_CLOSE => 20,
  :INDEX_OPEN => 21,
  :INDEX_CLOSE => 22,
  :REF_CLOSE => 23,
  :VERB_OPEN => 24,
  :VERB_CLOSE => 25 }

racc_nt_base = 26

racc_use_result_var = true

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",
  "EX_LOW",
  "QUOTE",
  "BAR",
  "SLASH",
  "BACK_SLASH",
  "URL",
  "OTHER",
  "REF_OPEN",
  "FOOTNOTE_OPEN",
  "FOOTNOTE_CLOSE",
  "EX_HIGH",
  "EM_OPEN",
  "EM_CLOSE",
  "CODE_OPEN",
  "CODE_CLOSE",
  "VAR_OPEN",
  "VAR_CLOSE",
  "KBD_OPEN",
  "KBD_CLOSE",
  "INDEX_OPEN",
  "INDEX_CLOSE",
  "REF_CLOSE",
  "VERB_OPEN",
  "VERB_CLOSE",
  "$start",
  "content",
  "elements",
  "element",
  "emphasis",
  "code",
  "var",
  "keyboard",
  "index",
  "reference",
  "footnote",
  "verb",
  "normal_str_ele",
  "substitute",
  "ref_label",
  "ref_label2",
  "ref_url_strings",
  "filename",
  "element_label",
  "element_label2",
  "ref_subst_content",
  "ref_subst_content_q",
  "ref_subst_strings_q",
  "ref_subst_strings_first",
  "ref_subst_ele2",
  "ref_subst_eles",
  "ref_subst_str_ele_first",
  "ref_subst_eles_q",
  "ref_subst_ele",
  "ref_subst_ele_q",
  "ref_subst_str_ele",
  "ref_subst_str_ele_q",
  "ref_subst_strings",
  "ref_subst_string3",
  "ref_subst_string",
  "ref_subst_string_q",
  "ref_subst_string2",
  "ref_url_string",
  "verb_strings",
  "normal_string",
  "normal_strings",
  "verb_string",
  "verb_normal_string" ]

Racc_debug_parser = false

##### State transition tables end #####

# reduce 0 omitted

# reduce 1 omitted

def _reduce_2(val, _values, result)
 result.append val[1]
    result
end

def _reduce_3(val, _values, result)
 result = val[0]
    result
end

# reduce 4 omitted

# reduce 5 omitted

# reduce 6 omitted

# reduce 7 omitted

# reduce 8 omitted

# reduce 9 omitted

# reduce 10 omitted

# reduce 11 omitted

# reduce 12 omitted

def _reduce_13(val, _values, result)
      content = val[1]
      result = inline "<em>#{content}</em>", content

    result
end

def _reduce_14(val, _values, result)
      content = val[1]
      result = inline "<code>#{content}</code>", content

    result
end

def _reduce_15(val, _values, result)
      content = val[1]
      result = inline "+#{content}+", content

    result
end

def _reduce_16(val, _values, result)
      content = val[1]
      result = inline "<tt>#{content}</tt>", content

    result
end

def _reduce_17(val, _values, result)
      label = val[1]
      @block_parser.add_label label.reference
      result = "<span id=\"label-#{label}\">#{label}</span>"

    result
end

def _reduce_18(val, _values, result)
      result = "{#{val[1]}}[#{val[2].join}]"

    result
end

def _reduce_19(val, _values, result)
      scheme, inline = val[1]

      result = "{#{inline}}[#{scheme}#{inline.reference}]"

    result
end

def _reduce_20(val, _values, result)
      result = [nil, inline(val[1])]

    result
end

def _reduce_21(val, _values, result)
      result = [
        'rdoc-label:',
        inline("#{val[0].reference}/#{val[1].reference}")
      ]

    result
end

def _reduce_22(val, _values, result)
      result = ['rdoc-label:', val[0].reference]

    result
end

def _reduce_23(val, _values, result)
      result = ['rdoc-label:', "#{val[0].reference}/"]

    result
end

def _reduce_24(val, _values, result)
      result = [nil, inline(val[1])]

    result
end

def _reduce_25(val, _values, result)
      result = [
        'rdoc-label:',
        inline("#{val[0].reference}/#{val[1].reference}")
      ]

    result
end

def _reduce_26(val, _values, result)
      result = ['rdoc-label:', val[0]]

    result
end

def _reduce_27(val, _values, result)
      ref = val[0].reference
      result = ['rdoc-label:', inline(ref, "#{ref}/")]

    result
end

# reduce 28 omitted

def _reduce_29(val, _values, result)
 result = val[1]
    result
end

def _reduce_30(val, _values, result)
 result = val[1]
    result
end

def _reduce_31(val, _values, result)
      result = inline val[0]

    result
end

def _reduce_32(val, _values, result)
      result = inline "\"#{val[1]}\""

    result
end

def _reduce_33(val, _values, result)
      result = inline val[0]

    result
end

def _reduce_34(val, _values, result)
      result = inline "\"#{val[1]}\""

    result
end

# reduce 35 omitted

def _reduce_36(val, _values, result)
 result = val[1]
    result
end

def _reduce_37(val, _values, result)
 result = inline val[1]
    result
end

def _reduce_38(val, _values, result)
      result = val[0].append val[1]

    result
end

def _reduce_39(val, _values, result)
      result = val[0].append val[1]

    result
end

def _reduce_40(val, _values, result)
      result = val[0]

    result
end

def _reduce_41(val, _values, result)
      result = inline val[0]

    result
end

# reduce 42 omitted

def _reduce_43(val, _values, result)
      result = val[0].append val[1]

    result
end

def _reduce_44(val, _values, result)
      result = inline val[0]

    result
end

def _reduce_45(val, _values, result)
      result = val[0].append val[1]

    result
end

def _reduce_46(val, _values, result)
      result = val[0]

    result
end

# reduce 47 omitted

# reduce 48 omitted

# reduce 49 omitted

# reduce 50 omitted

# reduce 51 omitted

# reduce 52 omitted

# reduce 53 omitted

# reduce 54 omitted

# reduce 55 omitted

# reduce 56 omitted

def _reduce_57(val, _values, result)
      result = val[0]

    result
end

def _reduce_58(val, _values, result)
      result = inline val[0]

    result
end

def _reduce_59(val, _values, result)
      result = inline val[0]

    result
end

def _reduce_60(val, _values, result)
 result << val[1]
    result
end

# reduce 61 omitted

def _reduce_62(val, _values, result)
      result << val[1]

    result
end

# reduce 63 omitted

def _reduce_64(val, _values, result)
      result << val[1]

    result
end

# reduce 65 omitted

# reduce 66 omitted

# reduce 67 omitted

# reduce 68 omitted

# reduce 69 omitted

# reduce 70 omitted

# reduce 71 omitted

# reduce 72 omitted

# reduce 73 omitted

# reduce 74 omitted

# reduce 75 omitted

# reduce 76 omitted

# reduce 77 omitted

def _reduce_78(val, _values, result)
 result << val[1]
    result
end

# reduce 79 omitted

# reduce 80 omitted

# reduce 81 omitted

# reduce 82 omitted

# reduce 83 omitted

# reduce 84 omitted

# reduce 85 omitted

# reduce 86 omitted

# reduce 87 omitted

# reduce 88 omitted

# reduce 89 omitted

# reduce 90 omitted

# reduce 91 omitted

# reduce 92 omitted

# reduce 93 omitted

# reduce 94 omitted

# reduce 95 omitted

# reduce 96 omitted

# reduce 97 omitted

# reduce 98 omitted

# reduce 99 omitted

# reduce 100 omitted

def _reduce_101(val, _values, result)
      index = @block_parser.add_footnote val[1].rdoc
      result = "{*#{index}}[rdoc-label:foottext-#{index}:footmark-#{index}]"

    result
end

def _reduce_102(val, _values, result)
      result = inline "<tt>#{val[1]}</tt>", val[1]

    result
end

# reduce 103 omitted

# reduce 104 omitted

# reduce 105 omitted

# reduce 106 omitted

# reduce 107 omitted

# reduce 108 omitted

def _reduce_109(val, _values, result)
 result << val[1]
    result
end

# reduce 110 omitted

def _reduce_111(val, _values, result)
      result = inline val[0]

    result
end

# reduce 112 omitted

def _reduce_113(val, _values, result)
 result = val[1]
    result
end

def _reduce_114(val, _values, result)
 result = val[1]
    result
end

def _reduce_115(val, _values, result)
 result = val[1]
    result
end

# reduce 116 omitted

# reduce 117 omitted

# reduce 118 omitted

# reduce 119 omitted

# reduce 120 omitted

# reduce 121 omitted

# reduce 122 omitted

# reduce 123 omitted

# reduce 124 omitted

# reduce 125 omitted

# reduce 126 omitted

# reduce 127 omitted

# reduce 128 omitted

# reduce 129 omitted

# reduce 130 omitted

# reduce 131 omitted

# reduce 132 omitted

# reduce 133 omitted

# reduce 134 omitted

# reduce 135 omitted

def _reduce_136(val, _values, result)
 result << val[1]
    result
end

# reduce 137 omitted

def _reduce_none(val, _values, result)
  val[0]
end

end   # class InlineParser

end
# frozen_string_literal: true
#
# DO NOT MODIFY!!!!
# This file is automatically generated by Racc 1.5.2
# from Racc grammar file "".
#

require 'racc/parser.rb'

class RDoc::RD

##
# RD format parser for headings, paragraphs, lists, verbatim sections that
# exist as blocks.

class BlockParser < Racc::Parser


# :stopdoc:

TMPFILE = ["rdtmp", $$, 0]

MARK_TO_LEVEL = {
  '='    => 1,
  '=='   => 2,
  '==='  => 3,
  '====' => 4,
  '+'    => 5,
  '++'   => 6,
}

# :startdoc:

##
# Footnotes for this document

attr_reader :footnotes

##
# Labels for items in this document

attr_reader :labels

##
# Path to find included files in

attr_accessor :include_path

##
# Creates a new RDoc::RD::BlockParser.  Use #parse to parse an rd-format
# document.

def initialize
  @inline_parser = RDoc::RD::InlineParser.new self
  @include_path = []

  # for testing
  @footnotes = []
  @labels    = {}
end

##
# Parses +src+ and returns an RDoc::Markup::Document.

def parse src
  @src = src
  @src.push false

  @footnotes = []
  @labels    = {}

  # @i: index(line no.) of src
  @i = 0

  # stack for current indentation
  @indent_stack = []

  # how indented.
  @current_indent = @indent_stack.join("")

  # RDoc::RD::BlockParser for tmp src
  @subparser = nil

  # which part is in now
  @in_part = nil
  @part_content = []

  @in_verbatim = false

  @yydebug = true

  document = do_parse

  unless @footnotes.empty? then
    blankline = document.parts.pop

    document.parts << RDoc::Markup::Rule.new(1)
    document.parts.concat @footnotes

    document.parts.push blankline
  end

  document
end

##
# Returns the next token from the document

def next_token # :nodoc:
  # preprocessing
  # if it is not in RD part
  # => method
  while @in_part != "rd"
    line = @src[@i]
    @i += 1 # next line

    case line
    # src end
    when false
      return [false, false]
    # RD part begin
    when /^=begin\s*(?:\bRD\b.*)?\s*$/
      if @in_part # if in non-RD part
        @part_content.push(line)
      else
        @in_part = "rd"
        return [:WHITELINE, "=begin\n"] # <= for textblockand
      end
    # non-RD part begin
    when /^=begin\s+(\w+)/
      part = $1
      if @in_part # if in non-RD part
        @part_content.push(line)
      else
        @in_part = part if @tree.filter[part] # if filter exists
#  p "BEGIN_PART: #{@in_part}" # DEBUG
      end
    # non-RD part end
    when /^=end/
      if @in_part # if in non-RD part
#  p "END_PART: #{@in_part}" # DEBUG
        # make Part-in object
        part = RDoc::RD::Part.new(@part_content.join(""), @tree, "r")
        @part_content.clear
        # call filter, part_out is output(Part object)
        part_out = @tree.filter[@in_part].call(part)

        if @tree.filter[@in_part].mode == :rd # if output is RD formatted
          subtree = parse_subtree(part_out.to_a)
        else # if output is target formatted
          basename = TMPFILE.join('.')
          TMPFILE[-1] += 1
          tmpfile = open(@tree.tmp_dir + "/" + basename + ".#{@in_part}", "w")
          tmpfile.print(part_out)
          tmpfile.close
          subtree = parse_subtree(["=begin\n", "<<< #{basename}\n", "=end\n"])
        end
        @in_part = nil
        return [:SUBTREE, subtree]
      end
    else
      if @in_part # if in non-RD part
        @part_content.push(line)
      end
    end
  end

  @current_indent = @indent_stack.join("")
  line = @src[@i]
  case line
  when false
    if_current_indent_equal("") do
      [false, false]
    end
  when /^=end/
    if_current_indent_equal("") do
      @in_part = nil
      [:WHITELINE, "=end"] # MUST CHANGE??
    end
  when /^\s*$/
    @i += 1 # next line
    return [:WHITELINE, ':WHITELINE']
  when /^\#/  # comment line
    @i += 1 # next line
    self.next_token()
  when /^(={1,4})(?!=)\s*(?=\S)/, /^(\+{1,2})(?!\+)\s*(?=\S)/
    rest = $'                    # '
    rest.strip!
    mark = $1
    if_current_indent_equal("") do
      return [:HEADLINE, [MARK_TO_LEVEL[mark], rest]]
    end
  when /^<<<\s*(\S+)/
    file = $1
    if_current_indent_equal("") do
      suffix = file[-3 .. -1]
      if suffix == ".rd" or suffix == ".rb"
        subtree = parse_subtree(get_included(file))
        [:SUBTREE, subtree]
      else
        [:INCLUDE, file]
      end
    end
  when /^(\s*)\*(\s*)/
    rest = $'                   # '
    newIndent = $2
    if_current_indent_equal($1) do
      if @in_verbatim
        [:STRINGLINE, line]
      else
        @indent_stack.push("\s" + newIndent)
        [:ITEMLISTLINE, rest]
      end
    end
  when /^(\s*)(\(\d+\))(\s*)/
    rest = $'                     # '
    mark = $2
    newIndent = $3
    if_current_indent_equal($1) do
      if @in_verbatim
        [:STRINGLINE, line]
      else
        @indent_stack.push("\s" * mark.size + newIndent)
        [:ENUMLISTLINE, rest]
      end
    end
  when /^(\s*):(\s*)/
    rest = $'                    # '
    newIndent = $2
    if_current_indent_equal($1) do
      if @in_verbatim
        [:STRINGLINE, line]
      else
        @indent_stack.push("\s#{$2}")
        [:DESCLISTLINE, rest]
      end
    end
  when /^(\s*)---(?!-|\s*$)/
    indent = $1
    rest = $'
    /\s*/ === rest
    term = $'
    new_indent = $&
    if_current_indent_equal(indent) do
      if @in_verbatim
        [:STRINGLINE, line]
      else
        @indent_stack.push("\s\s\s" + new_indent)
        [:METHODLISTLINE, term]
      end
    end
  when /^(\s*)/
    if_current_indent_equal($1) do
      [:STRINGLINE, line]
    end
  else
    raise "[BUG] parsing error may occurred."
  end
end

##
# Yields to the given block if +indent+ matches the current indent, otherwise
# an indentation token is processed.

def if_current_indent_equal(indent)
  indent = indent.sub(/\t/, "\s" * 8)
  if @current_indent == indent
    @i += 1 # next line
    yield
  elsif indent.index(@current_indent) == 0
    @indent_stack.push(indent[@current_indent.size .. -1])
    [:INDENT, ":INDENT"]
  else
    @indent_stack.pop
    [:DEDENT, ":DEDENT"]
  end
end
private :if_current_indent_equal

##
# Cuts off excess whitespace in +src+

def cut_off(src)
  ret = []
  whiteline_buf = []

  line = src.shift
  /^\s*/ =~ line

  indent = Regexp.quote($&)
  ret.push($')

  while line = src.shift
    if /^(\s*)$/ =~ line
      whiteline_buf.push(line)
    elsif /^#{indent}/ =~ line
      unless whiteline_buf.empty?
        ret.concat(whiteline_buf)
        whiteline_buf.clear
      end
      ret.push($')
    else
      raise "[BUG]: probably Parser Error while cutting off.\n"
    end
  end
  ret
end
private :cut_off

def set_term_to_element(parent, term)
#  parent.set_term_under_document_struct(term, @tree.document_struct)
  parent.set_term_without_document_struct(term)
end
private :set_term_to_element

##
# Raises a ParseError when invalid formatting is found

def on_error(et, ev, _values)
  prv, cur, nxt = format_line_num(@i, @i+1, @i+2)

  raise ParseError, <<Msg

RD syntax error: line #{@i+1}:
  #{prv}  |#{@src[@i-1].chomp}
  #{cur}=>|#{@src[@i].chomp}
  #{nxt}  |#{@src[@i+1].chomp}

Msg
end

##
# Current line number

def line_index
  @i
end

##
# Parses subtree +src+

def parse_subtree src
  @subparser ||= RDoc::RD::BlockParser.new

  @subparser.parse src
end
private :parse_subtree

##
# Retrieves the content for +file+ from the include_path

def get_included(file)
  included = []

  @include_path.each do |dir|
    file_name = File.join dir, file

    if File.exist? file_name then
      included = IO.readlines file_name
      break
    end
  end

  included
end
private :get_included

##
# Formats line numbers +line_numbers+ prettily

def format_line_num(*line_numbers)
  width = line_numbers.collect{|i| i.to_s.length }.max
  line_numbers.collect{|i| sprintf("%#{width}d", i) }
end
private :format_line_num

##
# Retrieves the content of +values+ as a single String

def content values
 values.map { |value| value.content }.join
end

##
# Creates a paragraph for +value+

def paragraph value
  content = cut_off(value).join(' ').rstrip
  contents = @inline_parser.parse content

  RDoc::Markup::Paragraph.new(*contents)
end

##
# Adds footnote +content+ to the document

def add_footnote content
  index = @footnotes.length / 2 + 1

  footmark_link = "{^#{index}}[rdoc-label:footmark-#{index}:foottext-#{index}]"

  @footnotes << RDoc::Markup::Paragraph.new(footmark_link, ' ', *content)
  @footnotes << RDoc::Markup::BlankLine.new

  index
end

##
# Adds label +label+ to the document

def add_label label
  @labels[label] = true

  label
end

# :stopdoc:

##### State transition tables begin ###

racc_action_table = [
    34,    35,    30,    33,    40,    34,    35,    30,    33,    40,
    65,    34,    35,    30,    33,    14,    73,    36,    38,    34,
    15,    88,    34,    35,    30,    33,    14,     9,    10,    11,
    12,    15,    34,    35,    30,    33,    14,     9,    10,    11,
    12,    15,    34,    35,    30,    33,    35,    47,    30,    54,
    33,    15,    34,    35,    30,    33,    54,    47,    14,    14,
    59,    15,    34,    35,    30,    33,    14,    73,    67,    76,
    77,    15,    34,    35,    30,    33,    14,    73,    54,    81,
    38,    15,    34,    35,    30,    33,    14,    73,    38,    40,
    83,    15,    34,    35,    30,    33,    14,    73,   nil,   nil,
   nil,    15,    34,    35,    30,    33,    14,    73,   nil,   nil,
   nil,    15,    34,    35,    30,    33,    14,    73,   nil,   nil,
   nil,    15,    34,    35,    30,    33,    14,    73,   nil,   nil,
   nil,    15,    34,    35,    30,    33,    14,    73,   nil,   nil,
   nil,    15,    34,    35,    30,    33,    14,    73,    61,    63,
   nil,    15,    14,    62,    60,    61,    63,    79,    61,    63,
    62,    87,   nil,    62,    34,    35,    30,    33 ]

racc_action_check = [
    41,    41,    41,    41,    41,    15,    15,    15,    15,    15,
    41,    86,    86,    86,    86,    86,    86,     1,    13,    22,
    86,    86,     0,     0,     0,     0,     0,     0,     0,     0,
     0,     0,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,    24,    24,    24,    24,    25,    24,    28,    30,
    31,    24,    27,    27,    27,    27,    33,    27,    34,    35,
    36,    27,    45,    45,    45,    45,    45,    45,    44,    49,
    51,    45,    46,    46,    46,    46,    46,    46,    54,    56,
    57,    46,    47,    47,    47,    47,    47,    47,    58,    62,
    66,    47,    68,    68,    68,    68,    68,    68,   nil,   nil,
   nil,    68,    74,    74,    74,    74,    74,    74,   nil,   nil,
   nil,    74,    75,    75,    75,    75,    75,    75,   nil,   nil,
   nil,    75,    78,    78,    78,    78,    78,    78,   nil,   nil,
   nil,    78,    79,    79,    79,    79,    79,    79,   nil,   nil,
   nil,    79,    85,    85,    85,    85,    85,    85,    39,    39,
   nil,    85,    52,    39,    39,    82,    82,    52,    64,    64,
    82,    82,   nil,    64,    20,    20,    20,    20 ]

racc_action_pointer = [
    19,    17,    29,   nil,   nil,   nil,   nil,   nil,   nil,   nil,
   nil,   nil,   nil,    11,   nil,     2,   nil,   nil,   nil,   nil,
   161,   nil,    16,   nil,    39,    42,   nil,    49,    43,   nil,
    41,    44,   nil,    48,    51,    52,    60,   nil,   nil,   141,
   nil,    -3,   nil,   nil,    55,    59,    69,    79,   nil,    56,
   nil,    57,   145,   nil,    70,   nil,    66,    73,    81,   nil,
   nil,   nil,    82,   nil,   151,   nil,    77,   nil,    89,   nil,
   nil,   nil,   nil,   nil,    99,   109,   nil,   nil,   119,   129,
   nil,   nil,   148,   nil,   nil,   139,     8,   nil,   nil ]

racc_action_default = [
    -2,   -73,    -1,    -4,    -5,    -6,    -7,    -8,    -9,   -10,
   -11,   -12,   -13,   -14,   -16,   -73,   -23,   -24,   -25,   -26,
   -27,   -31,   -32,   -34,   -72,   -36,   -38,   -72,   -40,   -42,
   -59,   -44,   -46,   -59,   -63,   -65,   -73,    -3,   -15,   -73,
   -22,   -73,   -30,   -33,   -73,   -69,   -70,   -71,   -37,   -73,
   -41,   -73,   -51,   -58,   -61,   -45,   -73,   -62,   -64,    89,
   -17,   -19,   -73,   -21,   -18,   -28,   -73,   -35,   -66,   -53,
   -54,   -55,   -56,   -57,   -67,   -68,   -39,   -43,   -49,   -73,
   -60,   -47,   -73,   -29,   -52,   -48,   -73,   -20,   -50 ]

racc_goto_table = [
     4,    39,     4,    68,    74,    75,     5,     6,     5,     6,
    44,    42,    51,    49,     3,    56,    37,    57,    58,     1,
     2,    66,    84,    41,    43,    48,    50,    64,    84,    84,
    45,    46,    42,    45,    46,    55,    85,    86,    80,    84,
    84,   nil,   nil,   nil,   nil,   nil,   nil,   nil,    82,   nil,
   nil,   nil,    78 ]

racc_goto_check = [
     4,    10,     4,    31,    31,    31,     5,     6,     5,     6,
    21,    12,    27,    21,     3,    27,     3,     9,     9,     1,
     2,    11,    32,    17,    19,    23,    26,    10,    32,    32,
     5,     6,    12,     5,     6,    29,    31,    31,    33,    32,
    32,   nil,   nil,   nil,   nil,   nil,   nil,   nil,    10,   nil,
   nil,   nil,     4 ]

racc_goto_pointer = [
   nil,    19,    20,    14,     0,     6,     7,   nil,   nil,   -17,
   -14,   -20,    -9,   nil,   nil,   nil,   nil,     8,   nil,     2,
   nil,   -14,   nil,     0,   nil,   nil,    -2,   -18,   nil,     4,
   nil,   -42,   -46,   -16 ]

racc_goto_default = [
   nil,   nil,   nil,   nil,    70,    71,    72,     7,     8,    13,
   nil,   nil,    21,    16,    17,    18,    19,    20,    22,    23,
    24,   nil,    25,    26,    27,    28,    29,   nil,    31,    32,
    52,   nil,    69,    53 ]

racc_reduce_table = [
  0, 0, :racc_error,
  1, 15, :_reduce_1,
  0, 15, :_reduce_2,
  2, 16, :_reduce_3,
  1, 16, :_reduce_4,
  1, 17, :_reduce_5,
  1, 17, :_reduce_6,
  1, 17, :_reduce_none,
  1, 17, :_reduce_8,
  1, 17, :_reduce_9,
  1, 17, :_reduce_10,
  1, 17, :_reduce_11,
  1, 21, :_reduce_12,
  1, 22, :_reduce_13,
  1, 18, :_reduce_14,
  2, 23, :_reduce_15,
  1, 23, :_reduce_16,
  3, 19, :_reduce_17,
  1, 25, :_reduce_18,
  2, 24, :_reduce_19,
  4, 24, :_reduce_20,
  2, 24, :_reduce_21,
  1, 24, :_reduce_22,
  1, 26, :_reduce_none,
  1, 26, :_reduce_none,
  1, 26, :_reduce_none,
  1, 26, :_reduce_none,
  1, 20, :_reduce_27,
  3, 20, :_reduce_28,
  4, 20, :_reduce_29,
  2, 31, :_reduce_30,
  1, 31, :_reduce_31,
  1, 27, :_reduce_32,
  2, 32, :_reduce_33,
  1, 32, :_reduce_34,
  3, 33, :_reduce_35,
  1, 28, :_reduce_36,
  2, 36, :_reduce_37,
  1, 36, :_reduce_38,
  3, 37, :_reduce_39,
  1, 29, :_reduce_40,
  2, 39, :_reduce_41,
  1, 39, :_reduce_42,
  3, 40, :_reduce_43,
  1, 30, :_reduce_44,
  2, 42, :_reduce_45,
  1, 42, :_reduce_46,
  3, 43, :_reduce_47,
  3, 41, :_reduce_48,
  2, 41, :_reduce_49,
  4, 41, :_reduce_50,
  1, 41, :_reduce_51,
  2, 45, :_reduce_52,
  1, 45, :_reduce_none,
  1, 46, :_reduce_54,
  1, 46, :_reduce_55,
  1, 46, :_reduce_none,
  1, 46, :_reduce_57,
  1, 44, :_reduce_none,
  0, 44, :_reduce_none,
  2, 47, :_reduce_none,
  1, 47, :_reduce_none,
  2, 34, :_reduce_62,
  1, 34, :_reduce_63,
  2, 38, :_reduce_64,
  1, 38, :_reduce_65,
  2, 35, :_reduce_66,
  2, 35, :_reduce_67,
  2, 35, :_reduce_68,
  1, 35, :_reduce_69,
  1, 35, :_reduce_none,
  1, 35, :_reduce_71,
  0, 35, :_reduce_72 ]

racc_reduce_n = 73

racc_shift_n = 89

racc_token_table = {
  false => 0,
  :error => 1,
  :DUMMY => 2,
  :ITEMLISTLINE => 3,
  :ENUMLISTLINE => 4,
  :DESCLISTLINE => 5,
  :METHODLISTLINE => 6,
  :STRINGLINE => 7,
  :WHITELINE => 8,
  :SUBTREE => 9,
  :HEADLINE => 10,
  :INCLUDE => 11,
  :INDENT => 12,
  :DEDENT => 13 }

racc_nt_base = 14

racc_use_result_var = true

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",
  "DUMMY",
  "ITEMLISTLINE",
  "ENUMLISTLINE",
  "DESCLISTLINE",
  "METHODLISTLINE",
  "STRINGLINE",
  "WHITELINE",
  "SUBTREE",
  "HEADLINE",
  "INCLUDE",
  "INDENT",
  "DEDENT",
  "$start",
  "document",
  "blocks",
  "block",
  "textblock",
  "verbatim",
  "lists",
  "headline",
  "include",
  "textblockcontent",
  "verbatimcontent",
  "verbatim_after_lists",
  "list",
  "itemlist",
  "enumlist",
  "desclist",
  "methodlist",
  "lists2",
  "itemlistitems",
  "itemlistitem",
  "first_textblock_in_itemlist",
  "other_blocks_in_list",
  "enumlistitems",
  "enumlistitem",
  "first_textblock_in_enumlist",
  "desclistitems",
  "desclistitem",
  "description_part",
  "methodlistitems",
  "methodlistitem",
  "whitelines",
  "blocks_in_list",
  "block_in_list",
  "whitelines2" ]

Racc_debug_parser = false

##### State transition tables end #####

# reduce 0 omitted

def _reduce_1(val, _values, result)
 result = RDoc::Markup::Document.new(*val[0])
    result
end

def _reduce_2(val, _values, result)
 raise ParseError, "file empty"
    result
end

def _reduce_3(val, _values, result)
 result = val[0].concat val[1]
    result
end

def _reduce_4(val, _values, result)
 result = val[0]
    result
end

def _reduce_5(val, _values, result)
 result = val
    result
end

def _reduce_6(val, _values, result)
 result = val
    result
end

# reduce 7 omitted

def _reduce_8(val, _values, result)
 result = val
    result
end

def _reduce_9(val, _values, result)
 result = val
    result
end

def _reduce_10(val, _values, result)
 result = [RDoc::Markup::BlankLine.new]
    result
end

def _reduce_11(val, _values, result)
 result = val[0].parts
    result
end

def _reduce_12(val, _values, result)
      # val[0] is like [level, title]
      title = @inline_parser.parse(val[0][1])
      result = RDoc::Markup::Heading.new(val[0][0], title)

    result
end

def _reduce_13(val, _values, result)
      result = RDoc::Markup::Include.new val[0], @include_path

    result
end

def _reduce_14(val, _values, result)
      # val[0] is Array of String
      result = paragraph val[0]

    result
end

def _reduce_15(val, _values, result)
 result << val[1].rstrip
    result
end

def _reduce_16(val, _values, result)
 result = [val[0].rstrip]
    result
end

def _reduce_17(val, _values, result)
      # val[1] is Array of String
      content = cut_off val[1]
      result = RDoc::Markup::Verbatim.new(*content)

      # imform to lexer.
      @in_verbatim = false

    result
end

def _reduce_18(val, _values, result)
      # val[0] is Array of String
      content = cut_off val[0]
      result = RDoc::Markup::Verbatim.new(*content)

      # imform to lexer.
      @in_verbatim = false

    result
end

def _reduce_19(val, _values, result)
      result << val[1]

    result
end

def _reduce_20(val, _values, result)
      result.concat val[2]

    result
end

def _reduce_21(val, _values, result)
      result << "\n"

    result
end

def _reduce_22(val, _values, result)
      result = val
      # inform to lexer.
      @in_verbatim = true

    result
end

# reduce 23 omitted

# reduce 24 omitted

# reduce 25 omitted

# reduce 26 omitted

def _reduce_27(val, _values, result)
      result = val[0]

    result
end

def _reduce_28(val, _values, result)
      result = val[1]

    result
end

def _reduce_29(val, _values, result)
      result = val[1].push(val[2])

    result
end

def _reduce_30(val, _values, result)
 result = val[0] << val[1]
    result
end

def _reduce_31(val, _values, result)
 result = [val[0]]
    result
end

def _reduce_32(val, _values, result)
      result = RDoc::Markup::List.new :BULLET, *val[0]

    result
end

def _reduce_33(val, _values, result)
 result.push(val[1])
    result
end

def _reduce_34(val, _values, result)
 result = val
    result
end

def _reduce_35(val, _values, result)
      result = RDoc::Markup::ListItem.new nil, val[0], *val[1]

    result
end

def _reduce_36(val, _values, result)
      result = RDoc::Markup::List.new :NUMBER, *val[0]

    result
end

def _reduce_37(val, _values, result)
 result.push(val[1])
    result
end

def _reduce_38(val, _values, result)
 result = val
    result
end

def _reduce_39(val, _values, result)
      result = RDoc::Markup::ListItem.new nil, val[0], *val[1]

    result
end

def _reduce_40(val, _values, result)
      result = RDoc::Markup::List.new :NOTE, *val[0]

    result
end

def _reduce_41(val, _values, result)
 result.push(val[1])
    result
end

def _reduce_42(val, _values, result)
 result = val
    result
end

def _reduce_43(val, _values, result)
      term = @inline_parser.parse val[0].strip

      result = RDoc::Markup::ListItem.new term, *val[1]

    result
end

def _reduce_44(val, _values, result)
      result = RDoc::Markup::List.new :LABEL, *val[0]

    result
end

def _reduce_45(val, _values, result)
 result.push(val[1])
    result
end

def _reduce_46(val, _values, result)
 result = val
    result
end

def _reduce_47(val, _values, result)
      result = RDoc::Markup::ListItem.new "<tt>#{val[0].strip}</tt>", *val[1]

    result
end

def _reduce_48(val, _values, result)
      result = [val[1]].concat(val[2])

    result
end

def _reduce_49(val, _values, result)
      result = [val[1]]

    result
end

def _reduce_50(val, _values, result)
      result = val[2]

    result
end

def _reduce_51(val, _values, result)
      result = []

    result
end

def _reduce_52(val, _values, result)
 result.concat val[1]
    result
end

# reduce 53 omitted

def _reduce_54(val, _values, result)
 result = val
    result
end

def _reduce_55(val, _values, result)
 result = val
    result
end

# reduce 56 omitted

def _reduce_57(val, _values, result)
 result = []
    result
end

# reduce 58 omitted

# reduce 59 omitted

# reduce 60 omitted

# reduce 61 omitted

def _reduce_62(val, _values, result)
      result = paragraph [val[0]].concat(val[1])

    result
end

def _reduce_63(val, _values, result)
      result = paragraph [val[0]]

    result
end

def _reduce_64(val, _values, result)
      result = paragraph [val[0]].concat(val[1])

    result
end

def _reduce_65(val, _values, result)
      result = paragraph [val[0]]

    result
end

def _reduce_66(val, _values, result)
      result = [val[0]].concat(val[1])

    result
end

def _reduce_67(val, _values, result)
 result.concat val[1]
    result
end

def _reduce_68(val, _values, result)
 result = val[1]
    result
end

def _reduce_69(val, _values, result)
 result = val
    result
end

# reduce 70 omitted

def _reduce_71(val, _values, result)
 result = []
    result
end

def _reduce_72(val, _values, result)
 result = []
    result
end

def _reduce_none(val, _values, result)
  val[0]
end

end   # class BlockParser

end
# frozen_string_literal: true
##
# GhostMethod represents a method referenced only by a comment

class RDoc::GhostMethod < RDoc::AnyMethod
end

# frozen_string_literal: true
##
# A Module extension to a class with \#extend
#
#   RDoc::Extend.new 'Enumerable', 'comment ...'

class RDoc::Extend < RDoc::Mixin

end

# 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
# frozen_string_literal: true
#--
# Copyright (c) 2003, 2004 Jim Weirich, 2009 Eric Hodel
#
# 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.
#++

begin
  gem 'rdoc'
rescue Gem::LoadError
end unless defined?(RDoc)

begin
  gem 'rake'
rescue Gem::LoadError
end unless defined?(Rake)

require 'rdoc'
require 'rake'
require 'rake/tasklib'

##
# RDoc::Task creates the following rake tasks to generate and clean up RDoc
# output:
#
# [rdoc]
#   Main task for this RDoc task.
#
# [clobber_rdoc]
#   Delete all the rdoc files.  This target is automatically added to the main
#   clobber target.
#
# [rerdoc]
#   Rebuild the rdoc files from scratch, even if they are not out of date.
#
# Simple Example:
#
#   require 'rdoc/task'
#
#   RDoc::Task.new do |rdoc|
#     rdoc.main = "README.rdoc"
#     rdoc.rdoc_files.include("README.rdoc", "lib/**/*.rb")
#   end
#
# The +rdoc+ object passed to the block is an RDoc::Task object. See the
# attributes list for the RDoc::Task class for available customization options.
#
# == Specifying different task names
#
# You may wish to give the task a different name, such as if you are
# generating two sets of documentation.  For instance, if you want to have a
# development set of documentation including private methods:
#
#   require 'rdoc/task'
#
#   RDoc::Task.new :rdoc_dev do |rdoc|
#     rdoc.main = "README.doc"
#     rdoc.rdoc_files.include("README.rdoc", "lib/**/*.rb")
#     rdoc.options << "--all"
#   end
#
# The tasks would then be named :<em>rdoc_dev</em>,
# :clobber_<em>rdoc_dev</em>, and :re<em>rdoc_dev</em>.
#
# If you wish to have completely different task names, then pass a Hash as
# first argument. With the <tt>:rdoc</tt>, <tt>:clobber_rdoc</tt> and
# <tt>:rerdoc</tt> options, you can customize the task names to your liking.
#
# For example:
#
#   require 'rdoc/task'
#
#   RDoc::Task.new(:rdoc => "rdoc", :clobber_rdoc => "rdoc:clean",
#                  :rerdoc => "rdoc:force")
#
# This will create the tasks <tt>:rdoc</tt>, <tt>:rdoc:clean</tt> and
# <tt>:rdoc:force</tt>.

class RDoc::Task < Rake::TaskLib

  ##
  # Name of the main, top level task.  (default is :rdoc)

  attr_accessor :name

  ##
  # Comment markup format.  rdoc, rd and tomdoc are supported.  (default is
  # 'rdoc')

  attr_accessor :markup

  ##
  # Name of directory to receive the html output files. (default is "html")

  attr_accessor :rdoc_dir

  ##
  # Title of RDoc documentation. (defaults to rdoc's default)

  attr_accessor :title

  ##
  # Name of file to be used as the main, top level file of the RDoc. (default
  # is none)

  attr_accessor :main

  ##
  # Name of template to be used by rdoc. (defaults to rdoc's default)

  attr_accessor :template

  ##
  # Name of format generator (<tt>--format</tt>) used by rdoc. (defaults to
  # rdoc's default)

  attr_accessor :generator

  ##
  # List of files to be included in the rdoc generation. (default is [])

  attr_accessor :rdoc_files

  ##
  # Additional list of options to be passed rdoc.  (default is [])

  attr_accessor :options

  ##
  # Whether to run the rdoc process as an external shell (default is false)

  attr_accessor :external

  ##
  # Create an RDoc task with the given name. See the RDoc::Task class overview
  # for documentation.

  def initialize name = :rdoc # :yield: self
    defaults

    check_names name

    @name = name

    yield self if block_given?

    define
  end

  ##
  # Ensures that +names+ only includes names for the :rdoc, :clobber_rdoc and
  # :rerdoc.  If other names are given an ArgumentError is raised.

  def check_names names
    return unless Hash === names

    invalid_options =
      names.keys.map { |k| k.to_sym } - [:rdoc, :clobber_rdoc, :rerdoc]

    unless invalid_options.empty? then
      raise ArgumentError, "invalid options: #{invalid_options.join ', '}"
    end
  end

  ##
  # Task description for the clobber rdoc task or its renamed equivalent

  def clobber_task_description
    "Remove RDoc HTML files"
  end

  ##
  # Sets default task values

  def defaults
    @name = :rdoc
    @rdoc_files = Rake::FileList.new
    @rdoc_dir = 'html'
    @main = nil
    @title = nil
    @template = nil
    @generator = nil
    @options = []
  end

  ##
  # All source is inline now.  This method is deprecated

  def inline_source # :nodoc:
    warn "RDoc::Task#inline_source is deprecated"
    true
  end

  ##
  # All source is inline now.  This method is deprecated

  def inline_source=(value) # :nodoc:
    warn "RDoc::Task#inline_source is deprecated"
  end

  ##
  # Create the tasks defined by this task lib.

  def define
    desc rdoc_task_description
    task rdoc_task_name

    desc rerdoc_task_description
    task rerdoc_task_name => [clobber_task_name, rdoc_task_name]

    desc clobber_task_description
    task clobber_task_name do
      rm_r @rdoc_dir rescue nil
    end

    task :clobber => [clobber_task_name]

    directory @rdoc_dir

    rdoc_target_deps = [
      @rdoc_files,
      Rake.application.rakefile
    ].flatten.compact

    task rdoc_task_name => [rdoc_target]
    file rdoc_target => rdoc_target_deps do
      @before_running_rdoc.call if @before_running_rdoc
      args = option_list + @rdoc_files

      $stderr.puts "rdoc #{args.join ' '}" if Rake.application.options.trace
      RDoc::RDoc.new.document args
    end

    self
  end

  ##
  # List of options that will be supplied to RDoc

  def option_list
    result = @options.dup
    result << "-o"       << @rdoc_dir
    result << "--main"   << main      if main
    result << "--markup" << markup    if markup
    result << "--title"  << title     if title
    result << "-T"       << template  if template
    result << '-f'       << generator if generator
    result
  end

  ##
  # The block passed to this method will be called just before running the
  # RDoc generator. It is allowed to modify RDoc::Task attributes inside the
  # block.

  def before_running_rdoc(&block)
    @before_running_rdoc = block
  end

  ##
  # Task description for the rdoc task or its renamed equivalent

  def rdoc_task_description
    'Build RDoc HTML files'
  end

  ##
  # Task description for the rerdoc task or its renamed description

  def rerdoc_task_description
    "Rebuild RDoc HTML files"
  end

  private

  def rdoc_target
    "#{rdoc_dir}/created.rid"
  end

  def rdoc_task_name
    case name
    when Hash then (name[:rdoc] || "rdoc").to_s
    else           name.to_s
    end
  end

  def clobber_task_name
    case name
    when Hash then (name[:clobber_rdoc] || "clobber_rdoc").to_s
    else           "clobber_#{name}"
    end
  end

  def rerdoc_task_name
    case name
    when Hash then (name[:rerdoc] || "rerdoc").to_s
    else           "re#{name}"
    end
  end

end

# :stopdoc:
module Rake

  ##
  # For backwards compatibility

  RDocTask = RDoc::Task

end
# :startdoc:
# 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*(?<name>[^\s;]+).*\n
      |
      <\?xml[^?]*encoding=(?<quote>["'])(?<name>.*?)\k<quote>.*\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
# frozen_string_literal: true
##
# MetaMethod represents a meta-programmed method

class RDoc::MetaMethod < RDoc::AnyMethod
end

# 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

# frozen_string_literal: true
##
# A TopLevel context is a representation of the contents of a single file

class RDoc::TopLevel < RDoc::Context

  MARSHAL_VERSION = 0 # :nodoc:

  ##
  # This TopLevel's File::Stat struct

  attr_accessor :file_stat

  ##
  # Relative name of this file

  attr_accessor :relative_name

  ##
  # Absolute name of this file

  attr_accessor :absolute_name

  ##
  # All the classes or modules that were declared in
  # this file. These are assigned to either +#classes_hash+
  # or +#modules_hash+ once we know what they really are.

  attr_reader :classes_or_modules

  attr_accessor :diagram # :nodoc:

  ##
  # The parser class that processed this file

  attr_reader :parser

  ##
  # Creates a new TopLevel for the file at +absolute_name+.  If documentation
  # is being generated outside the source dir +relative_name+ is relative to
  # the source directory.

  def initialize absolute_name, relative_name = absolute_name
    super()
    @name = nil
    @absolute_name = absolute_name
    @relative_name = relative_name
    @file_stat     = File.stat(absolute_name) rescue nil # HACK for testing
    @diagram       = nil
    @parser        = nil

    @classes_or_modules = []
  end

  def parser=(val)
    @parser = val
    @store.update_parser_of_file(absolute_name, val) if @store
    @parser
  end

  ##
  # An RDoc::TopLevel is equal to another with the same relative_name

  def == other
    self.class === other and @relative_name == other.relative_name
  end

  alias eql? ==

  ##
  # Adds +an_alias+ to +Object+ instead of +self+.

  def add_alias(an_alias)
    object_class.record_location self
    return an_alias unless @document_self
    object_class.add_alias an_alias
  end

  ##
  # Adds +constant+ to +Object+ instead of +self+.

  def add_constant constant
    object_class.record_location self
    return constant unless @document_self
    object_class.add_constant constant
  end

  ##
  # Adds +include+ to +Object+ instead of +self+.

  def add_include(include)
    object_class.record_location self
    return include unless @document_self
    object_class.add_include include
  end

  ##
  # Adds +method+ to +Object+ instead of +self+.

  def add_method(method)
    object_class.record_location self
    return method unless @document_self
    object_class.add_method method
  end

  ##
  # Adds class or module +mod+. Used in the building phase
  # by the Ruby parser.

  def add_to_classes_or_modules mod
    @classes_or_modules << mod
  end

  ##
  # Base name of this file

  def base_name
    File.basename @relative_name
  end

  alias name base_name

  ##
  # Only a TopLevel that contains text file) will be displayed.  See also
  # RDoc::CodeObject#display?

  def display?
    text? and super
  end

  ##
  # See RDoc::TopLevel::find_class_or_module
  #--
  # TODO Why do we search through all classes/modules found, not just the
  #       ones of this instance?

  def find_class_or_module name
    @store.find_class_or_module name
  end

  ##
  # Finds a class or module named +symbol+

  def find_local_symbol(symbol)
    find_class_or_module(symbol) || super
  end

  ##
  # Finds a module or class with +name+

  def find_module_named(name)
    find_class_or_module(name)
  end

  ##
  # Returns the relative name of this file

  def full_name
    @relative_name
  end

  ##
  # An RDoc::TopLevel has the same hash as another with the same
  # relative_name

  def hash
    @relative_name.hash
  end

  ##
  # URL for this with a +prefix+

  def http_url(prefix)
    path = [prefix, @relative_name.tr('.', '_')]

    File.join(*path.compact) + '.html'
  end

  def inspect # :nodoc:
    "#<%s:0x%x %p modules: %p classes: %p>" % [
      self.class, object_id,
      base_name,
      @modules.map { |n,m| m },
      @classes.map { |n,c| c }
    ]
  end

  ##
  # Time this file was last modified, if known

  def last_modified
    @file_stat ? file_stat.mtime : nil
  end

  ##
  # Dumps this TopLevel for use by ri.  See also #marshal_load

  def marshal_dump
    [
      MARSHAL_VERSION,
      @relative_name,
      @parser,
      parse(@comment),
    ]
  end

  ##
  # Loads this TopLevel from +array+.

  def marshal_load array # :nodoc:
    initialize array[1]

    @parser  = array[2]
    @comment = array[3]

    @file_stat          = nil
  end

  ##
  # Returns the NormalClass "Object", creating it if not found.
  #
  # Records +self+ as a location in "Object".

  def object_class
    @object_class ||= begin
      oc = @store.find_class_named('Object') || add_class(RDoc::NormalClass, 'Object')
      oc.record_location self
      oc
    end
  end

  ##
  # Base name of this file without the extension

  def page_name
    basename = File.basename @relative_name
    basename =~ /\.(rb|rdoc|txt|md)$/i

    $` || basename
  end

  ##
  # Path to this file for use with HTML generator output.

  def path
    http_url @store.rdoc.generator.file_dir
  end

  def pretty_print q # :nodoc:
    q.group 2, "[#{self.class}: ", "]" do
      q.text "base name: #{base_name.inspect}"
      q.breakable

      items = @modules.map { |n,m| m }
      items.concat @modules.map { |n,c| c }
      q.seplist items do |mod| q.pp mod end
    end
  end

  ##
  # Search record used by RDoc::Generator::JsonIndex

  def search_record
    return unless @parser < RDoc::Parser::Text

    [
      page_name,
      '',
      page_name,
      '',
      path,
      '',
      snippet(@comment),
    ]
  end

  ##
  # Is this TopLevel from a text file instead of a source code file?

  def text?
    @parser and @parser.include? RDoc::Parser::Text
  end

  def to_s # :nodoc:
    "file #{full_name}"
  end

end

# frozen_string_literal: true
begin
  require 'io/console/size'
rescue LoadError
  # for JRuby
  require 'io/console'
end

##
# Stats printer that prints just the files being documented with a progress
# bar

class RDoc::Stats::Normal < RDoc::Stats::Quiet

  def begin_adding # :nodoc:
    puts "Parsing sources..."
    @last_width = 0
  end

  ##
  # Prints a file with a progress bar

  def print_file files_so_far, filename
    progress_bar = sprintf("%3d%% [%2d/%2d]  ",
                           100 * files_so_far / @num_files,
                           files_so_far,
                           @num_files)

    if $stdout.tty?
      # Print a progress bar, but make sure it fits on a single line. Filename
      # will be truncated if necessary.
      size = IO.respond_to?(:console_size) ? IO.console_size : IO.console.winsize
      terminal_width = size[1].to_i.nonzero? || 80
      max_filename_size = (terminal_width - progress_bar.size) - 1

      if filename.size > max_filename_size then
        # Turn "some_long_filename.rb" to "...ong_filename.rb"
        filename = filename[(filename.size - max_filename_size) .. -1]
        filename[0..2] = "..."
      end

      # Clean the line with whitespaces so that leftover output from the
      # previous line doesn't show up.
      $stdout.print("\r\e[K") if @last_width && @last_width > 0
      @last_width = progress_bar.size + filename.size
      term = "\r"
    else
      term = "\n"
    end
    $stdout.print(progress_bar, filename, term)
    $stdout.flush
  end

  def done_adding # :nodoc:
    puts
  end

end
# frozen_string_literal: true
##
# Stats printer that prints nothing

class RDoc::Stats::Quiet

  ##
  # Creates a new Quiet that will print nothing

  def initialize num_files
    @num_files = num_files
  end

  ##
  # Prints a message at the beginning of parsing

  def begin_adding(*) end

  ##
  # Prints when an alias is added

  def print_alias(*) end

  ##
  # Prints when an attribute is added

  def print_attribute(*) end

  ##
  # Prints when a class is added

  def print_class(*) end

  ##
  # Prints when a constant is added

  def print_constant(*) end

  ##
  # Prints when a file is added

  def print_file(*) end

  ##
  # Prints when a method is added

  def print_method(*) end

  ##
  # Prints when a module is added

  def print_module(*) end

  ##
  # Prints when RDoc is done

  def done_adding(*) end

end

# frozen_string_literal: true
##
# Stats printer that prints everything documented, including the documented
# status

class RDoc::Stats::Verbose < RDoc::Stats::Normal

  ##
  # Returns a marker for RDoc::CodeObject +co+ being undocumented

  def nodoc co
    " (undocumented)" unless co.documented?
  end

  def print_alias as # :nodoc:
    puts "    alias #{as.new_name} #{as.old_name}#{nodoc as}"
  end

  def print_attribute attribute # :nodoc:
    puts "    #{attribute.definition} #{attribute.name}#{nodoc attribute}"
  end

  def print_class(klass) # :nodoc:
    puts "  class #{klass.full_name}#{nodoc klass}"
  end

  def print_constant(constant) # :nodoc:
    puts "    #{constant.name}#{nodoc constant}"
  end

  def print_file(files_so_far, file) # :nodoc:
    super
    puts
  end

  def print_method(method) # :nodoc:
    puts "    #{method.singleton ? '::' : '#'}#{method.name}#{nodoc method}"
  end

  def print_module(mod) # :nodoc:
    puts "  module #{mod.full_name}#{nodoc mod}"
  end

end


# frozen_string_literal: true
##
# An Indented Paragraph of text

class RDoc::Markup::IndentedParagraph < RDoc::Markup::Raw

  ##
  # The indent in number of spaces

  attr_reader :indent

  ##
  # Creates a new IndentedParagraph containing +parts+ indented with +indent+
  # spaces

  def initialize indent, *parts
    @indent = indent

    super(*parts)
  end

  def == other # :nodoc:
    super and indent == other.indent
  end

  ##
  # Calls #accept_indented_paragraph on +visitor+

  def accept visitor
    visitor.accept_indented_paragraph self
  end

  ##
  # Joins the raw paragraph text and converts inline HardBreaks to the
  # +hard_break+ text followed by the indent.

  def text hard_break = nil
    @parts.map do |part|
      if RDoc::Markup::HardBreak === part then
        '%1$s%3$*2$s' % [hard_break, @indent, ' '] if hard_break
      else
        part
      end
    end.join
  end

end

# frozen_string_literal: true
##
# Joins the parts of an RDoc::Markup::Paragraph into a single String.
#
# This allows for easier maintenance and testing of Markdown support.
#
# This formatter only works on Paragraph instances.  Attempting to process
# other markup syntax items will not work.

class RDoc::Markup::ToJoinedParagraph < RDoc::Markup::Formatter

  def initialize # :nodoc:
    super nil
  end

  def start_accepting # :nodoc:
  end

  def end_accepting # :nodoc:
  end

  ##
  # Converts the parts of +paragraph+ to a single entry.

  def accept_paragraph paragraph
    parts = paragraph.parts.chunk do |part|
      String === part
    end.map do |string, chunk|
      string ? chunk.join.rstrip : chunk
    end.flatten

    paragraph.parts.replace parts
  end

  alias accept_block_quote     ignore
  alias accept_heading         ignore
  alias accept_list_end        ignore
  alias accept_list_item_end   ignore
  alias accept_list_item_start ignore
  alias accept_list_start      ignore
  alias accept_raw             ignore
  alias accept_rule            ignore
  alias accept_verbatim        ignore
  alias accept_table           ignore

end

# frozen_string_literal: true
##
# A section of table

class RDoc::Markup::Table
  attr_accessor :header, :align, :body

  def initialize header, align, body
    @header, @align, @body = header, align, body
  end

  def == other
    self.class == other.class and
      @header == other.header and
      @align == other.align and
      @body == other.body
  end

  def accept visitor
    visitor.accept_table @header, @body, @align
  end

  def pretty_print q # :nodoc:
    q.group 2, '[Table: ', ']' do
      q.group 2, '[Head: ', ']' do
        q.seplist @header.zip(@align) do |text, align|
          q.pp text
          if align
            q.text ":"
            q.breakable
            q.text align.to_s
          end
        end
      end
      q.breakable
      q.group 2, '[Body: ', ']' do
        q.seplist @body do |body|
          q.group 2, '[', ']' do
            q.seplist body do |text|
              q.pp text
            end
          end
        end
      end
    end
  end
end
# frozen_string_literal: true
##
# A horizontal rule with a weight

class RDoc::Markup::Rule < Struct.new :weight

  ##
  # Calls #accept_rule on +visitor+

  def accept visitor
    visitor.accept_rule self
  end

  def pretty_print q # :nodoc:
    q.group 2, '[rule:', ']' do
      q.pp weight
    end
  end

end

# frozen_string_literal: true
##
# Extracts sections of text enclosed in plus, tt or code.  Used to discover
# undocumented parameters.

class RDoc::Markup::ToTtOnly < RDoc::Markup::Formatter

  ##
  # Stack of list types

  attr_reader :list_type

  ##
  # Output accumulator

  attr_reader :res

  ##
  # Creates a new tt-only formatter.

  def initialize markup = nil
    super nil, markup

    add_tag :TT, nil, nil
  end

  ##
  # Adds tts from +block_quote+ to the output

  def accept_block_quote block_quote
    tt_sections block_quote.text
  end

  ##
  # Pops the list type for +list+ from #list_type

  def accept_list_end list
    @list_type.pop
  end

  ##
  # Pushes the list type for +list+ onto #list_type

  def accept_list_start list
    @list_type << list.type
  end

  ##
  # Prepares the visitor for consuming +list_item+

  def accept_list_item_start list_item
    case @list_type.last
    when :NOTE, :LABEL then
      Array(list_item.label).map do |label|
        tt_sections label
      end.flatten
    end
  end

  ##
  # Adds +paragraph+ to the output

  def accept_paragraph paragraph
    tt_sections(paragraph.text)
  end

  ##
  # Does nothing to +markup_item+ because it doesn't have any user-built
  # content

  def do_nothing markup_item
  end

  alias accept_blank_line    do_nothing # :nodoc:
  alias accept_heading       do_nothing # :nodoc:
  alias accept_list_item_end do_nothing # :nodoc:
  alias accept_raw           do_nothing # :nodoc:
  alias accept_rule          do_nothing # :nodoc:
  alias accept_verbatim      do_nothing # :nodoc:

  ##
  # Extracts tt sections from +text+

  def tt_sections text
    flow = @am.flow text.dup

    flow.each do |item|
      case item
      when String then
        @res << item if in_tt?
      when RDoc::Markup::AttrChanger then
        off_tags res, item
        on_tags res, item
      when RDoc::Markup::RegexpHandling then
        @res << convert_regexp_handling(item) if in_tt? # TODO can this happen?
      else
        raise "Unknown flow element: #{item.inspect}"
      end
    end

    res
  end

  ##
  # Returns an Array of items that were wrapped in plus, tt or code.

  def end_accepting
    @res.compact
  end

  ##
  # Prepares the visitor for gathering tt sections

  def start_accepting
    @res = []

    @list_type = []
  end

end

# frozen_string_literal: true
##
# A quoted section which contains markup items.

class RDoc::Markup::BlockQuote < RDoc::Markup::Raw

  ##
  # Calls #accept_block_quote on +visitor+

  def accept visitor
    visitor.accept_block_quote self
  end

end

# frozen_string_literal: true
##
# We manage a set of attributes.  Each attribute has a symbol name and a bit
# value.

class RDoc::Markup::Attributes

  ##
  # The regexp handling attribute type. See RDoc::Markup#add_regexp_handling

  attr_reader :regexp_handling

  ##
  # Creates a new attributes set.

  def initialize
    @regexp_handling = 1

    @name_to_bitmap = [
      [:_REGEXP_HANDLING_, @regexp_handling],
    ]

    @next_bitmap = @regexp_handling << 1
  end

  ##
  # Returns a unique bit for +name+

  def bitmap_for name
    bitmap = @name_to_bitmap.assoc name

    unless bitmap then
      bitmap = @next_bitmap
      @next_bitmap <<= 1
      @name_to_bitmap << [name, bitmap]
    else
      bitmap = bitmap.last
    end

    bitmap
  end

  ##
  # Returns a string representation of +bitmap+

  def as_string bitmap
    return 'none' if bitmap.zero?
    res = []

    @name_to_bitmap.each do |name, bit|
      res << name if (bitmap & bit) != 0
    end

    res.join ','
  end

  ##
  # yields each attribute name in +bitmap+

  def each_name_of bitmap
    return enum_for __method__, bitmap unless block_given?

    @name_to_bitmap.each do |name, bit|
      next if bit == @regexp_handling

      yield name.to_s if (bitmap & bit) != 0
    end
  end

end

# frozen_string_literal: true
##
# A Document containing lists, headings, paragraphs, etc.

class RDoc::Markup::Document

  include Enumerable

  ##
  # The file this document was created from.  See also
  # RDoc::ClassModule#add_comment

  attr_reader :file

  ##
  # If a heading is below the given level it will be omitted from the
  # table_of_contents

  attr_accessor :omit_headings_below

  ##
  # The parts of the Document

  attr_reader :parts

  ##
  # Creates a new Document with +parts+

  def initialize *parts
    @parts = []
    @parts.concat parts

    @file = nil
    @omit_headings_from_table_of_contents_below = nil
  end

  ##
  # Appends +part+ to the document

  def << part
    case part
    when RDoc::Markup::Document then
      unless part.empty? then
        parts.concat part.parts
        parts << RDoc::Markup::BlankLine.new
      end
    when String then
      raise ArgumentError,
            "expected RDoc::Markup::Document and friends, got String" unless
        part.empty?
    else
      parts << part
    end
  end

  def == other # :nodoc:
    self.class == other.class and
      @file == other.file and
      @parts == other.parts
  end

  ##
  # Runs this document and all its #items through +visitor+

  def accept visitor
    visitor.start_accepting

    visitor.accept_document self

    visitor.end_accepting
  end

  ##
  # Concatenates the given +parts+ onto the document

  def concat parts
    self.parts.concat parts
  end

  ##
  # Enumerator for the parts of this document

  def each &block
    @parts.each(&block)
  end

  ##
  # Does this document have no parts?

  def empty?
    @parts.empty? or (@parts.length == 1 and merged? and @parts.first.empty?)
  end

  ##
  # The file this Document was created from.

  def file= location
    @file = case location
            when RDoc::TopLevel then
              location.relative_name
            else
              location
            end
  end

  ##
  # When this is a collection of documents (#file is not set and this document
  # contains only other documents as its direct children) #merge replaces
  # documents in this class with documents from +other+ when the file matches
  # and adds documents from +other+ when the files do not.
  #
  # The information in +other+ is preferred over the receiver

  def merge other
    if empty? then
      @parts = other.parts
      return self
    end

    other.parts.each do |other_part|
      self.parts.delete_if do |self_part|
        self_part.file and self_part.file == other_part.file
      end

      self.parts << other_part
    end

    self
  end

  ##
  # Does this Document contain other Documents?

  def merged?
    RDoc::Markup::Document === @parts.first
  end

  def pretty_print q # :nodoc:
    start = @file ? "[doc (#{@file}): " : '[doc: '

    q.group 2, start, ']' do
      q.seplist @parts do |part|
        q.pp part
      end
    end
  end

  ##
  # Appends +parts+ to the document

  def push *parts
    self.parts.concat parts
  end

  ##
  # Returns an Array of headings in the document.
  #
  # Require 'rdoc/markup/formatter' before calling this method.

  def table_of_contents
    accept RDoc::Markup::ToTableOfContents.to_toc
  end

end

# frozen_string_literal: true
##
# A List is a homogeneous set of ListItems.
#
# The supported list types include:
#
# :BULLET::
#   An unordered list
# :LABEL::
#   An unordered definition list, but using an alternate RDoc::Markup syntax
# :LALPHA::
#   An ordered list using increasing lowercase English letters
# :NOTE::
#   An unordered definition list
# :NUMBER::
#   An ordered list using increasing Arabic numerals
# :UALPHA::
#   An ordered list using increasing uppercase English letters
#
# Definition lists behave like HTML definition lists.  Each list item can
# describe multiple terms.  See RDoc::Markup::ListItem for how labels and
# definition are stored as list items.

class RDoc::Markup::List

  ##
  # The list's type

  attr_accessor :type

  ##
  # Items in the list

  attr_reader :items

  ##
  # Creates a new list of +type+ with +items+.  Valid list types are:
  # +:BULLET+, +:LABEL+, +:LALPHA+, +:NOTE+, +:NUMBER+, +:UALPHA+

  def initialize type = nil, *items
    @type = type
    @items = []
    @items.concat items
  end

  ##
  # Appends +item+ to the list

  def << item
    @items << item
  end

  def == other # :nodoc:
    self.class == other.class and
      @type == other.type and
      @items == other.items
  end

  ##
  # Runs this list and all its #items through +visitor+

  def accept visitor
    visitor.accept_list_start self

    @items.each do |item|
      item.accept visitor
    end

    visitor.accept_list_end self
  end

  ##
  # Is the list empty?

  def empty?
    @items.empty?
  end

  ##
  # Returns the last item in the list

  def last
    @items.last
  end

  def pretty_print q # :nodoc:
    q.group 2, "[list: #{@type} ", ']' do
      q.seplist @items do |item|
        q.pp item
      end
    end
  end

  ##
  # Appends +items+ to the list

  def push *items
    @items.concat items
  end

end

# frozen_string_literal: true
require 'strscan'

##
# A recursive-descent parser for RDoc markup.
#
# The parser tokenizes an input string then parses the tokens into a Document.
# Documents can be converted into output formats by writing a visitor like
# RDoc::Markup::ToHTML.
#
# The parser only handles the block-level constructs Paragraph, List,
# ListItem, Heading, Verbatim, BlankLine, Rule and BlockQuote.
# Inline markup such as <tt>\+blah\+</tt> is handled separately by
# RDoc::Markup::AttributeManager.
#
# To see what markup the Parser implements read RDoc.  To see how to use
# RDoc markup to format text in your program read RDoc::Markup.

class RDoc::Markup::Parser

  include RDoc::Text

  ##
  # List token types

  LIST_TOKENS = [
    :BULLET,
    :LABEL,
    :LALPHA,
    :NOTE,
    :NUMBER,
    :UALPHA,
  ]

  ##
  # Parser error subclass

  class Error < RuntimeError; end

  ##
  # Raised when the parser is unable to handle the given markup

  class ParseError < Error; end

  ##
  # Enables display of debugging information

  attr_accessor :debug

  ##
  # Token accessor

  attr_reader :tokens

  ##
  # Parses +str+ into a Document.
  #
  # Use RDoc::Markup#parse instead of this method.

  def self.parse str
    parser = new
    parser.tokenize str
    doc = RDoc::Markup::Document.new
    parser.parse doc
  end

  ##
  # Returns a token stream for +str+, for testing

  def self.tokenize str
    parser = new
    parser.tokenize str
    parser.tokens
  end

  ##
  # Creates a new Parser.  See also ::parse

  def initialize
    @binary_input   = nil
    @current_token  = nil
    @debug          = false
    @s              = nil
    @tokens         = []
  end

  ##
  # Builds a Heading of +level+

  def build_heading level
    type, text, = get

    text = case type
           when :TEXT then
             skip :NEWLINE
             text
           else
             unget
             ''
           end

    RDoc::Markup::Heading.new level, text
  end

  ##
  # Builds a List flush to +margin+

  def build_list margin
    p :list_start => margin if @debug

    list = RDoc::Markup::List.new
    label = nil

    until @tokens.empty? do
      type, data, column, = get

      case type
      when *LIST_TOKENS then
        if column < margin || (list.type && list.type != type) then
          unget
          break
        end

        list.type = type
        peek_type, _, column, = peek_token

        case type
        when :NOTE, :LABEL then
          label = [] unless label

          if peek_type == :NEWLINE then
            # description not on the same line as LABEL/NOTE
            # skip the trailing newline & any blank lines below
            while peek_type == :NEWLINE
              get
              peek_type, _, column, = peek_token
            end

            # we may be:
            #   - at end of stream
            #   - at a column < margin:
            #         [text]
            #       blah blah blah
            #   - at the same column, but with a different type of list item
            #       [text]
            #       * blah blah
            #   - at the same column, with the same type of list item
            #       [one]
            #       [two]
            # In all cases, we have an empty description.
            # In the last case only, we continue.
            if peek_type.nil? || column < margin then
              empty = true
            elsif column == margin then
              case peek_type
              when type
                empty = :continue
              when *LIST_TOKENS
                empty = true
              else
                empty = false
              end
            else
              empty = false
            end

            if empty then
              label << data
              next if empty == :continue
              break
            end
          end
        else
          data = nil
        end

        if label then
          data = label << data
          label = nil
        end

        list_item = RDoc::Markup::ListItem.new data
        parse list_item, column
        list << list_item

      else
        unget
        break
      end
    end

    p :list_end => margin if @debug

    if list.empty? then
      return nil unless label
      return nil unless [:LABEL, :NOTE].include? list.type

      list_item = RDoc::Markup::ListItem.new label, RDoc::Markup::BlankLine.new
      list << list_item
    end

    list
  end

  ##
  # Builds a Paragraph that is flush to +margin+

  def build_paragraph margin
    p :paragraph_start => margin if @debug

    paragraph = RDoc::Markup::Paragraph.new

    until @tokens.empty? do
      type, data, column, = get

      if type == :TEXT and column == margin then
        paragraph << data

        break if peek_token.first == :BREAK

        data << ' ' if skip :NEWLINE
      else
        unget
        break
      end
    end

    paragraph.parts.last.sub!(/ \z/, '') # cleanup

    p :paragraph_end => margin if @debug

    paragraph
  end

  ##
  # Builds a Verbatim that is indented from +margin+.
  #
  # The verbatim block is shifted left (the least indented lines start in
  # column 0).  Each part of the verbatim is one line of text, always
  # terminated by a newline.  Blank lines always consist of a single newline
  # character, and there is never a single newline at the end of the verbatim.

  def build_verbatim margin
    p :verbatim_begin => margin if @debug
    verbatim = RDoc::Markup::Verbatim.new

    min_indent = nil
    generate_leading_spaces = true
    line = ''.dup

    until @tokens.empty? do
      type, data, column, = get

      if type == :NEWLINE then
        line << data
        verbatim << line
        line = ''.dup
        generate_leading_spaces = true
        next
      end

      if column <= margin
        unget
        break
      end

      if generate_leading_spaces then
        indent = column - margin
        line << ' ' * indent
        min_indent = indent if min_indent.nil? || indent < min_indent
        generate_leading_spaces = false
      end

      case type
      when :HEADER then
        line << '=' * data
        _, _, peek_column, = peek_token
        peek_column ||= column + data
        indent = peek_column - column - data
        line << ' ' * indent
      when :RULE then
        width = 2 + data
        line << '-' * width
        _, _, peek_column, = peek_token
        peek_column ||= column + width
        indent = peek_column - column - width
        line << ' ' * indent
      when :BREAK, :TEXT then
        line << data
      else # *LIST_TOKENS
        list_marker = case type
                      when :BULLET then data
                      when :LABEL  then "[#{data}]"
                      when :NOTE   then "#{data}::"
                      else # :LALPHA, :NUMBER, :UALPHA
                        "#{data}."
                      end
        line << list_marker
        peek_type, _, peek_column = peek_token
        unless peek_type == :NEWLINE then
          peek_column ||= column + list_marker.length
          indent = peek_column - column - list_marker.length
          line << ' ' * indent
        end
      end

    end

    verbatim << line << "\n" unless line.empty?
    verbatim.parts.each { |p| p.slice!(0, min_indent) unless p == "\n" } if min_indent > 0
    verbatim.normalize

    p :verbatim_end => margin if @debug

    verbatim
  end

  ##
  # Pulls the next token from the stream.

  def get
    @current_token = @tokens.shift
    p :get => @current_token if @debug
    @current_token
  end

  ##
  # Parses the tokens into an array of RDoc::Markup::XXX objects,
  # and appends them to the passed +parent+ RDoc::Markup::YYY object.
  #
  # Exits at the end of the token stream, or when it encounters a token
  # in a column less than +indent+ (unless it is a NEWLINE).
  #
  # Returns +parent+.

  def parse parent, indent = 0
    p :parse_start => indent if @debug

    until @tokens.empty? do
      type, data, column, = get

      case type
      when :BREAK then
        parent << RDoc::Markup::BlankLine.new
        skip :NEWLINE, false
        next
      when :NEWLINE then
        # trailing newlines are skipped below, so this is a blank line
        parent << RDoc::Markup::BlankLine.new
        skip :NEWLINE, false
        next
      end

      # indentation change: break or verbatim
      if column < indent then
        unget
        break
      elsif column > indent then
        unget
        parent << build_verbatim(indent)
        next
      end

      # indentation is the same
      case type
      when :HEADER then
        parent << build_heading(data)
      when :RULE then
        parent << RDoc::Markup::Rule.new(data)
        skip :NEWLINE
      when :TEXT then
        unget
        parse_text parent, indent
      when :BLOCKQUOTE then
        type, _, column = get
        if type == :NEWLINE
          type, _, column = get
        end
        unget if type
        bq = RDoc::Markup::BlockQuote.new
        p :blockquote_start => [data, column] if @debug
        parse bq, column
        p :blockquote_end => indent if @debug
        parent << bq
      when *LIST_TOKENS then
        unget
        parent << build_list(indent)
      else
        type, data, column, line = @current_token
        raise ParseError, "Unhandled token #{type} (#{data.inspect}) at #{line}:#{column}"
      end
    end

    p :parse_end => indent if @debug

    parent

  end

  ##
  # Small hook that is overridden by RDoc::TomDoc

  def parse_text parent, indent # :nodoc:
    parent << build_paragraph(indent)
  end

  ##
  # Returns the next token on the stream without modifying the stream

  def peek_token
    token = @tokens.first || []
    p :peek => token if @debug
    token
  end

  ##
  # A simple wrapper of StringScanner that is aware of the current column and lineno

  class MyStringScanner
    def initialize(input)
      @line = @column = 0
      @s = StringScanner.new input
    end

    def scan(re)
      ret = @s.scan(re)
      @column += ret.length if ret
      ret
    end

    def unscan(s)
      @s.pos -= s.bytesize
      @column -= s.length
    end

    def pos
      [@column, @line]
    end

    def newline!
      @column = 0
      @line += 1
    end

    def eos?
      @s.eos?
    end

    def matched
      @s.matched
    end

    def [](i)
      @s[i]
    end
  end

  ##
  # Creates the StringScanner

  def setup_scanner input
    @s = MyStringScanner.new input
  end

  ##
  # Skips the next token if its type is +token_type+.
  #
  # Optionally raises an error if the next token is not of the expected type.

  def skip token_type, error = true
    type, = get
    return unless type # end of stream
    return @current_token if token_type == type
    unget
    raise ParseError, "expected #{token_type} got #{@current_token.inspect}" if error
  end

  ##
  # Turns text +input+ into a stream of tokens

  def tokenize input
    setup_scanner input

    until @s.eos? do
      pos = @s.pos

      # leading spaces will be reflected by the column of the next token
      # the only thing we loose are trailing spaces at the end of the file
      next if @s.scan(/ +/)

      # note: after BULLET, LABEL, etc.,
      # indent will be the column of the next non-newline token

      @tokens << case
                 # [CR]LF => :NEWLINE
                 when @s.scan(/\r?\n/) then
                   token = [:NEWLINE, @s.matched, *pos]
                   @s.newline!
                   token
                 # === text => :HEADER then :TEXT
                 when @s.scan(/(=+)(\s*)/) then
                   level = @s[1].length
                   header = [:HEADER, level, *pos]

                   if @s[2] =~ /^\r?\n/ then
                     @s.unscan(@s[2])
                     header
                   else
                     pos = @s.pos
                     @s.scan(/.*/)
                     @tokens << header
                     [:TEXT, @s.matched.sub(/\r$/, ''), *pos]
                   end
                 # --- (at least 3) and nothing else on the line => :RULE
                 when @s.scan(/(-{3,}) *\r?$/) then
                   [:RULE, @s[1].length - 2, *pos]
                 # * or - followed by white space and text => :BULLET
                 when @s.scan(/([*-]) +(\S)/) then
                   @s.unscan(@s[2])
                   [:BULLET, @s[1], *pos]
                 # A. text, a. text, 12. text => :UALPHA, :LALPHA, :NUMBER
                 when @s.scan(/([a-z]|\d+)\. +(\S)/i) then
                   # FIXME if tab(s), the column will be wrong
                   # either support tabs everywhere by first expanding them to
                   # spaces, or assume that they will have been replaced
                   # before (and provide a check for that at least in debug
                   # mode)
                   list_label = @s[1]
                   @s.unscan(@s[2])
                   list_type =
                     case list_label
                     when /[a-z]/ then :LALPHA
                     when /[A-Z]/ then :UALPHA
                     when /\d/    then :NUMBER
                     else
                       raise ParseError, "BUG token #{list_label}"
                     end
                   [list_type, list_label, *pos]
                 # [text] followed by spaces or end of line => :LABEL
                 when @s.scan(/\[(.*?)\]( +|\r?$)/) then
                   [:LABEL, @s[1], *pos]
                 # text:: followed by spaces or end of line => :NOTE
                 when @s.scan(/(.*?)::( +|\r?$)/) then
                   [:NOTE, @s[1], *pos]
                 # >>> followed by end of line => :BLOCKQUOTE
                 when @s.scan(/>>> *(\w+)?$/) then
                   [:BLOCKQUOTE, @s[1], *pos]
                 # anything else: :TEXT
                 else
                   @s.scan(/(.*?)(  )?\r?$/)
                   token = [:TEXT, @s[1], *pos]

                   if @s[2] then
                     @tokens << token
                     [:BREAK, @s[2], pos[0] + @s[1].length, pos[1]]
                   else
                     token
                   end
                 end
    end

    self
  end

  ##
  # Returns the current token to the token stream

  def unget
    token = @current_token
    p :unget => token if @debug
    raise Error, 'too many #ungets' if token == @tokens.first
    @tokens.unshift token if token
  end

end
# frozen_string_literal: true
##
# Base class for RDoc markup formatters
#
# Formatters are a visitor that converts an RDoc::Markup tree (from a comment)
# into some kind of output.  RDoc ships with formatters for converting back to
# rdoc, ANSI text, HTML, a Table of Contents and other formats.
#
# If you'd like to write your own Formatter use
# RDoc::Markup::FormatterTestCase.  If you're writing a text-output formatter
# use RDoc::Markup::TextFormatterTestCase which provides extra test cases.

class RDoc::Markup::Formatter

  ##
  # Tag for inline markup containing a +bit+ for the bitmask and the +on+ and
  # +off+ triggers.

  InlineTag = Struct.new(:bit, :on, :off)

  ##
  # Converts a target url to one that is relative to a given path

  def self.gen_relative_url path, target
    from        = File.dirname path
    to, to_file = File.split target

    from = from.split "/"
    to   = to.split "/"

    from.delete '.'
    to.delete '.'

    while from.size > 0 and to.size > 0 and from[0] == to[0] do
      from.shift
      to.shift
    end

    from.fill ".."
    from.concat to
    from << to_file
    File.join(*from)
  end

  ##
  # Creates a new Formatter

  def initialize options, markup = nil
    @options = options

    @markup = markup || RDoc::Markup.new
    @am     = @markup.attribute_manager
    @am.add_regexp_handling(/<br>/, :HARD_BREAK)

    @attributes = @am.attributes

    @attr_tags = []

    @in_tt = 0
    @tt_bit = @attributes.bitmap_for :TT

    @hard_break = ''
    @from_path = '.'
  end

  ##
  # Adds +document+ to the output

  def accept_document document
    document.parts.each do |item|
      case item
      when RDoc::Markup::Document then # HACK
        accept_document item
      else
        item.accept self
      end
    end
  end

  ##
  # Adds a regexp handling for links of the form rdoc-...:

  def add_regexp_handling_RDOCLINK
    @markup.add_regexp_handling(/rdoc-[a-z]+:[^\s\]]+/, :RDOCLINK)
  end

  ##
  # Adds a regexp handling for links of the form {<text>}[<url>] and
  # <word>[<url>]

  def add_regexp_handling_TIDYLINK
    @markup.add_regexp_handling(/(?:
                                  \{.*?\} |    # multi-word label
                                  \b[^\s{}]+? # single-word label
                                 )

                                 \[\S+?\]     # link target
                                /x, :TIDYLINK)
  end

  ##
  # Add a new set of tags for an attribute. We allow separate start and end
  # tags for flexibility

  def add_tag(name, start, stop)
    attr = @attributes.bitmap_for name
    @attr_tags << InlineTag.new(attr, start, stop)
  end

  ##
  # Allows +tag+ to be decorated with additional information.

  def annotate(tag)
    tag
  end

  ##
  # Marks up +content+

  def convert content
    @markup.convert content, self
  end

  ##
  # Converts flow items +flow+

  def convert_flow(flow)
    res = []

    flow.each do |item|
      case item
      when String then
        res << convert_string(item)
      when RDoc::Markup::AttrChanger then
        off_tags res, item
        on_tags res, item
      when RDoc::Markup::RegexpHandling then
        res << convert_regexp_handling(item)
      else
        raise "Unknown flow element: #{item.inspect}"
      end
    end

    res.join
  end

  ##
  # Converts added regexp handlings. See RDoc::Markup#add_regexp_handling

  def convert_regexp_handling target
    return target.text if in_tt?

    handled = false

    @attributes.each_name_of target.type do |name|
      method_name = "handle_regexp_#{name}"

      if respond_to? method_name then
        target.text = public_send method_name, target
        handled = true
      end
    end

    unless handled then
      target_name = @attributes.as_string target.type

      raise RDoc::Error, "Unhandled regexp handling #{target_name}: #{target}"
    end

    target.text
  end

  ##
  # Converts a string to be fancier if desired

  def convert_string string
    string
  end

  ##
  # Use ignore in your subclass to ignore the content of a node.
  #
  #   ##
  #   # We don't support raw nodes in ToNoRaw
  #
  #   alias accept_raw ignore

  def ignore *node
  end

  ##
  # Are we currently inside tt tags?

  def in_tt?
    @in_tt > 0
  end

  ##
  # Turns on tags for +item+ on +res+

  def on_tags res, item
    attr_mask = item.turn_on
    return if attr_mask.zero?

    @attr_tags.each do |tag|
      if attr_mask & tag.bit != 0 then
        res << annotate(tag.on)
        @in_tt += 1 if tt? tag
      end
    end
  end

  ##
  # Turns off tags for +item+ on +res+

  def off_tags res, item
    attr_mask = item.turn_off
    return if attr_mask.zero?

    @attr_tags.reverse_each do |tag|
      if attr_mask & tag.bit != 0 then
        @in_tt -= 1 if tt? tag
        res << annotate(tag.off)
      end
    end
  end

  ##
  # Extracts and a scheme, url and an anchor id from +url+ and returns them.

  def parse_url url
    case url
    when /^rdoc-label:([^:]*)(?::(.*))?/ then
      scheme = 'link'
      path   = "##{$1}"
      id     = " id=\"#{$2}\"" if $2
    when /([A-Za-z]+):(.*)/ then
      scheme = $1.downcase
      path   = $2
    when /^#/ then
    else
      scheme = 'http'
      path   = url
      url    = url
    end

    if scheme == 'link' then
      url = if path[0, 1] == '#' then # is this meaningful?
              path
            else
              self.class.gen_relative_url @from_path, path
            end
    end

    [scheme, url, id]
  end

  ##
  # Is +tag+ a tt tag?

  def tt? tag
    tag.bit == @tt_bit
  end

end

# frozen_string_literal: true
class RDoc::Markup

  AttrChanger = Struct.new :turn_on, :turn_off # :nodoc:

end

##
# An AttrChanger records a change in attributes. It contains a bitmap of the
# attributes to turn on, and a bitmap of those to turn off.

class RDoc::Markup::AttrChanger

  def to_s # :nodoc:
    "Attr: +#{turn_on}/-#{turn_off}"
  end

  def inspect # :nodoc:
    '+%d/-%d' % [turn_on, turn_off]
  end

end

# frozen_string_literal: true
##
# Outputs RDoc markup as RDoc markup! (mostly)

class RDoc::Markup::ToRdoc < RDoc::Markup::Formatter

  ##
  # Current indent amount for output in characters

  attr_accessor :indent

  ##
  # Output width in characters

  attr_accessor :width

  ##
  # Stack of current list indexes for alphabetic and numeric lists

  attr_reader :list_index

  ##
  # Stack of list types

  attr_reader :list_type

  ##
  # Stack of list widths for indentation

  attr_reader :list_width

  ##
  # Prefix for the next list item.  See #use_prefix

  attr_reader :prefix

  ##
  # Output accumulator

  attr_reader :res

  ##
  # Creates a new formatter that will output (mostly) \RDoc markup

  def initialize markup = nil
    super nil, markup

    @markup.add_regexp_handling(/\\\S/, :SUPPRESSED_CROSSREF)
    @width = 78
    init_tags

    @headings = {}
    @headings.default = []

    @headings[1] = ['= ',      '']
    @headings[2] = ['== ',     '']
    @headings[3] = ['=== ',    '']
    @headings[4] = ['==== ',   '']
    @headings[5] = ['===== ',  '']
    @headings[6] = ['====== ', '']

    @hard_break = "\n"
  end

  ##
  # Maps attributes to HTML sequences

  def init_tags
    add_tag :BOLD, "<b>", "</b>"
    add_tag :TT,   "<tt>", "</tt>"
    add_tag :EM,   "<em>", "</em>"
  end

  ##
  # Adds +blank_line+ to the output

  def accept_blank_line blank_line
    @res << "\n"
  end

  ##
  # Adds +paragraph+ to the output

  def accept_block_quote block_quote
    @indent += 2

    block_quote.parts.each do |part|
      @prefix = '> '

      part.accept self
    end

    @indent -= 2
  end

  ##
  # Adds +heading+ to the output

  def accept_heading heading
    use_prefix or @res << ' ' * @indent
    @res << @headings[heading.level][0]
    @res << attributes(heading.text)
    @res << @headings[heading.level][1]
    @res << "\n"
  end

  ##
  # Finishes consumption of +list+

  def accept_list_end list
    @list_index.pop
    @list_type.pop
    @list_width.pop
  end

  ##
  # Finishes consumption of +list_item+

  def accept_list_item_end list_item
    width = case @list_type.last
            when :BULLET then
              2
            when :NOTE, :LABEL then
              if @prefix then
                @res << @prefix.strip
                @prefix = nil
              end

              @res << "\n"
              2
            else
              bullet = @list_index.last.to_s
              @list_index[-1] = @list_index.last.succ
              bullet.length + 2
            end

    @indent -= width
  end

  ##
  # Prepares the visitor for consuming +list_item+

  def accept_list_item_start list_item
    type = @list_type.last

    case type
    when :NOTE, :LABEL then
      bullets = Array(list_item.label).map do |label|
        attributes(label).strip
      end.join "\n"

      bullets << ":\n" unless bullets.empty?

      @prefix = ' ' * @indent
      @indent += 2
      @prefix << bullets + (' ' * @indent)
    else
      bullet = type == :BULLET ? '*' :  @list_index.last.to_s + '.'
      @prefix = (' ' * @indent) + bullet.ljust(bullet.length + 1)
      width = bullet.length + 1
      @indent += width
    end
  end

  ##
  # Prepares the visitor for consuming +list+

  def accept_list_start list
    case list.type
    when :BULLET then
      @list_index << nil
      @list_width << 1
    when :LABEL, :NOTE then
      @list_index << nil
      @list_width << 2
    when :LALPHA then
      @list_index << 'a'
      @list_width << list.items.length.to_s.length
    when :NUMBER then
      @list_index << 1
      @list_width << list.items.length.to_s.length
    when :UALPHA then
      @list_index << 'A'
      @list_width << list.items.length.to_s.length
    else
      raise RDoc::Error, "invalid list type #{list.type}"
    end

    @list_type << list.type
  end

  ##
  # Adds +paragraph+ to the output

  def accept_paragraph paragraph
    text = paragraph.text @hard_break
    wrap attributes text
  end

  ##
  # Adds +paragraph+ to the output

  def accept_indented_paragraph paragraph
    @indent += paragraph.indent
    text = paragraph.text @hard_break
    wrap attributes text
    @indent -= paragraph.indent
  end

  ##
  # Adds +raw+ to the output

  def accept_raw raw
    @res << raw.parts.join("\n")
  end

  ##
  # Adds +rule+ to the output

  def accept_rule rule
    use_prefix or @res << ' ' * @indent
    @res << '-' * (@width - @indent)
    @res << "\n"
  end

  ##
  # Outputs +verbatim+ indented 2 columns

  def accept_verbatim verbatim
    indent = ' ' * (@indent + 2)

    verbatim.parts.each do |part|
      @res << indent unless part == "\n"
      @res << part
    end

    @res << "\n"
  end

  ##
  # Adds +table+ to the output

  def accept_table header, body, aligns
    widths = header.zip(body) do |h, b|
      [h.size, b.size].max
    end
    aligns = aligns.map do |a|
      case a
      when nil
        :center
      when :left
        :ljust
      when :right
        :rjust
      end
    end
    @res << header.zip(widths, aligns) do |h, w, a|
      h.__send__(a, w)
    end.join("|").rstrip << "\n"
    @res << widths.map {|w| "-" * w }.join("|") << "\n"
    body.each do |row|
      @res << row.zip(widths, aligns) do |t, w, a|
        t.__send__(a, w)
      end.join("|").rstrip << "\n"
    end
  end

  ##
  # Applies attribute-specific markup to +text+ using RDoc::AttributeManager

  def attributes text
    flow = @am.flow text.dup
    convert_flow flow
  end

  ##
  # Returns the generated output

  def end_accepting
    @res.join
  end

  ##
  # Removes preceding \\ from the suppressed crossref +target+

  def handle_regexp_SUPPRESSED_CROSSREF target
    text = target.text
    text = text.sub('\\', '') unless in_tt?
    text
  end

  ##
  # Adds a newline to the output

  def handle_regexp_HARD_BREAK target
    "\n"
  end

  ##
  # Prepares the visitor for text generation

  def start_accepting
    @res = [""]
    @indent = 0
    @prefix = nil

    @list_index = []
    @list_type  = []
    @list_width = []
  end

  ##
  # Adds the stored #prefix to the output and clears it.  Lists generate a
  # prefix for later consumption.

  def use_prefix
    prefix, @prefix = @prefix, nil
    @res << prefix if prefix

    prefix
  end

  ##
  # Wraps +text+ to #width

  def wrap text
    return unless text && !text.empty?

    text_len = @width - @indent

    text_len = 20 if text_len < 20

    re = /^(.{0,#{text_len}})[ \n]/
    next_prefix = ' ' * @indent

    prefix = @prefix || next_prefix
    @prefix = nil

    @res << prefix

    while text.length > text_len
      if text =~ re then
        @res << $1
        text.slice!(0, $&.length)
      else
        @res << text.slice!(0, text_len)
      end

      @res << "\n" << next_prefix
    end

    if text.empty? then
      @res.pop
      @res.pop
    else
      @res << text
      @res << "\n"
    end
  end

end

# frozen_string_literal: true
require 'cgi'

##
# Creates HTML-safe labels suitable for use in id attributes.  Tidylinks are
# converted to their link part and cross-reference links have the suppression
# marks removed (\\SomeClass is converted to SomeClass).

class RDoc::Markup::ToLabel < RDoc::Markup::Formatter

  attr_reader :res # :nodoc:

  ##
  # Creates a new formatter that will output HTML-safe labels

  def initialize markup = nil
    super nil, markup

    @markup.add_regexp_handling RDoc::CrossReference::CROSSREF_REGEXP, :CROSSREF
    @markup.add_regexp_handling(/(((\{.*?\})|\b\S+?)\[\S+?\])/, :TIDYLINK)

    add_tag :BOLD, '', ''
    add_tag :TT,   '', ''
    add_tag :EM,   '', ''

    @res = []
  end

  ##
  # Converts +text+ to an HTML-safe label

  def convert text
    label = convert_flow @am.flow text

    CGI.escape(label).gsub('%', '-').sub(/^-/, '')
  end

  ##
  # Converts the CROSSREF +target+ to plain text, removing the suppression
  # marker, if any

  def handle_regexp_CROSSREF target
    text = target.text

    text.sub(/^\\/, '')
  end

  ##
  # Converts the TIDYLINK +target+ to just the text part

  def handle_regexp_TIDYLINK target
    text = target.text

    return text unless text =~ /\{(.*?)\}\[(.*?)\]/ or text =~ /(\S+)\[(.*?)\]/

    $1
  end

  alias accept_blank_line         ignore
  alias accept_block_quote        ignore
  alias accept_heading            ignore
  alias accept_list_end           ignore
  alias accept_list_item_end      ignore
  alias accept_list_item_start    ignore
  alias accept_list_start         ignore
  alias accept_paragraph          ignore
  alias accept_raw                ignore
  alias accept_rule               ignore
  alias accept_verbatim           ignore
  alias end_accepting             ignore
  alias handle_regexp_HARD_BREAK  ignore
  alias start_accepting           ignore

end

# frozen_string_literal: true
##
# Extracts just the RDoc::Markup::Heading elements from a
# RDoc::Markup::Document to help build a table of contents

class RDoc::Markup::ToTableOfContents < RDoc::Markup::Formatter

  @to_toc = nil

  ##
  # Singleton for table-of-contents generation

  def self.to_toc
    @to_toc ||= new
  end

  ##
  # Output accumulator

  attr_reader :res

  ##
  # Omits headings with a level less than the given level.

  attr_accessor :omit_headings_below

  def initialize # :nodoc:
    super nil

    @omit_headings_below = nil
  end

  ##
  # Adds +document+ to the output, using its heading cutoff if present

  def accept_document document
    @omit_headings_below = document.omit_headings_below

    super
  end

  ##
  # Adds +heading+ to the table of contents

  def accept_heading heading
    @res << heading unless suppressed? heading
  end

  ##
  # Returns the table of contents

  def end_accepting
    @res
  end

  ##
  # Prepares the visitor for text generation

  def start_accepting
    @omit_headings_below = nil
    @res = []
  end

  ##
  # Returns true if +heading+ is below the display threshold

  def suppressed? heading
    return false unless @omit_headings_below

    heading.level > @omit_headings_below
  end

  # :stopdoc:
  alias accept_block_quote     ignore
  alias accept_raw             ignore
  alias accept_rule            ignore
  alias accept_blank_line      ignore
  alias accept_paragraph       ignore
  alias accept_verbatim        ignore
  alias accept_list_end        ignore
  alias accept_list_item_start ignore
  alias accept_list_item_end   ignore
  alias accept_list_end_bullet ignore
  alias accept_list_start      ignore
  alias accept_table           ignore
  # :startdoc:

end

# frozen_string_literal: true
##
# Outputs RDoc markup with hot backspace action!  You will probably need a
# pager to use this output format.
#
# This formatter won't work on 1.8.6 because it lacks String#chars.

class RDoc::Markup::ToBs < RDoc::Markup::ToRdoc

  ##
  # Returns a new ToBs that is ready for hot backspace action!

  def initialize markup = nil
    super

    @in_b  = false
    @in_em = false
  end

  ##
  # Sets a flag that is picked up by #annotate to do the right thing in
  # #convert_string

  def init_tags
    add_tag :BOLD, '+b', '-b'
    add_tag :EM,   '+_', '-_'
    add_tag :TT,   ''  , ''   # we need in_tt information maintained
  end

  ##
  # Makes heading text bold.

  def accept_heading heading
    use_prefix or @res << ' ' * @indent
    @res << @headings[heading.level][0]
    @in_b = true
    @res << attributes(heading.text)
    @in_b = false
    @res << @headings[heading.level][1]
    @res << "\n"
  end

  ##
  # Turns on or off regexp handling for +convert_string+

  def annotate tag
    case tag
    when '+b' then @in_b = true
    when '-b' then @in_b = false
    when '+_' then @in_em = true
    when '-_' then @in_em = false
    end
    ''
  end

  ##
  # Calls convert_string on the result of convert_regexp_handling

  def convert_regexp_handling target
    convert_string super
  end

  ##
  # Adds bold or underline mixed with backspaces

  def convert_string string
    return string unless @in_b or @in_em
    chars = if @in_b then
              string.chars.map do |char| "#{char}\b#{char}" end
            elsif @in_em then
              string.chars.map do |char| "_\b#{char}" end
            end

    chars.join
  end

end
# frozen_string_literal: true
##
# This Markup outputter is used for testing purposes.

class RDoc::Markup::ToTest < RDoc::Markup::Formatter

  # :stopdoc:

  ##
  # :section: Visitor

  def start_accepting
    @res = []
    @list = []
  end

  def end_accepting
    @res
  end

  def accept_paragraph(paragraph)
    @res << convert_flow(@am.flow(paragraph.text))
  end

  def accept_raw raw
    @res << raw.parts.join
  end

  def accept_verbatim(verbatim)
    @res << verbatim.text.gsub(/^(\S)/, '  \1')
  end

  def accept_list_start(list)
    @list << case list.type
             when :BULLET then
               '*'
             when :NUMBER then
               '1'
             else
               list.type
             end
  end

  def accept_list_end(list)
    @list.pop
  end

  def accept_list_item_start(list_item)
    @res << "#{' ' * (@list.size - 1)}#{@list.last}: "
  end

  def accept_list_item_end(list_item)
  end

  def accept_blank_line(blank_line)
    @res << "\n"
  end

  def accept_heading(heading)
    @res << "#{'=' * heading.level} #{heading.text}"
  end

  def accept_rule(rule)
    @res << '-' * rule.weight
  end

  # :startdoc:

end

# frozen_string_literal: true
##
# Manages changes of attributes in a block of text

class RDoc::Markup::AttributeManager

  ##
  # The NUL character

  NULL = "\000".freeze

  #--
  # We work by substituting non-printing characters in to the text. For now
  # I'm assuming that I can substitute a character in the range 0..8 for a 7
  # bit character without damaging the encoded string, but this might be
  # optimistic
  #++

  A_PROTECT = 004 # :nodoc:

  ##
  # Special mask character to prevent inline markup handling

  PROTECT_ATTR = A_PROTECT.chr # :nodoc:

  ##
  # The attributes enabled for this markup object.

  attr_reader :attributes

  ##
  # This maps delimiters that occur around words (such as *bold* or +tt+)
  # where the start and end delimiters and the same. This lets us optimize
  # the regexp

  attr_reader :matching_word_pairs

  ##
  # And this is used when the delimiters aren't the same. In this case the
  # hash maps a pattern to the attribute character

  attr_reader :word_pair_map

  ##
  # This maps HTML tags to the corresponding attribute char

  attr_reader :html_tags

  ##
  # A \ in front of a character that would normally be processed turns off
  # processing. We do this by turning \< into <#{PROTECT}

  attr_reader :protectable

  ##
  # And this maps _regexp handling_ sequences to a name. A regexp handling
  # sequence is something like a WikiWord

  attr_reader :regexp_handlings

  ##
  # A bits of exclusive maps
  attr_reader :exclusive_bitmap

  ##
  # Creates a new attribute manager that understands bold, emphasized and
  # teletype text.

  def initialize
    @html_tags = {}
    @matching_word_pairs = {}
    @protectable = %w[<]
    @regexp_handlings = []
    @word_pair_map = {}
    @exclusive_bitmap = 0
    @attributes = RDoc::Markup::Attributes.new

    add_word_pair "*", "*", :BOLD, true
    add_word_pair "_", "_", :EM, true
    add_word_pair "+", "+", :TT, true

    add_html "em", :EM, true
    add_html "i",  :EM, true
    add_html "b",  :BOLD, true
    add_html "tt",   :TT, true
    add_html "code", :TT, true
  end

  ##
  # Return an attribute object with the given turn_on and turn_off bits set

  def attribute(turn_on, turn_off)
    RDoc::Markup::AttrChanger.new turn_on, turn_off
  end

  ##
  # Changes the current attribute from +current+ to +new+

  def change_attribute current, new
    diff = current ^ new
    attribute(new & diff, current & diff)
  end

  ##
  # Used by the tests to change attributes by name from +current_set+ to
  # +new_set+

  def changed_attribute_by_name current_set, new_set
    current = new = 0
    current_set.each do |name|
      current |= @attributes.bitmap_for(name)
    end

    new_set.each do |name|
      new |= @attributes.bitmap_for(name)
    end

    change_attribute(current, new)
  end

  ##
  # Copies +start_pos+ to +end_pos+ from the current string

  def copy_string(start_pos, end_pos)
    res = @str[start_pos...end_pos]
    res.gsub!(/\000/, '')
    res
  end

  def exclusive?(attr)
    (attr & @exclusive_bitmap) != 0
  end

  NON_PRINTING_START = "\1" # :nodoc:
  NON_PRINTING_END = "\2" # :nodoc:

  ##
  # Map attributes like <b>text</b>to the sequence
  # \001\002<char>\001\003<char>, where <char> is a per-attribute specific
  # character

  def convert_attrs(str, attrs, exclusive = false)
    convert_attrs_matching_word_pairs(str, attrs, exclusive)
    convert_attrs_word_pair_map(str, attrs, exclusive)
  end

  def convert_attrs_matching_word_pairs(str, attrs, exclusive)
    # first do matching ones
    tags = @matching_word_pairs.select { |start, bitmap|
      if exclusive && exclusive?(bitmap)
        true
      elsif !exclusive && !exclusive?(bitmap)
        true
      else
        false
      end
    }.keys
    return if tags.empty?
    all_tags = @matching_word_pairs.keys

    re = /(^|\W|[#{all_tags.join("")}])([#{tags.join("")}])(\2*[#\\]?[\w:.\/\[\]-]+?\S?)\2(?!\2)([#{all_tags.join("")}]|\W|$)/

    1 while str.gsub!(re) { |orig|
      attr = @matching_word_pairs[$2]
      attr_updated = attrs.set_attrs($`.length + $1.length + $2.length, $3.length, attr)
      if attr_updated
        $1 + NULL * $2.length + $3 + NULL * $2.length + $4
      else
        $1 + NON_PRINTING_START + $2 + NON_PRINTING_END + $3 + NON_PRINTING_START + $2 + NON_PRINTING_END + $4
      end
    }
    str.delete!(NON_PRINTING_START + NON_PRINTING_END)
  end

  def convert_attrs_word_pair_map(str, attrs, exclusive)
    # then non-matching
    unless @word_pair_map.empty? then
      @word_pair_map.each do |regexp, attr|
        if !exclusive
          next if exclusive?(attr)
        else
          next if !exclusive?(attr)
        end
        1 while str.gsub!(regexp) { |orig|
          updated = attrs.set_attrs($`.length + $1.length, $2.length, attr)
          if updated
            NULL * $1.length + $2 + NULL * $3.length
          else
            orig
          end
        }
      end
    end
  end

  ##
  # Converts HTML tags to RDoc attributes

  def convert_html(str, attrs, exclusive = false)
    tags = @html_tags.select { |start, bitmap|
      if exclusive && exclusive?(bitmap)
        true
      elsif !exclusive && !exclusive?(bitmap)
        true
      else
        false
      end
    }.keys.join '|'

    1 while str.gsub!(/<(#{tags})>(.*?)<\/\1>/i) { |orig|
      attr = @html_tags[$1.downcase]
      html_length = $1.length + 2
      seq = NULL * html_length
      attrs.set_attrs($`.length + html_length, $2.length, attr)
      seq + $2 + seq + NULL
    }
  end

  ##
  # Converts regexp handling sequences to RDoc attributes

  def convert_regexp_handlings str, attrs, exclusive = false
    @regexp_handlings.each do |regexp, attribute|
      if exclusive
        next if !exclusive?(attribute)
      else
        next if exclusive?(attribute)
      end
      str.scan(regexp) do
        capture = $~.size == 1 ? 0 : 1

        s, e = $~.offset capture

        attrs.set_attrs s, e - s, attribute | @attributes.regexp_handling
      end
    end
  end

  ##
  # Escapes regexp handling sequences of text to prevent conversion to RDoc

  def mask_protected_sequences
    # protect __send__, __FILE__, etc.
    @str.gsub!(/__([a-z]+)__/i,
      "_#{PROTECT_ATTR}_#{PROTECT_ATTR}\\1_#{PROTECT_ATTR}_#{PROTECT_ATTR}")
    @str.gsub!(/(\A|[^\\])\\([#{Regexp.escape @protectable.join}])/m,
               "\\1\\2#{PROTECT_ATTR}")
    @str.gsub!(/\\(\\[#{Regexp.escape @protectable.join}])/m, "\\1")
  end

  ##
  # Unescapes regexp handling sequences of text

  def unmask_protected_sequences
    @str.gsub!(/(.)#{PROTECT_ATTR}/, "\\1\000")
  end

  ##
  # Adds a markup class with +name+ for words wrapped in the +start+ and
  # +stop+ character.  To make words wrapped with "*" bold:
  #
  #   am.add_word_pair '*', '*', :BOLD

  def add_word_pair(start, stop, name, exclusive = false)
    raise ArgumentError, "Word flags may not start with '<'" if
      start[0,1] == '<'

    bitmap = @attributes.bitmap_for name

    if start == stop then
      @matching_word_pairs[start] = bitmap
    else
      pattern = /(#{Regexp.escape start})(\S+)(#{Regexp.escape stop})/
      @word_pair_map[pattern] = bitmap
    end

    @protectable << start[0,1]
    @protectable.uniq!

    @exclusive_bitmap |= bitmap if exclusive
  end

  ##
  # Adds a markup class with +name+ for words surrounded by HTML tag +tag+.
  # To process emphasis tags:
  #
  #   am.add_html 'em', :EM

  def add_html(tag, name, exclusive = false)
    bitmap = @attributes.bitmap_for name
    @html_tags[tag.downcase] = bitmap
    @exclusive_bitmap |= bitmap if exclusive
  end

  ##
  # Adds a regexp handling for +pattern+ with +name+.  A simple URL handler
  # would be:
  #
  #   @am.add_regexp_handling(/((https?:)\S+\w)/, :HYPERLINK)

  def add_regexp_handling pattern, name, exclusive = false
    bitmap = @attributes.bitmap_for(name)
    @regexp_handlings << [pattern, bitmap]
    @exclusive_bitmap |= bitmap if exclusive
  end

  ##
  # Processes +str+ converting attributes, HTML and regexp handlings

  def flow str
    @str = str.dup

    mask_protected_sequences

    @attrs = RDoc::Markup::AttrSpan.new @str.length, @exclusive_bitmap

    convert_attrs            @str, @attrs, true
    convert_html             @str, @attrs, true
    convert_regexp_handlings @str, @attrs, true
    convert_attrs            @str, @attrs
    convert_html             @str, @attrs
    convert_regexp_handlings @str, @attrs

    unmask_protected_sequences

    split_into_flow
  end

  ##
  # Debug method that prints a string along with its attributes

  def display_attributes
    puts
    puts @str.tr(NULL, "!")
    bit = 1
    16.times do |bno|
      line = ""
      @str.length.times do |i|
        if (@attrs[i] & bit) == 0
          line << " "
        else
          if bno.zero?
            line << "S"
          else
            line << ("%d" % (bno+1))
          end
        end
      end
      puts(line) unless line =~ /^ *$/
      bit <<= 1
    end
  end

  ##
  # Splits the string into chunks by attribute change

  def split_into_flow
    res = []
    current_attr = 0

    str_len = @str.length

    # skip leading invisible text
    i = 0
    i += 1 while i < str_len and @str[i].chr == "\0"
    start_pos = i

    # then scan the string, chunking it on attribute changes
    while i < str_len
      new_attr = @attrs[i]
      if new_attr != current_attr
        if i > start_pos
          res << copy_string(start_pos, i)
          start_pos = i
        end

        res << change_attribute(current_attr, new_attr)
        current_attr = new_attr

        if (current_attr & @attributes.regexp_handling) != 0 then
          i += 1 while
            i < str_len and (@attrs[i] & @attributes.regexp_handling) != 0

          res << RDoc::Markup::RegexpHandling.new(current_attr,
                                                  copy_string(start_pos, i))
          start_pos = i
          next
        end
      end

      # move on, skipping any invisible characters
      begin
        i += 1
      end while i < str_len and @str[i].chr == "\0"
    end

    # tidy up trailing text
    if start_pos < str_len
      res << copy_string(start_pos, str_len)
    end

    # and reset to all attributes off
    res << change_attribute(current_attr, 0) if current_attr != 0

    res
  end

end

# frozen_string_literal: true
##
# Subclass of the RDoc::Markup::ToHtml class that supports looking up method
# names, classes, etc to create links.  RDoc::CrossReference is used to
# generate those links based on the current context.

class RDoc::Markup::ToHtmlCrossref < RDoc::Markup::ToHtml

  # :stopdoc:
  ALL_CROSSREF_REGEXP = RDoc::CrossReference::ALL_CROSSREF_REGEXP
  CLASS_REGEXP_STR    = RDoc::CrossReference::CLASS_REGEXP_STR
  CROSSREF_REGEXP     = RDoc::CrossReference::CROSSREF_REGEXP
  METHOD_REGEXP_STR   = RDoc::CrossReference::METHOD_REGEXP_STR
  # :startdoc:

  ##
  # RDoc::CodeObject for generating references

  attr_accessor :context

  ##
  # Should we show '#' characters on method references?

  attr_accessor :show_hash

  ##
  # Creates a new crossref resolver that generates links relative to +context+
  # which lives at +from_path+ in the generated files.  '#' characters on
  # references are removed unless +show_hash+ is true.  Only method names
  # preceded by '#' or '::' are linked, unless +hyperlink_all+ is true.

  def initialize(options, from_path, context, markup = nil)
    raise ArgumentError, 'from_path cannot be nil' if from_path.nil?

    super options, markup

    @context       = context
    @from_path     = from_path
    @hyperlink_all = @options.hyperlink_all
    @show_hash     = @options.show_hash

    @cross_reference = RDoc::CrossReference.new @context
  end

  def init_link_notation_regexp_handlings
    add_regexp_handling_RDOCLINK

    # The crossref must be linked before tidylink because Klass.method[:sym]
    # will be processed as a tidylink first and will be broken.
    crossref_re = @options.hyperlink_all ? ALL_CROSSREF_REGEXP : CROSSREF_REGEXP
    @markup.add_regexp_handling crossref_re, :CROSSREF

    add_regexp_handling_TIDYLINK
  end

  ##
  # Creates a link to the reference +name+ if the name exists.  If +text+ is
  # given it is used as the link text, otherwise +name+ is used.

  def cross_reference name, text = nil, code = true
    lookup = name

    name = name[1..-1] unless @show_hash if name[0, 1] == '#'

    if !(name.end_with?('+@', '-@')) and name =~ /(.*[^#:])@/
      text ||= "#{CGI.unescape $'} at <code>#{$1}</code>"
      code = false
    else
      text ||= name
    end

    link lookup, text, code
  end

  ##
  # We're invoked when any text matches the CROSSREF pattern.  If we find the
  # corresponding reference, generate a link.  If the name we're looking for
  # contains no punctuation, we look for it up the module/class chain.  For
  # example, ToHtml is found, even without the <tt>RDoc::Markup::</tt> prefix,
  # because we look for it in module Markup first.

  def handle_regexp_CROSSREF(target)
    name = target.text

    return name if name =~ /@[\w-]+\.[\w-]/ # labels that look like emails

    unless @hyperlink_all then
      # This ensures that words entirely consisting of lowercase letters will
      # not have cross-references generated (to suppress lots of erroneous
      # cross-references to "new" in text, for instance)
      return name if name =~ /\A[a-z]*\z/
    end

    cross_reference name
  end

  ##
  # Handles <tt>rdoc-ref:</tt> scheme links and allows RDoc::Markup::ToHtml to
  # handle other schemes.

  def handle_regexp_HYPERLINK target
    return cross_reference $' if target.text =~ /\Ardoc-ref:/

    super
  end

  ##
  # +target+ is an rdoc-schemed link that will be converted into a hyperlink.
  # For the rdoc-ref scheme the cross-reference will be looked up and the
  # given name will be used.
  #
  # All other contents are handled by
  # {the superclass}[rdoc-ref:RDoc::Markup::ToHtml#handle_regexp_RDOCLINK]

  def handle_regexp_RDOCLINK target
    url = target.text

    case url
    when /\Ardoc-ref:/ then
      cross_reference $'
    else
      super
    end
  end

  ##
  # Generates links for <tt>rdoc-ref:</tt> scheme URLs and allows
  # RDoc::Markup::ToHtml to handle other schemes.

  def gen_url url, text
    return super unless url =~ /\Ardoc-ref:/

    name = $'
    cross_reference name, text, name == text
  end

  ##
  # Creates an HTML link to +name+ with the given +text+.

  def link name, text, code = true
    if !(name.end_with?('+@', '-@')) and name =~ /(.*[^#:])@/
      name = $1
      label = $'
    end

    ref = @cross_reference.resolve name, text

    case ref
    when String then
      ref
    else
      path = ref.as_href @from_path

      if code and RDoc::CodeObject === ref and !(RDoc::TopLevel === ref)
        text = "<code>#{CGI.escapeHTML text}</code>"
      end

      if path =~ /#/ then
        path << "-label-#{label}"
      elsif ref.sections and
            ref.sections.any? { |section| label == section.title } then
        path << "##{label}"
      else
        if ref.respond_to?(:aref)
          path << "##{ref.aref}-label-#{label}"
        else
          path << "#label-#{label}"
        end
      end if label

      "<a href=\"#{path}\">#{text}</a>"
    end
  end

end

# frozen_string_literal: true
##
# A section of verbatim text

class RDoc::Markup::Verbatim < RDoc::Markup::Raw

  ##
  # Format of this verbatim section

  attr_accessor :format

  def initialize *parts # :nodoc:
    super

    @format = nil
  end

  def == other # :nodoc:
    super and @format == other.format
  end

  ##
  # Calls #accept_verbatim on +visitor+

  def accept visitor
    visitor.accept_verbatim self
  end

  ##
  # Collapses 3+ newlines into two newlines

  def normalize
    parts = []

    newlines = 0

    @parts.each do |part|
      case part
      when /^\s*\n/ then
        newlines += 1
        parts << part if newlines == 1
      else
        newlines = 0
        parts << part
      end
    end

    parts.pop if parts.last =~ /\A\r?\n\z/

    @parts = parts
  end

  def pretty_print q # :nodoc:
    self.class.name =~ /.*::(\w{1,4})/i

    q.group 2, "[#{$1.downcase}: ", ']' do
      if @format then
        q.text "format: #{@format}"
        q.breakable
      end

      q.seplist @parts do |part|
        q.pp part
      end
    end
  end

  ##
  # Is this verbatim section Ruby code?

  def ruby?
    @format ||= nil # TODO for older ri data, switch the tree to marshal_dump
    @format == :ruby
  end

  ##
  # The text of the section

  def text
    @parts.join
  end

end

# frozen_string_literal: true
##
# An empty line.  This class is a singleton.

class RDoc::Markup::BlankLine

  @instance = new

  ##
  # RDoc::Markup::BlankLine is a singleton

  def self.new
    @instance
  end

  ##
  # Calls #accept_blank_line on +visitor+

  def accept visitor
    visitor.accept_blank_line self
  end

  def pretty_print q # :nodoc:
    q.text 'blankline'
  end

end

# frozen_string_literal: true
require 'cgi'

##
# Outputs RDoc markup as HTML.

class RDoc::Markup::ToHtml < RDoc::Markup::Formatter

  include RDoc::Text

  # :section: Utilities

  ##
  # Maps RDoc::Markup::Parser::LIST_TOKENS types to HTML tags

  LIST_TYPE_TO_HTML = {
    :BULLET => ['<ul>',                                      '</ul>'],
    :LABEL  => ['<dl class="rdoc-list label-list">',         '</dl>'],
    :LALPHA => ['<ol style="list-style-type: lower-alpha">', '</ol>'],
    :NOTE   => ['<dl class="rdoc-list note-list">',          '</dl>'],
    :NUMBER => ['<ol>',                                      '</ol>'],
    :UALPHA => ['<ol style="list-style-type: upper-alpha">', '</ol>'],
  }

  attr_reader :res # :nodoc:
  attr_reader :in_list_entry # :nodoc:
  attr_reader :list # :nodoc:

  ##
  # The RDoc::CodeObject HTML is being generated for.  This is used to
  # generate namespaced URI fragments

  attr_accessor :code_object

  ##
  # Path to this document for relative links

  attr_accessor :from_path

  # :section:

  ##
  # Creates a new formatter that will output HTML

  def initialize options, markup = nil
    super

    @code_object = nil
    @from_path = ''
    @in_list_entry = nil
    @list = nil
    @th = nil
    @hard_break = "<br>\n"

    init_regexp_handlings

    init_tags
  end

  # :section: Regexp Handling
  #
  # These methods are used by regexp handling markup added by RDoc::Markup#add_regexp_handling.

  ##
  # Adds regexp handlings.

  def init_regexp_handlings
    # external links
    @markup.add_regexp_handling(/(?:link:|https?:|mailto:|ftp:|irc:|www\.)\S+\w/,
                                :HYPERLINK)
    init_link_notation_regexp_handlings
  end

  ##
  # Adds regexp handlings about link notations.

  def init_link_notation_regexp_handlings
    add_regexp_handling_RDOCLINK
    add_regexp_handling_TIDYLINK
  end

  def handle_RDOCLINK url # :nodoc:
    case url
    when /^rdoc-ref:/
      $'
    when /^rdoc-label:/
      text = $'

      text = case text
             when /\Alabel-/    then $'
             when /\Afootmark-/ then $'
             when /\Afoottext-/ then $'
             else                    text
             end

      gen_url url, text
    when /^rdoc-image:/
      "<img src=\"#{$'}\">"
    else
      url =~ /\Ardoc-[a-z]+:/

      $'
    end
  end

  ##
  # +target+ is a <code><br></code>

  def handle_regexp_HARD_BREAK target
    '<br>'
  end

  ##
  # +target+ is a potential link.  The following schemes are handled:
  #
  # <tt>mailto:</tt>::
  #   Inserted as-is.
  # <tt>http:</tt>::
  #   Links are checked to see if they reference an image. If so, that image
  #   gets inserted using an <tt><img></tt> tag. Otherwise a conventional
  #   <tt><a href></tt> is used.
  # <tt>link:</tt>::
  #   Reference to a local file relative to the output directory.

  def handle_regexp_HYPERLINK(target)
    url = target.text

    gen_url url, url
  end

  ##
  # +target+ is an rdoc-schemed link that will be converted into a hyperlink.
  #
  # For the +rdoc-ref+ scheme the named reference will be returned without
  # creating a link.
  #
  # For the +rdoc-label+ scheme the footnote and label prefixes are stripped
  # when creating a link.  All other contents will be linked verbatim.

  def handle_regexp_RDOCLINK target
    handle_RDOCLINK target.text
  end

  ##
  # This +target+ is a link where the label is different from the URL
  # <tt>label[url]</tt> or <tt>{long label}[url]</tt>

  def handle_regexp_TIDYLINK(target)
    text = target.text

    return text unless
      text =~ /^\{(.*)\}\[(.*?)\]$/ or text =~ /^(\S+)\[(.*?)\]$/

    label = $1
    url   = $2

    label = handle_RDOCLINK label if /^rdoc-image:/ =~ label

    gen_url url, label
  end

  # :section: Visitor
  #
  # These methods implement the HTML visitor.

  ##
  # Prepares the visitor for HTML generation

  def start_accepting
    @res = []
    @in_list_entry = []
    @list = []
  end

  ##
  # Returns the generated output

  def end_accepting
    @res.join
  end

  ##
  # Adds +block_quote+ to the output

  def accept_block_quote block_quote
    @res << "\n<blockquote>"

    block_quote.parts.each do |part|
      part.accept self
    end

    @res << "</blockquote>\n"
  end

  ##
  # Adds +paragraph+ to the output

  def accept_paragraph paragraph
    @res << "\n<p>"
    text = paragraph.text @hard_break
    text = text.gsub(/\r?\n/, ' ')
    @res << to_html(text)
    @res << "</p>\n"
  end

  ##
  # Adds +verbatim+ to the output

  def accept_verbatim verbatim
    text = verbatim.text.rstrip

    klass = nil

    content = if verbatim.ruby? or parseable? text then
                begin
                  tokens = RDoc::Parser::RipperStateLex.parse text
                  klass  = ' class="ruby"'

                  result = RDoc::TokenStream.to_html tokens
                  result = result + "\n" unless "\n" == result[-1]
                  result
                rescue
                  CGI.escapeHTML text
                end
              else
                CGI.escapeHTML text
              end

    if @options.pipe then
      @res << "\n<pre><code>#{CGI.escapeHTML text}\n</code></pre>\n"
    else
      @res << "\n<pre#{klass}>#{content}</pre>\n"
    end
  end

  ##
  # Adds +rule+ to the output

  def accept_rule rule
    @res << "<hr>\n"
  end

  ##
  # Prepares the visitor for consuming +list+

  def accept_list_start(list)
    @list << list.type
    @res << html_list_name(list.type, true)
    @in_list_entry.push false
  end

  ##
  # Finishes consumption of +list+

  def accept_list_end(list)
    @list.pop
    if tag = @in_list_entry.pop
      @res << tag
    end
    @res << html_list_name(list.type, false) << "\n"
  end

  ##
  # Prepares the visitor for consuming +list_item+

  def accept_list_item_start(list_item)
    if tag = @in_list_entry.last
      @res << tag
    end

    @res << list_item_start(list_item, @list.last)
  end

  ##
  # Finishes consumption of +list_item+

  def accept_list_item_end(list_item)
    @in_list_entry[-1] = list_end_for(@list.last)
  end

  ##
  # Adds +blank_line+ to the output

  def accept_blank_line(blank_line)
    # @res << annotate("<p />") << "\n"
  end

  ##
  # Adds +heading+ to the output.  The headings greater than 6 are trimmed to
  # level 6.

  def accept_heading heading
    level = [6, heading.level].min

    label = heading.label @code_object

    @res << if @options.output_decoration
              "\n<h#{level} id=\"#{label}\">"
            else
              "\n<h#{level}>"
            end
    @res << to_html(heading.text)
    unless @options.pipe then
      @res << "<span><a href=\"##{label}\">&para;</a>"
      @res << " <a href=\"#top\">&uarr;</a></span>"
    end
    @res << "</h#{level}>\n"
  end

  ##
  # Adds +raw+ to the output

  def accept_raw raw
    @res << raw.parts.join("\n")
  end

  ##
  # Adds +table+ to the output

  def accept_table header, body, aligns
    @res << "\n<table role=\"table\">\n<thead>\n<tr>\n"
    header.zip(aligns) do |text, align|
      @res << '<th'
      @res << ' align="' << align << '"' if align
      @res << '>' << CGI.escapeHTML(text) << "</th>\n"
    end
    @res << "</tr>\n</thead>\n<tbody>\n"
    body.each do |row|
      @res << "<tr>\n"
      row.zip(aligns) do |text, align|
        @res << '<td'
        @res << ' align="' << align << '"' if align
        @res << '>' << CGI.escapeHTML(text) << "</td>\n"
      end
      @res << "</tr>\n"
    end
    @res << "</tbody>\n</table>\n"
  end

  # :section: Utilities

  ##
  # CGI-escapes +text+

  def convert_string(text)
    CGI.escapeHTML text
  end

  ##
  # Generate a link to +url+ with content +text+.  Handles the special cases
  # for img: and link: described under handle_regexp_HYPERLINK

  def gen_url url, text
    scheme, url, id = parse_url url

    if %w[http https link].include?(scheme) and
       url =~ /\.(gif|png|jpg|jpeg|bmp)$/ then
      "<img src=\"#{url}\" />"
    else
      if scheme != 'link' and /\.(?:rb|rdoc|md)\z/i =~ url
        url = url.sub(%r%\A([./]*)(.*)\z%) { "#$1#{$2.tr('.', '_')}.html" }
      end

      text = text.sub %r%^#{scheme}:/*%i, ''
      text = text.sub %r%^[*\^](\d+)$%,   '\1'

      link = "<a#{id} href=\"#{url}\">#{text}</a>"

      link = "<sup>#{link}</sup>" if /"foot/ =~ id

      link
    end
  end

  ##
  # Determines the HTML list element for +list_type+ and +open_tag+

  def html_list_name(list_type, open_tag)
    tags = LIST_TYPE_TO_HTML[list_type]
    raise RDoc::Error, "Invalid list type: #{list_type.inspect}" unless tags
    tags[open_tag ? 0 : 1]
  end

  ##
  # Maps attributes to HTML tags

  def init_tags
    add_tag :BOLD, "<strong>", "</strong>"
    add_tag :TT,   "<code>",   "</code>"
    add_tag :EM,   "<em>",     "</em>"
  end

  ##
  # Returns the HTML tag for +list_type+, possible using a label from
  # +list_item+

  def list_item_start(list_item, list_type)
    case list_type
    when :BULLET, :LALPHA, :NUMBER, :UALPHA then
      "<li>"
    when :LABEL, :NOTE then
      Array(list_item.label).map do |label|
        "<dt>#{to_html label}\n"
      end.join << "<dd>"
    else
      raise RDoc::Error, "Invalid list type: #{list_type.inspect}"
    end
  end

  ##
  # Returns the HTML end-tag for +list_type+

  def list_end_for(list_type)
    case list_type
    when :BULLET, :LALPHA, :NUMBER, :UALPHA then
      "</li>"
    when :LABEL, :NOTE then
      "</dd>"
    else
      raise RDoc::Error, "Invalid list type: #{list_type.inspect}"
    end
  end

  ##
  # Returns true if text is valid ruby syntax

  def parseable? text
    verbose, $VERBOSE = $VERBOSE, nil
    eval("BEGIN {return true}\n#{text}")
  rescue SyntaxError
    false
  ensure
    $VERBOSE = verbose
  end

  ##
  # Converts +item+ to HTML using RDoc::Text#to_html

  def to_html item
    super convert_flow @am.flow item
  end

end

# frozen_string_literal: true
##
# Handle common directives that can occur in a block of text:
#
#   \:include: filename
#
# Directives can be escaped by preceding them with a backslash.
#
# RDoc plugin authors can register additional directives to be handled by
# using RDoc::Markup::PreProcess::register.
#
# Any directive that is not built-in to RDoc (including those registered via
# plugins) will be stored in the metadata hash on the CodeObject the comment
# is attached to.  See RDoc::Markup@Directives for the list of built-in
# directives.

class RDoc::Markup::PreProcess

  ##
  # An RDoc::Options instance that will be filled in with overrides from
  # directives

  attr_accessor :options

  ##
  # Adds a post-process handler for directives.  The handler will be called
  # with the result RDoc::Comment (or text String) and the code object for the
  # comment (if any).

  def self.post_process &block
    @post_processors << block
  end

  ##
  # Registered post-processors

  def self.post_processors
    @post_processors
  end

  ##
  # Registers +directive+ as one handled by RDoc.  If a block is given the
  # directive will be replaced by the result of the block, otherwise the
  # directive will be removed from the processed text.
  #
  # The block will be called with the directive name and the directive
  # parameter:
  #
  #   RDoc::Markup::PreProcess.register 'my-directive' do |directive, param|
  #     # replace text, etc.
  #   end

  def self.register directive, &block
    @registered[directive] = block
  end

  ##
  # Registered directives

  def self.registered
    @registered
  end

  ##
  # Clears all registered directives and post-processors

  def self.reset
    @post_processors = []
    @registered = {}
  end

  reset

  ##
  # Creates a new pre-processor for +input_file_name+ that will look for
  # included files in +include_path+

  def initialize(input_file_name, include_path)
    @input_file_name = input_file_name
    @include_path = include_path
    @options = nil
  end

  ##
  # Look for directives in the given +text+.
  #
  # Options that we don't handle are yielded.  If the block returns false the
  # directive is restored to the text.  If the block returns nil or no block
  # was given the directive is handled according to the registered directives.
  # If a String was returned the directive is replaced with the string.
  #
  # If no matching directive was registered the directive is restored to the
  # text.
  #
  # If +code_object+ is given and the directive is unknown then the
  # directive's parameter is set as metadata on the +code_object+.  See
  # RDoc::CodeObject#metadata for details.

  def handle text, code_object = nil, &block
    if RDoc::Comment === text then
      comment = text
      text = text.text
    end

    # regexp helper (square brackets for optional)
    # $1      $2  $3        $4      $5
    # [prefix][\]:directive:[spaces][param]newline
    text = text.gsub(/^([ \t]*(?:#|\/?\*)?[ \t]*)(\\?):(\w+):([ \t]*)(.+)?(\r?\n|$)/) do
      # skip something like ':toto::'
      next $& if $4.empty? and $5 and $5[0, 1] == ':'

      # skip if escaped
      next "#$1:#$3:#$4#$5\n" unless $2.empty?

      # This is not in handle_directive because I didn't want to pass another
      # argument into it
      if comment and $3 == 'markup' then
        next "#{$1.strip}\n" unless $5
        comment.format = $5.downcase
        next "#{$1.strip}\n"
      end

      handle_directive $1, $3, $5, code_object, text.encoding, &block
    end

    if comment then
      comment.text = text
    else
      comment = text
    end

    self.class.post_processors.each do |handler|
      handler.call comment, code_object
    end

    text
  end

  ##
  # Performs the actions described by +directive+ and its parameter +param+.
  #
  # +code_object+ is used for directives that operate on a class or module.
  # +prefix+ is used to ensure the replacement for handled directives is
  # correct.  +encoding+ is used for the <tt>include</tt> directive.
  #
  # For a list of directives in RDoc see RDoc::Markup.
  #--
  # When 1.8.7 support is ditched prefix can be defaulted to ''

  def handle_directive prefix, directive, param, code_object = nil,
                       encoding = nil
    blankline = "#{prefix.strip}\n"
    directive = directive.downcase

    case directive
    when 'arg', 'args' then
      return "#{prefix}:#{directive}: #{param}\n" unless code_object && code_object.kind_of?(RDoc::AnyMethod)

      code_object.params = param

      blankline
    when 'category' then
      if RDoc::Context === code_object then
        section = code_object.add_section param
        code_object.temporary_section = section
      end

      blankline # ignore category if we're not on an RDoc::Context
    when 'doc' then
      return blankline unless code_object
      code_object.document_self = true
      code_object.force_documentation = true

      blankline
    when 'enddoc' then
      return blankline unless code_object
      code_object.done_documenting = true

      blankline
    when 'include' then
      filename = param.split(' ', 2).first
      include_file filename, prefix, encoding
    when 'main' then
      @options.main_page = param if @options.respond_to? :main_page

      blankline
    when 'nodoc' then
      return blankline unless code_object
      code_object.document_self = nil # notify nodoc
      code_object.document_children = param !~ /all/i

      blankline
    when 'notnew', 'not_new', 'not-new' then
      return blankline unless RDoc::AnyMethod === code_object

      code_object.dont_rename_initialize = true

      blankline
    when 'startdoc' then
      return blankline unless code_object

      code_object.start_doc
      code_object.force_documentation = true

      blankline
    when 'stopdoc' then
      return blankline unless code_object

      code_object.stop_doc

      blankline
    when 'title' then
      @options.default_title = param if @options.respond_to? :default_title=

      blankline
    when 'yield', 'yields' then
      return blankline unless code_object
      # remove parameter &block
      code_object.params = code_object.params.sub(/,?\s*&\w+/, '') if code_object.params

      code_object.block_params = param

      blankline
    else
      result = yield directive, param if block_given?

      case result
      when nil then
        code_object.metadata[directive] = param if code_object

        if RDoc::Markup::PreProcess.registered.include? directive then
          handler = RDoc::Markup::PreProcess.registered[directive]
          result = handler.call directive, param if handler
        else
          result = "#{prefix}:#{directive}: #{param}\n"
        end
      when false then
        result = "#{prefix}:#{directive}: #{param}\n"
      end

      result
    end
  end

  ##
  # Handles the <tt>:include: _filename_</tt> directive.
  #
  # If the first line of the included file starts with '#', and contains
  # an encoding information in the form 'coding:' or 'coding=', it is
  # removed.
  #
  # If all lines in the included file start with a '#', this leading '#'
  # is removed before inclusion. The included content is indented like
  # the <tt>:include:</tt> directive.
  #--
  # so all content will be verbatim because of the likely space after '#'?
  # TODO shift left the whole file content in that case
  # TODO comment stop/start #-- and #++ in included file must be processed here

  def include_file name, indent, encoding
    full_name = find_include_file name

    unless full_name then
      warn "Couldn't find file to include '#{name}' from #{@input_file_name}"
      return ''
    end

    content = RDoc::Encoding.read_file full_name, encoding, true
    content = RDoc::Encoding.remove_magic_comment content

    # strip magic comment
    content = content.sub(/\A# .*coding[=:].*$/, '').lstrip

    # strip leading '#'s, but only if all lines start with them
    if content =~ /^[^#]/ then
      content.gsub(/^/, indent)
    else
      content.gsub(/^#?/, indent)
    end
  end

  ##
  # Look for the given file in the directory containing the current file,
  # and then in each of the directories specified in the RDOC_INCLUDE path

  def find_include_file(name)
    to_search = [File.dirname(@input_file_name)].concat @include_path
    to_search.each do |dir|
      full_name = File.join(dir, name)
      stat = File.stat(full_name) rescue next
      return full_name if stat.readable?
    end
    nil
  end

end
# frozen_string_literal: true
##
# A Paragraph of text

class RDoc::Markup::Paragraph < RDoc::Markup::Raw

  ##
  # Calls #accept_paragraph on +visitor+

  def accept visitor
    visitor.accept_paragraph self
  end

  ##
  # Joins the raw paragraph text and converts inline HardBreaks to the
  # +hard_break+ text.

  def text hard_break = ''
    @parts.map do |part|
      if RDoc::Markup::HardBreak === part then
        hard_break
      else
        part
      end
    end.join
  end

end

# frozen_string_literal: true
# :markup: markdown

##
# Outputs parsed markup as Markdown

class RDoc::Markup::ToMarkdown < RDoc::Markup::ToRdoc

  ##
  # Creates a new formatter that will output Markdown format text

  def initialize markup = nil
    super

    @headings[1] = ['# ',      '']
    @headings[2] = ['## ',     '']
    @headings[3] = ['### ',    '']
    @headings[4] = ['#### ',   '']
    @headings[5] = ['##### ',  '']
    @headings[6] = ['###### ', '']

    add_regexp_handling_RDOCLINK
    add_regexp_handling_TIDYLINK

    @hard_break = "  \n"
  end

  ##
  # Maps attributes to HTML sequences

  def init_tags
    add_tag :BOLD, '**', '**'
    add_tag :EM,   '*',  '*'
    add_tag :TT,   '`',  '`'
  end

  ##
  # Adds a newline to the output

  def handle_regexp_HARD_BREAK target
    "  \n"
  end

  ##
  # Finishes consumption of `list`

  def accept_list_end list
    @res << "\n"

    super
  end

  ##
  # Finishes consumption of `list_item`

  def accept_list_item_end list_item
    width = case @list_type.last
            when :BULLET then
              4
            when :NOTE, :LABEL then
              use_prefix

              4
            else
              @list_index[-1] = @list_index.last.succ
              4
            end

    @indent -= width
  end

  ##
  # Prepares the visitor for consuming `list_item`

  def accept_list_item_start list_item
    type = @list_type.last

    case type
    when :NOTE, :LABEL then
      bullets = Array(list_item.label).map do |label|
        attributes(label).strip
      end.join "\n"

      bullets << "\n:"

      @prefix = ' ' * @indent
      @indent += 4
      @prefix << bullets + (' ' * (@indent - 1))
    else
      bullet = type == :BULLET ? '*' : @list_index.last.to_s + '.'
      @prefix = (' ' * @indent) + bullet.ljust(4)

      @indent += 4
    end
  end

  ##
  # Prepares the visitor for consuming `list`

  def accept_list_start list
    case list.type
    when :BULLET, :LABEL, :NOTE then
      @list_index << nil
    when :LALPHA, :NUMBER, :UALPHA then
      @list_index << 1
    else
      raise RDoc::Error, "invalid list type #{list.type}"
    end

    @list_width << 4
    @list_type << list.type
  end

  ##
  # Adds `rule` to the output

  def accept_rule rule
    use_prefix or @res << ' ' * @indent
    @res << '-' * 3
    @res << "\n"
  end

  ##
  # Outputs `verbatim` indented 4 columns

  def accept_verbatim verbatim
    indent = ' ' * (@indent + 4)

    verbatim.parts.each do |part|
      @res << indent unless part == "\n"
      @res << part
    end

    @res << "\n"
  end

  ##
  # Creates a Markdown-style URL from +url+ with +text+.

  def gen_url url, text
    scheme, url, = parse_url url

    "[#{text.sub(%r{^#{scheme}:/*}i, '')}](#{url})"
  end

  ##
  # Handles <tt>rdoc-</tt> type links for footnotes.

  def handle_rdoc_link url
    case url
    when /^rdoc-ref:/ then
      $'
    when /^rdoc-label:footmark-(\d+)/ then
      "[^#{$1}]:"
    when /^rdoc-label:foottext-(\d+)/ then
      "[^#{$1}]"
    when /^rdoc-label:label-/ then
      gen_url url, $'
    when /^rdoc-image:/ then
      "![](#{$'})"
    when /^rdoc-[a-z]+:/ then
      $'
    end
  end

  ##
  # Converts the RDoc markup tidylink into a Markdown.style link.

  def handle_regexp_TIDYLINK target
    text = target.text

    return text unless text =~ /\{(.*?)\}\[(.*?)\]/ or text =~ /(\S+)\[(.*?)\]/

    label = $1
    url   = $2

    if url =~ /^rdoc-label:foot/ then
      handle_rdoc_link url
    else
      gen_url url, label
    end
  end

  ##
  # Converts the rdoc-...: links into a Markdown.style links.

  def handle_regexp_RDOCLINK target
    handle_rdoc_link target.text
  end

end

# frozen_string_literal: true
##
# Outputs RDoc markup as paragraphs with inline markup only.

class RDoc::Markup::ToHtmlSnippet < RDoc::Markup::ToHtml

  ##
  # After this many characters the input will be cut off.

  attr_reader :character_limit

  ##
  # The number of characters seen so far.

  attr_reader :characters # :nodoc:

  ##
  # The attribute bitmask

  attr_reader :mask

  ##
  # After this many paragraphs the input will be cut off.

  attr_reader :paragraph_limit

  ##
  # Count of paragraphs found

  attr_reader :paragraphs

  ##
  # Creates a new ToHtmlSnippet formatter that will cut off the input on the
  # next word boundary after the given number of +characters+ or +paragraphs+
  # of text have been encountered.

  def initialize options, characters = 100, paragraphs = 3, markup = nil
    super options, markup

    @character_limit = characters
    @paragraph_limit = paragraphs

    @characters = 0
    @mask       = 0
    @paragraphs = 0

    @markup.add_regexp_handling RDoc::CrossReference::CROSSREF_REGEXP, :CROSSREF
  end

  ##
  # Adds +heading+ to the output as a paragraph

  def accept_heading heading
    @res << "<p>#{to_html heading.text}\n"

    add_paragraph
  end

  ##
  # Raw sections are untrusted and ignored

  alias accept_raw ignore

  ##
  # Rules are ignored

  alias accept_rule ignore

  def accept_paragraph paragraph
    para = @in_list_entry.last || "<p>"

    text = paragraph.text @hard_break

    @res << "#{para}#{to_html text}\n"

    add_paragraph
  end

  ##
  # Finishes consumption of +list_item+

  def accept_list_item_end list_item
  end

  ##
  # Prepares the visitor for consuming +list_item+

  def accept_list_item_start list_item
    @res << list_item_start(list_item, @list.last)
  end

  ##
  # Prepares the visitor for consuming +list+

  def accept_list_start list
    @list << list.type
    @res << html_list_name(list.type, true)
    @in_list_entry.push ''
  end

  ##
  # Adds +verbatim+ to the output

  def accept_verbatim verbatim
    throw :done if @characters >= @character_limit
    input = verbatim.text.rstrip

    text = truncate input
    text << ' ...' unless text == input

    super RDoc::Markup::Verbatim.new text

    add_paragraph
  end

  ##
  # Prepares the visitor for HTML snippet generation

  def start_accepting
    super

    @characters = 0
  end

  ##
  # Removes escaping from the cross-references in +target+

  def handle_regexp_CROSSREF target
    target.text.sub(/\A\\/, '')
  end

  ##
  # +target+ is a <code><br></code>

  def handle_regexp_HARD_BREAK target
    @characters -= 4
    '<br>'
  end

  ##
  # Lists are paragraphs, but notes and labels have a separator

  def list_item_start list_item, list_type
    throw :done if @characters >= @character_limit

    case list_type
    when :BULLET, :LALPHA, :NUMBER, :UALPHA then
      "<p>"
    when :LABEL, :NOTE then
      labels = Array(list_item.label).map do |label|
        to_html label
      end.join ', '

      labels << " &mdash; " unless labels.empty?

      start = "<p>#{labels}"
      @characters += 1 # try to include the label
      start
    else
      raise RDoc::Error, "Invalid list type: #{list_type.inspect}"
    end
  end

  ##
  # Returns just the text of +link+, +url+ is only used to determine the link
  # type.

  def gen_url url, text
    if url =~ /^rdoc-label:([^:]*)(?::(.*))?/ then
      type = "link"
    elsif url =~ /([A-Za-z]+):(.*)/ then
      type = $1
    else
      type = "http"
    end

    if (type == "http" or type == "https" or type == "link") and
       url =~ /\.(gif|png|jpg|jpeg|bmp)$/ then
      ''
    else
      text.sub(%r%^#{type}:/*%, '')
    end
  end

  ##
  # In snippets, there are no lists

  def html_list_name list_type, open_tag
    ''
  end

  ##
  # Throws +:done+ when paragraph_limit paragraphs have been encountered

  def add_paragraph
    @paragraphs += 1

    throw :done if @paragraphs >= @paragraph_limit
  end

  ##
  # Marks up +content+

  def convert content
    catch :done do
      return super
    end

    end_accepting
  end

  ##
  # Converts flow items +flow+

  def convert_flow flow
    throw :done if @characters >= @character_limit

    res = []
    @mask = 0

    flow.each do |item|
      case item
      when RDoc::Markup::AttrChanger then
        off_tags res, item
        on_tags  res, item
      when String then
        text = convert_string item
        res << truncate(text)
      when RDoc::Markup::RegexpHandling then
        text = convert_regexp_handling item
        res << truncate(text)
      else
        raise "Unknown flow element: #{item.inspect}"
      end

      if @characters >= @character_limit then
        off_tags res, RDoc::Markup::AttrChanger.new(0, @mask)
        break
      end
    end

    res << ' ...' if @characters >= @character_limit

    res.join
  end

  ##
  # Maintains a bitmask to allow HTML elements to be closed properly.  See
  # RDoc::Markup::Formatter.

  def on_tags res, item
    @mask ^= item.turn_on

    super
  end

  ##
  # Maintains a bitmask to allow HTML elements to be closed properly.  See
  # RDoc::Markup::Formatter.

  def off_tags res, item
    @mask ^= item.turn_off

    super
  end

  ##
  # Truncates +text+ at the end of the first word after the character_limit.

  def truncate text
    length = text.length
    characters = @characters
    @characters += length

    return text if @characters < @character_limit

    remaining = @character_limit - characters

    text =~ /\A(.{#{remaining},}?)(\s|$)/m # TODO word-break instead of \s?

    $1
  end

end

# frozen_string_literal: true
##
# A section of text that is added to the output document as-is

class RDoc::Markup::Raw

  ##
  # The component parts of the list

  attr_reader :parts

  ##
  # Creates a new Raw containing +parts+

  def initialize *parts
    @parts = []
    @parts.concat parts
  end

  ##
  # Appends +text+

  def << text
    @parts << text
  end

  def == other # :nodoc:
    self.class == other.class and @parts == other.parts
  end

  ##
  # Calls #accept_raw+ on +visitor+

  def accept visitor
    visitor.accept_raw self
  end

  ##
  # Appends +other+'s parts

  def merge other
    @parts.concat other.parts
  end

  def pretty_print q # :nodoc:
    self.class.name =~ /.*::(\w{1,4})/i

    q.group 2, "[#{$1.downcase}: ", ']' do
      q.seplist @parts do |part|
        q.pp part
      end
    end
  end

  ##
  # Appends +texts+ onto this Paragraph

  def push *texts
    self.parts.concat texts
  end

  ##
  # The raw text

  def text
    @parts.join ' '
  end

end

# frozen_string_literal: true
##
# Hold details of a regexp handling sequence

class RDoc::Markup::RegexpHandling

  ##
  # Regexp handling type

  attr_reader   :type

  ##
  # Regexp handling text

  attr_accessor :text

  ##
  # Creates a new regexp handling sequence of +type+ with +text+

  def initialize(type, text)
    @type, @text = type, text
  end

  ##
  # Regexp handlings are equal when the have the same text and type

  def ==(o)
    self.text == o.text && self.type == o.type
  end

  def inspect # :nodoc:
    "#<RDoc::Markup::RegexpHandling:0x%x @type=%p, @text=%p>" % [
      object_id, @type, text.dump]
  end

  def to_s # :nodoc:
    "RegexpHandling: type=#{type} text=#{text.dump}"
  end

end

# frozen_string_literal: true
##
# An array of attributes which parallels the characters in a string.

class RDoc::Markup::AttrSpan

  ##
  # Creates a new AttrSpan for +length+ characters

  def initialize(length, exclusive)
    @attrs = Array.new(length, 0)
    @exclusive = exclusive
  end

  ##
  # Toggles +bits+ from +start+ to +length+
  def set_attrs(start, length, bits)
    updated = false
    for i in start ... (start+length)
      if (@exclusive & @attrs[i]) == 0 || (@exclusive & bits) != 0
        @attrs[i] |= bits
        updated = true
      end
    end
    updated
  end

  ##
  # Accesses flags for character +n+

  def [](n)
    @attrs[n]
  end

end

# frozen_string_literal: true
##
# A file included at generation time.  Objects of this class are created by
# RDoc::RD for an extension-less include.
#
# This implementation in incomplete.

class RDoc::Markup::Include

  ##
  # The filename to be included, without extension

  attr_reader :file

  ##
  # Directories to search for #file

  attr_reader :include_path

  ##
  # Creates a new include that will import +file+ from +include_path+

  def initialize file, include_path
    @file = file
    @include_path = include_path
  end

  def == other # :nodoc:
    self.class === other and
      @file == other.file and @include_path == other.include_path
  end

  def pretty_print q # :nodoc:
    q.group 2, '[incl ', ']' do
      q.text file
      q.breakable
      q.text 'from '
      q.pp include_path
    end
  end

end

# frozen_string_literal: true
##
# A hard-break in the middle of a paragraph.

class RDoc::Markup::HardBreak

  @instance = new

  ##
  # RDoc::Markup::HardBreak is a singleton

  def self.new
    @instance
  end

  ##
  # Calls #accept_hard_break on +visitor+

  def accept visitor
    visitor.accept_hard_break self
  end

  def == other # :nodoc:
    self.class === other
  end

  def pretty_print q # :nodoc:
    q.text "[break]"
  end

end

# frozen_string_literal: true
##
# A heading with a level (1-6) and text

RDoc::Markup::Heading =
  Struct.new :level, :text do

  @to_html = nil
  @to_label = nil

  ##
  # A singleton RDoc::Markup::ToLabel formatter for headings.

  def self.to_label
    @to_label ||= RDoc::Markup::ToLabel.new
  end

  ##
  # A singleton plain HTML formatter for headings.  Used for creating labels
  # for the Table of Contents

  def self.to_html
    return @to_html if @to_html

    markup = RDoc::Markup.new
    markup.add_regexp_handling RDoc::CrossReference::CROSSREF_REGEXP, :CROSSREF

    @to_html = RDoc::Markup::ToHtml.new nil

    def @to_html.handle_regexp_CROSSREF target
      target.text.sub(/^\\/, '')
    end

    @to_html
  end

  ##
  # Calls #accept_heading on +visitor+

  def accept visitor
    visitor.accept_heading self
  end

  ##
  # An HTML-safe anchor reference for this header.

  def aref
    "label-#{self.class.to_label.convert text.dup}"
  end

  ##
  # Creates a fully-qualified label which will include the label from
  # +context+.  This helps keep ids unique in HTML.

  def label context = nil
    label = aref

    label = [context.aref, label].compact.join '-' if
      context and context.respond_to? :aref

    label
  end

  ##
  # HTML markup of the text of this label without the surrounding header
  # element.

  def plain_html
    self.class.to_html.to_html(text.dup)
  end

  def pretty_print q # :nodoc:
    q.group 2, "[head: #{level} ", ']' do
      q.pp text
    end
  end

end

# frozen_string_literal: true
##
# An item within a List that contains paragraphs, headings, etc.
#
# For BULLET, NUMBER, LALPHA and UALPHA lists, the label will always be nil.
# For NOTE and LABEL lists, the list label may contain:
#
# * a single String for a single label
# * an Array of Strings for a list item with multiple terms
# * nil for an extra description attached to a previously labeled list item

class RDoc::Markup::ListItem

  ##
  # The label for the ListItem

  attr_accessor :label

  ##
  # Parts of the ListItem

  attr_reader :parts

  ##
  # Creates a new ListItem with an optional +label+ containing +parts+

  def initialize label = nil, *parts
    @label = label
    @parts = []
    @parts.concat parts
  end

  ##
  # Appends +part+ to the ListItem

  def << part
    @parts << part
  end

  def == other # :nodoc:
    self.class == other.class and
      @label == other.label and
      @parts == other.parts
  end

  ##
  # Runs this list item and all its #parts through +visitor+

  def accept visitor
    visitor.accept_list_item_start self

    @parts.each do |part|
      part.accept visitor
    end

    visitor.accept_list_item_end self
  end

  ##
  # Is the ListItem empty?

  def empty?
    @parts.empty?
  end

  ##
  # Length of parts in the ListItem

  def length
    @parts.length
  end

  def pretty_print q # :nodoc:
    q.group 2, '[item: ', ']' do
      case @label
      when Array then
        q.pp @label
        q.text ';'
        q.breakable
      when String then
        q.pp @label
        q.text ';'
        q.breakable
      end

      q.seplist @parts do |part|
        q.pp part
      end
    end
  end

  ##
  # Adds +parts+ to the ListItem

  def push *parts
    @parts.concat parts
  end

end

# frozen_string_literal: true
##
# Outputs RDoc markup with vibrant ANSI color!

class RDoc::Markup::ToAnsi < RDoc::Markup::ToRdoc

  ##
  # Creates a new ToAnsi visitor that is ready to output vibrant ANSI color!

  def initialize markup = nil
    super

    @headings.clear
    @headings[1] = ["\e[1;32m", "\e[m"] # bold
    @headings[2] = ["\e[4;32m", "\e[m"] # underline
    @headings[3] = ["\e[32m",   "\e[m"] # just green
  end

  ##
  # Maps attributes to ANSI sequences

  def init_tags
    add_tag :BOLD, "\e[1m", "\e[m"
    add_tag :TT,   "\e[7m", "\e[m"
    add_tag :EM,   "\e[4m", "\e[m"
  end

  ##
  # Overrides indent width to ensure output lines up correctly.

  def accept_list_item_end list_item
    width = case @list_type.last
            when :BULLET then
              2
            when :NOTE, :LABEL then
              if @prefix then
                @res << @prefix.strip
                @prefix = nil
              end

              @res << "\n" unless res.length == 1
              2
            else
              bullet = @list_index.last.to_s
              @list_index[-1] = @list_index.last.succ
              bullet.length + 2
            end

    @indent -= width
  end

  ##
  # Adds coloring to note and label list items

  def accept_list_item_start list_item
    bullet = case @list_type.last
             when :BULLET then
               '*'
             when :NOTE, :LABEL then
               labels = Array(list_item.label).map do |label|
                 attributes(label).strip
               end.join "\n"

               labels << ":\n" unless labels.empty?

               labels
             else
               @list_index.last.to_s + '.'
             end

    case @list_type.last
    when :NOTE, :LABEL then
      @indent += 2
      @prefix = bullet + (' ' * @indent)
    else
      @prefix = (' ' * @indent) + bullet.ljust(bullet.length + 1)

      width = bullet.gsub(/\e\[[\d;]*m/, '').length + 1

      @indent += width
    end
  end

  ##
  # Starts accepting with a reset screen

  def start_accepting
    super

    @res = ["\e[0m"]
  end

end

# 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

# frozen_string_literal: true
##
# RDoc::RD implements the RD format from the rdtool gem.
#
# To choose RD as your only default format see
# RDoc::Options@Saved+Options for instructions on setting up a
# <code>.doc_options</code> file to store your project default.
#
# == LICENSE
#
# The grammar that produces RDoc::RD::BlockParser and RDoc::RD::InlineParser
# is included in RDoc under the Ruby License.
#
# You can find the original source for rdtool at
# https://github.com/uwabami/rdtool/
#
# You can use, re-distribute or change these files under Ruby's License or GPL.
#
# 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.

class RDoc::RD

  ##
  # Parses +rd+ source and returns an RDoc::Markup::Document.  If the
  # <tt>=begin</tt> or <tt>=end</tt> lines are missing they will be added.

  def self.parse rd
    rd = rd.lines.to_a

    if rd.find { |i| /\S/ === i } and !rd.find{|i| /^=begin\b/ === i } then
      rd.unshift("=begin\n").push("=end\n")
    end

    parser = RDoc::RD::BlockParser.new
    document = parser.parse rd

    # isn't this always true?
    document.parts.shift if RDoc::Markup::BlankLine === document.parts.first
    document.parts.pop   if RDoc::Markup::BlankLine === document.parts.last

    document
  end

  autoload :BlockParser,  'rdoc/rd/block_parser'
  autoload :InlineParser, 'rdoc/rd/inline_parser'
  autoload :Inline,       'rdoc/rd/inline'

end

# frozen_string_literal: true
##
# For RubyGems backwards compatibility

module RDoc::RI::Formatter # :nodoc:
end
# frozen_string_literal: true
require_relative '../rdoc'

##
# The directories where ri data lives.  Paths can be enumerated via ::each, or
# queried individually via ::system_dir, ::site_dir, ::home_dir and ::gem_dir.

module RDoc::RI::Paths

  #:stopdoc:
  require 'rbconfig'

  version = RbConfig::CONFIG['ruby_version_dir_name'] || RbConfig::CONFIG['ruby_version']

  BASE    = File.join RbConfig::CONFIG['ridir'], version

  HOMEDIR = RDoc.home
  #:startdoc:

  ##
  # Iterates over each selected path yielding the directory and type.
  #
  # Yielded types:
  # :system:: Where Ruby's ri data is stored.  Yielded when +system+ is
  #           true
  # :site:: Where ri for installed libraries are stored.  Yielded when
  #         +site+ is true.  Normally no ri data is stored here.
  # :home:: ~/.rdoc.  Yielded when +home+ is true.
  # :gem:: ri data for an installed gem.  Yielded when +gems+ is true.
  # :extra:: ri data directory from the command line.  Yielded for each
  #          entry in +extra_dirs+

  def self.each system = true, site = true, home = true, gems = :latest, *extra_dirs # :yields: directory, type
    return enum_for __method__, system, site, home, gems, *extra_dirs unless
      block_given?

    extra_dirs.each do |dir|
      yield dir, :extra
    end

    yield system_dir,  :system if system
    yield site_dir,    :site   if site
    yield home_dir,    :home   if home and HOMEDIR

    gemdirs(gems).each do |dir|
      yield dir, :gem
    end if gems

    nil
  end

  ##
  # The ri directory for the gem with +gem_name+.

  def self.gem_dir name, version
    req = Gem::Requirement.new "= #{version}"

    spec = Gem::Specification.find_by_name name, req

    File.join spec.doc_dir, 'ri'
  end

  ##
  # The latest installed gems' ri directories.  +filter+ can be :all or
  # :latest.
  #
  # A +filter+ :all includes all versions of gems and includes gems without
  # ri documentation.

  def self.gemdirs filter = :latest
    ri_paths = {}

    all = Gem::Specification.map do |spec|
      [File.join(spec.doc_dir, 'ri'), spec.name, spec.version]
    end

    if filter == :all then
      gemdirs = []

      all.group_by do |_, name, _|
        name
      end.sort_by do |group, _|
        group
      end.map do |group, items|
        items.sort_by do |_, _, version|
          version
        end.reverse_each do |dir,|
          gemdirs << dir
        end
      end

      return gemdirs
    end

    all.each do |dir, name, ver|
      next unless File.exist? dir

      if ri_paths[name].nil? or ver > ri_paths[name].first then
        ri_paths[name] = [ver, name, dir]
      end
    end

    ri_paths.sort_by { |_, (_, name, _)| name }.map { |k, v| v.last }
  rescue LoadError
    []
  end

  ##
  # The location of the rdoc data in the user's home directory.
  #
  # Like ::system, ri data in the user's home directory is rare and predates
  # libraries distributed via RubyGems.  ri data is rarely generated into this
  # directory.

  def self.home_dir
    HOMEDIR
  end

  ##
  # Returns existing directories from the selected documentation directories
  # as an Array.
  #
  # See also ::each

  def self.path(system = true, site = true, home = true, gems = :latest, *extra_dirs)
    path = raw_path system, site, home, gems, *extra_dirs

    path.select { |directory| File.directory? directory }
  end

  ##
  # Returns selected documentation directories including nonexistent
  # directories.
  #
  # See also ::each

  def self.raw_path(system, site, home, gems, *extra_dirs)
    path = []

    each(system, site, home, gems, *extra_dirs) do |dir, type|
      path << dir
    end

    path.compact
  end

  ##
  # The location of ri data installed into the site dir.
  #
  # Historically this was available for documentation installed by Ruby
  # libraries predating RubyGems.  It is unlikely to contain any content for
  # modern Ruby installations.

  def self.site_dir
    File.join BASE, 'site'
  end

  ##
  # The location of the built-in ri data.
  #
  # This data is built automatically when `make` is run when Ruby is
  # installed.  If you did not install Ruby by hand you may need to install
  # the documentation yourself.  Please consult the documentation for your
  # package manager or Ruby installer for details.  You can also use the
  # rdoc-data gem to install system ri data for common versions of Ruby.

  def self.system_dir
    File.join BASE, 'system'
  end

end
# frozen_string_literal: true
begin
  gem 'rdoc'
rescue Gem::LoadError
end unless defined?(RDoc)

require_relative '../task'

##
# RDoc::RI::Task creates ri data in <code>./.rdoc</code> for your project.
#
# It contains the following tasks:
#
# [ri]
#   Build ri data
#
# [clobber_ri]
#   Delete ri data files.  This target is automatically added to the main
#   clobber target.
#
# [reri]
#   Rebuild the ri data from scratch even if they are not out of date.
#
# Simple example:
#
#   require 'rdoc/ri/task'
#
#   RDoc::RI::Task.new do |ri|
#     ri.main = 'README.rdoc'
#     ri.rdoc_files.include 'README.rdoc', 'lib/**/*.rb'
#   end
#
# For further configuration details see RDoc::Task.

class RDoc::RI::Task < RDoc::Task

  DEFAULT_NAMES = { # :nodoc:
    :clobber_rdoc => :clobber_ri,
    :rdoc         => :ri,
    :rerdoc       => :reri,
  }

  ##
  # Create an ri task with the given name. See RDoc::Task for documentation on
  # setting names.

  def initialize name = DEFAULT_NAMES # :yield: self
    super
  end

  def clobber_task_description # :nodoc:
    "Remove RI data files"
  end

  ##
  # Sets default task values

  def defaults
    super

    @rdoc_dir = '.rdoc'
  end

  def rdoc_task_description # :nodoc:
    'Build RI data files'
  end

  def rerdoc_task_description # :nodoc:
    'Rebuild RI data files'
  end
end
# frozen_string_literal: true
require 'abbrev'
require 'optparse'

begin
  require 'readline'
rescue LoadError
end

begin
  require 'win32console'
rescue LoadError
end

require 'rdoc'

##
# For RubyGems backwards compatibility

require_relative 'formatter'

##
# The RI driver implements the command-line ri tool.
#
# The driver supports:
# * loading RI data from:
#   * Ruby's standard library
#   * RubyGems
#   * ~/.rdoc
#   * A user-supplied directory
# * Paging output (uses RI_PAGER environment variable, PAGER environment
#   variable or the less, more and pager programs)
# * Interactive mode with tab-completion
# * Abbreviated names (ri Zl shows Zlib documentation)
# * Colorized output
# * Merging output from multiple RI data sources

class RDoc::RI::Driver

  ##
  # Base Driver error class

  class Error < RDoc::RI::Error; end

  ##
  # Raised when a name isn't found in the ri data stores

  class NotFoundError < Error

    def initialize(klass, suggestions = nil) # :nodoc:
      @klass = klass
      @suggestions = suggestions
    end

    ##
    # Name that wasn't found

    def name
      @klass
    end

    def message # :nodoc:
      str = "Nothing known about #{@klass}"
      if @suggestions and !@suggestions.empty?
        str += "\nDid you mean?  #{@suggestions.join("\n               ")}"
      end
      str
    end
  end

  ##
  # Show all method documentation following a class or module

  attr_accessor :show_all

  ##
  # An RDoc::RI::Store for each entry in the RI path

  attr_accessor :stores

  ##
  # Controls the user of the pager vs $stdout

  attr_accessor :use_stdout

  ##
  # Default options for ri

  def self.default_options
    options = {}
    options[:interactive] = false
    options[:profile]     = false
    options[:show_all]    = false
    options[:use_stdout]  = !$stdout.tty?
    options[:width]       = 72

    # By default all standard paths are used.
    options[:use_system]     = true
    options[:use_site]       = true
    options[:use_home]       = true
    options[:use_gems]       = true
    options[:extra_doc_dirs] = []

    return options
  end

  ##
  # Dump +data_path+ using pp

  def self.dump data_path
    require 'pp'

    File.open data_path, 'rb' do |io|
      pp Marshal.load(io.read)
    end
  end

  ##
  # Parses +argv+ and returns a Hash of options

  def self.process_args argv
    options = default_options

    opts = OptionParser.new do |opt|
      opt.accept File do |file,|
        File.readable?(file) and not File.directory?(file) and file
      end

      opt.program_name = File.basename $0
      opt.version = RDoc::VERSION
      opt.release = nil
      opt.summary_indent = ' ' * 4

      opt.banner = <<-EOT
Usage: #{opt.program_name} [options] [name ...]

Where name can be:

  Class | Module | Module::Class

  Class::method | Class#method | Class.method | method

  gem_name: | gem_name:README | gem_name:History

All class names may be abbreviated to their minimum unambiguous form.
If a name is ambiguous, all valid options will be listed.

A '.' matches either class or instance methods, while #method
matches only instance and ::method matches only class methods.

README and other files may be displayed by prefixing them with the gem name
they're contained in.  If the gem name is followed by a ':' all files in the
gem will be shown.  The file name extension may be omitted where it is
unambiguous.

For example:

    #{opt.program_name} Fil
    #{opt.program_name} File
    #{opt.program_name} File.new
    #{opt.program_name} zip
    #{opt.program_name} rdoc:README

Note that shell quoting or escaping may be required for method names
containing punctuation:

    #{opt.program_name} 'Array.[]'
    #{opt.program_name} compact\\!

To see the default directories #{opt.program_name} will search, run:

    #{opt.program_name} --list-doc-dirs

Specifying the --system, --site, --home, --gems, or --doc-dir options
will limit ri to searching only the specified directories.

ri options may be set in the RI environment variable.

The ri pager can be set with the RI_PAGER environment variable
or the PAGER environment variable.
      EOT

      opt.separator nil
      opt.separator "Options:"

      opt.separator nil

      opt.on("--[no-]interactive", "-i",
             "In interactive mode you can repeatedly",
             "look up methods with autocomplete.") do |interactive|
        options[:interactive] = interactive
      end

      opt.separator nil

      opt.on("--[no-]all", "-a",
             "Show all documentation for a class or",
             "module.") do |show_all|
        options[:show_all] = show_all
      end

      opt.separator nil

      opt.on("--[no-]list", "-l",
             "List classes ri knows about.") do |list|
        options[:list] = list
      end

      opt.separator nil

      opt.on("--[no-]pager",
             "Send output to a pager,",
             "rather than directly to stdout.") do |use_pager|
        options[:use_stdout] = !use_pager
      end

      opt.separator nil

      opt.on("-T",
             "Synonym for --no-pager.") do
        options[:use_stdout] = true
      end

      opt.separator nil

      opt.on("--width=WIDTH", "-w", OptionParser::DecimalInteger,
             "Set the width of the output.") do |width|
        options[:width] = width
      end

      opt.separator nil

      opt.on("--server[=PORT]", Integer,
             "Run RDoc server on the given port.",
             "The default port is 8214.") do |port|
        options[:server] = port || 8214
      end

      opt.separator nil

      formatters = RDoc::Markup.constants.grep(/^To[A-Z][a-z]+$/).sort
      formatters = formatters.sort.map do |formatter|
        formatter.to_s.sub('To', '').downcase
      end
      formatters -= %w[html label test] # remove useless output formats

      opt.on("--format=NAME", "-f",
             "Use the selected formatter.  The default",
             "formatter is bs for paged output and ansi",
             "otherwise.  Valid formatters are:",
             "#{formatters.join(', ')}.", formatters) do |value|
        options[:formatter] = RDoc::Markup.const_get "To#{value.capitalize}"
      end

      opt.separator nil

      opt.on("--help", "-h",
             "Show help and exit.") do
        puts opts
        exit
      end

      opt.separator nil

      opt.on("--version", "-v",
             "Output version information and exit.") do
        puts "#{opts.program_name} #{opts.version}"
        exit
      end

      opt.separator nil
      opt.separator "Data source options:"
      opt.separator nil

      opt.on("--[no-]list-doc-dirs",
             "List the directories from which ri will",
             "source documentation on stdout and exit.") do |list_doc_dirs|
        options[:list_doc_dirs] = list_doc_dirs
      end

      opt.separator nil

      opt.on("--doc-dir=DIRNAME", "-d", Array,
             "List of directories from which to source",
             "documentation in addition to the standard",
             "directories.  May be repeated.") do |value|
        value.each do |dir|
          unless File.directory? dir then
            raise OptionParser::InvalidArgument, "#{dir} is not a directory"
          end

          options[:extra_doc_dirs] << File.expand_path(dir)
        end
      end

      opt.separator nil

      opt.on("--no-standard-docs",
             "Do not include documentation from",
             "the Ruby standard library, site_lib,",
             "installed gems, or ~/.rdoc.",
             "Use with --doc-dir.") do
        options[:use_system] = false
        options[:use_site] = false
        options[:use_gems] = false
        options[:use_home] = false
      end

      opt.separator nil

      opt.on("--[no-]system",
             "Include documentation from Ruby's",
             "standard library.  Defaults to true.") do |value|
        options[:use_system] = value
      end

      opt.separator nil

      opt.on("--[no-]site",
             "Include documentation from libraries",
             "installed in site_lib.",
             "Defaults to true.") do |value|
        options[:use_site] = value
      end

      opt.separator nil

      opt.on("--[no-]gems",
             "Include documentation from RubyGems.",
             "Defaults to true.") do |value|
        options[:use_gems] = value
      end

      opt.separator nil

      opt.on("--[no-]home",
             "Include documentation stored in ~/.rdoc.",
             "Defaults to true.") do |value|
        options[:use_home] = value
      end

      opt.separator nil
      opt.separator "Debug options:"
      opt.separator nil

      opt.on("--[no-]profile",
             "Run with the ruby profiler.") do |value|
        options[:profile] = value
      end

      opt.separator nil

      opt.on("--dump=CACHE", File,
             "Dump data from an ri cache or data file.") do |value|
        options[:dump_path] = value
      end
    end

    argv = ENV['RI'].to_s.split(' ').concat argv

    opts.parse! argv

    options[:names] = argv

    options[:use_stdout] ||= !$stdout.tty?
    options[:use_stdout] ||= options[:interactive]
    options[:width] ||= 72

    options

  rescue OptionParser::InvalidArgument, OptionParser::InvalidOption => e
    puts opts
    puts
    puts e
    exit 1
  end

  ##
  # Runs the ri command line executable using +argv+

  def self.run argv = ARGV
    options = process_args argv

    if options[:dump_path] then
      dump options[:dump_path]
      return
    end

    ri = new options
    ri.run
  end

  ##
  # Creates a new driver using +initial_options+ from ::process_args

  def initialize initial_options = {}
    @paging = false
    @classes = nil

    options = self.class.default_options.update(initial_options)

    @formatter_klass = options[:formatter]

    require 'profile' if options[:profile]

    @names = options[:names]
    @list = options[:list]

    @doc_dirs = []
    @stores   = []

    RDoc::RI::Paths.each(options[:use_system], options[:use_site],
                         options[:use_home], options[:use_gems],
                         *options[:extra_doc_dirs]) do |path, type|
      @doc_dirs << path

      store = RDoc::RI::Store.new path, type
      store.load_cache
      @stores << store
    end

    @list_doc_dirs = options[:list_doc_dirs]

    @interactive = options[:interactive]
    @server      = options[:server]
    @use_stdout  = options[:use_stdout]
    @show_all    = options[:show_all]
    @width       = options[:width]

    # pager process for jruby
    @jruby_pager_process = nil
  end

  ##
  # Adds paths for undocumented classes +also_in+ to +out+

  def add_also_in out, also_in
    return if also_in.empty?

    out << RDoc::Markup::Rule.new(1)
    out << RDoc::Markup::Paragraph.new("Also found in:")

    paths = RDoc::Markup::Verbatim.new
    also_in.each do |store|
      paths.parts.push store.friendly_path, "\n"
    end
    out << paths
  end

  ##
  # Adds a class header to +out+ for class +name+ which is described in
  # +classes+.

  def add_class out, name, classes
    heading = if classes.all? { |klass| klass.module? } then
                name
              else
                superclass = classes.map do |klass|
                  klass.superclass unless klass.module?
                end.compact.shift || 'Object'

                superclass = superclass.full_name unless String === superclass

                "#{name} < #{superclass}"
              end

    out << RDoc::Markup::Heading.new(1, heading)
    out << RDoc::Markup::BlankLine.new
  end

  ##
  # Adds "(from ...)" to +out+ for +store+

  def add_from out, store
    out << RDoc::Markup::Paragraph.new("(from #{store.friendly_path})")
  end

  ##
  # Adds +extends+ to +out+

  def add_extends out, extends
    add_extension_modules out, 'Extended by', extends
  end

  ##
  # Adds a list of +extensions+ to this module of the given +type+ to +out+.
  # add_includes and add_extends call this, so you should use those directly.

  def add_extension_modules out, type, extensions
    return if extensions.empty?

    out << RDoc::Markup::Rule.new(1)
    out << RDoc::Markup::Heading.new(1, "#{type}:")

    extensions.each do |modules, store|
      if modules.length == 1 then
        add_extension_modules_single out, store, modules.first
      else
        add_extension_modules_multiple out, store, modules
      end
    end
  end

  ##
  # Renders multiple included +modules+ from +store+ to +out+.

  def add_extension_modules_multiple out, store, modules # :nodoc:
    out << RDoc::Markup::Paragraph.new("(from #{store.friendly_path})")

    wout, with = modules.partition { |incl| incl.comment.empty? }

    out << RDoc::Markup::BlankLine.new unless with.empty?

    with.each do |incl|
      out << RDoc::Markup::Paragraph.new(incl.name)
      out << RDoc::Markup::BlankLine.new
      out << incl.comment
    end

    unless wout.empty? then
      verb = RDoc::Markup::Verbatim.new

      wout.each do |incl|
        verb.push incl.name, "\n"
      end

      out << verb
    end
  end

  ##
  # Adds a single extension module +include+ from +store+ to +out+

  def add_extension_modules_single out, store, include # :nodoc:
    name = include.name
    path = store.friendly_path
    out << RDoc::Markup::Paragraph.new("#{name} (from #{path})")

    if include.comment then
      out << RDoc::Markup::BlankLine.new
      out << include.comment
    end
  end

  ##
  # Adds +includes+ to +out+

  def add_includes out, includes
    add_extension_modules out, 'Includes', includes
  end

  ##
  # Looks up the method +name+ and adds it to +out+

  def add_method out, name
    filtered   = lookup_method name

    method_out = method_document name, filtered

    out.concat method_out.parts
  end

  ##
  # Adds documentation for all methods in +klass+ to +out+

  def add_method_documentation out, klass
    klass.method_list.each do |method|
      begin
        add_method out, method.full_name
      rescue NotFoundError
        next
      end
    end
  end

  ##
  # Adds a list of +methods+ to +out+ with a heading of +name+

  def add_method_list out, methods, name
    return if methods.empty?

    out << RDoc::Markup::Heading.new(1, "#{name}:")
    out << RDoc::Markup::BlankLine.new

    if @use_stdout and !@interactive then
      out.concat methods.map { |method|
        RDoc::Markup::Verbatim.new method
      }
    else
      out << RDoc::Markup::IndentedParagraph.new(2, methods.join(', '))
    end

    out << RDoc::Markup::BlankLine.new
  end

  ##
  # Returns ancestor classes of +klass+

  def ancestors_of klass
    ancestors = []

    unexamined = [klass]
    seen = []

    loop do
      break if unexamined.empty?
      current = unexamined.shift
      seen << current

      stores = classes[current]

      break unless stores and not stores.empty?

      klasses = stores.map do |store|
        store.ancestors[current]
      end.flatten.uniq

      klasses = klasses - seen

      ancestors.concat klasses
      unexamined.concat klasses
    end

    ancestors.reverse
  end

  ##
  # For RubyGems backwards compatibility

  def class_cache # :nodoc:
  end

  ##
  # Builds a RDoc::Markup::Document from +found+, +klasess+ and +includes+

  def class_document name, found, klasses, includes, extends
    also_in = []

    out = RDoc::Markup::Document.new

    add_class out, name, klasses

    add_includes out, includes
    add_extends  out, extends

    found.each do |store, klass|
      render_class out, store, klass, also_in
    end

    add_also_in out, also_in

    out
  end

  ##
  # Adds the class +comment+ to +out+.

  def class_document_comment out, comment # :nodoc:
    unless comment.empty? then
      out << RDoc::Markup::Rule.new(1)

      if comment.merged? then
        parts = comment.parts
        parts = parts.zip [RDoc::Markup::BlankLine.new] * parts.length
        parts.flatten!
        parts.pop

        out.concat parts
      else
        out << comment
      end
    end
  end

  ##
  # Adds the constants from +klass+ to the Document +out+.

  def class_document_constants out, klass # :nodoc:
    return if klass.constants.empty?

    out << RDoc::Markup::Heading.new(1, "Constants:")
    out << RDoc::Markup::BlankLine.new
    list = RDoc::Markup::List.new :NOTE

    constants = klass.constants.sort_by { |constant| constant.name }

    list.items.concat constants.map { |constant|
      parts = constant.comment.parts if constant.comment
      parts << RDoc::Markup::Paragraph.new('[not documented]') if
        parts.empty?

      RDoc::Markup::ListItem.new(constant.name, *parts)
    }

    out << list
    out << RDoc::Markup::BlankLine.new
  end

  ##
  # Hash mapping a known class or module to the stores it can be loaded from

  def classes
    return @classes if @classes

    @classes = {}

    @stores.each do |store|
      store.cache[:modules].each do |mod|
        # using default block causes searched-for modules to be added
        @classes[mod] ||= []
        @classes[mod] << store
      end
    end

    @classes
  end

  ##
  # Returns the stores wherein +name+ is found along with the classes,
  # extends and includes that match it

  def classes_and_includes_and_extends_for name
    klasses = []
    extends = []
    includes = []

    found = @stores.map do |store|
      begin
        klass = store.load_class name
        klasses  << klass
        extends  << [klass.extends,  store] if klass.extends
        includes << [klass.includes, store] if klass.includes
        [store, klass]
      rescue RDoc::Store::MissingFileError
      end
    end.compact

    extends.reject!  do |modules,| modules.empty? end
    includes.reject! do |modules,| modules.empty? end

    [found, klasses, includes, extends]
  end

  ##
  # Completes +name+ based on the caches.  For Readline

  def complete name
    completions = []

    klass, selector, method = parse_name name

    complete_klass  name, klass, selector, method, completions
    complete_method name, klass, selector,         completions

    completions.sort.uniq
  end

  def complete_klass name, klass, selector, method, completions # :nodoc:
    klasses = classes.keys

    # may need to include Foo when given Foo::
    klass_name = method ? name : klass

    if name !~ /#|\./ then
      completions.replace klasses.grep(/^#{Regexp.escape klass_name}[^:]*$/)
      completions.concat klasses.grep(/^#{Regexp.escape name}[^:]*$/) if
        name =~ /::$/

      completions << klass if classes.key? klass # to complete a method name
    elsif selector then
      completions << klass if classes.key? klass
    elsif classes.key? klass_name then
      completions << klass_name
    end
  end

  def complete_method name, klass, selector, completions # :nodoc:
    if completions.include? klass and name =~ /#|\.|::/ then
      methods = list_methods_matching name

      if not methods.empty? then
        # remove Foo if given Foo:: and a method was found
        completions.delete klass
      elsif selector then
        # replace Foo with Foo:: as given
        completions.delete klass
        completions << "#{klass}#{selector}"
      end

      completions.concat methods
    end
  end

  ##
  # Converts +document+ to text and writes it to the pager

  def display document
    page do |io|
      f = formatter(io)
      f.width = @width if @width and f.respond_to?(:width)
      text = document.accept f

      io.write text
    end
  end

  ##
  # Outputs formatted RI data for class +name+.  Groups undocumented classes

  def display_class name
    return if name =~ /#|\./

    found, klasses, includes, extends =
      classes_and_includes_and_extends_for name

    return if found.empty?

    out = class_document name, found, klasses, includes, extends

    display out
  end

  ##
  # Outputs formatted RI data for method +name+

  def display_method name
    out = RDoc::Markup::Document.new

    add_method out, name

    display out
  end

  ##
  # Outputs formatted RI data for the class or method +name+.
  #
  # Returns true if +name+ was found, false if it was not an alternative could
  # be guessed, raises an error if +name+ couldn't be guessed.

  def display_name name
    if name =~ /\w:(\w|$)/ then
      display_page name
      return true
    end

    return true if display_class name

    display_method name if name =~ /::|#|\./

    true
  rescue NotFoundError
    matches = list_methods_matching name if name =~ /::|#|\./
    matches = classes.keys.grep(/^#{Regexp.escape name}/) if matches.empty?

    raise if matches.empty?

    page do |io|
      io.puts "#{name} not found, maybe you meant:"
      io.puts
      io.puts matches.sort.join("\n")
    end

    false
  end

  ##
  # Displays each name in +name+

  def display_names names
    names.each do |name|
      name = expand_name name

      display_name name
    end
  end

  ##
  # Outputs formatted RI data for page +name+.

  def display_page name
    store_name, page_name = name.split ':', 2

    store = @stores.find { |s| s.source == store_name }

    return display_page_list store if page_name.empty?

    pages = store.cache[:pages]

    unless pages.include? page_name then
      found_names = pages.select do |n|
        n =~ /#{Regexp.escape page_name}\.[^.]+$/
      end

      if found_names.length.zero? then
        return display_page_list store, pages
      elsif found_names.length > 1 then
        return display_page_list store, found_names, page_name
      end

      page_name = found_names.first
    end

    page = store.load_page page_name

    display page.comment
  end

  ##
  # Outputs a formatted RI page list for the pages in +store+.

  def display_page_list store, pages = store.cache[:pages], search = nil
    out = RDoc::Markup::Document.new

    title = if search then
              "#{search} pages"
            else
              'Pages'
            end

    out << RDoc::Markup::Heading.new(1, "#{title} in #{store.friendly_path}")
    out << RDoc::Markup::BlankLine.new

    list = RDoc::Markup::List.new(:BULLET)

    pages.each do |page|
      list << RDoc::Markup::Paragraph.new(page)
    end

    out << list

    display out
  end

  def check_did_you_mean # :nodoc:
    if defined? DidYouMean::SpellChecker
      true
    else
      begin
        require 'did_you_mean'
        if defined? DidYouMean::SpellChecker
          true
        else
          false
        end
      rescue LoadError
        false
      end
    end
  end

  ##
  # Expands abbreviated klass +klass+ into a fully-qualified class.  "Zl::Da"
  # will be expanded to Zlib::DataError.

  def expand_class klass
    class_names = classes.keys
    ary = class_names.grep(Regexp.new("\\A#{klass.gsub(/(?=::|\z)/, '[^:]*')}\\z"))
    if ary.length != 1 && ary.first != klass
      if check_did_you_mean
        suggestions = DidYouMean::SpellChecker.new(dictionary: class_names).correct(klass)
        raise NotFoundError.new(klass, suggestions)
      else
        raise NotFoundError, klass
      end
    end
    ary.first
  end

  ##
  # Expands the class portion of +name+ into a fully-qualified class.  See
  # #expand_class.

  def expand_name name
    klass, selector, method = parse_name name

    return [selector, method].join if klass.empty?

    case selector
    when ':' then
      [find_store(klass),   selector, method]
    else
      [expand_class(klass), selector, method]
    end.join
  end

  ##
  # Filters the methods in +found+ trying to find a match for +name+.

  def filter_methods found, name
    regexp = name_regexp name

    filtered = found.find_all do |store, methods|
      methods.any? { |method| method.full_name =~ regexp }
    end

    return filtered unless filtered.empty?

    found
  end

  ##
  # Yields items matching +name+ including the store they were found in, the
  # class being searched for, the class they were found in (an ancestor) the
  # types of methods to look up (from #method_type), and the method name being
  # searched for

  def find_methods name
    klass, selector, method = parse_name name

    types = method_type selector

    klasses = nil
    ambiguous = klass.empty?

    if ambiguous then
      klasses = classes.keys
    else
      klasses = ancestors_of klass
      klasses.unshift klass
    end

    methods = []

    klasses.each do |ancestor|
      ancestors = classes[ancestor]

      next unless ancestors

      klass = ancestor if ambiguous

      ancestors.each do |store|
        methods << [store, klass, ancestor, types, method]
      end
    end

    methods = methods.sort_by do |_, k, a, _, m|
      [k, a, m].compact
    end

    methods.each do |item|
      yield(*item) # :yields: store, klass, ancestor, types, method
    end

    self
  end

  ##
  # Finds the given +pager+ for jruby.  Returns an IO if +pager+ was found.
  #
  # Returns false if +pager+ does not exist.
  #
  # Returns nil if the jruby JVM doesn't support ProcessBuilder redirection
  # (1.6 and older).

  def find_pager_jruby pager
    require 'java'
    require 'shellwords'

    return nil unless java.lang.ProcessBuilder.constants.include? :Redirect

    pager = Shellwords.split pager

    pb = java.lang.ProcessBuilder.new(*pager)
    pb = pb.redirect_output java.lang.ProcessBuilder::Redirect::INHERIT

    @jruby_pager_process = pb.start

    input = @jruby_pager_process.output_stream

    io = input.to_io
    io.sync = true
    io
  rescue java.io.IOException
    false
  end

  ##
  # Finds a store that matches +name+ which can be the name of a gem, "ruby",
  # "home" or "site".
  #
  # See also RDoc::Store#source

  def find_store name
    @stores.each do |store|
      source = store.source

      return source if source == name

      return source if
        store.type == :gem and source =~ /^#{Regexp.escape name}-\d/
    end

    raise RDoc::RI::Driver::NotFoundError, name
  end

  ##
  # Creates a new RDoc::Markup::Formatter.  If a formatter is given with -f,
  # use it.  If we're outputting to a pager, use bs, otherwise ansi.

  def formatter(io)
    if @formatter_klass then
      @formatter_klass.new
    elsif paging? or !io.tty? then
      RDoc::Markup::ToBs.new
    else
      RDoc::Markup::ToAnsi.new
    end
  end

  ##
  # Runs ri interactively using Readline if it is available.

  def interactive
    puts "\nEnter the method name you want to look up."

    if defined? Readline then
      Readline.completion_proc = method :complete
      puts "You can use tab to autocomplete."
    end

    puts "Enter a blank line to exit.\n\n"

    loop do
      name = if defined? Readline then
               Readline.readline ">> "
             else
               print ">> "
               $stdin.gets
             end

      return if name.nil? or name.empty?

      begin
        display_name expand_name(name.strip)
      rescue NotFoundError => e
        puts e.message
      end
    end

  rescue Interrupt
    exit
  end

  ##
  # Is +file+ in ENV['PATH']?

  def in_path? file
    return true if file =~ %r%\A/% and File.exist? file

    ENV['PATH'].split(File::PATH_SEPARATOR).any? do |path|
      File.exist? File.join(path, file)
    end
  end

  ##
  # Lists classes known to ri starting with +names+.  If +names+ is empty all
  # known classes are shown.

  def list_known_classes names = []
    classes = []

    stores.each do |store|
      classes << store.module_names
    end

    classes = classes.flatten.uniq.sort

    unless names.empty? then
      filter = Regexp.union names.map { |name| /^#{name}/ }

      classes = classes.grep filter
    end

    page do |io|
      if paging? or io.tty? then
        if names.empty? then
          io.puts "Classes and Modules known to ri:"
        else
          io.puts "Classes and Modules starting with #{names.join ', '}:"
        end
        io.puts
      end

      io.puts classes.join("\n")
    end
  end

  ##
  # Returns an Array of methods matching +name+

  def list_methods_matching name
    found = []

    find_methods name do |store, klass, ancestor, types, method|
      if types == :instance or types == :both then
        methods = store.instance_methods[ancestor]

        if methods then
          matches = methods.grep(/^#{Regexp.escape method.to_s}/)

          matches = matches.map do |match|
            "#{klass}##{match}"
          end

          found.concat matches
        end
      end

      if types == :class or types == :both then
        methods = store.class_methods[ancestor]

        next unless methods
        matches = methods.grep(/^#{Regexp.escape method.to_s}/)

        matches = matches.map do |match|
          "#{klass}::#{match}"
        end

        found.concat matches
      end
    end

    found.uniq
  end

  ##
  # Loads RI data for method +name+ on +klass+ from +store+.  +type+ and
  # +cache+ indicate if it is a class or instance method.

  def load_method store, cache, klass, type, name
    methods = store.public_send(cache)[klass]

    return unless methods

    method = methods.find do |method_name|
      method_name == name
    end

    return unless method

    store.load_method klass, "#{type}#{method}"
  rescue RDoc::Store::MissingFileError => e
    comment = RDoc::Comment.new("missing documentation at #{e.file}").parse

    method = RDoc::AnyMethod.new nil, name
    method.comment = comment
    method
  end

  ##
  # Returns an Array of RI data for methods matching +name+

  def load_methods_matching name
    found = []

    find_methods name do |store, klass, ancestor, types, method|
      methods = []

      methods << load_method(store, :class_methods, ancestor, '::',  method) if
        [:class, :both].include? types

      methods << load_method(store, :instance_methods, ancestor, '#',  method) if
        [:instance, :both].include? types

      found << [store, methods.compact]
    end

    found.reject do |path, methods| methods.empty? end
  end

  ##
  # Returns a filtered list of methods matching +name+

  def lookup_method name
    found = load_methods_matching name

    if found.empty?
      if check_did_you_mean
        methods = []
        _, _, method_name = parse_name name
        find_methods name do |store, klass, ancestor, types, method|
          methods.push(*store.class_methods[klass]) if [:class, :both].include? types
          methods.push(*store.instance_methods[klass]) if [:instance, :both].include? types
        end
        methods = methods.uniq
        suggestions = DidYouMean::SpellChecker.new(dictionary: methods).correct(method_name)
        raise NotFoundError.new(name, suggestions)
      else
        raise NotFoundError, name
      end
    end

    filter_methods found, name
  end

  ##
  # Builds a RDoc::Markup::Document from +found+, +klasses+ and +includes+

  def method_document name, filtered
    out = RDoc::Markup::Document.new

    out << RDoc::Markup::Heading.new(1, name)
    out << RDoc::Markup::BlankLine.new

    filtered.each do |store, methods|
      methods.each do |method|
        render_method out, store, method, name
      end
    end

    out
  end

  ##
  # Returns the type of method (:both, :instance, :class) for +selector+

  def method_type selector
    case selector
    when '.', nil then :both
    when '#'      then :instance
    else               :class
    end
  end

  ##
  # Returns a regular expression for +name+ that will match an
  # RDoc::AnyMethod's name.

  def name_regexp name
    klass, type, name = parse_name name

    case type
    when '#', '::' then
      /^#{klass}#{type}#{Regexp.escape name}$/
    else
      /^#{klass}(#|::)#{Regexp.escape name}$/
    end
  end

  ##
  # Paginates output through a pager program.

  def page
    if pager = setup_pager then
      begin
        yield pager
      ensure
        pager.close
        @jruby_pager_process.wait_for if @jruby_pager_process
      end
    else
      yield $stdout
    end
  rescue Errno::EPIPE
  ensure
    @paging = false
  end

  ##
  # Are we using a pager?

  def paging?
    @paging
  end

  ##
  # Extracts the class, selector and method name parts from +name+ like
  # Foo::Bar#baz.
  #
  # NOTE: Given Foo::Bar, Bar is considered a class even though it may be a
  # method

  def parse_name name
    parts = name.split(/(::?|#|\.)/)

    if parts.length == 1 then
      if parts.first =~ /^[a-z]|^([%&*+\/<>^`|~-]|\+@|-@|<<|<=>?|===?|=>|=~|>>|\[\]=?|~@)$/ then
        type = '.'
        meth = parts.pop
      else
        type = nil
        meth = nil
      end
    elsif parts.length == 2 or parts.last =~ /::|#|\./ then
      type = parts.pop
      meth = nil
    elsif parts[1] == ':' then
      klass = parts.shift
      type  = parts.shift
      meth  = parts.join
    elsif parts[-2] != '::' or parts.last !~ /^[A-Z]/ then
      meth = parts.pop
      type = parts.pop
    end

    klass ||= parts.join

    [klass, type, meth]
  end

  ##
  # Renders the +klass+ from +store+ to +out+.  If the klass has no
  # documentable items the class is added to +also_in+ instead.

  def render_class out, store, klass, also_in # :nodoc:
    comment = klass.comment
    # TODO the store's cache should always return an empty Array
    class_methods    = store.class_methods[klass.full_name]    || []
    instance_methods = store.instance_methods[klass.full_name] || []
    attributes       = store.attributes[klass.full_name]       || []

    if comment.empty? and
       instance_methods.empty? and class_methods.empty? then
      also_in << store
      return
    end

    add_from out, store

    class_document_comment out, comment

    if class_methods or instance_methods or not klass.constants.empty? then
      out << RDoc::Markup::Rule.new(1)
    end

    class_document_constants out, klass

    add_method_list out, class_methods,    'Class methods'
    add_method_list out, instance_methods, 'Instance methods'
    add_method_list out, attributes,       'Attributes'

    add_method_documentation out, klass if @show_all
  end

  def render_method out, store, method, name # :nodoc:
    out << RDoc::Markup::Paragraph.new("(from #{store.friendly_path})")

    unless name =~ /^#{Regexp.escape method.parent_name}/ then
      out << RDoc::Markup::Heading.new(3, "Implementation from #{method.parent_name}")
    end

    out << RDoc::Markup::Rule.new(1)

    render_method_arguments out, method.arglists
    render_method_superclass out, method
    if method.is_alias_for
      al = method.is_alias_for
      alias_for = store.load_method al.parent_name, "#{al.name_prefix}#{al.name}"
      render_method_comment out, method, alias_for
    else
      render_method_comment out, method
    end
  end

  def render_method_arguments out, arglists # :nodoc:
    return unless arglists

    arglists = arglists.chomp.split "\n"
    arglists = arglists.map { |line| line + "\n" }
    out << RDoc::Markup::Verbatim.new(*arglists)
    out << RDoc::Markup::Rule.new(1)
  end

  def render_method_comment out, method, alias_for = nil# :nodoc:
    if alias_for
      unless method.comment.nil? or method.comment.empty?
        out << RDoc::Markup::BlankLine.new
        out << method.comment
      end
      out << RDoc::Markup::BlankLine.new
      out << RDoc::Markup::Paragraph.new("(This method is an alias for #{alias_for.full_name}.)")
      out << RDoc::Markup::BlankLine.new
      out << alias_for.comment
      out << RDoc::Markup::BlankLine.new
    else
      out << RDoc::Markup::BlankLine.new
      out << method.comment
      out << RDoc::Markup::BlankLine.new
    end
  end

  def render_method_superclass out, method # :nodoc:
    return unless
      method.respond_to?(:superclass_method) and method.superclass_method

    out << RDoc::Markup::BlankLine.new
    out << RDoc::Markup::Heading.new(4, "(Uses superclass method #{method.superclass_method})")
    out << RDoc::Markup::Rule.new(1)
  end

  ##
  # Looks up and displays ri data according to the options given.

  def run
    if @list_doc_dirs then
      puts @doc_dirs
    elsif @list then
      list_known_classes @names
    elsif @server then
      start_server
    elsif @interactive or @names.empty? then
      interactive
    else
      display_names @names
    end
  rescue NotFoundError => e
    abort e.message
  end

  ##
  # Sets up a pager program to pass output through.  Tries the RI_PAGER and
  # PAGER environment variables followed by pager, less then more.

  def setup_pager
    return if @use_stdout

    jruby = RUBY_ENGINE == 'jruby'

    pagers = [ENV['RI_PAGER'], ENV['PAGER'], 'pager', 'less', 'more']

    pagers.compact.uniq.each do |pager|
      next unless pager

      pager_cmd = pager.split(' ').first

      next unless in_path? pager_cmd

      if jruby then
        case io = find_pager_jruby(pager)
        when nil   then break
        when false then next
        else            io
        end
      else
        io = IO.popen(pager, 'w') rescue next
      end

      next if $? and $?.pid == io.pid and $?.exited? # pager didn't work

      @paging = true

      return io
    end

    @use_stdout = true

    nil
  end

  ##
  # Starts a WEBrick server for ri.

  def start_server
    begin
      require 'webrick'
    rescue LoadError
      abort "webrick is not found. You may need to `gem install webrick` to install webrick."
    end

    server = WEBrick::HTTPServer.new :Port => @server

    extra_doc_dirs = @stores.map {|s| s.type == :extra ? s.path : nil}.compact

    server.mount '/', RDoc::Servlet, nil, extra_doc_dirs

    trap 'INT'  do server.shutdown end
    trap 'TERM' do server.shutdown end

    server.start
  end

end
# frozen_string_literal: true
module RDoc::RI

  Store = RDoc::Store # :nodoc:

end

# frozen_string_literal: true
# :markup: tomdoc

# A parser for TomDoc based on TomDoc 1.0.0-rc1 (02adef9b5a)
#
# The TomDoc specification can be found at:
#
# http://tomdoc.org
#
# The latest version of the TomDoc specification can be found at:
#
# https://github.com/mojombo/tomdoc/blob/master/tomdoc.md
#
# To choose TomDoc as your only default format see RDoc::Options@Saved+Options
# for instructions on setting up a <code>.rdoc_options</code> file to store
# your project default.
#
# There are a few differences between this parser and the specification.  A
# best-effort was made to follow the specification as closely as possible but
# some choices to deviate were made.
#
# A future version of RDoc will warn when a MUST or MUST NOT is violated and
# may warn when a SHOULD or SHOULD NOT is violated.  RDoc will always try
# to emit documentation even if given invalid TomDoc.
#
# Here are some implementation choices this parser currently makes:
#
# This parser allows rdoc-style inline markup but you should not depended on
# it.
#
# This parser allows a space between the comment and the method body.
#
# This parser does not require the default value to be described for an
# optional argument.
#
# This parser does not examine the order of sections.  An Examples section may
# precede the Arguments section.
#
# This class is documented in TomDoc format.  Since this is a subclass of the
# RDoc markup parser there isn't much to see here, unfortunately.

class RDoc::TomDoc < RDoc::Markup::Parser

  # Internal: Token accessor

  attr_reader :tokens

  # Internal: Adds a post-processor which sets the RDoc section based on the
  # comment's status.
  #
  # Returns nothing.

  def self.add_post_processor # :nodoc:
    RDoc::Markup::PreProcess.post_process do |comment, code_object|
      next unless code_object and
                  RDoc::Comment === comment and comment.format == 'tomdoc'

      comment.text.gsub!(/(\A\s*# )(Public|Internal|Deprecated):\s+/) do
        section = code_object.add_section $2
        code_object.temporary_section = section

        $1
      end
    end
  end

  add_post_processor

  # Public: Parses TomDoc from text
  #
  # text - A String containing TomDoc-format text.
  #
  # Examples
  #
  #   RDoc::TomDoc.parse <<-TOMDOC
  #   This method does some things
  #
  #   Returns nothing.
  #   TOMDOC
  #   # => #<RDoc::Markup::Document:0xXXX @parts=[...], @file=nil>
  #
  # Returns an RDoc::Markup::Document representing the TomDoc format.

  def self.parse text
    parser = new

    parser.tokenize text
    doc = RDoc::Markup::Document.new
    parser.parse doc
    doc
  end

  # Internal: Extracts the Signature section's method signature
  #
  # comment - An RDoc::Comment that will be parsed and have the signature
  #           extracted
  #
  # Returns a String containing the signature and nil if not

  def self.signature comment
    return unless comment.tomdoc?

    document = comment.parse

    signature = nil
    found_heading = false
    found_signature = false

    document.parts.delete_if do |part|
      next false if found_signature

      found_heading ||=
        RDoc::Markup::Heading === part && part.text == 'Signature'

      next false unless found_heading

      next true if RDoc::Markup::BlankLine === part

      if RDoc::Markup::Verbatim === part then
        signature = part
        found_signature = true
      end
    end

    signature and signature.text
  end

  # Public: Creates a new TomDoc parser.  See also RDoc::Markup::parse

  def initialize
    super

    @section      = nil
    @seen_returns = false
  end

  # Internal: Builds a heading from the token stream
  #
  # level - The level of heading to create
  #
  # Returns an RDoc::Markup::Heading

  def build_heading level
    heading = super

    @section = heading.text

    heading
  end

  # Internal: Builds a verbatim from the token stream.  A verbatim in the
  # Examples section will be marked as in Ruby format.
  #
  # margin - The indentation from the margin for lines that belong to this
  #          verbatim section.
  #
  # Returns an RDoc::Markup::Verbatim

  def build_verbatim margin
    verbatim = super

    verbatim.format = :ruby if @section == 'Examples'

    verbatim
  end

  # Internal: Builds a paragraph from the token stream
  #
  # margin - Unused
  #
  # Returns an RDoc::Markup::Paragraph.

  def build_paragraph margin
    p :paragraph_start => margin if @debug

    paragraph = RDoc::Markup::Paragraph.new

    until @tokens.empty? do
      type, data, = get

      case type
      when :TEXT then
        @section = 'Returns' if data =~ /\A(Returns|Raises)/

        paragraph << data
      when :NEWLINE then
        if :TEXT == peek_token[0] then
          # Lines beginning with 'Raises' in the Returns section should not be
          # treated as multiline text
          if 'Returns' == @section and
            peek_token[1].start_with?('Raises') then
            break
          else
            paragraph << ' '
          end
        else
          break
        end
      else
        unget
        break
      end
    end

    p :paragraph_end => margin if @debug

    paragraph
  end

  ##
  # Detects a section change to "Returns" and adds a heading

  def parse_text parent, indent # :nodoc:
    paragraph = build_paragraph indent

    if false == @seen_returns and 'Returns' == @section then
      @seen_returns = true
      parent << RDoc::Markup::Heading.new(3, 'Returns')
      parent << RDoc::Markup::BlankLine.new
    end

    parent << paragraph
  end

  # Internal: Turns text into an Array of tokens
  #
  # text - A String containing TomDoc-format text.
  #
  # Returns self.

  def tokenize text
    text = text.sub(/\A(Public|Internal|Deprecated):\s+/, '')

    setup_scanner text

    until @s.eos? do
      pos = @s.pos

      # leading spaces will be reflected by the column of the next token
      # the only thing we loose are trailing spaces at the end of the file
      next if @s.scan(/ +/)

      @tokens << case
                 when @s.scan(/\r?\n/) then
                   token = [:NEWLINE, @s.matched, *pos]
                   @s.newline!
                   token
                 when @s.scan(/(Examples|Signature)$/) then
                   @tokens << [:HEADER, 3, *pos]

                   [:TEXT, @s[1], *pos]
                 when @s.scan(/([:\w][\w\[\]]*)[ ]+- /) then
                   [:NOTE, @s[1], *pos]
                 else
                   @s.scan(/.*/)
                   [:TEXT, @s.matched.sub(/\r$/, ''), *pos]
                 end
    end

    self
  end

end
# frozen_string_literal: true
##
# RDoc statistics collector which prints a summary and report of a project's
# documentation totals.

class RDoc::Stats

  include RDoc::Text

  ##
  # Output level for the coverage report

  attr_reader :coverage_level

  ##
  # Count of files parsed during parsing

  attr_reader :files_so_far

  ##
  # Total number of files found

  attr_reader :num_files

  ##
  # Creates a new Stats that will have +num_files+.  +verbosity+ defaults to 1
  # which will create an RDoc::Stats::Normal outputter.

  def initialize store, num_files, verbosity = 1
    @num_files = num_files
    @store     = store

    @coverage_level   = 0
    @doc_items        = nil
    @files_so_far     = 0
    @fully_documented = false
    @num_params       = 0
    @percent_doc      = nil
    @start            = Time.now
    @undoc_params     = 0

    @display = case verbosity
               when 0 then Quiet.new   num_files
               when 1 then Normal.new  num_files
               else        Verbose.new num_files
               end
  end

  ##
  # Records the parsing of an alias +as+.

  def add_alias as
    @display.print_alias as
  end

  ##
  # Records the parsing of an attribute +attribute+

  def add_attribute attribute
    @display.print_attribute attribute
  end

  ##
  # Records the parsing of a class +klass+

  def add_class klass
    @display.print_class klass
  end

  ##
  # Records the parsing of +constant+

  def add_constant constant
    @display.print_constant constant
  end

  ##
  # Records the parsing of +file+

  def add_file(file)
    @files_so_far += 1
    @display.print_file @files_so_far, file
  end

  ##
  # Records the parsing of +method+

  def add_method(method)
    @display.print_method method
  end

  ##
  # Records the parsing of a module +mod+

  def add_module(mod)
    @display.print_module mod
  end

  ##
  # Call this to mark the beginning of parsing for display purposes

  def begin_adding
    @display.begin_adding
  end

  ##
  # Calculates documentation totals and percentages for classes, modules,
  # constants, attributes and methods.

  def calculate
    return if @doc_items

    ucm = @store.unique_classes_and_modules

    classes = @store.unique_classes.reject { |cm| cm.full_name == 'Object' }

    constants = []
    ucm.each { |cm| constants.concat cm.constants }

    methods = []
    ucm.each { |cm| methods.concat cm.method_list }

    attributes = []
    ucm.each { |cm| attributes.concat cm.attributes }

    @num_attributes, @undoc_attributes = doc_stats attributes
    @num_classes,    @undoc_classes    = doc_stats classes
    @num_constants,  @undoc_constants  = doc_stats constants
    @num_methods,    @undoc_methods    = doc_stats methods
    @num_modules,    @undoc_modules    = doc_stats @store.unique_modules

    @num_items =
      @num_attributes +
      @num_classes +
      @num_constants +
      @num_methods +
      @num_modules +
      @num_params

    @undoc_items =
      @undoc_attributes +
      @undoc_classes +
      @undoc_constants +
      @undoc_methods +
      @undoc_modules +
      @undoc_params

    @doc_items = @num_items - @undoc_items
  end

  ##
  # Sets coverage report level.  Accepted values are:
  #
  # false or nil:: No report
  # 0:: Classes, modules, constants, attributes, methods
  # 1:: Level 0 + method parameters

  def coverage_level= level
    level = -1 unless level

    @coverage_level = level
  end

  ##
  # Returns the length and number of undocumented items in +collection+.

  def doc_stats collection
    visible = collection.select { |item| item.display? }
    [visible.length, visible.count { |item| not item.documented? }]
  end

  ##
  # Call this to mark the end of parsing for display purposes

  def done_adding
    @display.done_adding
  end

  ##
  # The documentation status of this project.  +true+ when 100%, +false+ when
  # less than 100% and +nil+ when unknown.
  #
  # Set by calling #calculate

  def fully_documented?
    @fully_documented
  end

  ##
  # A report that says you did a great job!

  def great_job
    report = RDoc::Markup::Document.new

    report << RDoc::Markup::Paragraph.new('100% documentation!')
    report << RDoc::Markup::Paragraph.new('Great Job!')

    report
  end

  ##
  # Calculates the percentage of items documented.

  def percent_doc
    return @percent_doc if @percent_doc

    @fully_documented = (@num_items - @doc_items) == 0

    @percent_doc = @doc_items.to_f / @num_items * 100 if @num_items.nonzero?
    @percent_doc ||= 0

    @percent_doc
  end

  ##
  # Returns a report on which items are not documented

  def report
    if @coverage_level > 0 then
      extend RDoc::Text
    end

    if @coverage_level.zero? then
      calculate

      return great_job if @num_items == @doc_items
    end

    ucm = @store.unique_classes_and_modules

    report = RDoc::Markup::Document.new
    report << RDoc::Markup::Paragraph.new('The following items are not documented:')
    report << RDoc::Markup::BlankLine.new

    ucm.sort.each do |cm|
      body = report_class_module(cm) {
        [
          report_constants(cm),
          report_attributes(cm),
          report_methods(cm),
        ].compact
      }

      report << body if body
    end

    if @coverage_level > 0 then
      calculate

      return great_job if @num_items == @doc_items
    end

    report
  end

  ##
  # Returns a report on undocumented attributes in ClassModule +cm+

  def report_attributes cm
    return if cm.attributes.empty?

    report = []

    cm.each_attribute do |attr|
      next if attr.documented?
      line = attr.line ? ":#{attr.line}" : nil
      report << "  #{attr.definition} :#{attr.name} # in file #{attr.file.full_name}#{line}\n"
      report << "\n"
    end

    report
  end

  ##
  # Returns a report on undocumented items in ClassModule +cm+

  def report_class_module cm
    return if cm.fully_documented? and @coverage_level.zero?
    return unless cm.display?

    report = RDoc::Markup::Document.new

    if cm.in_files.empty? then
      report << RDoc::Markup::Paragraph.new("#{cm.definition} is referenced but empty.")
      report << RDoc::Markup::Paragraph.new("It probably came from another project.  I'm sorry I'm holding it against you.")

      return report
    elsif cm.documented? then
      documented = true
      klass = RDoc::Markup::Verbatim.new("#{cm.definition} # is documented\n")
    else
      report << RDoc::Markup::Paragraph.new('In files:')

      list = RDoc::Markup::List.new :BULLET

      cm.in_files.each do |file|
        para = RDoc::Markup::Paragraph.new file.full_name
        list << RDoc::Markup::ListItem.new(nil, para)
      end

      report << list
      report << RDoc::Markup::BlankLine.new

      klass = RDoc::Markup::Verbatim.new("#{cm.definition}\n")
    end

    klass << "\n"

    body = yield.flatten # HACK remove #flatten

    if body.empty? then
      return if documented

      klass.parts.pop
    else
      klass.parts.concat body
    end

    klass << "end\n"

    report << klass

    report
  end

  ##
  # Returns a report on undocumented constants in ClassModule +cm+

  def report_constants cm
    return if cm.constants.empty?

    report = []

    cm.each_constant do |constant|
      # TODO constant aliases are listed in the summary but not reported
      # figure out what to do here
      next if constant.documented? || constant.is_alias_for

      line = constant.line ? ":#{constant.line}" : line
      report << "  # in file #{constant.file.full_name}#{line}\n"
      report << "  #{constant.name} = nil\n"
      report << "\n"
    end

    report
  end

  ##
  # Returns a report on undocumented methods in ClassModule +cm+

  def report_methods cm
    return if cm.method_list.empty?

    report = []

    cm.each_method do |method|
      next if method.documented? and @coverage_level.zero?

      if @coverage_level > 0 then
        params, undoc = undoc_params method

        @num_params += params

        unless undoc.empty? then
          @undoc_params += undoc.length

          undoc = undoc.map do |param| "+#{param}+" end
          param_report = "  # #{undoc.join ', '} is not documented\n"
        end
      end

      next if method.documented? and not param_report

      line = method.line ? ":#{method.line}" : nil
      scope = method.singleton ? 'self.' : nil

      report << "  # in file #{method.file.full_name}#{line}\n"
      report << param_report if param_report
      report << "  def #{scope}#{method.name}#{method.params}; end\n"
      report << "\n"
    end

    report
  end

  ##
  # Returns a summary of the collected statistics.

  def summary
    calculate

    num_width = [@num_files, @num_items].max.to_s.length
    undoc_width = [
      @undoc_attributes,
      @undoc_classes,
      @undoc_constants,
      @undoc_items,
      @undoc_methods,
      @undoc_modules,
      @undoc_params,
    ].max.to_s.length

    report = RDoc::Markup::Verbatim.new

    report << "Files:      %*d\n" % [num_width, @num_files]

    report << "\n"

    report << "Classes:    %*d (%*d undocumented)\n" % [
      num_width, @num_classes, undoc_width, @undoc_classes]
    report << "Modules:    %*d (%*d undocumented)\n" % [
      num_width, @num_modules, undoc_width, @undoc_modules]
    report << "Constants:  %*d (%*d undocumented)\n" % [
      num_width, @num_constants, undoc_width, @undoc_constants]
    report << "Attributes: %*d (%*d undocumented)\n" % [
      num_width, @num_attributes, undoc_width, @undoc_attributes]
    report << "Methods:    %*d (%*d undocumented)\n" % [
      num_width, @num_methods, undoc_width, @undoc_methods]
    report << "Parameters: %*d (%*d undocumented)\n" % [
      num_width, @num_params, undoc_width, @undoc_params] if
        @coverage_level > 0

    report << "\n"

    report << "Total:      %*d (%*d undocumented)\n" % [
      num_width, @num_items, undoc_width, @undoc_items]

    report << "%6.2f%% documented\n" % percent_doc
    report << "\n"
    report << "Elapsed: %0.1fs\n" % (Time.now - @start)

    RDoc::Markup::Document.new report
  end

  ##
  # Determines which parameters in +method+ were not documented.  Returns a
  # total parameter count and an Array of undocumented methods.

  def undoc_params method
    @formatter ||= RDoc::Markup::ToTtOnly.new

    params = method.param_list

    params = params.map { |param| param.gsub(/^\*\*?/, '') }

    return 0, [] if params.empty?

    document = parse method.comment

    tts = document.accept @formatter

    undoc = params - tts

    [params.length, undoc]
  end

  autoload :Quiet,   'rdoc/stats/quiet'
  autoload :Normal,  'rdoc/stats/normal'
  autoload :Verbose, 'rdoc/stats/verbose'

end

# frozen_string_literal: true
##
# RDoc::Markup parses plain text documents and attempts to decompose them into
# their constituent parts.  Some of these parts are high-level: paragraphs,
# chunks of verbatim text, list entries and the like.  Other parts happen at
# the character level: a piece of bold text, a word in code font.  This markup
# is similar in spirit to that used on WikiWiki webs, where folks create web
# pages using a simple set of formatting rules.
#
# RDoc::Markup and other markup formats do no output formatting, this is
# handled by the RDoc::Markup::Formatter subclasses.
#
# = Supported Formats
#
# Besides the RDoc::Markup format, the following formats are built in to RDoc:
#
# markdown::
#   The markdown format as described by
#   http://daringfireball.net/projects/markdown/.  See RDoc::Markdown for
#   details on the parser and supported extensions.
# rd::
#   The rdtool format.  See RDoc::RD for details on the parser and format.
# tomdoc::
#   The TomDoc format as described by http://tomdoc.org/.  See RDoc::TomDoc
#   for details on the parser and supported extensions.
#
# You can choose a markup format using the following methods:
#
# per project::
#   If you build your documentation with rake use RDoc::Task#markup.
#
#   If you build your documentation by hand run:
#
#      rdoc --markup your_favorite_format --write-options
#
#   and commit <tt>.rdoc_options</tt> and ship it with your packaged gem.
# per file::
#   At the top of the file use the <tt>:markup:</tt> directive to set the
#   default format for the rest of the file.
# per comment::
#   Use the <tt>:markup:</tt> directive at the top of a comment you want
#   to write in a different format.
#
# = RDoc::Markup
#
# RDoc::Markup is extensible at runtime: you can add \new markup elements to
# be recognized in the documents that RDoc::Markup parses.
#
# RDoc::Markup is intended to be the basis for a family of tools which share
# the common requirement that simple, plain-text should be rendered in a
# variety of different output formats and media.  It is envisaged that
# RDoc::Markup could be the basis for formatting RDoc style comment blocks,
# Wiki entries, and online FAQs.
#
# == Synopsis
#
# This code converts +input_string+ to HTML.  The conversion takes place in
# the +convert+ method, so you can use the same RDoc::Markup converter to
# convert multiple input strings.
#
#   require 'rdoc'
#
#   h = RDoc::Markup::ToHtml.new(RDoc::Options.new)
#
#   puts h.convert(input_string)
#
# You can extend the RDoc::Markup parser to recognize new markup
# sequences, and to add regexp handling. Here we make WikiWords significant to
# the parser, and also make the sequences {word} and \<no>text...</no> signify
# strike-through text.  We then subclass the HTML output class to deal
# with these:
#
#   require 'rdoc'
#
#   class WikiHtml < RDoc::Markup::ToHtml
#     def handle_regexp_WIKIWORD(target)
#       "<font color=red>" + target.text + "</font>"
#     end
#   end
#
#   markup = RDoc::Markup.new
#   markup.add_word_pair("{", "}", :STRIKE)
#   markup.add_html("no", :STRIKE)
#
#   markup.add_regexp_handling(/\b([A-Z][a-z]+[A-Z]\w+)/, :WIKIWORD)
#
#   wh = WikiHtml.new RDoc::Options.new, markup
#   wh.add_tag(:STRIKE, "<strike>", "</strike>")
#
#   puts "<body>#{wh.convert ARGF.read}</body>"
#
# == Encoding
#
# Where Encoding support is available, RDoc will automatically convert all
# documents to the same output encoding.  The output encoding can be set via
# RDoc::Options#encoding and defaults to Encoding.default_external.
#
# = \RDoc Markup Reference
#
# == Block Markup
#
# === Paragraphs and Verbatim
#
# The markup engine looks for a document's natural left margin.  This is
# used as the initial margin for the document.
#
# Consecutive lines starting at this margin are considered to be a
# paragraph. Empty lines separate paragraphs.
#
# Any line that starts to the right of the current margin is treated
# as verbatim text.  This is useful for code listings:
#
#   3.times { puts "Ruby" }
#
# In verbatim text, two or more blank lines are collapsed into one,
# and trailing blank lines are removed:
#
#   This is the first line
#
#
#   This is the second non-blank line,
#   after 2 blank lines in the source markup.
#
#
# There were two trailing blank lines right above this paragraph, that
# have been removed. In addition, the verbatim text has been shifted
# left, so the amount of indentation of verbatim text is unimportant.
#
# For HTML output RDoc makes a small effort to determine if a verbatim section
# contains Ruby source code.  If so, the verbatim block will be marked up as
# HTML.  Triggers include "def", "class", "module", "require", the "hash
# rocket"# (=>) or a block call with a parameter.
#
# === Headers
#
# A line starting with an equal sign (=) is treated as a
# heading.  Level one headings have one equals sign, level two headings
# have two, and so on until level six, which is the maximum
# (seven hyphens or more result in a level six heading).
#
# For example, the above header was obtained with:
#
#   === Headers
#
# In HTML output headers have an id matching their name.  The above example's
# HTML is:
#
#   <h3 id="label-Headers">Headers</h3>
#
# If a heading is inside a method body the id will be prefixed with the
# method's id.  If the above header where in the documentation for a method
# such as:
#
#   ##
#   # This method does fun things
#   #
#   # = Example
#   #
#   #   Example of fun things goes here ...
#
#   def do_fun_things
#   end
#
# The header's id would be:
#
#   <h1 id="method-i-do_fun_things-label-Example">Example</h1>
#
# The label can be linked-to using <tt>SomeClass@Headers</tt>.  See
# {Links}[RDoc::Markup@Links] for further details.
#
# === Rules
#
# A line starting with three or more hyphens (at the current indent)
# generates a horizontal rule.
#
#   ---
#
# produces:
#
# ---
#
# === Simple Lists
#
# If a paragraph starts with a "*", "-", "<digit>." or "<letter>.",
# then it is taken to be the start of a list.  The margin is increased to be
# the first non-space following the list start flag.  Subsequent lines
# should be indented to this new margin until the list ends.  For example:
#
#   * this is a list with three paragraphs in
#     the first item.  This is the first paragraph.
#
#     And this is the second paragraph.
#
#     1. This is an indented, numbered list.
#     2. This is the second item in that list
#
#     This is the third conventional paragraph in the
#     first list item.
#
#   * This is the second item in the original list
#
# produces:
#
# * this is a list with three paragraphs in
#   the first item.  This is the first paragraph.
#
#   And this is the second paragraph.
#
#   1. This is an indented, numbered list.
#   2. This is the second item in that list
#
#   This is the third conventional paragraph in the
#   first list item.
#
# * This is the second item in the original list
#
# === Labeled Lists
#
# You can also construct labeled lists, sometimes called description
# or definition lists.  Do this by putting the label in square brackets
# and indenting the list body:
#
#   [cat]  a small furry mammal
#          that seems to sleep a lot
#
#   [ant]  a little insect that is known
#          to enjoy picnics
#
# produces:
#
# [cat]  a small furry mammal
#        that seems to sleep a lot
#
# [ant]  a little insect that is known
#        to enjoy picnics
#
# If you want the list bodies to line up to the left of the labels,
# use two colons:
#
#   cat::  a small furry mammal
#          that seems to sleep a lot
#
#   ant::  a little insect that is known
#          to enjoy picnics
#
# produces:
#
# cat::  a small furry mammal
#        that seems to sleep a lot
#
# ant::  a little insect that is known
#        to enjoy picnics
#
# Notice that blank lines right after the label are ignored in labeled lists:
#
#   [one]
#
#       definition 1
#
#   [two]
#
#       definition 2
#
# produces the same output as
#
#   [one]  definition 1
#   [two]  definition 2
#
#
# === Lists and Verbatim
#
# If you want to introduce a verbatim section right after a list, it has to be
# less indented than the list item bodies, but more indented than the list
# label, letter, digit or bullet. For instance:
#
#   *   point 1
#
#   *   point 2, first paragraph
#
#       point 2, second paragraph
#         verbatim text inside point 2
#       point 2, third paragraph
#     verbatim text outside of the list (the list is therefore closed)
#   regular paragraph after the list
#
# produces:
#
# *   point 1
#
# *   point 2, first paragraph
#
#     point 2, second paragraph
#       verbatim text inside point 2
#     point 2, third paragraph
#   verbatim text outside of the list (the list is therefore closed)
# regular paragraph after the list
#
# == Text Markup
#
# === Bold, Italic, Typewriter Text
#
# You can use markup within text (except verbatim) to change the
# appearance of parts of that text.  Out of the box, RDoc::Markup
# supports word-based and general markup.
#
# Word-based markup uses flag characters around individual words:
#
# <tt>\*_word_\*</tt>::  displays _word_ in a *bold* font
# <tt>\__word_\_</tt>::  displays _word_ in an _emphasized_ font
# <tt>\+_word_\+</tt>::  displays _word_ in a +code+ font
#
# General markup affects text between a start delimiter and an end
# delimiter.  Not surprisingly, these delimiters look like HTML markup.
#
# <tt>\<b>_text_</b></tt>::    displays _text_ in a *bold* font
# <tt>\<em>_text_</em></tt>::  displays _text_ in an _emphasized_ font
#                              (alternate tag: <tt>\<i></tt>)
# <tt>\<tt>_text_\</tt></tt>:: displays _text_ in a +code+ font
#                              (alternate tag: <tt>\<code></tt>)
#
# Unlike conventional Wiki markup, general markup can cross line
# boundaries.  You can turn off the interpretation of markup by
# preceding the first character with a backslash (see <i>Escaping
# Text Markup</i>, below).
#
# === Links
#
# Links to starting with +http:+, +https:+, +mailto:+, +ftp:+ or +www.+
# are recognized.  An HTTP url that references an external image is converted
# into an inline image element.
#
# Classes and methods will be automatically linked to their definition.  For
# example, <tt>RDoc::Markup</tt> will link to this documentation.  By default
# methods will only be automatically linked if they contain an <tt>_</tt> (all
# methods can be automatically linked through the <tt>--hyperlink-all</tt>
# command line option).
#
# Single-word methods can be linked by using the <tt>#</tt> character for
# instance methods or <tt>::</tt> for class methods.  For example,
# <tt>#convert</tt> links to #convert.  A class or method may be combined like
# <tt>RDoc::Markup#convert</tt>.
#
# A heading inside the documentation can be linked by following the class
# or method by an <tt>@</tt> then the heading name.
# <tt>RDoc::Markup@Links</tt> will link to this section like this:
# RDoc::Markup@Links.  Spaces in headings with multiple words must be escaped
# with <tt>+</tt> like <tt>RDoc::Markup@Escaping+Text+Markup</tt>.
# Punctuation and other special characters must be escaped like CGI.escape.
#
# The <tt>@</tt> can also be used to link to sections.  If a section and a
# heading share the same name the section is preferred for the link.
#
# Links can also be of the form <tt>label[url]</tt>, in which case +label+ is
# used in the displayed text, and +url+ is used as the target.  If +label+
# contains multiple words, put it in braces: <tt>{multi word label}[url]</tt>.
# The +url+ may be an +http:+-type link or a cross-reference to a class,
# module or method with a label.
#
# Links with the <code>rdoc-image:</code> scheme will create an image tag for
# HTML output.  Only fully-qualified URLs are supported.
#
# Links with the <tt>rdoc-ref:</tt> scheme will link to the referenced class,
# module, method, file, etc.  If the referenced item is does not exist
# no link will be generated and <tt>rdoc-ref:</tt> will be removed from the
# resulting text.
#
# Links starting with <tt>rdoc-label:label_name</tt> will link to the
# +label_name+.  You can create a label for the current link (for
# bidirectional links) by supplying a name for the current link like
# <tt>rdoc-label:label-other:label-mine</tt>.
#
# Links starting with +link:+ refer to local files whose path is relative to
# the <tt>--op</tt> directory.  Use <tt>rdoc-ref:</tt> instead of
# <tt>link:</tt> to link to files generated by RDoc as the link target may
# be different across RDoc generators.
#
# Example links:
#
#   https://github.com/ruby/rdoc
#   mailto:user@example.com
#   {RDoc Documentation}[http://rdoc.rubyforge.org]
#   {RDoc Markup}[rdoc-ref:RDoc::Markup]
#
# === Escaping Text Markup
#
# Text markup can be escaped with a backslash, as in \<tt>, which was obtained
# with <tt>\\<tt></tt>.  Except in verbatim sections and between \<tt> tags,
# to produce a backslash you have to double it unless it is followed by a
# space, tab or newline. Otherwise, the HTML formatter will discard it, as it
# is used to escape potential links:
#
#   * The \ must be doubled if not followed by white space: \\.
#   * But not in \<tt> tags: in a Regexp, <tt>\S</tt> matches non-space.
#   * This is a link to {ruby-lang}[www.ruby-lang.org].
#   * This is not a link, however: \{ruby-lang.org}[www.ruby-lang.org].
#   * This will not be linked to \RDoc::RDoc#document
#
# generates:
#
# * The \ must be doubled if not followed by white space: \\.
# * But not in \<tt> tags: in a Regexp, <tt>\S</tt> matches non-space.
# * This is a link to {ruby-lang}[www.ruby-lang.org]
# * This is not a link, however: \{ruby-lang.org}[www.ruby-lang.org]
# * This will not be linked to \RDoc::RDoc#document
#
# Inside \<tt> tags, more precisely, leading backslashes are removed only if
# followed by a markup character (<tt><*_+</tt>), a backslash, or a known link
# reference (a known class or method). So in the example above, the backslash
# of <tt>\S</tt> would be removed if there was a class or module named +S+ in
# the current context.
#
# This behavior is inherited from RDoc version 1, and has been kept for
# compatibility with existing RDoc documentation.
#
# === Conversion of characters
#
# HTML will convert two/three dashes to an em-dash. Other common characters are
# converted as well:
#
#   em-dash::  -- or ---
#   ellipsis:: ...
#
#   single quotes:: 'text' or `text'
#   double quotes:: "text" or ``text''
#
#   copyright:: (c)
#   registered trademark:: (r)
#
# produces:
#
# em-dash::  -- or ---
# ellipsis:: ...
#
# single quotes:: 'text' or `text'
# double quotes:: "text" or ``text''
#
# copyright:: (c)
# registered trademark:: (r)
#
#
# == Documenting Source Code
#
# Comment blocks can be written fairly naturally, either using <tt>#</tt> on
# successive lines of the comment, or by including the comment in
# a <tt>=begin</tt>/<tt>=end</tt> block.  If you use the latter form,
# the <tt>=begin</tt> line _must_ be flagged with an +rdoc+ tag:
#
#   =begin rdoc
#   Documentation to be processed by RDoc.
#
#   ...
#   =end
#
# RDoc stops processing comments if it finds a comment line starting
# with <tt>--</tt> right after the <tt>#</tt> character (otherwise,
# it will be treated as a rule if it has three dashes or more).
# This can be used to separate external from internal comments,
# or to stop a comment being associated with a method, class, or module.
# Commenting can be turned back on with a line that starts with <tt>++</tt>.
#
#   ##
#   # Extract the age and calculate the date-of-birth.
#   #--
#   # FIXME: fails if the birthday falls on February 29th
#   #++
#   # The DOB is returned as a Time object.
#
#   def get_dob(person)
#     # ...
#   end
#
# Names of classes, files, and any method names containing an underscore or
# preceded by a hash character are automatically linked from comment text to
# their description. This linking works inside the current class or module,
# and with ancestor methods (in included modules or in the superclass).
#
# Method parameter lists are extracted and displayed with the method
# description.  If a method calls +yield+, then the parameters passed to yield
# will also be displayed:
#
#   def fred
#     ...
#     yield line, address
#
# This will get documented as:
#
#   fred() { |line, address| ... }
#
# You can override this using a comment containing ':yields: ...' immediately
# after the method definition
#
#   def fred # :yields: index, position
#     # ...
#
#     yield line, address
#
# which will get documented as
#
#    fred() { |index, position| ... }
#
# +:yields:+ is an example of a documentation directive.  These appear
# immediately after the start of the document element they are modifying.
#
# RDoc automatically cross-references words with underscores or camel-case.
# To suppress cross-references, prefix the word with a \ character.  To
# include special characters like "<tt>\n</tt>", you'll need to use
# two \ characters in normal text, but only one in \<tt> text:
#
#   "\\n" or "<tt>\n</tt>"
#
# produces:
#
# "\\n" or "<tt>\n</tt>"
#
# == Directives
#
# Directives are keywords surrounded by ":" characters.
#
# === Controlling what is documented
#
# [+:nodoc:+ / <tt>:nodoc: all</tt>]
#   This directive prevents documentation for the element from
#   being generated.  For classes and modules, methods, aliases,
#   constants, and attributes directly within the affected class or
#   module also will be omitted.  By default, though, modules and
#   classes within that class or module _will_ be documented.  This is
#   turned off by adding the +all+ modifier.
#
#     module MyModule # :nodoc:
#       class Input
#       end
#     end
#
#     module OtherModule # :nodoc: all
#       class Output
#       end
#     end
#
#   In the above code, only class <tt>MyModule::Input</tt> will be documented.
#
#   The +:nodoc:+ directive, like +:enddoc:+, +:stopdoc:+ and +:startdoc:+
#   presented below, is local to the current file: if you do not want to
#   document a module that appears in several files, specify +:nodoc:+ on each
#   appearance, at least once per file.
#
# [+:stopdoc:+ / +:startdoc:+]
#   Stop and start adding new documentation elements to the current container.
#   For example, if a class has a number of constants that you don't want to
#   document, put a +:stopdoc:+ before the first, and a +:startdoc:+ after the
#   last.  If you don't specify a +:startdoc:+ by the end of the container,
#   disables documentation for the rest of the current file.
#
# [+:doc:+]
#   Forces a method or attribute to be documented even if it wouldn't be
#   otherwise.  Useful if, for example, you want to include documentation of a
#   particular private method.
#
# [+:enddoc:+]
#   Document nothing further at the current level: directives +:startdoc:+ and
#   +:doc:+ that appear after this will not be honored for the current container
#   (file, class or module), in the current file.
#
# [+:notnew:+ / +:not_new:+ / +:not-new:+ ]
#   Only applicable to the +initialize+ instance method.  Normally RDoc
#   assumes that the documentation and parameters for +initialize+ are
#   actually for the +new+ method, and so fakes out a +new+ for the class.
#   The +:notnew:+ directive stops this.  Remember that +initialize+ is private,
#   so you won't see the documentation unless you use the +-a+ command line
#   option.
#
# === Method arguments
#
# [+:arg:+ or +:args:+ _parameters_]
#   Overrides the default argument handling with exactly these parameters.
#
#     ##
#     #  :args: a, b
#
#     def some_method(*a)
#     end
#
# [+:yield:+ or +:yields:+ _parameters_]
#   Overrides the default yield discovery with these parameters.
#
#     ##
#     # :yields: key, value
#
#     def each_thing &block
#       @things.each(&block)
#     end
#
# [+:call-seq:+]
#   Lines up to the next blank line or lines with a common prefix in the
#   comment are treated as the method's calling sequence, overriding the
#   default parsing of method parameters and yield arguments.
#
#   Multiple lines may be used.
#
#     # :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
#     #
#     # The remaining lines are documentation ...
#
# === Sections
#
# Sections allow you to group methods in a class into sensible containers.  If
# you use the sections 'Public', 'Internal' and 'Deprecated' (the three
# allowed method statuses from TomDoc) the sections will be displayed in that
# order placing the most useful methods at the top.  Otherwise, sections will
# be displayed in alphabetical order.
#
# [+:category:+ _section_]
#   Adds this item to the named +section+ overriding the current section.  Use
#   this to group methods by section in RDoc output while maintaining a
#   sensible ordering (like alphabetical).
#
#     # :category: Utility Methods
#     #
#     # CGI escapes +text+
#
#     def convert_string text
#       CGI.escapeHTML text
#     end
#
#   An empty category will place the item in the default category:
#
#     # :category:
#     #
#     # This method is in the default category
#
#     def some_method
#       # ...
#     end
#
#   Unlike the :section: directive, :category: is not sticky.  The category
#   only applies to the item immediately following the comment.
#
#   Use the :section: directive to provide introductory text for a section of
#   documentation.
#
# [+:section:+ _title_]
#   Provides section introductory text in RDoc output.  The title following
#   +:section:+ is used as the section name and the remainder of the comment
#   containing the section is used as introductory text.  A section's comment
#   block must be separated from following comment blocks.  Use an empty title
#   to switch to the default section.
#
#   The :section: directive is sticky, so subsequent methods, aliases,
#   attributes, and classes will be contained in this section until the
#   section is changed.  The :category: directive will override the :section:
#   directive.
#
#   A :section: comment block may have one or more lines before the :section:
#   directive.  These will be removed, and any identical lines at the end of
#   the block are also removed.  This allows you to add visual cues to the
#   section.
#
#   Example:
#
#     # ----------------------------------------
#     # :section: My Section
#     # This is the section that I wrote.
#     # See it glisten in the noon-day sun.
#     # ----------------------------------------
#
#     ##
#     # Comment for some_method
#
#     def some_method
#       # ...
#     end
#
# === Other directives
#
# [+:markup:+ _type_]
#   Overrides the default markup type for this comment with the specified
#   markup type.  For Ruby files, if the first comment contains this directive
#   it is applied automatically to all comments in the file.
#
#   Unless you are converting between markup formats you should use a
#   <code>.rdoc_options</code> file to specify the default documentation
#   format for your entire project.  See RDoc::Options@Saved+Options for
#   instructions.
#
#   At the top of a file the +:markup:+ directive applies to the entire file:
#
#     # coding: UTF-8
#     # :markup: TomDoc
#
#     # TomDoc comment here ...
#
#     class MyClass
#       # ...
#
#   For just one comment:
#
#       # ...
#     end
#
#     # :markup: RDoc
#     #
#     # This is a comment in RDoc markup format ...
#
#     def some_method
#       # ...
#
#   See Markup@CONTRIBUTING for instructions on adding a new markup format.
#
# [+:include:+ _filename_]
#   Include the contents of the named file at this point. This directive
#   must appear alone on one line, possibly preceded by spaces. In this
#   position, it can be escaped with a \ in front of the first colon.
#
#   The file will be searched for in the directories listed by the +--include+
#   option, or in the current directory by default.  The contents of the file
#   will be shifted to have the same indentation as the ':' at the start of
#   the +:include:+ directive.
#
# [+:title:+ _text_]
#   Sets the title for the document.  Equivalent to the <tt>--title</tt>
#   command line parameter.  (The command line parameter overrides any :title:
#   directive in the source).
#
# [+:main:+ _name_]
#   Equivalent to the <tt>--main</tt> command line parameter.
#
#--
# Original Author:: Dave Thomas,  dave@pragmaticprogrammer.com
# License:: Ruby license

class RDoc::Markup

  ##
  # An AttributeManager which handles inline markup.

  attr_reader :attribute_manager

  ##
  # Parses +str+ into an RDoc::Markup::Document.

  def self.parse str
    RDoc::Markup::Parser.parse str
  rescue RDoc::Markup::Parser::Error => e
    $stderr.puts <<-EOF
While parsing markup, RDoc encountered a #{e.class}:

#{e}
\tfrom #{e.backtrace.join "\n\tfrom "}

---8<---
#{text}
---8<---

RDoc #{RDoc::VERSION}

Ruby #{RUBY_VERSION}-p#{RUBY_PATCHLEVEL} #{RUBY_RELEASE_DATE}

Please file a bug report with the above information at:

https://github.com/ruby/rdoc/issues

    EOF
    raise
  end

  ##
  # Take a block of text and use various heuristics to determine its
  # structure (paragraphs, lists, and so on).  Invoke an event handler as we
  # identify significant chunks.

  def initialize attribute_manager = nil
    @attribute_manager = attribute_manager || RDoc::Markup::AttributeManager.new
    @output = nil
  end

  ##
  # Add to the sequences used to add formatting to an individual word (such
  # as *bold*).  Matching entries will generate attributes that the output
  # formatters can recognize by their +name+.

  def add_word_pair(start, stop, name)
    @attribute_manager.add_word_pair(start, stop, name)
  end

  ##
  # Add to the sequences recognized as general markup.

  def add_html(tag, name)
    @attribute_manager.add_html(tag, name)
  end

  ##
  # Add to other inline sequences.  For example, we could add WikiWords using
  # something like:
  #
  #    parser.add_regexp_handling(/\b([A-Z][a-z]+[A-Z]\w+)/, :WIKIWORD)
  #
  # Each wiki word will be presented to the output formatter.

  def add_regexp_handling(pattern, name)
    @attribute_manager.add_regexp_handling(pattern, name)
  end

  ##
  # We take +input+, parse it if necessary, then invoke the output +formatter+
  # using a Visitor to render the result.

  def convert input, formatter
    document = case input
               when RDoc::Markup::Document then
                 input
               else
                 RDoc::Markup::Parser.parse input
               end

    document.accept formatter
  end

  autoload :Parser,                'rdoc/markup/parser'
  autoload :PreProcess,            'rdoc/markup/pre_process'

  # Inline markup classes
  autoload :AttrChanger,           'rdoc/markup/attr_changer'
  autoload :AttrSpan,              'rdoc/markup/attr_span'
  autoload :Attributes,            'rdoc/markup/attributes'
  autoload :AttributeManager,      'rdoc/markup/attribute_manager'
  autoload :RegexpHandling,        'rdoc/markup/regexp_handling'

  # RDoc::Markup AST
  autoload :BlankLine,             'rdoc/markup/blank_line'
  autoload :BlockQuote,            'rdoc/markup/block_quote'
  autoload :Document,              'rdoc/markup/document'
  autoload :HardBreak,             'rdoc/markup/hard_break'
  autoload :Heading,               'rdoc/markup/heading'
  autoload :Include,               'rdoc/markup/include'
  autoload :IndentedParagraph,     'rdoc/markup/indented_paragraph'
  autoload :List,                  'rdoc/markup/list'
  autoload :ListItem,              'rdoc/markup/list_item'
  autoload :Paragraph,             'rdoc/markup/paragraph'
  autoload :Table,                 'rdoc/markup/table'
  autoload :Raw,                   'rdoc/markup/raw'
  autoload :Rule,                  'rdoc/markup/rule'
  autoload :Verbatim,              'rdoc/markup/verbatim'

  # Formatters
  autoload :Formatter,             'rdoc/markup/formatter'

  autoload :ToAnsi,                'rdoc/markup/to_ansi'
  autoload :ToBs,                  'rdoc/markup/to_bs'
  autoload :ToHtml,                'rdoc/markup/to_html'
  autoload :ToHtmlCrossref,        'rdoc/markup/to_html_crossref'
  autoload :ToHtmlSnippet,         'rdoc/markup/to_html_snippet'
  autoload :ToLabel,               'rdoc/markup/to_label'
  autoload :ToMarkdown,            'rdoc/markup/to_markdown'
  autoload :ToRdoc,                'rdoc/markup/to_rdoc'
  autoload :ToTableOfContents,     'rdoc/markup/to_table_of_contents'
  autoload :ToTest,                'rdoc/markup/to_test'
  autoload :ToTtOnly,              'rdoc/markup/to_tt_only'

end

# frozen_string_literal: true
require 'fileutils'

##
# A set of rdoc data for a single project (gem, path, etc.).
#
# The store manages reading and writing ri data for a project and maintains a
# cache of methods, classes and ancestors in the store.
#
# The store maintains a #cache of its contents for faster lookup.  After
# adding items to the store it must be flushed using #save_cache.  The cache
# contains the following structures:
#
#    @cache = {
#      :ancestors        => {}, # class name => ancestor names
#      :attributes       => {}, # class name => attributes
#      :class_methods    => {}, # class name => class methods
#      :instance_methods => {}, # class name => instance methods
#      :modules          => [], # classes and modules in this store
#      :pages            => [], # page names
#    }
#--
# TODO need to prune classes

class RDoc::Store

  ##
  # Errors raised from loading or saving the store

  class Error < RDoc::Error
  end

  ##
  # Raised when a stored file for a class, module, page or method is missing.

  class MissingFileError < Error

    ##
    # The store the file should exist in

    attr_reader :store

    ##
    # The file the #name should be saved as

    attr_reader :file

    ##
    # The name of the object the #file would be loaded from

    attr_reader :name

    ##
    # Creates a new MissingFileError for the missing +file+ for the given
    # +name+ that should have been in the +store+.

    def initialize store, file, name
      @store = store
      @file  = file
      @name  = name
    end

    def message # :nodoc:
      "store at #{@store.path} missing file #{@file} for #{@name}"
    end

  end

  ##
  # Stores the name of the C variable a class belongs to.  This helps wire up
  # classes defined from C across files.

  attr_reader :c_enclosure_classes # :nodoc:

  attr_reader :c_enclosure_names # :nodoc:

  ##
  # Maps C variables to class or module names for each parsed C file.

  attr_reader :c_class_variables

  ##
  # Maps C variables to singleton class names for each parsed C file.

  attr_reader :c_singleton_class_variables

  ##
  # If true this Store will not write any files

  attr_accessor :dry_run

  ##
  # Path this store reads or writes

  attr_accessor :path

  ##
  # The RDoc::RDoc driver for this parse tree.  This allows classes consulting
  # the documentation tree to access user-set options, for example.

  attr_accessor :rdoc

  ##
  # Type of ri datastore this was loaded from.  See RDoc::RI::Driver,
  # RDoc::RI::Paths.

  attr_accessor :type

  ##
  # The contents of the Store

  attr_reader :cache

  ##
  # The encoding of the contents in the Store

  attr_accessor :encoding

  ##
  # The lazy constants alias will be discovered in passing

  attr_reader :unmatched_constant_alias

  ##
  # Creates a new Store of +type+ that will load or save to +path+

  def initialize path = nil, type = nil
    @dry_run  = false
    @encoding = nil
    @path     = path
    @rdoc     = nil
    @type     = type

    @cache = {
      :ancestors                   => {},
      :attributes                  => {},
      :class_methods               => {},
      :c_class_variables           => {},
      :c_singleton_class_variables => {},
      :encoding                    => @encoding,
      :instance_methods            => {},
      :main                        => nil,
      :modules                     => [],
      :pages                       => [],
      :title                       => nil,
    }

    @classes_hash = {}
    @modules_hash = {}
    @files_hash   = {}
    @text_files_hash = {}

    @c_enclosure_classes = {}
    @c_enclosure_names   = {}

    @c_class_variables           = {}
    @c_singleton_class_variables = {}

    @unique_classes = nil
    @unique_modules = nil

    @unmatched_constant_alias = {}
  end

  ##
  # Adds +module+ as an enclosure (namespace) for the given +variable+ for C
  # files.

  def add_c_enclosure variable, namespace
    @c_enclosure_classes[variable] = namespace
  end

  ##
  # Adds C variables from an RDoc::Parser::C

  def add_c_variables c_parser
    filename = c_parser.top_level.relative_name

    @c_class_variables[filename] = make_variable_map c_parser.classes

    @c_singleton_class_variables[filename] = c_parser.singleton_classes
  end

  ##
  # Adds the file with +name+ as an RDoc::TopLevel to the store.  Returns the
  # created RDoc::TopLevel.

  def add_file absolute_name, relative_name: absolute_name, parser: nil
    unless top_level = @files_hash[relative_name] then
      top_level = RDoc::TopLevel.new absolute_name, relative_name
      top_level.parser = parser if parser
      top_level.store = self
      @files_hash[relative_name] = top_level
      @text_files_hash[relative_name] = top_level if top_level.text?
    end

    top_level
  end

  def update_parser_of_file(absolute_name, parser)
    if top_level = @files_hash[absolute_name] then
      @text_files_hash[absolute_name] = top_level if top_level.text?
    end
  end

  ##
  # Returns all classes discovered by RDoc

  def all_classes
    @classes_hash.values
  end

  ##
  # Returns all classes and modules discovered by RDoc

  def all_classes_and_modules
    @classes_hash.values + @modules_hash.values
  end

  ##
  # All TopLevels known to RDoc

  def all_files
    @files_hash.values
  end

  ##
  # Returns all modules discovered by RDoc

  def all_modules
    modules_hash.values
  end

  ##
  # Ancestors cache accessor.  Maps a klass name to an Array of its ancestors
  # in this store.  If Foo in this store inherits from Object, Kernel won't be
  # listed (it will be included from ruby's ri store).

  def ancestors
    @cache[:ancestors]
  end

  ##
  # Attributes cache accessor.  Maps a class to an Array of its attributes.

  def attributes
    @cache[:attributes]
  end

  ##
  # Path to the cache file

  def cache_path
    File.join @path, 'cache.ri'
  end

  ##
  # Path to the ri data for +klass_name+

  def class_file klass_name
    name = klass_name.split('::').last
    File.join class_path(klass_name), "cdesc-#{name}.ri"
  end

  ##
  # Class methods cache accessor.  Maps a class to an Array of its class
  # methods (not full name).

  def class_methods
    @cache[:class_methods]
  end

  ##
  # Path where data for +klass_name+ will be stored (methods or class data)

  def class_path klass_name
    File.join @path, *klass_name.split('::')
  end

  ##
  # Hash of all classes known to RDoc

  def classes_hash
    @classes_hash
  end

  ##
  # Removes empty items and ensures item in each collection are unique and
  # sorted

  def clean_cache_collection collection # :nodoc:
    collection.each do |name, item|
      if item.empty? then
        collection.delete name
      else
        # HACK mongrel-1.1.5 documents its files twice
        item.uniq!
        item.sort!
      end
    end
  end

  ##
  # Prepares the RDoc code object tree for use by a generator.
  #
  # It finds unique classes/modules defined, and replaces classes/modules that
  # are aliases for another one by a copy with RDoc::ClassModule#is_alias_for
  # set.
  #
  # It updates the RDoc::ClassModule#constant_aliases attribute of "real"
  # classes or modules.
  #
  # It also completely removes the classes and modules that should be removed
  # from the documentation and the methods that have a visibility below
  # +min_visibility+, which is the <tt>--visibility</tt> option.
  #
  # See also RDoc::Context#remove_from_documentation?

  def complete min_visibility
    fix_basic_object_inheritance

    # cache included modules before they are removed from the documentation
    all_classes_and_modules.each { |cm| cm.ancestors }

    unless min_visibility == :nodoc then
      remove_nodoc @classes_hash
      remove_nodoc @modules_hash
    end

    @unique_classes = find_unique @classes_hash
    @unique_modules = find_unique @modules_hash

    unique_classes_and_modules.each do |cm|
      cm.complete min_visibility
    end

    @files_hash.each_key do |file_name|
      tl = @files_hash[file_name]

      unless tl.text? then
        tl.modules_hash.clear
        tl.classes_hash.clear

        tl.classes_or_modules.each do |cm|
          name = cm.full_name
          if cm.type == 'class' then
            tl.classes_hash[name] = cm if @classes_hash[name]
          else
            tl.modules_hash[name] = cm if @modules_hash[name]
          end
        end
      end
    end
  end

  ##
  # Hash of all files known to RDoc

  def files_hash
    @files_hash
  end

  ##
  # Finds the enclosure (namespace) for the given C +variable+.

  def find_c_enclosure variable
    @c_enclosure_classes.fetch variable do
      break unless name = @c_enclosure_names[variable]

      mod = find_class_or_module name

      unless mod then
        loaded_mod = load_class_data name

        file = loaded_mod.in_files.first

        return unless file # legacy data source

        file.store = self

        mod = file.add_module RDoc::NormalModule, name
      end

      @c_enclosure_classes[variable] = mod
    end
  end

  ##
  # Finds the class with +name+ in all discovered classes

  def find_class_named name
    @classes_hash[name]
  end

  ##
  # Finds the class with +name+ starting in namespace +from+

  def find_class_named_from name, from
    from = find_class_named from unless RDoc::Context === from

    until RDoc::TopLevel === from do
      return nil unless from

      klass = from.find_class_named name
      return klass if klass

      from = from.parent
    end

    find_class_named name
  end

  ##
  # Finds the class or module with +name+

  def find_class_or_module name
    name = $' if name =~ /^::/
    @classes_hash[name] || @modules_hash[name]
  end

  ##
  # Finds the file with +name+ in all discovered files

  def find_file_named name
    @files_hash[name]
  end

  ##
  # Finds the module with +name+ in all discovered modules

  def find_module_named name
    @modules_hash[name]
  end

  ##
  # Returns the RDoc::TopLevel that is a text file and has the given
  # +file_name+

  def find_text_page file_name
    @text_files_hash.each_value.find do |file|
      file.full_name == file_name
    end
  end

  ##
  # Finds unique classes/modules defined in +all_hash+,
  # and returns them as an array. Performs the alias
  # updates in +all_hash+: see ::complete.
  #--
  # TODO  aliases should be registered by Context#add_module_alias

  def find_unique all_hash
    unique = []

    all_hash.each_pair do |full_name, cm|
      unique << cm if full_name == cm.full_name
    end

    unique
  end

  ##
  # Fixes the erroneous <tt>BasicObject < Object</tt> in 1.9.
  #
  # Because we assumed all classes without a stated superclass
  # inherit from Object, we have the above wrong inheritance.
  #
  # We fix BasicObject right away if we are running in a Ruby
  # version >= 1.9.

  def fix_basic_object_inheritance
    basic = classes_hash['BasicObject']
    return unless basic
    basic.superclass = nil
  end

  ##
  # Friendly rendition of #path

  def friendly_path
    case type
    when :gem    then
      parent = File.expand_path '..', @path
      "gem #{File.basename parent}"
    when :home   then RDoc.home
    when :site   then 'ruby site'
    when :system then 'ruby core'
    else @path
    end
  end

  def inspect # :nodoc:
    "#<%s:0x%x %s %p>" % [self.class, object_id, @path, module_names.sort]
  end

  ##
  # Instance methods cache accessor.  Maps a class to an Array of its
  # instance methods (not full name).

  def instance_methods
    @cache[:instance_methods]
  end

  ##
  # Loads all items from this store into memory.  This recreates a
  # documentation tree for use by a generator

  def load_all
    load_cache

    module_names.each do |module_name|
      mod = find_class_or_module(module_name) || load_class(module_name)

      # load method documentation since the loaded class/module does not have
      # it
      loaded_methods = mod.method_list.map do |method|
        load_method module_name, method.full_name
      end

      mod.method_list.replace loaded_methods

      loaded_attributes = mod.attributes.map do |attribute|
        load_method module_name, attribute.full_name
      end

      mod.attributes.replace loaded_attributes
    end

    all_classes_and_modules.each do |mod|
      descendent_re = /^#{mod.full_name}::[^:]+$/

      module_names.each do |name|
        next unless name =~ descendent_re

        descendent = find_class_or_module name

        case descendent
        when RDoc::NormalClass then
          mod.classes_hash[name] = descendent
        when RDoc::NormalModule then
          mod.modules_hash[name] = descendent
        end
      end
    end

    @cache[:pages].each do |page_name|
      page = load_page page_name
      @files_hash[page_name] = page
      @text_files_hash[page_name] = page if page.text?
    end
  end

  ##
  # Loads cache file for this store

  def load_cache
    #orig_enc = @encoding

    @cache = marshal_load(cache_path)

    load_enc = @cache[:encoding]

    # TODO this feature will be time-consuming to add:
    # a) Encodings may be incompatible but transcodeable
    # b) Need to warn in the appropriate spots, wherever they may be
    # c) Need to handle cross-cache differences in encodings
    # d) Need to warn when generating into a cache with different encodings
    #
    #if orig_enc and load_enc != orig_enc then
    #  warn "Cached encoding #{load_enc} is incompatible with #{orig_enc}\n" \
    #       "from #{path}/cache.ri" unless
    #    Encoding.compatible? orig_enc, load_enc
    #end

    @encoding = load_enc unless @encoding

    @cache[:pages]                       ||= []
    @cache[:main]                        ||= nil
    @cache[:c_class_variables]           ||= {}
    @cache[:c_singleton_class_variables] ||= {}

    @cache[:c_class_variables].each do |_, map|
      map.each do |variable, name|
        @c_enclosure_names[variable] = name
      end
    end

    @cache
  rescue Errno::ENOENT
  end

  ##
  # Loads ri data for +klass_name+ and hooks it up to this store.

  def load_class klass_name
    obj = load_class_data klass_name

    obj.store = self

    case obj
    when RDoc::NormalClass then
      @classes_hash[klass_name] = obj
    when RDoc::SingleClass then
      @classes_hash[klass_name] = obj
    when RDoc::NormalModule then
      @modules_hash[klass_name] = obj
    end
  end

  ##
  # Loads ri data for +klass_name+

  def load_class_data klass_name
    file = class_file klass_name

    marshal_load(file)
  rescue Errno::ENOENT => e
    error = MissingFileError.new(self, file, klass_name)
    error.set_backtrace e.backtrace
    raise error
  end

  ##
  # Loads ri data for +method_name+ in +klass_name+

  def load_method klass_name, method_name
    file = method_file klass_name, method_name

    obj = marshal_load(file)
    obj.store = self
    obj.parent ||= find_class_or_module(klass_name) || load_class(klass_name)
    obj
  rescue Errno::ENOENT => e
    error = MissingFileError.new(self, file, klass_name + method_name)
    error.set_backtrace e.backtrace
    raise error
  end

  ##
  # Loads ri data for +page_name+

  def load_page page_name
    file = page_file page_name

    obj = marshal_load(file)
    obj.store = self
    obj
  rescue Errno::ENOENT => e
    error = MissingFileError.new(self, file, page_name)
    error.set_backtrace e.backtrace
    raise error
  end

  ##
  # Gets the main page for this RDoc store.  This page is used as the root of
  # the RDoc server.

  def main
    @cache[:main]
  end

  ##
  # Sets the main page for this RDoc store.

  def main= page
    @cache[:main] = page
  end

  ##
  # Converts the variable => ClassModule map +variables+ from a C parser into
  # a variable => class name map.

  def make_variable_map variables
    map = {}

    variables.each { |variable, class_module|
      map[variable] = class_module.full_name
    }

    map
  end

  ##
  # Path to the ri data for +method_name+ in +klass_name+

  def method_file klass_name, method_name
    method_name = method_name.split('::').last
    method_name =~ /#(.*)/
    method_type = $1 ? 'i' : 'c'
    method_name = $1 if $1
    method_name = method_name.gsub(/\W/) { "%%%02x" % $&[0].ord }

    File.join class_path(klass_name), "#{method_name}-#{method_type}.ri"
  end

  ##
  # Modules cache accessor.  An Array of all the module (and class) names in
  # the store.

  def module_names
    @cache[:modules]
  end

  ##
  # Hash of all modules known to RDoc

  def modules_hash
    @modules_hash
  end

  ##
  # Returns the RDoc::TopLevel that is a text file and has the given +name+

  def page name
    @text_files_hash.each_value.find do |file|
      file.page_name == name or file.base_name == name
    end
  end

  ##
  # Path to the ri data for +page_name+

  def page_file page_name
    file_name = File.basename(page_name).gsub('.', '_')

    File.join @path, File.dirname(page_name), "page-#{file_name}.ri"
  end

  ##
  # Removes from +all_hash+ the contexts that are nodoc or have no content.
  #
  # See RDoc::Context#remove_from_documentation?

  def remove_nodoc all_hash
    all_hash.keys.each do |name|
      context = all_hash[name]
      all_hash.delete(name) if context.remove_from_documentation?
    end
  end

  ##
  # Saves all entries in the store

  def save
    load_cache

    all_classes_and_modules.each do |klass|
      save_class klass

      klass.each_method do |method|
        save_method klass, method
      end

      klass.each_attribute do |attribute|
        save_method klass, attribute
      end
    end

    all_files.each do |file|
      save_page file
    end

    save_cache
  end

  ##
  # Writes the cache file for this store

  def save_cache
    clean_cache_collection @cache[:ancestors]
    clean_cache_collection @cache[:attributes]
    clean_cache_collection @cache[:class_methods]
    clean_cache_collection @cache[:instance_methods]

    @cache[:modules].uniq!
    @cache[:modules].sort!

    @cache[:pages].uniq!
    @cache[:pages].sort!

    @cache[:encoding] = @encoding # this gets set twice due to assert_cache

    @cache[:c_class_variables].merge!           @c_class_variables
    @cache[:c_singleton_class_variables].merge! @c_singleton_class_variables

    return if @dry_run

    File.open cache_path, 'wb' do |io|
      Marshal.dump @cache, io
    end
  end

  ##
  # Writes the ri data for +klass+ (or module)

  def save_class klass
    full_name = klass.full_name

    FileUtils.mkdir_p class_path(full_name) unless @dry_run

    @cache[:modules] << full_name

    path = class_file full_name

    begin
      disk_klass = load_class full_name

      klass = disk_klass.merge klass
    rescue MissingFileError
    end

    # BasicObject has no ancestors
    ancestors = klass.direct_ancestors.compact.map do |ancestor|
      # HACK for classes we don't know about (class X < RuntimeError)
      String === ancestor ? ancestor : ancestor.full_name
    end

    @cache[:ancestors][full_name] ||= []
    @cache[:ancestors][full_name].concat ancestors

    attribute_definitions = klass.attributes.map do |attribute|
      "#{attribute.definition} #{attribute.name}"
    end

    unless attribute_definitions.empty? then
      @cache[:attributes][full_name] ||= []
      @cache[:attributes][full_name].concat attribute_definitions
    end

    to_delete = []

    unless klass.method_list.empty? then
      @cache[:class_methods][full_name]    ||= []
      @cache[:instance_methods][full_name] ||= []

      class_methods, instance_methods =
        klass.method_list.partition { |meth| meth.singleton }

      class_methods    = class_methods.   map { |method| method.name }
      instance_methods = instance_methods.map { |method| method.name }
      attribute_names  = klass.attributes.map { |attr|   attr.name }

      old = @cache[:class_methods][full_name] - class_methods
      to_delete.concat old.map { |method|
        method_file full_name, "#{full_name}::#{method}"
      }

      old = @cache[:instance_methods][full_name] -
        instance_methods - attribute_names
      to_delete.concat old.map { |method|
        method_file full_name, "#{full_name}##{method}"
      }

      @cache[:class_methods][full_name]    = class_methods
      @cache[:instance_methods][full_name] = instance_methods
    end

    return if @dry_run

    FileUtils.rm_f to_delete

    File.open path, 'wb' do |io|
      Marshal.dump klass, io
    end
  end

  ##
  # Writes the ri data for +method+ on +klass+

  def save_method klass, method
    full_name = klass.full_name

    FileUtils.mkdir_p class_path(full_name) unless @dry_run

    cache = if method.singleton then
              @cache[:class_methods]
            else
              @cache[:instance_methods]
            end
    cache[full_name] ||= []
    cache[full_name] << method.name

    return if @dry_run

    File.open method_file(full_name, method.full_name), 'wb' do |io|
      Marshal.dump method, io
    end
  end

  ##
  # Writes the ri data for +page+

  def save_page page
    return unless page.text?

    path = page_file page.full_name

    FileUtils.mkdir_p File.dirname(path) unless @dry_run

    cache[:pages] ||= []
    cache[:pages] << page.full_name

    return if @dry_run

    File.open path, 'wb' do |io|
      Marshal.dump page, io
    end
  end

  ##
  # Source of the contents of this store.
  #
  # For a store from a gem the source is the gem name.  For a store from the
  # home directory the source is "home".  For system ri store (the standard
  # library documentation) the source is"ruby".  For a store from the site
  # ri directory the store is "site".  For other stores the source is the
  # #path.

  def source
    case type
    when :gem    then File.basename File.expand_path '..', @path
    when :home   then 'home'
    when :site   then 'site'
    when :system then 'ruby'
    else @path
    end
  end

  ##
  # Gets the title for this RDoc store.  This is used as the title in each
  # page on the RDoc server

  def title
    @cache[:title]
  end

  ##
  # Sets the title page for this RDoc store.

  def title= title
    @cache[:title] = title
  end

  ##
  # Returns the unique classes discovered by RDoc.
  #
  # ::complete must have been called prior to using this method.

  def unique_classes
    @unique_classes
  end

  ##
  # Returns the unique classes and modules discovered by RDoc.
  # ::complete must have been called prior to using this method.

  def unique_classes_and_modules
    @unique_classes + @unique_modules
  end

  ##
  # Returns the unique modules discovered by RDoc.
  # ::complete must have been called prior to using this method.

  def unique_modules
    @unique_modules
  end

  private
  def marshal_load(file)
    File.open(file, 'rb') {|io| Marshal.load(io, MarshalFilter)}
  end

  MarshalFilter = proc do |obj|
    case obj
    when true, false, nil, Array, Class, Encoding, Hash, Integer, String, Symbol, RDoc::Text
    else
      unless obj.class.name.start_with?("RDoc::")
        raise TypeError, "not permitted class: #{obj.class.name}"
      end
    end
    obj
  end
  private_constant :MarshalFilter

end
# coding: UTF-8
# frozen_string_literal: true
# :markup: markdown

##
# RDoc::Markdown as described by the [markdown syntax][syntax].
#
# To choose Markdown as your only default format see
# RDoc::Options@Saved+Options for instructions on setting up a `.doc_options`
# file to store your project default.
#
# ## Usage
#
# Here is a brief example of using this parse to read a markdown file by hand.
#
#     data = File.read("README.md")
#     formatter = RDoc::Markup::ToHtml.new(RDoc::Options.new, nil)
#     html = RDoc::Markdown.parse(data).accept(formatter)
#
#     # do something with html
#
# ## Extensions
#
# The following markdown extensions are supported by the parser, but not all
# are used in RDoc output by default.
#
# ### RDoc
#
# The RDoc Markdown parser has the following built-in behaviors that cannot be
# disabled.
#
# Underscores embedded in words are never interpreted as emphasis.  (While the
# [markdown dingus][dingus] emphasizes in-word underscores, neither the
# Markdown syntax nor MarkdownTest mention this behavior.)
#
# For HTML output, RDoc always auto-links bare URLs.
#
# ### Break on Newline
#
# The break_on_newline extension converts all newlines into hard line breaks
# as in [Github Flavored Markdown][GFM].  This extension is disabled by
# default.
#
# ### CSS
#
# The #css extension enables CSS blocks to be included in the output, but they
# are not used for any built-in RDoc output format.  This extension is disabled
# by default.
#
# Example:
#
#     <style type="text/css">
#     h1 { font-size: 3em }
#     </style>
#
# ### Definition Lists
#
# The definition_lists extension allows definition lists using the [PHP
# Markdown Extra syntax][PHPE], but only one label and definition are supported
# at this time.  This extension is enabled by default.
#
# Example:
#
# ```
# cat
# :   A small furry mammal
# that seems to sleep a lot
#
# ant
# :   A little insect that is known
# to enjoy picnics
#
# ```
#
# Produces:
#
# cat
# :   A small furry mammal
# that seems to sleep a lot
#
# ant
# :   A little insect that is known
# to enjoy picnics
#
# ### Strike
#
# Example:
#
# ```
# This is ~~striked~~.
# ```
#
# Produces:
#
# This is ~~striked~~.
#
# ### Github
#
# The #github extension enables a partial set of [Github Flavored Markdown]
# [GFM].  This extension is enabled by default.
#
# Supported github extensions include:
#
# #### Fenced code blocks
#
# Use ` ``` ` around a block of code instead of indenting it four spaces.
#
# #### Syntax highlighting
#
# Use ` ``` ruby ` as the start of a code fence to add syntax highlighting.
# (Currently only `ruby` syntax is supported).
#
# ### HTML
#
# Enables raw HTML to be included in the output.  This extension is enabled by
# default.
#
# Example:
#
#     <table>
#     ...
#     </table>
#
# ### Notes
#
# The #notes extension enables footnote support.  This extension is enabled by
# default.
#
# Example:
#
#     Here is some text[^1] including an inline footnote ^[for short footnotes]
#
#     ...
#
#     [^1]: With the footnote text down at the bottom
#
# Produces:
#
# Here is some text[^1] including an inline footnote ^[for short footnotes]
#
# [^1]: With the footnote text down at the bottom
#
# ## Limitations
#
# * Link titles are not used
# * Footnotes are collapsed into a single paragraph
#
# ## Author
#
# This markdown parser is a port to kpeg from [peg-markdown][pegmarkdown] by
# John MacFarlane.
#
# It is used under the MIT license:
#
# 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.
#
# The port to kpeg was performed by Eric Hodel and Evan Phoenix
#
# [dingus]: http://daringfireball.net/projects/markdown/dingus
# [GFM]: https://github.github.com/gfm/
# [pegmarkdown]: https://github.com/jgm/peg-markdown
# [PHPE]: http://michelf.com/projects/php-markdown/extra/#def-list
# [syntax]: http://daringfireball.net/projects/markdown/syntax
#--
# Last updated to jgm/peg-markdown commit 8f8fc22ef0
class RDoc::Markdown
  # :stopdoc:

    # This is distinct from setup_parser so that a standalone parser
    # can redefine #initialize and still have access to the proper
    # parser setup code.
    def initialize(str, debug=false)
      setup_parser(str, debug)
    end



    # Prepares for parsing +str+.  If you define a custom initialize you must
    # call this method before #parse
    def setup_parser(str, debug=false)
      set_string str, 0
      @memoizations = Hash.new { |h,k| h[k] = {} }
      @result = nil
      @failed_rule = nil
      @failing_rule_offset = -1

      setup_foreign_grammar
    end

    attr_reader :string
    attr_reader :failing_rule_offset
    attr_accessor :result, :pos

    def current_column(target=pos)
      if c = string.rindex("\n", target-1)
        return target - c - 1
      end

      target + 1
    end

    def current_line(target=pos)
      cur_offset = 0
      cur_line = 0

      string.each_line do |line|
        cur_line += 1
        cur_offset += line.size
        return cur_line if cur_offset >= target
      end

      -1
    end

    def lines
      lines = []
      string.each_line { |l| lines << l }
      lines
    end



    def get_text(start)
      @string[start..@pos-1]
    end

    # Sets the string and current parsing position for the parser.
    def set_string string, pos
      @string = string
      @string_size = string ? string.size : 0
      @pos = pos
    end

    def show_pos
      width = 10
      if @pos < width
        "#{@pos} (\"#{@string[0,@pos]}\" @ \"#{@string[@pos,width]}\")"
      else
        "#{@pos} (\"... #{@string[@pos - width, width]}\" @ \"#{@string[@pos,width]}\")"
      end
    end

    def failure_info
      l = current_line @failing_rule_offset
      c = current_column @failing_rule_offset

      if @failed_rule.kind_of? Symbol
        info = self.class::Rules[@failed_rule]
        "line #{l}, column #{c}: failed rule '#{info.name}' = '#{info.rendered}'"
      else
        "line #{l}, column #{c}: failed rule '#{@failed_rule}'"
      end
    end

    def failure_caret
      l = current_line @failing_rule_offset
      c = current_column @failing_rule_offset

      line = lines[l-1]
      "#{line}\n#{' ' * (c - 1)}^"
    end

    def failure_character
      l = current_line @failing_rule_offset
      c = current_column @failing_rule_offset
      lines[l-1][c-1, 1]
    end

    def failure_oneline
      l = current_line @failing_rule_offset
      c = current_column @failing_rule_offset

      char = lines[l-1][c-1, 1]

      if @failed_rule.kind_of? Symbol
        info = self.class::Rules[@failed_rule]
        "@#{l}:#{c} failed rule '#{info.name}', got '#{char}'"
      else
        "@#{l}:#{c} failed rule '#{@failed_rule}', got '#{char}'"
      end
    end

    class ParseError < RuntimeError
    end

    def raise_error
      raise ParseError, failure_oneline
    end

    def show_error(io=STDOUT)
      error_pos = @failing_rule_offset
      line_no = current_line(error_pos)
      col_no = current_column(error_pos)

      io.puts "On line #{line_no}, column #{col_no}:"

      if @failed_rule.kind_of? Symbol
        info = self.class::Rules[@failed_rule]
        io.puts "Failed to match '#{info.rendered}' (rule '#{info.name}')"
      else
        io.puts "Failed to match rule '#{@failed_rule}'"
      end

      io.puts "Got: #{string[error_pos,1].inspect}"
      line = lines[line_no-1]
      io.puts "=> #{line}"
      io.print(" " * (col_no + 3))
      io.puts "^"
    end

    def set_failed_rule(name)
      if @pos > @failing_rule_offset
        @failed_rule = name
        @failing_rule_offset = @pos
      end
    end

    attr_reader :failed_rule

    def match_string(str)
      len = str.size
      if @string[pos,len] == str
        @pos += len
        return str
      end

      return nil
    end

    def scan(reg)
      if m = reg.match(@string, @pos)
        @pos = m.end(0)
        return true
      end

      return nil
    end

    if "".respond_to? :ord
      def get_byte
        if @pos >= @string_size
          return nil
        end

        s = @string[@pos].ord
        @pos += 1
        s
      end
    else
      def get_byte
        if @pos >= @string_size
          return nil
        end

        s = @string[@pos]
        @pos += 1
        s
      end
    end

    def parse(rule=nil)
      # We invoke the rules indirectly via apply
      # instead of by just calling them as methods because
      # if the rules use left recursion, apply needs to
      # manage that.

      if !rule
        apply(:_root)
      else
        method = rule.gsub("-","_hyphen_")
        apply :"_#{method}"
      end
    end

    class MemoEntry
      def initialize(ans, pos)
        @ans = ans
        @pos = pos
        @result = nil
        @set = false
        @left_rec = false
      end

      attr_reader :ans, :pos, :result, :set
      attr_accessor :left_rec

      def move!(ans, pos, result)
        @ans = ans
        @pos = pos
        @result = result
        @set = true
        @left_rec = false
      end
    end

    def external_invoke(other, rule, *args)
      old_pos = @pos
      old_string = @string

      set_string other.string, other.pos

      begin
        if val = __send__(rule, *args)
          other.pos = @pos
          other.result = @result
        else
          other.set_failed_rule "#{self.class}##{rule}"
        end
        val
      ensure
        set_string old_string, old_pos
      end
    end

    def apply_with_args(rule, *args)
      memo_key = [rule, args]
      if m = @memoizations[memo_key][@pos]
        @pos = m.pos
        if !m.set
          m.left_rec = true
          return nil
        end

        @result = m.result

        return m.ans
      else
        m = MemoEntry.new(nil, @pos)
        @memoizations[memo_key][@pos] = m
        start_pos = @pos

        ans = __send__ rule, *args

        lr = m.left_rec

        m.move! ans, @pos, @result

        # Don't bother trying to grow the left recursion
        # if it's failing straight away (thus there is no seed)
        if ans and lr
          return grow_lr(rule, args, start_pos, m)
        else
          return ans
        end
      end
    end

    def apply(rule)
      if m = @memoizations[rule][@pos]
        @pos = m.pos
        if !m.set
          m.left_rec = true
          return nil
        end

        @result = m.result

        return m.ans
      else
        m = MemoEntry.new(nil, @pos)
        @memoizations[rule][@pos] = m
        start_pos = @pos

        ans = __send__ rule

        lr = m.left_rec

        m.move! ans, @pos, @result

        # Don't bother trying to grow the left recursion
        # if it's failing straight away (thus there is no seed)
        if ans and lr
          return grow_lr(rule, nil, start_pos, m)
        else
          return ans
        end
      end
    end

    def grow_lr(rule, args, start_pos, m)
      while true
        @pos = start_pos
        @result = m.result

        if args
          ans = __send__ rule, *args
        else
          ans = __send__ rule
        end
        return nil unless ans

        break if @pos <= m.pos

        m.move! ans, @pos, @result
      end

      @result = m.result
      @pos = m.pos
      return m.ans
    end

    class RuleInfo
      def initialize(name, rendered)
        @name = name
        @rendered = rendered
      end

      attr_reader :name, :rendered
    end

    def self.rule_info(name, rendered)
      RuleInfo.new(name, rendered)
    end


  # :startdoc:



  require 'rdoc'
  require 'rdoc/markup/to_joined_paragraph'
  require 'rdoc/markdown/entities'

  require 'rdoc/markdown/literals'

  ##
  # Supported extensions

  EXTENSIONS = []

  ##
  # Extensions enabled by default

  DEFAULT_EXTENSIONS = [
    :definition_lists,
    :github,
    :html,
    :notes,
    :strike,
  ]

  # :section: Extensions

  ##
  # Creates extension methods for the `name` extension to enable and disable
  # the extension and to query if they are active.

  def self.extension name
    EXTENSIONS << name

    define_method "#{name}?" do
      extension? name
    end

    define_method "#{name}=" do |enable|
      extension name, enable
    end
  end

  ##
  # Converts all newlines into hard breaks

  extension :break_on_newline

  ##
  # Allow style blocks

  extension :css

  ##
  # Allow PHP Markdown Extras style definition lists

  extension :definition_lists

  ##
  # Allow Github Flavored Markdown

  extension :github

  ##
  # Allow HTML

  extension :html

  ##
  # Enables the notes extension

  extension :notes

  ##
  # Enables the strike extension

  extension :strike

  # :section:

  ##
  # Parses the `markdown` document into an RDoc::Document using the default
  # extensions.

  def self.parse markdown
    parser = new

    parser.parse markdown
  end

  # TODO remove when kpeg 0.10 is released
  alias orig_initialize initialize # :nodoc:

  ##
  # Creates a new markdown parser that enables the given +extensions+.

  def initialize extensions = DEFAULT_EXTENSIONS, debug = false
    @debug      = debug
    @formatter  = RDoc::Markup::ToJoinedParagraph.new
    @extensions = extensions

    @references          = nil
    @unlinked_references = nil

    @footnotes       = nil
    @note_order      = nil
  end

  ##
  # Wraps `text` in emphasis for rdoc inline formatting

  def emphasis text
    if text =~ /\A[a-z\d.\/]+\z/i then
      "_#{text}_"
    else
      "<em>#{text}</em>"
    end
  end

  ##
  # :category: Extensions
  #
  # Is the extension `name` enabled?

  def extension? name
    @extensions.include? name
  end

  ##
  # :category: Extensions
  #
  # Enables or disables the extension with `name`

  def extension name, enable
    if enable then
      @extensions |= [name]
    else
      @extensions -= [name]
    end
  end

  ##
  # Parses `text` in a clone of this parser.  This is used for handling nested
  # lists the same way as markdown_parser.

  def inner_parse text # :nodoc:
    parser = clone

    parser.setup_parser text, @debug

    parser.peg_parse

    doc = parser.result

    doc.accept @formatter

    doc.parts
  end

  ##
  # Finds a link reference for `label` and creates a new link to it with
  # `content` as the link text.  If `label` was not encountered in the
  # reference-gathering parser pass the label and content are reconstructed
  # with the linking `text` (usually whitespace).

  def link_to content, label = content, text = nil
    raise ParseError, 'enable notes extension' if
      content.start_with? '^' and label.equal? content

    if ref = @references[label] then
      "{#{content}}[#{ref}]"
    elsif label.equal? content then
      "[#{content}]#{text}"
    else
      "[#{content}]#{text}[#{label}]"
    end
  end

  ##
  # Creates an RDoc::Markup::ListItem by parsing the `unparsed` content from
  # the first parsing pass.

  def list_item_from unparsed
    parsed = inner_parse unparsed.join
    RDoc::Markup::ListItem.new nil, *parsed
  end

  ##
  # Stores `label` as a note and fills in previously unknown note references.

  def note label
    #foottext = "rdoc-label:foottext-#{label}:footmark-#{label}"

    #ref.replace foottext if ref = @unlinked_notes.delete(label)

    @notes[label] = foottext

    #"{^1}[rdoc-label:footmark-#{label}:foottext-#{label}] "
  end

  ##
  # Creates a new link for the footnote `reference` and adds the reference to
  # the note order list for proper display at the end of the document.

  def note_for ref
    @note_order << ref

    label = @note_order.length

    "{*#{label}}[rdoc-label:foottext-#{label}:footmark-#{label}]"
  end

  ##
  # The internal kpeg parse method

  alias peg_parse parse # :nodoc:

  ##
  # Creates an RDoc::Markup::Paragraph from `parts` and including
  # extension-specific behavior

  def paragraph parts
    parts = parts.map do |part|
      if "\n" == part then
        RDoc::Markup::HardBreak.new
      else
        part
      end
    end if break_on_newline?

    RDoc::Markup::Paragraph.new(*parts)
  end

  ##
  # Parses `markdown` into an RDoc::Document

  def parse markdown
    @references          = {}
    @unlinked_references = {}

    markdown += "\n\n"

    setup_parser markdown, @debug
    peg_parse 'References'

    if notes? then
      @footnotes       = {}

      setup_parser markdown, @debug
      peg_parse 'Notes'

      # using note_order on the first pass would be a bug
      @note_order      = []
    end

    setup_parser markdown, @debug
    peg_parse

    doc = result

    if notes? and not @footnotes.empty? then
      doc << RDoc::Markup::Rule.new(1)

      @note_order.each_with_index do |ref, index|
        label = index + 1
        note = @footnotes[ref]

        link = "{^#{label}}[rdoc-label:footmark-#{label}:foottext-#{label}] "
        note.parts.unshift link

        doc << note
      end
    end

    doc.accept @formatter

    doc
  end

  ##
  # Stores `label` as a reference to `link` and fills in previously unknown
  # link references.

  def reference label, link
    if ref = @unlinked_references.delete(label) then
      ref.replace link
    end

    @references[label] = link
  end

  ##
  # Wraps `text` in strong markup for rdoc inline formatting

  def strong text
    if text =~ /\A[a-z\d.\/-]+\z/i then
      "*#{text}*"
    else
      "<b>#{text}</b>"
    end
  end

  ##
  # Wraps `text` in strike markup for rdoc inline formatting

  def strike text
    if text =~ /\A[a-z\d.\/-]+\z/i then
      "~#{text}~"
    else
      "<s>#{text}</s>"
    end
  end


  # :stopdoc:
  def setup_foreign_grammar
    @_grammar_literals = RDoc::Markdown::Literals.new(nil)
  end

  # root = Doc
  def _root
    _tmp = apply(:_Doc)
    set_failed_rule :_root unless _tmp
    return _tmp
  end

  # Doc = BOM? Block*:a { RDoc::Markup::Document.new(*a.compact) }
  def _Doc

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = apply(:_BOM)
      unless _tmp
        _tmp = true
        self.pos = _save1
      end
      unless _tmp
        self.pos = _save
        break
      end
      _ary = []
      while true
        _tmp = apply(:_Block)
        _ary << @result if _tmp
        break unless _tmp
      end
      _tmp = true
      @result = _ary
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  RDoc::Markup::Document.new(*a.compact) ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Doc unless _tmp
    return _tmp
  end

  # Block = @BlankLine* (BlockQuote | Verbatim | CodeFence | Table | Note | Reference | HorizontalRule | Heading | OrderedList | BulletList | DefinitionList | HtmlBlock | StyleBlock | Para | Plain)
  def _Block

    _save = self.pos
    while true # sequence
      while true
        _tmp = _BlankLine()
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end

      _save2 = self.pos
      while true # choice
        _tmp = apply(:_BlockQuote)
        break if _tmp
        self.pos = _save2
        _tmp = apply(:_Verbatim)
        break if _tmp
        self.pos = _save2
        _tmp = apply(:_CodeFence)
        break if _tmp
        self.pos = _save2
        _tmp = apply(:_Table)
        break if _tmp
        self.pos = _save2
        _tmp = apply(:_Note)
        break if _tmp
        self.pos = _save2
        _tmp = apply(:_Reference)
        break if _tmp
        self.pos = _save2
        _tmp = apply(:_HorizontalRule)
        break if _tmp
        self.pos = _save2
        _tmp = apply(:_Heading)
        break if _tmp
        self.pos = _save2
        _tmp = apply(:_OrderedList)
        break if _tmp
        self.pos = _save2
        _tmp = apply(:_BulletList)
        break if _tmp
        self.pos = _save2
        _tmp = apply(:_DefinitionList)
        break if _tmp
        self.pos = _save2
        _tmp = apply(:_HtmlBlock)
        break if _tmp
        self.pos = _save2
        _tmp = apply(:_StyleBlock)
        break if _tmp
        self.pos = _save2
        _tmp = apply(:_Para)
        break if _tmp
        self.pos = _save2
        _tmp = apply(:_Plain)
        break if _tmp
        self.pos = _save2
        break
      end # end choice

      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Block unless _tmp
    return _tmp
  end

  # Para = @NonindentSpace Inlines:a @BlankLine+ { paragraph a }
  def _Para

    _save = self.pos
    while true # sequence
      _tmp = _NonindentSpace()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Inlines)
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _tmp = _BlankLine()
      if _tmp
        while true
          _tmp = _BlankLine()
          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save1
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  paragraph a ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Para unless _tmp
    return _tmp
  end

  # Plain = Inlines:a { paragraph a }
  def _Plain

    _save = self.pos
    while true # sequence
      _tmp = apply(:_Inlines)
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  paragraph a ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Plain unless _tmp
    return _tmp
  end

  # AtxInline = !@Newline !(@Sp /#*/ @Sp @Newline) Inline
  def _AtxInline

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = _Newline()
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos

      _save3 = self.pos
      while true # sequence
        _tmp = _Sp()
        unless _tmp
          self.pos = _save3
          break
        end
        _tmp = scan(/\G(?-mix:#*)/)
        unless _tmp
          self.pos = _save3
          break
        end
        _tmp = _Sp()
        unless _tmp
          self.pos = _save3
          break
        end
        _tmp = _Newline()
        unless _tmp
          self.pos = _save3
        end
        break
      end # end sequence

      _tmp = _tmp ? nil : true
      self.pos = _save2
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Inline)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_AtxInline unless _tmp
    return _tmp
  end

  # AtxStart = < /\#{1,6}/ > { text.length }
  def _AtxStart

    _save = self.pos
    while true # sequence
      _text_start = self.pos
      _tmp = scan(/\G(?-mix:\#{1,6})/)
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  text.length ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_AtxStart unless _tmp
    return _tmp
  end

  # AtxHeading = AtxStart:s @Sp AtxInline+:a (@Sp /#*/ @Sp)? @Newline { RDoc::Markup::Heading.new(s, a.join) }
  def _AtxHeading

    _save = self.pos
    while true # sequence
      _tmp = apply(:_AtxStart)
      s = @result
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Sp()
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _ary = []
      _tmp = apply(:_AtxInline)
      if _tmp
        _ary << @result
        while true
          _tmp = apply(:_AtxInline)
          _ary << @result if _tmp
          break unless _tmp
        end
        _tmp = true
        @result = _ary
      else
        self.pos = _save1
      end
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos

      _save3 = self.pos
      while true # sequence
        _tmp = _Sp()
        unless _tmp
          self.pos = _save3
          break
        end
        _tmp = scan(/\G(?-mix:#*)/)
        unless _tmp
          self.pos = _save3
          break
        end
        _tmp = _Sp()
        unless _tmp
          self.pos = _save3
        end
        break
      end # end sequence

      unless _tmp
        _tmp = true
        self.pos = _save2
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Newline()
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  RDoc::Markup::Heading.new(s, a.join) ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_AtxHeading unless _tmp
    return _tmp
  end

  # SetextHeading = (SetextHeading1 | SetextHeading2)
  def _SetextHeading

    _save = self.pos
    while true # choice
      _tmp = apply(:_SetextHeading1)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_SetextHeading2)
      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_SetextHeading unless _tmp
    return _tmp
  end

  # SetextBottom1 = /={1,}/ @Newline
  def _SetextBottom1

    _save = self.pos
    while true # sequence
      _tmp = scan(/\G(?-mix:={1,})/)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Newline()
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_SetextBottom1 unless _tmp
    return _tmp
  end

  # SetextBottom2 = /-{1,}/ @Newline
  def _SetextBottom2

    _save = self.pos
    while true # sequence
      _tmp = scan(/\G(?-mix:-{1,})/)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Newline()
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_SetextBottom2 unless _tmp
    return _tmp
  end

  # SetextHeading1 = &(@RawLine SetextBottom1) @StartList:a (!@Endline Inline:b { a << b })+ @Sp @Newline SetextBottom1 { RDoc::Markup::Heading.new(1, a.join) }
  def _SetextHeading1

    _save = self.pos
    while true # sequence
      _save1 = self.pos

      _save2 = self.pos
      while true # sequence
        _tmp = _RawLine()
        unless _tmp
          self.pos = _save2
          break
        end
        _tmp = apply(:_SetextBottom1)
        unless _tmp
          self.pos = _save2
        end
        break
      end # end sequence

      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _StartList()
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save3 = self.pos

      _save4 = self.pos
      while true # sequence
        _save5 = self.pos
        _tmp = _Endline()
        _tmp = _tmp ? nil : true
        self.pos = _save5
        unless _tmp
          self.pos = _save4
          break
        end
        _tmp = apply(:_Inline)
        b = @result
        unless _tmp
          self.pos = _save4
          break
        end
        @result = begin;  a << b ; end
        _tmp = true
        unless _tmp
          self.pos = _save4
        end
        break
      end # end sequence

      if _tmp
        while true

          _save6 = self.pos
          while true # sequence
            _save7 = self.pos
            _tmp = _Endline()
            _tmp = _tmp ? nil : true
            self.pos = _save7
            unless _tmp
              self.pos = _save6
              break
            end
            _tmp = apply(:_Inline)
            b = @result
            unless _tmp
              self.pos = _save6
              break
            end
            @result = begin;  a << b ; end
            _tmp = true
            unless _tmp
              self.pos = _save6
            end
            break
          end # end sequence

          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save3
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Sp()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Newline()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_SetextBottom1)
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  RDoc::Markup::Heading.new(1, a.join) ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_SetextHeading1 unless _tmp
    return _tmp
  end

  # SetextHeading2 = &(@RawLine SetextBottom2) @StartList:a (!@Endline Inline:b { a << b })+ @Sp @Newline SetextBottom2 { RDoc::Markup::Heading.new(2, a.join) }
  def _SetextHeading2

    _save = self.pos
    while true # sequence
      _save1 = self.pos

      _save2 = self.pos
      while true # sequence
        _tmp = _RawLine()
        unless _tmp
          self.pos = _save2
          break
        end
        _tmp = apply(:_SetextBottom2)
        unless _tmp
          self.pos = _save2
        end
        break
      end # end sequence

      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _StartList()
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save3 = self.pos

      _save4 = self.pos
      while true # sequence
        _save5 = self.pos
        _tmp = _Endline()
        _tmp = _tmp ? nil : true
        self.pos = _save5
        unless _tmp
          self.pos = _save4
          break
        end
        _tmp = apply(:_Inline)
        b = @result
        unless _tmp
          self.pos = _save4
          break
        end
        @result = begin;  a << b ; end
        _tmp = true
        unless _tmp
          self.pos = _save4
        end
        break
      end # end sequence

      if _tmp
        while true

          _save6 = self.pos
          while true # sequence
            _save7 = self.pos
            _tmp = _Endline()
            _tmp = _tmp ? nil : true
            self.pos = _save7
            unless _tmp
              self.pos = _save6
              break
            end
            _tmp = apply(:_Inline)
            b = @result
            unless _tmp
              self.pos = _save6
              break
            end
            @result = begin;  a << b ; end
            _tmp = true
            unless _tmp
              self.pos = _save6
            end
            break
          end # end sequence

          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save3
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Sp()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Newline()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_SetextBottom2)
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  RDoc::Markup::Heading.new(2, a.join) ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_SetextHeading2 unless _tmp
    return _tmp
  end

  # Heading = (SetextHeading | AtxHeading)
  def _Heading

    _save = self.pos
    while true # choice
      _tmp = apply(:_SetextHeading)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_AtxHeading)
      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_Heading unless _tmp
    return _tmp
  end

  # BlockQuote = BlockQuoteRaw:a { RDoc::Markup::BlockQuote.new(*a) }
  def _BlockQuote

    _save = self.pos
    while true # sequence
      _tmp = apply(:_BlockQuoteRaw)
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  RDoc::Markup::BlockQuote.new(*a) ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_BlockQuote unless _tmp
    return _tmp
  end

  # BlockQuoteRaw = @StartList:a (">" " "? Line:l { a << l } (!">" !@BlankLine Line:c { a << c })* (@BlankLine:n { a << n })*)+ { inner_parse a.join }
  def _BlockQuoteRaw

    _save = self.pos
    while true # sequence
      _tmp = _StartList()
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos

      _save2 = self.pos
      while true # sequence
        _tmp = match_string(">")
        unless _tmp
          self.pos = _save2
          break
        end
        _save3 = self.pos
        _tmp = match_string(" ")
        unless _tmp
          _tmp = true
          self.pos = _save3
        end
        unless _tmp
          self.pos = _save2
          break
        end
        _tmp = apply(:_Line)
        l = @result
        unless _tmp
          self.pos = _save2
          break
        end
        @result = begin;  a << l ; end
        _tmp = true
        unless _tmp
          self.pos = _save2
          break
        end
        while true

          _save5 = self.pos
          while true # sequence
            _save6 = self.pos
            _tmp = match_string(">")
            _tmp = _tmp ? nil : true
            self.pos = _save6
            unless _tmp
              self.pos = _save5
              break
            end
            _save7 = self.pos
            _tmp = _BlankLine()
            _tmp = _tmp ? nil : true
            self.pos = _save7
            unless _tmp
              self.pos = _save5
              break
            end
            _tmp = apply(:_Line)
            c = @result
            unless _tmp
              self.pos = _save5
              break
            end
            @result = begin;  a << c ; end
            _tmp = true
            unless _tmp
              self.pos = _save5
            end
            break
          end # end sequence

          break unless _tmp
        end
        _tmp = true
        unless _tmp
          self.pos = _save2
          break
        end
        while true

          _save9 = self.pos
          while true # sequence
            _tmp = _BlankLine()
            n = @result
            unless _tmp
              self.pos = _save9
              break
            end
            @result = begin;  a << n ; end
            _tmp = true
            unless _tmp
              self.pos = _save9
            end
            break
          end # end sequence

          break unless _tmp
        end
        _tmp = true
        unless _tmp
          self.pos = _save2
        end
        break
      end # end sequence

      if _tmp
        while true

          _save10 = self.pos
          while true # sequence
            _tmp = match_string(">")
            unless _tmp
              self.pos = _save10
              break
            end
            _save11 = self.pos
            _tmp = match_string(" ")
            unless _tmp
              _tmp = true
              self.pos = _save11
            end
            unless _tmp
              self.pos = _save10
              break
            end
            _tmp = apply(:_Line)
            l = @result
            unless _tmp
              self.pos = _save10
              break
            end
            @result = begin;  a << l ; end
            _tmp = true
            unless _tmp
              self.pos = _save10
              break
            end
            while true

              _save13 = self.pos
              while true # sequence
                _save14 = self.pos
                _tmp = match_string(">")
                _tmp = _tmp ? nil : true
                self.pos = _save14
                unless _tmp
                  self.pos = _save13
                  break
                end
                _save15 = self.pos
                _tmp = _BlankLine()
                _tmp = _tmp ? nil : true
                self.pos = _save15
                unless _tmp
                  self.pos = _save13
                  break
                end
                _tmp = apply(:_Line)
                c = @result
                unless _tmp
                  self.pos = _save13
                  break
                end
                @result = begin;  a << c ; end
                _tmp = true
                unless _tmp
                  self.pos = _save13
                end
                break
              end # end sequence

              break unless _tmp
            end
            _tmp = true
            unless _tmp
              self.pos = _save10
              break
            end
            while true

              _save17 = self.pos
              while true # sequence
                _tmp = _BlankLine()
                n = @result
                unless _tmp
                  self.pos = _save17
                  break
                end
                @result = begin;  a << n ; end
                _tmp = true
                unless _tmp
                  self.pos = _save17
                end
                break
              end # end sequence

              break unless _tmp
            end
            _tmp = true
            unless _tmp
              self.pos = _save10
            end
            break
          end # end sequence

          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save1
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  inner_parse a.join ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_BlockQuoteRaw unless _tmp
    return _tmp
  end

  # NonblankIndentedLine = !@BlankLine IndentedLine
  def _NonblankIndentedLine

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = _BlankLine()
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_IndentedLine)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_NonblankIndentedLine unless _tmp
    return _tmp
  end

  # VerbatimChunk = @BlankLine*:a NonblankIndentedLine+:b { a.concat b }
  def _VerbatimChunk

    _save = self.pos
    while true # sequence
      _ary = []
      while true
        _tmp = _BlankLine()
        _ary << @result if _tmp
        break unless _tmp
      end
      _tmp = true
      @result = _ary
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos
      _ary = []
      _tmp = apply(:_NonblankIndentedLine)
      if _tmp
        _ary << @result
        while true
          _tmp = apply(:_NonblankIndentedLine)
          _ary << @result if _tmp
          break unless _tmp
        end
        _tmp = true
        @result = _ary
      else
        self.pos = _save2
      end
      b = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  a.concat b ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_VerbatimChunk unless _tmp
    return _tmp
  end

  # Verbatim = VerbatimChunk+:a { RDoc::Markup::Verbatim.new(*a.flatten) }
  def _Verbatim

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _ary = []
      _tmp = apply(:_VerbatimChunk)
      if _tmp
        _ary << @result
        while true
          _tmp = apply(:_VerbatimChunk)
          _ary << @result if _tmp
          break unless _tmp
        end
        _tmp = true
        @result = _ary
      else
        self.pos = _save1
      end
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  RDoc::Markup::Verbatim.new(*a.flatten) ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Verbatim unless _tmp
    return _tmp
  end

  # HorizontalRule = @NonindentSpace ("*" @Sp "*" @Sp "*" (@Sp "*")* | "-" @Sp "-" @Sp "-" (@Sp "-")* | "_" @Sp "_" @Sp "_" (@Sp "_")*) @Sp @Newline @BlankLine+ { RDoc::Markup::Rule.new 1 }
  def _HorizontalRule

    _save = self.pos
    while true # sequence
      _tmp = _NonindentSpace()
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice

        _save2 = self.pos
        while true # sequence
          _tmp = match_string("*")
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = _Sp()
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = match_string("*")
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = _Sp()
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = match_string("*")
          unless _tmp
            self.pos = _save2
            break
          end
          while true

            _save4 = self.pos
            while true # sequence
              _tmp = _Sp()
              unless _tmp
                self.pos = _save4
                break
              end
              _tmp = match_string("*")
              unless _tmp
                self.pos = _save4
              end
              break
            end # end sequence

            break unless _tmp
          end
          _tmp = true
          unless _tmp
            self.pos = _save2
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save1

        _save5 = self.pos
        while true # sequence
          _tmp = match_string("-")
          unless _tmp
            self.pos = _save5
            break
          end
          _tmp = _Sp()
          unless _tmp
            self.pos = _save5
            break
          end
          _tmp = match_string("-")
          unless _tmp
            self.pos = _save5
            break
          end
          _tmp = _Sp()
          unless _tmp
            self.pos = _save5
            break
          end
          _tmp = match_string("-")
          unless _tmp
            self.pos = _save5
            break
          end
          while true

            _save7 = self.pos
            while true # sequence
              _tmp = _Sp()
              unless _tmp
                self.pos = _save7
                break
              end
              _tmp = match_string("-")
              unless _tmp
                self.pos = _save7
              end
              break
            end # end sequence

            break unless _tmp
          end
          _tmp = true
          unless _tmp
            self.pos = _save5
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save1

        _save8 = self.pos
        while true # sequence
          _tmp = match_string("_")
          unless _tmp
            self.pos = _save8
            break
          end
          _tmp = _Sp()
          unless _tmp
            self.pos = _save8
            break
          end
          _tmp = match_string("_")
          unless _tmp
            self.pos = _save8
            break
          end
          _tmp = _Sp()
          unless _tmp
            self.pos = _save8
            break
          end
          _tmp = match_string("_")
          unless _tmp
            self.pos = _save8
            break
          end
          while true

            _save10 = self.pos
            while true # sequence
              _tmp = _Sp()
              unless _tmp
                self.pos = _save10
                break
              end
              _tmp = match_string("_")
              unless _tmp
                self.pos = _save10
              end
              break
            end # end sequence

            break unless _tmp
          end
          _tmp = true
          unless _tmp
            self.pos = _save8
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Sp()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Newline()
      unless _tmp
        self.pos = _save
        break
      end
      _save11 = self.pos
      _tmp = _BlankLine()
      if _tmp
        while true
          _tmp = _BlankLine()
          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save11
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  RDoc::Markup::Rule.new 1 ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HorizontalRule unless _tmp
    return _tmp
  end

  # Bullet = !HorizontalRule @NonindentSpace /[+*-]/ @Spacechar+
  def _Bullet

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = apply(:_HorizontalRule)
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _NonindentSpace()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = scan(/\G(?-mix:[+*-])/)
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos
      _tmp = _Spacechar()
      if _tmp
        while true
          _tmp = _Spacechar()
          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save2
      end
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Bullet unless _tmp
    return _tmp
  end

  # BulletList = &Bullet (ListTight | ListLoose):a { RDoc::Markup::List.new(:BULLET, *a) }
  def _BulletList

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = apply(:_Bullet)
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end

      _save2 = self.pos
      while true # choice
        _tmp = apply(:_ListTight)
        break if _tmp
        self.pos = _save2
        _tmp = apply(:_ListLoose)
        break if _tmp
        self.pos = _save2
        break
      end # end choice

      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  RDoc::Markup::List.new(:BULLET, *a) ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_BulletList unless _tmp
    return _tmp
  end

  # ListTight = ListItemTight+:a @BlankLine* !(Bullet | Enumerator) { a }
  def _ListTight

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _ary = []
      _tmp = apply(:_ListItemTight)
      if _tmp
        _ary << @result
        while true
          _tmp = apply(:_ListItemTight)
          _ary << @result if _tmp
          break unless _tmp
        end
        _tmp = true
        @result = _ary
      else
        self.pos = _save1
      end
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = _BlankLine()
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _save3 = self.pos

      _save4 = self.pos
      while true # choice
        _tmp = apply(:_Bullet)
        break if _tmp
        self.pos = _save4
        _tmp = apply(:_Enumerator)
        break if _tmp
        self.pos = _save4
        break
      end # end choice

      _tmp = _tmp ? nil : true
      self.pos = _save3
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  a ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_ListTight unless _tmp
    return _tmp
  end

  # ListLoose = @StartList:a (ListItem:b @BlankLine* { a << b })+ { a }
  def _ListLoose

    _save = self.pos
    while true # sequence
      _tmp = _StartList()
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos

      _save2 = self.pos
      while true # sequence
        _tmp = apply(:_ListItem)
        b = @result
        unless _tmp
          self.pos = _save2
          break
        end
        while true
          _tmp = _BlankLine()
          break unless _tmp
        end
        _tmp = true
        unless _tmp
          self.pos = _save2
          break
        end
        @result = begin;  a << b ; end
        _tmp = true
        unless _tmp
          self.pos = _save2
        end
        break
      end # end sequence

      if _tmp
        while true

          _save4 = self.pos
          while true # sequence
            _tmp = apply(:_ListItem)
            b = @result
            unless _tmp
              self.pos = _save4
              break
            end
            while true
              _tmp = _BlankLine()
              break unless _tmp
            end
            _tmp = true
            unless _tmp
              self.pos = _save4
              break
            end
            @result = begin;  a << b ; end
            _tmp = true
            unless _tmp
              self.pos = _save4
            end
            break
          end # end sequence

          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save1
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  a ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_ListLoose unless _tmp
    return _tmp
  end

  # ListItem = (Bullet | Enumerator) @StartList:a ListBlock:b { a << b } (ListContinuationBlock:c { a.push(*c) })* { list_item_from a }
  def _ListItem

    _save = self.pos
    while true # sequence

      _save1 = self.pos
      while true # choice
        _tmp = apply(:_Bullet)
        break if _tmp
        self.pos = _save1
        _tmp = apply(:_Enumerator)
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _StartList()
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_ListBlock)
      b = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  a << b ; end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save3 = self.pos
        while true # sequence
          _tmp = apply(:_ListContinuationBlock)
          c = @result
          unless _tmp
            self.pos = _save3
            break
          end
          @result = begin;  a.push(*c) ; end
          _tmp = true
          unless _tmp
            self.pos = _save3
          end
          break
        end # end sequence

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  list_item_from a ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_ListItem unless _tmp
    return _tmp
  end

  # ListItemTight = (Bullet | Enumerator) ListBlock:a (!@BlankLine ListContinuationBlock:b { a.push(*b) })* !ListContinuationBlock { list_item_from a }
  def _ListItemTight

    _save = self.pos
    while true # sequence

      _save1 = self.pos
      while true # choice
        _tmp = apply(:_Bullet)
        break if _tmp
        self.pos = _save1
        _tmp = apply(:_Enumerator)
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_ListBlock)
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save3 = self.pos
        while true # sequence
          _save4 = self.pos
          _tmp = _BlankLine()
          _tmp = _tmp ? nil : true
          self.pos = _save4
          unless _tmp
            self.pos = _save3
            break
          end
          _tmp = apply(:_ListContinuationBlock)
          b = @result
          unless _tmp
            self.pos = _save3
            break
          end
          @result = begin;  a.push(*b) ; end
          _tmp = true
          unless _tmp
            self.pos = _save3
          end
          break
        end # end sequence

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _save5 = self.pos
      _tmp = apply(:_ListContinuationBlock)
      _tmp = _tmp ? nil : true
      self.pos = _save5
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  list_item_from a ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_ListItemTight unless _tmp
    return _tmp
  end

  # ListBlock = !@BlankLine Line:a ListBlockLine*:c { [a, *c] }
  def _ListBlock

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = _BlankLine()
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Line)
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _ary = []
      while true
        _tmp = apply(:_ListBlockLine)
        _ary << @result if _tmp
        break unless _tmp
      end
      _tmp = true
      @result = _ary
      c = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  [a, *c] ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_ListBlock unless _tmp
    return _tmp
  end

  # ListContinuationBlock = @StartList:a @BlankLine* { a << "\n" } (Indent ListBlock:b { a.concat b })+ { a }
  def _ListContinuationBlock

    _save = self.pos
    while true # sequence
      _tmp = _StartList()
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = _BlankLine()
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  a << "\n" ; end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos

      _save3 = self.pos
      while true # sequence
        _tmp = apply(:_Indent)
        unless _tmp
          self.pos = _save3
          break
        end
        _tmp = apply(:_ListBlock)
        b = @result
        unless _tmp
          self.pos = _save3
          break
        end
        @result = begin;  a.concat b ; end
        _tmp = true
        unless _tmp
          self.pos = _save3
        end
        break
      end # end sequence

      if _tmp
        while true

          _save4 = self.pos
          while true # sequence
            _tmp = apply(:_Indent)
            unless _tmp
              self.pos = _save4
              break
            end
            _tmp = apply(:_ListBlock)
            b = @result
            unless _tmp
              self.pos = _save4
              break
            end
            @result = begin;  a.concat b ; end
            _tmp = true
            unless _tmp
              self.pos = _save4
            end
            break
          end # end sequence

          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save2
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  a ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_ListContinuationBlock unless _tmp
    return _tmp
  end

  # Enumerator = @NonindentSpace [0-9]+ "." @Spacechar+
  def _Enumerator

    _save = self.pos
    while true # sequence
      _tmp = _NonindentSpace()
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _save2 = self.pos
      _tmp = get_byte
      if _tmp
        unless _tmp >= 48 and _tmp <= 57
          self.pos = _save2
          _tmp = nil
        end
      end
      if _tmp
        while true
          _save3 = self.pos
          _tmp = get_byte
          if _tmp
            unless _tmp >= 48 and _tmp <= 57
              self.pos = _save3
              _tmp = nil
            end
          end
          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save1
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(".")
      unless _tmp
        self.pos = _save
        break
      end
      _save4 = self.pos
      _tmp = _Spacechar()
      if _tmp
        while true
          _tmp = _Spacechar()
          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save4
      end
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Enumerator unless _tmp
    return _tmp
  end

  # OrderedList = &Enumerator (ListTight | ListLoose):a { RDoc::Markup::List.new(:NUMBER, *a) }
  def _OrderedList

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = apply(:_Enumerator)
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end

      _save2 = self.pos
      while true # choice
        _tmp = apply(:_ListTight)
        break if _tmp
        self.pos = _save2
        _tmp = apply(:_ListLoose)
        break if _tmp
        self.pos = _save2
        break
      end # end choice

      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  RDoc::Markup::List.new(:NUMBER, *a) ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_OrderedList unless _tmp
    return _tmp
  end

  # ListBlockLine = !@BlankLine !(Indent? (Bullet | Enumerator)) !HorizontalRule OptionallyIndentedLine
  def _ListBlockLine

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = _BlankLine()
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos

      _save3 = self.pos
      while true # sequence
        _save4 = self.pos
        _tmp = apply(:_Indent)
        unless _tmp
          _tmp = true
          self.pos = _save4
        end
        unless _tmp
          self.pos = _save3
          break
        end

        _save5 = self.pos
        while true # choice
          _tmp = apply(:_Bullet)
          break if _tmp
          self.pos = _save5
          _tmp = apply(:_Enumerator)
          break if _tmp
          self.pos = _save5
          break
        end # end choice

        unless _tmp
          self.pos = _save3
        end
        break
      end # end sequence

      _tmp = _tmp ? nil : true
      self.pos = _save2
      unless _tmp
        self.pos = _save
        break
      end
      _save6 = self.pos
      _tmp = apply(:_HorizontalRule)
      _tmp = _tmp ? nil : true
      self.pos = _save6
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_OptionallyIndentedLine)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_ListBlockLine unless _tmp
    return _tmp
  end

  # HtmlOpenAnchor = "<" Spnl ("a" | "A") Spnl HtmlAttribute* ">"
  def _HtmlOpenAnchor

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("a")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("A")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlOpenAnchor unless _tmp
    return _tmp
  end

  # HtmlCloseAnchor = "<" Spnl "/" ("a" | "A") Spnl ">"
  def _HtmlCloseAnchor

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("a")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("A")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlCloseAnchor unless _tmp
    return _tmp
  end

  # HtmlAnchor = HtmlOpenAnchor (HtmlAnchor | !HtmlCloseAnchor .)* HtmlCloseAnchor
  def _HtmlAnchor

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlOpenAnchor)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlAnchor)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlCloseAnchor)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlCloseAnchor)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlAnchor unless _tmp
    return _tmp
  end

  # HtmlBlockOpenAddress = "<" Spnl ("address" | "ADDRESS") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenAddress

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("address")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("ADDRESS")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenAddress unless _tmp
    return _tmp
  end

  # HtmlBlockCloseAddress = "<" Spnl "/" ("address" | "ADDRESS") Spnl ">"
  def _HtmlBlockCloseAddress

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("address")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("ADDRESS")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseAddress unless _tmp
    return _tmp
  end

  # HtmlBlockAddress = HtmlBlockOpenAddress (HtmlBlockAddress | !HtmlBlockCloseAddress .)* HtmlBlockCloseAddress
  def _HtmlBlockAddress

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenAddress)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockAddress)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseAddress)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseAddress)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockAddress unless _tmp
    return _tmp
  end

  # HtmlBlockOpenBlockquote = "<" Spnl ("blockquote" | "BLOCKQUOTE") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenBlockquote

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("blockquote")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("BLOCKQUOTE")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenBlockquote unless _tmp
    return _tmp
  end

  # HtmlBlockCloseBlockquote = "<" Spnl "/" ("blockquote" | "BLOCKQUOTE") Spnl ">"
  def _HtmlBlockCloseBlockquote

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("blockquote")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("BLOCKQUOTE")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseBlockquote unless _tmp
    return _tmp
  end

  # HtmlBlockBlockquote = HtmlBlockOpenBlockquote (HtmlBlockBlockquote | !HtmlBlockCloseBlockquote .)* HtmlBlockCloseBlockquote
  def _HtmlBlockBlockquote

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenBlockquote)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockBlockquote)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseBlockquote)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseBlockquote)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockBlockquote unless _tmp
    return _tmp
  end

  # HtmlBlockOpenCenter = "<" Spnl ("center" | "CENTER") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenCenter

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("center")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("CENTER")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenCenter unless _tmp
    return _tmp
  end

  # HtmlBlockCloseCenter = "<" Spnl "/" ("center" | "CENTER") Spnl ">"
  def _HtmlBlockCloseCenter

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("center")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("CENTER")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseCenter unless _tmp
    return _tmp
  end

  # HtmlBlockCenter = HtmlBlockOpenCenter (HtmlBlockCenter | !HtmlBlockCloseCenter .)* HtmlBlockCloseCenter
  def _HtmlBlockCenter

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenCenter)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockCenter)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseCenter)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseCenter)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCenter unless _tmp
    return _tmp
  end

  # HtmlBlockOpenDir = "<" Spnl ("dir" | "DIR") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenDir

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("dir")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("DIR")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenDir unless _tmp
    return _tmp
  end

  # HtmlBlockCloseDir = "<" Spnl "/" ("dir" | "DIR") Spnl ">"
  def _HtmlBlockCloseDir

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("dir")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("DIR")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseDir unless _tmp
    return _tmp
  end

  # HtmlBlockDir = HtmlBlockOpenDir (HtmlBlockDir | !HtmlBlockCloseDir .)* HtmlBlockCloseDir
  def _HtmlBlockDir

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenDir)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockDir)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseDir)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseDir)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockDir unless _tmp
    return _tmp
  end

  # HtmlBlockOpenDiv = "<" Spnl ("div" | "DIV") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenDiv

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("div")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("DIV")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenDiv unless _tmp
    return _tmp
  end

  # HtmlBlockCloseDiv = "<" Spnl "/" ("div" | "DIV") Spnl ">"
  def _HtmlBlockCloseDiv

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("div")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("DIV")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseDiv unless _tmp
    return _tmp
  end

  # HtmlBlockDiv = HtmlBlockOpenDiv (HtmlBlockDiv | !HtmlBlockCloseDiv .)* HtmlBlockCloseDiv
  def _HtmlBlockDiv

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenDiv)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockDiv)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseDiv)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseDiv)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockDiv unless _tmp
    return _tmp
  end

  # HtmlBlockOpenDl = "<" Spnl ("dl" | "DL") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenDl

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("dl")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("DL")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenDl unless _tmp
    return _tmp
  end

  # HtmlBlockCloseDl = "<" Spnl "/" ("dl" | "DL") Spnl ">"
  def _HtmlBlockCloseDl

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("dl")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("DL")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseDl unless _tmp
    return _tmp
  end

  # HtmlBlockDl = HtmlBlockOpenDl (HtmlBlockDl | !HtmlBlockCloseDl .)* HtmlBlockCloseDl
  def _HtmlBlockDl

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenDl)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockDl)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseDl)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseDl)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockDl unless _tmp
    return _tmp
  end

  # HtmlBlockOpenFieldset = "<" Spnl ("fieldset" | "FIELDSET") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenFieldset

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("fieldset")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("FIELDSET")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenFieldset unless _tmp
    return _tmp
  end

  # HtmlBlockCloseFieldset = "<" Spnl "/" ("fieldset" | "FIELDSET") Spnl ">"
  def _HtmlBlockCloseFieldset

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("fieldset")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("FIELDSET")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseFieldset unless _tmp
    return _tmp
  end

  # HtmlBlockFieldset = HtmlBlockOpenFieldset (HtmlBlockFieldset | !HtmlBlockCloseFieldset .)* HtmlBlockCloseFieldset
  def _HtmlBlockFieldset

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenFieldset)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockFieldset)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseFieldset)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseFieldset)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockFieldset unless _tmp
    return _tmp
  end

  # HtmlBlockOpenForm = "<" Spnl ("form" | "FORM") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenForm

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("form")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("FORM")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenForm unless _tmp
    return _tmp
  end

  # HtmlBlockCloseForm = "<" Spnl "/" ("form" | "FORM") Spnl ">"
  def _HtmlBlockCloseForm

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("form")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("FORM")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseForm unless _tmp
    return _tmp
  end

  # HtmlBlockForm = HtmlBlockOpenForm (HtmlBlockForm | !HtmlBlockCloseForm .)* HtmlBlockCloseForm
  def _HtmlBlockForm

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenForm)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockForm)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseForm)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseForm)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockForm unless _tmp
    return _tmp
  end

  # HtmlBlockOpenH1 = "<" Spnl ("h1" | "H1") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenH1

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("h1")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("H1")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenH1 unless _tmp
    return _tmp
  end

  # HtmlBlockCloseH1 = "<" Spnl "/" ("h1" | "H1") Spnl ">"
  def _HtmlBlockCloseH1

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("h1")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("H1")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseH1 unless _tmp
    return _tmp
  end

  # HtmlBlockH1 = HtmlBlockOpenH1 (HtmlBlockH1 | !HtmlBlockCloseH1 .)* HtmlBlockCloseH1
  def _HtmlBlockH1

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenH1)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockH1)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseH1)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseH1)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockH1 unless _tmp
    return _tmp
  end

  # HtmlBlockOpenH2 = "<" Spnl ("h2" | "H2") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenH2

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("h2")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("H2")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenH2 unless _tmp
    return _tmp
  end

  # HtmlBlockCloseH2 = "<" Spnl "/" ("h2" | "H2") Spnl ">"
  def _HtmlBlockCloseH2

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("h2")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("H2")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseH2 unless _tmp
    return _tmp
  end

  # HtmlBlockH2 = HtmlBlockOpenH2 (HtmlBlockH2 | !HtmlBlockCloseH2 .)* HtmlBlockCloseH2
  def _HtmlBlockH2

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenH2)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockH2)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseH2)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseH2)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockH2 unless _tmp
    return _tmp
  end

  # HtmlBlockOpenH3 = "<" Spnl ("h3" | "H3") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenH3

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("h3")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("H3")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenH3 unless _tmp
    return _tmp
  end

  # HtmlBlockCloseH3 = "<" Spnl "/" ("h3" | "H3") Spnl ">"
  def _HtmlBlockCloseH3

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("h3")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("H3")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseH3 unless _tmp
    return _tmp
  end

  # HtmlBlockH3 = HtmlBlockOpenH3 (HtmlBlockH3 | !HtmlBlockCloseH3 .)* HtmlBlockCloseH3
  def _HtmlBlockH3

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenH3)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockH3)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseH3)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseH3)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockH3 unless _tmp
    return _tmp
  end

  # HtmlBlockOpenH4 = "<" Spnl ("h4" | "H4") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenH4

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("h4")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("H4")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenH4 unless _tmp
    return _tmp
  end

  # HtmlBlockCloseH4 = "<" Spnl "/" ("h4" | "H4") Spnl ">"
  def _HtmlBlockCloseH4

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("h4")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("H4")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseH4 unless _tmp
    return _tmp
  end

  # HtmlBlockH4 = HtmlBlockOpenH4 (HtmlBlockH4 | !HtmlBlockCloseH4 .)* HtmlBlockCloseH4
  def _HtmlBlockH4

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenH4)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockH4)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseH4)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseH4)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockH4 unless _tmp
    return _tmp
  end

  # HtmlBlockOpenH5 = "<" Spnl ("h5" | "H5") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenH5

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("h5")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("H5")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenH5 unless _tmp
    return _tmp
  end

  # HtmlBlockCloseH5 = "<" Spnl "/" ("h5" | "H5") Spnl ">"
  def _HtmlBlockCloseH5

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("h5")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("H5")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseH5 unless _tmp
    return _tmp
  end

  # HtmlBlockH5 = HtmlBlockOpenH5 (HtmlBlockH5 | !HtmlBlockCloseH5 .)* HtmlBlockCloseH5
  def _HtmlBlockH5

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenH5)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockH5)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseH5)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseH5)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockH5 unless _tmp
    return _tmp
  end

  # HtmlBlockOpenH6 = "<" Spnl ("h6" | "H6") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenH6

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("h6")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("H6")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenH6 unless _tmp
    return _tmp
  end

  # HtmlBlockCloseH6 = "<" Spnl "/" ("h6" | "H6") Spnl ">"
  def _HtmlBlockCloseH6

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("h6")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("H6")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseH6 unless _tmp
    return _tmp
  end

  # HtmlBlockH6 = HtmlBlockOpenH6 (HtmlBlockH6 | !HtmlBlockCloseH6 .)* HtmlBlockCloseH6
  def _HtmlBlockH6

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenH6)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockH6)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseH6)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseH6)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockH6 unless _tmp
    return _tmp
  end

  # HtmlBlockOpenMenu = "<" Spnl ("menu" | "MENU") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenMenu

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("menu")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("MENU")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenMenu unless _tmp
    return _tmp
  end

  # HtmlBlockCloseMenu = "<" Spnl "/" ("menu" | "MENU") Spnl ">"
  def _HtmlBlockCloseMenu

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("menu")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("MENU")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseMenu unless _tmp
    return _tmp
  end

  # HtmlBlockMenu = HtmlBlockOpenMenu (HtmlBlockMenu | !HtmlBlockCloseMenu .)* HtmlBlockCloseMenu
  def _HtmlBlockMenu

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenMenu)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockMenu)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseMenu)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseMenu)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockMenu unless _tmp
    return _tmp
  end

  # HtmlBlockOpenNoframes = "<" Spnl ("noframes" | "NOFRAMES") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenNoframes

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("noframes")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("NOFRAMES")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenNoframes unless _tmp
    return _tmp
  end

  # HtmlBlockCloseNoframes = "<" Spnl "/" ("noframes" | "NOFRAMES") Spnl ">"
  def _HtmlBlockCloseNoframes

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("noframes")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("NOFRAMES")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseNoframes unless _tmp
    return _tmp
  end

  # HtmlBlockNoframes = HtmlBlockOpenNoframes (HtmlBlockNoframes | !HtmlBlockCloseNoframes .)* HtmlBlockCloseNoframes
  def _HtmlBlockNoframes

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenNoframes)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockNoframes)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseNoframes)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseNoframes)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockNoframes unless _tmp
    return _tmp
  end

  # HtmlBlockOpenNoscript = "<" Spnl ("noscript" | "NOSCRIPT") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenNoscript

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("noscript")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("NOSCRIPT")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenNoscript unless _tmp
    return _tmp
  end

  # HtmlBlockCloseNoscript = "<" Spnl "/" ("noscript" | "NOSCRIPT") Spnl ">"
  def _HtmlBlockCloseNoscript

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("noscript")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("NOSCRIPT")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseNoscript unless _tmp
    return _tmp
  end

  # HtmlBlockNoscript = HtmlBlockOpenNoscript (HtmlBlockNoscript | !HtmlBlockCloseNoscript .)* HtmlBlockCloseNoscript
  def _HtmlBlockNoscript

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenNoscript)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockNoscript)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseNoscript)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseNoscript)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockNoscript unless _tmp
    return _tmp
  end

  # HtmlBlockOpenOl = "<" Spnl ("ol" | "OL") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenOl

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("ol")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("OL")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenOl unless _tmp
    return _tmp
  end

  # HtmlBlockCloseOl = "<" Spnl "/" ("ol" | "OL") Spnl ">"
  def _HtmlBlockCloseOl

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("ol")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("OL")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseOl unless _tmp
    return _tmp
  end

  # HtmlBlockOl = HtmlBlockOpenOl (HtmlBlockOl | !HtmlBlockCloseOl .)* HtmlBlockCloseOl
  def _HtmlBlockOl

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenOl)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockOl)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseOl)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseOl)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOl unless _tmp
    return _tmp
  end

  # HtmlBlockOpenP = "<" Spnl ("p" | "P") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenP

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("p")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("P")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenP unless _tmp
    return _tmp
  end

  # HtmlBlockCloseP = "<" Spnl "/" ("p" | "P") Spnl ">"
  def _HtmlBlockCloseP

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("p")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("P")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseP unless _tmp
    return _tmp
  end

  # HtmlBlockP = HtmlBlockOpenP (HtmlBlockP | !HtmlBlockCloseP .)* HtmlBlockCloseP
  def _HtmlBlockP

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenP)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockP)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseP)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseP)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockP unless _tmp
    return _tmp
  end

  # HtmlBlockOpenPre = "<" Spnl ("pre" | "PRE") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenPre

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("pre")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("PRE")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenPre unless _tmp
    return _tmp
  end

  # HtmlBlockClosePre = "<" Spnl "/" ("pre" | "PRE") Spnl ">"
  def _HtmlBlockClosePre

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("pre")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("PRE")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockClosePre unless _tmp
    return _tmp
  end

  # HtmlBlockPre = HtmlBlockOpenPre (HtmlBlockPre | !HtmlBlockClosePre .)* HtmlBlockClosePre
  def _HtmlBlockPre

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenPre)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockPre)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockClosePre)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockClosePre)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockPre unless _tmp
    return _tmp
  end

  # HtmlBlockOpenTable = "<" Spnl ("table" | "TABLE") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenTable

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("table")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("TABLE")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenTable unless _tmp
    return _tmp
  end

  # HtmlBlockCloseTable = "<" Spnl "/" ("table" | "TABLE") Spnl ">"
  def _HtmlBlockCloseTable

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("table")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("TABLE")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseTable unless _tmp
    return _tmp
  end

  # HtmlBlockTable = HtmlBlockOpenTable (HtmlBlockTable | !HtmlBlockCloseTable .)* HtmlBlockCloseTable
  def _HtmlBlockTable

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenTable)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockTable)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseTable)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseTable)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockTable unless _tmp
    return _tmp
  end

  # HtmlBlockOpenUl = "<" Spnl ("ul" | "UL") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenUl

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("ul")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("UL")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenUl unless _tmp
    return _tmp
  end

  # HtmlBlockCloseUl = "<" Spnl "/" ("ul" | "UL") Spnl ">"
  def _HtmlBlockCloseUl

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("ul")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("UL")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseUl unless _tmp
    return _tmp
  end

  # HtmlBlockUl = HtmlBlockOpenUl (HtmlBlockUl | !HtmlBlockCloseUl .)* HtmlBlockCloseUl
  def _HtmlBlockUl

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenUl)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockUl)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseUl)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseUl)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockUl unless _tmp
    return _tmp
  end

  # HtmlBlockOpenDd = "<" Spnl ("dd" | "DD") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenDd

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("dd")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("DD")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenDd unless _tmp
    return _tmp
  end

  # HtmlBlockCloseDd = "<" Spnl "/" ("dd" | "DD") Spnl ">"
  def _HtmlBlockCloseDd

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("dd")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("DD")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseDd unless _tmp
    return _tmp
  end

  # HtmlBlockDd = HtmlBlockOpenDd (HtmlBlockDd | !HtmlBlockCloseDd .)* HtmlBlockCloseDd
  def _HtmlBlockDd

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenDd)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockDd)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseDd)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseDd)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockDd unless _tmp
    return _tmp
  end

  # HtmlBlockOpenDt = "<" Spnl ("dt" | "DT") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenDt

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("dt")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("DT")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenDt unless _tmp
    return _tmp
  end

  # HtmlBlockCloseDt = "<" Spnl "/" ("dt" | "DT") Spnl ">"
  def _HtmlBlockCloseDt

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("dt")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("DT")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseDt unless _tmp
    return _tmp
  end

  # HtmlBlockDt = HtmlBlockOpenDt (HtmlBlockDt | !HtmlBlockCloseDt .)* HtmlBlockCloseDt
  def _HtmlBlockDt

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenDt)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockDt)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseDt)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseDt)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockDt unless _tmp
    return _tmp
  end

  # HtmlBlockOpenFrameset = "<" Spnl ("frameset" | "FRAMESET") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenFrameset

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("frameset")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("FRAMESET")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenFrameset unless _tmp
    return _tmp
  end

  # HtmlBlockCloseFrameset = "<" Spnl "/" ("frameset" | "FRAMESET") Spnl ">"
  def _HtmlBlockCloseFrameset

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("frameset")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("FRAMESET")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseFrameset unless _tmp
    return _tmp
  end

  # HtmlBlockFrameset = HtmlBlockOpenFrameset (HtmlBlockFrameset | !HtmlBlockCloseFrameset .)* HtmlBlockCloseFrameset
  def _HtmlBlockFrameset

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenFrameset)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockFrameset)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseFrameset)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseFrameset)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockFrameset unless _tmp
    return _tmp
  end

  # HtmlBlockOpenLi = "<" Spnl ("li" | "LI") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenLi

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("li")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("LI")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenLi unless _tmp
    return _tmp
  end

  # HtmlBlockCloseLi = "<" Spnl "/" ("li" | "LI") Spnl ">"
  def _HtmlBlockCloseLi

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("li")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("LI")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseLi unless _tmp
    return _tmp
  end

  # HtmlBlockLi = HtmlBlockOpenLi (HtmlBlockLi | !HtmlBlockCloseLi .)* HtmlBlockCloseLi
  def _HtmlBlockLi

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenLi)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockLi)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseLi)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseLi)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockLi unless _tmp
    return _tmp
  end

  # HtmlBlockOpenTbody = "<" Spnl ("tbody" | "TBODY") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenTbody

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("tbody")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("TBODY")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenTbody unless _tmp
    return _tmp
  end

  # HtmlBlockCloseTbody = "<" Spnl "/" ("tbody" | "TBODY") Spnl ">"
  def _HtmlBlockCloseTbody

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("tbody")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("TBODY")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseTbody unless _tmp
    return _tmp
  end

  # HtmlBlockTbody = HtmlBlockOpenTbody (HtmlBlockTbody | !HtmlBlockCloseTbody .)* HtmlBlockCloseTbody
  def _HtmlBlockTbody

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenTbody)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockTbody)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseTbody)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseTbody)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockTbody unless _tmp
    return _tmp
  end

  # HtmlBlockOpenTd = "<" Spnl ("td" | "TD") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenTd

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("td")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("TD")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenTd unless _tmp
    return _tmp
  end

  # HtmlBlockCloseTd = "<" Spnl "/" ("td" | "TD") Spnl ">"
  def _HtmlBlockCloseTd

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("td")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("TD")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseTd unless _tmp
    return _tmp
  end

  # HtmlBlockTd = HtmlBlockOpenTd (HtmlBlockTd | !HtmlBlockCloseTd .)* HtmlBlockCloseTd
  def _HtmlBlockTd

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenTd)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockTd)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseTd)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseTd)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockTd unless _tmp
    return _tmp
  end

  # HtmlBlockOpenTfoot = "<" Spnl ("tfoot" | "TFOOT") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenTfoot

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("tfoot")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("TFOOT")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenTfoot unless _tmp
    return _tmp
  end

  # HtmlBlockCloseTfoot = "<" Spnl "/" ("tfoot" | "TFOOT") Spnl ">"
  def _HtmlBlockCloseTfoot

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("tfoot")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("TFOOT")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseTfoot unless _tmp
    return _tmp
  end

  # HtmlBlockTfoot = HtmlBlockOpenTfoot (HtmlBlockTfoot | !HtmlBlockCloseTfoot .)* HtmlBlockCloseTfoot
  def _HtmlBlockTfoot

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenTfoot)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockTfoot)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseTfoot)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseTfoot)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockTfoot unless _tmp
    return _tmp
  end

  # HtmlBlockOpenTh = "<" Spnl ("th" | "TH") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenTh

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("th")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("TH")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenTh unless _tmp
    return _tmp
  end

  # HtmlBlockCloseTh = "<" Spnl "/" ("th" | "TH") Spnl ">"
  def _HtmlBlockCloseTh

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("th")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("TH")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseTh unless _tmp
    return _tmp
  end

  # HtmlBlockTh = HtmlBlockOpenTh (HtmlBlockTh | !HtmlBlockCloseTh .)* HtmlBlockCloseTh
  def _HtmlBlockTh

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenTh)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockTh)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseTh)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseTh)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockTh unless _tmp
    return _tmp
  end

  # HtmlBlockOpenThead = "<" Spnl ("thead" | "THEAD") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenThead

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("thead")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("THEAD")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenThead unless _tmp
    return _tmp
  end

  # HtmlBlockCloseThead = "<" Spnl "/" ("thead" | "THEAD") Spnl ">"
  def _HtmlBlockCloseThead

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("thead")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("THEAD")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseThead unless _tmp
    return _tmp
  end

  # HtmlBlockThead = HtmlBlockOpenThead (HtmlBlockThead | !HtmlBlockCloseThead .)* HtmlBlockCloseThead
  def _HtmlBlockThead

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenThead)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockThead)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseThead)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseThead)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockThead unless _tmp
    return _tmp
  end

  # HtmlBlockOpenTr = "<" Spnl ("tr" | "TR") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenTr

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("tr")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("TR")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenTr unless _tmp
    return _tmp
  end

  # HtmlBlockCloseTr = "<" Spnl "/" ("tr" | "TR") Spnl ">"
  def _HtmlBlockCloseTr

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("tr")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("TR")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseTr unless _tmp
    return _tmp
  end

  # HtmlBlockTr = HtmlBlockOpenTr (HtmlBlockTr | !HtmlBlockCloseTr .)* HtmlBlockCloseTr
  def _HtmlBlockTr

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenTr)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # choice
          _tmp = apply(:_HtmlBlockTr)
          break if _tmp
          self.pos = _save2

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = apply(:_HtmlBlockCloseTr)
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break if _tmp
          self.pos = _save2
          break
        end # end choice

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseTr)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockTr unless _tmp
    return _tmp
  end

  # HtmlBlockOpenScript = "<" Spnl ("script" | "SCRIPT") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenScript

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("script")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("SCRIPT")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenScript unless _tmp
    return _tmp
  end

  # HtmlBlockCloseScript = "<" Spnl "/" ("script" | "SCRIPT") Spnl ">"
  def _HtmlBlockCloseScript

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("script")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("SCRIPT")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseScript unless _tmp
    return _tmp
  end

  # HtmlBlockScript = HtmlBlockOpenScript (!HtmlBlockCloseScript .)* HtmlBlockCloseScript
  def _HtmlBlockScript

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenScript)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # sequence
          _save3 = self.pos
          _tmp = apply(:_HtmlBlockCloseScript)
          _tmp = _tmp ? nil : true
          self.pos = _save3
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = get_byte
          unless _tmp
            self.pos = _save2
          end
          break
        end # end sequence

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseScript)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockScript unless _tmp
    return _tmp
  end

  # HtmlBlockOpenHead = "<" Spnl ("head" | "HEAD") Spnl HtmlAttribute* ">"
  def _HtmlBlockOpenHead

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("head")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("HEAD")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockOpenHead unless _tmp
    return _tmp
  end

  # HtmlBlockCloseHead = "<" Spnl "/" ("head" | "HEAD") Spnl ">"
  def _HtmlBlockCloseHead

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("head")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("HEAD")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockCloseHead unless _tmp
    return _tmp
  end

  # HtmlBlockHead = HtmlBlockOpenHead (!HtmlBlockCloseHead .)* HtmlBlockCloseHead
  def _HtmlBlockHead

    _save = self.pos
    while true # sequence
      _tmp = apply(:_HtmlBlockOpenHead)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # sequence
          _save3 = self.pos
          _tmp = apply(:_HtmlBlockCloseHead)
          _tmp = _tmp ? nil : true
          self.pos = _save3
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = get_byte
          unless _tmp
            self.pos = _save2
          end
          break
        end # end sequence

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockCloseHead)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockHead unless _tmp
    return _tmp
  end

  # HtmlBlockInTags = (HtmlAnchor | HtmlBlockAddress | HtmlBlockBlockquote | HtmlBlockCenter | HtmlBlockDir | HtmlBlockDiv | HtmlBlockDl | HtmlBlockFieldset | HtmlBlockForm | HtmlBlockH1 | HtmlBlockH2 | HtmlBlockH3 | HtmlBlockH4 | HtmlBlockH5 | HtmlBlockH6 | HtmlBlockMenu | HtmlBlockNoframes | HtmlBlockNoscript | HtmlBlockOl | HtmlBlockP | HtmlBlockPre | HtmlBlockTable | HtmlBlockUl | HtmlBlockDd | HtmlBlockDt | HtmlBlockFrameset | HtmlBlockLi | HtmlBlockTbody | HtmlBlockTd | HtmlBlockTfoot | HtmlBlockTh | HtmlBlockThead | HtmlBlockTr | HtmlBlockScript | HtmlBlockHead)
  def _HtmlBlockInTags

    _save = self.pos
    while true # choice
      _tmp = apply(:_HtmlAnchor)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockAddress)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockBlockquote)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockCenter)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockDir)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockDiv)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockDl)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockFieldset)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockForm)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockH1)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockH2)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockH3)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockH4)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockH5)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockH6)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockMenu)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockNoframes)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockNoscript)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockOl)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockP)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockPre)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockTable)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockUl)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockDd)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockDt)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockFrameset)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockLi)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockTbody)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockTd)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockTfoot)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockTh)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockThead)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockTr)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockScript)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_HtmlBlockHead)
      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_HtmlBlockInTags unless _tmp
    return _tmp
  end

  # HtmlBlock = < (HtmlBlockInTags | HtmlComment | HtmlBlockSelfClosing | HtmlUnclosed) > @BlankLine+ { if html? then                 RDoc::Markup::Raw.new text               end }
  def _HtmlBlock

    _save = self.pos
    while true # sequence
      _text_start = self.pos

      _save1 = self.pos
      while true # choice
        _tmp = apply(:_HtmlBlockInTags)
        break if _tmp
        self.pos = _save1
        _tmp = apply(:_HtmlComment)
        break if _tmp
        self.pos = _save1
        _tmp = apply(:_HtmlBlockSelfClosing)
        break if _tmp
        self.pos = _save1
        _tmp = apply(:_HtmlUnclosed)
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos
      _tmp = _BlankLine()
      if _tmp
        while true
          _tmp = _BlankLine()
          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save2
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  if html? then
                RDoc::Markup::Raw.new text
              end ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlock unless _tmp
    return _tmp
  end

  # HtmlUnclosed = "<" Spnl HtmlUnclosedType Spnl HtmlAttribute* Spnl ">"
  def _HtmlUnclosed

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlUnclosedType)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlUnclosed unless _tmp
    return _tmp
  end

  # HtmlUnclosedType = ("HR" | "hr")
  def _HtmlUnclosedType

    _save = self.pos
    while true # choice
      _tmp = match_string("HR")
      break if _tmp
      self.pos = _save
      _tmp = match_string("hr")
      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_HtmlUnclosedType unless _tmp
    return _tmp
  end

  # HtmlBlockSelfClosing = "<" Spnl HtmlBlockType Spnl HtmlAttribute* "/" Spnl ">"
  def _HtmlBlockSelfClosing

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_HtmlBlockType)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlBlockSelfClosing unless _tmp
    return _tmp
  end

  # HtmlBlockType = ("ADDRESS" | "BLOCKQUOTE" | "CENTER" | "DD" | "DIR" | "DIV" | "DL" | "DT" | "FIELDSET" | "FORM" | "FRAMESET" | "H1" | "H2" | "H3" | "H4" | "H5" | "H6" | "HR" | "ISINDEX" | "LI" | "MENU" | "NOFRAMES" | "NOSCRIPT" | "OL" | "P" | "PRE" | "SCRIPT" | "TABLE" | "TBODY" | "TD" | "TFOOT" | "TH" | "THEAD" | "TR" | "UL" | "address" | "blockquote" | "center" | "dd" | "dir" | "div" | "dl" | "dt" | "fieldset" | "form" | "frameset" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "hr" | "isindex" | "li" | "menu" | "noframes" | "noscript" | "ol" | "p" | "pre" | "script" | "table" | "tbody" | "td" | "tfoot" | "th" | "thead" | "tr" | "ul")
  def _HtmlBlockType

    _save = self.pos
    while true # choice
      _tmp = match_string("ADDRESS")
      break if _tmp
      self.pos = _save
      _tmp = match_string("BLOCKQUOTE")
      break if _tmp
      self.pos = _save
      _tmp = match_string("CENTER")
      break if _tmp
      self.pos = _save
      _tmp = match_string("DD")
      break if _tmp
      self.pos = _save
      _tmp = match_string("DIR")
      break if _tmp
      self.pos = _save
      _tmp = match_string("DIV")
      break if _tmp
      self.pos = _save
      _tmp = match_string("DL")
      break if _tmp
      self.pos = _save
      _tmp = match_string("DT")
      break if _tmp
      self.pos = _save
      _tmp = match_string("FIELDSET")
      break if _tmp
      self.pos = _save
      _tmp = match_string("FORM")
      break if _tmp
      self.pos = _save
      _tmp = match_string("FRAMESET")
      break if _tmp
      self.pos = _save
      _tmp = match_string("H1")
      break if _tmp
      self.pos = _save
      _tmp = match_string("H2")
      break if _tmp
      self.pos = _save
      _tmp = match_string("H3")
      break if _tmp
      self.pos = _save
      _tmp = match_string("H4")
      break if _tmp
      self.pos = _save
      _tmp = match_string("H5")
      break if _tmp
      self.pos = _save
      _tmp = match_string("H6")
      break if _tmp
      self.pos = _save
      _tmp = match_string("HR")
      break if _tmp
      self.pos = _save
      _tmp = match_string("ISINDEX")
      break if _tmp
      self.pos = _save
      _tmp = match_string("LI")
      break if _tmp
      self.pos = _save
      _tmp = match_string("MENU")
      break if _tmp
      self.pos = _save
      _tmp = match_string("NOFRAMES")
      break if _tmp
      self.pos = _save
      _tmp = match_string("NOSCRIPT")
      break if _tmp
      self.pos = _save
      _tmp = match_string("OL")
      break if _tmp
      self.pos = _save
      _tmp = match_string("P")
      break if _tmp
      self.pos = _save
      _tmp = match_string("PRE")
      break if _tmp
      self.pos = _save
      _tmp = match_string("SCRIPT")
      break if _tmp
      self.pos = _save
      _tmp = match_string("TABLE")
      break if _tmp
      self.pos = _save
      _tmp = match_string("TBODY")
      break if _tmp
      self.pos = _save
      _tmp = match_string("TD")
      break if _tmp
      self.pos = _save
      _tmp = match_string("TFOOT")
      break if _tmp
      self.pos = _save
      _tmp = match_string("TH")
      break if _tmp
      self.pos = _save
      _tmp = match_string("THEAD")
      break if _tmp
      self.pos = _save
      _tmp = match_string("TR")
      break if _tmp
      self.pos = _save
      _tmp = match_string("UL")
      break if _tmp
      self.pos = _save
      _tmp = match_string("address")
      break if _tmp
      self.pos = _save
      _tmp = match_string("blockquote")
      break if _tmp
      self.pos = _save
      _tmp = match_string("center")
      break if _tmp
      self.pos = _save
      _tmp = match_string("dd")
      break if _tmp
      self.pos = _save
      _tmp = match_string("dir")
      break if _tmp
      self.pos = _save
      _tmp = match_string("div")
      break if _tmp
      self.pos = _save
      _tmp = match_string("dl")
      break if _tmp
      self.pos = _save
      _tmp = match_string("dt")
      break if _tmp
      self.pos = _save
      _tmp = match_string("fieldset")
      break if _tmp
      self.pos = _save
      _tmp = match_string("form")
      break if _tmp
      self.pos = _save
      _tmp = match_string("frameset")
      break if _tmp
      self.pos = _save
      _tmp = match_string("h1")
      break if _tmp
      self.pos = _save
      _tmp = match_string("h2")
      break if _tmp
      self.pos = _save
      _tmp = match_string("h3")
      break if _tmp
      self.pos = _save
      _tmp = match_string("h4")
      break if _tmp
      self.pos = _save
      _tmp = match_string("h5")
      break if _tmp
      self.pos = _save
      _tmp = match_string("h6")
      break if _tmp
      self.pos = _save
      _tmp = match_string("hr")
      break if _tmp
      self.pos = _save
      _tmp = match_string("isindex")
      break if _tmp
      self.pos = _save
      _tmp = match_string("li")
      break if _tmp
      self.pos = _save
      _tmp = match_string("menu")
      break if _tmp
      self.pos = _save
      _tmp = match_string("noframes")
      break if _tmp
      self.pos = _save
      _tmp = match_string("noscript")
      break if _tmp
      self.pos = _save
      _tmp = match_string("ol")
      break if _tmp
      self.pos = _save
      _tmp = match_string("p")
      break if _tmp
      self.pos = _save
      _tmp = match_string("pre")
      break if _tmp
      self.pos = _save
      _tmp = match_string("script")
      break if _tmp
      self.pos = _save
      _tmp = match_string("table")
      break if _tmp
      self.pos = _save
      _tmp = match_string("tbody")
      break if _tmp
      self.pos = _save
      _tmp = match_string("td")
      break if _tmp
      self.pos = _save
      _tmp = match_string("tfoot")
      break if _tmp
      self.pos = _save
      _tmp = match_string("th")
      break if _tmp
      self.pos = _save
      _tmp = match_string("thead")
      break if _tmp
      self.pos = _save
      _tmp = match_string("tr")
      break if _tmp
      self.pos = _save
      _tmp = match_string("ul")
      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_HtmlBlockType unless _tmp
    return _tmp
  end

  # StyleOpen = "<" Spnl ("style" | "STYLE") Spnl HtmlAttribute* ">"
  def _StyleOpen

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("style")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("STYLE")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_StyleOpen unless _tmp
    return _tmp
  end

  # StyleClose = "<" Spnl "/" ("style" | "STYLE") Spnl ">"
  def _StyleClose

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("/")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = match_string("style")
        break if _tmp
        self.pos = _save1
        _tmp = match_string("STYLE")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_StyleClose unless _tmp
    return _tmp
  end

  # InStyleTags = StyleOpen (!StyleClose .)* StyleClose
  def _InStyleTags

    _save = self.pos
    while true # sequence
      _tmp = apply(:_StyleOpen)
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # sequence
          _save3 = self.pos
          _tmp = apply(:_StyleClose)
          _tmp = _tmp ? nil : true
          self.pos = _save3
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = get_byte
          unless _tmp
            self.pos = _save2
          end
          break
        end # end sequence

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_StyleClose)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_InStyleTags unless _tmp
    return _tmp
  end

  # StyleBlock = < InStyleTags > @BlankLine* { if css? then                     RDoc::Markup::Raw.new text                   end }
  def _StyleBlock

    _save = self.pos
    while true # sequence
      _text_start = self.pos
      _tmp = apply(:_InStyleTags)
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = _BlankLine()
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  if css? then
                    RDoc::Markup::Raw.new text
                  end ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_StyleBlock unless _tmp
    return _tmp
  end

  # Inlines = (!@Endline Inline:i { i } | @Endline:c !(&{ github? } Ticks3 /[^`\n]*$/) &Inline { c })+:chunks @Endline? { chunks }
  def _Inlines

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _ary = []

      _save2 = self.pos
      while true # choice

        _save3 = self.pos
        while true # sequence
          _save4 = self.pos
          _tmp = _Endline()
          _tmp = _tmp ? nil : true
          self.pos = _save4
          unless _tmp
            self.pos = _save3
            break
          end
          _tmp = apply(:_Inline)
          i = @result
          unless _tmp
            self.pos = _save3
            break
          end
          @result = begin;  i ; end
          _tmp = true
          unless _tmp
            self.pos = _save3
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save2

        _save5 = self.pos
        while true # sequence
          _tmp = _Endline()
          c = @result
          unless _tmp
            self.pos = _save5
            break
          end
          _save6 = self.pos

          _save7 = self.pos
          while true # sequence
            _save8 = self.pos
            _tmp = begin;  github? ; end
            self.pos = _save8
            unless _tmp
              self.pos = _save7
              break
            end
            _tmp = apply(:_Ticks3)
            unless _tmp
              self.pos = _save7
              break
            end
            _tmp = scan(/\G(?-mix:[^`\n]*$)/)
            unless _tmp
              self.pos = _save7
            end
            break
          end # end sequence

          _tmp = _tmp ? nil : true
          self.pos = _save6
          unless _tmp
            self.pos = _save5
            break
          end
          _save9 = self.pos
          _tmp = apply(:_Inline)
          self.pos = _save9
          unless _tmp
            self.pos = _save5
            break
          end
          @result = begin;  c ; end
          _tmp = true
          unless _tmp
            self.pos = _save5
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save2
        break
      end # end choice

      if _tmp
        _ary << @result
        while true

          _save10 = self.pos
          while true # choice

            _save11 = self.pos
            while true # sequence
              _save12 = self.pos
              _tmp = _Endline()
              _tmp = _tmp ? nil : true
              self.pos = _save12
              unless _tmp
                self.pos = _save11
                break
              end
              _tmp = apply(:_Inline)
              i = @result
              unless _tmp
                self.pos = _save11
                break
              end
              @result = begin;  i ; end
              _tmp = true
              unless _tmp
                self.pos = _save11
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save10

            _save13 = self.pos
            while true # sequence
              _tmp = _Endline()
              c = @result
              unless _tmp
                self.pos = _save13
                break
              end
              _save14 = self.pos

              _save15 = self.pos
              while true # sequence
                _save16 = self.pos
                _tmp = begin;  github? ; end
                self.pos = _save16
                unless _tmp
                  self.pos = _save15
                  break
                end
                _tmp = apply(:_Ticks3)
                unless _tmp
                  self.pos = _save15
                  break
                end
                _tmp = scan(/\G(?-mix:[^`\n]*$)/)
                unless _tmp
                  self.pos = _save15
                end
                break
              end # end sequence

              _tmp = _tmp ? nil : true
              self.pos = _save14
              unless _tmp
                self.pos = _save13
                break
              end
              _save17 = self.pos
              _tmp = apply(:_Inline)
              self.pos = _save17
              unless _tmp
                self.pos = _save13
                break
              end
              @result = begin;  c ; end
              _tmp = true
              unless _tmp
                self.pos = _save13
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save10
            break
          end # end choice

          _ary << @result if _tmp
          break unless _tmp
        end
        _tmp = true
        @result = _ary
      else
        self.pos = _save1
      end
      chunks = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save18 = self.pos
      _tmp = _Endline()
      unless _tmp
        _tmp = true
        self.pos = _save18
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  chunks ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Inlines unless _tmp
    return _tmp
  end

  # Inline = (Str | @Endline | UlOrStarLine | @Space | Strong | Emph | Strike | Image | Link | NoteReference | InlineNote | Code | RawHtml | Entity | EscapedChar | Symbol)
  def _Inline

    _save = self.pos
    while true # choice
      _tmp = apply(:_Str)
      break if _tmp
      self.pos = _save
      _tmp = _Endline()
      break if _tmp
      self.pos = _save
      _tmp = apply(:_UlOrStarLine)
      break if _tmp
      self.pos = _save
      _tmp = _Space()
      break if _tmp
      self.pos = _save
      _tmp = apply(:_Strong)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_Emph)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_Strike)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_Image)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_Link)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_NoteReference)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_InlineNote)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_Code)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_RawHtml)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_Entity)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_EscapedChar)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_Symbol)
      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_Inline unless _tmp
    return _tmp
  end

  # Space = @Spacechar+ { " " }
  def _Space

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = _Spacechar()
      if _tmp
        while true
          _tmp = _Spacechar()
          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save1
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  " " ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Space unless _tmp
    return _tmp
  end

  # Str = @StartList:a < @NormalChar+ > { a = text } (StrChunk:c { a << c })* { a }
  def _Str

    _save = self.pos
    while true # sequence
      _tmp = _StartList()
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _text_start = self.pos
      _save1 = self.pos
      _tmp = _NormalChar()
      if _tmp
        while true
          _tmp = _NormalChar()
          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save1
      end
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  a = text ; end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save3 = self.pos
        while true # sequence
          _tmp = apply(:_StrChunk)
          c = @result
          unless _tmp
            self.pos = _save3
            break
          end
          @result = begin;  a << c ; end
          _tmp = true
          unless _tmp
            self.pos = _save3
          end
          break
        end # end sequence

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  a ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Str unless _tmp
    return _tmp
  end

  # StrChunk = < (@NormalChar | /_+/ &Alphanumeric)+ > { text }
  def _StrChunk

    _save = self.pos
    while true # sequence
      _text_start = self.pos
      _save1 = self.pos

      _save2 = self.pos
      while true # choice
        _tmp = _NormalChar()
        break if _tmp
        self.pos = _save2

        _save3 = self.pos
        while true # sequence
          _tmp = scan(/\G(?-mix:_+)/)
          unless _tmp
            self.pos = _save3
            break
          end
          _save4 = self.pos
          _tmp = apply(:_Alphanumeric)
          self.pos = _save4
          unless _tmp
            self.pos = _save3
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save2
        break
      end # end choice

      if _tmp
        while true

          _save5 = self.pos
          while true # choice
            _tmp = _NormalChar()
            break if _tmp
            self.pos = _save5

            _save6 = self.pos
            while true # sequence
              _tmp = scan(/\G(?-mix:_+)/)
              unless _tmp
                self.pos = _save6
                break
              end
              _save7 = self.pos
              _tmp = apply(:_Alphanumeric)
              self.pos = _save7
              unless _tmp
                self.pos = _save6
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save5
            break
          end # end choice

          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save1
      end
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  text ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_StrChunk unless _tmp
    return _tmp
  end

  # EscapedChar = "\\" !@Newline < /[:\\`|*_{}\[\]()#+.!><-]/ > { text }
  def _EscapedChar

    _save = self.pos
    while true # sequence
      _tmp = match_string("\\")
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _tmp = _Newline()
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _text_start = self.pos
      _tmp = scan(/\G(?-mix:[:\\`|*_{}\[\]()#+.!><-])/)
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  text ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_EscapedChar unless _tmp
    return _tmp
  end

  # Entity = (HexEntity | DecEntity | CharEntity):a { a }
  def _Entity

    _save = self.pos
    while true # sequence

      _save1 = self.pos
      while true # choice
        _tmp = apply(:_HexEntity)
        break if _tmp
        self.pos = _save1
        _tmp = apply(:_DecEntity)
        break if _tmp
        self.pos = _save1
        _tmp = apply(:_CharEntity)
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  a ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Entity unless _tmp
    return _tmp
  end

  # Endline = (@LineBreak | @TerminalEndline | @NormalEndline)
  def _Endline

    _save = self.pos
    while true # choice
      _tmp = _LineBreak()
      break if _tmp
      self.pos = _save
      _tmp = _TerminalEndline()
      break if _tmp
      self.pos = _save
      _tmp = _NormalEndline()
      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_Endline unless _tmp
    return _tmp
  end

  # NormalEndline = @Sp @Newline !@BlankLine !">" !AtxStart !(Line /={1,}|-{1,}/ @Newline) { "\n" }
  def _NormalEndline

    _save = self.pos
    while true # sequence
      _tmp = _Sp()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Newline()
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _tmp = _BlankLine()
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos
      _tmp = match_string(">")
      _tmp = _tmp ? nil : true
      self.pos = _save2
      unless _tmp
        self.pos = _save
        break
      end
      _save3 = self.pos
      _tmp = apply(:_AtxStart)
      _tmp = _tmp ? nil : true
      self.pos = _save3
      unless _tmp
        self.pos = _save
        break
      end
      _save4 = self.pos

      _save5 = self.pos
      while true # sequence
        _tmp = apply(:_Line)
        unless _tmp
          self.pos = _save5
          break
        end
        _tmp = scan(/\G(?-mix:={1,}|-{1,})/)
        unless _tmp
          self.pos = _save5
          break
        end
        _tmp = _Newline()
        unless _tmp
          self.pos = _save5
        end
        break
      end # end sequence

      _tmp = _tmp ? nil : true
      self.pos = _save4
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  "\n" ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_NormalEndline unless _tmp
    return _tmp
  end

  # TerminalEndline = @Sp @Newline @Eof
  def _TerminalEndline

    _save = self.pos
    while true # sequence
      _tmp = _Sp()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Newline()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Eof()
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_TerminalEndline unless _tmp
    return _tmp
  end

  # LineBreak = "  " @NormalEndline { RDoc::Markup::HardBreak.new }
  def _LineBreak

    _save = self.pos
    while true # sequence
      _tmp = match_string("  ")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _NormalEndline()
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  RDoc::Markup::HardBreak.new ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_LineBreak unless _tmp
    return _tmp
  end

  # Symbol = < @SpecialChar > { text }
  def _Symbol

    _save = self.pos
    while true # sequence
      _text_start = self.pos
      _tmp = _SpecialChar()
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  text ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Symbol unless _tmp
    return _tmp
  end

  # UlOrStarLine = (UlLine | StarLine):a { a }
  def _UlOrStarLine

    _save = self.pos
    while true # sequence

      _save1 = self.pos
      while true # choice
        _tmp = apply(:_UlLine)
        break if _tmp
        self.pos = _save1
        _tmp = apply(:_StarLine)
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  a ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_UlOrStarLine unless _tmp
    return _tmp
  end

  # StarLine = (< /\*{4,}/ > { text } | < @Spacechar /\*+/ &@Spacechar > { text })
  def _StarLine

    _save = self.pos
    while true # choice

      _save1 = self.pos
      while true # sequence
        _text_start = self.pos
        _tmp = scan(/\G(?-mix:\*{4,})/)
        if _tmp
          text = get_text(_text_start)
        end
        unless _tmp
          self.pos = _save1
          break
        end
        @result = begin;  text ; end
        _tmp = true
        unless _tmp
          self.pos = _save1
        end
        break
      end # end sequence

      break if _tmp
      self.pos = _save

      _save2 = self.pos
      while true # sequence
        _text_start = self.pos

        _save3 = self.pos
        while true # sequence
          _tmp = _Spacechar()
          unless _tmp
            self.pos = _save3
            break
          end
          _tmp = scan(/\G(?-mix:\*+)/)
          unless _tmp
            self.pos = _save3
            break
          end
          _save4 = self.pos
          _tmp = _Spacechar()
          self.pos = _save4
          unless _tmp
            self.pos = _save3
          end
          break
        end # end sequence

        if _tmp
          text = get_text(_text_start)
        end
        unless _tmp
          self.pos = _save2
          break
        end
        @result = begin;  text ; end
        _tmp = true
        unless _tmp
          self.pos = _save2
        end
        break
      end # end sequence

      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_StarLine unless _tmp
    return _tmp
  end

  # UlLine = (< /_{4,}/ > { text } | < @Spacechar /_+/ &@Spacechar > { text })
  def _UlLine

    _save = self.pos
    while true # choice

      _save1 = self.pos
      while true # sequence
        _text_start = self.pos
        _tmp = scan(/\G(?-mix:_{4,})/)
        if _tmp
          text = get_text(_text_start)
        end
        unless _tmp
          self.pos = _save1
          break
        end
        @result = begin;  text ; end
        _tmp = true
        unless _tmp
          self.pos = _save1
        end
        break
      end # end sequence

      break if _tmp
      self.pos = _save

      _save2 = self.pos
      while true # sequence
        _text_start = self.pos

        _save3 = self.pos
        while true # sequence
          _tmp = _Spacechar()
          unless _tmp
            self.pos = _save3
            break
          end
          _tmp = scan(/\G(?-mix:_+)/)
          unless _tmp
            self.pos = _save3
            break
          end
          _save4 = self.pos
          _tmp = _Spacechar()
          self.pos = _save4
          unless _tmp
            self.pos = _save3
          end
          break
        end # end sequence

        if _tmp
          text = get_text(_text_start)
        end
        unless _tmp
          self.pos = _save2
          break
        end
        @result = begin;  text ; end
        _tmp = true
        unless _tmp
          self.pos = _save2
        end
        break
      end # end sequence

      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_UlLine unless _tmp
    return _tmp
  end

  # Emph = (EmphStar | EmphUl)
  def _Emph

    _save = self.pos
    while true # choice
      _tmp = apply(:_EmphStar)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_EmphUl)
      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_Emph unless _tmp
    return _tmp
  end

  # Whitespace = (@Spacechar | @Newline)
  def _Whitespace

    _save = self.pos
    while true # choice
      _tmp = _Spacechar()
      break if _tmp
      self.pos = _save
      _tmp = _Newline()
      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_Whitespace unless _tmp
    return _tmp
  end

  # EmphStar = "*" !@Whitespace @StartList:a (!"*" Inline:b { a << b } | StrongStar:b { a << b })+ "*" { emphasis a.join }
  def _EmphStar

    _save = self.pos
    while true # sequence
      _tmp = match_string("*")
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _tmp = _Whitespace()
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _StartList()
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos

      _save3 = self.pos
      while true # choice

        _save4 = self.pos
        while true # sequence
          _save5 = self.pos
          _tmp = match_string("*")
          _tmp = _tmp ? nil : true
          self.pos = _save5
          unless _tmp
            self.pos = _save4
            break
          end
          _tmp = apply(:_Inline)
          b = @result
          unless _tmp
            self.pos = _save4
            break
          end
          @result = begin;  a << b ; end
          _tmp = true
          unless _tmp
            self.pos = _save4
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save3

        _save6 = self.pos
        while true # sequence
          _tmp = apply(:_StrongStar)
          b = @result
          unless _tmp
            self.pos = _save6
            break
          end
          @result = begin;  a << b ; end
          _tmp = true
          unless _tmp
            self.pos = _save6
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save3
        break
      end # end choice

      if _tmp
        while true

          _save7 = self.pos
          while true # choice

            _save8 = self.pos
            while true # sequence
              _save9 = self.pos
              _tmp = match_string("*")
              _tmp = _tmp ? nil : true
              self.pos = _save9
              unless _tmp
                self.pos = _save8
                break
              end
              _tmp = apply(:_Inline)
              b = @result
              unless _tmp
                self.pos = _save8
                break
              end
              @result = begin;  a << b ; end
              _tmp = true
              unless _tmp
                self.pos = _save8
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save7

            _save10 = self.pos
            while true # sequence
              _tmp = apply(:_StrongStar)
              b = @result
              unless _tmp
                self.pos = _save10
                break
              end
              @result = begin;  a << b ; end
              _tmp = true
              unless _tmp
                self.pos = _save10
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save7
            break
          end # end choice

          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save2
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("*")
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  emphasis a.join ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_EmphStar unless _tmp
    return _tmp
  end

  # EmphUl = "_" !@Whitespace @StartList:a (!"_" Inline:b { a << b } | StrongUl:b { a << b })+ "_" { emphasis a.join }
  def _EmphUl

    _save = self.pos
    while true # sequence
      _tmp = match_string("_")
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _tmp = _Whitespace()
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _StartList()
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos

      _save3 = self.pos
      while true # choice

        _save4 = self.pos
        while true # sequence
          _save5 = self.pos
          _tmp = match_string("_")
          _tmp = _tmp ? nil : true
          self.pos = _save5
          unless _tmp
            self.pos = _save4
            break
          end
          _tmp = apply(:_Inline)
          b = @result
          unless _tmp
            self.pos = _save4
            break
          end
          @result = begin;  a << b ; end
          _tmp = true
          unless _tmp
            self.pos = _save4
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save3

        _save6 = self.pos
        while true # sequence
          _tmp = apply(:_StrongUl)
          b = @result
          unless _tmp
            self.pos = _save6
            break
          end
          @result = begin;  a << b ; end
          _tmp = true
          unless _tmp
            self.pos = _save6
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save3
        break
      end # end choice

      if _tmp
        while true

          _save7 = self.pos
          while true # choice

            _save8 = self.pos
            while true # sequence
              _save9 = self.pos
              _tmp = match_string("_")
              _tmp = _tmp ? nil : true
              self.pos = _save9
              unless _tmp
                self.pos = _save8
                break
              end
              _tmp = apply(:_Inline)
              b = @result
              unless _tmp
                self.pos = _save8
                break
              end
              @result = begin;  a << b ; end
              _tmp = true
              unless _tmp
                self.pos = _save8
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save7

            _save10 = self.pos
            while true # sequence
              _tmp = apply(:_StrongUl)
              b = @result
              unless _tmp
                self.pos = _save10
                break
              end
              @result = begin;  a << b ; end
              _tmp = true
              unless _tmp
                self.pos = _save10
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save7
            break
          end # end choice

          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save2
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("_")
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  emphasis a.join ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_EmphUl unless _tmp
    return _tmp
  end

  # Strong = (StrongStar | StrongUl)
  def _Strong

    _save = self.pos
    while true # choice
      _tmp = apply(:_StrongStar)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_StrongUl)
      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_Strong unless _tmp
    return _tmp
  end

  # StrongStar = "**" !@Whitespace @StartList:a (!"**" Inline:b { a << b })+ "**" { strong a.join }
  def _StrongStar

    _save = self.pos
    while true # sequence
      _tmp = match_string("**")
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _tmp = _Whitespace()
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _StartList()
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos

      _save3 = self.pos
      while true # sequence
        _save4 = self.pos
        _tmp = match_string("**")
        _tmp = _tmp ? nil : true
        self.pos = _save4
        unless _tmp
          self.pos = _save3
          break
        end
        _tmp = apply(:_Inline)
        b = @result
        unless _tmp
          self.pos = _save3
          break
        end
        @result = begin;  a << b ; end
        _tmp = true
        unless _tmp
          self.pos = _save3
        end
        break
      end # end sequence

      if _tmp
        while true

          _save5 = self.pos
          while true # sequence
            _save6 = self.pos
            _tmp = match_string("**")
            _tmp = _tmp ? nil : true
            self.pos = _save6
            unless _tmp
              self.pos = _save5
              break
            end
            _tmp = apply(:_Inline)
            b = @result
            unless _tmp
              self.pos = _save5
              break
            end
            @result = begin;  a << b ; end
            _tmp = true
            unless _tmp
              self.pos = _save5
            end
            break
          end # end sequence

          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save2
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("**")
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  strong a.join ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_StrongStar unless _tmp
    return _tmp
  end

  # StrongUl = "__" !@Whitespace @StartList:a (!"__" Inline:b { a << b })+ "__" { strong a.join }
  def _StrongUl

    _save = self.pos
    while true # sequence
      _tmp = match_string("__")
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _tmp = _Whitespace()
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _StartList()
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos

      _save3 = self.pos
      while true # sequence
        _save4 = self.pos
        _tmp = match_string("__")
        _tmp = _tmp ? nil : true
        self.pos = _save4
        unless _tmp
          self.pos = _save3
          break
        end
        _tmp = apply(:_Inline)
        b = @result
        unless _tmp
          self.pos = _save3
          break
        end
        @result = begin;  a << b ; end
        _tmp = true
        unless _tmp
          self.pos = _save3
        end
        break
      end # end sequence

      if _tmp
        while true

          _save5 = self.pos
          while true # sequence
            _save6 = self.pos
            _tmp = match_string("__")
            _tmp = _tmp ? nil : true
            self.pos = _save6
            unless _tmp
              self.pos = _save5
              break
            end
            _tmp = apply(:_Inline)
            b = @result
            unless _tmp
              self.pos = _save5
              break
            end
            @result = begin;  a << b ; end
            _tmp = true
            unless _tmp
              self.pos = _save5
            end
            break
          end # end sequence

          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save2
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("__")
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  strong a.join ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_StrongUl unless _tmp
    return _tmp
  end

  # Strike = &{ strike? } "~~" !@Whitespace @StartList:a (!"~~" Inline:b { a << b })+ "~~" { strike a.join }
  def _Strike

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = begin;  strike? ; end
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("~~")
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos
      _tmp = _Whitespace()
      _tmp = _tmp ? nil : true
      self.pos = _save2
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _StartList()
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save3 = self.pos

      _save4 = self.pos
      while true # sequence
        _save5 = self.pos
        _tmp = match_string("~~")
        _tmp = _tmp ? nil : true
        self.pos = _save5
        unless _tmp
          self.pos = _save4
          break
        end
        _tmp = apply(:_Inline)
        b = @result
        unless _tmp
          self.pos = _save4
          break
        end
        @result = begin;  a << b ; end
        _tmp = true
        unless _tmp
          self.pos = _save4
        end
        break
      end # end sequence

      if _tmp
        while true

          _save6 = self.pos
          while true # sequence
            _save7 = self.pos
            _tmp = match_string("~~")
            _tmp = _tmp ? nil : true
            self.pos = _save7
            unless _tmp
              self.pos = _save6
              break
            end
            _tmp = apply(:_Inline)
            b = @result
            unless _tmp
              self.pos = _save6
              break
            end
            @result = begin;  a << b ; end
            _tmp = true
            unless _tmp
              self.pos = _save6
            end
            break
          end # end sequence

          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save3
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("~~")
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  strike a.join ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Strike unless _tmp
    return _tmp
  end

  # Image = "!" (ExplicitLink | ReferenceLink):a { "rdoc-image:#{a[/\[(.*)\]/, 1]}" }
  def _Image

    _save = self.pos
    while true # sequence
      _tmp = match_string("!")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice
        _tmp = apply(:_ExplicitLink)
        break if _tmp
        self.pos = _save1
        _tmp = apply(:_ReferenceLink)
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  "rdoc-image:#{a[/\[(.*)\]/, 1]}" ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Image unless _tmp
    return _tmp
  end

  # Link = (ExplicitLink | ReferenceLink | AutoLink)
  def _Link

    _save = self.pos
    while true # choice
      _tmp = apply(:_ExplicitLink)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_ReferenceLink)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_AutoLink)
      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_Link unless _tmp
    return _tmp
  end

  # ReferenceLink = (ReferenceLinkDouble | ReferenceLinkSingle)
  def _ReferenceLink

    _save = self.pos
    while true # choice
      _tmp = apply(:_ReferenceLinkDouble)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_ReferenceLinkSingle)
      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_ReferenceLink unless _tmp
    return _tmp
  end

  # ReferenceLinkDouble = Label:content < Spnl > !"[]" Label:label { link_to content, label, text }
  def _ReferenceLinkDouble

    _save = self.pos
    while true # sequence
      _tmp = apply(:_Label)
      content = @result
      unless _tmp
        self.pos = _save
        break
      end
      _text_start = self.pos
      _tmp = apply(:_Spnl)
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _tmp = match_string("[]")
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Label)
      label = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  link_to content, label, text ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_ReferenceLinkDouble unless _tmp
    return _tmp
  end

  # ReferenceLinkSingle = Label:content < (Spnl "[]")? > { link_to content, content, text }
  def _ReferenceLinkSingle

    _save = self.pos
    while true # sequence
      _tmp = apply(:_Label)
      content = @result
      unless _tmp
        self.pos = _save
        break
      end
      _text_start = self.pos
      _save1 = self.pos

      _save2 = self.pos
      while true # sequence
        _tmp = apply(:_Spnl)
        unless _tmp
          self.pos = _save2
          break
        end
        _tmp = match_string("[]")
        unless _tmp
          self.pos = _save2
        end
        break
      end # end sequence

      unless _tmp
        _tmp = true
        self.pos = _save1
      end
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  link_to content, content, text ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_ReferenceLinkSingle unless _tmp
    return _tmp
  end

  # ExplicitLink = Label:l "(" @Sp Source:s Spnl Title @Sp ")" { "{#{l}}[#{s}]" }
  def _ExplicitLink

    _save = self.pos
    while true # sequence
      _tmp = apply(:_Label)
      l = @result
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("(")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Sp()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Source)
      s = @result
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Title)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Sp()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(")")
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  "{#{l}}[#{s}]" ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_ExplicitLink unless _tmp
    return _tmp
  end

  # Source = ("<" < SourceContents > ">" | < SourceContents >) { text }
  def _Source

    _save = self.pos
    while true # sequence

      _save1 = self.pos
      while true # choice

        _save2 = self.pos
        while true # sequence
          _tmp = match_string("<")
          unless _tmp
            self.pos = _save2
            break
          end
          _text_start = self.pos
          _tmp = apply(:_SourceContents)
          if _tmp
            text = get_text(_text_start)
          end
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = match_string(">")
          unless _tmp
            self.pos = _save2
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save1
        _text_start = self.pos
        _tmp = apply(:_SourceContents)
        if _tmp
          text = get_text(_text_start)
        end
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  text ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Source unless _tmp
    return _tmp
  end

  # SourceContents = ((!"(" !")" !">" Nonspacechar)+ | "(" SourceContents ")")*
  def _SourceContents
    while true

      _save1 = self.pos
      while true # choice
        _save2 = self.pos

        _save3 = self.pos
        while true # sequence
          _save4 = self.pos
          _tmp = match_string("(")
          _tmp = _tmp ? nil : true
          self.pos = _save4
          unless _tmp
            self.pos = _save3
            break
          end
          _save5 = self.pos
          _tmp = match_string(")")
          _tmp = _tmp ? nil : true
          self.pos = _save5
          unless _tmp
            self.pos = _save3
            break
          end
          _save6 = self.pos
          _tmp = match_string(">")
          _tmp = _tmp ? nil : true
          self.pos = _save6
          unless _tmp
            self.pos = _save3
            break
          end
          _tmp = apply(:_Nonspacechar)
          unless _tmp
            self.pos = _save3
          end
          break
        end # end sequence

        if _tmp
          while true

            _save7 = self.pos
            while true # sequence
              _save8 = self.pos
              _tmp = match_string("(")
              _tmp = _tmp ? nil : true
              self.pos = _save8
              unless _tmp
                self.pos = _save7
                break
              end
              _save9 = self.pos
              _tmp = match_string(")")
              _tmp = _tmp ? nil : true
              self.pos = _save9
              unless _tmp
                self.pos = _save7
                break
              end
              _save10 = self.pos
              _tmp = match_string(">")
              _tmp = _tmp ? nil : true
              self.pos = _save10
              unless _tmp
                self.pos = _save7
                break
              end
              _tmp = apply(:_Nonspacechar)
              unless _tmp
                self.pos = _save7
              end
              break
            end # end sequence

            break unless _tmp
          end
          _tmp = true
        else
          self.pos = _save2
        end
        break if _tmp
        self.pos = _save1

        _save11 = self.pos
        while true # sequence
          _tmp = match_string("(")
          unless _tmp
            self.pos = _save11
            break
          end
          _tmp = apply(:_SourceContents)
          unless _tmp
            self.pos = _save11
            break
          end
          _tmp = match_string(")")
          unless _tmp
            self.pos = _save11
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save1
        break
      end # end choice

      break unless _tmp
    end
    _tmp = true
    set_failed_rule :_SourceContents unless _tmp
    return _tmp
  end

  # Title = (TitleSingle | TitleDouble | ""):a { a }
  def _Title

    _save = self.pos
    while true # sequence

      _save1 = self.pos
      while true # choice
        _tmp = apply(:_TitleSingle)
        break if _tmp
        self.pos = _save1
        _tmp = apply(:_TitleDouble)
        break if _tmp
        self.pos = _save1
        _tmp = match_string("")
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  a ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Title unless _tmp
    return _tmp
  end

  # TitleSingle = "'" (!("'" @Sp (")" | @Newline)) .)* "'"
  def _TitleSingle

    _save = self.pos
    while true # sequence
      _tmp = match_string("'")
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # sequence
          _save3 = self.pos

          _save4 = self.pos
          while true # sequence
            _tmp = match_string("'")
            unless _tmp
              self.pos = _save4
              break
            end
            _tmp = _Sp()
            unless _tmp
              self.pos = _save4
              break
            end

            _save5 = self.pos
            while true # choice
              _tmp = match_string(")")
              break if _tmp
              self.pos = _save5
              _tmp = _Newline()
              break if _tmp
              self.pos = _save5
              break
            end # end choice

            unless _tmp
              self.pos = _save4
            end
            break
          end # end sequence

          _tmp = _tmp ? nil : true
          self.pos = _save3
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = get_byte
          unless _tmp
            self.pos = _save2
          end
          break
        end # end sequence

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("'")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_TitleSingle unless _tmp
    return _tmp
  end

  # TitleDouble = "\"" (!("\"" @Sp (")" | @Newline)) .)* "\""
  def _TitleDouble

    _save = self.pos
    while true # sequence
      _tmp = match_string("\"")
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # sequence
          _save3 = self.pos

          _save4 = self.pos
          while true # sequence
            _tmp = match_string("\"")
            unless _tmp
              self.pos = _save4
              break
            end
            _tmp = _Sp()
            unless _tmp
              self.pos = _save4
              break
            end

            _save5 = self.pos
            while true # choice
              _tmp = match_string(")")
              break if _tmp
              self.pos = _save5
              _tmp = _Newline()
              break if _tmp
              self.pos = _save5
              break
            end # end choice

            unless _tmp
              self.pos = _save4
            end
            break
          end # end sequence

          _tmp = _tmp ? nil : true
          self.pos = _save3
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = get_byte
          unless _tmp
            self.pos = _save2
          end
          break
        end # end sequence

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("\"")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_TitleDouble unless _tmp
    return _tmp
  end

  # AutoLink = (AutoLinkUrl | AutoLinkEmail)
  def _AutoLink

    _save = self.pos
    while true # choice
      _tmp = apply(:_AutoLinkUrl)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_AutoLinkEmail)
      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_AutoLink unless _tmp
    return _tmp
  end

  # AutoLinkUrl = "<" < /[A-Za-z]+/ "://" (!@Newline !">" .)+ > ">" { text }
  def _AutoLinkUrl

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _text_start = self.pos

      _save1 = self.pos
      while true # sequence
        _tmp = scan(/\G(?-mix:[A-Za-z]+)/)
        unless _tmp
          self.pos = _save1
          break
        end
        _tmp = match_string("://")
        unless _tmp
          self.pos = _save1
          break
        end
        _save2 = self.pos

        _save3 = self.pos
        while true # sequence
          _save4 = self.pos
          _tmp = _Newline()
          _tmp = _tmp ? nil : true
          self.pos = _save4
          unless _tmp
            self.pos = _save3
            break
          end
          _save5 = self.pos
          _tmp = match_string(">")
          _tmp = _tmp ? nil : true
          self.pos = _save5
          unless _tmp
            self.pos = _save3
            break
          end
          _tmp = get_byte
          unless _tmp
            self.pos = _save3
          end
          break
        end # end sequence

        if _tmp
          while true

            _save6 = self.pos
            while true # sequence
              _save7 = self.pos
              _tmp = _Newline()
              _tmp = _tmp ? nil : true
              self.pos = _save7
              unless _tmp
                self.pos = _save6
                break
              end
              _save8 = self.pos
              _tmp = match_string(">")
              _tmp = _tmp ? nil : true
              self.pos = _save8
              unless _tmp
                self.pos = _save6
                break
              end
              _tmp = get_byte
              unless _tmp
                self.pos = _save6
              end
              break
            end # end sequence

            break unless _tmp
          end
          _tmp = true
        else
          self.pos = _save2
        end
        unless _tmp
          self.pos = _save1
        end
        break
      end # end sequence

      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  text ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_AutoLinkUrl unless _tmp
    return _tmp
  end

  # AutoLinkEmail = "<" "mailto:"? < /[\w+.\/!%~$-]+/i "@" (!@Newline !">" .)+ > ">" { "mailto:#{text}" }
  def _AutoLinkEmail

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _tmp = match_string("mailto:")
      unless _tmp
        _tmp = true
        self.pos = _save1
      end
      unless _tmp
        self.pos = _save
        break
      end
      _text_start = self.pos

      _save2 = self.pos
      while true # sequence
        _tmp = scan(/\G(?i-mx:[\w+.\/!%~$-]+)/)
        unless _tmp
          self.pos = _save2
          break
        end
        _tmp = match_string("@")
        unless _tmp
          self.pos = _save2
          break
        end
        _save3 = self.pos

        _save4 = self.pos
        while true # sequence
          _save5 = self.pos
          _tmp = _Newline()
          _tmp = _tmp ? nil : true
          self.pos = _save5
          unless _tmp
            self.pos = _save4
            break
          end
          _save6 = self.pos
          _tmp = match_string(">")
          _tmp = _tmp ? nil : true
          self.pos = _save6
          unless _tmp
            self.pos = _save4
            break
          end
          _tmp = get_byte
          unless _tmp
            self.pos = _save4
          end
          break
        end # end sequence

        if _tmp
          while true

            _save7 = self.pos
            while true # sequence
              _save8 = self.pos
              _tmp = _Newline()
              _tmp = _tmp ? nil : true
              self.pos = _save8
              unless _tmp
                self.pos = _save7
                break
              end
              _save9 = self.pos
              _tmp = match_string(">")
              _tmp = _tmp ? nil : true
              self.pos = _save9
              unless _tmp
                self.pos = _save7
                break
              end
              _tmp = get_byte
              unless _tmp
                self.pos = _save7
              end
              break
            end # end sequence

            break unless _tmp
          end
          _tmp = true
        else
          self.pos = _save3
        end
        unless _tmp
          self.pos = _save2
        end
        break
      end # end sequence

      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  "mailto:#{text}" ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_AutoLinkEmail unless _tmp
    return _tmp
  end

  # Reference = @NonindentSpace !"[]" Label:label ":" Spnl RefSrc:link RefTitle @BlankLine+ { # TODO use title               reference label, link               nil             }
  def _Reference

    _save = self.pos
    while true # sequence
      _tmp = _NonindentSpace()
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _tmp = match_string("[]")
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Label)
      label = @result
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(":")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_RefSrc)
      link = @result
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_RefTitle)
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos
      _tmp = _BlankLine()
      if _tmp
        while true
          _tmp = _BlankLine()
          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save2
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  # TODO use title
              reference label, link
              nil
            ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Reference unless _tmp
    return _tmp
  end

  # Label = "[" (!"^" &{ notes? } | &. &{ !notes? }) @StartList:a (!"]" Inline:l { a << l })* "]" { a.join.gsub(/\s+/, ' ') }
  def _Label

    _save = self.pos
    while true # sequence
      _tmp = match_string("[")
      unless _tmp
        self.pos = _save
        break
      end

      _save1 = self.pos
      while true # choice

        _save2 = self.pos
        while true # sequence
          _save3 = self.pos
          _tmp = match_string("^")
          _tmp = _tmp ? nil : true
          self.pos = _save3
          unless _tmp
            self.pos = _save2
            break
          end
          _save4 = self.pos
          _tmp = begin;  notes? ; end
          self.pos = _save4
          unless _tmp
            self.pos = _save2
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save1

        _save5 = self.pos
        while true # sequence
          _save6 = self.pos
          _tmp = get_byte
          self.pos = _save6
          unless _tmp
            self.pos = _save5
            break
          end
          _save7 = self.pos
          _tmp = begin;  !notes? ; end
          self.pos = _save7
          unless _tmp
            self.pos = _save5
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _StartList()
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save9 = self.pos
        while true # sequence
          _save10 = self.pos
          _tmp = match_string("]")
          _tmp = _tmp ? nil : true
          self.pos = _save10
          unless _tmp
            self.pos = _save9
            break
          end
          _tmp = apply(:_Inline)
          l = @result
          unless _tmp
            self.pos = _save9
            break
          end
          @result = begin;  a << l ; end
          _tmp = true
          unless _tmp
            self.pos = _save9
          end
          break
        end # end sequence

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("]")
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  a.join.gsub(/\s+/, ' ') ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Label unless _tmp
    return _tmp
  end

  # RefSrc = < Nonspacechar+ > { text }
  def _RefSrc

    _save = self.pos
    while true # sequence
      _text_start = self.pos
      _save1 = self.pos
      _tmp = apply(:_Nonspacechar)
      if _tmp
        while true
          _tmp = apply(:_Nonspacechar)
          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save1
      end
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  text ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_RefSrc unless _tmp
    return _tmp
  end

  # RefTitle = (RefTitleSingle | RefTitleDouble | RefTitleParens | EmptyTitle)
  def _RefTitle

    _save = self.pos
    while true # choice
      _tmp = apply(:_RefTitleSingle)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_RefTitleDouble)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_RefTitleParens)
      break if _tmp
      self.pos = _save
      _tmp = apply(:_EmptyTitle)
      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_RefTitle unless _tmp
    return _tmp
  end

  # EmptyTitle = ""
  def _EmptyTitle
    _tmp = match_string("")
    set_failed_rule :_EmptyTitle unless _tmp
    return _tmp
  end

  # RefTitleSingle = Spnl "'" < (!("'" @Sp @Newline | @Newline) .)* > "'" { text }
  def _RefTitleSingle

    _save = self.pos
    while true # sequence
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("'")
      unless _tmp
        self.pos = _save
        break
      end
      _text_start = self.pos
      while true

        _save2 = self.pos
        while true # sequence
          _save3 = self.pos

          _save4 = self.pos
          while true # choice

            _save5 = self.pos
            while true # sequence
              _tmp = match_string("'")
              unless _tmp
                self.pos = _save5
                break
              end
              _tmp = _Sp()
              unless _tmp
                self.pos = _save5
                break
              end
              _tmp = _Newline()
              unless _tmp
                self.pos = _save5
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save4
            _tmp = _Newline()
            break if _tmp
            self.pos = _save4
            break
          end # end choice

          _tmp = _tmp ? nil : true
          self.pos = _save3
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = get_byte
          unless _tmp
            self.pos = _save2
          end
          break
        end # end sequence

        break unless _tmp
      end
      _tmp = true
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("'")
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  text ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_RefTitleSingle unless _tmp
    return _tmp
  end

  # RefTitleDouble = Spnl "\"" < (!("\"" @Sp @Newline | @Newline) .)* > "\"" { text }
  def _RefTitleDouble

    _save = self.pos
    while true # sequence
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("\"")
      unless _tmp
        self.pos = _save
        break
      end
      _text_start = self.pos
      while true

        _save2 = self.pos
        while true # sequence
          _save3 = self.pos

          _save4 = self.pos
          while true # choice

            _save5 = self.pos
            while true # sequence
              _tmp = match_string("\"")
              unless _tmp
                self.pos = _save5
                break
              end
              _tmp = _Sp()
              unless _tmp
                self.pos = _save5
                break
              end
              _tmp = _Newline()
              unless _tmp
                self.pos = _save5
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save4
            _tmp = _Newline()
            break if _tmp
            self.pos = _save4
            break
          end # end choice

          _tmp = _tmp ? nil : true
          self.pos = _save3
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = get_byte
          unless _tmp
            self.pos = _save2
          end
          break
        end # end sequence

        break unless _tmp
      end
      _tmp = true
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("\"")
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  text ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_RefTitleDouble unless _tmp
    return _tmp
  end

  # RefTitleParens = Spnl "(" < (!(")" @Sp @Newline | @Newline) .)* > ")" { text }
  def _RefTitleParens

    _save = self.pos
    while true # sequence
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("(")
      unless _tmp
        self.pos = _save
        break
      end
      _text_start = self.pos
      while true

        _save2 = self.pos
        while true # sequence
          _save3 = self.pos

          _save4 = self.pos
          while true # choice

            _save5 = self.pos
            while true # sequence
              _tmp = match_string(")")
              unless _tmp
                self.pos = _save5
                break
              end
              _tmp = _Sp()
              unless _tmp
                self.pos = _save5
                break
              end
              _tmp = _Newline()
              unless _tmp
                self.pos = _save5
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save4
            _tmp = _Newline()
            break if _tmp
            self.pos = _save4
            break
          end # end choice

          _tmp = _tmp ? nil : true
          self.pos = _save3
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = get_byte
          unless _tmp
            self.pos = _save2
          end
          break
        end # end sequence

        break unless _tmp
      end
      _tmp = true
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(")")
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  text ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_RefTitleParens unless _tmp
    return _tmp
  end

  # References = (Reference | SkipBlock)*
  def _References
    while true

      _save1 = self.pos
      while true # choice
        _tmp = apply(:_Reference)
        break if _tmp
        self.pos = _save1
        _tmp = apply(:_SkipBlock)
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      break unless _tmp
    end
    _tmp = true
    set_failed_rule :_References unless _tmp
    return _tmp
  end

  # Ticks1 = "`" !"`"
  def _Ticks1

    _save = self.pos
    while true # sequence
      _tmp = match_string("`")
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _tmp = match_string("`")
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Ticks1 unless _tmp
    return _tmp
  end

  # Ticks2 = "``" !"`"
  def _Ticks2

    _save = self.pos
    while true # sequence
      _tmp = match_string("``")
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _tmp = match_string("`")
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Ticks2 unless _tmp
    return _tmp
  end

  # Ticks3 = "```" !"`"
  def _Ticks3

    _save = self.pos
    while true # sequence
      _tmp = match_string("```")
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _tmp = match_string("`")
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Ticks3 unless _tmp
    return _tmp
  end

  # Ticks4 = "````" !"`"
  def _Ticks4

    _save = self.pos
    while true # sequence
      _tmp = match_string("````")
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _tmp = match_string("`")
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Ticks4 unless _tmp
    return _tmp
  end

  # Ticks5 = "`````" !"`"
  def _Ticks5

    _save = self.pos
    while true # sequence
      _tmp = match_string("`````")
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _tmp = match_string("`")
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Ticks5 unless _tmp
    return _tmp
  end

  # Code = (Ticks1 @Sp < ((!"`" Nonspacechar)+ | !Ticks1 /`+/ | !(@Sp Ticks1) (@Spacechar | @Newline !@BlankLine))+ > @Sp Ticks1 | Ticks2 @Sp < ((!"`" Nonspacechar)+ | !Ticks2 /`+/ | !(@Sp Ticks2) (@Spacechar | @Newline !@BlankLine))+ > @Sp Ticks2 | Ticks3 @Sp < ((!"`" Nonspacechar)+ | !Ticks3 /`+/ | !(@Sp Ticks3) (@Spacechar | @Newline !@BlankLine))+ > @Sp Ticks3 | Ticks4 @Sp < ((!"`" Nonspacechar)+ | !Ticks4 /`+/ | !(@Sp Ticks4) (@Spacechar | @Newline !@BlankLine))+ > @Sp Ticks4 | Ticks5 @Sp < ((!"`" Nonspacechar)+ | !Ticks5 /`+/ | !(@Sp Ticks5) (@Spacechar | @Newline !@BlankLine))+ > @Sp Ticks5) { "<code>#{text}</code>" }
  def _Code

    _save = self.pos
    while true # sequence

      _save1 = self.pos
      while true # choice

        _save2 = self.pos
        while true # sequence
          _tmp = apply(:_Ticks1)
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = _Sp()
          unless _tmp
            self.pos = _save2
            break
          end
          _text_start = self.pos
          _save3 = self.pos

          _save4 = self.pos
          while true # choice
            _save5 = self.pos

            _save6 = self.pos
            while true # sequence
              _save7 = self.pos
              _tmp = match_string("`")
              _tmp = _tmp ? nil : true
              self.pos = _save7
              unless _tmp
                self.pos = _save6
                break
              end
              _tmp = apply(:_Nonspacechar)
              unless _tmp
                self.pos = _save6
              end
              break
            end # end sequence

            if _tmp
              while true

                _save8 = self.pos
                while true # sequence
                  _save9 = self.pos
                  _tmp = match_string("`")
                  _tmp = _tmp ? nil : true
                  self.pos = _save9
                  unless _tmp
                    self.pos = _save8
                    break
                  end
                  _tmp = apply(:_Nonspacechar)
                  unless _tmp
                    self.pos = _save8
                  end
                  break
                end # end sequence

                break unless _tmp
              end
              _tmp = true
            else
              self.pos = _save5
            end
            break if _tmp
            self.pos = _save4

            _save10 = self.pos
            while true # sequence
              _save11 = self.pos
              _tmp = apply(:_Ticks1)
              _tmp = _tmp ? nil : true
              self.pos = _save11
              unless _tmp
                self.pos = _save10
                break
              end
              _tmp = scan(/\G(?-mix:`+)/)
              unless _tmp
                self.pos = _save10
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save4

            _save12 = self.pos
            while true # sequence
              _save13 = self.pos

              _save14 = self.pos
              while true # sequence
                _tmp = _Sp()
                unless _tmp
                  self.pos = _save14
                  break
                end
                _tmp = apply(:_Ticks1)
                unless _tmp
                  self.pos = _save14
                end
                break
              end # end sequence

              _tmp = _tmp ? nil : true
              self.pos = _save13
              unless _tmp
                self.pos = _save12
                break
              end

              _save15 = self.pos
              while true # choice
                _tmp = _Spacechar()
                break if _tmp
                self.pos = _save15

                _save16 = self.pos
                while true # sequence
                  _tmp = _Newline()
                  unless _tmp
                    self.pos = _save16
                    break
                  end
                  _save17 = self.pos
                  _tmp = _BlankLine()
                  _tmp = _tmp ? nil : true
                  self.pos = _save17
                  unless _tmp
                    self.pos = _save16
                  end
                  break
                end # end sequence

                break if _tmp
                self.pos = _save15
                break
              end # end choice

              unless _tmp
                self.pos = _save12
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save4
            break
          end # end choice

          if _tmp
            while true

              _save18 = self.pos
              while true # choice
                _save19 = self.pos

                _save20 = self.pos
                while true # sequence
                  _save21 = self.pos
                  _tmp = match_string("`")
                  _tmp = _tmp ? nil : true
                  self.pos = _save21
                  unless _tmp
                    self.pos = _save20
                    break
                  end
                  _tmp = apply(:_Nonspacechar)
                  unless _tmp
                    self.pos = _save20
                  end
                  break
                end # end sequence

                if _tmp
                  while true

                    _save22 = self.pos
                    while true # sequence
                      _save23 = self.pos
                      _tmp = match_string("`")
                      _tmp = _tmp ? nil : true
                      self.pos = _save23
                      unless _tmp
                        self.pos = _save22
                        break
                      end
                      _tmp = apply(:_Nonspacechar)
                      unless _tmp
                        self.pos = _save22
                      end
                      break
                    end # end sequence

                    break unless _tmp
                  end
                  _tmp = true
                else
                  self.pos = _save19
                end
                break if _tmp
                self.pos = _save18

                _save24 = self.pos
                while true # sequence
                  _save25 = self.pos
                  _tmp = apply(:_Ticks1)
                  _tmp = _tmp ? nil : true
                  self.pos = _save25
                  unless _tmp
                    self.pos = _save24
                    break
                  end
                  _tmp = scan(/\G(?-mix:`+)/)
                  unless _tmp
                    self.pos = _save24
                  end
                  break
                end # end sequence

                break if _tmp
                self.pos = _save18

                _save26 = self.pos
                while true # sequence
                  _save27 = self.pos

                  _save28 = self.pos
                  while true # sequence
                    _tmp = _Sp()
                    unless _tmp
                      self.pos = _save28
                      break
                    end
                    _tmp = apply(:_Ticks1)
                    unless _tmp
                      self.pos = _save28
                    end
                    break
                  end # end sequence

                  _tmp = _tmp ? nil : true
                  self.pos = _save27
                  unless _tmp
                    self.pos = _save26
                    break
                  end

                  _save29 = self.pos
                  while true # choice
                    _tmp = _Spacechar()
                    break if _tmp
                    self.pos = _save29

                    _save30 = self.pos
                    while true # sequence
                      _tmp = _Newline()
                      unless _tmp
                        self.pos = _save30
                        break
                      end
                      _save31 = self.pos
                      _tmp = _BlankLine()
                      _tmp = _tmp ? nil : true
                      self.pos = _save31
                      unless _tmp
                        self.pos = _save30
                      end
                      break
                    end # end sequence

                    break if _tmp
                    self.pos = _save29
                    break
                  end # end choice

                  unless _tmp
                    self.pos = _save26
                  end
                  break
                end # end sequence

                break if _tmp
                self.pos = _save18
                break
              end # end choice

              break unless _tmp
            end
            _tmp = true
          else
            self.pos = _save3
          end
          if _tmp
            text = get_text(_text_start)
          end
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = _Sp()
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = apply(:_Ticks1)
          unless _tmp
            self.pos = _save2
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save1

        _save32 = self.pos
        while true # sequence
          _tmp = apply(:_Ticks2)
          unless _tmp
            self.pos = _save32
            break
          end
          _tmp = _Sp()
          unless _tmp
            self.pos = _save32
            break
          end
          _text_start = self.pos
          _save33 = self.pos

          _save34 = self.pos
          while true # choice
            _save35 = self.pos

            _save36 = self.pos
            while true # sequence
              _save37 = self.pos
              _tmp = match_string("`")
              _tmp = _tmp ? nil : true
              self.pos = _save37
              unless _tmp
                self.pos = _save36
                break
              end
              _tmp = apply(:_Nonspacechar)
              unless _tmp
                self.pos = _save36
              end
              break
            end # end sequence

            if _tmp
              while true

                _save38 = self.pos
                while true # sequence
                  _save39 = self.pos
                  _tmp = match_string("`")
                  _tmp = _tmp ? nil : true
                  self.pos = _save39
                  unless _tmp
                    self.pos = _save38
                    break
                  end
                  _tmp = apply(:_Nonspacechar)
                  unless _tmp
                    self.pos = _save38
                  end
                  break
                end # end sequence

                break unless _tmp
              end
              _tmp = true
            else
              self.pos = _save35
            end
            break if _tmp
            self.pos = _save34

            _save40 = self.pos
            while true # sequence
              _save41 = self.pos
              _tmp = apply(:_Ticks2)
              _tmp = _tmp ? nil : true
              self.pos = _save41
              unless _tmp
                self.pos = _save40
                break
              end
              _tmp = scan(/\G(?-mix:`+)/)
              unless _tmp
                self.pos = _save40
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save34

            _save42 = self.pos
            while true # sequence
              _save43 = self.pos

              _save44 = self.pos
              while true # sequence
                _tmp = _Sp()
                unless _tmp
                  self.pos = _save44
                  break
                end
                _tmp = apply(:_Ticks2)
                unless _tmp
                  self.pos = _save44
                end
                break
              end # end sequence

              _tmp = _tmp ? nil : true
              self.pos = _save43
              unless _tmp
                self.pos = _save42
                break
              end

              _save45 = self.pos
              while true # choice
                _tmp = _Spacechar()
                break if _tmp
                self.pos = _save45

                _save46 = self.pos
                while true # sequence
                  _tmp = _Newline()
                  unless _tmp
                    self.pos = _save46
                    break
                  end
                  _save47 = self.pos
                  _tmp = _BlankLine()
                  _tmp = _tmp ? nil : true
                  self.pos = _save47
                  unless _tmp
                    self.pos = _save46
                  end
                  break
                end # end sequence

                break if _tmp
                self.pos = _save45
                break
              end # end choice

              unless _tmp
                self.pos = _save42
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save34
            break
          end # end choice

          if _tmp
            while true

              _save48 = self.pos
              while true # choice
                _save49 = self.pos

                _save50 = self.pos
                while true # sequence
                  _save51 = self.pos
                  _tmp = match_string("`")
                  _tmp = _tmp ? nil : true
                  self.pos = _save51
                  unless _tmp
                    self.pos = _save50
                    break
                  end
                  _tmp = apply(:_Nonspacechar)
                  unless _tmp
                    self.pos = _save50
                  end
                  break
                end # end sequence

                if _tmp
                  while true

                    _save52 = self.pos
                    while true # sequence
                      _save53 = self.pos
                      _tmp = match_string("`")
                      _tmp = _tmp ? nil : true
                      self.pos = _save53
                      unless _tmp
                        self.pos = _save52
                        break
                      end
                      _tmp = apply(:_Nonspacechar)
                      unless _tmp
                        self.pos = _save52
                      end
                      break
                    end # end sequence

                    break unless _tmp
                  end
                  _tmp = true
                else
                  self.pos = _save49
                end
                break if _tmp
                self.pos = _save48

                _save54 = self.pos
                while true # sequence
                  _save55 = self.pos
                  _tmp = apply(:_Ticks2)
                  _tmp = _tmp ? nil : true
                  self.pos = _save55
                  unless _tmp
                    self.pos = _save54
                    break
                  end
                  _tmp = scan(/\G(?-mix:`+)/)
                  unless _tmp
                    self.pos = _save54
                  end
                  break
                end # end sequence

                break if _tmp
                self.pos = _save48

                _save56 = self.pos
                while true # sequence
                  _save57 = self.pos

                  _save58 = self.pos
                  while true # sequence
                    _tmp = _Sp()
                    unless _tmp
                      self.pos = _save58
                      break
                    end
                    _tmp = apply(:_Ticks2)
                    unless _tmp
                      self.pos = _save58
                    end
                    break
                  end # end sequence

                  _tmp = _tmp ? nil : true
                  self.pos = _save57
                  unless _tmp
                    self.pos = _save56
                    break
                  end

                  _save59 = self.pos
                  while true # choice
                    _tmp = _Spacechar()
                    break if _tmp
                    self.pos = _save59

                    _save60 = self.pos
                    while true # sequence
                      _tmp = _Newline()
                      unless _tmp
                        self.pos = _save60
                        break
                      end
                      _save61 = self.pos
                      _tmp = _BlankLine()
                      _tmp = _tmp ? nil : true
                      self.pos = _save61
                      unless _tmp
                        self.pos = _save60
                      end
                      break
                    end # end sequence

                    break if _tmp
                    self.pos = _save59
                    break
                  end # end choice

                  unless _tmp
                    self.pos = _save56
                  end
                  break
                end # end sequence

                break if _tmp
                self.pos = _save48
                break
              end # end choice

              break unless _tmp
            end
            _tmp = true
          else
            self.pos = _save33
          end
          if _tmp
            text = get_text(_text_start)
          end
          unless _tmp
            self.pos = _save32
            break
          end
          _tmp = _Sp()
          unless _tmp
            self.pos = _save32
            break
          end
          _tmp = apply(:_Ticks2)
          unless _tmp
            self.pos = _save32
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save1

        _save62 = self.pos
        while true # sequence
          _tmp = apply(:_Ticks3)
          unless _tmp
            self.pos = _save62
            break
          end
          _tmp = _Sp()
          unless _tmp
            self.pos = _save62
            break
          end
          _text_start = self.pos
          _save63 = self.pos

          _save64 = self.pos
          while true # choice
            _save65 = self.pos

            _save66 = self.pos
            while true # sequence
              _save67 = self.pos
              _tmp = match_string("`")
              _tmp = _tmp ? nil : true
              self.pos = _save67
              unless _tmp
                self.pos = _save66
                break
              end
              _tmp = apply(:_Nonspacechar)
              unless _tmp
                self.pos = _save66
              end
              break
            end # end sequence

            if _tmp
              while true

                _save68 = self.pos
                while true # sequence
                  _save69 = self.pos
                  _tmp = match_string("`")
                  _tmp = _tmp ? nil : true
                  self.pos = _save69
                  unless _tmp
                    self.pos = _save68
                    break
                  end
                  _tmp = apply(:_Nonspacechar)
                  unless _tmp
                    self.pos = _save68
                  end
                  break
                end # end sequence

                break unless _tmp
              end
              _tmp = true
            else
              self.pos = _save65
            end
            break if _tmp
            self.pos = _save64

            _save70 = self.pos
            while true # sequence
              _save71 = self.pos
              _tmp = apply(:_Ticks3)
              _tmp = _tmp ? nil : true
              self.pos = _save71
              unless _tmp
                self.pos = _save70
                break
              end
              _tmp = scan(/\G(?-mix:`+)/)
              unless _tmp
                self.pos = _save70
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save64

            _save72 = self.pos
            while true # sequence
              _save73 = self.pos

              _save74 = self.pos
              while true # sequence
                _tmp = _Sp()
                unless _tmp
                  self.pos = _save74
                  break
                end
                _tmp = apply(:_Ticks3)
                unless _tmp
                  self.pos = _save74
                end
                break
              end # end sequence

              _tmp = _tmp ? nil : true
              self.pos = _save73
              unless _tmp
                self.pos = _save72
                break
              end

              _save75 = self.pos
              while true # choice
                _tmp = _Spacechar()
                break if _tmp
                self.pos = _save75

                _save76 = self.pos
                while true # sequence
                  _tmp = _Newline()
                  unless _tmp
                    self.pos = _save76
                    break
                  end
                  _save77 = self.pos
                  _tmp = _BlankLine()
                  _tmp = _tmp ? nil : true
                  self.pos = _save77
                  unless _tmp
                    self.pos = _save76
                  end
                  break
                end # end sequence

                break if _tmp
                self.pos = _save75
                break
              end # end choice

              unless _tmp
                self.pos = _save72
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save64
            break
          end # end choice

          if _tmp
            while true

              _save78 = self.pos
              while true # choice
                _save79 = self.pos

                _save80 = self.pos
                while true # sequence
                  _save81 = self.pos
                  _tmp = match_string("`")
                  _tmp = _tmp ? nil : true
                  self.pos = _save81
                  unless _tmp
                    self.pos = _save80
                    break
                  end
                  _tmp = apply(:_Nonspacechar)
                  unless _tmp
                    self.pos = _save80
                  end
                  break
                end # end sequence

                if _tmp
                  while true

                    _save82 = self.pos
                    while true # sequence
                      _save83 = self.pos
                      _tmp = match_string("`")
                      _tmp = _tmp ? nil : true
                      self.pos = _save83
                      unless _tmp
                        self.pos = _save82
                        break
                      end
                      _tmp = apply(:_Nonspacechar)
                      unless _tmp
                        self.pos = _save82
                      end
                      break
                    end # end sequence

                    break unless _tmp
                  end
                  _tmp = true
                else
                  self.pos = _save79
                end
                break if _tmp
                self.pos = _save78

                _save84 = self.pos
                while true # sequence
                  _save85 = self.pos
                  _tmp = apply(:_Ticks3)
                  _tmp = _tmp ? nil : true
                  self.pos = _save85
                  unless _tmp
                    self.pos = _save84
                    break
                  end
                  _tmp = scan(/\G(?-mix:`+)/)
                  unless _tmp
                    self.pos = _save84
                  end
                  break
                end # end sequence

                break if _tmp
                self.pos = _save78

                _save86 = self.pos
                while true # sequence
                  _save87 = self.pos

                  _save88 = self.pos
                  while true # sequence
                    _tmp = _Sp()
                    unless _tmp
                      self.pos = _save88
                      break
                    end
                    _tmp = apply(:_Ticks3)
                    unless _tmp
                      self.pos = _save88
                    end
                    break
                  end # end sequence

                  _tmp = _tmp ? nil : true
                  self.pos = _save87
                  unless _tmp
                    self.pos = _save86
                    break
                  end

                  _save89 = self.pos
                  while true # choice
                    _tmp = _Spacechar()
                    break if _tmp
                    self.pos = _save89

                    _save90 = self.pos
                    while true # sequence
                      _tmp = _Newline()
                      unless _tmp
                        self.pos = _save90
                        break
                      end
                      _save91 = self.pos
                      _tmp = _BlankLine()
                      _tmp = _tmp ? nil : true
                      self.pos = _save91
                      unless _tmp
                        self.pos = _save90
                      end
                      break
                    end # end sequence

                    break if _tmp
                    self.pos = _save89
                    break
                  end # end choice

                  unless _tmp
                    self.pos = _save86
                  end
                  break
                end # end sequence

                break if _tmp
                self.pos = _save78
                break
              end # end choice

              break unless _tmp
            end
            _tmp = true
          else
            self.pos = _save63
          end
          if _tmp
            text = get_text(_text_start)
          end
          unless _tmp
            self.pos = _save62
            break
          end
          _tmp = _Sp()
          unless _tmp
            self.pos = _save62
            break
          end
          _tmp = apply(:_Ticks3)
          unless _tmp
            self.pos = _save62
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save1

        _save92 = self.pos
        while true # sequence
          _tmp = apply(:_Ticks4)
          unless _tmp
            self.pos = _save92
            break
          end
          _tmp = _Sp()
          unless _tmp
            self.pos = _save92
            break
          end
          _text_start = self.pos
          _save93 = self.pos

          _save94 = self.pos
          while true # choice
            _save95 = self.pos

            _save96 = self.pos
            while true # sequence
              _save97 = self.pos
              _tmp = match_string("`")
              _tmp = _tmp ? nil : true
              self.pos = _save97
              unless _tmp
                self.pos = _save96
                break
              end
              _tmp = apply(:_Nonspacechar)
              unless _tmp
                self.pos = _save96
              end
              break
            end # end sequence

            if _tmp
              while true

                _save98 = self.pos
                while true # sequence
                  _save99 = self.pos
                  _tmp = match_string("`")
                  _tmp = _tmp ? nil : true
                  self.pos = _save99
                  unless _tmp
                    self.pos = _save98
                    break
                  end
                  _tmp = apply(:_Nonspacechar)
                  unless _tmp
                    self.pos = _save98
                  end
                  break
                end # end sequence

                break unless _tmp
              end
              _tmp = true
            else
              self.pos = _save95
            end
            break if _tmp
            self.pos = _save94

            _save100 = self.pos
            while true # sequence
              _save101 = self.pos
              _tmp = apply(:_Ticks4)
              _tmp = _tmp ? nil : true
              self.pos = _save101
              unless _tmp
                self.pos = _save100
                break
              end
              _tmp = scan(/\G(?-mix:`+)/)
              unless _tmp
                self.pos = _save100
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save94

            _save102 = self.pos
            while true # sequence
              _save103 = self.pos

              _save104 = self.pos
              while true # sequence
                _tmp = _Sp()
                unless _tmp
                  self.pos = _save104
                  break
                end
                _tmp = apply(:_Ticks4)
                unless _tmp
                  self.pos = _save104
                end
                break
              end # end sequence

              _tmp = _tmp ? nil : true
              self.pos = _save103
              unless _tmp
                self.pos = _save102
                break
              end

              _save105 = self.pos
              while true # choice
                _tmp = _Spacechar()
                break if _tmp
                self.pos = _save105

                _save106 = self.pos
                while true # sequence
                  _tmp = _Newline()
                  unless _tmp
                    self.pos = _save106
                    break
                  end
                  _save107 = self.pos
                  _tmp = _BlankLine()
                  _tmp = _tmp ? nil : true
                  self.pos = _save107
                  unless _tmp
                    self.pos = _save106
                  end
                  break
                end # end sequence

                break if _tmp
                self.pos = _save105
                break
              end # end choice

              unless _tmp
                self.pos = _save102
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save94
            break
          end # end choice

          if _tmp
            while true

              _save108 = self.pos
              while true # choice
                _save109 = self.pos

                _save110 = self.pos
                while true # sequence
                  _save111 = self.pos
                  _tmp = match_string("`")
                  _tmp = _tmp ? nil : true
                  self.pos = _save111
                  unless _tmp
                    self.pos = _save110
                    break
                  end
                  _tmp = apply(:_Nonspacechar)
                  unless _tmp
                    self.pos = _save110
                  end
                  break
                end # end sequence

                if _tmp
                  while true

                    _save112 = self.pos
                    while true # sequence
                      _save113 = self.pos
                      _tmp = match_string("`")
                      _tmp = _tmp ? nil : true
                      self.pos = _save113
                      unless _tmp
                        self.pos = _save112
                        break
                      end
                      _tmp = apply(:_Nonspacechar)
                      unless _tmp
                        self.pos = _save112
                      end
                      break
                    end # end sequence

                    break unless _tmp
                  end
                  _tmp = true
                else
                  self.pos = _save109
                end
                break if _tmp
                self.pos = _save108

                _save114 = self.pos
                while true # sequence
                  _save115 = self.pos
                  _tmp = apply(:_Ticks4)
                  _tmp = _tmp ? nil : true
                  self.pos = _save115
                  unless _tmp
                    self.pos = _save114
                    break
                  end
                  _tmp = scan(/\G(?-mix:`+)/)
                  unless _tmp
                    self.pos = _save114
                  end
                  break
                end # end sequence

                break if _tmp
                self.pos = _save108

                _save116 = self.pos
                while true # sequence
                  _save117 = self.pos

                  _save118 = self.pos
                  while true # sequence
                    _tmp = _Sp()
                    unless _tmp
                      self.pos = _save118
                      break
                    end
                    _tmp = apply(:_Ticks4)
                    unless _tmp
                      self.pos = _save118
                    end
                    break
                  end # end sequence

                  _tmp = _tmp ? nil : true
                  self.pos = _save117
                  unless _tmp
                    self.pos = _save116
                    break
                  end

                  _save119 = self.pos
                  while true # choice
                    _tmp = _Spacechar()
                    break if _tmp
                    self.pos = _save119

                    _save120 = self.pos
                    while true # sequence
                      _tmp = _Newline()
                      unless _tmp
                        self.pos = _save120
                        break
                      end
                      _save121 = self.pos
                      _tmp = _BlankLine()
                      _tmp = _tmp ? nil : true
                      self.pos = _save121
                      unless _tmp
                        self.pos = _save120
                      end
                      break
                    end # end sequence

                    break if _tmp
                    self.pos = _save119
                    break
                  end # end choice

                  unless _tmp
                    self.pos = _save116
                  end
                  break
                end # end sequence

                break if _tmp
                self.pos = _save108
                break
              end # end choice

              break unless _tmp
            end
            _tmp = true
          else
            self.pos = _save93
          end
          if _tmp
            text = get_text(_text_start)
          end
          unless _tmp
            self.pos = _save92
            break
          end
          _tmp = _Sp()
          unless _tmp
            self.pos = _save92
            break
          end
          _tmp = apply(:_Ticks4)
          unless _tmp
            self.pos = _save92
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save1

        _save122 = self.pos
        while true # sequence
          _tmp = apply(:_Ticks5)
          unless _tmp
            self.pos = _save122
            break
          end
          _tmp = _Sp()
          unless _tmp
            self.pos = _save122
            break
          end
          _text_start = self.pos
          _save123 = self.pos

          _save124 = self.pos
          while true # choice
            _save125 = self.pos

            _save126 = self.pos
            while true # sequence
              _save127 = self.pos
              _tmp = match_string("`")
              _tmp = _tmp ? nil : true
              self.pos = _save127
              unless _tmp
                self.pos = _save126
                break
              end
              _tmp = apply(:_Nonspacechar)
              unless _tmp
                self.pos = _save126
              end
              break
            end # end sequence

            if _tmp
              while true

                _save128 = self.pos
                while true # sequence
                  _save129 = self.pos
                  _tmp = match_string("`")
                  _tmp = _tmp ? nil : true
                  self.pos = _save129
                  unless _tmp
                    self.pos = _save128
                    break
                  end
                  _tmp = apply(:_Nonspacechar)
                  unless _tmp
                    self.pos = _save128
                  end
                  break
                end # end sequence

                break unless _tmp
              end
              _tmp = true
            else
              self.pos = _save125
            end
            break if _tmp
            self.pos = _save124

            _save130 = self.pos
            while true # sequence
              _save131 = self.pos
              _tmp = apply(:_Ticks5)
              _tmp = _tmp ? nil : true
              self.pos = _save131
              unless _tmp
                self.pos = _save130
                break
              end
              _tmp = scan(/\G(?-mix:`+)/)
              unless _tmp
                self.pos = _save130
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save124

            _save132 = self.pos
            while true # sequence
              _save133 = self.pos

              _save134 = self.pos
              while true # sequence
                _tmp = _Sp()
                unless _tmp
                  self.pos = _save134
                  break
                end
                _tmp = apply(:_Ticks5)
                unless _tmp
                  self.pos = _save134
                end
                break
              end # end sequence

              _tmp = _tmp ? nil : true
              self.pos = _save133
              unless _tmp
                self.pos = _save132
                break
              end

              _save135 = self.pos
              while true # choice
                _tmp = _Spacechar()
                break if _tmp
                self.pos = _save135

                _save136 = self.pos
                while true # sequence
                  _tmp = _Newline()
                  unless _tmp
                    self.pos = _save136
                    break
                  end
                  _save137 = self.pos
                  _tmp = _BlankLine()
                  _tmp = _tmp ? nil : true
                  self.pos = _save137
                  unless _tmp
                    self.pos = _save136
                  end
                  break
                end # end sequence

                break if _tmp
                self.pos = _save135
                break
              end # end choice

              unless _tmp
                self.pos = _save132
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save124
            break
          end # end choice

          if _tmp
            while true

              _save138 = self.pos
              while true # choice
                _save139 = self.pos

                _save140 = self.pos
                while true # sequence
                  _save141 = self.pos
                  _tmp = match_string("`")
                  _tmp = _tmp ? nil : true
                  self.pos = _save141
                  unless _tmp
                    self.pos = _save140
                    break
                  end
                  _tmp = apply(:_Nonspacechar)
                  unless _tmp
                    self.pos = _save140
                  end
                  break
                end # end sequence

                if _tmp
                  while true

                    _save142 = self.pos
                    while true # sequence
                      _save143 = self.pos
                      _tmp = match_string("`")
                      _tmp = _tmp ? nil : true
                      self.pos = _save143
                      unless _tmp
                        self.pos = _save142
                        break
                      end
                      _tmp = apply(:_Nonspacechar)
                      unless _tmp
                        self.pos = _save142
                      end
                      break
                    end # end sequence

                    break unless _tmp
                  end
                  _tmp = true
                else
                  self.pos = _save139
                end
                break if _tmp
                self.pos = _save138

                _save144 = self.pos
                while true # sequence
                  _save145 = self.pos
                  _tmp = apply(:_Ticks5)
                  _tmp = _tmp ? nil : true
                  self.pos = _save145
                  unless _tmp
                    self.pos = _save144
                    break
                  end
                  _tmp = scan(/\G(?-mix:`+)/)
                  unless _tmp
                    self.pos = _save144
                  end
                  break
                end # end sequence

                break if _tmp
                self.pos = _save138

                _save146 = self.pos
                while true # sequence
                  _save147 = self.pos

                  _save148 = self.pos
                  while true # sequence
                    _tmp = _Sp()
                    unless _tmp
                      self.pos = _save148
                      break
                    end
                    _tmp = apply(:_Ticks5)
                    unless _tmp
                      self.pos = _save148
                    end
                    break
                  end # end sequence

                  _tmp = _tmp ? nil : true
                  self.pos = _save147
                  unless _tmp
                    self.pos = _save146
                    break
                  end

                  _save149 = self.pos
                  while true # choice
                    _tmp = _Spacechar()
                    break if _tmp
                    self.pos = _save149

                    _save150 = self.pos
                    while true # sequence
                      _tmp = _Newline()
                      unless _tmp
                        self.pos = _save150
                        break
                      end
                      _save151 = self.pos
                      _tmp = _BlankLine()
                      _tmp = _tmp ? nil : true
                      self.pos = _save151
                      unless _tmp
                        self.pos = _save150
                      end
                      break
                    end # end sequence

                    break if _tmp
                    self.pos = _save149
                    break
                  end # end choice

                  unless _tmp
                    self.pos = _save146
                  end
                  break
                end # end sequence

                break if _tmp
                self.pos = _save138
                break
              end # end choice

              break unless _tmp
            end
            _tmp = true
          else
            self.pos = _save123
          end
          if _tmp
            text = get_text(_text_start)
          end
          unless _tmp
            self.pos = _save122
            break
          end
          _tmp = _Sp()
          unless _tmp
            self.pos = _save122
            break
          end
          _tmp = apply(:_Ticks5)
          unless _tmp
            self.pos = _save122
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  "<code>#{text}</code>" ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Code unless _tmp
    return _tmp
  end

  # RawHtml = < (HtmlComment | HtmlBlockScript | HtmlTag) > { if html? then text else '' end }
  def _RawHtml

    _save = self.pos
    while true # sequence
      _text_start = self.pos

      _save1 = self.pos
      while true # choice
        _tmp = apply(:_HtmlComment)
        break if _tmp
        self.pos = _save1
        _tmp = apply(:_HtmlBlockScript)
        break if _tmp
        self.pos = _save1
        _tmp = apply(:_HtmlTag)
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  if html? then text else '' end ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_RawHtml unless _tmp
    return _tmp
  end

  # BlankLine = @Sp @Newline { "\n" }
  def _BlankLine

    _save = self.pos
    while true # sequence
      _tmp = _Sp()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Newline()
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  "\n" ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_BlankLine unless _tmp
    return _tmp
  end

  # Quoted = ("\"" (!"\"" .)* "\"" | "'" (!"'" .)* "'")
  def _Quoted

    _save = self.pos
    while true # choice

      _save1 = self.pos
      while true # sequence
        _tmp = match_string("\"")
        unless _tmp
          self.pos = _save1
          break
        end
        while true

          _save3 = self.pos
          while true # sequence
            _save4 = self.pos
            _tmp = match_string("\"")
            _tmp = _tmp ? nil : true
            self.pos = _save4
            unless _tmp
              self.pos = _save3
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save3
            end
            break
          end # end sequence

          break unless _tmp
        end
        _tmp = true
        unless _tmp
          self.pos = _save1
          break
        end
        _tmp = match_string("\"")
        unless _tmp
          self.pos = _save1
        end
        break
      end # end sequence

      break if _tmp
      self.pos = _save

      _save5 = self.pos
      while true # sequence
        _tmp = match_string("'")
        unless _tmp
          self.pos = _save5
          break
        end
        while true

          _save7 = self.pos
          while true # sequence
            _save8 = self.pos
            _tmp = match_string("'")
            _tmp = _tmp ? nil : true
            self.pos = _save8
            unless _tmp
              self.pos = _save7
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save7
            end
            break
          end # end sequence

          break unless _tmp
        end
        _tmp = true
        unless _tmp
          self.pos = _save5
          break
        end
        _tmp = match_string("'")
        unless _tmp
          self.pos = _save5
        end
        break
      end # end sequence

      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_Quoted unless _tmp
    return _tmp
  end

  # HtmlAttribute = (AlphanumericAscii | "-")+ Spnl ("=" Spnl (Quoted | (!">" Nonspacechar)+))? Spnl
  def _HtmlAttribute

    _save = self.pos
    while true # sequence
      _save1 = self.pos

      _save2 = self.pos
      while true # choice
        _tmp = apply(:_AlphanumericAscii)
        break if _tmp
        self.pos = _save2
        _tmp = match_string("-")
        break if _tmp
        self.pos = _save2
        break
      end # end choice

      if _tmp
        while true

          _save3 = self.pos
          while true # choice
            _tmp = apply(:_AlphanumericAscii)
            break if _tmp
            self.pos = _save3
            _tmp = match_string("-")
            break if _tmp
            self.pos = _save3
            break
          end # end choice

          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save1
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _save4 = self.pos

      _save5 = self.pos
      while true # sequence
        _tmp = match_string("=")
        unless _tmp
          self.pos = _save5
          break
        end
        _tmp = apply(:_Spnl)
        unless _tmp
          self.pos = _save5
          break
        end

        _save6 = self.pos
        while true # choice
          _tmp = apply(:_Quoted)
          break if _tmp
          self.pos = _save6
          _save7 = self.pos

          _save8 = self.pos
          while true # sequence
            _save9 = self.pos
            _tmp = match_string(">")
            _tmp = _tmp ? nil : true
            self.pos = _save9
            unless _tmp
              self.pos = _save8
              break
            end
            _tmp = apply(:_Nonspacechar)
            unless _tmp
              self.pos = _save8
            end
            break
          end # end sequence

          if _tmp
            while true

              _save10 = self.pos
              while true # sequence
                _save11 = self.pos
                _tmp = match_string(">")
                _tmp = _tmp ? nil : true
                self.pos = _save11
                unless _tmp
                  self.pos = _save10
                  break
                end
                _tmp = apply(:_Nonspacechar)
                unless _tmp
                  self.pos = _save10
                end
                break
              end # end sequence

              break unless _tmp
            end
            _tmp = true
          else
            self.pos = _save7
          end
          break if _tmp
          self.pos = _save6
          break
        end # end choice

        unless _tmp
          self.pos = _save5
        end
        break
      end # end sequence

      unless _tmp
        _tmp = true
        self.pos = _save4
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlAttribute unless _tmp
    return _tmp
  end

  # HtmlComment = "<!--" (!"-->" .)* "-->"
  def _HtmlComment

    _save = self.pos
    while true # sequence
      _tmp = match_string("<!--")
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save2 = self.pos
        while true # sequence
          _save3 = self.pos
          _tmp = match_string("-->")
          _tmp = _tmp ? nil : true
          self.pos = _save3
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = get_byte
          unless _tmp
            self.pos = _save2
          end
          break
        end # end sequence

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("-->")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlComment unless _tmp
    return _tmp
  end

  # HtmlTag = "<" Spnl "/"? AlphanumericAscii+ Spnl HtmlAttribute* "/"? Spnl ">"
  def _HtmlTag

    _save = self.pos
    while true # sequence
      _tmp = match_string("<")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _tmp = match_string("/")
      unless _tmp
        _tmp = true
        self.pos = _save1
      end
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos
      _tmp = apply(:_AlphanumericAscii)
      if _tmp
        while true
          _tmp = apply(:_AlphanumericAscii)
          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save2
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = apply(:_HtmlAttribute)
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      _save4 = self.pos
      _tmp = match_string("/")
      unless _tmp
        _tmp = true
        self.pos = _save4
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(">")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HtmlTag unless _tmp
    return _tmp
  end

  # Eof = !.
  def _Eof
    _save = self.pos
    _tmp = get_byte
    _tmp = _tmp ? nil : true
    self.pos = _save
    set_failed_rule :_Eof unless _tmp
    return _tmp
  end

  # Nonspacechar = !@Spacechar !@Newline .
  def _Nonspacechar

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = _Spacechar()
      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos
      _tmp = _Newline()
      _tmp = _tmp ? nil : true
      self.pos = _save2
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = get_byte
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Nonspacechar unless _tmp
    return _tmp
  end

  # Sp = @Spacechar*
  def _Sp
    while true
      _tmp = _Spacechar()
      break unless _tmp
    end
    _tmp = true
    set_failed_rule :_Sp unless _tmp
    return _tmp
  end

  # Spnl = @Sp (@Newline @Sp)?
  def _Spnl

    _save = self.pos
    while true # sequence
      _tmp = _Sp()
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos

      _save2 = self.pos
      while true # sequence
        _tmp = _Newline()
        unless _tmp
          self.pos = _save2
          break
        end
        _tmp = _Sp()
        unless _tmp
          self.pos = _save2
        end
        break
      end # end sequence

      unless _tmp
        _tmp = true
        self.pos = _save1
      end
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Spnl unless _tmp
    return _tmp
  end

  # SpecialChar = (/[~*_`&\[\]()<!#\\'"]/ | @ExtendedSpecialChar)
  def _SpecialChar

    _save = self.pos
    while true # choice
      _tmp = scan(/\G(?-mix:[~*_`&\[\]()<!#\\'"])/)
      break if _tmp
      self.pos = _save
      _tmp = _ExtendedSpecialChar()
      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_SpecialChar unless _tmp
    return _tmp
  end

  # NormalChar = !(@SpecialChar | @Spacechar | @Newline) .
  def _NormalChar

    _save = self.pos
    while true # sequence
      _save1 = self.pos

      _save2 = self.pos
      while true # choice
        _tmp = _SpecialChar()
        break if _tmp
        self.pos = _save2
        _tmp = _Spacechar()
        break if _tmp
        self.pos = _save2
        _tmp = _Newline()
        break if _tmp
        self.pos = _save2
        break
      end # end choice

      _tmp = _tmp ? nil : true
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = get_byte
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_NormalChar unless _tmp
    return _tmp
  end

  # Digit = [0-9]
  def _Digit
    _save = self.pos
    _tmp = get_byte
    if _tmp
      unless _tmp >= 48 and _tmp <= 57
        self.pos = _save
        _tmp = nil
      end
    end
    set_failed_rule :_Digit unless _tmp
    return _tmp
  end

  # Alphanumeric = %literals.Alphanumeric
  def _Alphanumeric
    _tmp = @_grammar_literals.external_invoke(self, :_Alphanumeric)
    set_failed_rule :_Alphanumeric unless _tmp
    return _tmp
  end

  # AlphanumericAscii = %literals.AlphanumericAscii
  def _AlphanumericAscii
    _tmp = @_grammar_literals.external_invoke(self, :_AlphanumericAscii)
    set_failed_rule :_AlphanumericAscii unless _tmp
    return _tmp
  end

  # BOM = %literals.BOM
  def _BOM
    _tmp = @_grammar_literals.external_invoke(self, :_BOM)
    set_failed_rule :_BOM unless _tmp
    return _tmp
  end

  # Newline = %literals.Newline
  def _Newline
    _tmp = @_grammar_literals.external_invoke(self, :_Newline)
    set_failed_rule :_Newline unless _tmp
    return _tmp
  end

  # Spacechar = %literals.Spacechar
  def _Spacechar
    _tmp = @_grammar_literals.external_invoke(self, :_Spacechar)
    set_failed_rule :_Spacechar unless _tmp
    return _tmp
  end

  # HexEntity = /&#x/i < /[0-9a-fA-F]+/ > ";" { [text.to_i(16)].pack 'U' }
  def _HexEntity

    _save = self.pos
    while true # sequence
      _tmp = scan(/\G(?i-mx:&#x)/)
      unless _tmp
        self.pos = _save
        break
      end
      _text_start = self.pos
      _tmp = scan(/\G(?-mix:[0-9a-fA-F]+)/)
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(";")
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  [text.to_i(16)].pack 'U' ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_HexEntity unless _tmp
    return _tmp
  end

  # DecEntity = "&#" < /[0-9]+/ > ";" { [text.to_i].pack 'U' }
  def _DecEntity

    _save = self.pos
    while true # sequence
      _tmp = match_string("&#")
      unless _tmp
        self.pos = _save
        break
      end
      _text_start = self.pos
      _tmp = scan(/\G(?-mix:[0-9]+)/)
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(";")
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  [text.to_i].pack 'U' ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_DecEntity unless _tmp
    return _tmp
  end

  # CharEntity = "&" < /[A-Za-z0-9]+/ > ";" { if entity = HTML_ENTITIES[text] then                  entity.pack 'U*'                else                  "&#{text};"                end              }
  def _CharEntity

    _save = self.pos
    while true # sequence
      _tmp = match_string("&")
      unless _tmp
        self.pos = _save
        break
      end
      _text_start = self.pos
      _tmp = scan(/\G(?-mix:[A-Za-z0-9]+)/)
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(";")
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  if entity = HTML_ENTITIES[text] then
                 entity.pack 'U*'
               else
                 "&#{text};"
               end
             ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_CharEntity unless _tmp
    return _tmp
  end

  # NonindentSpace = / {0,3}/
  def _NonindentSpace
    _tmp = scan(/\G(?-mix: {0,3})/)
    set_failed_rule :_NonindentSpace unless _tmp
    return _tmp
  end

  # Indent = /\t|    /
  def _Indent
    _tmp = scan(/\G(?-mix:\t|    )/)
    set_failed_rule :_Indent unless _tmp
    return _tmp
  end

  # IndentedLine = Indent Line
  def _IndentedLine

    _save = self.pos
    while true # sequence
      _tmp = apply(:_Indent)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Line)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_IndentedLine unless _tmp
    return _tmp
  end

  # OptionallyIndentedLine = Indent? Line
  def _OptionallyIndentedLine

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = apply(:_Indent)
      unless _tmp
        _tmp = true
        self.pos = _save1
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Line)
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_OptionallyIndentedLine unless _tmp
    return _tmp
  end

  # StartList = &. { [] }
  def _StartList

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = get_byte
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  [] ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_StartList unless _tmp
    return _tmp
  end

  # Line = @RawLine:a { a }
  def _Line

    _save = self.pos
    while true # sequence
      _tmp = _RawLine()
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  a ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Line unless _tmp
    return _tmp
  end

  # RawLine = (< (!"\r" !"\n" .)* @Newline > | < .+ > @Eof) { text }
  def _RawLine

    _save = self.pos
    while true # sequence

      _save1 = self.pos
      while true # choice
        _text_start = self.pos

        _save2 = self.pos
        while true # sequence
          while true

            _save4 = self.pos
            while true # sequence
              _save5 = self.pos
              _tmp = match_string("\r")
              _tmp = _tmp ? nil : true
              self.pos = _save5
              unless _tmp
                self.pos = _save4
                break
              end
              _save6 = self.pos
              _tmp = match_string("\n")
              _tmp = _tmp ? nil : true
              self.pos = _save6
              unless _tmp
                self.pos = _save4
                break
              end
              _tmp = get_byte
              unless _tmp
                self.pos = _save4
              end
              break
            end # end sequence

            break unless _tmp
          end
          _tmp = true
          unless _tmp
            self.pos = _save2
            break
          end
          _tmp = _Newline()
          unless _tmp
            self.pos = _save2
          end
          break
        end # end sequence

        if _tmp
          text = get_text(_text_start)
        end
        break if _tmp
        self.pos = _save1

        _save7 = self.pos
        while true # sequence
          _text_start = self.pos
          _save8 = self.pos
          _tmp = get_byte
          if _tmp
            while true
              _tmp = get_byte
              break unless _tmp
            end
            _tmp = true
          else
            self.pos = _save8
          end
          if _tmp
            text = get_text(_text_start)
          end
          unless _tmp
            self.pos = _save7
            break
          end
          _tmp = _Eof()
          unless _tmp
            self.pos = _save7
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save1
        break
      end # end choice

      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  text ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_RawLine unless _tmp
    return _tmp
  end

  # SkipBlock = (HtmlBlock | (!"#" !SetextBottom1 !SetextBottom2 !@BlankLine @RawLine)+ @BlankLine* | @BlankLine+ | @RawLine)
  def _SkipBlock

    _save = self.pos
    while true # choice
      _tmp = apply(:_HtmlBlock)
      break if _tmp
      self.pos = _save

      _save1 = self.pos
      while true # sequence
        _save2 = self.pos

        _save3 = self.pos
        while true # sequence
          _save4 = self.pos
          _tmp = match_string("#")
          _tmp = _tmp ? nil : true
          self.pos = _save4
          unless _tmp
            self.pos = _save3
            break
          end
          _save5 = self.pos
          _tmp = apply(:_SetextBottom1)
          _tmp = _tmp ? nil : true
          self.pos = _save5
          unless _tmp
            self.pos = _save3
            break
          end
          _save6 = self.pos
          _tmp = apply(:_SetextBottom2)
          _tmp = _tmp ? nil : true
          self.pos = _save6
          unless _tmp
            self.pos = _save3
            break
          end
          _save7 = self.pos
          _tmp = _BlankLine()
          _tmp = _tmp ? nil : true
          self.pos = _save7
          unless _tmp
            self.pos = _save3
            break
          end
          _tmp = _RawLine()
          unless _tmp
            self.pos = _save3
          end
          break
        end # end sequence

        if _tmp
          while true

            _save8 = self.pos
            while true # sequence
              _save9 = self.pos
              _tmp = match_string("#")
              _tmp = _tmp ? nil : true
              self.pos = _save9
              unless _tmp
                self.pos = _save8
                break
              end
              _save10 = self.pos
              _tmp = apply(:_SetextBottom1)
              _tmp = _tmp ? nil : true
              self.pos = _save10
              unless _tmp
                self.pos = _save8
                break
              end
              _save11 = self.pos
              _tmp = apply(:_SetextBottom2)
              _tmp = _tmp ? nil : true
              self.pos = _save11
              unless _tmp
                self.pos = _save8
                break
              end
              _save12 = self.pos
              _tmp = _BlankLine()
              _tmp = _tmp ? nil : true
              self.pos = _save12
              unless _tmp
                self.pos = _save8
                break
              end
              _tmp = _RawLine()
              unless _tmp
                self.pos = _save8
              end
              break
            end # end sequence

            break unless _tmp
          end
          _tmp = true
        else
          self.pos = _save2
        end
        unless _tmp
          self.pos = _save1
          break
        end
        while true
          _tmp = _BlankLine()
          break unless _tmp
        end
        _tmp = true
        unless _tmp
          self.pos = _save1
        end
        break
      end # end sequence

      break if _tmp
      self.pos = _save
      _save14 = self.pos
      _tmp = _BlankLine()
      if _tmp
        while true
          _tmp = _BlankLine()
          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save14
      end
      break if _tmp
      self.pos = _save
      _tmp = _RawLine()
      break if _tmp
      self.pos = _save
      break
    end # end choice

    set_failed_rule :_SkipBlock unless _tmp
    return _tmp
  end

  # ExtendedSpecialChar = &{ notes? } "^"
  def _ExtendedSpecialChar

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = begin;  notes? ; end
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("^")
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_ExtendedSpecialChar unless _tmp
    return _tmp
  end

  # NoteReference = &{ notes? } RawNoteReference:ref { note_for ref }
  def _NoteReference

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = begin;  notes? ; end
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_RawNoteReference)
      ref = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  note_for ref ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_NoteReference unless _tmp
    return _tmp
  end

  # RawNoteReference = "[^" < (!@Newline !"]" .)+ > "]" { text }
  def _RawNoteReference

    _save = self.pos
    while true # sequence
      _tmp = match_string("[^")
      unless _tmp
        self.pos = _save
        break
      end
      _text_start = self.pos
      _save1 = self.pos

      _save2 = self.pos
      while true # sequence
        _save3 = self.pos
        _tmp = _Newline()
        _tmp = _tmp ? nil : true
        self.pos = _save3
        unless _tmp
          self.pos = _save2
          break
        end
        _save4 = self.pos
        _tmp = match_string("]")
        _tmp = _tmp ? nil : true
        self.pos = _save4
        unless _tmp
          self.pos = _save2
          break
        end
        _tmp = get_byte
        unless _tmp
          self.pos = _save2
        end
        break
      end # end sequence

      if _tmp
        while true

          _save5 = self.pos
          while true # sequence
            _save6 = self.pos
            _tmp = _Newline()
            _tmp = _tmp ? nil : true
            self.pos = _save6
            unless _tmp
              self.pos = _save5
              break
            end
            _save7 = self.pos
            _tmp = match_string("]")
            _tmp = _tmp ? nil : true
            self.pos = _save7
            unless _tmp
              self.pos = _save5
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save5
            end
            break
          end # end sequence

          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save1
      end
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("]")
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  text ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_RawNoteReference unless _tmp
    return _tmp
  end

  # Note = &{ notes? } @NonindentSpace RawNoteReference:ref ":" @Sp @StartList:a RawNoteBlock:i { a.concat i } (&Indent RawNoteBlock:i { a.concat i })* { @footnotes[ref] = paragraph a                    nil                 }
  def _Note

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = begin;  notes? ; end
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _NonindentSpace()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_RawNoteReference)
      ref = @result
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(":")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Sp()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _StartList()
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_RawNoteBlock)
      i = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  a.concat i ; end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      while true

        _save3 = self.pos
        while true # sequence
          _save4 = self.pos
          _tmp = apply(:_Indent)
          self.pos = _save4
          unless _tmp
            self.pos = _save3
            break
          end
          _tmp = apply(:_RawNoteBlock)
          i = @result
          unless _tmp
            self.pos = _save3
            break
          end
          @result = begin;  a.concat i ; end
          _tmp = true
          unless _tmp
            self.pos = _save3
          end
          break
        end # end sequence

        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  @footnotes[ref] = paragraph a

                  nil
                ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Note unless _tmp
    return _tmp
  end

  # InlineNote = &{ notes? } "^[" @StartList:a (!"]" Inline:l { a << l })+ "]" { ref = [:inline, @note_order.length]                @footnotes[ref] = paragraph a                 note_for ref              }
  def _InlineNote

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = begin;  notes? ; end
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("^[")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _StartList()
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos

      _save3 = self.pos
      while true # sequence
        _save4 = self.pos
        _tmp = match_string("]")
        _tmp = _tmp ? nil : true
        self.pos = _save4
        unless _tmp
          self.pos = _save3
          break
        end
        _tmp = apply(:_Inline)
        l = @result
        unless _tmp
          self.pos = _save3
          break
        end
        @result = begin;  a << l ; end
        _tmp = true
        unless _tmp
          self.pos = _save3
        end
        break
      end # end sequence

      if _tmp
        while true

          _save5 = self.pos
          while true # sequence
            _save6 = self.pos
            _tmp = match_string("]")
            _tmp = _tmp ? nil : true
            self.pos = _save6
            unless _tmp
              self.pos = _save5
              break
            end
            _tmp = apply(:_Inline)
            l = @result
            unless _tmp
              self.pos = _save5
              break
            end
            @result = begin;  a << l ; end
            _tmp = true
            unless _tmp
              self.pos = _save5
            end
            break
          end # end sequence

          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save2
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("]")
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  ref = [:inline, @note_order.length]
               @footnotes[ref] = paragraph a

               note_for ref
             ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_InlineNote unless _tmp
    return _tmp
  end

  # Notes = (Note | SkipBlock)*
  def _Notes
    while true

      _save1 = self.pos
      while true # choice
        _tmp = apply(:_Note)
        break if _tmp
        self.pos = _save1
        _tmp = apply(:_SkipBlock)
        break if _tmp
        self.pos = _save1
        break
      end # end choice

      break unless _tmp
    end
    _tmp = true
    set_failed_rule :_Notes unless _tmp
    return _tmp
  end

  # RawNoteBlock = @StartList:a (!@BlankLine OptionallyIndentedLine:l { a << l })+ < @BlankLine* > { a << text } { a }
  def _RawNoteBlock

    _save = self.pos
    while true # sequence
      _tmp = _StartList()
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos

      _save2 = self.pos
      while true # sequence
        _save3 = self.pos
        _tmp = _BlankLine()
        _tmp = _tmp ? nil : true
        self.pos = _save3
        unless _tmp
          self.pos = _save2
          break
        end
        _tmp = apply(:_OptionallyIndentedLine)
        l = @result
        unless _tmp
          self.pos = _save2
          break
        end
        @result = begin;  a << l ; end
        _tmp = true
        unless _tmp
          self.pos = _save2
        end
        break
      end # end sequence

      if _tmp
        while true

          _save4 = self.pos
          while true # sequence
            _save5 = self.pos
            _tmp = _BlankLine()
            _tmp = _tmp ? nil : true
            self.pos = _save5
            unless _tmp
              self.pos = _save4
              break
            end
            _tmp = apply(:_OptionallyIndentedLine)
            l = @result
            unless _tmp
              self.pos = _save4
              break
            end
            @result = begin;  a << l ; end
            _tmp = true
            unless _tmp
              self.pos = _save4
            end
            break
          end # end sequence

          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save1
      end
      unless _tmp
        self.pos = _save
        break
      end
      _text_start = self.pos
      while true
        _tmp = _BlankLine()
        break unless _tmp
      end
      _tmp = true
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  a << text ; end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  a ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_RawNoteBlock unless _tmp
    return _tmp
  end

  # CodeFence = &{ github? } Ticks3 (@Sp StrChunk:format)? Spnl < ((!"`" Nonspacechar)+ | !Ticks3 /`+/ | Spacechar | @Newline)+ > Ticks3 @Sp @Newline* { verbatim = RDoc::Markup::Verbatim.new text               verbatim.format = format.intern if format.instance_of?(String)               verbatim             }
  def _CodeFence

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = begin;  github? ; end
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Ticks3)
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos

      _save3 = self.pos
      while true # sequence
        _tmp = _Sp()
        unless _tmp
          self.pos = _save3
          break
        end
        _tmp = apply(:_StrChunk)
        format = @result
        unless _tmp
          self.pos = _save3
        end
        break
      end # end sequence

      unless _tmp
        _tmp = true
        self.pos = _save2
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Spnl)
      unless _tmp
        self.pos = _save
        break
      end
      _text_start = self.pos
      _save4 = self.pos

      _save5 = self.pos
      while true # choice
        _save6 = self.pos

        _save7 = self.pos
        while true # sequence
          _save8 = self.pos
          _tmp = match_string("`")
          _tmp = _tmp ? nil : true
          self.pos = _save8
          unless _tmp
            self.pos = _save7
            break
          end
          _tmp = apply(:_Nonspacechar)
          unless _tmp
            self.pos = _save7
          end
          break
        end # end sequence

        if _tmp
          while true

            _save9 = self.pos
            while true # sequence
              _save10 = self.pos
              _tmp = match_string("`")
              _tmp = _tmp ? nil : true
              self.pos = _save10
              unless _tmp
                self.pos = _save9
                break
              end
              _tmp = apply(:_Nonspacechar)
              unless _tmp
                self.pos = _save9
              end
              break
            end # end sequence

            break unless _tmp
          end
          _tmp = true
        else
          self.pos = _save6
        end
        break if _tmp
        self.pos = _save5

        _save11 = self.pos
        while true # sequence
          _save12 = self.pos
          _tmp = apply(:_Ticks3)
          _tmp = _tmp ? nil : true
          self.pos = _save12
          unless _tmp
            self.pos = _save11
            break
          end
          _tmp = scan(/\G(?-mix:`+)/)
          unless _tmp
            self.pos = _save11
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save5
        _tmp = apply(:_Spacechar)
        break if _tmp
        self.pos = _save5
        _tmp = _Newline()
        break if _tmp
        self.pos = _save5
        break
      end # end choice

      if _tmp
        while true

          _save13 = self.pos
          while true # choice
            _save14 = self.pos

            _save15 = self.pos
            while true # sequence
              _save16 = self.pos
              _tmp = match_string("`")
              _tmp = _tmp ? nil : true
              self.pos = _save16
              unless _tmp
                self.pos = _save15
                break
              end
              _tmp = apply(:_Nonspacechar)
              unless _tmp
                self.pos = _save15
              end
              break
            end # end sequence

            if _tmp
              while true

                _save17 = self.pos
                while true # sequence
                  _save18 = self.pos
                  _tmp = match_string("`")
                  _tmp = _tmp ? nil : true
                  self.pos = _save18
                  unless _tmp
                    self.pos = _save17
                    break
                  end
                  _tmp = apply(:_Nonspacechar)
                  unless _tmp
                    self.pos = _save17
                  end
                  break
                end # end sequence

                break unless _tmp
              end
              _tmp = true
            else
              self.pos = _save14
            end
            break if _tmp
            self.pos = _save13

            _save19 = self.pos
            while true # sequence
              _save20 = self.pos
              _tmp = apply(:_Ticks3)
              _tmp = _tmp ? nil : true
              self.pos = _save20
              unless _tmp
                self.pos = _save19
                break
              end
              _tmp = scan(/\G(?-mix:`+)/)
              unless _tmp
                self.pos = _save19
              end
              break
            end # end sequence

            break if _tmp
            self.pos = _save13
            _tmp = apply(:_Spacechar)
            break if _tmp
            self.pos = _save13
            _tmp = _Newline()
            break if _tmp
            self.pos = _save13
            break
          end # end choice

          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save4
      end
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Ticks3)
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Sp()
      unless _tmp
        self.pos = _save
        break
      end
      while true
        _tmp = _Newline()
        break unless _tmp
      end
      _tmp = true
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  verbatim = RDoc::Markup::Verbatim.new text
              verbatim.format = format.intern if format.instance_of?(String)
              verbatim
            ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_CodeFence unless _tmp
    return _tmp
  end

  # Table = &{ github? } TableRow:header TableLine:line TableRow+:body { table = RDoc::Markup::Table.new(header, line, body) }
  def _Table

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = begin;  github? ; end
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_TableRow)
      header = @result
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_TableLine)
      line = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos
      _ary = []
      _tmp = apply(:_TableRow)
      if _tmp
        _ary << @result
        while true
          _tmp = apply(:_TableRow)
          _ary << @result if _tmp
          break unless _tmp
        end
        _tmp = true
        @result = _ary
      else
        self.pos = _save2
      end
      body = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  table = RDoc::Markup::Table.new(header, line, body) ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_Table unless _tmp
    return _tmp
  end

  # TableRow = TableItem+:row "|" @Newline { row }
  def _TableRow

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _ary = []
      _tmp = apply(:_TableItem)
      if _tmp
        _ary << @result
        while true
          _tmp = apply(:_TableItem)
          _ary << @result if _tmp
          break unless _tmp
        end
        _tmp = true
        @result = _ary
      else
        self.pos = _save1
      end
      row = @result
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("|")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Newline()
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  row ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_TableRow unless _tmp
    return _tmp
  end

  # TableItem = "|" < (!"|" !@Newline .)+ > { text.strip }
  def _TableItem

    _save = self.pos
    while true # sequence
      _tmp = match_string("|")
      unless _tmp
        self.pos = _save
        break
      end
      _text_start = self.pos
      _save1 = self.pos

      _save2 = self.pos
      while true # sequence
        _save3 = self.pos
        _tmp = match_string("|")
        _tmp = _tmp ? nil : true
        self.pos = _save3
        unless _tmp
          self.pos = _save2
          break
        end
        _save4 = self.pos
        _tmp = _Newline()
        _tmp = _tmp ? nil : true
        self.pos = _save4
        unless _tmp
          self.pos = _save2
          break
        end
        _tmp = get_byte
        unless _tmp
          self.pos = _save2
        end
        break
      end # end sequence

      if _tmp
        while true

          _save5 = self.pos
          while true # sequence
            _save6 = self.pos
            _tmp = match_string("|")
            _tmp = _tmp ? nil : true
            self.pos = _save6
            unless _tmp
              self.pos = _save5
              break
            end
            _save7 = self.pos
            _tmp = _Newline()
            _tmp = _tmp ? nil : true
            self.pos = _save7
            unless _tmp
              self.pos = _save5
              break
            end
            _tmp = get_byte
            unless _tmp
              self.pos = _save5
            end
            break
          end # end sequence

          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save1
      end
      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  text.strip ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_TableItem unless _tmp
    return _tmp
  end

  # TableLine = TableColumn+:line "|" @Newline { line }
  def _TableLine

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _ary = []
      _tmp = apply(:_TableColumn)
      if _tmp
        _ary << @result
        while true
          _tmp = apply(:_TableColumn)
          _ary << @result if _tmp
          break unless _tmp
        end
        _tmp = true
        @result = _ary
      else
        self.pos = _save1
      end
      line = @result
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string("|")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Newline()
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  line ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_TableLine unless _tmp
    return _tmp
  end

  # TableColumn = "|" < ("-"+ ":"? | ":" "-"*) > { text.start_with?(":") ? :left :                 text.end_with?(":") ? :right : nil               }
  def _TableColumn

    _save = self.pos
    while true # sequence
      _tmp = match_string("|")
      unless _tmp
        self.pos = _save
        break
      end
      _text_start = self.pos

      _save1 = self.pos
      while true # choice

        _save2 = self.pos
        while true # sequence
          _save3 = self.pos
          _tmp = match_string("-")
          if _tmp
            while true
              _tmp = match_string("-")
              break unless _tmp
            end
            _tmp = true
          else
            self.pos = _save3
          end
          unless _tmp
            self.pos = _save2
            break
          end
          _save4 = self.pos
          _tmp = match_string(":")
          unless _tmp
            _tmp = true
            self.pos = _save4
          end
          unless _tmp
            self.pos = _save2
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save1

        _save5 = self.pos
        while true # sequence
          _tmp = match_string(":")
          unless _tmp
            self.pos = _save5
            break
          end
          while true
            _tmp = match_string("-")
            break unless _tmp
          end
          _tmp = true
          unless _tmp
            self.pos = _save5
          end
          break
        end # end sequence

        break if _tmp
        self.pos = _save1
        break
      end # end choice

      if _tmp
        text = get_text(_text_start)
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  text.start_with?(":") ? :left :
                text.end_with?(":") ? :right : nil
              ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_TableColumn unless _tmp
    return _tmp
  end

  # DefinitionList = &{ definition_lists? } DefinitionListItem+:list { RDoc::Markup::List.new :NOTE, *list.flatten }
  def _DefinitionList

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _tmp = begin;  definition_lists? ; end
      self.pos = _save1
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos
      _ary = []
      _tmp = apply(:_DefinitionListItem)
      if _tmp
        _ary << @result
        while true
          _tmp = apply(:_DefinitionListItem)
          _ary << @result if _tmp
          break unless _tmp
        end
        _tmp = true
        @result = _ary
      else
        self.pos = _save2
      end
      list = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  RDoc::Markup::List.new :NOTE, *list.flatten ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_DefinitionList unless _tmp
    return _tmp
  end

  # DefinitionListItem = DefinitionListLabel+:label DefinitionListDefinition+:defns { list_items = []                        list_items <<                          RDoc::Markup::ListItem.new(label, defns.shift)                         list_items.concat defns.map { |defn|                          RDoc::Markup::ListItem.new nil, defn                        } unless list_items.empty?                         list_items                      }
  def _DefinitionListItem

    _save = self.pos
    while true # sequence
      _save1 = self.pos
      _ary = []
      _tmp = apply(:_DefinitionListLabel)
      if _tmp
        _ary << @result
        while true
          _tmp = apply(:_DefinitionListLabel)
          _ary << @result if _tmp
          break unless _tmp
        end
        _tmp = true
        @result = _ary
      else
        self.pos = _save1
      end
      label = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save2 = self.pos
      _ary = []
      _tmp = apply(:_DefinitionListDefinition)
      if _tmp
        _ary << @result
        while true
          _tmp = apply(:_DefinitionListDefinition)
          _ary << @result if _tmp
          break unless _tmp
        end
        _tmp = true
        @result = _ary
      else
        self.pos = _save2
      end
      defns = @result
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  list_items = []
                       list_items <<
                         RDoc::Markup::ListItem.new(label, defns.shift)

                       list_items.concat defns.map { |defn|
                         RDoc::Markup::ListItem.new nil, defn
                       } unless list_items.empty?

                       list_items
                     ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_DefinitionListItem unless _tmp
    return _tmp
  end

  # DefinitionListLabel = StrChunk:label @Sp @Newline { label }
  def _DefinitionListLabel

    _save = self.pos
    while true # sequence
      _tmp = apply(:_StrChunk)
      label = @result
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Sp()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Newline()
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  label ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_DefinitionListLabel unless _tmp
    return _tmp
  end

  # DefinitionListDefinition = @NonindentSpace ":" @Space Inlines:a @BlankLine+ { paragraph a }
  def _DefinitionListDefinition

    _save = self.pos
    while true # sequence
      _tmp = _NonindentSpace()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = match_string(":")
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = _Space()
      unless _tmp
        self.pos = _save
        break
      end
      _tmp = apply(:_Inlines)
      a = @result
      unless _tmp
        self.pos = _save
        break
      end
      _save1 = self.pos
      _tmp = _BlankLine()
      if _tmp
        while true
          _tmp = _BlankLine()
          break unless _tmp
        end
        _tmp = true
      else
        self.pos = _save1
      end
      unless _tmp
        self.pos = _save
        break
      end
      @result = begin;  paragraph a ; end
      _tmp = true
      unless _tmp
        self.pos = _save
      end
      break
    end # end sequence

    set_failed_rule :_DefinitionListDefinition unless _tmp
    return _tmp
  end

  Rules = {}
  Rules[:_root] = rule_info("root", "Doc")
  Rules[:_Doc] = rule_info("Doc", "BOM? Block*:a { RDoc::Markup::Document.new(*a.compact) }")
  Rules[:_Block] = rule_info("Block", "@BlankLine* (BlockQuote | Verbatim | CodeFence | Table | Note | Reference | HorizontalRule | Heading | OrderedList | BulletList | DefinitionList | HtmlBlock | StyleBlock | Para | Plain)")
  Rules[:_Para] = rule_info("Para", "@NonindentSpace Inlines:a @BlankLine+ { paragraph a }")
  Rules[:_Plain] = rule_info("Plain", "Inlines:a { paragraph a }")
  Rules[:_AtxInline] = rule_info("AtxInline", "!@Newline !(@Sp /\#*/ @Sp @Newline) Inline")
  Rules[:_AtxStart] = rule_info("AtxStart", "< /\\\#{1,6}/ > { text.length }")
  Rules[:_AtxHeading] = rule_info("AtxHeading", "AtxStart:s @Sp AtxInline+:a (@Sp /\#*/ @Sp)? @Newline { RDoc::Markup::Heading.new(s, a.join) }")
  Rules[:_SetextHeading] = rule_info("SetextHeading", "(SetextHeading1 | SetextHeading2)")
  Rules[:_SetextBottom1] = rule_info("SetextBottom1", "/={1,}/ @Newline")
  Rules[:_SetextBottom2] = rule_info("SetextBottom2", "/-{1,}/ @Newline")
  Rules[:_SetextHeading1] = rule_info("SetextHeading1", "&(@RawLine SetextBottom1) @StartList:a (!@Endline Inline:b { a << b })+ @Sp @Newline SetextBottom1 { RDoc::Markup::Heading.new(1, a.join) }")
  Rules[:_SetextHeading2] = rule_info("SetextHeading2", "&(@RawLine SetextBottom2) @StartList:a (!@Endline Inline:b { a << b })+ @Sp @Newline SetextBottom2 { RDoc::Markup::Heading.new(2, a.join) }")
  Rules[:_Heading] = rule_info("Heading", "(SetextHeading | AtxHeading)")
  Rules[:_BlockQuote] = rule_info("BlockQuote", "BlockQuoteRaw:a { RDoc::Markup::BlockQuote.new(*a) }")
  Rules[:_BlockQuoteRaw] = rule_info("BlockQuoteRaw", "@StartList:a (\">\" \" \"? Line:l { a << l } (!\">\" !@BlankLine Line:c { a << c })* (@BlankLine:n { a << n })*)+ { inner_parse a.join }")
  Rules[:_NonblankIndentedLine] = rule_info("NonblankIndentedLine", "!@BlankLine IndentedLine")
  Rules[:_VerbatimChunk] = rule_info("VerbatimChunk", "@BlankLine*:a NonblankIndentedLine+:b { a.concat b }")
  Rules[:_Verbatim] = rule_info("Verbatim", "VerbatimChunk+:a { RDoc::Markup::Verbatim.new(*a.flatten) }")
  Rules[:_HorizontalRule] = rule_info("HorizontalRule", "@NonindentSpace (\"*\" @Sp \"*\" @Sp \"*\" (@Sp \"*\")* | \"-\" @Sp \"-\" @Sp \"-\" (@Sp \"-\")* | \"_\" @Sp \"_\" @Sp \"_\" (@Sp \"_\")*) @Sp @Newline @BlankLine+ { RDoc::Markup::Rule.new 1 }")
  Rules[:_Bullet] = rule_info("Bullet", "!HorizontalRule @NonindentSpace /[+*-]/ @Spacechar+")
  Rules[:_BulletList] = rule_info("BulletList", "&Bullet (ListTight | ListLoose):a { RDoc::Markup::List.new(:BULLET, *a) }")
  Rules[:_ListTight] = rule_info("ListTight", "ListItemTight+:a @BlankLine* !(Bullet | Enumerator) { a }")
  Rules[:_ListLoose] = rule_info("ListLoose", "@StartList:a (ListItem:b @BlankLine* { a << b })+ { a }")
  Rules[:_ListItem] = rule_info("ListItem", "(Bullet | Enumerator) @StartList:a ListBlock:b { a << b } (ListContinuationBlock:c { a.push(*c) })* { list_item_from a }")
  Rules[:_ListItemTight] = rule_info("ListItemTight", "(Bullet | Enumerator) ListBlock:a (!@BlankLine ListContinuationBlock:b { a.push(*b) })* !ListContinuationBlock { list_item_from a }")
  Rules[:_ListBlock] = rule_info("ListBlock", "!@BlankLine Line:a ListBlockLine*:c { [a, *c] }")
  Rules[:_ListContinuationBlock] = rule_info("ListContinuationBlock", "@StartList:a @BlankLine* { a << \"\\n\" } (Indent ListBlock:b { a.concat b })+ { a }")
  Rules[:_Enumerator] = rule_info("Enumerator", "@NonindentSpace [0-9]+ \".\" @Spacechar+")
  Rules[:_OrderedList] = rule_info("OrderedList", "&Enumerator (ListTight | ListLoose):a { RDoc::Markup::List.new(:NUMBER, *a) }")
  Rules[:_ListBlockLine] = rule_info("ListBlockLine", "!@BlankLine !(Indent? (Bullet | Enumerator)) !HorizontalRule OptionallyIndentedLine")
  Rules[:_HtmlOpenAnchor] = rule_info("HtmlOpenAnchor", "\"<\" Spnl (\"a\" | \"A\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlCloseAnchor] = rule_info("HtmlCloseAnchor", "\"<\" Spnl \"/\" (\"a\" | \"A\") Spnl \">\"")
  Rules[:_HtmlAnchor] = rule_info("HtmlAnchor", "HtmlOpenAnchor (HtmlAnchor | !HtmlCloseAnchor .)* HtmlCloseAnchor")
  Rules[:_HtmlBlockOpenAddress] = rule_info("HtmlBlockOpenAddress", "\"<\" Spnl (\"address\" | \"ADDRESS\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseAddress] = rule_info("HtmlBlockCloseAddress", "\"<\" Spnl \"/\" (\"address\" | \"ADDRESS\") Spnl \">\"")
  Rules[:_HtmlBlockAddress] = rule_info("HtmlBlockAddress", "HtmlBlockOpenAddress (HtmlBlockAddress | !HtmlBlockCloseAddress .)* HtmlBlockCloseAddress")
  Rules[:_HtmlBlockOpenBlockquote] = rule_info("HtmlBlockOpenBlockquote", "\"<\" Spnl (\"blockquote\" | \"BLOCKQUOTE\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseBlockquote] = rule_info("HtmlBlockCloseBlockquote", "\"<\" Spnl \"/\" (\"blockquote\" | \"BLOCKQUOTE\") Spnl \">\"")
  Rules[:_HtmlBlockBlockquote] = rule_info("HtmlBlockBlockquote", "HtmlBlockOpenBlockquote (HtmlBlockBlockquote | !HtmlBlockCloseBlockquote .)* HtmlBlockCloseBlockquote")
  Rules[:_HtmlBlockOpenCenter] = rule_info("HtmlBlockOpenCenter", "\"<\" Spnl (\"center\" | \"CENTER\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseCenter] = rule_info("HtmlBlockCloseCenter", "\"<\" Spnl \"/\" (\"center\" | \"CENTER\") Spnl \">\"")
  Rules[:_HtmlBlockCenter] = rule_info("HtmlBlockCenter", "HtmlBlockOpenCenter (HtmlBlockCenter | !HtmlBlockCloseCenter .)* HtmlBlockCloseCenter")
  Rules[:_HtmlBlockOpenDir] = rule_info("HtmlBlockOpenDir", "\"<\" Spnl (\"dir\" | \"DIR\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseDir] = rule_info("HtmlBlockCloseDir", "\"<\" Spnl \"/\" (\"dir\" | \"DIR\") Spnl \">\"")
  Rules[:_HtmlBlockDir] = rule_info("HtmlBlockDir", "HtmlBlockOpenDir (HtmlBlockDir | !HtmlBlockCloseDir .)* HtmlBlockCloseDir")
  Rules[:_HtmlBlockOpenDiv] = rule_info("HtmlBlockOpenDiv", "\"<\" Spnl (\"div\" | \"DIV\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseDiv] = rule_info("HtmlBlockCloseDiv", "\"<\" Spnl \"/\" (\"div\" | \"DIV\") Spnl \">\"")
  Rules[:_HtmlBlockDiv] = rule_info("HtmlBlockDiv", "HtmlBlockOpenDiv (HtmlBlockDiv | !HtmlBlockCloseDiv .)* HtmlBlockCloseDiv")
  Rules[:_HtmlBlockOpenDl] = rule_info("HtmlBlockOpenDl", "\"<\" Spnl (\"dl\" | \"DL\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseDl] = rule_info("HtmlBlockCloseDl", "\"<\" Spnl \"/\" (\"dl\" | \"DL\") Spnl \">\"")
  Rules[:_HtmlBlockDl] = rule_info("HtmlBlockDl", "HtmlBlockOpenDl (HtmlBlockDl | !HtmlBlockCloseDl .)* HtmlBlockCloseDl")
  Rules[:_HtmlBlockOpenFieldset] = rule_info("HtmlBlockOpenFieldset", "\"<\" Spnl (\"fieldset\" | \"FIELDSET\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseFieldset] = rule_info("HtmlBlockCloseFieldset", "\"<\" Spnl \"/\" (\"fieldset\" | \"FIELDSET\") Spnl \">\"")
  Rules[:_HtmlBlockFieldset] = rule_info("HtmlBlockFieldset", "HtmlBlockOpenFieldset (HtmlBlockFieldset | !HtmlBlockCloseFieldset .)* HtmlBlockCloseFieldset")
  Rules[:_HtmlBlockOpenForm] = rule_info("HtmlBlockOpenForm", "\"<\" Spnl (\"form\" | \"FORM\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseForm] = rule_info("HtmlBlockCloseForm", "\"<\" Spnl \"/\" (\"form\" | \"FORM\") Spnl \">\"")
  Rules[:_HtmlBlockForm] = rule_info("HtmlBlockForm", "HtmlBlockOpenForm (HtmlBlockForm | !HtmlBlockCloseForm .)* HtmlBlockCloseForm")
  Rules[:_HtmlBlockOpenH1] = rule_info("HtmlBlockOpenH1", "\"<\" Spnl (\"h1\" | \"H1\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseH1] = rule_info("HtmlBlockCloseH1", "\"<\" Spnl \"/\" (\"h1\" | \"H1\") Spnl \">\"")
  Rules[:_HtmlBlockH1] = rule_info("HtmlBlockH1", "HtmlBlockOpenH1 (HtmlBlockH1 | !HtmlBlockCloseH1 .)* HtmlBlockCloseH1")
  Rules[:_HtmlBlockOpenH2] = rule_info("HtmlBlockOpenH2", "\"<\" Spnl (\"h2\" | \"H2\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseH2] = rule_info("HtmlBlockCloseH2", "\"<\" Spnl \"/\" (\"h2\" | \"H2\") Spnl \">\"")
  Rules[:_HtmlBlockH2] = rule_info("HtmlBlockH2", "HtmlBlockOpenH2 (HtmlBlockH2 | !HtmlBlockCloseH2 .)* HtmlBlockCloseH2")
  Rules[:_HtmlBlockOpenH3] = rule_info("HtmlBlockOpenH3", "\"<\" Spnl (\"h3\" | \"H3\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseH3] = rule_info("HtmlBlockCloseH3", "\"<\" Spnl \"/\" (\"h3\" | \"H3\") Spnl \">\"")
  Rules[:_HtmlBlockH3] = rule_info("HtmlBlockH3", "HtmlBlockOpenH3 (HtmlBlockH3 | !HtmlBlockCloseH3 .)* HtmlBlockCloseH3")
  Rules[:_HtmlBlockOpenH4] = rule_info("HtmlBlockOpenH4", "\"<\" Spnl (\"h4\" | \"H4\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseH4] = rule_info("HtmlBlockCloseH4", "\"<\" Spnl \"/\" (\"h4\" | \"H4\") Spnl \">\"")
  Rules[:_HtmlBlockH4] = rule_info("HtmlBlockH4", "HtmlBlockOpenH4 (HtmlBlockH4 | !HtmlBlockCloseH4 .)* HtmlBlockCloseH4")
  Rules[:_HtmlBlockOpenH5] = rule_info("HtmlBlockOpenH5", "\"<\" Spnl (\"h5\" | \"H5\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseH5] = rule_info("HtmlBlockCloseH5", "\"<\" Spnl \"/\" (\"h5\" | \"H5\") Spnl \">\"")
  Rules[:_HtmlBlockH5] = rule_info("HtmlBlockH5", "HtmlBlockOpenH5 (HtmlBlockH5 | !HtmlBlockCloseH5 .)* HtmlBlockCloseH5")
  Rules[:_HtmlBlockOpenH6] = rule_info("HtmlBlockOpenH6", "\"<\" Spnl (\"h6\" | \"H6\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseH6] = rule_info("HtmlBlockCloseH6", "\"<\" Spnl \"/\" (\"h6\" | \"H6\") Spnl \">\"")
  Rules[:_HtmlBlockH6] = rule_info("HtmlBlockH6", "HtmlBlockOpenH6 (HtmlBlockH6 | !HtmlBlockCloseH6 .)* HtmlBlockCloseH6")
  Rules[:_HtmlBlockOpenMenu] = rule_info("HtmlBlockOpenMenu", "\"<\" Spnl (\"menu\" | \"MENU\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseMenu] = rule_info("HtmlBlockCloseMenu", "\"<\" Spnl \"/\" (\"menu\" | \"MENU\") Spnl \">\"")
  Rules[:_HtmlBlockMenu] = rule_info("HtmlBlockMenu", "HtmlBlockOpenMenu (HtmlBlockMenu | !HtmlBlockCloseMenu .)* HtmlBlockCloseMenu")
  Rules[:_HtmlBlockOpenNoframes] = rule_info("HtmlBlockOpenNoframes", "\"<\" Spnl (\"noframes\" | \"NOFRAMES\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseNoframes] = rule_info("HtmlBlockCloseNoframes", "\"<\" Spnl \"/\" (\"noframes\" | \"NOFRAMES\") Spnl \">\"")
  Rules[:_HtmlBlockNoframes] = rule_info("HtmlBlockNoframes", "HtmlBlockOpenNoframes (HtmlBlockNoframes | !HtmlBlockCloseNoframes .)* HtmlBlockCloseNoframes")
  Rules[:_HtmlBlockOpenNoscript] = rule_info("HtmlBlockOpenNoscript", "\"<\" Spnl (\"noscript\" | \"NOSCRIPT\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseNoscript] = rule_info("HtmlBlockCloseNoscript", "\"<\" Spnl \"/\" (\"noscript\" | \"NOSCRIPT\") Spnl \">\"")
  Rules[:_HtmlBlockNoscript] = rule_info("HtmlBlockNoscript", "HtmlBlockOpenNoscript (HtmlBlockNoscript | !HtmlBlockCloseNoscript .)* HtmlBlockCloseNoscript")
  Rules[:_HtmlBlockOpenOl] = rule_info("HtmlBlockOpenOl", "\"<\" Spnl (\"ol\" | \"OL\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseOl] = rule_info("HtmlBlockCloseOl", "\"<\" Spnl \"/\" (\"ol\" | \"OL\") Spnl \">\"")
  Rules[:_HtmlBlockOl] = rule_info("HtmlBlockOl", "HtmlBlockOpenOl (HtmlBlockOl | !HtmlBlockCloseOl .)* HtmlBlockCloseOl")
  Rules[:_HtmlBlockOpenP] = rule_info("HtmlBlockOpenP", "\"<\" Spnl (\"p\" | \"P\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseP] = rule_info("HtmlBlockCloseP", "\"<\" Spnl \"/\" (\"p\" | \"P\") Spnl \">\"")
  Rules[:_HtmlBlockP] = rule_info("HtmlBlockP", "HtmlBlockOpenP (HtmlBlockP | !HtmlBlockCloseP .)* HtmlBlockCloseP")
  Rules[:_HtmlBlockOpenPre] = rule_info("HtmlBlockOpenPre", "\"<\" Spnl (\"pre\" | \"PRE\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockClosePre] = rule_info("HtmlBlockClosePre", "\"<\" Spnl \"/\" (\"pre\" | \"PRE\") Spnl \">\"")
  Rules[:_HtmlBlockPre] = rule_info("HtmlBlockPre", "HtmlBlockOpenPre (HtmlBlockPre | !HtmlBlockClosePre .)* HtmlBlockClosePre")
  Rules[:_HtmlBlockOpenTable] = rule_info("HtmlBlockOpenTable", "\"<\" Spnl (\"table\" | \"TABLE\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseTable] = rule_info("HtmlBlockCloseTable", "\"<\" Spnl \"/\" (\"table\" | \"TABLE\") Spnl \">\"")
  Rules[:_HtmlBlockTable] = rule_info("HtmlBlockTable", "HtmlBlockOpenTable (HtmlBlockTable | !HtmlBlockCloseTable .)* HtmlBlockCloseTable")
  Rules[:_HtmlBlockOpenUl] = rule_info("HtmlBlockOpenUl", "\"<\" Spnl (\"ul\" | \"UL\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseUl] = rule_info("HtmlBlockCloseUl", "\"<\" Spnl \"/\" (\"ul\" | \"UL\") Spnl \">\"")
  Rules[:_HtmlBlockUl] = rule_info("HtmlBlockUl", "HtmlBlockOpenUl (HtmlBlockUl | !HtmlBlockCloseUl .)* HtmlBlockCloseUl")
  Rules[:_HtmlBlockOpenDd] = rule_info("HtmlBlockOpenDd", "\"<\" Spnl (\"dd\" | \"DD\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseDd] = rule_info("HtmlBlockCloseDd", "\"<\" Spnl \"/\" (\"dd\" | \"DD\") Spnl \">\"")
  Rules[:_HtmlBlockDd] = rule_info("HtmlBlockDd", "HtmlBlockOpenDd (HtmlBlockDd | !HtmlBlockCloseDd .)* HtmlBlockCloseDd")
  Rules[:_HtmlBlockOpenDt] = rule_info("HtmlBlockOpenDt", "\"<\" Spnl (\"dt\" | \"DT\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseDt] = rule_info("HtmlBlockCloseDt", "\"<\" Spnl \"/\" (\"dt\" | \"DT\") Spnl \">\"")
  Rules[:_HtmlBlockDt] = rule_info("HtmlBlockDt", "HtmlBlockOpenDt (HtmlBlockDt | !HtmlBlockCloseDt .)* HtmlBlockCloseDt")
  Rules[:_HtmlBlockOpenFrameset] = rule_info("HtmlBlockOpenFrameset", "\"<\" Spnl (\"frameset\" | \"FRAMESET\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseFrameset] = rule_info("HtmlBlockCloseFrameset", "\"<\" Spnl \"/\" (\"frameset\" | \"FRAMESET\") Spnl \">\"")
  Rules[:_HtmlBlockFrameset] = rule_info("HtmlBlockFrameset", "HtmlBlockOpenFrameset (HtmlBlockFrameset | !HtmlBlockCloseFrameset .)* HtmlBlockCloseFrameset")
  Rules[:_HtmlBlockOpenLi] = rule_info("HtmlBlockOpenLi", "\"<\" Spnl (\"li\" | \"LI\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseLi] = rule_info("HtmlBlockCloseLi", "\"<\" Spnl \"/\" (\"li\" | \"LI\") Spnl \">\"")
  Rules[:_HtmlBlockLi] = rule_info("HtmlBlockLi", "HtmlBlockOpenLi (HtmlBlockLi | !HtmlBlockCloseLi .)* HtmlBlockCloseLi")
  Rules[:_HtmlBlockOpenTbody] = rule_info("HtmlBlockOpenTbody", "\"<\" Spnl (\"tbody\" | \"TBODY\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseTbody] = rule_info("HtmlBlockCloseTbody", "\"<\" Spnl \"/\" (\"tbody\" | \"TBODY\") Spnl \">\"")
  Rules[:_HtmlBlockTbody] = rule_info("HtmlBlockTbody", "HtmlBlockOpenTbody (HtmlBlockTbody | !HtmlBlockCloseTbody .)* HtmlBlockCloseTbody")
  Rules[:_HtmlBlockOpenTd] = rule_info("HtmlBlockOpenTd", "\"<\" Spnl (\"td\" | \"TD\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseTd] = rule_info("HtmlBlockCloseTd", "\"<\" Spnl \"/\" (\"td\" | \"TD\") Spnl \">\"")
  Rules[:_HtmlBlockTd] = rule_info("HtmlBlockTd", "HtmlBlockOpenTd (HtmlBlockTd | !HtmlBlockCloseTd .)* HtmlBlockCloseTd")
  Rules[:_HtmlBlockOpenTfoot] = rule_info("HtmlBlockOpenTfoot", "\"<\" Spnl (\"tfoot\" | \"TFOOT\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseTfoot] = rule_info("HtmlBlockCloseTfoot", "\"<\" Spnl \"/\" (\"tfoot\" | \"TFOOT\") Spnl \">\"")
  Rules[:_HtmlBlockTfoot] = rule_info("HtmlBlockTfoot", "HtmlBlockOpenTfoot (HtmlBlockTfoot | !HtmlBlockCloseTfoot .)* HtmlBlockCloseTfoot")
  Rules[:_HtmlBlockOpenTh] = rule_info("HtmlBlockOpenTh", "\"<\" Spnl (\"th\" | \"TH\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseTh] = rule_info("HtmlBlockCloseTh", "\"<\" Spnl \"/\" (\"th\" | \"TH\") Spnl \">\"")
  Rules[:_HtmlBlockTh] = rule_info("HtmlBlockTh", "HtmlBlockOpenTh (HtmlBlockTh | !HtmlBlockCloseTh .)* HtmlBlockCloseTh")
  Rules[:_HtmlBlockOpenThead] = rule_info("HtmlBlockOpenThead", "\"<\" Spnl (\"thead\" | \"THEAD\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseThead] = rule_info("HtmlBlockCloseThead", "\"<\" Spnl \"/\" (\"thead\" | \"THEAD\") Spnl \">\"")
  Rules[:_HtmlBlockThead] = rule_info("HtmlBlockThead", "HtmlBlockOpenThead (HtmlBlockThead | !HtmlBlockCloseThead .)* HtmlBlockCloseThead")
  Rules[:_HtmlBlockOpenTr] = rule_info("HtmlBlockOpenTr", "\"<\" Spnl (\"tr\" | \"TR\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseTr] = rule_info("HtmlBlockCloseTr", "\"<\" Spnl \"/\" (\"tr\" | \"TR\") Spnl \">\"")
  Rules[:_HtmlBlockTr] = rule_info("HtmlBlockTr", "HtmlBlockOpenTr (HtmlBlockTr | !HtmlBlockCloseTr .)* HtmlBlockCloseTr")
  Rules[:_HtmlBlockOpenScript] = rule_info("HtmlBlockOpenScript", "\"<\" Spnl (\"script\" | \"SCRIPT\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseScript] = rule_info("HtmlBlockCloseScript", "\"<\" Spnl \"/\" (\"script\" | \"SCRIPT\") Spnl \">\"")
  Rules[:_HtmlBlockScript] = rule_info("HtmlBlockScript", "HtmlBlockOpenScript (!HtmlBlockCloseScript .)* HtmlBlockCloseScript")
  Rules[:_HtmlBlockOpenHead] = rule_info("HtmlBlockOpenHead", "\"<\" Spnl (\"head\" | \"HEAD\") Spnl HtmlAttribute* \">\"")
  Rules[:_HtmlBlockCloseHead] = rule_info("HtmlBlockCloseHead", "\"<\" Spnl \"/\" (\"head\" | \"HEAD\") Spnl \">\"")
  Rules[:_HtmlBlockHead] = rule_info("HtmlBlockHead", "HtmlBlockOpenHead (!HtmlBlockCloseHead .)* HtmlBlockCloseHead")
  Rules[:_HtmlBlockInTags] = rule_info("HtmlBlockInTags", "(HtmlAnchor | HtmlBlockAddress | HtmlBlockBlockquote | HtmlBlockCenter | HtmlBlockDir | HtmlBlockDiv | HtmlBlockDl | HtmlBlockFieldset | HtmlBlockForm | HtmlBlockH1 | HtmlBlockH2 | HtmlBlockH3 | HtmlBlockH4 | HtmlBlockH5 | HtmlBlockH6 | HtmlBlockMenu | HtmlBlockNoframes | HtmlBlockNoscript | HtmlBlockOl | HtmlBlockP | HtmlBlockPre | HtmlBlockTable | HtmlBlockUl | HtmlBlockDd | HtmlBlockDt | HtmlBlockFrameset | HtmlBlockLi | HtmlBlockTbody | HtmlBlockTd | HtmlBlockTfoot | HtmlBlockTh | HtmlBlockThead | HtmlBlockTr | HtmlBlockScript | HtmlBlockHead)")
  Rules[:_HtmlBlock] = rule_info("HtmlBlock", "< (HtmlBlockInTags | HtmlComment | HtmlBlockSelfClosing | HtmlUnclosed) > @BlankLine+ { if html? then                 RDoc::Markup::Raw.new text               end }")
  Rules[:_HtmlUnclosed] = rule_info("HtmlUnclosed", "\"<\" Spnl HtmlUnclosedType Spnl HtmlAttribute* Spnl \">\"")
  Rules[:_HtmlUnclosedType] = rule_info("HtmlUnclosedType", "(\"HR\" | \"hr\")")
  Rules[:_HtmlBlockSelfClosing] = rule_info("HtmlBlockSelfClosing", "\"<\" Spnl HtmlBlockType Spnl HtmlAttribute* \"/\" Spnl \">\"")
  Rules[:_HtmlBlockType] = rule_info("HtmlBlockType", "(\"ADDRESS\" | \"BLOCKQUOTE\" | \"CENTER\" | \"DD\" | \"DIR\" | \"DIV\" | \"DL\" | \"DT\" | \"FIELDSET\" | \"FORM\" | \"FRAMESET\" | \"H1\" | \"H2\" | \"H3\" | \"H4\" | \"H5\" | \"H6\" | \"HR\" | \"ISINDEX\" | \"LI\" | \"MENU\" | \"NOFRAMES\" | \"NOSCRIPT\" | \"OL\" | \"P\" | \"PRE\" | \"SCRIPT\" | \"TABLE\" | \"TBODY\" | \"TD\" | \"TFOOT\" | \"TH\" | \"THEAD\" | \"TR\" | \"UL\" | \"address\" | \"blockquote\" | \"center\" | \"dd\" | \"dir\" | \"div\" | \"dl\" | \"dt\" | \"fieldset\" | \"form\" | \"frameset\" | \"h1\" | \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"h6\" | \"hr\" | \"isindex\" | \"li\" | \"menu\" | \"noframes\" | \"noscript\" | \"ol\" | \"p\" | \"pre\" | \"script\" | \"table\" | \"tbody\" | \"td\" | \"tfoot\" | \"th\" | \"thead\" | \"tr\" | \"ul\")")
  Rules[:_StyleOpen] = rule_info("StyleOpen", "\"<\" Spnl (\"style\" | \"STYLE\") Spnl HtmlAttribute* \">\"")
  Rules[:_StyleClose] = rule_info("StyleClose", "\"<\" Spnl \"/\" (\"style\" | \"STYLE\") Spnl \">\"")
  Rules[:_InStyleTags] = rule_info("InStyleTags", "StyleOpen (!StyleClose .)* StyleClose")
  Rules[:_StyleBlock] = rule_info("StyleBlock", "< InStyleTags > @BlankLine* { if css? then                     RDoc::Markup::Raw.new text                   end }")
  Rules[:_Inlines] = rule_info("Inlines", "(!@Endline Inline:i { i } | @Endline:c !(&{ github? } Ticks3 /[^`\\n]*$/) &Inline { c })+:chunks @Endline? { chunks }")
  Rules[:_Inline] = rule_info("Inline", "(Str | @Endline | UlOrStarLine | @Space | Strong | Emph | Strike | Image | Link | NoteReference | InlineNote | Code | RawHtml | Entity | EscapedChar | Symbol)")
  Rules[:_Space] = rule_info("Space", "@Spacechar+ { \" \" }")
  Rules[:_Str] = rule_info("Str", "@StartList:a < @NormalChar+ > { a = text } (StrChunk:c { a << c })* { a }")
  Rules[:_StrChunk] = rule_info("StrChunk", "< (@NormalChar | /_+/ &Alphanumeric)+ > { text }")
  Rules[:_EscapedChar] = rule_info("EscapedChar", "\"\\\\\" !@Newline < /[:\\\\`|*_{}\\[\\]()\#+.!><-]/ > { text }")
  Rules[:_Entity] = rule_info("Entity", "(HexEntity | DecEntity | CharEntity):a { a }")
  Rules[:_Endline] = rule_info("Endline", "(@LineBreak | @TerminalEndline | @NormalEndline)")
  Rules[:_NormalEndline] = rule_info("NormalEndline", "@Sp @Newline !@BlankLine !\">\" !AtxStart !(Line /={1,}|-{1,}/ @Newline) { \"\\n\" }")
  Rules[:_TerminalEndline] = rule_info("TerminalEndline", "@Sp @Newline @Eof")
  Rules[:_LineBreak] = rule_info("LineBreak", "\"  \" @NormalEndline { RDoc::Markup::HardBreak.new }")
  Rules[:_Symbol] = rule_info("Symbol", "< @SpecialChar > { text }")
  Rules[:_UlOrStarLine] = rule_info("UlOrStarLine", "(UlLine | StarLine):a { a }")
  Rules[:_StarLine] = rule_info("StarLine", "(< /\\*{4,}/ > { text } | < @Spacechar /\\*+/ &@Spacechar > { text })")
  Rules[:_UlLine] = rule_info("UlLine", "(< /_{4,}/ > { text } | < @Spacechar /_+/ &@Spacechar > { text })")
  Rules[:_Emph] = rule_info("Emph", "(EmphStar | EmphUl)")
  Rules[:_Whitespace] = rule_info("Whitespace", "(@Spacechar | @Newline)")
  Rules[:_EmphStar] = rule_info("EmphStar", "\"*\" !@Whitespace @StartList:a (!\"*\" Inline:b { a << b } | StrongStar:b { a << b })+ \"*\" { emphasis a.join }")
  Rules[:_EmphUl] = rule_info("EmphUl", "\"_\" !@Whitespace @StartList:a (!\"_\" Inline:b { a << b } | StrongUl:b { a << b })+ \"_\" { emphasis a.join }")
  Rules[:_Strong] = rule_info("Strong", "(StrongStar | StrongUl)")
  Rules[:_StrongStar] = rule_info("StrongStar", "\"**\" !@Whitespace @StartList:a (!\"**\" Inline:b { a << b })+ \"**\" { strong a.join }")
  Rules[:_StrongUl] = rule_info("StrongUl", "\"__\" !@Whitespace @StartList:a (!\"__\" Inline:b { a << b })+ \"__\" { strong a.join }")
  Rules[:_Strike] = rule_info("Strike", "&{ strike? } \"~~\" !@Whitespace @StartList:a (!\"~~\" Inline:b { a << b })+ \"~~\" { strike a.join }")
  Rules[:_Image] = rule_info("Image", "\"!\" (ExplicitLink | ReferenceLink):a { \"rdoc-image:\#{a[/\\[(.*)\\]/, 1]}\" }")
  Rules[:_Link] = rule_info("Link", "(ExplicitLink | ReferenceLink | AutoLink)")
  Rules[:_ReferenceLink] = rule_info("ReferenceLink", "(ReferenceLinkDouble | ReferenceLinkSingle)")
  Rules[:_ReferenceLinkDouble] = rule_info("ReferenceLinkDouble", "Label:content < Spnl > !\"[]\" Label:label { link_to content, label, text }")
  Rules[:_ReferenceLinkSingle] = rule_info("ReferenceLinkSingle", "Label:content < (Spnl \"[]\")? > { link_to content, content, text }")
  Rules[:_ExplicitLink] = rule_info("ExplicitLink", "Label:l \"(\" @Sp Source:s Spnl Title @Sp \")\" { \"{\#{l}}[\#{s}]\" }")
  Rules[:_Source] = rule_info("Source", "(\"<\" < SourceContents > \">\" | < SourceContents >) { text }")
  Rules[:_SourceContents] = rule_info("SourceContents", "((!\"(\" !\")\" !\">\" Nonspacechar)+ | \"(\" SourceContents \")\")*")
  Rules[:_Title] = rule_info("Title", "(TitleSingle | TitleDouble | \"\"):a { a }")
  Rules[:_TitleSingle] = rule_info("TitleSingle", "\"'\" (!(\"'\" @Sp (\")\" | @Newline)) .)* \"'\"")
  Rules[:_TitleDouble] = rule_info("TitleDouble", "\"\\\"\" (!(\"\\\"\" @Sp (\")\" | @Newline)) .)* \"\\\"\"")
  Rules[:_AutoLink] = rule_info("AutoLink", "(AutoLinkUrl | AutoLinkEmail)")
  Rules[:_AutoLinkUrl] = rule_info("AutoLinkUrl", "\"<\" < /[A-Za-z]+/ \"://\" (!@Newline !\">\" .)+ > \">\" { text }")
  Rules[:_AutoLinkEmail] = rule_info("AutoLinkEmail", "\"<\" \"mailto:\"? < /[\\w+.\\/!%~$-]+/i \"@\" (!@Newline !\">\" .)+ > \">\" { \"mailto:\#{text}\" }")
  Rules[:_Reference] = rule_info("Reference", "@NonindentSpace !\"[]\" Label:label \":\" Spnl RefSrc:link RefTitle @BlankLine+ { \# TODO use title               reference label, link               nil             }")
  Rules[:_Label] = rule_info("Label", "\"[\" (!\"^\" &{ notes? } | &. &{ !notes? }) @StartList:a (!\"]\" Inline:l { a << l })* \"]\" { a.join.gsub(/\\s+/, ' ') }")
  Rules[:_RefSrc] = rule_info("RefSrc", "< Nonspacechar+ > { text }")
  Rules[:_RefTitle] = rule_info("RefTitle", "(RefTitleSingle | RefTitleDouble | RefTitleParens | EmptyTitle)")
  Rules[:_EmptyTitle] = rule_info("EmptyTitle", "\"\"")
  Rules[:_RefTitleSingle] = rule_info("RefTitleSingle", "Spnl \"'\" < (!(\"'\" @Sp @Newline | @Newline) .)* > \"'\" { text }")
  Rules[:_RefTitleDouble] = rule_info("RefTitleDouble", "Spnl \"\\\"\" < (!(\"\\\"\" @Sp @Newline | @Newline) .)* > \"\\\"\" { text }")
  Rules[:_RefTitleParens] = rule_info("RefTitleParens", "Spnl \"(\" < (!(\")\" @Sp @Newline | @Newline) .)* > \")\" { text }")
  Rules[:_References] = rule_info("References", "(Reference | SkipBlock)*")
  Rules[:_Ticks1] = rule_info("Ticks1", "\"`\" !\"`\"")
  Rules[:_Ticks2] = rule_info("Ticks2", "\"``\" !\"`\"")
  Rules[:_Ticks3] = rule_info("Ticks3", "\"```\" !\"`\"")
  Rules[:_Ticks4] = rule_info("Ticks4", "\"````\" !\"`\"")
  Rules[:_Ticks5] = rule_info("Ticks5", "\"`````\" !\"`\"")
  Rules[:_Code] = rule_info("Code", "(Ticks1 @Sp < ((!\"`\" Nonspacechar)+ | !Ticks1 /`+/ | !(@Sp Ticks1) (@Spacechar | @Newline !@BlankLine))+ > @Sp Ticks1 | Ticks2 @Sp < ((!\"`\" Nonspacechar)+ | !Ticks2 /`+/ | !(@Sp Ticks2) (@Spacechar | @Newline !@BlankLine))+ > @Sp Ticks2 | Ticks3 @Sp < ((!\"`\" Nonspacechar)+ | !Ticks3 /`+/ | !(@Sp Ticks3) (@Spacechar | @Newline !@BlankLine))+ > @Sp Ticks3 | Ticks4 @Sp < ((!\"`\" Nonspacechar)+ | !Ticks4 /`+/ | !(@Sp Ticks4) (@Spacechar | @Newline !@BlankLine))+ > @Sp Ticks4 | Ticks5 @Sp < ((!\"`\" Nonspacechar)+ | !Ticks5 /`+/ | !(@Sp Ticks5) (@Spacechar | @Newline !@BlankLine))+ > @Sp Ticks5) { \"<code>\#{text}</code>\" }")
  Rules[:_RawHtml] = rule_info("RawHtml", "< (HtmlComment | HtmlBlockScript | HtmlTag) > { if html? then text else '' end }")
  Rules[:_BlankLine] = rule_info("BlankLine", "@Sp @Newline { \"\\n\" }")
  Rules[:_Quoted] = rule_info("Quoted", "(\"\\\"\" (!\"\\\"\" .)* \"\\\"\" | \"'\" (!\"'\" .)* \"'\")")
  Rules[:_HtmlAttribute] = rule_info("HtmlAttribute", "(AlphanumericAscii | \"-\")+ Spnl (\"=\" Spnl (Quoted | (!\">\" Nonspacechar)+))? Spnl")
  Rules[:_HtmlComment] = rule_info("HtmlComment", "\"<!--\" (!\"-->\" .)* \"-->\"")
  Rules[:_HtmlTag] = rule_info("HtmlTag", "\"<\" Spnl \"/\"? AlphanumericAscii+ Spnl HtmlAttribute* \"/\"? Spnl \">\"")
  Rules[:_Eof] = rule_info("Eof", "!.")
  Rules[:_Nonspacechar] = rule_info("Nonspacechar", "!@Spacechar !@Newline .")
  Rules[:_Sp] = rule_info("Sp", "@Spacechar*")
  Rules[:_Spnl] = rule_info("Spnl", "@Sp (@Newline @Sp)?")
  Rules[:_SpecialChar] = rule_info("SpecialChar", "(/[~*_`&\\[\\]()<!\#\\\\'\"]/ | @ExtendedSpecialChar)")
  Rules[:_NormalChar] = rule_info("NormalChar", "!(@SpecialChar | @Spacechar | @Newline) .")
  Rules[:_Digit] = rule_info("Digit", "[0-9]")
  Rules[:_Alphanumeric] = rule_info("Alphanumeric", "%literals.Alphanumeric")
  Rules[:_AlphanumericAscii] = rule_info("AlphanumericAscii", "%literals.AlphanumericAscii")
  Rules[:_BOM] = rule_info("BOM", "%literals.BOM")
  Rules[:_Newline] = rule_info("Newline", "%literals.Newline")
  Rules[:_Spacechar] = rule_info("Spacechar", "%literals.Spacechar")
  Rules[:_HexEntity] = rule_info("HexEntity", "/&\#x/i < /[0-9a-fA-F]+/ > \";\" { [text.to_i(16)].pack 'U' }")
  Rules[:_DecEntity] = rule_info("DecEntity", "\"&\#\" < /[0-9]+/ > \";\" { [text.to_i].pack 'U' }")
  Rules[:_CharEntity] = rule_info("CharEntity", "\"&\" < /[A-Za-z0-9]+/ > \";\" { if entity = HTML_ENTITIES[text] then                  entity.pack 'U*'                else                  \"&\#{text};\"                end              }")
  Rules[:_NonindentSpace] = rule_info("NonindentSpace", "/ {0,3}/")
  Rules[:_Indent] = rule_info("Indent", "/\\t|    /")
  Rules[:_IndentedLine] = rule_info("IndentedLine", "Indent Line")
  Rules[:_OptionallyIndentedLine] = rule_info("OptionallyIndentedLine", "Indent? Line")
  Rules[:_StartList] = rule_info("StartList", "&. { [] }")
  Rules[:_Line] = rule_info("Line", "@RawLine:a { a }")
  Rules[:_RawLine] = rule_info("RawLine", "(< (!\"\\r\" !\"\\n\" .)* @Newline > | < .+ > @Eof) { text }")
  Rules[:_SkipBlock] = rule_info("SkipBlock", "(HtmlBlock | (!\"\#\" !SetextBottom1 !SetextBottom2 !@BlankLine @RawLine)+ @BlankLine* | @BlankLine+ | @RawLine)")
  Rules[:_ExtendedSpecialChar] = rule_info("ExtendedSpecialChar", "&{ notes? } \"^\"")
  Rules[:_NoteReference] = rule_info("NoteReference", "&{ notes? } RawNoteReference:ref { note_for ref }")
  Rules[:_RawNoteReference] = rule_info("RawNoteReference", "\"[^\" < (!@Newline !\"]\" .)+ > \"]\" { text }")
  Rules[:_Note] = rule_info("Note", "&{ notes? } @NonindentSpace RawNoteReference:ref \":\" @Sp @StartList:a RawNoteBlock:i { a.concat i } (&Indent RawNoteBlock:i { a.concat i })* { @footnotes[ref] = paragraph a                    nil                 }")
  Rules[:_InlineNote] = rule_info("InlineNote", "&{ notes? } \"^[\" @StartList:a (!\"]\" Inline:l { a << l })+ \"]\" { ref = [:inline, @note_order.length]                @footnotes[ref] = paragraph a                 note_for ref              }")
  Rules[:_Notes] = rule_info("Notes", "(Note | SkipBlock)*")
  Rules[:_RawNoteBlock] = rule_info("RawNoteBlock", "@StartList:a (!@BlankLine OptionallyIndentedLine:l { a << l })+ < @BlankLine* > { a << text } { a }")
  Rules[:_CodeFence] = rule_info("CodeFence", "&{ github? } Ticks3 (@Sp StrChunk:format)? Spnl < ((!\"`\" Nonspacechar)+ | !Ticks3 /`+/ | Spacechar | @Newline)+ > Ticks3 @Sp @Newline* { verbatim = RDoc::Markup::Verbatim.new text               verbatim.format = format.intern if format.instance_of?(String)               verbatim             }")
  Rules[:_Table] = rule_info("Table", "&{ github? } TableRow:header TableLine:line TableRow+:body { table = RDoc::Markup::Table.new(header, line, body) }")
  Rules[:_TableRow] = rule_info("TableRow", "TableItem+:row \"|\" @Newline { row }")
  Rules[:_TableItem] = rule_info("TableItem", "\"|\" < (!\"|\" !@Newline .)+ > { text.strip }")
  Rules[:_TableLine] = rule_info("TableLine", "TableColumn+:line \"|\" @Newline { line }")
  Rules[:_TableColumn] = rule_info("TableColumn", "\"|\" < (\"-\"+ \":\"? | \":\" \"-\"*) > { text.start_with?(\":\") ? :left :                 text.end_with?(\":\") ? :right : nil               }")
  Rules[:_DefinitionList] = rule_info("DefinitionList", "&{ definition_lists? } DefinitionListItem+:list { RDoc::Markup::List.new :NOTE, *list.flatten }")
  Rules[:_DefinitionListItem] = rule_info("DefinitionListItem", "DefinitionListLabel+:label DefinitionListDefinition+:defns { list_items = []                        list_items <<                          RDoc::Markup::ListItem.new(label, defns.shift)                         list_items.concat defns.map { |defn|                          RDoc::Markup::ListItem.new nil, defn                        } unless list_items.empty?                         list_items                      }")
  Rules[:_DefinitionListLabel] = rule_info("DefinitionListLabel", "StrChunk:label @Sp @Newline { label }")
  Rules[:_DefinitionListDefinition] = rule_info("DefinitionListDefinition", "@NonindentSpace \":\" @Space Inlines:a @BlankLine+ { paragraph a }")
  # :startdoc:
end
# frozen_string_literal: true
require 'optparse'
require 'pathname'

##
# RDoc::Options handles the parsing and storage of options
#
# == Saved Options
#
# You can save some options like the markup format in the
# <tt>.rdoc_options</tt> file in your gem.  The easiest way to do this is:
#
#   rdoc --markup tomdoc --write-options
#
# Which will automatically create the file and fill it with the options you
# specified.
#
# The following options will not be saved since they interfere with the user's
# preferences or with the normal operation of RDoc:
#
# * +--coverage-report+
# * +--dry-run+
# * +--encoding+
# * +--force-update+
# * +--format+
# * +--pipe+
# * +--quiet+
# * +--template+
# * +--verbose+
#
# == Custom Options
#
# Generators can hook into RDoc::Options to add generator-specific command
# line options.
#
# When <tt>--format</tt> is encountered in ARGV, RDoc calls ::setup_options on
# the generator class to add extra options to the option parser.  Options for
# custom generators must occur after <tt>--format</tt>.  <tt>rdoc --help</tt>
# will list options for all installed generators.
#
# Example:
#
#   class RDoc::Generator::Spellcheck
#     RDoc::RDoc.add_generator self
#
#     def self.setup_options rdoc_options
#       op = rdoc_options.option_parser
#
#       op.on('--spell-dictionary DICTIONARY',
#             RDoc::Options::Path) do |dictionary|
#         rdoc_options.spell_dictionary = dictionary
#       end
#     end
#   end
#
# Of course, RDoc::Options does not respond to +spell_dictionary+ by default
# so you will need to add it:
#
#   class RDoc::Options
#
#     ##
#     # The spell dictionary used by the spell-checking plugin.
#
#     attr_accessor :spell_dictionary
#
#   end
#
# == Option Validators
#
# OptionParser validators will validate and cast user input values.  In
# addition to the validators that ship with OptionParser (String, Integer,
# Float, TrueClass, FalseClass, Array, Regexp, Date, Time, URI, etc.),
# RDoc::Options adds Path, PathArray and Template.

class RDoc::Options

  ##
  # The deprecated options.

  DEPRECATED = {
    '--accessor'      => 'support discontinued',
    '--diagram'       => 'support discontinued',
    '--help-output'   => 'support discontinued',
    '--image-format'  => 'was an option for --diagram',
    '--inline-source' => 'source code is now always inlined',
    '--merge'         => 'ri now always merges class information',
    '--one-file'      => 'support discontinued',
    '--op-name'       => 'support discontinued',
    '--opname'        => 'support discontinued',
    '--promiscuous'   => 'files always only document their content',
    '--ri-system'     => 'Ruby installers use other techniques',
  }

  ##
  # RDoc options ignored (or handled specially) by --write-options

  SPECIAL = %w[
    coverage_report
    dry_run
    encoding
    files
    force_output
    force_update
    generator
    generator_name
    generator_options
    generators
    op_dir
    option_parser
    pipe
    rdoc_include
    root
    static_path
    stylesheet_url
    template
    template_dir
    update_output_dir
    verbosity
    write_options
  ]

  ##
  # Option validator for OptionParser that matches a directory that exists on
  # the filesystem.

  Directory = Object.new

  ##
  # Option validator for OptionParser that matches a file or directory that
  # exists on the filesystem.

  Path = Object.new

  ##
  # Option validator for OptionParser that matches a comma-separated list of
  # files or directories that exist on the filesystem.

  PathArray = Object.new

  ##
  # Option validator for OptionParser that matches a template directory for an
  # installed generator that lives in
  # <tt>"rdoc/generator/template/#{template_name}"</tt>

  Template = Object.new

  ##
  # Character-set for HTML output.  #encoding is preferred over #charset

  attr_accessor :charset

  ##
  # If true, RDoc will not write any files.

  attr_accessor :dry_run

  ##
  # The output encoding.  All input files will be transcoded to this encoding.
  #
  # The default encoding is UTF-8.  This is set via --encoding.

  attr_accessor :encoding

  ##
  # Files matching this pattern will be excluded

  attr_writer :exclude

  ##
  # The list of files to be processed

  attr_accessor :files

  ##
  # Create the output even if the output directory does not look
  # like an rdoc output directory

  attr_accessor :force_output

  ##
  # Scan newer sources than the flag file if true.

  attr_accessor :force_update

  ##
  # Formatter to mark up text with

  attr_accessor :formatter

  ##
  # Description of the output generator (set with the <tt>--format</tt> option)

  attr_accessor :generator

  ##
  # For #==

  attr_reader :generator_name # :nodoc:

  ##
  # Loaded generator options.  Used to prevent --help from loading the same
  # options multiple times.

  attr_accessor :generator_options

  ##
  # Old rdoc behavior: hyperlink all words that match a method name,
  # even if not preceded by '#' or '::'

  attr_accessor :hyperlink_all

  ##
  # Include line numbers in the source code

  attr_accessor :line_numbers

  ##
  # The output locale.

  attr_accessor :locale

  ##
  # The directory where locale data live.

  attr_accessor :locale_dir

  ##
  # Name of the file, class or module to display in the initial index page (if
  # not specified the first file we encounter is used)

  attr_accessor :main_page

  ##
  # The default markup format.  The default is 'rdoc'.  'markdown', 'tomdoc'
  # and 'rd' are also built-in.

  attr_accessor :markup

  ##
  # If true, only report on undocumented files

  attr_accessor :coverage_report

  ##
  # The name of the output directory

  attr_accessor :op_dir

  ##
  # The OptionParser for this instance

  attr_accessor :option_parser

  ##
  # Output heading decorations?
  attr_accessor :output_decoration

  ##
  # Directory where guides, FAQ, and other pages not associated with a class
  # live.  You may leave this unset if these are at the root of your project.

  attr_accessor :page_dir

  ##
  # Is RDoc in pipe mode?

  attr_accessor :pipe

  ##
  # Array of directories to search for files to satisfy an :include:

  attr_accessor :rdoc_include

  ##
  # Root of the source documentation will be generated for.  Set this when
  # building documentation outside the source directory.  Defaults to the
  # current directory.

  attr_accessor :root

  ##
  # Include the '#' at the front of hyperlinked instance method names

  attr_accessor :show_hash

  ##
  # Directory to copy static files from

  attr_accessor :static_path

  ##
  # The number of columns in a tab

  attr_accessor :tab_width

  ##
  # Template to be used when generating output

  attr_accessor :template

  ##
  # Directory the template lives in

  attr_accessor :template_dir

  ##
  # Additional template stylesheets

  attr_accessor :template_stylesheets

  ##
  # Documentation title

  attr_accessor :title

  ##
  # Should RDoc update the timestamps in the output dir?

  attr_accessor :update_output_dir

  ##
  # Verbosity, zero means quiet

  attr_accessor :verbosity

  ##
  # URL of web cvs frontend

  attr_accessor :webcvs

  ##
  # Minimum visibility of a documented method. One of +:public+, +:protected+,
  # +:private+ or +:nodoc+.
  #
  # The +:nodoc+ visibility ignores all directives related to visibility.  The
  # other visibilities may be overridden on a per-method basis with the :doc:
  # directive.

  attr_reader :visibility

  def initialize loaded_options = nil # :nodoc:
    init_ivars
    override loaded_options if loaded_options
  end

  def init_ivars # :nodoc:
    @dry_run = false
    @exclude = %w[
      ~\z \.orig\z \.rej\z \.bak\z
      \.gemspec\z
    ]
    @files = nil
    @force_output = false
    @force_update = true
    @generator = nil
    @generator_name = nil
    @generator_options = []
    @generators = RDoc::RDoc::GENERATORS
    @hyperlink_all = false
    @line_numbers = false
    @locale = nil
    @locale_name = nil
    @locale_dir = 'locale'
    @main_page = nil
    @markup = 'rdoc'
    @coverage_report = false
    @op_dir = nil
    @page_dir = nil
    @pipe = false
    @output_decoration = true
    @rdoc_include = []
    @root = Pathname(Dir.pwd)
    @show_hash = false
    @static_path = []
    @stylesheet_url = nil # TODO remove in RDoc 4
    @tab_width = 8
    @template = nil
    @template_dir = nil
    @template_stylesheets = []
    @title = nil
    @update_output_dir = true
    @verbosity = 1
    @visibility = :protected
    @webcvs = nil
    @write_options = false
    @encoding = Encoding::UTF_8
    @charset = @encoding.name
  end

  def init_with map # :nodoc:
    init_ivars

    encoding = map['encoding']
    @encoding = encoding ? Encoding.find(encoding) : encoding

    @charset        = map['charset']
    @exclude        = map['exclude']
    @generator_name = map['generator_name']
    @hyperlink_all  = map['hyperlink_all']
    @line_numbers   = map['line_numbers']
    @locale_name    = map['locale_name']
    @locale_dir     = map['locale_dir']
    @main_page      = map['main_page']
    @markup         = map['markup']
    @op_dir         = map['op_dir']
    @show_hash      = map['show_hash']
    @tab_width      = map['tab_width']
    @template_dir   = map['template_dir']
    @title          = map['title']
    @visibility     = map['visibility']
    @webcvs         = map['webcvs']

    @rdoc_include = sanitize_path map['rdoc_include']
    @static_path  = sanitize_path map['static_path']
  end

  def yaml_initialize tag, map # :nodoc:
    init_with map
  end

  def override map # :nodoc:
    if map.has_key?('encoding')
      encoding = map['encoding']
      @encoding = encoding ? Encoding.find(encoding) : encoding
    end

    @charset        = map['charset']        if map.has_key?('charset')
    @exclude        = map['exclude']        if map.has_key?('exclude')
    @generator_name = map['generator_name'] if map.has_key?('generator_name')
    @hyperlink_all  = map['hyperlink_all']  if map.has_key?('hyperlink_all')
    @line_numbers   = map['line_numbers']   if map.has_key?('line_numbers')
    @locale_name    = map['locale_name']    if map.has_key?('locale_name')
    @locale_dir     = map['locale_dir']     if map.has_key?('locale_dir')
    @main_page      = map['main_page']      if map.has_key?('main_page')
    @markup         = map['markup']         if map.has_key?('markup')
    @op_dir         = map['op_dir']         if map.has_key?('op_dir')
    @show_hash      = map['show_hash']      if map.has_key?('show_hash')
    @tab_width      = map['tab_width']      if map.has_key?('tab_width')
    @template_dir   = map['template_dir']   if map.has_key?('template_dir')
    @title          = map['title']          if map.has_key?('title')
    @visibility     = map['visibility']     if map.has_key?('visibility')
    @webcvs         = map['webcvs']         if map.has_key?('webcvs')

    if map.has_key?('rdoc_include')
      @rdoc_include = sanitize_path map['rdoc_include']
    end
    if map.has_key?('static_path')
      @static_path  = sanitize_path map['static_path']
    end
  end

  def == other # :nodoc:
    self.class === other and
      @encoding       == other.encoding       and
      @generator_name == other.generator_name and
      @hyperlink_all  == other.hyperlink_all  and
      @line_numbers   == other.line_numbers   and
      @locale         == other.locale         and
      @locale_dir     == other.locale_dir and
      @main_page      == other.main_page      and
      @markup         == other.markup         and
      @op_dir         == other.op_dir         and
      @rdoc_include   == other.rdoc_include   and
      @show_hash      == other.show_hash      and
      @static_path    == other.static_path    and
      @tab_width      == other.tab_width      and
      @template       == other.template       and
      @title          == other.title          and
      @visibility     == other.visibility     and
      @webcvs         == other.webcvs
  end

  ##
  # Check that the files on the command line exist

  def check_files
    @files.delete_if do |file|
      if File.exist? file then
        if File.readable? file then
          false
        else
          warn "file '#{file}' not readable"

          true
        end
      else
        warn "file '#{file}' not found"

        true
      end
    end
  end

  ##
  # Ensure only one generator is loaded

  def check_generator
    if @generator then
      raise OptionParser::InvalidOption,
        "generator already set to #{@generator_name}"
    end
  end

  ##
  # Set the title, but only if not already set. Used to set the title
  # from a source file, so that a title set from the command line
  # will have the priority.

  def default_title=(string)
    @title ||= string
  end

  ##
  # For dumping YAML

  def encode_with coder # :nodoc:
    encoding = @encoding ? @encoding.name : nil

    coder.add 'encoding', encoding
    coder.add 'static_path',  sanitize_path(@static_path)
    coder.add 'rdoc_include', sanitize_path(@rdoc_include)

    ivars = instance_variables.map { |ivar| ivar.to_s[1..-1] }
    ivars -= SPECIAL

    ivars.sort.each do |ivar|
      coder.add ivar, instance_variable_get("@#{ivar}")
    end
  end

  ##
  # Create a regexp for #exclude

  def exclude
    if @exclude.nil? or Regexp === @exclude then
      # done, #finish is being re-run
      @exclude
    elsif @exclude.empty? then
      nil
    else
      Regexp.new(@exclude.join("|"))
    end
  end

  ##
  # Completes any unfinished option setup business such as filtering for
  # existent files, creating a regexp for #exclude and setting a default
  # #template.

  def finish
    @op_dir ||= 'doc'

    @rdoc_include << "." if @rdoc_include.empty?
    root = @root.to_s
    @rdoc_include << root unless @rdoc_include.include?(root)

    @exclude = self.exclude

    finish_page_dir

    check_files

    # If no template was specified, use the default template for the output
    # formatter

    unless @template then
      @template     = @generator_name
      @template_dir = template_dir_for @template
    end

    if @locale_name
      @locale = RDoc::I18n::Locale[@locale_name]
      @locale.load(@locale_dir)
    else
      @locale = nil
    end

    self
  end

  ##
  # Fixes the page_dir to be relative to the root_dir and adds the page_dir to
  # the files list.

  def finish_page_dir
    return unless @page_dir

    @files << @page_dir.to_s

    page_dir = nil
    begin
      page_dir = @page_dir.expand_path.relative_path_from @root
    rescue ArgumentError
      # On Windows, sometimes crosses different drive letters.
      page_dir = @page_dir.expand_path
    end

    @page_dir = page_dir
  end

  ##
  # Returns a properly-space list of generators and their descriptions.

  def generator_descriptions
    lengths = []

    generators = RDoc::RDoc::GENERATORS.map do |name, generator|
      lengths << name.length

      description = generator::DESCRIPTION if
        generator.const_defined? :DESCRIPTION

      [name, description]
    end

    longest = lengths.max

    generators.sort.map do |name, description|
      if description then
        "  %-*s - %s" % [longest, name, description]
      else
        "  #{name}"
      end
    end.join "\n"
  end

  ##
  # Parses command line options.

  def parse argv
    ignore_invalid = true

    argv.insert(0, *ENV['RDOCOPT'].split) if ENV['RDOCOPT']

    opts = OptionParser.new do |opt|
      @option_parser = opt
      opt.program_name = File.basename $0
      opt.version = RDoc::VERSION
      opt.release = nil
      opt.summary_indent = ' ' * 4
      opt.banner = <<-EOF
Usage: #{opt.program_name} [options] [names...]

  Files are parsed, and the information they contain collected, before any
  output is produced. This allows cross references between all files to be
  resolved. If a name is a directory, it is traversed. If no names are
  specified, all Ruby files in the current directory (and subdirectories) are
  processed.

  How RDoc generates output depends on the output formatter being used, and on
  the options you give.

  Options can be specified via the RDOCOPT environment variable, which
  functions similar to the RUBYOPT environment variable for ruby.

    $ export RDOCOPT="--show-hash"

  will make rdoc show hashes in method links by default.  Command-line options
  always will override those in RDOCOPT.

  Available formatters:

#{generator_descriptions}

  RDoc understands the following file formats:

      EOF

      parsers = Hash.new { |h,parser| h[parser] = [] }

      RDoc::Parser.parsers.each do |regexp, parser|
        parsers[parser.name.sub('RDoc::Parser::', '')] << regexp.source
      end

      parsers.sort.each do |parser, regexp|
        opt.banner += "  - #{parser}: #{regexp.join ', '}\n"
      end
      opt.banner += "  - TomDoc:  Only in ruby files\n"

      opt.banner += "\n  The following options are deprecated:\n\n"

      name_length = DEPRECATED.keys.sort_by { |k| k.length }.last.length

      DEPRECATED.sort_by { |k,| k }.each do |name, reason|
        opt.banner += "    %*1$2$s  %3$s\n" % [-name_length, name, reason]
      end

      opt.accept Template do |template|
        template_dir = template_dir_for template

        unless template_dir then
          $stderr.puts "could not find template #{template}"
          nil
        else
          [template, template_dir]
        end
      end

      opt.accept Directory do |directory|
        directory = File.expand_path directory

        raise OptionParser::InvalidArgument unless File.directory? directory

        directory
      end

      opt.accept Path do |path|
        path = File.expand_path path

        raise OptionParser::InvalidArgument unless File.exist? path

        path
      end

      opt.accept PathArray do |paths,|
        paths = if paths then
                  paths.split(',').map { |d| d unless d.empty? }
                end

        paths.map do |path|
          path = File.expand_path path

          raise OptionParser::InvalidArgument unless File.exist? path

          path
        end
      end

      opt.separator nil
      opt.separator "Parsing options:"
      opt.separator nil

      opt.on("--encoding=ENCODING", "-e", Encoding.list.map { |e| e.name },
             "Specifies the output encoding.  All files",
             "read will be converted to this encoding.",
             "The default encoding is UTF-8.",
             "--encoding is preferred over --charset") do |value|
               @encoding = Encoding.find value
               @charset = @encoding.name # may not be valid value
             end

      opt.separator nil

      opt.on("--locale=NAME",
             "Specifies the output locale.") do |value|
        @locale_name = value
      end

      opt.on("--locale-data-dir=DIR",
             "Specifies the directory where locale data live.") do |value|
        @locale_dir = value
      end

      opt.separator nil

      opt.on("--all", "-a",
             "Synonym for --visibility=private.") do |value|
        @visibility = :private
      end

      opt.separator nil

      opt.on("--exclude=PATTERN", "-x", Regexp,
             "Do not process files or directories",
             "matching PATTERN.") do |value|
        @exclude << value
      end

      opt.separator nil

      opt.on("--extension=NEW=OLD", "-E",
             "Treat files ending with .new as if they",
             "ended with .old. Using '-E cgi=rb' will",
             "cause xxx.cgi to be parsed as a Ruby file.") do |value|
        new, old = value.split(/=/, 2)

        unless new and old then
          raise OptionParser::InvalidArgument, "Invalid parameter to '-E'"
        end

        unless RDoc::Parser.alias_extension old, new then
          raise OptionParser::InvalidArgument, "Unknown extension .#{old} to -E"
        end
      end

      opt.separator nil

      opt.on("--[no-]force-update", "-U",
             "Forces rdoc to scan all sources even if",
             "no files are newer than the flag file.") do |value|
        @force_update = value
      end

      opt.separator nil

      opt.on("--pipe", "-p",
             "Convert RDoc on stdin to HTML") do
        @pipe = true
      end

      opt.separator nil

      opt.on("--tab-width=WIDTH", "-w", Integer,
             "Set the width of tab characters.") do |value|
        raise OptionParser::InvalidArgument,
              "#{value} is an invalid tab width" if value <= 0
        @tab_width = value
      end

      opt.separator nil

      opt.on("--visibility=VISIBILITY", "-V", RDoc::VISIBILITIES + [:nodoc],
             "Minimum visibility to document a method.",
             "One of 'public', 'protected' (the default),",
             "'private' or 'nodoc' (show everything)") do |value|
        @visibility = value
      end

      opt.separator nil

      markup_formats = RDoc::Text::MARKUP_FORMAT.keys.sort

      opt.on("--markup=MARKUP", markup_formats,
             "The markup format for the named files.",
             "The default is rdoc.  Valid values are:",
             markup_formats.join(', ')) do |value|
        @markup = value
      end

      opt.separator nil

      opt.on("--root=ROOT", Directory,
             "Root of the source tree documentation",
             "will be generated for.  Set this when",
             "building documentation outside the",
             "source directory.  Default is the",
             "current directory.") do |root|
        @root = Pathname(root)
      end

      opt.separator nil

      opt.on("--page-dir=DIR", Directory,
             "Directory where guides, your FAQ or",
             "other pages not associated with a class",
             "live.  Set this when you don't store",
             "such files at your project root.",
             "NOTE: Do not use the same file name in",
             "the page dir and the root of your project") do |page_dir|
        @page_dir = Pathname(page_dir)
      end

      opt.separator nil
      opt.separator "Common generator options:"
      opt.separator nil

      opt.on("--force-output", "-O",
             "Forces rdoc to write the output files,",
             "even if the output directory exists",
             "and does not seem to have been created",
             "by rdoc.") do |value|
        @force_output = value
      end

      opt.separator nil

      generator_text = @generators.keys.map { |name| "  #{name}" }.sort

      opt.on("-f", "--fmt=FORMAT", "--format=FORMAT", @generators.keys,
             "Set the output formatter.  One of:", *generator_text) do |value|
        check_generator

        @generator_name = value.downcase
        setup_generator
      end

      opt.separator nil

      opt.on("--include=DIRECTORIES", "-i", PathArray,
             "Set (or add to) the list of directories to",
             "be searched when satisfying :include:",
             "requests. Can be used more than once.") do |value|
        @rdoc_include.concat value.map { |dir| dir.strip }
      end

      opt.separator nil

      opt.on("--[no-]coverage-report=[LEVEL]", "--[no-]dcov", "-C", Integer,
             "Prints a report on undocumented items.",
             "Does not generate files.") do |value|
        value = 0 if value.nil? # Integer converts -C to nil

        @coverage_report = value
        @force_update = true if value
      end

      opt.separator nil

      opt.on("--output=DIR", "--op", "-o",
             "Set the output directory.") do |value|
        @op_dir = value
      end

      opt.separator nil

      opt.on("-d",
             "Deprecated --diagram option.",
             "Prevents firing debug mode",
             "with legacy invocation.") do |value|
      end

      opt.separator nil
      opt.separator 'HTML generator options:'
      opt.separator nil

      opt.on("--charset=CHARSET", "-c",
             "Specifies the output HTML character-set.",
             "Use --encoding instead of --charset if",
             "available.") do |value|
        @charset = value
      end

      opt.separator nil

      opt.on("--hyperlink-all", "-A",
             "Generate hyperlinks for all words that",
             "correspond to known methods, even if they",
             "do not start with '#' or '::' (legacy",
             "behavior).") do |value|
        @hyperlink_all = value
      end

      opt.separator nil

      opt.on("--main=NAME", "-m",
             "NAME will be the initial page displayed.") do |value|
        @main_page = value
      end

      opt.separator nil

      opt.on("--[no-]line-numbers", "-N",
             "Include line numbers in the source code.",
             "By default, only the number of the first",
             "line is displayed, in a leading comment.") do |value|
        @line_numbers = value
      end

      opt.separator nil

      opt.on("--show-hash", "-H",
             "A name of the form #name in a comment is a",
             "possible hyperlink to an instance method",
             "name. When displayed, the '#' is removed",
             "unless this option is specified.") do |value|
        @show_hash = value
      end

      opt.separator nil

      opt.on("--template=NAME", "-T", Template,
             "Set the template used when generating",
             "output. The default depends on the",
             "formatter used.") do |(template, template_dir)|
        @template     = template
        @template_dir = template_dir
      end

      opt.separator nil

      opt.on("--template-stylesheets=FILES", PathArray,
             "Set (or add to) the list of files to",
             "include with the html template.") do |value|
        @template_stylesheets << value
      end

      opt.separator nil

      opt.on("--title=TITLE", "-t",
             "Set TITLE as the title for HTML output.") do |value|
        @title = value
      end

      opt.separator nil

      opt.on("--copy-files=PATH", Path,
             "Specify a file or directory to copy static",
             "files from.",
             "If a file is given it will be copied into",
             "the output dir.  If a directory is given the",
             "entire directory will be copied.",
             "You can use this multiple times") do |value|
        @static_path << value
      end

      opt.separator nil

      opt.on("--webcvs=URL", "-W",
             "Specify a URL for linking to a web frontend",
             "to CVS. If the URL contains a '\%s', the",
             "name of the current file will be",
             "substituted; if the URL doesn't contain a",
             "'\%s', the filename will be appended to it.") do |value|
        @webcvs = value
      end

      opt.separator nil
      opt.separator "ri generator options:"
      opt.separator nil

      opt.on("--ri", "-r",
             "Generate output for use by `ri`. The files",
             "are stored in the '.rdoc' directory under",
             "your home directory unless overridden by a",
             "subsequent --op parameter, so no special",
             "privileges are needed.") do |value|
        check_generator

        @generator_name = "ri"
        @op_dir ||= RDoc::RI::Paths::HOMEDIR
        setup_generator
      end

      opt.separator nil

      opt.on("--ri-site", "-R",
             "Generate output for use by `ri`. The files",
             "are stored in a site-wide directory,",
             "making them accessible to others, so",
             "special privileges are needed.") do |value|
        check_generator

        @generator_name = "ri"
        @op_dir = RDoc::RI::Paths.site_dir
        setup_generator
      end

      opt.separator nil
      opt.separator "Generic options:"
      opt.separator nil

      opt.on("--write-options",
             "Write .rdoc_options to the current",
             "directory with the given options.  Not all",
             "options will be used.  See RDoc::Options",
             "for details.") do |value|
        @write_options = true
      end

      opt.separator nil

      opt.on("--[no-]dry-run",
             "Don't write any files") do |value|
        @dry_run = value
      end

      opt.separator nil

      opt.on("-D", "--[no-]debug",
             "Displays lots on internal stuff.") do |value|
        $DEBUG_RDOC = value
      end

      opt.separator nil

      opt.on("--[no-]ignore-invalid",
             "Ignore invalid options and continue",
             "(default true).") do |value|
        ignore_invalid = value
      end

      opt.separator nil

      opt.on("--quiet", "-q",
             "Don't show progress as we parse.") do |value|
        @verbosity = 0
      end

      opt.separator nil

      opt.on("--verbose", "-V",
             "Display extra progress as RDoc parses") do |value|
        @verbosity = 2
      end

      opt.separator nil

      opt.on("--version", "-v", "print the version") do
        puts opt.version
        exit
      end

      opt.separator nil

      opt.on("--help", "-h", "Display this help") do
        RDoc::RDoc::GENERATORS.each_key do |generator|
          setup_generator generator
        end

        puts opt.help
        exit
      end

      opt.separator nil
    end

    setup_generator 'darkfish' if
      argv.grep(/\A(-f|--fmt|--format|-r|-R|--ri|--ri-site)\b/).empty?

    deprecated = []
    invalid = []

    begin
      opts.parse! argv
    rescue OptionParser::ParseError => e
      if DEPRECATED[e.args.first] then
        deprecated << e.args.first
      elsif %w[--format --ri -r --ri-site -R].include? e.args.first then
        raise
      else
        invalid << e.args.join(' ')
      end

      retry
    end

    unless @generator then
      @generator = RDoc::Generator::Darkfish
      @generator_name = 'darkfish'
    end

    if @pipe and not argv.empty? then
      @pipe = false
      invalid << '-p (with files)'
    end

    unless quiet then
      deprecated.each do |opt|
        $stderr.puts 'option ' + opt + ' is deprecated: ' + DEPRECATED[opt]
      end
    end

    unless invalid.empty? then
      invalid = "invalid options: #{invalid.join ', '}"

      if ignore_invalid then
        unless quiet then
          $stderr.puts invalid
          $stderr.puts '(invalid options are ignored)'
        end
      else
        unless quiet then
          $stderr.puts opts
        end
        $stderr.puts invalid
        exit 1
      end
    end

    @files = argv.dup

    finish

    if @write_options then
      write_options
      exit
    end

    self
  end

  ##
  # Don't display progress as we process the files

  def quiet
    @verbosity.zero?
  end

  ##
  # Set quietness to +bool+

  def quiet= bool
    @verbosity = bool ? 0 : 1
  end

  ##
  # Removes directories from +path+ that are outside the current directory

  def sanitize_path path
    require 'pathname'
    dot = Pathname.new('.').expand_path

    path.reject do |item|
      path = Pathname.new(item).expand_path
      is_reject = nil
      relative = nil
      begin
        relative = path.relative_path_from(dot).to_s
      rescue ArgumentError
        # On Windows, sometimes crosses different drive letters.
        is_reject = true
      else
        is_reject = relative.start_with? '..'
      end
      is_reject
    end
  end

  ##
  # Set up an output generator for the named +generator_name+.
  #
  # If the found generator responds to :setup_options it will be called with
  # the options instance.  This allows generators to add custom options or set
  # default options.

  def setup_generator generator_name = @generator_name
    @generator = @generators[generator_name]

    unless @generator then
      raise OptionParser::InvalidArgument,
            "Invalid output formatter #{generator_name}"
    end

    return if @generator_options.include? @generator

    @generator_name = generator_name
    @generator_options << @generator

    if @generator.respond_to? :setup_options then
      @option_parser ||= OptionParser.new
      @generator.setup_options self
    end
  end

  ##
  # Finds the template dir for +template+

  def template_dir_for template
    template_path = File.join 'rdoc', 'generator', 'template', template

    $LOAD_PATH.map do |path|
      File.join File.expand_path(path), template_path
    end.find do |dir|
      File.directory? dir
    end
  end

  # Sets the minimum visibility of a documented method.
  #
  # Accepts +:public+, +:protected+, +:private+, +:nodoc+, or +:all+.
  #
  # When +:all+ is passed, visibility is set to +:private+, similarly to
  # RDOCOPT="--all", see #visibility for more information.

  def visibility= visibility
    case visibility
    when :all
      @visibility = :private
    else
      @visibility = visibility
    end
  end

  ##
  # Displays a warning using Kernel#warn if we're being verbose

  def warn message
    super message if @verbosity > 1
  end

  ##
  # Writes the YAML file .rdoc_options to the current directory containing the
  # parsed options.

  def write_options
    RDoc.load_yaml

    File.open '.rdoc_options', 'w' do |io|
      io.set_encoding Encoding::UTF_8

      YAML.dump self, io
    end
  end

end
# frozen_string_literal: true
require 'rdoc'

##
# Namespace for the ri command line tool's implementation.
#
# See <tt>ri --help</tt> for details.

module RDoc::RI

  ##
  # Base RI error class

  class Error < RDoc::Error; end

  autoload :Driver, 'rdoc/ri/driver'
  autoload :Paths,  'rdoc/ri/paths'
  autoload :Store,  'rdoc/ri/store'

end

# coding: UTF-8
# frozen_string_literal: true
# :markup: markdown

##
#--
# This set of literals is for Ruby 1.9 regular expressions and gives full
# unicode support.
#
# Unlike peg-markdown, this set of literals recognizes Unicode alphanumeric
# characters, newlines and spaces.
class RDoc::Markdown::Literals
  # :stopdoc:

    # This is distinct from setup_parser so that a standalone parser
    # can redefine #initialize and still have access to the proper
    # parser setup code.
    def initialize(str, debug=false)
      setup_parser(str, debug)
    end



    # Prepares for parsing +str+.  If you define a custom initialize you must
    # call this method before #parse
    def setup_parser(str, debug=false)
      set_string str, 0
      @memoizations = Hash.new { |h,k| h[k] = {} }
      @result = nil
      @failed_rule = nil
      @failing_rule_offset = -1

      setup_foreign_grammar
    end

    attr_reader :string
    attr_reader :failing_rule_offset
    attr_accessor :result, :pos

    def current_column(target=pos)
      if c = string.rindex("\n", target-1)
        return target - c - 1
      end

      target + 1
    end

    def current_line(target=pos)
      cur_offset = 0
      cur_line = 0

      string.each_line do |line|
        cur_line += 1
        cur_offset += line.size
        return cur_line if cur_offset >= target
      end

      -1
    end

    def lines
      lines = []
      string.each_line { |l| lines << l }
      lines
    end



    def get_text(start)
      @string[start..@pos-1]
    end

    # Sets the string and current parsing position for the parser.
    def set_string string, pos
      @string = string
      @string_size = string ? string.size : 0
      @pos = pos
    end

    def show_pos
      width = 10
      if @pos < width
        "#{@pos} (\"#{@string[0,@pos]}\" @ \"#{@string[@pos,width]}\")"
      else
        "#{@pos} (\"... #{@string[@pos - width, width]}\" @ \"#{@string[@pos,width]}\")"
      end
    end

    def failure_info
      l = current_line @failing_rule_offset
      c = current_column @failing_rule_offset

      if @failed_rule.kind_of? Symbol
        info = self.class::Rules[@failed_rule]
        "line #{l}, column #{c}: failed rule '#{info.name}' = '#{info.rendered}'"
      else
        "line #{l}, column #{c}: failed rule '#{@failed_rule}'"
      end
    end

    def failure_caret
      l = current_line @failing_rule_offset
      c = current_column @failing_rule_offset

      line = lines[l-1]
      "#{line}\n#{' ' * (c - 1)}^"
    end

    def failure_character
      l = current_line @failing_rule_offset
      c = current_column @failing_rule_offset
      lines[l-1][c-1, 1]
    end

    def failure_oneline
      l = current_line @failing_rule_offset
      c = current_column @failing_rule_offset

      char = lines[l-1][c-1, 1]

      if @failed_rule.kind_of? Symbol
        info = self.class::Rules[@failed_rule]
        "@#{l}:#{c} failed rule '#{info.name}', got '#{char}'"
      else
        "@#{l}:#{c} failed rule '#{@failed_rule}', got '#{char}'"
      end
    end

    class ParseError < RuntimeError
    end

    def raise_error
      raise ParseError, failure_oneline
    end

    def show_error(io=STDOUT)
      error_pos = @failing_rule_offset
      line_no = current_line(error_pos)
      col_no = current_column(error_pos)

      io.puts "On line #{line_no}, column #{col_no}:"

      if @failed_rule.kind_of? Symbol
        info = self.class::Rules[@failed_rule]
        io.puts "Failed to match '#{info.rendered}' (rule '#{info.name}')"
      else
        io.puts "Failed to match rule '#{@failed_rule}'"
      end

      io.puts "Got: #{string[error_pos,1].inspect}"
      line = lines[line_no-1]
      io.puts "=> #{line}"
      io.print(" " * (col_no + 3))
      io.puts "^"
    end

    def set_failed_rule(name)
      if @pos > @failing_rule_offset
        @failed_rule = name
        @failing_rule_offset = @pos
      end
    end

    attr_reader :failed_rule

    def match_string(str)
      len = str.size
      if @string[pos,len] == str
        @pos += len
        return str
      end

      return nil
    end

    def scan(reg)
      if m = reg.match(@string, @pos)
        @pos = m.end(0)
        return true
      end

      return nil
    end

    if "".respond_to? :ord
      def get_byte
        if @pos >= @string_size
          return nil
        end

        s = @string[@pos].ord
        @pos += 1
        s
      end
    else
      def get_byte
        if @pos >= @string_size
          return nil
        end

        s = @string[@pos]
        @pos += 1
        s
      end
    end

    def parse(rule=nil)
      # We invoke the rules indirectly via apply
      # instead of by just calling them as methods because
      # if the rules use left recursion, apply needs to
      # manage that.

      if !rule
        apply(:_root)
      else
        method = rule.gsub("-","_hyphen_")
        apply :"_#{method}"
      end
    end

    class MemoEntry
      def initialize(ans, pos)
        @ans = ans
        @pos = pos
        @result = nil
        @set = false
        @left_rec = false
      end

      attr_reader :ans, :pos, :result, :set
      attr_accessor :left_rec

      def move!(ans, pos, result)
        @ans = ans
        @pos = pos
        @result = result
        @set = true
        @left_rec = false
      end
    end

    def external_invoke(other, rule, *args)
      old_pos = @pos
      old_string = @string

      set_string other.string, other.pos

      begin
        if val = __send__(rule, *args)
          other.pos = @pos
          other.result = @result
        else
          other.set_failed_rule "#{self.class}##{rule}"
        end
        val
      ensure
        set_string old_string, old_pos
      end
    end

    def apply_with_args(rule, *args)
      memo_key = [rule, args]
      if m = @memoizations[memo_key][@pos]
        @pos = m.pos
        if !m.set
          m.left_rec = true
          return nil
        end

        @result = m.result

        return m.ans
      else
        m = MemoEntry.new(nil, @pos)
        @memoizations[memo_key][@pos] = m
        start_pos = @pos

        ans = __send__ rule, *args

        lr = m.left_rec

        m.move! ans, @pos, @result

        # Don't bother trying to grow the left recursion
        # if it's failing straight away (thus there is no seed)
        if ans and lr
          return grow_lr(rule, args, start_pos, m)
        else
          return ans
        end
      end
    end

    def apply(rule)
      if m = @memoizations[rule][@pos]
        @pos = m.pos
        if !m.set
          m.left_rec = true
          return nil
        end

        @result = m.result

        return m.ans
      else
        m = MemoEntry.new(nil, @pos)
        @memoizations[rule][@pos] = m
        start_pos = @pos

        ans = __send__ rule

        lr = m.left_rec

        m.move! ans, @pos, @result

        # Don't bother trying to grow the left recursion
        # if it's failing straight away (thus there is no seed)
        if ans and lr
          return grow_lr(rule, nil, start_pos, m)
        else
          return ans
        end
      end
    end

    def grow_lr(rule, args, start_pos, m)
      while true
        @pos = start_pos
        @result = m.result

        if args
          ans = __send__ rule, *args
        else
          ans = __send__ rule
        end
        return nil unless ans

        break if @pos <= m.pos

        m.move! ans, @pos, @result
      end

      @result = m.result
      @pos = m.pos
      return m.ans
    end

    class RuleInfo
      def initialize(name, rendered)
        @name = name
        @rendered = rendered
      end

      attr_reader :name, :rendered
    end

    def self.rule_info(name, rendered)
      RuleInfo.new(name, rendered)
    end


  # :startdoc:
  # :stopdoc:
  def setup_foreign_grammar; end

  # Alphanumeric = /\p{Word}/
  def _Alphanumeric
    _tmp = scan(/\G(?-mix:\p{Word})/)
    set_failed_rule :_Alphanumeric unless _tmp
    return _tmp
  end

  # AlphanumericAscii = /[A-Za-z0-9]/
  def _AlphanumericAscii
    _tmp = scan(/\G(?-mix:[A-Za-z0-9])/)
    set_failed_rule :_AlphanumericAscii unless _tmp
    return _tmp
  end

  # BOM = "uFEFF"
  def _BOM
    _tmp = match_string("uFEFF")
    set_failed_rule :_BOM unless _tmp
    return _tmp
  end

  # Newline = /\n|\r\n?|\p{Zl}|\p{Zp}/
  def _Newline
    _tmp = scan(/\G(?-mix:\n|\r\n?|\p{Zl}|\p{Zp})/)
    set_failed_rule :_Newline unless _tmp
    return _tmp
  end

  # NonAlphanumeric = /\p{^Word}/
  def _NonAlphanumeric
    _tmp = scan(/\G(?-mix:\p{^Word})/)
    set_failed_rule :_NonAlphanumeric unless _tmp
    return _tmp
  end

  # Spacechar = /\t|\p{Zs}/
  def _Spacechar
    _tmp = scan(/\G(?-mix:\t|\p{Zs})/)
    set_failed_rule :_Spacechar unless _tmp
    return _tmp
  end

  Rules = {}
  Rules[:_Alphanumeric] = rule_info("Alphanumeric", "/\\p{Word}/")
  Rules[:_AlphanumericAscii] = rule_info("AlphanumericAscii", "/[A-Za-z0-9]/")
  Rules[:_BOM] = rule_info("BOM", "\"uFEFF\"")
  Rules[:_Newline] = rule_info("Newline", "/\\n|\\r\\n?|\\p{Zl}|\\p{Zp}/")
  Rules[:_NonAlphanumeric] = rule_info("NonAlphanumeric", "/\\p{^Word}/")
  Rules[:_Spacechar] = rule_info("Spacechar", "/\\t|\\p{Zs}/")
  # :startdoc:
end
# frozen_string_literal: true
##
# HTML entity name map for RDoc::Markdown

RDoc::Markdown::HTML_ENTITIES = {
  "AElig" => [0x000C6],
  "AMP" => [0x00026],
  "Aacute" => [0x000C1],
  "Abreve" => [0x00102],
  "Acirc" => [0x000C2],
  "Acy" => [0x00410],
  "Afr" => [0x1D504],
  "Agrave" => [0x000C0],
  "Alpha" => [0x00391],
  "Amacr" => [0x00100],
  "And" => [0x02A53],
  "Aogon" => [0x00104],
  "Aopf" => [0x1D538],
  "ApplyFunction" => [0x02061],
  "Aring" => [0x000C5],
  "Ascr" => [0x1D49C],
  "Assign" => [0x02254],
  "Atilde" => [0x000C3],
  "Auml" => [0x000C4],
  "Backslash" => [0x02216],
  "Barv" => [0x02AE7],
  "Barwed" => [0x02306],
  "Bcy" => [0x00411],
  "Because" => [0x02235],
  "Bernoullis" => [0x0212C],
  "Beta" => [0x00392],
  "Bfr" => [0x1D505],
  "Bopf" => [0x1D539],
  "Breve" => [0x002D8],
  "Bscr" => [0x0212C],
  "Bumpeq" => [0x0224E],
  "CHcy" => [0x00427],
  "COPY" => [0x000A9],
  "Cacute" => [0x00106],
  "Cap" => [0x022D2],
  "CapitalDifferentialD" => [0x02145],
  "Cayleys" => [0x0212D],
  "Ccaron" => [0x0010C],
  "Ccedil" => [0x000C7],
  "Ccirc" => [0x00108],
  "Cconint" => [0x02230],
  "Cdot" => [0x0010A],
  "Cedilla" => [0x000B8],
  "CenterDot" => [0x000B7],
  "Cfr" => [0x0212D],
  "Chi" => [0x003A7],
  "CircleDot" => [0x02299],
  "CircleMinus" => [0x02296],
  "CirclePlus" => [0x02295],
  "CircleTimes" => [0x02297],
  "ClockwiseContourIntegral" => [0x02232],
  "CloseCurlyDoubleQuote" => [0x0201D],
  "CloseCurlyQuote" => [0x02019],
  "Colon" => [0x02237],
  "Colone" => [0x02A74],
  "Congruent" => [0x02261],
  "Conint" => [0x0222F],
  "ContourIntegral" => [0x0222E],
  "Copf" => [0x02102],
  "Coproduct" => [0x02210],
  "CounterClockwiseContourIntegral" => [0x02233],
  "Cross" => [0x02A2F],
  "Cscr" => [0x1D49E],
  "Cup" => [0x022D3],
  "CupCap" => [0x0224D],
  "DD" => [0x02145],
  "DDotrahd" => [0x02911],
  "DJcy" => [0x00402],
  "DScy" => [0x00405],
  "DZcy" => [0x0040F],
  "Dagger" => [0x02021],
  "Darr" => [0x021A1],
  "Dashv" => [0x02AE4],
  "Dcaron" => [0x0010E],
  "Dcy" => [0x00414],
  "Del" => [0x02207],
  "Delta" => [0x00394],
  "Dfr" => [0x1D507],
  "DiacriticalAcute" => [0x000B4],
  "DiacriticalDot" => [0x002D9],
  "DiacriticalDoubleAcute" => [0x002DD],
  "DiacriticalGrave" => [0x00060],
  "DiacriticalTilde" => [0x002DC],
  "Diamond" => [0x022C4],
  "DifferentialD" => [0x02146],
  "Dopf" => [0x1D53B],
  "Dot" => [0x000A8],
  "DotDot" => [0x020DC],
  "DotEqual" => [0x02250],
  "DoubleContourIntegral" => [0x0222F],
  "DoubleDot" => [0x000A8],
  "DoubleDownArrow" => [0x021D3],
  "DoubleLeftArrow" => [0x021D0],
  "DoubleLeftRightArrow" => [0x021D4],
  "DoubleLeftTee" => [0x02AE4],
  "DoubleLongLeftArrow" => [0x027F8],
  "DoubleLongLeftRightArrow" => [0x027FA],
  "DoubleLongRightArrow" => [0x027F9],
  "DoubleRightArrow" => [0x021D2],
  "DoubleRightTee" => [0x022A8],
  "DoubleUpArrow" => [0x021D1],
  "DoubleUpDownArrow" => [0x021D5],
  "DoubleVerticalBar" => [0x02225],
  "DownArrow" => [0x02193],
  "DownArrowBar" => [0x02913],
  "DownArrowUpArrow" => [0x021F5],
  "DownBreve" => [0x00311],
  "DownLeftRightVector" => [0x02950],
  "DownLeftTeeVector" => [0x0295E],
  "DownLeftVector" => [0x021BD],
  "DownLeftVectorBar" => [0x02956],
  "DownRightTeeVector" => [0x0295F],
  "DownRightVector" => [0x021C1],
  "DownRightVectorBar" => [0x02957],
  "DownTee" => [0x022A4],
  "DownTeeArrow" => [0x021A7],
  "Downarrow" => [0x021D3],
  "Dscr" => [0x1D49F],
  "Dstrok" => [0x00110],
  "ENG" => [0x0014A],
  "ETH" => [0x000D0],
  "Eacute" => [0x000C9],
  "Ecaron" => [0x0011A],
  "Ecirc" => [0x000CA],
  "Ecy" => [0x0042D],
  "Edot" => [0x00116],
  "Efr" => [0x1D508],
  "Egrave" => [0x000C8],
  "Element" => [0x02208],
  "Emacr" => [0x00112],
  "EmptySmallSquare" => [0x025FB],
  "EmptyVerySmallSquare" => [0x025AB],
  "Eogon" => [0x00118],
  "Eopf" => [0x1D53C],
  "Epsilon" => [0x00395],
  "Equal" => [0x02A75],
  "EqualTilde" => [0x02242],
  "Equilibrium" => [0x021CC],
  "Escr" => [0x02130],
  "Esim" => [0x02A73],
  "Eta" => [0x00397],
  "Euml" => [0x000CB],
  "Exists" => [0x02203],
  "ExponentialE" => [0x02147],
  "Fcy" => [0x00424],
  "Ffr" => [0x1D509],
  "FilledSmallSquare" => [0x025FC],
  "FilledVerySmallSquare" => [0x025AA],
  "Fopf" => [0x1D53D],
  "ForAll" => [0x02200],
  "Fouriertrf" => [0x02131],
  "Fscr" => [0x02131],
  "GJcy" => [0x00403],
  "GT" => [0x0003E],
  "Gamma" => [0x00393],
  "Gammad" => [0x003DC],
  "Gbreve" => [0x0011E],
  "Gcedil" => [0x00122],
  "Gcirc" => [0x0011C],
  "Gcy" => [0x00413],
  "Gdot" => [0x00120],
  "Gfr" => [0x1D50A],
  "Gg" => [0x022D9],
  "Gopf" => [0x1D53E],
  "GreaterEqual" => [0x02265],
  "GreaterEqualLess" => [0x022DB],
  "GreaterFullEqual" => [0x02267],
  "GreaterGreater" => [0x02AA2],
  "GreaterLess" => [0x02277],
  "GreaterSlantEqual" => [0x02A7E],
  "GreaterTilde" => [0x02273],
  "Gscr" => [0x1D4A2],
  "Gt" => [0x0226B],
  "HARDcy" => [0x0042A],
  "Hacek" => [0x002C7],
  "Hat" => [0x0005E],
  "Hcirc" => [0x00124],
  "Hfr" => [0x0210C],
  "HilbertSpace" => [0x0210B],
  "Hopf" => [0x0210D],
  "HorizontalLine" => [0x02500],
  "Hscr" => [0x0210B],
  "Hstrok" => [0x00126],
  "HumpDownHump" => [0x0224E],
  "HumpEqual" => [0x0224F],
  "IEcy" => [0x00415],
  "IJlig" => [0x00132],
  "IOcy" => [0x00401],
  "Iacute" => [0x000CD],
  "Icirc" => [0x000CE],
  "Icy" => [0x00418],
  "Idot" => [0x00130],
  "Ifr" => [0x02111],
  "Igrave" => [0x000CC],
  "Im" => [0x02111],
  "Imacr" => [0x0012A],
  "ImaginaryI" => [0x02148],
  "Implies" => [0x021D2],
  "Int" => [0x0222C],
  "Integral" => [0x0222B],
  "Intersection" => [0x022C2],
  "InvisibleComma" => [0x02063],
  "InvisibleTimes" => [0x02062],
  "Iogon" => [0x0012E],
  "Iopf" => [0x1D540],
  "Iota" => [0x00399],
  "Iscr" => [0x02110],
  "Itilde" => [0x00128],
  "Iukcy" => [0x00406],
  "Iuml" => [0x000CF],
  "Jcirc" => [0x00134],
  "Jcy" => [0x00419],
  "Jfr" => [0x1D50D],
  "Jopf" => [0x1D541],
  "Jscr" => [0x1D4A5],
  "Jsercy" => [0x00408],
  "Jukcy" => [0x00404],
  "KHcy" => [0x00425],
  "KJcy" => [0x0040C],
  "Kappa" => [0x0039A],
  "Kcedil" => [0x00136],
  "Kcy" => [0x0041A],
  "Kfr" => [0x1D50E],
  "Kopf" => [0x1D542],
  "Kscr" => [0x1D4A6],
  "LJcy" => [0x00409],
  "LT" => [0x0003C],
  "Lacute" => [0x00139],
  "Lambda" => [0x0039B],
  "Lang" => [0x027EA],
  "Laplacetrf" => [0x02112],
  "Larr" => [0x0219E],
  "Lcaron" => [0x0013D],
  "Lcedil" => [0x0013B],
  "Lcy" => [0x0041B],
  "LeftAngleBracket" => [0x027E8],
  "LeftArrow" => [0x02190],
  "LeftArrowBar" => [0x021E4],
  "LeftArrowRightArrow" => [0x021C6],
  "LeftCeiling" => [0x02308],
  "LeftDoubleBracket" => [0x027E6],
  "LeftDownTeeVector" => [0x02961],
  "LeftDownVector" => [0x021C3],
  "LeftDownVectorBar" => [0x02959],
  "LeftFloor" => [0x0230A],
  "LeftRightArrow" => [0x02194],
  "LeftRightVector" => [0x0294E],
  "LeftTee" => [0x022A3],
  "LeftTeeArrow" => [0x021A4],
  "LeftTeeVector" => [0x0295A],
  "LeftTriangle" => [0x022B2],
  "LeftTriangleBar" => [0x029CF],
  "LeftTriangleEqual" => [0x022B4],
  "LeftUpDownVector" => [0x02951],
  "LeftUpTeeVector" => [0x02960],
  "LeftUpVector" => [0x021BF],
  "LeftUpVectorBar" => [0x02958],
  "LeftVector" => [0x021BC],
  "LeftVectorBar" => [0x02952],
  "Leftarrow" => [0x021D0],
  "Leftrightarrow" => [0x021D4],
  "LessEqualGreater" => [0x022DA],
  "LessFullEqual" => [0x02266],
  "LessGreater" => [0x02276],
  "LessLess" => [0x02AA1],
  "LessSlantEqual" => [0x02A7D],
  "LessTilde" => [0x02272],
  "Lfr" => [0x1D50F],
  "Ll" => [0x022D8],
  "Lleftarrow" => [0x021DA],
  "Lmidot" => [0x0013F],
  "LongLeftArrow" => [0x027F5],
  "LongLeftRightArrow" => [0x027F7],
  "LongRightArrow" => [0x027F6],
  "Longleftarrow" => [0x027F8],
  "Longleftrightarrow" => [0x027FA],
  "Longrightarrow" => [0x027F9],
  "Lopf" => [0x1D543],
  "LowerLeftArrow" => [0x02199],
  "LowerRightArrow" => [0x02198],
  "Lscr" => [0x02112],
  "Lsh" => [0x021B0],
  "Lstrok" => [0x00141],
  "Lt" => [0x0226A],
  "Map" => [0x02905],
  "Mcy" => [0x0041C],
  "MediumSpace" => [0x0205F],
  "Mellintrf" => [0x02133],
  "Mfr" => [0x1D510],
  "MinusPlus" => [0x02213],
  "Mopf" => [0x1D544],
  "Mscr" => [0x02133],
  "Mu" => [0x0039C],
  "NJcy" => [0x0040A],
  "Nacute" => [0x00143],
  "Ncaron" => [0x00147],
  "Ncedil" => [0x00145],
  "Ncy" => [0x0041D],
  "NegativeMediumSpace" => [0x0200B],
  "NegativeThickSpace" => [0x0200B],
  "NegativeThinSpace" => [0x0200B],
  "NegativeVeryThinSpace" => [0x0200B],
  "NestedGreaterGreater" => [0x0226B],
  "NestedLessLess" => [0x0226A],
  "NewLine" => [0x0000A],
  "Nfr" => [0x1D511],
  "NoBreak" => [0x02060],
  "NonBreakingSpace" => [0x000A0],
  "Nopf" => [0x02115],
  "Not" => [0x02AEC],
  "NotCongruent" => [0x02262],
  "NotCupCap" => [0x0226D],
  "NotDoubleVerticalBar" => [0x02226],
  "NotElement" => [0x02209],
  "NotEqual" => [0x02260],
  "NotEqualTilde" => [0x02242, 0x00338],
  "NotExists" => [0x02204],
  "NotGreater" => [0x0226F],
  "NotGreaterEqual" => [0x02271],
  "NotGreaterFullEqual" => [0x02267, 0x00338],
  "NotGreaterGreater" => [0x0226B, 0x00338],
  "NotGreaterLess" => [0x02279],
  "NotGreaterSlantEqual" => [0x02A7E, 0x00338],
  "NotGreaterTilde" => [0x02275],
  "NotHumpDownHump" => [0x0224E, 0x00338],
  "NotHumpEqual" => [0x0224F, 0x00338],
  "NotLeftTriangle" => [0x022EA],
  "NotLeftTriangleBar" => [0x029CF, 0x00338],
  "NotLeftTriangleEqual" => [0x022EC],
  "NotLess" => [0x0226E],
  "NotLessEqual" => [0x02270],
  "NotLessGreater" => [0x02278],
  "NotLessLess" => [0x0226A, 0x00338],
  "NotLessSlantEqual" => [0x02A7D, 0x00338],
  "NotLessTilde" => [0x02274],
  "NotNestedGreaterGreater" => [0x02AA2, 0x00338],
  "NotNestedLessLess" => [0x02AA1, 0x00338],
  "NotPrecedes" => [0x02280],
  "NotPrecedesEqual" => [0x02AAF, 0x00338],
  "NotPrecedesSlantEqual" => [0x022E0],
  "NotReverseElement" => [0x0220C],
  "NotRightTriangle" => [0x022EB],
  "NotRightTriangleBar" => [0x029D0, 0x00338],
  "NotRightTriangleEqual" => [0x022ED],
  "NotSquareSubset" => [0x0228F, 0x00338],
  "NotSquareSubsetEqual" => [0x022E2],
  "NotSquareSuperset" => [0x02290, 0x00338],
  "NotSquareSupersetEqual" => [0x022E3],
  "NotSubset" => [0x02282, 0x020D2],
  "NotSubsetEqual" => [0x02288],
  "NotSucceeds" => [0x02281],
  "NotSucceedsEqual" => [0x02AB0, 0x00338],
  "NotSucceedsSlantEqual" => [0x022E1],
  "NotSucceedsTilde" => [0x0227F, 0x00338],
  "NotSuperset" => [0x02283, 0x020D2],
  "NotSupersetEqual" => [0x02289],
  "NotTilde" => [0x02241],
  "NotTildeEqual" => [0x02244],
  "NotTildeFullEqual" => [0x02247],
  "NotTildeTilde" => [0x02249],
  "NotVerticalBar" => [0x02224],
  "Nscr" => [0x1D4A9],
  "Ntilde" => [0x000D1],
  "Nu" => [0x0039D],
  "OElig" => [0x00152],
  "Oacute" => [0x000D3],
  "Ocirc" => [0x000D4],
  "Ocy" => [0x0041E],
  "Odblac" => [0x00150],
  "Ofr" => [0x1D512],
  "Ograve" => [0x000D2],
  "Omacr" => [0x0014C],
  "Omega" => [0x003A9],
  "Omicron" => [0x0039F],
  "Oopf" => [0x1D546],
  "OpenCurlyDoubleQuote" => [0x0201C],
  "OpenCurlyQuote" => [0x02018],
  "Or" => [0x02A54],
  "Oscr" => [0x1D4AA],
  "Oslash" => [0x000D8],
  "Otilde" => [0x000D5],
  "Otimes" => [0x02A37],
  "Ouml" => [0x000D6],
  "OverBar" => [0x0203E],
  "OverBrace" => [0x023DE],
  "OverBracket" => [0x023B4],
  "OverParenthesis" => [0x023DC],
  "PartialD" => [0x02202],
  "Pcy" => [0x0041F],
  "Pfr" => [0x1D513],
  "Phi" => [0x003A6],
  "Pi" => [0x003A0],
  "PlusMinus" => [0x000B1],
  "Poincareplane" => [0x0210C],
  "Popf" => [0x02119],
  "Pr" => [0x02ABB],
  "Precedes" => [0x0227A],
  "PrecedesEqual" => [0x02AAF],
  "PrecedesSlantEqual" => [0x0227C],
  "PrecedesTilde" => [0x0227E],
  "Prime" => [0x02033],
  "Product" => [0x0220F],
  "Proportion" => [0x02237],
  "Proportional" => [0x0221D],
  "Pscr" => [0x1D4AB],
  "Psi" => [0x003A8],
  "QUOT" => [0x00022],
  "Qfr" => [0x1D514],
  "Qopf" => [0x0211A],
  "Qscr" => [0x1D4AC],
  "RBarr" => [0x02910],
  "REG" => [0x000AE],
  "Racute" => [0x00154],
  "Rang" => [0x027EB],
  "Rarr" => [0x021A0],
  "Rarrtl" => [0x02916],
  "Rcaron" => [0x00158],
  "Rcedil" => [0x00156],
  "Rcy" => [0x00420],
  "Re" => [0x0211C],
  "ReverseElement" => [0x0220B],
  "ReverseEquilibrium" => [0x021CB],
  "ReverseUpEquilibrium" => [0x0296F],
  "Rfr" => [0x0211C],
  "Rho" => [0x003A1],
  "RightAngleBracket" => [0x027E9],
  "RightArrow" => [0x02192],
  "RightArrowBar" => [0x021E5],
  "RightArrowLeftArrow" => [0x021C4],
  "RightCeiling" => [0x02309],
  "RightDoubleBracket" => [0x027E7],
  "RightDownTeeVector" => [0x0295D],
  "RightDownVector" => [0x021C2],
  "RightDownVectorBar" => [0x02955],
  "RightFloor" => [0x0230B],
  "RightTee" => [0x022A2],
  "RightTeeArrow" => [0x021A6],
  "RightTeeVector" => [0x0295B],
  "RightTriangle" => [0x022B3],
  "RightTriangleBar" => [0x029D0],
  "RightTriangleEqual" => [0x022B5],
  "RightUpDownVector" => [0x0294F],
  "RightUpTeeVector" => [0x0295C],
  "RightUpVector" => [0x021BE],
  "RightUpVectorBar" => [0x02954],
  "RightVector" => [0x021C0],
  "RightVectorBar" => [0x02953],
  "Rightarrow" => [0x021D2],
  "Ropf" => [0x0211D],
  "RoundImplies" => [0x02970],
  "Rrightarrow" => [0x021DB],
  "Rscr" => [0x0211B],
  "Rsh" => [0x021B1],
  "RuleDelayed" => [0x029F4],
  "SHCHcy" => [0x00429],
  "SHcy" => [0x00428],
  "SOFTcy" => [0x0042C],
  "Sacute" => [0x0015A],
  "Sc" => [0x02ABC],
  "Scaron" => [0x00160],
  "Scedil" => [0x0015E],
  "Scirc" => [0x0015C],
  "Scy" => [0x00421],
  "Sfr" => [0x1D516],
  "ShortDownArrow" => [0x02193],
  "ShortLeftArrow" => [0x02190],
  "ShortRightArrow" => [0x02192],
  "ShortUpArrow" => [0x02191],
  "Sigma" => [0x003A3],
  "SmallCircle" => [0x02218],
  "Sopf" => [0x1D54A],
  "Sqrt" => [0x0221A],
  "Square" => [0x025A1],
  "SquareIntersection" => [0x02293],
  "SquareSubset" => [0x0228F],
  "SquareSubsetEqual" => [0x02291],
  "SquareSuperset" => [0x02290],
  "SquareSupersetEqual" => [0x02292],
  "SquareUnion" => [0x02294],
  "Sscr" => [0x1D4AE],
  "Star" => [0x022C6],
  "Sub" => [0x022D0],
  "Subset" => [0x022D0],
  "SubsetEqual" => [0x02286],
  "Succeeds" => [0x0227B],
  "SucceedsEqual" => [0x02AB0],
  "SucceedsSlantEqual" => [0x0227D],
  "SucceedsTilde" => [0x0227F],
  "SuchThat" => [0x0220B],
  "Sum" => [0x02211],
  "Sup" => [0x022D1],
  "Superset" => [0x02283],
  "SupersetEqual" => [0x02287],
  "Supset" => [0x022D1],
  "THORN" => [0x000DE],
  "TRADE" => [0x02122],
  "TSHcy" => [0x0040B],
  "TScy" => [0x00426],
  "Tab" => [0x00009],
  "Tau" => [0x003A4],
  "Tcaron" => [0x00164],
  "Tcedil" => [0x00162],
  "Tcy" => [0x00422],
  "Tfr" => [0x1D517],
  "Therefore" => [0x02234],
  "Theta" => [0x00398],
  "ThickSpace" => [0x0205F, 0x0200A],
  "ThinSpace" => [0x02009],
  "Tilde" => [0x0223C],
  "TildeEqual" => [0x02243],
  "TildeFullEqual" => [0x02245],
  "TildeTilde" => [0x02248],
  "Topf" => [0x1D54B],
  "TripleDot" => [0x020DB],
  "Tscr" => [0x1D4AF],
  "Tstrok" => [0x00166],
  "Uacute" => [0x000DA],
  "Uarr" => [0x0219F],
  "Uarrocir" => [0x02949],
  "Ubrcy" => [0x0040E],
  "Ubreve" => [0x0016C],
  "Ucirc" => [0x000DB],
  "Ucy" => [0x00423],
  "Udblac" => [0x00170],
  "Ufr" => [0x1D518],
  "Ugrave" => [0x000D9],
  "Umacr" => [0x0016A],
  "UnderBar" => [0x0005F],
  "UnderBrace" => [0x023DF],
  "UnderBracket" => [0x023B5],
  "UnderParenthesis" => [0x023DD],
  "Union" => [0x022C3],
  "UnionPlus" => [0x0228E],
  "Uogon" => [0x00172],
  "Uopf" => [0x1D54C],
  "UpArrow" => [0x02191],
  "UpArrowBar" => [0x02912],
  "UpArrowDownArrow" => [0x021C5],
  "UpDownArrow" => [0x02195],
  "UpEquilibrium" => [0x0296E],
  "UpTee" => [0x022A5],
  "UpTeeArrow" => [0x021A5],
  "Uparrow" => [0x021D1],
  "Updownarrow" => [0x021D5],
  "UpperLeftArrow" => [0x02196],
  "UpperRightArrow" => [0x02197],
  "Upsi" => [0x003D2],
  "Upsilon" => [0x003A5],
  "Uring" => [0x0016E],
  "Uscr" => [0x1D4B0],
  "Utilde" => [0x00168],
  "Uuml" => [0x000DC],
  "VDash" => [0x022AB],
  "Vbar" => [0x02AEB],
  "Vcy" => [0x00412],
  "Vdash" => [0x022A9],
  "Vdashl" => [0x02AE6],
  "Vee" => [0x022C1],
  "Verbar" => [0x02016],
  "Vert" => [0x02016],
  "VerticalBar" => [0x02223],
  "VerticalLine" => [0x0007C],
  "VerticalSeparator" => [0x02758],
  "VerticalTilde" => [0x02240],
  "VeryThinSpace" => [0x0200A],
  "Vfr" => [0x1D519],
  "Vopf" => [0x1D54D],
  "Vscr" => [0x1D4B1],
  "Vvdash" => [0x022AA],
  "Wcirc" => [0x00174],
  "Wedge" => [0x022C0],
  "Wfr" => [0x1D51A],
  "Wopf" => [0x1D54E],
  "Wscr" => [0x1D4B2],
  "Xfr" => [0x1D51B],
  "Xi" => [0x0039E],
  "Xopf" => [0x1D54F],
  "Xscr" => [0x1D4B3],
  "YAcy" => [0x0042F],
  "YIcy" => [0x00407],
  "YUcy" => [0x0042E],
  "Yacute" => [0x000DD],
  "Ycirc" => [0x00176],
  "Ycy" => [0x0042B],
  "Yfr" => [0x1D51C],
  "Yopf" => [0x1D550],
  "Yscr" => [0x1D4B4],
  "Yuml" => [0x00178],
  "ZHcy" => [0x00416],
  "Zacute" => [0x00179],
  "Zcaron" => [0x0017D],
  "Zcy" => [0x00417],
  "Zdot" => [0x0017B],
  "ZeroWidthSpace" => [0x0200B],
  "Zeta" => [0x00396],
  "Zfr" => [0x02128],
  "Zopf" => [0x02124],
  "Zscr" => [0x1D4B5],
  "aacute" => [0x000E1],
  "abreve" => [0x00103],
  "ac" => [0x0223E],
  "acE" => [0x0223E, 0x00333],
  "acd" => [0x0223F],
  "acirc" => [0x000E2],
  "acute" => [0x000B4],
  "acy" => [0x00430],
  "aelig" => [0x000E6],
  "af" => [0x02061],
  "afr" => [0x1D51E],
  "agrave" => [0x000E0],
  "alefsym" => [0x02135],
  "aleph" => [0x02135],
  "alpha" => [0x003B1],
  "amacr" => [0x00101],
  "amalg" => [0x02A3F],
  "amp" => [0x00026],
  "and" => [0x02227],
  "andand" => [0x02A55],
  "andd" => [0x02A5C],
  "andslope" => [0x02A58],
  "andv" => [0x02A5A],
  "ang" => [0x02220],
  "ange" => [0x029A4],
  "angle" => [0x02220],
  "angmsd" => [0x02221],
  "angmsdaa" => [0x029A8],
  "angmsdab" => [0x029A9],
  "angmsdac" => [0x029AA],
  "angmsdad" => [0x029AB],
  "angmsdae" => [0x029AC],
  "angmsdaf" => [0x029AD],
  "angmsdag" => [0x029AE],
  "angmsdah" => [0x029AF],
  "angrt" => [0x0221F],
  "angrtvb" => [0x022BE],
  "angrtvbd" => [0x0299D],
  "angsph" => [0x02222],
  "angst" => [0x000C5],
  "angzarr" => [0x0237C],
  "aogon" => [0x00105],
  "aopf" => [0x1D552],
  "ap" => [0x02248],
  "apE" => [0x02A70],
  "apacir" => [0x02A6F],
  "ape" => [0x0224A],
  "apid" => [0x0224B],
  "apos" => [0x00027],
  "approx" => [0x02248],
  "approxeq" => [0x0224A],
  "aring" => [0x000E5],
  "ascr" => [0x1D4B6],
  "ast" => [0x0002A],
  "asymp" => [0x02248],
  "asympeq" => [0x0224D],
  "atilde" => [0x000E3],
  "auml" => [0x000E4],
  "awconint" => [0x02233],
  "awint" => [0x02A11],
  "bNot" => [0x02AED],
  "backcong" => [0x0224C],
  "backepsilon" => [0x003F6],
  "backprime" => [0x02035],
  "backsim" => [0x0223D],
  "backsimeq" => [0x022CD],
  "barvee" => [0x022BD],
  "barwed" => [0x02305],
  "barwedge" => [0x02305],
  "bbrk" => [0x023B5],
  "bbrktbrk" => [0x023B6],
  "bcong" => [0x0224C],
  "bcy" => [0x00431],
  "bdquo" => [0x0201E],
  "becaus" => [0x02235],
  "because" => [0x02235],
  "bemptyv" => [0x029B0],
  "bepsi" => [0x003F6],
  "bernou" => [0x0212C],
  "beta" => [0x003B2],
  "beth" => [0x02136],
  "between" => [0x0226C],
  "bfr" => [0x1D51F],
  "bigcap" => [0x022C2],
  "bigcirc" => [0x025EF],
  "bigcup" => [0x022C3],
  "bigodot" => [0x02A00],
  "bigoplus" => [0x02A01],
  "bigotimes" => [0x02A02],
  "bigsqcup" => [0x02A06],
  "bigstar" => [0x02605],
  "bigtriangledown" => [0x025BD],
  "bigtriangleup" => [0x025B3],
  "biguplus" => [0x02A04],
  "bigvee" => [0x022C1],
  "bigwedge" => [0x022C0],
  "bkarow" => [0x0290D],
  "blacklozenge" => [0x029EB],
  "blacksquare" => [0x025AA],
  "blacktriangle" => [0x025B4],
  "blacktriangledown" => [0x025BE],
  "blacktriangleleft" => [0x025C2],
  "blacktriangleright" => [0x025B8],
  "blank" => [0x02423],
  "blk12" => [0x02592],
  "blk14" => [0x02591],
  "blk34" => [0x02593],
  "block" => [0x02588],
  "bne" => [0x0003D, 0x020E5],
  "bnequiv" => [0x02261, 0x020E5],
  "bnot" => [0x02310],
  "bopf" => [0x1D553],
  "bot" => [0x022A5],
  "bottom" => [0x022A5],
  "bowtie" => [0x022C8],
  "boxDL" => [0x02557],
  "boxDR" => [0x02554],
  "boxDl" => [0x02556],
  "boxDr" => [0x02553],
  "boxH" => [0x02550],
  "boxHD" => [0x02566],
  "boxHU" => [0x02569],
  "boxHd" => [0x02564],
  "boxHu" => [0x02567],
  "boxUL" => [0x0255D],
  "boxUR" => [0x0255A],
  "boxUl" => [0x0255C],
  "boxUr" => [0x02559],
  "boxV" => [0x02551],
  "boxVH" => [0x0256C],
  "boxVL" => [0x02563],
  "boxVR" => [0x02560],
  "boxVh" => [0x0256B],
  "boxVl" => [0x02562],
  "boxVr" => [0x0255F],
  "boxbox" => [0x029C9],
  "boxdL" => [0x02555],
  "boxdR" => [0x02552],
  "boxdl" => [0x02510],
  "boxdr" => [0x0250C],
  "boxh" => [0x02500],
  "boxhD" => [0x02565],
  "boxhU" => [0x02568],
  "boxhd" => [0x0252C],
  "boxhu" => [0x02534],
  "boxminus" => [0x0229F],
  "boxplus" => [0x0229E],
  "boxtimes" => [0x022A0],
  "boxuL" => [0x0255B],
  "boxuR" => [0x02558],
  "boxul" => [0x02518],
  "boxur" => [0x02514],
  "boxv" => [0x02502],
  "boxvH" => [0x0256A],
  "boxvL" => [0x02561],
  "boxvR" => [0x0255E],
  "boxvh" => [0x0253C],
  "boxvl" => [0x02524],
  "boxvr" => [0x0251C],
  "bprime" => [0x02035],
  "breve" => [0x002D8],
  "brvbar" => [0x000A6],
  "bscr" => [0x1D4B7],
  "bsemi" => [0x0204F],
  "bsim" => [0x0223D],
  "bsime" => [0x022CD],
  "bsol" => [0x0005C],
  "bsolb" => [0x029C5],
  "bsolhsub" => [0x027C8],
  "bull" => [0x02022],
  "bullet" => [0x02022],
  "bump" => [0x0224E],
  "bumpE" => [0x02AAE],
  "bumpe" => [0x0224F],
  "bumpeq" => [0x0224F],
  "cacute" => [0x00107],
  "cap" => [0x02229],
  "capand" => [0x02A44],
  "capbrcup" => [0x02A49],
  "capcap" => [0x02A4B],
  "capcup" => [0x02A47],
  "capdot" => [0x02A40],
  "caps" => [0x02229, 0x0FE00],
  "caret" => [0x02041],
  "caron" => [0x002C7],
  "ccaps" => [0x02A4D],
  "ccaron" => [0x0010D],
  "ccedil" => [0x000E7],
  "ccirc" => [0x00109],
  "ccups" => [0x02A4C],
  "ccupssm" => [0x02A50],
  "cdot" => [0x0010B],
  "cedil" => [0x000B8],
  "cemptyv" => [0x029B2],
  "cent" => [0x000A2],
  "centerdot" => [0x000B7],
  "cfr" => [0x1D520],
  "chcy" => [0x00447],
  "check" => [0x02713],
  "checkmark" => [0x02713],
  "chi" => [0x003C7],
  "cir" => [0x025CB],
  "cirE" => [0x029C3],
  "circ" => [0x002C6],
  "circeq" => [0x02257],
  "circlearrowleft" => [0x021BA],
  "circlearrowright" => [0x021BB],
  "circledR" => [0x000AE],
  "circledS" => [0x024C8],
  "circledast" => [0x0229B],
  "circledcirc" => [0x0229A],
  "circleddash" => [0x0229D],
  "cire" => [0x02257],
  "cirfnint" => [0x02A10],
  "cirmid" => [0x02AEF],
  "cirscir" => [0x029C2],
  "clubs" => [0x02663],
  "clubsuit" => [0x02663],
  "colon" => [0x0003A],
  "colone" => [0x02254],
  "coloneq" => [0x02254],
  "comma" => [0x0002C],
  "commat" => [0x00040],
  "comp" => [0x02201],
  "compfn" => [0x02218],
  "complement" => [0x02201],
  "complexes" => [0x02102],
  "cong" => [0x02245],
  "congdot" => [0x02A6D],
  "conint" => [0x0222E],
  "copf" => [0x1D554],
  "coprod" => [0x02210],
  "copy" => [0x000A9],
  "copysr" => [0x02117],
  "crarr" => [0x021B5],
  "cross" => [0x02717],
  "cscr" => [0x1D4B8],
  "csub" => [0x02ACF],
  "csube" => [0x02AD1],
  "csup" => [0x02AD0],
  "csupe" => [0x02AD2],
  "ctdot" => [0x022EF],
  "cudarrl" => [0x02938],
  "cudarrr" => [0x02935],
  "cuepr" => [0x022DE],
  "cuesc" => [0x022DF],
  "cularr" => [0x021B6],
  "cularrp" => [0x0293D],
  "cup" => [0x0222A],
  "cupbrcap" => [0x02A48],
  "cupcap" => [0x02A46],
  "cupcup" => [0x02A4A],
  "cupdot" => [0x0228D],
  "cupor" => [0x02A45],
  "cups" => [0x0222A, 0x0FE00],
  "curarr" => [0x021B7],
  "curarrm" => [0x0293C],
  "curlyeqprec" => [0x022DE],
  "curlyeqsucc" => [0x022DF],
  "curlyvee" => [0x022CE],
  "curlywedge" => [0x022CF],
  "curren" => [0x000A4],
  "curvearrowleft" => [0x021B6],
  "curvearrowright" => [0x021B7],
  "cuvee" => [0x022CE],
  "cuwed" => [0x022CF],
  "cwconint" => [0x02232],
  "cwint" => [0x02231],
  "cylcty" => [0x0232D],
  "dArr" => [0x021D3],
  "dHar" => [0x02965],
  "dagger" => [0x02020],
  "daleth" => [0x02138],
  "darr" => [0x02193],
  "dash" => [0x02010],
  "dashv" => [0x022A3],
  "dbkarow" => [0x0290F],
  "dblac" => [0x002DD],
  "dcaron" => [0x0010F],
  "dcy" => [0x00434],
  "dd" => [0x02146],
  "ddagger" => [0x02021],
  "ddarr" => [0x021CA],
  "ddotseq" => [0x02A77],
  "deg" => [0x000B0],
  "delta" => [0x003B4],
  "demptyv" => [0x029B1],
  "dfisht" => [0x0297F],
  "dfr" => [0x1D521],
  "dharl" => [0x021C3],
  "dharr" => [0x021C2],
  "diam" => [0x022C4],
  "diamond" => [0x022C4],
  "diamondsuit" => [0x02666],
  "diams" => [0x02666],
  "die" => [0x000A8],
  "digamma" => [0x003DD],
  "disin" => [0x022F2],
  "div" => [0x000F7],
  "divide" => [0x000F7],
  "divideontimes" => [0x022C7],
  "divonx" => [0x022C7],
  "djcy" => [0x00452],
  "dlcorn" => [0x0231E],
  "dlcrop" => [0x0230D],
  "dollar" => [0x00024],
  "dopf" => [0x1D555],
  "dot" => [0x002D9],
  "doteq" => [0x02250],
  "doteqdot" => [0x02251],
  "dotminus" => [0x02238],
  "dotplus" => [0x02214],
  "dotsquare" => [0x022A1],
  "doublebarwedge" => [0x02306],
  "downarrow" => [0x02193],
  "downdownarrows" => [0x021CA],
  "downharpoonleft" => [0x021C3],
  "downharpoonright" => [0x021C2],
  "drbkarow" => [0x02910],
  "drcorn" => [0x0231F],
  "drcrop" => [0x0230C],
  "dscr" => [0x1D4B9],
  "dscy" => [0x00455],
  "dsol" => [0x029F6],
  "dstrok" => [0x00111],
  "dtdot" => [0x022F1],
  "dtri" => [0x025BF],
  "dtrif" => [0x025BE],
  "duarr" => [0x021F5],
  "duhar" => [0x0296F],
  "dwangle" => [0x029A6],
  "dzcy" => [0x0045F],
  "dzigrarr" => [0x027FF],
  "eDDot" => [0x02A77],
  "eDot" => [0x02251],
  "eacute" => [0x000E9],
  "easter" => [0x02A6E],
  "ecaron" => [0x0011B],
  "ecir" => [0x02256],
  "ecirc" => [0x000EA],
  "ecolon" => [0x02255],
  "ecy" => [0x0044D],
  "edot" => [0x00117],
  "ee" => [0x02147],
  "efDot" => [0x02252],
  "efr" => [0x1D522],
  "eg" => [0x02A9A],
  "egrave" => [0x000E8],
  "egs" => [0x02A96],
  "egsdot" => [0x02A98],
  "el" => [0x02A99],
  "elinters" => [0x023E7],
  "ell" => [0x02113],
  "els" => [0x02A95],
  "elsdot" => [0x02A97],
  "emacr" => [0x00113],
  "empty" => [0x02205],
  "emptyset" => [0x02205],
  "emptyv" => [0x02205],
  "emsp" => [0x02003],
  "emsp13" => [0x02004],
  "emsp14" => [0x02005],
  "eng" => [0x0014B],
  "ensp" => [0x02002],
  "eogon" => [0x00119],
  "eopf" => [0x1D556],
  "epar" => [0x022D5],
  "eparsl" => [0x029E3],
  "eplus" => [0x02A71],
  "epsi" => [0x003B5],
  "epsilon" => [0x003B5],
  "epsiv" => [0x003F5],
  "eqcirc" => [0x02256],
  "eqcolon" => [0x02255],
  "eqsim" => [0x02242],
  "eqslantgtr" => [0x02A96],
  "eqslantless" => [0x02A95],
  "equals" => [0x0003D],
  "equest" => [0x0225F],
  "equiv" => [0x02261],
  "equivDD" => [0x02A78],
  "eqvparsl" => [0x029E5],
  "erDot" => [0x02253],
  "erarr" => [0x02971],
  "escr" => [0x0212F],
  "esdot" => [0x02250],
  "esim" => [0x02242],
  "eta" => [0x003B7],
  "eth" => [0x000F0],
  "euml" => [0x000EB],
  "euro" => [0x020AC],
  "excl" => [0x00021],
  "exist" => [0x02203],
  "expectation" => [0x02130],
  "exponentiale" => [0x02147],
  "fallingdotseq" => [0x02252],
  "fcy" => [0x00444],
  "female" => [0x02640],
  "ffilig" => [0x0FB03],
  "fflig" => [0x0FB00],
  "ffllig" => [0x0FB04],
  "ffr" => [0x1D523],
  "filig" => [0x0FB01],
  "fjlig" => [0x00066, 0x0006A],
  "flat" => [0x0266D],
  "fllig" => [0x0FB02],
  "fltns" => [0x025B1],
  "fnof" => [0x00192],
  "fopf" => [0x1D557],
  "forall" => [0x02200],
  "fork" => [0x022D4],
  "forkv" => [0x02AD9],
  "fpartint" => [0x02A0D],
  "frac12" => [0x000BD],
  "frac13" => [0x02153],
  "frac14" => [0x000BC],
  "frac15" => [0x02155],
  "frac16" => [0x02159],
  "frac18" => [0x0215B],
  "frac23" => [0x02154],
  "frac25" => [0x02156],
  "frac34" => [0x000BE],
  "frac35" => [0x02157],
  "frac38" => [0x0215C],
  "frac45" => [0x02158],
  "frac56" => [0x0215A],
  "frac58" => [0x0215D],
  "frac78" => [0x0215E],
  "frasl" => [0x02044],
  "frown" => [0x02322],
  "fscr" => [0x1D4BB],
  "gE" => [0x02267],
  "gEl" => [0x02A8C],
  "gacute" => [0x001F5],
  "gamma" => [0x003B3],
  "gammad" => [0x003DD],
  "gap" => [0x02A86],
  "gbreve" => [0x0011F],
  "gcirc" => [0x0011D],
  "gcy" => [0x00433],
  "gdot" => [0x00121],
  "ge" => [0x02265],
  "gel" => [0x022DB],
  "geq" => [0x02265],
  "geqq" => [0x02267],
  "geqslant" => [0x02A7E],
  "ges" => [0x02A7E],
  "gescc" => [0x02AA9],
  "gesdot" => [0x02A80],
  "gesdoto" => [0x02A82],
  "gesdotol" => [0x02A84],
  "gesl" => [0x022DB, 0x0FE00],
  "gesles" => [0x02A94],
  "gfr" => [0x1D524],
  "gg" => [0x0226B],
  "ggg" => [0x022D9],
  "gimel" => [0x02137],
  "gjcy" => [0x00453],
  "gl" => [0x02277],
  "glE" => [0x02A92],
  "gla" => [0x02AA5],
  "glj" => [0x02AA4],
  "gnE" => [0x02269],
  "gnap" => [0x02A8A],
  "gnapprox" => [0x02A8A],
  "gne" => [0x02A88],
  "gneq" => [0x02A88],
  "gneqq" => [0x02269],
  "gnsim" => [0x022E7],
  "gopf" => [0x1D558],
  "grave" => [0x00060],
  "gscr" => [0x0210A],
  "gsim" => [0x02273],
  "gsime" => [0x02A8E],
  "gsiml" => [0x02A90],
  "gt" => [0x0003E],
  "gtcc" => [0x02AA7],
  "gtcir" => [0x02A7A],
  "gtdot" => [0x022D7],
  "gtlPar" => [0x02995],
  "gtquest" => [0x02A7C],
  "gtrapprox" => [0x02A86],
  "gtrarr" => [0x02978],
  "gtrdot" => [0x022D7],
  "gtreqless" => [0x022DB],
  "gtreqqless" => [0x02A8C],
  "gtrless" => [0x02277],
  "gtrsim" => [0x02273],
  "gvertneqq" => [0x02269, 0x0FE00],
  "gvnE" => [0x02269, 0x0FE00],
  "hArr" => [0x021D4],
  "hairsp" => [0x0200A],
  "half" => [0x000BD],
  "hamilt" => [0x0210B],
  "hardcy" => [0x0044A],
  "harr" => [0x02194],
  "harrcir" => [0x02948],
  "harrw" => [0x021AD],
  "hbar" => [0x0210F],
  "hcirc" => [0x00125],
  "hearts" => [0x02665],
  "heartsuit" => [0x02665],
  "hellip" => [0x02026],
  "hercon" => [0x022B9],
  "hfr" => [0x1D525],
  "hksearow" => [0x02925],
  "hkswarow" => [0x02926],
  "hoarr" => [0x021FF],
  "homtht" => [0x0223B],
  "hookleftarrow" => [0x021A9],
  "hookrightarrow" => [0x021AA],
  "hopf" => [0x1D559],
  "horbar" => [0x02015],
  "hscr" => [0x1D4BD],
  "hslash" => [0x0210F],
  "hstrok" => [0x00127],
  "hybull" => [0x02043],
  "hyphen" => [0x02010],
  "iacute" => [0x000ED],
  "ic" => [0x02063],
  "icirc" => [0x000EE],
  "icy" => [0x00438],
  "iecy" => [0x00435],
  "iexcl" => [0x000A1],
  "iff" => [0x021D4],
  "ifr" => [0x1D526],
  "igrave" => [0x000EC],
  "ii" => [0x02148],
  "iiiint" => [0x02A0C],
  "iiint" => [0x0222D],
  "iinfin" => [0x029DC],
  "iiota" => [0x02129],
  "ijlig" => [0x00133],
  "imacr" => [0x0012B],
  "image" => [0x02111],
  "imagline" => [0x02110],
  "imagpart" => [0x02111],
  "imath" => [0x00131],
  "imof" => [0x022B7],
  "imped" => [0x001B5],
  "in" => [0x02208],
  "incare" => [0x02105],
  "infin" => [0x0221E],
  "infintie" => [0x029DD],
  "inodot" => [0x00131],
  "int" => [0x0222B],
  "intcal" => [0x022BA],
  "integers" => [0x02124],
  "intercal" => [0x022BA],
  "intlarhk" => [0x02A17],
  "intprod" => [0x02A3C],
  "iocy" => [0x00451],
  "iogon" => [0x0012F],
  "iopf" => [0x1D55A],
  "iota" => [0x003B9],
  "iprod" => [0x02A3C],
  "iquest" => [0x000BF],
  "iscr" => [0x1D4BE],
  "isin" => [0x02208],
  "isinE" => [0x022F9],
  "isindot" => [0x022F5],
  "isins" => [0x022F4],
  "isinsv" => [0x022F3],
  "isinv" => [0x02208],
  "it" => [0x02062],
  "itilde" => [0x00129],
  "iukcy" => [0x00456],
  "iuml" => [0x000EF],
  "jcirc" => [0x00135],
  "jcy" => [0x00439],
  "jfr" => [0x1D527],
  "jmath" => [0x00237],
  "jopf" => [0x1D55B],
  "jscr" => [0x1D4BF],
  "jsercy" => [0x00458],
  "jukcy" => [0x00454],
  "kappa" => [0x003BA],
  "kappav" => [0x003F0],
  "kcedil" => [0x00137],
  "kcy" => [0x0043A],
  "kfr" => [0x1D528],
  "kgreen" => [0x00138],
  "khcy" => [0x00445],
  "kjcy" => [0x0045C],
  "kopf" => [0x1D55C],
  "kscr" => [0x1D4C0],
  "lAarr" => [0x021DA],
  "lArr" => [0x021D0],
  "lAtail" => [0x0291B],
  "lBarr" => [0x0290E],
  "lE" => [0x02266],
  "lEg" => [0x02A8B],
  "lHar" => [0x02962],
  "lacute" => [0x0013A],
  "laemptyv" => [0x029B4],
  "lagran" => [0x02112],
  "lambda" => [0x003BB],
  "lang" => [0x027E8],
  "langd" => [0x02991],
  "langle" => [0x027E8],
  "lap" => [0x02A85],
  "laquo" => [0x000AB],
  "larr" => [0x02190],
  "larrb" => [0x021E4],
  "larrbfs" => [0x0291F],
  "larrfs" => [0x0291D],
  "larrhk" => [0x021A9],
  "larrlp" => [0x021AB],
  "larrpl" => [0x02939],
  "larrsim" => [0x02973],
  "larrtl" => [0x021A2],
  "lat" => [0x02AAB],
  "latail" => [0x02919],
  "late" => [0x02AAD],
  "lates" => [0x02AAD, 0x0FE00],
  "lbarr" => [0x0290C],
  "lbbrk" => [0x02772],
  "lbrace" => [0x0007B],
  "lbrack" => [0x0005B],
  "lbrke" => [0x0298B],
  "lbrksld" => [0x0298F],
  "lbrkslu" => [0x0298D],
  "lcaron" => [0x0013E],
  "lcedil" => [0x0013C],
  "lceil" => [0x02308],
  "lcub" => [0x0007B],
  "lcy" => [0x0043B],
  "ldca" => [0x02936],
  "ldquo" => [0x0201C],
  "ldquor" => [0x0201E],
  "ldrdhar" => [0x02967],
  "ldrushar" => [0x0294B],
  "ldsh" => [0x021B2],
  "le" => [0x02264],
  "leftarrow" => [0x02190],
  "leftarrowtail" => [0x021A2],
  "leftharpoondown" => [0x021BD],
  "leftharpoonup" => [0x021BC],
  "leftleftarrows" => [0x021C7],
  "leftrightarrow" => [0x02194],
  "leftrightarrows" => [0x021C6],
  "leftrightharpoons" => [0x021CB],
  "leftrightsquigarrow" => [0x021AD],
  "leftthreetimes" => [0x022CB],
  "leg" => [0x022DA],
  "leq" => [0x02264],
  "leqq" => [0x02266],
  "leqslant" => [0x02A7D],
  "les" => [0x02A7D],
  "lescc" => [0x02AA8],
  "lesdot" => [0x02A7F],
  "lesdoto" => [0x02A81],
  "lesdotor" => [0x02A83],
  "lesg" => [0x022DA, 0x0FE00],
  "lesges" => [0x02A93],
  "lessapprox" => [0x02A85],
  "lessdot" => [0x022D6],
  "lesseqgtr" => [0x022DA],
  "lesseqqgtr" => [0x02A8B],
  "lessgtr" => [0x02276],
  "lesssim" => [0x02272],
  "lfisht" => [0x0297C],
  "lfloor" => [0x0230A],
  "lfr" => [0x1D529],
  "lg" => [0x02276],
  "lgE" => [0x02A91],
  "lhard" => [0x021BD],
  "lharu" => [0x021BC],
  "lharul" => [0x0296A],
  "lhblk" => [0x02584],
  "ljcy" => [0x00459],
  "ll" => [0x0226A],
  "llarr" => [0x021C7],
  "llcorner" => [0x0231E],
  "llhard" => [0x0296B],
  "lltri" => [0x025FA],
  "lmidot" => [0x00140],
  "lmoust" => [0x023B0],
  "lmoustache" => [0x023B0],
  "lnE" => [0x02268],
  "lnap" => [0x02A89],
  "lnapprox" => [0x02A89],
  "lne" => [0x02A87],
  "lneq" => [0x02A87],
  "lneqq" => [0x02268],
  "lnsim" => [0x022E6],
  "loang" => [0x027EC],
  "loarr" => [0x021FD],
  "lobrk" => [0x027E6],
  "longleftarrow" => [0x027F5],
  "longleftrightarrow" => [0x027F7],
  "longmapsto" => [0x027FC],
  "longrightarrow" => [0x027F6],
  "looparrowleft" => [0x021AB],
  "looparrowright" => [0x021AC],
  "lopar" => [0x02985],
  "lopf" => [0x1D55D],
  "loplus" => [0x02A2D],
  "lotimes" => [0x02A34],
  "lowast" => [0x02217],
  "lowbar" => [0x0005F],
  "loz" => [0x025CA],
  "lozenge" => [0x025CA],
  "lozf" => [0x029EB],
  "lpar" => [0x00028],
  "lparlt" => [0x02993],
  "lrarr" => [0x021C6],
  "lrcorner" => [0x0231F],
  "lrhar" => [0x021CB],
  "lrhard" => [0x0296D],
  "lrm" => [0x0200E],
  "lrtri" => [0x022BF],
  "lsaquo" => [0x02039],
  "lscr" => [0x1D4C1],
  "lsh" => [0x021B0],
  "lsim" => [0x02272],
  "lsime" => [0x02A8D],
  "lsimg" => [0x02A8F],
  "lsqb" => [0x0005B],
  "lsquo" => [0x02018],
  "lsquor" => [0x0201A],
  "lstrok" => [0x00142],
  "lt" => [0x0003C],
  "ltcc" => [0x02AA6],
  "ltcir" => [0x02A79],
  "ltdot" => [0x022D6],
  "lthree" => [0x022CB],
  "ltimes" => [0x022C9],
  "ltlarr" => [0x02976],
  "ltquest" => [0x02A7B],
  "ltrPar" => [0x02996],
  "ltri" => [0x025C3],
  "ltrie" => [0x022B4],
  "ltrif" => [0x025C2],
  "lurdshar" => [0x0294A],
  "luruhar" => [0x02966],
  "lvertneqq" => [0x02268, 0x0FE00],
  "lvnE" => [0x02268, 0x0FE00],
  "mDDot" => [0x0223A],
  "macr" => [0x000AF],
  "male" => [0x02642],
  "malt" => [0x02720],
  "maltese" => [0x02720],
  "map" => [0x021A6],
  "mapsto" => [0x021A6],
  "mapstodown" => [0x021A7],
  "mapstoleft" => [0x021A4],
  "mapstoup" => [0x021A5],
  "marker" => [0x025AE],
  "mcomma" => [0x02A29],
  "mcy" => [0x0043C],
  "mdash" => [0x02014],
  "measuredangle" => [0x02221],
  "mfr" => [0x1D52A],
  "mho" => [0x02127],
  "micro" => [0x000B5],
  "mid" => [0x02223],
  "midast" => [0x0002A],
  "midcir" => [0x02AF0],
  "middot" => [0x000B7],
  "minus" => [0x02212],
  "minusb" => [0x0229F],
  "minusd" => [0x02238],
  "minusdu" => [0x02A2A],
  "mlcp" => [0x02ADB],
  "mldr" => [0x02026],
  "mnplus" => [0x02213],
  "models" => [0x022A7],
  "mopf" => [0x1D55E],
  "mp" => [0x02213],
  "mscr" => [0x1D4C2],
  "mstpos" => [0x0223E],
  "mu" => [0x003BC],
  "multimap" => [0x022B8],
  "mumap" => [0x022B8],
  "nGg" => [0x022D9, 0x00338],
  "nGt" => [0x0226B, 0x020D2],
  "nGtv" => [0x0226B, 0x00338],
  "nLeftarrow" => [0x021CD],
  "nLeftrightarrow" => [0x021CE],
  "nLl" => [0x022D8, 0x00338],
  "nLt" => [0x0226A, 0x020D2],
  "nLtv" => [0x0226A, 0x00338],
  "nRightarrow" => [0x021CF],
  "nVDash" => [0x022AF],
  "nVdash" => [0x022AE],
  "nabla" => [0x02207],
  "nacute" => [0x00144],
  "nang" => [0x02220, 0x020D2],
  "nap" => [0x02249],
  "napE" => [0x02A70, 0x00338],
  "napid" => [0x0224B, 0x00338],
  "napos" => [0x00149],
  "napprox" => [0x02249],
  "natur" => [0x0266E],
  "natural" => [0x0266E],
  "naturals" => [0x02115],
  "nbsp" => [0x000A0],
  "nbump" => [0x0224E, 0x00338],
  "nbumpe" => [0x0224F, 0x00338],
  "ncap" => [0x02A43],
  "ncaron" => [0x00148],
  "ncedil" => [0x00146],
  "ncong" => [0x02247],
  "ncongdot" => [0x02A6D, 0x00338],
  "ncup" => [0x02A42],
  "ncy" => [0x0043D],
  "ndash" => [0x02013],
  "ne" => [0x02260],
  "neArr" => [0x021D7],
  "nearhk" => [0x02924],
  "nearr" => [0x02197],
  "nearrow" => [0x02197],
  "nedot" => [0x02250, 0x00338],
  "nequiv" => [0x02262],
  "nesear" => [0x02928],
  "nesim" => [0x02242, 0x00338],
  "nexist" => [0x02204],
  "nexists" => [0x02204],
  "nfr" => [0x1D52B],
  "ngE" => [0x02267, 0x00338],
  "nge" => [0x02271],
  "ngeq" => [0x02271],
  "ngeqq" => [0x02267, 0x00338],
  "ngeqslant" => [0x02A7E, 0x00338],
  "nges" => [0x02A7E, 0x00338],
  "ngsim" => [0x02275],
  "ngt" => [0x0226F],
  "ngtr" => [0x0226F],
  "nhArr" => [0x021CE],
  "nharr" => [0x021AE],
  "nhpar" => [0x02AF2],
  "ni" => [0x0220B],
  "nis" => [0x022FC],
  "nisd" => [0x022FA],
  "niv" => [0x0220B],
  "njcy" => [0x0045A],
  "nlArr" => [0x021CD],
  "nlE" => [0x02266, 0x00338],
  "nlarr" => [0x0219A],
  "nldr" => [0x02025],
  "nle" => [0x02270],
  "nleftarrow" => [0x0219A],
  "nleftrightarrow" => [0x021AE],
  "nleq" => [0x02270],
  "nleqq" => [0x02266, 0x00338],
  "nleqslant" => [0x02A7D, 0x00338],
  "nles" => [0x02A7D, 0x00338],
  "nless" => [0x0226E],
  "nlsim" => [0x02274],
  "nlt" => [0x0226E],
  "nltri" => [0x022EA],
  "nltrie" => [0x022EC],
  "nmid" => [0x02224],
  "nopf" => [0x1D55F],
  "not" => [0x000AC],
  "notin" => [0x02209],
  "notinE" => [0x022F9, 0x00338],
  "notindot" => [0x022F5, 0x00338],
  "notinva" => [0x02209],
  "notinvb" => [0x022F7],
  "notinvc" => [0x022F6],
  "notni" => [0x0220C],
  "notniva" => [0x0220C],
  "notnivb" => [0x022FE],
  "notnivc" => [0x022FD],
  "npar" => [0x02226],
  "nparallel" => [0x02226],
  "nparsl" => [0x02AFD, 0x020E5],
  "npart" => [0x02202, 0x00338],
  "npolint" => [0x02A14],
  "npr" => [0x02280],
  "nprcue" => [0x022E0],
  "npre" => [0x02AAF, 0x00338],
  "nprec" => [0x02280],
  "npreceq" => [0x02AAF, 0x00338],
  "nrArr" => [0x021CF],
  "nrarr" => [0x0219B],
  "nrarrc" => [0x02933, 0x00338],
  "nrarrw" => [0x0219D, 0x00338],
  "nrightarrow" => [0x0219B],
  "nrtri" => [0x022EB],
  "nrtrie" => [0x022ED],
  "nsc" => [0x02281],
  "nsccue" => [0x022E1],
  "nsce" => [0x02AB0, 0x00338],
  "nscr" => [0x1D4C3],
  "nshortmid" => [0x02224],
  "nshortparallel" => [0x02226],
  "nsim" => [0x02241],
  "nsime" => [0x02244],
  "nsimeq" => [0x02244],
  "nsmid" => [0x02224],
  "nspar" => [0x02226],
  "nsqsube" => [0x022E2],
  "nsqsupe" => [0x022E3],
  "nsub" => [0x02284],
  "nsubE" => [0x02AC5, 0x00338],
  "nsube" => [0x02288],
  "nsubset" => [0x02282, 0x020D2],
  "nsubseteq" => [0x02288],
  "nsubseteqq" => [0x02AC5, 0x00338],
  "nsucc" => [0x02281],
  "nsucceq" => [0x02AB0, 0x00338],
  "nsup" => [0x02285],
  "nsupE" => [0x02AC6, 0x00338],
  "nsupe" => [0x02289],
  "nsupset" => [0x02283, 0x020D2],
  "nsupseteq" => [0x02289],
  "nsupseteqq" => [0x02AC6, 0x00338],
  "ntgl" => [0x02279],
  "ntilde" => [0x000F1],
  "ntlg" => [0x02278],
  "ntriangleleft" => [0x022EA],
  "ntrianglelefteq" => [0x022EC],
  "ntriangleright" => [0x022EB],
  "ntrianglerighteq" => [0x022ED],
  "nu" => [0x003BD],
  "num" => [0x00023],
  "numero" => [0x02116],
  "numsp" => [0x02007],
  "nvDash" => [0x022AD],
  "nvHarr" => [0x02904],
  "nvap" => [0x0224D, 0x020D2],
  "nvdash" => [0x022AC],
  "nvge" => [0x02265, 0x020D2],
  "nvgt" => [0x0003E, 0x020D2],
  "nvinfin" => [0x029DE],
  "nvlArr" => [0x02902],
  "nvle" => [0x02264, 0x020D2],
  "nvlt" => [0x0003C, 0x020D2],
  "nvltrie" => [0x022B4, 0x020D2],
  "nvrArr" => [0x02903],
  "nvrtrie" => [0x022B5, 0x020D2],
  "nvsim" => [0x0223C, 0x020D2],
  "nwArr" => [0x021D6],
  "nwarhk" => [0x02923],
  "nwarr" => [0x02196],
  "nwarrow" => [0x02196],
  "nwnear" => [0x02927],
  "oS" => [0x024C8],
  "oacute" => [0x000F3],
  "oast" => [0x0229B],
  "ocir" => [0x0229A],
  "ocirc" => [0x000F4],
  "ocy" => [0x0043E],
  "odash" => [0x0229D],
  "odblac" => [0x00151],
  "odiv" => [0x02A38],
  "odot" => [0x02299],
  "odsold" => [0x029BC],
  "oelig" => [0x00153],
  "ofcir" => [0x029BF],
  "ofr" => [0x1D52C],
  "ogon" => [0x002DB],
  "ograve" => [0x000F2],
  "ogt" => [0x029C1],
  "ohbar" => [0x029B5],
  "ohm" => [0x003A9],
  "oint" => [0x0222E],
  "olarr" => [0x021BA],
  "olcir" => [0x029BE],
  "olcross" => [0x029BB],
  "oline" => [0x0203E],
  "olt" => [0x029C0],
  "omacr" => [0x0014D],
  "omega" => [0x003C9],
  "omicron" => [0x003BF],
  "omid" => [0x029B6],
  "ominus" => [0x02296],
  "oopf" => [0x1D560],
  "opar" => [0x029B7],
  "operp" => [0x029B9],
  "oplus" => [0x02295],
  "or" => [0x02228],
  "orarr" => [0x021BB],
  "ord" => [0x02A5D],
  "order" => [0x02134],
  "orderof" => [0x02134],
  "ordf" => [0x000AA],
  "ordm" => [0x000BA],
  "origof" => [0x022B6],
  "oror" => [0x02A56],
  "orslope" => [0x02A57],
  "orv" => [0x02A5B],
  "oscr" => [0x02134],
  "oslash" => [0x000F8],
  "osol" => [0x02298],
  "otilde" => [0x000F5],
  "otimes" => [0x02297],
  "otimesas" => [0x02A36],
  "ouml" => [0x000F6],
  "ovbar" => [0x0233D],
  "par" => [0x02225],
  "para" => [0x000B6],
  "parallel" => [0x02225],
  "parsim" => [0x02AF3],
  "parsl" => [0x02AFD],
  "part" => [0x02202],
  "pcy" => [0x0043F],
  "percnt" => [0x00025],
  "period" => [0x0002E],
  "permil" => [0x02030],
  "perp" => [0x022A5],
  "pertenk" => [0x02031],
  "pfr" => [0x1D52D],
  "phi" => [0x003C6],
  "phiv" => [0x003D5],
  "phmmat" => [0x02133],
  "phone" => [0x0260E],
  "pi" => [0x003C0],
  "pitchfork" => [0x022D4],
  "piv" => [0x003D6],
  "planck" => [0x0210F],
  "planckh" => [0x0210E],
  "plankv" => [0x0210F],
  "plus" => [0x0002B],
  "plusacir" => [0x02A23],
  "plusb" => [0x0229E],
  "pluscir" => [0x02A22],
  "plusdo" => [0x02214],
  "plusdu" => [0x02A25],
  "pluse" => [0x02A72],
  "plusmn" => [0x000B1],
  "plussim" => [0x02A26],
  "plustwo" => [0x02A27],
  "pm" => [0x000B1],
  "pointint" => [0x02A15],
  "popf" => [0x1D561],
  "pound" => [0x000A3],
  "pr" => [0x0227A],
  "prE" => [0x02AB3],
  "prap" => [0x02AB7],
  "prcue" => [0x0227C],
  "pre" => [0x02AAF],
  "prec" => [0x0227A],
  "precapprox" => [0x02AB7],
  "preccurlyeq" => [0x0227C],
  "preceq" => [0x02AAF],
  "precnapprox" => [0x02AB9],
  "precneqq" => [0x02AB5],
  "precnsim" => [0x022E8],
  "precsim" => [0x0227E],
  "prime" => [0x02032],
  "primes" => [0x02119],
  "prnE" => [0x02AB5],
  "prnap" => [0x02AB9],
  "prnsim" => [0x022E8],
  "prod" => [0x0220F],
  "profalar" => [0x0232E],
  "profline" => [0x02312],
  "profsurf" => [0x02313],
  "prop" => [0x0221D],
  "propto" => [0x0221D],
  "prsim" => [0x0227E],
  "prurel" => [0x022B0],
  "pscr" => [0x1D4C5],
  "psi" => [0x003C8],
  "puncsp" => [0x02008],
  "qfr" => [0x1D52E],
  "qint" => [0x02A0C],
  "qopf" => [0x1D562],
  "qprime" => [0x02057],
  "qscr" => [0x1D4C6],
  "quaternions" => [0x0210D],
  "quatint" => [0x02A16],
  "quest" => [0x0003F],
  "questeq" => [0x0225F],
  "quot" => [0x00022],
  "rAarr" => [0x021DB],
  "rArr" => [0x021D2],
  "rAtail" => [0x0291C],
  "rBarr" => [0x0290F],
  "rHar" => [0x02964],
  "race" => [0x0223D, 0x00331],
  "racute" => [0x00155],
  "radic" => [0x0221A],
  "raemptyv" => [0x029B3],
  "rang" => [0x027E9],
  "rangd" => [0x02992],
  "range" => [0x029A5],
  "rangle" => [0x027E9],
  "raquo" => [0x000BB],
  "rarr" => [0x02192],
  "rarrap" => [0x02975],
  "rarrb" => [0x021E5],
  "rarrbfs" => [0x02920],
  "rarrc" => [0x02933],
  "rarrfs" => [0x0291E],
  "rarrhk" => [0x021AA],
  "rarrlp" => [0x021AC],
  "rarrpl" => [0x02945],
  "rarrsim" => [0x02974],
  "rarrtl" => [0x021A3],
  "rarrw" => [0x0219D],
  "ratail" => [0x0291A],
  "ratio" => [0x02236],
  "rationals" => [0x0211A],
  "rbarr" => [0x0290D],
  "rbbrk" => [0x02773],
  "rbrace" => [0x0007D],
  "rbrack" => [0x0005D],
  "rbrke" => [0x0298C],
  "rbrksld" => [0x0298E],
  "rbrkslu" => [0x02990],
  "rcaron" => [0x00159],
  "rcedil" => [0x00157],
  "rceil" => [0x02309],
  "rcub" => [0x0007D],
  "rcy" => [0x00440],
  "rdca" => [0x02937],
  "rdldhar" => [0x02969],
  "rdquo" => [0x0201D],
  "rdquor" => [0x0201D],
  "rdsh" => [0x021B3],
  "real" => [0x0211C],
  "realine" => [0x0211B],
  "realpart" => [0x0211C],
  "reals" => [0x0211D],
  "rect" => [0x025AD],
  "reg" => [0x000AE],
  "rfisht" => [0x0297D],
  "rfloor" => [0x0230B],
  "rfr" => [0x1D52F],
  "rhard" => [0x021C1],
  "rharu" => [0x021C0],
  "rharul" => [0x0296C],
  "rho" => [0x003C1],
  "rhov" => [0x003F1],
  "rightarrow" => [0x02192],
  "rightarrowtail" => [0x021A3],
  "rightharpoondown" => [0x021C1],
  "rightharpoonup" => [0x021C0],
  "rightleftarrows" => [0x021C4],
  "rightleftharpoons" => [0x021CC],
  "rightrightarrows" => [0x021C9],
  "rightsquigarrow" => [0x0219D],
  "rightthreetimes" => [0x022CC],
  "ring" => [0x002DA],
  "risingdotseq" => [0x02253],
  "rlarr" => [0x021C4],
  "rlhar" => [0x021CC],
  "rlm" => [0x0200F],
  "rmoust" => [0x023B1],
  "rmoustache" => [0x023B1],
  "rnmid" => [0x02AEE],
  "roang" => [0x027ED],
  "roarr" => [0x021FE],
  "robrk" => [0x027E7],
  "ropar" => [0x02986],
  "ropf" => [0x1D563],
  "roplus" => [0x02A2E],
  "rotimes" => [0x02A35],
  "rpar" => [0x00029],
  "rpargt" => [0x02994],
  "rppolint" => [0x02A12],
  "rrarr" => [0x021C9],
  "rsaquo" => [0x0203A],
  "rscr" => [0x1D4C7],
  "rsh" => [0x021B1],
  "rsqb" => [0x0005D],
  "rsquo" => [0x02019],
  "rsquor" => [0x02019],
  "rthree" => [0x022CC],
  "rtimes" => [0x022CA],
  "rtri" => [0x025B9],
  "rtrie" => [0x022B5],
  "rtrif" => [0x025B8],
  "rtriltri" => [0x029CE],
  "ruluhar" => [0x02968],
  "rx" => [0x0211E],
  "sacute" => [0x0015B],
  "sbquo" => [0x0201A],
  "sc" => [0x0227B],
  "scE" => [0x02AB4],
  "scap" => [0x02AB8],
  "scaron" => [0x00161],
  "sccue" => [0x0227D],
  "sce" => [0x02AB0],
  "scedil" => [0x0015F],
  "scirc" => [0x0015D],
  "scnE" => [0x02AB6],
  "scnap" => [0x02ABA],
  "scnsim" => [0x022E9],
  "scpolint" => [0x02A13],
  "scsim" => [0x0227F],
  "scy" => [0x00441],
  "sdot" => [0x022C5],
  "sdotb" => [0x022A1],
  "sdote" => [0x02A66],
  "seArr" => [0x021D8],
  "searhk" => [0x02925],
  "searr" => [0x02198],
  "searrow" => [0x02198],
  "sect" => [0x000A7],
  "semi" => [0x0003B],
  "seswar" => [0x02929],
  "setminus" => [0x02216],
  "setmn" => [0x02216],
  "sext" => [0x02736],
  "sfr" => [0x1D530],
  "sfrown" => [0x02322],
  "sharp" => [0x0266F],
  "shchcy" => [0x00449],
  "shcy" => [0x00448],
  "shortmid" => [0x02223],
  "shortparallel" => [0x02225],
  "shy" => [0x000AD],
  "sigma" => [0x003C3],
  "sigmaf" => [0x003C2],
  "sigmav" => [0x003C2],
  "sim" => [0x0223C],
  "simdot" => [0x02A6A],
  "sime" => [0x02243],
  "simeq" => [0x02243],
  "simg" => [0x02A9E],
  "simgE" => [0x02AA0],
  "siml" => [0x02A9D],
  "simlE" => [0x02A9F],
  "simne" => [0x02246],
  "simplus" => [0x02A24],
  "simrarr" => [0x02972],
  "slarr" => [0x02190],
  "smallsetminus" => [0x02216],
  "smashp" => [0x02A33],
  "smeparsl" => [0x029E4],
  "smid" => [0x02223],
  "smile" => [0x02323],
  "smt" => [0x02AAA],
  "smte" => [0x02AAC],
  "smtes" => [0x02AAC, 0x0FE00],
  "softcy" => [0x0044C],
  "sol" => [0x0002F],
  "solb" => [0x029C4],
  "solbar" => [0x0233F],
  "sopf" => [0x1D564],
  "spades" => [0x02660],
  "spadesuit" => [0x02660],
  "spar" => [0x02225],
  "sqcap" => [0x02293],
  "sqcaps" => [0x02293, 0x0FE00],
  "sqcup" => [0x02294],
  "sqcups" => [0x02294, 0x0FE00],
  "sqsub" => [0x0228F],
  "sqsube" => [0x02291],
  "sqsubset" => [0x0228F],
  "sqsubseteq" => [0x02291],
  "sqsup" => [0x02290],
  "sqsupe" => [0x02292],
  "sqsupset" => [0x02290],
  "sqsupseteq" => [0x02292],
  "squ" => [0x025A1],
  "square" => [0x025A1],
  "squarf" => [0x025AA],
  "squf" => [0x025AA],
  "srarr" => [0x02192],
  "sscr" => [0x1D4C8],
  "ssetmn" => [0x02216],
  "ssmile" => [0x02323],
  "sstarf" => [0x022C6],
  "star" => [0x02606],
  "starf" => [0x02605],
  "straightepsilon" => [0x003F5],
  "straightphi" => [0x003D5],
  "strns" => [0x000AF],
  "sub" => [0x02282],
  "subE" => [0x02AC5],
  "subdot" => [0x02ABD],
  "sube" => [0x02286],
  "subedot" => [0x02AC3],
  "submult" => [0x02AC1],
  "subnE" => [0x02ACB],
  "subne" => [0x0228A],
  "subplus" => [0x02ABF],
  "subrarr" => [0x02979],
  "subset" => [0x02282],
  "subseteq" => [0x02286],
  "subseteqq" => [0x02AC5],
  "subsetneq" => [0x0228A],
  "subsetneqq" => [0x02ACB],
  "subsim" => [0x02AC7],
  "subsub" => [0x02AD5],
  "subsup" => [0x02AD3],
  "succ" => [0x0227B],
  "succapprox" => [0x02AB8],
  "succcurlyeq" => [0x0227D],
  "succeq" => [0x02AB0],
  "succnapprox" => [0x02ABA],
  "succneqq" => [0x02AB6],
  "succnsim" => [0x022E9],
  "succsim" => [0x0227F],
  "sum" => [0x02211],
  "sung" => [0x0266A],
  "sup" => [0x02283],
  "sup1" => [0x000B9],
  "sup2" => [0x000B2],
  "sup3" => [0x000B3],
  "supE" => [0x02AC6],
  "supdot" => [0x02ABE],
  "supdsub" => [0x02AD8],
  "supe" => [0x02287],
  "supedot" => [0x02AC4],
  "suphsol" => [0x027C9],
  "suphsub" => [0x02AD7],
  "suplarr" => [0x0297B],
  "supmult" => [0x02AC2],
  "supnE" => [0x02ACC],
  "supne" => [0x0228B],
  "supplus" => [0x02AC0],
  "supset" => [0x02283],
  "supseteq" => [0x02287],
  "supseteqq" => [0x02AC6],
  "supsetneq" => [0x0228B],
  "supsetneqq" => [0x02ACC],
  "supsim" => [0x02AC8],
  "supsub" => [0x02AD4],
  "supsup" => [0x02AD6],
  "swArr" => [0x021D9],
  "swarhk" => [0x02926],
  "swarr" => [0x02199],
  "swarrow" => [0x02199],
  "swnwar" => [0x0292A],
  "szlig" => [0x000DF],
  "target" => [0x02316],
  "tau" => [0x003C4],
  "tbrk" => [0x023B4],
  "tcaron" => [0x00165],
  "tcedil" => [0x00163],
  "tcy" => [0x00442],
  "tdot" => [0x020DB],
  "telrec" => [0x02315],
  "tfr" => [0x1D531],
  "there4" => [0x02234],
  "therefore" => [0x02234],
  "theta" => [0x003B8],
  "thetasym" => [0x003D1],
  "thetav" => [0x003D1],
  "thickapprox" => [0x02248],
  "thicksim" => [0x0223C],
  "thinsp" => [0x02009],
  "thkap" => [0x02248],
  "thksim" => [0x0223C],
  "thorn" => [0x000FE],
  "tilde" => [0x002DC],
  "times" => [0x000D7],
  "timesb" => [0x022A0],
  "timesbar" => [0x02A31],
  "timesd" => [0x02A30],
  "tint" => [0x0222D],
  "toea" => [0x02928],
  "top" => [0x022A4],
  "topbot" => [0x02336],
  "topcir" => [0x02AF1],
  "topf" => [0x1D565],
  "topfork" => [0x02ADA],
  "tosa" => [0x02929],
  "tprime" => [0x02034],
  "trade" => [0x02122],
  "triangle" => [0x025B5],
  "triangledown" => [0x025BF],
  "triangleleft" => [0x025C3],
  "trianglelefteq" => [0x022B4],
  "triangleq" => [0x0225C],
  "triangleright" => [0x025B9],
  "trianglerighteq" => [0x022B5],
  "tridot" => [0x025EC],
  "trie" => [0x0225C],
  "triminus" => [0x02A3A],
  "triplus" => [0x02A39],
  "trisb" => [0x029CD],
  "tritime" => [0x02A3B],
  "trpezium" => [0x023E2],
  "tscr" => [0x1D4C9],
  "tscy" => [0x00446],
  "tshcy" => [0x0045B],
  "tstrok" => [0x00167],
  "twixt" => [0x0226C],
  "twoheadleftarrow" => [0x0219E],
  "twoheadrightarrow" => [0x021A0],
  "uArr" => [0x021D1],
  "uHar" => [0x02963],
  "uacute" => [0x000FA],
  "uarr" => [0x02191],
  "ubrcy" => [0x0045E],
  "ubreve" => [0x0016D],
  "ucirc" => [0x000FB],
  "ucy" => [0x00443],
  "udarr" => [0x021C5],
  "udblac" => [0x00171],
  "udhar" => [0x0296E],
  "ufisht" => [0x0297E],
  "ufr" => [0x1D532],
  "ugrave" => [0x000F9],
  "uharl" => [0x021BF],
  "uharr" => [0x021BE],
  "uhblk" => [0x02580],
  "ulcorn" => [0x0231C],
  "ulcorner" => [0x0231C],
  "ulcrop" => [0x0230F],
  "ultri" => [0x025F8],
  "umacr" => [0x0016B],
  "uml" => [0x000A8],
  "uogon" => [0x00173],
  "uopf" => [0x1D566],
  "uparrow" => [0x02191],
  "updownarrow" => [0x02195],
  "upharpoonleft" => [0x021BF],
  "upharpoonright" => [0x021BE],
  "uplus" => [0x0228E],
  "upsi" => [0x003C5],
  "upsih" => [0x003D2],
  "upsilon" => [0x003C5],
  "upuparrows" => [0x021C8],
  "urcorn" => [0x0231D],
  "urcorner" => [0x0231D],
  "urcrop" => [0x0230E],
  "uring" => [0x0016F],
  "urtri" => [0x025F9],
  "uscr" => [0x1D4CA],
  "utdot" => [0x022F0],
  "utilde" => [0x00169],
  "utri" => [0x025B5],
  "utrif" => [0x025B4],
  "uuarr" => [0x021C8],
  "uuml" => [0x000FC],
  "uwangle" => [0x029A7],
  "vArr" => [0x021D5],
  "vBar" => [0x02AE8],
  "vBarv" => [0x02AE9],
  "vDash" => [0x022A8],
  "vangrt" => [0x0299C],
  "varepsilon" => [0x003F5],
  "varkappa" => [0x003F0],
  "varnothing" => [0x02205],
  "varphi" => [0x003D5],
  "varpi" => [0x003D6],
  "varpropto" => [0x0221D],
  "varr" => [0x02195],
  "varrho" => [0x003F1],
  "varsigma" => [0x003C2],
  "varsubsetneq" => [0x0228A, 0x0FE00],
  "varsubsetneqq" => [0x02ACB, 0x0FE00],
  "varsupsetneq" => [0x0228B, 0x0FE00],
  "varsupsetneqq" => [0x02ACC, 0x0FE00],
  "vartheta" => [0x003D1],
  "vartriangleleft" => [0x022B2],
  "vartriangleright" => [0x022B3],
  "vcy" => [0x00432],
  "vdash" => [0x022A2],
  "vee" => [0x02228],
  "veebar" => [0x022BB],
  "veeeq" => [0x0225A],
  "vellip" => [0x022EE],
  "verbar" => [0x0007C],
  "vert" => [0x0007C],
  "vfr" => [0x1D533],
  "vltri" => [0x022B2],
  "vnsub" => [0x02282, 0x020D2],
  "vnsup" => [0x02283, 0x020D2],
  "vopf" => [0x1D567],
  "vprop" => [0x0221D],
  "vrtri" => [0x022B3],
  "vscr" => [0x1D4CB],
  "vsubnE" => [0x02ACB, 0x0FE00],
  "vsubne" => [0x0228A, 0x0FE00],
  "vsupnE" => [0x02ACC, 0x0FE00],
  "vsupne" => [0x0228B, 0x0FE00],
  "vzigzag" => [0x0299A],
  "wcirc" => [0x00175],
  "wedbar" => [0x02A5F],
  "wedge" => [0x02227],
  "wedgeq" => [0x02259],
  "weierp" => [0x02118],
  "wfr" => [0x1D534],
  "wopf" => [0x1D568],
  "wp" => [0x02118],
  "wr" => [0x02240],
  "wreath" => [0x02240],
  "wscr" => [0x1D4CC],
  "xcap" => [0x022C2],
  "xcirc" => [0x025EF],
  "xcup" => [0x022C3],
  "xdtri" => [0x025BD],
  "xfr" => [0x1D535],
  "xhArr" => [0x027FA],
  "xharr" => [0x027F7],
  "xi" => [0x003BE],
  "xlArr" => [0x027F8],
  "xlarr" => [0x027F5],
  "xmap" => [0x027FC],
  "xnis" => [0x022FB],
  "xodot" => [0x02A00],
  "xopf" => [0x1D569],
  "xoplus" => [0x02A01],
  "xotime" => [0x02A02],
  "xrArr" => [0x027F9],
  "xrarr" => [0x027F6],
  "xscr" => [0x1D4CD],
  "xsqcup" => [0x02A06],
  "xuplus" => [0x02A04],
  "xutri" => [0x025B3],
  "xvee" => [0x022C1],
  "xwedge" => [0x022C0],
  "yacute" => [0x000FD],
  "yacy" => [0x0044F],
  "ycirc" => [0x00177],
  "ycy" => [0x0044B],
  "yen" => [0x000A5],
  "yfr" => [0x1D536],
  "yicy" => [0x00457],
  "yopf" => [0x1D56A],
  "yscr" => [0x1D4CE],
  "yucy" => [0x0044E],
  "yuml" => [0x000FF],
  "zacute" => [0x0017A],
  "zcaron" => [0x0017E],
  "zcy" => [0x00437],
  "zdot" => [0x0017C],
  "zeetrf" => [0x02128],
  "zeta" => [0x003B6],
  "zfr" => [0x1D537],
  "zhcy" => [0x00436],
  "zigrarr" => [0x021DD],
  "zopf" => [0x1D56B],
  "zscr" => [0x1D4CF],
  "zwj" => [0x0200D],
  "zwnj" => [0x0200C],
}

# frozen_string_literal: true
##
# A normal class, neither singleton nor anonymous

class RDoc::NormalClass < RDoc::ClassModule

  ##
  # The ancestors of this class including modules.  Unlike Module#ancestors,
  # this class is not included in the result.  The result will contain both
  # RDoc::ClassModules and Strings.

  def ancestors
    if String === superclass then
      super << superclass
    elsif superclass then
      ancestors = super
      ancestors << superclass
      ancestors.concat superclass.ancestors
    else
      super
    end
  end

  def aref_prefix # :nodoc:
    'class'
  end

  ##
  # The definition of this class, <tt>class MyClassName</tt>

  def definition
    "class #{full_name}"
  end

  def direct_ancestors
    superclass ? super + [superclass] : super
  end

  def inspect # :nodoc:
    superclass = @superclass ? " < #{@superclass}" : nil
    "<%s:0x%x class %s%s includes: %p extends: %p attributes: %p methods: %p aliases: %p>" % [
      self.class, object_id,
      full_name, superclass, @includes, @extends, @attributes, @method_list, @aliases
    ]
  end

  def to_s # :nodoc:
    display = "#{self.class.name} #{self.full_name}"
    if superclass
      display += ' < ' + (superclass.is_a?(String) ? superclass : superclass.full_name)
    end
    display += ' -> ' + is_alias_for.to_s if is_alias_for
    display
  end

  def pretty_print q # :nodoc:
    superclass = @superclass ? " < #{@superclass}" : nil

    q.group 2, "[class #{full_name}#{superclass} ", "]" do
      q.breakable
      q.text "includes:"
      q.breakable
      q.seplist @includes do |inc| q.pp inc end

      q.breakable
      q.text "constants:"
      q.breakable
      q.seplist @constants do |const| q.pp const end

      q.breakable
      q.text "attributes:"
      q.breakable
      q.seplist @attributes do |attr| q.pp attr end

      q.breakable
      q.text "methods:"
      q.breakable
      q.seplist @method_list do |meth| q.pp meth end

      q.breakable
      q.text "aliases:"
      q.breakable
      q.seplist @aliases do |aliaz| q.pp aliaz end

      q.breakable
      q.text "comment:"
      q.breakable
      q.pp comment
    end
  end

end

# frozen_string_literal: true
##
# This module provides i18n related features.

module RDoc::I18n

  autoload :Locale, 'rdoc/i18n/locale'
  require_relative 'i18n/text'

end
# frozen_string_literal: true
##
# A Module included in a class with \#include
#
#   RDoc::Include.new 'Enumerable', 'comment ...'

class RDoc::Include < RDoc::Mixin

end

# 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-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}

                       # Stand-alone method (preceded by a #)
                       | \\?\##{METHOD_REGEXP_STR}

                       # Stand-alone method (preceded by ::)
                       | ::#{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)

                       # 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 \<tt>, though.
                       # TODO: including < is a hack, not very satisfying.
                       | \\[^\s<]
                      )

                      # labels for headings
                      (?:@[\w+%-]+(?:\.[\w|%-]+)?)?
                     )/x

  ##
  # Version of CROSSREF_REGEXP used when <tt>--hyperlink-all</tt> is specified.

  ALL_CROSSREF_REGEXP = /
                     (?:^|[\s()])
                     (
                      (?:
                       # A::B::C.meth
                       #{CLASS_REGEXP_STR}(?:[.#]|::)#{METHOD_REGEXP_STR}

                       # Stand-alone method
                       | \\?#{METHOD_REGEXP_STR}

                       # A::B::C
                       | #{CLASS_REGEXP_STR}(?=[@\s).?!,;<\000]|\z)

                       # 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

  ##
  # 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

    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 = case name
          when /^\\(#{CLASS_REGEXP_STR})$/o then
            @context.find_symbol $1
          else
            @context.find_symbol name
          end 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 <tt>
            ref ? $' : name
          elsif ref then
            if ref.display? then
              ref
            else
              text
            end
          else
            text
          end

    @seen[name] = out

    out
  end

end

module RDoc

  ##
  # RDoc version you are using

  VERSION = '6.3.4.1'

end
# 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

  # 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.join "\n"
  end
end
# frozen_string_literal: true
require 'rubygems/user_interaction'
require 'fileutils'
require 'rdoc'

##
# Gem::RDoc provides methods to generate RDoc and ri data for installed gems
# upon gem installation.
#
# This file is automatically required by RubyGems 1.9 and newer.

class RDoc::RubygemsHook

  include Gem::UserInteraction
  extend  Gem::UserInteraction

  @rdoc_version = nil
  @specs = []

  ##
  # Force installation of documentation?

  attr_accessor :force

  ##
  # Generate rdoc?

  attr_accessor :generate_rdoc

  ##
  # Generate ri data?

  attr_accessor :generate_ri

  class << self

    ##
    # Loaded version of RDoc.  Set by ::load_rdoc

    attr_reader :rdoc_version

  end

  ##
  # Post installs hook that generates documentation for each specification in
  # +specs+

  def self.generation_hook installer, specs
    start = Time.now
    types = installer.document

    generate_rdoc = types.include? 'rdoc'
    generate_ri   = types.include? 'ri'

    specs.each do |spec|
      new(spec, generate_rdoc, generate_ri).generate
    end

    return unless generate_rdoc or generate_ri

    duration = (Time.now - start).to_i
    names    = specs.map(&:name).join ', '

    say "Done installing documentation for #{names} after #{duration} seconds"
  end

  ##
  # Loads the RDoc generator

  def self.load_rdoc
    return if @rdoc_version

    require_relative 'rdoc'

    @rdoc_version = Gem::Version.new ::RDoc::VERSION
  end

  ##
  # Creates a new documentation generator for +spec+.  RDoc and ri data
  # generation can be enabled or disabled through +generate_rdoc+ and
  # +generate_ri+ respectively.
  #
  # Only +generate_ri+ is enabled by default.

  def initialize spec, generate_rdoc = false, generate_ri = true
    @doc_dir   = spec.doc_dir
    @force     = false
    @rdoc      = nil
    @spec      = spec

    @generate_rdoc = generate_rdoc
    @generate_ri   = generate_ri

    @rdoc_dir = spec.doc_dir 'rdoc'
    @ri_dir   = spec.doc_dir 'ri'
  end

  ##
  # Removes legacy rdoc arguments from +args+
  #--
  # TODO move to RDoc::Options

  def delete_legacy_args args
    args.delete '--inline-source'
    args.delete '--promiscuous'
    args.delete '-p'
    args.delete '--one-file'
  end

  ##
  # Generates documentation using the named +generator+ ("darkfish" or "ri")
  # and following the given +options+.
  #
  # Documentation will be generated into +destination+

  def document generator, options, destination
    generator_name = generator

    options = options.dup
    options.exclude ||= [] # TODO maybe move to RDoc::Options#finish
    options.setup_generator generator
    options.op_dir = destination
    options.finish

    generator = options.generator.new @rdoc.store, options

    @rdoc.options = options
    @rdoc.generator = generator

    say "Installing #{generator_name} documentation for #{@spec.full_name}"

    FileUtils.mkdir_p options.op_dir

    Dir.chdir options.op_dir do
      begin
        @rdoc.class.current = @rdoc
        @rdoc.generator.generate
      ensure
        @rdoc.class.current = nil
      end
    end
  end

  ##
  # Generates RDoc and ri data

  def generate
    return if @spec.default_gem?
    return unless @generate_ri or @generate_rdoc

    setup

    options = nil

    args = @spec.rdoc_options
    args.concat @spec.source_paths
    args.concat @spec.extra_rdoc_files

    case config_args = Gem.configuration[:rdoc]
    when String then
      args = args.concat config_args.split(' ')
    when Array then
      args = args.concat config_args
    end

    delete_legacy_args args

    Dir.chdir @spec.full_gem_path do
      options = ::RDoc::Options.new
      options.default_title = "#{@spec.full_name} Documentation"
      options.parse args
    end

    options.quiet = !Gem.configuration.really_verbose

    @rdoc = new_rdoc
    @rdoc.options = options

    store = RDoc::Store.new
    store.encoding = options.encoding
    store.dry_run  = options.dry_run
    store.main     = options.main_page
    store.title    = options.title

    @rdoc.store = store

    say "Parsing documentation for #{@spec.full_name}"

    Dir.chdir @spec.full_gem_path do
      @rdoc.parse_files options.files
    end

    document 'ri',       options, @ri_dir if
      @generate_ri   and (@force or not File.exist? @ri_dir)

    document 'darkfish', options, @rdoc_dir if
      @generate_rdoc and (@force or not File.exist? @rdoc_dir)
  end

  ##
  # #new_rdoc creates a new RDoc instance.  This method is provided only to
  # make testing easier.

  def new_rdoc # :nodoc:
    ::RDoc::RDoc.new
  end

  ##
  # Is rdoc documentation installed?

  def rdoc_installed?
    File.exist? @rdoc_dir
  end

  ##
  # Removes generated RDoc and ri data

  def remove
    base_dir = @spec.base_dir

    raise Gem::FilePermissionError, base_dir unless File.writable? base_dir

    FileUtils.rm_rf @rdoc_dir
    FileUtils.rm_rf @ri_dir
  end

  ##
  # Is ri data installed?

  def ri_installed?
    File.exist? @ri_dir
  end

  ##
  # Prepares the spec for documentation generation

  def setup
    self.class.load_rdoc

    raise Gem::FilePermissionError, @doc_dir if
      File.exist?(@doc_dir) and not File.writable?(@doc_dir)

    FileUtils.mkdir_p @doc_dir unless File.exist? @doc_dir
  end

end
# frozen_string_literal: true
##
# A TokenStream is a list of tokens, gathered during the parse of some entity
# (say a method). Entities populate these streams by being registered with the
# lexer. Any class can collect tokens by including TokenStream. From the
# outside, you use such an object by calling the start_collecting_tokens
# method, followed by calls to add_token and pop_token.

module RDoc::TokenStream

  ##
  # Converts +token_stream+ to HTML wrapping various tokens with
  # <tt><span></tt> elements. Some tokens types are wrapped in spans
  # with the given class names. Other token types are not wrapped in spans.

  def self.to_html token_stream
    starting_title = false

    token_stream.map do |t|
      next unless t

      style = case t[:kind]
              when :on_const   then 'ruby-constant'
              when :on_kw      then 'ruby-keyword'
              when :on_ivar    then 'ruby-ivar'
              when :on_cvar    then 'ruby-identifier'
              when :on_gvar    then 'ruby-identifier'
              when '=' != t[:text] && :on_op
                               then 'ruby-operator'
              when :on_tlambda then 'ruby-operator'
              when :on_ident   then 'ruby-identifier'
              when :on_label   then 'ruby-value'
              when :on_backref, :on_dstring
                               then 'ruby-node'
              when :on_comment then 'ruby-comment'
              when :on_embdoc  then 'ruby-comment'
              when :on_regexp  then 'ruby-regexp'
              when :on_tstring then 'ruby-string'
              when :on_int, :on_float,
                   :on_rational, :on_imaginary,
                   :on_heredoc,
                   :on_symbol, :on_CHAR then 'ruby-value'
              when :on_heredoc_beg, :on_heredoc_end
                               then 'ruby-identifier'
              end

      comment_with_nl = false
      if :on_comment == t[:kind] or :on_embdoc == t[:kind] or :on_heredoc_end == t[:kind]
        comment_with_nl = true if "\n" == t[:text][-1]
        text = t[:text].rstrip
      else
        text = t[:text]
      end

      if :on_ident == t[:kind] && starting_title
        starting_title = false
        style = 'ruby-identifier ruby-title'
      end

      if :on_kw == t[:kind] and 'def' == t[:text]
        starting_title = true
      end

      text = CGI.escapeHTML text

      if style then
        "<span class=\"#{style}\">#{text}</span>#{"\n" if comment_with_nl}"
      else
        text
      end
    end.join
  end

  ##
  # Adds +tokens+ to the collected tokens

  def add_tokens(tokens)
    @token_stream.concat(tokens)
  end

  ##
  # Adds one +token+ to the collected tokens

  def add_token(token)
    @token_stream.push(token)
  end

  ##
  # Starts collecting tokens

  def collect_tokens
    @token_stream = []
  end

  alias start_collecting_tokens collect_tokens

  ##
  # Remove the last token from the collected tokens

  def pop_token
    @token_stream.pop
  end

  ##
  # Current token stream

  def token_stream
    @token_stream
  end

  ##
  # Returns a string representation of the token stream

  def tokens_to_s
    token_stream.compact.map { |token| token[:text] }.join ''
  end

end

# frozen_string_literal: false
# fallback to console window size
def IO.default_console_size
  [
    ENV["LINES"].to_i.nonzero? || 25,
    ENV["COLUMNS"].to_i.nonzero? || 80,
  ]
end

begin
  require 'io/console'
rescue LoadError
  class << IO
    alias console_size default_console_size
  end
else
  # returns console window size
  def IO.console_size
    console.winsize
  rescue NoMethodError
    default_console_size
  end
end
# Security Policy

Please see our main security policy: https://github.com/rack/rack/security/policy
# Rackup

`rackup` provides a command line interface for running a Rack-compatible application.

[![Development Status](https://github.com/rack/rackup/workflows/Test/badge.svg)](https://github.com/rack/rackup/actions?workflow=Test)

## Installation

``` bash
$ gem install rackup
```

## Usage

In a directory with your `config.ru` simply run the command:

``` bash
$ rackup
```

Your application should now be available locally, typically `http://localhost:9292`.

## Contributing

We welcome contributions to this project.

1.  Fork it.
2.  Create your feature branch (`git checkout -b my-new-feature`).
3.  Commit your changes (`git commit -am 'Add some feature'`).
4.  Push to the branch (`git push origin my-new-feature`).
5.  Create new Pull Request.
#!/usr/bin/env ruby
# frozen_string_literal: true

require_relative "../lib/rackup"
Rackup::Server.start
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2022-2023, by Samuel Williams.

require_relative 'rackup/handler'
require_relative 'rackup/server'
require_relative 'rackup/version'

require_relative 'rackup/handler/webrick'
require_relative 'rackup/handler/cgi'
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2022-2023, by Samuel Williams.

module Rackup
  module Handler
    class CGI
      include Rack

      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_INPUT        => $stdin,
          RACK_ERRORS       => $stderr,
          RACK_URL_SCHEME   => ["yes", "on", "1"].include?(ENV[HTTPS]) ? "https" : "http"
        )

        env[QUERY_STRING] ||= ""
        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

    register :cgi, CGI
  end
end
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2022-2023, by Samuel Williams.
# Copyright, 2022, by Jeremy Evans.

require 'webrick'
require 'stringio'

require 'rack/constants'
require_relative '../handler'
require_relative '../version'

require_relative '../stream'

module Rackup
  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 "/", Rackup::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

      # This handles mapping the WEBrick request to a Rack input stream.
      class Input
        include Stream::Reader

        def initialize(request)
          @request = request

          @reader = Fiber.new do
            @request.body do |chunk|
              Fiber.yield(chunk)
            end

            Fiber.yield(nil)

            # End of stream:
            @reader = nil
          end
        end

        def close
          @request = nil
          @reader = nil
        end

        private

        # Read one chunk from the request body.
        def read_next
          @reader&.resume
        end
      end

      def service(req, res)
        env = req.meta_vars
        env.delete_if { |k, v| v.nil? }

        input = Input.new(req)

        env.update(
          ::Rack::RACK_INPUT => input,
          ::Rack::RACK_ERRORS => $stderr,
          ::Rack::RACK_URL_SCHEME => ["yes", "on", "1"].include?(env[::Rack::HTTPS]) ? "https" : "http",
          ::Rack::RACK_IS_HIJACK => true,
        )

        env[::Rack::QUERY_STRING] ||= ""
        unless env[::Rack::PATH_INFO] == ""
          path, n = req.request_uri.path, env[::Rack::SCRIPT_NAME].length
          env[::Rack::PATH_INFO] = path[n, path.length - n]
        end
        env[::Rack::REQUEST_PATH] ||= [env[::Rack::SCRIPT_NAME], env[::Rack::PATH_INFO]].join

        status, headers, body = @app.call(env)
        begin
          res.status = status

          if value = headers[::Rack::RACK_HIJACK]
            io_lambda = value
            body = nil
          elsif !body.respond_to?(:to_path) && !body.respond_to?(:each)
            io_lambda = body
            body = nil
          end

          if value = headers.delete('set-cookie')
            res.cookies.concat(Array(value))
          end

          headers.each do |key, value|
            # Skip keys starting with rack., per Rack SPEC
            next if key.start_with?('rack.')

            # Since WEBrick won't accept repeated headers,
            # merge the values per RFC 1945 section 4.2.
            value = value.join(", ") if Array === value
            res[key] = value
          end

          if io_lambda
            protocol = headers['rack.protocol'] || headers['upgrade']

            if protocol
              # Set all the headers correctly for an upgrade response:
              res.upgrade!(protocol)
            end
            res.body = io_lambda
          elsif body.respond_to?(:to_path)
            res.body = ::File.open(body.to_path, 'rb')
          else
            buffer = String.new
            body.each do |part|
              buffer << part
            end
            res.body = buffer
          end
        ensure
          body.close if body.respond_to?(:close)
        end
      end
    end

    register :webrick, WEBrick
  end
end
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2022-2023, by Samuel Williams.

require 'optparse'
require 'fileutils'

require 'rack/builder'
require 'rack/common_logger'
require 'rack/content_length'
require 'rack/show_exceptions'
require 'rack/lint'
require 'rack/tempfile_reaper'

require 'rack/version'

require_relative 'version'
require_relative 'handler'

module Rackup
  class Server
    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] ||= true
          }

          opts.on("--daemonize-noclose", "run daemonized in the background without closing stdout/stderr") {
            options[:daemonize] = :noclose
          }

          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|
            unless %w[cpu wall object].include?(e)
              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::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)
        info = []
        server = Rackup::Handler.get(options[:server]) || Rackup::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 << sprintf("  -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

    # 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 Rackup::Handler, e.g. cgi, fcgi, webrick
    # * :daemonize
    #     if truthy, the server will daemonize itself (fork, detach, etc)
    #     if :noclose, the server will not close STDOUT/STDERR
    # * :pid
    #     path to write a pid file after daemonize
    # * :Host
    #     the host address to bind to (used by supporting Rackup::Handler)
    # * :Port
    #     the port to bind to (used by supporting Rackup::Handler)
    # * :AccessLog
    #     webrick access log options (or supporting Rackup::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
        @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 ||= Handler.get(options[:server]) || Handler.default
    end

    private
      def build_app_and_options_from_config
        if !::File.exist? options[:config]
          abort "configuration #{options[:config]} not found"
        end

        return Rack::Builder.parse_file(self.options[:config])
      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.
        args.clear if ENV.include?(Rack::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(true, options[:daemonize] == :noclose)
        # :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!
        return unless ::File.exist?(options[:pid])

        pid = ::File.read(options[:pid]).to_i
        raise Errno::ESRCH if pid == 0

        Process.kill(0, pid)
        exit_with_pid(pid)
      rescue Errno::ESRCH
        ::File.delete(options[:pid])
      rescue Errno::EPERM
        exit_with_pid(pid)
      end

      def exit_with_pid(pid)
        $stderr.puts "A server is already running (pid: #{pid}, file: #{options[:pid]})."
        exit(1)
      end
  end

end
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2022-2023, by Samuel Williams.

module Rackup
  # *Handlers* connect web servers with Rack.
  #
  # Rackup includes Handlers for WEBrick and CGI.
  #
  # Handlers usually are activated by calling <tt>MyHandler.run(myapp)</tt>.
  # A second optional hash can be passed to include server-specific
  # configuration.
  module Handler
    @handlers = {}

    # Register a named handler class.
    def self.register(name, klass)
      if klass.is_a?(String)
        warn "Calling Rackup::Handler.register with a string is deprecated, use the class/module itself.", uplevel: 1

        klass = self.const_get(klass, false)
      end

      name = name.to_sym

      @handlers[name] = klass
    end

    def self.[](name)
      name = name.to_sym

      begin
        @handlers[name] || self.const_get(name, false)
      rescue NameError
        # Ignore.
      end
    end

    def self.get(name)
      return nil unless name

      name = name.to_sym

      if server = self[name]
        return server
      end

      begin
        require_handler("rackup/handler", name)
      rescue LoadError
        require_handler("rack/handler", name)
      end

      return self[name]
    end

    RACK_HANDLER = 'RACK_HANDLER'
    RACKUP_HANDLER = 'RACKUP_HANDLER'

    SERVER_NAMES = %i(puma falcon webrick).freeze
    private_constant :SERVER_NAMES

    # Select first available Rack handler given an `Array` of server names.
    # Raises `LoadError` if no handler was found.
    #
    #   > pick ['puma', 'webrick']
    #   => Rackup::Handler::WEBrick
    def self.pick(server_names)
      server_names = Array(server_names)

      server_names.each do |server_name|
        begin
          server = self.get(server_name)
         return server if server
        rescue LoadError
          # Ignore.
        end
      end

      raise LoadError, "Couldn't find handler for: #{server_names.join(', ')}."
    end

    def self.default
      if rack_handler = ENV[RACKUP_HANDLER]
        self.get(rack_handler)
      elsif rack_handler = ENV[RACK_HANDLER]
        warn "RACK_HANDLER is deprecated, use RACKUP_HANDLER."
        self.get(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.require_handler(prefix, const_name)
      file = const_name.to_s.gsub(/^[A-Z]+/) { |pre| pre.downcase }.
        gsub(/[A-Z]+[^A-Z]/, '_\&').downcase

      require(::File.join(prefix, file))
    end
  end
end
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2019-2022, by Samuel Williams.

module Rackup
  # 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.
  class Stream
    def initialize(input = nil, output = Buffered.new)
      @input = input
      @output = output

      raise ArgumentError, "Non-writable output!" unless output.respond_to?(:write)

      # Will hold remaining data in `#read`.
      @buffer = nil
      @closed = false
    end

    attr :input
    attr :output

    # This provides a read-only interface for data, which is surprisingly tricky to implement correctly.
    module Reader
      # rack.hijack_io must respond to:
      # read, write, read_nonblock, write_nonblock, flush, close, close_read, close_write, closed?

      # 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.
      # @param length [Integer] the amount of data to read
      # @param buffer [String] the buffer which will receive the data
      # @return a buffer containing the data
      def read(length = nil, buffer = nil)
        return '' if length == 0

        buffer ||= String.new.force_encoding(Encoding::BINARY)

        # Take any previously buffered data and replace it into the given buffer.
        if @buffer
          buffer.replace(@buffer)
          @buffer = nil
        else
          buffer.clear
        end

        if length
          while buffer.bytesize < length and chunk = read_next
            buffer << chunk
          end

          # This ensures the subsequent `slice!` works correctly.
          buffer.force_encoding(Encoding::BINARY)

          # This will be at least one copy:
          @buffer = buffer.byteslice(length, buffer.bytesize)

          # This should be zero-copy:
          buffer.slice!(length, buffer.bytesize)

          if buffer.empty?
            return nil
          else
            return buffer
          end
        else
          while chunk = read_next
            buffer << chunk
          end

          return buffer
        end
      end

      # Read at most `length` bytes from the stream. Will avoid reading from the underlying stream if possible.
      def read_partial(length = nil)
        if @buffer
          buffer = @buffer
          @buffer = nil
        else
          buffer = read_next
        end

        if buffer and length
          if buffer.bytesize > length
            # This ensures the subsequent `slice!` works correctly.
            buffer.force_encoding(Encoding::BINARY)

            @buffer = buffer.byteslice(length, buffer.bytesize)
            buffer.slice!(length, buffer.bytesize)
          end
        end

        return buffer
      end

      def gets
        read_partial
      end

      def each
        while chunk = read_partial
          yield chunk
        end
      end

      def read_nonblock(length, buffer = nil)
        @buffer ||= read_next
        chunk = nil

        unless @buffer
          buffer&.clear
          return
        end

        if @buffer.bytesize > length
          chunk = @buffer.byteslice(0, length)
          @buffer = @buffer.byteslice(length, @buffer.bytesize)
        else
          chunk = @buffer
          @buffer = nil
        end

        if buffer
          buffer.replace(chunk)
        else
          buffer = chunk
        end

        return buffer
      end
    end

    include Reader

    def write(buffer)
      if @output
        @output.write(buffer)
        return buffer.bytesize
      else
        raise IOError, "Stream is not writable, output has been closed!"
      end
    end

    def write_nonblock(buffer)
      write(buffer)
    end

    def <<(buffer)
      write(buffer)
    end

    def flush
    end

    def close_read
      @input&.close
      @input = nil
    end

    # close must never be called on the input stream. huh?
    def close_write
      if @output.respond_to?(:close)
        @output&.close
      end

      @output = nil
    end

    # Close the input and output bodies.
    def close(error = nil)
      self.close_read
      self.close_write

      return nil
    ensure
      @closed = true
    end

    # Whether the stream has been closed.
    def closed?
      @closed
    end

    # Whether there are any output chunks remaining?
    def empty?
      @output.empty?
    end

    private

    def read_next
      if @input
        return @input.read
      else
        @input = nil
        raise IOError, "Stream is not readable, input has been closed!"
      end
    end
  end
end
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2022-2023, by Samuel Williams.

require 'zlib'

require 'rack/constants'
require 'rack/request'
require 'rack/response'

module Rackup
  # Paste has a Pony, Rack has a Lobster!
  class Lobster
    include Rack

    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 = ["<title>Lobstericious!</title>",
                 "<pre>", lobster, "</pre>",
                 "<a href='#{href}'>flip!</a>"]
      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 "<title>Lobstericious!</title>"
      res.write "<pre>"
      res.write lobster
      res.write "</pre>"
      res.write "<p><a href='#{href}'>flip!</a></p>"
      res.write "<p><a href='?flip=crash'>crash!</a></p>"
      res.finish
    end

  end
end

if $0 == __FILE__
  # :nocov:
  require_relative 'server'
  require_relative 'show_exceptions'
  require_relative 'lint'
  Rackup::Server.start(
    app: Rack::ShowExceptions.new(Rack::Lint.new(Rackup::Lobster.new)), Port: 9292
  )
  # :nocov:
end
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2022-2023, by Samuel Williams.

module Rackup
  VERSION = "2.1.0"
end
# MIT License

Copyright, 2007-2009, by Leah Neukirchen.  
Copyright, 2008, by Marc-André Cournoyer.  
Copyright, 2009, by Aaron Pfeifer.  
Copyright, 2009-2010, by Megan Batty.  
Copyright, 2009-2010, by Michael Fellinger.  
Copyright, 2009, by Genki Takiuchi.  
Copyright, 2009, by Joshua Peek.  
Copyright, 2009, by Yehuda Katz + Carl Lerche.  
Copyright, 2009, by Carl Lerche.  
Copyright, 2010, by Julik Tarkhanov.  
Copyright, 2010-2016, by James Tucker.  
Copyright, 2010, by Timur Batyrshin.  
Copyright, 2010, by Loren Segal.  
Copyright, 2010, by Andrew Bortz.  
Copyright, 2010, by John Barnette.  
Copyright, 2010, by John Sumsion.  
Copyright, 2011-2018, by Aaron Patterson.  
Copyright, 2011, by Konstantin Haase.  
Copyright, 2011, by Blake Mizerany.  
Copyright, 2011, by Tsutomu Kuroda.  
Copyright, 2012, by Jean Boussier.  
Copyright, 2012, by Trevor Wennblom.  
Copyright, 2012, by Anurag Priyam.  
Copyright, 2012, by Hrvoje Šimić.  
Copyright, 2013, by Uchio KONDO.  
Copyright, 2013, by Tim Moore.  
Copyright, 2013, by Postmodern.  
Copyright, 2013, by Bas Vodde.  
Copyright, 2013, by Joe Fiorini.  
Copyright, 2014, by Wyatt Pan.  
Copyright, 2014, by Lenny Marks.  
Copyright, 2014, by Igor Bochkariov.  
Copyright, 2014, by Max Cantor.  
Copyright, 2014, by David Celis.  
Copyright, 2014, by Rafael Mendonça França.  
Copyright, 2014, by Jeremy Kemper.  
Copyright, 2014, by Richard Schneeman.  
Copyright, 2015, by Peter Wilmott.  
Copyright, 2015, by Sean McGivern.  
Copyright, 2015, by Tadashi Saito.  
Copyright, 2015, by deepj.  
Copyright, 2015, by Zachary Scott.  
Copyright, 2016, by Sophie Deziel.  
Copyright, 2016, by Kazuya Hotta.  
Copyright, 2017, by Ryunosuke Sato.  
Copyright, 2017-2023, by Samuel Williams.  
Copyright, 2018, by Dillon Welch.  
Copyright, 2018, by Yoshiyuki Hirano.  
Copyright, 2018, by Nick LaMuro.  
Copyright, 2019, by Rafael França.  
Copyright, 2019, by Krzysztof Rybka.  
Copyright, 2019, by Misaki Shioi.  
Copyright, 2020-2022, by Jeremy Evans.  
Copyright, 2021, by Katsuhiko YOSHIDA.  
Copyright, 2021, by KS.  
Copyright, 2021, by Stephen Paul Weber.  
Copyright, 2022, by Akira Matsuda.  
Copyright, 2022, by Andrew Hoglund.  

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.
# 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 'psych/y'
end
# frozen_string_literal: true
require 'psych/visitors/visitor'
require 'psych/visitors/to_ruby'
require 'psych/visitors/emitter'
require 'psych/visitors/yaml_tree'
require 'psych/visitors/json_tree'
require 'psych/visitors/depth_first'
# 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
# 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
# frozen_string_literal: true
require 'stringio'
require 'psych/class_loader'
require 'psych/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
# 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
# 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
# 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
# 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
# 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
# frozen_string_literal: true
module Psych
  class Set < ::Hash
  end
end
# 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
# frozen_string_literal: true
require 'psych/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
# frozen_string_literal: true
require 'psych/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
# frozen_string_literal: true
require 'psych/omap'
require 'psych/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, 'Symbol'
        end
      end

      private

      def find klassname
        if @classes.include? klassname
          super
        else
          raise DisallowedClass, klassname
        end
      end
    end
  end
end
# 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
# frozen_string_literal: true
require 'psych/json/ruby_events'
require 'psych/json/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
# 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
# frozen_string_literal: true
require 'psych/json/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
# 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
# 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
    FLOAT = /^(?:[-+]?([0-9][0-9_,]*)?\.[0-9]*([eE][-+][0-9]+)?(?# base 10)
              |[-+]?\.(inf|Inf|INF)(?# infinity)
              |\.(nan|NaN|NAN)(?# not a number))$/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_,]*) (?# 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?(/^[^\d\.:-]?[A-Za-z_\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
# frozen_string_literal: true
require 'psych/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 || '<unknown>'
      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
# 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

# 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
# frozen_string_literal: true
require 'psych/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
# 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
# frozen_string_literal: true
require 'psych/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
# 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
# frozen_string_literal: true
require 'psych/scalar_scanner'
require 'psych/class_loader'
require 'psych/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
# 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
# frozen_string_literal: true
require 'psych/tree_builder'
require 'psych/scalar_scanner'
require 'psych/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 # => #<Psych::Nodes::Stream .. }
    #
    class YAMLTree < Psych::Visitors::Visitor
      class Registrar # :nodoc:
        def initialize
          @obj_to_id   = {}
          @obj_to_node = {}
          @targets     = []
          @counter     = 0
        end

        def register target, node
          return unless target.respond_to? :object_id
          @targets << target
          @obj_to_node[target.object_id] = node
        end

        def key? target
          @obj_to_node.key? target.object_id
        rescue NoMethodError
          false
        end

        def id_for target
          @obj_to_id[target.object_id] ||= (@counter += 1)
        end

        def node_for target
          @obj_to_node[target.object_id]
        end
      end

      attr_reader :started, :finished
      alias :finished? :finished
      alias :started? :started

      def self.create options = {}, emitter = nil
        emitter      ||= TreeBuilder.new
        class_loader = ClassLoader.new
        ss           = ScalarScanner.new class_loader
        new(emitter, ss, options)
      end

      def initialize emitter, ss, options
        super()
        @started    = false
        @finished   = false
        @emitter    = emitter
        @st         = Registrar.new
        @ss         = ss
        @options    = options
        @line_width = options[:line_width]
        if @line_width && @line_width < 0
          if @line_width == -1
            # Treat -1 as unlimited line-width, same as libyaml does.
            @line_width = nil
          else
            fail(ArgumentError, "Invalid line_width #{@line_width}, must be non-negative or -1 for unlimited.")
          end
        end
        @coders     = []

        @dispatch_cache = Hash.new do |h,klass|
          method = "visit_#{(klass.name || '').split('::').join('_')}"

          method = respond_to?(method) ? method : h[klass.superclass]

          raise(TypeError, "Can't dump #{target.class}") unless method

          h[klass] = method
        end.compare_by_identity
      end

      def start encoding = Nodes::Stream::UTF8
        @emitter.start_stream(encoding).tap do
          @started = true
        end
      end

      def finish
        @emitter.end_stream.tap do
          @finished = true
        end
      end

      def tree
        finish unless finished?
        @emitter.root
      end

      def push object
        start unless started?
        version = []
        version = [1,1] if @options[:header]

        case @options[:version]
        when Array
          version = @options[:version]
        when String
          version = @options[:version].split('.').map { |x| x.to_i }
        else
          version = [1,1]
        end if @options.key? :version

        @emitter.start_document version, [], false
        accept object
        @emitter.end_document !@emitter.streaming?
      end
      alias :<< :push

      def accept target
        # return any aliases we find
        if @st.key? target
          oid         = @st.id_for target
          node        = @st.node_for target
          anchor      = oid.to_s
          node.anchor = anchor
          return @emitter.alias anchor
        end

        if target.respond_to?(:encode_with)
          dump_coder target
        else
          send(@dispatch_cache[target.class], target)
        end
      end

      def visit_Psych_Omap o
        seq = @emitter.start_sequence(nil, 'tag:yaml.org,2002:omap', false, Nodes::Sequence::BLOCK)
        register(o, seq)

        o.each { |k,v| visit_Hash k => 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 @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
  end
end
# frozen_string_literal: true
module Psych
  class Omap < ::Hash
  end
end
# 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
# frozen_string_literal: true
module Psych
  class Exception < RuntimeError
  end

  class BadAlias < Exception
  end

  class DisallowedClass < Exception
    def initialize klass_name
      super "Tried to load unspecified class: #{klass_name}"
    end
  end
end
# frozen_string_literal: true

module Psych
  # The version of Psych you are using
  VERSION = '3.3.2'

  if RUBY_ENGINE == 'jruby'
    DEFAULT_SNAKEYAML_VERSION = '1.28'.freeze
  end
end
# frozen_string_literal: true
require 'psych/nodes/node'
require 'psych/nodes/stream'
require 'psych/nodes/document'
require 'psych/nodes/sequence'
require 'psych/nodes/scalar'
require 'psych/nodes/mapping'
require 'psych/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
# frozen_string_literal: true
require 'psych/versions'
case RUBY_ENGINE
when 'jruby'
  require '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 'psych/nodes'
require 'psych/streaming'
require 'psych/visitors'
require 'psych/handler'
require 'psych/tree_builder'
require 'psych/parser'
require 'psych/omap'
require 'psych/set'
require 'psych/coder'
require 'psych/core_ext'
require 'psych/stream'
require 'psych/json/tree_builder'
require 'psych/json/stream'
require 'psych/handlers/document_stream'
require 'psych/class_loader'

###
# = Overview
#
# Psych is a YAML parser and emitter.
# Psych leverages libyaml [Home page: https://pyyaml.org/wiki/LibYAML]
# or [HG repo: https://bitbucket.org/xi/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)  # => #<StringIO:0x000001009d0890>
#
#   # 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) # => #<Psych::Parser>
#   parser = Psych.parser                       # it's an alias for the above
#
#   parser.parse("---\n - a\n - b")             # => #<Psych::Parser>
#   parser.handler                              # => #<Psych::TreeBuilder>
#   parser.handler.root                         # => #<Psych::Nodes::Stream>
#
# ==== 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")       # => #<Psych::Parser>
#
#   parser.handler.first              # => #<Psych::Nodes::Stream>
#   parser.handler.first.to_ruby      # => ["a"]
#
#   parser.handler.root.first         # => #<Psych::Nodes::Document>
#   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
  # Deprecation guard
  NOT_GIVEN = Object.new.freeze
  private_constant :NOT_GIVEN

  ###
  # 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
  #
  # 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 method.
  #
  def self.unsafe_load yaml, legacy_filename = NOT_GIVEN, filename: nil, fallback: false, symbolize_names: false, freeze: false
    if legacy_filename != NOT_GIVEN
      warn_with_uplevel 'Passing filename with the 2nd argument of Psych.load is deprecated. Use keyword argument like Psych.load(yaml, filename: ...) instead.', uplevel: 1 if $VERBOSE
      filename = legacy_filename
    end

    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
  # * Numeric
  # * 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, legacy_permitted_classes = NOT_GIVEN, legacy_permitted_symbols = NOT_GIVEN, legacy_aliases = NOT_GIVEN, legacy_filename = NOT_GIVEN, permitted_classes: [], permitted_symbols: [], aliases: false, filename: nil, fallback: nil, symbolize_names: false, freeze: false
    if legacy_permitted_classes != NOT_GIVEN
      warn_with_uplevel 'Passing permitted_classes with the 2nd argument of Psych.safe_load is deprecated. Use keyword argument like Psych.safe_load(yaml, permitted_classes: ...) instead.', uplevel: 1 if $VERBOSE
      permitted_classes = legacy_permitted_classes
    end

    if legacy_permitted_symbols != NOT_GIVEN
      warn_with_uplevel 'Passing permitted_symbols with the 3rd argument of Psych.safe_load is deprecated. Use keyword argument like Psych.safe_load(yaml, permitted_symbols: ...) instead.', uplevel: 1 if $VERBOSE
      permitted_symbols = legacy_permitted_symbols
    end

    if legacy_aliases != NOT_GIVEN
      warn_with_uplevel 'Passing aliases with the 4th argument of Psych.safe_load is deprecated. Use keyword argument like Psych.safe_load(yaml, aliases: ...) instead.', uplevel: 1 if $VERBOSE
      aliases = legacy_aliases
    end

    if legacy_filename != NOT_GIVEN
      warn_with_uplevel 'Passing filename with the 5th argument of Psych.safe_load is deprecated. Use keyword argument like Psych.safe_load(yaml, filename: ...) instead.', uplevel: 1 if $VERBOSE
      filename = legacy_filename
    end

    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

  ###
  # 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") # => #<Psych::Nodes::Document:0x00>
  #
  #   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, legacy_filename = NOT_GIVEN, filename: nil, fallback: NOT_GIVEN
    if legacy_filename != NOT_GIVEN
      warn_with_uplevel 'Passing filename with the 2nd argument of Psych.parse is deprecated. Use keyword argument like Psych.parse(yaml, filename: ...) instead.', uplevel: 1 if $VERBOSE
      filename = legacy_filename
    end

    parse_stream(yaml, filename: filename) do |node|
      return node
    end

    if fallback != NOT_GIVEN
      warn_with_uplevel 'Passing the `fallback` keyword argument of Psych.parse is deprecated.', uplevel: 1 if $VERBOSE
      fallback
    else
      false
    end
  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::Nodes::Stream:0x00>
  #
  #   Psych.parse_stream("--- a\n--- b") do |node|
  #     node # => #<Psych::Nodes::Document:0x00>
  #   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, legacy_filename = NOT_GIVEN, filename: nil, &block
    if legacy_filename != NOT_GIVEN
      warn_with_uplevel 'Passing filename with the 2nd argument of Psych.parse_stream is deprecated. Use keyword argument like Psych.parse_stream(yaml, filename: ...) instead.', uplevel: 1 if $VERBOSE
      filename = legacy_filename
    end

    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:
  #
  # [<tt>:indentation</tt>]   Number of space characters used to indent.
  #                           Acceptable value should be in <tt>0..9</tt> range,
  #                           otherwise option is ignored.
  #
  #                           Default: <tt>2</tt>.
  # [<tt>:line_width</tt>]    Max character to wrap line at.
  #
  #                           Default: <tt>0</tt> (meaning "wrap at 81").
  # [<tt>:canonical</tt>]     Write "canonical" YAML form (very verbose, yet
  #                           strictly formal).
  #
  #                           Default: <tt>false</tt>.
  # [<tt>:header</tt>]        Write <tt>%YAML [version]</tt> at the beginning of document.
  #
  #                           Default: <tt>false</tt>.
  #
  # 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)  # => #<StringIO:0x000001009d0890>
  #
  #   # 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

  ###
  # 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, legacy_filename = NOT_GIVEN, filename: nil, fallback: [], **kwargs
    if legacy_filename != NOT_GIVEN
      warn_with_uplevel 'Passing filename with the 2nd argument of Psych.load_stream is deprecated. Use keyword argument like Psych.load_stream(yaml, filename: ...) instead.', uplevel: 1 if $VERBOSE
      filename = legacy_filename
    end

    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
  class << self; alias :load_file :unsafe_load_file; 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

  # :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
The MIT License (MIT)

Copyright (C) 2007-2021 Leah Neukirchen <http://leahneukirchen.org/infopage.html>

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.
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 a non-frozen 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 Rack application is free to modify the
environment.

The environment is required to include these variables
(adopted from {PEP 333}[https://peps.python.org/pep-0333/]), except when they'd be empty, but see
below.
<tt>REQUEST_METHOD</tt>:: The HTTP request method, such as
                          "GET" or "POST". This cannot ever
                          be an empty string, and so is
                          always required.
<tt>SCRIPT_NAME</tt>:: 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.
<tt>PATH_INFO</tt>:: 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.
<tt>QUERY_STRING</tt>:: The portion of the request URL that
                        follows the <tt>?</tt>, if any. May be
                        empty, but is always required!
<tt>SERVER_NAME</tt>:: When combined with <tt>SCRIPT_NAME</tt> and
                       <tt>PATH_INFO</tt>, these variables can be
                       used to complete the URL. Note, however,
                       that <tt>HTTP_HOST</tt>, if present,
                       should be used in preference to
                       <tt>SERVER_NAME</tt> for reconstructing
                       the request URL.
                       <tt>SERVER_NAME</tt> can never be an empty
                       string, and so is always required.
<tt>SERVER_PORT</tt>:: 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.
<tt>SERVER_PROTOCOL</tt>:: A string representing the HTTP version used
                           for the request.
<tt>HTTP_</tt> Variables:: Variables corresponding to the
                           client-supplied HTTP request
                           headers (i.e., variables whose
                           names begin with <tt>HTTP_</tt>). 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:
<tt>rack.url_scheme</tt>:: +http+ or +https+, depending on the
                           request URL.
<tt>rack.input</tt>:: See below, the input stream.
<tt>rack.errors</tt>:: See below, the error stream.
<tt>rack.hijack?</tt>:: See below, if present and true, indicates
                        that the server supports partial hijacking.
<tt>rack.hijack</tt>:: See below, if present, an object responding
                       to +call+ that is used to perform a full
                       hijack.
Additional environment specifications have approved to
standardized middleware APIs. None of these are required to
be implemented by the server.
<tt>rack.session</tt>:: 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);
<tt>rack.logger</tt>:: 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)
<tt>rack.multipart.buffer_size</tt>:: An Integer hint to the multipart parser as to what chunk size to use for reads and writes.
<tt>rack.multipart.tempfile_factory</tt>:: 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 <tt>rack.</tt>
is reserved for use with the Rack core distribution and other
accepted specifications and must not be used otherwise.

The <tt>SERVER_PORT</tt> must be an Integer if set.
The <tt>SERVER_NAME</tt> must be a valid authority as defined by RFC7540.
The <tt>HTTP_HOST</tt> must be a valid authority as defined by RFC7540.
The <tt>SERVER_PROTOCOL</tt> must match the regexp <tt>HTTP/\d(\.\d)?</tt>.
If the <tt>HTTP_VERSION</tt> is present, it must equal the <tt>SERVER_PROTOCOL</tt>.
The environment must not contain the keys
<tt>HTTP_CONTENT_TYPE</tt> or <tt>HTTP_CONTENT_LENGTH</tt>
(use the versions without <tt>HTTP_</tt>).
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:
* <tt>rack.url_scheme</tt> must either be +http+ or +https+.
* There must be a valid input stream in <tt>rack.input</tt>.
* There must be a valid error stream in <tt>rack.errors</tt>.
* There may be a valid hijack callback in <tt>rack.hijack</tt>
* The <tt>REQUEST_METHOD</tt> must be a valid token.
* The <tt>SCRIPT_NAME</tt>, if non-empty, must start with <tt>/</tt>
* The <tt>PATH_INFO</tt>, if non-empty, must start with <tt>/</tt>
* The <tt>CONTENT_LENGTH</tt>, if given, must consist of digits only.
* One of <tt>SCRIPT_NAME</tt> or <tt>PATH_INFO</tt> must be
  set. <tt>PATH_INFO</tt> should be <tt>/</tt> if
  <tt>SCRIPT_NAME</tt> is empty.
  <tt>SCRIPT_NAME</tt> never should be <tt>/</tt>, but instead be empty.
<tt>rack.response_finished</tt>:: An array of callables run by the server after the response has been
processed. This would typically be invoked after sending the response to the client, but it could also be
invoked if an error occurs while generating the response or sending the response; in that case, the error
argument will be a subclass of +Exception+.
The callables are invoked with +env, status, headers, error+ arguments and should not raise any
exceptions. They should be invoked in reverse order of registration.

=== 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+, and +read+.
* +gets+ must be called without arguments and return a string,
  or +nil+ on EOF.
* +read+ behaves like IO#read.
  Its signature is <tt>read([length, [buffer]])</tt>.

  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.
* +close+ can be called on the input stream to indicate that the
any remaining input is not needed.

=== 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

The hijacking interfaces provides a means for an application to take
control of the HTTP connection. There are two distinct hijack
interfaces: full hijacking where the application takes over the raw
connection, and partial hijacking where the application takes over
just the response body stream. In both cases, the application is
responsible for closing the hijacked stream.

Full hijacking only works with HTTP/1. Partial hijacking is functionally
equivalent to streaming bodies, and is still optionally supported for
backwards compatibility with older Rack versions.

==== Full Hijack

Full hijack is used to completely take over an HTTP/1 connection. It
occurs before any headers are written and causes the request to
ignores any response generated by the application.

It is intended to be used when applications need access to raw HTTP/1
connection.

If +rack.hijack+ is present in +env+, it must respond to +call+
and return an +IO+ instance which can be used to read and write
to the underlying connection using HTTP/1 semantics and
formatting.

==== Partial Hijack

Partial hijack is used for bi-directional streaming of the request and
response body. It occurs after the status and headers are written by
the server and causes the server to ignore the Body of the response.

It is intended to be used when applications need bi-directional
streaming.

If +rack.hijack?+ is present in +env+ and truthy,
an application may set the special response header +rack.hijack+
to an object that responds to +call+,
accepting a +stream+ argument.

After the response status and headers have been sent, this hijack
callback will be invoked with a +stream+ argument which follows the
same interface as outlined in "Streaming Body". Servers must
ignore the +body+ part of the response tuple when the
+rack.hijack+ response header is present. Using an empty +Array+
instance is recommended.

The special response header +rack.hijack+ must only be set
if the request +env+ has a truthy +rack.hijack?+.
== The Response

=== The Status

This is an HTTP status. It must be an Integer greater than or equal to
100.

=== The Headers

The headers must be a unfrozen Hash.
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.
Header keys must conform to RFC7230 token specification, i.e. cannot
contain non-printable ASCII, DQUOTE or "(),/:;<=>?@[\]{}".
Header keys must not contain uppercase ASCII characters (A-Z).
Header values must be either a String instance,
or an Array of String instances,
such that each String instance must not contain characters below 037.

=== The content-type

There must not be a <tt>content-type</tt> header key when the +Status+ is 1xx,
204, or 304.

=== The content-length

There must not be a <tt>content-length</tt> header key when the
+Status+ is 1xx, 204, or 304.

=== The Body

The Body is typically an +Array+ of +String+ instances, an enumerable
that yields +String+ instances, a +Proc+ instance, or a File-like
object.

The Body must respond to +each+ or +call+. It may optionally respond
to +to_path+ or +to_ary+. A Body that responds to +each+ is considered
to be an Enumerable Body. A Body that responds to +call+ is considered
to be a Streaming Body.

A Body that responds to both +each+ and +call+ must be treated as an
Enumerable Body, not a Streaming Body. If it responds to +each+, you
must call +each+ and not +call+. If the Body doesn't respond to
+each+, then you can assume it responds to +call+.

The Body must either be consumed or returned. The Body is consumed by
optionally calling either +each+ or +call+.
Then, if the Body responds to +close+, it must be called to release
any resources associated with the generation of the body.
In other words, +close+ must always be called at least once; typically
after the web server has sent the response to the client, but also in
cases where the Rack application makes internal/virtual requests and
discards the response.


After calling +close+, the Body is considered closed and should not
be consumed again.
If the original Body is replaced by a new Body, the new Body must
also consume the original Body by calling +close+ if possible.

If the Body responds to +to_path+, it must return a +String+
path for the local file system 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 +to_path+ method does not consume
the body.

==== Enumerable Body

The Enumerable Body must respond to +each+.
It must only be called once.
It must not be called after being closed.
and must only yield String values.

The Body itself should not be an instance of String, as this will
break in Ruby 1.9.

Middleware must not call +each+ directly on the Body.
Instead, middleware can return a new Body that calls +each+ on the
original Body, yielding at least once per iteration.

If the Body responds to +to_ary+, it must return an +Array+ whose
contents are identical to that produced by calling +each+.
Middleware may call +to_ary+ directly on the Body and return a new
Body in its place. In other words, middleware can only process the
Body directly if it responds to +to_ary+. If the Body responds to both
+to_ary+ and +close+, its implementation of +to_ary+ must call
+close+.

==== Streaming Body

The Streaming Body must respond to +call+.
It must only be called once.
It must not be called after being closed.
It takes a +stream+ argument.

The +stream+ argument must implement:
<tt>read, write, <<, flush, close, close_read, close_write, closed?</tt>

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 HTTP/2.

== Thanks
Some parts of this specification are adopted from {PEP 333 – Python Web Server Gateway Interface v1.0}[https://peps.python.org/pep-0333/]
I'd like to thank everyone involved in that effort.
# 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) and
[propose features and discuss issues](https://github.com/rack/rack/issues).

## Fork the Project

Fork the [project on GitHub](https://github.com/rack/rack) and check out your
copy.

```
git clone https://github.com/(your-github-username)/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 main
git pull upstream main
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
```

## 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 all tests pass:

```
bundle exec rake test
```

## Write Documentation

Document any external behavior in the [README](README.md).

## 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 your fork of rack on GitHub 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/main.

```
git fetch upstream
git rebase upstream/main
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
tests with GitHub Actions. 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 in
there!

## Thank You

Please do know that we really appreciate and value your time and work. We love
you, really.
# 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/).

## [3.0.7] - 2023-03-16

- Make query parameters without `=` have `nil` values. ([#2059](https://github.com/rack/rack/pull/2059), [@jeremyevans])

## [3.0.6.1] - 2023-03-13

- [CVE-2023-27539] Avoid ReDoS in header parsing

## [3.0.6] - 2023-03-13

- Add `QueryParser#missing_value` for handling missing values + tests. ([#2052](https://github.com/rack/rack/pull/2052), [@ioquatix])

## [3.0.5] - 2023-03-13

- Split form/query parsing into two steps. ([#2038](https://github.com/rack/rack/pull/2038), [@matthewd](https://github.com/matthewd))

## [3.0.4.1] - 2023-03-02

- [CVE-2023-27530] Introduce multipart_total_part_limit to limit total parts

## [3.0.4.1] - 2023-01-17

- [CVE-2022-44571] Fix ReDoS vulnerability in multipart parser
- [CVE-2022-44570] Fix ReDoS in Rack::Utils.get_byte_ranges
- [CVE-2022-44572] Forbid control characters in attributes (also ReDoS)

## [3.0.4] - 2023-01-17

- `Rack::Request#POST` should consistently raise errors. Cache errors that occur when invoking `Rack::Request#POST` so they can be raised again later. ([#2010](https://github.com/rack/rack/pull/2010), [@ioquatix])
- Fix `Rack::Lint` error message for `HTTP_CONTENT_TYPE` and `HTTP_CONTENT_LENGTH`. ([#2007](https://github.com/rack/rack/pull/2007), [@byroot](https://github.com/byroot))
- Extend `Rack::MethodOverride` to handle `QueryParser::ParamsTooDeepError` error. ([#2006](https://github.com/rack/rack/pull/2006), [@byroot](https://github.com/byroot))

## [3.0.3] - 2022-12-27

### Fixed

- `Rack::URLMap` uses non-deprecated form of `Regexp.new`. ([#1998](https://github.com/rack/rack/pull/1998), [@weizheheng](https://github.com/weizheheng))

## [3.0.2] - 2022-12-05

### Fixed

- `Utils.build_nested_query` URL-encodes nested field names including the square brackets.
- Allow `Rack::Response` to pass through streaming bodies. ([#1993](https://github.com/rack/rack/pull/1993), [@ioquatix])

## [3.0.1] - 2022-11-18

### Fixed

- `MethodOverride` does not look for an override if a request does not include form/parseable data.
- `Rack::Lint::Wrapper` correctly handles `respond_to?` with `to_ary`, `each`, `call` and `to_path`, forwarding to the body. ([#1981](https://github.com/rack/rack/pull/1981), [@ioquatix])

## [3.0.0] - 2022-09-06

- No changes

## [3.0.0.rc1] - 2022-09-04

### SPEC Changes

- Stream argument must implement `<<` https://github.com/rack/rack/pull/1959
- `close` may be called on `rack.input` https://github.com/rack/rack/pull/1956
- `rack.response_finished` may be used for executing code after the response has been finished https://github.com/rack/rack/pull/1952

## [3.0.0.beta1] - 2022-08-08

### Security

- Do not use semicolon as GET parameter separator. ([#1733](https://github.com/rack/rack/pull/1733), [@jeremyevans])

### SPEC Changes

- Response array must now be non-frozen.
- Response `status` must now be an integer greater than or equal to 100.
- Response `headers` must now be an unfrozen hash.
- Response header keys can no longer include uppercase characters.
- Response header values can be an `Array` to handle multiple values (and no longer supports `\n` encoded headers).
- Response body can now respond to `#call` (streaming body) instead of `#each` (enumerable body), for the equivalent of response hijacking in previous versions.
- Middleware must no longer call `#each` on the body, but they can call `#to_ary` on the body if it responds to `#to_ary`.
- `rack.input` is no longer required to be rewindable.
- `rack.multithread`/`rack.multiprocess`/`rack.run_once`/`rack.version` are no longer required environment keys.
- `SERVER_PROTOCOL` is now a required environment key, matching the HTTP protocol used in the request.
- `rack.hijack?` (partial hijack) and `rack.hijack` (full hijack) are now independently optional.
- `rack.hijack_io` has been removed completely.
- `rack.response_finished` is an optional environment key which contains an array of callable objects that must accept `#call(env, status, headers, error)` and are invoked after the response is finished (either successfully or unsuccessfully).
- It is okay to call `#close` on `rack.input` to indicate that you no longer need or care about the input.
- The stream argument supplied to the streaming body and hijack must support `#<<` for writing output.

### Removed

- Remove `rack.multithread`/`rack.multiprocess`/`rack.run_once`. These variables generally come too late to be useful. ([#1720](https://github.com/rack/rack/pull/1720), [@ioquatix], [@jeremyevans]))
- Remove deprecated Rack::Request::SCHEME_WHITELIST. ([@jeremyevans])
- Remove internal cookie deletion using pattern matching, there are very few practical cases where it would be useful and browsers handle it correctly without us doing anything special. ([#1844](https://github.com/rack/rack/pull/1844), [@ioquatix])
- Remove `rack.version` as it comes too late to be useful. ([#1938](https://github.com/rack/rack/pull/1938), [@ioquatix])
- Extract `rackup` command, `Rack::Server`, `Rack::Handler` and related code into a separate gem. ([#1937](https://github.com/rack/rack/pull/1937), [@ioquatix])

### Added

- `Rack::Headers` added to support lower-case header keys. ([@jeremyevans])
- `Rack::Utils#set_cookie_header` now supports `escape_key: false` to avoid key escaping.  ([@jeremyevans])
- `Rack::RewindableInput` supports size. ([@ahorek](https://github.com/ahorek))
- `Rack::RewindableInput::Middleware` added for making `rack.input` rewindable. ([@jeremyevans])
- The RFC 7239 Forwarded header is now supported and considered by default when looking for information on forwarding, falling back to the X-Forwarded-* headers. `Rack::Request.forwarded_priority` accessor has been added for configuring the priority of which header to check.  ([#1423](https://github.com/rack/rack/issues/1423), [@jeremyevans])
- Allow response headers to contain array of values. ([#1598](https://github.com/rack/rack/issues/1598), [@ioquatix])
- Support callable body for explicit streaming support and clarify streaming response body behaviour. ([#1745](https://github.com/rack/rack/pull/1745), [@ioquatix], [#1748](https://github.com/rack/rack/pull/1748), [@wjordan])
- Allow `Rack::Builder#run` to take a block instead of an argument. ([#1942](https://github.com/rack/rack/pull/1942), [@ioquatix])
- Add `rack.response_finished` to `Rack::Lint`. ([#1802](https://github.com/rack/rack/pull/1802), [@BlakeWilliams], [#1952](https://github.com/rack/rack/pull/1952), [@ioquatix])
- The stream argument must implement `#<<`. ([#1959](https://github.com/rack/rack/pull/1959), [@ioquatix])

### Changed

- BREAKING CHANGE: Require `status` to be an Integer. ([#1662](https://github.com/rack/rack/pull/1662), [@olleolleolle](https://github.com/olleolleolle))
- BREAKING CHANGE: Query parsing now treats parameters without `=` as having the empty string value instead of nil value, to conform to the URL spec. ([#1696](https://github.com/rack/rack/issues/1696), [@jeremyevans])
- Relax validations around `Rack::Request#host` and `Rack::Request#hostname`. ([#1606](https://github.com/rack/rack/issues/1606), [@pvande](https://github.com/pvande))
- Removed antiquated handlers: FCGI, LSWS, SCGI, Thin. ([#1658](https://github.com/rack/rack/pull/1658), [@ioquatix])
- Removed options from `Rack::Builder.parse_file` and `Rack::Builder.load_file`. ([#1663](https://github.com/rack/rack/pull/1663), [@ioquatix])
- `Rack::HTTP_VERSION` has been removed and the `HTTP_VERSION` env setting is no longer set in the CGI and Webrick handlers. ([#970](https://github.com/rack/rack/issues/970), [@jeremyevans])
- `Rack::Request#[]` and `#[]=` now warn even in non-verbose mode. ([#1277](https://github.com/rack/rack/issues/1277), [@jeremyevans])
- Decrease default allowed parameter recursion level from 100 to 32. ([#1640](https://github.com/rack/rack/issues/1640), [@jeremyevans])
- Attempting to parse a multipart response with an empty body now raises Rack::Multipart::EmptyContentError. ([#1603](https://github.com/rack/rack/issues/1603), [@jeremyevans])
- `Rack::Utils.secure_compare` uses OpenSSL's faster implementation if available. ([#1711](https://github.com/rack/rack/pull/1711), [@bdewater](https://github.com/bdewater))
- `Rack::Request#POST` now caches an empty hash if input content type is not parseable. ([#749](https://github.com/rack/rack/pull/749), [@jeremyevans])
- BREAKING CHANGE: Updated `trusted_proxy?` to match full 127.0.0.0/8 network. ([#1781](https://github.com/rack/rack/pull/1781), [@snbloch](https://github.com/snbloch))
- Explicitly deprecate `Rack::File` which was an alias for `Rack::Files`. ([#1811](https://github.com/rack/rack/pull/1720), [@ioquatix]).
- Moved `Rack::Session` into [separate gem](https://github.com/rack/rack-session). ([#1805](https://github.com/rack/rack/pull/1805), [@ioquatix])
- `rackup -D` option to daemonizes no longer changes the working directory to the root. ([#1813](https://github.com/rack/rack/pull/1813), [@jeremyevans])
- The `x-forwarded-proto` header is now considered before the `x-forwarded-scheme` header for determining the forwarded protocol. `Rack::Request.x_forwarded_proto_priority` accessor has been added for configuring the priority of which header to check.  ([#1809](https://github.com/rack/rack/issues/1809), [@jeremyevans])
- `Rack::Request.forwarded_authority` (and methods that call it, such as `host`) now returns the last authority in the forwarded header, instead of the first, as earlier forwarded authorities can be forged by clients. This restores the Rack 2.1 behavior. ([#1829](https://github.com/rack/rack/issues/1809), [@jeremyevans])
- Use lower case cookie attributes when creating cookies, and fold cookie attributes to lower case when reading cookies (specifically impacting `secure` and `httponly` attributes). ([#1849](https://github.com/rack/rack/pull/1849), [@ioquatix])
- The response array must now be mutable (non-frozen) so middleware can modify it without allocating a new Array,therefore reducing object allocations. ([#1887](https://github.com/rack/rack/pull/1887), [#1927](https://github.com/rack/rack/pull/1927), [@amatsuda], [@ioquatix])
- `rack.hijack?` (partial hijack) and `rack.hijack` (full hijack) are now independently optional. `rack.hijack_io` is no longer required/specified. ([#1939](https://github.com/rack/rack/pull/1939), [@ioquatix])
- Allow calling close on `rack.input`. ([#1956](https://github.com/rack/rack/pull/1956), [@ioquatix])

### Fixed

- Make Rack::MockResponse handle non-hash headers. ([#1629](https://github.com/rack/rack/issues/1629), [@jeremyevans])
- TempfileReaper now deletes temp files if application raises an exception. ([#1679](https://github.com/rack/rack/issues/1679), [@jeremyevans])
- Handle cookies with values that end in '=' ([#1645](https://github.com/rack/rack/pull/1645), [@lukaso](https://github.com/lukaso))
- Make `Rack::NullLogger` respond to `#fatal!` [@jeremyevans])
- Fix multipart filename generation for filenames that contain spaces. Encode spaces as "%20" instead of "+" which will be decoded properly by the multipart parser. ([#1736](https://github.com/rack/rack/pull/1645), [@muirdm](https://github.com/muirdm))
- `Rack::Request#scheme` returns `ws` or `wss` when one of the `X-Forwarded-Scheme` / `X-Forwarded-Proto` headers is set to `ws` or `wss`, respectively. ([#1730](https://github.com/rack/rack/issues/1730), [@erwanst](https://github.com/erwanst))

## [2.2.4] - 2022-06-30

- Better support for lower case headers in `Rack::ETag` middleware. ([#1919](https://github.com/rack/rack/pull/1919), [@ioquatix](https://github.com/ioquatix))
- Use custom exception on params too deep error. ([#1838](https://github.com/rack/rack/pull/1838), [@simi](https://github.com/simi))

## [2.2.3.1] - 2022-05-27

- [CVE-2022-30123] Fix shell escaping issue in Common Logger
- [CVE-2022-30122] Restrict parsing of broken MIME attachments

## [2.2.3] - 2020-06-15

### Security

- [[CVE-2020-8184](https://nvd.nist.gov/vuln/detail/CVE-2020-8184)] Do not allow percent-encoded cookie name to override existing cookie names. BREAKING CHANGE: Accessing cookie names that require URL encoding with decoded name no longer works. ([@fletchto99](https://github.com/fletchto99))

## [2.2.2] - 2020-02-11

### Fixed

- Fix incorrect `Rack::Request#host` value. ([#1591](https://github.com/rack/rack/pull/1591), [@ioquatix])
- Revert `Rack::Handler::Thin` implementation. ([#1583](https://github.com/rack/rack/pull/1583), [@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])

## [2.2.0] - 2020-02-08

### SPEC Changes

- `rack.session` request environment entry must respond to `to_hash` and return unfrozen Hash. ([@jeremyevans])
- Request environment cannot be frozen. ([@jeremyevans])
- CGI values in the request environment with non-ASCII characters must use ASCII-8BIT encoding. ([@jeremyevans])
- Improve SPEC/lint relating to SERVER_NAME, SERVER_PORT and HTTP_HOST. ([#1561](https://github.com/rack/rack/pull/1561), [@ioquatix])

### Added

- `rackup` supports multiple `-r` options and will require all arguments. ([@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])
- `Multipart::UploadedFile` supports keyword arguments `:path`, `:content_type`, and `:binary` in addition to positional arguments. ([@jeremyevans])
- `Static` supports a `:cascade` option for calling the app if there is no matching file. ([@jeremyevans])
- `Session::Abstract::SessionHash#dig`. ([@jeremyevans])
- `Response.[]` and `MockResponse.[]` for creating instances using status, headers, and body. ([@ioquatix])
- Convenient cache and content type methods for `Rack::Response`. ([#1555](https://github.com/rack/rack/pull/1555), [@ioquatix])

### Changed

- `Request#params` no longer rescues EOFError. ([@jeremyevans])
- `Directory` uses a streaming approach, significantly improving time to first byte for large directories. ([@jeremyevans])
- `Directory` no longer includes a Parent directory link in the root directory index. ([@jeremyevans])
- `QueryParser#parse_nested_query` uses original backtrace when reraising exception with new class. ([@jeremyevans])
- `ConditionalGet` follows RFC 7232 precedence if both If-None-Match and If-Modified-Since headers are provided. ([@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])
- BREAKING CHANGE: `Etag` will continue sending ETag even if the response should not be cached. Streaming no longer works without a workaround, see [#1619](https://github.com/rack/rack/issues/1619#issuecomment-848460528). ([@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])
- `Files` handling of range requests no longer return a body that supports `to_path`, to ensure range requests are handled correctly. ([@jeremyevans])
- `Multipart::Generator` only includes `Content-Length` for files with paths, and `Content-Disposition` `filename` if the `UploadedFile` instance has one. ([@jeremyevans])
- `Request#ssl?` is true for the `wss` scheme (secure websockets). ([@jeremyevans])
- `Rack::HeaderHash` is memoized by default. ([#1549](https://github.com/rack/rack/pull/1549), [@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], [@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])
- `Rack::Builder` parsing options on first `#\` line is deprecated. ([#1574](https://github.com/rack/rack/pull/1574), [@ioquatix])

### Removed

- `Directory#path` as it was not used and always returned nil. ([@jeremyevans])
- `BodyProxy#each` as it was only needed to work around a bug in Ruby <1.9.3. ([@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])
- Remove `Rack::Files#response_body` as the implementation was broken. ([#1153](https://github.com/rack/rack/pull/1153), [@ioquatix])
- Remove `SERVER_ADDR` which was never part of the original SPEC. ([#1573](https://github.com/rack/rack/pull/1573), [@ioquatix])

### Fixed

- `Directory` correctly handles root paths containing glob metacharacters. ([@jeremyevans])
- `Cascade` uses a new response object for each call if initialized with no apps. ([@jeremyevans])
- `BodyProxy` correctly delegates keyword arguments to the body object on Ruby 2.7+. ([@jeremyevans])
- `BodyProxy#method` correctly handles methods delegated to the body object. ([@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])
- `Response#write` correctly updates `Content-Length` if initialized with a body. ([@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])
- `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])
- `Request#delete_cookie` and related `Utils` methods do an exact match on `:domain` and `:path` options. ([@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])
- Thin handler supports options passed directly to `Thin::Controllers::Controller`. ([@jeremyevans])
- WEBrick handler no longer ignores `:BindAddress` option. ([@jeremyevans])
- `ShowExceptions` handles invalid POST data. ([@jeremyevans])
- Basic authentication requires a password, even if the password is empty. ([@jeremyevans])
- `Lint` checks response is array with 3 elements, per SPEC. ([@jeremyevans])
- Support for using `:SSLEnable` option when using WEBrick handler. (Gregor Melhorn)
- Close response body after buffering it when buffering. ([@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])

### Documentation

- CHANGELOG updates. ([@aupajo](https://github.com/aupajo))
- Added [CONTRIBUTING](CONTRIBUTING.md). ([@dblock](https://github.com/dblock))

## [2.0.9] - 2020-02-08

- Handle case where session id key is requested but missing ([@jeremyevans])
- Restore support for code relying on `SessionId#to_s`. ([@jeremyevans])
- Add support for `SameSite=None` cookie value. ([@hennikul](https://github.com/hennikul))

## [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])
- 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])

## [2.1.1] - 2020-01-12

- Remove `Rack::Chunked` from `Rack::Server` default middleware. ([#1475](https://github.com/rack/rack/pull/1475), [@ioquatix])
- Restore support for code relying on `SessionId#to_s`. ([@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])
- Add API to extract cookies from `Rack::MockResponse`. ([@petercline](https://github.com/petercline))

### Changed

- Don't propagate nil values from middleware. ([@ioquatix])
- Lazily initialize the response body and only buffer it if required. ([@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])
- 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])

### Removed

- BREAKING CHANGE: 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])

### 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])
- Prevent exceptions caused by a race condition on multi-threaded servers. ([@sophiedeziel](https://github.com/sophiedeziel))
- Add RDoc as an explicit dependency 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::<h>#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 greater 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 <josh@joshpeek.com>
  - 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

[@ioquatix]: https://github.com/ioquatix "Samuel Williams"
[@jeremyevans]: https://github.com/jeremyevans "Jeremy Evans"
[@amatsuda]: https://github.com/amatsuda "Akira Matsuda"
[@wjordan]: https://github.com/wjordan "Will Jordan"
[@BlakeWilliams]: https://github.com/BlakeWilliams "Blake Williams"
# frozen_string_literal: true

require_relative 'constants'

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
# frozen_string_literal: true

require 'tempfile'
require 'fileutils'

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
# frozen_string_literal: true

require 'strscan'

require_relative '../utils'

module Rack
  module Multipart
    class MultipartPartLimitError < Errno::EMFILE; end

    class MultipartTotalPartLimitError < StandardError; end

    # Use specific error class when parsing multipart request
    # that ends early.
    class EmptyContentError < ::EOFError; end

    # Base class for multipart exceptions that do not subclass from
    # other exception classes for backwards compatibility.
    class Error < StandardError; end

    EOL = "\r\n"
    MULTIPART = %r|\Amultipart/.*boundary=\"?([^\";,]+)\"?|ni
    TOKEN = /[^\s()<>,;:\\"\/\[\]?=]+/
    CONDISP = /Content-Disposition:\s*#{TOKEN}\s*/i
    VALUE = /"(?:\\"|[^"])*"|#{TOKEN}/
    BROKEN = /^#{CONDISP}.*;\s*filename=(#{VALUE})/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{[^ \x00-\x1f\x7f)(><@,;:\\"/\[\]?='*%]}
    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 Parser
      BUFSIZE = 1_048_576
      TEXT_PLAIN = "text/plain"
      TEMPFILE_FACTORY = lambda { |filename, content_type|
        Tempfile.new(["RackMultipart", ::File.extname(filename.gsub("\0", '%00'))])
      }

      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
      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

        if boundary.length > 70
          # RFC 1521 Section 7.2.1 imposes a 70 character maximum for the boundary.
          # Most clients use no more than 55 characters.
          raise Error, "multipart boundary size too large (#{boundary.length} characters)"
        end

        io = BoundedIO.new(io, content_length) if content_length

        parser = new(boundary, tmpfile, bufsize, qp)
        parser.parse(io)

        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_part_limits
        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_part_limits
          file_limit = Utils.multipart_file_limit
          part_limit = Utils.multipart_total_part_limit

          if file_limit && file_limit > 0
            if @open_files >= file_limit
              @mime_parts.each(&:close)
              raise MultipartPartLimitError, 'Maximum file multiparts in content reached'
            end
          end

          if part_limit && part_limit > 0
            if @mime_parts.size >= part_limit
              @mime_parts.each(&:close)
              raise MultipartTotalPartLimitError, 'Maximum total 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
        @bufsize        = bufsize

        @state = :FAST_FORWARD
        @mime_index = 0
        @collector = Collector.new tempfile

        @sbuf = StringScanner.new("".dup)
        @body_regex = /(?:#{EOL}|\A)--#{Regexp.quote(boundary)}(?:#{EOL}|--)/m
        @rx_max_size = boundary.bytesize + 6 # (\r\n-- at start, either \r\n or -- at finish)
        @head_regex = /(.*?#{EOL})#{EOL}/m
      end

      def parse(io)
        outbuf = String.new
        read_data(io, outbuf)

        loop do
          status =
            case @state
            when :FAST_FORWARD
              handle_fast_forward
            when :CONSUME_TOKEN
              handle_consume_token
            when :MIME_HEAD
              handle_mime_head
            when :MIME_BODY
              handle_mime_body
            else # when :DONE
              return
            end

          read_data(io, outbuf) if status == :want_read
        end
      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)
          end
        end
        MultipartInfo.new @params.to_params_hash, @collector.find_all(&:file?).map(&:body)
      end

      private

      def dequote(str) # From WEBrick::HTTPUtils
        ret = (/\A"(.*)"\Z/ =~ str) ? $1 : str.dup
        ret.gsub!(/\\(.)/, "\\1")
        ret
      end

      def read_data(io, outbuf)
        content = io.read(@bufsize, outbuf)
        handle_empty_content!(content)
        @sbuf.concat(content)
      end

      # This handles the initial parser state.  We read until we find the starting
      # boundary, then we can transition to the next state. If we find the ending
      # boundary, this is an invalid multipart upload, but keep scanning for opening
      # boundary in that case. If no boundary found, we need to keep reading data
      # and retry. It's highly unlikely the initial read will not consume the
      # boundary.  The client would have to deliberately craft a response
      # with the opening boundary beyond the buffer size for that to happen.
      def handle_fast_forward
        while true
          case consume_boundary
          when :BOUNDARY
            # found opening boundary, transition to next state
            @state = :MIME_HEAD
            return
          when :END_BOUNDARY
            # invalid multipart upload, but retry for opening boundary
          else
            # no boundary found, keep reading data
            return :want_read
          end
        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 = 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

      # Scan until the we find the start or end of the boundary.
      # If we find it, return the appropriate symbol for the start or
      # end of the boundary.  If we don't find the start or end of the
      # boundary, clear the buffer and return nil.
      def consume_boundary
        if read_buffer = @sbuf.scan_until(@body_regex)
          read_buffer.end_with?(EOL) ? :BOUNDARY : :END_BOUNDARY
        else
          @sbuf.terminate
          nil
        end
      end

      def get_filename(head)
        filename = nil
        case head
        when RFC2183
          params = Hash[*head.scan(DISPPARM).flat_map(&:compact)]

          if filename = params['filename*']
            encoding, _, filename = filename.split("'", 3)
          elsif filename = params['filename']
            filename = $1 if filename =~ /^"(.*)"$/
          end
        when BROKEN
          filename = $1
          filename = $1 if filename =~ /^"(.*)"$/
        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"
      deprecate_constant :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?('"')
              if k == "charset"
                encoding = begin
                  Encoding.find v
                rescue ArgumentError
                  Encoding::BINARY
                end
              end
            end
          end
        end

        name.force_encoding(encoding)
        body.force_encoding(encoding)
      end

      def handle_empty_content!(content)
        if content.nil? || content.empty?
          raise EmptyContentError
        end
      end
    end
  end
end
# frozen_string_literal: true

require_relative 'uploaded_file'

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_path(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
module Rack
  # Rack::Headers is a Hash subclass that downcases all keys.  It's designed
  # to be used by rack applications that don't implement the Rack 3 SPEC
  # (by using non-lowercase response header keys), automatically handling
  # the downcasing of keys.
  class Headers < Hash
    def self.[](*items)
      if items.length % 2 != 0
        if items.length == 1 && items.first.is_a?(Hash)
          new.merge!(items.first)
        else
          raise ArgumentError, "odd number of arguments for Rack::Headers"
        end
      else
        hash = new
        loop do
          break if items.length == 0
          key = items.shift
          value = items.shift
          hash[key] = value
        end
        hash
      end
    end

    def [](key)
      super(downcase_key(key))
    end

    def []=(key, value)
      super(key.downcase.freeze, value)
    end
    alias store []=

    def assoc(key)
      super(downcase_key(key))
    end

    def compare_by_identity
      raise TypeError, "Rack::Headers cannot compare by identity, use regular Hash"
    end

    def delete(key)
      super(downcase_key(key))
    end

    def dig(key, *a)
      super(downcase_key(key), *a)
    end

    def fetch(key, *default, &block)
      key = downcase_key(key)
      super
    end

    def fetch_values(*a)
      super(*a.map!{|key| downcase_key(key)})
    end

    def has_key?(key)
      super(downcase_key(key))
    end
    alias include? has_key?
    alias key? has_key?
    alias member? has_key?

    def invert
      hash = self.class.new
      each{|key, value| hash[value] = key}
      hash
    end

    def merge(hash, &block)
      dup.merge!(hash, &block)
    end

    def reject(&block)
      hash = dup
      hash.reject!(&block)
      hash
    end

    def replace(hash)
      clear
      update(hash)
    end

    def select(&block)
      hash = dup
      hash.select!(&block)
      hash
    end

    def to_proc
      lambda{|x| self[x]}
    end

    def transform_values(&block)
      dup.transform_values!(&block)
    end

    def update(hash, &block)
      hash.each do |key, value|
        self[key] = if block_given? && include?(key)
          block.call(key, self[key], value)
        else
          value
        end
      end
      self
    end
    alias merge! update

    def values_at(*keys)
      keys.map{|key| self[key]}
    end

    # :nocov:
    if RUBY_VERSION >= '2.5'
    # :nocov:
      def slice(*a)
        h = self.class.new
        a.each{|k| h[k] = self[k] if has_key?(k)}
        h
      end

      def transform_keys(&block)
        dup.transform_keys!(&block)
      end

      def transform_keys!
        hash = self.class.new
        each do |k, v|
          hash[yield k] = v
        end
        replace(hash)
      end
    end

    # :nocov:
    if RUBY_VERSION >= '3.0'
    # :nocov:
      def except(*a)
        super(*a.map!{|key| downcase_key(key)})
      end
    end

    private

    def downcase_key(key)
      key.is_a?(String) ? key.downcase : key
    end
  end
end
# frozen_string_literal: true

require 'ostruct'
require 'erb'

require_relative 'constants'
require_relative 'utils'
require_relative 'request'

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)
      if exception.respond_to?(:detailed_message)
        message = exception.detailed_message(highlight: false)
      else
        message = exception.message
      end
      string = "#{exception.class}: #{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 <www.djangoproject.com>
    # 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(/^      /, ''))
      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
      <html lang="en">
      <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <meta name="robots" content="NONE,NOARCHIVE" />
        <title><%=h exception.class %> at <%=h path %></title>
        <style type="text/css">
          html * { padding:0; margin:0; }
          body * { padding:10px 20px; }
          body * * { padding:0; }
          body { font:small sans-serif; }
          body>div { border-bottom:1px solid #ddd; }
          h1 { font-weight:normal; }
          h2 { margin-bottom:.8em; }
          h2 span { font-size:80%; color:#666; font-weight:normal; }
          h3 { margin:1em 0 .5em 0; }
          h4 { margin:0 0 .5em 0; font-weight: normal; }
          table {
              border:1px solid #ccc; border-collapse: collapse; background:white; }
          tbody td, tbody th { vertical-align:top; padding:2px 3px; }
          thead th {
              padding:1px 6px 1px 3px; background:#fefefe; text-align:left;
              font-weight:normal; font-size:11px; border:1px solid #ddd; }
          tbody th { text-align:right; color:#666; padding-right:.5em; }
          table.vars { margin:5px 0 2px 40px; }
          table.vars td, table.req td { font-family:monospace; }
          table td.code { width:100%;}
          table td.code div { overflow:hidden; }
          table.source th { color:#666; }
          table.source td {
              font-family:monospace; white-space:pre; border-bottom:1px solid #eee; }
          ul.traceback { list-style-type:none; }
          ul.traceback li.frame { margin-bottom:1em; }
          div.context { margin: 10px 0; }
          div.context ol {
              padding-left:30px; margin:0 10px; list-style-position: inside; }
          div.context ol li {
              font-family:monospace; white-space:pre; color:#666; cursor:pointer; }
          div.context ol.context-line li { color:black; background-color:#ccc; }
          div.context ol.context-line li span { float: right; }
          div.commands { margin-left: 40px; }
          div.commands a { color:black; text-decoration:none; }
          #summary { background: #ffc; }
          #summary h2 { font-family: monospace; font-weight: normal; color: #666; white-space: pre-wrap; }
          #summary ul#quicklinks { list-style-type: none; margin-bottom: 2em; }
          #summary ul#quicklinks li { float: left; padding: 0 1em; }
          #summary ul#quicklinks>li+li { border-left: 1px #666 solid; }
          #explanation { background:#eee; }
          #template, #template-not-exist { background:#f6f6f6; }
          #template-not-exist ul { margin: 0 0 0 20px; }
          #traceback { background:#eee; }
          #requestinfo { background:#f6f6f6; padding-left:120px; }
          #summary table { border:none; background:transparent; }
          #requestinfo h2, #requestinfo h3 { position:relative; margin-left:-100px; }
          #requestinfo h3 { margin-bottom:-1em; }
          .error { background: #ffc; }
          .specific { color:#cc3300; font-weight:bold; }
        </style>
        <script type="text/javascript">
        //<!--
          function getElementsByClassName(oElm, strTagName, strClassName){
              // Written by Jonathan Snook, http://www.snook.ca/jon;
              // Add-ons by Robert Nyman, http://www.robertnyman.com
              var arrElements = (strTagName == "*" && document.all)? document.all :
              oElm.getElementsByTagName(strTagName);
              var arrReturnElements = new Array();
              strClassName = strClassName.replace(/\-/g, "\\-");
              var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$$)");
              var oElement;
              for(var i=0; i<arrElements.length; i++){
                  oElement = arrElements[i];
                  if(oRegExp.test(oElement.className)){
                      arrReturnElements.push(oElement);
                  }
              }
              return (arrReturnElements)
          }
          function hideAll(elems) {
            for (var e = 0; e < elems.length; e++) {
              elems[e].style.display = 'none';
            }
          }
          window.onload = function() {
            hideAll(getElementsByClassName(document, 'table', 'vars'));
            hideAll(getElementsByClassName(document, 'ol', 'pre-context'));
            hideAll(getElementsByClassName(document, 'ol', 'post-context'));
          }
          function toggle() {
            for (var i = 0; i < arguments.length; i++) {
              var e = document.getElementById(arguments[i]);
              if (e) {
                e.style.display = e.style.display == 'none' ? 'block' : 'none';
              }
            }
            return false;
          }
          function varToggle(link, id) {
            toggle('v' + id);
            var s = link.getElementsByTagName('span')[0];
            var uarr = String.fromCharCode(0x25b6);
            var darr = String.fromCharCode(0x25bc);
            s.innerHTML = s.innerHTML == uarr ? darr : uarr;
            return false;
          }
          //-->
        </script>
      </head>
      <body>

      <div id="summary">
        <h1><%=h exception.class %> at <%=h path %></h1>
      <% if exception.respond_to?(:detailed_message) %>
        <h2><%=h exception.detailed_message(highlight: false) %></h2>
      <% else %>
        <h2><%=h exception.message %></h2>
      <% end %>
        <table><tr>
          <th>Ruby</th>
          <td>
      <% if first = frames.first %>
            <code><%=h first.filename %></code>: in <code><%=h first.function %></code>, line <%=h frames.first.lineno %>
      <% else %>
            unknown location
      <% end %>
          </td>
        </tr><tr>
          <th>Web</th>
          <td><code><%=h req.request_method %> <%=h(req.host + path)%></code></td>
        </tr></table>

        <h3>Jump to:</h3>
        <ul id="quicklinks">
          <li><a href="#get-info">GET</a></li>
          <li><a href="#post-info">POST</a></li>
          <li><a href="#cookie-info">Cookies</a></li>
          <li><a href="#env-info">ENV</a></li>
        </ul>
      </div>

      <div id="traceback">
        <h2>Traceback <span>(innermost first)</span></h2>
        <ul class="traceback">
      <% frames.each { |frame| %>
            <li class="frame">
              <code><%=h frame.filename %></code>: in <code><%=h frame.function %></code>

                <% if frame.context_line %>
                <div class="context" id="c<%=h frame.object_id %>">
                    <% if frame.pre_context %>
                    <ol start="<%=h frame.pre_context_lineno+1 %>" class="pre-context" id="pre<%=h frame.object_id %>">
                      <% frame.pre_context.each { |line| %>
                      <li onclick="toggle('pre<%=h frame.object_id %>', 'post<%=h frame.object_id %>')"><%=h line %></li>
                      <% } %>
                    </ol>
                    <% end %>

                  <ol start="<%=h frame.lineno %>" class="context-line">
                    <li onclick="toggle('pre<%=h frame.object_id %>', 'post<%=h frame.object_id %>')"><%=h frame.context_line %><span>...</span></li></ol>

                    <% if frame.post_context %>
                    <ol start='<%=h frame.lineno+1 %>' class="post-context" id="post<%=h frame.object_id %>">
                      <% frame.post_context.each { |line| %>
                      <li onclick="toggle('pre<%=h frame.object_id %>', 'post<%=h frame.object_id %>')"><%=h line %></li>
                      <% } %>
                    </ol>
                    <% end %>
                </div>
                <% end %>
            </li>
      <% } %>
        </ul>
      </div>

      <div id="requestinfo">
        <h2>Request information</h2>

        <h3 id="get-info">GET</h3>
        <% if req.GET and not req.GET.empty? %>
          <table class="req">
            <thead>
              <tr>
                <th>Variable</th>
                <th>Value</th>
              </tr>
            </thead>
            <tbody>
                <% req.GET.sort_by { |k, v| k.to_s }.each { |key, val| %>
                <tr>
                  <td><%=h key %></td>
                  <td class="code"><div><%=h val.inspect %></div></td>
                </tr>
                <% } %>
            </tbody>
          </table>
        <% else %>
          <p>No GET data.</p>
        <% end %>

        <h3 id="post-info">POST</h3>
        <% if ((req.POST and not req.POST.empty?) rescue (no_post_data = "Invalid POST data"; nil)) %>
          <table class="req">
            <thead>
              <tr>
                <th>Variable</th>
                <th>Value</th>
              </tr>
            </thead>
            <tbody>
                <% req.POST.sort_by { |k, v| k.to_s }.each { |key, val| %>
                <tr>
                  <td><%=h key %></td>
                  <td class="code"><div><%=h val.inspect %></div></td>
                </tr>
                <% } %>
            </tbody>
          </table>
        <% else %>
          <p><%= no_post_data || "No POST data" %>.</p>
        <% end %>


        <h3 id="cookie-info">COOKIES</h3>
        <% unless req.cookies.empty? %>
          <table class="req">
            <thead>
              <tr>
                <th>Variable</th>
                <th>Value</th>
              </tr>
            </thead>
            <tbody>
              <% req.cookies.each { |key, val| %>
                <tr>
                  <td><%=h key %></td>
                  <td class="code"><div><%=h val.inspect %></div></td>
                </tr>
              <% } %>
            </tbody>
          </table>
        <% else %>
          <p>No cookie data.</p>
        <% end %>

        <h3 id="env-info">Rack ENV</h3>
          <table class="req">
            <thead>
              <tr>
                <th>Variable</th>
                <th>Value</th>
              </tr>
            </thead>
            <tbody>
                <% env.sort_by { |k, v| k.to_s }.each { |key, val| %>
                <tr>
                  <td><%=h key %></td>
                  <td class="code"><div><%=h val.inspect %></div></td>
                </tr>
                <% } %>
            </tbody>
          </table>

      </div>

      <div id="explanation">
        <p>
          You're seeing this error because you use <code>Rack::ShowExceptions</code>.
        </p>
      </div>

      </body>
      </html>
    HTML

    # :startdoc:
  end
end
# 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
# frozen_string_literal: true

require 'time'

require_relative 'constants'
require_relative 'utils'
require_relative 'media_type'
require_relative 'headers'

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.
    def header
      warn 'Rack::Response#header is deprecated and will be removed in Rack 3.1', uplevel: 1

      headers
    end

    # Initialize the response object with the specified +body+, +status+
    # and +headers+.
    #
    # If the +body+ is +nil+, construct an empty response object with internal
    # buffering.
    #
    # If the +body+ responds to +to_str+, assume it's a string-like object and
    # construct a buffered response object containing using that string as the
    # initial contents of the buffer.
    #
    # Otherwise it is expected +body+ conforms to the normal requirements of a
    # Rack response body, typically implementing one of +each+ (enumerable
    # body) or +call+ (streaming body).
    #
    # The +status+ defaults to +200+ which is the "OK" HTTP status code. You
    # can provide any other valid status code.
    #
    # The +headers+ must be a +Hash+ of key-value header pairs which conform to
    # the Rack specification for response headers. The key must be a +String+
    # instance and the value can be either a +String+ or +Array+ instance.
    def initialize(body = nil, status = 200, headers = {})
      @status = status.to_i

      unless headers.is_a?(Hash)
        warn "Providing non-hash headers to Rack::Response is deprecated and will be removed in Rack 3.1", uplevel: 1
      end

      @headers = Headers.new
      # Convert headers input to a plain hash with lowercase keys.
      headers.each do |k, v|
        @headers[k] = v
      end

      @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 = nil # undetermined as of yet.
        @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

    def no_entity_body?
      # The response body is an enumerable body and it is not allowed to have an entity body.
      @body.respond_to?(:each) && STATUS_WITH_NO_ENTITY_BODY[@status]
    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 no_entity_body?
        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)
      raise ArgumentError unless key.is_a?(String)
      @headers.key?(key)
    end
    def get_header(key)
      raise ArgumentError unless key.is_a?(String)
      @headers[key]
    end
    def set_header(key, value)
      raise ArgumentError unless key.is_a?(String)
      @headers[key] = value
    end
    def delete_header(key)
      raise ArgumentError unless key.is_a?(String)
      @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 not_acceptable?;      status == 406;                        end
      def request_timeout?;     status == 408;                        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, value)
        raise ArgumentError unless key.is_a?(String)

        if value.nil?
          return get_header(key)
        end

        value = value.to_s

        if header = get_header(key)
          if header.is_a?(Array)
            header << value
          else
            set_header(key, [header, value])
          end
        else
          set_header(key, value)
        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)
        add_header SET_COOKIE, Utils.set_cookie_header(key, value)
      end

      def delete_cookie(key, value = {})
        set_header(SET_COOKIE,
          Utils.delete_set_cookie_header!(
            get_header(SET_COOKIE), key, value
          )
        )
      end

      def set_cookie_header
        get_header SET_COOKIE
      end

      def set_cookie_header=(value)
        set_header SET_COOKIE, value
      end

      def cache_control
        get_header CACHE_CONTROL
      end

      def cache_control=(value)
        set_header CACHE_CONTROL, value
      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=(value)
        set_header ETAG, value
      end

    protected

      def buffered_body!
        if @buffered.nil?
          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
          elsif @body.respond_to?(:each)
            # 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)

            @buffered = true
          else
            @buffered = false
          end
        end

        return @buffered
      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, value)
        headers[key] = value
      end

      def delete_header(key)
        headers.delete(key)
      end
    end
  end
end
# frozen_string_literal: true

require_relative 'utils'

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.to_s.downcase}" if name
    end

    def call(env)
      start_time = Utils.clock_time
      _, headers, _ = response = @app.call(env)

      request_time = Utils.clock_time - start_time

      unless headers.key?(@header_name)
        headers[@header_name] = FORMAT_STRING % request_time
      end

      response
    end
  end
end
# frozen_string_literal: true

require_relative 'mock_request'
# -*- encoding: binary -*-
# frozen_string_literal: true

require 'tempfile'

require_relative 'constants'

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.
  #
  # 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
    # Makes rack.input rewindable, for compatibility with applications and middleware
    # designed for earlier versions of Rack (where rack.input was required to be
    # rewindable).
    class Middleware
      def initialize(app)
        @app = app
      end

      def call(env)
        env[RACK_INPUT] = RewindableInput.new(env[RACK_INPUT])
        @app.call(env)
      end
    end

    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

    def size
      make_rewindable unless @rewindable_io
      @rewindable_io.size
    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)
      @rewindable_io.binmode
      # :nocov:
      if filesystem_has_posix_semantics?
        raise 'Unlink failed. IO closed.' if @rewindable_io.closed?
        @unlinked = true
      end
      # :nocov:

      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
# 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
    # :nocov:
    ruby2_keywords(:method_missing) if respond_to?(:ruby2_keywords, true)
    # :nocov:
  end
end
# frozen_string_literal: true

require "zlib"
require "time"  # for Time.httpdate

require_relative 'constants'
require_relative 'utils'
require_relative 'request'
require_relative 'body_proxy'

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
    # Creates Rack::Deflater middleware. Options:
    #
    # :if :: a lambda enabling / disabling deflation based on returned boolean value
    #        (e.g <tt>use Rack::Deflater, :if => lambda { |*, body| sum=0; body.each { |i| sum += i.length }; sum > 512 }</tt>).
    #        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 = response = @app.call(env)

      unless should_deflate?(env, status, headers, body)
        return response
      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.any?{|v| v.downcase == '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
        response[2] = GzipStream.new(body, mtime, @sync)
        response
      when "identity"
        response
      else # when nil
        # Only possible encoding values here are 'gzip', 'identity', and 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

      BUFFER_LENGTH = 128 * 1_024

      # 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 is equivalent to @body.gets (slow)
        if @body.is_a? ::File # XXX: Should probably be ::IO
          while part = @body.read(BUFFER_LENGTH)
            gzip.write(part)
            gzip.flush if @sync
          end
        else
          @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
          }
        end
      ensure
        gzip.finish
      end

      # Call the block passed to #each with 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
require_relative '../digest'
require_relative '../digest'
require_relative '../digest'
require_relative '../digest'
# 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.

    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
# frozen_string_literal: true

require_relative '../../constants'

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
# frozen_string_literal: true

require_relative '../../request'

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&.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
# frozen_string_literal: true

require_relative 'abstract/handler'
require_relative 'abstract/request'
require 'digest/md5'
require 'base64'

module Rack
  warn "Rack::Auth::Digest is deprecated and will be removed in Rack 3.1", uplevel: 1

  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

      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

      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

      # 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

# frozen_string_literal: true

require_relative 'body_proxy'

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
      begin
        response = @app.call(env)
        returned = response << BodyProxy.new(response.pop) { unlock }
      ensure
        unlock unless returned
      end
    end

    private

    def unlock
      @mutex.unlock
    end
  end
end
# frozen_string_literal: true

require_relative 'constants'
require_relative 'utils'

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 = response = @app.call(env)

      if !STATUS_WITH_NO_ENTITY_BODY.key?(status.to_i) &&
         !headers[CONTENT_LENGTH] &&
         !headers[TRANSFER_ENCODING] &&
         body.respond_to?(:to_ary)

        response[2] = body = body.to_ary
        headers[CONTENT_LENGTH] = body.sum(&:bytesize).to_s
      end

      response
    end
  end
end
# frozen_string_literal: true

require 'time'

require_relative 'constants'
require_relative 'head'
require_relative 'utils'
require_relative 'request'
require_relative 'mime'

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'

    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
      else
        # 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
# frozen_string_literal: true

require_relative 'files'

module Rack
  warn "Rack::File is deprecated and will be removed in Rack 3.1", uplevel: 1

  File = Files
end
# frozen_string_literal: true

require_relative 'constants'
require_relative 'body_proxy'

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)
      _, _, body = response = @app.call(env)

      if env[REQUEST_METHOD] == HEAD
        response[2] = Rack::BodyProxy.new([]) do
          body.close if body.respond_to? :close
        end
      end

      response
    end
  end
end
# frozen_string_literal: true

require_relative 'body_proxy'
require_relative 'request'
require_relative 'response'

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
# frozen_string_literal: true

require_relative 'constants'
require_relative 'body_proxy'

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] ||= []

      begin
        _, _, body = response = @app.call(env)
      rescue Exception
        env[RACK_TEMPFILES]&.each(&:close!)
        raise
      end

      response[2] = BodyProxy.new(body) do
        env[RACK_TEMPFILES]&.each(&:close!)
      end

      response
    end
  end
end
# frozen_string_literal: true

require 'cgi/cookie'
require 'time'

require_relative 'response'

module Rack
  # 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 = nil)
      @original_headers = headers

      if errors
        @errors = errors.string if errors.respond_to?(:string)
      else
        @errors = ""
      end

      super(body, status, headers)

      @cookies = parse_cookies_from_header
      buffered_body!
    end

    def =~(other)
      body =~ other
    end

    def match(other)
      body.match other
    end

    def body
      return @buffered_body if defined?(@buffered_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 = @buffered_body = String.new

      @body.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 headers.has_key? 'set-cookie'
        set_cookie_header = headers.fetch('set-cookie')
        Array(set_cookie_header).each do |header_value|
          header_value.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
      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.drop(1).each do |bit|
        if bit.include? '='
          cookie_attribute, attribute_value = bit.split('=', 2)
          cookie_attributes.store(cookie_attribute.strip.downcase, attribute_value.strip)
        end
        if bit.include? 'secure'
          cookie_attributes.store('secure', true)
        end
      end

      if cookie_attributes.key? 'max-age'
        cookie_attributes.store('expires', Time.now + cookie_attributes['max-age'].to_i)
      elsif cookie_attributes.key? 'expires'
        cookie_attributes.store('expires', Time.httpdate(cookie_attributes['expires']))
      end

      cookie_attributes
    end

  end
end
# frozen_string_literal: true

require_relative 'urlmap'

module Rack
  # Rack::Builder provides a domain-specific language (DSL) to construct Rack
  # applications. It is primarily used to parse +config.ru+ files which
  # instantiate several middleware and a final application which are hosted
  # by a Rack-compatible web server.
  #
  # Example:
  #
  #   app = Rack::Builder.new do
  #     use Rack::CommonLogger
  #     map "/ok" do
  #       run lambda { |env| [200, {'content-type' => 'text/plain'}, ['OK']] }
  #     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.
    #
    # 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.
    #
    # 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(path)
      if path.end_with?('.ru')
        return self.load_file(path)
      else
        require path
        return Object.const_get(::File.basename(path, '.rb').split('_').map(&:capitalize).join(''))
      end
    end

    # Load the given file as a rackup file, treating the
    # contents as if specified inside a Rack::Builder block.
    #
    # 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
    #
    #   use Rack::ContentLength
    #   require './app.rb'
    #   run App
    def self.load_file(path)
      config = ::File.read(path)
      config.slice!(/\A#{UTF_8_BOM}/) if config.encoding == Encoding::UTF_8

      if config[/^#\\(.*)/]
        fail "Parsing options from the first comment line is no longer supported: #{path}"
      end

      config.sub!(/^__END__\n.*\Z/m, '')

      return new_from_string(config, path)
    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

      return 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 evaluated in the context of the instance.
    def initialize(default_app = nil, &block)
      @use = []
      @map = nil
      @run = default_app
      @warmup = nil
      @freeze_app = 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
    # :nocov:
    ruby2_keywords(:use) if respond_to?(:ruby2_keywords, true)
    # :nocov:

    # Takes a block or argument that is an object that responds to #call and
    # returns a Rack response.
    #
    # You can use a block:
    #
    #   run do |env|
    #     [200, { "content-type" => "text/plain" }, ["Hello World!"]]
    #   end
    #
    # You can also provide a lambda:
    #
    #   run lambda { |env| [200, { "content-type" => "text/plain" }, ["OK"]] }
    #
    # You can also provide a class instance:
    #
    #   class Heartbeat
    #     def call(env)
    #      [200, { "content-type" => "text/plain" }, ["OK"]]
    #     end
    #   end
    #
    #   run Heartbeat.new
    #
    def run(app = nil, &block)
      raise ArgumentError, "Both app and block given!" if app && block_given?

      @run = app || block
    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.
    #
    #   class App
    #     def call(env)
    #       [200, {'content-type' => 'text/plain'}, ["Hello World"]]
    #     end
    #   end
    #
    #   class Heartbeat
    #     def call(env)
    #       [200, { "content-type" => "text/plain" }, ["OK"]]
    #     end
    #   end
    #
    #   app = Rack::Builder.app do
    #     map '/heartbeat' do
    #       run Heartbeat.new
    #     end
    #     run App.new
    #   end
    #
    #   run app
    #
    # The +use+ method can also be used inside the block to specify middleware to run under a specific path:
    #
    #   app = Rack::Builder.app do
    #     map '/heartbeat' do
    #       use Middleware
    #       run Heartbeat.new
    #     end
    #     run App.new
    #   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
# frozen_string_literal: true

require 'set'

require_relative 'constants'

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 <tt>http://</tt> or <tt>https://</tt>.
  #
  # 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('/', '/+')}(.*)", Regexp::NOENCODING)

        [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
# -*- encoding: binary -*-
# frozen_string_literal: true

require 'uri'
require 'fileutils'
require 'set'
require 'tempfile'
require 'time'

require_relative 'query_parser'
require_relative 'mime'
require_relative 'headers'
require_relative 'constants'

module Rack
  # Rack::Utils contains a grab-bag of useful methods for writing web
  # applications adopted from all kinds of Ruby libraries.

  module Utils
    ParameterTypeError = QueryParser::ParameterTypeError
    InvalidParameterError = QueryParser::InvalidParameterError
    ParamsTooDeepError = QueryParser::ParamsTooDeepError
    DEFAULT_SEP = QueryParser::DEFAULT_SEP
    COMMON_SEP = QueryParser::COMMON_SEP
    KeySpaceConstrainedParams = QueryParser::Params

    class << self
      attr_accessor :default_query_parser
    end
    # The default amount of nesting to allowed by hash parameters.
    # This helps prevent a rogue client from triggering a possible stack overflow
    # when parsing parameters.
    self.default_query_parser = QueryParser.make_default(32)

    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_total_part_limit

      attr_accessor :multipart_file_limit

      # multipart_part_limit is the original name of multipart_file_limit, but
      # the limit only counts parts with filenames.
      alias multipart_part_limit multipart_file_limit
      alias multipart_part_limit= multipart_file_limit=
    end

    # The maximum number of file parts a request can contain. Accepting too
    # many parts can lead to the server running out of file handles.
    # Set to `0` for no limit.
    self.multipart_file_limit = (ENV['RACK_MULTIPART_PART_LIMIT'] || ENV['RACK_MULTIPART_FILE_LIMIT'] || 128).to_i

    # The maximum total number of parts a request can contain. Accepting too
    # many can lead to excessive memory use and parsing time.
    self.multipart_total_part_limit = (ENV['RACK_MULTIPART_TOTAL_PART_LIMIT'] || 4096).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
      warn("`Rack::Utils.key_space_limit` is deprecated as this value no longer has an effect. It will be removed in Rack 3.1", uplevel: 1)
      65536
    end

    def self.key_space_limit=(v)
      warn("`Rack::Utils.key_space_limit=` is deprecated and no longer has an effect. It will be removed in Rack 3.1", uplevel: 1)
    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}[#{k}]" : k)
        }.delete_if(&:empty?).join('&')
      when nil
        escape(prefix)
      else
        raise ArgumentError, "value must be a Hash" if prefix.nil?
        "#{escape(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

    def forwarded_values(forwarded_header)
      return nil unless forwarded_header
      forwarded_header = forwarded_header.to_s.gsub("\n", ";")

      forwarded_header.split(/\s*;\s*/).each_with_object({}) do |field, values|
        field.split(/\s*,\s*/).each do |pair|
          return nil unless pair =~ /\A\s*(by|for|host|proto)\s*=\s*"?([^"]+)"?\s*\Z/i
          (values[$1.downcase.to_sym] ||= []) << $2
        end
      end
    end
    module_function :forwarded_values

    # 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&.first
    end

    ESCAPE_HTML = {
      "&" => "&amp;",
      "<" => "&lt;",
      ">" => "&gt;",
      "'" => "&#x27;",
      '"' => "&quot;",
      "/" => "&#x2F;"
    }

    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

    # :call-seq:
    #   parse_cookies_header(value) -> hash
    #
    # Parse cookies from the provided header +value+ according to RFC6265. The
    # syntax for cookie headers only supports semicolons. Returns a map of
    # cookie +key+ to cookie +value+.
    #
    #   parse_cookies_header('myname=myvalue; max-age=0')
    #   # => {"myname"=>"myvalue", "max-age"=>"0"}
    #
    def parse_cookies_header(value)
      return {} unless value

      value.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)
      warn("add_cookie_to_header is deprecated and will be removed in Rack 3.1", uplevel: 1)

      case header
      when nil, ''
        return set_cookie_header(key, value)
      when String
        [header, set_cookie_header(key, value)]
      when Array
        header + [set_cookie_header(key, value)]
      else
        raise ArgumentError, "Unrecognized cookie header value. Expected String, Array, or nil, got #{header.inspect}"
      end
    end

    # :call-seq:
    #   parse_cookies(env) -> hash
    #
    # Parse cookies from the provided request environment using
    # parse_cookies_header. Returns a map of cookie +key+ to cookie +value+.
    #
    #   parse_cookies({'HTTP_COOKIE' => 'myname=myvalue'})
    #   # => {'myname' => 'myvalue'}
    #
    def parse_cookies(env)
      parse_cookies_header env[HTTP_COOKIE]
    end

    # :call-seq:
    #   set_cookie_header(key, value) -> encoded string
    #
    # Generate an encoded string using the provided +key+ and +value+ suitable
    # for the +set-cookie+ header according to RFC6265. The +value+ may be an
    # instance of either +String+ or +Hash+.
    #
    # If the cookie +value+ is an instance of +Hash+, it considers the following
    # cookie attribute keys: +domain+, +max_age+, +expires+ (must be instance
    # of +Time+), +secure+, +http_only+, +same_site+ and +value+. For more
    # details about the interpretation of these fields, consult
    # [RFC6265 Section 5.2](https://datatracker.ietf.org/doc/html/rfc6265#section-5.2).
    #
    # An extra cookie attribute +escape_key+ can be provided to control whether
    # or not the cookie key is URL encoded. If explicitly set to +false+, the
    # cookie key name will not be url encoded (escaped). The default is +true+.
    #
    #   set_cookie_header("myname", "myvalue")
    #   # => "myname=myvalue"
    #
    #   set_cookie_header("myname", {value: "myvalue", max_age: 10})
    #   # => "myname=myvalue; max-age=10"
    #
    def set_cookie_header(key, value)
      case value
      when Hash
        key = escape(key) unless value[:escape_key] == false
        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]
      else
        key = escape(key)
      end

      value = [value] unless Array === value

      return "#{key}=#{value.map { |v| escape v }.join('&')}#{domain}" \
        "#{path}#{max_age}#{expires}#{secure}#{httponly}#{same_site}"
    end

    # :call-seq:
    #   set_cookie_header!(headers, key, value) -> header value
    #
    # Append a cookie in the specified headers with the given cookie +key+ and
    # +value+ using set_cookie_header.
    #
    # If the headers already contains a +set-cookie+ key, it will be converted
    # to an +Array+ if not already, and appended to.
    def set_cookie_header!(headers, key, value)
      if header = headers[SET_COOKIE]
        if header.is_a?(Array)
          header << set_cookie_header(key, value)
        else
          headers[SET_COOKIE] = [header, set_cookie_header(key, value)]
        end
      else
        headers[SET_COOKIE] = set_cookie_header(key, value)
      end
    end

    # :call-seq:
    #   delete_set_cookie_header(key, value = {}) -> encoded string
    #
    # Generate an encoded string based on the given +key+ and +value+ using
    # set_cookie_header for the purpose of causing the specified cookie to be
    # deleted. The +value+ may be an instance of +Hash+ and can include
    # attributes as outlined by set_cookie_header. The encoded cookie will have
    # a +max_age+ of 0 seconds, an +expires+ date in the past and an empty
    # +value+. When used with the +set-cookie+ header, it will cause the client
    # to *remove* any matching cookie.
    #
    #   delete_set_cookie_header("myname")
    #   # => "myname=; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT"
    #
    def delete_set_cookie_header(key, value = {})
      set_cookie_header(key, value.merge(max_age: '0', expires: Time.at(0), value: ''))
    end

    def make_delete_cookie_header(header, key, value)
      warn("make_delete_cookie_header is deprecated and will be removed in Rack 3.1, use delete_set_cookie_header! instead", uplevel: 1)

      delete_set_cookie_header!(header, key, value)
    end

    def delete_cookie_header!(headers, key, value = {})
      headers[SET_COOKIE] = delete_set_cookie_header!(headers[SET_COOKIE], key, value)

      return nil
    end

    def add_remove_cookie_to_header(header, key, value = {})
      warn("add_remove_cookie_to_header is deprecated and will be removed in Rack 3.1, use delete_set_cookie_header! instead", uplevel: 1)

      delete_set_cookie_header!(header, key, value)
    end

    # :call-seq:
    #   delete_set_cookie_header!(header, key, value = {}) -> header value
    #
    # Set an expired cookie in the specified headers with the given cookie
    # +key+ and +value+ using delete_set_cookie_header. This causes
    # the client to immediately delete the specified cookie.
    #
    #   delete_set_cookie_header!(nil, "mycookie")
    #   # => "mycookie=; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT"
    #
    # If the header is non-nil, it will be modified in place.
    #
    #   header = []
    #   delete_set_cookie_header!(header, "mycookie")
    #   # => ["mycookie=; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT"]
    #   header
    #   # => ["mycookie=; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT"]
    #
    def delete_set_cookie_header!(header, key, value = {})
      if header
        header = Array(header)
        header << delete_set_cookie_header(key, value)
      else
        header = delete_set_cookie_header(key, value)
      end

      return header
    end

    def rfc2822(time)
      time.rfc2822
    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)
      get_byte_ranges env['HTTP_RANGE'], size
    end

    def get_byte_ranges(http_range, size)
      # See <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35>
      return nil unless http_range && http_range =~ /bytes=([^;]+)/
      ranges = []
      $1.split(/,\s*/).each do |range_spec|
        return nil unless range_spec.include?('-')
        range = range_spec.split('-')
        r0, r1 = range[0], range[1]
        if r0.nil? || r0.empty?
          return nil if r1.nil?
          # 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.nil?
            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

    # :nocov:
    if defined?(OpenSSL.fixed_length_secure_compare)
      # 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

        OpenSSL.fixed_length_secure_compare(a, b)
      end
    # :nocov:
    else
      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
    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 wrapper around Headers
    # header when set.
    #
    # @api private
    class HeaderHash < Hash # :nodoc:
      def self.[](headers)
        warn "Rack::Utils::HeaderHash is deprecated and will be removed in Rack 3.1, switch to Rack::Headers", uplevel: 1
        if headers.is_a?(Headers) && !headers.frozen?
          return headers
        end

        new_headers = Headers.new
        headers.each{|k,v| new_headers[k] = v}
        new_headers
      end

      def self.new(hash = {})
        warn "Rack::Utils::HeaderHash is deprecated and will be removed in Rack 3.1, switch to Rack::Headers", uplevel: 1
        headers = Headers.new
        hash.each{|k,v| headers[k] = v}
        headers
      end

      def self.allocate
        raise TypeError, "cannot allocate HeaderHash"
      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
# frozen_string_literal: true

require 'uri'
require 'stringio'

require_relative 'constants'
require_relative 'mock_response'

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.
  # <tt>:input</tt>:: A String or IO-like to be used as rack.input.
  # <tt>:fatal</tt>:: Raise a FatalWarning if the app writes to rack.errors.
  # <tt>:lint</tt>:: 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_INPUT        => StringIO.new,
      RACK_ERRORS       => StringIO.new,
    }.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
    # :http_version :: The SERVER_PROTOCOL 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[SERVER_PROTOCOL] = opts[:http_version] || 'HTTP/1.1'
      env[QUERY_STRING]    = (uri.query.to_s).b
      env[PATH_INFO]       = (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

      opts[:input] ||= String.new
      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
end
# frozen_string_literal: true

require_relative 'constants'
require_relative 'utils'

module Rack
  warn "Rack::Chunked is deprecated and will be removed in Rack 3.1", uplevel: 1

  # 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 = response = @app.call(env)

      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']
          response[2] = TrailerBody.new(body)
        else
          response[2] = Body.new(body)
        end
      end

      response
    end
  end
end
# frozen_string_literal: true

require 'uri'

module Rack
  class QueryParser
    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

    # ParamsTooDeepError is the error that is raised when params are recursively
    # nested over the specified limit.
    class ParamsTooDeepError < RangeError; end

    def self.make_default(_key_space_limit=(not_deprecated = true; nil), param_depth_limit)
      unless not_deprecated
        warn("`first argument `key_space limit` is deprecated and no longer has an effect. Please call with only one argument, which will be required in a future version of Rack", uplevel: 1)
      end

      new Params, param_depth_limit
    end

    attr_reader :param_depth_limit

    def initialize(params_class, _key_space_limit=(not_deprecated = true; nil), param_depth_limit)
      unless not_deprecated
        warn("`second argument `key_space limit` is deprecated and no longer has an effect. Please call with only two arguments, which will be required in a future version of Rack", uplevel: 1)
      end

      @params_class = params_class
      @param_depth_limit = param_depth_limit
    end

    # Stolen from Mongrel, with some small modifications:
    # Parses a query string by breaking it up at the '&'.  You can also use this
    # to parse cookies by changing the characters used in the second parameter
    # (which defaults to '&').
    def parse_query(qs, separator = nil, &unescaper)
      unescaper ||= method(:unescape)

      params = make_params

      (qs || '').split(separator ? (COMMON_SEP[separator] || /[#{separator}] */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, separator = nil)
      params = make_params

      unless qs.nil? || qs.empty?
        (qs || '').split(separator ? (COMMON_SEP[separator] || /[#{separator}] */n) : DEFAULT_SEP).each do |p|
          k, v = p.split('=', 2).map! { |s| unescape(s) }

          _normalize_params(params, k, v, 0)
        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.  The depth argument is deprecated
    # and should no longer be used, it is kept for backwards compatibility with
    # earlier versions of rack.
    def normalize_params(params, name, v, _depth=nil)
      _normalize_params(params, name, v, 0)
    end

    private def _normalize_params(params, name, v, depth)
      raise ParamsTooDeepError if depth >= param_depth_limit

      if !name
        # nil name, treat same as empty string (required by tests)
        k = after = ''
      elsif depth == 0
        # Start of parsing, don't treat [] or [ at start of string specially
        if start = name.index('[', 1)
          # Start of parameter nesting, use part before brackets as key
          k = name[0, start]
          after = name[start, name.length]
        else
          # Plain parameter with no nesting
          k = name
          after = ''
        end
      elsif name.start_with?('[]')
        # Array nesting
        k = '[]'
        after = name[2, name.length]
      elsif name.start_with?('[') && (start = name.index(']', 1))
        # Hash nesting, use the part inside brackets as the key
        k = name[1, start-1]
        after = name[start+1, name.length]
      else
        # Probably malformed input, nested but not starting with [
        # treat full name as key for backwards compatibility.
        k = name
        after = ''
      end

      return if k.empty?

      if after == ''
        if k == '[]' && depth != 0
          return [v]
        else
          params[k] = v
        end
      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.start_with?('[]')
        # Recognize x[][y] (hash inside array) parameters
        unless after[2] == '[' && after.end_with?(']') && (child_key = after[3, after.length-4]) && !child_key.empty? && !child_key.index('[') && !child_key.index(']')
          # Handle other nested array parameters
          child_key = after[2, after.length]
        end
        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
    end

    def new_depth_limit(param_depth_limit)
      self.class.new @params_class, 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(string, encoding = Encoding::UTF_8)
      URI.decode_www_form_component(string, encoding)
    end

    class Params
      def initialize
        @size   = 0
        @params = {}
      end

      def [](key)
        @params[key]
      end

      def []=(key, value)
        @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
# frozen_string_literal: true

require 'digest/sha2'

require_relative 'constants'
require_relative 'utils'

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 = response = @app.call(env)

      if etag_status?(status) && body.respond_to?(:to_ary) && !skip_caching?(headers)
        body = body.to_ary
        digest = digest_body(body)
        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

      response
    end

    private

      def etag_status?(status)
        status == 200 || status == 201
      end

      def skip_caching?(headers)
        headers.key?(ETAG_STRING) || headers.key?('last-modified')
      end

      def digest_body(body)
        digest = nil

        body.each do |part|
          (digest ||= Digest::SHA256.new) << part unless part.empty?
        end

        digest && digest.hexdigest.byteslice(0,32)
      end
  end
end
# frozen_string_literal: true

module Rack
  # Request env keys
  HTTP_HOST         = 'HTTP_HOST'
  HTTP_PORT         = 'HTTP_PORT'
  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'
  HTTP_COOKIE       = 'HTTP_COOKIE'

  # Response Header Keys
  CACHE_CONTROL     = 'cache-control'
  CONTENT_LENGTH    = 'content-length'
  CONTENT_TYPE      = 'content-type'
  ETAG              = 'etag'
  EXPIRES           = 'expires'
  SET_COOKIE        = 'set-cookie'
  TRANSFER_ENCODING = 'transfer-encoding'

  # 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_URL_SCHEME                     = 'rack.url_scheme'
  RACK_HIJACK                         = 'rack.hijack'
  RACK_IS_HIJACK                      = 'rack.hijack?'
  RACK_RECURSIVE_INCLUDE              = 'rack.recursive.include'
  RACK_MULTIPART_BUFFER_SIZE          = 'rack.multipart.buffer_size'
  RACK_MULTIPART_TEMPFILE_FACTORY     = 'rack.multipart.tempfile_factory'
  RACK_RESPONSE_FINISHED              = 'rack.response_finished'
  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_FORM_ERROR             = 'rack.request.form_error'
  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'
end
# 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",
      ".apng"      => "image/apng",
      ".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",
      ".avif"      => "image/avif",
      ".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",
      ".flif"      => "image/flif",
      ".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",
      ".heic"      => "image/heic",
      ".heics"     => "image/heic-sequence",
      ".heif"      => "image/heif",
      ".heifs"     => "image/heif-sequence",
      ".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",
      ".webp"      => "image/webp",
      ".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
# frozen_string_literal: true

require_relative 'constants'
require_relative 'files'
require_relative 'mime'

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
    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
            response[1][CONTENT_TYPE] = Mime.mime_type(::File.extname(path), 'text/plain')
            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
# frozen_string_literal: true

require_relative 'constants'
require_relative 'utils'
require_relative 'body_proxy'

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)
      _, headers, body = response = @app.call(env)

      if body.respond_to?(:to_path)
        case type = variation(env)
        when /x-accel-redirect/i
          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.downcase] = ::Rack::Utils.escape_path(url).gsub('?', '%3F')
            obody = body
            response[2] = 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/i
          path = ::File.expand_path(body.to_path)
          headers[CONTENT_LENGTH] = '0'
          headers[type.downcase] = path
          obody = body
          response[2] = 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
      response
    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
# frozen_string_literal: true

require_relative 'constants'
require_relative 'utils'
require_relative 'body_proxy'

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 = response = @app.call(env)

        if status == 200 && fresh?(env, headers)
          response[0] = 304
          headers.delete(CONTENT_TYPE)
          headers.delete(CONTENT_LENGTH)
          response[2] = Rack::BodyProxy.new([]) do
            body.close if body.respond_to?(:close)
          end
        end
        response
      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
# 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
# frozen_string_literal: true

require 'forwardable'

require_relative 'constants'
require_relative 'utils'

module Rack
  # Rack::Lint validates your application and the requests and
  # responses according to the Rack spec.

  class Lint
    def initialize(app)
      @app = app
    end

    # :stopdoc:

    class LintError < RuntimeError; end
    # AUTHORS: n.b. The trailing whitespace between paragraphs is important and
    # should not be removed. The whitespace creates paragraphs in the RDoc
    # output.
    #
    ## 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)
      Wrapper.new(@app, env).response
    end

    class Wrapper
      def initialize(app, env)
        @app = app
        @env = env
        @response = nil
        @head_request = false

        @status = nil
        @headers = nil
        @body = nil
        @invoked = nil
        @content_length = nil
        @closed = false
        @size = 0
      end

      def response
        ## It takes exactly one argument, the *environment*
        raise LintError, "No env given" unless @env
        check_environment(@env)

        @env[RACK_INPUT] = InputWrapper.new(@env[RACK_INPUT])
        @env[RACK_ERRORS] = ErrorWrapper.new(@env[RACK_ERRORS])

        ## and returns a non-frozen Array of exactly three values:
        @response = @app.call(@env)
        raise LintError, "response is not an Array, but #{@response.class}" unless @response.kind_of? Array
        raise LintError, "response is frozen" if @response.frozen?
        raise LintError, "response array has #{@response.size} elements instead of 3" unless @response.size == 3

        @status, @headers, @body = @response
        ## The *status*,
        check_status(@status)

        ## the *headers*,
        check_headers(@headers)

        hijack_proc = check_hijack_response(@headers, @env)
        if hijack_proc
          @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

        @lint = (@env['rack.lint'] ||= []) << self

        if (@env['rack.lint.body_iteration'] ||= 0) > 0
          raise LintError, "Middleware must not call #each directly"
        end

        return [@status, @headers, self]
      end

      ##
      ## == The Environment
      ##
      def check_environment(env)
        ## The environment must be an unfrozen instance of Hash that includes
        ## CGI-like headers. The Rack application is free to modify the
        ## environment.
        raise LintError, "env #{env.inspect} is not a Hash, but #{env.class}" unless env.kind_of? Hash
        raise LintError, "env should not be frozen, but is" if env.frozen?

        ##
        ## The environment is required to include these variables
        ## (adopted from {PEP 333}[https://peps.python.org/pep-0333/]), except when they'd be empty, but see
        ## below.

        ## <tt>REQUEST_METHOD</tt>:: The HTTP request method, such as
        ##                           "GET" or "POST". This cannot ever
        ##                           be an empty string, and so is
        ##                           always required.

        ## <tt>SCRIPT_NAME</tt>:: 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.

        ## <tt>PATH_INFO</tt>:: 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.

        ## <tt>QUERY_STRING</tt>:: The portion of the request URL that
        ##                         follows the <tt>?</tt>, if any. May be
        ##                         empty, but is always required!

        ## <tt>SERVER_NAME</tt>:: When combined with <tt>SCRIPT_NAME</tt> and
        ##                        <tt>PATH_INFO</tt>, these variables can be
        ##                        used to complete the URL. Note, however,
        ##                        that <tt>HTTP_HOST</tt>, if present,
        ##                        should be used in preference to
        ##                        <tt>SERVER_NAME</tt> for reconstructing
        ##                        the request URL.
        ##                        <tt>SERVER_NAME</tt> can never be an empty
        ##                        string, and so is always required.

        ## <tt>SERVER_PORT</tt>:: 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.

        ## <tt>SERVER_PROTOCOL</tt>:: A string representing the HTTP version used
        ##                            for the request.

        ## <tt>HTTP_</tt> Variables:: Variables corresponding to the
        ##                            client-supplied HTTP request
        ##                            headers (i.e., variables whose
        ##                            names begin with <tt>HTTP_</tt>). 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:

        ## <tt>rack.url_scheme</tt>:: +http+ or +https+, depending on the
        ##                            request URL.

        ## <tt>rack.input</tt>:: See below, the input stream.

        ## <tt>rack.errors</tt>:: See below, the error stream.

        ## <tt>rack.hijack?</tt>:: See below, if present and true, indicates
        ##                         that the server supports partial hijacking.

        ## <tt>rack.hijack</tt>:: See below, if present, an object responding
        ##                        to +call+ that is used to perform a full
        ##                        hijack.

        ## Additional environment specifications have approved to
        ## standardized middleware APIs. None of these are required to
        ## be implemented by the server.

        ## <tt>rack.session</tt>:: A hash-like interface for storing
        ##                         request session data.
        ##                         The store must implement:
        if session = env[RACK_SESSION]
          ##                         store(key, value)         (aliased as []=);
          unless session.respond_to?(:store) && session.respond_to?(:[]=)
            raise LintError, "session #{session.inspect} must respond to store and []="
          end

          ##                         fetch(key, default = nil) (aliased as []);
          unless session.respond_to?(:fetch) && session.respond_to?(:[])
            raise LintError, "session #{session.inspect} must respond to fetch and []"
          end

          ##                         delete(key);
          unless session.respond_to?(:delete)
            raise LintError, "session #{session.inspect} must respond to delete"
          end

          ##                         clear;
          unless session.respond_to?(:clear)
            raise LintError, "session #{session.inspect} must respond to clear"
          end

          ##                         to_hash (returning unfrozen Hash instance);
          unless session.respond_to?(:to_hash) && session.to_hash.kind_of?(Hash) && !session.to_hash.frozen?
            raise LintError, "session #{session.inspect} must respond to to_hash and return unfrozen Hash instance"
          end
        end

        ## <tt>rack.logger</tt>:: A common object interface for logging messages.
        ##                        The object must implement:
        if logger = env[RACK_LOGGER]
          ##                         info(message, &block)
          unless logger.respond_to?(:info)
            raise LintError, "logger #{logger.inspect} must respond to info"
          end

          ##                         debug(message, &block)
          unless logger.respond_to?(:debug)
            raise LintError, "logger #{logger.inspect} must respond to debug"
          end

          ##                         warn(message, &block)
          unless logger.respond_to?(:warn)
            raise LintError, "logger #{logger.inspect} must respond to warn"
          end

          ##                         error(message, &block)
          unless logger.respond_to?(:error)
            raise LintError, "logger #{logger.inspect} must respond to error"
          end

          ##                         fatal(message, &block)
          unless logger.respond_to?(:fatal)
            raise LintError, "logger #{logger.inspect} must respond to fatal"
          end
        end

        ## <tt>rack.multipart.buffer_size</tt>:: 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]
          unless bufsize.is_a?(Integer) && bufsize > 0
            raise LintError, "rack.multipart.buffer_size must be an Integer > 0 if specified"
          end
        end

        ## <tt>rack.multipart.tempfile_factory</tt>:: 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]
          raise LintError, "rack.multipart.tempfile_factory must respond to #call" unless tempfile_factory.respond_to?(:call)
          env[RACK_MULTIPART_TEMPFILE_FACTORY] = lambda do |filename, content_type|
            io = tempfile_factory.call(filename, content_type)
            raise LintError, "rack.multipart.tempfile_factory return value must respond to #<<" unless 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 <tt>rack.</tt>
        ## 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 SERVER_PROTOCOL
           rack.input rack.errors].each { |header|
          raise LintError, "env missing required key #{header}" unless env.include? header
        }

        ## The <tt>SERVER_PORT</tt> must be an Integer if set.
        server_port = env["SERVER_PORT"]
        unless server_port.nil? || (Integer(server_port) rescue false)
          raise LintError, "env[SERVER_PORT] is not an Integer"
        end

        ## The <tt>SERVER_NAME</tt> must be a valid authority as defined by RFC7540.
        unless (URI.parse("http://#{env[SERVER_NAME]}/") rescue false)
          raise LintError, "#{env[SERVER_NAME]} must be a valid authority"
        end

        ## The <tt>HTTP_HOST</tt> must be a valid authority as defined by RFC7540.
        unless (URI.parse("http://#{env[HTTP_HOST]}/") rescue false)
          raise LintError, "#{env[HTTP_HOST]} must be a valid authority"
        end

        ## The <tt>SERVER_PROTOCOL</tt> must match the regexp <tt>HTTP/\d(\.\d)?</tt>.
        server_protocol = env['SERVER_PROTOCOL']
        unless %r{HTTP/\d(\.\d)?}.match?(server_protocol)
          raise LintError, "env[SERVER_PROTOCOL] does not match HTTP/\\d(\\.\\d)?"
        end

        ## If the <tt>HTTP_VERSION</tt> is present, it must equal the <tt>SERVER_PROTOCOL</tt>.
        if env['HTTP_VERSION'] && env['HTTP_VERSION'] != server_protocol
          raise LintError, "env[HTTP_VERSION] does not equal env[SERVER_PROTOCOL]"
        end

        ## The environment must not contain the keys
        ## <tt>HTTP_CONTENT_TYPE</tt> or <tt>HTTP_CONTENT_LENGTH</tt>
        ## (use the versions without <tt>HTTP_</tt>).
        %w[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH].each { |header|
          if env.include? header
            raise LintError, "env contains #{header}, must use #{header[5..-1]}"
          end
        }

        ## 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
          unless value.kind_of? String
            raise LintError, "env variable #{key} has non-string value #{value.inspect}"
          end
          next if value.encoding == Encoding::ASCII_8BIT
          unless value.b !~ /[\x80-\xff]/n
            raise LintError, "env variable #{key} has value containing non-ASCII characters and has non-ASCII-8BIT encoding #{value.inspect} encoding: #{value.encoding}"
          end
        }

        ## There are the following restrictions:

        ## * <tt>rack.url_scheme</tt> must either be +http+ or +https+.
        unless %w[http https].include?(env[RACK_URL_SCHEME])
          raise LintError, "rack.url_scheme unknown: #{env[RACK_URL_SCHEME].inspect}"
        end

        ## * There must be a valid input stream in <tt>rack.input</tt>.
        check_input env[RACK_INPUT]
        ## * There must be a valid error stream in <tt>rack.errors</tt>.
        check_error env[RACK_ERRORS]
        ## * There may be a valid hijack callback in <tt>rack.hijack</tt>
        check_hijack env

        ## * The <tt>REQUEST_METHOD</tt> must be a valid token.
        unless env[REQUEST_METHOD] =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/
          raise LintError, "REQUEST_METHOD unknown: #{env[REQUEST_METHOD].dump}"
        end

        ## * The <tt>SCRIPT_NAME</tt>, if non-empty, must start with <tt>/</tt>
        if env.include?(SCRIPT_NAME) && env[SCRIPT_NAME] != "" && env[SCRIPT_NAME] !~ /\A\//
          raise LintError, "SCRIPT_NAME must start with /"
        end
        ## * The <tt>PATH_INFO</tt>, if non-empty, must start with <tt>/</tt>
        if env.include?(PATH_INFO) && env[PATH_INFO] != "" && env[PATH_INFO] !~ /\A\//
          raise LintError, "PATH_INFO must start with /"
        end
        ## * The <tt>CONTENT_LENGTH</tt>, if given, must consist of digits only.
        if env.include?("CONTENT_LENGTH") && env["CONTENT_LENGTH"] !~ /\A\d+\z/
          raise LintError, "Invalid CONTENT_LENGTH: #{env["CONTENT_LENGTH"]}"
        end

        ## * One of <tt>SCRIPT_NAME</tt> or <tt>PATH_INFO</tt> must be
        ##   set. <tt>PATH_INFO</tt> should be <tt>/</tt> if
        ##   <tt>SCRIPT_NAME</tt> is empty.
        unless env[SCRIPT_NAME] || env[PATH_INFO]
          raise LintError, "One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)"
        end
        ##   <tt>SCRIPT_NAME</tt> never should be <tt>/</tt>, but instead be empty.
        unless env[SCRIPT_NAME] != "/"
          raise LintError, "SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'"
        end

        ## <tt>rack.response_finished</tt>:: An array of callables run by the server after the response has been
        ## processed. This would typically be invoked after sending the response to the client, but it could also be
        ## invoked if an error occurs while generating the response or sending the response; in that case, the error
        ## argument will be a subclass of +Exception+.
        ## The callables are invoked with +env, status, headers, error+ arguments and should not raise any
        ## exceptions. They should be invoked in reverse order of registration.
        if callables = env[RACK_RESPONSE_FINISHED]
          raise LintError, "rack.response_finished must be an array of callable objects" unless callables.is_a?(Array)

          callables.each do |callable|
            raise LintError, "rack.response_finished values must respond to call(env, status, headers, error)" unless callable.respond_to?(:call)
          end
        end
      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.
        if input.respond_to?(:external_encoding) && input.external_encoding != Encoding::ASCII_8BIT
          raise LintError, "rack.input #{input} does not have ASCII-8BIT as its external encoding"
        end
        if input.respond_to?(:binmode?) && !input.binmode?
          raise LintError, "rack.input #{input} is not opened in binary mode"
        end

        ## The input stream must respond to +gets+, +each+, and +read+.
        [:gets, :each, :read].each { |method|
          unless input.respond_to? method
            raise LintError, "rack.input #{input} does not respond to ##{method}"
          end
        }
      end

      class InputWrapper
        def initialize(input)
          @input = input
        end

        ## * +gets+ must be called without arguments and return a string,
        ##   or +nil+ on EOF.
        def gets(*args)
          raise LintError, "rack.input#gets called with arguments" unless args.size == 0
          v = @input.gets
          unless v.nil? or v.kind_of? String
            raise LintError, "rack.input#gets didn't return a String"
          end
          v
        end

        ## * +read+ behaves like IO#read.
        ##   Its signature is <tt>read([length, [buffer]])</tt>.
        ##
        ##   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)
          unless args.size <= 2
            raise LintError, "rack.input#read called with too many arguments"
          end
          if args.size >= 1
            unless args.first.kind_of?(Integer) || args.first.nil?
              raise LintError, "rack.input#read called with non-integer and non-nil length"
            end
            unless args.first.nil? || args.first >= 0
              raise LintError, "rack.input#read called with a negative length"
            end
          end
          if args.size >= 2
            unless args[1].kind_of?(String)
              raise LintError, "rack.input#read called with non-String buffer"
            end
          end

          v = @input.read(*args)

          unless v.nil? or v.kind_of? String
            raise LintError, "rack.input#read didn't return nil or a String"
          end
          if args[0].nil?
            unless !v.nil?
              raise LintError, "rack.input#read(nil) returned nil on EOF"
            end
          end

          v
        end

        ## * +each+ must be called without arguments and only yield Strings.
        def each(*args)
          raise LintError, "rack.input#each called with arguments" unless args.size == 0
          @input.each { |line|
            unless line.kind_of? String
              raise LintError, "rack.input#each didn't yield a String"
            end
            yield line
          }
        end

        ## * +close+ can be called on the input stream to indicate that the
        ## any remaining input is not needed.
        def close(*args)
          @input.close(*args)
        end
      end

      ##
      ## === The Error Stream
      ##
      def check_error(error)
        ## The error stream must respond to +puts+, +write+ and +flush+.
        [:puts, :write, :flush].each { |method|
          unless error.respond_to? method
            raise LintError, "rack.error #{error} does not respond to ##{method}"
          end
        }
      end

      class ErrorWrapper
        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)
          raise LintError, "rack.errors#write not called with a String" unless 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)
          raise LintError, "rack.errors#close must not be called"
        end
      end

      ##
      ## === Hijacking
      ##
      ## The hijacking interfaces provides a means for an application to take
      ## control of the HTTP connection. There are two distinct hijack
      ## interfaces: full hijacking where the application takes over the raw
      ## connection, and partial hijacking where the application takes over
      ## just the response body stream. In both cases, the application is
      ## responsible for closing the hijacked stream.
      ##
      ## Full hijacking only works with HTTP/1. Partial hijacking is functionally
      ## equivalent to streaming bodies, and is still optionally supported for
      ## backwards compatibility with older Rack versions.
      ##
      ## ==== Full Hijack
      ##
      ## Full hijack is used to completely take over an HTTP/1 connection. It
      ## occurs before any headers are written and causes the request to
      ## ignores any response generated by the application.
      ##
      ## It is intended to be used when applications need access to raw HTTP/1
      ## connection.
      ##
      def check_hijack(env)
        ## If +rack.hijack+ is present in +env+, it must respond to +call+
        if original_hijack = env[RACK_HIJACK]
          raise LintError, "rack.hijack must respond to call" unless original_hijack.respond_to?(:call)

          env[RACK_HIJACK] = proc do
            io = original_hijack.call

            ## and return an +IO+ instance which can be used to read and write
            ## to the underlying connection using HTTP/1 semantics and
            ## formatting.
            raise LintError, "rack.hijack must return an IO instance" unless io.is_a?(IO)

            io
          end
        end
      end

      ##
      ## ==== Partial Hijack
      ##
      ## Partial hijack is used for bi-directional streaming of the request and
      ## response body. It occurs after the status and headers are written by
      ## the server and causes the server to ignore the Body of the response.
      ##
      ## It is intended to be used when applications need bi-directional
      ## streaming.
      ##
      def check_hijack_response(headers, env)
        ## If +rack.hijack?+ is present in +env+ and truthy,
        if env[RACK_IS_HIJACK]
          ## an application may set the special response header +rack.hijack+
          if original_hijack = headers[RACK_HIJACK]
            ## to an object that responds to +call+,
            unless original_hijack.respond_to?(:call)
              raise LintError, 'rack.hijack header must respond to #call'
            end
            ## accepting a +stream+ argument.
            return proc do |io|
              original_hijack.call StreamWrapper.new(io)
            end
          end
          ##
          ## After the response status and headers have been sent, this hijack
          ## callback will be invoked with a +stream+ argument which follows the
          ## same interface as outlined in "Streaming Body". Servers must
          ## ignore the +body+ part of the response tuple when the
          ## +rack.hijack+ response header is present. Using an empty +Array+
          ## instance is recommended.
        else
          ##
          ## The special response header +rack.hijack+ must only be set
          ## if the request +env+ has a truthy +rack.hijack?+.
          if headers.key?(RACK_HIJACK)
            raise LintError, 'rack.hijack header must not be present if server does not support hijacking'
          end
        end

        nil
      end

      ## == The Response
      ##
      ## === The Status
      ##
      def check_status(status)
        ## This is an HTTP status. It must be an Integer greater than or equal to
        ## 100.
        unless status.is_a?(Integer) && status >= 100
          raise LintError, "Status must be an Integer >=100"
        end
      end

      ##
      ## === The Headers
      ##
      def check_headers(headers)
        ## The headers must be a unfrozen Hash.
        unless headers.kind_of?(Hash)
          raise LintError, "headers object should be a hash, but isn't (got #{headers.class} as headers)"
        end

        if headers.frozen?
          raise LintError, "headers object should not be frozen, but is"
        end

        headers.each do |key, value|
          ## The header keys must be Strings.
          unless key.kind_of? String
            raise LintError, "header key must be a string, was #{key.class}"
          end

          ## Special headers starting "rack." are for communicating with the
          ## server, and must not be sent back to the client.
          next if key.start_with?("rack.")

          ## The header must not contain a +Status+ key.
          raise LintError, "header must not contain status" if key == "status"
          ## Header keys must conform to RFC7230 token specification, i.e. cannot
          ## contain non-printable ASCII, DQUOTE or "(),/:;<=>?@[\]{}".
          raise LintError, "invalid header name: #{key}" if key =~ /[\(\),\/:;<=>\?@\[\\\]{}[:cntrl:]]/
          ## Header keys must not contain uppercase ASCII characters (A-Z).
          raise LintError, "uppercase character in header name: #{key}" if key =~ /[A-Z]/

          ## Header values must be either a String instance,
          if value.kind_of?(String)
            check_header_value(key, value)
          elsif value.kind_of?(Array)
            ## or an Array of String instances,
            value.each{|value| check_header_value(key, value)}
          else
            raise LintError, "a header value must be a String or Array of Strings, but the value of '#{key}' is a #{value.class}"
          end
        end
      end

      def check_header_value(key, value)
        ## such that each String instance must not contain characters below 037.
        if value =~ /[\000-\037]/
          raise LintError, "invalid header value #{key}: #{value.inspect}"
        end
      end

      ##
      ## === The content-type
      ##
      def check_content_type(status, headers)
        headers.each { |key, value|
          ## There must not be a <tt>content-type</tt> header key when the +Status+ is 1xx,
          ## 204, or 304.
          if key == "content-type"
            if Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.key? status.to_i
              raise LintError, "content-type header found in #{status} response, not allowed"
            end
            return
          end
        }
      end

      ##
      ## === The content-length
      ##
      def check_content_length(status, headers)
        headers.each { |key, value|
          if key == 'content-length'
            ## There must not be a <tt>content-length</tt> header key when the
            ## +Status+ is 1xx, 204, or 304.
            if Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.key? status.to_i
              raise LintError, "content-length header found in #{status} response, not allowed"
            end
            @content_length = value
          end
        }
      end

      def verify_content_length(size)
        if @head_request
          unless size == 0
            raise LintError, "Response body was given for HEAD request, but should be empty"
          end
        elsif @content_length
          unless @content_length == size.to_s
            raise LintError, "content-length header was #{@content_length}, but should be #{size}"
          end
        end
      end

      ##
      ## === The Body
      ##
      ## The Body is typically an +Array+ of +String+ instances, an enumerable
      ## that yields +String+ instances, a +Proc+ instance, or a File-like
      ## object.
      ##
      ## The Body must respond to +each+ or +call+. It may optionally respond
      ## to +to_path+ or +to_ary+. A Body that responds to +each+ is considered
      ## to be an Enumerable Body. A Body that responds to +call+ is considered
      ## to be a Streaming Body.
      ##
      ## A Body that responds to both +each+ and +call+ must be treated as an
      ## Enumerable Body, not a Streaming Body. If it responds to +each+, you
      ## must call +each+ and not +call+. If the Body doesn't respond to
      ## +each+, then you can assume it responds to +call+.
      ##
      ## The Body must either be consumed or returned. The Body is consumed by
      ## optionally calling either +each+ or +call+.
      ## Then, if the Body responds to +close+, it must be called to release
      ## any resources associated with the generation of the body.
      ## In other words, +close+ must always be called at least once; typically
      ## after the web server has sent the response to the client, but also in
      ## cases where the Rack application makes internal/virtual requests and
      ## discards the response.
      ##
      def close
        ##
        ## After calling +close+, the Body is considered closed and should not
        ## be consumed again.
        @closed = true

        ## If the original Body is replaced by a new Body, the new Body must
        ## also consume the original Body by calling +close+ if possible.
        @body.close if @body.respond_to?(:close)

        index = @lint.index(self)
        unless @env['rack.lint'][0..index].all? {|lint| lint.instance_variable_get(:@closed)}
          raise LintError, "Body has not been closed"
        end
      end

      def verify_to_path
        ##
        ## If the Body responds to +to_path+, it must return a +String+
        ## path for the local file system 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 +to_path+ method does not consume
        ## the body.
        if @body.respond_to?(:to_path)
          unless ::File.exist? @body.to_path
            raise LintError, "The file identified by body.to_path does not exist"
          end
        end
      end

      ##
      ## ==== Enumerable Body
      ##
      def each
        ## The Enumerable Body must respond to +each+.
        raise LintError, "Enumerable Body must respond to each" unless @body.respond_to?(:each)

        ## It must only be called once.
        raise LintError, "Response body must only be invoked once (#{@invoked})" unless @invoked.nil?

        ## It must not be called after being closed.
        raise LintError, "Response body is already closed" if @closed

        @invoked = :each

        @body.each do |chunk|
          ## and must only yield String values.
          unless chunk.kind_of? String
            raise LintError, "Body yielded non-string value #{chunk.inspect}"
          end

          ##
          ## The Body itself should not be an instance of String, as this will
          ## break in Ruby 1.9.
          ##
          ## Middleware must not call +each+ directly on the Body.
          ## Instead, middleware can return a new Body that calls +each+ on the
          ## original Body, yielding at least once per iteration.
          if @lint[0] == self
            @env['rack.lint.body_iteration'] += 1
          else
            if (@env['rack.lint.body_iteration'] -= 1) > 0
              raise LintError, "New body must yield at least once per iteration of old body"
            end
          end

          @size += chunk.bytesize
          yield chunk
        end

        verify_content_length(@size)

        verify_to_path
      end

      BODY_METHODS = {to_ary: true, each: true, call: true, to_path: true}

      def to_path
        @body.to_path
      end

      def respond_to?(name, *)
        if BODY_METHODS.key?(name)
          @body.respond_to?(name)
        else
          super
        end
      end

      ##
      ## If the Body responds to +to_ary+, it must return an +Array+ whose
      ## contents are identical to that produced by calling +each+.
      ## Middleware may call +to_ary+ directly on the Body and return a new
      ## Body in its place. In other words, middleware can only process the
      ## Body directly if it responds to +to_ary+. If the Body responds to both
      ## +to_ary+ and +close+, its implementation of +to_ary+ must call
      ## +close+.
      def to_ary
        @body.to_ary.tap do |content|
          unless content == @body.enum_for.to_a
            raise LintError, "#to_ary not identical to contents produced by calling #each"
          end
        end
      ensure
        close
      end

      ##
      ## ==== Streaming Body
      ##
      def call(stream)
        ## The Streaming Body must respond to +call+.
        raise LintError, "Streaming Body must respond to call" unless @body.respond_to?(:call)

        ## It must only be called once.
        raise LintError, "Response body must only be invoked once (#{@invoked})" unless @invoked.nil?

        ## It must not be called after being closed.
        raise LintError, "Response body is already closed" if @closed

        @invoked = :call

        ## It takes a +stream+ argument.
        ##
        ## The +stream+ argument must implement:
        ## <tt>read, write, <<, flush, close, close_read, close_write, closed?</tt>
        ##
        @body.call(StreamWrapper.new(stream))
      end

      class StreamWrapper
        extend Forwardable

        ## 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 HTTP/2.
        REQUIRED_METHODS = [
          :read, :write, :<<, :flush, :close,
          :close_read, :close_write, :closed?
        ]

        def_delegators :@stream, *REQUIRED_METHODS

        def initialize(stream)
          @stream = stream

          REQUIRED_METHODS.each do |method_name|
            raise LintError, "Stream must respond to #{method_name}" unless stream.respond_to?(method_name)
          end
        end
      end

      # :startdoc:
    end
  end
end

##
## == Thanks
## Some parts of this specification are adopted from {PEP 333 – Python Web Server Gateway Interface v1.0}[https://peps.python.org/pep-0333/]
## I'd like to thank everyone involved in that effort.
# frozen_string_literal: true

require_relative 'constants'

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 debug! ; end
    def error! ; end
    def fatal! ; end
    def info! ; end
    def warn! ; 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 log(severity, message = nil, progname = nil, &block); end
    def <<(msg); end
    def reopen(logdev = nil); end
  end
end
# frozen_string_literal: true

require_relative 'constants'
require_relative 'utils'

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 = app
      @content_type = content_type
    end

    def call(env)
      status, headers, _ = response = @app.call(env)

      unless STATUS_WITH_NO_ENTITY_BODY.key?(status.to_i)
        headers[CONTENT_TYPE] ||= @content_type
      end

      response
    end
  end
end
# frozen_string_literal: true

require_relative 'constants'
require_relative 'utils'

require_relative 'multipart/parser'
require_relative 'multipart/generator'

module Rack
  # A multipart form data parser, adapted from IOWA.
  #
  # Usually, Rack::Request#POST takes care of calling this.
  module Multipart
    MULTIPART_BOUNDARY = "AaB03x"

    class << self
      def parse_multipart(env, params = Rack::Utils.default_query_parser)
        io = env[RACK_INPUT]

        if content_length = env['CONTENT_LENGTH']
          content_length = content_length.to_i
        end

        content_type = env['CONTENT_TYPE']

        tempfile = env[RACK_MULTIPART_TEMPFILE_FACTORY] || Parser::TEMPFILE_FACTORY
        bufsize = env[RACK_MULTIPART_BUFFER_SIZE] || Parser::BUFSIZE

        info = Parser.parse(io, content_length, content_type, tempfile, bufsize, params)
        env[RACK_TEMPFILES] = info.tmp_files

        return info.params
      end

      def extract_multipart(request, params = Rack::Utils.default_query_parser)
        parse_multipart(request.env)
      end

      def build_multipart(params, first = true)
        Generator.new(params, first).dump
      end
    end
  end
end
# frozen_string_literal: true

require 'erb'

require_relative 'constants'
require_relative 'utils'
require_relative 'request'
require_relative 'body_proxy'

module Rack
  # Rack::ShowStatus catches all empty responses and replaces them
  # with a site explaining the error.
  #
  # Additional details can be put into <tt>rack.showstatus.detail</tt>
  # 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 = response = @app.call(env)
      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

        html = @template.result(binding)
        size = html.bytesize

        response[2] = Rack::BodyProxy.new([html]) do
          body.close if body.respond_to?(:close)
        end

        headers[CONTENT_TYPE] = "text/html"
        headers[CONTENT_LENGTH] = size.to_s
      end

      response
    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 <www.djangoproject.com>
# 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'
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title><%=h message %> at <%=h req.script_name + req.path_info %></title>
  <meta name="robots" content="NONE,NOARCHIVE" />
  <style type="text/css">
    html * { padding:0; margin:0; }
    body * { padding:10px 20px; }
    body * * { padding:0; }
    body { font:small sans-serif; background:#eee; }
    body>div { border-bottom:1px solid #ddd; }
    h1 { font-weight:normal; margin-bottom:.4em; }
    h1 span { font-size:60%; color:#666; font-weight:normal; }
    table { border:none; border-collapse: collapse; width:100%; }
    td, th { vertical-align:top; padding:2px 3px; }
    th { width:12em; text-align:right; color:#666; padding-right:.5em; }
    #info { background:#f6f6f6; }
    #info ol { margin: 0.5em 4em; }
    #info ol li { font-family: monospace; }
    #summary { background: #ffc; }
    #explanation { background:#eee; border-bottom: 0px none; }
  </style>
</head>
<body>
  <div id="summary">
    <h1><%=h message %> <span>(<%= status.to_i %>)</span></h1>
    <table class="meta">
      <tr>
        <th>Request Method:</th>
        <td><%=h req.request_method %></td>
      </tr>
      <tr>
        <th>Request URL:</th>
      <td><%=h req.url %></td>
      </tr>
    </table>
  </div>
  <div id="info">
    <p><%=h detail %></p>
  </div>

  <div id="explanation">
    <p>
    You're seeing this error because you use <code>Rack::ShowStatus</code>.
    </p>
  </div>
</body>
</html>
HTML

    # :startdoc:
  end
end
# frozen_string_literal: true

require_relative 'constants'
require_relative 'utils'
require_relative 'body_proxy'
require_relative 'request'

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 <tt>env['rack.errors']</tt>.
    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 = response = @app.call(env)

      response[2] = BodyProxy.new(body) { log(env, status, headers, began_at) }
      response
    end

    private

    # Log the request to the configured logger.
    def log(env, status, response_headers, began_at)
      request = Rack::Request.new(env)
      length = extract_content_length(response_headers)

      msg = sprintf(FORMAT,
        request.ip || "-",
        request.get_header("REMOTE_USER") || "-",
        Time.now.strftime("%d/%b/%Y:%H:%M:%S %z"),
        request.request_method,
        request.script_name,
        request.path_info,
        request.query_string.empty? ? "" : "?#{request.query_string}",
        request.get_header(SERVER_PROTOCOL),
        status.to_s[0..3],
        length,
        Utils.clock_time - began_at)

      msg.gsub!(/[^[:print:]\n]/) { |c| sprintf("\\x%x", c.ord) }

      logger = @logger || request.get_header(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
# frozen_string_literal: true

require_relative 'constants'
require_relative 'utils'
require_relative 'media_type'

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
    class << self
      attr_accessor :ip_filter

      # The priority when checking forwarded headers. The default
      # is <tt>[:forwarded, :x_forwarded]</tt>, which means, check the
      # +Forwarded+ header first, followed by the appropriate
      # <tt>X-Forwarded-*</tt> header.  You can revert the priority by
      # reversing the priority, or remove checking of either
      # or both headers by removing elements from the array.
      #
      # This should be set as appropriate in your environment
      # based on what reverse proxies are in use.  If you are not
      # using reverse proxies, you should probably use an empty
      # array.
      attr_accessor :forwarded_priority

      # The priority when checking either the <tt>X-Forwarded-Proto</tt>
      # or <tt>X-Forwarded-Scheme</tt> header for the forwarded protocol.
      # The default is <tt>[:proto, :scheme]</tt>, to try the
      # <tt>X-Forwarded-Proto</tt> header before the
      # <tt>X-Forwarded-Scheme</tt> header.  Rack 2 had behavior
      # similar to <tt>[:scheme, :proto]</tt>.  You can remove either or
      # both of the entries in array to ignore that respective header.
      attr_accessor :x_forwarded_proto_priority
    end

    @forwarded_priority = [:forwarded, :x_forwarded]
    @x_forwarded_proto_priority = [:proto, :scheme]

    valid_ipv4_octet = /\.(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])/

    trusted_proxies = Regexp.union(
      /\A127#{valid_ipv4_octet}{3}\z/,                          # localhost IPv4 range 127.x.x.x, per RFC-3330
      /\A::1\z/,                                                # localhost IPv6 ::1
      /\Af[cd][0-9a-f]{2}(?::[0-9a-f]{0,4}){0,7}\z/i,           # private IPv6 range fc00 .. fdff
      /\A10#{valid_ipv4_octet}{3}\z/,                           # private IPv4 range 10.x.x.x
      /\A172\.(1[6-9]|2[0-9]|3[01])#{valid_ipv4_octet}{2}\z/,   # private IPv4 range 172.16.0.0 .. 172.31.255.255
      /\A192\.168#{valid_ipv4_octet}{2}\z/,                     # private IPv4 range 192.168.x.x
      /\Alocalhost\z|\Aunix(\z|:)/i,                            # localhost hostname, and unix domain sockets
    )

    self.ip_filter = lambda { |ip| trusted_proxies.match?(ip) }

    ALLOWED_SCHEMES = %w(https http wss ws).freeze

    def initialize(env)
      @env = env
      @params = nil
    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
        # This module is included at least in `ActionDispatch::Request`
        # The call to `super()` allows additional mixed-in initializers are called
        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'

      HTTP_FORWARDED          = 'HTTP_FORWARDED'

      # 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 specifying 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

      # 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
        get_header(SERVER_PORT)
      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(authority)
        end

        port || forwarded_port&.last || DEFAULT_PORTS[scheme] || server_port
      end

      def forwarded_for
        forwarded_priority.each do |type|
          case type
          when :forwarded
            if forwarded_for = get_http_forwarded(:for)
              return(forwarded_for.map! do |authority|
                split_authority(authority)[1]
              end)
            end
          when :x_forwarded
            if value = get_header(HTTP_X_FORWARDED_FOR)
              return(split_header(value).map do |authority|
                split_authority(wrap_ipv6(authority))[1]
              end)
            end
          end
        end

        nil
      end

      def forwarded_port
        forwarded_priority.each do |type|
          case type
          when :forwarded
            if forwarded = get_http_forwarded(:for)
              return(forwarded.map do |authority|
                split_authority(authority)[2]
              end.compact)
            end
          when :x_forwarded
            if value = get_header(HTTP_X_FORWARDED_PORT)
              return split_header(value).map(&:to_i)
            end
          end
        end

        nil
      end

      def forwarded_authority
        forwarded_priority.each do |type|
          case type
          when :forwarded
            if forwarded = get_http_forwarded(:host)
              return forwarded.last
            end
          when :x_forwarded
            if value = get_header(HTTP_X_FORWARDED_HOST)
              return wrap_ipv6(split_header(value).last)
            end
          end
        end

        nil
      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.last
        end

        if (forwarded_for = self.forwarded_for) && !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

        # 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 error = get_header(RACK_REQUEST_FORM_ERROR)
          raise error.class, error.message, cause: error.cause
        end

        begin
          rack_input = get_header(RACK_INPUT)

          # If the form hash was already memoized:
          if form_hash = get_header(RACK_REQUEST_FORM_HASH)
            # And it was memoized from the same input:
            if get_header(RACK_REQUEST_FORM_INPUT).equal?(rack_input)
              return form_hash
            end
          end

          # Otherwise, figure out how to parse the input:
          if rack_input.nil?
            set_header RACK_REQUEST_FORM_INPUT, nil
            set_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, '&')
            end

            set_header RACK_REQUEST_FORM_INPUT, get_header(RACK_INPUT)
            get_header RACK_REQUEST_FORM_HASH
          else
            set_header RACK_REQUEST_FORM_INPUT, get_header(RACK_INPUT)
            set_header(RACK_REQUEST_FORM_HASH, {})
          end
        rescue => error
          set_header(RACK_REQUEST_FORM_ERROR, error)
          raise
        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.
      #
      # <tt>env['rack.input']</tt> 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.
      #
      # <tt>env['rack.input']</tt> 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 <tt>request.params[key]</tt>
      def [](key)
        warn("Request#[] is deprecated and will be removed in a future version of Rack. Please use request.params[] instead", uplevel: 1)

        params[key.to_s]
      end

      # shortcut for <tt>request.params[key] = value</tt>
      #
      # 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)
        warn("Request#[]= is deprecated and will be removed in a future version of Rack. Please use request.params[]= instead", uplevel: 1)

        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(",").each(&:strip!).map do |part|
          attribute, parameters = part.split(";", 2).each(&:strip!)
          quality = 1.0
          if parameters and /\Aq=([\d.]+)/ =~ parameters
            quality = $1.to_f
          end
          [attribute, quality]
        end
      end

      # Get an array of values set in the RFC 7239 `Forwarded` request header.
      def get_http_forwarded(token)
        Utils.forwarded_values(get_header(HTTP_FORWARDED))&.[](token)
      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

      # ipv6 extracted from resolv stdlib, simplified
      # to remove numbered match group creation.
      ipv6 = Regexp.union(
        /(?:[0-9A-Fa-f]{1,4}:){7}
         [0-9A-Fa-f]{1,4}/x,
        /(?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)? ::
         (?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?/x,
        /(?:[0-9A-Fa-f]{1,4}:){6,6}
         \d+\.\d+\.\d+\.\d+/x,
        /(?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)? ::
         (?:[0-9A-Fa-f]{1,4}:)*
         \d+\.\d+\.\d+\.\d+/x,
        /[Ff][Ee]80
         (?::[0-9A-Fa-f]{1,4}){7}
         %[-0-9A-Za-z._~]+/x,
        /[Ff][Ee]80:
         (?:
           (?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)? ::
           (?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?
           |
           :(?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?
         )?
         :[0-9A-Fa-f]{1,4}%[-0-9A-Za-z._~]+/x)

      AUTHORITY = /
        \A
        (?<host>
          # Match IPv6 as a string of hex digits and colons in square brackets
          \[(?<address>#{ipv6})\]
          |
          # Match any other printable string (except square brackets) as a hostname
          (?<address>[[[:graph:]&&[^\[\]]]]*?)
        )
        (:(?<port>\d+))?
        \z
      /x

      private_constant :AUTHORITY

      def split_authority(authority)
        return [] if authority.nil?
        return [] unless match = AUTHORITY.match(authority)
        return match[:host], match[:address], match[:port]&.to_i
      end

      def reject_trusted_ip_addresses(ip_addresses)
        ip_addresses.reject { |ip| trusted_proxy?(ip) }
      end

      FORWARDED_SCHEME_HEADERS = {
        proto: HTTP_X_FORWARDED_PROTO,
        scheme: HTTP_X_FORWARDED_SCHEME
      }.freeze
      private_constant :FORWARDED_SCHEME_HEADERS
      def forwarded_scheme
        forwarded_priority.each do |type|
          case type
          when :forwarded
            if (forwarded_proto = get_http_forwarded(:proto)) &&
               (scheme = allowed_scheme(forwarded_proto.last))
              return scheme
            end
          when :x_forwarded
            x_forwarded_proto_priority.each do |x_type|
              if header = FORWARDED_SCHEME_HEADERS[x_type]
                split_header(get_header(header)).reverse_each do |scheme|
                  if allowed_scheme(scheme)
                    return scheme
                  end
                end
              end
            end
          end
        end

        nil
      end

      def allowed_scheme(header)
        header if ALLOWED_SCHEMES.include?(header)
      end

      def forwarded_priority
        Request.forwarded_priority
      end

      def x_forwarded_proto_priority
        Request.x_forwarded_proto_priority
      end
    end

    include Env
    include Helpers
  end
end

# :nocov:
require_relative 'multipart' unless defined?(Rack::Multipart)
# :nocov:
# frozen_string_literal: true

require 'time'

require_relative 'constants'
require_relative 'utils'
require_relative 'head'
require_relative 'mime'
require_relative 'files'

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 = "<tr><td class='name'><a href='%s'>%s</a></td><td class='size'>%s</td><td class='type'>%s</td><td class='mtime'>%s</td></tr>\n"
    DIR_PAGE_HEADER = <<-PAGE
<html><head>
  <title>%s</title>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <style type='text/css'>
table { width:100%%; }
.name { text-align:left; }
.size, .mtime { text-align:right; }
.type { width:11em; }
.mtime { width:15em; }
  </style>
</head><body>
<h1>%s</h1>
<hr />
<table>
  <tr>
    <th class='name'>Name</th>
    <th class='size'>Size</th>
    <th class='type'>Type</th>
    <th class='mtime'>Last Modified</th>
  </tr>
    PAGE
    DIR_PAGE_FOOTER = <<-PAGE
</table>
<hr />
</body></html>
    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
# frozen_string_literal: true

require 'logger'

require_relative 'constants'

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
# frozen_string_literal: true

require_relative 'constants'
require_relative 'request'
require_relative 'utils'

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] if req.form_data? || req.parseable_data?
    rescue Utils::InvalidParameterError, Utils::ParameterTypeError, QueryParser::ParamsTooDeepError
      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
# frozen_string_literal: true

# Copyright (C) 2007-2019 Leah Neukirchen <http://leahneukirchen.org/infopage.html>
#
# 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 <tt>autoload</tt>ed here,
# so it should be enough just to <tt>require 'rack'</tt> in your code.

module Rack
  # The Rack protocol version number implemented.
  VERSION = [1, 3].freeze
  deprecate_constant :VERSION

  VERSION_STRING = "1.3".freeze
  deprecate_constant :VERSION_STRING

  # The Rack protocol version number implemented.
  def self.version
    warn "Rack.version is deprecated and will be removed in Rack 3.1!", uplevel: 1
    VERSION
  end

  RELEASE = "3.0.8"

  # Return the Rack release as a dotted string.
  def self.release
    RELEASE
  end
end
# frozen_string_literal: true

require 'uri'

require_relative 'constants'

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
  # <tt>rack['rack.recursive.include'][...]</tt> 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
# frozen_string_literal: true

# Copyright (C) 2009-2018 Michael Fellinger <m.fellinger@gmail.com>
# 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
    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
# frozen_string_literal: true

# Copyright (C) 2007-2019 Leah Neukirchen <http://leahneukirchen.org/infopage.html>
#
# 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 <tt>autoload</tt>ed here,
# so it should be enough just to <tt>require 'rack'</tt> in your code.

require_relative 'rack/version'
require_relative 'rack/constants'

module Rack
  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 :Headers, "rack/headers"
  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 :QueryParser, "rack/query_parser"
  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_request"
  autoload :MockResponse, "rack/mock_response"

  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"
    autoload :Digest, "rack/auth/digest"
  end
end
# ![Rack](contrib/logo.webp)

> **_NOTE:_** Rack v3.0.0 was recently released. Please check the [Upgrade
> Guide](UPGRADE-GUIDE.md) for more details about migrating your existing
> servers, middlewares and applications. For detailed information on specific
> changes, check the [Change Log](CHANGELOG.md).

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 bridge between web servers, web
frameworks, and web application into a single method call.

The exact details of this are described in the [Rack Specification], which all
Rack applications should conform to.

## Installation

Add the rack gem to your application bundle, or follow the instructions provided
by a [supported web framework](#supported-web-frameworks):

```bash
# Install it generally:
$ gem install rack --pre

# or, add it to your current application gemfile:
$ bundle add rack --version 3.0.0
```

If you need features from `Rack::Session` or `bin/rackup` please add those gems separately.

```bash
$ gem install rack-session rackup
```

## Usage

Create a file called `config.ru` with the following contents:

```ruby
run do |env|
  [200, {}, ["Hello World"]]
end
```

Run this using the rackup gem or another [supported web
server](#supported-web-servers).

```bash
$ gem install rackup
$ rackup
$ curl http://localhost:9292
Hello World
```

## Supported web servers

Rack is supported by a wide range of servers, including:

* [Agoo](https://github.com/ohler55/agoo)
* [Falcon](https://github.com/socketry/falcon) **(Rack 3 Compatible)**
* [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/)
* [Thin](https://github.com/macournoyer/thin)
* [Unicorn](https://yhbt.net/unicorn/)
* [uWSGI](https://uwsgi-docs.readthedocs.io/en/latest/)
* [Lamby](https://lamby.custominktech.com) (for AWS Lambda)

You will need to consult the server documentation to find out what features and
limitations they may have. In general, any valid Rack app will run the same on
all these servers, without changing anything.

### Rackup

Rack provides a separate gem, [rackup](https://github.com/rack/rackup) which is
a generic interface for running a Rack application on supported servers, which
include `WEBRick`, `Puma`, `Falcon` and others.

## Supported web frameworks

These frameworks and many others support the [Rack Specification]:

* [Camping](https://github.com/camping/camping)
* [Hanami](https://hanamirb.org/)
* [Padrino](https://padrinorb.com/)
* [Roda](https://github.com/jeremyevans/roda) **(Rack 3 Compatible)**
* [Ruby on Rails](https://rubyonrails.org/)
* [Sinatra](https://sinatrarb.com/)
* [Utopia](https://github.com/socketry/utopia) **(Rack 3 Compatible)**
* [WABuR](https://github.com/ohler55/wabur)

### Older (possibly unsupported) web frameworks

* [Ramaze](http://ramaze.net/)
* [Rum](https://github.com/leahneukirchen/rum)

## 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::CommonLogger` for creating Apache-style logfiles.
* `Rack::ConditionalGet` for returning [Not
  Modified](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304)
  responses when the response has not changed.
* `Rack::Config` for modifying the environment before processing the request.
* `Rack::ContentLength` for setting a `content-length` header based on body
  size.
* `Rack::ContentType` for setting a default `content-type` header for responses.
* `Rack::Deflater` for compressing responses with gzip.
* `Rack::ETag` for setting `etag` header on bodies that can be buffered.
* `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 Specification].
* `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 interfaces

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.

## Configuration

Rack exposes several configuration parameters to control various features of the
implementation.

### `param_depth_limit`

```ruby
Rack::Utils.param_depth_limit = 32 # default
```

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.

### `multipart_file_limit`

```ruby
Rack::Utils.multipart_file_limit = 128 # default
```

The maximum number of parts with a filename a request can contain. Accepting
too many parts 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_FILE_LIMIT` environment variable.

(This is also aliased as `multipart_part_limit` and `RACK_MULTIPART_PART_LIMIT` for compatibility)


### `multipart_total_part_limit`

The maximum total number of parts a request can contain of any type, including
both file and non-file form fields.

The default is 4096, which means that a single request can't contain more than
4096 parts.

Set to 0 for no limit.

Can also be set via the `RACK_MULTIPART_TOTAL_PART_LIMIT` environment variable.


## Changelog

See [CHANGELOG.md](CHANGELOG.md).

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md) for specific details about how to make a
contribution to Rack.

Please post bugs, suggestions and patches to [GitHub
Issues](https://github.com/rack/rack/issues).

Please check our [Security Policy](https://github.com/rack/rack/security/policy)
for responsible disclosure and security bug reporting process. 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.

## See Also

### `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

### `rack-session`

Provides convenient session management for Rack.

* https://github.com/rack/rack-session

## 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.

## License

Rack is released under the [MIT License](MIT-LICENSE).

[Rack Specification]: SPEC.rdoc
source "https://rubygems.org"

gemspec

group :development do
  gem "bundler"
  gem "minitest"
  gem "coveralls"
  gem "rubocop"
end
Copyright (c) Jim Weirich

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.

# Rakefile for rake        -*- ruby -*-

# Copyright 2003, 2004, 2005 by Jim Weirich (jim@weirichhouse.org)
# All rights reserved.

# This file may be distributed under an MIT style license.  See
# MIT-LICENSE for details.

lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)

begin
  require "bundler/gem_tasks"
rescue LoadError
end

require "rake/testtask"
Rake::TestTask.new(:test) do |t|
  t.libs << "test"
  t.verbose = true
  t.test_files = FileList["test/**/test_*.rb"]
end

require "rdoc/task"
RDoc::Task.new do |doc|
  doc.main   = "README.rdoc"
  doc.title  = "Rake -- Ruby Make"
  doc.rdoc_files = FileList.new %w[lib MIT-LICENSE doc/**/*.rdoc *.rdoc]
  doc.rdoc_dir = "html"
end

task ghpages: :rdoc do
  %x[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

task default: :test
= Why rake?

Ok, let me state from the beginning that I never intended to write this
code.  I'm not convinced it is useful, and I'm not convinced anyone
would even be interested in it.  All I can say is that Why's onion truck
must by been passing through the Ohio valley.

What am I talking about? ... A Ruby version of Make.

See, I can sense you cringing already, and I agree.  The world certainly
doesn't need yet another reworking of the "make" program.  I mean, we
already have "ant".  Isn't that enough?

It started yesterday.  I was helping a coworker fix a problem in one of
the Makefiles we use in our project.  Not a particularly tough problem,
but during the course of the conversation I began lamenting some of the
shortcomings of make.  In particular, in one of my makefiles I wanted to
determine the name of a file dynamically and had to resort to some
simple scripting (in Ruby) to make it work.  "Wouldn't it be nice if you
could just use Ruby inside a Makefile" I said.

My coworker (a recent convert to Ruby) agreed, but wondered what it
would look like.  So I sketched the following on the whiteboard...

    "What if you could specify the make tasks in Ruby, like this ..."

      task "build" do
        java_compile(...args, etc ...)
      end

    "The task function would register "build" as a target to be made,
    and the block would be the action executed whenever the build
    system determined that it was time to do the build target."

We agreed that would be cool, but writing make from scratch would be WAY
too much work.  And that was the end of that!

... Except I couldn't get the thought out of my head.  What exactly
would be needed to make the about syntax work as a make file?  Hmmm, you
would need to register the tasks, you need some way of specifying
dependencies between tasks, and some way of kicking off the process.
Hey!  What if we did ... and fifteen minutes later I had a working
prototype of Ruby make, complete with dependencies and actions.

I showed the code to my coworker and we had a good laugh.  It was just
about a page worth of code that reproduced an amazing amount of the
functionality of make.  We were both truly stunned with the power of
Ruby.

But it didn't do everything make did.  In particular, it didn't have
timestamp based file dependencies (where a file is rebuilt if any of its
prerequisite files have a later timestamp).  Obviously THAT would be a
pain to add and so Ruby Make would remain an interesting experiment.

... Except as I walked back to my desk, I started thinking about what
file based dependencies would really need.  Rats!  I was hooked again,
and by adding a new class and two new methods, file/timestamp
dependencies were implemented.

Ok, now I was really hooked.  Last night (during CSI!) I massaged the
code and cleaned it up a bit.  The result is a bare-bones replacement
for make in exactly 100 lines of code.

For the curious, you can see it at ...
* doc/proto_rake.rdoc

Oh, about the name.  When I wrote the example Ruby Make task on my
whiteboard, my coworker exclaimed "Oh! I have the perfect name: Rake ...
Get it?  Ruby-Make. Rake!"  He said he envisioned the tasks as leaves
and Rake would clean them up  ... or something like that.  Anyways, the
name stuck.

Some quick examples ...

A simple task to delete backup files ...

   task :clean do
     Dir['*~'].each {|fn| rm fn rescue nil}
   end

Note that task names are symbols (they are slightly easier to type
than quoted strings ... but you may use quoted string if you would
rather). Rake makes the methods of the FileUtils module directly
available, so we take advantage of the <tt>rm</tt> command.  Also note
the use of "rescue nil" to trap and ignore errors in the <tt>rm</tt>
command.

To run it, just type "rake clean".  Rake will automatically find a
Rakefile in the current directory (or above!) and will invoke the
targets named on the command line.  If there are no targets explicitly
named, rake will invoke the task "default".

Here's another task with dependencies ...

   task :clobber => [:clean] do
     rm_r "tempdir"
   end

Task :clobber depends upon task :clean, so :clean will be run before
:clobber is executed.

Files are specified by using the "file" command.  It is similar to the
task command, except that the task name represents a file, and the task
will be run only if the file doesn't exist, or if its modification time
is earlier than any of its prerequisites.

Here is a file based dependency that will compile "hello.cc" to
"hello.o".

   file "hello.cc"
   file "hello.o" => ["hello.cc"] do |t|
     srcfile = t.name.sub(/\.o$/, ".cc")
     sh %{g++ #{srcfile} -c -o #{t.name}}
   end

I normally specify file tasks with string (rather than symbols).  Some
file names can't be represented by symbols.  Plus it makes the
distinction between them more clear to the casual reader.

Currently writing a task for each and every file in the project would be
tedious at best.  I envision a set of libraries to make this job
easier.  For instance, perhaps something like this ...

   require 'rake/ctools'
   Dir['*.c'].each do |fn|
     c_source_file(fn)
   end

where "c_source_file" will create all the tasks need to compile all the
C source files in a directory.  Any number of useful libraries could be
created for rake.

That's it.  There's no documentation (other than whats in this
message).  Does this sound interesting to anyone?  If so, I'll continue
to clean it up and write it up and publish it on RAA.  Otherwise, I'll
leave it as an interesting exercise and a tribute to the power of Ruby.

Why /might/ rake be interesting to Ruby programmers.  I don't know,
perhaps ...

* No weird make syntax (only weird Ruby syntax :-)
* No need to edit or read XML (a la ant)
* Platform independent build scripts.
* Will run anywhere Ruby exists, so no need to have "make" installed.
  If you stay away from the "sys" command and use things like
  'ftools', you can have a perfectly platform independent
  build script.  Also rake is only 100 lines of code, so it can
  easily be packaged along with the rest of your code.

So ... Sorry for the long rambling message.  Like I said, I never
intended to write this code at all.
= Original Prototype Rake

This is the original 100 line prototype rake program.

---
 #!/opt/alt/ruby30/bin/ruby

 require 'ftools'

 class Task
   TASKS = Hash.new

   attr_reader :prerequisites

   def initialize(task_name)
     @name = task_name
     @prerequisites = []
     @actions = []
   end

   def enhance(deps=nil, &block)
     @prerequisites |= deps if deps
     @actions << block if block_given?
     self
   end

   def name
     @name.to_s
   end

   def invoke
     @prerequisites.each { |n| Task[n].invoke }
     execute if needed?
   end

   def execute
     return if @triggered
     @triggered = true
     @actions.collect { |act| result = act.call(self) }.last
   end

   def needed?
     true
   end

   def timestamp
     Time.now
   end

   class << self
     def [](task_name)
       TASKS[intern(task_name)] or fail "Don't know how to rake #{task_name}"
     end

     def define_task(args, &block)
       case args
       when Hash
 	fail "Too Many Target Names: #{args.keys.join(' ')}" if args.size > 1
 	fail "No Task Name Given" if args.size < 1
 	task_name = args.keys[0]
 	deps = args[task_name]
       else
 	task_name = args
 	deps = []
       end
       deps = deps.collect {|d| intern(d) }
       get(task_name).enhance(deps, &block)
     end

     def get(task_name)
       name = intern(task_name)
       TASKS[name] ||= self.new(name)
     end

     def intern(task_name)
       (Symbol === task_name) ? task_name : task_name.intern
     end
   end
 end

 class FileTask < Task
   def needed?
     return true unless File.exist?(name)
     latest_prereq = @prerequisites.collect{|n| Task[n].timestamp}.max
     return false if latest_prereq.nil?
     timestamp < latest_prereq
   end

   def timestamp
     File.new(name.to_s).mtime
   end
 end

 def task(args, &block)
   Task.define_task(args, &block)
 end

 def file(args, &block)
   FileTask.define_task(args, &block)
 end

 def sys(cmd)
   puts cmd
   system(cmd) or fail "Command Failed: [#{cmd}]"
 end

 def rake
   begin
     here = Dir.pwd
     while ! File.exist?("Rakefile")
       Dir.chdir("..")
       fail "No Rakefile found" if Dir.pwd == here
       here = Dir.pwd
     end
     puts "(in #{Dir.pwd})"
     load "./Rakefile"
     ARGV.push("default") if ARGV.size == 0
     ARGV.each { |task_name| Task[task_name].invoke }
   rescue Exception => ex
     puts "rake aborted ... #{ex.message}"
     puts ex.backtrace.find {|str| str =~ /Rakefile/ } || ""
   end
 end

 if __FILE__ == $0 then
   rake
 end
= Glossary

action ::
  Code to be executed in order to perform a task.  Actions in a Rakefile are
  specified in a code block. (Usually delimited by +do+/+end+ pairs.)

execute ::
  When a task is executed, all of its actions are performed in the order they
  were defined.  Note that, unlike <tt>invoke</tt>, <tt>execute</tt> always
  executes the actions (without invoking or executing the prerequisites).

file task (Rake::FileTask) ::
  A file task is a task whose purpose is to create a file (which has the same
  name as the task).  When invoked, a file task will only execute if one or
  more of the following conditions are true.

  1. The associated file does not exist.
  2. A prerequisite has a later time stamp than the existing file.

  Because normal Tasks always have the current time as timestamp, a FileTask
  that has a normal Task prerequisite will always execute.

invoke ::
  When a task is invoked, first we check to see if it has been invoked before.
  If it has been, then nothing else is done.  If this is the first time it has
  been invoked, then we invoke each of its prerequisites.  Finally, we check
  to see if we need to execute the actions of this task by calling
  Rake::Task#needed?.  If the task is needed, we execute its actions.

  NOTE: Prerequisites are still invoked even if the task is not needed.

prerequisites ::
  Every task has a (possibly empty) set of prerequisites.  A prerequisite P to
  Task T is itself a task that must be invoked before Task T.

rule ::
  A rule is a recipe for synthesizing a task when no task is explicitly
  defined.  Rules generally synthesize file tasks.

task (Rake::Task) ::
  The basic unit of work in a Rakefile.  A task has a name, a set of 
  prerequisites, and a list of actions to be performed.
# frozen_string_literal: true
module RDoc
module Page

FONTS = "\"Bitstream Vera Sans\", Verdana, Arial, Helvetica, sans-serif"

STYLE = <<CSS
a {
  color: #00F;
  text-decoration: none;
}

a:hover {
  color: #77F;
  text-decoration: underline;
}

body, td, p {
  font-family: %fonts%;
  background: #FFF;
  color: #000;
  margin: 0px;
  font-size: small;
}

#content {
  margin: 2em;
}

#description p {
  margin-bottom: 0.5em;
}

.sectiontitle {
  margin-top: 1em;
  margin-bottom: 1em;
  padding: 0.5em;
  padding-left: 2em;
  background: #005;
  color: #FFF;
  font-weight: bold;
  border: 1px dotted black;
}

.attr-rw {
  padding-left: 1em;
  padding-right: 1em;
  text-align: center;
  color: #055;
}

.attr-name {
  font-weight: bold;
}

.attr-desc {
}

.attr-value {
  font-family: monospace;
}

.file-title-prefix {
  font-size: large;
}

.file-title {
  font-size: large;
  font-weight: bold;
  background: #005;
  color: #FFF;
}

.banner {
  background: #005;
  color: #FFF;
  border: 1px solid black;
  padding: 1em;
}

.banner td {
  background: transparent;
  color: #FFF;
}

h1 a, h2 a, .sectiontitle a, .banner a {
  color: #FF0;
}

h1 a:hover, h2 a:hover, .sectiontitle a:hover, .banner a:hover {
  color: #FF7;
}

.dyn-source {
  display: none;
  background: #FFE;
  color: #000;
  border: 1px dotted black;
  margin: 0.5em 2em 0.5em 2em;
  padding: 0.5em;
}

.dyn-source .cmt {
  color: #00F;
  font-style: italic;
}

.dyn-source .kw {
  color: #070;
  font-weight: bold;
}

.method {
  margin-left: 1em;
  margin-right: 1em;
  margin-bottom: 1em;
}

.description pre {
  padding: 0.5em;
  border: 1px dotted black;
  background: #FFE;
}

.method .title {
  font-family: monospace;
  font-size: large;
  border-bottom: 1px dashed black;
  margin-bottom: 0.3em;
  padding-bottom: 0.1em;
}

.method .description, .method .sourcecode {
  margin-left: 1em;
}

.description p, .sourcecode p {
  margin-bottom: 0.5em;
}

.method .sourcecode p.source-link {
  text-indent: 0em;
  margin-top: 0.5em;
}

.method .aka {
  margin-top: 0.3em;
  margin-left: 1em;
  font-style: italic;
  text-indent: 2em;
}

h1 {
  padding: 1em;
  border: 1px solid black;
  font-size: x-large;
  font-weight: bold;
  color: #FFF;
  background: #007;
}

h2 {
  padding: 0.5em 1em 0.5em 1em;
  border: 1px solid black;
  font-size: large;
  font-weight: bold;
  color: #FFF;
  background: #009;
}

h3, h4, h5, h6 {
  padding: 0.2em 1em 0.2em 1em;
  border: 1px dashed black;
  color: #000;
  background: #AAF;
}

.sourcecode > pre {
  padding: 0.5em;
  border: 1px dotted black;
  background: #FFE;
}

CSS

XHTML_PREAMBLE = %{<?xml version="1.0" encoding="%charset%"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
}

HEADER = XHTML_PREAMBLE + <<ENDHEADER
<html>
  <head>
    <title>%title%</title>
    <meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
    <link rel="stylesheet" href="%style_url%" type="text/css" media="screen" />

    <script language="JavaScript" type="text/javascript">
    // <![CDATA[

        function toggleSource( id )
        {
          var elem
          var link

          if( document.getElementById )
          {
            elem = document.getElementById( id )
            link = document.getElementById( "l_" + id )
          }
          else if ( document.all )
          {
            elem = eval( "document.all." + id )
            link = eval( "document.all.l_" + id )
          }
          else
            return false;

          if( elem.style.display == "block" )
          {
            elem.style.display = "none"
            link.innerHTML = "show source"
          }
          else
          {
            elem.style.display = "block"
            link.innerHTML = "hide source"
          }
        }

        function openCode( url )
        {
          window.open( url, "SOURCE_CODE", "width=400,height=400,scrollbars=yes" )
        }
      // ]]>
    </script>
  </head>

  <body>
ENDHEADER

FILE_PAGE = <<HTML
<table border='0' cellpadding='0' cellspacing='0' width="100%" class='banner'>
  <tr><td>
    <table width="100%" border='0' cellpadding='0' cellspacing='0'><tr>
      <td class="file-title" colspan="2"><span class="file-title-prefix">File</span><br />%short_name%</td>
      <td align="right">
        <table border='0' cellspacing="0" cellpadding="2">
          <tr>
            <td>Path:</td>
            <td>%full_path%
IF:cvsurl
              &nbsp;(<a href="%cvsurl%">CVS</a>)
ENDIF:cvsurl
            </td>
          </tr>
          <tr>
            <td>Modified:</td>
            <td>%dtm_modified%</td>
          </tr>
        </table>
      </td></tr>
    </table>
  </td></tr>
</table><br>
HTML

###################################################################

CLASS_PAGE = <<HTML
<table width="100%" border='0' cellpadding='0' cellspacing='0' class='banner'><tr>
  <td class="file-title"><span class="file-title-prefix">%classmod%</span><br />%full_name%</td>
  <td align="right">
    <table cellspacing=0 cellpadding=2>
      <tr valign="top">
        <td>In:</td>
        <td>
START:infiles
HREF:full_path_url:full_path:
IF:cvsurl
&nbsp;(<a href="%cvsurl%">CVS</a>)
ENDIF:cvsurl
END:infiles
        </td>
      </tr>
IF:parent
    <tr>
      <td>Parent:</td>
      <td>
IF:par_url
        <a href="%par_url%">
ENDIF:par_url
%parent%
IF:par_url
         </a>
ENDIF:par_url
     </td>
   </tr>
ENDIF:parent
         </table>
        </td>
        </tr>
      </table>
HTML

###################################################################

METHOD_LIST = <<HTML
  <div id="content">
IF:diagram
  <table cellpadding='0' cellspacing='0' border='0' width="100%"><tr><td align="center">
    %diagram%
  </td></tr></table>
ENDIF:diagram

IF:description
  <div class="description">%description%</div>
ENDIF:description

IF:requires
  <div class="sectiontitle">Required Files</div>
  <ul>
START:requires
  <li>HREF:aref:name:</li>
END:requires
  </ul>
ENDIF:requires

IF:toc
  <div class="sectiontitle">Contents</div>
  <ul>
START:toc
  <li><a href="#%href%">%secname%</a></li>
END:toc
  </ul>
ENDIF:toc

IF:methods
  <div class="sectiontitle">Methods</div>
  <ul>
START:methods
  <li>HREF:aref:name:</li>
END:methods
  </ul>
ENDIF:methods

IF:includes
<div class="sectiontitle">Included Modules</div>
<ul>
START:includes
  <li>HREF:aref:name:</li>
END:includes
</ul>
ENDIF:includes

START:sections
IF:sectitle
<div class="sectiontitle"><a nem="%secsequence%">%sectitle%</a></div>
IF:seccomment
<div class="description">
%seccomment%
</div>
ENDIF:seccomment
ENDIF:sectitle

IF:classlist
  <div class="sectiontitle">Classes and Modules</div>
  %classlist%
ENDIF:classlist

IF:constants
  <div class="sectiontitle">Constants</div>
  <table border='0' cellpadding='5'>
START:constants
  <tr valign='top'>
    <td class="attr-name">%name%</td>
    <td>=</td>
    <td class="attr-value">%value%</td>
  </tr>
IF:desc
  <tr valign='top'>
    <td>&nbsp;</td>
    <td colspan="2" class="attr-desc">%desc%</td>
  </tr>
ENDIF:desc
END:constants
  </table>
ENDIF:constants

IF:attributes
  <div class="sectiontitle">Attributes</div>
  <table border='0' cellpadding='5'>
START:attributes
  <tr valign='top'>
    <td class='attr-rw'>
IF:rw
[%rw%]
ENDIF:rw
    </td>
    <td class='attr-name'>%name%</td>
    <td class='attr-desc'>%a_desc%</td>
  </tr>
END:attributes
  </table>
ENDIF:attributes

IF:method_list
START:method_list
IF:methods
<div class="sectiontitle">%type% %category% methods</div>
START:methods
<div class="method">
  <div class="title">
IF:callseq
    <a name="%aref%"></a><b>%callseq%</b>
ENDIF:callseq
IFNOT:callseq
    <a name="%aref%"></a><b>%name%</b>%params%
ENDIF:callseq
IF:codeurl
[ <a href="javascript:openCode('%codeurl%')">source</a> ]
ENDIF:codeurl
  </div>
IF:m_desc
  <div class="description">
  %m_desc%
  </div>
ENDIF:m_desc
IF:aka
<div class="aka">
  This method is also aliased as
START:aka
  <a href="%aref%">%name%</a>
END:aka
</div>
ENDIF:aka
IF:sourcecode
<div class="sourcecode">
  <p class="source-link">[ <a href="javascript:toggleSource('%aref%_source')" id="l_%aref%_source">show source</a> ]</p>
  <div id="%aref%_source" class="dyn-source">
<pre>
%sourcecode%
</pre>
  </div>
</div>
ENDIF:sourcecode
</div>
END:methods
ENDIF:methods
END:method_list
ENDIF:method_list
END:sections
</div>
HTML

FOOTER = <<ENDFOOTER
  </body>
</html>
ENDFOOTER

BODY = HEADER + <<ENDBODY
  !INCLUDE! <!-- banner header -->

  <div id="bodyContent">
    #{METHOD_LIST}
  </div>

  #{FOOTER}
ENDBODY

########################## Source code ##########################

SRC_PAGE = XHTML_PREAMBLE + <<HTML
<html>
<head><title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%">
<style>
.ruby-comment    { color: green; font-style: italic }
.ruby-constant   { color: #4433aa; font-weight: bold; }
.ruby-identifier { color: #222222;  }
.ruby-ivar       { color: #2233dd; }
.ruby-keyword    { color: #3333FF; font-weight: bold }
.ruby-node       { color: #777777; }
.ruby-operator   { color: #111111;  }
.ruby-regexp     { color: #662222; }
.ruby-value      { color: #662222; font-style: italic }
  .kw { color: #3333FF; font-weight: bold }
  .cmt { color: green; font-style: italic }
  .str { color: #662222; font-style: italic }
  .re  { color: #662222; }
</style>
</head>
<body bgcolor="white">
<pre>%code%</pre>
</body>
</html>
HTML

########################## Index ################################

FR_INDEX_BODY = <<HTML
!INCLUDE!
HTML

FILE_INDEX = XHTML_PREAMBLE + <<HTML
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%">
<style>
<!--
  body {
    background-color: #EEE;
    font-family: #{FONTS};
    color: #000;
    margin: 0px;
  }
  .banner {
    background: #005;
    color: #FFF;
    padding: 0.2em;
    font-size: small;
    font-weight: bold;
    text-align: center;
  }
  .entries {
    margin: 0.25em 1em 0 1em;
    font-size: x-small;
  }
  a {
    color: #00F;
    text-decoration: none;
    white-space: nowrap;
  }
  a:hover {
    color: #77F;
    text-decoration: underline;
  }
-->
</style>
<base target="docwin">
</head>
<body>
<div class="banner">%list_title%</div>
<div class="entries">
START:entries
<a href="%href%">%name%</a><br>
END:entries
</div>
</body></html>
HTML

CLASS_INDEX = FILE_INDEX
METHOD_INDEX = FILE_INDEX

INDEX = XHTML_PREAMBLE + <<HTML
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>%title%</title>
  <meta http-equiv="Content-Type" content="text/html; charset=%charset%">
</head>

<frameset cols="20%,*">
    <frameset rows="15%,35%,50%">
        <frame src="fr_file_index.html"   title="Files" name="Files" />
        <frame src="fr_class_index.html"  name="Classes" />
        <frame src="fr_method_index.html" name="Methods" />
    </frameset>
IF:inline_source
      <frame  src="%initial_page%" name="docwin">
ENDIF:inline_source
IFNOT:inline_source
    <frameset rows="80%,20%">
      <frame  src="%initial_page%" name="docwin">
      <frame  src="blank.html" name="source">
    </frameset>
ENDIF:inline_source
    <noframes>
          <body bgcolor="white">
            Click <a href="html/index.html">here</a> for a non-frames
            version of this page.
          </body>
    </noframes>
</frameset>

</html>
HTML

end
end


= Rakefile Format

First of all, there is no special format for a Rakefile.  A Rakefile
contains executable Ruby code.  Anything legal in a ruby script is
allowed in a Rakefile.

Now that we understand there is no special syntax in a Rakefile, there
are some conventions that are used in a Rakefile that are a little
unusual in a typical Ruby program.  Since a Rakefile is tailored to
specifying tasks and actions, the idioms used in a Rakefile are
designed to support that.

So, what goes into a Rakefile?

== Tasks

Tasks are the main unit of work in a Rakefile.  Tasks have a name
(usually given as a symbol or a string), a list of prerequisites (more
symbols or strings) and a list of actions (given as a block).

=== Simple Tasks

A task is declared by using the +task+ method.  +task+ takes a single
parameter that is the name of the task.

  task :name

=== Tasks with Prerequisites

Any prerequisites are given as a list (enclosed in square brackets)
following the name and an arrow (=>).

  task name: [:prereq1, :prereq2]

*NOTE:* Although this syntax looks a little funky, it is legal
Ruby.  We are constructing a hash where the key is :name and the value
for that key is the list of prerequisites.  It is equivalent to the
following ...

  hash = Hash.new
  hash[:name] = [:prereq1, :prereq2]
  task(hash)

You can also use strings for task names and prerequisites, rake doesn't care.
This is the same task definition:

  task 'name' => %w[prereq1 prereq2]

As is this:

  task name: %w[prereq1 prereq2]

We'll prefer this style for regular tasks with prerequisites throughout the
rest of the document.  Using an array of strings for the prerequisites means
you will need to make fewer changes if you need to move tasks into namespaces
or perform other refactorings.

=== Tasks with Actions

Actions are defined by passing a block to the +task+ method.  Any Ruby
code can be placed in the block.  The block may reference the task
object via the block parameter.

  task name: [:prereq1, :prereq2] do |t|
    # actions (may reference t)
  end

=== Multiple Definitions

A task may be specified more than once.  Each specification adds its
prerequisites and actions to the existing definition.  This allows one
part of a rakefile to specify the actions and a different rakefile
(perhaps separately generated) to specify the dependencies.

For example, the following is equivalent to the single task
specification given above.

  task :name
  task name: :prereq1
  task name: %w[prereq2]
  task :name do |t|
    # actions
  end

== File Tasks

Some tasks are designed to create a file from one or more other files.
Tasks that generate these files may be skipped if the file already
exists.  File tasks are used to specify file creation tasks.

File tasks are declared using the +file+ method (instead of the +task+
method).  In addition, file tasks are usually named with a string
rather than a symbol.

The following file task creates a executable program (named +prog+)
given two object files named +a.o+ and +b.o+.  The tasks
for creating +a.o+ and +b.o+ are not shown.

  file "prog" => ["a.o", "b.o"] do |t|
    sh "cc -o #{t.name} #{t.prerequisites.join(' ')}"
  end

== Directory Tasks

It is common to need to create directories upon demand.  The
+directory+ convenience method is a short-hand for creating a FileTask
that creates the directory.  For example, the following declaration
...

  directory "testdata/examples/doc"

is equivalent to ...

  file "testdata" do |t| mkdir t.name end
  file "testdata/examples" => ["testdata"] do |t| mkdir t.name end
  file "testdata/examples/doc" => ["testdata/examples"] do |t| mkdir t.name end

The +directory+ method does not accept prerequisites or actions, but
both prerequisites and actions can be added later.  For example ...

  directory "testdata"
  file "testdata" => ["otherdata"]
  file "testdata" do
    cp Dir["standard_data/*.data"], "testdata"
  end

== Tasks with Parallel Prerequisites

Rake allows parallel execution of prerequisites using the following syntax:

  multitask copy_files: %w[copy_src copy_doc copy_bin] do
    puts "All Copies Complete"
  end

In this example, +copy_files+ is a normal rake task.  Its actions are
executed whenever all of its prerequisites are done.  The big
difference is that the prerequisites (+copy_src+, +copy_bin+ and
+copy_doc+) are executed in parallel.  Each of the prerequisites are
run in their own Ruby thread, possibly allowing faster overall runtime.

=== Secondary Prerequisites

If any of the primary prerequisites of a multitask have common secondary
prerequisites, all of the primary/parallel prerequisites will wait
until the common prerequisites have been run.

For example, if the <tt>copy_<em>xxx</em></tt> tasks have the
following prerequisites:

  task copy_src: :prep_for_copy
  task copy_bin: :prep_for_copy
  task copy_doc: :prep_for_copy

Then the +prep_for_copy+ task is run before starting all the copies in
parallel.  Once +prep_for_copy+ is complete, +copy_src+, +copy_bin+,
and +copy_doc+ are all run in parallel.  Note that +prep_for_copy+ is
run only once, even though it is referenced in multiple threads.

=== Thread Safety

The Rake internal data structures are thread-safe with respect
to the multitask parallel execution, so there is no need for the user
to do extra synchronization for Rake's benefit.  However, if there are
user data structures shared between the parallel prerequisites, the
user must do whatever is necessary to prevent race conditions.

== Tasks with Arguments

Prior to version 0.8.0, rake was only able to handle command line
arguments of the form NAME=VALUE that were passed into Rake via the
ENV hash.  Many folks had asked for some kind of simple command line
arguments, perhaps using "--" to separate regular task names from
argument values on the command line.  The problem is that there was no
easy way to associate positional arguments on the command line with
different tasks.  Suppose both tasks :a and :b expect a command line
argument: does the first value go with :a?  What if :b is run first?
Should it then get the first command line argument.

Rake 0.8.0 solves this problem by explicitly passing values directly
to the tasks that need them.  For example, if I had a release task
that required a version number, I could say:

   rake release[0.8.2]

And the string "0.8.2" will be passed to the :release task.  Multiple
arguments can be passed by separating them with a comma, for example:

   rake name[john,doe]

Just a few words of caution.  The rake task name and its arguments
need to be a single command line argument to rake.  This generally
means no spaces.  If spaces are needed, then the entire name +
argument string should be quoted.  Something like this:

   rake "name[billy bob, smith]"

(Quoting rules vary between operating systems and shells, so make sure
you consult the proper docs for your OS/shell).

=== Tasks that Expect Parameters

Parameters are only given to tasks that are setup to expect them.  In
order to handle named parameters, the task declaration syntax for
tasks has been extended slightly.

For example, a task that needs a first name and last name might be
declared as:

   task :name, [:first_name, :last_name]

The first argument is still the name of the task (:name in this case).
The next two arguments are the names of the parameters expected by
:name in an array (:first_name and :last_name in the example).

To access the values of the parameters, the block defining the task
behaviour can now accept a second parameter:

   task :name, [:first_name, :last_name] do |t, args|
     puts "First name is #{args.first_name}"
     puts "Last  name is #{args.last_name}"
   end

The first argument of the block "t" is always bound to the current
task object.  The second argument "args" is an open-struct like object
that allows access to the task arguments.  Extra command line
arguments to a task are ignored.

If you wish to specify default values for the arguments, you can use
the with_defaults method in the task body.  Here is the above example
where we specify default values for the first and last names:

   task :name, [:first_name, :last_name] do |t, args|
     args.with_defaults(:first_name => "John", :last_name => "Dough")
     puts "First name is #{args.first_name}"
     puts "Last  name is #{args.last_name}"
   end

=== Tasks that Expect Parameters and Have Prerequisites

Tasks that use parameters have a slightly different format for
prerequisites.  Use the arrow notation to indicate the prerequisites
for tasks with arguments.  For example:

   task :name, [:first_name, :last_name] => [:pre_name] do |t, args|
     args.with_defaults(:first_name => "John", :last_name => "Dough")
     puts "First name is #{args.first_name}"
     puts "Last  name is #{args.last_name}"
   end

=== Tasks that take Variable-length Parameters

Tasks that need to handle a list of values as a parameter can use the
extras method of the args variable.  This allows for tasks that can
loop over a variable number of values, and its compatible with named
parameters as well:

   task :email, [:message] do |t, args|
     mail = Mail.new(args.message)
     recipients = args.extras
     recipients.each do |target|
       mail.send_to(target)
     end
   end

There is also the convenience method to_a that returns all parameters
in the sequential order they were given, including those associated
with named parameters.

=== Deprecated Task Parameters Format

There is an older format for declaring task parameters that omitted
the task argument array and used the :needs keyword to introduce the
dependencies.  That format is still supported for compatibility, but
is not recommended for use.  The older format may be dropped in future
versions of rake.

== Accessing Task Programmatically

Sometimes it is useful to manipulate tasks programmatically in a
Rakefile. To find a task object use Rake::Task.[].

=== Programmatic Task Example

For example, the following Rakefile defines two tasks.  The :doit task
simply prints a simple "DONE" message.  The :dont class will lookup
the doit class and remove (clear) all of its prerequisites and
actions.

   task :doit do
     puts "DONE"
   end

   task :dont do
     Rake::Task[:doit].clear
   end

Running this example:

  $ rake doit
  (in /Users/jim/working/git/rake/x)
  DONE
  $ rake dont doit
  (in /Users/jim/working/git/rake/x)
  $

The ability to programmatically manipulate tasks gives rake very
powerful meta-programming capabilities w.r.t. task execution, but
should be used with caution.

== Rules

When a file is named as a prerequisite, but does not have a file task
defined for it, Rake will attempt to synthesize a task by looking at a
list of rules supplied in the Rakefile.

Suppose we were trying to invoke task "mycode.o", but no task is
defined for it.  But the rakefile has a rule that look like this ...

  rule '.o' => ['.c'] do |t|
    sh "cc #{t.source} -c -o #{t.name}"
  end

This rule will synthesize any task that ends in ".o".  It has a
prerequisite a source file with an extension of ".c" must exist.  If
Rake is able to find a file named "mycode.c", it will automatically
create a task that builds "mycode.o" from "mycode.c".

If the file "mycode.c" does not exist, rake will attempt
to recursively synthesize a rule for it.

When a task is synthesized from a rule, the +source+ attribute of the
task is set to the matching source file.  This allows us to write
rules with actions that reference the source file.

=== Advanced Rules

Any regular expression may be used as the rule pattern.  Additionally,
a proc may be used to calculate the name of the source file.  This
allows for complex patterns and sources.

The following rule is equivalent to the example above.

  rule( /\.o$/ => [
    proc {|task_name| task_name.sub(/\.[^.]+$/, '.c') }
  ]) do |t|
    sh "cc #{t.source} -c -o #{t.name}"
  end

*NOTE:* Because of a _quirk_ in Ruby syntax, parenthesis are
required on *rule* when the first argument is a regular expression.

The following rule might be used for Java files ...

  rule '.class' => [
    proc { |tn| tn.sub(/\.class$/, '.java').sub(/^classes\//, 'src/') }
  ] do |t|
    java_compile(t.source, t.name)
  end

*NOTE:* +java_compile+ is a hypothetical method that invokes the
java compiler.

== Importing Dependencies

Any ruby file (including other rakefiles) can be included with a
standard Ruby +require+ command.  The rules and declarations in the
required file are just added to the definitions already accumulated.

Because the files are loaded _before_ the rake targets are evaluated,
the loaded files must be "ready to go" when the rake command is
invoked. This makes generated dependency files difficult to use. By
the time rake gets around to updating the dependencies file, it is too
late to load it.

The +import+ command addresses this by specifying a file to be loaded
_after_ the main rakefile is loaded, but _before_ any targets on the
command line are invoked. In addition, if the file name matches an
explicit task, that task is invoked before loading the file. This
allows dependency files to be generated and used in a single rake
command invocation.

Example:

  require 'rake/loaders/makefile'

  file ".depends.mf" => [SRC_LIST] do |t|
    sh "makedepend -f- -- #{CFLAGS} -- #{t.prerequisites} > #{t.name}"
  end

  import ".depends.mf"

If ".depends" does not exist, or is out of date w.r.t. the source
files, a new ".depends" file is generated using +makedepend+ before
loading.

== Comments

Standard Ruby comments (beginning with "#") can be used anywhere it is
legal in Ruby source code, including comments for tasks and rules.
However, if you wish a task to be described using the "-T" switch,
then you need to use the +desc+ command to describe the task.

Example:

  desc "Create a distribution package"
  task package: %w[ ... ] do ... end

The "-T" switch (or "--tasks" if you like to spell things out) will
display a list of tasks that have a description.  If you use +desc+ to
describe your major tasks, you have a semi-automatic way of generating
a summary of your Rake file.

  $ rake -T
  (in /home/.../rake)
  rake clean            # Remove any temporary products.
  rake clobber          # Remove any generated file.
  rake clobber_rdoc     # Remove rdoc products
  rake contrib_test     # Run tests for contrib_test
  rake default          # Default Task
  rake install          # Install the application
  rake lines            # Count lines in the main rake file
  rake rdoc             # Build the rdoc HTML Files
  rake rerdoc           # Force a rebuild of the RDOC files
  rake test             # Run tests
  rake testall          # Run all test targets

Only tasks with descriptions will be displayed with the "-T" switch.
Use "-P" (or "--prereqs") to get a list of all tasks and their
prerequisites.

== Namespaces

As projects grow (and along with it, the number of tasks), it is
common for task names to begin to clash.  For example, if you might
have a main program and a set of sample programs built by a single
Rakefile.  By placing the tasks related to the main program in one
namespace, and the tasks for building the sample programs in a
different namespace, the task names will not interfere with each other.

For example:

  namespace "main" do
    task :build do
      # Build the main program
    end
  end

  namespace "samples" do
    task :build do
      # Build the sample programs
    end
  end

  task build: %w[main:build samples:build]

Referencing a task in a separate namespace can be achieved by
prefixing the task name with the namespace and a colon
(e.g. "main:build" refers to the :build task in the +main+ namespace).
Nested namespaces are supported.

Note that the name given in the +task+ command is always the unadorned
task name without any namespace prefixes.  The +task+ command always
defines a task in the current namespace.

=== FileTasks

File task names are not scoped by the namespace command.  Since the
name of a file task is the name of an actual file in the file system,
it makes little sense to include file task names in name space.
Directory tasks (created by the +directory+ command) are a type of
file task and are also not affected by namespaces.

=== Name Resolution

When looking up a task name, rake will start with the current
namespace and attempt to find the name there.  If it fails to find a
name in the current namespace, it will search the parent namespaces
until a match is found (or an error occurs if there is no match).

The "rake" namespace is a special implicit namespace that refers to
the toplevel names.

If a task name begins with a "^" character, the name resolution will
start in the parent namespace.  Multiple "^" characters are allowed.

Here is an example file with multiple :run tasks and how various names
resolve in different locations.

  task :run

  namespace "one" do
    task :run

    namespace "two" do
      task :run

      # :run            => "one:two:run"
      # "two:run"       => "one:two:run"
      # "one:two:run"   => "one:two:run"
      # "one:run"       => "one:run"
      # "^run"          => "one:run"
      # "^^run"         => "rake:run" (the top level task)
      # "rake:run"      => "rake:run" (the top level task)
    end

    # :run       => "one:run"
    # "two:run"  => "one:two:run"
    # "^run"     => "rake:run"
  end

  # :run           => "rake:run"
  # "one:run"      => "one:run"
  # "one:two:run"  => "one:two:run"

== FileLists

FileLists are the way Rake manages lists of files.  You can treat a
FileList as an array of strings for the most part, but FileLists
support some additional operations.

=== Creating a FileList

Creating a file list is easy.  Just give it the list of file names:

   fl = FileList['file1.rb', file2.rb']

Or give it a glob pattern:

   fl = FileList['*.rb']

== Odds and Ends

=== do/end versus { }

Blocks may be specified with either a +do+/+end+ pair, or with curly
braces in Ruby.  We _strongly_ recommend using +do+/+end+ to specify the
actions for tasks and rules.  Because the rakefile idiom tends to
leave off parentheses on the task/file/rule methods, unusual
ambiguities can arise when using curly braces.

For example, suppose that the method +object_files+ returns a list of
object files in a project.  Now we use +object_files+ as the
prerequisites in a rule specified with actions in curly braces.

  # DON'T DO THIS!
  file "prog" => object_files {
    # Actions are expected here (but it doesn't work)!
  }

Because curly braces have a higher precedence than +do+/+end+, the
block is associated with the +object_files+ method rather than the
+file+ method.

This is the proper way to specify the task ...

  # THIS IS FINE
  file "prog" => object_files do
    # Actions go here
  end

== Rakefile Path

When issuing the +rake+ command in a terminal, Rake will look
for a Rakefile in the current directory. If a Rakefile  is not found,
it will search parent directories until one is found.

For example, if a Rakefile resides in the +project/+ directory,
moving deeper into the project's directory tree will not have an adverse
effect on rake tasks:

  $ pwd
  /home/user/project

  $ cd lib/foo/bar
  $ pwd
  /home/user/project/lib/foo/bar

  $ rake run_pwd
  /home/user/project

As far as rake is concerned, all tasks are run from the directory in
which the Rakefile resides.

=== Multiple Rake Files

Not all tasks need to be included in a single Rakefile. Additional
rake files (with the file extension "+.rake+") may be placed in
+rakelib+ directory located at the top level of a project (i.e.
the same directory that contains the main +Rakefile+).

Also, rails projects may include additional rake files in the
+lib/tasks+ directory.

=== Clean and Clobber Tasks

Through <tt>require 'rake/clean'</tt> Rake provides +clean+ and +clobber+
tasks:

+clean+ ::
  Clean up the project by deleting scratch files and backup files.  Add files
  to the +CLEAN+ FileList to have the +clean+ target handle them.

+clobber+ ::
  Clobber all generated and non-source files in a project.  The task depends
  on +clean+, so all the +CLEAN+ files will be deleted as well as files in the
  +CLOBBER+ FileList.  The intent of this task is to return a project to its
  pristine, just unpacked state.

You can add file names or glob patterns to both the +CLEAN+ and +CLOBBER+
lists.

=== Phony Task

The phony task can be used as a dependency to allow file-based tasks to use
non-file-based-tasks as prerequisites without forcing them to rebuild.  You
can <tt>require 'rake/phony'</tt> to add the +phony+ task.

----

== See

* README.rdoc -- Main documentation for Rake.
#include <stdio.h>

void a()
{
    printf ("In function a\n");
}
# Example Rakefile -*- ruby -*-
# Using the power of Ruby

task :default => [:main]

def ext(fn, newext)
  fn.sub(/\.[^.]+$/, newext)
end

SRCFILES = Dir['*.c']
OBJFILES = SRCFILES.collect { |fn| ext(fn,".o") }

OBJFILES.each do |objfile|
  srcfile = ext(objfile, ".c")
  file objfile => [srcfile] do |t|
    sh "gcc #{srcfile} -c -o #{t.name}"
  end
end

file "main" => OBJFILES do |t|
  sh "gcc -o #{t.name} main.o a.o b.o"
end

task :clean do
  rm_f FileList['*.o']
  Dir['*~'].each { |fn| rm_f fn }
end

task :clobber => [:clean] do
  rm_f "main"
end

task :run => ["main"] do
  sh "./main"
end
#include <stdio.h>

void b()
{
    printf ("In function b\n");
}
# Example Rakefile -*- ruby -*-

task :default => [:main]

file "a.o" => ["a.c"] do |t|
  src = t.name.sub(/\.o$/, '.c')
  sh "gcc #{src} -c -o #{t.name}"
end

file "b.o" => ["b.c"] do |t|
  src = t.name.sub(/\.o$/, '.c')
  sh "gcc #{src} -c -o #{t.name}"
end

file "main.o" => ["main.c"] do |t|
  src = t.name.sub(/\.o$/, '.c')
  sh "gcc #{src} -c -o #{t.name}"
end

OBJFILES = ["a.o", "b.o", "main.o"]
task :obj => OBJFILES

file "main" => OBJFILES do |t|
  sh "gcc -o #{t.name} main.o a.o b.o"
end

task :clean do
  rm_f FileList['*.o']
  Dir['*~'].each { |fn| rm_f fn }
end

task :clobber => [:clean] do
  rm_f "main"
end

task :run => ["main"] do
  sh "./main"
end
#include <stdio.h>

extern void a();
extern void b();

int main ()
{
    a();
    b();
    return 0;
}
= Rake Command Line Usage

Rake is invoked from the command line using:

    % rake [options ...]  [VAR=VALUE ...]  [targets ...]

Options are:

[<tt><em>name</em>=<em>value</em></tt>]
    Set the environment variable <em>name</em> to <em>value</em>
    during the execution of the <b>rake</b> command.  You can access
    the value by using ENV['<em>name</em>'].

[<tt>--all</tt> (-A)]
    Used in combination with the -T and -D options, will force
    those options to show all the tasks, even the ones without comments.

[<tt>--backtrace</tt>{=_output_} (-n)]
    Enable a full backtrace (i.e. like --trace, but without the task
    tracing details). The _output_ parameter is optional, but if
    specified it controls where the backtrace output is sent. If
    _output_ is <tt>stdout</tt>, then backtrace output is directed to
    standard output. If _output_ is <tt>stderr</tt>, or if it is
    missing, then the backtrace output is sent to standard error.

[<tt>--comments</tt>]
    Used in combination with the -W options to force the output to
    contain commented options only. This is the reverse of
    <tt>--all</tt>.

[<tt>--describe</tt> _pattern_ (-D)]
    Describe the tasks (matching optional PATTERN), then exit.

[<tt>--dry-run</tt> (-n)]
    Do a dry run.  Print the tasks invoked and executed, but do not
    actually execute any of the actions.

[<tt>--execute</tt> _code_ (-e)]
    Execute some Ruby code and exit.

[<tt>--execute-print</tt> _code_ (-p)]
    Execute some Ruby code, print the result, and exit.

[<tt>--execute-continue</tt> _code_ (-E)]
    Execute some Ruby code, then continue with normal task processing.

[<tt>--help</tt>  (-H)]
    Display some help text and exit.

[<tt>--jobs</tt> _number_  (-j)]

    Specifies the maximum number of concurrent threads allowed. Rake
    will allocate threads as needed up to this maximum number.

    If omitted, Rake will attempt to estimate the number of CPUs on
    the system and add 4 to that number.

    The concurrent threads are used to execute the <tt>multitask</tt>
    prerequisites. Also see the <tt>-m</tt> option which turns all
    tasks into multitasks.

    Sample values:
       (no -j)   : Allow up to (# of CPUs + 4) number of threads
       --jobs    : Allow unlimited number of threads
       --jobs=1  : Allow only one thread (the main thread)
       --jobs=16 : Allow up to 16 concurrent threads

[<tt>--job-stats</tt> _level_]

    Display job statistics at the completion of the run. By default,
    this will display the requested number of active threads (from the
    -j options) and the maximum number of threads in play at any given
    time.

    If the optional _level_ is <tt>history</tt>, then a complete trace
    of task history will be displayed on standard output.

[<tt>--libdir</tt> _directory_  (-I)]
    Add _directory_ to the list of directories searched for require.

[<tt>--multitask</tt> (-m)]
    Treat all tasks as multitasks. ('make/drake' semantics)

[<tt>--nosearch</tt>  (-N)]
    Do not search for a Rakefile in parent directories.

[<tt>--prereqs</tt>  (-P)]
    Display a list of all tasks and their immediate prerequisites.

[<tt>--quiet</tt> (-q)]
    Do not echo commands from FileUtils.

[<tt>--rakefile</tt> _filename_ (-f)]
    Use _filename_ as the name of the rakefile. The default rakefile
    names are +rakefile+ and +Rakefile+ (with +rakefile+ taking
    precedence). If the rakefile is not found in the current
    directory, +rake+ will search parent directories for a match. The
    directory where the Rakefile is found will become the current
    directory for the actions executed in the Rakefile.

[<tt>--rakelibdir</tt> _rakelibdir_ (-R)]
    Auto-import any .rake files in RAKELIBDIR. (default is 'rakelib')

[<tt>--require</tt> _name_ (-r)]
    Require _name_ before executing the Rakefile.

[<tt>--rules</tt>]
    Trace the rules resolution.

[<tt>--silent (-s)</tt>]
    Like --quiet, but also suppresses the 'in directory' announcement.

[<tt>--suppress-backtrace _pattern_ </tt>]
    Line matching the regular expression _pattern_ will be removed
    from the backtrace output. Note that the --backtrace option is the
    full backtrace without these lines suppressed.

[<tt>--system</tt> (-g)]
    Use the system wide (global) rakefiles. The project Rakefile is
    ignored. By default, the system wide rakefiles are used only if no
    project Rakefile is found. On Unix-like system, the system wide
    rake files are located in $HOME/.rake. On a windows system they
    are stored in $APPDATA/Rake.

[<tt>--no-system</tt> (-G)]
    Use the project level Rakefile, ignoring the system-wide (global)
    rakefiles.

[<tt>--tasks</tt> <em>pattern</em> (-T)]
    Display a list of the major tasks and their comments.  Comments
    are defined using the "desc" command.  If a pattern is given, then
    only tasks matching the pattern are displayed.

[<tt>--trace</tt>{=_output_} (-t)]
    Turn on invoke/execute tracing. Also enable full backtrace on
    errors. The _output_ parameter is optional, but if specified it
    controls where the trace output is sent. If _output_ is
    <tt>stdout</tt>, then trace output is directed to standard output.
    If _output_ is <tt>stderr</tt>, or if it is missing, then trace
    output is sent to standard error.

[<tt>--verbose</tt> (-v)]
    Echo the Sys commands to standard output.

[<tt>--version</tt> (-V)]
    Display the program version and exit.

[<tt>--where</tt> <em>pattern</em> (-W)]
    Display tasks that match <em>pattern</em> and the file and line
    number where the task is defined. By default this option will
    display all tasks, not just the tasks that have descriptions.

[<tt>--no-deprecation-warnings</tt> (-X)]
    Do not display the deprecation warnings.

In addition, any command line option of the form
<em>VAR</em>=<em>VALUE</em> will be added to the environment hash
<tt>ENV</tt> and may be tested in the Rakefile.
#!/opt/alt/ruby30/bin/ruby
# frozen_string_literal: true

#
# This file was generated by Bundler.
#
# The application 'bundle' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require "rubygems"

m = Module.new do
    module_function

  def invoked_as_script?
    File.expand_path($0) == File.expand_path(__FILE__)
  end

  def env_var_version
    ENV["BUNDLER_VERSION"]
  end

  def cli_arg_version
    return unless invoked_as_script? # don't want to hijack other binstubs
    return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update`
    bundler_version = nil
    update_index = nil
    ARGV.each_with_index do |a, i|
      if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN
        bundler_version = a
      end
      next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/
      bundler_version = $1 || ">= 0.a"
      update_index = i
    end
    bundler_version
  end

  def gemfile
    gemfile = ENV["BUNDLE_GEMFILE"]
    return gemfile if gemfile && !gemfile.empty?

    File.expand_path("../../Gemfile", __FILE__)
  end

  def lockfile
    lockfile =
      case File.basename(gemfile)
      when "gems.rb" then gemfile.sub(/\.rb$/, gemfile)
      else "#{gemfile}.lock"
      end
    File.expand_path(lockfile)
  end

  def lockfile_version
    return unless File.file?(lockfile)
    lockfile_contents = File.read(lockfile)
    return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/
    Regexp.last_match(1)
  end

  def bundler_version
    @bundler_version ||= begin
      env_var_version || cli_arg_version ||
        lockfile_version || "#{Gem::Requirement.default}.a"
    end
  end

  def load_bundler!
    ENV["BUNDLE_GEMFILE"] ||= gemfile

    # must dup string for RG < 1.8 compatibility
    activate_bundler(bundler_version.dup)
  end

  def activate_bundler(bundler_version)
    if Gem::Version.correct?(bundler_version) && Gem::Version.new(bundler_version).release < Gem::Version.new("2.0")
      bundler_version = "< 2"
    end
    gem_error = activation_error_handling do
      gem "bundler", bundler_version
    end
    return if gem_error.nil?
    require_error = activation_error_handling do
      require "bundler/version"
    end
    return if require_error.nil? && Gem::Requirement.new(bundler_version).satisfied_by?(Gem::Version.new(Bundler::VERSION))
    warn "Activating bundler (#{bundler_version}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_version}'`"
    exit 42
  end

  def activation_error_handling
    yield
    nil
  rescue StandardError, LoadError => e
    e
  end
end

m.load_bundler!

if m.invoked_as_script?
  load Gem.bin_path("bundler", "bundle")
end
#!/opt/alt/ruby30/bin/ruby
# frozen_string_literal: true

#
# This file was generated by Bundler.
#
# The application 'rubocop' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
  Pathname.new(__FILE__).realpath)

bundle_binstub = File.expand_path("../bundle", __FILE__)

if File.file?(bundle_binstub)
  if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
    load(bundle_binstub)
  else
    abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
  end
end

require "rubygems"
require "bundler/setup"

load Gem.bin_path("rubocop", "rubocop")
#!/opt/alt/ruby30/bin/ruby

require "bundler/setup"
require "rake"

require "irb"
IRB.start
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
set -vx

bundle install
#!/opt/alt/ruby30/bin/ruby
# frozen_string_literal: true

#
# This file was generated by Bundler.
#
# The application 'rake' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
  Pathname.new(__FILE__).realpath)

bundle_binstub = File.expand_path("../bundle", __FILE__)

if File.file?(bundle_binstub)
  if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
    load(bundle_binstub)
  else
    abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
  end
end

require "rubygems"
require "bundler/setup"

load Gem.bin_path("rake", "rake")
#!/opt/alt/ruby30/bin/ruby
# frozen_string_literal: true

#
# This file was generated by Bundler.
#
# The application 'rdoc' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
  Pathname.new(__FILE__).realpath)

bundle_binstub = File.expand_path("../bundle", __FILE__)

if File.file?(bundle_binstub)
  if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
    load(bundle_binstub)
  else
    abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
  end
end

require "rubygems"
require "bundler/setup"

load Gem.bin_path("rdoc", "rdoc")
= RAKE -- Ruby Make

home :: https://github.com/ruby/rake
bugs :: https://github.com/ruby/rake/issues
docs :: https://ruby.github.io/rake

== Description

Rake is a Make-like program implemented in Ruby. Tasks and dependencies are
specified in standard Ruby syntax.

Rake has the following features:

* Rakefiles (rake's version of Makefiles) are completely defined in
  standard Ruby syntax.  No XML files to edit.  No quirky Makefile
  syntax to worry about (is that a tab or a space?)

* Users can specify tasks with prerequisites.

* Rake supports rule patterns to synthesize implicit tasks.

* Flexible FileLists that act like arrays but know about manipulating
  file names and paths.

* A library of prepackaged tasks to make building rakefiles easier. For example,
  tasks for building tarballs. (Formerly
  tasks for building RDoc, Gems, and publishing to FTP were included in rake but they're now
  available in RDoc, RubyGems, and rake-contrib respectively.)

* Supports parallel execution of tasks.

== Installation

=== Gem Installation

Download and install rake with the following.

  gem install rake

== Usage

=== Simple Example

First, you must write a "Rakefile" file which contains the build rules. Here's
a simple example:

  task default: %w[test]

  task :test do
    ruby "test/unittest.rb"
  end

This Rakefile has two tasks:

* A task named "test", which -- upon invocation -- will run a unit test file
  in Ruby.
* A task named "default". This task does nothing by itself, but it has exactly
  one dependency, namely the "test" task. Invoking the "default" task will
  cause Rake to invoke the "test" task as well.

Running the "rake" command without any options will cause it to run the
"default" task in the Rakefile:

  % ls
  Rakefile     test/
  % rake
  (in /home/some_user/Projects/rake)
  ruby test/unittest.rb
  ....unit test output here...

Type "rake --help" for all available options.

== Resources

=== Rake Information

* {Rake command-line}[link:doc/command_line_usage.rdoc]
* {Writing Rakefiles}[link:doc/rakefile.rdoc]
* The original {Rake announcement}[link:doc/rational.rdoc]
* Rake {glossary}[link:doc/glossary.rdoc]

=== Presentations and Articles about Rake

* Avdi Grimm's rake series:
  1. {Rake Basics}[https://avdi.codes/rake-part-1-basics/]
  2. {Rake File Lists}[https://avdi.codes/rake-part-2-file-lists-2/]
  3. {Rake Rules}[https://avdi.codes/rake-part-3-rules/]
  4. {Rake Pathmap}[https://avdi.codes/rake-part-4-pathmap/]
  5. {File Operations}[https://avdi.codes/rake-part-5-file-operations/]
  6. {Clean and Clobber}[https://avdi.codes/rake-part-6-clean-and-clobber/]
  7. {MultiTask}[https://avdi.codes/rake-part-7-multitask/]
* {Jim Weirich's 2003 RubyConf presentation}[https://web.archive.org/web/20140221123354/http://onestepback.org/articles/buildingwithrake/]
* Martin Fowler's article on Rake: https://martinfowler.com/articles/rake.html

== Other Make Re-envisionings ...

Rake is a late entry in the make replacement field.  Here are links to
other projects with similar (and not so similar) goals.

* https://directory.fsf.org/wiki/Bras -- Bras, one of earliest
  implementations of "make in a scripting language".
* http://www.a-a-p.org -- Make in Python
* https://ant.apache.org -- The Ant project
* https://search.cpan.org/search?query=PerlBuildSystem -- The Perl Build System
* https://www.rubydoc.info/gems/rant/0.5.7/frames -- Rant, another Ruby make tool.

== Credits

[<b>Jim Weirich</b>] Who originally created Rake.

[<b>Ryan Dlugosz</b>] For the initial conversation that sparked Rake.

[<b>Nobuyoshi Nakada <nobu@ruby-lang.org></b>] For the initial patch for rule support.

[<b>Tilman Sauerbeck <tilman@code-monkey.de></b>] For the recursive rule patch.

[<b>Eric Hodel</b>] For aid in maintaining rake.

[<b>Hiroshi SHIBATA</b>] Maintainer of Rake 10.X and Rake 11.X

== License

Rake is available under an MIT-style license.

:include: MIT-LICENSE

---

= Other stuff

Author::   Jim Weirich <jim.weirich@gmail.com>
Requires:: Ruby 2.0.0 or later
License::  Copyright Jim Weirich.
           Released under an MIT-style license.  See the MIT-LICENSE
           file included in the distribution.

== 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.

== Historical

Rake was originally created by Jim Weirich, who unfortunately passed away in
February 2014. This repository was originally hosted at
{github.com/jimweirich/rake}[https://github.com/jimweirich/rake/], however
with his passing, has been moved to {ruby/rake}[https://github.com/ruby/rake].

You can view Jim's last commit here:
https://github.com/jimweirich/rake/tree/336559f28f55bce418e2ebcc0a57548dcbac4025

You can {read more about Jim}[https://en.wikipedia.org/wiki/Jim_Weirich] at Wikipedia.

Thank you for this great tool, Jim. We'll remember you.
= Source Repository

Rake is currently hosted at github. The github web page is
https://github.com/ruby/rake . The public git clone URL is

  https://github.com/ruby/rake.git

= Running the Rake Test Suite

If you wish to run the unit and functional tests that come with Rake:

* +cd+ into the top project directory of rake.
* Install gem dependency using bundler:

    $ bundle install  # Install bundler, minitest and rdoc

* Run the test suite

    $ rake

= Rubocop

Rake uses Rubocop to enforce a consistent style on new changes being
proposed. You can check your code with Rubocop using:

  $ ./bin/rubocop

= Issues and Bug Reports

Feel free to submit commits or feature requests.  If you send a patch,
remember to update the corresponding unit tests.  In fact, I prefer
new feature to be submitted in the form of new unit tests.

For other information, feel free to ask on the ruby-talk mailing list.

If you have found a bug in rake please try with the latest version of rake
before filing an issue.  Also check History.rdoc for bug fixes that may have
addressed your issue.

When submitting pull requests please check the rake Travis-CI page for test
failures:

  https://travis-ci.org/ruby/rake
#!/opt/alt/ruby30/bin/ruby

#--
# Copyright (c) 2003, 2004, 2005, 2006, 2007  Jim Weirich
#
# 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 "rake"

Rake.application.run
# frozen_string_literal: true
#--
# Copyright 2003-2010 by Jim Weirich (jim.weirich@gmail.com)
#
# 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.
#++

module Rake; end

require "rake/version"

require "rbconfig"
require "fileutils"
require "singleton"
require "monitor"
require "optparse"
require "ostruct"

require "rake/ext/string"

require "rake/win32"

require "rake/linked_list"
require "rake/cpu_counter"
require "rake/scope"
require "rake/task_argument_error"
require "rake/rule_recursion_overflow_error"
require "rake/rake_module"
require "rake/trace_output"
require "rake/pseudo_status"
require "rake/task_arguments"
require "rake/invocation_chain"
require "rake/task"
require "rake/file_task"
require "rake/file_creation_task"
require "rake/multi_task"
require "rake/dsl_definition"
require "rake/file_utils_ext"
require "rake/file_list"
require "rake/default_loader"
require "rake/early_time"
require "rake/late_time"
require "rake/name_space"
require "rake/task_manager"
require "rake/application"
require "rake/backtrace"

$trace = false

# :stopdoc:
#
# Some top level Constants.

FileList = Rake::FileList
RakeFileUtils = Rake::FileUtilsExt
# frozen_string_literal: true
##
# The NameSpace class will lookup task names in the scope defined by a
# +namespace+ command.

class Rake::NameSpace

  ##
  # Create a namespace lookup object using the given task manager
  # and the list of scopes.

  def initialize(task_manager, scope_list)
    @task_manager = task_manager
    @scope = scope_list.dup
  end

  ##
  # Lookup a task named +name+ in the namespace.

  def [](name)
    @task_manager.lookup(name, @scope)
  end

  ##
  # The scope of the namespace (a LinkedList)

  def scope
    @scope.dup
  end

  ##
  # Return the list of tasks defined in this and nested namespaces.

  def tasks
    @task_manager.tasks_in_scope(@scope)
  end

end
# frozen_string_literal: true
require "rake"

module Rake

  # Base class for Task Libraries.
  class TaskLib
    include Cloneable
    include Rake::DSL
  end

end
# frozen_string_literal: true
module Rake

  # Makefile loader to be used with the import file loader.  Use this to
  # import dependencies from make dependency tools:
  #
  #   require 'rake/loaders/makefile'
  #
  #   file ".depends.mf" => [SRC_LIST] do |t|
  #     sh "makedepend -f- -- #{CFLAGS} -- #{t.prerequisites} > #{t.name}"
  #   end
  #
  #   import ".depends.mf"
  #
  # See {Importing Dependencies}[link:doc/rakefile_rdoc.html#label-Importing+Dependencies]
  # for further details.

  class MakefileLoader
    include Rake::DSL

    SPACE_MARK = "\0" # :nodoc:

    # Load the makefile dependencies in +fn+.
    def load(fn) # :nodoc:
      lines = File.read fn
      lines.gsub!(/\\ /, SPACE_MARK)
      lines.gsub!(/#[^\n]*\n/m, "")
      lines.gsub!(/\\\n/, " ")
      lines.each_line do |line|
        process_line(line)
      end
    end

    private

    # Process one logical line of makefile data.
    def process_line(line) # :nodoc:
      file_tasks, args = line.split(":", 2)
      return if args.nil?
      dependents = args.split.map { |d| respace(d) }
      file_tasks.scan(/\S+/) do |file_task|
        file_task = respace(file_task)
        file file_task => dependents
      end
    end

    def respace(str) # :nodoc:
      str.tr SPACE_MARK, " "
    end
  end

  # Install the handler
  Rake.application.add_loader("mf", MakefileLoader.new)
end
# frozen_string_literal: true
module Rake
  module InvocationExceptionMixin
    # Return the invocation chain (list of Rake tasks) that were in
    # effect when this exception was detected by rake.  May be null if
    # no tasks were active.
    def chain
      @rake_invocation_chain ||= nil
    end

    # Set the invocation chain in effect when this exception was
    # detected.
    def chain=(value)
      @rake_invocation_chain = value
    end
  end
end
# frozen_string_literal: true
module Rake

  ##
  # TaskArguments manage the arguments passed to a task.
  #
  class TaskArguments
    include Enumerable

    # Argument names
    attr_reader :names

    # Create a TaskArgument object with a list of argument +names+ and a set
    # of associated +values+.  +parent+ is the parent argument object.
    def initialize(names, values, parent=nil)
      @names = names
      @parent = parent
      @hash = {}
      @values = values
      names.each_with_index { |name, i|
        next if values[i].nil? || values[i] == ""
        @hash[name.to_sym] = values[i]
      }
    end

    # Retrieve the complete array of sequential values
    def to_a
      @values.dup
    end

    # Retrieve the list of values not associated with named arguments
    def extras
      @values[@names.length..-1] || []
    end

    # Create a new argument scope using the prerequisite argument
    # names.
    def new_scope(names)
      values = names.map { |n| self[n] }
      self.class.new(names, values + extras, self)
    end

    # Find an argument value by name or index.
    def [](index)
      lookup(index.to_sym)
    end

    # Specify a hash of default values for task arguments. Use the
    # defaults only if there is no specific value for the given
    # argument.
    def with_defaults(defaults)
      @hash = defaults.merge(@hash)
    end

    # Enumerates the arguments and their values
    def each(&block)
      @hash.each(&block)
    end

    # Extracts the argument values at +keys+
    def values_at(*keys)
      keys.map { |k| lookup(k) }
    end

    # Returns the value of the given argument via method_missing
    def method_missing(sym, *args)
      lookup(sym.to_sym)
    end

    # Returns a Hash of arguments and their values
    def to_hash
      @hash.dup
    end

    def to_s # :nodoc:
      inspect
    end

    def inspect # :nodoc:
      inspection = @hash.map do |k,v|
        "#{k.to_s}: #{v.to_s}"
      end.join(", ")

      "#<#{self.class} #{inspection}>"
    end

    # Returns true if +key+ is one of the arguments
    def has_key?(key)
      @hash.has_key?(key)
    end
    alias key? has_key?

    def fetch(*args, &block)
      @hash.fetch(*args, &block)
    end

    protected

    def lookup(name) # :nodoc:
      if @hash.has_key?(name)
        @hash[name]
      elsif @parent
        @parent.lookup(name)
      end
    end
  end

  EMPTY_TASK_ARGS = TaskArguments.new([], []) # :nodoc:
end
# frozen_string_literal: true
require "optparse"

require "rake/task_manager"
require "rake/file_list"
require "rake/thread_pool"
require "rake/thread_history_display"
require "rake/trace_output"
require "rake/win32"

module Rake

  CommandLineOptionError = Class.new(StandardError)

  ##
  # Rake main application object.  When invoking +rake+ from the
  # command line, a Rake::Application object is created and run.

  class Application
    include TaskManager
    include TraceOutput

    # The name of the application (typically 'rake')
    attr_reader :name

    # The original directory where rake was invoked.
    attr_reader :original_dir

    # Name of the actual rakefile used.
    attr_reader :rakefile

    # Number of columns on the terminal
    attr_accessor :terminal_columns

    # List of the top level task names (task names from the command line).
    attr_reader :top_level_tasks

    # Override the detected TTY output state (mostly for testing)
    attr_writer :tty_output

    DEFAULT_RAKEFILES = [
      "rakefile",
      "Rakefile",
      "rakefile.rb",
      "Rakefile.rb"
    ].freeze

    # Initialize a Rake::Application object.
    def initialize
      super
      @name = "rake"
      @rakefiles = DEFAULT_RAKEFILES.dup
      @rakefile = nil
      @pending_imports = []
      @imported = []
      @loaders = {}
      @default_loader = Rake::DefaultLoader.new
      @original_dir = Dir.pwd
      @top_level_tasks = []
      add_loader("rb", DefaultLoader.new)
      add_loader("rf", DefaultLoader.new)
      add_loader("rake", DefaultLoader.new)
      @tty_output = STDOUT.tty?
      @terminal_columns = ENV["RAKE_COLUMNS"].to_i

      set_default_options
    end

    # Run the Rake application.  The run method performs the following
    # three steps:
    #
    # * Initialize the command line options (+init+).
    # * Define the tasks (+load_rakefile+).
    # * Run the top level tasks (+top_level+).
    #
    # If you wish to build a custom rake command, you should call
    # +init+ on your application.  Then define any tasks.  Finally,
    # call +top_level+ to run your top level tasks.
    def run(argv = ARGV)
      standard_exception_handling do
        init "rake", argv
        load_rakefile
        top_level
      end
    end

    # Initialize the command line parameters and app name.
    def init(app_name="rake", argv = ARGV)
      standard_exception_handling do
        @name = app_name
        begin
          args = handle_options argv
        rescue ArgumentError
          # Backward compatibility for capistrano
          args = handle_options
        end
        collect_command_line_tasks(args)
      end
    end

    # Find the rakefile and then load it and any pending imports.
    def load_rakefile
      standard_exception_handling do
        raw_load_rakefile
      end
    end

    # Run the top level tasks of a Rake application.
    def top_level
      run_with_threads do
        if options.show_tasks
          display_tasks_and_comments
        elsif options.show_prereqs
          display_prerequisites
        else
          top_level_tasks.each { |task_name| invoke_task(task_name) }
        end
      end
    end

    # Run the given block with the thread startup and shutdown.
    def run_with_threads
      thread_pool.gather_history if options.job_stats == :history

      yield

      thread_pool.join
      if options.job_stats
        stats = thread_pool.statistics
        puts "Maximum active threads: #{stats[:max_active_threads]} + main"
        puts "Total threads in play:  #{stats[:total_threads_in_play]} + main"
      end
      ThreadHistoryDisplay.new(thread_pool.history).show if
        options.job_stats == :history
    end

    # Add a loader to handle imported files ending in the extension
    # +ext+.
    def add_loader(ext, loader)
      ext = ".#{ext}" unless ext =~ /^\./
      @loaders[ext] = loader
    end

    # Application options from the command line
    def options
      @options ||= OpenStruct.new
    end

    # Return the thread pool used for multithreaded processing.
    def thread_pool             # :nodoc:
      @thread_pool ||= ThreadPool.new(options.thread_pool_size || Rake.suggested_thread_count-1)
    end

    # internal ----------------------------------------------------------------

    # Invokes a task with arguments that are extracted from +task_string+
    def invoke_task(task_string) # :nodoc:
      name, args = parse_task_string(task_string)
      t = self[name]
      t.invoke(*args)
    end

    def parse_task_string(string) # :nodoc:
      /^([^\[]+)(?:\[(.*)\])$/ =~ string.to_s

      name           = $1
      remaining_args = $2

      return string, [] unless name
      return name,   [] if     remaining_args.empty?

      args = []

      begin
        /\s*((?:[^\\,]|\\.)*?)\s*(?:,\s*(.*))?$/ =~ remaining_args

        remaining_args = $2
        args << $1.gsub(/\\(.)/, '\1')
      end while remaining_args

      return name, args
    end

    # Provide standard exception handling for the given block.
    def standard_exception_handling # :nodoc:
      yield
    rescue SystemExit
      # Exit silently with current status
      raise
    rescue OptionParser::InvalidOption => ex
      $stderr.puts ex.message
      exit(false)
    rescue Exception => ex
      # Exit with error message
      display_error_message(ex)
      exit_because_of_exception(ex)
    end

    # Exit the program because of an unhandled exception.
    # (may be overridden by subclasses)
    def exit_because_of_exception(ex) # :nodoc:
      exit(false)
    end

    # Display the error message that caused the exception.
    def display_error_message(ex) # :nodoc:
      trace "#{name} aborted!"
      display_exception_details(ex)
      trace "Tasks: #{ex.chain}" if has_chain?(ex)
      trace "(See full trace by running task with --trace)" unless
         options.backtrace
    end

    def display_exception_details(ex) # :nodoc:
      display_exception_details_seen << ex

      display_exception_message_details(ex)
      display_exception_backtrace(ex)
      display_cause_details(ex.cause) if has_cause?(ex)
    end

    def display_cause_details(ex) # :nodoc:
      return if display_exception_details_seen.include? ex

      trace "\nCaused by:"
      display_exception_details(ex)
    end

    def display_exception_details_seen # :nodoc:
      Thread.current[:rake_display_exception_details_seen] ||= []
    end

    def has_cause?(ex) # :nodoc:
      ex.respond_to?(:cause) && ex.cause
    end

    def display_exception_message_details(ex) # :nodoc:
      if ex.instance_of?(RuntimeError)
        trace ex.message
      else
        trace "#{ex.class.name}: #{ex.message}"
      end
    end

    def display_exception_backtrace(ex) # :nodoc:
      if options.backtrace
        trace ex.backtrace.join("\n")
      else
        trace Backtrace.collapse(ex.backtrace).join("\n")
      end
    end

    # Warn about deprecated usage.
    #
    # Example:
    #    Rake.application.deprecate("import", "Rake.import", caller.first)
    #
    def deprecate(old_usage, new_usage, call_site) # :nodoc:
      unless options.ignore_deprecate
        $stderr.puts "WARNING: '#{old_usage}' is deprecated.  " +
          "Please use '#{new_usage}' instead.\n" +
          "    at #{call_site}"
      end
    end

    # Does the exception have a task invocation chain?
    def has_chain?(exception) # :nodoc:
      exception.respond_to?(:chain) && exception.chain
    end
    private :has_chain?

    # True if one of the files in RAKEFILES is in the current directory.
    # If a match is found, it is copied into @rakefile.
    def have_rakefile # :nodoc:
      @rakefiles.each do |fn|
        if File.exist?(fn)
          others = FileList.glob(fn, File::FNM_CASEFOLD)
          return others.size == 1 ? others.first : fn
        elsif fn == ""
          return fn
        end
      end
      return nil
    end

    # True if we are outputting to TTY, false otherwise
    def tty_output? # :nodoc:
      @tty_output
    end

    # We will truncate output if we are outputting to a TTY or if we've been
    # given an explicit column width to honor
    def truncate_output? # :nodoc:
      tty_output? || @terminal_columns.nonzero?
    end

    # Display the tasks and comments.
    def display_tasks_and_comments # :nodoc:
      displayable_tasks = tasks.select { |t|
        (options.show_all_tasks || t.comment) &&
          t.name =~ options.show_task_pattern
      }
      case options.show_tasks
      when :tasks
        width = displayable_tasks.map { |t| t.name_with_args.length }.max || 10
        if truncate_output?
          max_column = terminal_width - name.size - width - 7
        else
          max_column = nil
        end

        displayable_tasks.each do |t|
          printf("#{name} %-#{width}s  # %s\n",
            t.name_with_args,
            max_column ? truncate(t.comment, max_column) : t.comment)
        end
      when :describe
        displayable_tasks.each do |t|
          puts "#{name} #{t.name_with_args}"
          comment = t.full_comment || ""
          comment.split("\n").each do |line|
            puts "    #{line}"
          end
          puts
        end
      when :lines
        displayable_tasks.each do |t|
          t.locations.each do |loc|
            printf "#{name} %-30s %s\n", t.name_with_args, loc
          end
        end
      else
        fail "Unknown show task mode: '#{options.show_tasks}'"
      end
    end

    def terminal_width # :nodoc:
      if @terminal_columns.nonzero?
        result = @terminal_columns
      else
        result = unix? ? dynamic_width : 80
      end
      (result < 10) ? 80 : result
    rescue
      80
    end

    # Calculate the dynamic width of the
    def dynamic_width # :nodoc:
      @dynamic_width ||= (dynamic_width_stty.nonzero? || dynamic_width_tput)
    end

    def dynamic_width_stty # :nodoc:
      %x{stty size 2>/dev/null}.split[1].to_i
    end

    def dynamic_width_tput # :nodoc:
      %x{tput cols 2>/dev/null}.to_i
    end

    def unix? # :nodoc:
      RbConfig::CONFIG["host_os"] =~
        /(aix|darwin|linux|(net|free|open)bsd|cygwin|solaris|irix|hpux)/i
    end

    def windows? # :nodoc:
      Win32.windows?
    end

    def truncate(string, width) # :nodoc:
      if string.nil?
        ""
      elsif string.length <= width
        string
      else
        (string[0, width - 3] || "") + "..."
      end
    end

    # Display the tasks and prerequisites
    def display_prerequisites # :nodoc:
      tasks.each do |t|
        puts "#{name} #{t.name}"
        t.prerequisites.each { |pre| puts "    #{pre}" }
      end
    end

    def trace(*strings) # :nodoc:
      options.trace_output ||= $stderr
      trace_on(options.trace_output, *strings)
    end

    def sort_options(options) # :nodoc:
      options.sort_by { |opt|
        opt.select { |o| o.is_a?(String) && o =~ /^-/ }.map(&:downcase).sort.reverse
      }
    end
    private :sort_options

    # A list of all the standard options used in rake, suitable for
    # passing to OptionParser.
    def standard_rake_options # :nodoc:
      sort_options(
        [
          ["--all", "-A",
            "Show all tasks, even uncommented ones (in combination with -T or -D)",
            lambda { |value|
              options.show_all_tasks = value
            }
          ],
          ["--backtrace=[OUT]",
            "Enable full backtrace.  OUT can be stderr (default) or stdout.",
            lambda { |value|
              options.backtrace = true
              select_trace_output(options, "backtrace", value)
            }
          ],
          ["--build-all", "-B",
           "Build all prerequisites, including those which are up-to-date.",
           lambda { |value|
             options.build_all = true
           }
          ],
          ["--comments",
            "Show commented tasks only",
            lambda { |value|
              options.show_all_tasks = !value
            }
          ],
          ["--describe", "-D [PATTERN]",
            "Describe the tasks (matching optional PATTERN), then exit.",
            lambda { |value|
              select_tasks_to_show(options, :describe, value)
            }
          ],
          ["--dry-run", "-n",
            "Do a dry run without executing actions.",
            lambda { |value|
              Rake.verbose(true)
              Rake.nowrite(true)
              options.dryrun = true
              options.trace = true
            }
          ],
          ["--execute", "-e CODE",
            "Execute some Ruby code and exit.",
            lambda { |value|
              eval(value)
              exit
            }
          ],
          ["--execute-print", "-p CODE",
            "Execute some Ruby code, print the result, then exit.",
            lambda { |value|
              puts eval(value)
              exit
            }
          ],
          ["--execute-continue",  "-E CODE",
            "Execute some Ruby code, " +
            "then continue with normal task processing.",
            lambda { |value| eval(value) }
          ],
          ["--jobs",  "-j [NUMBER]",
            "Specifies the maximum number of tasks to execute in parallel. " +
            "(default is number of CPU cores + 4)",
            lambda { |value|
              if value.nil? || value == ""
                value = Float::INFINITY
              elsif value =~ /^\d+$/
                value = value.to_i
              else
                value = Rake.suggested_thread_count
              end
              value = 1 if value < 1
              options.thread_pool_size = value - 1
            }
          ],
          ["--job-stats [LEVEL]",
            "Display job statistics. " +
            "LEVEL=history displays a complete job list",
            lambda { |value|
              if value =~ /^history/i
                options.job_stats = :history
              else
                options.job_stats = true
              end
            }
          ],
          ["--libdir", "-I LIBDIR",
            "Include LIBDIR in the search path for required modules.",
            lambda { |value| $:.push(value) }
          ],
          ["--multitask", "-m",
            "Treat all tasks as multitasks.",
            lambda { |value| options.always_multitask = true }
          ],
          ["--no-search", "--nosearch",
            "-N", "Do not search parent directories for the Rakefile.",
            lambda { |value| options.nosearch = true }
          ],
          ["--prereqs", "-P",
            "Display the tasks and dependencies, then exit.",
            lambda { |value| options.show_prereqs = true }
          ],
          ["--quiet", "-q",
            "Do not log messages to standard output.",
            lambda { |value| Rake.verbose(false) }
          ],
          ["--rakefile", "-f [FILENAME]",
            "Use FILENAME as the rakefile to search for.",
            lambda { |value|
              value ||= ""
              @rakefiles.clear
              @rakefiles << value
            }
          ],
          ["--rakelibdir", "--rakelib", "-R RAKELIBDIR",
            "Auto-import any .rake files in RAKELIBDIR. " +
            "(default is 'rakelib')",
            lambda { |value|
              options.rakelib = value.split(File::PATH_SEPARATOR)
            }
          ],
          ["--require", "-r MODULE",
            "Require MODULE before executing rakefile.",
            lambda { |value|
              begin
                require value
              rescue LoadError => ex
                begin
                  rake_require value
                rescue LoadError
                  raise ex
                end
              end
            }
          ],
          ["--rules",
            "Trace the rules resolution.",
            lambda { |value| options.trace_rules = true }
          ],
          ["--silent", "-s",
            "Like --quiet, but also suppresses the " +
            "'in directory' announcement.",
            lambda { |value|
              Rake.verbose(false)
              options.silent = true
            }
          ],
          ["--suppress-backtrace PATTERN",
            "Suppress backtrace lines matching regexp PATTERN. " +
            "Ignored if --trace is on.",
            lambda { |value|
              options.suppress_backtrace_pattern = Regexp.new(value)
            }
          ],
          ["--system",  "-g",
            "Using system wide (global) rakefiles " +
            "(usually '~/.rake/*.rake').",
            lambda { |value| options.load_system = true }
          ],
          ["--no-system", "--nosystem", "-G",
            "Use standard project Rakefile search paths, " +
            "ignore system wide rakefiles.",
            lambda { |value| options.ignore_system = true }
          ],
          ["--tasks", "-T [PATTERN]",
            "Display the tasks (matching optional PATTERN) " +
            "with descriptions, then exit. " +
            "-AT combination displays all of tasks contained no description.",
            lambda { |value|
              select_tasks_to_show(options, :tasks, value)
            }
          ],
          ["--trace=[OUT]", "-t",
            "Turn on invoke/execute tracing, enable full backtrace. " +
            "OUT can be stderr (default) or stdout.",
            lambda { |value|
              options.trace = true
              options.backtrace = true
              select_trace_output(options, "trace", value)
              Rake.verbose(true)
            }
          ],
          ["--verbose", "-v",
            "Log message to standard output.",
            lambda { |value| Rake.verbose(true) }
          ],
          ["--version", "-V",
            "Display the program version.",
            lambda { |value|
              puts "rake, version #{Rake::VERSION}"
              exit
            }
          ],
          ["--where", "-W [PATTERN]",
            "Describe the tasks (matching optional PATTERN), then exit.",
            lambda { |value|
              select_tasks_to_show(options, :lines, value)
              options.show_all_tasks = true
            }
          ],
          ["--no-deprecation-warnings", "-X",
            "Disable the deprecation warnings.",
            lambda { |value|
              options.ignore_deprecate = true
            }
          ],
        ])
    end

    def select_tasks_to_show(options, show_tasks, value) # :nodoc:
      options.show_tasks = show_tasks
      options.show_task_pattern = Regexp.new(value || "")
      Rake::TaskManager.record_task_metadata = true
    end
    private :select_tasks_to_show

    def select_trace_output(options, trace_option, value) # :nodoc:
      value = value.strip unless value.nil?
      case value
      when "stdout"
        options.trace_output = $stdout
      when "stderr", nil
        options.trace_output = $stderr
      else
        fail CommandLineOptionError,
          "Unrecognized --#{trace_option} option '#{value}'"
      end
    end
    private :select_trace_output

    # Read and handle the command line options.  Returns the command line
    # arguments that we didn't understand, which should (in theory) be just
    # task names and env vars.
    def handle_options(argv) # :nodoc:
      set_default_options

      OptionParser.new do |opts|
        opts.banner = "#{Rake.application.name} [-f rakefile] {options} targets..."
        opts.separator ""
        opts.separator "Options are ..."

        opts.on_tail("-h", "--help", "-H", "Display this help message.") do
          puts opts
          exit
        end

        standard_rake_options.each { |args| opts.on(*args) }
        opts.environment("RAKEOPT")
      end.parse(argv)
    end

    # Similar to the regular Ruby +require+ command, but will check
    # for *.rake files in addition to *.rb files.
    def rake_require(file_name, paths=$LOAD_PATH, loaded=$") # :nodoc:
      fn = file_name + ".rake"
      return false if loaded.include?(fn)
      paths.each do |path|
        full_path = File.join(path, fn)
        if File.exist?(full_path)
          Rake.load_rakefile(full_path)
          loaded << fn
          return true
        end
      end
      fail LoadError, "Can't find #{file_name}"
    end

    def find_rakefile_location # :nodoc:
      here = Dir.pwd
      until (fn = have_rakefile)
        Dir.chdir("..")
        return nil if Dir.pwd == here || options.nosearch
        here = Dir.pwd
      end
      [fn, here]
    ensure
      Dir.chdir(Rake.original_dir)
    end

    def print_rakefile_directory(location) # :nodoc:
      $stderr.puts "(in #{Dir.pwd})" unless
        options.silent or original_dir == location
    end

    def raw_load_rakefile # :nodoc:
      rakefile, location = find_rakefile_location
      if (!options.ignore_system) &&
          (options.load_system || rakefile.nil?) &&
          system_dir && File.directory?(system_dir)
        print_rakefile_directory(location)
        glob("#{system_dir}/*.rake") do |name|
          add_import name
        end
      else
        fail "No Rakefile found (looking for: #{@rakefiles.join(', ')})" if
          rakefile.nil?
        @rakefile = rakefile
        Dir.chdir(location)
        print_rakefile_directory(location)
        Rake.load_rakefile(File.expand_path(@rakefile)) if
          @rakefile && @rakefile != ""
        options.rakelib.each do |rlib|
          glob("#{rlib}/*.rake") do |name|
            add_import name
          end
        end
      end
      load_imports
    end

    def glob(path, &block) # :nodoc:
      FileList.glob(path.tr("\\", "/")).each(&block)
    end
    private :glob

    # The directory path containing the system wide rakefiles.
    def system_dir # :nodoc:
      @system_dir ||=
        begin
          if ENV["RAKE_SYSTEM"]
            ENV["RAKE_SYSTEM"]
          else
            standard_system_dir
          end
        end
    end

    # The standard directory containing system wide rake files.
    if Win32.windows?
      def standard_system_dir #:nodoc:
        Win32.win32_system_dir
      end
    else
      def standard_system_dir #:nodoc:
        File.join(File.expand_path("~"), ".rake")
      end
    end
    private :standard_system_dir

    # Collect the list of tasks on the command line.  If no tasks are
    # given, return a list containing only the default task.
    # Environmental assignments are processed at this time as well.
    #
    # `args` is the list of arguments to peruse to get the list of tasks.
    # It should be the command line that was given to rake, less any
    # recognised command-line options, which OptionParser.parse will
    # have taken care of already.
    def collect_command_line_tasks(args) # :nodoc:
      @top_level_tasks = []
      args.each do |arg|
        if arg =~ /^(\w+)=(.*)$/m
          ENV[$1] = $2
        else
          @top_level_tasks << arg unless arg =~ /^-/
        end
      end
      @top_level_tasks.push(default_task_name) if @top_level_tasks.empty?
    end

    # Default task name ("default").
    # (May be overridden by subclasses)
    def default_task_name # :nodoc:
      "default"
    end

    # Add a file to the list of files to be imported.
    def add_import(fn) # :nodoc:
      @pending_imports << fn
    end

    # Load the pending list of imported files.
    def load_imports # :nodoc:
      while fn = @pending_imports.shift
        next if @imported.member?(fn)
        fn_task = lookup(fn) and fn_task.invoke
        ext = File.extname(fn)
        loader = @loaders[ext] || @default_loader
        loader.load(fn)
        if fn_task = lookup(fn) and fn_task.needed?
          fn_task.reenable
          fn_task.invoke
          loader.load(fn)
        end
        @imported << fn
      end
    end

    def rakefile_location(backtrace=caller) # :nodoc:
      backtrace.map { |t| t[/([^:]+):/, 1] }

      re = /^#{@rakefile}$/
      re = /#{re.source}/i if windows?

      backtrace.find { |str| str =~ re } || ""
    end

    def set_default_options # :nodoc:
      options.always_multitask           = false
      options.backtrace                  = false
      options.build_all                  = false
      options.dryrun                     = false
      options.ignore_deprecate           = false
      options.ignore_system              = false
      options.job_stats                  = false
      options.load_system                = false
      options.nosearch                   = false
      options.rakelib                    = %w[rakelib]
      options.show_all_tasks             = false
      options.show_prereqs               = false
      options.show_task_pattern          = nil
      options.show_tasks                 = nil
      options.silent                     = false
      options.suppress_backtrace_pattern = nil
      options.thread_pool_size           = Rake.suggested_thread_count
      options.trace                      = false
      options.trace_output               = $stderr
      options.trace_rules                = false
    end

  end
end
# frozen_string_literal: true
module Rake

  # The TaskManager module is a mixin for managing tasks.
  module TaskManager
    # Track the last comment made in the Rakefile.
    attr_accessor :last_description

    def initialize # :nodoc:
      super
      @tasks = Hash.new
      @rules = Array.new
      @scope = Scope.make
      @last_description = nil
    end

    def create_rule(*args, &block) # :nodoc:
      pattern, args, deps, order_only = resolve_args(args)
      pattern = Regexp.new(Regexp.quote(pattern) + "$") if String === pattern
      @rules << [pattern, args, deps, order_only, block]
    end

    def define_task(task_class, *args, &block) # :nodoc:
      task_name, arg_names, deps, order_only = resolve_args(args)

      original_scope = @scope
      if String === task_name and
         not task_class.ancestors.include? Rake::FileTask
        task_name, *definition_scope = *(task_name.split(":").reverse)
        @scope = Scope.make(*(definition_scope + @scope.to_a))
      end

      task_name = task_class.scope_name(@scope, task_name)
      task = intern(task_class, task_name)
      task.set_arg_names(arg_names) unless arg_names.empty?
      if Rake::TaskManager.record_task_metadata
        add_location(task)
        task.add_description(get_description(task))
      end
      task.enhance(Task.format_deps(deps), &block)
      task | order_only unless order_only.nil?
      task
    ensure
      @scope = original_scope
    end

    # Lookup a task.  Return an existing task if found, otherwise
    # create a task of the current type.
    def intern(task_class, task_name)
      @tasks[task_name.to_s] ||= task_class.new(task_name, self)
    end

    # Find a matching task for +task_name+.
    def [](task_name, scopes=nil)
      task_name = task_name.to_s
      self.lookup(task_name, scopes) or
        enhance_with_matching_rule(task_name) or
        synthesize_file_task(task_name) or
        fail generate_message_for_undefined_task(task_name)
    end

    def generate_message_for_undefined_task(task_name)
      message = "Don't know how to build task '#{task_name}' "\
                "(See the list of available tasks with `#{Rake.application.name} --tasks`)"
      message + generate_did_you_mean_suggestions(task_name)
    end

    def generate_did_you_mean_suggestions(task_name)
      return "" unless defined?(::DidYouMean::SpellChecker)

      suggestions = ::DidYouMean::SpellChecker.new(dictionary: @tasks.keys).correct(task_name.to_s)
      if ::DidYouMean.respond_to?(:formatter)# did_you_mean v1.2.0 or later
        ::DidYouMean.formatter.message_for(suggestions)
      elsif defined?(::DidYouMean::Formatter) # before did_you_mean v1.2.0
        ::DidYouMean::Formatter.new(suggestions).to_s
      else
        ""
      end
    end

    def synthesize_file_task(task_name) # :nodoc:
      return nil unless File.exist?(task_name)
      define_task(Rake::FileTask, task_name)
    end

    # Resolve the arguments for a task/rule.  Returns a tuple of
    # [task_name, arg_name_list, prerequisites, order_only_prerequisites].
    def resolve_args(args)
      if args.last.is_a?(Hash)
        deps = args.pop
        resolve_args_with_dependencies(args, deps)
      else
        resolve_args_without_dependencies(args)
      end
    end

    # Resolve task arguments for a task or rule when there are no
    # dependencies declared.
    #
    # The patterns recognized by this argument resolving function are:
    #
    #   task :t
    #   task :t, [:a]
    #
    def resolve_args_without_dependencies(args)
      task_name = args.shift
      if args.size == 1 && args.first.respond_to?(:to_ary)
        arg_names = args.first.to_ary
      else
        arg_names = args
      end
      [task_name, arg_names, [], nil]
    end
    private :resolve_args_without_dependencies

    # Resolve task arguments for a task or rule when there are
    # dependencies declared.
    #
    # The patterns recognized by this argument resolving function are:
    #
    #   task :t, order_only: [:e]
    #   task :t => [:d]
    #   task :t => [:d], order_only: [:e]
    #   task :t, [a] => [:d]
    #   task :t, [a] => [:d], order_only: [:e]
    #
    def resolve_args_with_dependencies(args, hash) # :nodoc:
      fail "Task Argument Error" if
        hash.size != 1 &&
        (hash.size != 2 || !hash.key?(:order_only))
      order_only = hash.delete(:order_only)
      key, value = hash.map { |k, v| [k, v] }.first
      if args.empty?
        task_name = key
        arg_names = []
        deps = value || []
      else
        task_name = args.shift
        arg_names = key || args.shift|| []
        deps = value || []
      end
      deps = [deps] unless deps.respond_to?(:to_ary)
      [task_name, arg_names, deps, order_only]
    end
    private :resolve_args_with_dependencies

    # If a rule can be found that matches the task name, enhance the
    # task with the prerequisites and actions from the rule.  Set the
    # source attribute of the task appropriately for the rule.  Return
    # the enhanced task or nil of no rule was found.
    def enhance_with_matching_rule(task_name, level=0)
      fail Rake::RuleRecursionOverflowError,
        "Rule Recursion Too Deep" if level >= 16
      @rules.each do |pattern, args, extensions, order_only, block|
        if pattern && pattern.match(task_name)
          task = attempt_rule(task_name, pattern, args, extensions, block, level)
          task | order_only unless order_only.nil?
          return task if task
        end
      end
      nil
    rescue Rake::RuleRecursionOverflowError => ex
      ex.add_target(task_name)
      fail ex
    end

    # List of all defined tasks in this application.
    def tasks
      @tasks.values.sort_by { |t| t.name }
    end

    # List of all the tasks defined in the given scope (and its
    # sub-scopes).
    def tasks_in_scope(scope)
      prefix = scope.path
      tasks.select { |t|
        /^#{prefix}:/ =~ t.name
      }
    end

    # Clear all tasks in this application.
    def clear
      @tasks.clear
      @rules.clear
    end

    # Lookup a task, using scope and the scope hints in the task name.
    # This method performs straight lookups without trying to
    # synthesize file tasks or rules.  Special scope names (e.g. '^')
    # are recognized.  If no scope argument is supplied, use the
    # current scope.  Return nil if the task cannot be found.
    def lookup(task_name, initial_scope=nil)
      initial_scope ||= @scope
      task_name = task_name.to_s
      if task_name =~ /^rake:/
        scopes = Scope.make
        task_name = task_name.sub(/^rake:/, "")
      elsif task_name =~ /^(\^+)/
        scopes = initial_scope.trim($1.size)
        task_name = task_name.sub(/^(\^+)/, "")
      else
        scopes = initial_scope
      end
      lookup_in_scope(task_name, scopes)
    end

    # Lookup the task name
    def lookup_in_scope(name, scope)
      loop do
        tn = scope.path_with_task_name(name)
        task = @tasks[tn]
        return task if task
        break if scope.empty?
        scope = scope.tail
      end
      nil
    end
    private :lookup_in_scope

    # Return the list of scope names currently active in the task
    # manager.
    def current_scope
      @scope
    end

    # Evaluate the block in a nested namespace named +name+.  Create
    # an anonymous namespace if +name+ is nil.
    def in_namespace(name)
      name ||= generate_name
      @scope = Scope.new(name, @scope)
      ns = NameSpace.new(self, @scope)
      yield(ns)
      ns
    ensure
      @scope = @scope.tail
    end

    private

    # Add a location to the locations field of the given task.
    def add_location(task)
      loc = find_location
      task.locations << loc if loc
      task
    end

    # Find the location that called into the dsl layer.
    def find_location
      locations = caller
      i = 0
      while locations[i]
        return locations[i + 1] if locations[i] =~ /rake\/dsl_definition.rb/
        i += 1
      end
      nil
    end

    # Generate an anonymous namespace name.
    def generate_name
      @seed ||= 0
      @seed += 1
      "_anon_#{@seed}"
    end

    def trace_rule(level, message) # :nodoc:
      options.trace_output.puts "#{"    " * level}#{message}" if
        Rake.application.options.trace_rules
    end

    # Attempt to create a rule given the list of prerequisites.
    def attempt_rule(task_name, task_pattern, args, extensions, block, level)
      sources = make_sources(task_name, task_pattern, extensions)
      prereqs = sources.map { |source|
        trace_rule level, "Attempting Rule #{task_name} => #{source}"
        if File.exist?(source) || Rake::Task.task_defined?(source)
          trace_rule level, "(#{task_name} => #{source} ... EXIST)"
          source
        elsif parent = enhance_with_matching_rule(source, level + 1)
          trace_rule level, "(#{task_name} => #{source} ... ENHANCE)"
          parent.name
        else
          trace_rule level, "(#{task_name} => #{source} ... FAIL)"
          return nil
        end
      }
      task = FileTask.define_task(task_name, { args => prereqs }, &block)
      task.sources = prereqs
      task
    end

    # Make a list of sources from the list of file name extensions /
    # translation procs.
    def make_sources(task_name, task_pattern, extensions)
      result = extensions.map { |ext|
        case ext
        when /%/
          task_name.pathmap(ext)
        when %r{/}
          ext
        when /^\./
          source = task_name.sub(task_pattern, ext)
          source == ext ? task_name.ext(ext) : source
        when String
          ext
        when Proc, Method
          if ext.arity == 1
            ext.call(task_name)
          else
            ext.call
          end
        else
          fail "Don't know how to handle rule dependent: #{ext.inspect}"
        end
      }
      result.flatten
    end

    # Return the current description, clearing it in the process.
    def get_description(task)
      desc = @last_description
      @last_description = nil
      desc
    end

    class << self
      attr_accessor :record_task_metadata # :nodoc:
      TaskManager.record_task_metadata = false
    end
  end

end
# frozen_string_literal: true
# Rake DSL functions.
require "rake/file_utils_ext"

module Rake

  ##
  # DSL is a module that provides #task, #desc, #namespace, etc.  Use this
  # when you'd like to use rake outside the top level scope.
  #
  # For a Rakefile you run from the command line this module is automatically
  # included.

  module DSL

    #--
    # Include the FileUtils file manipulation functions in the top
    # level module, but mark them private so that they don't
    # unintentionally define methods on other objects.
    #++

    include FileUtilsExt
    private(*FileUtils.instance_methods(false))
    private(*FileUtilsExt.instance_methods(false))

    private

    # :call-seq:
    #   task(task_name)
    #   task(task_name: dependencies)
    #   task(task_name, arguments => dependencies)
    #
    # Declare a basic task.  The +task_name+ is always the first argument.  If
    # the task name contains a ":" it is defined in that namespace.
    #
    # The +dependencies+ may be a single task name or an Array of task names.
    # The +argument+ (a single name) or +arguments+ (an Array of names) define
    # the arguments provided to the task.
    #
    # The task, argument and dependency names may be either symbols or
    # strings.
    #
    # A task with a single dependency:
    #
    #   task clobber: %w[clean] do
    #     rm_rf "html"
    #   end
    #
    # A task with an argument and a dependency:
    #
    #   task :package, [:version] => :test do |t, args|
    #     # ...
    #   end
    #
    # To invoke this task from the command line:
    #
    #   $ rake package[1.2.3]
    #
    def task(*args, &block) # :doc:
      Rake::Task.define_task(*args, &block)
    end

    # Declare a file task.
    #
    # Example:
    #   file "config.cfg" => ["config.template"] do
    #     open("config.cfg", "w") do |outfile|
    #       open("config.template") do |infile|
    #         while line = infile.gets
    #           outfile.puts line
    #         end
    #       end
    #     end
    #  end
    #
    def file(*args, &block) # :doc:
      Rake::FileTask.define_task(*args, &block)
    end

    # Declare a file creation task.
    # (Mainly used for the directory command).
    def file_create(*args, &block)
      Rake::FileCreationTask.define_task(*args, &block)
    end

    # Declare a set of files tasks to create the given directories on
    # demand.
    #
    # Example:
    #   directory "testdata/doc"
    #
    def directory(*args, &block) # :doc:
      result = file_create(*args, &block)
      dir, _ = *Rake.application.resolve_args(args)
      dir = Rake.from_pathname(dir)
      Rake.each_dir_parent(dir) do |d|
        file_create d do |t|
          mkdir_p t.name unless File.exist?(t.name)
        end
      end
      result
    end

    # Declare a task that performs its prerequisites in
    # parallel. Multitasks does *not* guarantee that its prerequisites
    # will execute in any given order (which is obvious when you think
    # about it)
    #
    # Example:
    #   multitask deploy: %w[deploy_gem deploy_rdoc]
    #
    def multitask(*args, &block) # :doc:
      Rake::MultiTask.define_task(*args, &block)
    end

    # Create a new rake namespace and use it for evaluating the given
    # block.  Returns a NameSpace object that can be used to lookup
    # tasks defined in the namespace.
    #
    # Example:
    #
    #   ns = namespace "nested" do
    #     # the "nested:run" task
    #     task :run
    #   end
    #   task_run = ns[:run] # find :run in the given namespace.
    #
    # Tasks can also be defined in a namespace by using a ":" in the task
    # name:
    #
    #   task "nested:test" do
    #     # ...
    #   end
    #
    def namespace(name=nil, &block) # :doc:
      name = name.to_s if name.kind_of?(Symbol)
      name = name.to_str if name.respond_to?(:to_str)
      unless name.kind_of?(String) || name.nil?
        raise ArgumentError, "Expected a String or Symbol for a namespace name"
      end
      Rake.application.in_namespace(name, &block)
    end

    # Declare a rule for auto-tasks.
    #
    # Example:
    #  rule '.o' => '.c' do |t|
    #    sh 'cc', '-o', t.name, t.source
    #  end
    #
    def rule(*args, &block) # :doc:
      Rake::Task.create_rule(*args, &block)
    end

    # Describes the next rake task.  Duplicate descriptions are discarded.
    # Descriptions are shown with <code>rake -T</code> (up to the first
    # sentence) and <code>rake -D</code> (the entire description).
    #
    # Example:
    #   desc "Run the Unit Tests"
    #   task test: [:build]
    #     # ... run tests
    #   end
    #
    def desc(description) # :doc:
      Rake.application.last_description = description
    end

    # Import the partial Rakefiles +fn+.  Imported files are loaded
    # _after_ the current file is completely loaded.  This allows the
    # import statement to appear anywhere in the importing file, and yet
    # allowing the imported files to depend on objects defined in the
    # importing file.
    #
    # A common use of the import statement is to include files
    # containing dependency declarations.
    #
    # See also the --rakelibdir command line option.
    #
    # Example:
    #   import ".depend", "my_rules"
    #
    def import(*fns) # :doc:
      fns.each do |fn|
        Rake.application.add_import(fn)
      end
    end
  end
  extend FileUtilsExt
end

# Extend the main object with the DSL commands. This allows top-level
# calls to task, etc. to work from a Rakefile without polluting the
# object inheritance tree.
self.extend Rake::DSL
# frozen_string_literal: true
module Rake

  # Polylithic linked list structure used to implement several data
  # structures in Rake.
  class LinkedList
    include Enumerable
    attr_reader :head, :tail

    # Polymorphically add a new element to the head of a list. The
    # type of head node will be the same list type as the tail.
    def conj(item)
      self.class.cons(item, self)
    end

    # Is the list empty?
    # .make guards against a list being empty making any instantiated LinkedList
    # object not empty by default
    # You should consider overriding this method if you implement your own .make method
    def empty?
      false
    end

    # Lists are structurally equivalent.
    def ==(other)
      current = self
      while !current.empty? && !other.empty?
        return false if current.head != other.head
        current = current.tail
        other = other.tail
      end
      current.empty? && other.empty?
    end

    # Convert to string: LL(item, item...)
    def to_s
      items = map(&:to_s).join(", ")
      "LL(#{items})"
    end

    # Same as +to_s+, but with inspected items.
    def inspect
      items = map(&:inspect).join(", ")
      "LL(#{items})"
    end

    # For each item in the list.
    def each
      current = self
      while !current.empty?
        yield(current.head)
        current = current.tail
      end
      self
    end

    # Make a list out of the given arguments. This method is
    # polymorphic
    def self.make(*args)
      # return an EmptyLinkedList if there are no arguments
      return empty if !args || args.empty?

      # build a LinkedList by starting at the tail and iterating
      # through each argument
      # inject takes an EmptyLinkedList to start
      args.reverse.inject(empty) do |list, item|
        list = cons(item, list)
        list # return the newly created list for each item in the block
      end
    end

    # Cons a new head onto the tail list.
    def self.cons(head, tail)
      new(head, tail)
    end

    # The standard empty list class for the given LinkedList class.
    def self.empty
      self::EMPTY
    end

    protected

    def initialize(head, tail=EMPTY)
      @head = head
      @tail = tail
    end

    # Represent an empty list, using the Null Object Pattern.
    #
    # When inheriting from the LinkedList class, you should implement
    # a type specific Empty class as well. Make sure you set the class
    # instance variable @parent to the associated list class (this
    # allows conj, cons and make to work polymorphically).
    class EmptyLinkedList < LinkedList
      @parent = LinkedList

      def initialize
      end

      def empty?
        true
      end

      def self.cons(head, tail)
        @parent.cons(head, tail)
      end
    end

    EMPTY = EmptyLinkedList.new
  end
end
# frozen_string_literal: true
module Rake

  # Same as a regular task, but the immediate prerequisites are done in
  # parallel using Ruby threads.
  #
  class MultiTask < Task
    private

    def invoke_prerequisites(task_args, invocation_chain) # :nodoc:
      invoke_prerequisites_concurrently(task_args, invocation_chain)
    end
  end
end
# frozen_string_literal: true
require "rake"

# Load the test files from the command line.
argv = ARGV.select do |argument|
  begin
    case argument
    when /^-/ then
      argument
    when /\*/ then
      FileList[argument].to_a.each do |file|
        require File.expand_path file
      end

      false
    else
      require File.expand_path argument

      false
    end
  rescue LoadError => e
    raise unless e.path
    abort "\nFile does not exist: #{e.path}\n\n"
  end
end

ARGV.replace argv
# frozen_string_literal: true
module Rake

  ##
  # Exit status class for times the system just gives us a nil.
  class PseudoStatus # :nodoc: all
    attr_reader :exitstatus

    def initialize(code=0)
      @exitstatus = code
    end

    def to_i
      @exitstatus << 8
    end

    def >>(n)
      to_i >> n
    end

    def stopped?
      false
    end

    def exited?
      true
    end
  end

end
# frozen_string_literal: true
require "rake/cloneable"
require "rake/file_utils_ext"
require "rake/ext/string"

module Rake

  ##
  # A FileList is essentially an array with a few helper methods defined to
  # make file manipulation a bit easier.
  #
  # FileLists are lazy.  When given a list of glob patterns for possible files
  # to be included in the file list, instead of searching the file structures
  # to find the files, a FileList holds the pattern for latter use.
  #
  # This allows us to define a number of FileList to match any number of
  # files, but only search out the actual files when then FileList itself is
  # actually used.  The key is that the first time an element of the
  # FileList/Array is requested, the pending patterns are resolved into a real
  # list of file names.
  #
  class FileList

    include Cloneable

    # == Method Delegation
    #
    # The lazy evaluation magic of FileLists happens by implementing all the
    # array specific methods to call +resolve+ before delegating the heavy
    # lifting to an embedded array object (@items).
    #
    # In addition, there are two kinds of delegation calls.  The regular kind
    # delegates to the @items array and returns the result directly.  Well,
    # almost directly.  It checks if the returned value is the @items object
    # itself, and if so will return the FileList object instead.
    #
    # The second kind of delegation call is used in methods that normally
    # return a new Array object.  We want to capture the return value of these
    # methods and wrap them in a new FileList object.  We enumerate these
    # methods in the +SPECIAL_RETURN+ list below.

    # List of array methods (that are not in +Object+) that need to be
    # delegated.
    ARRAY_METHODS = (Array.instance_methods - Object.instance_methods).map(&:to_s)

    # List of additional methods that must be delegated.
    MUST_DEFINE = %w[inspect <=>]

    # List of methods that should not be delegated here (we define special
    # versions of them explicitly below).
    MUST_NOT_DEFINE = %w[to_a to_ary partition * <<]

    # List of delegated methods that return new array values which need
    # wrapping.
    SPECIAL_RETURN = %w[
      map collect sort sort_by select find_all reject grep
      compact flatten uniq values_at
      + - & |
    ]

    DELEGATING_METHODS = (ARRAY_METHODS + MUST_DEFINE - MUST_NOT_DEFINE).map(&:to_s).sort.uniq

    # Now do the delegation.
    DELEGATING_METHODS.each do |sym|
      if SPECIAL_RETURN.include?(sym)
        ln = __LINE__ + 1
        class_eval %{
          def #{sym}(*args, &block)
            resolve
            result = @items.send(:#{sym}, *args, &block)
            self.class.new.import(result)
          end
        }, __FILE__, ln
      else
        ln = __LINE__ + 1
        class_eval %{
          def #{sym}(*args, &block)
            resolve
            result = @items.send(:#{sym}, *args, &block)
            result.object_id == @items.object_id ? self : result
          end
        }, __FILE__, ln
      end
    end

    GLOB_PATTERN = %r{[*?\[\{]}

    # Create a file list from the globbable patterns given.  If you wish to
    # perform multiple includes or excludes at object build time, use the
    # "yield self" pattern.
    #
    # Example:
    #   file_list = FileList.new('lib/**/*.rb', 'test/test*.rb')
    #
    #   pkg_files = FileList.new('lib/**/*') do |fl|
    #     fl.exclude(/\bCVS\b/)
    #   end
    #
    def initialize(*patterns)
      @pending_add = []
      @pending = false
      @exclude_patterns = DEFAULT_IGNORE_PATTERNS.dup
      @exclude_procs = DEFAULT_IGNORE_PROCS.dup
      @items = []
      patterns.each { |pattern| include(pattern) }
      yield self if block_given?
    end

    # Add file names defined by glob patterns to the file list.  If an array
    # is given, add each element of the array.
    #
    # Example:
    #   file_list.include("*.java", "*.cfg")
    #   file_list.include %w( math.c lib.h *.o )
    #
    def include(*filenames)
      # TODO: check for pending
      filenames.each do |fn|
        if fn.respond_to? :to_ary
          include(*fn.to_ary)
        else
          @pending_add << Rake.from_pathname(fn)
        end
      end
      @pending = true
      self
    end
    alias :add :include

    # Register a list of file name patterns that should be excluded from the
    # list.  Patterns may be regular expressions, glob patterns or regular
    # strings.  In addition, a block given to exclude will remove entries that
    # return true when given to the block.
    #
    # Note that glob patterns are expanded against the file system. If a file
    # is explicitly added to a file list, but does not exist in the file
    # system, then an glob pattern in the exclude list will not exclude the
    # file.
    #
    # Examples:
    #   FileList['a.c', 'b.c'].exclude("a.c") => ['b.c']
    #   FileList['a.c', 'b.c'].exclude(/^a/)  => ['b.c']
    #
    # If "a.c" is a file, then ...
    #   FileList['a.c', 'b.c'].exclude("a.*") => ['b.c']
    #
    # If "a.c" is not a file, then ...
    #   FileList['a.c', 'b.c'].exclude("a.*") => ['a.c', 'b.c']
    #
    def exclude(*patterns, &block)
      patterns.each do |pat|
        if pat.respond_to? :to_ary
          exclude(*pat.to_ary)
        else
          @exclude_patterns << Rake.from_pathname(pat)
        end
      end
      @exclude_procs << block if block_given?
      resolve_exclude unless @pending
      self
    end

    # Clear all the exclude patterns so that we exclude nothing.
    def clear_exclude
      @exclude_patterns = []
      @exclude_procs = []
      self
    end

    # A FileList is equal through array equality.
    def ==(array)
      to_ary == array
    end

    # Return the internal array object.
    def to_a
      resolve
      @items
    end

    # Return the internal array object.
    def to_ary
      to_a
    end

    # Lie about our class.
    def is_a?(klass)
      klass == Array || super(klass)
    end
    alias kind_of? is_a?

    # Redefine * to return either a string or a new file list.
    def *(other)
      result = @items * other
      case result
      when Array
        self.class.new.import(result)
      else
        result
      end
    end

    def <<(obj)
      resolve
      @items << Rake.from_pathname(obj)
      self
    end

    # Resolve all the pending adds now.
    def resolve
      if @pending
        @pending = false
        @pending_add.each do |fn| resolve_add(fn) end
        @pending_add = []
        resolve_exclude
      end
      self
    end

    def resolve_add(fn) # :nodoc:
      case fn
      when GLOB_PATTERN
        add_matching(fn)
      else
        self << fn
      end
    end
    private :resolve_add

    def resolve_exclude # :nodoc:
      reject! { |fn| excluded_from_list?(fn) }
      self
    end
    private :resolve_exclude

    # Return a new FileList with the results of running +sub+ against each
    # element of the original list.
    #
    # Example:
    #   FileList['a.c', 'b.c'].sub(/\.c$/, '.o')  => ['a.o', 'b.o']
    #
    def sub(pat, rep)
      inject(self.class.new) { |res, fn| res << fn.sub(pat, rep) }
    end

    # Return a new FileList with the results of running +gsub+ against each
    # element of the original list.
    #
    # Example:
    #   FileList['lib/test/file', 'x/y'].gsub(/\//, "\\")
    #      => ['lib\\test\\file', 'x\\y']
    #
    def gsub(pat, rep)
      inject(self.class.new) { |res, fn| res << fn.gsub(pat, rep) }
    end

    # Same as +sub+ except that the original file list is modified.
    def sub!(pat, rep)
      each_with_index { |fn, i| self[i] = fn.sub(pat, rep) }
      self
    end

    # Same as +gsub+ except that the original file list is modified.
    def gsub!(pat, rep)
      each_with_index { |fn, i| self[i] = fn.gsub(pat, rep) }
      self
    end

    # Apply the pathmap spec to each of the included file names, returning a
    # new file list with the modified paths.  (See String#pathmap for
    # details.)
    def pathmap(spec=nil, &block)
      collect { |fn| fn.pathmap(spec, &block) }
    end

    # Return a new FileList with <tt>String#ext</tt> method applied to
    # each member of the array.
    #
    # This method is a shortcut for:
    #
    #    array.collect { |item| item.ext(newext) }
    #
    # +ext+ is a user added method for the Array class.
    def ext(newext="")
      collect { |fn| fn.ext(newext) }
    end

    # Grep each of the files in the filelist using the given pattern. If a
    # block is given, call the block on each matching line, passing the file
    # name, line number, and the matching line of text.  If no block is given,
    # a standard emacs style file:linenumber:line message will be printed to
    # standard out.  Returns the number of matched items.
    def egrep(pattern, *options)
      matched = 0
      each do |fn|
        begin
          File.open(fn, "r", *options) do |inf|
            count = 0
            inf.each do |line|
              count += 1
              if pattern.match(line)
                matched += 1
                if block_given?
                  yield fn, count, line
                else
                  puts "#{fn}:#{count}:#{line}"
                end
              end
            end
          end
        rescue StandardError => ex
          $stderr.puts "Error while processing '#{fn}': #{ex}"
        end
      end
      matched
    end

    # Return a new file list that only contains file names from the current
    # file list that exist on the file system.
    def existing
      select { |fn| File.exist?(fn) }.uniq
    end

    # Modify the current file list so that it contains only file name that
    # exist on the file system.
    def existing!
      resolve
      @items = @items.select { |fn| File.exist?(fn) }.uniq
      self
    end

    # FileList version of partition.  Needed because the nested arrays should
    # be FileLists in this version.
    def partition(&block)       # :nodoc:
      resolve
      result = @items.partition(&block)
      [
        self.class.new.import(result[0]),
        self.class.new.import(result[1]),
      ]
    end

    # Convert a FileList to a string by joining all elements with a space.
    def to_s
      resolve
      self.join(" ")
    end

    # Add matching glob patterns.
    def add_matching(pattern)
      self.class.glob(pattern).each do |fn|
        self << fn unless excluded_from_list?(fn)
      end
    end
    private :add_matching

    # Should the given file name be excluded from the list?
    #
    # NOTE: This method was formerly named "exclude?", but Rails
    # introduced an exclude? method as an array method and setup a
    # conflict with file list. We renamed the method to avoid
    # confusion. If you were using "FileList#exclude?" in your user
    # code, you will need to update.
    def excluded_from_list?(fn)
      return true if @exclude_patterns.any? do |pat|
        case pat
        when Regexp
          fn =~ pat
        when GLOB_PATTERN
          flags = File::FNM_PATHNAME
          # Ruby <= 1.9.3 does not support File::FNM_EXTGLOB
          flags |= File::FNM_EXTGLOB if defined? File::FNM_EXTGLOB
          File.fnmatch?(pat, fn, flags)
        else
          fn == pat
        end
      end
      @exclude_procs.any? { |p| p.call(fn) }
    end

    DEFAULT_IGNORE_PATTERNS = [
      /(^|[\/\\])CVS([\/\\]|$)/,
      /(^|[\/\\])\.svn([\/\\]|$)/,
      /\.bak$/,
      /~$/
    ]
    DEFAULT_IGNORE_PROCS = [
      proc { |fn| fn =~ /(^|[\/\\])core$/ && !File.directory?(fn) }
    ]

    def import(array) # :nodoc:
      @items = array
      self
    end

    class << self
      # Create a new file list including the files listed. Similar to:
      #
      #   FileList.new(*args)
      def [](*args)
        new(*args)
      end

      # Get a sorted list of files matching the pattern. This method
      # should be preferred to Dir[pattern] and Dir.glob(pattern) because
      # the files returned are guaranteed to be sorted.
      def glob(pattern, *args)
        Dir.glob(pattern, *args).sort
      end
    end
  end
end

module Rake
  class << self

    # Yield each file or directory component.
    def each_dir_parent(dir)    # :nodoc:
      old_length = nil
      while dir != "." && dir.length != old_length
        yield(dir)
        old_length = dir.length
        dir = File.dirname(dir)
      end
    end

    # Convert Pathname and Pathname-like objects to strings;
    # leave everything else alone
    def from_pathname(path)    # :nodoc:
      path = path.to_path if path.respond_to?(:to_path)
      path = path.to_str if path.respond_to?(:to_str)
      path
    end
  end
end # module Rake
# frozen_string_literal: true
module Rake
  class Scope < LinkedList # :nodoc: all

    # Path for the scope.
    def path
      map(&:to_s).reverse.join(":")
    end

    # Path for the scope + the named path.
    def path_with_task_name(task_name)
      "#{path}:#{task_name}"
    end

    # Trim +n+ innermost scope levels from the scope. In no case will
    # this trim beyond the toplevel scope.
    def trim(n)
      result = self
      while n > 0 && !result.empty?
        result = result.tail
        n -= 1
      end
      result
    end

    # Scope lists always end with an EmptyScope object. See Null
    # Object Pattern)
    class EmptyScope < EmptyLinkedList
      @parent = Scope

      def path
        ""
      end

      def path_with_task_name(task_name)
        task_name
      end
    end

    # Singleton null object for an empty scope.
    EMPTY = EmptyScope.new
  end
end
# frozen_string_literal: true
class Module
  # Check for an existing method in the current class before extending.  If
  # the method already exists, then a warning is printed and the extension is
  # not added.  Otherwise the block is yielded and any definitions in the
  # block will take effect.
  #
  # Usage:
  #
  #   class String
  #     rake_extension("xyz") do
  #       def xyz
  #         ...
  #       end
  #     end
  #   end
  #
  def rake_extension(method) # :nodoc:
    if method_defined?(method)
      $stderr.puts "WARNING: Possible conflict with Rake extension: " +
        "#{self}##{method} already exists"
    else
      yield
    end
  end
end
# frozen_string_literal: true
require "rake/ext/core"

class String

  rake_extension("ext") do
    # Replace the file extension with +newext+.  If there is no extension on
    # the string, append the new extension to the end.  If the new extension
    # is not given, or is the empty string, remove any existing extension.
    #
    # +ext+ is a user added method for the String class.
    #
    # This String extension comes from Rake
    def ext(newext="")
      return self.dup if [".", ".."].include? self
      if newext != ""
        newext = "." + newext unless newext =~ /^\./
      end
      self.chomp(File.extname(self)) << newext
    end
  end

  rake_extension("pathmap") do
    # Explode a path into individual components.  Used by +pathmap+.
    #
    # This String extension comes from Rake
    def pathmap_explode
      head, tail = File.split(self)
      return [self] if head == self
      return [tail] if head == "." || tail == "/"
      return [head, tail] if head == "/"
      return head.pathmap_explode + [tail]
    end
    protected :pathmap_explode

    # Extract a partial path from the path.  Include +n+ directories from the
    # front end (left hand side) if +n+ is positive.  Include |+n+|
    # directories from the back end (right hand side) if +n+ is negative.
    #
    # This String extension comes from Rake
    def pathmap_partial(n)
      dirs = File.dirname(self).pathmap_explode
      partial_dirs =
        if n > 0
          dirs[0...n]
        elsif n < 0
          dirs.reverse[0...-n].reverse
        else
          "."
        end
      File.join(partial_dirs)
    end
    protected :pathmap_partial

    # Perform the pathmap replacement operations on the given path. The
    # patterns take the form 'pat1,rep1;pat2,rep2...'.
    #
    # This String extension comes from Rake
    def pathmap_replace(patterns, &block)
      result = self
      patterns.split(";").each do |pair|
        pattern, replacement = pair.split(",")
        pattern = Regexp.new(pattern)
        if replacement == "*" && block_given?
          result = result.sub(pattern, &block)
        elsif replacement
          result = result.sub(pattern, replacement)
        else
          result = result.sub(pattern, "")
        end
      end
      result
    end
    protected :pathmap_replace

    # Map the path according to the given specification.  The specification
    # controls the details of the mapping.  The following special patterns are
    # recognized:
    #
    # <tt>%p</tt> :: The complete path.
    # <tt>%f</tt> :: The base file name of the path, with its file extension,
    #                but without any directories.
    # <tt>%n</tt> :: The file name of the path without its file extension.
    # <tt>%d</tt> :: The directory list of the path.
    # <tt>%x</tt> :: The file extension of the path.  An empty string if there
    #                is no extension.
    # <tt>%X</tt> :: Everything *but* the file extension.
    # <tt>%s</tt> :: The alternate file separator if defined, otherwise use #
    #                the standard file separator.
    # <tt>%%</tt> :: A percent sign.
    #
    # The <tt>%d</tt> specifier can also have a numeric prefix (e.g. '%2d').
    # If the number is positive, only return (up to) +n+ directories in the
    # path, starting from the left hand side.  If +n+ is negative, return (up
    # to) +n+ directories from the right hand side of the path.
    #
    # Examples:
    #
    #   'a/b/c/d/file.txt'.pathmap("%2d")   => 'a/b'
    #   'a/b/c/d/file.txt'.pathmap("%-2d")  => 'c/d'
    #
    # Also the <tt>%d</tt>, <tt>%p</tt>, <tt>%f</tt>, <tt>%n</tt>,
    # <tt>%x</tt>, and <tt>%X</tt> operators can take a pattern/replacement
    # argument to perform simple string substitutions on a particular part of
    # the path.  The pattern and replacement are separated by a comma and are
    # enclosed by curly braces.  The replacement spec comes after the %
    # character but before the operator letter.  (e.g. "%{old,new}d").
    # Multiple replacement specs should be separated by semi-colons (e.g.
    # "%{old,new;src,bin}d").
    #
    # Regular expressions may be used for the pattern, and back refs may be
    # used in the replacement text.  Curly braces, commas and semi-colons are
    # excluded from both the pattern and replacement text (let's keep parsing
    # reasonable).
    #
    # For example:
    #
    #    "src/org/onestepback/proj/A.java".pathmap("%{^src,class}X.class")
    #
    # returns:
    #
    #    "class/org/onestepback/proj/A.class"
    #
    # If the replacement text is '*', then a block may be provided to perform
    # some arbitrary calculation for the replacement.
    #
    # For example:
    #
    #   "/path/to/file.TXT".pathmap("%X%{.*,*}x") { |ext|
    #      ext.downcase
    #   }
    #
    # Returns:
    #
    #  "/path/to/file.txt"
    #
    # This String extension comes from Rake
    def pathmap(spec=nil, &block)
      return self if spec.nil?
      result = "".dup
      spec.scan(/%\{[^}]*\}-?\d*[sdpfnxX%]|%-?\d+d|%.|[^%]+/) do |frag|
        case frag
        when "%f"
          result << File.basename(self)
        when "%n"
          result << File.basename(self).ext
        when "%d"
          result << File.dirname(self)
        when "%x"
          result << File.extname(self)
        when "%X"
          result << self.ext
        when "%p"
          result << self
        when "%s"
          result << (File::ALT_SEPARATOR || File::SEPARATOR)
        when "%-"
          # do nothing
        when "%%"
          result << "%"
        when /%(-?\d+)d/
          result << pathmap_partial($1.to_i)
        when /^%\{([^}]*)\}(\d*[dpfnxX])/
          patterns, operator = $1, $2
          result << pathmap("%" + operator).pathmap_replace(patterns, &block)
        when /^%/
          fail ArgumentError, "Unknown pathmap specifier #{frag} in '#{spec}'"
        else
          result << frag
        end
      end
      result
    end
  end

end
# frozen_string_literal: true
require "rake/task"
require "rake/early_time"

module Rake

  # A FileTask is a task that includes time based dependencies.  If any of a
  # FileTask's prerequisites have a timestamp that is later than the file
  # represented by this task, then the file must be rebuilt (using the
  # supplied actions).
  #
  class FileTask < Task

    # Is this file task needed?  Yes if it doesn't exist, or if its time stamp
    # is out of date.
    def needed?
      !File.exist?(name) || out_of_date?(timestamp) || @application.options.build_all
    end

    # Time stamp for file task.
    def timestamp
      if File.exist?(name)
        File.mtime(name.to_s)
      else
        Rake::LATE
      end
    end

    private

    # Are there any prerequisites with a later time than the given time stamp?
    def out_of_date?(stamp)
      all_prerequisite_tasks.any? { |prereq|
        prereq_task = application[prereq, @scope]
        if prereq_task.instance_of?(Rake::FileTask)
          prereq_task.timestamp > stamp || @application.options.build_all
        else
          prereq_task.timestamp > stamp
        end
      }
    end

    # ----------------------------------------------------------------
    # Task class methods.
    #
    class << self
      # Apply the scope to the task name according to the rules for this kind
      # of task.  File based tasks ignore the scope when creating the name.
      def scope_name(scope, task_name)
        Rake.from_pathname(task_name)
      end
    end
  end
end
# frozen_string_literal: true
module Rake

  # Error indicating a recursion overflow error in task selection.
  class RuleRecursionOverflowError < StandardError
    def initialize(*args)
      super
      @targets = []
    end

    def add_target(target)
      @targets << target
    end

    def message
      super + ": [" + @targets.reverse.join(" => ") + "]"
    end
  end

end
# frozen_string_literal: true
require "set"

require "rake/promise"

module Rake

  class ThreadPool # :nodoc: all

    # Creates a ThreadPool object.  The +thread_count+ parameter is the size
    # of the pool.
    def initialize(thread_count)
      @max_active_threads = [thread_count, 0].max
      @threads = Set.new
      @threads_mon = Monitor.new
      @queue = Queue.new
      @join_cond = @threads_mon.new_cond

      @history_start_time = nil
      @history = []
      @history_mon = Monitor.new
      @total_threads_in_play = 0
    end

    # Creates a future executed by the +ThreadPool+.
    #
    # The args are passed to the block when executing (similarly to
    # Thread#new) The return value is an object representing
    # a future which has been created and added to the queue in the
    # pool. Sending #value to the object will sleep the
    # current thread until the future is finished and will return the
    # result (or raise an exception thrown from the future)
    def future(*args, &block)
      promise = Promise.new(args, &block)
      promise.recorder = lambda { |*stats| stat(*stats) }

      @queue.enq promise
      stat :queued, item_id: promise.object_id
      start_thread
      promise
    end

    # Waits until the queue of futures is empty and all threads have exited.
    def join
      @threads_mon.synchronize do
        begin
          stat :joining
          @join_cond.wait unless @threads.empty?
          stat :joined
        rescue Exception => e
          stat :joined
          $stderr.puts e
          $stderr.print "Queue contains #{@queue.size} items. " +
            "Thread pool contains #{@threads.count} threads\n"
          $stderr.print "Current Thread #{Thread.current} status = " +
            "#{Thread.current.status}\n"
          $stderr.puts e.backtrace.join("\n")
          @threads.each do |t|
            $stderr.print "Thread #{t} status = #{t.status}\n"
            $stderr.puts t.backtrace.join("\n")
          end
          raise e
        end
      end
    end

    # Enable the gathering of history events.
    def gather_history          #:nodoc:
      @history_start_time = Time.now if @history_start_time.nil?
    end

    # Return a array of history events for the thread pool.
    #
    # History gathering must be enabled to be able to see the events
    # (see #gather_history). Best to call this when the job is
    # complete (i.e. after ThreadPool#join is called).
    def history                 # :nodoc:
      @history_mon.synchronize { @history.dup }.
        sort_by { |i| i[:time] }.
        each { |i| i[:time] -= @history_start_time }
    end

    # Return a hash of always collected statistics for the thread pool.
    def statistics              #  :nodoc:
      {
        total_threads_in_play: @total_threads_in_play,
        max_active_threads: @max_active_threads,
      }
    end

    private

    # processes one item on the queue. Returns true if there was an
    # item to process, false if there was no item
    def process_queue_item      #:nodoc:
      return false if @queue.empty?

      # Even though we just asked if the queue was empty, it
      # still could have had an item which by this statement
      # is now gone. For this reason we pass true to Queue#deq
      # because we will sleep indefinitely if it is empty.
      promise = @queue.deq(true)
      stat :dequeued, item_id: promise.object_id
      promise.work
      return true

    rescue ThreadError # this means the queue is empty
      false
    end

    def safe_thread_count
      @threads_mon.synchronize do
        @threads.count
      end
    end

    def start_thread # :nodoc:
      @threads_mon.synchronize do
        next unless @threads.count < @max_active_threads

        t = Thread.new do
          begin
            while safe_thread_count <= @max_active_threads
              break unless process_queue_item
            end
          ensure
            @threads_mon.synchronize do
              @threads.delete Thread.current
              stat :ended, thread_count: @threads.count
              @join_cond.broadcast if @threads.empty?
            end
          end
        end

        @threads << t
        stat(
          :spawned,
          new_thread: t.object_id,
          thread_count: @threads.count)
        @total_threads_in_play = @threads.count if
          @threads.count > @total_threads_in_play
      end
    end

    def stat(event, data=nil) # :nodoc:
      return if @history_start_time.nil?
      info = {
        event: event,
        data: data,
        time: Time.now,
        thread: Thread.current.object_id,
      }
      @history_mon.synchronize { @history << info }
    end

    # for testing only

    def __queue__ # :nodoc:
      @queue
    end
  end

end
# frozen_string_literal: true
require "rake/invocation_exception_mixin"

module Rake

  ##
  # A Task is the basic unit of work in a Rakefile.  Tasks have associated
  # actions (possibly more than one) and a list of prerequisites.  When
  # invoked, a task will first ensure that all of its prerequisites have an
  # opportunity to run and then it will execute its own actions.
  #
  # Tasks are not usually created directly using the new method, but rather
  # use the +file+ and +task+ convenience methods.
  #
  class Task
    # List of prerequisites for a task.
    attr_reader :prerequisites
    alias prereqs prerequisites

    # List of order only prerequisites for a task.
    attr_reader :order_only_prerequisites

    # List of actions attached to a task.
    attr_reader :actions

    # Application owning this task.
    attr_accessor :application

    # Array of nested namespaces names used for task lookup by this task.
    attr_reader :scope

    # File/Line locations of each of the task definitions for this
    # task (only valid if the task was defined with the detect
    # location option set).
    attr_reader :locations

    # Has this task already been invoked?  Already invoked tasks
    # will be skipped unless you reenable them.
    attr_reader :already_invoked

    # Return task name
    def to_s
      name
    end

    def inspect # :nodoc:
      "<#{self.class} #{name} => [#{prerequisites.join(', ')}]>"
    end

    # List of sources for task.
    attr_writer :sources
    def sources
      if defined?(@sources)
        @sources
      else
        prerequisites
      end
    end

    # List of prerequisite tasks
    def prerequisite_tasks
      (prerequisites + order_only_prerequisites).map { |pre| lookup_prerequisite(pre) }
    end

    def lookup_prerequisite(prerequisite_name) # :nodoc:
      scoped_prerequisite_task = application[prerequisite_name, @scope]
      if scoped_prerequisite_task == self
        unscoped_prerequisite_task = application[prerequisite_name]
      end
      unscoped_prerequisite_task || scoped_prerequisite_task
    end
    private :lookup_prerequisite

    # List of all unique prerequisite tasks including prerequisite tasks'
    # prerequisites.
    # Includes self when cyclic dependencies are found.
    def all_prerequisite_tasks
      seen = {}
      collect_prerequisites(seen)
      seen.values
    end

    def collect_prerequisites(seen) # :nodoc:
      prerequisite_tasks.each do |pre|
        next if seen[pre.name]
        seen[pre.name] = pre
        pre.collect_prerequisites(seen)
      end
    end
    protected :collect_prerequisites

    # First source from a rule (nil if no sources)
    def source
      sources.first
    end

    # Create a task named +task_name+ with no actions or prerequisites. Use
    # +enhance+ to add actions and prerequisites.
    def initialize(task_name, app)
      @name            = task_name.to_s
      @prerequisites   = []
      @actions         = []
      @already_invoked = false
      @comments        = []
      @lock            = Monitor.new
      @application     = app
      @scope           = app.current_scope
      @arg_names       = nil
      @locations       = []
      @invocation_exception = nil
      @order_only_prerequisites = []
    end

    # Enhance a task with prerequisites or actions.  Returns self.
    def enhance(deps=nil, &block)
      @prerequisites |= deps if deps
      @actions << block if block_given?
      self
    end

    # Name of the task, including any namespace qualifiers.
    def name
      @name.to_s
    end

    # Name of task with argument list description.
    def name_with_args # :nodoc:
      if arg_description
        "#{name}#{arg_description}"
      else
        name
      end
    end

    # Argument description (nil if none).
    def arg_description # :nodoc:
      @arg_names ? "[#{arg_names.join(',')}]" : nil
    end

    # Name of arguments for this task.
    def arg_names
      @arg_names || []
    end

    # Reenable the task, allowing its tasks to be executed if the task
    # is invoked again.
    def reenable
      @already_invoked = false
      @invocation_exception = nil
    end

    # Clear the existing prerequisites, actions, comments, and arguments of a rake task.
    def clear
      clear_prerequisites
      clear_actions
      clear_comments
      clear_args
      self
    end

    # Clear the existing prerequisites of a rake task.
    def clear_prerequisites
      prerequisites.clear
      self
    end

    # Clear the existing actions on a rake task.
    def clear_actions
      actions.clear
      self
    end

    # Clear the existing comments on a rake task.
    def clear_comments
      @comments = []
      self
    end

    # Clear the existing arguments on a rake task.
    def clear_args
      @arg_names = nil
      self
    end

    # Invoke the task if it is needed.  Prerequisites are invoked first.
    def invoke(*args)
      task_args = TaskArguments.new(arg_names, args)
      invoke_with_call_chain(task_args, InvocationChain::EMPTY)
    end

    # Same as invoke, but explicitly pass a call chain to detect
    # circular dependencies.
    #
    # If multiple tasks depend on this
    # one in parallel, they will all fail if the first execution of
    # this task fails.
    def invoke_with_call_chain(task_args, invocation_chain)
      new_chain = Rake::InvocationChain.append(self, invocation_chain)
      @lock.synchronize do
        begin
          if application.options.trace
            application.trace "** Invoke #{name} #{format_trace_flags}"
          end

          if @already_invoked
            if @invocation_exception
              if application.options.trace
                application.trace "** Previous invocation of #{name} failed #{format_trace_flags}"
              end
              raise @invocation_exception
            else
              return
            end
          end

          @already_invoked = true

          invoke_prerequisites(task_args, new_chain)
          execute(task_args) if needed?
        rescue Exception => ex
          add_chain_to(ex, new_chain)
          @invocation_exception = ex
          raise ex
        end
      end
    end
    protected :invoke_with_call_chain

    def add_chain_to(exception, new_chain) # :nodoc:
      exception.extend(InvocationExceptionMixin) unless
        exception.respond_to?(:chain)
      exception.chain = new_chain if exception.chain.nil?
    end
    private :add_chain_to

    # Invoke all the prerequisites of a task.
    def invoke_prerequisites(task_args, invocation_chain) # :nodoc:
      if application.options.always_multitask
        invoke_prerequisites_concurrently(task_args, invocation_chain)
      else
        prerequisite_tasks.each { |p|
          prereq_args = task_args.new_scope(p.arg_names)
          p.invoke_with_call_chain(prereq_args, invocation_chain)
        }
      end
    end

    # Invoke all the prerequisites of a task in parallel.
    def invoke_prerequisites_concurrently(task_args, invocation_chain)# :nodoc:
      futures = prerequisite_tasks.map do |p|
        prereq_args = task_args.new_scope(p.arg_names)
        application.thread_pool.future(p) do |r|
          r.invoke_with_call_chain(prereq_args, invocation_chain)
        end
      end
      # Iterate in reverse to improve performance related to thread waiting and switching
      futures.reverse_each(&:value)
    end

    # Format the trace flags for display.
    def format_trace_flags
      flags = []
      flags << "first_time" unless @already_invoked
      flags << "not_needed" unless needed?
      flags.empty? ? "" : "(" + flags.join(", ") + ")"
    end
    private :format_trace_flags

    # Execute the actions associated with this task.
    def execute(args=nil)
      args ||= EMPTY_TASK_ARGS
      if application.options.dryrun
        application.trace "** Execute (dry run) #{name}"
        return
      end
      application.trace "** Execute #{name}" if application.options.trace
      application.enhance_with_matching_rule(name) if @actions.empty?
      if opts = Hash.try_convert(args) and !opts.empty?
        @actions.each { |act| act.call(self, args, **opts)}
      else
        @actions.each { |act| act.call(self, args)}
      end
    end

    # Is this task needed?
    def needed?
      true
    end

    # Timestamp for this task.  Basic tasks return the current time for their
    # time stamp.  Other tasks can be more sophisticated.
    def timestamp
      Time.now
    end

    # Add a description to the task.  The description can consist of an option
    # argument list (enclosed brackets) and an optional comment.
    def add_description(description)
      return unless description
      comment = description.strip
      add_comment(comment) if comment && !comment.empty?
    end

    def comment=(comment) # :nodoc:
      add_comment(comment)
    end

    def add_comment(comment) # :nodoc:
      return if comment.nil?
      @comments << comment unless @comments.include?(comment)
    end
    private :add_comment

    # Full collection of comments. Multiple comments are separated by
    # newlines.
    def full_comment
      transform_comments("\n")
    end

    # First line (or sentence) of all comments. Multiple comments are
    # separated by a "/".
    def comment
      transform_comments(" / ") { |c| first_sentence(c) }
    end

    # Transform the list of comments as specified by the block and
    # join with the separator.
    def transform_comments(separator, &block)
      if @comments.empty?
        nil
      else
        block ||= lambda { |c| c }
        @comments.map(&block).join(separator)
      end
    end
    private :transform_comments

    # Get the first sentence in a string. The sentence is terminated
    # by the first period, exclamation mark, or the end of the line.
    # Decimal points do not count as periods.
    def first_sentence(string)
      string.split(/(?<=\w)(\.|!)[ \t]|(\.$|!)|\n/).first
    end
    private :first_sentence

    # Set the names of the arguments for this task. +args+ should be
    # an array of symbols, one for each argument name.
    def set_arg_names(args)
      @arg_names = args.map(&:to_sym)
    end

    # Return a string describing the internal state of a task.  Useful for
    # debugging.
    def investigation
      result = "------------------------------\n".dup
      result << "Investigating #{name}\n"
      result << "class: #{self.class}\n"
      result <<  "task needed: #{needed?}\n"
      result <<  "timestamp: #{timestamp}\n"
      result << "pre-requisites: \n"
      prereqs = prerequisite_tasks
      prereqs.sort! { |a, b| a.timestamp <=> b.timestamp }
      prereqs.each do |p|
        result << "--#{p.name} (#{p.timestamp})\n"
      end
      latest_prereq = prerequisite_tasks.map(&:timestamp).max
      result <<  "latest-prerequisite time: #{latest_prereq}\n"
      result << "................................\n\n"
      return result
    end

    # Format dependencies parameter to pass to task.
    def self.format_deps(deps)
      deps = [deps] unless deps.respond_to?(:to_ary)
      deps.map { |d| Rake.from_pathname(d).to_s }
    end

    # Add order only dependencies.
    def |(deps)
      @order_only_prerequisites |= Task.format_deps(deps) - @prerequisites
      self
    end

    # ----------------------------------------------------------------
    # Rake Module Methods
    #
    class << self

      # Clear the task list.  This cause rake to immediately forget all the
      # tasks that have been assigned.  (Normally used in the unit tests.)
      def clear
        Rake.application.clear
      end

      # List of all defined tasks.
      def tasks
        Rake.application.tasks
      end

      # Return a task with the given name.  If the task is not currently
      # known, try to synthesize one from the defined rules.  If no rules are
      # found, but an existing file matches the task name, assume it is a file
      # task with no dependencies or actions.
      def [](task_name)
        Rake.application[task_name]
      end

      # TRUE if the task name is already defined.
      def task_defined?(task_name)
        Rake.application.lookup(task_name) != nil
      end

      # Define a task given +args+ and an option block.  If a rule with the
      # given name already exists, the prerequisites and actions are added to
      # the existing task.  Returns the defined task.
      def define_task(*args, &block)
        Rake.application.define_task(self, *args, &block)
      end

      # Define a rule for synthesizing tasks.
      def create_rule(*args, &block)
        Rake.application.create_rule(*args, &block)
      end

      # Apply the scope to the task name according to the rules for
      # this kind of task.  Generic tasks will accept the scope as
      # part of the name.
      def scope_name(scope, task_name)
        scope.path_with_task_name(task_name)
      end

    end # class << Rake::Task
  end # class Rake::Task
end
# frozen_string_literal: true
module Rake
  ##
  # Mixin for creating easily cloned objects.

  module Cloneable # :nodoc:
    # The hook that is invoked by 'clone' and 'dup' methods.
    def initialize_copy(source)
      super
      source.instance_variables.each do |var|
        src_value  = source.instance_variable_get(var)
        value = src_value.clone rescue src_value
        instance_variable_set(var, value)
      end
    end
  end
end
# frozen_string_literal: true
module Rake

  # InvocationChain tracks the chain of task invocations to detect
  # circular dependencies.
  class InvocationChain < LinkedList

    # Is the invocation already in the chain?
    def member?(invocation)
      head == invocation || tail.member?(invocation)
    end

    # Append an invocation to the chain of invocations. It is an error
    # if the invocation already listed.
    def append(invocation)
      if member?(invocation)
        fail RuntimeError, "Circular dependency detected: #{to_s} => #{invocation}"
      end
      conj(invocation)
    end

    # Convert to string, ie: TOP => invocation => invocation
    def to_s
      "#{prefix}#{head}"
    end

    # Class level append.
    def self.append(invocation, chain)
      chain.append(invocation)
    end

    private

    def prefix
      "#{tail} => "
    end

    # Null object for an empty chain.
    class EmptyInvocationChain < LinkedList::EmptyLinkedList
      @parent = InvocationChain

      def member?(obj)
        false
      end

      def append(invocation)
        conj(invocation)
      end

      def to_s
        "TOP"
      end
    end

    EMPTY = EmptyInvocationChain.new
  end
end
# frozen_string_literal: true
# The 'rake/clean' file defines two file lists (CLEAN and CLOBBER) and
# two rake tasks (:clean and :clobber).
#
# [:clean] Clean up the project by deleting scratch files and backup
#          files.  Add files to the CLEAN file list to have the :clean
#          target handle them.
#
# [:clobber] Clobber all generated and non-source files in a project.
#            The task depends on :clean, so all the clean files will
#            be deleted as well as files in the CLOBBER file list.
#            The intent of this task is to return a project to its
#            pristine, just unpacked state.

require "rake"

# :stopdoc:

module Rake
  module Cleaner
    extend FileUtils

    module_function

    def cleanup_files(file_names)
      file_names.each do |file_name|
        cleanup(file_name)
      end
    end

    def cleanup(file_name, **opts)
      begin
        opts = { verbose: Rake.application.options.trace }.merge(opts)
        rm_r file_name, **opts
      rescue StandardError => ex
        puts "Failed to remove #{file_name}: #{ex}" unless file_already_gone?(file_name)
      end
    end

    def file_already_gone?(file_name)
      return false if File.exist?(file_name)

      path = file_name
      prev = nil

      while path = File.dirname(path)
        return false if cant_be_deleted?(path)
        break if [prev, "."].include?(path)
        prev = path
      end
      true
    end
    private_class_method :file_already_gone?

    def cant_be_deleted?(path_name)
      File.exist?(path_name) &&
        (!File.readable?(path_name) || !File.executable?(path_name))
    end
    private_class_method :cant_be_deleted?
  end
end

CLEAN = ::Rake::FileList["**/*~", "**/*.bak", "**/core"]
CLEAN.clear_exclude.exclude { |fn|
  fn.pathmap("%f").downcase == "core" && File.directory?(fn)
}

desc "Remove any temporary products."
task :clean do
  Rake::Cleaner.cleanup_files(CLEAN)
end

CLOBBER = ::Rake::FileList.new

desc "Remove any generated files."
task clobber: [:clean] do
  Rake::Cleaner.cleanup_files(CLOBBER)
end
# frozen_string_literal: true
require "rbconfig"

module Rake
  # Win 32 interface methods for Rake. Windows specific functionality
  # will be placed here to collect that knowledge in one spot.
  module Win32 # :nodoc: all

    # Error indicating a problem in locating the home directory on a
    # Win32 system.
    class Win32HomeError < RuntimeError
    end

    class << self
      # True if running on a windows system.
      def windows?
        RbConfig::CONFIG["host_os"] =~ %r!(msdos|mswin|djgpp|mingw|[Ww]indows)!
      end

      # The standard directory containing system wide rake files on
      # Win 32 systems. Try the following environment variables (in
      # order):
      #
      # * HOME
      # * HOMEDRIVE + HOMEPATH
      # * APPDATA
      # * USERPROFILE
      #
      # If the above are not defined, the return nil.
      def win32_system_dir #:nodoc:
        win32_shared_path = ENV["HOME"]
        if win32_shared_path.nil? && ENV["HOMEDRIVE"] && ENV["HOMEPATH"]
          win32_shared_path = ENV["HOMEDRIVE"] + ENV["HOMEPATH"]
        end

        win32_shared_path ||= ENV["APPDATA"]
        win32_shared_path ||= ENV["USERPROFILE"]
        raise Win32HomeError,
          "Unable to determine home path environment variable." if
            win32_shared_path.nil? or win32_shared_path.empty?
        normalize(File.join(win32_shared_path, "Rake"))
      end

      # Normalize a win32 path so that the slashes are all forward slashes.
      def normalize(path)
        path.gsub(/\\/, "/")
      end

    end
  end
end
# frozen_string_literal: true
require "rake/file_task"
require "rake/early_time"

module Rake

  # A FileCreationTask is a file task that when used as a dependency will be
  # needed if and only if the file has not been created.  Once created, it is
  # not re-triggered if any of its dependencies are newer, nor does trigger
  # any rebuilds of tasks that depend on it whenever it is updated.
  #
  class FileCreationTask < FileTask
    # Is this file task needed?  Yes if it doesn't exist.
    def needed?
      !File.exist?(name)
    end

    # Time stamp for file creation task.  This time stamp is earlier
    # than any other time stamp.
    def timestamp
      Rake::EARLY
    end
  end

end
# frozen_string_literal: true
module Rake
  module TraceOutput # :nodoc: all

    # Write trace output to output stream +out+.
    #
    # The write is done as a single IO call (to print) to lessen the
    # chance that the trace output is interrupted by other tasks also
    # producing output.
    def trace_on(out, *strings)
      sep = $\ || "\n"
      if strings.empty?
        output = sep
      else
        output = strings.map { |s|
          next if s.nil?
          s.end_with?(sep) ? s : s + sep
        }.join
      end
      out.print(output)
    end
  end
end
# frozen_string_literal: true
require "rake/application"

module Rake

  class << self
    # Current Rake Application
    def application
      @application ||= Rake::Application.new
    end

    # Set the current Rake application object.
    def application=(app)
      @application = app
    end

    def suggested_thread_count # :nodoc:
      @cpu_count ||= Rake::CpuCounter.count
      @cpu_count + 4
    end

    # Return the original directory where the Rake application was started.
    def original_dir
      application.original_dir
    end

    # Load a rakefile.
    def load_rakefile(path)
      load(path)
    end

    # Add files to the rakelib list
    def add_rakelib(*files)
      application.options.rakelib ||= []
      application.options.rakelib.concat(files)
    end

    # Make +block_application+ the default rake application inside a block so
    # you can load rakefiles into a different application.
    #
    # This is useful when you want to run rake tasks inside a library without
    # running rake in a sub-shell.
    #
    # Example:
    #
    #   Dir.chdir 'other/directory'
    #
    #   other_rake = Rake.with_application do |rake|
    #     rake.load_rakefile
    #   end
    #
    #   puts other_rake.tasks

    def with_application(block_application = Rake::Application.new)
      orig_application = Rake.application

      Rake.application = block_application

      yield block_application

      block_application
    ensure
      Rake.application = orig_application
    end
  end

end
# frozen_string_literal: true
module Rake

  # Default Rakefile loader used by +import+.
  class DefaultLoader

    ##
    # Loads a rakefile into the current application from +fn+

    def load(fn)
      Rake.load_rakefile(File.expand_path(fn))
    end
  end

end
# frozen_string_literal: true
require "rake/private_reader"

module Rake

  class ThreadHistoryDisplay    # :nodoc: all
    include Rake::PrivateReader

    private_reader :stats, :items, :threads

    def initialize(stats)
      @stats   = stats
      @items   = { _seq_: 1  }
      @threads = { _seq_: "A" }
    end

    def show
      puts "Job History:"
      stats.each do |stat|
        stat[:data] ||= {}
        rename(stat, :thread, threads)
        rename(stat[:data], :item_id, items)
        rename(stat[:data], :new_thread, threads)
        rename(stat[:data], :deleted_thread, threads)
        printf("%8d %2s %-20s %s\n",
          (stat[:time] * 1_000_000).round,
          stat[:thread],
          stat[:event],
          stat[:data].map do |k, v| "#{k}:#{v}" end.join(" "))
      end
    end

    private

    def rename(hash, key, renames)
      if hash && hash[key]
        original = hash[key]
        value = renames[original]
        unless value
          value = renames[:_seq_]
          renames[:_seq_] = renames[:_seq_].succ
          renames[original] = value
        end
        hash[key] = value
      end
    end
  end

end
# frozen_string_literal: true
module Rake
  module Backtrace # :nodoc: all
    SYS_KEYS  = RbConfig::CONFIG.keys.grep(/(?:[a-z]prefix|libdir)\z/)
    SYS_PATHS = RbConfig::CONFIG.values_at(*SYS_KEYS).uniq +
      [ File.join(File.dirname(__FILE__), "..") ]

    SUPPRESSED_PATHS = SYS_PATHS.
      map { |s| s.tr("\\", "/") }.
      map { |f| File.expand_path(f) }.
      reject { |s| s.nil? || s =~ /^ *$/ }
    SUPPRESSED_PATHS_RE = SUPPRESSED_PATHS.map { |f| Regexp.quote(f) }.join("|")
    SUPPRESSED_PATHS_RE << "|^org\\/jruby\\/\\w+\\.java" if
      Object.const_defined?(:RUBY_ENGINE) and RUBY_ENGINE == "jruby"

    SUPPRESS_PATTERN = %r!(\A(#{SUPPRESSED_PATHS_RE})|bin/rake:\d+)!i

    def self.collapse(backtrace)
      pattern = Rake.application.options.suppress_backtrace_pattern ||
                SUPPRESS_PATTERN
      backtrace.reject { |elem| elem =~ pattern }
    end
  end
end
# frozen_string_literal: true
require "rake/file_utils"

module Rake
  #
  # FileUtilsExt provides a custom version of the FileUtils methods
  # that respond to the <tt>verbose</tt> and <tt>nowrite</tt>
  # commands.
  #
  module FileUtilsExt
    include FileUtils

    class << self
      attr_accessor :verbose_flag, :nowrite_flag
    end

    DEFAULT = Object.new

    FileUtilsExt.verbose_flag = DEFAULT
    FileUtilsExt.nowrite_flag = false

    FileUtils.commands.each do |name|
      opts = FileUtils.options_of name
      default_options = []
      if opts.include?("verbose")
        default_options << "verbose: FileUtilsExt.verbose_flag"
      end
      if opts.include?("noop")
        default_options << "noop: FileUtilsExt.nowrite_flag"
      end

      next if default_options.empty?
      module_eval(<<-EOS, __FILE__, __LINE__ + 1)
      def #{name}(*args, **options, &block)
        super(*args,
            #{default_options.join(', ')},
            **options, &block)
      end
      EOS
    end

    # Get/set the verbose flag controlling output from the FileUtils
    # utilities.  If verbose is true, then the utility method is
    # echoed to standard output.
    #
    # Examples:
    #    verbose              # return the current value of the
    #                         # verbose flag
    #    verbose(v)           # set the verbose flag to _v_.
    #    verbose(v) { code }  # Execute code with the verbose flag set
    #                         # temporarily to _v_.  Return to the
    #                         # original value when code is done.
    def verbose(value=nil)
      oldvalue = FileUtilsExt.verbose_flag
      FileUtilsExt.verbose_flag = value unless value.nil?
      if block_given?
        begin
          yield
        ensure
          FileUtilsExt.verbose_flag = oldvalue
        end
      end
      FileUtilsExt.verbose_flag
    end

    # Get/set the nowrite flag controlling output from the FileUtils
    # utilities.  If verbose is true, then the utility method is
    # echoed to standard output.
    #
    # Examples:
    #    nowrite              # return the current value of the
    #                         # nowrite flag
    #    nowrite(v)           # set the nowrite flag to _v_.
    #    nowrite(v) { code }  # Execute code with the nowrite flag set
    #                         # temporarily to _v_. Return to the
    #                         # original value when code is done.
    def nowrite(value=nil)
      oldvalue = FileUtilsExt.nowrite_flag
      FileUtilsExt.nowrite_flag = value unless value.nil?
      if block_given?
        begin
          yield
        ensure
          FileUtilsExt.nowrite_flag = oldvalue
        end
      end
      oldvalue
    end

    # Use this function to prevent potentially destructive ruby code
    # from running when the :nowrite flag is set.
    #
    # Example:
    #
    #   when_writing("Building Project") do
    #     project.build
    #   end
    #
    # The following code will build the project under normal
    # conditions. If the nowrite(true) flag is set, then the example
    # will print:
    #
    #      DRYRUN: Building Project
    #
    # instead of actually building the project.
    #
    def when_writing(msg=nil)
      if FileUtilsExt.nowrite_flag
        $stderr.puts "DRYRUN: #{msg}" if msg
      else
        yield
      end
    end

    # Send the message to the default rake output (which is $stderr).
    def rake_output_message(message)
      $stderr.puts(message)
    end

    # Check that the options do not contain options not listed in
    # +optdecl+.  An ArgumentError exception is thrown if non-declared
    # options are found.
    def rake_check_options(options, *optdecl)
      h = options.dup
      optdecl.each do |name|
        h.delete name
      end
      raise ArgumentError, "no such option: #{h.keys.join(' ')}" unless
        h.empty?
    end

    extend self
  end
end
# frozen_string_literal: true
module Rake

  # Based on a script at:
  #   http://stackoverflow.com/questions/891537/ruby-detect-number-of-cpus-installed
  class CpuCounter # :nodoc: all
    def self.count
      new.count_with_default
    end

    def count_with_default(default=4)
      count || default
    rescue StandardError
      default
    end

    begin
      require "etc"
    rescue LoadError
    else
      if Etc.respond_to?(:nprocessors)
        def count
          return Etc.nprocessors
        end
      end
    end
  end
end

unless Rake::CpuCounter.method_defined?(:count)
  Rake::CpuCounter.class_eval <<-'end;', __FILE__, __LINE__+1
    require 'rbconfig'

    def count
      if RUBY_PLATFORM == 'java'
        count_via_java_runtime
      else
        case RbConfig::CONFIG['host_os']
        when /linux/
          count_via_cpuinfo
        when /darwin|bsd/
          count_via_sysctl
        when /mswin|mingw/
          count_via_win32
        else
          # Try everything
          count_via_win32 ||
          count_via_sysctl ||
          count_via_cpuinfo
        end
      end
    end

    def count_via_java_runtime
      Java::Java.lang.Runtime.getRuntime.availableProcessors
    rescue StandardError
      nil
    end

    def count_via_win32
      require 'win32ole'
      wmi = WIN32OLE.connect("winmgmts://")
      cpu = wmi.ExecQuery("select NumberOfCores from Win32_Processor") # TODO count hyper-threaded in this
      cpu.to_enum.first.NumberOfCores
    rescue StandardError, LoadError
      nil
    end

    def count_via_cpuinfo
      open('/proc/cpuinfo') { |f| f.readlines }.grep(/processor/).size
    rescue StandardError
      nil
    end

    def count_via_sysctl
      run 'sysctl', '-n', 'hw.ncpu'
    end

    def run(command, *args)
      cmd = resolve_command(command)
      if cmd
        IO.popen [cmd, *args] do |io|
          io.read.to_i
        end
      else
        nil
      end
    end

    def resolve_command(command)
      look_for_command("/usr/sbin", command) ||
        look_for_command("/sbin", command) ||
        in_path_command(command)
    end

    def look_for_command(dir, command)
      path = File.join(dir, command)
      File.exist?(path) ? path : nil
    end

    def in_path_command(command)
      IO.popen ['which', command] do |io|
        io.eof? ? nil : command
      end
    end
  end;
end
# frozen_string_literal: true
require "rbconfig"
require "fileutils"

#--
# This a FileUtils extension that defines several additional commands to be
# added to the FileUtils utility functions.
module FileUtils
  # Path to the currently running Ruby program
  RUBY = ENV["RUBY"] || File.join(
    RbConfig::CONFIG["bindir"],
    RbConfig::CONFIG["ruby_install_name"] + RbConfig::CONFIG["EXEEXT"]).
    sub(/.*\s.*/m, '"\&"')

  # Run the system command +cmd+.  If multiple arguments are given the command
  # is run directly (without the shell, same semantics as Kernel::exec and
  # Kernel::system).
  #
  # It is recommended you use the multiple argument form over interpolating
  # user input for both usability and security reasons.  With the multiple
  # argument form you can easily process files with spaces or other shell
  # reserved characters in them.  With the multiple argument form your rake
  # tasks are not vulnerable to users providing an argument like
  # <code>; rm # -rf /</code>.
  #
  # If a block is given, upon command completion the block is called with an
  # OK flag (true on a zero exit status) and a Process::Status object.
  # Without a block a RuntimeError is raised when the command exits non-zero.
  #
  # Examples:
  #
  #   sh 'ls -ltr'
  #
  #   sh 'ls', 'file with spaces'
  #
  #   # check exit status after command runs
  #   sh %{grep pattern file} do |ok, res|
  #     if !ok
  #       puts "pattern not found (status = #{res.exitstatus})"
  #     end
  #   end
  #
  def sh(*cmd, &block)
    options = (Hash === cmd.last) ? cmd.pop : {}
    shell_runner = block_given? ? block : create_shell_runner(cmd)

    set_verbose_option(options)
    verbose = options.delete :verbose
    noop    = options.delete(:noop) || Rake::FileUtilsExt.nowrite_flag

    Rake.rake_output_message sh_show_command cmd if verbose

    unless noop
      res = (Hash === cmd.last) ? system(*cmd) : system(*cmd, options)
      status = $?
      status = Rake::PseudoStatus.new(1) if !res && status.nil?
      shell_runner.call(res, status)
    end
  end

  def create_shell_runner(cmd) # :nodoc:
    show_command = sh_show_command cmd
    show_command = show_command[0, 42] + "..." unless $trace

    lambda do |ok, status|
      ok or
        fail "Command failed with status (#{status.exitstatus}): " +
        "[#{show_command}]"
    end
  end
  private :create_shell_runner

  def sh_show_command(cmd) # :nodoc:
    cmd = cmd.dup

    if Hash === cmd.first
      env = cmd.first
      env = env.map { |name, value| "#{name}=#{value}" }.join " "
      cmd[0] = env
    end

    cmd.join " "
  end
  private :sh_show_command

  def set_verbose_option(options) # :nodoc:
    unless options.key? :verbose
      options[:verbose] =
        (Rake::FileUtilsExt.verbose_flag == Rake::FileUtilsExt::DEFAULT) ||
        Rake::FileUtilsExt.verbose_flag
    end
  end
  private :set_verbose_option

  # Run a Ruby interpreter with the given arguments.
  #
  # Example:
  #   ruby %{-pe '$_.upcase!' <README}
  #
  def ruby(*args, **options, &block)
    if args.length > 1
      sh(RUBY, *args, **options, &block)
    else
      sh("#{RUBY} #{args.first}", **options, &block)
    end
  end

  LN_SUPPORTED = [true]

  #  Attempt to do a normal file link, but fall back to a copy if the link
  #  fails.
  def safe_ln(*args, **options)
    if LN_SUPPORTED[0]
      begin
        return options.empty? ? ln(*args) : ln(*args, **options)
      rescue StandardError, NotImplementedError
        LN_SUPPORTED[0] = false
      end
    end
    options.empty? ? cp(*args) : cp(*args, **options)
  end

  # Split a file path into individual directory names.
  #
  # Example:
  #   split_all("a/b/c") =>  ['a', 'b', 'c']
  #
  def split_all(path)
    head, tail = File.split(path)
    return [tail] if head == "." || tail == "/"
    return [head, tail] if head == "/"
    return split_all(head) + [tail]
  end
end
# frozen_string_literal: true
module Rake

  # EarlyTime is a fake timestamp that occurs _before_ any other time value.
  class EarlyTime
    include Comparable
    include Singleton

    ##
    # The EarlyTime always comes before +other+!

    def <=>(other)
      -1
    end

    def to_s # :nodoc:
      "<EARLY TIME>"
    end
  end

  EARLY = EarlyTime.instance
end
# frozen_string_literal: true
module Rake

  # Include PrivateReader to use +private_reader+.
  module PrivateReader           # :nodoc: all

    def self.included(base)
      base.extend(ClassMethods)
    end

    module ClassMethods

      # Declare a list of private accessors
      def private_reader(*names)
        attr_reader(*names)
        private(*names)
      end
    end

  end
end
# frozen_string_literal: true
# Define a package task library to aid in the definition of
# redistributable package files.

require "rake"
require "rake/tasklib"

module Rake

  # Create a packaging task that will package the project into
  # distributable files (e.g zip archive or tar files).
  #
  # The PackageTask will create the following targets:
  #
  # +:package+ ::
  #   Create all the requested package files.
  #
  # +:clobber_package+ ::
  #   Delete all the package files.  This target is automatically
  #   added to the main clobber target.
  #
  # +:repackage+ ::
  #   Rebuild the package files from scratch, even if they are not out
  #   of date.
  #
  # <tt>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tgz"</tt> ::
  #   Create a gzipped tar package (if <em>need_tar</em> is true).
  #
  # <tt>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tar.gz"</tt> ::
  #   Create a gzipped tar package (if <em>need_tar_gz</em> is true).
  #
  # <tt>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tar.bz2"</tt> ::
  #   Create a bzip2'd tar package (if <em>need_tar_bz2</em> is true).
  #
  # <tt>"<em>package_dir</em>/<em>name</em>-<em>version</em>.zip"</tt> ::
  #   Create a zip package archive (if <em>need_zip</em> is true).
  #
  # Example:
  #
  #   Rake::PackageTask.new("rake", "1.2.3") do |p|
  #     p.need_tar = true
  #     p.package_files.include("lib/**/*.rb")
  #   end
  #
  class PackageTask < TaskLib
    # Name of the package (from the GEM Spec).
    attr_accessor :name

    # Version of the package (e.g. '1.3.2').
    attr_accessor :version

    # Directory used to store the package files (default is 'pkg').
    attr_accessor :package_dir

    # True if a gzipped tar file (tgz) should be produced (default is
    # false).
    attr_accessor :need_tar

    # True if a gzipped tar file (tar.gz) should be produced (default
    # is false).
    attr_accessor :need_tar_gz

    # True if a bzip2'd tar file (tar.bz2) should be produced (default
    # is false).
    attr_accessor :need_tar_bz2

    # True if a xz'd tar file (tar.xz) should be produced (default is false)
    attr_accessor :need_tar_xz

    # True if a zip file should be produced (default is false)
    attr_accessor :need_zip

    # List of files to be included in the package.
    attr_accessor :package_files

    # Tar command for gzipped or bzip2ed archives.  The default is 'tar'.
    attr_accessor :tar_command

    # Zip command for zipped archives.  The default is 'zip'.
    attr_accessor :zip_command

    # True if parent directory should be omited (default is false)
    attr_accessor :without_parent_dir

    # Create a Package Task with the given name and version.  Use +:noversion+
    # as the version to build a package without a version or to provide a
    # fully-versioned package name.

    def initialize(name=nil, version=nil)
      init(name, version)
      yield self if block_given?
      define unless name.nil?
    end

    # Initialization that bypasses the "yield self" and "define" step.
    def init(name, version)
      @name = name
      @version = version
      @package_files = Rake::FileList.new
      @package_dir = "pkg"
      @need_tar = false
      @need_tar_gz = false
      @need_tar_bz2 = false
      @need_tar_xz = false
      @need_zip = false
      @tar_command = "tar"
      @zip_command = "zip"
      @without_parent_dir = false
    end

    # Create the tasks defined by this task library.
    def define
      fail "Version required (or :noversion)" if @version.nil?
      @version = nil if :noversion == @version

      desc "Build all the packages"
      task :package

      desc "Force a rebuild of the package files"
      task repackage: [:clobber_package, :package]

      desc "Remove package products"
      task :clobber_package do
        rm_r package_dir rescue nil
      end

      task clobber: [:clobber_package]

      [
        [need_tar, tgz_file, "z"],
        [need_tar_gz, tar_gz_file, "z"],
        [need_tar_bz2, tar_bz2_file, "j"],
        [need_tar_xz, tar_xz_file, "J"]
      ].each do |need, file, flag|
        if need
          task package: ["#{package_dir}/#{file}"]
          file "#{package_dir}/#{file}" =>
            [package_dir_path] + package_files do
            chdir(working_dir) { sh @tar_command, "#{flag}cvf", file, target_dir }
            mv "#{package_dir_path}/#{target_dir}", package_dir if without_parent_dir
          end
        end
      end

      if need_zip
        task package: ["#{package_dir}/#{zip_file}"]
        file "#{package_dir}/#{zip_file}" =>
          [package_dir_path] + package_files do
          chdir(working_dir) { sh @zip_command, "-r", zip_file, target_dir }
          mv "#{package_dir_path}/#{zip_file}", package_dir if without_parent_dir
        end
      end

      directory package_dir_path => @package_files do
        @package_files.each do |fn|
          f = File.join(package_dir_path, fn)
          fdir = File.dirname(f)
          mkdir_p(fdir) unless File.exist?(fdir)
          if File.directory?(fn)
            mkdir_p(f)
          else
            rm_f f
            safe_ln(fn, f)
          end
        end
      end
      self
    end

    # The name of this package

    def package_name
      @version ? "#{@name}-#{@version}" : @name
    end

    # The directory this package will be built in

    def package_dir_path
      "#{package_dir}/#{package_name}"
    end

    # The package name with .tgz added

    def tgz_file
      "#{package_name}.tgz"
    end

    # The package name with .tar.gz added

    def tar_gz_file
      "#{package_name}.tar.gz"
    end

    # The package name with .tar.bz2 added

    def tar_bz2_file
      "#{package_name}.tar.bz2"
    end

    # The package name with .tar.xz added

    def tar_xz_file
      "#{package_name}.tar.xz"
    end

    # The package name with .zip added

    def zip_file
      "#{package_name}.zip"
    end

    def working_dir
      without_parent_dir ? package_dir_path : package_dir
    end

    # target directory relative to working_dir
    def target_dir
      without_parent_dir ? "." : package_name
    end
  end

end
# frozen_string_literal: true
module Rake

  # Error indicating an ill-formed task declaration.
  class TaskArgumentError < ArgumentError
  end

end
# frozen_string_literal: true
require "rake"
require "rake/tasklib"

module Rake

  # Create a task that runs a set of tests.
  #
  # Example:
  #   require "rake/testtask"
  #
  #   Rake::TestTask.new do |t|
  #     t.libs << "test"
  #     t.test_files = FileList['test/test*.rb']
  #     t.verbose = true
  #   end
  #
  # If rake is invoked with a "TEST=filename" command line option,
  # then the list of test files will be overridden to include only the
  # filename specified on the command line.  This provides an easy way
  # to run just one test.
  #
  # If rake is invoked with a "TESTOPTS=options" command line option,
  # then the given options are passed to the test process after a
  # '--'.  This allows Test::Unit options to be passed to the test
  # suite.
  #
  # Examples:
  #
  #   rake test                           # run tests normally
  #   rake test TEST=just_one_file.rb     # run just one test file.
  #   rake test TESTOPTS="-v"             # run in verbose mode
  #   rake test TESTOPTS="--runner=fox"   # use the fox test runner
  #
  class TestTask < TaskLib

    # Name of test task. (default is :test)
    attr_accessor :name

    # List of directories added to $LOAD_PATH before running the
    # tests. (default is 'lib')
    attr_accessor :libs

    # True if verbose test output desired. (default is false)
    attr_accessor :verbose

    # Test options passed to the test suite.  An explicit
    # TESTOPTS=opts on the command line will override this. (default
    # is NONE)
    attr_accessor :options

    # Request that the tests be run with the warning flag set.
    # E.g. warning=true implies "ruby -w" used to run the tests.
    # (default is true)
    attr_accessor :warning

    # Glob pattern to match test files. (default is 'test/test*.rb')
    attr_accessor :pattern

    # Style of test loader to use.  Options are:
    #
    # * :rake -- Rake provided test loading script (default).
    # * :testrb -- Ruby provided test loading script.
    # * :direct -- Load tests using command line loader.
    #
    attr_accessor :loader

    # Array of command line options to pass to ruby when running test loader.
    attr_accessor :ruby_opts

    # Description of the test task. (default is 'Run tests')
    attr_accessor :description

    # Task prerequisites.
    attr_accessor :deps

    # Explicitly define the list of test files to be included in a
    # test.  +list+ is expected to be an array of file names (a
    # FileList is acceptable).  If both +pattern+ and +test_files+ are
    # used, then the list of test files is the union of the two.
    def test_files=(list)
      @test_files = list
    end

    # Create a testing task.
    def initialize(name=:test)
      @name = name
      @libs = ["lib"]
      @pattern = nil
      @options = nil
      @test_files = nil
      @verbose = false
      @warning = true
      @loader = :rake
      @ruby_opts = []
      @description = "Run tests" + (@name == :test ? "" : " for #{@name}")
      @deps = []
      if @name.is_a?(Hash)
        @deps = @name.values.first
        @name = @name.keys.first
      end
      yield self if block_given?
      @pattern = "test/test*.rb" if @pattern.nil? && @test_files.nil?
      define
    end

    # Create the tasks defined by this task lib.
    def define
      desc @description
      task @name => Array(deps) do
        FileUtilsExt.verbose(@verbose) do
          puts "Use TESTOPTS=\"--verbose\" to pass --verbose" \
            ", etc. to runners." if ARGV.include? "--verbose"
          args =
            "#{ruby_opts_string} #{run_code} " +
            "#{file_list_string} #{option_list}"
          ruby args do |ok, status|
            if !ok && status.respond_to?(:signaled?) && status.signaled?
              raise SignalException.new(status.termsig)
            elsif !ok
              status  = "Command failed with status (#{status.exitstatus})"
              details = ": [ruby #{args}]"
              message =
                if Rake.application.options.trace or @verbose
                  status + details
                else
                  status
                end

              fail message
            end
          end
        end
      end
      self
    end

    def option_list # :nodoc:
      (ENV["TESTOPTS"] ||
        ENV["TESTOPT"] ||
        ENV["TEST_OPTS"] ||
        ENV["TEST_OPT"] ||
        @options ||
        "")
    end

    def ruby_opts_string # :nodoc:
      opts = @ruby_opts.dup
      opts.unshift("-I\"#{lib_path}\"") unless @libs.empty?
      opts.unshift("-w") if @warning
      opts.join(" ")
    end

    def lib_path # :nodoc:
      @libs.join(File::PATH_SEPARATOR)
    end

    def file_list_string # :nodoc:
      file_list.map { |fn| "\"#{fn}\"" }.join(" ")
    end

    def file_list # :nodoc:
      if ENV["TEST"]
        FileList[ENV["TEST"]]
      else
        result = []
        result += @test_files.to_a if @test_files
        result += FileList[@pattern].to_a if @pattern
        result
      end
    end

    def ruby_version # :nodoc:
      RUBY_VERSION
    end

    def run_code # :nodoc:
      case @loader
      when :direct
        "-e \"ARGV.each{|f| require f}\""
      when :testrb
        "-S testrb"
      when :rake
        "#{__dir__}/rake_test_loader.rb"
      end
    end

  end
end
# frozen_string_literal: true
# Defines a :phony task that you can use as a dependency. This allows
# file-based tasks to use non-file-based tasks as prerequisites
# without forcing them to rebuild.
#
# See FileTask#out_of_date? and Task#timestamp for more info.

require "rake"

task :phony

Rake::Task[:phony].tap do |task|
  def task.timestamp # :nodoc:
    Time.at 0
  end
end
# frozen_string_literal: true
module Rake
  VERSION = "13.0.3"

  module Version # :nodoc: all
    MAJOR, MINOR, BUILD, *OTHER = Rake::VERSION.split "."

    NUMBERS = [MAJOR, MINOR, BUILD, *OTHER]
  end
end
# frozen_string_literal: true
module Rake
  # LateTime is a fake timestamp that occurs _after_ any other time value.
  class LateTime
    include Comparable
    include Singleton

    def <=>(other)
      1
    end

    def to_s
      "<LATE TIME>"
    end
  end

  LATE = LateTime.instance
end
# frozen_string_literal: true
module Rake

  # A Promise object represents a promise to do work (a chore) in the
  # future. The promise is created with a block and a list of
  # arguments for the block. Calling value will return the value of
  # the promised chore.
  #
  # Used by ThreadPool.
  #
  class Promise               # :nodoc: all
    NOT_SET = Object.new.freeze # :nodoc:

    attr_accessor :recorder

    # Create a promise to do the chore specified by the block.
    def initialize(args, &block)
      @mutex = Mutex.new
      @result = NOT_SET
      @error = NOT_SET
      @args = args
      @block = block
    end

    # Return the value of this promise.
    #
    # If the promised chore is not yet complete, then do the work
    # synchronously. We will wait.
    def value
      unless complete?
        stat :sleeping_on, item_id: object_id
        @mutex.synchronize do
          stat :has_lock_on, item_id: object_id
          chore
          stat :releasing_lock_on, item_id: object_id
        end
      end
      error? ? raise(@error) : @result
    end

    # If no one else is working this promise, go ahead and do the chore.
    def work
      stat :attempting_lock_on, item_id: object_id
      if @mutex.try_lock
        stat :has_lock_on, item_id: object_id
        chore
        stat :releasing_lock_on, item_id: object_id
        @mutex.unlock
      else
        stat :bailed_on, item_id: object_id
      end
    end

    private

    # Perform the chore promised
    def chore
      if complete?
        stat :found_completed, item_id: object_id
        return
      end
      stat :will_execute, item_id: object_id
      begin
        @result = @block.call(*@args)
      rescue Exception => e
        @error = e
      end
      stat :did_execute, item_id: object_id
      discard
    end

    # Do we have a result for the promise
    def result?
      !@result.equal?(NOT_SET)
    end

    # Did the promise throw an error
    def error?
      !@error.equal?(NOT_SET)
    end

    # Are we done with the promise
    def complete?
      result? || error?
    end

    # free up these items for the GC
    def discard
      @args = nil
      @block = nil
    end

    # Record execution statistics if there is a recorder
    def stat(*args)
      @recorder.call(*args) if @recorder
    end

  end

end
=== 13.0.3

* Fix breaking change of execution order on TestTask.
  Pull request #368 by ysakasin

=== 13.0.2

==== Enhancements

* Fix tests to work with current FileUtils
  Pull Request #358 by jeremyevans
* Simplify default rake test loader
  Pull Request #357 by deivid-rodriguez
* Update rdoc
  Pull Request #366 by bahasalien
* Update broken links to rake articles from Avdi in README
  Pull Request #360 by svl7

=== 13.0.1

==== Bug fixes

* Fixed bug: Reenabled task raises previous exception on second invokation 
  Pull Request #271 by thorsteneckel
* Fix an incorrectly resolved arg pattern
  Pull Request #327 by mjbellantoni

=== 13.0.0

==== Enhancements

* Follows recent changes on keyword arguments in ruby 2.7.
  Pull Request #326 by nobu
* Make `PackageTask` be able to omit parent directory while packing files 
  Pull Request #310 by tonytonyjan
* Add order only dependency
  Pull Request #269 by take-cheeze

==== Compatibility changes

* Drop old ruby versions(< 2.2)

=== 12.3.3

==== Bug fixes

* Use the application's name in error message if a task is not found.
  Pull Request #303 by tmatilai

==== Enhancements:

* Use File.open explicitly.

=== 12.3.2

==== Bug fixes

* Fixed test fails caused by 2.6 warnings.
  Pull Request #297 by hsbt

==== Enhancements:

* Rdoc improvements.
  Pull Request #293 by colby-swandale
* Improve multitask performance.
  Pull Request #273 by jsm
* Add alias `prereqs`.
  Pull Request #268 by take-cheeze

=== 12.3.1

==== Bug fixes

* Support did_you_mean >= v1.2.0 which has a breaking change on formatters.
  Pull request #262 by FUJI Goro.

==== Enhancements:

* Don't run task if it depends on already invoked but failed task.
  Pull request #252 by Gonzalo Rodriguez.
* Make space trimming consistent for all task arguments.
  Pull request #259 by Gonzalo Rodriguez.
* Removes duplicated inclusion of Rake::DSL in tests.
  Pull request #254 by Gonzalo Rodriguez.
* Re-raise a LoadError that didn't come from require in the test loader.
  Pull request #250 by Dylan Thacker-Smith.

=== 12.3.0

==== Compatibility Changes

* Bump `required_ruby_version` to Ruby 2.0.0. Rake has already
  removed support for Ruby 1.9.x.

==== Enhancements:

* Support `test-bundled-gems` task on ruby core.

=== 12.2.1

==== Bug fixes

* Fixed to break Capistrano::Application on capistrano3.

=== 12.2.0

==== Enhancements:

* Make rake easier to use as a library
  Pull request #211 by @drbrain
* Fix quadratic performance in FileTask#out_of_date?
  Pull request #224 by @doudou
* Clarify output when printing nested exception traces
  Pull request #232 by @urbanautomaton

==== Bug fixes

* Account for a file that match 2 or more patterns.
  Pull request #231 by @styd

=== 12.1.0

==== Enhancements:

* Added did_you_mean feature for invalid rake task.
  Pull request #221 by @xtina-starr
* Enabled to dependency chained by extensions. Pull request #39 by Petr Skocik.
* Make all of string literals to frozen objects on Ruby 2.4 or later.

==== Bug fixes

* Typo fixes in rakefile.rdoc. Pull request #180 by Yuta Kurotaki.
* Fix unexpected behavior of file task with dryrun option.
  Pull request #183 by @aycabta.
* Make LoadError from running tests more obvious. Pull request #195
  by Eric Hodel.
* Fix unexpected TypeError with hash style option. Pull request #202
  by Kuniaki IGARASHI.

=== 12.0.0

==== Compatibility Changes

* Removed arguments on clear #157 by Jesse Bowes
* Removed `rake/contrib` packages. These are extracted to `rake-contrib` gem.
* Removed deprecated method named `last\_comment`.

==== Enhancements:

* Re-use trace option on `cleanup` task. #164 by Brian Henderson
* Actions adore keyword arguments #174 by Josh Cheek
* Rake::TaskArguments#key? alias of #has_key? #175 by Paul Annesley

=== 11.3.0 / 2016-09-20

==== Enhancements:

* Remove to reference `Fixnum` constant. Pull request #160 by nobu

=== 11.2.2 / 2016-06-12

==== Bug fixes

* Fix unexpected behavior with multiple dependencies on Rake::TestTask

=== 11.2.1 / 2016-06-12

==== Bug fixes

* Fix regression of dependencies handling on Rake::TestTask. Report #139

=== 11.2.0 / 2016-06-11

==== Bug fixes

* Fix unexpected cut-out behavior on task description using triple dots
  and exclamation. Report #106 from Stephan Kämper and Pull request #134 by Lee
* Fix empty argument assignment with `with_defaults` option. Pull request #135
  by bakunyo
* Ignore to use `hwprefs` on Darwin platform. Use sysctl now. Report #128

==== Enhancements

* Spawn options for sh Pull equest #138 by Eric Hodel.
* Allow to specify dependencies(prerequisites) for Rake::TestTask
  Pull request #117 by Tim Maslyuchenko
* Use Bundler task instead of hoe for gem release.
* Remove explicitly load to rubygems for Ruby 1.8.
* Unify to declare `Rake::VERSION`.
* Support xz format for PackageTask.

=== 11.1.2 / 2016-03-28

==== Bug fixes

* Remove `-W` option when Rake::TestTask#verbose enabled. It's misunderstanding
  specification change with Rake 11. Partly revert #67

=== 11.1.1 / 2016-03-14

==== Bug fixes

* Use `-W` instead of `--verbose` when Rake::TestTask#verbose enabled.
  JRuby doesn't have `--verbose` option.

=== 11.1.0 / 2016-03-11

==== Compatibility Changes

* Revert to remove `last\_comment`. It will remove Rake 12.

=== 11.0.1 / 2016-03-09

==== Bug fixes

* Fixed packaging manifest.

=== 11.0.0 / 2016-03-09

==== Bug fixes

* Correctly handle bad encoding in exception messages. Pull request #113
  by Tomer Brisker
* Fix verbose option at TestTask. Pull request #67 by Mike Blumtritt

==== Enhancements

* Make FileList#exclude more analogous to FileList#include.
* Use IO.open instead of Open3.popen3 for CPU counter.
* Make Rake::Task#already_invoked publicly accessible.
  Pull request #93 by Joe Rafaniello
* Lookup prerequisites with same name outside of scope instead of
  matching self. Pull request #96 by Sandy Vanderbleek
* Make FileList#pathmap behave like String#pathmap.
  Pull request #61 by Daniel Tamai
* Add fetch method to task arguments.
  Pull request #12 by Chris Keathley
* Use ruby warnings by default. Pull request #97 by Harold Giménez

==== Compatibility Changes

* Removed to support Ruby 1.8.x
* Removed constant named `RAKEVERSION`
* Removed Rake::AltSystem
* Removed Rake::RubyForgePublisher
* Removed Rake::TaskManager#last\_comment. Use last\_description.
* Removed Rake::TaskLib#paste
* Removed Top-level SshDirPublisher, SshFreshDirPublisher, SshFilePublisher
  and CompositePublisher from lib/rake/contrib/publisher.rb
* Removed "rake/runtest.rb"

=== 10.5.0 / 2016-01-13

==== Enhancements

* Removed monkey patching for Ruby 1.8. Pull request #46 by Pablo Herrero.
* Inheritance class of Rake::FileList returns always self class.
  Pull request #74 by Thomas Scholz

=== 10.4.2 / 2014-12-02

==== Bug fixes

* Rake no longer edits ARGV.  This allows you to re-exec rake from a rake
  task.  Pull requset #9 by Matt Palmer.
* Documented how Rake::DSL#desc handles sentences in task descriptions.
  Issue #7 by Raza Sayed.
* Fixed test error on 1.9.3 with legacy RubyGems.  Issue #8 by Matt Palmer.
* Deleted duplicated History entry.  Pull request #10 by Yuji Yamamoto.

=== 10.4.1 / 2014-12-01

==== Bug fixes

* Reverted fix for #277 as it caused numerous issues for rake users.
  rails/spring issue #366 by Gustavo Dutra.

=== 10.4.0 / 2014-11-22

==== Enhancements

* Upgraded to minitest 5.  Pull request #292 by Teo Ljungberg.
* Added support for Pathname in rake tasks.  Pull request #271 by Randy
  Coulman.
* Rake now ignores falsy dependencies which allows for easier programmatic
  creation of tasks.  Pull request #273 by Manav.
* Rake no longer edits ARGV.  This allows you to re-exec rake from a rake
  task.  Issue #277 by Matt Palmer.
* Etc.nprocessors is used for counting the number of CPUs.

==== Bug fixes

* Updated rake manpage.  Issue #283 by Nathan Long, pull request #291 by
  skittleys.
* Add Rake::LATE to allow rebuilding of files that depend on deleted files.
  Bug #286, pull request #287 by David Grayson.
* Fix relinking of files when repackaging.  Bug #276 by Muenze.
* Fixed some typos.  Pull request #280 by Jed Northridge.
* Try counting CPUs via cpuinfo if host_os was not matched.  Pull request
  #282 by Edouard B.

=== 10.3.2 / 2014-05-15

==== Bug fixes

* Rake no longer infinitely loops when showing exception causes that refer to
  each other.  Bug #272 by Chris Bandy.
* Fixed documentation typos.  Bug #275 by Jake Worth.

=== 10.3.1 / 2014-04-17

==== Bug fixes

* Really stop reporting an error when cleaning already-deleted files.  Pull
  request #269 by Randy Coulman
* Fixed infinite loop when cleaning already-deleted files on windows.

=== 10.3 / 2014-04-15

==== Enhancements

* Added --build-all option to rake which treats all file prerequisites as
  out-of-date.  Pull request #254 by Andrew Gilbert.
* Added Rake::NameSpace#scope.  Issue #263 by Jon San Miguel.

==== Bug fixes

* Suppress org.jruby package files in rake error messages for JRuby users.
  Issue #213 by Charles Nutter.
* Fixed typo, removed extra "h".  Pull request #267 by Hsing-Hui Hsu.
* Rake no longer reports an error when cleaning already-deleted files.  Pull
  request #266 by Randy Coulman.
* Consume stderr while determining CPU count to avoid hang.  Issue #268 by
  Albert Sun.

=== 10.2.2 / 2014-03-27

==== Bug fixes

* Restored Ruby 1.8.7 compatibility

=== 10.2.1 / 2014-03-25

==== Bug fixes

* File tasks including a ':' are now top-level tasks again.  Issue #262 by
  Josh Holtrop.
* Use sysctl for CPU count for all BSDs.  Pull request #261 by Joshua Stein.
* Fixed CPU detection for unknown platforms.

=== 10.2.0 / 2014-03-24

==== Enhancements

* Rake now requires Ruby 1.9 or newer.  For me, this is a breaking change, but
  it seems that Jim planned to release it with Rake 10.2.  See also pull
  request #247 by Philip Arndt.
* Rake now allows you to declare tasks under a namespace like:

    task 'a:b' do ... end

  Pull request #232 by Judson Lester.
* Task#source defaults to the first prerequisite in non-rule tasks.  Pull
  request #215 by Avdi Grimm.
* Rake now automatically rebuilds and reloads imported files.  Pull request
  #209 by Randy Coulman.
* The rake task arguments can contain escaped commas.  Pull request #214 by
  Filip Hrbek.
* Rake now prints the exception class on errors.  Patch #251 by David Cornu.

==== Bug fixes

* Fixed typos.  Pull request #256 by Valera Rozuvan, #250 via Jake Worth, #260
  by Zachary Scott.
* Fixed documentation for calling tasks with arguments.  Pull request #235 by
  John Varghese.
* Clarified `rake -f` usage message.  Pull request #252 by Marco Pfatschbacher.
* Fixed a test failure on windows.  Pull request #231 by Hiroshi Shirosaki.
* Fixed corrupted rake.1.gz.  Pull request #225 by Michel Boaventura.
* Fixed bug in can\_detect\_signals? in test.  Patch from #243 by Alexey
  Borzenkov.

=== 10.1.1

* Use http://github.com/jimweirich/rake instead of http://rake.rubyforge.org for
  canonical project url.

=== 10.1.0

==== Changes

===== New Features

* Add support for variable length task argument lists. If more actual
  arguments are supplied than named arguments, then the extra
  arguments values will be in args.extras.

* Application name is not displayed in the help banner. (Previously
  "rake" was hardcoded, now rake-based applications can display their
  own names).

===== Bug Fixes

Bug fixes include:

* Fix backtrace suppression issues.

* Rules now explicit get task arguments passed to them.

* Rename FileList#exclude? to FileList#exclude\_from\_list? to avoid
  conflict with new Rails method.

* Clean / Clobber tasks now report failure to remove files.

* Plus heaps of internal code cleanup.

==== Thanks

As usual, it was input from users that drove a lot of these changes.
The following people contributed patches, made suggestions or made
otherwise helpful comments. Thanks to ...

* Michael Nikitochkin (general code cleanup)
* Vipul A M (general code cleanup)
* Dennis Bell (variable length task argument lists)
* Jacob Swanner (rules arguments)
* Rafael Rosa Fu (documentation typo)
* Stuart Nelson (install.rb fixes)
* Lee Hambley (application name in help banner)

-- Jim Weirich

=== 10.0.3

  "Jim, when will Rake reach version 1.0?"

Over the past several years I've been asked that question at
conferences, panels and over twitter. Due to historical reasons (or
maybe just plain laziness) Rake has (incorrectly) been treating the
second digit of the version as the major release number. So in my head
Rake was already at version 9.

Well, it's time to fix things. This next version of Rake drops old,
crufty, backwards compatibility hacks such as top level constants, DSL
methods defined in Object and numerous other features that are just no
longer desired. It's also time to drop the leading zero from the
version number as well and call this new version of rake what it
really is: Version 10.

So, welcome to Rake 10.0!

Rake 10 is actually feature identical to the latest version of Rake 9
(that would be the version spelled 0.9.3), *except* that Rake 10 drops
all the sundry deprecated features that have accumulated over the years.

If your Rakefile is up to date and current with all the new features
of Rake 10, you are ready to go. If your Rakefile still uses a few
deprecated feeatures, feel free to use Rake 9 (0.9.3) with the same
feature set. Just be aware that future features will be in Rake 10
family line.

==== Changes

As mentioned above, there are no new features in Rake 10. However,
there are a number of features missing:

* Classic namespaces are now gone. Rake is no longer able to reflect
  the options settings in the global variables ($rakefile, $show\_tasks,
  $show\_prereqs, $trace, $dryrun and $silent). The
  <tt>--classic-namespace</tt> option is no longer supported.

* Global constants are no longer supported. This includes
  <tt>Task</tt>, <tt>FileTask</tt>, <tt>FileCreationTask</tt> and
  <tt>RakeApp</tt>). The constant missing hook to warn about using
  global rake constants has been removed.

* The Rake DSL methods (task, file, directory, etc) are in their own
  module (Rake::DSL). The stub versions of these methods (that printed
  warnings) in Object have been removed. However, the DSL methods are
  added to the top-level <tt>main</tt> object. Since <tt>main</tt> is
  not in the inheritance tree, the presence of the DSL methods in main
  should be low impact on other libraries.

  If you want to use the Rake DSL commands from your own code, just
  include <tt>Rake::DSL</tt> into your own classes and modules.

* The deprecated syntax for task arguments (the one using
  <tt>:needs</tt>) has been removed.

* The <tt>--reduce-compat</tt> flag has been removed (it's not needed
  anymore).

* The deprecated <tt>rake/sys.rb</tt> library has been removed.

* The deprecated <tt>rake/rdoctask.rb</tt> library has been removed.
  RDoc supplies its own rake task now.

* The deprecated <tt>rake/gempackagetask.rb</tt> library has been
  removed. Gem supplies its own package task now.

There is one small behavioral change:

* Non-file tasks now always report the current time as their time
  stamp. This is different from the previous behavior where non-file
  tasks reported current time only if there were no prerequisites, and
  the max prerequisite timestamp otherwise. This lead to inconsistent
  and surprising behavior when adding prerequisites to tasks that in
  turn were prequisites to file tasks. The new behavior is more
  consistent and predictable.

==== Changes (from 0.9.3, 0.9.4, 0.9.5)

Since Rake 10 includes the changes from the last version of Rake 9,
we'll repeat the changes for versions 0.9.3 through 0.9.5 here.

===== New Features (in 0.9.3)

* Multitask tasks now use a thread pool. Use -j to limit the number of
  available threads.

* Use -m to turn regular tasks into multitasks (use at your own risk).

* You can now do "Rake.add_rakelib 'dir'" in your Rakefile to
  programatically add rake task libraries.

* You can specific backtrace suppression patterns (see
  --suppress-backtrace)

* Directory tasks can now take prerequisites and actions

* Use --backtrace to request a full backtrace without the task trace.

* You can say "--backtrace=stdout" and "--trace=stdout" to route trace
  output to standard output rather than standard error.

* Optional 'phony' target (enable with 'require 'rake/phony'") for
  special purpose builds.

* Task#clear now clears task comments as well as actions and
  prerequisites. Task#clear_comment will specifically target comments.

* The --all option will force -T and -D to consider all the tasks,
  with and without descriptions.

===== Bug Fixes (in 0.9.3)

* Semi-colons in windows rakefile paths now work.

* Improved Control-C support when invoking multiple test suites.

* egrep method now reads files in text mode (better support for
  Windows)

* Better deprecation line number reporting.

* The -W option now works with all tasks, whether they have a
  description or not.

* File globs in rake should not be sorted alphabetically, independent
  of file system and platform.

* Numerous internal improvements.

* Documentation typos and fixes.

===== Bug Fixes (in 0.9.4)

* Exit status with failing tests is not correctly set to non-zero.

* Simplified syntax for phony task (for older versions of RDoc).

* Stand alone FileList usage gets glob function (without loading in
  extra dependencies)

===== Bug Fixes (in 0.9.5)

* --trace and --backtrace no longer swallow following task names.

==== Thanks

As usual, it was input from users that drove a lot of these changes. The
following people contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* Aaron Patterson
* Dylan Smith
* Jo Liss
* Jonas Pfenniger
* Kazuki Tsujimoto
* Michael Bishop
* Michael Elufimov
* NAKAMURA Usaku
* Ryan Davis
* Sam Grönblom
* Sam Phippen
* Sergio Wong
* Tay Ray Chuan
* grosser
* quix

Also, many thanks to Eric Hodel for assisting with getting this release
out the door.

-- Jim Weirich

=== 10.0.2

==== Changes

===== Bug Fixes

* --trace and --backtrace no longer swallow following task names.

==== Thanks

As usual, it was input from users that drove a lot of these changes. The
following people contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* Aaron Patterson
* Dylan Smith
* Jo Liss
* Jonas Pfenniger
* Kazuki Tsujimoto
* Michael Bishop
* Michael Elufimov
* NAKAMURA Usaku
* Ryan Davis
* Sam Grönblom
* Sam Phippen
* Sergio Wong
* Tay Ray Chuan
* grosser
* quix

Also, many thanks to Eric Hodel for assisting with getting this release
out the door.

-- Jim Weirich

=== 10.0.1

==== Changes

===== Bug Fixes

* Exit status with failing tests is not correctly set to non-zero.

* Simplified syntax for phony task (for older versions of RDoc).

* Stand alone FileList usage gets glob function (without loading in
  extra dependencies)

==== Thanks

As usual, it was input from users that drove a lot of these changes. The
following people contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* Aaron Patterson
* Dylan Smith
* Jo Liss
* Jonas Pfenniger
* Kazuki Tsujimoto
* Michael Bishop
* Michael Elufimov
* NAKAMURA Usaku
* Ryan Davis
* Sam Grönblom
* Sam Phippen
* Sergio Wong
* Tay Ray Chuan
* grosser
* quix

Also, many thanks to Eric Hodel for assisting with getting this release
out the door.

-- Jim Weirich

=== 10.0.0

  "Jim, when will Rake reach version 1.0?"

Over the past several years I've been asked that question at
conferences, panels and over twitter. Due to historical reasons (or
maybe just plain laziness) Rake has (incorrectly) been treating the
second digit of the version as the major release number. So in my head
Rake was already at version 9.

Well, it's time to fix things. This next version of Rake drops old,
crufty, backwards compatibility hacks such as top level constants, DSL
methods defined in Object and numerous other features that are just no
longer desired. It's also time to drop the leading zero from the
version number as well and call this new version of rake what it
really is: Version 10.

So, welcome to Rake 10.0!

Rake 10 is actually feature identical to the latest version of Rake 9
(that would be the version spelled 0.9.3), *except* that Rake 10 drops
all the sundry deprecated features that have accumulated over the years.

If your Rakefile is up to date and current with all the new features
of Rake 10, you are ready to go. If your Rakefile still uses a few
deprecated feeatures, feel free to use Rake 9 (0.9.3) with the same
feature set. Just be aware that future features will be in Rake 10
family line.

==== Changes in 10.0

As mentioned above, there are no new features in Rake 10. However,
there are a number of features missing:

* Classic namespaces are now gone. Rake is no longer able to reflect
  the options settings in the global variables ($rakefile, $show\_tasks,
  $show\_prereqs, $trace, $dryrun and $silent). The
  <tt>--classic-namespace</tt> option is no longer supported.

* Global constants are no longer supported. This includes
  <tt>Task</tt>, <tt>FileTask</tt>, <tt>FileCreationTask</tt> and
  <tt>RakeApp</tt>). The constant missing hook to warn about using
  global rake constants has been removed.

* The Rake DSL methods (task, file, directory, etc) are in their own
  module (Rake::DSL). The stub versions of these methods (that printed
  warnings) in Object have been removed. However, the DSL methods are
  added to the top-level <tt>main</tt> object. Since <tt>main</tt> is
  not in the inheritance tree, the presence of the DSL methods in main
  should be low impact on other libraries.

  If you want to use the Rake DSL commands from your own code, just
  include <tt>Rake::DSL</tt> into your own classes and modules.

* The deprecated syntax for task arguments (the one using
  <tt>:needs</tt>) has been removed.

* The <tt>--reduce-compat</tt> flag has been removed (it's not needed
  anymore).

* The deprecated <tt>rake/sys.rb</tt> library has been removed.

* The deprecated <tt>rake/rdoctask.rb</tt> library has been removed.
  RDoc supplies its own rake task now.

* The deprecated <tt>rake/gempackagetask.rb</tt> library has been
  removed. Gem supplies its own package task now.

There is one small behavioral change:

* Non-file tasks now always report the current time as their time
  stamp. This is different from the previous behavior where non-file
  tasks reported current time only if there were no prerequisites, and
  the max prerequisite timestamp otherwise. This lead to inconsistent
  and surprising behavior when adding prerequisites to tasks that in
  turn were prequisites to file tasks. The new behavior is more
  consistent and predictable.

==== Changes (from 0.9.3)

Since Rake 10 includes the changes from the last version of Rake 9,
we'll repeat the changes for version 0.9.3 here.

===== New Features

* Multitask tasks now use a thread pool. Use -j to limit the number of
  available threads.

* Use -m to turn regular tasks into multitasks (use at your own risk).

* You can now do "Rake.add_rakelib 'dir'" in your Rakefile to
  programatically add rake task libraries.

* You can specific backtrace suppression patterns (see
  --suppress-backtrace)

* Directory tasks can now take prerequisites and actions

* Use --backtrace to request a full backtrace without the task trace.

* You can say "--backtrace=stdout" and "--trace=stdout" to route trace
  output to standard output rather than standard error.

* Optional 'phony' target (enable with 'require 'rake/phony'") for
  special purpose builds.

* Task#clear now clears task comments as well as actions and
  prerequisites. Task#clear_comment will specifically target comments.

* The --all option will force -T and -D to consider all the tasks,
  with and without descriptions.

===== Bug Fixes

* Semi-colons in windows rakefile paths now work.

* Improved Control-C support when invoking multiple test suites.

* egrep method now reads files in text mode (better support for
  Windows)

* Better deprecation line number reporting.

* The -W option now works with all tasks, whether they have a
  description or not.

* File globs in rake should not be sorted alphabetically, independent
  of file system and platform.

* Numerous internal improvements.

* Documentation typos and fixes.


==== Thanks

As usual, it was input from users that drove a lot of these changes. The
following people contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* Aaron Patterson
* Dylan Smith
* Jo Liss
* Jonas Pfenniger
* Kazuki Tsujimoto
* Michael Bishop
* Michael Elufimov
* NAKAMURA Usaku
* Ryan Davis
* Sam Grönblom
* Sam Phippen
* Sergio Wong
* Tay Ray Chuan
* grosser
* quix

Also, many thanks to Eric Hodel for assisting with getting this release
out the door.

-- Jim Weirich

=== 0.9.6

Rake version 0.9.6 contains a number of fixes mainly for merging
Rake into the Ruby source tree and fixing tests.

==== Changes

===== Bug Fixes (0.9.6)

* Better trace output when using a multi-threaded Rakefile.
* Arg parsing is now consistent for tasks and multitasks.
* Skip exit code test in versions of Ruby that don't support it well.

Changes for better integration with the Ruby source tree:

* Fix version literal for Ruby source tree build.
* Better loading of libraries for testing in Ruby build.
* Use the ruby version provided by Ruby's tests.

==== Thanks

As usual, it was input from users that drove a alot of these changes. The
following people either contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* Aaron Patterson
* Dylan Smith
* Jo Liss
* Jonas Pfenniger
* Kazuki Tsujimoto
* Michael Bishop
* Michael Elufimov
* NAKAMURA Usaku
* Ryan Davis
* Sam Grönblom
* Sam Phippen
* Sergio Wong
* Tay Ray Chuan
* grosser
* quix

Also, many thanks to Eric Hodel for assisting with getting this release
out the door.

-- Jim Weirich

=== 0.9.5

Rake version 0.9.5 contains a number of bug fixes.

==== Changes

===== Bug Fixes (0.9.5)

* --trace and --backtrace no longer swallow following task names.

==== Thanks

As usual, it was input from users that drove a alot of these changes. The
following people either contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* Aaron Patterson
* Dylan Smith
* Jo Liss
* Jonas Pfenniger
* Kazuki Tsujimoto
* Michael Bishop
* Michael Elufimov
* NAKAMURA Usaku
* Ryan Davis
* Sam Grönblom
* Sam Phippen
* Sergio Wong
* Tay Ray Chuan
* grosser
* quix

Also, many thanks to Eric Hodel for assisting with getting this release
out the door.

-- Jim Weirich

=== 0.9.4

Rake version 0.9.4 contains a number of bug fixes.

==== Changes

===== Bug Fixes (0.9.4)

* Exit status with failing tests is not correctly set to non-zero.

* Simplified syntax for phony task (for older versions of RDoc).

* Stand alone FileList usage gets glob function (without loading in
  extra dependencies)

==== Thanks

As usual, it was input from users that drove a alot of these changes. The
following people either contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* Aaron Patterson
* Dylan Smith
* Jo Liss
* Jonas Pfenniger
* Kazuki Tsujimoto
* Michael Bishop
* Michael Elufimov
* NAKAMURA Usaku
* Ryan Davis
* Sam Grönblom
* Sam Phippen
* Sergio Wong
* Tay Ray Chuan
* grosser
* quix

Also, many thanks to Eric Hodel for assisting with getting this release
out the door.

-- Jim Weirich

=== 0.9.3

Rake version 0.9.3 contains some new, backwards compatible features and
a number of bug fixes.

==== Changes

===== New Features

* Multitask tasks now use a thread pool. Use -j to limit the number of
  available threads.

* Use -m to turn regular tasks into multitasks (use at your own risk).

* You can now do "Rake.add_rakelib 'dir'" in your Rakefile to
  programatically add rake task libraries.

* You can specific backtrace suppression patterns (see
  --suppress-backtrace)

* Directory tasks can now take prerequisites and actions

* Use --backtrace to request a full backtrace without the task trace.

* You can say "--backtrace=stdout" and "--trace=stdout" to route trace
  output to standard output rather than standard error.

* Optional 'phony' target (enable with 'require 'rake/phony'") for
  special purpose builds.

* Task#clear now clears task comments as well as actions and
  prerequisites. Task#clear_comment will specifically target comments.

* The --all option will force -T and -D to consider all the tasks,
  with and without descriptions.

===== Bug Fixes

* Semi-colons in windows rakefile paths now work.

* Improved Control-C support when invoking multiple test suites.

* egrep method now reads files in text mode (better support for
  Windows)

* Better deprecation line number reporting.

* The -W option now works with all tasks, whether they have a
  description or not.

* File globs in rake should not be sorted alphabetically, independent
  of file system and platform.

* Numerous internal improvements.

* Documentation typos and fixes.

==== Thanks

As usual, it was input from users that drove a alot of these changes. The
following people either contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* Aaron Patterson
* Dylan Smith
* Jo Liss
* Jonas Pfenniger
* Kazuki Tsujimoto
* Michael Bishop
* Michael Elufimov
* NAKAMURA Usaku
* Ryan Davis
* Sam Grönblom
* Sam Phippen
* Sergio Wong
* Tay Ray Chuan
* grosser
* quix

Also, many thanks to Eric Hodel for assisting with getting this release
out the door.

-- Jim Weirich

=== Rake 0.9.2.2

Rake version 0.9.2.2 is mainly bug fixes.

==== Changes

* The rake test loader now removes arguments it has processed.  Issue #51
* Rake::TaskArguments now responds to #values\_at
* RakeFileUtils.verbose_flag = nil silences output the same as 0.8.7
* Rake tests are now directory-independent
* Rake tests are no longer require flexmock
* Commands constant is no longer polluting top level namespace.
* Show only the interesting portion of the backtrace by default (James M. Lawrence).
* Added --reduce-compat option to remove backward compatible DSL hacks (James M. Lawrence).

==== Thanks

As usual, it was input from users that drove a alot of these changes. The
following people either contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* James M. Lawrence (quix)
* Roger Pack
* Cezary Baginski
* Sean Scot August Moon
* R.T. Lechow
* Alex Chaffee
* James Tucker
* Matthias Lüdtke
* Santiago Pastorino

Also, bit thanks to Eric Hodel for assisting with getting this release
out the door (where "assisting" includes, but is not by any means
limited to, "pushing" me to get it done).

-- Jim Weirich

=== 0.9.2

Rake version 0.9.2 has a few small fixes.  See below for details.

==== Changes

* Support for Ruby 1.8.6 was fixed.
* Global DSL warnings now honor --no-deprecate

==== Thanks

As usual, it was input from users that drove a alot of these changes. The
following people either contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* James M. Lawrence (quix)
* Roger Pack
* Cezary Baginski
* Sean Scot August Moon
* R.T. Lechow
* Alex Chaffee
* James Tucker
* Matthias Lüdtke
* Santiago Pastorino

Also, bit thanks to Eric Hodel for assisting with getting this release
out the door (where "assisting" includes, but is not by any means
limited to, "pushing" me to get it done).

-- Jim Weirich

=== 0.9.1

Rake version 0.9.1 has a number of bug fixes and enhancments (see
below for more details).  Additionally, the internals have be slightly
restructured and improved.

==== Changes

Rake 0.9.1 adds back the global DSL methods, but with deprecation
messages.  This allows Rake 0.9.1 to be used with older rakefiles with
warning messages.

==== Thanks

As usual, it was input from users that drove a alot of these changes. The
following people either contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* James M. Lawrence (quix)
* Roger Pack
* Cezary Baginski
* Sean Scot August Moon
* R.T. Lechow
* Alex Chaffee
* James Tucker
* Matthias Lüdtke
* Santiago Pastorino

Also, bit thanks to Eric Hodel for assisting with getting this release
out the door (where "assisting" includes, but is not by any means
limited to, "pushing" me to get it done).

-- Jim Weirich

=== 0.9.0

Rake version 0.9.0 has a number of bug fixes and enhancments (see
below for more details).  Additionally, the internals have be slightly
restructured and improved.

==== Changes

===== New Features / Enhancements / Bug Fixes in Version 0.9.0

* Rake now warns when the deprecated :needs syntax used (and suggests
  the proper syntax in the warning).

* Moved Rake DSL commands to top level ruby object 'main'.  Rake DSL
  commands are no longer private methods in Object. (Suggested by
  James M. Lawrence/quix)

* Rake now uses case-insensitive comparisons to find the Rakefile on Windows.
  Based on patch by Roger Pack.

* Rake now requires (instead of loads) files in the test task.  Patch by Cezary
  Baginski.

* Fixed typos.  Patches by Sean Scot August Moon and R.T. Lechow.

* Rake now prints the Rakefile directory only when it's different from the
  current directory.  Patch by Alex Chaffee.

* Improved rakefile_location discovery on Windows.  Patch by James Tucker.

* Rake now recognizes "Windows Server" as a windows system.  Patch by Matthias
  Lüdtke

* Rake::RDocTask is deprecated.  Use RDoc::Task from RDoc 2.4.2+ (require
  'rdoc/task')

* Rake::GemPackageTask is deprecated.  Use Gem::PackageTask (require
  'rubygems/package\_task')

* Rake now outputs various messages to $stderr instead of $stdout.

* Rake no longer emits warnings for Config.  Patch by Santiago Pastorino.

* Removed Rake's DSL methods from the top level scope.  If you need to
  call 'task :xzy' in your code, include Rake::DSL into your class, or
  put the code in a Rake::DSL.environment do ... end block.

* Split rake.rb into individual files.

* Support for the --where (-W) flag for showing where a task is defined.

* Fixed quoting in test task.
  (http://onestepback.org/redmine/issues/show/44,
  http://www.pivotaltracker.com/story/show/1223138)

* Fixed the silent option parsing problem.
  (http://onestepback.org/redmine/issues/show/47)

* Fixed :verbose=>false flag on sh and ruby commands.

* Rake command line options may be given by default in a RAKEOPT
  environment variable.

* Errors in Rake will now display the task invocation chain in effect
  at the time of the error.

* Accepted change by warnickr to not expand test patterns in shell
  (allowing more files in the test suite).

* Fixed that file tasks did not perform prereq lookups in scope
  (Redmine #57).

==== Thanks

As usual, it was input from users that drove a alot of these changes. The
following people either contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* James M. Lawrence (quix)
* Roger Pack
* Cezary Baginski
* Sean Scot August Moon
* R.T. Lechow
* Alex Chaffee
* James Tucker
* Matthias Lüdtke
* Santiago Pastorino

Also, bit thanks to Eric Hodel for assisting with getting this release
out the door (where "assisting" includes, but is not by any means
limited to, "pushing" me to get it done).

-- Jim Weirich


=== 0.8.7

Rake version 0.8.5 introduced greatly improved support for executing
commands on Windows.  The "sh" command now has the same semantics on
Windows that it has on Unix based platforms.

Rake version 0.8.6 includes minor fixes the the RDoc generation.
Rake version 0.8.7 includes a minor fix for JRuby running on windows.

==== Changes

===== New Features / Enhancements in Version 0.8.5

* Improved implementation of the Rake system command for Windows.
  (patch from James M. Lawrence/quix)

* Support for Ruby 1.9's improved system command.  (patch from James
  M. Lawrence/quix)

* Rake now includes the configured extension when invoking an
  executable (Config::CONFIG['EXEEXT])

===== Bug Fixes in Version 0.8.5

* Environment variable keys are now correctly cased (it matters in
  some implementations).

==== Thanks

As usual, it was input from users that drove a alot of these changes. The
following people either contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* Charles Nutter

-- Jim Weirich

=== 0.8.6

Rake version 0.8.5 introduced greatly improved support for executing
commands on Windows.  The "sh" command now has the same semantics on
Windows that it has on Unix based platforms.

Rake version 0.8.5 includes minor fixes the the RDoc generation.

==== Thanks

As usual, it was input from users that drove a alot of these changes. The
following people either contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* James M. Lawrence/quix
* Luis Lavena

-- Jim Weirich

=== 0.8.5

Rake version 0.8.5 is a new release of Rake with greatly improved
support for executing commands on Windows.  The "sh" command now has
the same semantics on Windows that it has on Unix based platforms.

==== Changes

===== New Features / Enhancements in Version 0.8.5

* Improved implementation of the Rake system command for Windows.
  (patch from James M. Lawrence/quix)

* Support for Ruby 1.9's improved system command.  (patch from James
  M. Lawrence/quix)

* Rake now includes the configured extension when invoking an
  executable (Config::CONFIG['EXEEXT])

===== Bug Fixes in Version 0.8.5

* Environment variable keys are now correctly cased (it matters in
  some implementations).

==== Thanks

As usual, it was input from users that drove a alot of these changes. The
following people either contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* James M. Lawrence/quix
* Luis Lavena

-- Jim Weirich

=== 0.8.4

Rake version 0.8.4 is a bug-fix release of rake.

NOTE: The version of Rake that comes with Ruby 1.9 has diverged
      slightly from the core Rake code base.  Rake 0.8.4 will work
      with Ruby 1.9, but is not a strict upgrade for the Rake that
      comes with Ruby 1.9.  A (near) future release of Rake will unify
      those two codebases.

==== Letter Writing Campaign

Thanks to Aaron Patterson (@tenderlove) and Eric Hodel (@drbrain) for
their encouraging support in organizing a letter writing campaign to
lobby for the "Warning Free" release of rake 0.8.4.  A special callout
goes to Jonathan D. Lord, Sr (Dr. Wingnut) whose postcard was the
first to actually reach me. (see
http://tenderlovemaking.com/2009/02/26/we-need-a-new-version-of-rake/
for details)

==== Changes

===== New Features / Enhancements in Version 0.8.4

* Case is preserved on rakefile names. (patch from James
  M. Lawrence/quix)

* Improved Rakefile case insensitivity testing (patch from Luis
  Lavena).

* Windows system dir search order is now: HOME, HOMEDRIVE + HOMEPATH,
  APPDATA, USERPROFILE (patch from Luis Lavena)

* MingGW is now recognized as a windows platform.  (patch from Luis
  Lavena)

===== Bug Fixes in Version 0.8.4

* Removed reference to manage_gem to fix the warning produced by the
  gem package task.

* Fixed stray ARGV option problem that was interfering with
  Test::Unit::Runner. (patch from Pivotal Labs)

===== Infrastructure Improvements in Version 0.8.4

* Numerous fixes to the windows test suite (patch from Luis Lavena).

* Improved Rakefile case insensitivity testing (patch from Luis
  Lavena).

* Better support for windows paths in the test task (patch from Simon
  Chiang/bahuvrihi)

==== Thanks

As usual, it was input from users that drove a alot of these changes. The
following people either contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* James M. Lawrence/quix
* Luis Lavena
* Pivotal Labs
* Simon Chiang/bahuvrihi

-- Jim Weirich

=== 0.8.3

Rake version 0.8.3 is a bug-fix release of rake.

==== Changes

===== Bug Fixes in Version 0.8.3

* Enhanced the system directory detection in windows. We now check
  HOMEDRIVE/HOMEPATH and USERPROFILE if APPDATA isn't found. (Patch
  supplied by James Tucker). Rake no long aborts if it can't find the
  directory.

* Added fix to handle ruby installations in directories with spaces in
  their name.

==== Thanks

As usual, it was input from users that drove a alot of these changes. The
following people either contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* Edwin Pratomo
* Gavin Stark
* Adam Q. Salter
* Adam Majer
* Emanuel Indermühle
* Ittay Dror
* Bheeshmar Redheendran (for spending an afternoon with me debugging
  windows issues)

-- Jim Weirich


=== 0.8.2

Rake version 0.8.2 is a new release of rake that includes a number of
new features and numerous bug fixes.

==== Changes

===== New Features in Version 0.8.2

* Switched from getoptlong to optparse (patches supplied by Edwin
  Pratomo).

* The -T option will now attempt to dynamically sense the size of the
  terminal. The -T output will only self-truncate if the output is a
  tty. However, if RAKE_COLUMNS is explicitly set, it will be honored
  in any case. (Patch provided by Gavin Stark).

* The following public methods have been added to rake task objects:

  * task.clear -- Clear both the prerequisites and actions of the
    target rake task.
  * task.clear_prerequisites -- Clear all the existing prerequisites
    from the target rake task.
  * task.clear_actions -- Clear all the existing actions from the
    target rake task.
  * task.reenable -- Re-enable a task, allowing its actions to be
    executed again if the task is invoked.

* Changed RDoc test task to have no default template. This makes it
  easier for the tempate to pick up the template from the environment.

* Default values for task arguments can easily be specified with the
  :with_defaults method. (Idea for default argument merging supplied
  by (Adam Q. Salter)

===== Bug Fixes in Version 0.8.2

* Fixed bug in package task so that it will include the subdir
  directory in the package for testing. (Bug found by Adam Majer)

* Fixed filename dependency order bug in test\_inspect\_pending and
  test\_to\_s\_pending. (Bug found by Adam Majer)

* Fixed check for file utils options to make them immune to the
  symbol/string differences. (Patch supplied by Edwin Pratomo)

* Fixed bug with rules involving multiple source, where only the first
  dependency of a rule has any effect (Patch supplied by Emanuel
  Indermühle)

* FileList#clone and FileList#dup have better sematics w.r.t. taint
  and freeze.

* Changed from using Mutex to Monitor. Evidently Mutex causes thread
  join errors when Ruby is compiled with -disable-pthreads. (Patch
  supplied by Ittay Dror)

* Fixed bug in makefile parser that had problems with extra spaces in
  file task names. (Patch supplied by Ittay Dror)

==== Other changes in Version 0.8.2

* Added ENV var to rake's own Rakefile to prevent OS X from including
  extended attribute junk in the rake package tar file. (Bug found by
  Adam Majer)

* Added a performance patch for reading large makefile dependency
  files. (Patch supplied by Ittay Dror)

==== Task Argument Examples

Prior to version 0.8.0, rake was only able to handle command line
arguments of the form NAME=VALUE that were passed into Rake via the
ENV hash.  Many folks had asked for some kind of simple command line
arguments, perhaps using "--" to separate regular task names from
argument values on the command line.  The problem is that there was no
easy way to associate positional arguments on the command line with
different tasks.  Suppose both tasks :a and :b expect a command line
argument: does the first value go with :a?  What if :b is run first?
Should it then get the first command line argument.

Rake 0.8.0 solves this problem by explicitly passing values directly
to the tasks that need them.  For example, if I had a release task
that required a version number, I could say:

   rake release[0.8.2]

And the string "0.8.2" will be passed to the :release task.  Multiple
arguments can be passed by separating them with a comma, for example:

   rake name[john,doe]

Just a few words of caution.  The rake task name and its arguments
need to be a single command line argument to rake.  This generally
means no spaces.  If spaces are needed, then the entire rake +
argument string should be quoted.  Something like this:

   rake "name[billy bob, smith]"

(Quoting rules vary between operating systems and shells, so make sure
you consult the proper docs for your OS/shell).

===== Tasks that Expect Parameters

Parameters are only given to tasks that are setup to expect them.  In
order to handle named parameters, the task declaration syntax for
tasks has been extended slightly.

For example, a task that needs a first name and last name might be
declared as:

   task :name, :first_name, :last_name

The first argument is still the name of the task (:name in this case).
The next to argumements are the names of the parameters expected by
:name (:first_name and :last_name in the example).

To access the values of the parameters, the block defining the task
behaviour can now accept a second parameter:

   task :name, :first_name, :last_name do |t, args|
     puts "First name is #{args.first_name}"
     puts "Last  name is #{args.last_name}"
   end

The first argument of the block "t" is always bound to the current
task object.  The second argument "args" is an open-struct like object
that allows access to the task arguments.  Extra command line
arguments to a task are ignored.  Missing command line arguments are
given the nil value.

==== Thanks

As usual, it was input from users that drove a alot of these changes. The
following people either contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* Edwin Pratomo
* Gavin Stark
* Adam Q. Salter
* Adam Majer
* Emanuel Indermühle
* Ittay Dror
* Bheeshmar Redheendran (for spending an afternoon with me debugging
  windows issues)

-- Jim Weirich

=== 0.8.0/0.8.1

Rake version 0.8.0 is a new release of rake that includes serveral new
features.

==== Changes

===== New Features in Version 0.8.0

* Tasks can now receive command line parameters.  See the examples
  below for more details.

* Comments are limited to 80 columns on output, but full comments can
  be seen by using the -D parameter. (feature suggested by Jamis
  Buck).

* Explicit exit(n) calls will now set the exit status to n. (patch
  provided by Stephen Touset).

* Rake is now compatible with Ruby 1.9.

Version 0.8.1 is a minor update that includes additional Ruby 1.9
compatibility fixes.

==== Task Argument Examples

Prior to version 0.8.0, rake was only able to handle command line
arguments of the form NAME=VALUE that were passed into Rake via the
ENV hash.  Many folks had asked for some kind of simple command line
arguments, perhaps using "--" to separate regular task names from
argument values on the command line.  The problem is that there was no
easy way to associate positional arguments on the command line with
different tasks.  Suppose both tasks :a and :b expect a command line
argument: does the first value go with :a?  What if :b is run first?
Should it then get the first command line argument.

Rake 0.8.0 solves this problem by explicitly passing values directly
to the tasks that need them.  For example, if I had a release task
that required a version number, I could say:

   rake release[0.8.0]

And the string "0.8.0" will be passed to the :release task.  Multiple
arguments can be passed by separating them with a comma, for example:

   rake name[john,doe]

Just a few words of caution.  The rake task name and its arguments
need to be a single command line argument to rake.  This generally
means no spaces.  If spaces are needed, then the entire rake +
argument string should be quoted.  Something like this:

   rake "name[billy bob, smith]"

(Quoting rules vary between operating systems and shells, so make sure
you consult the proper docs for your OS/shell).

===== Tasks that Expect Parameters

Parameters are only given to tasks that are setup to expect them.  In
order to handle named parameters, the task declaration syntax for
tasks has been extended slightly.

For example, a task that needs a first name and last name might be
declared as:

   task :name, :first_name, :last_name

The first argument is still the name of the task (:name in this case).
The next to argumements are the names of the parameters expected by
:name (:first_name and :last_name in the example).

To access the values of the parameters, the block defining the task
behaviour can now accept a second parameter:

   task :name, :first_name, :last_name do |t, args|
     puts "First name is #{args.first_name}"
     puts "Last  name is #{args.last_name}"
   end

The first argument of the block "t" is always bound to the current
task object.  The second argument "args" is an open-struct like object
that allows access to the task arguments.  Extra command line
arguments to a task are ignored.  Missing command line arguments are
given the nil value.

==== Thanks

As usual, it was input from users that drove a alot of these changes. The
following people either contributed patches, made suggestions or made
otherwise helpful comments.  Thanks to ...

* Jamis Buck (for comment formatting suggestions)
* Stephen Touset (for exit status patch).

-- Jim Weirich


=== 0.7.3

Rake version 0.7.3 is a minor release that includes some refactoring to better
support custom Rake applications.

==== Changes

===== New Features in Version 0.7.3

* Added the +init+ and +top_level+ methods to make the creation of custom Rake applications a bit easier.  E.g.

    gem 'rake', ">= 0.7.3"
    require 'rake'

    Rake.application.init('myrake')

    task :default do
      something_interesting
    end

    Rake.application.top_level

==== Thanks

As usual, it was input from users that drove a alot of these changes. The
following people either contributed patches, made suggestions or made
otherwise helpful comments. Thanks to ...

-- Jim Weirich


=== 0.7.2


Version 0.7.2 supplies a bug fix and a few minor enhancements. In
particular, the new version fixes an incompatibility with the soon to
be released Ruby 1.8.6.  We strongly recommend upgrading to Rake 0.7.2
in order to be compatible with the new version of Ruby.

==== Changes

===== Bug Fixes in 0.7.2

There are quite a number of bug fixes in the new 0.7.2 version of
Rake:

* Removed dependency on internal fu_xxx functions from FileUtils.

* Error messages are now send to stderr rather than stdout (from
  Payton Quackenbush).

* Better error handling on invalid command line arguments (from Payton
  Quackenbush).

* Fixed some bugs where the application object was going to the global
  appliation instead of using its own data.

* Fixed the method name leak from FileUtils (bug found by Glenn
  Vanderburg).

* Added test for noop, bad_option and verbose flags to sh command.

* Added a description to the gem task in GemPackageTask.

* Fixed a bug when rules have multiple prerequisites (patch by Joel
  VanderWerf)

* Added the handful of RakeFileUtils to the private method as well.

===== New Features in 0.7.2

The following new features are available in Rake version 0.7.2:

* Added square and curly bracket patterns to FileList#include (Tilman
  Sauerbeck).

* FileLists can now pass a block to FileList#exclude to exclude files
  based on calculated values.

* Added plain filename support to rule dependents (suggested by Nobu
  Nakada).

* Added pathmap support to rule dependents.  In other words, if a
  pathmap format (beginning with a '%') is given as a Rake rule
  dependent, then the name of the depend will be the name of the
  target with the pathmap format applied.

* Added a 'tasks' method to a namespace to get a list of tasks
  associated with the namespace.

* Added tar_command and zip_command options to the Package task.

* The clean task will no longer delete 'core' if it is a directory.

===== Internal Rake Improvements

The following changes will are mainly internal improvements and
refactorings and have little effect on the end user.  But they may be
of interest to the general public.

* Added rcov task and updated unit testing for better code coverage.

* Added a 'shame' task to the Rakefile.

* Added rake_extension to handle detection of extension collisions.

* Added a protected 'require "rubygems"' to test/test_application to
  unbreak cruisecontrol.rb.

* Removed rake\_dup.  Now we just simply rescue a bad dup.

* Refactored the FileList reject logic to remove duplication.

* Removed if \_\_FILE\_\_ at the end of the rake.rb file.

==== Thanks

As usual, it was input from users that drove a alot of these changes.
The following people either contributed patches, made suggestions or
made otherwise helpful comments.  Thanks to ...

* Payton Quackenbush -- For several error handling improvements.

* Glenn Vanderburg -- For finding and fixing the method name leak from
  FileUtils.

* Joel VanderWerf -- for finding and fixing a bug in the handling of
  multiple prerequisites.

* Tilman Sauerbeck -- For some enhancing FileList to support more
  advanced file globbing.

* Nobu Nakada -- For suggesting plain file name support to rule dependents.

-- Jim Weirich

=== 0.7.1

Version 0.7.1 supplies a bug fix and a few minor enhancements.

==== Changes

===== Bug Fixes in 0.7.1

* Changes in the exception reported for the FileUtils.ln caused
  safe_ln to fail with a NotImplementedError.  Rake 0.7.1 will now
  catch that error or any StandardError and properly fall back to
  using +cp+.

===== New Features in 0.7.1

* You can filter the results of the --task option by supplying an
  optional regular expression.  This allows the user to easily find a
  particular task name in a long list of possible names.

* Transforming procs in a rule may now return a list of prerequisites.
  This allows more flexible rule formation.

* FileList and String now support a +pathmap+ melthod that makes the
  transforming paths a bit easier.  See the API docs for +pathmap+ for
  details.

* The -f option without a value will disable the search for a
  Rakefile.  This allows the Rakefile to be defined entirely in a
  library (and loaded with the -r option).  The current working
  directory is not changed when this is done.

==== Thanks

As usual, it was input from users that drove a alot of these changes.
The following people either contributed patches, made suggestions or
made otherwise helpful comments.  Thanks to ...

* James Britt and Assaph Mehr for reporting and helping to debug the
  safe_ln issue.

-- Jim Weirich


=== 0.7.0

These changes for Rake have been brewing for a long time.  Here they
are, I hope you enjoy them.

==== Changes

===== New Features

* Name space support for task names (see below).
* Prerequisites can be executed in parallel (see below).
* Added safe_ln support for openAFS (via Ludvig Omholt).
* RDoc defaults to internal (in-process) invocation.  The old behavior
  is still available by setting the +external+ flag to true.
* Rakefiles are now loaded with the expanded path to prevent
  accidental pollution from the Ruby load path.
* Task objects my now be used in prerequisite lists directly.
* Task objects (in addition to task names) may now be included in the
  prerequisite list of a task.
* Internals cleanup and refactoring.

===== Bug Fixes

* Compatibility fixes for Ruby 1.8.4 FileUtils changes.

===== Namespaces

Tasks can now be nested inside their own namespaces.  Tasks within one
namespace will not accidentally interfer with tasks named in a different
namespace.

For example:

  namespace "main" do
    task :build do
      # Build the main program
    end
  end

  namespace "samples" do
    task :build do
      # Build the sample programs
    end
  end

  task :build_all => ["main:build", "samples:build"]

Even though both tasks are named :build, they are separate tasks in
their own namespaces.  The :build_all task (defined in the toplevel
namespace) references both build tasks in its prerequisites.

You may invoke each of the individual build tasks with the following
commands:

  rake main:build
  rake samples:build

Or invoke both via the :build_all command:

  rake build_all

Namespaces may be nested arbitrarily.  Since the name of file tasks
correspond to the name of a file in the external file system,
FileTasks are not affected by the namespaces.

See the Rakefile format documentation (in the Rake API documents) for
more information.

===== Parallel Tasks

Sometimes you have several tasks that can be executed in parallel.  By
specifying these tasks as prerequisites to a +multitask+ task.

In the following example the tasks copy\_src, copy\_doc and copy\_bin
will all execute in parallel in their own thread.

  multitask :copy_files => [:copy_src, :copy_doc, :copy_bin] do
    puts "All Copies Complete"
  end

==== Thanks

As usual, it was input from users that drove a alot of these changes.
The following people either contributed patches, made suggestions or
made otherwise helpful comments.  Thanks to ...

* Doug Young (inspiration for the parallel task)
* David Heinemeier Hansson (for --trace message enhancement and for
  pushing for namespace support).
* Ludvig Omholt (for the openAFS fix)

-- Jim Weirich

=== 0.6.1

* Rebuilt 0.6.0 gem without signing.

=== 0.6.0

Its time for some long requested enhancements and lots of bug fixes
... And a whole new web page.

==== New Web Page

The primary documentation for rake has moved from the RubyForge based
wiki to its own Hieraki based web site.  Constant spam on the wiki
made it a difficult to keep clean.  The new site will be easier to
update and organize.

Check out the new documentation at: http://docs.rubyrake.org

We will be adding new documentation to the site as time goes on.

In addition to the new docs page, make sure you check out Martin
Fowlers article on rake at http://martinfowler.com/articles/rake.html

==== Changes

===== New Features

* Multiple prerequisites on Rake rules now allowed.  However, keep the
  following in mind:

  1. All the prerequisites of a rule must be available before a rule
     is triggered, where "enabled" means (a) an existing file, (b) a
     defined rule, or (c) another rule which also must be
     trigger-able.
  2. Rules are checked in order of definition, so it is important to
     order your rules properly.  If a file can be created by two
     different rules, put the more specific rule first (otherwise the
     more general rule will trigger first and the specific one will
     never be triggered).
  3. The <tt>source</tt> method now returns the name of the first
     prerequisite listed in the rule.  <tt>sources</tt> returns the
     names of all the rule prerequisites, ordered as they are defined
     in the rule.  If the task has other prerequisites not defined in
     the rule (but defined in an explicit task definition), then they
     will _not_ be included in the sources list.

* FileLists may now use the egrep command.  This popular enhancement
  is now a core part of the FileList object.  If you want to get a
  list of all your to-dos, fixmes and TBD comments, add the following
  to your Rakefile.

    desc "Look for TODO and FIXME tags in the code"
    task :todo do
      FileList['**/*.rb'].egrep /#.*(FIXME|TODO|TBD)/
    end

* The <tt>investigation</tt> method was added to task object to dump
  out some important values.  This makes it a bit easier to debug Rake
  tasks.

  For example, if you are having problems with a particular task, just
  print it out:

    task :huh do
      puts Rake::Task['huh'].investigation
    end

* The Rake::TestTask class now supports a "ruby\_opts" option to pass
  arbitrary ruby options to a test subprocess.

===== Some Incompatibilities

* When using the <tt>ruby</tt> command to start a Ruby subprocess, the
  Ruby interpreter that is currently running rake is used by default.
  This makes it easier to use rake in an environment with multiple
  ruby installation.  (Previously, the first ruby command found in the
  PATH was used).

  If you wish to chose a different Ruby interpreter, you can
  explicitly choose the interpreter via the <tt>sh</tt> command.

* The major rake classes (Task, FileTask, FileCreationTask, RakeApp)
  have been moved out of the toplevel scope and are now accessible as
  Rake::Task, Rake::FileTask, Rake::FileCreationTask and
  Rake::Application.  If your Rakefile
  directly references any one of these tasks, you may:

  1. Update your Rakefile to use the new classnames
  2. Use the --classic-namespace option on the rake command to get the
     old behavior,
  3. Add <code>require 'rake/classic_namespace'</code> to the
     Rakefile to get the old behavior.

  <tt>rake</tt> will print a rather annoying warning whenever a
  deprecated class name is referenced without enabling classic
  namespace.

===== Bug Fixes

* Several unit tests and functional tests were fixed to run better
  under windows.

* Directory tasks are now a specialized version of a File task.  A
  directory task will only be triggered if it doesn't exist.  It will
  not be triggered if it is out of date w.r.t. any of its
  prerequisites.

* Fixed a bug in the Rake::GemPackageTask class so that the gem now
  properly contains the platform name.

* Fixed a bug where a prerequisite on a <tt>file</tt> task would cause
  an exception if the prerequisite did not exist.

==== Thanks

As usual, it was input from users that drove a alot of these changes.
The following people either contributed patches, made suggestions or
made otherwise helpful comments.  Thanks to ...

* Greg Fast (better ruby_opt test options)
* Kelly Felkins (requested by better namespace support)
* Martin Fowler (suggested Task.investigation)
* Stuart Jansen (send initial patch for multiple prerequisites).
* Masao Mutch (better support for non-ruby Gem platforms)
* Philipp Neubeck (patch for file task exception fix)

-- Jim Weirich

=== 0.5.4

Time for some minor bug fixes and small enhancements

==== Changes

Here are the changes for version 0.5.4 ...

* Added double quotes to the test runner.  This allows the location of
  the tests (and runner) to be in a directory path that contains
  spaces (e.g. "C:/Program Files/ruby/bin").
* Added .svn to default ignore list.  Now subversion project metadata
  is automatically ignored by Rake's FileList.
* Updated FileList#include to support nested arrays and filelists.
  FileLists are flat lists of file names.  Using a FileList in an
  include will flatten out the nested file names.

== Thanks

As usual, it was input from users that drove a alot of these changes.
Thanks to ...

* Tilman Sauerbeck for the nested FileList suggestion.
* Josh Knowles for pointing out the spaces in directory name problem.

-- Jim Weirich

=== 0.5.3

Although it has only been two weeks since the last release, we have
enough updates to the Rake program to make it time for another
release.

==== Changes

Here are the changes for version 0.5.3 ...

* FileLists have been extensively changed so that they mimic the
  behavior of real arrays even more closely.  In particular,
  operations on FileLists that return a new collection (e.g. collect,
  reject) will now return a FileList rather than an array.  In
  addition, several places where FileLists were not properly expanded
  before use have been fixed.
* A method (+ext+) to simplify the handling of file extensions was
  added to String and to Array.
* The 'testrb' script in test/unit tends to silently swallow syntax
  errors in test suites.  Because of that, the default test loader is
  now a rake-provided script.  You can still use 'testrb' by setting
  the loader flag in the test task to :testrb.  (See the API documents
  for TestTask for all the loader flag values).
* FileUtil methods (e.g. cp, mv, install) are now declared to be
  private.  This will cut down on the interference with user defined
  methods of the same name.
* Fixed the verbose flag in the TestTask so that the test code is
  controlled by the flag.  Also shortened up some failure messages.
  (Thanks to Tobias Luetke for the suggestion).
* Rules will now properly detect a task that can generate a source
  file.  Previously rules would only consider source files that were
  already present.
* Added an +import+ command that allows Rake to dynamically import
  dependendencies into a running Rake session.  The +import+ command
  can run tasks to update the dependency file before loading them.
  Dependency files can be in rake or make format, allowing rake to
  work with tools designed to generate dependencies for make.

==== Thanks

As usual, it was input from users that drove a alot of these changes.
Thanks to ...

* Brian Gernhardt for the rules fix (especially for the patience to
  explain the problem to me until I got what he was talking about).
* Stefan Lang for pointing out problems in the dark corners of the
  FileList implementation.
* Alexey Verkhovsky pointing out the silently swallows syntax errors
  in tests.
* Tobias Luetke for beautifying the test task output.
* Sam Roberts for some of the ideas behind dependency loading.

-- Jim Weirich


=== 0.5.0

It has been a long time in coming, but we finally have a new version
of Rake available.

==== Changes

* Fixed documentation that was lacking the Rake module name (Tilman
  Sauerbeck).
* Added tar.gz and tar.bz2 support to package task (Tilman Sauerbeck).
* Recursive rules are now supported (Tilman Sauerbeck).
* Added warning option for the Test Task (requested by Eric Hodel).
* The jamis rdoc template is only used if it exists.
* Added fix for Ruby 1.8.2 test/unit and rails problem.
* Added contributed rake man file (Jani Monoses).
* Added Brian Candler's fix for problems in --trace and --dry-run
  mode.

==== Thanks

Lots of people provided input to this release.  Thanks to Tilman
Sauerbeck for numerous patches, documentation fixes and suggestions.
And for also pushing me to get this release out.  Also, thanks to
Brian Candler for the finding and fixing --trace/dry-run fix.  That
was an obscure bug.  Also to Eric Hodel for some good suggestions.

-- Jim Weirich

=== 0.4.15

==== Changes

Version 0.4.15 is a bug fix update for the Ruby 1.8.2 compatibility
changes.  This release includes:

* Fixed a bug that prevented the TESTOPTS flag from working with the
  revised for 1.8.2 test task.
* Updated the docs on --trace to indicate that it also enables a full
  backtrace on errors.
* Several fixes for new warnings generated.

==== Mini-Roadmap

I will continue to issue Rake updates in the 0.4.xx series as new
Ruby-1.8.2 issues become manifest.  Once the codebase stabilizes, I
will release a 0.5.0 version incorporating all the changes.  If you
are not using Ruby-1.8.2 and wish to avoid version churn, I recommend
staying with a release prior to Rake-0.4.14.

=== 0.4.14

Version 0.4.14 is a compatibility fix to allow Rake's test task to
work under Ruby 1.8.2.  A change in the Test::Unit autorun feature
prevented Rake from running any tests.  This release fixes the
problem.

Rake 0.4.14 is the recommended release for anyone using Ruby 1.8.2.

=== 0.4.13

* Fixed the dry-run flag so it is operating again.
* Multiple arguments to sh and ruby commands will not be interpreted
  by the shell (patch provided by Jonathan Paisley).

=== 0.4.12

* Added --silent (-s) to suppress the (in directory) rake message.

=== 0.4.11

* Changed the "don't know how to rake" message (finally)
* Changes references to a literal "Rakefile" to reference the global
  variable $rakefile (which contains the actual name of the rakefile).

=== 0.4.10

* Added block support to the "sh" command, allowing users to take
  special actions on the result of the system call.  E.g.

    sh "shell_command" do |ok, res|
      puts "Program returned #{res.exitstatus}" if ! ok
    end

=== 0.4.9

* Switched to Jamis Buck's RDoc template.
* Removed autorequire from Rake's gem spec.  This prevents the Rake
  libraries from loading while using rails.

=== 0.4.8

* Added support for .rb versions of Rakefile.
* Removed \\\n's from test task.
* Fixed Ruby 1.9 compatibility issue with FileList.

=== 0.4.7

* Fixed problem in FileList that caused Ruby 1.9 to go into infinite
  recursion.  Since to_a was removed from Object, it does not need to
  added back into the list of methods to rewrite in FileList.  (Thanks
  to Kent Sibilev for pointing this out).

=== 0.4.6
* Removed test version of ln in FileUtils that prevented safe_ln from
  using ln.

=== 0.4.5
* Upgraded comments in TestTask.
* FileList to_s and inspect now automatically resolve pending changes.
* FileList#exclude properly returns the FileList.

=== 0.4.4
* Fixed initialization problem with @comment.
* Now using multi -r technique in TestTask.  Switch Rakefile back to
  using the built-in test task macros because the rake runtime is no
  longer needed.
* Added 'TEST=filename' and 'TESTOPTS=options' to the Test Task
  macros.
* Allow a +test_files+ attribute in test tasks.  This allows more
  flexibility in specifying test files.

=== 0.4.3
* Fixed Comment leakage.

=== 0.4.2
* Added safe_ln that falls back to a copy if a file link is not supported.
* Package builder now uses safe\_ln.

=== 0.4.1
* Task comments are now additive, combined with "/".
* Works with (soon to be released) rubygems 0.6.2 (or 0.7.0)

=== 0.4.0
* FileList now uses deferred loading.  The file system is not searched
  until the first call that needs the file names.
* VAR=VALUE options are now accepted on the command line and are
  treated like environment variables.  The values may be tested in a
  Rakefile by referencing ENV['VAR'].
* File.mtime is now used (instead of File.new().mtime).

=== 0.3.2.x

* Removed some hidden dependencies on rubygems.  Tests now will test
  gems only if they are installed.
* Removed Sys from some example files.  I believe that is that last
  reference to Sys outside of the contrib area.
* Updated all copyright notices to include 2004.

=== 0.3.2

* GEM Installation now works with the application stub.

=== 0.3.1

* FileLists now automatically ignore CVS, .bak, !
* GEM Installation now works.

=== 0.3.0

Promoted 0.2.10.

=== 0.2.10
General

* Added title to Rake's rdocs
* Contrib packages are no longer included in the documentation.

RDoc Issues

* Removed default for the '--main' option
* Fixed rendering of the rdoc options
* Fixed clean/clobber confusion with rerdoc
* 'title' attribute added

Package Task Library Issues

* Version (or explicit :noversion) is required.
* +package_file+ attribute is now writable

FileList Issues

* Dropped bang version of exclude.  Now using ant-like include/exclude semantics.
* Enabled the "yield self" idiom in FileList#initialize.

=== 0.2.9

This version contains numerous changes as the RubyConf.new(2003)
presentation was being prepared.  The changes include:

* The monolithic rubyapp task library is in the process of being
  dropped in favor of lighter weight task libraries.

=== 0.2.7

* Added "desc" for task descriptions.
* -T will now display tasks with descriptions.
* -P will display tasks and prerequisites.
* Dropped the Sys module in favor of the 1.8.x FileUtils module.  Sys
  is still supported in the contrib area.

=== 0.2.6

* Moved to RubyForge

=== 0.2.5

* Switched to standard ruby app builder.
* Added no_match option to file matcher.

=== 0.2.4

* Fixed indir, which neglected to actually change directories.

=== 0.2.3

* Added rake module for a help target
* Added 'for\_files' to Sys
* Added a $rakefile constant
* Added test for selecting proper rule with multiple targets.
require 'json/common'

module JSON
  # This module holds all the modules/classes that implement JSON's
  # functionality as C extensions.
  module Ext
    require 'json/ext/parser'
    require 'json/ext/generator'
    $DEBUG and warn "Using Ext extension for JSON."
    JSON.parser = Parser
    JSON.generator = Generator
  end

  JSON_LOADED = true unless defined?(::JSON::JSON_LOADED)
end
#frozen_string_literal: false
unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
  require 'json'
end
defined?(::BigDecimal) or require 'bigdecimal'

class BigDecimal
  # Import a JSON Marshalled object.
  #
  # method used for JSON marshalling support.
  def self.json_create(object)
    BigDecimal._load object['b']
  end

  # Marshal the object to JSON.
  #
  # method used for JSON marshalling support.
  def as_json(*)
    {
      JSON.create_id => self.class.name,
      'b'            => _dump,
    }
  end

  # return the JSON value
  def to_json(*args)
    as_json.to_json(*args)
  end
end
#frozen_string_literal: false
unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
  require 'json'
end
require 'ostruct'

class OpenStruct

  # Deserializes JSON string by constructing new Struct object with values
  # <tt>t</tt> serialized by <tt>to_json</tt>.
  def self.json_create(object)
    new(object['t'] || object[:t])
  end

  # Returns a hash, that will be turned into a JSON object and represent this
  # object.
  def as_json(*)
    klass = self.class.name
    klass.to_s.empty? and raise JSON::JSONError, "Only named structs are supported!"
    {
      JSON.create_id => klass,
      't'            => table,
    }
  end

  # Stores class name (OpenStruct) with this struct's values <tt>t</tt> as a
  # JSON string.
  def to_json(*args)
    as_json.to_json(*args)
  end
end
#frozen_string_literal: false
# This file requires the implementations of ruby core's custom objects for
# serialisation/deserialisation.

require 'json/add/date'
require 'json/add/date_time'
require 'json/add/exception'
require 'json/add/range'
require 'json/add/regexp'
require 'json/add/struct'
require 'json/add/symbol'
require 'json/add/time'
unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
  require 'json'
end
defined?(::Set) or require 'set'

class Set
  # Import a JSON Marshalled object.
  #
  # method used for JSON marshalling support.
  def self.json_create(object)
    new object['a']
  end

  # Marshal the object to JSON.
  #
  # method used for JSON marshalling support.
  def as_json(*)
    {
      JSON.create_id => self.class.name,
      'a'            => to_a,
    }
  end

  # return the JSON value
  def to_json(*args)
    as_json.to_json(*args)
  end
end

#frozen_string_literal: false
unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
  require 'json'
end

class Regexp

  # Deserializes JSON string by constructing new Regexp object with source
  # <tt>s</tt> (Regexp or String) and options <tt>o</tt> serialized by
  # <tt>to_json</tt>
  def self.json_create(object)
    new(object['s'], object['o'])
  end

  # Returns a hash, that will be turned into a JSON object and represent this
  # object.
  def as_json(*)
    {
      JSON.create_id => self.class.name,
      'o'            => options,
      's'            => source,
    }
  end

  # Stores class name (Regexp) with options <tt>o</tt> and source <tt>s</tt>
  # (Regexp or String) as JSON string
  def to_json(*args)
    as_json.to_json(*args)
  end
end
#frozen_string_literal: false
unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
  require 'json'
end

class Time

  # Deserializes JSON string by converting time since epoch to Time
  def self.json_create(object)
    if usec = object.delete('u') # used to be tv_usec -> tv_nsec
      object['n'] = usec * 1000
    end
    if method_defined?(:tv_nsec)
      at(object['s'], Rational(object['n'], 1000))
    else
      at(object['s'], object['n'] / 1000)
    end
  end

  # Returns a hash, that will be turned into a JSON object and represent this
  # object.
  def as_json(*)
    nanoseconds = [ tv_usec * 1000 ]
    respond_to?(:tv_nsec) and nanoseconds << tv_nsec
    nanoseconds = nanoseconds.max
    {
      JSON.create_id => self.class.name,
      's'            => tv_sec,
      'n'            => nanoseconds,
    }
  end

  # Stores class name (Time) with number of seconds since epoch and number of
  # microseconds for Time as JSON string
  def to_json(*args)
    as_json.to_json(*args)
  end
end
#frozen_string_literal: false
unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
  require 'json'
end

class Rational
  # Deserializes JSON string by converting numerator value <tt>n</tt>,
  # denominator value <tt>d</tt>, to a Rational object.
  def self.json_create(object)
    Rational(object['n'], object['d'])
  end

  # Returns a hash, that will be turned into a JSON object and represent this
  # object.
  def as_json(*)
    {
      JSON.create_id => self.class.name,
      'n'            => numerator,
      'd'            => denominator,
    }
  end

  # Stores class name (Rational) along with numerator value <tt>n</tt> and denominator value <tt>d</tt> as JSON string
  def to_json(*args)
    as_json.to_json(*args)
  end
end
#frozen_string_literal: false
unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
  require 'json'
end

class Range

  # Deserializes JSON string by constructing new Range object with arguments
  # <tt>a</tt> serialized by <tt>to_json</tt>.
  def self.json_create(object)
    new(*object['a'])
  end

  # Returns a hash, that will be turned into a JSON object and represent this
  # object.
  def as_json(*)
    {
      JSON.create_id  => self.class.name,
      'a'             => [ first, last, exclude_end? ]
    }
  end

  # Stores class name (Range) with JSON array of arguments <tt>a</tt> which
  # include <tt>first</tt> (integer), <tt>last</tt> (integer), and
  # <tt>exclude_end?</tt> (boolean) as JSON string.
  def to_json(*args)
    as_json.to_json(*args)
  end
end
#frozen_string_literal: false
unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
  require 'json'
end

class Exception

  # Deserializes JSON string by constructing new Exception object with message
  # <tt>m</tt> and backtrace <tt>b</tt> serialized with <tt>to_json</tt>
  def self.json_create(object)
    result = new(object['m'])
    result.set_backtrace object['b']
    result
  end

  # Returns a hash, that will be turned into a JSON object and represent this
  # object.
  def as_json(*)
    {
      JSON.create_id => self.class.name,
      'm'            => message,
      'b'            => backtrace,
    }
  end

  # Stores class name (Exception) with message <tt>m</tt> and backtrace array
  # <tt>b</tt> as JSON string
  def to_json(*args)
    as_json.to_json(*args)
  end
end
#frozen_string_literal: false
unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
  require 'json'
end
require 'date'

class Date

  # Deserializes JSON string by converting Julian year <tt>y</tt>, month
  # <tt>m</tt>, day <tt>d</tt> and Day of Calendar Reform <tt>sg</tt> to Date.
  def self.json_create(object)
    civil(*object.values_at('y', 'm', 'd', 'sg'))
  end

  alias start sg unless method_defined?(:start)

  # Returns a hash, that will be turned into a JSON object and represent this
  # object.
  def as_json(*)
    {
      JSON.create_id => self.class.name,
      'y' => year,
      'm' => month,
      'd' => day,
      'sg' => start,
    }
  end

  # Stores class name (Date) with Julian year <tt>y</tt>, month <tt>m</tt>, day
  # <tt>d</tt> and Day of Calendar Reform <tt>sg</tt> as JSON string
  def to_json(*args)
    as_json.to_json(*args)
  end
end
#frozen_string_literal: false
unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
  require 'json'
end
require 'date'

class DateTime

  # Deserializes JSON string by converting year <tt>y</tt>, month <tt>m</tt>,
  # day <tt>d</tt>, hour <tt>H</tt>, minute <tt>M</tt>, second <tt>S</tt>,
  # offset <tt>of</tt> and Day of Calendar Reform <tt>sg</tt> to DateTime.
  def self.json_create(object)
    args = object.values_at('y', 'm', 'd', 'H', 'M', 'S')
    of_a, of_b = object['of'].split('/')
    if of_b and of_b != '0'
      args << Rational(of_a.to_i, of_b.to_i)
    else
      args << of_a
    end
    args << object['sg']
    civil(*args)
  end

  alias start sg unless method_defined?(:start)

  # Returns a hash, that will be turned into a JSON object and represent this
  # object.
  def as_json(*)
    {
      JSON.create_id => self.class.name,
      'y' => year,
      'm' => month,
      'd' => day,
      'H' => hour,
      'M' => min,
      'S' => sec,
      'of' => offset.to_s,
      'sg' => start,
    }
  end

  # Stores class name (DateTime) with Julian year <tt>y</tt>, month <tt>m</tt>,
  # day <tt>d</tt>, hour <tt>H</tt>, minute <tt>M</tt>, second <tt>S</tt>,
  # offset <tt>of</tt> and Day of Calendar Reform <tt>sg</tt> as JSON string
  def to_json(*args)
    as_json.to_json(*args)
  end
end


#frozen_string_literal: false
unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
  require 'json'
end

class Complex

  # Deserializes JSON string by converting Real value <tt>r</tt>, imaginary
  # value <tt>i</tt>, to a Complex object.
  def self.json_create(object)
    Complex(object['r'], object['i'])
  end

  # Returns a hash, that will be turned into a JSON object and represent this
  # object.
  def as_json(*)
    {
      JSON.create_id => self.class.name,
      'r'            => real,
      'i'            => imag,
    }
  end

  # Stores class name (Complex) along with real value <tt>r</tt> and imaginary value <tt>i</tt> as JSON string
  def to_json(*args)
    as_json.to_json(*args)
  end
end
#frozen_string_literal: false
unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
  require 'json'
end

class Symbol
  # Returns a hash, that will be turned into a JSON object and represent this
  # object.
  def as_json(*)
    {
      JSON.create_id => self.class.name,
      's'            => to_s,
    }
  end

  # Stores class name (Symbol) with String representation of Symbol as a JSON string.
  def to_json(*a)
    as_json.to_json(*a)
  end

  # Deserializes JSON string by converting the <tt>string</tt> value stored in the object to a Symbol
  def self.json_create(o)
    o['s'].to_sym
  end
end
#frozen_string_literal: false
unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
  require 'json'
end

class Struct

  # Deserializes JSON string by constructing new Struct object with values
  # <tt>v</tt> serialized by <tt>to_json</tt>.
  def self.json_create(object)
    new(*object['v'])
  end

  # Returns a hash, that will be turned into a JSON object and represent this
  # object.
  def as_json(*)
    klass = self.class.name
    klass.to_s.empty? and raise JSON::JSONError, "Only named structs are supported!"
    {
      JSON.create_id => klass,
      'v'            => values,
    }
  end

  # Stores class name (Struct) with Struct values <tt>v</tt> as a JSON string.
  # Only named structs are supported.
  def to_json(*args)
    as_json.to_json(*args)
  end
end
#frozen_string_literal: false
require 'json/version'
require 'json/generic_object'

module JSON
  class << self
    # :call-seq:
    #   JSON[object] -> new_array or new_string
    #
    # If +object+ is a \String,
    # calls JSON.parse with +object+ and +opts+ (see method #parse):
    #   json = '[0, 1, null]'
    #   JSON[json]# => [0, 1, nil]
    #
    # Otherwise, calls JSON.generate with +object+ and +opts+ (see method #generate):
    #   ruby = [0, 1, nil]
    #   JSON[ruby] # => '[0,1,null]'
    def [](object, opts = {})
      if object.respond_to? :to_str
        JSON.parse(object.to_str, opts)
      else
        JSON.generate(object, opts)
      end
    end

    # Returns the JSON parser class that is used by JSON. This is either
    # JSON::Ext::Parser or JSON::Pure::Parser:
    #   JSON.parser # => JSON::Ext::Parser
    attr_reader :parser

    # Set the JSON parser class _parser_ to be used by JSON.
    def parser=(parser) # :nodoc:
      @parser = parser
      remove_const :Parser if const_defined?(:Parser, false)
      const_set :Parser, parser
    end

    # Return the constant located at _path_. The format of _path_ has to be
    # either ::A::B::C or A::B::C. In any case, A has to be located at the top
    # level (absolute namespace path?). If there doesn't exist a constant at
    # the given path, an ArgumentError is raised.
    def deep_const_get(path) # :nodoc:
      path.to_s.split(/::/).inject(Object) do |p, c|
        case
        when c.empty?                  then p
        when p.const_defined?(c, true) then p.const_get(c)
        else
          begin
            p.const_missing(c)
          rescue NameError => e
            raise ArgumentError, "can't get const #{path}: #{e}"
          end
        end
      end
    end

    # Set the module _generator_ to be used by JSON.
    def generator=(generator) # :nodoc:
      old, $VERBOSE = $VERBOSE, nil
      @generator = generator
      generator_methods = generator::GeneratorMethods
      for const in generator_methods.constants
        klass = deep_const_get(const)
        modul = generator_methods.const_get(const)
        klass.class_eval do
          instance_methods(false).each do |m|
            m.to_s == 'to_json' and remove_method m
          end
          include modul
        end
      end
      self.state = generator::State
      const_set :State, self.state
      const_set :SAFE_STATE_PROTOTYPE, State.new # for JRuby
      const_set :FAST_STATE_PROTOTYPE, create_fast_state
      const_set :PRETTY_STATE_PROTOTYPE, create_pretty_state
    ensure
      $VERBOSE = old
    end

    def create_fast_state
      State.new(
        :indent         => '',
        :space          => '',
        :object_nl      => "",
        :array_nl       => "",
        :max_nesting    => false
      )
    end

    def create_pretty_state
      State.new(
        :indent         => '  ',
        :space          => ' ',
        :object_nl      => "\n",
        :array_nl       => "\n"
      )
    end

    # Returns the JSON generator module that is used by JSON. This is
    # either JSON::Ext::Generator or JSON::Pure::Generator:
    #   JSON.generator # => JSON::Ext::Generator
    attr_reader :generator

    # Sets or Returns the JSON generator state class that is used by JSON. This is
    # either JSON::Ext::Generator::State or JSON::Pure::Generator::State:
    #   JSON.state # => JSON::Ext::Generator::State
    attr_accessor :state
  end

  DEFAULT_CREATE_ID = 'json_class'.freeze
  private_constant :DEFAULT_CREATE_ID

  CREATE_ID_TLS_KEY = "JSON.create_id".freeze
  private_constant :CREATE_ID_TLS_KEY

  # Sets create identifier, which is used to decide if the _json_create_
  # hook of a class should be called; initial value is +json_class+:
  #   JSON.create_id # => 'json_class'
  def self.create_id=(new_value)
    Thread.current[CREATE_ID_TLS_KEY] = new_value.dup.freeze
  end

  # Returns the current create identifier.
  # See also JSON.create_id=.
  def self.create_id
    Thread.current[CREATE_ID_TLS_KEY] || DEFAULT_CREATE_ID
  end

  NaN           = 0.0/0

  Infinity      = 1.0/0

  MinusInfinity = -Infinity

  # The base exception for JSON errors.
  class JSONError < StandardError
    def self.wrap(exception)
      obj = new("Wrapped(#{exception.class}): #{exception.message.inspect}")
      obj.set_backtrace exception.backtrace
      obj
    end
  end

  # This exception is raised if a parser error occurs.
  class ParserError < JSONError; end

  # This exception is raised if the nesting of parsed data structures is too
  # deep.
  class NestingError < ParserError; end

  # :stopdoc:
  class CircularDatastructure < NestingError; end
  # :startdoc:

  # This exception is raised if a generator or unparser error occurs.
  class GeneratorError < JSONError; end
  # For backwards compatibility
  UnparserError = GeneratorError # :nodoc:

  # This exception is raised if the required unicode support is missing on the
  # system. Usually this means that the iconv library is not installed.
  class MissingUnicodeSupport < JSONError; end

  module_function

  # :call-seq:
  #   JSON.parse(source, opts) -> object
  #
  # Returns the Ruby objects created by parsing the given +source+.
  #
  # Argument +source+ contains the \String to be parsed.
  #
  # Argument +opts+, if given, contains a \Hash of options for the parsing.
  # See {Parsing Options}[#module-JSON-label-Parsing+Options].
  #
  # ---
  #
  # When +source+ is a \JSON array, returns a Ruby \Array:
  #   source = '["foo", 1.0, true, false, null]'
  #   ruby = JSON.parse(source)
  #   ruby # => ["foo", 1.0, true, false, nil]
  #   ruby.class # => Array
  #
  # When +source+ is a \JSON object, returns a Ruby \Hash:
  #   source = '{"a": "foo", "b": 1.0, "c": true, "d": false, "e": null}'
  #   ruby = JSON.parse(source)
  #   ruby # => {"a"=>"foo", "b"=>1.0, "c"=>true, "d"=>false, "e"=>nil}
  #   ruby.class # => Hash
  #
  # For examples of parsing for all \JSON data types, see
  # {Parsing \JSON}[#module-JSON-label-Parsing+JSON].
  #
  # Parses nested JSON objects:
  #   source = <<-EOT
  #   {
  #   "name": "Dave",
  #     "age" :40,
  #     "hats": [
  #       "Cattleman's",
  #       "Panama",
  #       "Tophat"
  #     ]
  #   }
  #   EOT
  #   ruby = JSON.parse(source)
  #   ruby # => {"name"=>"Dave", "age"=>40, "hats"=>["Cattleman's", "Panama", "Tophat"]}
  #
  # ---
  #
  # Raises an exception if +source+ is not valid JSON:
  #   # Raises JSON::ParserError (783: unexpected token at ''):
  #   JSON.parse('')
  #
  def parse(source, opts = {})
    Parser.new(source, **(opts||{})).parse
  end

  # :call-seq:
  #   JSON.parse!(source, opts) -> object
  #
  # Calls
  #   parse(source, opts)
  # with +source+ and possibly modified +opts+.
  #
  # Differences from JSON.parse:
  # - Option +max_nesting+, if not provided, defaults to +false+,
  #   which disables checking for nesting depth.
  # - Option +allow_nan+, if not provided, defaults to +true+.
  def parse!(source, opts = {})
    opts = {
      :max_nesting  => false,
      :allow_nan    => true
    }.merge(opts)
    Parser.new(source, **(opts||{})).parse
  end

  # :call-seq:
  #   JSON.load_file(path, opts={}) -> object
  #
  # Calls:
  #   parse(File.read(path), opts)
  #
  # See method #parse.
  def load_file(filespec, opts = {})
    parse(File.read(filespec), opts)
  end

  # :call-seq:
  #   JSON.load_file!(path, opts = {})
  #
  # Calls:
  #   JSON.parse!(File.read(path, opts))
  #
  # See method #parse!
  def load_file!(filespec, opts = {})
    parse!(File.read(filespec), opts)
  end

  # :call-seq:
  #   JSON.generate(obj, opts = nil) -> new_string
  #
  # Returns a \String containing the generated \JSON data.
  #
  # See also JSON.fast_generate, JSON.pretty_generate.
  #
  # Argument +obj+ is the Ruby object to be converted to \JSON.
  #
  # Argument +opts+, if given, contains a \Hash of options for the generation.
  # See {Generating Options}[#module-JSON-label-Generating+Options].
  #
  # ---
  #
  # When +obj+ is an \Array, returns a \String containing a \JSON array:
  #   obj = ["foo", 1.0, true, false, nil]
  #   json = JSON.generate(obj)
  #   json # => '["foo",1.0,true,false,null]'
  #
  # When +obj+ is a \Hash, returns a \String containing a \JSON object:
  #   obj = {foo: 0, bar: 's', baz: :bat}
  #   json = JSON.generate(obj)
  #   json # => '{"foo":0,"bar":"s","baz":"bat"}'
  #
  # For examples of generating from other Ruby objects, see
  # {Generating \JSON from Other Objects}[#module-JSON-label-Generating+JSON+from+Other+Objects].
  #
  # ---
  #
  # Raises an exception if any formatting option is not a \String.
  #
  # Raises an exception if +obj+ contains circular references:
  #   a = []; b = []; a.push(b); b.push(a)
  #   # Raises JSON::NestingError (nesting of 100 is too deep):
  #   JSON.generate(a)
  #
  def generate(obj, opts = nil)
    if State === opts
      state, opts = opts, nil
    else
      state = State.new
    end
    if opts
      if opts.respond_to? :to_hash
        opts = opts.to_hash
      elsif opts.respond_to? :to_h
        opts = opts.to_h
      else
        raise TypeError, "can't convert #{opts.class} into Hash"
      end
      state = state.configure(opts)
    end
    state.generate(obj)
  end

  # :stopdoc:
  # I want to deprecate these later, so I'll first be silent about them, and
  # later delete them.
  alias unparse generate
  module_function :unparse
  # :startdoc:

  # :call-seq:
  #   JSON.fast_generate(obj, opts) -> new_string
  #
  # Arguments +obj+ and +opts+ here are the same as
  # arguments +obj+ and +opts+ in JSON.generate.
  #
  # By default, generates \JSON data without checking
  # for circular references in +obj+ (option +max_nesting+ set to +false+, disabled).
  #
  # Raises an exception if +obj+ contains circular references:
  #   a = []; b = []; a.push(b); b.push(a)
  #   # Raises SystemStackError (stack level too deep):
  #   JSON.fast_generate(a)
  def fast_generate(obj, opts = nil)
    if State === opts
      state, opts = opts, nil
    else
      state = JSON.create_fast_state
    end
    if opts
      if opts.respond_to? :to_hash
        opts = opts.to_hash
      elsif opts.respond_to? :to_h
        opts = opts.to_h
      else
        raise TypeError, "can't convert #{opts.class} into Hash"
      end
      state.configure(opts)
    end
    state.generate(obj)
  end

  # :stopdoc:
  # I want to deprecate these later, so I'll first be silent about them, and later delete them.
  alias fast_unparse fast_generate
  module_function :fast_unparse
  # :startdoc:

  # :call-seq:
  #   JSON.pretty_generate(obj, opts = nil) -> new_string
  #
  # Arguments +obj+ and +opts+ here are the same as
  # arguments +obj+ and +opts+ in JSON.generate.
  #
  # Default options are:
  #   {
  #     indent: '  ',   # Two spaces
  #     space: ' ',     # One space
  #     array_nl: "\n", # Newline
  #     object_nl: "\n" # Newline
  #   }
  #
  # Example:
  #   obj = {foo: [:bar, :baz], bat: {bam: 0, bad: 1}}
  #   json = JSON.pretty_generate(obj)
  #   puts json
  # Output:
  #   {
  #     "foo": [
  #       "bar",
  #       "baz"
  #     ],
  #     "bat": {
  #       "bam": 0,
  #       "bad": 1
  #     }
  #   }
  #
  def pretty_generate(obj, opts = nil)
    if State === opts
      state, opts = opts, nil
    else
      state = JSON.create_pretty_state
    end
    if opts
      if opts.respond_to? :to_hash
        opts = opts.to_hash
      elsif opts.respond_to? :to_h
        opts = opts.to_h
      else
        raise TypeError, "can't convert #{opts.class} into Hash"
      end
      state.configure(opts)
    end
    state.generate(obj)
  end

  # :stopdoc:
  # I want to deprecate these later, so I'll first be silent about them, and later delete them.
  alias pretty_unparse pretty_generate
  module_function :pretty_unparse
  # :startdoc:

  class << self
    # Sets or returns default options for the JSON.load method.
    # Initially:
    #   opts = JSON.load_default_options
    #   opts # => {:max_nesting=>false, :allow_nan=>true, :allow_blank=>true, :create_additions=>true}
    attr_accessor :load_default_options
  end
  self.load_default_options = {
    :max_nesting      => false,
    :allow_nan        => true,
    :allow_blank       => true,
    :create_additions => true,
  }

  # :call-seq:
  #   JSON.load(source, proc = nil, options = {}) -> object
  #
  # Returns the Ruby objects created by parsing the given +source+.
  #
  # - Argument +source+ must be, or be convertible to, a \String:
  #   - If +source+ responds to instance method +to_str+,
  #     <tt>source.to_str</tt> becomes the source.
  #   - If +source+ responds to instance method +to_io+,
  #     <tt>source.to_io.read</tt> becomes the source.
  #   - If +source+ responds to instance method +read+,
  #     <tt>source.read</tt> becomes the source.
  #   - If both of the following are true, source becomes the \String <tt>'null'</tt>:
  #     - Option +allow_blank+ specifies a truthy value.
  #     - The source, as defined above, is +nil+ or the empty \String <tt>''</tt>.
  #   - Otherwise, +source+ remains the source.
  # - Argument +proc+, if given, must be a \Proc that accepts one argument.
  #   It will be called recursively with each result (depth-first order).
  #   See details below.
  #   BEWARE: This method is meant to serialise data from trusted user input,
  #   like from your own database server or clients under your control, it could
  #   be dangerous to allow untrusted users to pass JSON sources into it.
  # - Argument +opts+, if given, contains a \Hash of options for the parsing.
  #   See {Parsing Options}[#module-JSON-label-Parsing+Options].
  #   The default options can be changed via method JSON.load_default_options=.
  #
  # ---
  #
  # When no +proc+ is given, modifies +source+ as above and returns the result of
  # <tt>parse(source, opts)</tt>;  see #parse.
  #
  # Source for following examples:
  #   source = <<-EOT
  #   {
  #   "name": "Dave",
  #     "age" :40,
  #     "hats": [
  #       "Cattleman's",
  #       "Panama",
  #       "Tophat"
  #     ]
  #   }
  #   EOT
  #
  # Load a \String:
  #   ruby = JSON.load(source)
  #   ruby # => {"name"=>"Dave", "age"=>40, "hats"=>["Cattleman's", "Panama", "Tophat"]}
  #
  # Load an \IO object:
  #   require 'stringio'
  #   object = JSON.load(StringIO.new(source))
  #   object # => {"name"=>"Dave", "age"=>40, "hats"=>["Cattleman's", "Panama", "Tophat"]}
  #
  # Load a \File object:
  #   path = 't.json'
  #   File.write(path, source)
  #   File.open(path) do |file|
  #     JSON.load(file)
  #   end # => {"name"=>"Dave", "age"=>40, "hats"=>["Cattleman's", "Panama", "Tophat"]}
  #
  # ---
  #
  # When +proc+ is given:
  # - Modifies +source+ as above.
  # - Gets the +result+ from calling <tt>parse(source, opts)</tt>.
  # - Recursively calls <tt>proc(result)</tt>.
  # - Returns the final result.
  #
  # Example:
  #   require 'json'
  #
  #   # Some classes for the example.
  #   class Base
  #     def initialize(attributes)
  #       @attributes = attributes
  #     end
  #   end
  #   class User    < Base; end
  #   class Account < Base; end
  #   class Admin   < Base; end
  #   # The JSON source.
  #   json = <<-EOF
  #   {
  #     "users": [
  #         {"type": "User", "username": "jane", "email": "jane@example.com"},
  #         {"type": "User", "username": "john", "email": "john@example.com"}
  #     ],
  #     "accounts": [
  #         {"account": {"type": "Account", "paid": true, "account_id": "1234"}},
  #         {"account": {"type": "Account", "paid": false, "account_id": "1235"}}
  #     ],
  #     "admins": {"type": "Admin", "password": "0wn3d"}
  #   }
  #   EOF
  #   # Deserializer method.
  #   def deserialize_obj(obj, safe_types = %w(User Account Admin))
  #     type = obj.is_a?(Hash) && obj["type"]
  #     safe_types.include?(type) ? Object.const_get(type).new(obj) : obj
  #   end
  #   # Call to JSON.load
  #   ruby = JSON.load(json, proc {|obj|
  #     case obj
  #     when Hash
  #       obj.each {|k, v| obj[k] = deserialize_obj v }
  #     when Array
  #       obj.map! {|v| deserialize_obj v }
  #     end
  #   })
  #   pp ruby
  # Output:
  #   {"users"=>
  #      [#<User:0x00000000064c4c98
  #        @attributes=
  #          {"type"=>"User", "username"=>"jane", "email"=>"jane@example.com"}>,
  #        #<User:0x00000000064c4bd0
  #        @attributes=
  #          {"type"=>"User", "username"=>"john", "email"=>"john@example.com"}>],
  #    "accounts"=>
  #      [{"account"=>
  #          #<Account:0x00000000064c4928
  #          @attributes={"type"=>"Account", "paid"=>true, "account_id"=>"1234"}>},
  #       {"account"=>
  #          #<Account:0x00000000064c4680
  #          @attributes={"type"=>"Account", "paid"=>false, "account_id"=>"1235"}>}],
  #    "admins"=>
  #      #<Admin:0x00000000064c41f8
  #      @attributes={"type"=>"Admin", "password"=>"0wn3d"}>}
  #
  def load(source, proc = nil, options = {})
    opts = load_default_options.merge options
    if source.respond_to? :to_str
      source = source.to_str
    elsif source.respond_to? :to_io
      source = source.to_io.read
    elsif source.respond_to?(:read)
      source = source.read
    end
    if opts[:allow_blank] && (source.nil? || source.empty?)
      source = 'null'
    end
    result = parse(source, opts)
    recurse_proc(result, &proc) if proc
    result
  end

  # Recursively calls passed _Proc_ if the parsed data structure is an _Array_ or _Hash_
  def recurse_proc(result, &proc) # :nodoc:
    case result
    when Array
      result.each { |x| recurse_proc x, &proc }
      proc.call result
    when Hash
      result.each { |x, y| recurse_proc x, &proc; recurse_proc y, &proc }
      proc.call result
    else
      proc.call result
    end
  end

  alias restore load
  module_function :restore

  class << self
    # Sets or returns the default options for the JSON.dump method.
    # Initially:
    #   opts = JSON.dump_default_options
    #   opts # => {:max_nesting=>false, :allow_nan=>true, :escape_slash=>false}
    attr_accessor :dump_default_options
  end
  self.dump_default_options = {
    :max_nesting => false,
    :allow_nan   => true,
    :escape_slash => false,
  }

  # :call-seq:
  #   JSON.dump(obj, io = nil, limit = nil)
  #
  # Dumps +obj+ as a \JSON string, i.e. calls generate on the object and returns the result.
  #
  # The default options can be changed via method JSON.dump_default_options.
  #
  # - Argument +io+, if given, should respond to method +write+;
  #   the \JSON \String is written to +io+, and +io+ is returned.
  #   If +io+ is not given, the \JSON \String is returned.
  # - Argument +limit+, if given, is passed to JSON.generate as option +max_nesting+.
  #
  # ---
  #
  # When argument +io+ is not given, returns the \JSON \String generated from +obj+:
  #   obj = {foo: [0, 1], bar: {baz: 2, bat: 3}, bam: :bad}
  #   json = JSON.dump(obj)
  #   json # => "{\"foo\":[0,1],\"bar\":{\"baz\":2,\"bat\":3},\"bam\":\"bad\"}"
  #
  # When argument +io+ is given, writes the \JSON \String to +io+ and returns +io+:
  #   path = 't.json'
  #   File.open(path, 'w') do |file|
  #     JSON.dump(obj, file)
  #   end # => #<File:t.json (closed)>
  #   puts File.read(path)
  # Output:
  #   {"foo":[0,1],"bar":{"baz":2,"bat":3},"bam":"bad"}
  def dump(obj, anIO = nil, limit = nil)
    if anIO and limit.nil?
      anIO = anIO.to_io if anIO.respond_to?(:to_io)
      unless anIO.respond_to?(:write)
        limit = anIO
        anIO = nil
      end
    end
    opts = JSON.dump_default_options
    opts = opts.merge(:max_nesting => limit) if limit
    result = generate(obj, opts)
    if anIO
      anIO.write result
      anIO
    else
      result
    end
  rescue JSON::NestingError
    raise ArgumentError, "exceed depth limit"
  end

  # Encodes string using String.encode.
  def self.iconv(to, from, string)
    string.encode(to, from)
  end
end

module ::Kernel
  private

  # Outputs _objs_ to STDOUT as JSON strings in the shortest form, that is in
  # one line.
  def j(*objs)
    objs.each do |obj|
      puts JSON::generate(obj, :allow_nan => true, :max_nesting => false)
    end
    nil
  end

  # Outputs _objs_ to STDOUT as JSON strings in a pretty format, with
  # indentation and over many lines.
  def jj(*objs)
    objs.each do |obj|
      puts JSON::pretty_generate(obj, :allow_nan => true, :max_nesting => false)
    end
    nil
  end

  # If _object_ is string-like, parse the string and return the parsed result as
  # a Ruby data structure. Otherwise, generate a JSON text from the Ruby data
  # structure object and return it.
  #
  # The _opts_ argument is passed through to generate/parse respectively. See
  # generate and parse for their documentation.
  def JSON(object, *args)
    if object.respond_to? :to_str
      JSON.parse(object.to_str, args.first)
    else
      JSON.generate(object, args.first)
    end
  end
end

# Extends any Class to include _json_creatable?_ method.
class ::Class
  # Returns true if this class can be used to create an instance
  # from a serialised JSON string. The class has to implement a class
  # method _json_create_ that expects a hash as first parameter. The hash
  # should include the required data.
  def json_creatable?
    respond_to?(:json_create)
  end
end
#frozen_string_literal: false
require 'ostruct'

module JSON
  class GenericObject < OpenStruct
    class << self
      alias [] new

      def json_creatable?
        @json_creatable
      end

      attr_writer :json_creatable

      def json_create(data)
        data = data.dup
        data.delete JSON.create_id
        self[data]
      end

      def from_hash(object)
        case
        when object.respond_to?(:to_hash)
          result = new
          object.to_hash.each do |key, value|
            result[key] = from_hash(value)
          end
          result
        when object.respond_to?(:to_ary)
          object.to_ary.map { |a| from_hash(a) }
        else
          object
        end
      end

      def load(source, proc = nil, opts = {})
        result = ::JSON.load(source, proc, opts.merge(:object_class => self))
        result.nil? ? new : result
      end

      def dump(obj, *args)
        ::JSON.dump(obj, *args)
      end
    end
    self.json_creatable = false

    def to_hash
      table
    end

    def [](name)
      __send__(name)
    end unless method_defined?(:[])

    def []=(name, value)
      __send__("#{name}=", value)
    end unless method_defined?(:[]=)

    def |(other)
      self.class[other.to_hash.merge(to_hash)]
    end

    def as_json(*)
      { JSON.create_id => self.class.name }.merge to_hash
    end

    def to_json(*a)
      as_json.to_json(*a)
    end
  end
end
# frozen_string_literal: false
module JSON
  # JSON version
  VERSION         = '2.5.1'
  VERSION_ARRAY   = VERSION.split(/\./).map { |x| x.to_i } # :nodoc:
  VERSION_MAJOR   = VERSION_ARRAY[0] # :nodoc:
  VERSION_MINOR   = VERSION_ARRAY[1] # :nodoc:
  VERSION_BUILD   = VERSION_ARRAY[2] # :nodoc:
end
#frozen_string_literal: false
require 'json/common'

##
# = JavaScript \Object Notation (\JSON)
#
# \JSON is a lightweight data-interchange format.
#
# A \JSON value is one of the following:
# - Double-quoted text:  <tt>"foo"</tt>.
# - Number:  +1+, +1.0+, +2.0e2+.
# - Boolean:  +true+, +false+.
# - Null: +null+.
# - \Array: an ordered list of values, enclosed by square brackets:
#     ["foo", 1, 1.0, 2.0e2, true, false, null]
#
# - \Object: a collection of name/value pairs, enclosed by curly braces;
#   each name is double-quoted text;
#   the values may be any \JSON values:
#     {"a": "foo", "b": 1, "c": 1.0, "d": 2.0e2, "e": true, "f": false, "g": null}
#
# A \JSON array or object may contain nested arrays, objects, and scalars
# to any depth:
#   {"foo": {"bar": 1, "baz": 2}, "bat": [0, 1, 2]}
#   [{"foo": 0, "bar": 1}, ["baz", 2]]
#
# == Using \Module \JSON
#
# To make module \JSON available in your code, begin with:
#   require 'json'
#
# All examples here assume that this has been done.
#
# === Parsing \JSON
#
# You can parse a \String containing \JSON data using
# either of two methods:
# - <tt>JSON.parse(source, opts)</tt>
# - <tt>JSON.parse!(source, opts)</tt>
#
# where
# - +source+ is a Ruby object.
# - +opts+ is a \Hash object containing options
#   that control both input allowed and output formatting.
#
# The difference between the two methods
# is that JSON.parse! omits some checks
# and may not be safe for some +source+ data;
# use it only for data from trusted sources.
# Use the safer method JSON.parse for less trusted sources.
#
# ==== Parsing \JSON Arrays
#
# When +source+ is a \JSON array, JSON.parse by default returns a Ruby \Array:
#   json = '["foo", 1, 1.0, 2.0e2, true, false, null]'
#   ruby = JSON.parse(json)
#   ruby # => ["foo", 1, 1.0, 200.0, true, false, nil]
#   ruby.class # => Array
#
# The \JSON array may contain nested arrays, objects, and scalars
# to any depth:
#   json = '[{"foo": 0, "bar": 1}, ["baz", 2]]'
#   JSON.parse(json) # => [{"foo"=>0, "bar"=>1}, ["baz", 2]]
#
# ==== Parsing \JSON \Objects
#
# When the source is a \JSON object, JSON.parse by default returns a Ruby \Hash:
#   json = '{"a": "foo", "b": 1, "c": 1.0, "d": 2.0e2, "e": true, "f": false, "g": null}'
#   ruby = JSON.parse(json)
#   ruby # => {"a"=>"foo", "b"=>1, "c"=>1.0, "d"=>200.0, "e"=>true, "f"=>false, "g"=>nil}
#   ruby.class # => Hash
#
# The \JSON object may contain nested arrays, objects, and scalars
# to any depth:
#   json = '{"foo": {"bar": 1, "baz": 2}, "bat": [0, 1, 2]}'
#   JSON.parse(json) # => {"foo"=>{"bar"=>1, "baz"=>2}, "bat"=>[0, 1, 2]}
#
# ==== Parsing \JSON Scalars
#
# When the source is a \JSON scalar (not an array or object),
# JSON.parse returns a Ruby scalar.
#
# \String:
#   ruby = JSON.parse('"foo"')
#   ruby # => 'foo'
#   ruby.class # => String
# \Integer:
#   ruby = JSON.parse('1')
#   ruby # => 1
#   ruby.class # => Integer
# \Float:
#   ruby = JSON.parse('1.0')
#   ruby # => 1.0
#   ruby.class # => Float
#   ruby = JSON.parse('2.0e2')
#   ruby # => 200
#   ruby.class # => Float
# Boolean:
#   ruby = JSON.parse('true')
#   ruby # => true
#   ruby.class # => TrueClass
#   ruby = JSON.parse('false')
#   ruby # => false
#   ruby.class # => FalseClass
# Null:
#   ruby = JSON.parse('null')
#   ruby # => nil
#   ruby.class # => NilClass
#
# ==== Parsing Options
#
# ====== Input Options
#
# Option +max_nesting+ (\Integer) specifies the maximum nesting depth allowed;
# defaults to +100+; specify +false+ to disable depth checking.
#
# With the default, +false+:
#   source = '[0, [1, [2, [3]]]]'
#   ruby = JSON.parse(source)
#   ruby # => [0, [1, [2, [3]]]]
# Too deep:
#   # Raises JSON::NestingError (nesting of 2 is too deep):
#   JSON.parse(source, {max_nesting: 1})
# Bad value:
#   # Raises TypeError (wrong argument type Symbol (expected Fixnum)):
#   JSON.parse(source, {max_nesting: :foo})
#
# ---
#
# Option +allow_nan+ (boolean) specifies whether to allow
# NaN, Infinity, and MinusInfinity in +source+;
# defaults to +false+.
#
# With the default, +false+:
#   # Raises JSON::ParserError (225: unexpected token at '[NaN]'):
#   JSON.parse('[NaN]')
#   # Raises JSON::ParserError (232: unexpected token at '[Infinity]'):
#   JSON.parse('[Infinity]')
#   # Raises JSON::ParserError (248: unexpected token at '[-Infinity]'):
#   JSON.parse('[-Infinity]')
# Allow:
#   source = '[NaN, Infinity, -Infinity]'
#   ruby = JSON.parse(source, {allow_nan: true})
#   ruby # => [NaN, Infinity, -Infinity]
#
# ====== Output Options
#
# Option +symbolize_names+ (boolean) specifies whether returned \Hash keys
# should be Symbols;
# defaults to +false+ (use Strings).
#
# With the default, +false+:
#   source = '{"a": "foo", "b": 1.0, "c": true, "d": false, "e": null}'
#   ruby = JSON.parse(source)
#   ruby # => {"a"=>"foo", "b"=>1.0, "c"=>true, "d"=>false, "e"=>nil}
# Use Symbols:
#   ruby = JSON.parse(source, {symbolize_names: true})
#   ruby # => {:a=>"foo", :b=>1.0, :c=>true, :d=>false, :e=>nil}
#
# ---
#
# Option +object_class+ (\Class) specifies the Ruby class to be used
# for each \JSON object;
# defaults to \Hash.
#
# With the default, \Hash:
#   source = '{"a": "foo", "b": 1.0, "c": true, "d": false, "e": null}'
#   ruby = JSON.parse(source)
#   ruby.class # => Hash
# Use class \OpenStruct:
#   ruby = JSON.parse(source, {object_class: OpenStruct})
#   ruby # => #<OpenStruct a="foo", b=1.0, c=true, d=false, e=nil>
#
# ---
#
# Option +array_class+ (\Class) specifies the Ruby class to be used
# for each \JSON array;
# defaults to \Array.
#
# With the default, \Array:
#   source = '["foo", 1.0, true, false, null]'
#   ruby = JSON.parse(source)
#   ruby.class # => Array
# Use class \Set:
#   ruby = JSON.parse(source, {array_class: Set})
#   ruby # => #<Set: {"foo", 1.0, true, false, nil}>
#
# ---
#
# Option +create_additions+ (boolean) specifies whether to use \JSON additions in parsing.
# See {\JSON Additions}[#module-JSON-label-JSON+Additions].
#
# === Generating \JSON
#
# To generate a Ruby \String containing \JSON data,
# use method <tt>JSON.generate(source, opts)</tt>, where
# - +source+ is a Ruby object.
# - +opts+ is a \Hash object containing options
#   that control both input allowed and output formatting.
#
# ==== Generating \JSON from Arrays
#
# When the source is a Ruby \Array, JSON.generate returns
# a \String containing a \JSON array:
#   ruby = [0, 's', :foo]
#   json = JSON.generate(ruby)
#   json # => '[0,"s","foo"]'
#
# The Ruby \Array array may contain nested arrays, hashes, and scalars
# to any depth:
#   ruby = [0, [1, 2], {foo: 3, bar: 4}]
#   json = JSON.generate(ruby)
#   json # => '[0,[1,2],{"foo":3,"bar":4}]'
#
# ==== Generating \JSON from Hashes
#
# When the source is a Ruby \Hash, JSON.generate returns
# a \String containing a \JSON object:
#   ruby = {foo: 0, bar: 's', baz: :bat}
#   json = JSON.generate(ruby)
#   json # => '{"foo":0,"bar":"s","baz":"bat"}'
#
# The Ruby \Hash array may contain nested arrays, hashes, and scalars
# to any depth:
#   ruby = {foo: [0, 1], bar: {baz: 2, bat: 3}, bam: :bad}
#   json = JSON.generate(ruby)
#   json # => '{"foo":[0,1],"bar":{"baz":2,"bat":3},"bam":"bad"}'
#
# ==== Generating \JSON from Other Objects
#
# When the source is neither an \Array nor a \Hash,
# the generated \JSON data depends on the class of the source.
#
# When the source is a Ruby \Integer or \Float, JSON.generate returns
# a \String containing a \JSON number:
#   JSON.generate(42) # => '42'
#   JSON.generate(0.42) # => '0.42'
#
# When the source is a Ruby \String, JSON.generate returns
# a \String containing a \JSON string (with double-quotes):
#   JSON.generate('A string') # => '"A string"'
#
# When the source is +true+, +false+ or +nil+, JSON.generate returns
# a \String containing the corresponding \JSON token:
#   JSON.generate(true) # => 'true'
#   JSON.generate(false) # => 'false'
#   JSON.generate(nil) # => 'null'
#
# When the source is none of the above, JSON.generate returns
# a \String containing a \JSON string representation of the source:
#   JSON.generate(:foo) # => '"foo"'
#   JSON.generate(Complex(0, 0)) # => '"0+0i"'
#   JSON.generate(Dir.new('.')) # => '"#<Dir>"'
#
# ==== Generating Options
#
# ====== Input Options
#
# Option +allow_nan+ (boolean) specifies whether
# +NaN+, +Infinity+, and <tt>-Infinity</tt> may be generated;
# defaults to +false+.
#
# With the default, +false+:
#   # Raises JSON::GeneratorError (920: NaN not allowed in JSON):
#   JSON.generate(JSON::NaN)
#   # Raises JSON::GeneratorError (917: Infinity not allowed in JSON):
#   JSON.generate(JSON::Infinity)
#   # Raises JSON::GeneratorError (917: -Infinity not allowed in JSON):
#   JSON.generate(JSON::MinusInfinity)
#
# Allow:
#   ruby = [Float::NaN, Float::Infinity, Float::MinusInfinity]
#   JSON.generate(ruby, allow_nan: true) # => '[NaN,Infinity,-Infinity]'
#
# ---
#
# Option +max_nesting+ (\Integer) specifies the maximum nesting depth
# in +obj+; defaults to +100+.
#
# With the default, +100+:
#   obj = [[[[[[0]]]]]]
#   JSON.generate(obj) # => '[[[[[[0]]]]]]'
#
# Too deep:
#   # Raises JSON::NestingError (nesting of 2 is too deep):
#   JSON.generate(obj, max_nesting: 2)
#
# ====== Output Options
#
# The default formatting options generate the most compact
# \JSON data, all on one line and with no whitespace.
#
# You can use these formatting options to generate
# \JSON data in a more open format, using whitespace.
# See also JSON.pretty_generate.
#
# - Option +array_nl+ (\String) specifies a string (usually a newline)
#   to be inserted after each \JSON array; defaults to the empty \String, <tt>''</tt>.
# - Option +object_nl+ (\String) specifies a string (usually a newline)
#   to be inserted after each \JSON object; defaults to the empty \String, <tt>''</tt>.
# - Option +indent+ (\String) specifies the string (usually spaces) to be
#   used for indentation; defaults to the empty \String, <tt>''</tt>;
#   defaults to the empty \String, <tt>''</tt>;
#   has no effect unless options +array_nl+ or +object_nl+ specify newlines.
# - Option +space+ (\String) specifies a string (usually a space) to be
#   inserted after the colon in each \JSON object's pair;
#   defaults to the empty \String, <tt>''</tt>.
# - Option +space_before+ (\String) specifies a string (usually a space) to be
#   inserted before the colon in each \JSON object's pair;
#   defaults to the empty \String, <tt>''</tt>.
#
# In this example, +obj+ is used first to generate the shortest
# \JSON data (no whitespace), then again with all formatting options
# specified:
#
#   obj = {foo: [:bar, :baz], bat: {bam: 0, bad: 1}}
#   json = JSON.generate(obj)
#   puts 'Compact:', json
#   opts = {
#     array_nl: "\n",
#     object_nl: "\n",
#     indent: '  ',
#     space_before: ' ',
#     space: ' '
#   }
#   puts 'Open:', JSON.generate(obj, opts)
#
# Output:
#   Compact:
#   {"foo":["bar","baz"],"bat":{"bam":0,"bad":1}}
#   Open:
#   {
#     "foo" : [
#       "bar",
#       "baz"
#   ],
#     "bat" : {
#       "bam" : 0,
#       "bad" : 1
#     }
#   }
#
# == \JSON Additions
#
# When you "round trip" a non-\String object from Ruby to \JSON and back,
# you have a new \String, instead of the object you began with:
#   ruby0 = Range.new(0, 2)
#   json = JSON.generate(ruby0)
#   json # => '0..2"'
#   ruby1 = JSON.parse(json)
#   ruby1 # => '0..2'
#   ruby1.class # => String
#
# You can use \JSON _additions_ to preserve the original object.
# The addition is an extension of a ruby class, so that:
# - \JSON.generate stores more information in the \JSON string.
# - \JSON.parse, called with option +create_additions+,
#   uses that information to create a proper Ruby object.
#
# This example shows a \Range being generated into \JSON
# and parsed back into Ruby, both without and with
# the addition for \Range:
#   ruby = Range.new(0, 2)
#   # This passage does not use the addition for Range.
#   json0 = JSON.generate(ruby)
#   ruby0 = JSON.parse(json0)
#   # This passage uses the addition for Range.
#   require 'json/add/range'
#   json1 = JSON.generate(ruby)
#   ruby1 = JSON.parse(json1, create_additions: true)
#   # Make a nice display.
#   display = <<EOT
#   Generated JSON:
#     Without addition:  #{json0} (#{json0.class})
#     With addition:     #{json1} (#{json1.class})
#   Parsed JSON:
#     Without addition:  #{ruby0.inspect} (#{ruby0.class})
#     With addition:     #{ruby1.inspect} (#{ruby1.class})
#   EOT
#   puts display
#
# This output shows the different results:
#   Generated JSON:
#     Without addition:  "0..2" (String)
#     With addition:     {"json_class":"Range","a":[0,2,false]} (String)
#   Parsed JSON:
#     Without addition:  "0..2" (String)
#     With addition:     0..2 (Range)
#
# The \JSON module includes additions for certain classes.
# You can also craft custom additions.
# See {Custom \JSON Additions}[#module-JSON-label-Custom+JSON+Additions].
#
# === Built-in Additions
#
# The \JSON module includes additions for certain classes.
# To use an addition, +require+ its source:
# - BigDecimal: <tt>require 'json/add/bigdecimal'</tt>
# - Complex: <tt>require 'json/add/complex'</tt>
# - Date: <tt>require 'json/add/date'</tt>
# - DateTime: <tt>require 'json/add/date_time'</tt>
# - Exception: <tt>require 'json/add/exception'</tt>
# - OpenStruct: <tt>require 'json/add/ostruct'</tt>
# - Range: <tt>require 'json/add/range'</tt>
# - Rational: <tt>require 'json/add/rational'</tt>
# - Regexp: <tt>require 'json/add/regexp'</tt>
# - Set: <tt>require 'json/add/set'</tt>
# - Struct: <tt>require 'json/add/struct'</tt>
# - Symbol: <tt>require 'json/add/symbol'</tt>
# - Time: <tt>require 'json/add/time'</tt>
#
# To reduce punctuation clutter, the examples below
# show the generated \JSON via +puts+, rather than the usual +inspect+,
#
# \BigDecimal:
#   require 'json/add/bigdecimal'
#   ruby0 = BigDecimal(0) # 0.0
#   json = JSON.generate(ruby0) # {"json_class":"BigDecimal","b":"27:0.0"}
#   ruby1 = JSON.parse(json, create_additions: true) # 0.0
#   ruby1.class # => BigDecimal
#
# \Complex:
#   require 'json/add/complex'
#   ruby0 = Complex(1+0i) # 1+0i
#   json = JSON.generate(ruby0) # {"json_class":"Complex","r":1,"i":0}
#   ruby1 = JSON.parse(json, create_additions: true) # 1+0i
#   ruby1.class # Complex
#
# \Date:
#   require 'json/add/date'
#   ruby0 = Date.today # 2020-05-02
#   json = JSON.generate(ruby0) # {"json_class":"Date","y":2020,"m":5,"d":2,"sg":2299161.0}
#   ruby1 = JSON.parse(json, create_additions: true) # 2020-05-02
#   ruby1.class # Date
#
# \DateTime:
#   require 'json/add/date_time'
#   ruby0 = DateTime.now # 2020-05-02T10:38:13-05:00
#   json = JSON.generate(ruby0) # {"json_class":"DateTime","y":2020,"m":5,"d":2,"H":10,"M":38,"S":13,"of":"-5/24","sg":2299161.0}
#   ruby1 = JSON.parse(json, create_additions: true) # 2020-05-02T10:38:13-05:00
#   ruby1.class # DateTime
#
# \Exception (and its subclasses including \RuntimeError):
#   require 'json/add/exception'
#   ruby0 = Exception.new('A message') # A message
#   json = JSON.generate(ruby0) # {"json_class":"Exception","m":"A message","b":null}
#   ruby1 = JSON.parse(json, create_additions: true) # A message
#   ruby1.class # Exception
#   ruby0 = RuntimeError.new('Another message') # Another message
#   json = JSON.generate(ruby0) # {"json_class":"RuntimeError","m":"Another message","b":null}
#   ruby1 = JSON.parse(json, create_additions: true) # Another message
#   ruby1.class # RuntimeError
#
# \OpenStruct:
#   require 'json/add/ostruct'
#   ruby0 = OpenStruct.new(name: 'Matz', language: 'Ruby') # #<OpenStruct name="Matz", language="Ruby">
#   json = JSON.generate(ruby0) # {"json_class":"OpenStruct","t":{"name":"Matz","language":"Ruby"}}
#   ruby1 = JSON.parse(json, create_additions: true) # #<OpenStruct name="Matz", language="Ruby">
#   ruby1.class # OpenStruct
#
# \Range:
#   require 'json/add/range'
#   ruby0 = Range.new(0, 2) # 0..2
#   json = JSON.generate(ruby0) # {"json_class":"Range","a":[0,2,false]}
#   ruby1 = JSON.parse(json, create_additions: true) # 0..2
#   ruby1.class # Range
#
# \Rational:
#   require 'json/add/rational'
#   ruby0 = Rational(1, 3) # 1/3
#   json = JSON.generate(ruby0) # {"json_class":"Rational","n":1,"d":3}
#   ruby1 = JSON.parse(json, create_additions: true) # 1/3
#   ruby1.class # Rational
#
# \Regexp:
#   require 'json/add/regexp'
#   ruby0 = Regexp.new('foo') # (?-mix:foo)
#   json = JSON.generate(ruby0) # {"json_class":"Regexp","o":0,"s":"foo"}
#   ruby1 = JSON.parse(json, create_additions: true) # (?-mix:foo)
#   ruby1.class # Regexp
#
# \Set:
#   require 'json/add/set'
#   ruby0 = Set.new([0, 1, 2]) # #<Set: {0, 1, 2}>
#   json = JSON.generate(ruby0) # {"json_class":"Set","a":[0,1,2]}
#   ruby1 = JSON.parse(json, create_additions: true) # #<Set: {0, 1, 2}>
#   ruby1.class # Set
#
# \Struct:
#   require 'json/add/struct'
#   Customer = Struct.new(:name, :address) # Customer
#   ruby0 = Customer.new("Dave", "123 Main") # #<struct Customer name="Dave", address="123 Main">
#   json = JSON.generate(ruby0) # {"json_class":"Customer","v":["Dave","123 Main"]}
#   ruby1 = JSON.parse(json, create_additions: true) # #<struct Customer name="Dave", address="123 Main">
#   ruby1.class # Customer
  #
# \Symbol:
#   require 'json/add/symbol'
#   ruby0 = :foo # foo
#   json = JSON.generate(ruby0) # {"json_class":"Symbol","s":"foo"}
#   ruby1 = JSON.parse(json, create_additions: true) # foo
#   ruby1.class # Symbol
#
# \Time:
#   require 'json/add/time'
#   ruby0 = Time.now # 2020-05-02 11:28:26 -0500
#   json = JSON.generate(ruby0) # {"json_class":"Time","s":1588436906,"n":840560000}
#   ruby1 = JSON.parse(json, create_additions: true) # 2020-05-02 11:28:26 -0500
#   ruby1.class # Time
#
#
# === Custom \JSON Additions
#
# In addition to the \JSON additions provided,
# you can craft \JSON additions of your own,
# either for Ruby built-in classes or for user-defined classes.
#
# Here's a user-defined class +Foo+:
#   class Foo
#     attr_accessor :bar, :baz
#     def initialize(bar, baz)
#       self.bar = bar
#       self.baz = baz
#     end
#   end
#
# Here's the \JSON addition for it:
#   # Extend class Foo with JSON addition.
#   class Foo
#     # Serialize Foo object with its class name and arguments
#     def to_json(*args)
#       {
#         JSON.create_id  => self.class.name,
#         'a'             => [ bar, baz ]
#       }.to_json(*args)
#     end
#     # Deserialize JSON string by constructing new Foo object with arguments.
#     def self.json_create(object)
#       new(*object['a'])
#     end
#   end
#
# Demonstration:
#   require 'json'
#   # This Foo object has no custom addition.
#   foo0 = Foo.new(0, 1)
#   json0 = JSON.generate(foo0)
#   obj0 = JSON.parse(json0)
#   # Lood the custom addition.
#   require_relative 'foo_addition'
#   # This foo has the custom addition.
#   foo1 = Foo.new(0, 1)
#   json1 = JSON.generate(foo1)
#   obj1 = JSON.parse(json1, create_additions: true)
#   #   Make a nice display.
#   display = <<EOT
#   Generated JSON:
#     Without custom addition:  #{json0} (#{json0.class})
#     With custom addition:     #{json1} (#{json1.class})
#   Parsed JSON:
#     Without custom addition:  #{obj0.inspect} (#{obj0.class})
#     With custom addition:     #{obj1.inspect} (#{obj1.class})
#   EOT
#   puts display
#
# Output:
#
#   Generated JSON:
#     Without custom addition:  "#<Foo:0x0000000006534e80>" (String)
#     With custom addition:     {"json_class":"Foo","a":[0,1]} (String)
#   Parsed JSON:
#     Without custom addition:  "#<Foo:0x0000000006534e80>" (String)
#     With custom addition:     #<Foo:0x0000000006473bb8 @bar=0, @baz=1> (Foo)
#
module JSON
  require 'json/version'

  begin
    require 'json/ext'
  rescue LoadError
    require 'json/pure'
  end
end
# -*- encoding: utf-8 -*-
# stub: rack 3.0.8 ruby lib

Gem::Specification.new do |s|
  s.name = "rack".freeze
  s.version = "3.0.8"

  s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
  s.metadata = { "bug_tracker_uri" => "https://github.com/rack/rack/issues", "changelog_uri" => "https://github.com/rack/rack/blob/main/CHANGELOG.md", "documentation_uri" => "https://rubydoc.info/github/rack/rack", "source_code_uri" => "https://github.com/rack/rack" } if s.respond_to? :metadata=
  s.require_paths = ["lib".freeze]
  s.authors = ["Leah Neukirchen".freeze]
  s.date = "2023-06-14"
  s.description = "Rack provides a minimal, modular and adaptable interface for developing\nweb applications in Ruby. By wrapping HTTP requests and responses in\nthe simplest way possible, it unifies and distills the API for web\nservers, web frameworks, and software in between (the so-called\nmiddleware) into a single method call.\n".freeze
  s.email = "leah@vuxu.org".freeze
  s.extra_rdoc_files = ["README.md".freeze, "CHANGELOG.md".freeze, "CONTRIBUTING.md".freeze]
  s.files = ["CHANGELOG.md".freeze, "CONTRIBUTING.md".freeze, "README.md".freeze]
  s.homepage = "https://github.com/rack/rack".freeze
  s.licenses = ["MIT".freeze]
  s.required_ruby_version = Gem::Requirement.new(">= 2.4.0".freeze)
  s.rubygems_version = "3.2.33".freeze
  s.summary = "A modular Ruby webserver interface.".freeze

  s.installed_by_version = "3.2.33" if s.respond_to? :installed_by_version

  if s.respond_to? :specification_version then
    s.specification_version = 4
  end

  if s.respond_to? :add_runtime_dependency then
    s.add_development_dependency(%q<minitest>.freeze, ["~> 5.0"])
    s.add_development_dependency(%q<minitest-global_expectations>.freeze, [">= 0"])
    s.add_development_dependency(%q<bundler>.freeze, [">= 0"])
    s.add_development_dependency(%q<rake>.freeze, [">= 0"])
  else
    s.add_dependency(%q<minitest>.freeze, ["~> 5.0"])
    s.add_dependency(%q<minitest-global_expectations>.freeze, [">= 0"])
    s.add_dependency(%q<bundler>.freeze, [">= 0"])
    s.add_dependency(%q<rake>.freeze, [">= 0"])
  end
end
# -*- encoding: utf-8 -*-
# stub: json 2.5.1 ruby lib

Gem::Specification.new do |s|
  s.name = "json".freeze
  s.version = "2.5.1"

  s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
  s.metadata = { "bug_tracker_uri" => "https://github.com/flori/json/issues", "changelog_uri" => "https://github.com/flori/json/blob/master/CHANGES.md", "documentation_uri" => "http://flori.github.io/json/doc/index.html", "homepage_uri" => "http://flori.github.io/json/", "source_code_uri" => "https://github.com/flori/json", "wiki_uri" => "https://github.com/flori/json/wiki" } if s.respond_to? :metadata=
  s.require_paths = ["lib".freeze]
  s.authors = ["Florian Frank".freeze]
  s.date = "2024-06-26"
  s.description = "This is a JSON implementation as a Ruby extension in C.".freeze
  s.email = "flori@ping.de".freeze
  s.extensions = ["ext/json/ext/generator/extconf.rb".freeze, "ext/json/ext/parser/extconf.rb".freeze, "ext/json/extconf.rb".freeze]
  s.extra_rdoc_files = ["README.md".freeze]
  s.files = ["README.md".freeze, "ext/json/ext/generator/extconf.rb".freeze, "ext/json/ext/parser/extconf.rb".freeze, "ext/json/extconf.rb".freeze, "json.rb".freeze, "json/add/bigdecimal.rb".freeze, "json/add/complex.rb".freeze, "json/add/core.rb".freeze, "json/add/date.rb".freeze, "json/add/date_time.rb".freeze, "json/add/exception.rb".freeze, "json/add/ostruct.rb".freeze, "json/add/range.rb".freeze, "json/add/rational.rb".freeze, "json/add/regexp.rb".freeze, "json/add/set.rb".freeze, "json/add/struct.rb".freeze, "json/add/symbol.rb".freeze, "json/add/time.rb".freeze, "json/common.rb".freeze, "json/ext.rb".freeze, "json/ext/generator.so".freeze, "json/ext/parser.so".freeze, "json/generic_object.rb".freeze, "json/version.rb".freeze, "tests/test_helper.rb".freeze]
  s.homepage = "http://flori.github.com/json".freeze
  s.licenses = ["Ruby".freeze]
  s.rdoc_options = ["--title".freeze, "JSON implementation for Ruby".freeze, "--main".freeze, "README.md".freeze]
  s.required_ruby_version = Gem::Requirement.new(">= 2.0".freeze)
  s.rubygems_version = "3.2.33".freeze
  s.summary = "JSON Implementation for Ruby".freeze
  s.test_files = ["tests/test_helper.rb".freeze]

  if s.respond_to? :specification_version then
    s.specification_version = 4
  end

  if s.respond_to? :add_runtime_dependency then
    s.add_development_dependency(%q<rake>.freeze, [">= 0"])
    s.add_development_dependency(%q<test-unit>.freeze, [">= 0"])
  else
    s.add_dependency(%q<rake>.freeze, [">= 0"])
    s.add_dependency(%q<test-unit>.freeze, [">= 0"])
  end
end
# -*- encoding: utf-8 -*-
# stub: rdoc 6.3.4.1 ruby lib

Gem::Specification.new do |s|
  s.name = "rdoc".freeze
  s.version = "6.3.4.1"

  s.required_rubygems_version = Gem::Requirement.new(">= 2.2".freeze) if s.respond_to? :required_rubygems_version=
  s.require_paths = ["lib".freeze]
  s.authors = ["Eric Hodel".freeze, "Dave Thomas".freeze, "Phil Hagelberg".freeze, "Tony Strauss".freeze, "Zachary Scott".freeze, "Hiroshi SHIBATA".freeze, "ITOYANAGI Sakura".freeze]
  s.bindir = "exe".freeze
  s.date = "2024-06-26"
  s.description = "RDoc produces HTML and command-line documentation for Ruby projects.\nRDoc includes the +rdoc+ and +ri+ tools for generating and displaying documentation from the command-line.\n".freeze
  s.email = ["drbrain@segment7.net".freeze, "".freeze, "".freeze, "".freeze, "mail@zzak.io".freeze, "hsbt@ruby-lang.org".freeze, "aycabta@gmail.com".freeze]
  s.executables = ["rdoc".freeze, "ri".freeze]
  s.extra_rdoc_files = ["CVE-2013-0256.rdoc".freeze, "CONTRIBUTING.rdoc".freeze, "ExampleMarkdown.md".freeze, "ExampleRDoc.rdoc".freeze, "History.rdoc".freeze, "LEGAL.rdoc".freeze, "LICENSE.rdoc".freeze, "README.rdoc".freeze, "RI.rdoc".freeze, "TODO.rdoc".freeze]
  s.files = ["CONTRIBUTING.rdoc".freeze, "CVE-2013-0256.rdoc".freeze, "ExampleMarkdown.md".freeze, "ExampleRDoc.rdoc".freeze, "History.rdoc".freeze, "LEGAL.rdoc".freeze, "LICENSE.rdoc".freeze, "README.rdoc".freeze, "RI.rdoc".freeze, "TODO.rdoc".freeze, "exe/rdoc".freeze, "exe/ri".freeze, "rdoc.rb".freeze, "rdoc/alias.rb".freeze, "rdoc/anon_class.rb".freeze, "rdoc/any_method.rb".freeze, "rdoc/attr.rb".freeze, "rdoc/class_module.rb".freeze, "rdoc/code_object.rb".freeze, "rdoc/code_objects.rb".freeze, "rdoc/comment.rb".freeze, "rdoc/constant.rb".freeze, "rdoc/context.rb".freeze, "rdoc/context/section.rb".freeze, "rdoc/cross_reference.rb".freeze, "rdoc/encoding.rb".freeze, "rdoc/erb_partial.rb".freeze, "rdoc/erbio.rb".freeze, "rdoc/extend.rb".freeze, "rdoc/generator.rb".freeze, "rdoc/generator/darkfish.rb".freeze, "rdoc/generator/json_index.rb".freeze, "rdoc/generator/markup.rb".freeze, "rdoc/generator/pot.rb".freeze, "rdoc/generator/pot/message_extractor.rb".freeze, "rdoc/generator/pot/po.rb".freeze, "rdoc/generator/pot/po_entry.rb".freeze, "rdoc/generator/ri.rb".freeze, "rdoc/ghost_method.rb".freeze, "rdoc/i18n.rb".freeze, "rdoc/i18n/locale.rb".freeze, "rdoc/i18n/text.rb".freeze, "rdoc/include.rb".freeze, "rdoc/known_classes.rb".freeze, "rdoc/markdown.rb".freeze, "rdoc/markdown/entities.rb".freeze, "rdoc/markdown/literals.rb".freeze, "rdoc/markup.rb".freeze, "rdoc/markup/attr_changer.rb".freeze, "rdoc/markup/attr_span.rb".freeze, "rdoc/markup/attribute_manager.rb".freeze, "rdoc/markup/attributes.rb".freeze, "rdoc/markup/blank_line.rb".freeze, "rdoc/markup/block_quote.rb".freeze, "rdoc/markup/document.rb".freeze, "rdoc/markup/formatter.rb".freeze, "rdoc/markup/hard_break.rb".freeze, "rdoc/markup/heading.rb".freeze, "rdoc/markup/include.rb".freeze, "rdoc/markup/indented_paragraph.rb".freeze, "rdoc/markup/list.rb".freeze, "rdoc/markup/list_item.rb".freeze, "rdoc/markup/paragraph.rb".freeze, "rdoc/markup/parser.rb".freeze, "rdoc/markup/pre_process.rb".freeze, "rdoc/markup/raw.rb".freeze, "rdoc/markup/regexp_handling.rb".freeze, "rdoc/markup/rule.rb".freeze, "rdoc/markup/table.rb".freeze, "rdoc/markup/to_ansi.rb".freeze, "rdoc/markup/to_bs.rb".freeze, "rdoc/markup/to_html.rb".freeze, "rdoc/markup/to_html_crossref.rb".freeze, "rdoc/markup/to_html_snippet.rb".freeze, "rdoc/markup/to_joined_paragraph.rb".freeze, "rdoc/markup/to_label.rb".freeze, "rdoc/markup/to_markdown.rb".freeze, "rdoc/markup/to_rdoc.rb".freeze, "rdoc/markup/to_table_of_contents.rb".freeze, "rdoc/markup/to_test.rb".freeze, "rdoc/markup/to_tt_only.rb".freeze, "rdoc/markup/verbatim.rb".freeze, "rdoc/meta_method.rb".freeze, "rdoc/method_attr.rb".freeze, "rdoc/mixin.rb".freeze, "rdoc/normal_class.rb".freeze, "rdoc/normal_module.rb".freeze, "rdoc/options.rb".freeze, "rdoc/parser.rb".freeze, "rdoc/parser/c.rb".freeze, "rdoc/parser/changelog.rb".freeze, "rdoc/parser/markdown.rb".freeze, "rdoc/parser/rd.rb".freeze, "rdoc/parser/ripper_state_lex.rb".freeze, "rdoc/parser/ruby.rb".freeze, "rdoc/parser/ruby_tools.rb".freeze, "rdoc/parser/simple.rb".freeze, "rdoc/parser/text.rb".freeze, "rdoc/rd.rb".freeze, "rdoc/rd/block_parser.rb".freeze, "rdoc/rd/inline.rb".freeze, "rdoc/rd/inline_parser.rb".freeze, "rdoc/rdoc.rb".freeze, "rdoc/require.rb".freeze, "rdoc/ri.rb".freeze, "rdoc/ri/driver.rb".freeze, "rdoc/ri/formatter.rb".freeze, "rdoc/ri/paths.rb".freeze, "rdoc/ri/store.rb".freeze, "rdoc/ri/task.rb".freeze, "rdoc/rubygems_hook.rb".freeze, "rdoc/servlet.rb".freeze, "rdoc/single_class.rb".freeze, "rdoc/stats.rb".freeze, "rdoc/stats/normal.rb".freeze, "rdoc/stats/quiet.rb".freeze, "rdoc/stats/verbose.rb".freeze, "rdoc/store.rb".freeze, "rdoc/task.rb".freeze, "rdoc/text.rb".freeze, "rdoc/token_stream.rb".freeze, "rdoc/tom_doc.rb".freeze, "rdoc/top_level.rb".freeze, "rdoc/version.rb".freeze]
  s.homepage = "https://ruby.github.io/rdoc".freeze
  s.licenses = ["Ruby".freeze]
  s.rdoc_options = ["--main".freeze, "README.rdoc".freeze]
  s.required_ruby_version = Gem::Requirement.new(">= 2.4.0".freeze)
  s.rubygems_version = "3.2.33".freeze
  s.summary = "RDoc produces HTML and command-line documentation for Ruby projects".freeze

  if s.respond_to? :specification_version then
    s.specification_version = 4
  end

  if s.respond_to? :add_runtime_dependency then
    s.add_development_dependency(%q<gettext>.freeze, [">= 0"])
  else
    s.add_dependency(%q<gettext>.freeze, [">= 0"])
  end
end
# -*- encoding: utf-8 -*-
# stub: rackup 2.1.0 ruby lib

Gem::Specification.new do |s|
  s.name = "rackup".freeze
  s.version = "2.1.0"

  s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
  s.require_paths = ["lib".freeze]
  s.authors = ["Samuel Williams".freeze, "Jeremy Evans".freeze]
  s.date = "2023-01-27"
  s.executables = ["rackup".freeze]
  s.files = ["bin/rackup".freeze]
  s.homepage = "https://github.com/rack/rackup".freeze
  s.licenses = ["MIT".freeze]
  s.required_ruby_version = Gem::Requirement.new(">= 2.4.0".freeze)
  s.rubygems_version = "3.2.33".freeze
  s.summary = "A general server command for Rack applications.".freeze

  s.installed_by_version = "3.2.33" if s.respond_to? :installed_by_version

  if s.respond_to? :specification_version then
    s.specification_version = 4
  end

  if s.respond_to? :add_runtime_dependency then
    s.add_runtime_dependency(%q<rack>.freeze, [">= 3"])
    s.add_runtime_dependency(%q<webrick>.freeze, ["~> 1.8"])
    s.add_development_dependency(%q<bundler>.freeze, [">= 0"])
    s.add_development_dependency(%q<minitest>.freeze, ["~> 5.0"])
    s.add_development_dependency(%q<minitest-global_expectations>.freeze, [">= 0"])
    s.add_development_dependency(%q<minitest-sprint>.freeze, [">= 0"])
    s.add_development_dependency(%q<rake>.freeze, [">= 0"])
  else
    s.add_dependency(%q<rack>.freeze, [">= 3"])
    s.add_dependency(%q<webrick>.freeze, ["~> 1.8"])
    s.add_dependency(%q<bundler>.freeze, [">= 0"])
    s.add_dependency(%q<minitest>.freeze, ["~> 5.0"])
    s.add_dependency(%q<minitest-global_expectations>.freeze, [">= 0"])
    s.add_dependency(%q<minitest-sprint>.freeze, [">= 0"])
    s.add_dependency(%q<rake>.freeze, [">= 0"])
  end
end
# -*- encoding: utf-8 -*-
# stub: bigdecimal 3.0.0 ruby lib
# stub: ext/bigdecimal/extconf.rb

Gem::Specification.new do |s|
  s.name = "bigdecimal".freeze
  s.version = "3.0.0"

  s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
  s.require_paths = ["lib".freeze]
  s.authors = ["Kenta Murata".freeze, "Zachary Scott".freeze, "Shigeo Kobayashi".freeze]
  s.date = "2024-06-26"
  s.description = "This library provides arbitrary-precision decimal floating-point number class.".freeze
  s.email = ["mrkn@mrkn.jp".freeze]
  s.extensions = ["ext/bigdecimal/extconf.rb".freeze]
  s.files = ["bigdecimal.rb".freeze, "bigdecimal.so".freeze, "bigdecimal/jacobian.rb".freeze, "bigdecimal/ludcmp.rb".freeze, "bigdecimal/math.rb".freeze, "bigdecimal/newton.rb".freeze, "bigdecimal/util.rb".freeze, "ext/bigdecimal/extconf.rb".freeze]
  s.homepage = "https://github.com/ruby/bigdecimal".freeze
  s.licenses = ["Ruby".freeze]
  s.required_ruby_version = Gem::Requirement.new(">= 2.4.0".freeze)
  s.rubygems_version = "3.2.33".freeze
  s.summary = "Arbitrary-precision decimal floating-point number library.".freeze

  if s.respond_to? :specification_version then
    s.specification_version = 4
  end

  if s.respond_to? :add_runtime_dependency then
    s.add_development_dependency(%q<rake>.freeze, [">= 12.3.3"])
    s.add_development_dependency(%q<rake-compiler>.freeze, [">= 0.9"])
    s.add_development_dependency(%q<minitest>.freeze, ["< 5.0.0"])
    s.add_development_dependency(%q<pry>.freeze, [">= 0"])
  else
    s.add_dependency(%q<rake>.freeze, [">= 12.3.3"])
    s.add_dependency(%q<rake-compiler>.freeze, [">= 0.9"])
    s.add_dependency(%q<minitest>.freeze, ["< 5.0.0"])
    s.add_dependency(%q<pry>.freeze, [">= 0"])
  end
end
# -*- encoding: utf-8 -*-
# stub: ruby-lsapi 5.6 ruby lib
# stub: ext/lsapi/extconf.rb

Gem::Specification.new do |s|
  s.name = "ruby-lsapi".freeze
  s.version = "5.6"

  s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
  s.require_paths = ["lib".freeze]
  s.authors = ["LiteSpeed Technologies Inc.".freeze]
  s.date = "2024-01-22"
  s.description = "This is a ruby extension for fast communication with LiteSpeed Web Server.".freeze
  s.email = "info@litespeedtech.com".freeze
  s.extensions = ["ext/lsapi/extconf.rb".freeze]
  s.extra_rdoc_files = ["README".freeze]
  s.files = ["README".freeze, "ext/lsapi/extconf.rb".freeze]
  s.homepage = "http://www.litespeedtech.com/".freeze
  s.rubygems_version = "3.2.33".freeze
  s.summary = "A ruby extension for fast communication with LiteSpeed Web Server.".freeze

  s.installed_by_version = "3.2.33" if s.respond_to? :installed_by_version
end
# -*- encoding: utf-8 -*-
# stub: io-console 0.5.7 ruby lib
# stub: ext/io/console/extconf.rb

Gem::Specification.new do |s|
  s.name = "io-console".freeze
  s.version = "0.5.7"

  s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
  s.metadata = { "source_code_url" => "https://github.com/ruby/io-console" } if s.respond_to? :metadata=
  s.require_paths = ["lib".freeze]
  s.authors = ["Nobu Nakada".freeze]
  s.date = "2024-06-26"
  s.description = "add console capabilities to IO instances.".freeze
  s.email = "nobu@ruby-lang.org".freeze
  s.extensions = ["ext/io/console/extconf.rb".freeze]
  s.files = ["ext/io/console/extconf.rb".freeze, "io/console.so".freeze, "io/console/size.rb".freeze]
  s.homepage = "https://github.com/ruby/io-console".freeze
  s.licenses = ["Ruby".freeze, "BSD-2-Clause".freeze]
  s.required_ruby_version = Gem::Requirement.new(">= 2.4.0".freeze)
  s.rubygems_version = "3.2.33".freeze
  s.summary = "Console interface".freeze
end
# -*- encoding: utf-8 -*-
# stub: psych 3.3.2 ruby lib
# stub: ext/psych/extconf.rb

Gem::Specification.new do |s|
  s.name = "psych".freeze
  s.version = "3.3.2"

  s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
  s.require_paths = ["lib".freeze]
  s.authors = ["Aaron Patterson".freeze, "SHIBATA Hiroshi".freeze, "Charles Oliver Nutter".freeze]
  s.date = "2024-06-26"
  s.description = "Psych is a YAML parser and emitter. Psych leverages libyaml[https://pyyaml.org/wiki/LibYAML]\nfor its YAML parsing and emitting capabilities. In addition to wrapping libyaml,\nPsych also knows how to serialize and de-serialize most Ruby objects to and from the YAML format.\n".freeze
  s.email = ["aaron@tenderlovemaking.com".freeze, "hsbt@ruby-lang.org".freeze, "headius@headius.com".freeze]
  s.extensions = ["ext/psych/extconf.rb".freeze]
  s.extra_rdoc_files = ["README.md".freeze]
  s.files = ["README.md".freeze, "ext/psych/extconf.rb".freeze, "psych.rb".freeze, "psych.so".freeze, "psych/class_loader.rb".freeze, "psych/coder.rb".freeze, "psych/core_ext.rb".freeze, "psych/exception.rb".freeze, "psych/handler.rb".freeze, "psych/handlers/document_stream.rb".freeze, "psych/handlers/recorder.rb".freeze, "psych/json/ruby_events.rb".freeze, "psych/json/stream.rb".freeze, "psych/json/tree_builder.rb".freeze, "psych/json/yaml_events.rb".freeze, "psych/nodes.rb".freeze, "psych/nodes/alias.rb".freeze, "psych/nodes/document.rb".freeze, "psych/nodes/mapping.rb".freeze, "psych/nodes/node.rb".freeze, "psych/nodes/scalar.rb".freeze, "psych/nodes/sequence.rb".freeze, "psych/nodes/stream.rb".freeze, "psych/omap.rb".freeze, "psych/parser.rb".freeze, "psych/scalar_scanner.rb".freeze, "psych/set.rb".freeze, "psych/stream.rb".freeze, "psych/streaming.rb".freeze, "psych/syntax_error.rb".freeze, "psych/tree_builder.rb".freeze, "psych/versions.rb".freeze, "psych/visitors.rb".freeze, "psych/visitors/depth_first.rb".freeze, "psych/visitors/emitter.rb".freeze, "psych/visitors/json_tree.rb".freeze, "psych/visitors/to_ruby.rb".freeze, "psych/visitors/visitor.rb".freeze, "psych/visitors/yaml_tree.rb".freeze, "psych/y.rb".freeze]
  s.homepage = "https://github.com/ruby/psych".freeze
  s.licenses = ["MIT".freeze]
  s.rdoc_options = ["--main".freeze, "README.md".freeze]
  s.required_ruby_version = Gem::Requirement.new(">= 2.4.0".freeze)
  s.rubygems_version = "3.2.33".freeze
  s.summary = "Psych is a YAML parser and emitter".freeze
end
# -*- encoding: utf-8 -*-
# stub: bundler 2.2.33 ruby lib

Gem::Specification.new do |s|
  s.name = "bundler".freeze
  s.version = "2.2.33"

  s.required_rubygems_version = Gem::Requirement.new(">= 2.5.2".freeze) if s.respond_to? :required_rubygems_version=
  s.metadata = { "bug_tracker_uri" => "https://github.com/rubygems/rubygems/issues?q=is%3Aopen+is%3Aissue+label%3ABundler", "changelog_uri" => "https://github.com/rubygems/rubygems/blob/master/bundler/CHANGELOG.md", "homepage_uri" => "https://bundler.io/", "source_code_uri" => "https://github.com/rubygems/rubygems/" } if s.respond_to? :metadata=
  s.require_paths = ["lib".freeze]
  s.authors = ["Andr\u00E9 Arko".freeze, "Samuel Giddins".freeze, "Colby Swandale".freeze, "Hiroshi Shibata".freeze, "David Rodr\u00EDguez".freeze, "Grey Baker".freeze, "Stephanie Morillo".freeze, "Chris Morris".freeze, "James Wen".freeze, "Tim Moore".freeze, "Andr\u00E9 Medeiros".freeze, "Jessica Lynn Suttles".freeze, "Terence Lee".freeze, "Carl Lerche".freeze, "Yehuda Katz".freeze]
  s.bindir = "libexec".freeze
  s.date = "2024-06-26"
  s.description = "Bundler manages an application's dependencies through its entire life, across many machines, systematically and repeatably".freeze
  s.email = ["team@bundler.io".freeze]
  s.executables = ["bundle".freeze, "bundler".freeze]
  s.files = ["bundler.rb".freeze, "bundler/build_metadata.rb".freeze, "bundler/capistrano.rb".freeze, "bundler/cli.rb".freeze, "bundler/cli/add.rb".freeze, "bundler/cli/binstubs.rb".freeze, "bundler/cli/cache.rb".freeze, "bundler/cli/check.rb".freeze, "bundler/cli/clean.rb".freeze, "bundler/cli/common.rb".freeze, "bundler/cli/config.rb".freeze, "bundler/cli/console.rb".freeze, "bundler/cli/doctor.rb".freeze, "bundler/cli/exec.rb".freeze, "bundler/cli/fund.rb".freeze, "bundler/cli/gem.rb".freeze, "bundler/cli/info.rb".freeze, "bundler/cli/init.rb".freeze, "bundler/cli/inject.rb".freeze, "bundler/cli/install.rb".freeze, "bundler/cli/issue.rb".freeze, "bundler/cli/list.rb".freeze, "bundler/cli/lock.rb".freeze, "bundler/cli/open.rb".freeze, "bundler/cli/outdated.rb".freeze, "bundler/cli/platform.rb".freeze, "bundler/cli/plugin.rb".freeze, "bundler/cli/pristine.rb".freeze, "bundler/cli/remove.rb".freeze, "bundler/cli/show.rb".freeze, "bundler/cli/update.rb".freeze, "bundler/cli/viz.rb".freeze, "bundler/compact_index_client.rb".freeze, "bundler/compact_index_client/cache.rb".freeze, "bundler/compact_index_client/gem_parser.rb".freeze, "bundler/compact_index_client/updater.rb".freeze, "bundler/constants.rb".freeze, "bundler/current_ruby.rb".freeze, "bundler/definition.rb".freeze, "bundler/dep_proxy.rb".freeze, "bundler/dependency.rb".freeze, "bundler/deployment.rb".freeze, "bundler/deprecate.rb".freeze, "bundler/digest.rb".freeze, "bundler/dsl.rb".freeze, "bundler/endpoint_specification.rb".freeze, "bundler/env.rb".freeze, "bundler/environment_preserver.rb".freeze, "bundler/errors.rb".freeze, "bundler/feature_flag.rb".freeze, "bundler/fetcher.rb".freeze, "bundler/fetcher/base.rb".freeze, "bundler/fetcher/compact_index.rb".freeze, "bundler/fetcher/dependency.rb".freeze, "bundler/fetcher/downloader.rb".freeze, "bundler/fetcher/index.rb".freeze, "bundler/friendly_errors.rb".freeze, "bundler/gem_helper.rb".freeze, "bundler/gem_helpers.rb".freeze, "bundler/gem_tasks.rb".freeze, "bundler/gem_version_promoter.rb".freeze, "bundler/gemdeps.rb".freeze, "bundler/graph.rb".freeze, "bundler/index.rb".freeze, "bundler/injector.rb".freeze, "bundler/inline.rb".freeze, "bundler/installer.rb".freeze, "bundler/installer/gem_installer.rb".freeze, "bundler/installer/parallel_installer.rb".freeze, "bundler/installer/standalone.rb".freeze, "bundler/lazy_specification.rb".freeze, "bundler/lockfile_generator.rb".freeze, "bundler/lockfile_parser.rb".freeze, "bundler/match_platform.rb".freeze, "bundler/mirror.rb".freeze, "bundler/plugin.rb".freeze, "bundler/plugin/api.rb".freeze, "bundler/plugin/api/source.rb".freeze, "bundler/plugin/dsl.rb".freeze, "bundler/plugin/events.rb".freeze, "bundler/plugin/index.rb".freeze, "bundler/plugin/installer.rb".freeze, "bundler/plugin/installer/git.rb".freeze, "bundler/plugin/installer/rubygems.rb".freeze, "bundler/plugin/source_list.rb".freeze, "bundler/process_lock.rb".freeze, "bundler/psyched_yaml.rb".freeze, "bundler/remote_specification.rb".freeze, "bundler/resolver.rb".freeze, "bundler/resolver/spec_group.rb".freeze, "bundler/retry.rb".freeze, "bundler/ruby_dsl.rb".freeze, "bundler/ruby_version.rb".freeze, "bundler/rubygems_ext.rb".freeze, "bundler/rubygems_gem_installer.rb".freeze, "bundler/rubygems_integration.rb".freeze, "bundler/runtime.rb".freeze, "bundler/settings.rb".freeze, "bundler/settings/validator.rb".freeze, "bundler/setup.rb".freeze, "bundler/shared_helpers.rb".freeze, "bundler/similarity_detector.rb".freeze, "bundler/source.rb".freeze, "bundler/source/gemspec.rb".freeze, "bundler/source/git.rb".freeze, "bundler/source/git/git_proxy.rb".freeze, "bundler/source/metadata.rb".freeze, "bundler/source/path.rb".freeze, "bundler/source/path/installer.rb".freeze, "bundler/source/rubygems.rb".freeze, "bundler/source/rubygems/remote.rb".freeze, "bundler/source/rubygems_aggregate.rb".freeze, "bundler/source_list.rb".freeze, "bundler/source_map.rb".freeze, "bundler/spec_set.rb".freeze, "bundler/stub_specification.rb".freeze, "bundler/templates/gems.rb".freeze, "bundler/ui.rb".freeze, "bundler/ui/rg_proxy.rb".freeze, "bundler/ui/shell.rb".freeze, "bundler/ui/silent.rb".freeze, "bundler/uri_credentials_filter.rb".freeze, "bundler/vendor/connection_pool/lib/connection_pool.rb".freeze, "bundler/vendor/connection_pool/lib/connection_pool/timed_stack.rb".freeze, "bundler/vendor/connection_pool/lib/connection_pool/version.rb".freeze, "bundler/vendor/connection_pool/lib/connection_pool/wrapper.rb".freeze, "bundler/vendor/fileutils/lib/fileutils.rb".freeze, "bundler/vendor/molinillo/lib/molinillo.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/delegates/resolution_state.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/delegates/specification_provider.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/dependency_graph.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/dependency_graph/action.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/dependency_graph/add_edge_no_circular.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/dependency_graph/add_vertex.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/dependency_graph/delete_edge.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/dependency_graph/detach_vertex_named.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/dependency_graph/log.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/dependency_graph/set_payload.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/dependency_graph/tag.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/dependency_graph/vertex.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/errors.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/gem_metadata.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/modules/specification_provider.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/modules/ui.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/resolution.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/resolver.rb".freeze, "bundler/vendor/molinillo/lib/molinillo/state.rb".freeze, "bundler/vendor/net-http-persistent/lib/net/http/persistent.rb".freeze, "bundler/vendor/net-http-persistent/lib/net/http/persistent/connection.rb".freeze, "bundler/vendor/net-http-persistent/lib/net/http/persistent/pool.rb".freeze, "bundler/vendor/net-http-persistent/lib/net/http/persistent/timed_stack_multi.rb".freeze, "bundler/vendor/thor/lib/thor.rb".freeze, "bundler/vendor/thor/lib/thor/actions.rb".freeze, "bundler/vendor/thor/lib/thor/actions/create_file.rb".freeze, "bundler/vendor/thor/lib/thor/actions/create_link.rb".freeze, "bundler/vendor/thor/lib/thor/actions/directory.rb".freeze, "bundler/vendor/thor/lib/thor/actions/empty_directory.rb".freeze, "bundler/vendor/thor/lib/thor/actions/file_manipulation.rb".freeze, "bundler/vendor/thor/lib/thor/actions/inject_into_file.rb".freeze, "bundler/vendor/thor/lib/thor/base.rb".freeze, "bundler/vendor/thor/lib/thor/command.rb".freeze, "bundler/vendor/thor/lib/thor/core_ext/hash_with_indifferent_access.rb".freeze, "bundler/vendor/thor/lib/thor/error.rb".freeze, "bundler/vendor/thor/lib/thor/group.rb".freeze, "bundler/vendor/thor/lib/thor/invocation.rb".freeze, "bundler/vendor/thor/lib/thor/line_editor.rb".freeze, "bundler/vendor/thor/lib/thor/line_editor/basic.rb".freeze, "bundler/vendor/thor/lib/thor/line_editor/readline.rb".freeze, "bundler/vendor/thor/lib/thor/nested_context.rb".freeze, "bundler/vendor/thor/lib/thor/parser.rb".freeze, "bundler/vendor/thor/lib/thor/parser/argument.rb".freeze, "bundler/vendor/thor/lib/thor/parser/arguments.rb".freeze, "bundler/vendor/thor/lib/thor/parser/option.rb".freeze, "bundler/vendor/thor/lib/thor/parser/options.rb".freeze, "bundler/vendor/thor/lib/thor/rake_compat.rb".freeze, "bundler/vendor/thor/lib/thor/runner.rb".freeze, "bundler/vendor/thor/lib/thor/shell.rb".freeze, "bundler/vendor/thor/lib/thor/shell/basic.rb".freeze, "bundler/vendor/thor/lib/thor/shell/color.rb".freeze, "bundler/vendor/thor/lib/thor/shell/html.rb".freeze, "bundler/vendor/thor/lib/thor/util.rb".freeze, "bundler/vendor/thor/lib/thor/version.rb".freeze, "bundler/vendor/tmpdir/lib/tmpdir.rb".freeze, "bundler/vendor/tsort/lib/tsort.rb".freeze, "bundler/vendor/uri/lib/uri.rb".freeze, "bundler/vendor/uri/lib/uri/common.rb".freeze, "bundler/vendor/uri/lib/uri/file.rb".freeze, "bundler/vendor/uri/lib/uri/ftp.rb".freeze, "bundler/vendor/uri/lib/uri/generic.rb".freeze, "bundler/vendor/uri/lib/uri/http.rb".freeze, "bundler/vendor/uri/lib/uri/https.rb".freeze, "bundler/vendor/uri/lib/uri/ldap.rb".freeze, "bundler/vendor/uri/lib/uri/ldaps.rb".freeze, "bundler/vendor/uri/lib/uri/mailto.rb".freeze, "bundler/vendor/uri/lib/uri/rfc2396_parser.rb".freeze, "bundler/vendor/uri/lib/uri/rfc3986_parser.rb".freeze, "bundler/vendor/uri/lib/uri/version.rb".freeze, "bundler/vendored_fileutils.rb".freeze, "bundler/vendored_molinillo.rb".freeze, "bundler/vendored_persistent.rb".freeze, "bundler/vendored_thor.rb".freeze, "bundler/vendored_tmpdir.rb".freeze, "bundler/vendored_tsort.rb".freeze, "bundler/vendored_uri.rb".freeze, "bundler/version.rb".freeze, "bundler/version_ranges.rb".freeze, "bundler/vlad.rb".freeze, "bundler/worker.rb".freeze, "bundler/yaml_serializer.rb".freeze, "libexec/bundle".freeze, "libexec/bundler".freeze]
  s.homepage = "https://bundler.io".freeze
  s.licenses = ["MIT".freeze]
  s.required_ruby_version = Gem::Requirement.new(">= 2.3.0".freeze)
  s.rubygems_version = "3.2.33".freeze
  s.summary = "The best way to manage your application's dependencies".freeze
end
# -*- encoding: utf-8 -*-
# stub: rake 13.0.3 ruby lib

Gem::Specification.new do |s|
  s.name = "rake".freeze
  s.version = "13.0.3"

  s.required_rubygems_version = Gem::Requirement.new(">= 1.3.2".freeze) if s.respond_to? :required_rubygems_version=
  s.metadata = { "bug_tracker_uri" => "https://github.com/ruby/rake/issues", "changelog_uri" => "https://github.com/ruby/rake/blob/v13.0.3/History.rdoc", "documentation_uri" => "https://ruby.github.io/rake", "source_code_uri" => "https://github.com/ruby/rake/tree/v13.0.3" } if s.respond_to? :metadata=
  s.require_paths = ["lib".freeze]
  s.authors = ["Hiroshi SHIBATA".freeze, "Eric Hodel".freeze, "Jim Weirich".freeze]
  s.bindir = "exe".freeze
  s.date = "2020-12-21"
  s.description = "Rake is a Make-like program implemented in Ruby. Tasks and dependencies are\nspecified in standard Ruby syntax.\nRake has the following features:\n  * Rakefiles (rake's version of Makefiles) are completely defined in standard Ruby syntax.\n    No XML files to edit. No quirky Makefile syntax to worry about (is that a tab or a space?)\n  * Users can specify tasks with prerequisites.\n  * Rake supports rule patterns to synthesize implicit tasks.\n  * Flexible FileLists that act like arrays but know about manipulating file names and paths.\n  * Supports parallel execution of tasks.\n".freeze
  s.email = ["hsbt@ruby-lang.org".freeze, "drbrain@segment7.net".freeze, "".freeze]
  s.executables = ["rake".freeze]
  s.files = ["exe/rake".freeze]
  s.homepage = "https://github.com/ruby/rake".freeze
  s.licenses = ["MIT".freeze]
  s.rdoc_options = ["--main".freeze, "README.rdoc".freeze]
  s.required_ruby_version = Gem::Requirement.new(">= 2.2".freeze)
  s.rubygems_version = "3.2.33".freeze
  s.summary = "Rake is a Make-like program implemented in Ruby".freeze

  s.installed_by_version = "3.2.33" if s.respond_to? :installed_by_version
end
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "GEMFILE" "5" "December 2021" "" ""
.
.SH "NAME"
\fBGemfile\fR \- A format for describing gem dependencies for Ruby programs
.
.SH "SYNOPSIS"
A \fBGemfile\fR describes the gem dependencies required to execute associated Ruby code\.
.
.P
Place the \fBGemfile\fR in the root of the directory containing the associated code\. For instance, in a Rails application, place the \fBGemfile\fR in the same directory as the \fBRakefile\fR\.
.
.SH "SYNTAX"
A \fBGemfile\fR is evaluated as Ruby code, in a context which makes available a number of methods used to describe the gem requirements\.
.
.SH "GLOBAL SOURCES"
At the top of the \fBGemfile\fR, add a line for the \fBRubygems\fR source that contains the gems listed in the \fBGemfile\fR\.
.
.IP "" 4
.
.nf

source "https://rubygems\.org"
.
.fi
.
.IP "" 0
.
.P
It is possible, but not recommended as of Bundler 1\.7, to add multiple global \fBsource\fR lines\. Each of these \fBsource\fRs \fBMUST\fR be a valid Rubygems repository\.
.
.P
Sources are checked for gems following the heuristics described in \fISOURCE PRIORITY\fR\. If a gem is found in more than one global source, Bundler will print a warning after installing the gem indicating which source was used, and listing the other sources where the gem is available\. A specific source can be selected for gems that need to use a non\-standard repository, suppressing this warning, by using the \fI\fB:source\fR option\fR or a \fI\fBsource\fR block\fR\.
.
.SS "CREDENTIALS"
Some gem sources require a username and password\. Use bundle config(1) \fIbundle\-config\.1\.html\fR to set the username and password for any of the sources that need it\. The command must be run once on each computer that will install the Gemfile, but this keeps the credentials from being stored in plain text in version control\.
.
.IP "" 4
.
.nf

bundle config gems\.example\.com user:password
.
.fi
.
.IP "" 0
.
.P
For some sources, like a company Gemfury account, it may be easier to include the credentials in the Gemfile as part of the source URL\.
.
.IP "" 4
.
.nf

source "https://user:password@gems\.example\.com"
.
.fi
.
.IP "" 0
.
.P
Credentials in the source URL will take precedence over credentials set using \fBconfig\fR\.
.
.SH "RUBY"
If your application requires a specific Ruby version or engine, specify your requirements using the \fBruby\fR method, with the following arguments\. All parameters are \fBOPTIONAL\fR unless otherwise specified\.
.
.SS "VERSION (required)"
The version of Ruby that your application requires\. If your application requires an alternate Ruby engine, such as JRuby, Rubinius or TruffleRuby, this should be the Ruby version that the engine is compatible with\.
.
.IP "" 4
.
.nf

ruby "1\.9\.3"
.
.fi
.
.IP "" 0
.
.SS "ENGINE"
Each application \fImay\fR specify a Ruby engine\. If an engine is specified, an engine version \fImust\fR also be specified\.
.
.P
What exactly is an Engine? \- A Ruby engine is an implementation of the Ruby language\.
.
.IP "\(bu" 4
For background: the reference or original implementation of the Ruby programming language is called Matz\'s Ruby Interpreter \fIhttps://en\.wikipedia\.org/wiki/Ruby_MRI\fR, or MRI for short\. This is named after Ruby creator Yukihiro Matsumoto, also known as Matz\. MRI is also known as CRuby, because it is written in C\. MRI is the most widely used Ruby engine\.
.
.IP "\(bu" 4
Other implementations \fIhttps://www\.ruby\-lang\.org/en/about/\fR of Ruby exist\. Some of the more well\-known implementations include Rubinius \fIhttps://rubinius\.com/\fR, and JRuby \fIhttp://jruby\.org/\fR\. Rubinius is an alternative implementation of Ruby written in Ruby\. JRuby is an implementation of Ruby on the JVM, short for Java Virtual Machine\.
.
.IP "" 0
.
.SS "ENGINE VERSION"
Each application \fImay\fR specify a Ruby engine version\. If an engine version is specified, an engine \fImust\fR also be specified\. If the engine is "ruby" the engine version specified \fImust\fR match the Ruby version\.
.
.IP "" 4
.
.nf

ruby "1\.8\.7", :engine => "jruby", :engine_version => "1\.6\.7"
.
.fi
.
.IP "" 0
.
.SS "PATCHLEVEL"
Each application \fImay\fR specify a Ruby patchlevel\.
.
.IP "" 4
.
.nf

ruby "2\.0\.0", :patchlevel => "247"
.
.fi
.
.IP "" 0
.
.SH "GEMS"
Specify gem requirements using the \fBgem\fR method, with the following arguments\. All parameters are \fBOPTIONAL\fR unless otherwise specified\.
.
.SS "NAME (required)"
For each gem requirement, list a single \fIgem\fR line\.
.
.IP "" 4
.
.nf

gem "nokogiri"
.
.fi
.
.IP "" 0
.
.SS "VERSION"
Each \fIgem\fR \fBMAY\fR have one or more version specifiers\.
.
.IP "" 4
.
.nf

gem "nokogiri", ">= 1\.4\.2"
gem "RedCloth", ">= 4\.1\.0", "< 4\.2\.0"
.
.fi
.
.IP "" 0
.
.SS "REQUIRE AS"
Each \fIgem\fR \fBMAY\fR specify files that should be used when autorequiring via \fBBundler\.require\fR\. You may pass an array with multiple files or \fBtrue\fR if the file you want \fBrequired\fR has the same name as \fIgem\fR or \fBfalse\fR to prevent any file from being autorequired\.
.
.IP "" 4
.
.nf

gem "redis", :require => ["redis/connection/hiredis", "redis"]
gem "webmock", :require => false
gem "byebug", :require => true
.
.fi
.
.IP "" 0
.
.P
The argument defaults to the name of the gem\. For example, these are identical:
.
.IP "" 4
.
.nf

gem "nokogiri"
gem "nokogiri", :require => "nokogiri"
gem "nokogiri", :require => true
.
.fi
.
.IP "" 0
.
.SS "GROUPS"
Each \fIgem\fR \fBMAY\fR specify membership in one or more groups\. Any \fIgem\fR that does not specify membership in any group is placed in the \fBdefault\fR group\.
.
.IP "" 4
.
.nf

gem "rspec", :group => :test
gem "wirble", :groups => [:development, :test]
.
.fi
.
.IP "" 0
.
.P
The Bundler runtime allows its two main methods, \fBBundler\.setup\fR and \fBBundler\.require\fR, to limit their impact to particular groups\.
.
.IP "" 4
.
.nf

# setup adds gems to Ruby\'s load path
Bundler\.setup                    # defaults to all groups
require "bundler/setup"          # same as Bundler\.setup
Bundler\.setup(:default)          # only set up the _default_ group
Bundler\.setup(:test)             # only set up the _test_ group (but `not` _default_)
Bundler\.setup(:default, :test)   # set up the _default_ and _test_ groups, but no others

# require requires all of the gems in the specified groups
Bundler\.require                  # defaults to the _default_ group
Bundler\.require(:default)        # identical
Bundler\.require(:default, :test) # requires the _default_ and _test_ groups
Bundler\.require(:test)           # requires the _test_ group
.
.fi
.
.IP "" 0
.
.P
The Bundler CLI allows you to specify a list of groups whose gems \fBbundle install\fR should not install with the \fBwithout\fR configuration\.
.
.P
To specify multiple groups to ignore, specify a list of groups separated by spaces\.
.
.IP "" 4
.
.nf

bundle config set \-\-local without test
bundle config set \-\-local without development test
.
.fi
.
.IP "" 0
.
.P
Also, calling \fBBundler\.setup\fR with no parameters, or calling \fBrequire "bundler/setup"\fR will setup all groups except for the ones you excluded via \fB\-\-without\fR (since they are not available)\.
.
.P
Note that on \fBbundle install\fR, bundler downloads and evaluates all gems, in order to create a single canonical list of all of the required gems and their dependencies\. This means that you cannot list different versions of the same gems in different groups\. For more details, see Understanding Bundler \fIhttps://bundler\.io/rationale\.html\fR\.
.
.SS "PLATFORMS"
If a gem should only be used in a particular platform or set of platforms, you can specify them\. Platforms are essentially identical to groups, except that you do not need to use the \fB\-\-without\fR install\-time flag to exclude groups of gems for other platforms\.
.
.P
There are a number of \fBGemfile\fR platforms:
.
.TP
\fBruby\fR
C Ruby (MRI), Rubinius or TruffleRuby, but \fBNOT\fR Windows
.
.TP
\fBmri\fR
Same as \fIruby\fR, but only C Ruby (MRI)
.
.TP
\fBmingw\fR
Windows 32 bit \'mingw32\' platform (aka RubyInstaller)
.
.TP
\fBx64_mingw\fR
Windows 64 bit \'mingw32\' platform (aka RubyInstaller x64)
.
.TP
\fBrbx\fR
Rubinius
.
.TP
\fBjruby\fR
JRuby
.
.TP
\fBtruffleruby\fR
TruffleRuby
.
.TP
\fBmswin\fR
Windows
.
.P
You can restrict further by platform and version for all platforms \fIexcept\fR for \fBrbx\fR, \fBjruby\fR, \fBtruffleruby\fR and \fBmswin\fR\.
.
.P
To specify a version in addition to a platform, append the version number without the delimiter to the platform\. For example, to specify that a gem should only be used on platforms with Ruby 2\.3, use:
.
.IP "" 4
.
.nf

ruby_23
.
.fi
.
.IP "" 0
.
.P
The full list of platforms and supported versions includes:
.
.TP
\fBruby\fR
1\.8, 1\.9, 2\.0, 2\.1, 2\.2, 2\.3, 2\.4, 2\.5, 2\.6
.
.TP
\fBmri\fR
1\.8, 1\.9, 2\.0, 2\.1, 2\.2, 2\.3, 2\.4, 2\.5, 2\.6
.
.TP
\fBmingw\fR
1\.8, 1\.9, 2\.0, 2\.1, 2\.2, 2\.3, 2\.4, 2\.5, 2\.6
.
.TP
\fBx64_mingw\fR
2\.0, 2\.1, 2\.2, 2\.3, 2\.4, 2\.5, 2\.6
.
.P
As with groups, you can specify one or more platforms:
.
.IP "" 4
.
.nf

gem "weakling",   :platforms => :jruby
gem "ruby\-debug", :platforms => :mri_18
gem "nokogiri",   :platforms => [:mri_18, :jruby]
.
.fi
.
.IP "" 0
.
.P
All operations involving groups (\fBbundle install\fR \fIbundle\-install\.1\.html\fR, \fBBundler\.setup\fR, \fBBundler\.require\fR) behave exactly the same as if any groups not matching the current platform were explicitly excluded\.
.
.SS "SOURCE"
You can select an alternate Rubygems repository for a gem using the \':source\' option\.
.
.IP "" 4
.
.nf

gem "some_internal_gem", :source => "https://gems\.example\.com"
.
.fi
.
.IP "" 0
.
.P
This forces the gem to be loaded from this source and ignores any global sources declared at the top level of the file\. If the gem does not exist in this source, it will not be installed\.
.
.P
Bundler will search for child dependencies of this gem by first looking in the source selected for the parent, but if they are not found there, it will fall back on global sources using the ordering described in \fISOURCE PRIORITY\fR\.
.
.P
Selecting a specific source repository this way also suppresses the ambiguous gem warning described above in \fIGLOBAL SOURCES (#source)\fR\.
.
.P
Using the \fB:source\fR option for an individual gem will also make that source available as a possible global source for any other gems which do not specify explicit sources\. Thus, when adding gems with explicit sources, it is recommended that you also ensure all other gems in the Gemfile are using explicit sources\.
.
.SS "GIT"
If necessary, you can specify that a gem is located at a particular git repository using the \fB:git\fR parameter\. The repository can be accessed via several protocols:
.
.TP
\fBHTTP(S)\fR
gem "rails", :git => "https://github\.com/rails/rails\.git"
.
.TP
\fBSSH\fR
gem "rails", :git => "git@github\.com:rails/rails\.git"
.
.TP
\fBgit\fR
gem "rails", :git => "git://github\.com/rails/rails\.git"
.
.P
If using SSH, the user that you use to run \fBbundle install\fR \fBMUST\fR have the appropriate keys available in their \fB$HOME/\.ssh\fR\.
.
.P
\fBNOTE\fR: \fBhttp://\fR and \fBgit://\fR URLs should be avoided if at all possible\. These protocols are unauthenticated, so a man\-in\-the\-middle attacker can deliver malicious code and compromise your system\. HTTPS and SSH are strongly preferred\.
.
.P
The \fBgroup\fR, \fBplatforms\fR, and \fBrequire\fR options are available and behave exactly the same as they would for a normal gem\.
.
.P
A git repository \fBSHOULD\fR have at least one file, at the root of the directory containing the gem, with the extension \fB\.gemspec\fR\. This file \fBMUST\fR contain a valid gem specification, as expected by the \fBgem build\fR command\.
.
.P
If a git repository does not have a \fB\.gemspec\fR, bundler will attempt to create one, but it will not contain any dependencies, executables, or C extension compilation instructions\. As a result, it may fail to properly integrate into your application\.
.
.P
If a git repository does have a \fB\.gemspec\fR for the gem you attached it to, a version specifier, if provided, means that the git repository is only valid if the \fB\.gemspec\fR specifies a version matching the version specifier\. If not, bundler will print a warning\.
.
.IP "" 4
.
.nf

gem "rails", "2\.3\.8", :git => "https://github\.com/rails/rails\.git"
# bundle install will fail, because the \.gemspec in the rails
# repository\'s master branch specifies version 3\.0\.0
.
.fi
.
.IP "" 0
.
.P
If a git repository does \fBnot\fR have a \fB\.gemspec\fR for the gem you attached it to, a version specifier \fBMUST\fR be provided\. Bundler will use this version in the simple \fB\.gemspec\fR it creates\.
.
.P
Git repositories support a number of additional options\.
.
.TP
\fBbranch\fR, \fBtag\fR, and \fBref\fR
You \fBMUST\fR only specify at most one of these options\. The default is \fB:branch => "master"\fR\. For example:
.
.IP
gem "rails", :git => "https://github\.com/rails/rails\.git", :branch => "5\-0\-stable"
.
.IP
gem "rails", :git => "https://github\.com/rails/rails\.git", :tag => "v5\.0\.0"
.
.IP
gem "rails", :git => "https://github\.com/rails/rails\.git", :ref => "4aded"
.
.TP
\fBsubmodules\fR
For reference, a git submodule \fIhttps://git\-scm\.com/book/en/v2/Git\-Tools\-Submodules\fR lets you have another git repository within a subfolder of your repository\. Specify \fB:submodules => true\fR to cause bundler to expand any submodules included in the git repository
.
.P
If a git repository contains multiple \fB\.gemspecs\fR, each \fB\.gemspec\fR represents a gem located at the same place in the file system as the \fB\.gemspec\fR\.
.
.IP "" 4
.
.nf

|~rails                   [git root]
| |\-rails\.gemspec         [rails gem located here]
|~actionpack
| |\-actionpack\.gemspec    [actionpack gem located here]
|~activesupport
| |\-activesupport\.gemspec [activesupport gem located here]
|\.\.\.
.
.fi
.
.IP "" 0
.
.P
To install a gem located in a git repository, bundler changes to the directory containing the gemspec, runs \fBgem build name\.gemspec\fR and then installs the resulting gem\. The \fBgem build\fR command, which comes standard with Rubygems, evaluates the \fB\.gemspec\fR in the context of the directory in which it is located\.
.
.SS "GIT SOURCE"
A custom git source can be defined via the \fBgit_source\fR method\. Provide the source\'s name as an argument, and a block which receives a single argument and interpolates it into a string to return the full repo address:
.
.IP "" 4
.
.nf

git_source(:stash){ |repo_name| "https://stash\.corp\.acme\.pl/#{repo_name}\.git" }
gem \'rails\', :stash => \'forks/rails\'
.
.fi
.
.IP "" 0
.
.P
In addition, if you wish to choose a specific branch:
.
.IP "" 4
.
.nf

gem "rails", :stash => "forks/rails", :branch => "branch_name"
.
.fi
.
.IP "" 0
.
.SS "GITHUB"
\fBNOTE\fR: This shorthand should be avoided until Bundler 2\.0, since it currently expands to an insecure \fBgit://\fR URL\. This allows a man\-in\-the\-middle attacker to compromise your system\.
.
.P
If the git repository you want to use is hosted on GitHub and is public, you can use the :github shorthand to specify the github username and repository name (without the trailing "\.git"), separated by a slash\. If both the username and repository name are the same, you can omit one\.
.
.IP "" 4
.
.nf

gem "rails", :github => "rails/rails"
gem "rails", :github => "rails"
.
.fi
.
.IP "" 0
.
.P
Are both equivalent to
.
.IP "" 4
.
.nf

gem "rails", :git => "git://github\.com/rails/rails\.git"
.
.fi
.
.IP "" 0
.
.P
Since the \fBgithub\fR method is a specialization of \fBgit_source\fR, it accepts a \fB:branch\fR named argument\.
.
.P
You can also directly pass a pull request URL:
.
.IP "" 4
.
.nf

gem "rails", :github => "https://github\.com/rails/rails/pull/43753"
.
.fi
.
.IP "" 0
.
.P
Which is equivalent to:
.
.IP "" 4
.
.nf

gem "rails", :github => "rails/rails", branch: "refs/pull/43753/head"
.
.fi
.
.IP "" 0
.
.SS "GIST"
If the git repository you want to use is hosted as a Github Gist and is public, you can use the :gist shorthand to specify the gist identifier (without the trailing "\.git")\.
.
.IP "" 4
.
.nf

gem "the_hatch", :gist => "4815162342"
.
.fi
.
.IP "" 0
.
.P
Is equivalent to:
.
.IP "" 4
.
.nf

gem "the_hatch", :git => "https://gist\.github\.com/4815162342\.git"
.
.fi
.
.IP "" 0
.
.P
Since the \fBgist\fR method is a specialization of \fBgit_source\fR, it accepts a \fB:branch\fR named argument\.
.
.SS "BITBUCKET"
If the git repository you want to use is hosted on Bitbucket and is public, you can use the :bitbucket shorthand to specify the bitbucket username and repository name (without the trailing "\.git"), separated by a slash\. If both the username and repository name are the same, you can omit one\.
.
.IP "" 4
.
.nf

gem "rails", :bitbucket => "rails/rails"
gem "rails", :bitbucket => "rails"
.
.fi
.
.IP "" 0
.
.P
Are both equivalent to
.
.IP "" 4
.
.nf

gem "rails", :git => "https://rails@bitbucket\.org/rails/rails\.git"
.
.fi
.
.IP "" 0
.
.P
Since the \fBbitbucket\fR method is a specialization of \fBgit_source\fR, it accepts a \fB:branch\fR named argument\.
.
.SS "PATH"
You can specify that a gem is located in a particular location on the file system\. Relative paths are resolved relative to the directory containing the \fBGemfile\fR\.
.
.P
Similar to the semantics of the \fB:git\fR option, the \fB:path\fR option requires that the directory in question either contains a \fB\.gemspec\fR for the gem, or that you specify an explicit version that bundler should use\.
.
.P
Unlike \fB:git\fR, bundler does not compile C extensions for gems specified as paths\.
.
.IP "" 4
.
.nf

gem "rails", :path => "vendor/rails"
.
.fi
.
.IP "" 0
.
.P
If you would like to use multiple local gems directly from the filesystem, you can set a global \fBpath\fR option to the path containing the gem\'s files\. This will automatically load gemspec files from subdirectories\.
.
.IP "" 4
.
.nf

path \'components\' do
  gem \'admin_ui\'
  gem \'public_ui\'
end
.
.fi
.
.IP "" 0
.
.SH "BLOCK FORM OF SOURCE, GIT, PATH, GROUP and PLATFORMS"
The \fB:source\fR, \fB:git\fR, \fB:path\fR, \fB:group\fR, and \fB:platforms\fR options may be applied to a group of gems by using block form\.
.
.IP "" 4
.
.nf

source "https://gems\.example\.com" do
  gem "some_internal_gem"
  gem "another_internal_gem"
end

git "https://github\.com/rails/rails\.git" do
  gem "activesupport"
  gem "actionpack"
end

platforms :ruby do
  gem "ruby\-debug"
  gem "sqlite3"
end

group :development, :optional => true do
  gem "wirble"
  gem "faker"
end
.
.fi
.
.IP "" 0
.
.P
In the case of the group block form the :optional option can be given to prevent a group from being installed unless listed in the \fB\-\-with\fR option given to the \fBbundle install\fR command\.
.
.P
In the case of the \fBgit\fR block form, the \fB:ref\fR, \fB:branch\fR, \fB:tag\fR, and \fB:submodules\fR options may be passed to the \fBgit\fR method, and all gems in the block will inherit those options\.
.
.P
The presence of a \fBsource\fR block in a Gemfile also makes that source available as a possible global source for any other gems which do not specify explicit sources\. Thus, when defining source blocks, it is recommended that you also ensure all other gems in the Gemfile are using explicit sources, either via source blocks or \fB:source\fR directives on individual gems\.
.
.SH "INSTALL_IF"
The \fBinstall_if\fR method allows gems to be installed based on a proc or lambda\. This is especially useful for optional gems that can only be used if certain software is installed or some other conditions are met\.
.
.IP "" 4
.
.nf

install_if \-> { RUBY_PLATFORM =~ /darwin/ } do
  gem "pasteboard"
end
.
.fi
.
.IP "" 0
.
.SH "GEMSPEC"
The \fB\.gemspec\fR \fIhttp://guides\.rubygems\.org/specification\-reference/\fR file is where you provide metadata about your gem to Rubygems\. Some required Gemspec attributes include the name, description, and homepage of your gem\. This is also where you specify the dependencies your gem needs to run\.
.
.P
If you wish to use Bundler to help install dependencies for a gem while it is being developed, use the \fBgemspec\fR method to pull in the dependencies listed in the \fB\.gemspec\fR file\.
.
.P
The \fBgemspec\fR method adds any runtime dependencies as gem requirements in the default group\. It also adds development dependencies as gem requirements in the \fBdevelopment\fR group\. Finally, it adds a gem requirement on your project (\fB:path => \'\.\'\fR)\. In conjunction with \fBBundler\.setup\fR, this allows you to require project files in your test code as you would if the project were installed as a gem; you need not manipulate the load path manually or require project files via relative paths\.
.
.P
The \fBgemspec\fR method supports optional \fB:path\fR, \fB:glob\fR, \fB:name\fR, and \fB:development_group\fR options, which control where bundler looks for the \fB\.gemspec\fR, the glob it uses to look for the gemspec (defaults to: "{,\fI,\fR/*}\.gemspec"), what named \fB\.gemspec\fR it uses (if more than one is present), and which group development dependencies are included in\.
.
.P
When a \fBgemspec\fR dependency encounters version conflicts during resolution, the local version under development will always be selected \-\- even if there are remote versions that better match other requirements for the \fBgemspec\fR gem\.
.
.SH "SOURCE PRIORITY"
When attempting to locate a gem to satisfy a gem requirement, bundler uses the following priority order:
.
.IP "1." 4
The source explicitly attached to the gem (using \fB:source\fR, \fB:path\fR, or \fB:git\fR)
.
.IP "2." 4
For implicit gems (dependencies of explicit gems), any source, git, or path repository declared on the parent\. This results in bundler prioritizing the ActiveSupport gem from the Rails git repository over ones from \fBrubygems\.org\fR
.
.IP "3." 4
The sources specified via global \fBsource\fR lines, searching each source in your \fBGemfile\fR from last added to first added\.
.
.IP "" 0

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-DOCTOR" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-doctor\fR \- Checks the bundle for common problems
.
.SH "SYNOPSIS"
\fBbundle doctor\fR [\-\-quiet] [\-\-gemfile=GEMFILE]
.
.SH "DESCRIPTION"
Checks your Gemfile and gem environment for common problems\. If issues are detected, Bundler prints them and exits status 1\. Otherwise, Bundler prints a success message and exits status 0\.
.
.P
Examples of common problems caught by bundle\-doctor include:
.
.IP "\(bu" 4
Invalid Bundler settings
.
.IP "\(bu" 4
Mismatched Ruby versions
.
.IP "\(bu" 4
Mismatched platforms
.
.IP "\(bu" 4
Uninstalled gems
.
.IP "\(bu" 4
Missing dependencies
.
.IP "" 0
.
.SH "OPTIONS"
.
.TP
\fB\-\-quiet\fR
Only output warnings and errors\.
.
.TP
\fB\-\-gemfile=<gemfile>\fR
The location of the Gemfile(5) which Bundler should use\. This defaults to a Gemfile(5) in the current working directory\. In general, Bundler will assume that the location of the Gemfile(5) is also the project\'s root and will try to find \fBGemfile\.lock\fR and \fBvendor/cache\fR relative to this location\.

.\"Ruby is copyrighted by Yukihiro Matsumoto <matz@netlab.jp>.
.Dd April 14, 2018
.Dt RUBY \&1 "Ruby Programmer's Reference Guide"
.Os UNIX
.Sh NAME
.Nm ruby
.Nd Interpreted object-oriented scripting language
.Sh SYNOPSIS
.Nm
.Op Fl -copyright
.Op Fl -version
.Op Fl SUacdlnpswvy
.Op Fl 0 Ns Op Ar octal
.Op Fl C Ar directory
.Op Fl E Ar external Ns Op : Ns Ar internal
.Op Fl F Ns Op Ar pattern
.Op Fl I Ar directory
.Op Fl K Ns Op Ar c
.Op Fl T Ns Op Ar level
.Op Fl W Ns Op Ar level
.Op Fl e Ar command
.Op Fl i Ns Op Ar extension
.Op Fl r Ar library
.Op Fl x Ns Op Ar directory
.Op Fl - Ns Bro Cm enable Ns | Ns Cm disable Brc Ns - Ns Ar FEATURE
.Op Fl -dump Ns = Ns Ar target
.Op Fl -verbose
.Op Fl -
.Op Ar program_file
.Op Ar argument ...
.Sh DESCRIPTION
Ruby is an interpreted scripting language for quick and easy
object-oriented programming.  It has many features to process text
files and to do system management tasks (like in Perl).  It is simple,
straight-forward, and extensible.
.Pp
If you want a language for easy object-oriented programming, or you
don't like the Perl ugliness, or you do like the concept of LISP, but
don't like too many parentheses, Ruby might be your language of
choice.
.Sh FEATURES
Ruby's features are as follows:
.Bl -tag -width 6n
.It Sy "Interpretive"
Ruby is an interpreted language, so you don't have to recompile
programs written in Ruby to execute them.
.Pp
.It Sy "Variables have no type (dynamic typing)"
Variables in Ruby can contain data of any type.  You don't have to
worry about variable typing.  Consequently, it has a weaker compile
time check.
.Pp
.It Sy "No declaration needed"
You can use variables in your Ruby programs without any declarations.
Variable names denote their scope - global, class, instance, or local.
.Pp
.It Sy "Simple syntax"
Ruby has a simple syntax influenced slightly from Eiffel.
.Pp
.It Sy "No user-level memory management"
Ruby has automatic memory management.  Objects no longer referenced
from anywhere are automatically collected by the garbage collector
built into the interpreter.
.Pp
.It Sy "Everything is an object"
Ruby is a purely object-oriented language, and was so since its
creation.  Even such basic data as integers are seen as objects.
.Pp
.It Sy "Class, inheritance, and methods"
Being an object-oriented language, Ruby naturally has basic
features like classes, inheritance, and methods.
.Pp
.It Sy "Singleton methods"
Ruby has the ability to define methods for certain objects.  For
example, you can define a press-button action for certain widget by
defining a singleton method for the button.  Or, you can make up your
own prototype based object system using singleton methods, if you want
to.
.Pp
.It Sy "Mix-in by modules"
Ruby intentionally does not have the multiple inheritance as it is a
source of confusion.  Instead, Ruby has the ability to share
implementations across the inheritance tree.  This is often called a
.Sq Mix-in .
.Pp
.It Sy "Iterators"
Ruby has iterators for loop abstraction.
.Pp
.It Sy "Closures"
In Ruby, you can objectify the procedure.
.Pp
.It Sy "Text processing and regular expressions"
Ruby has a bunch of text processing features like in Perl.
.Pp
.It Sy "M17N, character set independent"
Ruby supports multilingualized programming. Easy to process texts
written in many different natural languages and encoded in many
different character encodings, without dependence on Unicode.
.Pp
.It Sy "Bignums"
With built-in bignums, you can for example calculate factorial(400).
.Pp
.It Sy "Reflection and domain specific languages"
Class is also an instance of the Class class. Definition of classes and methods
is an expression just as 1+1 is. So your programs can even write and modify programs.
Thus you can write your application in your own programming language on top of Ruby.
.Pp
.It Sy "Exception handling"
As in Java(tm).
.Pp
.It Sy "Direct access to the OS"
Ruby can use most
.Ux
system calls, often used in system programming.
.Pp
.It Sy "Dynamic loading"
On most
.Ux
systems, you can load object files into the Ruby interpreter
on-the-fly.
.It Sy "Rich libraries"
In addition to the
.Dq builtin libraries
and
.Dq standard libraries
that are bundled with Ruby, a vast amount of third-party libraries
.Pq Dq gems
are available via the package management system called
.Sq RubyGems ,
namely the
.Xr gem 1
command.  Visit RubyGems.org
.Pq Lk https://rubygems.org/
to find the gems you need, and explore GitHub
.Pq Lk https://github.com/
to see how they are being developed and used.
.El
.Pp
.Sh OPTIONS
The Ruby interpreter accepts the following command-line options (switches).
They are quite similar to those of
.Xr perl 1 .
.Bl -tag -width "1234567890123" -compact
.Pp
.It Fl -copyright
Prints the copyright notice, and quits immediately without running any
script.
.Pp
.It Fl -version
Prints the version of the Ruby interpreter, and quits immediately without
running any script.
.Pp
.It Fl 0 Ns Op Ar octal
(The digit
.Dq zero . )
Specifies the input record separator
.Pf ( Li "$/" )
as an octal number. If no digit is given, the null character is taken
as the separator.  Other switches may follow the digits.
.Fl 00
turns Ruby into paragraph mode.
.Fl 0777
makes Ruby read whole file at once as a single string since there is
no legal character with that value.
.Pp
.It Fl C Ar directory
.It Fl X Ar directory
Causes Ruby to switch to the directory.
.Pp
.It Fl E Ar external Ns Op : Ns Ar internal
.It Fl -encoding Ar external Ns Op : Ns Ar internal
Specifies the default value(s) for external encodings and internal encoding. Values should be separated with colon (:).
.Pp
You can omit the one for internal encodings, then the value
.Pf ( Li "Encoding.default_internal" ) will be nil.
.Pp
.It Fl -external-encoding Ns = Ns Ar encoding
.It Fl -internal-encoding Ns = Ns Ar encoding
Specify the default external or internal character encoding
.Pp
.It Fl F Ar pattern
Specifies input field separator
.Pf ( Li "$;" ) .
.Pp
.It Fl I Ar directory
Used to tell Ruby where to load the library scripts.  Directory path
will be added to the load-path variable
.Pf ( Li "$:" ) .
.Pp
.It Fl K Ar kcode
Specifies KANJI (Japanese) encoding. The default value for script encodings
.Pf ( Li "__ENCODING__" ) and external encodings ( Li "Encoding.default_external" ) will be the specified one.
.Ar kcode
can be one of
.Bl -hang -offset indent
.It Sy e
EUC-JP
.Pp
.It Sy s
Windows-31J (CP932)
.Pp
.It Sy u
UTF-8
.Pp
.It Sy n
ASCII-8BIT (BINARY)
.El
.Pp
.It Fl S
Makes Ruby use the
.Ev PATH
environment variable to search for script, unless its name begins
with a slash.  This is used to emulate
.Li #!
on machines that don't support it, in the following manner:
.Bd -literal -offset indent
#! /usr/local/bin/ruby
# This line makes the next one a comment in Ruby \e
  exec /usr/local/bin/ruby -S $0 $*
.Ed
.Pp
On some systems
.Li "$0"
does not always contain the full pathname, so you need the
.Fl S
switch to tell Ruby to search for the script if necessary (to handle embedded
spaces and such).  A better construct than
.Li "$*"
would be
.Li ${1+"$@"} ,
but it does not work if the script is being interpreted by
.Xr csh 1 .
.Pp
.It Fl T Ns Op Ar level=1
Turns on taint checks at the specified level (default 1).
.Pp
.It Fl U
Sets the default value for internal encodings
.Pf ( Li "Encoding.default_internal" ) to UTF-8.
.Pp
.It Fl W Ns Op Ar level=2
Turns on verbose mode at the specified level without printing the version
message at the beginning. The level can be;
.Bl -hang -offset indent
.It Sy 0
Verbose mode is "silence". It sets the
.Li "$VERBOSE"
to nil.
.Pp
.It Sy 1
Verbose mode is "medium". It sets the
.Li "$VERBOSE"
to false.
.Pp
.It Sy 2 (default)
Verbose mode is "verbose". It sets the
.Li "$VERBOSE"
to true.
.Fl W Ns
2 is same as
.Fl w
.
.El
.Pp
.It Fl a
Turns on auto-split mode when used with
.Fl n
or
.Fl p .
In auto-split mode, Ruby executes
.Dl $F = $_.split
at beginning of each loop.
.Pp
.It Fl c
Causes Ruby to check the syntax of the script and exit without
executing. If there are no syntax errors, Ruby will print
.Dq Syntax OK
to the standard output.
.Pp
.It Fl d
.It Fl -debug
Turns on debug mode.
.Li "$DEBUG"
will be set to true.
.Pp
.It Fl e Ar command
Specifies script from command-line while telling Ruby not to search
the rest of the arguments for a script file name.
.Pp
.It Fl h
.It Fl -help
Prints a summary of the options.
.Pp
.It Fl i Ar extension
Specifies in-place-edit mode.  The extension, if specified, is added
to old file name to make a backup copy.  For example:
.Bd -literal -offset indent
% echo matz > /tmp/junk
% cat /tmp/junk
matz
% ruby -p -i.bak -e '$_.upcase!' /tmp/junk
% cat /tmp/junk
MATZ
% cat /tmp/junk.bak
matz
.Ed
.Pp
.It Fl l
(The lowercase letter
.Dq ell . )
Enables automatic line-ending processing, which means to firstly set
.Li "$\e"
to the value of
.Li "$/" ,
and secondly chops every line read using
.Li chomp! .
.Pp
.It Fl n
Causes Ruby to assume the following loop around your script, which
makes it iterate over file name arguments somewhat like
.Nm sed
.Fl n
or
.Nm awk .
.Bd -literal -offset indent
while gets
  ...
end
.Ed
.Pp
.It Fl p
Acts mostly same as -n switch, but print the value of variable
.Li "$_"
at the each end of the loop.  For example:
.Bd -literal -offset indent
% echo matz | ruby -p -e '$_.tr! "a-z", "A-Z"'
MATZ
.Ed
.Pp
.It Fl r Ar library
Causes Ruby to load the library using require.  It is useful when using
.Fl n
or
.Fl p .
.Pp
.It Fl s
Enables some switch parsing for switches after script name but before
any file name arguments (or before a
.Fl - ) .
Any switches found there are removed from
.Li ARGV
and set the corresponding variable in the script.  For example:
.Bd -literal -offset indent
#! /usr/local/bin/ruby -s
# prints "true" if invoked with `-xyz' switch.
print "true\en" if $xyz
.Ed
.Pp
.It Fl v
Enables verbose mode.  Ruby will print its version at the beginning
and set the variable
.Li "$VERBOSE"
to true.  Some methods print extra messages if this variable is true.
If this switch is given, and no other switches are present, Ruby quits
after printing its version.
.Pp
.It Fl w
Enables verbose mode without printing version message at the
beginning.  It sets the
.Li "$VERBOSE"
variable to true.
.Pp
.It Fl x Ns Op Ar directory
Tells Ruby that the script is embedded in a message.  Leading garbage
will be discarded until the first line that starts with
.Dq #!
and contains the string,
.Dq ruby .
Any meaningful switches on that line will be applied.  The end of the script
must be specified with either
.Li EOF ,
.Li "^D" ( Li "control-D" ) ,
.Li "^Z" ( Li "control-Z" ) ,
or the reserved word
.Li __END__ .
If the directory name is specified, Ruby will switch to that directory
before executing script.
.Pp
.It Fl y
.It Fl -yydebug
DO NOT USE.
.Pp
Turns on compiler debug mode.  Ruby will print a bunch of internal
state messages during compilation.  Only specify this switch you are going to
debug the Ruby interpreter.
.Pp
.It Fl -disable- Ns Ar FEATURE
.It Fl -enable- Ns Ar FEATURE
Disables (or enables) the specified
.Ar FEATURE .
.Bl -tag -width "--disable-rubyopt" -compact
.It Fl -disable-gems
.It Fl -enable-gems
Disables (or enables) RubyGems libraries.  By default, Ruby will load the latest
version of each installed gem. The
.Li Gem
constant is true if RubyGems is enabled, false if otherwise.
.Pp
.It Fl -disable-rubyopt
.It Fl -enable-rubyopt
Ignores (or considers) the
.Ev RUBYOPT
environment variable. By default, Ruby considers the variable.
.Pp
.It Fl -disable-all
.It Fl -enable-all
Disables (or enables) all features.
.Pp
.El
.Pp
.It Fl -dump Ns = Ns Ar target
Dump some information.
.Pp
Prints the specified target.
.Ar target
can be one of;
.Bl -hang -offset indent
.It Sy version
version description same as
.Fl -version
.It Sy usage
brief usage message same as
.Fl h
.It Sy help
Show long help message same as
.Fl -help
.It Sy syntax
check of syntax same as
.Fl c
.Fl -yydebug
.It Sy yydebug
compiler debug mode, same as
.Fl -yydebug
.Pp
Only specify this switch if you are going to debug the Ruby interpreter.
.It Sy parsetree
.It Sy parsetree_with_comment
AST nodes tree
.Pp
Only specify this switch if you are going to debug the Ruby interpreter.
.It Sy insns
disassembled instructions
.Pp
Only specify this switch if you are going to debug the Ruby interpreter.
.El
.Pp
.It Fl -verbose
Enables verbose mode without printing version message at the
beginning.  It sets the
.Li "$VERBOSE"
variable to true.
If this switch is given, and no script arguments (script file or
.Fl e
options) are present, Ruby quits immediately.
.El
.Pp
.Sh ENVIRONMENT
.Bl -tag -width "RUBYSHELL" -compact
.It Ev RUBYLIB
A colon-separated list of directories that are added to Ruby's
library load path
.Pf ( Li "$:" ) . Directories from this environment variable are searched
before the standard load path is searched.
.Pp
e.g.:
.Dl RUBYLIB="$HOME/lib/ruby:$HOME/lib/rubyext"
.Pp
.It Ev RUBYOPT
Additional Ruby options.
.Pp
e.g.
.Dl RUBYOPT="-w -Ke"
.Pp
Note that RUBYOPT can contain only
.Fl d , Fl E , Fl I , Fl K , Fl r , Fl T , Fl U , Fl v , Fl w , Fl W, Fl -debug ,
.Fl -disable- Ns Ar FEATURE
and
.Fl -enable- Ns Ar FEATURE .
.Pp
.It Ev RUBYPATH
A colon-separated list of directories that Ruby searches for
Ruby programs when the
.Fl S
flag is specified.  This variable precedes the
.Ev PATH
environment variable.
.Pp
.It Ev RUBYSHELL
The path to the system shell command.  This environment variable is
enabled for only mswin32, mingw32, and OS/2 platforms.  If this
variable is not defined, Ruby refers to
.Ev COMSPEC .
.Pp
.It Ev PATH
Ruby refers to the
.Ev PATH
environment variable on calling Kernel#system.
.El
.Pp
And Ruby depends on some RubyGems related environment variables unless RubyGems is disabled.
See the help of
.Xr gem 1
as below.
.Bd -literal -offset indent
% gem help
.Ed
.Pp
.Sh GC ENVIRONMENT
The Ruby garbage collector (GC) tracks objects in fixed-sized slots,
but each object may have auxiliary memory allocations handled by the
malloc family of C standard library calls (
.Xr malloc 3 ,
.Xr calloc 3 ,
and
.Xr realloc 3 ) .
In this documentatation, the "heap" refers to the Ruby object heap
of fixed-sized slots, while "malloc" refers to auxiliary
allocations commonly referred to as the "process heap".
Thus there are at least two possible ways to trigger GC:
.Bl -hang -offset indent
.It Sy 1
Reaching the object limit.
.It Sy 2
Reaching the malloc limit.
.Pp
.El
In Ruby 2.1, the generational GC was introduced and the limits are divided
into young and old generations, providing two additional ways to trigger
a GC:
.Bl -hang -offset indent
.It Sy 3
Reaching the old object limit.
.It Sy 4
Reaching the old malloc limit.
.El
.Pp
There are currently 4 possible areas where the GC may be tuned by
the following 11 environment variables:
.Bl -hang -compact -width "RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR"
.It Ev RUBY_GC_HEAP_INIT_SLOTS
Initial allocation slots.  Introduced in Ruby 2.1, default: 10000.
.Pp
.It Ev RUBY_GC_HEAP_FREE_SLOTS
Prepare at least this amount of slots after GC.
Allocate this number slots if there are not enough slots.
Introduced in Ruby 2.1, default: 4096
.Pp
.It Ev RUBY_GC_HEAP_GROWTH_FACTOR
Increase allocation rate of heap slots by this factor.
Introduced in Ruby 2.1, default: 1.8, minimum: 1.0 (no growth)
.Pp
.It Ev RUBY_GC_HEAP_GROWTH_MAX_SLOTS
Allocation rate is limited to this number of slots,
preventing excessive allocation due to RUBY_GC_HEAP_GROWTH_FACTOR.
Introduced in Ruby 2.1, default: 0 (no limit)
.Pp
.It Ev RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR
Perform a full GC when the number of old objects is more than R * N,
where R is this factor and N is the number of old objects after the
last full GC.
Introduced in Ruby 2.1.1, default: 2.0
.Pp
.It Ev RUBY_GC_MALLOC_LIMIT
The initial limit of young generation allocation from the malloc-family.
GC will start when this limit is reached.
Default: 16MB
.Pp
.It Ev RUBY_GC_MALLOC_LIMIT_MAX
The maximum limit of young generation allocation from malloc before GC starts.
Prevents excessive malloc growth due to RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR.
Introduced in Ruby 2.1, default: 32MB.
.Pp
.It Ev RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR
Increases the limit of young generation malloc calls, reducing
GC frequency but increasing malloc growth until RUBY_GC_MALLOC_LIMIT_MAX
is reached.
Introduced in Ruby 2.1, default: 1.4, minimum: 1.0 (no growth)
.Pp
.It Ev RUBY_GC_OLDMALLOC_LIMIT
The initial limit of old generation allocation from malloc,
a full GC will start when this limit is reached.
Introduced in Ruby 2.1, default: 16MB
.Pp
.It Ev RUBY_GC_OLDMALLOC_LIMIT_MAX
The maximum limit of old generation allocation from malloc before a
full GC starts.
Prevents excessive malloc growth due to RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR.
Introduced in Ruby 2.1, default: 128MB
.Pp
.It Ev RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR
Increases the limit of old generation malloc allocation, reducing full
GC frequency but increasing malloc growth until RUBY_GC_OLDMALLOC_LIMIT_MAX
is reached.
Introduced in Ruby 2.1, default: 1.2, minimum: 1.0 (no growth)
.Pp
.El
.Sh STACK SIZE ENVIRONMENT
Stack size environment variables are implementation-dependent and
subject to change with different versions of Ruby.  The VM stack is used
for pure-Ruby code and managed by the virtual machine.  Machine stack is
used by the operating system and its usage is dependent on C extensions
as well as C compiler options.  Using lower values for these may allow
applications to keep more Fibers or Threads running; but increases the
chance of SystemStackError exceptions and segmentation faults (SIGSEGV).
These environment variables are available since Ruby 2.0.0.
All values are specified in bytes.
.Pp
.Bl -hang -compact -width "RUBY_THREAD_MACHINE_STACK_SIZE"
.It Ev RUBY_THREAD_VM_STACK_SIZE
VM stack size used at thread creation.
default: 131072 (32-bit CPU) or 262144 (64-bit)
.Pp
.It Ev RUBY_THREAD_MACHINE_STACK_SIZE
Machine stack size used at thread creation.
default: 524288 or 1048575
.Pp
.It Ev RUBY_FIBER_VM_STACK_SIZE
VM stack size used at fiber creation.
default: 65536 or 131072
.Pp
.It Ev RUBY_FIBER_MACHINE_STACK_SIZE
Machine stack size used at fiber creation.
default: 262144 or 524288
.Pp
.El
.Sh SEE ALSO
.Bl -hang -compact -width "https://www.ruby-toolbox.com/"
.It Lk https://www.ruby-lang.org/
The official web site.
.It Lk https://www.ruby-toolbox.com/
Comprehensive catalog of Ruby libraries.
.El
.Pp
.Sh REPORTING BUGS
.Bl -bullet
.It
Security vulnerabilities should be reported via an email to
.Mt security@ruby-lang.org .
Reported problems will be published after being fixed.
.Pp
.It
Other bugs and feature requests can be reported via the
Ruby Issue Tracking System
.Pq Lk https://bugs.ruby-lang.org/ .
Do not report security vulnerabilities
via this system because it publishes the vulnerabilities immediately.
.El
.Sh AUTHORS
Ruby is designed and implemented by
.An Yukihiro Matsumoto Aq matz@netlab.jp .
.Pp
See
.Aq Lk https://bugs.ruby-lang.org/projects/ruby/wiki/Contributors
for contributors to Ruby.
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-UPDATE" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-update\fR \- Update your gems to the latest available versions
.
.SH "SYNOPSIS"
\fBbundle update\fR \fI*gems\fR [\-\-all] [\-\-group=NAME] [\-\-source=NAME] [\-\-local] [\-\-ruby] [\-\-bundler[=VERSION]] [\-\-full\-index] [\-\-jobs=JOBS] [\-\-quiet] [\-\-patch|\-\-minor|\-\-major] [\-\-redownload] [\-\-strict] [\-\-conservative]
.
.SH "DESCRIPTION"
Update the gems specified (all gems, if \fB\-\-all\fR flag is used), ignoring the previously installed gems specified in the \fBGemfile\.lock\fR\. In general, you should use bundle install(1) \fIbundle\-install\.1\.html\fR to install the same exact gems and versions across machines\.
.
.P
You would use \fBbundle update\fR to explicitly update the version of a gem\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-all\fR
Update all gems specified in Gemfile\.
.
.TP
\fB\-\-group=<name>\fR, \fB\-g=[<name>]\fR
Only update the gems in the specified group\. For instance, you can update all gems in the development group with \fBbundle update \-\-group development\fR\. You can also call \fBbundle update rails \-\-group test\fR to update the rails gem and all gems in the test group, for example\.
.
.TP
\fB\-\-source=<name>\fR
The name of a \fB:git\fR or \fB:path\fR source used in the Gemfile(5)\. For instance, with a \fB:git\fR source of \fBhttp://github\.com/rails/rails\.git\fR, you would call \fBbundle update \-\-source rails\fR
.
.TP
\fB\-\-local\fR
Do not attempt to fetch gems remotely and use the gem cache instead\.
.
.TP
\fB\-\-ruby\fR
Update the locked version of Ruby to the current version of Ruby\.
.
.TP
\fB\-\-bundler\fR
Update the locked version of bundler to the invoked bundler version\.
.
.TP
\fB\-\-full\-index\fR
Fall back to using the single\-file index of all gems\.
.
.TP
\fB\-\-jobs=[<number>]\fR, \fB\-j[<number>]\fR
Specify the number of jobs to run in parallel\. The default is \fB1\fR\.
.
.TP
\fB\-\-retry=[<number>]\fR
Retry failed network or git requests for \fInumber\fR times\.
.
.TP
\fB\-\-quiet\fR
Only output warnings and errors\.
.
.TP
\fB\-\-redownload\fR
Force downloading every gem\.
.
.TP
\fB\-\-patch\fR
Prefer updating only to next patch version\.
.
.TP
\fB\-\-minor\fR
Prefer updating only to next minor version\.
.
.TP
\fB\-\-major\fR
Prefer updating to next major version (default)\.
.
.TP
\fB\-\-strict\fR
Do not allow any gem to be updated past latest \fB\-\-patch\fR | \fB\-\-minor\fR | \fB\-\-major\fR\.
.
.TP
\fB\-\-conservative\fR
Use bundle install conservative update behavior and do not allow indirect dependencies to be updated\.
.
.SH "UPDATING ALL GEMS"
If you run \fBbundle update \-\-all\fR, bundler will ignore any previously installed gems and resolve all dependencies again based on the latest versions of all gems available in the sources\.
.
.P
Consider the following Gemfile(5):
.
.IP "" 4
.
.nf

source "https://rubygems\.org"

gem "rails", "3\.0\.0\.rc"
gem "nokogiri"
.
.fi
.
.IP "" 0
.
.P
When you run bundle install(1) \fIbundle\-install\.1\.html\fR the first time, bundler will resolve all of the dependencies, all the way down, and install what you need:
.
.IP "" 4
.
.nf

Fetching gem metadata from https://rubygems\.org/\.\.\.\.\.\.\.\.\.
Resolving dependencies\.\.\.
Installing builder 2\.1\.2
Installing abstract 1\.0\.0
Installing rack 1\.2\.8
Using bundler 1\.7\.6
Installing rake 10\.4\.0
Installing polyglot 0\.3\.5
Installing mime\-types 1\.25\.1
Installing i18n 0\.4\.2
Installing mini_portile 0\.6\.1
Installing tzinfo 0\.3\.42
Installing rack\-mount 0\.6\.14
Installing rack\-test 0\.5\.7
Installing treetop 1\.4\.15
Installing thor 0\.14\.6
Installing activesupport 3\.0\.0\.rc
Installing erubis 2\.6\.6
Installing activemodel 3\.0\.0\.rc
Installing arel 0\.4\.0
Installing mail 2\.2\.20
Installing activeresource 3\.0\.0\.rc
Installing actionpack 3\.0\.0\.rc
Installing activerecord 3\.0\.0\.rc
Installing actionmailer 3\.0\.0\.rc
Installing railties 3\.0\.0\.rc
Installing rails 3\.0\.0\.rc
Installing nokogiri 1\.6\.5

Bundle complete! 2 Gemfile dependencies, 26 gems total\.
Use `bundle show [gemname]` to see where a bundled gem is installed\.
.
.fi
.
.IP "" 0
.
.P
As you can see, even though you have two gems in the Gemfile(5), your application needs 26 different gems in order to run\. Bundler remembers the exact versions it installed in \fBGemfile\.lock\fR\. The next time you run bundle install(1) \fIbundle\-install\.1\.html\fR, bundler skips the dependency resolution and installs the same gems as it installed last time\.
.
.P
After checking in the \fBGemfile\.lock\fR into version control and cloning it on another machine, running bundle install(1) \fIbundle\-install\.1\.html\fR will \fIstill\fR install the gems that you installed last time\. You don\'t need to worry that a new release of \fBerubis\fR or \fBmail\fR changes the gems you use\.
.
.P
However, from time to time, you might want to update the gems you are using to the newest versions that still match the gems in your Gemfile(5)\.
.
.P
To do this, run \fBbundle update \-\-all\fR, which will ignore the \fBGemfile\.lock\fR, and resolve all the dependencies again\. Keep in mind that this process can result in a significantly different set of the 25 gems, based on the requirements of new gems that the gem authors released since the last time you ran \fBbundle update \-\-all\fR\.
.
.SH "UPDATING A LIST OF GEMS"
Sometimes, you want to update a single gem in the Gemfile(5), and leave the rest of the gems that you specified locked to the versions in the \fBGemfile\.lock\fR\.
.
.P
For instance, in the scenario above, imagine that \fBnokogiri\fR releases version \fB1\.4\.4\fR, and you want to update it \fIwithout\fR updating Rails and all of its dependencies\. To do this, run \fBbundle update nokogiri\fR\.
.
.P
Bundler will update \fBnokogiri\fR and any of its dependencies, but leave alone Rails and its dependencies\.
.
.SH "OVERLAPPING DEPENDENCIES"
Sometimes, multiple gems declared in your Gemfile(5) are satisfied by the same second\-level dependency\. For instance, consider the case of \fBthin\fR and \fBrack\-perftools\-profiler\fR\.
.
.IP "" 4
.
.nf

source "https://rubygems\.org"

gem "thin"
gem "rack\-perftools\-profiler"
.
.fi
.
.IP "" 0
.
.P
The \fBthin\fR gem depends on \fBrack >= 1\.0\fR, while \fBrack\-perftools\-profiler\fR depends on \fBrack ~> 1\.0\fR\. If you run bundle install, you get:
.
.IP "" 4
.
.nf

Fetching source index for https://rubygems\.org/
Installing daemons (1\.1\.0)
Installing eventmachine (0\.12\.10) with native extensions
Installing open4 (1\.0\.1)
Installing perftools\.rb (0\.4\.7) with native extensions
Installing rack (1\.2\.1)
Installing rack\-perftools_profiler (0\.0\.2)
Installing thin (1\.2\.7) with native extensions
Using bundler (1\.0\.0\.rc\.3)
.
.fi
.
.IP "" 0
.
.P
In this case, the two gems have their own set of dependencies, but they share \fBrack\fR in common\. If you run \fBbundle update thin\fR, bundler will update \fBdaemons\fR, \fBeventmachine\fR and \fBrack\fR, which are dependencies of \fBthin\fR, but not \fBopen4\fR or \fBperftools\.rb\fR, which are dependencies of \fBrack\-perftools_profiler\fR\. Note that \fBbundle update thin\fR will update \fBrack\fR even though it\'s \fIalso\fR a dependency of \fBrack\-perftools_profiler\fR\.
.
.P
In short, by default, when you update a gem using \fBbundle update\fR, bundler will update all dependencies of that gem, including those that are also dependencies of another gem\.
.
.P
To prevent updating indirect dependencies, prior to version 1\.14 the only option was the \fBCONSERVATIVE UPDATING\fR behavior in bundle install(1) \fIbundle\-install\.1\.html\fR:
.
.P
In this scenario, updating the \fBthin\fR version manually in the Gemfile(5), and then running bundle install(1) \fIbundle\-install\.1\.html\fR will only update \fBdaemons\fR and \fBeventmachine\fR, but not \fBrack\fR\. For more information, see the \fBCONSERVATIVE UPDATING\fR section of bundle install(1) \fIbundle\-install\.1\.html\fR\.
.
.P
Starting with 1\.14, specifying the \fB\-\-conservative\fR option will also prevent indirect dependencies from being updated\.
.
.SH "PATCH LEVEL OPTIONS"
Version 1\.14 introduced 4 patch\-level options that will influence how gem versions are resolved\. One of the following options can be used: \fB\-\-patch\fR, \fB\-\-minor\fR or \fB\-\-major\fR\. \fB\-\-strict\fR can be added to further influence resolution\.
.
.TP
\fB\-\-patch\fR
Prefer updating only to next patch version\.
.
.TP
\fB\-\-minor\fR
Prefer updating only to next minor version\.
.
.TP
\fB\-\-major\fR
Prefer updating to next major version (default)\.
.
.TP
\fB\-\-strict\fR
Do not allow any gem to be updated past latest \fB\-\-patch\fR | \fB\-\-minor\fR | \fB\-\-major\fR\.
.
.P
When Bundler is resolving what versions to use to satisfy declared requirements in the Gemfile or in parent gems, it looks up all available versions, filters out any versions that don\'t satisfy the requirement, and then, by default, sorts them from newest to oldest, considering them in that order\.
.
.P
Providing one of the patch level options (e\.g\. \fB\-\-patch\fR) changes the sort order of the satisfying versions, causing Bundler to consider the latest \fB\-\-patch\fR or \fB\-\-minor\fR version available before other versions\. Note that versions outside the stated patch level could still be resolved to if necessary to find a suitable dependency graph\.
.
.P
For example, if gem \'foo\' is locked at 1\.0\.2, with no gem requirement defined in the Gemfile, and versions 1\.0\.3, 1\.0\.4, 1\.1\.0, 1\.1\.1, 2\.0\.0 all exist, the default order of preference by default (\fB\-\-major\fR) will be "2\.0\.0, 1\.1\.1, 1\.1\.0, 1\.0\.4, 1\.0\.3, 1\.0\.2"\.
.
.P
If the \fB\-\-patch\fR option is used, the order of preference will change to "1\.0\.4, 1\.0\.3, 1\.0\.2, 1\.1\.1, 1\.1\.0, 2\.0\.0"\.
.
.P
If the \fB\-\-minor\fR option is used, the order of preference will change to "1\.1\.1, 1\.1\.0, 1\.0\.4, 1\.0\.3, 1\.0\.2, 2\.0\.0"\.
.
.P
Combining the \fB\-\-strict\fR option with any of the patch level options will remove any versions beyond the scope of the patch level option, to ensure that no gem is updated that far\.
.
.P
To continue the previous example, if both \fB\-\-patch\fR and \fB\-\-strict\fR options are used, the available versions for resolution would be "1\.0\.4, 1\.0\.3, 1\.0\.2"\. If \fB\-\-minor\fR and \fB\-\-strict\fR are used, it would be "1\.1\.1, 1\.1\.0, 1\.0\.4, 1\.0\.3, 1\.0\.2"\.
.
.P
Gem requirements as defined in the Gemfile will still be the first determining factor for what versions are available\. If the gem requirement for \fBfoo\fR in the Gemfile is \'~> 1\.0\', that will accomplish the same thing as providing the \fB\-\-minor\fR and \fB\-\-strict\fR options\.
.
.SH "PATCH LEVEL EXAMPLES"
Given the following gem specifications:
.
.IP "" 4
.
.nf

foo 1\.4\.3, requires: ~> bar 2\.0
foo 1\.4\.4, requires: ~> bar 2\.0
foo 1\.4\.5, requires: ~> bar 2\.1
foo 1\.5\.0, requires: ~> bar 2\.1
foo 1\.5\.1, requires: ~> bar 3\.0
bar with versions 2\.0\.3, 2\.0\.4, 2\.1\.0, 2\.1\.1, 3\.0\.0
.
.fi
.
.IP "" 0
.
.P
Gemfile:
.
.IP "" 4
.
.nf

gem \'foo\'
.
.fi
.
.IP "" 0
.
.P
Gemfile\.lock:
.
.IP "" 4
.
.nf

foo (1\.4\.3)
  bar (~> 2\.0)
bar (2\.0\.3)
.
.fi
.
.IP "" 0
.
.P
Cases:
.
.IP "" 4
.
.nf

#  Command Line                     Result
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
1  bundle update \-\-patch            \'foo 1\.4\.5\', \'bar 2\.1\.1\'
2  bundle update \-\-patch foo        \'foo 1\.4\.5\', \'bar 2\.1\.1\'
3  bundle update \-\-minor            \'foo 1\.5\.1\', \'bar 3\.0\.0\'
4  bundle update \-\-minor \-\-strict   \'foo 1\.5\.0\', \'bar 2\.1\.1\'
5  bundle update \-\-patch \-\-strict   \'foo 1\.4\.4\', \'bar 2\.0\.4\'
.
.fi
.
.IP "" 0
.
.P
In case 1, bar is upgraded to 2\.1\.1, a minor version increase, because the dependency from foo 1\.4\.5 required it\.
.
.P
In case 2, only foo is requested to be unlocked, but bar is also allowed to move because it\'s not a declared dependency in the Gemfile\.
.
.P
In case 3, bar goes up a whole major release, because a minor increase is preferred now for foo, and when it goes to 1\.5\.1, it requires 3\.0\.0 of bar\.
.
.P
In case 4, foo is preferred up to a minor version, but 1\.5\.1 won\'t work because the \-\-strict flag removes bar 3\.0\.0 from consideration since it\'s a major increment\.
.
.P
In case 5, both foo and bar have any minor or major increments removed from consideration because of the \-\-strict flag, so the most they can move is up to 1\.4\.4 and 2\.0\.4\.
.
.SH "RECOMMENDED WORKFLOW"
In general, when working with an application managed with bundler, you should use the following workflow:
.
.IP "\(bu" 4
After you create your Gemfile(5) for the first time, run
.
.IP
$ bundle install
.
.IP "\(bu" 4
Check the resulting \fBGemfile\.lock\fR into version control
.
.IP
$ git add Gemfile\.lock
.
.IP "\(bu" 4
When checking out this repository on another development machine, run
.
.IP
$ bundle install
.
.IP "\(bu" 4
When checking out this repository on a deployment machine, run
.
.IP
$ bundle install \-\-deployment
.
.IP "\(bu" 4
After changing the Gemfile(5) to reflect a new or update dependency, run
.
.IP
$ bundle install
.
.IP "\(bu" 4
Make sure to check the updated \fBGemfile\.lock\fR into version control
.
.IP
$ git add Gemfile\.lock
.
.IP "\(bu" 4
If bundle install(1) \fIbundle\-install\.1\.html\fR reports a conflict, manually update the specific gems that you changed in the Gemfile(5)
.
.IP
$ bundle update rails thin
.
.IP "\(bu" 4
If you want to update all the gems to the latest possible versions that still match the gems listed in the Gemfile(5), run
.
.IP
$ bundle update \-\-all
.
.IP "" 0

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-INFO" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-info\fR \- Show information for the given gem in your bundle
.
.SH "SYNOPSIS"
\fBbundle info\fR [GEM] [\-\-path]
.
.SH "DESCRIPTION"
Print the basic information about the provided GEM such as homepage, version, path and summary\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-path\fR
Print the path of the given gem

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-ADD" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-add\fR \- Add gem to the Gemfile and run bundle install
.
.SH "SYNOPSIS"
\fBbundle add\fR \fIGEM_NAME\fR [\-\-group=GROUP] [\-\-version=VERSION] [\-\-source=SOURCE] [\-\-git=GIT] [\-\-branch=BRANCH] [\-\-skip\-install] [\-\-strict] [\-\-optimistic]
.
.SH "DESCRIPTION"
Adds the named gem to the Gemfile and run \fBbundle install\fR\. \fBbundle install\fR can be avoided by using the flag \fB\-\-skip\-install\fR\.
.
.P
Example:
.
.P
bundle add rails
.
.P
bundle add rails \-\-version "< 3\.0, > 1\.1"
.
.P
bundle add rails \-\-version "~> 5\.0\.0" \-\-source "https://gems\.example\.com" \-\-group "development"
.
.P
bundle add rails \-\-skip\-install
.
.P
bundle add rails \-\-group "development, test"
.
.SH "OPTIONS"
.
.TP
\fB\-\-version\fR, \fB\-v\fR
Specify version requirements(s) for the added gem\.
.
.TP
\fB\-\-group\fR, \fB\-g\fR
Specify the group(s) for the added gem\. Multiple groups should be separated by commas\.
.
.TP
\fB\-\-source\fR, , \fB\-s\fR
Specify the source for the added gem\.
.
.TP
\fB\-\-git\fR
Specify the git source for the added gem\.
.
.TP
\fB\-\-branch\fR
Specify the git branch for the added gem\.
.
.TP
\fB\-\-skip\-install\fR
Adds the gem to the Gemfile but does not install it\.
.
.TP
\fB\-\-optimistic\fR
Adds optimistic declaration of version
.
.TP
\fB\-\-strict\fR
Adds strict declaration of version

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-LOCK" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-lock\fR \- Creates / Updates a lockfile without installing
.
.SH "SYNOPSIS"
\fBbundle lock\fR [\-\-update] [\-\-local] [\-\-print] [\-\-lockfile=PATH] [\-\-full\-index] [\-\-add\-platform] [\-\-remove\-platform] [\-\-patch] [\-\-minor] [\-\-major] [\-\-strict] [\-\-conservative]
.
.SH "DESCRIPTION"
Lock the gems specified in Gemfile\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-update=<*gems>\fR
Ignores the existing lockfile\. Resolve then updates lockfile\. Taking a list of gems or updating all gems if no list is given\.
.
.TP
\fB\-\-local\fR
Do not attempt to connect to \fBrubygems\.org\fR\. Instead, Bundler will use the gems already present in Rubygems\' cache or in \fBvendor/cache\fR\. Note that if a appropriate platform\-specific gem exists on \fBrubygems\.org\fR it will not be found\.
.
.TP
\fB\-\-print\fR
Prints the lockfile to STDOUT instead of writing to the file system\.
.
.TP
\fB\-\-lockfile=<path>\fR
The path where the lockfile should be written to\.
.
.TP
\fB\-\-full\-index\fR
Fall back to using the single\-file index of all gems\.
.
.TP
\fB\-\-add\-platform\fR
Add a new platform to the lockfile, re\-resolving for the addition of that platform\.
.
.TP
\fB\-\-remove\-platform\fR
Remove a platform from the lockfile\.
.
.TP
\fB\-\-patch\fR
If updating, prefer updating only to next patch version\.
.
.TP
\fB\-\-minor\fR
If updating, prefer updating only to next minor version\.
.
.TP
\fB\-\-major\fR
If updating, prefer updating to next major version (default)\.
.
.TP
\fB\-\-strict\fR
If updating, do not allow any gem to be updated past latest \-\-patch | \-\-minor | \-\-major\.
.
.TP
\fB\-\-conservative\fR
If updating, use bundle install conservative update behavior and do not allow shared dependencies to be updated\.
.
.SH "UPDATING ALL GEMS"
If you run \fBbundle lock\fR with \fB\-\-update\fR option without list of gems, bundler will ignore any previously installed gems and resolve all dependencies again based on the latest versions of all gems available in the sources\.
.
.SH "UPDATING A LIST OF GEMS"
Sometimes, you want to update a single gem in the Gemfile(5), and leave the rest of the gems that you specified locked to the versions in the \fBGemfile\.lock\fR\.
.
.P
For instance, you only want to update \fBnokogiri\fR, run \fBbundle lock \-\-update nokogiri\fR\.
.
.P
Bundler will update \fBnokogiri\fR and any of its dependencies, but leave the rest of the gems that you specified locked to the versions in the \fBGemfile\.lock\fR\.
.
.SH "SUPPORTING OTHER PLATFORMS"
If you want your bundle to support platforms other than the one you\'re running locally, you can run \fBbundle lock \-\-add\-platform PLATFORM\fR to add PLATFORM to the lockfile, force bundler to re\-resolve and consider the new platform when picking gems, all without needing to have a machine that matches PLATFORM handy to install those platform\-specific gems on\.
.
.P
For a full explanation of gem platforms, see \fBgem help platform\fR\.
.
.SH "PATCH LEVEL OPTIONS"
See bundle update(1) \fIbundle\-update\.1\.html\fR for details\.
.\"Ruby is copyrighted by Yukihiro Matsumoto <matz@netlab.jp>.
.Dd April 20, 2017
.Dt RI \&1 "Ruby Programmer's Reference Guide"
.Os UNIX
.Sh NAME
.Nm ri
.Nd Ruby API reference front end
.Sh SYNOPSIS
.Nm
.Op Fl ahilTv
.Op Fl d Ar DIRNAME
.Op Fl f Ar FORMAT
.Op Fl w Ar WIDTH
.Op Fl - Ns Oo Cm no- Oc Ns Cm pager
.Op Fl -server Ns Oo = Ns Ar PORT Oc
.Op Fl - Ns Oo Cm no- Oc Ns Cm list-doc-dirs
.Op Fl -no-standard-docs
.Op Fl - Ns Oo Cm no- Oc Ns Bro Cm system Ns | Ns Cm site Ns | Ns Cm gems Ns | Ns Cm home Brc
.Op Fl - Ns Oo Cm no- Oc Ns Cm profile
.Op Fl -dump Ns = Ns Ar CACHE
.Op Ar name ...
.Sh DESCRIPTION
.Nm
is a command-line front end for the Ruby API reference.
You can search and read the API reference for classes and methods with
.Nm .
.Pp
.Nm
is a part of Ruby.
.Pp
.Ar name
can be:
.Bl -diag -offset indent
.It Class | Module | Module::Class
.Pp
.It Class::method | Class#method | Class.method | method
.Pp
.It gem_name: | gem_name:README | gem_name:History
.El
.Pp
All class names may be abbreviated to their minimum unambiguous form.
If a name is ambiguous, all valid options will be listed.
.Pp
A
.Ql \&.
matches either class or instance methods, while #method
matches only instance and ::method matches only class methods.
.Pp
README and other files may be displayed by prefixing them with the gem name
they're contained in.  If the gem name is followed by a
.Ql \&:
all files in the gem will be shown.
The file name extension may be omitted where it is unambiguous.
.Pp
For example:
.Bd -literal -offset indent
ri Fil
ri File
ri File.new
ri zip
ri rdoc:README
.Ed
.Pp
Note that shell quoting or escaping may be required for method names
containing punctuation:
.Bd -literal -offset indent
ri 'Array.[]'
ri compact\e!
.Ed
.Pp
To see the default directories
.Nm
will search, run:
.Bd -literal -offset indent
ri --list-doc-dirs
.Ed
.Pp
Specifying the
.Fl -system , Fl -site , Fl -home , Fl -gems ,
or
.Fl -doc-dir
options will limit
.Nm
to searching only the specified directories.
.Pp
.Nm
options may be set in the
.Ev RI
environment variable.
.Pp
The
.Nm
pager can be set with the
.Ev RI_PAGER
environment variable or the
.Ev PAGER
environment variable.
.Pp
.Sh OPTIONS
.Bl -tag -width "1234567890123" -compact
.Pp
.It Fl i
.It Fl - Ns Oo Cm no- Oc Ns Cm interactive
In interactive mode you can repeatedly
look up methods with autocomplete.
.Pp
.It Fl a
.It Fl - Ns Oo Cm no- Oc Ns Cm all
Show all documentation for a class or module.
.Pp
.It Fl l
.It Fl - Ns Oo Cm no- Oc Ns Cm list
List classes
.Nm
knows about.
.Pp
.It Fl - Ns Oo Cm no- Oc Ns Cm pager
Send output to a pager,
rather than directly to stdout.
.Pp
.It Fl T
Synonym for
.Fl -no-pager .
.Pp
.It Fl w Ar WIDTH
.It Fl -width Ns = Ns Ar WIDTH
Set the width of the output.
.Pp
.It Fl -server Ns Oo = Ns Ar PORT Oc
Run RDoc server on the given port.
The default port is\~8214.
.Pp
.It Fl f Ar FORMAT
.It Fl -format Ns = Ns Ar FORMAT
Use the selected formatter.
The default formatter is
.Li bs
for paged output and
.Li ansi
otherwise.
Valid formatters are:
.Li ansi , Li bs , Li markdown , Li rdoc .
.Pp
.It Fl h
.It Fl -help
Show help and exit.
.Pp
.It Fl v
.It Fl -version
Output version information and exit.
.El
.Pp
Data source options:
.Bl -tag -width "1234567890123" -compact
.Pp
.It Fl - Ns Oo Cm no- Oc Ns Cm list-doc-dirs
List the directories from which
.Nm
will source documentation on stdout and exit.
.Pp
.It Fl d Ar DIRNAME
.It Fl -doc-dir Ns = Ns Ar DIRNAME
List of directories from which to source
documentation in addition to the standard
directories.  May be repeated.
.Pp
.It Fl -no-standard-docs
Do not include documentation from the Ruby standard library,
.Pa site_lib ,
installed gems, or
.Pa ~/.rdoc .
Use with
.Fl -doc-dir .
.Pp
.It Fl - Ns Oo Cm no- Oc Ns Cm system
Include documentation from Ruby's standard library.  Defaults to true.
.Pp
.It Fl - Ns Oo Cm no- Oc Ns Cm site
Include documentation from libraries installed in
.Pa site_lib .
Defaults to true.
.Pp
.It Fl - Ns Oo Cm no- Oc Ns Cm gems
Include documentation from RubyGems.  Defaults to true.
.Pp
.It Fl - Ns Oo Cm no- Oc Ns Cm home
Include documentation stored in
.Pa ~/.rdoc .
Defaults to true.
.El
.Pp
Debug options:
.Bl -tag -width "1234567890123" -compact
.Pp
.It Fl - Ns Oo Cm no- Oc Ns Cm profile
Run with the Ruby profiler.
.Pp
.It Fl -dump Ns = Ns Ar CACHE
Dump data from an ri cache or data file.
.El
.Pp
.Sh ENVIRONMENT
.Bl -tag -width "USERPROFILE" -compact
.Pp
.It Ev RI
Options to prepend to those specified on the command-line.
.Pp
.It Ev RI_PAGER
.It Ev PAGER
Pager program to use for displaying.
.Pp
.It Ev HOME
.It Ev USERPROFILE
.It Ev HOMEPATH
Path to the user's home directory.
.El
.Pp
.Sh FILES
.Bl -tag -width "USERPROFILE" -compact
.Pp
.It Pa ~/.rdoc
Path for ri data in the user's home directory.
.Pp
.El
.Pp
.Sh SEE ALSO
.Xr ruby 1 ,
.Xr rdoc 1 ,
.Xr gem 1
.Pp
.Sh REPORTING BUGS
.Bl -bullet
.It
Security vulnerabilities should be reported via an email to
.Mt security@ruby-lang.org .
Reported problems will be published after being fixed.
.Pp
.It
Other bugs and feature requests can be reported via the
Ruby Issue Tracking System
.Pq Lk https://bugs.ruby-lang.org/ .
Do not report security vulnerabilities
via this system because it publishes the vulnerabilities immediately.
.El
.Sh AUTHORS
Written by
.An Dave Thomas Aq dave@pragmaticprogrammer.com .
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-CHECK" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-check\fR \- Verifies if dependencies are satisfied by installed gems
.
.SH "SYNOPSIS"
\fBbundle check\fR [\-\-dry\-run] [\-\-gemfile=FILE] [\-\-path=PATH]
.
.SH "DESCRIPTION"
\fBcheck\fR searches the local machine for each of the gems requested in the Gemfile\. If all gems are found, Bundler prints a success message and exits with a status of 0\.
.
.P
If not, the first missing gem is listed and Bundler exits status 1\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-dry\-run\fR
Locks the [\fBGemfile(5)\fR][Gemfile(5)] before running the command\.
.
.TP
\fB\-\-gemfile\fR
Use the specified gemfile instead of the [\fBGemfile(5)\fR][Gemfile(5)]\.
.
.TP
\fB\-\-path\fR
Specify a different path than the system default (\fB$BUNDLE_PATH\fR or \fB$GEM_HOME\fR)\. Bundler will remember this value for future installs on this machine\.

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-CLEAN" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-clean\fR \- Cleans up unused gems in your bundler directory
.
.SH "SYNOPSIS"
\fBbundle clean\fR [\-\-dry\-run] [\-\-force]
.
.SH "DESCRIPTION"
This command will remove all unused gems in your bundler directory\. This is useful when you have made many changes to your gem dependencies\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-dry\-run\fR
Print the changes, but do not clean the unused gems\.
.
.TP
\fB\-\-force\fR
Force a clean even if \fB\-\-path\fR is not set\.

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-OPEN" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-open\fR \- Opens the source directory for a gem in your bundle
.
.SH "SYNOPSIS"
\fBbundle open\fR [GEM]
.
.SH "DESCRIPTION"
Opens the source directory of the provided GEM in your editor\.
.
.P
For this to work the \fBEDITOR\fR or \fBBUNDLER_EDITOR\fR environment variable has to be set\.
.
.P
Example:
.
.IP "" 4
.
.nf

bundle open \'rack\'
.
.fi
.
.IP "" 0
.
.P
Will open the source directory for the \'rack\' gem in your bundle\.
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-INIT" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-init\fR \- Generates a Gemfile into the current working directory
.
.SH "SYNOPSIS"
\fBbundle init\fR [\-\-gemspec=FILE]
.
.SH "DESCRIPTION"
Init generates a default [\fBGemfile(5)\fR][Gemfile(5)] in the current working directory\. When adding a [\fBGemfile(5)\fR][Gemfile(5)] to a gem with a gemspec, the \fB\-\-gemspec\fR option will automatically add each dependency listed in the gemspec file to the newly created [\fBGemfile(5)\fR][Gemfile(5)]\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-gemspec\fR
Use the specified \.gemspec to create the [\fBGemfile(5)\fR][Gemfile(5)]
.
.SH "FILES"
Included in the default [\fBGemfile(5)\fR][Gemfile(5)] generated is the line \fB# frozen_string_literal: true\fR\. This is a magic comment supported for the first time in Ruby 2\.3\. The presence of this line results in all string literals in the file being implicitly frozen\.
.
.SH "SEE ALSO"
Gemfile(5) \fIhttps://bundler\.io/man/gemfile\.5\.html\fR
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-PRISTINE" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-pristine\fR \- Restores installed gems to their pristine condition
.
.SH "SYNOPSIS"
\fBbundle pristine\fR
.
.SH "DESCRIPTION"
\fBpristine\fR restores the installed gems in the bundle to their pristine condition using the local gem cache from RubyGems\. For git gems, a forced checkout will be performed\.
.
.P
For further explanation, \fBbundle pristine\fR ignores unpacked files on disk\. In other words, this command utilizes the local \fB\.gem\fR cache or the gem\'s git repository as if one were installing from scratch\.
.
.P
Note: the Bundler gem cannot be restored to its original state with \fBpristine\fR\. One also cannot use \fBbundle pristine\fR on gems with a \'path\' option in the Gemfile, because bundler has no original copy it can restore from\.
.
.P
When is it practical to use \fBbundle pristine\fR?
.
.P
It comes in handy when a developer is debugging a gem\. \fBbundle pristine\fR is a great way to get rid of experimental changes to a gem that one may not want\.
.
.P
Why use \fBbundle pristine\fR over \fBgem pristine \-\-all\fR?
.
.P
Both commands are very similar\. For context: \fBbundle pristine\fR, without arguments, cleans all gems from the lockfile\. Meanwhile, \fBgem pristine \-\-all\fR cleans all installed gems for that Ruby version\.
.
.P
If a developer forgets which gems in their project they might have been debugging, the Rubygems \fBgem pristine [GEMNAME]\fR command may be inconvenient\. One can avoid waiting for \fBgem pristine \-\-all\fR, and instead run \fBbundle pristine\fR\.
.Dd June 12, 2016
.Dt RAKE 1
.Os rake 11.2.2
.Sh NAME
.Nm rake
.Nd make-like build utility for Ruby
.Sh SYNOPSIS
.Nm
.Op Fl f Ar rakefile
.Op Ar options
.Ar targets ...
.Sh DESCRIPTION
.Nm
is a
.Xr make 1 Ns -like
build utility for Ruby.
Tasks and dependencies are specified in standard Ruby syntax.
.Sh OPTIONS
.Bl -tag -width Ds
.It Fl m , Fl -multitask
Treat all tasks as multitasks.
.It Fl B , Fl -build-all
Build all prerequisites, including those which are up\-to\-date.
.It Fl j , Fl -jobs Ar num_jobs
Specifies the maximum number of tasks to execute in parallel (default is number of CPU cores + 4).
.El
.Ss Modules
.Bl -tag -width Ds
.It Fl I , Fl -libdir Ar libdir
Include
.Ar libdir
in the search path for required modules.
.It Fl r , Fl -require Ar module
Require
.Ar module
before executing
.Pa rakefile .
.El
.Ss Rakefile location
.Bl -tag -width Ds
.It Fl f , Fl -rakefile Ar filename
Use
.Ar filename
as the rakefile to search for.
.It Fl N , Fl -no-search , Fl -nosearch
Do not search parent directories for the Rakefile.
.It Fl G , Fl -no-system , Fl -nosystem
Use standard project Rakefile search paths, ignore system wide rakefiles.
.It Fl R , Fl -rakelib Ar rakelibdir , Fl -rakelibdir Ar rakelibdir
Auto-import any .rake files in
.Ar rakelibdir
(default is
.Sq rakelib )
.It Fl g , Fl -system
Use system-wide (global) rakefiles (usually
.Pa ~/.rake/*.rake ) .
.El
.Ss Debugging
.Bl -tag -width Ds
.It Fl -backtrace Ns = Ns Ar out
Enable full backtrace.
.Ar out
can be
.Dv stderr
(default) or
.Dv stdout .
.It Fl t , Fl -trace Ns = Ns Ar out
Turn on invoke/execute tracing, enable full backtrace.
.Ar out
can be
.Dv stderr
(default) or
.Dv stdout .
.It Fl -suppress-backtrace Ar pattern
Suppress backtrace lines matching regexp
.Ar pattern .
Ignored if
.Fl -trace
is on.
.It Fl -rules
Trace the rules resolution.
.It Fl n , Fl -dry-run
Do a dry run without executing actions.
.It Fl T , Fl -tasks Op Ar pattern
Display the tasks (matching optional
.Ar pattern )
with descriptions, then exit.
.It Fl D , Fl -describe Op Ar pattern
Describe the tasks (matching optional
.Ar pattern ) ,
then exit.
.It Fl W , Fl -where Op Ar pattern
Describe the tasks (matching optional
.Ar pattern ) ,
then exit.
.It Fl P , Fl -prereqs
Display the tasks and dependencies, then exit.
.It Fl e , Fl -execute Ar code
Execute some Ruby code and exit.
.It Fl p , Fl -execute-print Ar code
Execute some Ruby code, print the result, then exit.
.It Fl E , Fl -execute-continue Ar code
Execute some Ruby code, then continue with normal task processing.
.El
.Ss Information
.Bl -tag -width Ds
.It Fl v , Fl -verbose
Log message to standard output.
.It Fl q , Fl -quiet
Do not log messages to standard output.
.It Fl s , Fl -silent
Like
.Fl -quiet ,
but also suppresses the
.Sq in directory
announcement.
.It Fl X , Fl -no-deprecation-warnings
Disable the deprecation warnings.
.It Fl -comments
Show commented tasks only
.It Fl A , Fl -all
Show all tasks, even uncommented ones (in combination with
.Fl T
or
.Fl D )
.It Fl -job-stats Op Ar level
Display job statistics.
If
.Ar level
is
.Sq history ,
displays a complete job list.
.It Fl V , Fl -version
Display the program version.
.It Fl h , Fl H , Fl -help
Display a help message.
.El
.Sh SEE ALSO
The complete documentation for
.Nm rake
has been installed at
.Pa /usr/share/doc/rake-doc/html/index.html .
It is also available online at
.Lk https://ruby.github.io/rake .
.Sh AUTHORS
.An -nosplit
.Nm
was written by
.An Jim Weirich Aq Mt jim@weirichhouse.org .
.Pp
This manual was created by
.An Caitlin Matos Aq Mt caitlin.matos@zoho.com
for the Debian project (but may be used by others).
It was inspired by the manual by
.An Jani Monoses Aq Mt jani@iv.ro
for the Ubuntu project.
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-VIZ" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-viz\fR \- Generates a visual dependency graph for your Gemfile
.
.SH "SYNOPSIS"
\fBbundle viz\fR [\-\-file=FILE] [\-\-format=FORMAT] [\-\-requirements] [\-\-version] [\-\-without=GROUP GROUP]
.
.SH "DESCRIPTION"
\fBviz\fR generates a PNG file of the current \fBGemfile(5)\fR as a dependency graph\. \fBviz\fR requires the ruby\-graphviz gem (and its dependencies)\.
.
.P
The associated gems must also be installed via \fBbundle install(1)\fR \fIbundle\-install\.1\.html\fR\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-file\fR, \fB\-f\fR
The name to use for the generated file\. See \fB\-\-format\fR option
.
.TP
\fB\-\-format\fR, \fB\-F\fR
This is output format option\. Supported format is png, jpg, svg, dot \.\.\.
.
.TP
\fB\-\-requirements\fR, \fB\-R\fR
Set to show the version of each required dependency\.
.
.TP
\fB\-\-version\fR, \fB\-v\fR
Set to show each gem version\.
.
.TP
\fB\-\-without\fR, \fB\-W\fR
Exclude gems that are part of the specified named group\.

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-PLATFORM" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-platform\fR \- Displays platform compatibility information
.
.SH "SYNOPSIS"
\fBbundle platform\fR [\-\-ruby]
.
.SH "DESCRIPTION"
\fBplatform\fR will display information from your Gemfile, Gemfile\.lock, and Ruby VM about your platform\.
.
.P
For instance, using this Gemfile(5):
.
.IP "" 4
.
.nf

source "https://rubygems\.org"

ruby "1\.9\.3"

gem "rack"
.
.fi
.
.IP "" 0
.
.P
If you run \fBbundle platform\fR on Ruby 1\.9\.3, it will display the following output:
.
.IP "" 4
.
.nf

Your platform is: x86_64\-linux

Your app has gems that work on these platforms:
* ruby

Your Gemfile specifies a Ruby version requirement:
* ruby 1\.9\.3

Your current platform satisfies the Ruby version requirement\.
.
.fi
.
.IP "" 0
.
.P
\fBplatform\fR will list all the platforms in your \fBGemfile\.lock\fR as well as the \fBruby\fR directive if applicable from your Gemfile(5)\. It will also let you know if the \fBruby\fR directive requirement has been met\. If \fBruby\fR directive doesn\'t match the running Ruby VM, it will tell you what part does not\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-ruby\fR
It will display the ruby directive information, so you don\'t have to parse it from the Gemfile(5)\.

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-INSTALL" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-install\fR \- Install the dependencies specified in your Gemfile
.
.SH "SYNOPSIS"
\fBbundle install\fR [\-\-binstubs[=DIRECTORY]] [\-\-clean] [\-\-deployment] [\-\-frozen] [\-\-full\-index] [\-\-gemfile=GEMFILE] [\-\-jobs=NUMBER] [\-\-local] [\-\-no\-cache] [\-\-no\-prune] [\-\-path PATH] [\-\-quiet] [\-\-redownload] [\-\-retry=NUMBER] [\-\-shebang] [\-\-standalone[=GROUP[ GROUP\.\.\.]]] [\-\-system] [\-\-trust\-policy=POLICY] [\-\-with=GROUP[ GROUP\.\.\.]] [\-\-without=GROUP[ GROUP\.\.\.]]
.
.SH "DESCRIPTION"
Install the gems specified in your Gemfile(5)\. If this is the first time you run bundle install (and a \fBGemfile\.lock\fR does not exist), Bundler will fetch all remote sources, resolve dependencies and install all needed gems\.
.
.P
If a \fBGemfile\.lock\fR does exist, and you have not updated your Gemfile(5), Bundler will fetch all remote sources, but use the dependencies specified in the \fBGemfile\.lock\fR instead of resolving dependencies\.
.
.P
If a \fBGemfile\.lock\fR does exist, and you have updated your Gemfile(5), Bundler will use the dependencies in the \fBGemfile\.lock\fR for all gems that you did not update, but will re\-resolve the dependencies of gems that you did update\. You can find more information about this update process below under \fICONSERVATIVE UPDATING\fR\.
.
.SH "OPTIONS"
The \fB\-\-clean\fR, \fB\-\-deployment\fR, \fB\-\-frozen\fR, \fB\-\-no\-prune\fR, \fB\-\-path\fR, \fB\-\-shebang\fR, \fB\-\-system\fR, \fB\-\-without\fR and \fB\-\-with\fR options are deprecated because they only make sense if they are applied to every subsequent \fBbundle install\fR run automatically and that requires \fBbundler\fR to silently remember them\. Since \fBbundler\fR will no longer remember CLI flags in future versions, \fBbundle config\fR (see bundle\-config(1)) should be used to apply them permanently\.
.
.TP
\fB\-\-binstubs[=<directory>]\fR
Binstubs are scripts that wrap around executables\. Bundler creates a small Ruby file (a binstub) that loads Bundler, runs the command, and puts it in \fBbin/\fR\. This lets you link the binstub inside of an application to the exact gem version the application needs\.
.
.IP
Creates a directory (defaults to \fB~/bin\fR) and places any executables from the gem there\. These executables run in Bundler\'s context\. If used, you might add this directory to your environment\'s \fBPATH\fR variable\. For instance, if the \fBrails\fR gem comes with a \fBrails\fR executable, this flag will create a \fBbin/rails\fR executable that ensures that all referred dependencies will be resolved using the bundled gems\.
.
.TP
\fB\-\-clean\fR
On finishing the installation Bundler is going to remove any gems not present in the current Gemfile(5)\. Don\'t worry, gems currently in use will not be removed\.
.
.IP
This option is deprecated in favor of the \fBclean\fR setting\.
.
.TP
\fB\-\-deployment\fR
In \fIdeployment mode\fR, Bundler will \'roll\-out\' the bundle for production or CI use\. Please check carefully if you want to have this option enabled in your development environment\.
.
.IP
This option is deprecated in favor of the \fBdeployment\fR setting\.
.
.TP
\fB\-\-redownload\fR
Force download every gem, even if the required versions are already available locally\.
.
.TP
\fB\-\-frozen\fR
Do not allow the Gemfile\.lock to be updated after this install\. Exits non\-zero if there are going to be changes to the Gemfile\.lock\.
.
.IP
This option is deprecated in favor of the \fBfrozen\fR setting\.
.
.TP
\fB\-\-full\-index\fR
Bundler will not call Rubygems\' API endpoint (default) but download and cache a (currently big) index file of all gems\. Performance can be improved for large bundles that seldom change by enabling this option\.
.
.TP
\fB\-\-gemfile=<gemfile>\fR
The location of the Gemfile(5) which Bundler should use\. This defaults to a Gemfile(5) in the current working directory\. In general, Bundler will assume that the location of the Gemfile(5) is also the project\'s root and will try to find \fBGemfile\.lock\fR and \fBvendor/cache\fR relative to this location\.
.
.TP
\fB\-\-jobs=[<number>]\fR, \fB\-j[<number>]\fR
The maximum number of parallel download and install jobs\. The default is \fB1\fR\.
.
.TP
\fB\-\-local\fR
Do not attempt to connect to \fBrubygems\.org\fR\. Instead, Bundler will use the gems already present in Rubygems\' cache or in \fBvendor/cache\fR\. Note that if an appropriate platform\-specific gem exists on \fBrubygems\.org\fR it will not be found\.
.
.TP
\fB\-\-no\-cache\fR
Do not update the cache in \fBvendor/cache\fR with the newly bundled gems\. This does not remove any gems in the cache but keeps the newly bundled gems from being cached during the install\.
.
.TP
\fB\-\-no\-prune\fR
Don\'t remove stale gems from the cache when the installation finishes\.
.
.IP
This option is deprecated in favor of the \fBno_prune\fR setting\.
.
.TP
\fB\-\-path=<path>\fR
The location to install the specified gems to\. This defaults to Rubygems\' setting\. Bundler shares this location with Rubygems, \fBgem install \.\.\.\fR will have gem installed there, too\. Therefore, gems installed without a \fB\-\-path \.\.\.\fR setting will show up by calling \fBgem list\fR\. Accordingly, gems installed to other locations will not get listed\.
.
.IP
This option is deprecated in favor of the \fBpath\fR setting\.
.
.TP
\fB\-\-quiet\fR
Do not print progress information to the standard output\. Instead, Bundler will exit using a status code (\fB$?\fR)\.
.
.TP
\fB\-\-retry=[<number>]\fR
Retry failed network or git requests for \fInumber\fR times\.
.
.TP
\fB\-\-shebang=<ruby\-executable>\fR
Uses the specified ruby executable (usually \fBruby\fR) to execute the scripts created with \fB\-\-binstubs\fR\. In addition, if you use \fB\-\-binstubs\fR together with \fB\-\-shebang jruby\fR these executables will be changed to execute \fBjruby\fR instead\.
.
.IP
This option is deprecated in favor of the \fBshebang\fR setting\.
.
.TP
\fB\-\-standalone[=<list>]\fR
Makes a bundle that can work without depending on Rubygems or Bundler at runtime\. A space separated list of groups to install has to be specified\. Bundler creates a directory named \fBbundle\fR and installs the bundle there\. It also generates a \fBbundle/bundler/setup\.rb\fR file to replace Bundler\'s own setup in the manner required\. Using this option implicitly sets \fBpath\fR, which is a [remembered option][REMEMBERED OPTIONS]\.
.
.TP
\fB\-\-system\fR
Installs the gems specified in the bundle to the system\'s Rubygems location\. This overrides any previous configuration of \fB\-\-path\fR\.
.
.IP
This option is deprecated in favor of the \fBsystem\fR setting\.
.
.TP
\fB\-\-trust\-policy=[<policy>]\fR
Apply the Rubygems security policy \fIpolicy\fR, where policy is one of \fBHighSecurity\fR, \fBMediumSecurity\fR, \fBLowSecurity\fR, \fBAlmostNoSecurity\fR, or \fBNoSecurity\fR\. For more details, please see the Rubygems signing documentation linked below in \fISEE ALSO\fR\.
.
.TP
\fB\-\-with=<list>\fR
A space\-separated list of groups referencing gems to install\. If an optional group is given it is installed\. If a group is given that is in the remembered list of groups given to \-\-without, it is removed from that list\.
.
.IP
This option is deprecated in favor of the \fBwith\fR setting\.
.
.TP
\fB\-\-without=<list>\fR
A space\-separated list of groups referencing gems to skip during installation\. If a group is given that is in the remembered list of groups given to \-\-with, it is removed from that list\.
.
.IP
This option is deprecated in favor of the \fBwithout\fR setting\.
.
.SH "DEPLOYMENT MODE"
Bundler\'s defaults are optimized for development\. To switch to defaults optimized for deployment and for CI, use the \fB\-\-deployment\fR flag\. Do not activate deployment mode on development machines, as it will cause an error when the Gemfile(5) is modified\.
.
.IP "1." 4
A \fBGemfile\.lock\fR is required\.
.
.IP
To ensure that the same versions of the gems you developed with and tested with are also used in deployments, a \fBGemfile\.lock\fR is required\.
.
.IP
This is mainly to ensure that you remember to check your \fBGemfile\.lock\fR into version control\.
.
.IP "2." 4
The \fBGemfile\.lock\fR must be up to date
.
.IP
In development, you can modify your Gemfile(5) and re\-run \fBbundle install\fR to \fIconservatively update\fR your \fBGemfile\.lock\fR snapshot\.
.
.IP
In deployment, your \fBGemfile\.lock\fR should be up\-to\-date with changes made in your Gemfile(5)\.
.
.IP "3." 4
Gems are installed to \fBvendor/bundle\fR not your default system location
.
.IP
In development, it\'s convenient to share the gems used in your application with other applications and other scripts that run on the system\.
.
.IP
In deployment, isolation is a more important default\. In addition, the user deploying the application may not have permission to install gems to the system, or the web server may not have permission to read them\.
.
.IP
As a result, \fBbundle install \-\-deployment\fR installs gems to the \fBvendor/bundle\fR directory in the application\. This may be overridden using the \fB\-\-path\fR option\.
.
.IP "" 0
.
.SH "SUDO USAGE"
By default, Bundler installs gems to the same location as \fBgem install\fR\.
.
.P
In some cases, that location may not be writable by your Unix user\. In that case, Bundler will stage everything in a temporary directory, then ask you for your \fBsudo\fR password in order to copy the gems into their system location\.
.
.P
From your perspective, this is identical to installing the gems directly into the system\.
.
.P
You should never use \fBsudo bundle install\fR\. This is because several other steps in \fBbundle install\fR must be performed as the current user:
.
.IP "\(bu" 4
Updating your \fBGemfile\.lock\fR
.
.IP "\(bu" 4
Updating your \fBvendor/cache\fR, if necessary
.
.IP "\(bu" 4
Checking out private git repositories using your user\'s SSH keys
.
.IP "" 0
.
.P
Of these three, the first two could theoretically be performed by \fBchown\fRing the resulting files to \fB$SUDO_USER\fR\. The third, however, can only be performed by invoking the \fBgit\fR command as the current user\. Therefore, git gems are downloaded and installed into \fB~/\.bundle\fR rather than $GEM_HOME or $BUNDLE_PATH\.
.
.P
As a result, you should run \fBbundle install\fR as the current user, and Bundler will ask for your password if it is needed to put the gems into their final location\.
.
.SH "INSTALLING GROUPS"
By default, \fBbundle install\fR will install all gems in all groups in your Gemfile(5), except those declared for a different platform\.
.
.P
However, you can explicitly tell Bundler to skip installing certain groups with the \fB\-\-without\fR option\. This option takes a space\-separated list of groups\.
.
.P
While the \fB\-\-without\fR option will skip \fIinstalling\fR the gems in the specified groups, it will still \fIdownload\fR those gems and use them to resolve the dependencies of every gem in your Gemfile(5)\.
.
.P
This is so that installing a different set of groups on another machine (such as a production server) will not change the gems and versions that you have already developed and tested against\.
.
.P
\fBBundler offers a rock\-solid guarantee that the third\-party code you are running in development and testing is also the third\-party code you are running in production\. You can choose to exclude some of that code in different environments, but you will never be caught flat\-footed by different versions of third\-party code being used in different environments\.\fR
.
.P
For a simple illustration, consider the following Gemfile(5):
.
.IP "" 4
.
.nf

source \'https://rubygems\.org\'

gem \'sinatra\'

group :production do
  gem \'rack\-perftools\-profiler\'
end
.
.fi
.
.IP "" 0
.
.P
In this case, \fBsinatra\fR depends on any version of Rack (\fB>= 1\.0\fR), while \fBrack\-perftools\-profiler\fR depends on 1\.x (\fB~> 1\.0\fR)\.
.
.P
When you run \fBbundle install \-\-without production\fR in development, we look at the dependencies of \fBrack\-perftools\-profiler\fR as well\. That way, you do not spend all your time developing against Rack 2\.0, using new APIs unavailable in Rack 1\.x, only to have Bundler switch to Rack 1\.2 when the \fBproduction\fR group \fIis\fR used\.
.
.P
This should not cause any problems in practice, because we do not attempt to \fBinstall\fR the gems in the excluded groups, and only evaluate as part of the dependency resolution process\.
.
.P
This also means that you cannot include different versions of the same gem in different groups, because doing so would result in different sets of dependencies used in development and production\. Because of the vagaries of the dependency resolution process, this usually affects more than the gems you list in your Gemfile(5), and can (surprisingly) radically change the gems you are using\.
.
.SH "THE GEMFILE\.LOCK"
When you run \fBbundle install\fR, Bundler will persist the full names and versions of all gems that you used (including dependencies of the gems specified in the Gemfile(5)) into a file called \fBGemfile\.lock\fR\.
.
.P
Bundler uses this file in all subsequent calls to \fBbundle install\fR, which guarantees that you always use the same exact code, even as your application moves across machines\.
.
.P
Because of the way dependency resolution works, even a seemingly small change (for instance, an update to a point\-release of a dependency of a gem in your Gemfile(5)) can result in radically different gems being needed to satisfy all dependencies\.
.
.P
As a result, you \fBSHOULD\fR check your \fBGemfile\.lock\fR into version control, in both applications and gems\. If you do not, every machine that checks out your repository (including your production server) will resolve all dependencies again, which will result in different versions of third\-party code being used if \fBany\fR of the gems in the Gemfile(5) or any of their dependencies have been updated\.
.
.P
When Bundler first shipped, the \fBGemfile\.lock\fR was included in the \fB\.gitignore\fR file included with generated gems\. Over time, however, it became clear that this practice forces the pain of broken dependencies onto new contributors, while leaving existing contributors potentially unaware of the problem\. Since \fBbundle install\fR is usually the first step towards a contribution, the pain of broken dependencies would discourage new contributors from contributing\. As a result, we have revised our guidance for gem authors to now recommend checking in the lock for gems\.
.
.SH "CONSERVATIVE UPDATING"
When you make a change to the Gemfile(5) and then run \fBbundle install\fR, Bundler will update only the gems that you modified\.
.
.P
In other words, if a gem that you \fBdid not modify\fR worked before you called \fBbundle install\fR, it will continue to use the exact same versions of all dependencies as it used before the update\.
.
.P
Let\'s take a look at an example\. Here\'s your original Gemfile(5):
.
.IP "" 4
.
.nf

source \'https://rubygems\.org\'

gem \'actionpack\', \'2\.3\.8\'
gem \'activemerchant\'
.
.fi
.
.IP "" 0
.
.P
In this case, both \fBactionpack\fR and \fBactivemerchant\fR depend on \fBactivesupport\fR\. The \fBactionpack\fR gem depends on \fBactivesupport 2\.3\.8\fR and \fBrack ~> 1\.1\.0\fR, while the \fBactivemerchant\fR gem depends on \fBactivesupport >= 2\.3\.2\fR, \fBbraintree >= 2\.0\.0\fR, and \fBbuilder >= 2\.0\.0\fR\.
.
.P
When the dependencies are first resolved, Bundler will select \fBactivesupport 2\.3\.8\fR, which satisfies the requirements of both gems in your Gemfile(5)\.
.
.P
Next, you modify your Gemfile(5) to:
.
.IP "" 4
.
.nf

source \'https://rubygems\.org\'

gem \'actionpack\', \'3\.0\.0\.rc\'
gem \'activemerchant\'
.
.fi
.
.IP "" 0
.
.P
The \fBactionpack 3\.0\.0\.rc\fR gem has a number of new dependencies, and updates the \fBactivesupport\fR dependency to \fB= 3\.0\.0\.rc\fR and the \fBrack\fR dependency to \fB~> 1\.2\.1\fR\.
.
.P
When you run \fBbundle install\fR, Bundler notices that you changed the \fBactionpack\fR gem, but not the \fBactivemerchant\fR gem\. It evaluates the gems currently being used to satisfy its requirements:
.
.TP
\fBactivesupport 2\.3\.8\fR
also used to satisfy a dependency in \fBactivemerchant\fR, which is not being updated
.
.TP
\fBrack ~> 1\.1\.0\fR
not currently being used to satisfy another dependency
.
.P
Because you did not explicitly ask to update \fBactivemerchant\fR, you would not expect it to suddenly stop working after updating \fBactionpack\fR\. However, satisfying the new \fBactivesupport 3\.0\.0\.rc\fR dependency of actionpack requires updating one of its dependencies\.
.
.P
Even though \fBactivemerchant\fR declares a very loose dependency that theoretically matches \fBactivesupport 3\.0\.0\.rc\fR, Bundler treats gems in your Gemfile(5) that have not changed as an atomic unit together with their dependencies\. In this case, the \fBactivemerchant\fR dependency is treated as \fBactivemerchant 1\.7\.1 + activesupport 2\.3\.8\fR, so \fBbundle install\fR will report that it cannot update \fBactionpack\fR\.
.
.P
To explicitly update \fBactionpack\fR, including its dependencies which other gems in the Gemfile(5) still depend on, run \fBbundle update actionpack\fR (see \fBbundle update(1)\fR)\.
.
.P
\fBSummary\fR: In general, after making a change to the Gemfile(5) , you should first try to run \fBbundle install\fR, which will guarantee that no other gem in the Gemfile(5) is impacted by the change\. If that does not work, run bundle update(1) \fIbundle\-update\.1\.html\fR\.
.
.SH "SEE ALSO"
.
.IP "\(bu" 4
Gem install docs \fIhttp://guides\.rubygems\.org/rubygems\-basics/#installing\-gems\fR
.
.IP "\(bu" 4
Rubygems signing docs \fIhttp://guides\.rubygems\.org/security/\fR
.
.IP "" 0

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-INJECT" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-inject\fR \- Add named gem(s) with version requirements to Gemfile
.
.SH "SYNOPSIS"
\fBbundle inject\fR [GEM] [VERSION]
.
.SH "DESCRIPTION"
Adds the named gem(s) with their version requirements to the resolved [\fBGemfile(5)\fR][Gemfile(5)]\.
.
.P
This command will add the gem to both your [\fBGemfile(5)\fR][Gemfile(5)] and Gemfile\.lock if it isn\'t listed yet\.
.
.P
Example:
.
.IP "" 4
.
.nf

bundle install
bundle inject \'rack\' \'> 0\'
.
.fi
.
.IP "" 0
.
.P
This will inject the \'rack\' gem with a version greater than 0 in your [\fBGemfile(5)\fR][Gemfile(5)] and Gemfile\.lock
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-SHOW" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-show\fR \- Shows all the gems in your bundle, or the path to a gem
.
.SH "SYNOPSIS"
\fBbundle show\fR [GEM] [\-\-paths]
.
.SH "DESCRIPTION"
Without the [GEM] option, \fBshow\fR will print a list of the names and versions of all gems that are required by your [\fBGemfile(5)\fR][Gemfile(5)], sorted by name\.
.
.P
Calling show with [GEM] will list the exact location of that gem on your machine\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-paths\fR
List the paths of all gems that are required by your [\fBGemfile(5)\fR][Gemfile(5)], sorted by gem name\.

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\fR \- Ruby Dependency Management
.
.SH "SYNOPSIS"
\fBbundle\fR COMMAND [\-\-no\-color] [\-\-verbose] [ARGS]
.
.SH "DESCRIPTION"
Bundler manages an \fBapplication\'s dependencies\fR through its entire life across many machines systematically and repeatably\.
.
.P
See the bundler website \fIhttps://bundler\.io\fR for information on getting started, and Gemfile(5) for more information on the \fBGemfile\fR format\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-no\-color\fR
Print all output without color
.
.TP
\fB\-\-retry\fR, \fB\-r\fR
Specify the number of times you wish to attempt network commands
.
.TP
\fB\-\-verbose\fR, \fB\-V\fR
Print out additional logging information
.
.SH "BUNDLE COMMANDS"
We divide \fBbundle\fR subcommands into primary commands and utilities:
.
.SH "PRIMARY COMMANDS"
.
.TP
\fBbundle install(1)\fR \fIbundle\-install\.1\.html\fR
Install the gems specified by the \fBGemfile\fR or \fBGemfile\.lock\fR
.
.TP
\fBbundle update(1)\fR \fIbundle\-update\.1\.html\fR
Update dependencies to their latest versions
.
.TP
\fBbundle package(1)\fR \fIbundle\-package\.1\.html\fR
Package the \.gem files required by your application into the \fBvendor/cache\fR directory
.
.TP
\fBbundle exec(1)\fR \fIbundle\-exec\.1\.html\fR
Execute a script in the current bundle
.
.TP
\fBbundle config(1)\fR \fIbundle\-config\.1\.html\fR
Specify and read configuration options for Bundler
.
.TP
\fBbundle help(1)\fR
Display detailed help for each subcommand
.
.SH "UTILITIES"
.
.TP
\fBbundle add(1)\fR \fIbundle\-add\.1\.html\fR
Add the named gem to the Gemfile and run \fBbundle install\fR
.
.TP
\fBbundle binstubs(1)\fR \fIbundle\-binstubs\.1\.html\fR
Generate binstubs for executables in a gem
.
.TP
\fBbundle check(1)\fR \fIbundle\-check\.1\.html\fR
Determine whether the requirements for your application are installed and available to Bundler
.
.TP
\fBbundle show(1)\fR \fIbundle\-show\.1\.html\fR
Show the source location of a particular gem in the bundle
.
.TP
\fBbundle outdated(1)\fR \fIbundle\-outdated\.1\.html\fR
Show all of the outdated gems in the current bundle
.
.TP
\fBbundle console(1)\fR
Start an IRB session in the current bundle
.
.TP
\fBbundle open(1)\fR \fIbundle\-open\.1\.html\fR
Open an installed gem in the editor
.
.TP
\fBbundle lock(1)\fR \fIbundle\-lock\.1\.html\fR
Generate a lockfile for your dependencies
.
.TP
\fBbundle viz(1)\fR \fIbundle\-viz\.1\.html\fR
Generate a visual representation of your dependencies
.
.TP
\fBbundle init(1)\fR \fIbundle\-init\.1\.html\fR
Generate a simple \fBGemfile\fR, placed in the current directory
.
.TP
\fBbundle gem(1)\fR \fIbundle\-gem\.1\.html\fR
Create a simple gem, suitable for development with Bundler
.
.TP
\fBbundle platform(1)\fR \fIbundle\-platform\.1\.html\fR
Display platform compatibility information
.
.TP
\fBbundle clean(1)\fR \fIbundle\-clean\.1\.html\fR
Clean up unused gems in your Bundler directory
.
.TP
\fBbundle doctor(1)\fR \fIbundle\-doctor\.1\.html\fR
Display warnings about common problems
.
.TP
\fBbundle remove(1)\fR \fIbundle\-remove\.1\.html\fR
Removes gems from the Gemfile
.
.SH "PLUGINS"
When running a command that isn\'t listed in PRIMARY COMMANDS or UTILITIES, Bundler will try to find an executable on your path named \fBbundler\-<command>\fR and execute it, passing down any extra arguments to it\.
.
.SH "OBSOLETE"
These commands are obsolete and should no longer be used:
.
.IP "\(bu" 4
\fBbundle cache(1)\fR
.
.IP "\(bu" 4
\fBbundle show(1)\fR
.
.IP "" 0

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-GEM" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-gem\fR \- Generate a project skeleton for creating a rubygem
.
.SH "SYNOPSIS"
\fBbundle gem\fR \fIGEM_NAME\fR \fIOPTIONS\fR
.
.SH "DESCRIPTION"
Generates a directory named \fBGEM_NAME\fR with a \fBRakefile\fR, \fBGEM_NAME\.gemspec\fR, and other supporting files and directories that can be used to develop a rubygem with that name\.
.
.P
Run \fBrake \-T\fR in the resulting project for a list of Rake tasks that can be used to test and publish the gem to rubygems\.org\.
.
.P
The generated project skeleton can be customized with OPTIONS, as explained below\. Note that these options can also be specified via Bundler\'s global configuration file using the following names:
.
.IP "\(bu" 4
\fBgem\.coc\fR
.
.IP "\(bu" 4
\fBgem\.mit\fR
.
.IP "\(bu" 4
\fBgem\.test\fR
.
.IP "" 0
.
.SH "OPTIONS"
.
.TP
\fB\-\-exe\fR or \fB\-b\fR or \fB\-\-bin\fR
Specify that Bundler should create a binary executable (as \fBexe/GEM_NAME\fR) in the generated rubygem project\. This binary will also be added to the \fBGEM_NAME\.gemspec\fR manifest\. This behavior is disabled by default\.
.
.TP
\fB\-\-no\-exe\fR
Do not create a binary (overrides \fB\-\-exe\fR specified in the global config)\.
.
.TP
\fB\-\-coc\fR
Add a \fBCODE_OF_CONDUCT\.md\fR file to the root of the generated project\. If this option is unspecified, an interactive prompt will be displayed and the answer will be saved in Bundler\'s global config for future \fBbundle gem\fR use\.
.
.TP
\fB\-\-no\-coc\fR
Do not create a \fBCODE_OF_CONDUCT\.md\fR (overrides \fB\-\-coc\fR specified in the global config)\.
.
.TP
\fB\-\-ext\fR
Add boilerplate for C extension code to the generated project\. This behavior is disabled by default\.
.
.TP
\fB\-\-no\-ext\fR
Do not add C extension code (overrides \fB\-\-ext\fR specified in the global config)\.
.
.TP
\fB\-\-mit\fR
Add an MIT license to a \fBLICENSE\.txt\fR file in the root of the generated project\. Your name from the global git config is used for the copyright statement\. If this option is unspecified, an interactive prompt will be displayed and the answer will be saved in Bundler\'s global config for future \fBbundle gem\fR use\.
.
.TP
\fB\-\-no\-mit\fR
Do not create a \fBLICENSE\.txt\fR (overrides \fB\-\-mit\fR specified in the global config)\.
.
.TP
\fB\-t\fR, \fB\-\-test=minitest\fR, \fB\-\-test=rspec\fR, \fB\-\-test=test\-unit\fR
Specify the test framework that Bundler should use when generating the project\. Acceptable values are \fBminitest\fR, \fBrspec\fR and \fBtest\-unit\fR\. The \fBGEM_NAME\.gemspec\fR will be configured and a skeleton test/spec directory will be created based on this option\. Given no option is specified:
.
.IP
When Bundler is configured to generate tests, this defaults to Bundler\'s global config setting \fBgem\.test\fR\.
.
.IP
When Bundler is configured to not generate tests, an interactive prompt will be displayed and the answer will be used for the current rubygem project\.
.
.IP
When Bundler is unconfigured, an interactive prompt will be displayed and the answer will be saved in Bundler\'s global config for future \fBbundle gem\fR use\.
.
.TP
\fB\-\-ci\fR, \fB\-\-ci=github\fR, \fB\-\-ci=travis\fR, \fB\-\-ci=gitlab\fR, \fB\-\-ci=circle\fR
Specify the continuous integration service that Bundler should use when generating the project\. Acceptable values are \fBgithub\fR, \fBtravis\fR, \fBgitlab\fR and \fBcircle\fR\. A configuration file will be generated in the project directory\. Given no option is specified:
.
.IP
When Bundler is configured to generate CI files, this defaults to Bundler\'s global config setting \fBgem\.ci\fR\.
.
.IP
When Bundler is configured to not generate CI files, an interactive prompt will be displayed and the answer will be used for the current rubygem project\.
.
.IP
When Bundler is unconfigured, an interactive prompt will be displayed and the answer will be saved in Bundler\'s global config for future \fBbundle gem\fR use\.
.
.TP
\fB\-\-linter\fR, \fB\-\-linter=rubocop\fR, \fB\-\-linter=standard\fR
Specify the linter and code formatter that Bundler should add to the project\'s development dependencies\. Acceptable values are \fBrubocop\fR and \fBstandard\fR\. A configuration file will be generated in the project directory\. Given no option is specified:
.
.IP
When Bundler is configured to add a linter, this defaults to Bundler\'s global config setting \fBgem\.linter\fR\.
.
.IP
When Bundler is configured not to add a linter, an interactive prompt will be displayed and the answer will be used for the current rubygem project\.
.
.IP
When Bundler is unconfigured, an interactive prompt will be displayed and the answer will be saved in Bundler\'s global config for future \fBbundle gem\fR use\.
.
.TP
\fB\-e\fR, \fB\-\-edit[=EDITOR]\fR
Open the resulting GEM_NAME\.gemspec in EDITOR, or the default editor if not specified\. The default is \fB$BUNDLER_EDITOR\fR, \fB$VISUAL\fR, or \fB$EDITOR\fR\.
.
.SH "SEE ALSO"
.
.IP "\(bu" 4
bundle config(1) \fIbundle\-config\.1\.html\fR
.
.IP "" 0

.\"Ruby is copyrighted by Yukihiro Matsumoto <matz@netlab.jp>.
.Dd December 16, 2018
.Dt ERB \&1 "Ruby Programmer's Reference Guide"
.Os UNIX
.Sh NAME
.Nm erb
.Nd Ruby Templating
.Sh SYNOPSIS
.Nm
.Op Fl -version
.Op Fl UPdnvx
.Op Fl E Ar ext Ns Op Ns : Ns int
.Op Fl S Ar level
.Op Fl T Ar mode
.Op Fl r Ar library
.Op Fl -
.Op file ...
.Pp
.Sh DESCRIPTION
.Nm
is a command line front-end for
.Li "ERB"
library, which is an implementation of eRuby.
.Pp
ERB provides an easy to use but powerful templating system for Ruby.
Using ERB, actual Ruby code can be added to any plain text document for the
purposes of generating document information details and/or flow control.
.Pp
.Nm
is a part of
.Nm Ruby .
.Pp
.Sh OPTIONS
.Bl -tag -width "1234567890123" -compact
.Pp
.It Fl -version
Prints the version of
.Nm .
.Pp
.It Fl E Ar external Ns Op : Ns Ar internal
.It Fl -encoding Ar external Ns Op : Ns Ar internal
Specifies the default value(s) for external encodings and internal encoding. Values should be separated with colon (:).
.Pp
You can omit the one for internal encodings, then the value
.Pf ( Li "Encoding.default_internal" ) will be nil.
.Pp
.It Fl P
Disables ruby code evaluation for lines beginning with
.Li "%" .
.Pp
.It Fl S Ar level
Specifies the safe level in which eRuby script will run.
.Pp
.It Fl T Ar mode
Specifies trim mode (default 0).
.Ar mode
can be one of
.Bl -hang -offset indent
.It Sy 0
EOL remains after the embedded ruby script is evaluated.
.Pp
.It Sy 1
EOL is removed if the line ends with
.Li "%>" .
.Pp
.It Sy 2
EOL is removed if the line starts with
.Li "<%"
and ends with
.Li "%>" .
.Pp
.It Sy -
EOL is removed if the line ends with
.Li "-%>" .
And leading whitespaces are removed if the erb directive starts with
.Li "<%-" .
.Pp
.El
.It Fl r
Load a library
.Pp
.It Fl U
can be one of
Sets the default value for internal encodings
.Pf ( Li "Encoding.default_internal" ) to UTF-8.
.Pp
.It Fl d
.It Fl -debug
Turns on debug mode.
.Li "$DEBUG"
will be set to true.
.Pp
.It Fl h
.It Fl -help
Prints a summary of the options.
.Pp
.It Fl n
Used with
.Fl x .
Prepends the line number to each line in the output.
.Pp
.It Fl v
Enables verbose mode.
.Li "$VERBOSE"
will be set to true.
.Pp
.It Fl x
Converts the eRuby script into Ruby script and prints it without line numbers.
.Pp
.El
.Pp
.Sh EXAMPLES
Here is an eRuby script
.Bd -literal -offset indent
<?xml version="1.0" ?>
<% require 'prime' -%>
<erb-example>
  <calc><%= 1+1 %></calc>
  <var><%= __FILE__ %></var>
  <library><%= Prime.each(10).to_a.join(", ") %></library>
</erb-example>
.Ed
.Pp
Command
.Dl "% erb -T - example.erb"
prints
.Bd -literal -offset indent
<?xml version="1.0" ?>
<erb-example>
  <calc>2</calc>
  <var>example.erb</var>
  <library>2, 3, 5, 7</library>
</erb-example>
.Ed
.Pp
.Sh SEE ALSO
.Xr ruby 1 .
.Pp
And see
.Xr ri 1
documentation for
.Li "ERB"
class.
.Pp
.Sh REPORTING BUGS
.Bl -bullet
.It
Security vulnerabilities should be reported via an email to
.Mt security@ruby-lang.org .
Reported problems will be published after being fixed.
.Pp
.It
Other bugs and feature requests can be reported via the
Ruby Issue Tracking System
.Pq Lk https://bugs.ruby-lang.org/ .
Do not report security vulnerabilities
via this system because it publishes the vulnerabilities immediately.
.El
.Sh AUTHORS
Written by Masatoshi SEKI.
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-REMOVE" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-remove\fR \- Removes gems from the Gemfile
.
.SH "SYNOPSIS"
\fBbundle remove [GEM [GEM \.\.\.]] [\-\-install]\fR
.
.SH "DESCRIPTION"
Removes the given gems from the Gemfile while ensuring that the resulting Gemfile is still valid\. If a gem cannot be removed, a warning is printed\. If a gem is already absent from the Gemfile, and error is raised\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-install\fR
Runs \fBbundle install\fR after the given gems have been removed from the Gemfile, which ensures that both the lockfile and the installed gems on disk are also updated to remove the given gem(s)\.
.
.P
Example:
.
.P
bundle remove rails
.
.P
bundle remove rails rack
.
.P
bundle remove rails rack \-\-install
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-LIST" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-list\fR \- List all the gems in the bundle
.
.SH "SYNOPSIS"
\fBbundle list\fR [\-\-name\-only] [\-\-paths] [\-\-without\-group=GROUP[ GROUP\.\.\.]] [\-\-only\-group=GROUP[ GROUP\.\.\.]]
.
.SH "DESCRIPTION"
Prints a list of all the gems in the bundle including their version\.
.
.P
Example:
.
.P
bundle list \-\-name\-only
.
.P
bundle list \-\-paths
.
.P
bundle list \-\-without\-group test
.
.P
bundle list \-\-only\-group dev
.
.P
bundle list \-\-only\-group dev test \-\-paths
.
.SH "OPTIONS"
.
.TP
\fB\-\-name\-only\fR
Print only the name of each gem\.
.
.TP
\fB\-\-paths\fR
Print the path to each gem in the bundle\.
.
.TP
\fB\-\-without\-group=<list>\fR
A space\-separated list of groups of gems to skip during printing\.
.
.TP
\fB\-\-only\-group=<list>\fR
A space\-separated list of groups of gems to print\.

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-CACHE" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-cache\fR \- Package your needed \fB\.gem\fR files into your application
.
.SH "SYNOPSIS"
\fBbundle cache\fR
.
.SH "DESCRIPTION"
Copy all of the \fB\.gem\fR files needed to run the application into the \fBvendor/cache\fR directory\. In the future, when running [bundle install(1)][bundle\-install], use the gems in the cache in preference to the ones on \fBrubygems\.org\fR\.
.
.SH "GIT AND PATH GEMS"
The \fBbundle cache\fR command can also package \fB:git\fR and \fB:path\fR dependencies besides \.gem files\. This needs to be explicitly enabled via the \fB\-\-all\fR option\. Once used, the \fB\-\-all\fR option will be remembered\.
.
.SH "SUPPORT FOR MULTIPLE PLATFORMS"
When using gems that have different packages for different platforms, Bundler supports caching of gems for other platforms where the Gemfile has been resolved (i\.e\. present in the lockfile) in \fBvendor/cache\fR\. This needs to be enabled via the \fB\-\-all\-platforms\fR option\. This setting will be remembered in your local bundler configuration\.
.
.SH "REMOTE FETCHING"
By default, if you run \fBbundle install(1)\fR](bundle\-install\.1\.html) after running bundle cache(1) \fIbundle\-cache\.1\.html\fR, bundler will still connect to \fBrubygems\.org\fR to check whether a platform\-specific gem exists for any of the gems in \fBvendor/cache\fR\.
.
.P
For instance, consider this Gemfile(5):
.
.IP "" 4
.
.nf

source "https://rubygems\.org"

gem "nokogiri"
.
.fi
.
.IP "" 0
.
.P
If you run \fBbundle cache\fR under C Ruby, bundler will retrieve the version of \fBnokogiri\fR for the \fB"ruby"\fR platform\. If you deploy to JRuby and run \fBbundle install\fR, bundler is forced to check to see whether a \fB"java"\fR platformed \fBnokogiri\fR exists\.
.
.P
Even though the \fBnokogiri\fR gem for the Ruby platform is \fItechnically\fR acceptable on JRuby, it has a C extension that does not run on JRuby\. As a result, bundler will, by default, still connect to \fBrubygems\.org\fR to check whether it has a version of one of your gems more specific to your platform\.
.
.P
This problem is also not limited to the \fB"java"\fR platform\. A similar (common) problem can happen when developing on Windows and deploying to Linux, or even when developing on OSX and deploying to Linux\.
.
.P
If you know for sure that the gems packaged in \fBvendor/cache\fR are appropriate for the platform you are on, you can run \fBbundle install \-\-local\fR to skip checking for more appropriate gems, and use the ones in \fBvendor/cache\fR\.
.
.P
One way to be sure that you have the right platformed versions of all your gems is to run \fBbundle cache\fR on an identical machine and check in the gems\. For instance, you can run \fBbundle cache\fR on an identical staging box during your staging process, and check in the \fBvendor/cache\fR before deploying to production\.
.
.P
By default, bundle cache(1) \fIbundle\-cache\.1\.html\fR fetches and also installs the gems to the default location\. To package the dependencies to \fBvendor/cache\fR without installing them to the local install location, you can run \fBbundle cache \-\-no\-install\fR\.
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-CONFIG" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-config\fR \- Set bundler configuration options
.
.SH "SYNOPSIS"
\fBbundle config\fR [list|get|set|unset] [\fIname\fR [\fIvalue\fR]]
.
.SH "DESCRIPTION"
This command allows you to interact with Bundler\'s configuration system\.
.
.P
Bundler loads configuration settings in this order:
.
.IP "1." 4
Local config (\fB<project_root>/\.bundle/config\fR or \fB$BUNDLE_APP_CONFIG/config\fR)
.
.IP "2." 4
Environmental variables (\fBENV\fR)
.
.IP "3." 4
Global config (\fB~/\.bundle/config\fR)
.
.IP "4." 4
Bundler default config
.
.IP "" 0
.
.P
Executing \fBbundle config list\fR with will print a list of all bundler configuration for the current bundle, and where that configuration was set\.
.
.P
Executing \fBbundle config get <name>\fR will print the value of that configuration setting, and where it was set\.
.
.P
Executing \fBbundle config set <name> <value>\fR will set that configuration to the value specified for all bundles executed as the current user\. The configuration will be stored in \fB~/\.bundle/config\fR\. If \fIname\fR already is set, \fIname\fR will be overridden and user will be warned\.
.
.P
Executing \fBbundle config set \-\-global <name> <value>\fR works the same as above\.
.
.P
Executing \fBbundle config set \-\-local <name> <value>\fR will set that configuration in the directory for the local application\. The configuration will be stored in \fB<project_root>/\.bundle/config\fR\. If \fBBUNDLE_APP_CONFIG\fR is set, the configuration will be stored in \fB$BUNDLE_APP_CONFIG/config\fR\.
.
.P
Executing \fBbundle config unset <name>\fR will delete the configuration in both local and global sources\.
.
.P
Executing \fBbundle config unset \-\-global <name>\fR will delete the configuration only from the user configuration\.
.
.P
Executing \fBbundle config unset \-\-local <name> <value>\fR will delete the configuration only from the local application\.
.
.P
Executing bundle with the \fBBUNDLE_IGNORE_CONFIG\fR environment variable set will cause it to ignore all configuration\.
.
.SH "REMEMBERING OPTIONS"
Flags passed to \fBbundle install\fR or the Bundler runtime, such as \fB\-\-path foo\fR or \fB\-\-without production\fR, are remembered between commands and saved to your local application\'s configuration (normally, \fB\./\.bundle/config\fR)\.
.
.P
However, this will be changed in bundler 3, so it\'s better not to rely on this behavior\. If these options must be remembered, it\'s better to set them using \fBbundle config\fR (e\.g\., \fBbundle config set \-\-local path foo\fR)\.
.
.P
The options that can be configured are:
.
.TP
\fBbin\fR
Creates a directory (defaults to \fB~/bin\fR) and place any executables from the gem there\. These executables run in Bundler\'s context\. If used, you might add this directory to your environment\'s \fBPATH\fR variable\. For instance, if the \fBrails\fR gem comes with a \fBrails\fR executable, this flag will create a \fBbin/rails\fR executable that ensures that all referred dependencies will be resolved using the bundled gems\.
.
.TP
\fBdeployment\fR
In deployment mode, Bundler will \'roll\-out\' the bundle for \fBproduction\fR use\. Please check carefully if you want to have this option enabled in \fBdevelopment\fR or \fBtest\fR environments\.
.
.TP
\fBpath\fR
The location to install the specified gems to\. This defaults to Rubygems\' setting\. Bundler shares this location with Rubygems, \fBgem install \.\.\.\fR will have gem installed there, too\. Therefore, gems installed without a \fB\-\-path \.\.\.\fR setting will show up by calling \fBgem list\fR\. Accordingly, gems installed to other locations will not get listed\.
.
.TP
\fBwithout\fR
A space\-separated list of groups referencing gems to skip during installation\.
.
.TP
\fBwith\fR
A space\-separated list of groups referencing gems to include during installation\.
.
.SH "BUILD OPTIONS"
You can use \fBbundle config\fR to give Bundler the flags to pass to the gem installer every time bundler tries to install a particular gem\.
.
.P
A very common example, the \fBmysql\fR gem, requires Snow Leopard users to pass configuration flags to \fBgem install\fR to specify where to find the \fBmysql_config\fR executable\.
.
.IP "" 4
.
.nf

gem install mysql \-\- \-\-with\-mysql\-config=/usr/local/mysql/bin/mysql_config
.
.fi
.
.IP "" 0
.
.P
Since the specific location of that executable can change from machine to machine, you can specify these flags on a per\-machine basis\.
.
.IP "" 4
.
.nf

bundle config set \-\-global build\.mysql \-\-with\-mysql\-config=/usr/local/mysql/bin/mysql_config
.
.fi
.
.IP "" 0
.
.P
After running this command, every time bundler needs to install the \fBmysql\fR gem, it will pass along the flags you specified\.
.
.SH "CONFIGURATION KEYS"
Configuration keys in bundler have two forms: the canonical form and the environment variable form\.
.
.P
For instance, passing the \fB\-\-without\fR flag to bundle install(1) \fIbundle\-install\.1\.html\fR prevents Bundler from installing certain groups specified in the Gemfile(5)\. Bundler persists this value in \fBapp/\.bundle/config\fR so that calls to \fBBundler\.setup\fR do not try to find gems from the \fBGemfile\fR that you didn\'t install\. Additionally, subsequent calls to bundle install(1) \fIbundle\-install\.1\.html\fR remember this setting and skip those groups\.
.
.P
The canonical form of this configuration is \fB"without"\fR\. To convert the canonical form to the environment variable form, capitalize it, and prepend \fBBUNDLE_\fR\. The environment variable form of \fB"without"\fR is \fBBUNDLE_WITHOUT\fR\.
.
.P
Any periods in the configuration keys must be replaced with two underscores when setting it via environment variables\. The configuration key \fBlocal\.rack\fR becomes the environment variable \fBBUNDLE_LOCAL__RACK\fR\.
.
.SH "LIST OF AVAILABLE KEYS"
The following is a list of all configuration keys and their purpose\. You can learn more about their operation in bundle install(1) \fIbundle\-install\.1\.html\fR\.
.
.IP "\(bu" 4
\fBallow_deployment_source_credential_changes\fR (\fBBUNDLE_ALLOW_DEPLOYMENT_SOURCE_CREDENTIAL_CHANGES\fR): When in deployment mode, allow changing the credentials to a gem\'s source\. Ex: \fBhttps://some\.host\.com/gems/path/\fR \-> \fBhttps://user_name:password@some\.host\.com/gems/path\fR
.
.IP "\(bu" 4
\fBallow_offline_install\fR (\fBBUNDLE_ALLOW_OFFLINE_INSTALL\fR): Allow Bundler to use cached data when installing without network access\.
.
.IP "\(bu" 4
\fBauto_clean_without_path\fR (\fBBUNDLE_AUTO_CLEAN_WITHOUT_PATH\fR): Automatically run \fBbundle clean\fR after installing when an explicit \fBpath\fR has not been set and Bundler is not installing into the system gems\.
.
.IP "\(bu" 4
\fBauto_install\fR (\fBBUNDLE_AUTO_INSTALL\fR): Automatically run \fBbundle install\fR when gems are missing\.
.
.IP "\(bu" 4
\fBbin\fR (\fBBUNDLE_BIN\fR): Install executables from gems in the bundle to the specified directory\. Defaults to \fBfalse\fR\.
.
.IP "\(bu" 4
\fBcache_all\fR (\fBBUNDLE_CACHE_ALL\fR): Cache all gems, including path and git gems\. This needs to be explicitly configured on bundler 1 and bundler 2, but will be the default on bundler 3\.
.
.IP "\(bu" 4
\fBcache_all_platforms\fR (\fBBUNDLE_CACHE_ALL_PLATFORMS\fR): Cache gems for all platforms\.
.
.IP "\(bu" 4
\fBcache_path\fR (\fBBUNDLE_CACHE_PATH\fR): The directory that bundler will place cached gems in when running \fBbundle package\fR, and that bundler will look in when installing gems\. Defaults to \fBvendor/cache\fR\.
.
.IP "\(bu" 4
\fBclean\fR (\fBBUNDLE_CLEAN\fR): Whether Bundler should run \fBbundle clean\fR automatically after \fBbundle install\fR\.
.
.IP "\(bu" 4
\fBconsole\fR (\fBBUNDLE_CONSOLE\fR): The console that \fBbundle console\fR starts\. Defaults to \fBirb\fR\.
.
.IP "\(bu" 4
\fBdefault_install_uses_path\fR (\fBBUNDLE_DEFAULT_INSTALL_USES_PATH\fR): Whether a \fBbundle install\fR without an explicit \fB\-\-path\fR argument defaults to installing gems in \fB\.bundle\fR\.
.
.IP "\(bu" 4
\fBdeployment\fR (\fBBUNDLE_DEPLOYMENT\fR): Disallow changes to the \fBGemfile\fR\. When the \fBGemfile\fR is changed and the lockfile has not been updated, running Bundler commands will be blocked\.
.
.IP "\(bu" 4
\fBdisable_checksum_validation\fR (\fBBUNDLE_DISABLE_CHECKSUM_VALIDATION\fR): Allow installing gems even if they do not match the checksum provided by RubyGems\.
.
.IP "\(bu" 4
\fBdisable_exec_load\fR (\fBBUNDLE_DISABLE_EXEC_LOAD\fR): Stop Bundler from using \fBload\fR to launch an executable in\-process in \fBbundle exec\fR\.
.
.IP "\(bu" 4
\fBdisable_local_branch_check\fR (\fBBUNDLE_DISABLE_LOCAL_BRANCH_CHECK\fR): Allow Bundler to use a local git override without a branch specified in the Gemfile\.
.
.IP "\(bu" 4
\fBdisable_local_revision_check\fR (\fBBUNDLE_DISABLE_LOCAL_REVISION_CHECK\fR): Allow Bundler to use a local git override without checking if the revision present in the lockfile is present in the repository\.
.
.IP "\(bu" 4
\fBdisable_shared_gems\fR (\fBBUNDLE_DISABLE_SHARED_GEMS\fR): Stop Bundler from accessing gems installed to RubyGems\' normal location\.
.
.IP "\(bu" 4
\fBdisable_version_check\fR (\fBBUNDLE_DISABLE_VERSION_CHECK\fR): Stop Bundler from checking if a newer Bundler version is available on rubygems\.org\.
.
.IP "\(bu" 4
\fBforce_ruby_platform\fR (\fBBUNDLE_FORCE_RUBY_PLATFORM\fR): Ignore the current machine\'s platform and install only \fBruby\fR platform gems\. As a result, gems with native extensions will be compiled from source\.
.
.IP "\(bu" 4
\fBfrozen\fR (\fBBUNDLE_FROZEN\fR): Disallow changes to the \fBGemfile\fR\. When the \fBGemfile\fR is changed and the lockfile has not been updated, running Bundler commands will be blocked\. Defaults to \fBtrue\fR when \fB\-\-deployment\fR is used\.
.
.IP "\(bu" 4
\fBgem\.github_username\fR (\fBBUNDLE_GEM__GITHUB_USERNAME\fR): Sets a GitHub username or organization to be used in \fBREADME\fR file when you create a new gem via \fBbundle gem\fR command\. It can be overridden by passing an explicit \fB\-\-github\-username\fR flag to \fBbundle gem\fR\.
.
.IP "\(bu" 4
\fBgem\.push_key\fR (\fBBUNDLE_GEM__PUSH_KEY\fR): Sets the \fB\-\-key\fR parameter for \fBgem push\fR when using the \fBrake release\fR command with a private gemstash server\.
.
.IP "\(bu" 4
\fBgemfile\fR (\fBBUNDLE_GEMFILE\fR): The name of the file that bundler should use as the \fBGemfile\fR\. This location of this file also sets the root of the project, which is used to resolve relative paths in the \fBGemfile\fR, among other things\. By default, bundler will search up from the current working directory until it finds a \fBGemfile\fR\.
.
.IP "\(bu" 4
\fBglobal_gem_cache\fR (\fBBUNDLE_GLOBAL_GEM_CACHE\fR): Whether Bundler should cache all gems globally, rather than locally to the installing Ruby installation\.
.
.IP "\(bu" 4
\fBignore_messages\fR (\fBBUNDLE_IGNORE_MESSAGES\fR): When set, no post install messages will be printed\. To silence a single gem, use dot notation like \fBignore_messages\.httparty true\fR\.
.
.IP "\(bu" 4
\fBinit_gems_rb\fR (\fBBUNDLE_INIT_GEMS_RB\fR): Generate a \fBgems\.rb\fR instead of a \fBGemfile\fR when running \fBbundle init\fR\.
.
.IP "\(bu" 4
\fBjobs\fR (\fBBUNDLE_JOBS\fR): The number of gems Bundler can install in parallel\. Defaults to 1 on Windows, and to the the number of processors on other platforms\.
.
.IP "\(bu" 4
\fBno_install\fR (\fBBUNDLE_NO_INSTALL\fR): Whether \fBbundle package\fR should skip installing gems\.
.
.IP "\(bu" 4
\fBno_prune\fR (\fBBUNDLE_NO_PRUNE\fR): Whether Bundler should leave outdated gems unpruned when caching\.
.
.IP "\(bu" 4
\fBpath\fR (\fBBUNDLE_PATH\fR): The location on disk where all gems in your bundle will be located regardless of \fB$GEM_HOME\fR or \fB$GEM_PATH\fR values\. Bundle gems not found in this location will be installed by \fBbundle install\fR\. Defaults to \fBGem\.dir\fR\. When \-\-deployment is used, defaults to vendor/bundle\.
.
.IP "\(bu" 4
\fBpath\.system\fR (\fBBUNDLE_PATH__SYSTEM\fR): Whether Bundler will install gems into the default system path (\fBGem\.dir\fR)\.
.
.IP "\(bu" 4
\fBpath_relative_to_cwd\fR (\fBBUNDLE_PATH_RELATIVE_TO_CWD\fR) Makes \fB\-\-path\fR relative to the CWD instead of the \fBGemfile\fR\.
.
.IP "\(bu" 4
\fBplugins\fR (\fBBUNDLE_PLUGINS\fR): Enable Bundler\'s experimental plugin system\.
.
.IP "\(bu" 4
\fBprefer_patch\fR (BUNDLE_PREFER_PATCH): Prefer updating only to next patch version during updates\. Makes \fBbundle update\fR calls equivalent to \fBbundler update \-\-patch\fR\.
.
.IP "\(bu" 4
\fBprint_only_version_number\fR (\fBBUNDLE_PRINT_ONLY_VERSION_NUMBER\fR): Print only version number from \fBbundler \-\-version\fR\.
.
.IP "\(bu" 4
\fBredirect\fR (\fBBUNDLE_REDIRECT\fR): The number of redirects allowed for network requests\. Defaults to \fB5\fR\.
.
.IP "\(bu" 4
\fBretry\fR (\fBBUNDLE_RETRY\fR): The number of times to retry failed network requests\. Defaults to \fB3\fR\.
.
.IP "\(bu" 4
\fBsetup_makes_kernel_gem_public\fR (\fBBUNDLE_SETUP_MAKES_KERNEL_GEM_PUBLIC\fR): Have \fBBundler\.setup\fR make the \fBKernel#gem\fR method public, even though RubyGems declares it as private\.
.
.IP "\(bu" 4
\fBshebang\fR (\fBBUNDLE_SHEBANG\fR): The program name that should be invoked for generated binstubs\. Defaults to the ruby install name used to generate the binstub\.
.
.IP "\(bu" 4
\fBsilence_deprecations\fR (\fBBUNDLE_SILENCE_DEPRECATIONS\fR): Whether Bundler should silence deprecation warnings for behavior that will be changed in the next major version\.
.
.IP "\(bu" 4
\fBsilence_root_warning\fR (\fBBUNDLE_SILENCE_ROOT_WARNING\fR): Silence the warning Bundler prints when installing gems as root\.
.
.IP "\(bu" 4
\fBssl_ca_cert\fR (\fBBUNDLE_SSL_CA_CERT\fR): Path to a designated CA certificate file or folder containing multiple certificates for trusted CAs in PEM format\.
.
.IP "\(bu" 4
\fBssl_client_cert\fR (\fBBUNDLE_SSL_CLIENT_CERT\fR): Path to a designated file containing a X\.509 client certificate and key in PEM format\.
.
.IP "\(bu" 4
\fBssl_verify_mode\fR (\fBBUNDLE_SSL_VERIFY_MODE\fR): The SSL verification mode Bundler uses when making HTTPS requests\. Defaults to verify peer\.
.
.IP "\(bu" 4
\fBsuppress_install_using_messages\fR (\fBBUNDLE_SUPPRESS_INSTALL_USING_MESSAGES\fR): Avoid printing \fBUsing \.\.\.\fR messages during installation when the version of a gem has not changed\.
.
.IP "\(bu" 4
\fBsystem_bindir\fR (\fBBUNDLE_SYSTEM_BINDIR\fR): The location where RubyGems installs binstubs\. Defaults to \fBGem\.bindir\fR\.
.
.IP "\(bu" 4
\fBtimeout\fR (\fBBUNDLE_TIMEOUT\fR): The seconds allowed before timing out for network requests\. Defaults to \fB10\fR\.
.
.IP "\(bu" 4
\fBupdate_requires_all_flag\fR (\fBBUNDLE_UPDATE_REQUIRES_ALL_FLAG\fR): Require passing \fB\-\-all\fR to \fBbundle update\fR when everything should be updated, and disallow passing no options to \fBbundle update\fR\.
.
.IP "\(bu" 4
\fBuser_agent\fR (\fBBUNDLE_USER_AGENT\fR): The custom user agent fragment Bundler includes in API requests\.
.
.IP "\(bu" 4
\fBwith\fR (\fBBUNDLE_WITH\fR): A \fB:\fR\-separated list of groups whose gems bundler should install\.
.
.IP "\(bu" 4
\fBwithout\fR (\fBBUNDLE_WITHOUT\fR): A \fB:\fR\-separated list of groups whose gems bundler should not install\.
.
.IP "" 0
.
.P
In general, you should set these settings per\-application by using the applicable flag to the bundle install(1) \fIbundle\-install\.1\.html\fR or bundle package(1) \fIbundle\-package\.1\.html\fR command\.
.
.P
You can set them globally either via environment variables or \fBbundle config\fR, whichever is preferable for your setup\. If you use both, environment variables will take preference over global settings\.
.
.SH "LOCAL GIT REPOS"
Bundler also allows you to work against a git repository locally instead of using the remote version\. This can be achieved by setting up a local override:
.
.IP "" 4
.
.nf

bundle config set \-\-local local\.GEM_NAME /path/to/local/git/repository
.
.fi
.
.IP "" 0
.
.P
For example, in order to use a local Rack repository, a developer could call:
.
.IP "" 4
.
.nf

bundle config set \-\-local local\.rack ~/Work/git/rack
.
.fi
.
.IP "" 0
.
.P
Now instead of checking out the remote git repository, the local override will be used\. Similar to a path source, every time the local git repository change, changes will be automatically picked up by Bundler\. This means a commit in the local git repo will update the revision in the \fBGemfile\.lock\fR to the local git repo revision\. This requires the same attention as git submodules\. Before pushing to the remote, you need to ensure the local override was pushed, otherwise you may point to a commit that only exists in your local machine\. You\'ll also need to CGI escape your usernames and passwords as well\.
.
.P
Bundler does many checks to ensure a developer won\'t work with invalid references\. Particularly, we force a developer to specify a branch in the \fBGemfile\fR in order to use this feature\. If the branch specified in the \fBGemfile\fR and the current branch in the local git repository do not match, Bundler will abort\. This ensures that a developer is always working against the correct branches, and prevents accidental locking to a different branch\.
.
.P
Finally, Bundler also ensures that the current revision in the \fBGemfile\.lock\fR exists in the local git repository\. By doing this, Bundler forces you to fetch the latest changes in the remotes\.
.
.SH "MIRRORS OF GEM SOURCES"
Bundler supports overriding gem sources with mirrors\. This allows you to configure rubygems\.org as the gem source in your Gemfile while still using your mirror to fetch gems\.
.
.IP "" 4
.
.nf

bundle config set \-\-global mirror\.SOURCE_URL MIRROR_URL
.
.fi
.
.IP "" 0
.
.P
For example, to use a mirror of rubygems\.org hosted at rubygems\-mirror\.org:
.
.IP "" 4
.
.nf

bundle config set \-\-global mirror\.http://rubygems\.org http://rubygems\-mirror\.org
.
.fi
.
.IP "" 0
.
.P
Each mirror also provides a fallback timeout setting\. If the mirror does not respond within the fallback timeout, Bundler will try to use the original server instead of the mirror\.
.
.IP "" 4
.
.nf

bundle config set \-\-global mirror\.SOURCE_URL\.fallback_timeout TIMEOUT
.
.fi
.
.IP "" 0
.
.P
For example, to fall back to rubygems\.org after 3 seconds:
.
.IP "" 4
.
.nf

bundle config set \-\-global mirror\.https://rubygems\.org\.fallback_timeout 3
.
.fi
.
.IP "" 0
.
.P
The default fallback timeout is 0\.1 seconds, but the setting can currently only accept whole seconds (for example, 1, 15, or 30)\.
.
.SH "CREDENTIALS FOR GEM SOURCES"
Bundler allows you to configure credentials for any gem source, which allows you to avoid putting secrets into your Gemfile\.
.
.IP "" 4
.
.nf

bundle config set \-\-global SOURCE_HOSTNAME USERNAME:PASSWORD
.
.fi
.
.IP "" 0
.
.P
For example, to save the credentials of user \fBclaudette\fR for the gem source at \fBgems\.longerous\.com\fR, you would run:
.
.IP "" 4
.
.nf

bundle config set \-\-global gems\.longerous\.com claudette:s00pers3krit
.
.fi
.
.IP "" 0
.
.P
Or you can set the credentials as an environment variable like this:
.
.IP "" 4
.
.nf

export BUNDLE_GEMS__LONGEROUS__COM="claudette:s00pers3krit"
.
.fi
.
.IP "" 0
.
.P
For gems with a git source with HTTP(S) URL you can specify credentials like so:
.
.IP "" 4
.
.nf

bundle config set \-\-global https://github\.com/rubygems/rubygems\.git username:password
.
.fi
.
.IP "" 0
.
.P
Or you can set the credentials as an environment variable like so:
.
.IP "" 4
.
.nf

export BUNDLE_GITHUB__COM=username:password
.
.fi
.
.IP "" 0
.
.P
This is especially useful for private repositories on hosts such as Github, where you can use personal OAuth tokens:
.
.IP "" 4
.
.nf

export BUNDLE_GITHUB__COM=abcd0123generatedtoken:x\-oauth\-basic
.
.fi
.
.IP "" 0
.
.P
Note that any configured credentials will be redacted by informative commands such as \fBbundle config list\fR or \fBbundle config get\fR, unless you use the \fB\-\-parseable\fR flag\. This is to avoid unintentionally leaking credentials when copy\-pasting bundler output\.
.
.P
Also note that to guarantee a sane mapping between valid environment variable names and valid host names, bundler makes the following transformations:
.
.IP "\(bu" 4
Any \fB\-\fR characters in a host name are mapped to a triple dash (\fB___\fR) in the corresponding environment variable\.
.
.IP "\(bu" 4
Any \fB\.\fR characters in a host name are mapped to a double dash (\fB__\fR) in the corresponding environment variable\.
.
.IP "" 0
.
.P
This means that if you have a gem server named \fBmy\.gem\-host\.com\fR, you\'ll need to use the \fBBUNDLE_MY__GEM___HOST__COM\fR variable to configure credentials for it through ENV\.
.
.SH "CONFIGURE BUNDLER DIRECTORIES"
Bundler\'s home, config, cache and plugin directories are able to be configured through environment variables\. The default location for Bundler\'s home directory is \fB~/\.bundle\fR, which all directories inherit from by default\. The following outlines the available environment variables and their default values
.
.IP "" 4
.
.nf

BUNDLE_USER_HOME : $HOME/\.bundle
BUNDLE_USER_CACHE : $BUNDLE_USER_HOME/cache
BUNDLE_USER_CONFIG : $BUNDLE_USER_HOME/config
BUNDLE_USER_PLUGIN : $BUNDLE_USER_HOME/plugin
.
.fi
.
.IP "" 0

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-BINSTUBS" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-binstubs\fR \- Install the binstubs of the listed gems
.
.SH "SYNOPSIS"
\fBbundle binstubs\fR \fIGEM_NAME\fR [\-\-force] [\-\-path PATH] [\-\-standalone]
.
.SH "DESCRIPTION"
Binstubs are scripts that wrap around executables\. Bundler creates a small Ruby file (a binstub) that loads Bundler, runs the command, and puts it into \fBbin/\fR\. Binstubs are a shortcut\-or alternative\- to always using \fBbundle exec\fR\. This gives you a file that can be run directly, and one that will always run the correct gem version used by the application\.
.
.P
For example, if you run \fBbundle binstubs rspec\-core\fR, Bundler will create the file \fBbin/rspec\fR\. That file will contain enough code to load Bundler, tell it to load the bundled gems, and then run rspec\.
.
.P
This command generates binstubs for executables in \fBGEM_NAME\fR\. Binstubs are put into \fBbin\fR, or the \fB\-\-path\fR directory if one has been set\. Calling binstubs with [GEM [GEM]] will create binstubs for all given gems\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-force\fR
Overwrite existing binstubs if they exist\.
.
.TP
\fB\-\-path\fR
The location to install the specified binstubs to\. This defaults to \fBbin\fR\.
.
.TP
\fB\-\-standalone\fR
Makes binstubs that can work without depending on Rubygems or Bundler at runtime\.
.
.TP
\fB\-\-shebang\fR
Specify a different shebang executable name than the default (default \'ruby\')
.
.TP
\fB\-\-all\fR
Create binstubs for all gems in the bundle\.

.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-OUTDATED" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-outdated\fR \- List installed gems with newer versions available
.
.SH "SYNOPSIS"
\fBbundle outdated\fR [GEM] [\-\-local] [\-\-pre] [\-\-source] [\-\-strict] [\-\-parseable | \-\-porcelain] [\-\-group=GROUP] [\-\-groups] [\-\-update\-strict] [\-\-patch|\-\-minor|\-\-major] [\-\-filter\-major] [\-\-filter\-minor] [\-\-filter\-patch] [\-\-only\-explicit]
.
.SH "DESCRIPTION"
Outdated lists the names and versions of gems that have a newer version available in the given source\. Calling outdated with [GEM [GEM]] will only check for newer versions of the given gems\. Prerelease gems are ignored by default\. If your gems are up to date, Bundler will exit with a status of 0\. Otherwise, it will exit 1\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-local\fR
Do not attempt to fetch gems remotely and use the gem cache instead\.
.
.TP
\fB\-\-pre\fR
Check for newer pre\-release gems\.
.
.TP
\fB\-\-source\fR
Check against a specific source\.
.
.TP
\fB\-\-strict\fR
Only list newer versions allowed by your Gemfile requirements\.
.
.TP
\fB\-\-parseable\fR, \fB\-\-porcelain\fR
Use minimal formatting for more parseable output\.
.
.TP
\fB\-\-group\fR
List gems from a specific group\.
.
.TP
\fB\-\-groups\fR
List gems organized by groups\.
.
.TP
\fB\-\-update\-strict\fR
Strict conservative resolution, do not allow any gem to be updated past latest \-\-patch | \-\-minor| \-\-major\.
.
.TP
\fB\-\-minor\fR
Prefer updating only to next minor version\.
.
.TP
\fB\-\-major\fR
Prefer updating to next major version (default)\.
.
.TP
\fB\-\-patch\fR
Prefer updating only to next patch version\.
.
.TP
\fB\-\-filter\-major\fR
Only list major newer versions\.
.
.TP
\fB\-\-filter\-minor\fR
Only list minor newer versions\.
.
.TP
\fB\-\-filter\-patch\fR
Only list patch newer versions\.
.
.TP
\fB\-\-only\-explicit\fR
Only list gems specified in your Gemfile, not their dependencies\.
.
.SH "PATCH LEVEL OPTIONS"
See bundle update(1) \fIbundle\-update\.1\.html\fR for details\.
.
.P
One difference between the patch level options in \fBbundle update\fR and here is the \fB\-\-strict\fR option\. \fB\-\-strict\fR was already an option on outdated before the patch level options were added\. \fB\-\-strict\fR wasn\'t altered, and the \fB\-\-update\-strict\fR option on \fBoutdated\fR reflects what \fB\-\-strict\fR does on \fBbundle update\fR\.
.
.SH "FILTERING OUTPUT"
The 3 filtering options do not affect the resolution of versions, merely what versions are shown in the output\.
.
.P
If the regular output shows the following:
.
.IP "" 4
.
.nf

* faker (newest 1\.6\.6, installed 1\.6\.5, requested ~> 1\.4) in groups "development, test"
* hashie (newest 3\.4\.6, installed 1\.2\.0, requested = 1\.2\.0) in groups "default"
* headless (newest 2\.3\.1, installed 2\.2\.3) in groups "test"
.
.fi
.
.IP "" 0
.
.P
\fB\-\-filter\-major\fR would only show:
.
.IP "" 4
.
.nf

* hashie (newest 3\.4\.6, installed 1\.2\.0, requested = 1\.2\.0) in groups "default"
.
.fi
.
.IP "" 0
.
.P
\fB\-\-filter\-minor\fR would only show:
.
.IP "" 4
.
.nf

* headless (newest 2\.3\.1, installed 2\.2\.3) in groups "test"
.
.fi
.
.IP "" 0
.
.P
\fB\-\-filter\-patch\fR would only show:
.
.IP "" 4
.
.nf

* faker (newest 1\.6\.6, installed 1\.6\.5, requested ~> 1\.4) in groups "development, test"
.
.fi
.
.IP "" 0
.
.P
Filter options can be combined\. \fB\-\-filter\-minor\fR and \fB\-\-filter\-patch\fR would show:
.
.IP "" 4
.
.nf

* faker (newest 1\.6\.6, installed 1\.6\.5, requested ~> 1\.4) in groups "development, test"
* headless (newest 2\.3\.1, installed 2\.2\.3) in groups "test"
.
.fi
.
.IP "" 0
.
.P
Combining all three \fBfilter\fR options would be the same result as providing none of them\.
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "BUNDLE\-EXEC" "1" "December 2021" "" ""
.
.SH "NAME"
\fBbundle\-exec\fR \- Execute a command in the context of the bundle
.
.SH "SYNOPSIS"
\fBbundle exec\fR [\-\-keep\-file\-descriptors] \fIcommand\fR
.
.SH "DESCRIPTION"
This command executes the command, making all gems specified in the [\fBGemfile(5)\fR][Gemfile(5)] available to \fBrequire\fR in Ruby programs\.
.
.P
Essentially, if you would normally have run something like \fBrspec spec/my_spec\.rb\fR, and you want to use the gems specified in the [\fBGemfile(5)\fR][Gemfile(5)] and installed via bundle install(1) \fIbundle\-install\.1\.html\fR, you should run \fBbundle exec rspec spec/my_spec\.rb\fR\.
.
.P
Note that \fBbundle exec\fR does not require that an executable is available on your shell\'s \fB$PATH\fR\.
.
.SH "OPTIONS"
.
.TP
\fB\-\-keep\-file\-descriptors\fR
Exec in Ruby 2\.0 began discarding non\-standard file descriptors\. When this flag is passed, exec will revert to the 1\.9 behaviour of passing all file descriptors to the new process\.
.
.SH "BUNDLE INSTALL \-\-BINSTUBS"
If you use the \fB\-\-binstubs\fR flag in bundle install(1) \fIbundle\-install\.1\.html\fR, Bundler will automatically create a directory (which defaults to \fBapp_root/bin\fR) containing all of the executables available from gems in the bundle\.
.
.P
After using \fB\-\-binstubs\fR, \fBbin/rspec spec/my_spec\.rb\fR is identical to \fBbundle exec rspec spec/my_spec\.rb\fR\.
.
.SH "ENVIRONMENT MODIFICATIONS"
\fBbundle exec\fR makes a number of changes to the shell environment, then executes the command you specify in full\.
.
.IP "\(bu" 4
make sure that it\'s still possible to shell out to \fBbundle\fR from inside a command invoked by \fBbundle exec\fR (using \fB$BUNDLE_BIN_PATH\fR)
.
.IP "\(bu" 4
put the directory containing executables (like \fBrails\fR, \fBrspec\fR, \fBrackup\fR) for your bundle on \fB$PATH\fR
.
.IP "\(bu" 4
make sure that if bundler is invoked in the subshell, it uses the same \fBGemfile\fR (by setting \fBBUNDLE_GEMFILE\fR)
.
.IP "\(bu" 4
add \fB\-rbundler/setup\fR to \fB$RUBYOPT\fR, which makes sure that Ruby programs invoked in the subshell can see the gems in the bundle
.
.IP "" 0
.
.P
It also modifies Rubygems:
.
.IP "\(bu" 4
disallow loading additional gems not in the bundle
.
.IP "\(bu" 4
modify the \fBgem\fR method to be a no\-op if a gem matching the requirements is in the bundle, and to raise a \fBGem::LoadError\fR if it\'s not
.
.IP "\(bu" 4
Define \fBGem\.refresh\fR to be a no\-op, since the source index is always frozen when using bundler, and to prevent gems from the system leaking into the environment
.
.IP "\(bu" 4
Override \fBGem\.bin_path\fR to use the gems in the bundle, making system executables work
.
.IP "\(bu" 4
Add all gems in the bundle into Gem\.loaded_specs
.
.IP "" 0
.
.P
Finally, \fBbundle exec\fR also implicitly modifies \fBGemfile\.lock\fR if the lockfile and the Gemfile do not match\. Bundler needs the Gemfile to determine things such as a gem\'s groups, \fBautorequire\fR, and platforms, etc\., and that information isn\'t stored in the lockfile\. The Gemfile and lockfile must be synced in order to \fBbundle exec\fR successfully, so \fBbundle exec\fR updates the lockfile beforehand\.
.
.SS "Loading"
By default, when attempting to \fBbundle exec\fR to a file with a ruby shebang, Bundler will \fBKernel\.load\fR that file instead of using \fBKernel\.exec\fR\. For the vast majority of cases, this is a performance improvement\. In a rare few cases, this could cause some subtle side\-effects (such as dependence on the exact contents of \fB$0\fR or \fB__FILE__\fR) and the optimization can be disabled by enabling the \fBdisable_exec_load\fR setting\.
.
.SS "Shelling out"
Any Ruby code that opens a subshell (like \fBsystem\fR, backticks, or \fB%x{}\fR) will automatically use the current Bundler environment\. If you need to shell out to a Ruby command that is not part of your current bundle, use the \fBwith_clean_env\fR method with a block\. Any subshells created inside the block will be given the environment present before Bundler was activated\. For example, Homebrew commands run Ruby, but don\'t work inside a bundle:
.
.IP "" 4
.
.nf

Bundler\.with_clean_env do
  `brew install wget`
end
.
.fi
.
.IP "" 0
.
.P
Using \fBwith_clean_env\fR is also necessary if you are shelling out to a different bundle\. Any Bundler commands run in a subshell will inherit the current Gemfile, so commands that need to run in the context of a different bundle also need to use \fBwith_clean_env\fR\.
.
.IP "" 4
.
.nf

Bundler\.with_clean_env do
  Dir\.chdir "/other/bundler/project" do
    `bundle exec \./script`
  end
end
.
.fi
.
.IP "" 0
.
.P
Bundler provides convenience helpers that wrap \fBsystem\fR and \fBexec\fR, and they can be used like this:
.
.IP "" 4
.
.nf

Bundler\.clean_system(\'brew install wget\')
Bundler\.clean_exec(\'brew install wget\')
.
.fi
.
.IP "" 0
.
.SH "RUBYGEMS PLUGINS"
At present, the Rubygems plugin system requires all files named \fBrubygems_plugin\.rb\fR on the load path of \fIany\fR installed gem when any Ruby code requires \fBrubygems\.rb\fR\. This includes executables installed into the system, like \fBrails\fR, \fBrackup\fR, and \fBrspec\fR\.
.
.P
Since Rubygems plugins can contain arbitrary Ruby code, they commonly end up activating themselves or their dependencies\.
.
.P
For instance, the \fBgemcutter 0\.5\fR gem depended on \fBjson_pure\fR\. If you had that version of gemcutter installed (even if you \fIalso\fR had a newer version without this problem), Rubygems would activate \fBgemcutter 0\.5\fR and \fBjson_pure <latest>\fR\.
.
.P
If your Gemfile(5) also contained \fBjson_pure\fR (or a gem with a dependency on \fBjson_pure\fR), the latest version on your system might conflict with the version in your Gemfile(5), or the snapshot version in your \fBGemfile\.lock\fR\.
.
.P
If this happens, bundler will say:
.
.IP "" 4
.
.nf

You have already activated json_pure 1\.4\.6 but your Gemfile
requires json_pure 1\.4\.3\. Consider using bundle exec\.
.
.fi
.
.IP "" 0
.
.P
In this situation, you almost certainly want to remove the underlying gem with the problematic gem plugin\. In general, the authors of these plugins (in this case, the \fBgemcutter\fR gem) have released newer versions that are more careful in their plugins\.
.
.P
You can find a list of all the gems containing gem plugins by running
.
.IP "" 4
.
.nf

ruby \-rrubygems \-e "puts Gem\.find_files(\'rubygems_plugin\.rb\')"
.
.fi
.
.IP "" 0
.
.P
At the very least, you should remove all but the newest version of each gem plugin, and also remove all gem plugins that you aren\'t using (\fBgem uninstall gem_name\fR)\.
/* SystemTap tapset to make it easier to trace Ruby 2.0
 *
 * All probes provided by Ruby can be listed using following command
 * (the path to the library must be adjuste appropriately):
 *
 * stap -L 'process("/opt/alt/ruby30/lib*\/libruby.so.3.0").mark("*")'
 */

/**
 * probe ruby.array.create - Allocation of new array.
 *
 * @size: Number of elements (an int)
 * @file: The file name where the method is being called (string)
 * @line: The line number where the method is being called (int)
 */
probe ruby.array.create =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("array__create")
{
	size = $arg1
	file = user_string($arg2)
	line = $arg3
}

/**
 * probe ruby.cmethod.entry - Fired just before a method implemented in C is entered.
 *
 * @classname: Name of the class (string)
 * @methodname: The method about bo be executed (string)
 * @file: The file name where the method is being called (string)
 * @line: The line number where the method is being called (int)
 */
probe ruby.cmethod.entry =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("cmethod__entry")
{
	classname  = user_string($arg1)
	methodname = user_string($arg2)
	file = user_string($arg3)
	line = $arg4
}

/**
 * probe ruby.cmethod.return - Fired just after a method implemented in C has returned.
 *
 * @classname: Name of the class (string)
 * @methodname: The executed method (string)
 * @file: The file name where the method is being called (string)
 * @line: The line number where the method is being called (int)
 */
probe ruby.cmethod.return =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("cmethod__return")
{
	classname  = user_string($arg1)
	methodname = user_string($arg2)
	file = user_string($arg3)
	line = $arg4
}

/**
 * probe ruby.find.require.entry - Fired when require starts to search load
 * path for suitable file to require.
 *
 * @requiredfile: The name of the file to be required (string)
 * @file: The file name where the method is being called (string)
 * @line: The line number where the method is being called (int)
 */
probe ruby.find.require.entry =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("find__require__entry")
{
	requiredfile = user_string($arg1)
	file = user_string($arg2)
	line = $arg3
}

/**
 * probe ruby.find.require.return - Fired just after require has finished
 * search of load path for suitable file to require.
 *
 * @requiredfile: The name of the file to be required (string)
 * @file: The file name where the method is being called (string)
 * @line: The line number where the method is being called (int)
 */
probe ruby.find.require.return =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("find__require__return")
{
	requiredfile = user_string($arg1)
	file = user_string($arg2)
	line = $arg3
}

/**
 * probe ruby.gc.mark.begin - Fired when a GC mark phase is about to start.
 *
 * It takes no arguments.
 */
probe ruby.gc.mark.begin =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("gc__mark__begin")
{
}

/**
 * probe ruby.gc.mark.end - Fired when a GC mark phase has ended.
 *
 * It takes no arguments.
 */
probe ruby.gc.mark.end =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("gc__mark__end")
{
}

/**
 * probe ruby.gc.sweep.begin - Fired when a GC sweep phase is about to start.
 *
 * It takes no arguments.
 */
probe ruby.gc.sweep.begin =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("gc__sweep__begin")
{
}

/**
 * probe ruby.gc.sweep.end - Fired when a GC sweep phase has ended.
 *
 * It takes no arguments.
 */
probe ruby.gc.sweep.end =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("gc__sweep__end")
{
}

/**
 * probe ruby.hash.create - Allocation of new hash.
 *
 * @size: Number of elements (int)
 * @file: The file name where the method is being called (string)
 * @line: The line number where the method is being called (int)
 */
probe ruby.hash.create =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("hash__create")
{
	size = $arg1
	file = user_string($arg2)
	line = $arg3
}

/**
 * probe ruby.load.entry - Fired when calls to "load" are made.
 *
 * @loadedfile: The name of the file to be loaded (string)
 * @file: The file name where the method is being called (string)
 * @line: The line number where the method is being called (int)
 */
probe ruby.load.entry =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("load__entry")
{
	loadedfile = user_string($arg1)
	file = user_string($arg2)
	line = $arg3
}

/**
 * probe ruby.load.return - Fired just after require has finished
 * search of load path for suitable file to require.
 *
 * @loadedfile: The name of the file that was loaded (string)
 */
probe ruby.load.return =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("load__return")
{
	loadedfile = user_string($arg1)
}

/**
 * probe ruby.method.entry - Fired just before a method implemented in Ruby is entered.
 *
 * @classname: Name of the class (string)
 * @methodname: The method about bo be executed (string)
 * @file: The file name where the method is being called (string)
 * @line: The line number where the method is being called (int)
 */
probe ruby.method.entry =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("method__entry")
{
	classname  = user_string($arg1)
	methodname = user_string($arg2)
	file = user_string($arg3)
	line = $arg4
}

/**
 * probe ruby.method.return - Fired just after a method implemented in Ruby has returned.
 *
 * @classname: Name of the class (string)
 * @methodname: The executed method (string)
 * @file: The file name where the method is being called (string)
 * @line: The line number where the method is being called (int)
 */
probe ruby.method.return =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("method__return")
{
	classname  = user_string($arg1)
	methodname = user_string($arg2)
	file = user_string($arg3)
	line = $arg4
}

/**
 * probe ruby.object.create - Allocation of new object.
 *
 * @classname: Name of the class (string)
 * @file: The file name where the method is being called (string)
 * @line: The line number where the method is being called (int)
 */
probe ruby.object.create =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("object__create")
{
	classname = user_string($arg1)
	file = user_string($arg2)
	line = $arg3
}

/**
 * probe ruby.parse.begin - Fired just before a Ruby source file is parsed.
 *
 * @parsedfile: The name of the file to be parsed (string)
 * @parsedline: The line number of beginning of parsing (int)
 */
probe ruby.parse.begin =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("parse__begin")
{
	parsedfile = user_string($arg1)
	parsedline = $arg2
}

/**
 * probe ruby.parse.end - Fired just after a Ruby source file was parsed.
 *
 * @parsedfile: The name of parsed the file (string)
 * @parsedline: The line number of beginning of parsing (int)
 */
probe ruby.parse.end =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("parse__end")
{
	parsedfile = user_string($arg1)
	parsedline = $arg2
}

/**
 * probe ruby.raise - Fired when an exception is raised.
 *
 * @classname: The class name of the raised exception (string)
 * @file: The name of the file where the exception was raised (string)
 * @line: The line number in the file where the exception was raised (int)
 */
probe ruby.raise =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("raise")
{
	classname  = user_string($arg1)
	file = user_string($arg2)
	line = $arg3
}

/**
 * probe ruby.require.entry - Fired on calls to rb_require_safe (when a file
 * is required).
 *
 * @requiredfile: The name of the file to be required (string)
 * @file: The file that called "require" (string)
 * @line: The line number where the call to require was made(int)
 */
probe ruby.require.entry =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("require__entry")
{
	requiredfile = user_string($arg1)
	file = user_string($arg2)
	line = $arg3
}

/**
 * probe ruby.require.return - Fired just after require has finished
 * search of load path for suitable file to require.
 *
 * @requiredfile: The file that was required (string)
 */
probe ruby.require.return =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("require__return")
{
	requiredfile = user_string($arg1)
}

/**
 * probe ruby.string.create - Allocation of new string.
 *
 * @size: Number of elements (an int)
 * @file: The file name where the method is being called (string)
 * @line: The line number where the method is being called (int)
 */
probe ruby.string.create =
      process("/opt/alt/ruby30/lib*/libruby.so.3.0").mark("string__create")
{
	size = $arg1
	file = user_string($arg2)
	line = $arg3
}
Ruby is copyrighted free software by Yukihiro Matsumoto <matz@netlab.jp>.
You can redistribute it and/or modify it under either the terms of the
2-clause BSDL (see the file BSDL), 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.
                    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.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    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.
本プログラムはフリーソフトウェアです．2-clause BSDL
または以下に示す条件で本プログラムを再配布できます
2-clause BSDLについてはBSDLファイルを参照して下さい．

1. 複製は制限なく自由です．

2. 以下の条件のいずれかを満たす時に本プログラムのソースを
   自由に変更できます．

   a.  ネットニューズにポストしたり，作者に変更を送付する
       などの方法で，変更を公開する．

   b.  変更した本プログラムを自分の所属する組織内部だけで
       使う．

   c.  変更点を明示したうえ，ソフトウェアの名前を変更する．
       そのソフトウェアを配布する時には変更前の本プログラ
       ムも同時に配布する．または変更前の本プログラムのソー
       スの入手法を明示する．

   d.  その他の変更条件を作者と合意する．

3. 以下の条件のいずれかを満たす時に本プログラムをコンパイ
   ルしたオブジェクトコードや実行形式でも配布できます．

   a.  バイナリを受け取った人がソースを入手できるように，
       ソースの入手法を明示する．

   b.  機械可読なソースコードを添付する．

   c.  変更を行ったバイナリは名前を変更したうえ，オリジナ
       ルのソースコードの入手法を明示する．

   d.  その他の配布条件を作者と合意する．

4. 他のプログラムへの引用はいかなる目的であれ自由です．た
   だし，本プログラムに含まれる他の作者によるコードは，そ
   れぞれの作者の意向による制限が加えられる場合があります．

   それらファイルの一覧とそれぞれの配布条件などに付いては
   LEGALファイルを参照してください．

5. 本プログラムへの入力となるスクリプトおよび，本プログラ
   ムからの出力の権利は本プログラムの作者ではなく，それぞ
   れの入出力を生成した人に属します．また，本プログラムに
   組み込まれるための拡張ライブラリについても同様です．

6. 本プログラムは無保証です．作者は本プログラムをサポート
   する意志はありますが，プログラム自身のバグあるいは本プ
   ログラムの実行などから発生するいかなる損害に対しても責
   任を持ちません．
# -*- rdoc -*-

= LEGAL NOTICE INFORMATION
--------------------------

All the files in this distribution are covered under either the Ruby's
license (see the file COPYING) or public-domain except some files
mentioned below.

[addr2line.c]

  A part of this file is from FreeBSD.

  >>>
    Copyright (c) 1986, 1988, 1991, 1993::
    The Regents of the University of California.  All rights reserved.

    (c) UNIX System Laboratories, Inc.

    All or some portions of this file are derived from material licensed
    to the University of California by American Telephone and Telegraph
    Co. or Unix System Laboratories, Inc. and are reproduced herein with
    the permission of UNIX System Laboratories, Inc.

    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.
    4. Neither the name of the University 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 REGENTS 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 REGENTS 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.

	@(#)subr_prf.c	8.3 (Berkeley) 1/21/94


[ccan/build_assert/build_assert.h]
[ccan/check_type/check_type.h]
[ccan/container_of/container_of.h]
[ccan/str/str.h]

  These files are licensed under the {CC0}[https://creativecommons.org/choose/zero/].

[ccan/list/list.h]

  This file is licensed under the {MIT License}[rdoc-label:label-MIT+License].

[coroutine]

  Unless otherwise specified, these files are licensed under the
  {MIT License}[rdoc-label:label-MIT+License].

[include/ruby/onigmo.h]
[include/ruby/oniguruma.h]
[regcomp.c]
[regenc.c]
[regenc.h]
[regerror.c]
[regexec.c]
[regint.h]
[regparse.c]
[regparse.h]
[enc/ascii.c]
[enc/big5.c]
[enc/cp949.c]
[enc/emacs_mule.c]
[enc/encdb.c]
[enc/euc_jp.c]
[enc/euc_kr.c]
[enc/euc_tw.c]
[enc/gb18030.c]
[enc/gb2312.c]
[enc/gbk.c]
[enc/iso_8859_1.c]
[enc/iso_8859_10.c]
[enc/iso_8859_11.c]
[enc/iso_8859_13.c]
[enc/iso_8859_14.c]
[enc/iso_8859_15.c]
[enc/iso_8859_16.c]
[enc/iso_8859_2.c]
[enc/iso_8859_3.c]
[enc/iso_8859_4.c]
[enc/iso_8859_5.c]
[enc/iso_8859_6.c]
[enc/iso_8859_7.c]
[enc/iso_8859_8.c]
[enc/iso_8859_9.c]
[enc/koi8_r.c]
[enc/koi8_u.c]
[enc/shift_jis.c]
[enc/unicode.c]
[enc/us_ascii.c]
[enc/utf_16be.c]
[enc/utf_16le.c]
[enc/utf_32be.c]
[enc/utf_32le.c]
[enc/utf_8.c]
[enc/windows_1251.c]
[enc/windows_31j.c]

  Onigmo (Oniguruma-mod) LICENSE

  >>>
    Copyright (c) 2002-2009::  K.Kosako  <sndgk393 AT ybb DOT ne DOT jp>
    Copyright (c) 2011-2014::  K.Takata  <kentkt AT csc DOT jp>
    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.

  Oniguruma LICENSE

  >>>
    Copyright (c) 2002-2009::  K.Kosako  <sndgk393 AT ybb DOT ne DOT jp>
    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.

  * https://github.com/k-takata/Onigmo/
  * https://github.com/kkos/oniguruma
  * https://svnweb.freebsd.org/ports/head/devel/oniguruma/

    When this software is partly used or it is distributed with Ruby,
    this of Ruby follows the license of Ruby.

[enc/windows_1250.c]
[enc/windows_1252.c]

  >>>
    Copyright (c) 2006-2007::  Byte      <byte AT mail DOT kna DOT ru>
                               K.Kosako  <sndgk393 AT ybb DOT ne DOT jp>
    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.

[enc/cesu_8.c]
[enc/windows_1253.c]
[enc/windows_1254.c]
[enc/windows_1257.c]

  >>>
    Copyright (c) 2002-2007::  K.Kosako  <sndgk393 AT ybb DOT ne DOT jp>
    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.

[enc/trans/GB/GB12345%UCS.src]
[enc/trans/GB/UCS%GB12345.src]
[enc/trans/GB/GB2312%UCS.src]
[enc/trans/GB/UCS%GB2312.src]

  These files have this explanatory texts.

  >>>
    This mapping data was created from files provided by Unicode, Inc.
    (The Unicode Consortium). The files were used to create a product supporting
    Unicode, as explicitly permitted in the files' copyright notices.
    Please note that Unicode, Inc. never made any claims as to fitness of these
    files for any particular purpose, and has ceased to publish the files many
    years ago.

[enc/trans/JIS/JISX0201-KANA%UCS.src]
[enc/trans/JIS/JISX0208\@1990%UCS.src]
[enc/trans/JIS/JISX0212%UCS.src]
[enc/trans/JIS/UCS%JISX0201-KANA.src]
[enc/trans/JIS/UCS%JISX0208@1990.src]
[enc/trans/JIS/UCS%JISX0212.src]

  These files are copyrighted as the following.

  >>>
    © 2015 Unicode®, Inc.

    For terms of use, see http://www.unicode.org/terms_of_use.html

[enc/trans/JIS/JISX0213-1%UCS@BMP.src]
[enc/trans/JIS/JISX0213-1%UCS@SIP.src]
[enc/trans/JIS/JISX0213-2%UCS@BMP.src]
[enc/trans/JIS/JISX0213-2%UCS@SIP.src]

  These files are copyrighted as the following.

  >>>
    Copyright (C) 2001:: earthian@tama.or.jp, All Rights Reserved.
    Copyright (C) 2001:: I'O, All Rights Reserved.
    Copyright (C) 2006:: Project X0213, All Rights Reserved.
    You can use, modify, distribute this table freely.

[enc/trans/JIS/UCS@BMP%JISX0213-1.src]
[enc/trans/JIS/UCS@BMP%JISX0213-2.src]
[enc/trans/JIS/UCS@SIP%JISX0213-1.src]
[enc/trans/JIS/UCS@SIP%JISX0213-2.src]

  These files are copyrighted as the following.

  >>>
    Copyright (C) 2001:: earthian@tama.or.jp, All Rights Reserved.
    Copyright (C) 2001:: I'O, All Rights Reserved.
    You can use, modify, distribute this table freely.

[enc/trans/ucm/glibc-BIG5-2.3.3.ucm]
[enc/trans/ucm/glibc-BIG5HKSCS-2.3.3.ucm]

  >>>
    Copyright (C) 2001-2005:: International Business Machines
                              Corporation and others.  All Rights Reserved.

[enc/trans/ucm/windows-950-2000.ucm]
[enc/trans/ucm/windows-950_hkscs-2001.ucm]

  >>>
    Copyright (C) 2001-2002:: International Business Machines
                              Corporation and others.  All Rights Reserved.


[configure]

  This file is free software.

  >>>
    Copyright (C) 1992-1996, 1998-2012:: Free Software Foundation, Inc.

    This configure script is free software; the Free Software Foundation
    gives unlimited permission to copy, distribute and modify it.

[aclocal.m4]

  This file is free software.

  >>>
    Copyright (C) 1996-2020:: Free Software Foundation, Inc.

    This file is free software; the Free Software Foundation
    gives unlimited permission to copy and/or distribute it,
    with or without modifications, as long as this notice is preserved.

[tool/config.guess]
[tool/config.sub]

  As long as you distribute these files with the file configure, they
  are covered under the Ruby's license.

  >>>
    Copyright 1992-2018:: Free Software Foundation, Inc.

    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 <https://www.gnu.org/licenses/>.

    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").

[parse.c]
[parse.h]

  These files are licensed under the GPL, but are incorporated into Ruby and
  redistributed under the terms of the Ruby license, as permitted by the
  exception to the GPL below.

  >>>
    Copyright (C) 1984, 1989-1990, 2000-2015, 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.  If not, see <http://www.gnu.org/licenses/>.

    As a special exception, you may create a larger work that contains
    part or all of the Bison parser skeleton and distribute that work
    under terms of your choice, so long as that work isn't itself a
    parser generator using the skeleton or a modified version thereof
    as a parser skeleton.  Alternatively, if you modify or redistribute
    the parser skeleton itself, you may (at your option) remove this
    special exception, which will cause the skeleton and the resulting
    Bison output files to be licensed under the GNU General Public
    License without this special exception.

    This special exception was added by the Free Software Foundation in
    version 2.2 of Bison.

[missing/dtoa.c]

  This file is under these licenses.

  >>>
    Copyright (c) 1991, 2000, 2001:: by Lucent Technologies.

    Permission to use, copy, modify, and distribute this software for any
    purpose without fee is hereby granted, provided that this entire notice
    is included in all copies of any software which is or includes a copy
    or modification of this software and in all copies of the supporting
    documentation for such software.

    THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
    WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
    REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
    OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.

  >>>
    Copyright (c) 2004-2008:: David Schultz <das@FreeBSD.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:
    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.

[win32/win32.c]
[include/ruby/win32.h]

  You can apply the Artistic License to these files. (or GPL,
  alternatively)

  >>>
    Copyright (c) 1993:: Intergraph Corporation

    You may distribute under the terms of either the GNU General Public
    License or the Artistic License, as specified in the perl README file.

[missing/mt19937.c]

  This file is under the new-style BSD license.

  >>>
    A C-program for MT19937, with initialization improved 2002/2/10.::
    Coded by Takuji Nishimura and Makoto Matsumoto.  
    This is a faster version by taking Shawn Cokus's optimization,
    Matthe Bellew's simplification, Isaku Wada's real version.

    Before using, initialize the state by using init_genrand(seed)
    or init_by_array(init_key, key_length).

    Copyright (C) 1997 - 2002:: Makoto Matsumoto and Takuji Nishimura,
                                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.

    3. 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.


    Any feedback is very welcome.
    http://www.math.keio.ac.jp/matumoto/emt.html
    email: matumoto@math.keio.ac.jp

  The Wayback Machine url: http://web.archive.org/web/19990429082237/http://www.math.keio.ac.jp/matumoto/emt.html

[missing/procstat_vm.c]

  This file is under the new-style BSD license.

  >>>
    Copyright (c) 2007:: Robert N. M. Watson
                         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.

    $FreeBSD: head/usr.bin/procstat/procstat_vm.c 261780 2014-02-11 21:57:37Z jhb $

[vsnprintf.c]

  This file is under the {old-style BSD license}[rdoc-label:label-Old-style+BSD+license].

  >>>
    Copyright (c) 1990, 1993::
    The Regents of the University of California.  All rights reserved.

    This code is derived from software contributed to Berkeley by
    Chris Torek.

[st.c]
[strftime.c]
[include/ruby/st.h]
[missing/acosh.c]
[missing/alloca.c]
[missing/dup2.c]
[missing/erf.c]
[missing/finite.c]
[missing/hypot.c]
[missing/isinf.c]
[missing/isnan.c]
[missing/lgamma_r.c]
[missing/memcmp.c]
[missing/memmove.c]
[missing/strchr.c]
[missing/strerror.c]
[missing/strstr.c]
[missing/tgamma.c]
[ext/date/date_strftime.c]
[ext/digest/sha1/sha1.c]
[ext/digest/sha1/sha1.h]

  These files are all under public domain.

[missing/crypt.c]

  This file is under the {old-style BSD license}[rdoc-label:label-Old-style+BSD+license].

  >>>
    Copyright (c) 1989, 1993::
    The Regents of the University of California.  All rights reserved.

    This code is derived from software contributed to Berkeley by
    Tom Truscott.

[missing/setproctitle.c]

  This file is under the {old-style BSD license}[rdoc-label:label-Old-style+BSD+license].

  >>>
    Copyright 2003:: Damien Miller
    Copyright (c) 1983, 1995-1997:: Eric P. Allman
    Copyright (c) 1988, 1993::
    The Regents of the University of California.  All rights reserved.

[missing/strlcat.c]
[missing/strlcpy.c]

  These files are under an ISC-style license.

  >>>
    Copyright (c) 1998, 2015:: Todd C. Miller <Todd.Miller@courtesan.com>

    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.

[missing/langinfo.c]

  This file is from http://www.cl.cam.ac.uk/~mgk25/ucs/langinfo.c.
  Ruby uses a modified version. The file contains the following
  author/copyright notice:

  >>>
    Markus.Kuhn@cl.cam.ac.uk -- 2002-03-11::
    Permission to use, copy, modify, and distribute this software
    for any purpose and without fee is hereby granted. The author
    disclaims all warranties with regard to this software.

[ext/digest/md5/md5.c]
[ext/digest/md5/md5.h]

  These files are under the following license.  Ruby uses modified
  versions of them.

  >>>
    Copyright (C) 1999, 2000:: Aladdin Enterprises.  All rights reserved.

    This software is provided 'as-is', without any express or implied
    warranty.  In no event will the authors be held liable for any damages
    arising from the use of this software.

    Permission is granted to anyone to use this software for any purpose,
    including commercial applications, and to alter it and redistribute it
    freely, subject to the following restrictions:

    1. The origin of this software must not be misrepresented; you must not
       claim that you wrote the original software. If you use this software
       in a product, an acknowledgment in the product documentation would be
       appreciated but is not required.
    2. Altered source versions must be plainly marked as such, and must not be
       misrepresented as being the original software.
    3. This notice may not be removed or altered from any source distribution.

    L. Peter Deutsch
    ghost@aladdin.com

[ext/digest/rmd160/rmd160.c]
[ext/digest/rmd160/rmd160.h]

  These files have the following copyright information, and by the
  author we are allowed to use it under the new-style BSD license.

  >>>
    AUTHOR::  Antoon Bosselaers, ESAT-COSIC
              (Arranged for libc by Todd C. Miller)
    DATE::    1 March 1996

    Copyright (c):: Katholieke Universiteit Leuven
    1996, All Rights Reserved

[ext/digest/sha2/sha2.c]
[ext/digest/sha2/sha2.h]

  These files are under the new-style BSD license.

  >>>
    Copyright 2000:: Aaron D. Gifford.  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.
    3. Neither the name of the copyright holder nor the names of contributors
       may be used to endorse or promote products derived from this software
       without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTOR(S) ``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(S) OR CONTRIBUTOR(S) 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.

[ext/json/generator/generator.c]

  The file contains the following copyright notice.

  >>>
    Copyright 2001-2004:: Unicode, Inc.

    Disclaimer::

      This source code is provided as is by Unicode, Inc. No claims are
      made as to fitness for any particular purpose. No warranties of any
      kind are expressed or implied. The recipient agrees to determine
      applicability of information provided. If this file has been
      purchased on magnetic or optical media from Unicode, Inc., the
      sole remedy for any claim will be exchange of defective media
      within 90 days of receipt.

    Limitations on Rights to Redistribute This Code::

      Unicode, Inc. hereby grants the right to freely use the information
      supplied in this file in the creation of products supporting the
      Unicode Standard, and to make copies of this file in any form
      for internal or external distribution as long as this notice
      remains attached.

[ext/nkf/nkf-utf8/config.h]
[ext/nkf/nkf-utf8/nkf.c]
[ext/nkf/nkf-utf8/utf8tbl.c]

  These files are under the following license.  So to speak, it is
  copyrighted semi-public-domain software.

  >>>
    Copyright (C) 1987:: Fujitsu LTD. (Itaru ICHIKAWA)

    Everyone is permitted to do anything on this program
    including copying, modifying, improving,
    as long as you don't try to pretend that you wrote it.
    i.e., the above copyright notice has to appear in all copies.
    Binary distribution requires original version messages.
    You don't have to ask before copying, redistribution or publishing.
    THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE.

[ext/psych]
[test/psych]

  The files under these directories are under the following license, except for
  ext/psych/yaml.

  >>>
    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.

[ext/psych/yaml]

  The files under this directory are under the following license.

  >>>
    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.

[ext/pty/pty.c]

  >>>
    C) Copyright 1998:: by Akinori Ito.

    This software may be redistributed freely for this purpose, in full
    or in part, provided that this entire copyright notice is included
    on any copies of this software and applications and derivations thereof.

    This software is provided on an "as is" basis, without warranty of any
    kind, either expressed or implied, as to any matter including, but not
    limited to warranty of fitness of purpose, or merchantability, or
    results obtained from use of this software.

[ext/socket/addrinfo.h]
[ext/socket/getaddrinfo.c]
[ext/socket/getnameinfo.c]

  These files are under the new-style BSD license.

  >>>
    Copyright (C) 1995, 1996, 1997, 1998, and 1999:: WIDE Project.
    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.
    3. Neither the name of the 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 PROJECT 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 PROJECT 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.

[ext/win32ole/win32ole.c]

  You can apply the Artistic License to this file. (or GPL,
  alternatively)

  >>>
    (c) 1995:: Microsoft Corporation. All rights reserved.
    Developed by ActiveWare Internet Corp., http://www.ActiveWare.com

    Other modifications Copyright (c) 1997, 1998:: by Gurusamy Sarathy
    <gsar@umich.edu> and Jan Dubois <jan.dubois@ibm.net>

    You may distribute under the terms of either the GNU General Public
    License or the Artistic License, as specified in the README file
    of the Perl distribution.

  The Wayback Machine url: http://web.archive.org/web/19970607104352/http://www.activeware.com:80/

[lib/rdoc/generator/template/darkfish/css/fonts.css]

  This file is licensed under the {SIL Open Font License}[http://scripts.sil.org/OFL].

[spec/mspec]
[spec/ruby]

  The files under these directories are under the following license.

  >>>
    Copyright (c) 2008:: Engine Yard, Inc. All rights reserved.

    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.

[lib/rubygems.rb]
[lib/rubygems]
[test/rubygems]

  RubyGems is under the following license.

  >>>
    RubyGems is copyrighted free software by Chad Fowler, Rich Kilmer, Jim
    Weirich and others.  You can redistribute it and/or modify it under
    either the terms of the {MIT license}[rdoc-label:label-MIT+License], 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 executables 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 executable
       form, provided that you do at least ONE of the following:

       a. distribute the executables 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 executables 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).

    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.

[lib/bundler]
[lib/bundler.rb]
[lib/bundler.gemspec]
[spec/bundler]
[man/bundle-*,gemfile.*]

  Bundler is under the following license.

  >>>
    Portions copyright (c) 2010:: Andre Arko
    Portions copyright (c) 2009:: Engine Yard

    {MIT License}[rdoc-label:label-MIT+License]

[lib/did_you_mean]
[lib/did_you_mean.rb]
[test/did_you_mean]

  did_you_mean is under the following license.

  >>>
    Copyright (c) 2014-2016 Yuki Nishijima

    {MIT License}[rdoc-label:label-MIT+License]

[benchmark/so_ackermann.rb]
[benchmark/so_array.rb]
[benchmark/so_binary_trees.rb]
[benchmark/so_concatenate.rb]
[benchmark/so_count_words.yml]
[benchmark/so_exception.rb]
[benchmark/so_fannkuch.rb]
[benchmark/so_fasta.rb]
[benchmark/so_k_nucleotide.yml]
[benchmark/so_lists.rb]
[benchmark/so_mandelbrot.rb]
[benchmark/so_matrix.rb]
[benchmark/so_meteor_contest.rb]
[benchmark/so_nbody.rb]
[benchmark/so_nested_loop.rb]
[benchmark/so_nsieve.rb]
[benchmark/so_nsieve_bits.rb]
[benchmark/so_object.rb]
[benchmark/so_partial_sums.rb]
[benchmark/so_pidigits.rb]
[benchmark/so_random.rb]
[benchmark/so_reverse_complement.yml]
[benchmark/so_sieve.rb]
[benchmark/so_spectralnorm.rb]

  These files are very old copy of then-called "The Great Computer Language
  Shootout".  LEGAL SITUATION OF THESE FILES ARE UNCLEAR because the original
  site has been lost.  Upstream diverged to delete several benchmarks listed
  above.

== MIT License
>>>
      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.

== Old-style BSD license
>>>
      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.
      3. Neither the name of the University 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 REGENTS 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 REGENTS 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.

      IMPORTANT NOTE::

      From ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change
      paragraph 3 above is now null and void.
Ruby is copyrighted free software by Yukihiro Matsumoto <matz@netlab.jp>.
You can redistribute it and/or modify it under either the terms of the
2-clause BSDL (see the file BSDL), 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.
                    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.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    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.
本プログラムはフリーソフトウェアです．2-clause BSDL
または以下に示す条件で本プログラムを再配布できます
2-clause BSDLについてはBSDLファイルを参照して下さい．

1. 複製は制限なく自由です．

2. 以下の条件のいずれかを満たす時に本プログラムのソースを
   自由に変更できます．

   a.  ネットニューズにポストしたり，作者に変更を送付する
       などの方法で，変更を公開する．

   b.  変更した本プログラムを自分の所属する組織内部だけで
       使う．

   c.  変更点を明示したうえ，ソフトウェアの名前を変更する．
       そのソフトウェアを配布する時には変更前の本プログラ
       ムも同時に配布する．または変更前の本プログラムのソー
       スの入手法を明示する．

   d.  その他の変更条件を作者と合意する．

3. 以下の条件のいずれかを満たす時に本プログラムをコンパイ
   ルしたオブジェクトコードや実行形式でも配布できます．

   a.  バイナリを受け取った人がソースを入手できるように，
       ソースの入手法を明示する．

   b.  機械可読なソースコードを添付する．

   c.  変更を行ったバイナリは名前を変更したうえ，オリジナ
       ルのソースコードの入手法を明示する．

   d.  その他の配布条件を作者と合意する．

4. 他のプログラムへの引用はいかなる目的であれ自由です．た
   だし，本プログラムに含まれる他の作者によるコードは，そ
   れぞれの作者の意向による制限が加えられる場合があります．

   それらファイルの一覧とそれぞれの配布条件などに付いては
   LEGALファイルを参照してください．

5. 本プログラムへの入力となるスクリプトおよび，本プログラ
   ムからの出力の権利は本プログラムの作者ではなく，それぞ
   れの入出力を生成した人に属します．また，本プログラムに
   組み込まれるための拡張ライブラリについても同様です．

6. 本プログラムは無保証です．作者は本プログラムをサポート
   する意志はありますが，プログラム自身のバグあるいは本プ
   ログラムの実行などから発生するいかなる損害に対しても責
   任を持ちません．
# -*- rdoc -*-

= LEGAL NOTICE INFORMATION
--------------------------

All the files in this distribution are covered under either the Ruby's
license (see the file COPYING) or public-domain except some files
mentioned below.

[addr2line.c]

  A part of this file is from FreeBSD.

  >>>
    Copyright (c) 1986, 1988, 1991, 1993::
    The Regents of the University of California.  All rights reserved.

    (c) UNIX System Laboratories, Inc.

    All or some portions of this file are derived from material licensed
    to the University of California by American Telephone and Telegraph
    Co. or Unix System Laboratories, Inc. and are reproduced herein with
    the permission of UNIX System Laboratories, Inc.

    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.
    4. Neither the name of the University 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 REGENTS 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 REGENTS 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.

	@(#)subr_prf.c	8.3 (Berkeley) 1/21/94


[ccan/build_assert/build_assert.h]
[ccan/check_type/check_type.h]
[ccan/container_of/container_of.h]
[ccan/str/str.h]

  These files are licensed under the {CC0}[https://creativecommons.org/choose/zero/].

[ccan/list/list.h]

  This file is licensed under the {MIT License}[rdoc-label:label-MIT+License].

[coroutine]

  Unless otherwise specified, these files are licensed under the
  {MIT License}[rdoc-label:label-MIT+License].

[include/ruby/onigmo.h]
[include/ruby/oniguruma.h]
[regcomp.c]
[regenc.c]
[regenc.h]
[regerror.c]
[regexec.c]
[regint.h]
[regparse.c]
[regparse.h]
[enc/ascii.c]
[enc/big5.c]
[enc/cp949.c]
[enc/emacs_mule.c]
[enc/encdb.c]
[enc/euc_jp.c]
[enc/euc_kr.c]
[enc/euc_tw.c]
[enc/gb18030.c]
[enc/gb2312.c]
[enc/gbk.c]
[enc/iso_8859_1.c]
[enc/iso_8859_10.c]
[enc/iso_8859_11.c]
[enc/iso_8859_13.c]
[enc/iso_8859_14.c]
[enc/iso_8859_15.c]
[enc/iso_8859_16.c]
[enc/iso_8859_2.c]
[enc/iso_8859_3.c]
[enc/iso_8859_4.c]
[enc/iso_8859_5.c]
[enc/iso_8859_6.c]
[enc/iso_8859_7.c]
[enc/iso_8859_8.c]
[enc/iso_8859_9.c]
[enc/koi8_r.c]
[enc/koi8_u.c]
[enc/shift_jis.c]
[enc/unicode.c]
[enc/us_ascii.c]
[enc/utf_16be.c]
[enc/utf_16le.c]
[enc/utf_32be.c]
[enc/utf_32le.c]
[enc/utf_8.c]
[enc/windows_1251.c]
[enc/windows_31j.c]

  Onigmo (Oniguruma-mod) LICENSE

  >>>
    Copyright (c) 2002-2009::  K.Kosako  <sndgk393 AT ybb DOT ne DOT jp>
    Copyright (c) 2011-2014::  K.Takata  <kentkt AT csc DOT jp>
    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.

  Oniguruma LICENSE

  >>>
    Copyright (c) 2002-2009::  K.Kosako  <sndgk393 AT ybb DOT ne DOT jp>
    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.

  * https://github.com/k-takata/Onigmo/
  * https://github.com/kkos/oniguruma
  * https://svnweb.freebsd.org/ports/head/devel/oniguruma/

    When this software is partly used or it is distributed with Ruby,
    this of Ruby follows the license of Ruby.

[enc/windows_1250.c]
[enc/windows_1252.c]

  >>>
    Copyright (c) 2006-2007::  Byte      <byte AT mail DOT kna DOT ru>
                               K.Kosako  <sndgk393 AT ybb DOT ne DOT jp>
    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.

[enc/cesu_8.c]
[enc/windows_1253.c]
[enc/windows_1254.c]
[enc/windows_1257.c]

  >>>
    Copyright (c) 2002-2007::  K.Kosako  <sndgk393 AT ybb DOT ne DOT jp>
    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.

[enc/trans/GB/GB12345%UCS.src]
[enc/trans/GB/UCS%GB12345.src]
[enc/trans/GB/GB2312%UCS.src]
[enc/trans/GB/UCS%GB2312.src]

  These files have this explanatory texts.

  >>>
    This mapping data was created from files provided by Unicode, Inc.
    (The Unicode Consortium). The files were used to create a product supporting
    Unicode, as explicitly permitted in the files' copyright notices.
    Please note that Unicode, Inc. never made any claims as to fitness of these
    files for any particular purpose, and has ceased to publish the files many
    years ago.

[enc/trans/JIS/JISX0201-KANA%UCS.src]
[enc/trans/JIS/JISX0208\@1990%UCS.src]
[enc/trans/JIS/JISX0212%UCS.src]
[enc/trans/JIS/UCS%JISX0201-KANA.src]
[enc/trans/JIS/UCS%JISX0208@1990.src]
[enc/trans/JIS/UCS%JISX0212.src]

  These files are copyrighted as the following.

  >>>
    © 2015 Unicode®, Inc.

    For terms of use, see http://www.unicode.org/terms_of_use.html

[enc/trans/JIS/JISX0213-1%UCS@BMP.src]
[enc/trans/JIS/JISX0213-1%UCS@SIP.src]
[enc/trans/JIS/JISX0213-2%UCS@BMP.src]
[enc/trans/JIS/JISX0213-2%UCS@SIP.src]

  These files are copyrighted as the following.

  >>>
    Copyright (C) 2001:: earthian@tama.or.jp, All Rights Reserved.
    Copyright (C) 2001:: I'O, All Rights Reserved.
    Copyright (C) 2006:: Project X0213, All Rights Reserved.
    You can use, modify, distribute this table freely.

[enc/trans/JIS/UCS@BMP%JISX0213-1.src]
[enc/trans/JIS/UCS@BMP%JISX0213-2.src]
[enc/trans/JIS/UCS@SIP%JISX0213-1.src]
[enc/trans/JIS/UCS@SIP%JISX0213-2.src]

  These files are copyrighted as the following.

  >>>
    Copyright (C) 2001:: earthian@tama.or.jp, All Rights Reserved.
    Copyright (C) 2001:: I'O, All Rights Reserved.
    You can use, modify, distribute this table freely.

[enc/trans/ucm/glibc-BIG5-2.3.3.ucm]
[enc/trans/ucm/glibc-BIG5HKSCS-2.3.3.ucm]

  >>>
    Copyright (C) 2001-2005:: International Business Machines
                              Corporation and others.  All Rights Reserved.

[enc/trans/ucm/windows-950-2000.ucm]
[enc/trans/ucm/windows-950_hkscs-2001.ucm]

  >>>
    Copyright (C) 2001-2002:: International Business Machines
                              Corporation and others.  All Rights Reserved.


[configure]

  This file is free software.

  >>>
    Copyright (C) 1992-1996, 1998-2012:: Free Software Foundation, Inc.

    This configure script is free software; the Free Software Foundation
    gives unlimited permission to copy, distribute and modify it.

[aclocal.m4]

  This file is free software.

  >>>
    Copyright (C) 1996-2020:: Free Software Foundation, Inc.

    This file is free software; the Free Software Foundation
    gives unlimited permission to copy and/or distribute it,
    with or without modifications, as long as this notice is preserved.

[tool/config.guess]
[tool/config.sub]

  As long as you distribute these files with the file configure, they
  are covered under the Ruby's license.

  >>>
    Copyright 1992-2018:: Free Software Foundation, Inc.

    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 <https://www.gnu.org/licenses/>.

    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").

[parse.c]
[parse.h]

  These files are licensed under the GPL, but are incorporated into Ruby and
  redistributed under the terms of the Ruby license, as permitted by the
  exception to the GPL below.

  >>>
    Copyright (C) 1984, 1989-1990, 2000-2015, 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.  If not, see <http://www.gnu.org/licenses/>.

    As a special exception, you may create a larger work that contains
    part or all of the Bison parser skeleton and distribute that work
    under terms of your choice, so long as that work isn't itself a
    parser generator using the skeleton or a modified version thereof
    as a parser skeleton.  Alternatively, if you modify or redistribute
    the parser skeleton itself, you may (at your option) remove this
    special exception, which will cause the skeleton and the resulting
    Bison output files to be licensed under the GNU General Public
    License without this special exception.

    This special exception was added by the Free Software Foundation in
    version 2.2 of Bison.

[missing/dtoa.c]

  This file is under these licenses.

  >>>
    Copyright (c) 1991, 2000, 2001:: by Lucent Technologies.

    Permission to use, copy, modify, and distribute this software for any
    purpose without fee is hereby granted, provided that this entire notice
    is included in all copies of any software which is or includes a copy
    or modification of this software and in all copies of the supporting
    documentation for such software.

    THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
    WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
    REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
    OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.

  >>>
    Copyright (c) 2004-2008:: David Schultz <das@FreeBSD.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:
    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.

[win32/win32.c]
[include/ruby/win32.h]

  You can apply the Artistic License to these files. (or GPL,
  alternatively)

  >>>
    Copyright (c) 1993:: Intergraph Corporation

    You may distribute under the terms of either the GNU General Public
    License or the Artistic License, as specified in the perl README file.

[missing/mt19937.c]

  This file is under the new-style BSD license.

  >>>
    A C-program for MT19937, with initialization improved 2002/2/10.::
    Coded by Takuji Nishimura and Makoto Matsumoto.  
    This is a faster version by taking Shawn Cokus's optimization,
    Matthe Bellew's simplification, Isaku Wada's real version.

    Before using, initialize the state by using init_genrand(seed)
    or init_by_array(init_key, key_length).

    Copyright (C) 1997 - 2002:: Makoto Matsumoto and Takuji Nishimura,
                                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.

    3. 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.


    Any feedback is very welcome.
    http://www.math.keio.ac.jp/matumoto/emt.html
    email: matumoto@math.keio.ac.jp

  The Wayback Machine url: http://web.archive.org/web/19990429082237/http://www.math.keio.ac.jp/matumoto/emt.html

[missing/procstat_vm.c]

  This file is under the new-style BSD license.

  >>>
    Copyright (c) 2007:: Robert N. M. Watson
                         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.

    $FreeBSD: head/usr.bin/procstat/procstat_vm.c 261780 2014-02-11 21:57:37Z jhb $

[vsnprintf.c]

  This file is under the {old-style BSD license}[rdoc-label:label-Old-style+BSD+license].

  >>>
    Copyright (c) 1990, 1993::
    The Regents of the University of California.  All rights reserved.

    This code is derived from software contributed to Berkeley by
    Chris Torek.

[st.c]
[strftime.c]
[include/ruby/st.h]
[missing/acosh.c]
[missing/alloca.c]
[missing/dup2.c]
[missing/erf.c]
[missing/finite.c]
[missing/hypot.c]
[missing/isinf.c]
[missing/isnan.c]
[missing/lgamma_r.c]
[missing/memcmp.c]
[missing/memmove.c]
[missing/strchr.c]
[missing/strerror.c]
[missing/strstr.c]
[missing/tgamma.c]
[ext/date/date_strftime.c]
[ext/digest/sha1/sha1.c]
[ext/digest/sha1/sha1.h]

  These files are all under public domain.

[missing/crypt.c]

  This file is under the {old-style BSD license}[rdoc-label:label-Old-style+BSD+license].

  >>>
    Copyright (c) 1989, 1993::
    The Regents of the University of California.  All rights reserved.

    This code is derived from software contributed to Berkeley by
    Tom Truscott.

[missing/setproctitle.c]

  This file is under the {old-style BSD license}[rdoc-label:label-Old-style+BSD+license].

  >>>
    Copyright 2003:: Damien Miller
    Copyright (c) 1983, 1995-1997:: Eric P. Allman
    Copyright (c) 1988, 1993::
    The Regents of the University of California.  All rights reserved.

[missing/strlcat.c]
[missing/strlcpy.c]

  These files are under an ISC-style license.

  >>>
    Copyright (c) 1998, 2015:: Todd C. Miller <Todd.Miller@courtesan.com>

    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.

[missing/langinfo.c]

  This file is from http://www.cl.cam.ac.uk/~mgk25/ucs/langinfo.c.
  Ruby uses a modified version. The file contains the following
  author/copyright notice:

  >>>
    Markus.Kuhn@cl.cam.ac.uk -- 2002-03-11::
    Permission to use, copy, modify, and distribute this software
    for any purpose and without fee is hereby granted. The author
    disclaims all warranties with regard to this software.

[ext/digest/md5/md5.c]
[ext/digest/md5/md5.h]

  These files are under the following license.  Ruby uses modified
  versions of them.

  >>>
    Copyright (C) 1999, 2000:: Aladdin Enterprises.  All rights reserved.

    This software is provided 'as-is', without any express or implied
    warranty.  In no event will the authors be held liable for any damages
    arising from the use of this software.

    Permission is granted to anyone to use this software for any purpose,
    including commercial applications, and to alter it and redistribute it
    freely, subject to the following restrictions:

    1. The origin of this software must not be misrepresented; you must not
       claim that you wrote the original software. If you use this software
       in a product, an acknowledgment in the product documentation would be
       appreciated but is not required.
    2. Altered source versions must be plainly marked as such, and must not be
       misrepresented as being the original software.
    3. This notice may not be removed or altered from any source distribution.

    L. Peter Deutsch
    ghost@aladdin.com

[ext/digest/rmd160/rmd160.c]
[ext/digest/rmd160/rmd160.h]

  These files have the following copyright information, and by the
  author we are allowed to use it under the new-style BSD license.

  >>>
    AUTHOR::  Antoon Bosselaers, ESAT-COSIC
              (Arranged for libc by Todd C. Miller)
    DATE::    1 March 1996

    Copyright (c):: Katholieke Universiteit Leuven
    1996, All Rights Reserved

[ext/digest/sha2/sha2.c]
[ext/digest/sha2/sha2.h]

  These files are under the new-style BSD license.

  >>>
    Copyright 2000:: Aaron D. Gifford.  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.
    3. Neither the name of the copyright holder nor the names of contributors
       may be used to endorse or promote products derived from this software
       without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTOR(S) ``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(S) OR CONTRIBUTOR(S) 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.

[ext/json/generator/generator.c]

  The file contains the following copyright notice.

  >>>
    Copyright 2001-2004:: Unicode, Inc.

    Disclaimer::

      This source code is provided as is by Unicode, Inc. No claims are
      made as to fitness for any particular purpose. No warranties of any
      kind are expressed or implied. The recipient agrees to determine
      applicability of information provided. If this file has been
      purchased on magnetic or optical media from Unicode, Inc., the
      sole remedy for any claim will be exchange of defective media
      within 90 days of receipt.

    Limitations on Rights to Redistribute This Code::

      Unicode, Inc. hereby grants the right to freely use the information
      supplied in this file in the creation of products supporting the
      Unicode Standard, and to make copies of this file in any form
      for internal or external distribution as long as this notice
      remains attached.

[ext/nkf/nkf-utf8/config.h]
[ext/nkf/nkf-utf8/nkf.c]
[ext/nkf/nkf-utf8/utf8tbl.c]

  These files are under the following license.  So to speak, it is
  copyrighted semi-public-domain software.

  >>>
    Copyright (C) 1987:: Fujitsu LTD. (Itaru ICHIKAWA)

    Everyone is permitted to do anything on this program
    including copying, modifying, improving,
    as long as you don't try to pretend that you wrote it.
    i.e., the above copyright notice has to appear in all copies.
    Binary distribution requires original version messages.
    You don't have to ask before copying, redistribution or publishing.
    THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE.

[ext/psych]
[test/psych]

  The files under these directories are under the following license, except for
  ext/psych/yaml.

  >>>
    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.

[ext/psych/yaml]

  The files under this directory are under the following license.

  >>>
    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.

[ext/pty/pty.c]

  >>>
    C) Copyright 1998:: by Akinori Ito.

    This software may be redistributed freely for this purpose, in full
    or in part, provided that this entire copyright notice is included
    on any copies of this software and applications and derivations thereof.

    This software is provided on an "as is" basis, without warranty of any
    kind, either expressed or implied, as to any matter including, but not
    limited to warranty of fitness of purpose, or merchantability, or
    results obtained from use of this software.

[ext/socket/addrinfo.h]
[ext/socket/getaddrinfo.c]
[ext/socket/getnameinfo.c]

  These files are under the new-style BSD license.

  >>>
    Copyright (C) 1995, 1996, 1997, 1998, and 1999:: WIDE Project.
    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.
    3. Neither the name of the 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 PROJECT 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 PROJECT 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.

[ext/win32ole/win32ole.c]

  You can apply the Artistic License to this file. (or GPL,
  alternatively)

  >>>
    (c) 1995:: Microsoft Corporation. All rights reserved.
    Developed by ActiveWare Internet Corp., http://www.ActiveWare.com

    Other modifications Copyright (c) 1997, 1998:: by Gurusamy Sarathy
    <gsar@umich.edu> and Jan Dubois <jan.dubois@ibm.net>

    You may distribute under the terms of either the GNU General Public
    License or the Artistic License, as specified in the README file
    of the Perl distribution.

  The Wayback Machine url: http://web.archive.org/web/19970607104352/http://www.activeware.com:80/

[lib/rdoc/generator/template/darkfish/css/fonts.css]

  This file is licensed under the {SIL Open Font License}[http://scripts.sil.org/OFL].

[spec/mspec]
[spec/ruby]

  The files under these directories are under the following license.

  >>>
    Copyright (c) 2008:: Engine Yard, Inc. All rights reserved.

    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.

[lib/rubygems.rb]
[lib/rubygems]
[test/rubygems]

  RubyGems is under the following license.

  >>>
    RubyGems is copyrighted free software by Chad Fowler, Rich Kilmer, Jim
    Weirich and others.  You can redistribute it and/or modify it under
    either the terms of the {MIT license}[rdoc-label:label-MIT+License], 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 executables 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 executable
       form, provided that you do at least ONE of the following:

       a. distribute the executables 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 executables 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).

    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.

[lib/bundler]
[lib/bundler.rb]
[lib/bundler.gemspec]
[spec/bundler]
[man/bundle-*,gemfile.*]

  Bundler is under the following license.

  >>>
    Portions copyright (c) 2010:: Andre Arko
    Portions copyright (c) 2009:: Engine Yard

    {MIT License}[rdoc-label:label-MIT+License]

[lib/did_you_mean]
[lib/did_you_mean.rb]
[test/did_you_mean]

  did_you_mean is under the following license.

  >>>
    Copyright (c) 2014-2016 Yuki Nishijima

    {MIT License}[rdoc-label:label-MIT+License]

[benchmark/so_ackermann.rb]
[benchmark/so_array.rb]
[benchmark/so_binary_trees.rb]
[benchmark/so_concatenate.rb]
[benchmark/so_count_words.yml]
[benchmark/so_exception.rb]
[benchmark/so_fannkuch.rb]
[benchmark/so_fasta.rb]
[benchmark/so_k_nucleotide.yml]
[benchmark/so_lists.rb]
[benchmark/so_mandelbrot.rb]
[benchmark/so_matrix.rb]
[benchmark/so_meteor_contest.rb]
[benchmark/so_nbody.rb]
[benchmark/so_nested_loop.rb]
[benchmark/so_nsieve.rb]
[benchmark/so_nsieve_bits.rb]
[benchmark/so_object.rb]
[benchmark/so_partial_sums.rb]
[benchmark/so_pidigits.rb]
[benchmark/so_random.rb]
[benchmark/so_reverse_complement.yml]
[benchmark/so_sieve.rb]
[benchmark/so_spectralnorm.rb]

  These files are very old copy of then-called "The Great Computer Language
  Shootout".  LEGAL SITUATION OF THESE FILES ARE UNCLEAR because the original
  site has been lost.  Upstream diverged to delete several benchmarks listed
  above.

== MIT License
>>>
      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.

== Old-style BSD license
>>>
      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.
      3. Neither the name of the University 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 REGENTS 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 REGENTS 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.

      IMPORTANT NOTE::

      From ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change
      paragraph 3 above is now null and void.
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.
Ruby is copyrighted free software by Yukihiro Matsumoto <matz@netlab.jp>.
You can redistribute it and/or modify it under either the terms of the
2-clause BSDL (see the file BSDL), 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.
                    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.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    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.
本プログラムはフリーソフトウェアです．2-clause BSDL
または以下に示す条件で本プログラムを再配布できます
2-clause BSDLについてはBSDLファイルを参照して下さい．

1. 複製は制限なく自由です．

2. 以下の条件のいずれかを満たす時に本プログラムのソースを
   自由に変更できます．

   a.  ネットニューズにポストしたり，作者に変更を送付する
       などの方法で，変更を公開する．

   b.  変更した本プログラムを自分の所属する組織内部だけで
       使う．

   c.  変更点を明示したうえ，ソフトウェアの名前を変更する．
       そのソフトウェアを配布する時には変更前の本プログラ
       ムも同時に配布する．または変更前の本プログラムのソー
       スの入手法を明示する．

   d.  その他の変更条件を作者と合意する．

3. 以下の条件のいずれかを満たす時に本プログラムをコンパイ
   ルしたオブジェクトコードや実行形式でも配布できます．

   a.  バイナリを受け取った人がソースを入手できるように，
       ソースの入手法を明示する．

   b.  機械可読なソースコードを添付する．

   c.  変更を行ったバイナリは名前を変更したうえ，オリジナ
       ルのソースコードの入手法を明示する．

   d.  その他の配布条件を作者と合意する．

4. 他のプログラムへの引用はいかなる目的であれ自由です．た
   だし，本プログラムに含まれる他の作者によるコードは，そ
   れぞれの作者の意向による制限が加えられる場合があります．

   それらファイルの一覧とそれぞれの配布条件などに付いては
   LEGALファイルを参照してください．

5. 本プログラムへの入力となるスクリプトおよび，本プログラ
   ムからの出力の権利は本プログラムの作者ではなく，それぞ
   れの入出力を生成した人に属します．また，本プログラムに
   組み込まれるための拡張ライブラリについても同様です．

6. 本プログラムは無保証です．作者は本プログラムをサポート
   する意志はありますが，プログラム自身のバグあるいは本プ
   ログラムの実行などから発生するいかなる損害に対しても責
   任を持ちません．
# -*- rdoc -*-

= LEGAL NOTICE INFORMATION
--------------------------

All the files in this distribution are covered under either the Ruby's
license (see the file COPYING) or public-domain except some files
mentioned below.

[addr2line.c]

  A part of this file is from FreeBSD.

  >>>
    Copyright (c) 1986, 1988, 1991, 1993::
    The Regents of the University of California.  All rights reserved.

    (c) UNIX System Laboratories, Inc.

    All or some portions of this file are derived from material licensed
    to the University of California by American Telephone and Telegraph
    Co. or Unix System Laboratories, Inc. and are reproduced herein with
    the permission of UNIX System Laboratories, Inc.

    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.
    4. Neither the name of the University 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 REGENTS 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 REGENTS 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.

	@(#)subr_prf.c	8.3 (Berkeley) 1/21/94


[ccan/build_assert/build_assert.h]
[ccan/check_type/check_type.h]
[ccan/container_of/container_of.h]
[ccan/str/str.h]

  These files are licensed under the {CC0}[https://creativecommons.org/choose/zero/].

[ccan/list/list.h]

  This file is licensed under the {MIT License}[rdoc-label:label-MIT+License].

[coroutine]

  Unless otherwise specified, these files are licensed under the
  {MIT License}[rdoc-label:label-MIT+License].

[include/ruby/onigmo.h]
[include/ruby/oniguruma.h]
[regcomp.c]
[regenc.c]
[regenc.h]
[regerror.c]
[regexec.c]
[regint.h]
[regparse.c]
[regparse.h]
[enc/ascii.c]
[enc/big5.c]
[enc/cp949.c]
[enc/emacs_mule.c]
[enc/encdb.c]
[enc/euc_jp.c]
[enc/euc_kr.c]
[enc/euc_tw.c]
[enc/gb18030.c]
[enc/gb2312.c]
[enc/gbk.c]
[enc/iso_8859_1.c]
[enc/iso_8859_10.c]
[enc/iso_8859_11.c]
[enc/iso_8859_13.c]
[enc/iso_8859_14.c]
[enc/iso_8859_15.c]
[enc/iso_8859_16.c]
[enc/iso_8859_2.c]
[enc/iso_8859_3.c]
[enc/iso_8859_4.c]
[enc/iso_8859_5.c]
[enc/iso_8859_6.c]
[enc/iso_8859_7.c]
[enc/iso_8859_8.c]
[enc/iso_8859_9.c]
[enc/koi8_r.c]
[enc/koi8_u.c]
[enc/shift_jis.c]
[enc/unicode.c]
[enc/us_ascii.c]
[enc/utf_16be.c]
[enc/utf_16le.c]
[enc/utf_32be.c]
[enc/utf_32le.c]
[enc/utf_8.c]
[enc/windows_1251.c]
[enc/windows_31j.c]

  Onigmo (Oniguruma-mod) LICENSE

  >>>
    Copyright (c) 2002-2009::  K.Kosako  <sndgk393 AT ybb DOT ne DOT jp>
    Copyright (c) 2011-2014::  K.Takata  <kentkt AT csc DOT jp>
    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.

  Oniguruma LICENSE

  >>>
    Copyright (c) 2002-2009::  K.Kosako  <sndgk393 AT ybb DOT ne DOT jp>
    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.

  * https://github.com/k-takata/Onigmo/
  * https://github.com/kkos/oniguruma
  * https://svnweb.freebsd.org/ports/head/devel/oniguruma/

    When this software is partly used or it is distributed with Ruby,
    this of Ruby follows the license of Ruby.

[enc/windows_1250.c]
[enc/windows_1252.c]

  >>>
    Copyright (c) 2006-2007::  Byte      <byte AT mail DOT kna DOT ru>
                               K.Kosako  <sndgk393 AT ybb DOT ne DOT jp>
    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.

[enc/cesu_8.c]
[enc/windows_1253.c]
[enc/windows_1254.c]
[enc/windows_1257.c]

  >>>
    Copyright (c) 2002-2007::  K.Kosako  <sndgk393 AT ybb DOT ne DOT jp>
    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.

[enc/trans/GB/GB12345%UCS.src]
[enc/trans/GB/UCS%GB12345.src]
[enc/trans/GB/GB2312%UCS.src]
[enc/trans/GB/UCS%GB2312.src]

  These files have this explanatory texts.

  >>>
    This mapping data was created from files provided by Unicode, Inc.
    (The Unicode Consortium). The files were used to create a product supporting
    Unicode, as explicitly permitted in the files' copyright notices.
    Please note that Unicode, Inc. never made any claims as to fitness of these
    files for any particular purpose, and has ceased to publish the files many
    years ago.

[enc/trans/JIS/JISX0201-KANA%UCS.src]
[enc/trans/JIS/JISX0208\@1990%UCS.src]
[enc/trans/JIS/JISX0212%UCS.src]
[enc/trans/JIS/UCS%JISX0201-KANA.src]
[enc/trans/JIS/UCS%JISX0208@1990.src]
[enc/trans/JIS/UCS%JISX0212.src]

  These files are copyrighted as the following.

  >>>
    © 2015 Unicode®, Inc.

    For terms of use, see http://www.unicode.org/terms_of_use.html

[enc/trans/JIS/JISX0213-1%UCS@BMP.src]
[enc/trans/JIS/JISX0213-1%UCS@SIP.src]
[enc/trans/JIS/JISX0213-2%UCS@BMP.src]
[enc/trans/JIS/JISX0213-2%UCS@SIP.src]

  These files are copyrighted as the following.

  >>>
    Copyright (C) 2001:: earthian@tama.or.jp, All Rights Reserved.
    Copyright (C) 2001:: I'O, All Rights Reserved.
    Copyright (C) 2006:: Project X0213, All Rights Reserved.
    You can use, modify, distribute this table freely.

[enc/trans/JIS/UCS@BMP%JISX0213-1.src]
[enc/trans/JIS/UCS@BMP%JISX0213-2.src]
[enc/trans/JIS/UCS@SIP%JISX0213-1.src]
[enc/trans/JIS/UCS@SIP%JISX0213-2.src]

  These files are copyrighted as the following.

  >>>
    Copyright (C) 2001:: earthian@tama.or.jp, All Rights Reserved.
    Copyright (C) 2001:: I'O, All Rights Reserved.
    You can use, modify, distribute this table freely.

[enc/trans/ucm/glibc-BIG5-2.3.3.ucm]
[enc/trans/ucm/glibc-BIG5HKSCS-2.3.3.ucm]

  >>>
    Copyright (C) 2001-2005:: International Business Machines
                              Corporation and others.  All Rights Reserved.

[enc/trans/ucm/windows-950-2000.ucm]
[enc/trans/ucm/windows-950_hkscs-2001.ucm]

  >>>
    Copyright (C) 2001-2002:: International Business Machines
                              Corporation and others.  All Rights Reserved.


[configure]

  This file is free software.

  >>>
    Copyright (C) 1992-1996, 1998-2012:: Free Software Foundation, Inc.

    This configure script is free software; the Free Software Foundation
    gives unlimited permission to copy, distribute and modify it.

[aclocal.m4]

  This file is free software.

  >>>
    Copyright (C) 1996-2020:: Free Software Foundation, Inc.

    This file is free software; the Free Software Foundation
    gives unlimited permission to copy and/or distribute it,
    with or without modifications, as long as this notice is preserved.

[tool/config.guess]
[tool/config.sub]

  As long as you distribute these files with the file configure, they
  are covered under the Ruby's license.

  >>>
    Copyright 1992-2018:: Free Software Foundation, Inc.

    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 <https://www.gnu.org/licenses/>.

    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").

[parse.c]
[parse.h]

  These files are licensed under the GPL, but are incorporated into Ruby and
  redistributed under the terms of the Ruby license, as permitted by the
  exception to the GPL below.

  >>>
    Copyright (C) 1984, 1989-1990, 2000-2015, 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.  If not, see <http://www.gnu.org/licenses/>.

    As a special exception, you may create a larger work that contains
    part or all of the Bison parser skeleton and distribute that work
    under terms of your choice, so long as that work isn't itself a
    parser generator using the skeleton or a modified version thereof
    as a parser skeleton.  Alternatively, if you modify or redistribute
    the parser skeleton itself, you may (at your option) remove this
    special exception, which will cause the skeleton and the resulting
    Bison output files to be licensed under the GNU General Public
    License without this special exception.

    This special exception was added by the Free Software Foundation in
    version 2.2 of Bison.

[missing/dtoa.c]

  This file is under these licenses.

  >>>
    Copyright (c) 1991, 2000, 2001:: by Lucent Technologies.

    Permission to use, copy, modify, and distribute this software for any
    purpose without fee is hereby granted, provided that this entire notice
    is included in all copies of any software which is or includes a copy
    or modification of this software and in all copies of the supporting
    documentation for such software.

    THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
    WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
    REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
    OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.

  >>>
    Copyright (c) 2004-2008:: David Schultz <das@FreeBSD.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:
    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.

[win32/win32.c]
[include/ruby/win32.h]

  You can apply the Artistic License to these files. (or GPL,
  alternatively)

  >>>
    Copyright (c) 1993:: Intergraph Corporation

    You may distribute under the terms of either the GNU General Public
    License or the Artistic License, as specified in the perl README file.

[missing/mt19937.c]

  This file is under the new-style BSD license.

  >>>
    A C-program for MT19937, with initialization improved 2002/2/10.::
    Coded by Takuji Nishimura and Makoto Matsumoto.  
    This is a faster version by taking Shawn Cokus's optimization,
    Matthe Bellew's simplification, Isaku Wada's real version.

    Before using, initialize the state by using init_genrand(seed)
    or init_by_array(init_key, key_length).

    Copyright (C) 1997 - 2002:: Makoto Matsumoto and Takuji Nishimura,
                                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.

    3. 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.


    Any feedback is very welcome.
    http://www.math.keio.ac.jp/matumoto/emt.html
    email: matumoto@math.keio.ac.jp

  The Wayback Machine url: http://web.archive.org/web/19990429082237/http://www.math.keio.ac.jp/matumoto/emt.html

[missing/procstat_vm.c]

  This file is under the new-style BSD license.

  >>>
    Copyright (c) 2007:: Robert N. M. Watson
                         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.

    $FreeBSD: head/usr.bin/procstat/procstat_vm.c 261780 2014-02-11 21:57:37Z jhb $

[vsnprintf.c]

  This file is under the {old-style BSD license}[rdoc-label:label-Old-style+BSD+license].

  >>>
    Copyright (c) 1990, 1993::
    The Regents of the University of California.  All rights reserved.

    This code is derived from software contributed to Berkeley by
    Chris Torek.

[st.c]
[strftime.c]
[include/ruby/st.h]
[missing/acosh.c]
[missing/alloca.c]
[missing/dup2.c]
[missing/erf.c]
[missing/finite.c]
[missing/hypot.c]
[missing/isinf.c]
[missing/isnan.c]
[missing/lgamma_r.c]
[missing/memcmp.c]
[missing/memmove.c]
[missing/strchr.c]
[missing/strerror.c]
[missing/strstr.c]
[missing/tgamma.c]
[ext/date/date_strftime.c]
[ext/digest/sha1/sha1.c]
[ext/digest/sha1/sha1.h]

  These files are all under public domain.

[missing/crypt.c]

  This file is under the {old-style BSD license}[rdoc-label:label-Old-style+BSD+license].

  >>>
    Copyright (c) 1989, 1993::
    The Regents of the University of California.  All rights reserved.

    This code is derived from software contributed to Berkeley by
    Tom Truscott.

[missing/setproctitle.c]

  This file is under the {old-style BSD license}[rdoc-label:label-Old-style+BSD+license].

  >>>
    Copyright 2003:: Damien Miller
    Copyright (c) 1983, 1995-1997:: Eric P. Allman
    Copyright (c) 1988, 1993::
    The Regents of the University of California.  All rights reserved.

[missing/strlcat.c]
[missing/strlcpy.c]

  These files are under an ISC-style license.

  >>>
    Copyright (c) 1998, 2015:: Todd C. Miller <Todd.Miller@courtesan.com>

    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.

[missing/langinfo.c]

  This file is from http://www.cl.cam.ac.uk/~mgk25/ucs/langinfo.c.
  Ruby uses a modified version. The file contains the following
  author/copyright notice:

  >>>
    Markus.Kuhn@cl.cam.ac.uk -- 2002-03-11::
    Permission to use, copy, modify, and distribute this software
    for any purpose and without fee is hereby granted. The author
    disclaims all warranties with regard to this software.

[ext/digest/md5/md5.c]
[ext/digest/md5/md5.h]

  These files are under the following license.  Ruby uses modified
  versions of them.

  >>>
    Copyright (C) 1999, 2000:: Aladdin Enterprises.  All rights reserved.

    This software is provided 'as-is', without any express or implied
    warranty.  In no event will the authors be held liable for any damages
    arising from the use of this software.

    Permission is granted to anyone to use this software for any purpose,
    including commercial applications, and to alter it and redistribute it
    freely, subject to the following restrictions:

    1. The origin of this software must not be misrepresented; you must not
       claim that you wrote the original software. If you use this software
       in a product, an acknowledgment in the product documentation would be
       appreciated but is not required.
    2. Altered source versions must be plainly marked as such, and must not be
       misrepresented as being the original software.
    3. This notice may not be removed or altered from any source distribution.

    L. Peter Deutsch
    ghost@aladdin.com

[ext/digest/rmd160/rmd160.c]
[ext/digest/rmd160/rmd160.h]

  These files have the following copyright information, and by the
  author we are allowed to use it under the new-style BSD license.

  >>>
    AUTHOR::  Antoon Bosselaers, ESAT-COSIC
              (Arranged for libc by Todd C. Miller)
    DATE::    1 March 1996

    Copyright (c):: Katholieke Universiteit Leuven
    1996, All Rights Reserved

[ext/digest/sha2/sha2.c]
[ext/digest/sha2/sha2.h]

  These files are under the new-style BSD license.

  >>>
    Copyright 2000:: Aaron D. Gifford.  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.
    3. Neither the name of the copyright holder nor the names of contributors
       may be used to endorse or promote products derived from this software
       without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTOR(S) ``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(S) OR CONTRIBUTOR(S) 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.

[ext/json/generator/generator.c]

  The file contains the following copyright notice.

  >>>
    Copyright 2001-2004:: Unicode, Inc.

    Disclaimer::

      This source code is provided as is by Unicode, Inc. No claims are
      made as to fitness for any particular purpose. No warranties of any
      kind are expressed or implied. The recipient agrees to determine
      applicability of information provided. If this file has been
      purchased on magnetic or optical media from Unicode, Inc., the
      sole remedy for any claim will be exchange of defective media
      within 90 days of receipt.

    Limitations on Rights to Redistribute This Code::

      Unicode, Inc. hereby grants the right to freely use the information
      supplied in this file in the creation of products supporting the
      Unicode Standard, and to make copies of this file in any form
      for internal or external distribution as long as this notice
      remains attached.

[ext/nkf/nkf-utf8/config.h]
[ext/nkf/nkf-utf8/nkf.c]
[ext/nkf/nkf-utf8/utf8tbl.c]

  These files are under the following license.  So to speak, it is
  copyrighted semi-public-domain software.

  >>>
    Copyright (C) 1987:: Fujitsu LTD. (Itaru ICHIKAWA)

    Everyone is permitted to do anything on this program
    including copying, modifying, improving,
    as long as you don't try to pretend that you wrote it.
    i.e., the above copyright notice has to appear in all copies.
    Binary distribution requires original version messages.
    You don't have to ask before copying, redistribution or publishing.
    THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE.

[ext/psych]
[test/psych]

  The files under these directories are under the following license, except for
  ext/psych/yaml.

  >>>
    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.

[ext/psych/yaml]

  The files under this directory are under the following license.

  >>>
    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.

[ext/pty/pty.c]

  >>>
    C) Copyright 1998:: by Akinori Ito.

    This software may be redistributed freely for this purpose, in full
    or in part, provided that this entire copyright notice is included
    on any copies of this software and applications and derivations thereof.

    This software is provided on an "as is" basis, without warranty of any
    kind, either expressed or implied, as to any matter including, but not
    limited to warranty of fitness of purpose, or merchantability, or
    results obtained from use of this software.

[ext/socket/addrinfo.h]
[ext/socket/getaddrinfo.c]
[ext/socket/getnameinfo.c]

  These files are under the new-style BSD license.

  >>>
    Copyright (C) 1995, 1996, 1997, 1998, and 1999:: WIDE Project.
    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.
    3. Neither the name of the 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 PROJECT 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 PROJECT 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.

[ext/win32ole/win32ole.c]

  You can apply the Artistic License to this file. (or GPL,
  alternatively)

  >>>
    (c) 1995:: Microsoft Corporation. All rights reserved.
    Developed by ActiveWare Internet Corp., http://www.ActiveWare.com

    Other modifications Copyright (c) 1997, 1998:: by Gurusamy Sarathy
    <gsar@umich.edu> and Jan Dubois <jan.dubois@ibm.net>

    You may distribute under the terms of either the GNU General Public
    License or the Artistic License, as specified in the README file
    of the Perl distribution.

  The Wayback Machine url: http://web.archive.org/web/19970607104352/http://www.activeware.com:80/

[lib/rdoc/generator/template/darkfish/css/fonts.css]

  This file is licensed under the {SIL Open Font License}[http://scripts.sil.org/OFL].

[spec/mspec]
[spec/ruby]

  The files under these directories are under the following license.

  >>>
    Copyright (c) 2008:: Engine Yard, Inc. All rights reserved.

    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.

[lib/rubygems.rb]
[lib/rubygems]
[test/rubygems]

  RubyGems is under the following license.

  >>>
    RubyGems is copyrighted free software by Chad Fowler, Rich Kilmer, Jim
    Weirich and others.  You can redistribute it and/or modify it under
    either the terms of the {MIT license}[rdoc-label:label-MIT+License], 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 executables 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 executable
       form, provided that you do at least ONE of the following:

       a. distribute the executables 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 executables 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).

    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.

[lib/bundler]
[lib/bundler.rb]
[lib/bundler.gemspec]
[spec/bundler]
[man/bundle-*,gemfile.*]

  Bundler is under the following license.

  >>>
    Portions copyright (c) 2010:: Andre Arko
    Portions copyright (c) 2009:: Engine Yard

    {MIT License}[rdoc-label:label-MIT+License]

[lib/did_you_mean]
[lib/did_you_mean.rb]
[test/did_you_mean]

  did_you_mean is under the following license.

  >>>
    Copyright (c) 2014-2016 Yuki Nishijima

    {MIT License}[rdoc-label:label-MIT+License]

[benchmark/so_ackermann.rb]
[benchmark/so_array.rb]
[benchmark/so_binary_trees.rb]
[benchmark/so_concatenate.rb]
[benchmark/so_count_words.yml]
[benchmark/so_exception.rb]
[benchmark/so_fannkuch.rb]
[benchmark/so_fasta.rb]
[benchmark/so_k_nucleotide.yml]
[benchmark/so_lists.rb]
[benchmark/so_mandelbrot.rb]
[benchmark/so_matrix.rb]
[benchmark/so_meteor_contest.rb]
[benchmark/so_nbody.rb]
[benchmark/so_nested_loop.rb]
[benchmark/so_nsieve.rb]
[benchmark/so_nsieve_bits.rb]
[benchmark/so_object.rb]
[benchmark/so_partial_sums.rb]
[benchmark/so_pidigits.rb]
[benchmark/so_random.rb]
[benchmark/so_reverse_complement.yml]
[benchmark/so_sieve.rb]
[benchmark/so_spectralnorm.rb]

  These files are very old copy of then-called "The Great Computer Language
  Shootout".  LEGAL SITUATION OF THESE FILES ARE UNCLEAR because the original
  site has been lost.  Upstream diverged to delete several benchmarks listed
  above.

== MIT License
>>>
      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.

== Old-style BSD license
>>>
      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.
      3. Neither the name of the University 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 REGENTS 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 REGENTS 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.

      IMPORTANT NOTE::

      From ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change
      paragraph 3 above is now null and void.
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.
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require 'rbconfig'

module Gem
  VERSION = "3.2.33".freeze
end

# Must be first since it unloads the prelude from 1.9.2
require_relative 'rubygems/compatibility'

require_relative 'rubygems/defaults'
require_relative 'rubygems/deprecate'
require_relative 'rubygems/errors'

##
# RubyGems is the Ruby standard for publishing and managing third party
# libraries.
#
# For user documentation, see:
#
# * <tt>gem help</tt> and <tt>gem help [command]</tt>
# * {RubyGems User Guide}[https://guides.rubygems.org/]
# * {Frequently Asked Questions}[https://guides.rubygems.org/faqs]
#
# For gem developer documentation see:
#
# * {Creating Gems}[https://guides.rubygems.org/make-your-own-gem]
# * Gem::Specification
# * Gem::Version for version dependency notes
#
# Further RubyGems documentation can be found at:
#
# * {RubyGems Guides}[https://guides.rubygems.org]
# * {RubyGems API}[https://www.rubydoc.info/github/rubygems/rubygems] (also available from
#   <tt>gem server</tt>)
#
# == RubyGems Plugins
#
# RubyGems will load plugins in the latest version of each installed gem or
# $LOAD_PATH.  Plugins must be named 'rubygems_plugin' (.rb, .so, etc) and
# placed at the root of your gem's #require_path.  Plugins are installed at a
# special location and loaded on boot.
#
# For an example plugin, see the {Graph gem}[https://github.com/seattlerb/graph]
# which adds a `gem graph` command.
#
# == RubyGems Defaults, Packaging
#
# RubyGems defaults are stored in lib/rubygems/defaults.rb.  If you're packaging
# RubyGems or implementing Ruby you can change RubyGems' defaults.
#
# For RubyGems packagers, provide lib/rubygems/defaults/operating_system.rb
# and override any defaults from lib/rubygems/defaults.rb.
#
# For Ruby implementers, provide lib/rubygems/defaults/#{RUBY_ENGINE}.rb and
# override any defaults from lib/rubygems/defaults.rb.
#
# If you need RubyGems to perform extra work on install or uninstall, your
# defaults override file can set pre/post install and uninstall hooks.
# See Gem::pre_install, Gem::pre_uninstall, Gem::post_install,
# Gem::post_uninstall.
#
# == Bugs
#
# You can submit bugs to the
# {RubyGems bug tracker}[https://github.com/rubygems/rubygems/issues]
# on GitHub
#
# == Credits
#
# RubyGems is currently maintained by Eric Hodel.
#
# RubyGems was originally developed at RubyConf 2003 by:
#
# * Rich Kilmer  -- rich(at)infoether.com
# * Chad Fowler  -- chad(at)chadfowler.com
# * David Black  -- dblack(at)wobblini.net
# * Paul Brannan -- paul(at)atdesk.com
# * Jim Weirich   -- jim(at)weirichhouse.org
#
# Contributors:
#
# * Gavin Sinclair     -- gsinclair(at)soyabean.com.au
# * George Marrows     -- george.marrows(at)ntlworld.com
# * Dick Davies        -- rasputnik(at)hellooperator.net
# * Mauricio Fernandez -- batsman.geo(at)yahoo.com
# * Simon Strandgaard  -- neoneye(at)adslhome.dk
# * Dave Glasser       -- glasser(at)mit.edu
# * Paul Duncan        -- pabs(at)pablotron.org
# * Ville Aine         -- vaine(at)cs.helsinki.fi
# * Eric Hodel         -- drbrain(at)segment7.net
# * Daniel Berger      -- djberg96(at)gmail.com
# * Phil Hagelberg     -- technomancy(at)gmail.com
# * Ryan Davis         -- ryand-ruby(at)zenspider.com
# * Evan Phoenix       -- evan(at)fallingsnow.net
# * Steve Klabnik      -- steve(at)steveklabnik.com
#
# (If your name is missing, PLEASE let us know!)
#
# == License
#
# See {LICENSE.txt}[rdoc-ref:lib/rubygems/LICENSE.txt] for permissions.
#
# Thanks!
#
# -The RubyGems Team

module Gem
  RUBYGEMS_DIR = File.dirname File.expand_path(__FILE__)

  # Taint support is deprecated in Ruby 2.7.
  # This allows switching ".untaint" to ".tap(&Gem::UNTAINT)",
  # to avoid deprecation warnings in Ruby 2.7.
  UNTAINT = RUBY_VERSION < '2.7' ? :untaint.to_sym : proc{}

  # When https://bugs.ruby-lang.org/issues/17259 is available, there is no need to override Kernel#warn
  KERNEL_WARN_IGNORES_INTERNAL_ENTRIES = RUBY_ENGINE == "truffleruby" ||
      (RUBY_ENGINE == "ruby" && RUBY_VERSION >= '3.0')

  ##
  # An Array of Regexps that match windows Ruby platforms.

  WIN_PATTERNS = [
    /bccwin/i,
    /cygwin/i,
    /djgpp/i,
    /mingw/i,
    /mswin/i,
    /wince/i,
  ].freeze

  GEM_DEP_FILES = %w[
    gem.deps.rb
    gems.rb
    Gemfile
    Isolate
  ].freeze

  ##
  # Subdirectories in a gem repository

  REPOSITORY_SUBDIRECTORIES = %w[
    build_info
    cache
    doc
    extensions
    gems
    plugins
    specifications
  ].freeze

  ##
  # Subdirectories in a gem repository for default gems

  REPOSITORY_DEFAULT_GEM_SUBDIRECTORIES = %w[
    gems
    specifications/default
  ].freeze

  ##
  # Exception classes used in a Gem.read_binary +rescue+ statement

  READ_BINARY_ERRORS = [Errno::EACCES, Errno::EROFS, Errno::ENOSYS, Errno::ENOTSUP].freeze

  ##
  # Exception classes used in Gem.write_binary +rescue+ statement

  WRITE_BINARY_ERRORS = [Errno::ENOSYS, Errno::ENOTSUP].freeze

  @@win_platform = nil

  @configuration = nil
  @gemdeps = nil
  @loaded_specs = {}
  LOADED_SPECS_MUTEX = Thread::Mutex.new
  @path_to_default_spec_map = {}
  @platforms = []
  @ruby = nil
  @ruby_api_version = nil
  @sources = nil

  @post_build_hooks     ||= []
  @post_install_hooks   ||= []
  @post_uninstall_hooks ||= []
  @pre_uninstall_hooks  ||= []
  @pre_install_hooks    ||= []
  @pre_reset_hooks      ||= []
  @post_reset_hooks     ||= []

  @default_source_date_epoch = nil

  ##
  # Try to activate a gem containing +path+. Returns true if
  # activation succeeded or wasn't needed because it was already
  # activated. Returns false if it can't find the path in a gem.

  def self.try_activate(path)
    # finds the _latest_ version... regardless of loaded specs and their deps
    # if another gem had a requirement that would mean we shouldn't
    # activate the latest version, then either it would already be activated
    # or if it was ambiguous (and thus unresolved) the code in our custom
    # require will try to activate the more specific version.

    spec = Gem::Specification.find_by_path path
    return false unless spec
    return true if spec.activated?

    begin
      spec.activate
    rescue Gem::LoadError => e # this could fail due to gem dep collisions, go lax
      spec_by_name = Gem::Specification.find_by_name(spec.name)
      if spec_by_name.nil?
        raise e
      else
        spec_by_name.activate
      end
    end

    return true
  end

  def self.needs
    rs = Gem::RequestSet.new

    yield rs

    finish_resolve rs
  end

  def self.finish_resolve(request_set=Gem::RequestSet.new)
    request_set.import Gem::Specification.unresolved_deps.values
    request_set.import Gem.loaded_specs.values.map {|s| Gem::Dependency.new(s.name, s.version) }

    request_set.resolve_current.each do |s|
      s.full_spec.activate
    end
  end

  ##
  # Find the full path to the executable for gem +name+.  If the +exec_name+
  # is not given, an exception will be raised, otherwise the
  # specified executable's path is returned.  +requirements+ allows
  # you to specify specific gem versions.

  def self.bin_path(name, exec_name = nil, *requirements)
    requirements = Gem::Requirement.default if
      requirements.empty?

    find_spec_for_exe(name, exec_name, requirements).bin_file exec_name
  end

  def self.find_spec_for_exe(name, exec_name, requirements)
    raise ArgumentError, "you must supply exec_name" unless exec_name

    dep = Gem::Dependency.new name, requirements

    loaded = Gem.loaded_specs[name]

    return loaded if loaded && dep.matches_spec?(loaded)

    specs = dep.matching_specs(true)

    specs = specs.find_all do |spec|
      spec.executables.include? exec_name
    end if exec_name

    unless spec = specs.first
      msg = "can't find gem #{dep} with executable #{exec_name}"
      if dep.filters_bundler? && bundler_message = Gem::BundlerVersionFinder.missing_version_message
        msg = bundler_message
      end
      raise Gem::GemNotFoundException, msg
    end

    spec
  end
  private_class_method :find_spec_for_exe

  ##
  # Find the full path to the executable for gem +name+.  If the +exec_name+
  # is not given, an exception will be raised, otherwise the
  # specified executable's path is returned.  +requirements+ allows
  # you to specify specific gem versions.
  #
  # A side effect of this method is that it will activate the gem that
  # contains the executable.
  #
  # This method should *only* be used in bin stub files.

  def self.activate_bin_path(name, exec_name = nil, *requirements) # :nodoc:
    spec = find_spec_for_exe name, exec_name, requirements
    Gem::LOADED_SPECS_MUTEX.synchronize do
      spec.activate
      finish_resolve
    end
    spec.bin_file exec_name
  end

  ##
  # The mode needed to read a file as straight binary.

  def self.binary_mode
    'rb'
  end

  ##
  # The path where gem executables are to be installed.

  def self.bindir(install_dir=Gem.dir)
    return File.join install_dir, 'bin' unless
      install_dir.to_s == Gem.default_dir.to_s
    Gem.default_bindir
  end

  ##
  # The path were rubygems plugins are to be installed.

  def self.plugindir(install_dir=Gem.dir)
    File.join install_dir, 'plugins'
  end

  ##
  # Reset the +dir+ and +path+ values.  The next time +dir+ or +path+
  # is requested, the values will be calculated from scratch.  This is
  # mainly used by the unit tests to provide test isolation.

  def self.clear_paths
    @paths         = nil
    @user_home     = nil
    Gem::Specification.reset
    Gem::Security.reset if defined?(Gem::Security)
  end

  ##
  # The standard configuration object for gems.

  def self.configuration
    @configuration ||= Gem::ConfigFile.new []
  end

  ##
  # Use the given configuration object (which implements the ConfigFile
  # protocol) as the standard configuration object.

  def self.configuration=(config)
    @configuration = config
  end

  ##
  # The path to the data directory specified by the gem name.  If the
  # package is not available as a gem, return nil.

  def self.datadir(gem_name)
    spec = @loaded_specs[gem_name]
    return nil if spec.nil?
    spec.datadir
  end

  ##
  # A Zlib::Deflate.deflate wrapper

  def self.deflate(data)
    require 'zlib'
    Zlib::Deflate.deflate data
  end

  # Retrieve the PathSupport object that RubyGems uses to
  # lookup files.

  def self.paths
    @paths ||= Gem::PathSupport.new(ENV)
  end

  # Initialize the filesystem paths to use from +env+.
  # +env+ is a hash-like object (typically ENV) that
  # is queried for 'GEM_HOME', 'GEM_PATH', and 'GEM_SPEC_CACHE'
  # Keys for the +env+ hash should be Strings, and values of the hash should
  # be Strings or +nil+.

  def self.paths=(env)
    clear_paths
    target = {}
    env.each_pair do |k,v|
      case k
      when 'GEM_HOME', 'GEM_PATH', 'GEM_SPEC_CACHE'
        case v
        when nil, String
          target[k] = v
        when Array
          unless Gem::Deprecate.skip
            warn <<-EOWARN
Array values in the parameter to `Gem.paths=` are deprecated.
Please use a String or nil.
An Array (#{env.inspect}) was passed in from #{caller[3]}
            EOWARN
          end
          target[k] = v.join File::PATH_SEPARATOR
        end
      else
        target[k] = v
      end
    end
    @paths = Gem::PathSupport.new ENV.to_hash.merge(target)
    Gem::Specification.dirs = @paths.path
  end

  ##
  # The path where gems are to be installed.

  def self.dir
    paths.home
  end

  def self.path
    paths.path
  end

  def self.spec_cache_dir
    paths.spec_cache_dir
  end

  ##
  # Quietly ensure the Gem directory +dir+ contains all the proper
  # subdirectories.  If we can't create a directory due to a permission
  # problem, then we will silently continue.
  #
  # If +mode+ is given, missing directories are created with this mode.
  #
  # World-writable directories will never be created.

  def self.ensure_gem_subdirectories(dir = Gem.dir, mode = nil)
    ensure_subdirectories(dir, mode, REPOSITORY_SUBDIRECTORIES)
  end

  ##
  # Quietly ensure the Gem directory +dir+ contains all the proper
  # subdirectories for handling default gems.  If we can't create a
  # directory due to a permission problem, then we will silently continue.
  #
  # If +mode+ is given, missing directories are created with this mode.
  #
  # World-writable directories will never be created.

  def self.ensure_default_gem_subdirectories(dir = Gem.dir, mode = nil)
    ensure_subdirectories(dir, mode, REPOSITORY_DEFAULT_GEM_SUBDIRECTORIES)
  end

  def self.ensure_subdirectories(dir, mode, subdirs) # :nodoc:
    old_umask = File.umask
    File.umask old_umask | 002

    require 'fileutils'

    options = {}

    options[:mode] = mode if mode

    subdirs.each do |name|
      subdir = File.join dir, name
      next if File.exist? subdir
      begin
        FileUtils.mkdir_p subdir, **options
      rescue SystemCallError
      end
    end
  ensure
    File.umask old_umask
  end

  ##
  # The extension API version of ruby.  This includes the static vs non-static
  # distinction as extensions cannot be shared between the two.

  def self.extension_api_version # :nodoc:
    if 'no' == RbConfig::CONFIG['ENABLE_SHARED']
      "#{ruby_api_version}-static"
    else
      ruby_api_version
    end
  end

  ##
  # Returns a list of paths matching +glob+ that can be used by a gem to pick
  # up features from other gems.  For example:
  #
  #   Gem.find_files('rdoc/discover').each do |path| load path end
  #
  # if +check_load_path+ is true (the default), then find_files also searches
  # $LOAD_PATH for files as well as gems.
  #
  # Note that find_files will return all files even if they are from different
  # versions of the same gem.  See also find_latest_files

  def self.find_files(glob, check_load_path=true)
    files = []

    files = find_files_from_load_path glob if check_load_path

    gem_specifications = @gemdeps ? Gem.loaded_specs.values : Gem::Specification.stubs

    files.concat gem_specifications.map {|spec|
      spec.matches_for_glob("#{glob}#{Gem.suffix_pattern}")
    }.flatten

    # $LOAD_PATH might contain duplicate entries or reference
    # the spec dirs directly, so we prune.
    files.uniq! if check_load_path

    return files
  end

  def self.find_files_from_load_path(glob) # :nodoc:
    glob_with_suffixes = "#{glob}#{Gem.suffix_pattern}"
    $LOAD_PATH.map do |load_path|
      Gem::Util.glob_files_in_dir(glob_with_suffixes, load_path)
    end.flatten.select {|file| File.file? file.tap(&Gem::UNTAINT) }
  end

  ##
  # Returns a list of paths matching +glob+ from the latest gems that can be
  # used by a gem to pick up features from other gems.  For example:
  #
  #   Gem.find_latest_files('rdoc/discover').each do |path| load path end
  #
  # if +check_load_path+ is true (the default), then find_latest_files also
  # searches $LOAD_PATH for files as well as gems.
  #
  # Unlike find_files, find_latest_files will return only files from the
  # latest version of a gem.

  def self.find_latest_files(glob, check_load_path=true)
    files = []

    files = find_files_from_load_path glob if check_load_path

    files.concat Gem::Specification.latest_specs(true).map {|spec|
      spec.matches_for_glob("#{glob}#{Gem.suffix_pattern}")
    }.flatten

    # $LOAD_PATH might contain duplicate entries or reference
    # the spec dirs directly, so we prune.
    files.uniq! if check_load_path

    return files
  end

  ##
  # Top level install helper method. Allows you to install gems interactively:
  #
  #   % irb
  #   >> Gem.install "minitest"
  #   Fetching: minitest-5.14.0.gem (100%)
  #   => [#<Gem::Specification:0x1013b4528 @name="minitest", ...>]

  def self.install(name, version = Gem::Requirement.default, *options)
    require_relative "rubygems/dependency_installer"
    inst = Gem::DependencyInstaller.new(*options)
    inst.install name, version
    inst.installed_gems
  end

  ##
  # Get the default RubyGems API host. This is normally
  # <tt>https://rubygems.org</tt>.

  def self.host
    @host ||= Gem::DEFAULT_HOST
  end

  ## Set the default RubyGems API host.

  def self.host=(host)
    @host = host
  end

  ##
  # The index to insert activated gem paths into the $LOAD_PATH. The activated
  # gem's paths are inserted before site lib directory by default.

  def self.load_path_insert_index
    $LOAD_PATH.each_with_index do |path, i|
      return i if path.instance_variable_defined?(:@gem_prelude_index)
    end

    index = $LOAD_PATH.index RbConfig::CONFIG['sitelibdir']

    index || 0
  end

  ##
  # The number of paths in the `$LOAD_PATH` from activated gems. Used to
  # prioritize `-I` and `ENV['RUBYLIB`]` entries during `require`.

  def self.activated_gem_paths
    @activated_gem_paths ||= 0
  end

  ##
  # Add a list of paths to the $LOAD_PATH at the proper place.

  def self.add_to_load_path(*paths)
    @activated_gem_paths = activated_gem_paths + paths.size

    # gem directories must come after -I and ENV['RUBYLIB']
    $LOAD_PATH.insert(Gem.load_path_insert_index, *paths)
  end

  @yaml_loaded = false

  ##
  # Loads YAML, preferring Psych

  def self.load_yaml
    return if @yaml_loaded

    begin
      # Try requiring the gem version *or* stdlib version of psych.
      require 'psych'
    rescue ::LoadError
      # If we can't load psych, that's fine, go on.
    else
      require_relative 'rubygems/psych_additions'
      require_relative 'rubygems/psych_tree'
    end

    require 'yaml'
    require_relative 'rubygems/safe_yaml'

    @yaml_loaded = true
  end

  ##
  # The file name and line number of the caller of the caller of this method.
  #
  # +depth+ is how many layers up the call stack it should go.
  #
  # e.g.,
  #
  # def a; Gem.location_of_caller; end
  # a #=> ["x.rb", 2]  # (it'll vary depending on file name and line number)
  #
  # def b; c; end
  # def c; Gem.location_of_caller(2); end
  # b #=> ["x.rb", 6]  # (it'll vary depending on file name and line number)

  def self.location_of_caller(depth = 1)
    caller[depth] =~ /(.*?):(\d+).*?$/i
    file = $1
    lineno = $2.to_i

    [file, lineno]
  end

  ##
  # The version of the Marshal format for your Ruby.

  def self.marshal_version
    "#{Marshal::MAJOR_VERSION}.#{Marshal::MINOR_VERSION}"
  end

  ##
  # Set array of platforms this RubyGems supports (primarily for testing).

  def self.platforms=(platforms)
    @platforms = platforms
  end

  ##
  # Array of platforms this RubyGems supports.

  def self.platforms
    @platforms ||= []
    if @platforms.empty?
      @platforms = [Gem::Platform::RUBY, Gem::Platform.local]
    end
    @platforms
  end

  ##
  # Adds a post-build hook that will be passed an Gem::Installer instance
  # when Gem::Installer#install is called.  The hook is called after the gem
  # has been extracted and extensions have been built but before the
  # executables or gemspec has been written.  If the hook returns +false+ then
  # the gem's files will be removed and the install will be aborted.

  def self.post_build(&hook)
    @post_build_hooks << hook
  end

  ##
  # Adds a post-install hook that will be passed an Gem::Installer instance
  # when Gem::Installer#install is called

  def self.post_install(&hook)
    @post_install_hooks << hook
  end

  ##
  # Adds a post-installs hook that will be passed a Gem::DependencyInstaller
  # and a list of installed specifications when
  # Gem::DependencyInstaller#install is complete

  def self.done_installing(&hook)
    @done_installing_hooks << hook
  end

  ##
  # Adds a hook that will get run after Gem::Specification.reset is
  # run.

  def self.post_reset(&hook)
    @post_reset_hooks << hook
  end

  ##
  # Adds a post-uninstall hook that will be passed a Gem::Uninstaller instance
  # and the spec that was uninstalled when Gem::Uninstaller#uninstall is
  # called

  def self.post_uninstall(&hook)
    @post_uninstall_hooks << hook
  end

  ##
  # Adds a pre-install hook that will be passed an Gem::Installer instance
  # when Gem::Installer#install is called.  If the hook returns +false+ then
  # the install will be aborted.

  def self.pre_install(&hook)
    @pre_install_hooks << hook
  end

  ##
  # Adds a hook that will get run before Gem::Specification.reset is
  # run.

  def self.pre_reset(&hook)
    @pre_reset_hooks << hook
  end

  ##
  # Adds a pre-uninstall hook that will be passed an Gem::Uninstaller instance
  # and the spec that will be uninstalled when Gem::Uninstaller#uninstall is
  # called

  def self.pre_uninstall(&hook)
    @pre_uninstall_hooks << hook
  end

  ##
  # The directory prefix this RubyGems was installed at. If your
  # prefix is in a standard location (ie, rubygems is installed where
  # you'd expect it to be), then prefix returns nil.

  def self.prefix
    prefix = File.dirname RUBYGEMS_DIR

    if prefix != File.expand_path(RbConfig::CONFIG['sitelibdir']) and
       prefix != File.expand_path(RbConfig::CONFIG['libdir']) and
       'lib' == File.basename(RUBYGEMS_DIR)
      prefix
    end
  end

  ##
  # Refresh available gems from disk.

  def self.refresh
    Gem::Specification.reset
  end

  ##
  # Safely read a file in binary mode on all platforms.

  def self.read_binary(path)
    File.open path, 'rb+' do |f|
      f.flock(File::LOCK_EX)
      f.read
    end
  rescue *READ_BINARY_ERRORS
    File.open path, 'rb' do |f|
      f.read
    end
  rescue Errno::ENOLCK # NFS
    if Thread.main != Thread.current
      raise
    else
      File.open path, 'rb' do |f|
        f.read
      end
    end
  end

  ##
  # Safely write a file in binary mode on all platforms.
  def self.write_binary(path, data)
    File.open(path, File::RDWR | File::CREAT | File::BINARY | File::LOCK_EX) do |io|
      io.write data
    end
  rescue *WRITE_BINARY_ERRORS
    File.open(path, 'wb') do |io|
      io.write data
    end
  rescue Errno::ENOLCK # NFS
    if Thread.main != Thread.current
      raise
    else
      File.open(path, 'wb') do |io|
        io.write data
      end
    end
  end

  ##
  # The path to the running Ruby interpreter.

  def self.ruby
    if @ruby.nil?
      @ruby = RbConfig.ruby

      @ruby = "\"#{@ruby}\"" if @ruby =~ /\s/
    end

    @ruby
  end

  ##
  # Returns a String containing the API compatibility version of Ruby

  def self.ruby_api_version
    @ruby_api_version ||= RbConfig::CONFIG['ruby_version'].dup
  end

  def self.env_requirement(gem_name)
    @env_requirements_by_name ||= {}
    @env_requirements_by_name[gem_name] ||= begin
      req = ENV["GEM_REQUIREMENT_#{gem_name.upcase}"] || '>= 0'.freeze
      Gem::Requirement.create(req)
    end
  end
  post_reset { @env_requirements_by_name = {} }

  ##
  # Returns the latest release-version specification for the gem +name+.

  def self.latest_spec_for(name)
    dependency   = Gem::Dependency.new name
    fetcher      = Gem::SpecFetcher.fetcher
    spec_tuples, = fetcher.spec_for_dependency dependency

    spec, = spec_tuples.first

    spec
  end

  ##
  # Returns the latest release version of RubyGems.

  def self.latest_rubygems_version
    latest_version_for('rubygems-update') or
      raise "Can't find 'rubygems-update' in any repo. Check `gem source list`."
  end

  ##
  # Returns the version of the latest release-version of gem +name+

  def self.latest_version_for(name)
    spec = latest_spec_for name
    spec and spec.version
  end

  ##
  # A Gem::Version for the currently running Ruby.

  def self.ruby_version
    return @ruby_version if defined? @ruby_version
    version = RUBY_VERSION.dup

    if defined?(RUBY_PATCHLEVEL) && RUBY_PATCHLEVEL != -1
      version << ".#{RUBY_PATCHLEVEL}"
    elsif defined?(RUBY_DESCRIPTION)
      if RUBY_ENGINE == "ruby"
        desc = RUBY_DESCRIPTION[/\Aruby #{Regexp.quote(RUBY_VERSION)}([^ ]+) /, 1]
      else
        desc = RUBY_DESCRIPTION[/\A#{RUBY_ENGINE} #{Regexp.quote(RUBY_ENGINE_VERSION)} \(#{RUBY_VERSION}([^ ]+)\) /, 1]
      end
      version << ".#{desc}" if desc
    end

    @ruby_version = Gem::Version.new version
  end

  ##
  # A Gem::Version for the currently running RubyGems

  def self.rubygems_version
    return @rubygems_version if defined? @rubygems_version
    @rubygems_version = Gem::Version.new Gem::VERSION
  end

  ##
  # Returns an Array of sources to fetch remote gems from. Uses
  # default_sources if the sources list is empty.

  def self.sources
    source_list = configuration.sources || default_sources
    @sources ||= Gem::SourceList.from(source_list)
  end

  ##
  # Need to be able to set the sources without calling
  # Gem.sources.replace since that would cause an infinite loop.
  #
  # DOC: This comment is not documentation about the method itself, it's
  # more of a code comment about the implementation.

  def self.sources=(new_sources)
    if !new_sources
      @sources = nil
    else
      @sources = Gem::SourceList.from(new_sources)
    end
  end

  ##
  # Glob pattern for require-able path suffixes.

  def self.suffix_pattern
    @suffix_pattern ||= "{#{suffixes.join(',')}}"
  end

  ##
  # Regexp for require-able path suffixes.

  def self.suffix_regexp
    @suffix_regexp ||= /#{Regexp.union(suffixes)}\z/
  end

  ##
  # Glob pattern for require-able plugin suffixes.

  def self.plugin_suffix_pattern
    @plugin_suffix_pattern ||= "_plugin#{suffix_pattern}"
  end

  ##
  # Regexp for require-able plugin suffixes.

  def self.plugin_suffix_regexp
    @plugin_suffix_regexp ||= /_plugin#{suffix_regexp}\z/
  end

  ##
  # Suffixes for require-able paths.

  def self.suffixes
    @suffixes ||= ['',
                   '.rb',
                   *%w[DLEXT DLEXT2].map do |key|
                     val = RbConfig::CONFIG[key]
                     next unless val and not val.empty?
                     ".#{val}"
                   end,
                  ].compact.uniq
  end

  ##
  # Prints the amount of time the supplied block takes to run using the debug
  # UI output.

  def self.time(msg, width = 0, display = Gem.configuration.verbose)
    now = Time.now

    value = yield

    elapsed = Time.now - now

    ui.say "%2$*1$s: %3$3.3fs" % [-width, msg, elapsed] if display

    value
  end

  ##
  # Lazily loads DefaultUserInteraction and returns the default UI.

  def self.ui
    require_relative 'rubygems/user_interaction'

    Gem::DefaultUserInteraction.ui
  end

  ##
  # Use the +home+ and +paths+ values for Gem.dir and Gem.path.  Used mainly
  # by the unit tests to provide environment isolation.

  def self.use_paths(home, *paths)
    paths.flatten!
    paths.compact!
    hash = { "GEM_HOME" => home, "GEM_PATH" => paths.empty? ? home : paths.join(File::PATH_SEPARATOR) }
    hash.delete_if {|_, v| v.nil? }
    self.paths = hash
  end

  ##
  # Is this a windows platform?

  def self.win_platform?
    if @@win_platform.nil?
      ruby_platform = RbConfig::CONFIG['host_os']
      @@win_platform = !!WIN_PATTERNS.find {|r| ruby_platform =~ r }
    end

    @@win_platform
  end

  ##
  # Is this a java platform?

  def self.java_platform?
    RUBY_PLATFORM == "java"
  end

  ##
  # Load +plugins+ as Ruby files

  def self.load_plugin_files(plugins) # :nodoc:
    plugins.each do |plugin|

      # Skip older versions of the GemCutter plugin: Its commands are in
      # RubyGems proper now.

      next if plugin =~ /gemcutter-0\.[0-3]/

      begin
        load plugin
      rescue ::Exception => e
        details = "#{plugin.inspect}: #{e.message} (#{e.class})"
        warn "Error loading RubyGems plugin #{details}"
      end
    end
  end

  ##
  # Find rubygems plugin files in the standard location and load them

  def self.load_plugins
    Gem.path.each do |gem_path|
      load_plugin_files Gem::Util.glob_files_in_dir("*#{Gem.plugin_suffix_pattern}", plugindir(gem_path))
    end
  end

  ##
  # Find all 'rubygems_plugin' files in $LOAD_PATH and load them

  def self.load_env_plugins
    load_plugin_files find_files_from_load_path("rubygems_plugin")
  end

  ##
  # Looks for a gem dependency file at +path+ and activates the gems in the
  # file if found.  If the file is not found an ArgumentError is raised.
  #
  # If +path+ is not given the RUBYGEMS_GEMDEPS environment variable is used,
  # but if no file is found no exception is raised.
  #
  # If '-' is given for +path+ RubyGems searches up from the current working
  # directory for gem dependency files (gem.deps.rb, Gemfile, Isolate) and
  # activates the gems in the first one found.
  #
  # You can run this automatically when rubygems starts.  To enable, set
  # the <code>RUBYGEMS_GEMDEPS</code> environment variable to either the path
  # of your gem dependencies file or "-" to auto-discover in parent
  # directories.
  #
  # NOTE: Enabling automatic discovery on multiuser systems can lead to
  # execution of arbitrary code when used from directories outside your
  # control.

  def self.use_gemdeps(path = nil)
    raise_exception = path

    path ||= ENV['RUBYGEMS_GEMDEPS']
    return unless path

    path = path.dup

    if path == "-"
      Gem::Util.traverse_parents Dir.pwd do |directory|
        dep_file = GEM_DEP_FILES.find {|f| File.file?(f) }

        next unless dep_file

        path = File.join directory, dep_file
        break
      end
    end

    path.tap(&Gem::UNTAINT)

    unless File.file? path
      return unless raise_exception

      raise ArgumentError, "Unable to find gem dependencies file at #{path}"
    end

    ENV["BUNDLE_GEMFILE"] ||= File.expand_path(path)
    require_relative 'rubygems/user_interaction'
    require "bundler"
    begin
      Gem::DefaultUserInteraction.use_ui(ui) do
        begin
          Bundler.ui.silence do
            @gemdeps = Bundler.setup
          end
        ensure
          Gem::DefaultUserInteraction.ui.close
        end
      end
    rescue Bundler::BundlerError => e
      warn e.message
      warn "You may need to `bundle install` to install missing gems"
      warn ""
    end
  end

  ##
  # If the SOURCE_DATE_EPOCH environment variable is set, returns it's value.
  # Otherwise, returns the time that `Gem.source_date_epoch_string` was
  # first called in the same format as SOURCE_DATE_EPOCH.
  #
  # NOTE(@duckinator): The implementation is a tad weird because we want to:
  #   1. Make builds reproducible by default, by having this function always
  #      return the same result during a given run.
  #   2. Allow changing ENV['SOURCE_DATE_EPOCH'] at runtime, since multiple
  #      tests that set this variable will be run in a single process.
  #
  # If you simplify this function and a lot of tests fail, that is likely
  # due to #2 above.
  #
  # Details on SOURCE_DATE_EPOCH:
  # https://reproducible-builds.org/specs/source-date-epoch/

  def self.source_date_epoch_string
    # The value used if $SOURCE_DATE_EPOCH is not set.
    @default_source_date_epoch ||= Time.now.to_i.to_s

    specified_epoch = ENV["SOURCE_DATE_EPOCH"]

    # If it's empty or just whitespace, treat it like it wasn't set at all.
    specified_epoch = nil if !specified_epoch.nil? && specified_epoch.strip.empty?

    epoch = specified_epoch || @default_source_date_epoch

    epoch.strip
  end

  ##
  # Returns the value of Gem.source_date_epoch_string, as a Time object.
  #
  # This is used throughout RubyGems for enabling reproducible builds.

  def self.source_date_epoch
    Time.at(self.source_date_epoch_string.to_i).utc.freeze
  end

  # FIX: Almost everywhere else we use the `def self.` way of defining class
  # methods, and then we switch over to `class << self` here. Pick one or the
  # other.
  class << self
    ##
    # RubyGems distributors (like operating system package managers) can
    # disable RubyGems update by setting this to error message printed to
    # end-users on gem update --system instead of actual update.
    attr_accessor :disable_system_update_message

    ##
    # Hash of loaded Gem::Specification keyed by name

    attr_reader :loaded_specs

    ##
    # GemDependencyAPI object, which is set when .use_gemdeps is called.
    # This contains all the information from the Gemfile.

    attr_reader :gemdeps

    ##
    # Register a Gem::Specification for default gem.
    #
    # Two formats for the specification are supported:
    #
    # * MRI 2.0 style, where spec.files contains unprefixed require names.
    #   The spec's filenames will be registered as-is.
    # * New style, where spec.files contains files prefixed with paths
    #   from spec.require_paths. The prefixes are stripped before
    #   registering the spec's filenames. Unprefixed files are omitted.
    #

    def register_default_spec(spec)
      extended_require_paths = spec.require_paths.map {|f| f + "/" }
      new_format = extended_require_paths.any? {|path| spec.files.any? {|f| f.start_with? path } }

      if new_format
        prefix_group = extended_require_paths.join("|")
        prefix_pattern = /^(#{prefix_group})/
      end

      spec.files.each do |file|
        if new_format
          file = file.sub(prefix_pattern, "")
          next unless $~
        end

        spec.activate if already_loaded?(file)

        @path_to_default_spec_map[file] = spec
        @path_to_default_spec_map[file.sub(suffix_regexp, "")] = spec
      end
    end

    ##
    # Find a Gem::Specification of default gem from +path+

    def find_unresolved_default_spec(path)
      default_spec = @path_to_default_spec_map[path]
      return default_spec if default_spec && loaded_specs[default_spec.name] != default_spec
    end

    ##
    # Clear default gem related variables. It is for test

    def clear_default_specs
      @path_to_default_spec_map.clear
    end

    ##
    # The list of hooks to be run after Gem::Installer#install extracts files
    # and builds extensions

    attr_reader :post_build_hooks

    ##
    # The list of hooks to be run after Gem::Installer#install completes
    # installation

    attr_reader :post_install_hooks

    ##
    # The list of hooks to be run after Gem::DependencyInstaller installs a
    # set of gems

    attr_reader :done_installing_hooks

    ##
    # The list of hooks to be run after Gem::Specification.reset is run.

    attr_reader :post_reset_hooks

    ##
    # The list of hooks to be run after Gem::Uninstaller#uninstall completes
    # installation

    attr_reader :post_uninstall_hooks

    ##
    # The list of hooks to be run before Gem::Installer#install does any work

    attr_reader :pre_install_hooks

    ##
    # The list of hooks to be run before Gem::Specification.reset is run.

    attr_reader :pre_reset_hooks

    ##
    # The list of hooks to be run before Gem::Uninstaller#uninstall does any
    # work

    attr_reader :pre_uninstall_hooks

    private

    def already_loaded?(file)
      $LOADED_FEATURES.any? do |feature_path|
        feature_path.end_with?(file) && default_gem_load_paths.any? {|load_path_entry| feature_path == "#{load_path_entry}/#{file}" }
      end
    end

    def default_gem_load_paths
      @default_gem_load_paths ||= $LOAD_PATH[load_path_insert_index..-1].map do |lp|
        expanded = File.expand_path(lp)
        next expanded unless File.exist?(expanded)

        File.realpath(expanded)
      end
    end
  end

  ##
  # Location of Marshal quick gemspecs on remote repositories

  MARSHAL_SPEC_DIR = "quick/Marshal.#{Gem.marshal_version}/".freeze

  autoload :BundlerVersionFinder, File.expand_path('rubygems/bundler_version_finder', __dir__)
  autoload :ConfigFile,         File.expand_path('rubygems/config_file', __dir__)
  autoload :Dependency,         File.expand_path('rubygems/dependency', __dir__)
  autoload :DependencyList,     File.expand_path('rubygems/dependency_list', __dir__)
  autoload :Installer,          File.expand_path('rubygems/installer', __dir__)
  autoload :Licenses,           File.expand_path('rubygems/util/licenses', __dir__)
  autoload :NameTuple,          File.expand_path('rubygems/name_tuple', __dir__)
  autoload :PathSupport,        File.expand_path('rubygems/path_support', __dir__)
  autoload :RequestSet,         File.expand_path('rubygems/request_set', __dir__)
  autoload :Resolver,           File.expand_path('rubygems/resolver', __dir__)
  autoload :Source,             File.expand_path('rubygems/source', __dir__)
  autoload :SourceList,         File.expand_path('rubygems/source_list', __dir__)
  autoload :SpecFetcher,        File.expand_path('rubygems/spec_fetcher', __dir__)
  autoload :Util,               File.expand_path('rubygems/util', __dir__)
  autoload :Version,            File.expand_path('rubygems/version', __dir__)
end

require_relative 'rubygems/exceptions'
require_relative 'rubygems/specification'

# REFACTOR: This should be pulled out into some kind of hacks file.
begin
  ##
  # Defaults the operating system (or packager) wants to provide for RubyGems.

  require 'rubygems/defaults/operating_system'
rescue LoadError
  # Ignored
rescue StandardError => e
  msg = "#{e.message}\n" \
    "Loading the rubygems/defaults/operating_system.rb file caused an error. " \
    "This file is owned by your OS, not by rubygems upstream. " \
    "Please find out which OS package this file belongs to and follow the guidelines from your OS to report " \
    "the problem and ask for help."
  raise e.class, msg
end

begin
  ##
  # Defaults the Ruby implementation wants to provide for RubyGems

  require "rubygems/defaults/#{RUBY_ENGINE}"
rescue LoadError
end

##
# Loads the default specs.
Gem::Specification.load_defaults

require_relative 'rubygems/core_ext/kernel_gem'
require_relative 'rubygems/core_ext/kernel_require'
require_relative 'rubygems/core_ext/kernel_warn'
# frozen_string_literal: true

require_relative "text"
##
# A Source knows how to list and fetch gems from a RubyGems marshal index.
#
# There are other Source subclasses for installed gems, local gems, the
# bundler dependency API and so-forth.

class Gem::Source
  include Comparable
  include Gem::Text

  FILES = { # :nodoc:
    :released   => 'specs',
    :latest     => 'latest_specs',
    :prerelease => 'prerelease_specs',
  }.freeze

  ##
  # The URI this source will fetch gems from.

  attr_reader :uri

  ##
  # Creates a new Source which will use the index located at +uri+.

  def initialize(uri)
    begin
      unless uri.kind_of? URI
        uri = URI.parse(uri.to_s)
      end
    rescue URI::InvalidURIError
      raise if Gem::Source == self.class
    end

    @uri = uri
  end

  ##
  # Sources are ordered by installation preference.

  def <=>(other)
    case other
    when Gem::Source::Installed,
         Gem::Source::Local,
         Gem::Source::Lock,
         Gem::Source::SpecificFile,
         Gem::Source::Git,
         Gem::Source::Vendor then
      -1
    when Gem::Source then
      if !@uri
        return 0 unless other.uri
        return 1
      end

      return -1 if !other.uri

      # Returning 1 here ensures that when sorting a list of sources, the
      # original ordering of sources supplied by the user is preserved.
      return 1 unless @uri.to_s == other.uri.to_s

      0
    else
      nil
    end
  end

  def ==(other) # :nodoc:
    self.class === other and @uri == other.uri
  end

  alias_method :eql?, :== # :nodoc:

  ##
  # Returns a Set that can fetch specifications from this source.

  def dependency_resolver_set # :nodoc:
    return Gem::Resolver::IndexSet.new self if 'file' == uri.scheme

    fetch_uri = if uri.host == "rubygems.org"
                  index_uri = uri.dup
                  index_uri.host = "index.rubygems.org"
                  index_uri
                else
                  uri
                end

    bundler_api_uri = enforce_trailing_slash(fetch_uri)

    begin
      fetcher = Gem::RemoteFetcher.fetcher
      response = fetcher.fetch_path bundler_api_uri, nil, true
    rescue Gem::RemoteFetcher::FetchError
      Gem::Resolver::IndexSet.new self
    else
      Gem::Resolver::APISet.new response.uri + "./info/"
    end
  end

  def hash # :nodoc:
    @uri.hash
  end

  ##
  # Returns the local directory to write +uri+ to.

  def cache_dir(uri)
    # Correct for windows paths
    escaped_path = uri.path.sub(/^\/([a-z]):\//i, '/\\1-/')
    escaped_path.tap(&Gem::UNTAINT)

    File.join Gem.spec_cache_dir, "#{uri.host}%#{uri.port}", File.dirname(escaped_path)
  end

  ##
  # Returns true when it is possible and safe to update the cache directory.

  def update_cache?
    @update_cache ||=
      begin
        File.stat(Gem.user_home).uid == Process.uid
      rescue Errno::ENOENT
        false
      end
  end

  ##
  # Fetches a specification for the given +name_tuple+.

  def fetch_spec(name_tuple)
    fetcher = Gem::RemoteFetcher.fetcher

    spec_file_name = name_tuple.spec_name

    source_uri = enforce_trailing_slash(uri) + "#{Gem::MARSHAL_SPEC_DIR}#{spec_file_name}"

    cache_dir = cache_dir source_uri

    local_spec = File.join cache_dir, spec_file_name

    if File.exist? local_spec
      spec = Gem.read_binary local_spec
      spec = Marshal.load(spec) rescue nil
      return spec if spec
    end

    source_uri.path << '.rz'

    spec = fetcher.fetch_path source_uri
    spec = Gem::Util.inflate spec

    if update_cache?
      require "fileutils"
      FileUtils.mkdir_p cache_dir

      File.open local_spec, 'wb' do |io|
        io.write spec
      end
    end

    # TODO: Investigate setting Gem::Specification#loaded_from to a URI
    Marshal.load spec
  end

  ##
  # Loads +type+ kind of specs fetching from +@uri+ if the on-disk cache is
  # out of date.
  #
  # +type+ is one of the following:
  #
  # :released   => Return the list of all released specs
  # :latest     => Return the list of only the highest version of each gem
  # :prerelease => Return the list of all prerelease only specs
  #

  def load_specs(type)
    file       = FILES[type]
    fetcher    = Gem::RemoteFetcher.fetcher
    file_name  = "#{file}.#{Gem.marshal_version}"
    spec_path  = enforce_trailing_slash(uri) + "#{file_name}.gz"
    cache_dir  = cache_dir spec_path
    local_file = File.join(cache_dir, file_name)
    retried    = false

    if update_cache?
      require "fileutils"
      FileUtils.mkdir_p cache_dir
    end

    spec_dump = fetcher.cache_update_path spec_path, local_file, update_cache?

    begin
      Gem::NameTuple.from_list Marshal.load(spec_dump)
    rescue ArgumentError
      if update_cache? && !retried
        FileUtils.rm local_file
        retried = true
        retry
      else
        raise Gem::Exception.new("Invalid spec cache file in #{local_file}")
      end
    end
  end

  ##
  # Downloads +spec+ and writes it to +dir+.  See also
  # Gem::RemoteFetcher#download.

  def download(spec, dir=Dir.pwd)
    fetcher = Gem::RemoteFetcher.fetcher
    fetcher.download spec, uri.to_s, dir
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[Remote:', ']' do
      q.breakable
      q.text @uri.to_s

      if api = uri
        q.breakable
        q.text 'API URI: '
        q.text api.to_s
      end
    end
  end

  def typo_squatting?(host, distance_threshold=4)
    return if @uri.host.nil?
    levenshtein_distance(@uri.host, host).between? 1, distance_threshold
  end

  private

  def enforce_trailing_slash(uri)
    uri.merge(uri.path.gsub(/\/+$/, '') + '/')
  end
end

require_relative 'source/git'
require_relative 'source/installed'
require_relative 'source/specific_file'
require_relative 'source/local'
require_relative 'source/lock'
require_relative 'source/vendor'
# frozen_string_literal: true

##
# Helper methods for both Gem::Installer and Gem::Uninstaller

module Gem::InstallerUninstallerUtils

  def regenerate_plugins_for(spec, plugins_dir)
    plugins = spec.plugins
    return if plugins.empty?

    require 'pathname'

    spec.plugins.each do |plugin|
      plugin_script_path = File.join plugins_dir, "#{spec.name}_plugin#{File.extname(plugin)}"

      File.open plugin_script_path, 'wb' do |file|
        file.puts "require_relative '#{Pathname.new(plugin).relative_path_from(Pathname.new(plugins_dir))}'"
      end

      verbose plugin_script_path
    end
  end

  def remove_plugins_for(spec, plugins_dir)
    FileUtils.rm_f Gem::Util.glob_files_in_dir("#{spec.name}#{Gem.plugin_suffix_pattern}", plugins_dir)
  end

end
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

##
# Classes for building C extensions live here.

module Gem::Ext; end

require_relative 'ext/build_error'
require_relative 'ext/builder'
require_relative 'ext/configure_builder'
require_relative 'ext/ext_conf_builder'
require_relative 'ext/rake_builder'
require_relative 'ext/cmake_builder'
# frozen_string_literal: true
class Gem::AvailableSet
  include Enumerable

  Tuple = Struct.new(:spec, :source)

  attr_accessor :remote # :nodoc:

  def initialize
    @set = []
    @sorted = nil
    @remote = true
  end

  attr_reader :set

  def add(spec, source)
    @set << Tuple.new(spec, source)
    @sorted = nil
    self
  end

  def <<(o)
    case o
    when Gem::AvailableSet
      s = o.set
    when Array
      s = o.map do |sp,so|
        if !sp.kind_of?(Gem::Specification) or !so.kind_of?(Gem::Source)
          raise TypeError, "Array must be in [[spec, source], ...] form"
        end

        Tuple.new(sp,so)
      end
    else
      raise TypeError, "must be a Gem::AvailableSet"
    end

    @set += s
    @sorted = nil

    self
  end

  ##
  # Yields each Tuple in this AvailableSet

  def each
    return enum_for __method__ unless block_given?

    @set.each do |tuple|
      yield tuple
    end
  end

  ##
  # Yields the Gem::Specification for each Tuple in this AvailableSet

  def each_spec
    return enum_for __method__ unless block_given?

    each do |tuple|
      yield tuple.spec
    end
  end

  def empty?
    @set.empty?
  end

  def all_specs
    @set.map {|t| t.spec }
  end

  def match_platform!
    @set.reject! {|t| !Gem::Platform.match_spec?(t.spec) }
    @sorted = nil
    self
  end

  def sorted
    @sorted ||= @set.sort do |a,b|
      i = b.spec <=> a.spec
      i != 0 ? i : (a.source <=> b.source)
    end
  end

  def size
    @set.size
  end

  def source_for(spec)
    f = @set.find {|t| t.spec == spec }
    f.source
  end

  ##
  # Converts this AvailableSet into a RequestSet that can be used to install
  # gems.
  #
  # If +development+ is :none then no development dependencies are installed.
  # Other options are :shallow for only direct development dependencies of the
  # gems in this set or :all for all development dependencies.

  def to_request_set(development = :none)
    request_set = Gem::RequestSet.new
    request_set.development = :all == development

    each_spec do |spec|
      request_set.always_install << spec

      request_set.gem spec.name, spec.version
      request_set.import spec.development_dependencies if
        :shallow == development
    end

    request_set
  end

  ##
  #
  # Used by the Resolver, the protocol to use a AvailableSet as a
  # search Set.

  def find_all(req)
    dep = req.dependency

    match = @set.find_all do |t|
      dep.match? t.spec
    end

    match.map do |t|
      Gem::Resolver::LocalSpecification.new(self, t.spec, t.source)
    end
  end

  def prefetch(reqs)
  end

  def pick_best!
    return self if empty?

    @set = [sorted.first]
    @sorted = nil
    self
  end

  def remove_installed!(dep)
    @set.reject! do |t|
      # already locally installed
      Gem::Specification.any? do |installed_spec|
        dep.name == installed_spec.name and
          dep.requirement.satisfied_by? installed_spec.version
      end
    end

    @sorted = nil
    self
  end

  def inject_into_list(dep_list)
    @set.each {|t| dep_list.add t.spec }
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../package'
require_relative '../installer'
require_relative '../version_option'

class Gem::Commands::PristineCommand < Gem::Command
  include Gem::VersionOption

  def initialize
    super 'pristine',
          'Restores installed gems to pristine condition from files located in the gem cache',
          :version => Gem::Requirement.default,
          :extensions => true,
          :extensions_set => false,
          :all => false

    add_option('--all',
               'Restore all installed gems to pristine',
               'condition') do |value, options|
      options[:all] = value
    end

    add_option('--skip=gem_name',
               'used on --all, skip if name == gem_name') do |value, options|
      options[:skip] ||= []
      options[:skip] << value
    end

    add_option('--[no-]extensions',
               'Restore gems with extensions',
               'in addition to regular gems') do |value, options|
      options[:extensions_set] = true
      options[:extensions]     = value
    end

    add_option('--only-executables',
               'Only restore executables') do |value, options|
      options[:only_executables] = value
    end

    add_option('--only-plugins',
               'Only restore plugins') do |value, options|
      options[:only_plugins] = value
    end

    add_option('-E', '--[no-]env-shebang',
               'Rewrite executables with a shebang',
               'of /usr/bin/env') do |value, options|
      options[:env_shebang] = value
    end

    add_option('-i', '--install-dir DIR',
               'Gem repository to get binstubs and plugins installed') do |value, options|
      options[:install_dir] = File.expand_path(value)
    end

    add_option('-n', '--bindir DIR',
               'Directory where executables are',
               'located') do |value, options|
      options[:bin_dir] = File.expand_path(value)
    end

    add_version_option('restore to', 'pristine condition')
  end

  def arguments # :nodoc:
    "GEMNAME       gem to restore to pristine condition (unless --all)"
  end

  def defaults_str # :nodoc:
    '--extensions'
  end

  def description # :nodoc:
    <<-EOF
The pristine command compares an installed gem with the contents of its
cached .gem file and restores any files that don't match the cached .gem's
copy.

If you have made modifications to an installed gem, the pristine command
will revert them.  All extensions are rebuilt and all bin stubs for the gem
are regenerated after checking for modifications.

If the cached gem cannot be found it will be downloaded.

If --no-extensions is provided pristine will not attempt to restore a gem
with an extension.

If --extensions is given (but not --all or gem names) only gems with
extensions will be restored.
    EOF
  end

  def usage # :nodoc:
    "#{program_name} [GEMNAME ...]"
  end

  def execute
    specs = if options[:all]
              Gem::Specification.map

            # `--extensions` must be explicitly given to pristine only gems
            # with extensions.
            elsif options[:extensions_set] and
                  options[:extensions] and options[:args].empty?
              Gem::Specification.select do |spec|
                spec.extensions and not spec.extensions.empty?
              end
            else
              get_all_gem_names.sort.map do |gem_name|
                Gem::Specification.find_all_by_name(gem_name, options[:version]).reverse
              end.flatten
            end

    specs = specs.select{|spec| RUBY_ENGINE == spec.platform || Gem::Platform.local === spec.platform || spec.platform == Gem::Platform::RUBY }

    if specs.to_a.empty?
      raise Gem::Exception,
            "Failed to find gems #{options[:args]} #{options[:version]}"
    end

    say "Restoring gems to pristine condition..."

    specs.each do |spec|
      if spec.default_gem?
        say "Skipped #{spec.full_name}, it is a default gem"
        next
      end

      if options.has_key? :skip
        if options[:skip].include? spec.name
          say "Skipped #{spec.full_name}, it was given through options"
          next
        end
      end

      unless spec.extensions.empty? or options[:extensions] or options[:only_executables] or options[:only_plugins]
        say "Skipped #{spec.full_name}, it needs to compile an extension"
        next
      end

      gem = spec.cache_file

      unless File.exist? gem or options[:only_executables] or options[:only_plugins]
        require_relative '../remote_fetcher'

        say "Cached gem for #{spec.full_name} not found, attempting to fetch..."

        dep = Gem::Dependency.new spec.name, spec.version
        found, _ = Gem::SpecFetcher.fetcher.spec_for_dependency dep

        if found.empty?
          say "Skipped #{spec.full_name}, it was not found from cache and remote sources"
          next
        end

        spec_candidate, source = found.first
        Gem::RemoteFetcher.fetcher.download spec_candidate, source.uri.to_s, spec.base_dir
      end

      env_shebang =
        if options.include? :env_shebang
          options[:env_shebang]
        else
          install_defaults = Gem::ConfigFile::PLATFORM_DEFAULTS['install']
          install_defaults.to_s['--env-shebang']
        end

      bin_dir = options[:bin_dir] if options[:bin_dir]
      install_dir = options[:install_dir] if options[:install_dir]

      installer_options = {
        :wrappers => true,
        :force => true,
        :install_dir => install_dir || spec.base_dir,
        :env_shebang => env_shebang,
        :build_args => spec.build_args,
        :bin_dir => bin_dir,
      }

      if options[:only_executables]
        installer = Gem::Installer.for_spec(spec, installer_options)
        installer.generate_bin
      elsif options[:only_plugins]
        installer = Gem::Installer.for_spec(spec, installer_options)
        installer.generate_plugins
      else
        installer = Gem::Installer.at(gem, installer_options)
        installer.install
      end

      say "Restored #{spec.full_name}"
    end
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../indexer'

##
# Generates a index files for use as a gem server.
#
# See `gem help generate_index`

class Gem::Commands::GenerateIndexCommand < Gem::Command
  def initialize
    super 'generate_index',
          'Generates the index files for a gem server directory',
          :directory => '.', :build_modern => true

    add_option '-d', '--directory=DIRNAME',
               'repository base dir containing gems subdir' do |dir, options|
      options[:directory] = File.expand_path dir
    end

    add_option '--[no-]modern',
               'Generate indexes for RubyGems',
               '(always true)' do |value, options|
      options[:build_modern] = value
    end

    deprecate_option('--modern', version: '4.0', extra_msg: 'Modern indexes (specs, latest_specs, and prerelease_specs) are always generated, so this option is not needed.')
    deprecate_option('--no-modern', version: '4.0', extra_msg: 'The `--no-modern` option is currently ignored. Modern indexes (specs, latest_specs, and prerelease_specs) are always generated.')

    add_option '--update',
               'Update modern indexes with gems added',
               'since the last update' do |value, options|
      options[:update] = value
    end
  end

  def defaults_str # :nodoc:
    "--directory . --modern"
  end

  def description # :nodoc:
    <<-EOF
The generate_index command creates a set of indexes for serving gems
statically.  The command expects a 'gems' directory under the path given to
the --directory option.  The given directory will be the directory you serve
as the gem repository.

For `gem generate_index --directory /path/to/repo`, expose /path/to/repo via
your HTTP server configuration (not /path/to/repo/gems).

When done, it will generate a set of files like this:

  gems/*.gem                                   # .gem files you want to
                                               # index

  specs.<version>.gz                           # specs index
  latest_specs.<version>.gz                    # latest specs index
  prerelease_specs.<version>.gz                # prerelease specs index
  quick/Marshal.<version>/<gemname>.gemspec.rz # Marshal quick index file

The .rz extension files are compressed with the inflate algorithm.
The Marshal version number comes from ruby's Marshal::MAJOR_VERSION and
Marshal::MINOR_VERSION constants.  It is used to ensure compatibility.
    EOF
  end

  def execute
    # This is always true because it's the only way now.
    options[:build_modern] = true

    if not File.exist?(options[:directory]) or
       not File.directory?(options[:directory])
      alert_error "unknown directory name #{options[:directory]}."
      terminate_interaction 1
    else
      indexer = Gem::Indexer.new options.delete(:directory), options

      if options[:update]
        indexer.update_index
      else
        indexer.generate_index
      end
    end
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../version_option'

class Gem::Commands::ContentsCommand < Gem::Command
  include Gem::VersionOption

  def initialize
    super 'contents', 'Display the contents of the installed gems',
          :specdirs => [], :lib_only => false, :prefix => true,
          :show_install_dir => false

    add_version_option

    add_option('--all',
               "Contents for all gems") do |all, options|
      options[:all] = all
    end

    add_option('-s', '--spec-dir a,b,c', Array,
               "Search for gems under specific paths") do |spec_dirs, options|
      options[:specdirs] = spec_dirs
    end

    add_option('-l', '--[no-]lib-only',
               "Only return files in the Gem's lib_dirs") do |lib_only, options|
      options[:lib_only] = lib_only
    end

    add_option('--[no-]prefix',
               "Don't include installed path prefix") do |prefix, options|
      options[:prefix] = prefix
    end

    add_option('--[no-]show-install-dir',
               'Show only the gem install dir') do |show, options|
      options[:show_install_dir] = show
    end

    @path_kind = nil
    @spec_dirs = nil
    @version   = nil
  end

  def arguments # :nodoc:
    "GEMNAME       name of gem to list contents for"
  end

  def defaults_str # :nodoc:
    "--no-lib-only --prefix"
  end

  def description # :nodoc:
    <<-EOF
The contents command lists the files in an installed gem.  The listing can
be given as full file names, file names without the installed directory
prefix or only the files that are requireable.
    EOF
  end

  def usage # :nodoc:
    "#{program_name} GEMNAME [GEMNAME ...]"
  end

  def execute
    @version   = options[:version] || Gem::Requirement.default
    @spec_dirs = specification_directories
    @path_kind = path_description @spec_dirs

    names = gem_names

    names.each do |name|
      found =
        if options[:show_install_dir]
          gem_install_dir name
        else
          gem_contents name
        end

      terminate_interaction 1 unless found or names.length > 1
    end
  end

  def files_in(spec)
    if spec.default_gem?
      files_in_default_gem spec
    else
      files_in_gem spec
    end
  end

  def files_in_gem(spec)
    gem_path  = spec.full_gem_path
    extra     = "/{#{spec.require_paths.join ','}}" if options[:lib_only]
    glob      = "#{gem_path}#{extra}/**/*"
    prefix_re = /#{Regexp.escape(gem_path)}\//

    Dir[glob].map do |file|
      [gem_path, file.sub(prefix_re, "")]
    end
  end

  def files_in_default_gem(spec)
    spec.files.map do |file|
      case file
      when /\A#{spec.bindir}\//
        # $' is POSTMATCH
        [RbConfig::CONFIG['bindir'], $']
      when /\.so\z/
        [RbConfig::CONFIG['archdir'], file]
      else
        [RbConfig::CONFIG['rubylibdir'], file]
      end
    end
  end

  def gem_contents(name)
    spec = spec_for name

    return false unless spec

    files = files_in spec

    show_files files

    true
  end

  def gem_install_dir(name)
    spec = spec_for name

    return false unless spec

    say spec.gem_dir

    true
  end

  def gem_names # :nodoc:
    if options[:all]
      Gem::Specification.map(&:name)
    else
      get_all_gem_names
    end
  end

  def path_description(spec_dirs) # :nodoc:
    if spec_dirs.empty?
      "default gem paths"
    else
      "specified path"
    end
  end

  def show_files(files)
    files.sort.each do |prefix, basename|
      absolute_path = File.join(prefix, basename)
      next if File.directory? absolute_path

      if options[:prefix]
        say absolute_path
      else
        say basename
      end
    end
  end

  def spec_for(name)
    spec = Gem::Specification.find_all_by_name(name, @version).first

    return spec if spec

    say "Unable to find gem '#{name}' in #{@path_kind}"

    if Gem.configuration.verbose
      say "\nDirectories searched:"
      @spec_dirs.sort.each {|dir| say dir }
    end

    return nil
  end

  def specification_directories # :nodoc:
    options[:specdirs].map do |i|
      [i, File.join(i, "specifications")]
    end.flatten
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../local_remote_options'
require_relative '../version_option'
require_relative '../package'

class Gem::Commands::SpecificationCommand < Gem::Command
  include Gem::LocalRemoteOptions
  include Gem::VersionOption

  def initialize
    Gem.load_yaml

    super 'specification', 'Display gem specification (in yaml)',
          :domain => :local, :version => Gem::Requirement.default,
          :format => :yaml

    add_version_option('examine')
    add_platform_option
    add_prerelease_option

    add_option('--all', 'Output specifications for all versions of',
               'the gem') do |value, options|
      options[:all] = true
    end

    add_option('--ruby', 'Output ruby format') do |value, options|
      options[:format] = :ruby
    end

    add_option('--yaml', 'Output YAML format') do |value, options|
      options[:format] = :yaml
    end

    add_option('--marshal', 'Output Marshal format') do |value, options|
      options[:format] = :marshal
    end

    add_local_remote_options
  end

  def arguments # :nodoc:
    <<-ARGS
GEMFILE       name of gem to show the gemspec for
FIELD         name of gemspec field to show
    ARGS
  end

  def defaults_str # :nodoc:
    "--local --version '#{Gem::Requirement.default}' --yaml"
  end

  def description # :nodoc:
    <<-EOF
The specification command allows you to extract the specification from
a gem for examination.

The specification can be output in YAML, ruby or Marshal formats.

Specific fields in the specification can be extracted in YAML format:

  $ gem spec rake summary
  --- Ruby based make-like utility.
  ...

    EOF
  end

  def usage # :nodoc:
    "#{program_name} [GEMFILE] [FIELD]"
  end

  def execute
    specs = []
    gem = options[:args].shift

    unless gem
      raise Gem::CommandLineError,
            "Please specify a gem name or file on the command line"
    end

    case v = options[:version]
    when String
      req = Gem::Requirement.create v
    when Gem::Requirement
      req = v
    else
      raise Gem::CommandLineError, "Unsupported version type: '#{v}'"
    end

    if !req.none? and options[:all]
      alert_error "Specify --all or -v, not both"
      terminate_interaction 1
    end

    if options[:all]
      dep = Gem::Dependency.new gem
    else
      dep = Gem::Dependency.new gem, req
    end

    field = get_one_optional_argument

    raise Gem::CommandLineError, "--ruby and FIELD are mutually exclusive" if
      field and options[:format] == :ruby

    if local?
      if File.exist? gem
        specs << Gem::Package.new(gem).spec rescue nil
      end

      if specs.empty?
        specs.push(*dep.matching_specs)
      end
    end

    if remote?
      dep.prerelease = options[:prerelease]
      found, _ = Gem::SpecFetcher.fetcher.spec_for_dependency dep

      specs.push(*found.map {|spec,| spec })
    end

    if specs.empty?
      alert_error "No gem matching '#{dep}' found"
      terminate_interaction 1
    end

    platform = get_platform_from_requirements(options)

    if platform
      specs = specs.select{|s| s.platform.to_s == platform }
    end

    unless options[:all]
      specs = [specs.max_by {|s| s.version }]
    end

    specs.each do |s|
      s = s.send field if field

      say case options[:format]
          when :ruby then s.to_ruby
          when :marshal then Marshal.dump s
          else s.to_yaml
          end

      say "\n"
    end
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../local_remote_options'
require_relative '../version_option'

class Gem::Commands::DependencyCommand < Gem::Command
  include Gem::LocalRemoteOptions
  include Gem::VersionOption

  def initialize
    super 'dependency',
          'Show the dependencies of an installed gem',
          :version => Gem::Requirement.default, :domain => :local

    add_version_option
    add_platform_option
    add_prerelease_option

    add_option('-R', '--[no-]reverse-dependencies',
               'Include reverse dependencies in the output') do
      |value, options|
      options[:reverse_dependencies] = value
    end

    add_option('-p', '--pipe',
               "Pipe Format (name --version ver)") do |value, options|
      options[:pipe_format] = value
    end

    add_local_remote_options
  end

  def arguments # :nodoc:
    "REGEXP        show dependencies for gems whose names start with REGEXP"
  end

  def defaults_str # :nodoc:
    "--local --version '#{Gem::Requirement.default}' --no-reverse-dependencies"
  end

  def description # :nodoc:
    <<-EOF
The dependency commands lists which other gems a given gem depends on.  For
local gems only the reverse dependencies can be shown (which gems depend on
the named gem).

The dependency list can be displayed in a format suitable for piping for
use with other commands.
    EOF
  end

  def usage # :nodoc:
    "#{program_name} REGEXP"
  end

  def fetch_remote_specs(dependency) # :nodoc:
    fetcher = Gem::SpecFetcher.fetcher

    ss, = fetcher.spec_for_dependency dependency

    ss.map {|spec, _| spec }
  end

  def fetch_specs(name_pattern, dependency) # :nodoc:
    specs = []

    if local?
      specs.concat Gem::Specification.stubs.find_all {|spec|
        name_pattern =~ spec.name and
          dependency.requirement.satisfied_by? spec.version
      }.map(&:to_spec)
    end

    specs.concat fetch_remote_specs dependency if remote?

    ensure_specs specs

    specs.uniq.sort
  end

  def gem_dependency(pattern, version, prerelease) # :nodoc:
    dependency = Gem::Deprecate.skip_during do
      Gem::Dependency.new pattern, version
    end

    dependency.prerelease = prerelease

    dependency
  end

  def display_pipe(specs) # :nodoc:
    specs.each do |spec|
      unless spec.dependencies.empty?
        spec.dependencies.sort_by {|dep| dep.name }.each do |dep|
          say "#{dep.name} --version '#{dep.requirement}'"
        end
      end
    end
  end

  def display_readable(specs, reverse) # :nodoc:
    response = String.new

    specs.each do |spec|
      response << print_dependencies(spec)
      unless reverse[spec.full_name].empty?
        response << "  Used by\n"
        reverse[spec.full_name].each do |sp, dep|
          response << "    #{sp} (#{dep})\n"
        end
      end
      response << "\n"
    end

    say response
  end

  def execute
    ensure_local_only_reverse_dependencies

    pattern = name_pattern options[:args]

    dependency =
      gem_dependency pattern, options[:version], options[:prerelease]

    specs = fetch_specs pattern, dependency

    reverse = reverse_dependencies specs

    if options[:pipe_format]
      display_pipe specs
    else
      display_readable specs, reverse
    end
  end

  def ensure_local_only_reverse_dependencies # :nodoc:
    if options[:reverse_dependencies] and remote? and not local?
      alert_error 'Only reverse dependencies for local gems are supported.'
      terminate_interaction 1
    end
  end

  def ensure_specs(specs) # :nodoc:
    return unless specs.empty?

    patterns = options[:args].join ','
    say "No gems found matching #{patterns} (#{options[:version]})" if
      Gem.configuration.verbose

    terminate_interaction 1
  end

  def print_dependencies(spec, level = 0) # :nodoc:
    response = String.new
    response << '  ' * level + "Gem #{spec.full_name}\n"
    unless spec.dependencies.empty?
      spec.dependencies.sort_by {|dep| dep.name }.each do |dep|
        response << '  ' * level + "  #{dep}\n"
      end
    end
    response
  end

  def remote_specs(dependency) # :nodoc:
    fetcher = Gem::SpecFetcher.fetcher

    ss, _ = fetcher.spec_for_dependency dependency

    ss.map {|s,o| s }
  end

  def reverse_dependencies(specs) # :nodoc:
    reverse = Hash.new {|h, k| h[k] = [] }

    return reverse unless options[:reverse_dependencies]

    specs.each do |spec|
      reverse[spec.full_name] = find_reverse_dependencies spec
    end

    reverse
  end

  ##
  # Returns an Array of [specification, dep] that are satisfied by +spec+.

  def find_reverse_dependencies(spec) # :nodoc:
    result = []

    Gem::Specification.each do |sp|
      sp.dependencies.each do |dep|
        dep = Gem::Dependency.new(*dep) unless Gem::Dependency === dep

        if spec.name == dep.name and
           dep.requirement.satisfied_by?(spec.version)
          result << [sp.full_name, dep]
        end
      end
    end

    result
  end

  private

  def name_pattern(args)
    args << '' if args.empty?

    if args.length == 1 and args.first =~ /\A(.*)(i)?\z/m
      flags = $2 ? Regexp::IGNORECASE : nil
      Regexp.new $1, flags
    else
      /\A#{Regexp.union(*args)}/
    end
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../remote_fetcher'
require_relative '../spec_fetcher'
require_relative '../local_remote_options'

class Gem::Commands::SourcesCommand < Gem::Command
  include Gem::LocalRemoteOptions

  def initialize
    require 'fileutils'

    super 'sources',
          'Manage the sources and cache file RubyGems uses to search for gems'

    add_option '-a', '--add SOURCE_URI', 'Add source' do |value, options|
      options[:add] = value
    end

    add_option '-l', '--list', 'List sources' do |value, options|
      options[:list] = value
    end

    add_option '-r', '--remove SOURCE_URI', 'Remove source' do |value, options|
      options[:remove] = value
    end

    add_option '-c', '--clear-all',
               'Remove all sources (clear the cache)' do |value, options|
      options[:clear_all] = value
    end

    add_option '-u', '--update', 'Update source cache' do |value, options|
      options[:update] = value
    end

    add_option '-f', '--[no-]force', "Do not show any confirmation prompts and behave as if 'yes' was always answered" do |value, options|
      options[:force] = value
    end

    add_proxy_option
  end

  def add_source(source_uri) # :nodoc:
    check_rubygems_https source_uri

    source = Gem::Source.new source_uri

    check_typo_squatting(source)

    begin
      if Gem.sources.include? source
        say "source #{source_uri} already present in the cache"
      else
        source.load_specs :released
        Gem.sources << source
        Gem.configuration.write

        say "#{source_uri} added to sources"
      end
    rescue URI::Error, ArgumentError
      say "#{source_uri} is not a URI"
      terminate_interaction 1
    rescue Gem::RemoteFetcher::FetchError => e
      say "Error fetching #{source_uri}:\n\t#{e.message}"
      terminate_interaction 1
    end
  end

  def check_typo_squatting(source)
    if source.typo_squatting?("rubygems.org")
      question = <<-QUESTION.chomp
#{source.uri.to_s} is too similar to https://rubygems.org

Do you want to add this source?
      QUESTION

      terminate_interaction 1 unless options[:force] || ask_yes_no(question)
    end
  end

  def check_rubygems_https(source_uri) # :nodoc:
    uri = URI source_uri

    if uri.scheme and uri.scheme.downcase == 'http' and
       uri.host.downcase == 'rubygems.org'
      question = <<-QUESTION.chomp
https://rubygems.org is recommended for security over #{uri}

Do you want to add this insecure source?
      QUESTION

      terminate_interaction 1 unless options[:force] || ask_yes_no(question)
    end
  end

  def clear_all # :nodoc:
    path = Gem.spec_cache_dir
    FileUtils.rm_rf path

    unless File.exist? path
      say "*** Removed specs cache ***"
    else
      unless File.writable? path
        say "*** Unable to remove source cache (write protected) ***"
      else
        say "*** Unable to remove source cache ***"
      end

      terminate_interaction 1
    end
  end

  def defaults_str # :nodoc:
    '--list'
  end

  def description # :nodoc:
    <<-EOF
RubyGems fetches gems from the sources you have configured (stored in your
~/.gemrc).

The default source is https://rubygems.org, but you may have other sources
configured.  This guide will help you update your sources or configure
yourself to use your own gem server.

Without any arguments the sources lists your currently configured sources:

  $ gem sources
  *** CURRENT SOURCES ***

  https://rubygems.org

This may list multiple sources or non-rubygems sources.  You probably
configured them before or have an old `~/.gemrc`.  If you have sources you
do not recognize you should remove them.

RubyGems has been configured to serve gems via the following URLs through
its history:

* http://gems.rubyforge.org (RubyGems 1.3.6 and earlier)
* https://rubygems.org/       (RubyGems 1.3.7 through 1.8.25)
* https://rubygems.org      (RubyGems 2.0.1 and newer)

Since all of these sources point to the same set of gems you only need one
of them in your list.  https://rubygems.org is recommended as it brings the
protections of an SSL connection to gem downloads.

To add a source use the --add argument:

    $ gem sources --add https://rubygems.org
    https://rubygems.org added to sources

RubyGems will check to see if gems can be installed from the source given
before it is added.

To remove a source use the --remove argument:

    $ gem sources --remove https://rubygems.org/
    https://rubygems.org/ removed from sources

    EOF
  end

  def list # :nodoc:
    say "*** CURRENT SOURCES ***"
    say

    Gem.sources.each do |src|
      say src
    end
  end

  def list? # :nodoc:
    !(options[:add] ||
      options[:clear_all] ||
      options[:remove] ||
      options[:update])
  end

  def execute
    clear_all if options[:clear_all]

    source_uri = options[:add]
    add_source source_uri if source_uri

    source_uri = options[:remove]
    remove_source source_uri if source_uri

    update if options[:update]

    list if list?
  end

  def remove_source(source_uri) # :nodoc:
    unless Gem.sources.include? source_uri
      say "source #{source_uri} not present in cache"
    else
      Gem.sources.delete source_uri
      Gem.configuration.write

      say "#{source_uri} removed from sources"
    end
  end

  def update # :nodoc:
    Gem.sources.each_source do |src|
      src.load_specs :released
      src.load_specs :latest
    end

    say "source cache successfully updated"
  end

  def remove_cache_file(desc, path) # :nodoc:
    FileUtils.rm_rf path

    if not File.exist?(path)
      say "*** Removed #{desc} source cache ***"
    elsif not File.writable?(path)
      say "*** Unable to remove #{desc} source cache (write protected) ***"
    else
      say "*** Unable to remove #{desc} source cache ***"
    end
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../dependency_list'
require_relative '../uninstaller'

class Gem::Commands::CleanupCommand < Gem::Command
  def initialize
    super 'cleanup',
          'Clean up old versions of installed gems',
          :force => false, :install_dir => Gem.dir,
          :check_dev => true

    add_option('-n', '-d', '--dry-run',
               'Do not uninstall gems') do |value, options|
      options[:dryrun] = true
    end

    add_option(:Deprecated, '--dryrun',
               'Do not uninstall gems') do |value, options|
      options[:dryrun] = true
    end
    deprecate_option('--dryrun', extra_msg: 'Use --dry-run instead')

    add_option('-D', '--[no-]check-development',
               'Check development dependencies while uninstalling',
               '(default: true)') do |value, options|
      options[:check_dev] = value
    end

    add_option('--[no-]user-install',
               'Cleanup in user\'s home directory instead',
               'of GEM_HOME.') do |value, options|
      options[:user_install] = value
    end

    @candidate_gems  = nil
    @default_gems    = []
    @full            = nil
    @gems_to_cleanup = nil
    @original_home   = nil
    @original_path   = nil
    @primary_gems    = nil
  end

  def arguments # :nodoc:
    "GEMNAME       name of gem to cleanup"
  end

  def defaults_str # :nodoc:
    "--no-dry-run"
  end

  def description # :nodoc:
    <<-EOF
The cleanup command removes old versions of gems from GEM_HOME that are not
required to meet a dependency.  If a gem is installed elsewhere in GEM_PATH
the cleanup command won't delete it.

If no gems are named all gems in GEM_HOME are cleaned.
    EOF
  end

  def usage # :nodoc:
    "#{program_name} [GEMNAME ...]"
  end

  def execute
    say "Cleaning up installed gems..."

    if options[:args].empty?
      done     = false
      last_set = nil

      until done do
        clean_gems

        this_set = @gems_to_cleanup.map {|spec| spec.full_name }.sort

        done = this_set.empty? || last_set == this_set

        last_set = this_set
      end
    else
      clean_gems
    end

    say "Clean up complete"

    verbose do
      skipped = @default_gems.map {|spec| spec.full_name }

      "Skipped default gems: #{skipped.join ', '}"
    end
  end

  def clean_gems
    @original_home = Gem.dir
    @original_path = Gem.path

    get_primary_gems
    get_candidate_gems
    get_gems_to_cleanup

    @full = Gem::DependencyList.from_specs

    deplist = Gem::DependencyList.new
    @gems_to_cleanup.each {|spec| deplist.add spec }

    deps = deplist.strongly_connected_components.flatten

    deps.reverse_each do |spec|
      uninstall_dep spec
    end

    Gem::Specification.reset
  end

  def get_candidate_gems
    @candidate_gems = unless options[:args].empty?
                        options[:args].map do |gem_name|
                          Gem::Specification.find_all_by_name gem_name
                        end.flatten
                      else
                        Gem::Specification.to_a
                      end
  end

  def get_gems_to_cleanup
    gems_to_cleanup = @candidate_gems.select do |spec|
      @primary_gems[spec.name].version != spec.version
    end

    default_gems, gems_to_cleanup = gems_to_cleanup.partition do |spec|
      spec.default_gem?
    end

    uninstall_from = options[:user_install] ? Gem.user_dir : @original_home

    gems_to_cleanup = gems_to_cleanup.select do |spec|
      spec.base_dir == uninstall_from
    end

    @default_gems += default_gems
    @default_gems.uniq!
    @gems_to_cleanup = gems_to_cleanup.uniq
  end

  def get_primary_gems
    @primary_gems = {}

    Gem::Specification.each do |spec|
      if @primary_gems[spec.name].nil? or
         @primary_gems[spec.name].version < spec.version
        @primary_gems[spec.name] = spec
      end
    end
  end

  def uninstall_dep(spec)
    return unless @full.ok_to_remove?(spec.full_name, options[:check_dev])

    if options[:dryrun]
      say "Dry Run Mode: Would uninstall #{spec.full_name}"
      return
    end

    say "Attempting to uninstall #{spec.full_name}"

    uninstall_options = {
      :executables => false,
      :version => "= #{spec.version}",
    }

    uninstall_options[:user_install] = Gem.user_dir == spec.base_dir

    uninstaller = Gem::Uninstaller.new spec.name, uninstall_options

    begin
      uninstaller.uninstall
    rescue Gem::DependencyRemovalException, Gem::InstallError,
           Gem::GemNotInHomeException, Gem::FilePermissionError => e
      say "Unable to uninstall #{spec.full_name}:"
      say "\t#{e.class}: #{e.message}"
    end
  ensure
    # Restore path Gem::Uninstaller may have changed
    Gem.use_paths @original_home, *@original_path
  end
end
# frozen_string_literal: true

require_relative '../command'
require_relative '../query_utils'

class Gem::Commands::InfoCommand < Gem::Command
  include Gem::QueryUtils

  def initialize
    super "info", "Show information for the given gem",
         :name => //, :domain => :local, :details => false, :versions => true,
         :installed => nil, :version => Gem::Requirement.default

    add_query_options

    remove_option('-d')

    defaults[:details] = true
    defaults[:exact] = true
  end

  def description # :nodoc:
    "Info prints information about the gem such as name,"\
    " description, website, license and installed paths"
  end

  def usage # :nodoc:
    "#{program_name} GEMNAME"
  end

  def arguments # :nodoc:
    "GEMNAME        name of the gem to print information about"
  end

  def defaults_str
    "--local"
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../version_option'
require_relative '../security_option'
require_relative '../remote_fetcher'
require_relative '../package'

# forward-declare

module Gem::Security # :nodoc:
  class Policy # :nodoc:
  end
end

class Gem::Commands::UnpackCommand < Gem::Command
  include Gem::VersionOption
  include Gem::SecurityOption

  def initialize
    require 'fileutils'

    super 'unpack', 'Unpack an installed gem to the current directory',
          :version => Gem::Requirement.default,
          :target  => Dir.pwd

    add_option('--target=DIR',
               'target directory for unpacking') do |value, options|
      options[:target] = value
    end

    add_option('--spec', 'unpack the gem specification') do |value, options|
      options[:spec] = true
    end

    add_security_option
    add_version_option
  end

  def arguments # :nodoc:
    "GEMNAME       name of gem to unpack"
  end

  def defaults_str # :nodoc:
    "--version '#{Gem::Requirement.default}'"
  end

  def description
    <<-EOF
The unpack command allows you to examine the contents of a gem or modify
them to help diagnose a bug.

You can add the contents of the unpacked gem to the load path using the
RUBYLIB environment variable or -I:

  $ gem unpack my_gem
  Unpacked gem: '.../my_gem-1.0'
  [edit my_gem-1.0/lib/my_gem.rb]
  $ ruby -Imy_gem-1.0/lib -S other_program

You can repackage an unpacked gem using the build command.  See the build
command help for an example.
    EOF
  end

  def usage # :nodoc:
    "#{program_name} GEMNAME"
  end

  #--
  # TODO: allow, e.g., 'gem unpack rake-0.3.1'.  Find a general solution for
  # this, so that it works for uninstall as well.  (And check other commands
  # at the same time.)

  def execute
    security_policy = options[:security_policy]

    get_all_gem_names.each do |name|
      dependency = Gem::Dependency.new name, options[:version]
      path = get_path dependency

      unless path
        alert_error "Gem '#{name}' not installed nor fetchable."
        next
      end

      if @options[:spec]
        spec, metadata = Gem::Package.raw_spec(path, security_policy)

        if metadata.nil?
          alert_error "--spec is unsupported on '#{name}' (old format gem)"
          next
        end

        spec_file = File.basename spec.spec_file

        FileUtils.mkdir_p @options[:target] if @options[:target]

        destination = begin
          if @options[:target]
            File.join @options[:target], spec_file
          else
            spec_file
          end
        end

        File.open destination, 'w' do |io|
          io.write metadata
        end
      else
        basename = File.basename path, '.gem'
        target_dir = File.expand_path basename, options[:target]

        package = Gem::Package.new path, security_policy
        package.extract_files target_dir

        say "Unpacked gem: '#{target_dir}'"
      end
    end
  end

  ##
  #
  # Find cached filename in Gem.path. Returns nil if the file cannot be found.
  #
  #--
  # TODO: see comments in get_path() about general service.

  def find_in_cache(filename)
    Gem.path.each do |path|
      this_path = File.join(path, "cache", filename)
      return this_path if File.exist? this_path
    end

    return nil
  end

  ##
  # Return the full path to the cached gem file matching the given
  # name and version requirement.  Returns 'nil' if no match.
  #
  # Example:
  #
  #   get_path 'rake', '> 0.4' # "/usr/lib/ruby/gems/1.8/cache/rake-0.4.2.gem"
  #   get_path 'rake', '< 0.1' # nil
  #   get_path 'rak'           # nil (exact name required)
  #--
  # TODO: This should be refactored so that it's a general service. I don't
  # think any of our existing classes are the right place though.  Just maybe
  # 'Cache'?
  #
  # TODO: It just uses Gem.dir for now.  What's an easy way to get the list of
  # source directories?

  def get_path(dependency)
    return dependency.name if dependency.name =~ /\.gem$/i

    specs = dependency.matching_specs

    selected = specs.max_by {|s| s.version }

    return Gem::RemoteFetcher.fetcher.download_to_cache(dependency) unless
      selected

    return unless dependency.name =~ /^#{selected.name}$/i

    # We expect to find (basename).gem in the 'cache' directory.  Furthermore,
    # the name match must be exact (ignoring case).

    path = find_in_cache File.basename selected.cache_file

    return Gem::RemoteFetcher.fetcher.download_to_cache(dependency) unless path

    path
  end
end
# frozen_string_literal: true
require_relative '../command'

class Gem::Commands::HelpCommand < Gem::Command
  # :stopdoc:
  EXAMPLES = <<-EOF.freeze
Some examples of 'gem' usage.

* Install 'rake', either from local directory or remote server:

    gem install rake

* Install 'rake', only from remote server:

    gem install rake --remote

* Install 'rake', but only version 0.3.1, even if dependencies
  are not met, and into a user-specific directory:

    gem install rake --version 0.3.1 --force --user-install

* List local gems whose name begins with 'D':

    gem list D

* List local and remote gems whose name contains 'log':

    gem search log --both

* List only remote gems whose name contains 'log':

    gem search log --remote

* Uninstall 'rake':

    gem uninstall rake

* Create a gem:

    See https://guides.rubygems.org/make-your-own-gem/

* See information about RubyGems:

    gem environment

* Update all gems on your system:

    gem update

* Update your local version of RubyGems

    gem update --system
  EOF

  GEM_DEPENDENCIES = <<-EOF.freeze
A gem dependencies file allows installation of a consistent set of gems across
multiple environments.  The RubyGems implementation is designed to be
compatible with Bundler's Gemfile format.  You can see additional
documentation on the format at:

  http://bundler.io

RubyGems automatically looks for these gem dependencies files:

* gem.deps.rb
* Gemfile
* Isolate

These files are looked up automatically using `gem install -g`, or you can
specify a custom file.

When the RUBYGEMS_GEMDEPS environment variable is set to a gem dependencies
file the gems from that file will be activated at startup time.  Set it to a
specific filename or to "-" to have RubyGems automatically discover the gem
dependencies file by walking up from the current directory.

You can also activate gem dependencies at program startup using
Gem.use_gemdeps.

NOTE: Enabling automatic discovery on multiuser systems can lead to execution
of arbitrary code when used from directories outside your control.

Gem Dependencies
================

Use #gem to declare which gems you directly depend upon:

  gem 'rake'

To depend on a specific set of versions:

  gem 'rake', '~> 10.3', '>= 10.3.2'

RubyGems will require the gem name when activating the gem using
the RUBYGEMS_GEMDEPS environment variable or Gem::use_gemdeps.  Use the
require: option to override this behavior if the gem does not have a file of
that name or you don't want to require those files:

  gem 'my_gem', require: 'other_file'

To prevent RubyGems from requiring any files use:

  gem 'my_gem', require: false

To load dependencies from a .gemspec file:

  gemspec

RubyGems looks for the first .gemspec file in the current directory.  To
override this use the name: option:

  gemspec name: 'specific_gem'

To look in a different directory use the path: option:

  gemspec name: 'specific_gem', path: 'gemspecs'

To depend on a gem unpacked into a local directory:

  gem 'modified_gem', path: 'vendor/modified_gem'

To depend on a gem from git:

  gem 'private_gem', git: 'git@my.company.example:private_gem.git'

To depend on a gem from github:

  gem 'private_gem', github: 'my_company/private_gem'

To depend on a gem from a github gist:

  gem 'bang', gist: '1232884'

Git, github and gist support the ref:, branch: and tag: options to specify a
commit reference or hash, branch or tag respectively to use for the gem.

Setting the submodules: option to true for git, github and gist dependencies
causes fetching of submodules when fetching the repository.

You can depend on multiple gems from a single repository with the git method:

  git 'https://github.com/rails/rails.git' do
    gem 'activesupport'
    gem 'activerecord'
  end

Gem Sources
===========

RubyGems uses the default sources for regular `gem install` for gem
dependencies files.  Unlike bundler, you do need to specify a source.

You can override the sources used for downloading gems with:

  source 'https://gem_server.example'

You may specify multiple sources.  Unlike bundler the prepend: option is not
supported. Sources are used in-order, to prepend a source place it at the
front of the list.

Gem Platform
============

You can restrict gem dependencies to specific platforms with the #platform
and #platforms methods:

  platform :ruby_21 do
    gem 'debugger'
  end

See the bundler Gemfile manual page for a list of platforms supported in a gem
dependencies file.:

  http://bundler.io/v1.6/man/gemfile.5.html

Ruby Version and Engine Dependency
==================================

You can specify the version, engine and engine version of ruby to use with
your gem dependencies file.  If you are not running the specified version
RubyGems will raise an exception.

To depend on a specific version of ruby:

  ruby '2.1.2'

To depend on a specific ruby engine:

  ruby '1.9.3', engine: 'jruby'

To depend on a specific ruby engine version:

  ruby '1.9.3', engine: 'jruby', engine_version: '1.7.11'

Grouping Dependencies
=====================

Gem dependencies may be placed in groups that can be excluded from install.
Dependencies required for development or testing of your code may be excluded
when installed in a production environment.

A #gem dependency may be placed in a group using the group: option:

  gem 'minitest', group: :test

To install dependencies from a gemfile without specific groups use the
`--without` option for `gem install -g`:

  $ gem install -g --without test

The group: option also accepts multiple groups if the gem fits in multiple
categories.

Multiple groups may be excluded during install by comma-separating the groups for `--without` or by specifying `--without` multiple times.

The #group method can also be used to place gems in groups:

  group :test do
    gem 'minitest'
    gem 'minitest-emoji'
  end

The #group method allows multiple groups.

The #gemspec development dependencies are placed in the :development group by
default.  This may be overridden with the :development_group option:

  gemspec development_group: :other

  EOF

  PLATFORMS = <<-'EOF'.freeze
RubyGems platforms are composed of three parts, a CPU, an OS, and a
version.  These values are taken from values in rbconfig.rb.  You can view
your current platform by running `gem environment`.

RubyGems matches platforms as follows:

  * The CPU must match exactly unless one of the platforms has
    "universal" as the CPU or the local CPU starts with "arm" and the gem's
    CPU is exactly "arm" (for gems that support generic ARM architecture).
  * The OS must match exactly.
  * The versions must match exactly unless one of the versions is nil.

For commands that install, uninstall and list gems, you can override what
RubyGems thinks your platform is with the --platform option.  The platform
you pass must match "#{cpu}-#{os}" or "#{cpu}-#{os}-#{version}".  On mswin
platforms, the version is the compiler version, not the OS version.  (Ruby
compiled with VC6 uses "60" as the compiler version, VC8 uses "80".)

For the ARM architecture, gems with a platform of "arm-linux" should run on a
reasonable set of ARM CPUs and not depend on instructions present on a limited
subset of the architecture.  For example, the binary should run on platforms
armv5, armv6hf, armv6l, armv7, etc.  If you use the "arm-linux" platform
please test your gem on a variety of ARM hardware before release to ensure it
functions correctly.

Example platforms:

  x86-freebsd        # Any FreeBSD version on an x86 CPU
  universal-darwin-8 # Darwin 8 only gems that run on any CPU
  x86-mswin32-80     # Windows gems compiled with VC8
  armv7-linux        # Gem complied for an ARMv7 CPU running linux
  arm-linux          # Gem compiled for any ARM CPU running linux

When building platform gems, set the platform in the gem specification to
Gem::Platform::CURRENT.  This will correctly mark the gem with your ruby's
platform.
  EOF

  # NOTE when updating also update Gem::Command::HELP

  SUBCOMMANDS = [
    ["commands",         :show_commands],
    ["options",          Gem::Command::HELP],
    ["examples",         EXAMPLES],
    ["gem_dependencies", GEM_DEPENDENCIES],
    ["platforms",        PLATFORMS],
  ].freeze
  # :startdoc:

  def initialize
    super 'help', "Provide help on the 'gem' command"

    @command_manager = Gem::CommandManager.instance
  end

  def usage # :nodoc:
    "#{program_name} ARGUMENT"
  end

  def execute
    arg = options[:args][0]

    _, help = SUBCOMMANDS.find do |command,|
      begins? command, arg
    end

    if help
      if Symbol === help
        send help
      else
        say help
      end
      return
    end

    if options[:help]
      show_help

    elsif arg
      show_command_help arg

    else
      say Gem::Command::HELP
    end
  end

  def show_commands # :nodoc:
    out = []
    out << "GEM commands are:"
    out << nil

    margin_width = 4

    desc_width = @command_manager.command_names.map {|n| n.size }.max + 4

    summary_width = 80 - margin_width - desc_width
    wrap_indent = ' ' * (margin_width + desc_width)
    format = "#{' ' * margin_width}%-#{desc_width}s%s"

    @command_manager.command_names.each do |cmd_name|
      command = @command_manager[cmd_name]

      next if command.deprecated?

      summary =
        if command
          command.summary
        else
          "[No command found for #{cmd_name}]"
        end

      summary = wrap(summary, summary_width).split "\n"
      out << sprintf(format, cmd_name, summary.shift)
      until summary.empty? do
        out << "#{wrap_indent}#{summary.shift}"
      end
    end

    out << nil
    out << "For help on a particular command, use 'gem help COMMAND'."
    out << nil
    out << "Commands may be abbreviated, so long as they are unambiguous."
    out << "e.g. 'gem i rake' is short for 'gem install rake'."

    say out.join("\n")
  end

  def show_command_help(command_name) # :nodoc:
    command_name = command_name.downcase

    possibilities = @command_manager.find_command_possibilities command_name

    if possibilities.size == 1
      command = @command_manager[possibilities.first]
      command.invoke("--help")
    elsif possibilities.size > 1
      alert_warning "Ambiguous command #{command_name} (#{possibilities.join(', ')})"
    else
      alert_warning "Unknown command #{command_name}. Try: gem help commands"
    end
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../gemcutter_utilities'

class Gem::Commands::SigninCommand < Gem::Command
  include Gem::GemcutterUtilities

  def initialize
    super 'signin', 'Sign in to any gemcutter-compatible host. '\
          'It defaults to https://rubygems.org'

    add_option('--host HOST', 'Push to another gemcutter-compatible host') do |value, options|
      options[:host] = value
    end

    add_otp_option
  end

  def description # :nodoc:
    'The signin command executes host sign in for a push server (the default is'\
    ' https://rubygems.org). The host can be provided with the host flag or can'\
    ' be inferred from the provided gem. Host resolution matches the resolution'\
    ' strategy for the push command.'
  end

  def usage # :nodoc:
    program_name
  end

  def execute
    sign_in options[:host]
  end
end
# frozen_string_literal: true
require_relative '../command'

class Gem::Commands::EnvironmentCommand < Gem::Command
  def initialize
    super 'environment', 'Display information about the RubyGems environment'
  end

  def arguments # :nodoc:
    args = <<-EOF
          gemdir          display the path where gems are installed
          gempath         display path used to search for gems
          version         display the gem format version
          remotesources   display the remote gem servers
          platform        display the supported gem platforms
          <omitted>       display everything
    EOF
    return args.gsub(/^\s+/, '')
  end

  def description # :nodoc:
    <<-EOF
The environment command lets you query rubygems for its configuration for
use in shell scripts or as a debugging aid.

The RubyGems environment can be controlled through command line arguments,
gemrc files, environment variables and built-in defaults.

Command line argument defaults and some RubyGems defaults can be set in a
~/.gemrc file for individual users and a gemrc in the SYSTEM CONFIGURATION
DIRECTORY for all users. These files are YAML files with the following YAML
keys:

  :sources: A YAML array of remote gem repositories to install gems from
  :verbose: Verbosity of the gem command. false, true, and :really are the
            levels
  :update_sources: Enable/disable automatic updating of repository metadata
  :backtrace: Print backtrace when RubyGems encounters an error
  :gempath: The paths in which to look for gems
  :disable_default_gem_server: Force specification of gem server host on push
  <gem_command>: A string containing arguments for the specified gem command

Example:

  :verbose: false
  install: --no-wrappers
  update: --no-wrappers
  :disable_default_gem_server: true

RubyGems' default local repository can be overridden with the GEM_PATH and
GEM_HOME environment variables. GEM_HOME sets the default repository to
install into. GEM_PATH allows multiple local repositories to be searched for
gems.

If you are behind a proxy server, RubyGems uses the HTTP_PROXY,
HTTP_PROXY_USER and HTTP_PROXY_PASS environment variables to discover the
proxy server.

If you would like to push gems to a private gem server the RUBYGEMS_HOST
environment variable can be set to the URI for that server.

If you are packaging RubyGems all of RubyGems' defaults are in
lib/rubygems/defaults.rb.  You may override these in
lib/rubygems/defaults/operating_system.rb
    EOF
  end

  def usage # :nodoc:
    "#{program_name} [arg]"
  end

  def execute
    out = String.new
    arg = options[:args][0]
    out <<
      case arg
      when /^version/ then
        Gem::VERSION
      when /^gemdir/, /^gemhome/, /^home/, /^GEM_HOME/ then
        Gem.dir
      when /^gempath/, /^path/, /^GEM_PATH/ then
        Gem.path.join(File::PATH_SEPARATOR)
      when /^remotesources/ then
        Gem.sources.to_a.join("\n")
      when /^platform/ then
        Gem.platforms.join(File::PATH_SEPARATOR)
      when nil then
        show_environment
      else
        raise Gem::CommandLineError, "Unknown environment option [#{arg}]"
      end
    say out
    true
  end

  def add_path(out, path)
    path.each do |component|
      out << "     - #{component}\n"
    end
  end

  def show_environment # :nodoc:
    out = "RubyGems Environment:\n".dup

    out << "  - RUBYGEMS VERSION: #{Gem::VERSION}\n"

    out << "  - RUBY VERSION: #{RUBY_VERSION} (#{RUBY_RELEASE_DATE}"
    out << " patchlevel #{RUBY_PATCHLEVEL}" if defined? RUBY_PATCHLEVEL
    out << ") [#{RUBY_PLATFORM}]\n"

    out << "  - INSTALLATION DIRECTORY: #{Gem.dir}\n"

    out << "  - USER INSTALLATION DIRECTORY: #{Gem.user_dir}\n"

    out << "  - RUBYGEMS PREFIX: #{Gem.prefix}\n" unless Gem.prefix.nil?

    out << "  - RUBY EXECUTABLE: #{Gem.ruby}\n"

    out << "  - GIT EXECUTABLE: #{git_path}\n"

    out << "  - EXECUTABLE DIRECTORY: #{Gem.bindir}\n"

    out << "  - SPEC CACHE DIRECTORY: #{Gem.spec_cache_dir}\n"

    out << "  - SYSTEM CONFIGURATION DIRECTORY: #{Gem::ConfigFile::SYSTEM_CONFIG_PATH}\n"

    out << "  - RUBYGEMS PLATFORMS:\n"
    Gem.platforms.each do |platform|
      out << "     - #{platform}\n"
    end

    out << "  - GEM PATHS:\n"
    out << "     - #{Gem.dir}\n"

    gem_path = Gem.path.dup
    gem_path.delete Gem.dir
    add_path out, gem_path

    out << "  - GEM CONFIGURATION:\n"
    Gem.configuration.each do |name, value|
      value = value.gsub(/./, '*') if name == 'gemcutter_key'
      out << "     - #{name.inspect} => #{value.inspect}\n"
    end

    out << "  - REMOTE SOURCES:\n"
    Gem.sources.each do |s|
      out << "     - #{s}\n"
    end

    out << "  - SHELL PATH:\n"

    shell_path = ENV['PATH'].split(File::PATH_SEPARATOR)
    add_path out, shell_path

    out
  end

  private

  ##
  # Git binary path

  def git_path
    exts = ENV["PATHEXT"] ? ENV["PATHEXT"].split(";") : [""]
    ENV["PATH"].split(File::PATH_SEPARATOR).each do |path|
      exts.each do |ext|
        exe = File.join(path, "git#{ext}")
        return exe if File.executable?(exe) && !File.directory?(exe)
      end
    end

    return nil
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../command_manager'
require_relative '../dependency_installer'
require_relative '../install_update_options'
require_relative '../local_remote_options'
require_relative '../spec_fetcher'
require_relative '../version_option'
require_relative '../install_message' # must come before rdoc for messaging
require_relative '../rdoc'

class Gem::Commands::UpdateCommand < Gem::Command
  include Gem::InstallUpdateOptions
  include Gem::LocalRemoteOptions
  include Gem::VersionOption

  attr_reader :installer # :nodoc:

  attr_reader :updated # :nodoc:

  def initialize
    super 'update', 'Update installed gems to the latest version',
      :document => %w[rdoc ri],
      :force    => false

    add_install_update_options

    Gem::OptionParser.accept Gem::Version do |value|
      Gem::Version.new value

      value
    end

    add_option('--system [VERSION]', Gem::Version,
               'Update the RubyGems system software') do |value, options|
      value = true unless value

      options[:system] = value
    end

    add_local_remote_options
    add_platform_option
    add_prerelease_option "as update targets"

    @updated   = []
    @installer = nil
  end

  def arguments # :nodoc:
    "GEMNAME       name of gem to update"
  end

  def defaults_str # :nodoc:
    "--document --no-force --install-dir #{Gem.dir}"
  end

  def description # :nodoc:
    <<-EOF
The update command will update your gems to the latest version.

The update command does not remove the previous version. Use the cleanup
command to remove old versions.
    EOF
  end

  def usage # :nodoc:
    "#{program_name} GEMNAME [GEMNAME ...]"
  end

  def check_latest_rubygems(version) # :nodoc:
    if Gem.rubygems_version == version
      say "Latest version already installed. Done."
      terminate_interaction
    end
  end

  def check_oldest_rubygems(version) # :nodoc:
    if oldest_supported_version > version
      alert_error "rubygems #{version} is not supported on #{RUBY_VERSION}. The oldest version supported by this ruby is #{oldest_supported_version}"
      terminate_interaction 1
    end
  end

  def check_update_arguments # :nodoc:
    unless options[:args].empty?
      alert_error "Gem names are not allowed with the --system option"
      terminate_interaction 1
    end
  end

  def execute
    if options[:system]
      update_rubygems
      return
    end

    gems_to_update = which_to_update(
      highest_installed_gems,
      options[:args].uniq
    )

    if options[:explain]
      say "Gems to update:"

      gems_to_update.each do |name_tuple|
        say "  #{name_tuple.full_name}"
      end

      return
    end

    say "Updating installed gems"

    updated = update_gems gems_to_update

    updated_names = updated.map {|spec| spec.name }
    not_updated_names = options[:args].uniq - updated_names

    if updated.empty?
      say "Nothing to update"
    else
      say "Gems updated: #{updated_names.join(' ')}"
      say "Gems already up-to-date: #{not_updated_names.join(' ')}" unless not_updated_names.empty?
    end
  end

  def fetch_remote_gems(spec) # :nodoc:
    dependency = Gem::Dependency.new spec.name, "> #{spec.version}"
    dependency.prerelease = options[:prerelease]

    fetcher = Gem::SpecFetcher.fetcher

    spec_tuples, errors = fetcher.search_for_dependency dependency

    error = errors.find {|e| e.respond_to? :exception }

    raise error if error

    spec_tuples
  end

  def highest_installed_gems # :nodoc:
    hig = {} # highest installed gems

    # Get only gem specifications installed as --user-install
    Gem::Specification.dirs = Gem.user_dir if options[:user_install]

    Gem::Specification.each do |spec|
      if hig[spec.name].nil? or hig[spec.name].version < spec.version
        hig[spec.name] = spec
      end
    end

    hig
  end

  def highest_remote_name_tuple(spec) # :nodoc:
    spec_tuples = fetch_remote_gems spec

    matching_gems = spec_tuples.select do |g,_|
      g.name == spec.name and g.match_platform?
    end

    highest_remote_gem = matching_gems.max

    highest_remote_gem ||= [Gem::NameTuple.null]

    highest_remote_gem.first
  end

  def install_rubygems(version) # :nodoc:
    args = update_rubygems_arguments

    update_dir = File.join Gem.dir, 'gems', "rubygems-update-#{version}"

    Dir.chdir update_dir do
      say "Installing RubyGems #{version}" unless options[:silent]

      installed = preparing_gem_layout_for(version) do
        system Gem.ruby, '--disable-gems', 'setup.rb', *args
      end

      say "RubyGems system software updated" if installed unless options[:silent]
    end
  end

  def preparing_gem_layout_for(version)
    if Gem::Version.new(version) >= Gem::Version.new("3.2.a")
      yield
    else
      require "tmpdir"
      tmpdir = Dir.mktmpdir
      FileUtils.mv Gem.plugindir, tmpdir

      status = yield

      if status
        FileUtils.rm_rf tmpdir
      else
        FileUtils.mv File.join(tmpdir, "plugins"), Gem.plugindir
      end

      status
    end
  end

  def rubygems_target_version
    version = options[:system]
    update_latest = version == true

    if update_latest
      version     = Gem::Version.new     Gem::VERSION
      requirement = Gem::Requirement.new ">= #{Gem::VERSION}"
    else
      version     = Gem::Version.new     version
      requirement = Gem::Requirement.new version
    end

    rubygems_update         = Gem::Specification.new
    rubygems_update.name    = 'rubygems-update'
    rubygems_update.version = version

    hig = {
      'rubygems-update' => rubygems_update,
    }

    gems_to_update = which_to_update hig, options[:args], :system
    up_ver = gems_to_update.first.version

    target = if update_latest
               up_ver
             else
               version
             end

    return target, requirement
  end

  def update_gem(name, version = Gem::Requirement.default)
    return if @updated.any? {|spec| spec.name == name }

    update_options = options.dup
    update_options[:prerelease] = version.prerelease?

    @installer = Gem::DependencyInstaller.new update_options

    say "Updating #{name}" unless options[:system] && options[:silent]
    begin
      @installer.install name, Gem::Requirement.new(version)
    rescue Gem::InstallError, Gem::DependencyError => e
      alert_error "Error installing #{name}:\n\t#{e.message}"
    end

    @installer.installed_gems.each do |spec|
      @updated << spec
    end
  end

  def update_gems(gems_to_update)
    gems_to_update.uniq.sort.each do |name_tuple|
      update_gem name_tuple.name, name_tuple.version
    end

    @updated
  end

  ##
  # Update RubyGems software to the latest version.

  def update_rubygems
    if Gem.disable_system_update_message
      alert_error Gem.disable_system_update_message
      terminate_interaction 1
    end

    check_update_arguments

    version, requirement = rubygems_target_version

    check_latest_rubygems version

    check_oldest_rubygems version

    update_gem 'rubygems-update', version

    installed_gems = Gem::Specification.find_all_by_name 'rubygems-update', requirement
    version        = installed_gems.first.version

    install_rubygems version
  end

  def update_rubygems_arguments # :nodoc:
    args = []
    args << '--silent' if options[:silent]
    args << '--prefix' << Gem.prefix if Gem.prefix
    args << '--no-document' unless options[:document].include?('rdoc') || options[:document].include?('ri')
    args << '--no-format-executable' if options[:no_format_executable]
    args << '--previous-version' << Gem::VERSION if
      options[:system] == true or
        Gem::Version.new(options[:system]) >= Gem::Version.new(2)
    args
  end

  def which_to_update(highest_installed_gems, gem_names, system = false)
    result = []

    highest_installed_gems.each do |l_name, l_spec|
      next if not gem_names.empty? and
              gem_names.none? {|name| name == l_spec.name }

      highest_remote_tup = highest_remote_name_tuple l_spec
      highest_remote_ver = highest_remote_tup.version
      highest_installed_ver = l_spec.version

      if system or (highest_installed_ver < highest_remote_ver)
        result << Gem::NameTuple.new(l_spec.name, [highest_installed_ver, highest_remote_ver].max, highest_remote_tup.platform)
      end
    end

    result
  end

  private

  #
  # Oldest version we support downgrading to. This is the version that
  # originally ships with the first patch version of each ruby, because we never
  # test each ruby against older rubygems, so we can't really guarantee it
  # works. Version list can be checked here: https://stdgems.org/rubygems
  #
  def oldest_supported_version
    @oldest_supported_version ||=
      if Gem.ruby_version > Gem::Version.new("3.0.a")
        Gem::Version.new("3.2.3")
      elsif Gem.ruby_version > Gem::Version.new("2.7.a")
        Gem::Version.new("3.1.2")
      elsif Gem.ruby_version > Gem::Version.new("2.6.a")
        Gem::Version.new("3.0.1")
      elsif Gem.ruby_version > Gem::Version.new("2.5.a")
        Gem::Version.new("2.7.3")
      elsif Gem.ruby_version > Gem::Version.new("2.4.a")
        Gem::Version.new("2.6.8")
      else
        Gem::Version.new("2.5.2")
      end
  end
end
# frozen_string_literal: true
require_relative '../command'

unless defined? Gem::Commands::MirrorCommand
  class Gem::Commands::MirrorCommand < Gem::Command
    def initialize
      super('mirror', 'Mirror all gem files (requires rubygems-mirror)')
      begin
        Gem::Specification.find_by_name('rubygems-mirror').activate
      rescue Gem::LoadError
        # no-op
      end
    end

    def description # :nodoc:
      <<-EOF
The mirror command has been moved to the rubygems-mirror gem.
      EOF
    end

    def execute
      alert_error "Install the rubygems-mirror gem for the mirror command"
    end
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../query_utils'
require_relative '../deprecate'

class Gem::Commands::QueryCommand < Gem::Command
  extend Gem::Deprecate
  rubygems_deprecate_command

  include Gem::QueryUtils

  alias warning_without_suggested_alternatives deprecation_warning
  def deprecation_warning
    warning_without_suggested_alternatives

    message = "It is recommended that you use `gem search` or `gem list` instead.\n"
    alert_warning message unless Gem::Deprecate.skip
  end

  def initialize(name = 'query',
                 summary = 'Query gem information in local or remote repositories')
    super name, summary,
         :name => //, :domain => :local, :details => false, :versions => true,
         :installed => nil, :version => Gem::Requirement.default

    add_option('-n', '--name-matches REGEXP',
               'Name of gem(s) to query on matches the',
               'provided REGEXP') do |value, options|
      options[:name] = /#{value}/i
    end

    add_query_options
  end

  def description # :nodoc:
    <<-EOF
The query command is the basis for the list and search commands.

You should really use the list and search commands instead.  This command
is too hard to use.
    EOF
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../query_utils'

class Gem::Commands::SearchCommand < Gem::Command
  include Gem::QueryUtils

  def initialize
    super 'search', 'Display remote gems whose name matches REGEXP',
         :name => //, :domain => :remote, :details => false, :versions => true,
         :installed => nil, :version => Gem::Requirement.default

    add_query_options
  end

  def arguments # :nodoc:
    "REGEXP        regexp to search for in gem name"
  end

  def defaults_str # :nodoc:
    "--remote --no-details"
  end

  def description # :nodoc:
    <<-EOF
The search command displays remote gems whose name matches the given
regexp.

The --details option displays additional details from the gem but will
take a little longer to complete as it must download the information
individually from the index.

To list local gems use the list command.
    EOF
  end

  def usage # :nodoc:
    "#{program_name} [REGEXP]"
  end
end
# frozen_string_literal: true
require_relative '../command'

class Gem::Commands::StaleCommand < Gem::Command
  def initialize
    super('stale', 'List gems along with access times')
  end

  def description # :nodoc:
    <<-EOF
The stale command lists the latest access time for all the files in your
installed gems.

You can use this command to discover gems and gem versions you are no
longer using.
    EOF
  end

  def usage # :nodoc:
    "#{program_name}"
  end

  def execute
    gem_to_atime = {}
    Gem::Specification.each do |spec|
      name = spec.full_name
      Dir["#{spec.full_gem_path}/**/*.*"].each do |file|
        next if File.directory?(file)
        stat = File.stat(file)
        gem_to_atime[name] ||= stat.atime
        gem_to_atime[name] = stat.atime if gem_to_atime[name] < stat.atime
      end
    end

    gem_to_atime.sort_by {|_, atime| atime }.each do |name, atime|
      say "#{name} at #{atime.strftime '%c'}"
    end
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../local_remote_options'
require_relative '../gemcutter_utilities'
require_relative '../text'

class Gem::Commands::OwnerCommand < Gem::Command
  include Gem::Text
  include Gem::LocalRemoteOptions
  include Gem::GemcutterUtilities

  def description # :nodoc:
    <<-EOF
The owner command lets you add and remove owners of a gem on a push
server (the default is https://rubygems.org).

The owner of a gem has the permission to push new versions, yank existing
versions or edit the HTML page of the gem.  Be careful of who you give push
permission to.
    EOF
  end

  def arguments # :nodoc:
    "GEM       gem to manage owners for"
  end

  def usage # :nodoc:
    "#{program_name} GEM"
  end

  def initialize
    super 'owner', 'Manage gem owners of a gem on the push server'
    add_proxy_option
    add_key_option
    add_otp_option
    defaults.merge! :add => [], :remove => []

    add_option '-a', '--add EMAIL', 'Add an owner' do |value, options|
      options[:add] << value
    end

    add_option '-r', '--remove EMAIL', 'Remove an owner' do |value, options|
      options[:remove] << value
    end

    add_option '-h', '--host HOST',
               'Use another gemcutter-compatible host',
               '  (e.g. https://rubygems.org)' do |value, options|
      options[:host] = value
    end
  end

  def execute
    @host = options[:host]

    sign_in(scope: get_owner_scope)
    name = get_one_gem_name

    add_owners    name, options[:add]
    remove_owners name, options[:remove]
    show_owners   name
  end

  def show_owners(name)
    Gem.load_yaml

    response = rubygems_api_request :get, "api/v1/gems/#{name}/owners.yaml" do |request|
      request.add_field "Authorization", api_key
    end

    with_response response do |resp|
      owners = Gem::SafeYAML.load clean_text(resp.body)

      say "Owners for gem: #{name}"
      owners.each do |owner|
        say "- #{owner['email'] || owner['handle'] || owner['id']}"
      end
    end
  end

  def add_owners(name, owners)
    manage_owners :post, name, owners
  end

  def remove_owners(name, owners)
    manage_owners :delete, name, owners
  end

  def manage_owners(method, name, owners)
    owners.each do |owner|
      begin
        response = send_owner_request(method, name, owner)
        action = method == :delete ? "Removing" : "Adding"

        with_response response, "#{action} #{owner}"
      rescue
        # ignore
      end
    end
  end

  private

  def send_owner_request(method, name, owner)
    rubygems_api_request method, "api/v1/gems/#{name}/owners", scope: get_owner_scope(method: method) do |request|
      request.set_form_data 'email' => owner
      request.add_field "Authorization", api_key
    end
  end

  def get_owner_scope(method: nil)
    if method == :post || options.any? && options[:add].any?
      :add_owner
    elsif method == :delete || options.any? && options[:remove].any?
      :remove_owner
    end
  end
end
# frozen_string_literal: true
require_relative '../command'

class Gem::Commands::SignoutCommand < Gem::Command
  def initialize
    super 'signout', 'Sign out from all the current sessions.'
  end

  def description # :nodoc:
    'The `signout` command is used to sign out from all current sessions,'\
    ' allowing you to sign in using a different set of credentials.'
  end

  def usage # :nodoc:
    program_name
  end

  def execute
    credentials_path = Gem.configuration.credentials_path

    if !File.exist?(credentials_path)
      alert_error 'You are not currently signed in.'
    elsif !File.writable?(credentials_path)
      alert_error "File '#{Gem.configuration.credentials_path}' is read-only."\
                  ' Please make sure it is writable.'
    else
      Gem.configuration.unset_api_key!
      say 'You have successfully signed out from all sessions.'
    end
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../version_option'
require_relative '../rdoc'
require 'fileutils'

class Gem::Commands::RdocCommand < Gem::Command
  include Gem::VersionOption

  def initialize
    super 'rdoc', 'Generates RDoc for pre-installed gems',
          :version => Gem::Requirement.default,
          :include_rdoc => false, :include_ri => true, :overwrite => false

    add_option('--all',
               'Generate RDoc/RI documentation for all',
               'installed gems') do |value, options|
      options[:all] = value
    end

    add_option('--[no-]rdoc',
               'Generate RDoc HTML') do |value, options|
      options[:include_rdoc] = value
    end

    add_option('--[no-]ri',
               'Generate RI data') do |value, options|
      options[:include_ri] = value
    end

    add_option('--[no-]overwrite',
               'Overwrite installed documents') do |value, options|
      options[:overwrite] = value
    end

    add_version_option
  end

  def arguments # :nodoc:
    "GEMNAME       gem to generate documentation for (unless --all)"
  end

  def defaults_str # :nodoc:
    "--version '#{Gem::Requirement.default}' --ri --no-overwrite"
  end

  def description # :nodoc:
    <<-DESC
The rdoc command builds documentation for installed gems.  By default
only documentation is built using rdoc, but additional types of
documentation may be built through rubygems plugins and the
Gem.post_installs hook.

Use --overwrite to force rebuilding of documentation.
    DESC
  end

  def usage # :nodoc:
    "#{program_name} [args]"
  end

  def execute
    specs = if options[:all]
              Gem::Specification.to_a
            else
              get_all_gem_names.map do |name|
                Gem::Specification.find_by_name name, options[:version]
              end.flatten.uniq
            end

    if specs.empty?
      alert_error 'No matching gems found'
      terminate_interaction 1
    end

    specs.each do |spec|
      doc = Gem::RDoc.new spec, options[:include_rdoc], options[:include_ri]

      doc.force = options[:overwrite]

      if options[:overwrite]
        FileUtils.rm_rf File.join(spec.doc_dir, 'ri')
        FileUtils.rm_rf File.join(spec.doc_dir, 'rdoc')
      end

      begin
        doc.generate
      rescue Errno::ENOENT => e
        e.message =~ / - /
        alert_error "Unable to document #{spec.full_name}, #{$'} is missing, skipping"
        terminate_interaction 1 if specs.length == 1
      end
    end
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../local_remote_options'
require_relative '../version_option'
require_relative '../gemcutter_utilities'

class Gem::Commands::YankCommand < Gem::Command
  include Gem::LocalRemoteOptions
  include Gem::VersionOption
  include Gem::GemcutterUtilities

  def description # :nodoc:
    <<-EOF
The yank command permanently removes a gem you pushed to a server.

Once you have pushed a gem several downloads will happen automatically
via the webhooks. If you accidentally pushed passwords or other sensitive
data you will need to change them immediately and yank your gem.
    EOF
  end

  def arguments # :nodoc:
    "GEM       name of gem"
  end

  def usage # :nodoc:
    "#{program_name} -v VERSION [-p PLATFORM] [--key KEY_NAME] [--host HOST] GEM"
  end

  def initialize
    super 'yank', 'Remove a pushed gem from the index'

    add_version_option("remove")
    add_platform_option("remove")
    add_otp_option

    add_option('--host HOST',
               'Yank from another gemcutter-compatible host',
               '  (e.g. https://rubygems.org)') do |value, options|
      options[:host] = value
    end

    add_key_option
    @host = nil
  end

  def execute
    @host = options[:host]

    sign_in @host, scope: get_yank_scope

    version   = get_version_from_requirements(options[:version])
    platform  = get_platform_from_requirements(options)

    if version
      yank_gem(version, platform)
    else
      say "A version argument is required: #{usage}"
      terminate_interaction
    end
  end

  def yank_gem(version, platform)
    say "Yanking gem from #{self.host}..."
    args = [:delete, version, platform, "api/v1/gems/yank"]
    response = yank_api_request(*args)

    say response.body
  end

  private

  def yank_api_request(method, version, platform, api)
    name = get_one_gem_name
    response = rubygems_api_request(method, api, host, scope: get_yank_scope) do |request|
      request.add_field("Authorization", api_key)

      data = {
        'gem_name' => name,
        'version' => version,
      }
      data['platform'] = platform if platform

      request.set_form_data data
    end
    response
  end

  def get_version_from_requirements(requirements)
    requirements.requirements.first[1].version
  rescue
    nil
  end

  def get_yank_scope
    :yank_rubygem
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../local_remote_options'
require_relative '../spec_fetcher'
require_relative '../version_option'

class Gem::Commands::OutdatedCommand < Gem::Command
  include Gem::LocalRemoteOptions
  include Gem::VersionOption

  def initialize
    super 'outdated', 'Display all gems that need updates'

    add_local_remote_options
    add_platform_option
  end

  def description # :nodoc:
    <<-EOF
The outdated command lists gems you may wish to upgrade to a newer version.

You can check for dependency mismatches using the dependency command and
update the gems with the update or install commands.
    EOF
  end

  def execute
    Gem::Specification.outdated_and_latest_version.each do |spec, remote_version|
      say "#{spec.name} (#{spec.version} < #{remote_version})"
    end
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../install_update_options'
require_relative '../dependency_installer'
require_relative '../local_remote_options'
require_relative '../validator'
require_relative '../version_option'

##
# Gem installer command line tool
#
# See `gem help install`

class Gem::Commands::InstallCommand < Gem::Command
  attr_reader :installed_specs # :nodoc:

  include Gem::VersionOption
  include Gem::LocalRemoteOptions
  include Gem::InstallUpdateOptions

  def initialize
    defaults = Gem::DependencyInstaller::DEFAULT_OPTIONS.merge({
      :format_executable => false,
      :lock              => true,
      :suggest_alternate => true,
      :version           => Gem::Requirement.default,
      :without_groups    => [],
    })

    super 'install', 'Install a gem into the local repository', defaults

    add_install_update_options
    add_local_remote_options
    add_platform_option
    add_version_option
    add_prerelease_option "to be installed. (Only for listed gems)"

    @installed_specs = []
  end

  def arguments # :nodoc:
    "GEMNAME       name of gem to install"
  end

  def defaults_str # :nodoc:
    "--both --version '#{Gem::Requirement.default}' --document --no-force\n" +
    "--install-dir #{Gem.dir} --lock"
  end

  def description # :nodoc:
    <<-EOF
The install command installs local or remote gem into a gem repository.

For gems with executables ruby installs a wrapper file into the executable
directory by default.  This can be overridden with the --no-wrappers option.
The wrapper allows you to choose among alternate gem versions using _version_.

For example `rake _0.7.3_ --version` will run rake version 0.7.3 if a newer
version is also installed.

Gem Dependency Files
====================

RubyGems can install a consistent set of gems across multiple environments
using `gem install -g` when a gem dependencies file (gem.deps.rb, Gemfile or
Isolate) is present.  If no explicit file is given RubyGems attempts to find
one in the current directory.

When the RUBYGEMS_GEMDEPS environment variable is set to a gem dependencies
file the gems from that file will be activated at startup time.  Set it to a
specific filename or to "-" to have RubyGems automatically discover the gem
dependencies file by walking up from the current directory.

NOTE: Enabling automatic discovery on multiuser systems can lead to
execution of arbitrary code when used from directories outside your control.

Extension Install Failures
==========================

If an extension fails to compile during gem installation the gem
specification is not written out, but the gem remains unpacked in the
repository.  You may need to specify the path to the library's headers and
libraries to continue.  You can do this by adding a -- between RubyGems'
options and the extension's build options:

  $ gem install some_extension_gem
  [build fails]
  Gem files will remain installed in \\
  /path/to/gems/some_extension_gem-1.0 for inspection.
  Results logged to /path/to/gems/some_extension_gem-1.0/gem_make.out
  $ gem install some_extension_gem -- --with-extension-lib=/path/to/lib
  [build succeeds]
  $ gem list some_extension_gem

  *** LOCAL GEMS ***

  some_extension_gem (1.0)
  $

If you correct the compilation errors by editing the gem files you will need
to write the specification by hand.  For example:

  $ gem install some_extension_gem
  [build fails]
  Gem files will remain installed in \\
  /path/to/gems/some_extension_gem-1.0 for inspection.
  Results logged to /path/to/gems/some_extension_gem-1.0/gem_make.out
  $ [cd /path/to/gems/some_extension_gem-1.0]
  $ [edit files or what-have-you and run make]
  $ gem spec ../../cache/some_extension_gem-1.0.gem --ruby > \\
             ../../specifications/some_extension_gem-1.0.gemspec
  $ gem list some_extension_gem

  *** LOCAL GEMS ***

  some_extension_gem (1.0)
  $

Command Alias
==========================

You can use `i` command instead of `install`.

  $ gem i GEMNAME

    EOF
  end

  def usage # :nodoc:
    "#{program_name} [options] GEMNAME [GEMNAME ...] -- --build-flags"
  end

  def check_install_dir # :nodoc:
    if options[:install_dir] and options[:user_install]
      alert_error "Use --install-dir or --user-install but not both"
      terminate_interaction 1
    end
  end

  def check_version # :nodoc:
    if options[:version] != Gem::Requirement.default and
         get_all_gem_names.size > 1
      alert_error "Can't use --version with multiple gems. You can specify multiple gems with" \
                  " version requirements using `gem install 'my_gem:1.0.0' 'my_other_gem:~>2.0.0'`"
      terminate_interaction 1
    end
  end

  def execute
    if options.include? :gemdeps
      install_from_gemdeps
      return # not reached
    end

    @installed_specs = []

    ENV.delete 'GEM_PATH' if options[:install_dir].nil?

    check_install_dir
    check_version

    load_hooks

    exit_code = install_gems

    show_installed

    terminate_interaction exit_code
  end

  def install_from_gemdeps # :nodoc:
    require_relative '../request_set'
    rs = Gem::RequestSet.new

    specs = rs.install_from_gemdeps options do |req, inst|
      s = req.full_spec

      if inst
        say "Installing #{s.name} (#{s.version})"
      else
        say "Using #{s.name} (#{s.version})"
      end
    end

    @installed_specs = specs

    terminate_interaction
  end

  def install_gem(name, version) # :nodoc:
    return if options[:conservative] and
      not Gem::Dependency.new(name, version).matching_specs.empty?

    req = Gem::Requirement.create(version)

    dinst = Gem::DependencyInstaller.new options

    request_set = dinst.resolve_dependencies name, req

    if options[:explain]
      say "Gems to install:"

      request_set.sorted_requests.each do |activation_request|
        say "  #{activation_request.full_name}"
      end
    else
      @installed_specs.concat request_set.install options
    end

    show_install_errors dinst.errors
  end

  def install_gems # :nodoc:
    exit_code = 0

    get_all_gem_names_and_versions.each do |gem_name, gem_version|
      gem_version ||= options[:version]
      domain = options[:domain]
      domain = :local unless options[:suggest_alternate]
      suppress_suggestions = (domain == :local)

      begin
        install_gem gem_name, gem_version
      rescue Gem::InstallError => e
        alert_error "Error installing #{gem_name}:\n\t#{e.message}"
        exit_code |= 1
      rescue Gem::GemNotFoundException => e
        show_lookup_failure e.name, e.version, e.errors, suppress_suggestions

        exit_code |= 2
      rescue Gem::UnsatisfiableDependencyError => e
        show_lookup_failure e.name, e.version, e.errors, suppress_suggestions,
                            "'#{gem_name}' (#{gem_version})"

        exit_code |= 2
      end
    end

    exit_code
  end

  ##
  # Loads post-install hooks

  def load_hooks # :nodoc:
    if options[:install_as_default]
      require_relative '../install_default_message'
    else
      require_relative '../install_message'
    end
    require_relative '../rdoc'
  end

  def show_install_errors(errors) # :nodoc:
    return unless errors

    errors.each do |x|
      return unless Gem::SourceFetchProblem === x

      require_relative "../uri"
      msg = "Unable to pull data from '#{Gem::Uri.new(x.source.uri).redacted}': #{x.error.message}"

      alert_warning msg
    end
  end

  def show_installed # :nodoc:
    return if @installed_specs.empty?

    gems = @installed_specs.length == 1 ? 'gem' : 'gems'
    say "#{@installed_specs.length} #{gems} installed"
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../package'
require_relative '../version_option'

class Gem::Commands::BuildCommand < Gem::Command
  include Gem::VersionOption

  def initialize
    super 'build', 'Build a gem from a gemspec'

    add_platform_option

    add_option '--force', 'skip validation of the spec' do |value, options|
      options[:force] = true
    end

    add_option '--strict', 'consider warnings as errors when validating the spec' do |value, options|
      options[:strict] = true
    end

    add_option '-o', '--output FILE', 'output gem with the given filename' do |value, options|
      options[:output] = value
    end

    add_option '-C PATH', 'Run as if gem build was started in <PATH> instead of the current working directory.' do |value, options|
      options[:build_path] = value
    end
  end

  def arguments # :nodoc:
    "GEMSPEC_FILE  gemspec file name to build a gem for"
  end

  def description # :nodoc:
    <<-EOF
The build command allows you to create a gem from a ruby gemspec.

The best way to build a gem is to use a Rakefile and the Gem::PackageTask
which ships with RubyGems.

The gemspec can either be created by hand or extracted from an existing gem
with gem spec:

  $ gem unpack my_gem-1.0.gem
  Unpacked gem: '.../my_gem-1.0'
  $ gem spec my_gem-1.0.gem --ruby > my_gem-1.0/my_gem-1.0.gemspec
  $ cd my_gem-1.0
  [edit gem contents]
  $ gem build my_gem-1.0.gemspec

Gems can be saved to a specified filename with the output option:

  $ gem build my_gem-1.0.gemspec --output=release.gem

    EOF
  end

  def usage # :nodoc:
    "#{program_name} GEMSPEC_FILE"
  end

  def execute
    if build_path = options[:build_path]
      Dir.chdir(build_path) { build_gem }
      return
    end

    build_gem
  end

  private

  def find_gemspec(glob = "*.gemspec")
    gemspecs = Dir.glob(glob).sort

    if gemspecs.size > 1
      alert_error "Multiple gemspecs found: #{gemspecs}, please specify one"
      terminate_interaction(1)
    end

    gemspecs.first
  end

  def build_gem
    gemspec = resolve_gem_name

    if gemspec
      build_package(gemspec)
    else
      alert_error error_message
      terminate_interaction(1)
    end
  end

  def build_package(gemspec)
    spec = Gem::Specification.load(gemspec)
    if spec
      Gem::Package.build(
        spec,
        options[:force],
        options[:strict],
        options[:output]
      )
    else
      alert_error "Error loading gemspec. Aborting."
      terminate_interaction 1
    end
  end

  def resolve_gem_name
    return find_gemspec unless gem_name

    if File.exist?(gem_name)
      gem_name
    else
      find_gemspec("#{gem_name}.gemspec") || find_gemspec(gem_name)
    end
  end

  def error_message
    if gem_name
      "Couldn't find a gemspec file matching '#{gem_name}' in #{Dir.pwd}"
    else
      "Couldn't find a gemspec file in #{Dir.pwd}"
    end
  end

  def gem_name
    get_one_optional_argument
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../version_option'
require_relative '../validator'
require_relative '../doctor'

class Gem::Commands::CheckCommand < Gem::Command
  include Gem::VersionOption

  def initialize
    super 'check', 'Check a gem repository for added or missing files',
          :alien => true, :doctor => false, :dry_run => false, :gems => true

    add_option('-a', '--[no-]alien',
               'Report "unmanaged" or rogue files in the',
               'gem repository') do |value, options|
      options[:alien] = value
    end

    add_option('--[no-]doctor',
               'Clean up uninstalled gems and broken',
               'specifications') do |value, options|
      options[:doctor] = value
    end

    add_option('--[no-]dry-run',
               'Do not remove files, only report what',
               'would be removed') do |value, options|
      options[:dry_run] = value
    end

    add_option('--[no-]gems',
               'Check installed gems for problems') do |value, options|
      options[:gems] = value
    end

    add_version_option 'check'
  end

  def check_gems
    say 'Checking gems...'
    say
    gems = get_all_gem_names rescue []

    Gem::Validator.new.alien(gems).sort.each do |key, val|
      unless val.empty?
        say "#{key} has #{val.size} problems"
        val.each do |error_entry|
          say "  #{error_entry.path}:"
          say "    #{error_entry.problem}"
        end
      else
        say "#{key} is error-free" if Gem.configuration.verbose
      end
      say
    end
  end

  def doctor
    say 'Checking for files from uninstalled gems...'
    say

    Gem.path.each do |gem_repo|
      doctor = Gem::Doctor.new gem_repo, options[:dry_run]
      doctor.doctor
    end
  end

  def execute
    check_gems if options[:gems]
    doctor if options[:doctor]
  end

  def arguments # :nodoc:
    'GEMNAME       name of gem to check'
  end

  def defaults_str # :nodoc:
    '--gems --alien'
  end

  def description # :nodoc:
    <<-EOF
The check command can list and repair problems with installed gems and
specifications and will clean up gems that have been partially uninstalled.
    EOF
  end

  def usage # :nodoc:
    "#{program_name} [OPTIONS] [GEMNAME ...]"
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../local_remote_options'
require_relative '../version_option'

class Gem::Commands::FetchCommand < Gem::Command
  include Gem::LocalRemoteOptions
  include Gem::VersionOption

  def initialize
    super 'fetch', 'Download a gem and place it in the current directory'

    add_bulk_threshold_option
    add_proxy_option
    add_source_option
    add_clear_sources_option

    add_version_option
    add_platform_option
    add_prerelease_option
  end

  def arguments # :nodoc:
    'GEMNAME       name of gem to download'
  end

  def defaults_str # :nodoc:
    "--version '#{Gem::Requirement.default}'"
  end

  def description # :nodoc:
    <<-EOF
The fetch command fetches gem files that can be stored for later use or
unpacked to examine their contents.

See the build command help for an example of unpacking a gem, modifying it,
then repackaging it.
    EOF
  end

  def usage # :nodoc:
    "#{program_name} GEMNAME [GEMNAME ...]"
  end

  def execute
    version = options[:version] || Gem::Requirement.default

    platform  = Gem.platforms.last
    gem_names = get_all_gem_names

    gem_names.each do |gem_name|
      dep = Gem::Dependency.new gem_name, version
      dep.prerelease = options[:prerelease]

      specs_and_sources, errors =
        Gem::SpecFetcher.fetcher.spec_for_dependency dep

      if platform
        filtered = specs_and_sources.select {|s,| s.platform == platform }
        specs_and_sources = filtered unless filtered.empty?
      end

      spec, source = specs_and_sources.max_by {|s,| s }

      if spec.nil?
        show_lookup_failure gem_name, version, errors, options[:domain]
        next
      end

      source.download spec

      say "Downloaded #{spec.full_name}"
    end
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../security'

class Gem::Commands::CertCommand < Gem::Command
  def initialize
    super 'cert', 'Manage RubyGems certificates and signing settings',
          :add => [], :remove => [], :list => [], :build => [], :sign => []

    add_option('-a', '--add CERT',
               'Add a trusted certificate.') do |cert_file, options|
      options[:add] << open_cert(cert_file)
    end

    add_option('-l', '--list [FILTER]',
               'List trusted certificates where the',
               'subject contains FILTER') do |filter, options|
      filter ||= ''

      options[:list] << filter
    end

    add_option('-r', '--remove FILTER',
               'Remove trusted certificates where the',
               'subject contains FILTER') do |filter, options|
      options[:remove] << filter
    end

    add_option('-b', '--build EMAIL_ADDR',
               'Build private key and self-signed',
               'certificate for EMAIL_ADDR') do |email_address, options|
      options[:build] << email_address
    end

    add_option('-C', '--certificate CERT',
               'Signing certificate for --sign') do |cert_file, options|
      options[:issuer_cert] = open_cert(cert_file)
      options[:issuer_cert_file] = cert_file
    end

    add_option('-K', '--private-key KEY',
               'Key for --sign or --build') do |key_file, options|
      options[:key] = open_private_key(key_file)
    end

    add_option('-A', '--key-algorithm ALGORITHM',
               'Select which key algorithm to use for --build') do |algorithm, options|
      options[:key_algorithm] = algorithm
    end

    add_option('-s', '--sign CERT',
               'Signs CERT with the key from -K',
               'and the certificate from -C') do |cert_file, options|
      raise Gem::OptionParser::InvalidArgument, "#{cert_file}: does not exist" unless
        File.file? cert_file

      options[:sign] << cert_file
    end

    add_option('-d', '--days NUMBER_OF_DAYS',
               'Days before the certificate expires') do |days, options|
      options[:expiration_length_days] = days.to_i
    end

    add_option('-R', '--re-sign',
               'Re-signs the certificate from -C with the key from -K') do |resign, options|
      options[:resign] = resign
    end
  end

  def add_certificate(certificate) # :nodoc:
    Gem::Security.trust_dir.trust_cert certificate

    say "Added '#{certificate.subject}'"
  end

  def check_openssl
    return if Gem::HAVE_OPENSSL

    alert_error "OpenSSL library is required for the cert command"
    terminate_interaction 1
  end

  def open_cert(certificate_file)
    check_openssl
    OpenSSL::X509::Certificate.new File.read certificate_file
  rescue Errno::ENOENT
    raise Gem::OptionParser::InvalidArgument, "#{certificate_file}: does not exist"
  rescue OpenSSL::X509::CertificateError
    raise Gem::OptionParser::InvalidArgument,
      "#{certificate_file}: invalid X509 certificate"
  end

  def open_private_key(key_file)
    check_openssl
    passphrase = ENV['GEM_PRIVATE_KEY_PASSPHRASE']
    key = OpenSSL::PKey.read File.read(key_file), passphrase
    raise Gem::OptionParser::InvalidArgument,
      "#{key_file}: private key not found" unless key.private?
    key
  rescue Errno::ENOENT
    raise Gem::OptionParser::InvalidArgument, "#{key_file}: does not exist"
  rescue OpenSSL::PKey::PKeyError, ArgumentError
    raise Gem::OptionParser::InvalidArgument, "#{key_file}: invalid RSA, DSA, or EC key"
  end

  def execute
    check_openssl

    options[:add].each do |certificate|
      add_certificate certificate
    end

    options[:remove].each do |filter|
      remove_certificates_matching filter
    end

    options[:list].each do |filter|
      list_certificates_matching filter
    end

    options[:build].each do |email|
      build email
    end

    if options[:resign]
      re_sign_cert(
        options[:issuer_cert],
        options[:issuer_cert_file],
        options[:key]
      )
    end

    sign_certificates unless options[:sign].empty?
  end

  def build(email)
    if !valid_email?(email)
      raise Gem::CommandLineError, "Invalid email address #{email}"
    end

    key, key_path = build_key
    cert_path = build_cert email, key

    say "Certificate: #{cert_path}"

    if key_path
      say "Private Key: #{key_path}"
      say "Don't forget to move the key file to somewhere private!"
    end
  end

  def build_cert(email, key) # :nodoc:
    expiration_length_days = options[:expiration_length_days] ||
      Gem.configuration.cert_expiration_length_days

    cert = Gem::Security.create_cert_email(
      email,
      key,
      (Gem::Security::ONE_DAY * expiration_length_days)
    )

    Gem::Security.write cert, "gem-public_cert.pem"
  end

  def build_key # :nodoc:
    return options[:key] if options[:key]

    passphrase = ask_for_password 'Passphrase for your Private Key:'
    say "\n"

    passphrase_confirmation = ask_for_password 'Please repeat the passphrase for your Private Key:'
    say "\n"

    raise Gem::CommandLineError,
          "Passphrase and passphrase confirmation don't match" unless passphrase == passphrase_confirmation

    algorithm = options[:key_algorithm] || Gem::Security::DEFAULT_KEY_ALGORITHM
    key = Gem::Security.create_key(algorithm)
    key_path = Gem::Security.write key, "gem-private_key.pem", 0600, passphrase

    return key, key_path
  end

  def certificates_matching(filter)
    return enum_for __method__, filter unless block_given?

    Gem::Security.trusted_certificates.select do |certificate, _|
      subject = certificate.subject.to_s
      subject.downcase.index filter
    end.sort_by do |certificate, _|
      certificate.subject.to_a.map {|name, data,| [name, data] }
    end.each do |certificate, path|
      yield certificate, path
    end
  end

  def description # :nodoc:
    <<-EOF
The cert command manages signing keys and certificates for creating signed
gems.  Your signing certificate and private key are typically stored in
~/.gem/gem-public_cert.pem and ~/.gem/gem-private_key.pem respectively.

To build a certificate for signing gems:

  gem cert --build you@example

If you already have an RSA key, or are creating a new certificate for an
existing key:

  gem cert --build you@example --private-key /path/to/key.pem

If you wish to trust a certificate you can add it to the trust list with:

  gem cert --add /path/to/cert.pem

You can list trusted certificates with:

  gem cert --list

or:

  gem cert --list cert_subject_substring

If you wish to remove a previously trusted certificate:

  gem cert --remove cert_subject_substring

To sign another gem author's certificate:

  gem cert --sign /path/to/other_cert.pem

For further reading on signing gems see `ri Gem::Security`.
    EOF
  end

  def list_certificates_matching(filter) # :nodoc:
    certificates_matching filter do |certificate, _|
      # this could probably be formatted more gracefully
      say certificate.subject.to_s
    end
  end

  def load_default_cert
    cert_file = File.join Gem.default_cert_path
    cert = File.read cert_file
    options[:issuer_cert] = OpenSSL::X509::Certificate.new cert
  rescue Errno::ENOENT
    alert_error \
      "--certificate not specified and ~/.gem/gem-public_cert.pem does not exist"

    terminate_interaction 1
  rescue OpenSSL::X509::CertificateError
    alert_error \
      "--certificate not specified and ~/.gem/gem-public_cert.pem is not valid"

    terminate_interaction 1
  end

  def load_default_key
    key_file = File.join Gem.default_key_path
    key = File.read key_file
    passphrase = ENV['GEM_PRIVATE_KEY_PASSPHRASE']
    options[:key] = OpenSSL::PKey.read key, passphrase

  rescue Errno::ENOENT
    alert_error \
      "--private-key not specified and ~/.gem/gem-private_key.pem does not exist"

    terminate_interaction 1
  rescue OpenSSL::PKey::PKeyError
    alert_error \
      "--private-key not specified and ~/.gem/gem-private_key.pem is not valid"

    terminate_interaction 1
  end

  def load_defaults # :nodoc:
    load_default_cert unless options[:issuer_cert]
    load_default_key  unless options[:key]
  end

  def remove_certificates_matching(filter) # :nodoc:
    certificates_matching filter do |certificate, path|
      FileUtils.rm path
      say "Removed '#{certificate.subject}'"
    end
  end

  def sign(cert_file)
    cert = File.read cert_file
    cert = OpenSSL::X509::Certificate.new cert

    permissions = File.stat(cert_file).mode & 0777

    issuer_cert = options[:issuer_cert]
    issuer_key = options[:key]

    cert = Gem::Security.sign cert, issuer_key, issuer_cert

    Gem::Security.write cert, cert_file, permissions
  end

  def sign_certificates # :nodoc:
    load_defaults unless options[:sign].empty?

    options[:sign].each do |cert_file|
      sign cert_file
    end
  end

  def re_sign_cert(cert, cert_path, private_key)
    Gem::Security::Signer.re_sign_cert(cert, cert_path, private_key) do |expired_cert_path, new_expired_cert_path|
      alert("Your certificate #{expired_cert_path} has been re-signed")
      alert("Your expired certificate will be located at: #{new_expired_cert_path}")
    end
  end

  private

  def valid_email?(email)
    # It's simple, but is all we need
    email =~ /\A.+@.+\z/
  end
end
# frozen_string_literal: true
require_relative '../command'

##
# Installs RubyGems itself.  This command is ordinarily only available from a
# RubyGems checkout or tarball.

class Gem::Commands::SetupCommand < Gem::Command
  HISTORY_HEADER = /^#\s*[\d.a-zA-Z]+\s*\/\s*\d{4}-\d{2}-\d{2}\s*$/.freeze
  VERSION_MATCHER = /^#\s*([\d.a-zA-Z]+)\s*\/\s*\d{4}-\d{2}-\d{2}\s*$/.freeze

  ENV_PATHS = %w[/usr/bin/env /bin/env].freeze

  def initialize
    require 'tmpdir'

    super 'setup', 'Install RubyGems',
          :format_executable => false, :document => %w[ri],
          :force => true,
          :site_or_vendor => 'sitelibdir',
          :destdir => '', :prefix => '', :previous_version => '',
          :regenerate_binstubs => true,
          :regenerate_plugins => true

    add_option '--previous-version=VERSION',
               'Previous version of RubyGems',
               'Used for changelog processing' do |version, options|
      options[:previous_version] = version
    end

    add_option '--prefix=PREFIX',
               'Prefix path for installing RubyGems',
               'Will not affect gem repository location' do |prefix, options|
      options[:prefix] = File.expand_path prefix
    end

    add_option '--destdir=DESTDIR',
               'Root directory to install RubyGems into',
               'Mainly used for packaging RubyGems' do |destdir, options|
      options[:destdir] = File.expand_path destdir
    end

    add_option '--[no-]vendor',
               'Install into vendorlibdir not sitelibdir' do |vendor, options|
      options[:site_or_vendor] = vendor ? 'vendorlibdir' : 'sitelibdir'
    end

    add_option '--[no-]format-executable',
               'Makes `gem` match ruby',
               'If Ruby is ruby18, gem will be gem18' do |value, options|
      options[:format_executable] = value
    end

    add_option '--[no-]document [TYPES]', Array,
               'Generate documentation for RubyGems',
               'List the documentation types you wish to',
               'generate.  For example: rdoc,ri' do |value, options|
      options[:document] = case value
                           when nil   then %w[rdoc ri]
                           when false then []
                           else            value
                           end
    end

    add_option '--[no-]rdoc',
               'Generate RDoc documentation for RubyGems' do |value, options|
      if value
        options[:document] << 'rdoc'
      else
        options[:document].delete 'rdoc'
      end

      options[:document].uniq!
    end

    add_option '--[no-]ri',
               'Generate RI documentation for RubyGems' do |value, options|
      if value
        options[:document] << 'ri'
      else
        options[:document].delete 'ri'
      end

      options[:document].uniq!
    end

    add_option '--[no-]regenerate-binstubs',
               'Regenerate gem binstubs' do |value, options|
      options[:regenerate_binstubs] = value
    end

    add_option '--[no-]regenerate-plugins',
               'Regenerate gem plugins' do |value, options|
      options[:regenerate_plugins] = value
    end

    add_option '-f', '--[no-]force',
               'Forcefully overwrite binstubs' do |value, options|
      options[:force] = value
    end

    add_option('-E', '--[no-]env-shebang',
               'Rewrite executables with a shebang',
               'of /usr/bin/env') do |value, options|
      options[:env_shebang] = value
    end

    @verbose = nil
  end

  def check_ruby_version
    required_version = Gem::Requirement.new '>= 2.3.0'

    unless required_version.satisfied_by? Gem.ruby_version
      alert_error "Expected Ruby version #{required_version}, is #{Gem.ruby_version}"
      terminate_interaction 1
    end
  end

  def defaults_str # :nodoc:
    "--format-executable --document ri --regenerate-binstubs"
  end

  def description # :nodoc:
    <<-EOF
Installs RubyGems itself.

RubyGems installs RDoc for itself in GEM_HOME.  By default this is:
  #{Gem.dir}

If you prefer a different directory, set the GEM_HOME environment variable.

RubyGems will install the gem command with a name matching ruby's
prefix and suffix.  If ruby was installed as `ruby18`, gem will be
installed as `gem18`.

By default, this RubyGems will install gem as:
  #{Gem.default_exec_format % 'gem'}
    EOF
  end

  module MakeDirs
    def mkdir_p(path, **opts)
      super
      (@mkdirs ||= []) << path
    end
  end

  def execute
    @verbose = Gem.configuration.really_verbose

    check_ruby_version

    require 'fileutils'
    if Gem.configuration.really_verbose
      extend FileUtils::Verbose
    else
      extend FileUtils
    end
    extend MakeDirs

    lib_dir, bin_dir = make_destination_dirs
    man_dir = generate_default_man_dir

    install_lib lib_dir

    install_executables bin_dir

    remove_old_bin_files bin_dir

    remove_old_lib_files lib_dir

    # Can be removed one we drop support for bundler 2.2.3 (the last version installing man files to man_dir)
    remove_old_man_files man_dir if man_dir && File.exist?(man_dir)

    install_default_bundler_gem bin_dir

    if mode = options[:dir_mode]
      @mkdirs.uniq!
      File.chmod(mode, @mkdirs)
    end

    say "RubyGems #{Gem::VERSION} installed"

    regenerate_binstubs(bin_dir) if options[:regenerate_binstubs]
    regenerate_plugins(bin_dir) if options[:regenerate_plugins]

    uninstall_old_gemcutter

    documentation_success = install_rdoc

    say
    if @verbose
      say "-" * 78
      say
    end

    if options[:previous_version].empty?
      options[:previous_version] = Gem::VERSION.sub(/[0-9]+$/, '0')
    end

    options[:previous_version] = Gem::Version.new(options[:previous_version])

    show_release_notes

    say
    say "-" * 78
    say

    say "RubyGems installed the following executables:"
    say bin_file_names.map {|name| "\t#{name}\n" }
    say

    unless bin_file_names.grep(/#{File::SEPARATOR}gem$/)
      say "If `gem` was installed by a previous RubyGems installation, you may need"
      say "to remove it by hand."
      say
    end

    if documentation_success
      if options[:document].include? 'rdoc'
        say "Rdoc documentation was installed. You may now invoke:"
        say "  gem server"
        say "and then peruse beautifully formatted documentation for your gems"
        say "with your web browser."
        say "If you do not wish to install this documentation in the future, use the"
        say "--no-document flag, or set it as the default in your ~/.gemrc file. See"
        say "'gem help env' for details."
        say
      end

      if options[:document].include? 'ri'
        say "Ruby Interactive (ri) documentation was installed. ri is kind of like man "
        say "pages for Ruby libraries. You may access it like this:"
        say "  ri Classname"
        say "  ri Classname.class_method"
        say "  ri Classname#instance_method"
        say "If you do not wish to install this documentation in the future, use the"
        say "--no-document flag, or set it as the default in your ~/.gemrc file. See"
        say "'gem help env' for details."
        say
      end
    end
  end

  def install_executables(bin_dir)
    prog_mode = options[:prog_mode] || 0755

    executables = { 'gem' => 'bin' }
    executables.each do |tool, path|
      say "Installing #{tool} executable" if @verbose

      Dir.chdir path do
        bin_file = "gem"

        dest_file = target_bin_path(bin_dir, bin_file)
        bin_tmp_file = File.join Dir.tmpdir, "#{bin_file}.#{$$}"

        begin
          bin = File.readlines bin_file
          bin[0] = shebang

          File.open bin_tmp_file, 'w' do |fp|
            fp.puts bin.join
          end

          install bin_tmp_file, dest_file, :mode => prog_mode
          bin_file_names << dest_file
        ensure
          rm bin_tmp_file
        end

        next unless Gem.win_platform?

        begin
          bin_cmd_file = File.join Dir.tmpdir, "#{bin_file}.bat"

          File.open bin_cmd_file, 'w' do |file|
            file.puts <<-TEXT
  @ECHO OFF
  IF NOT "%~f0" == "~f0" GOTO :WinNT
  @"#{File.basename(Gem.ruby).chomp('"')}" "#{dest_file}" %1 %2 %3 %4 %5 %6 %7 %8 %9
  GOTO :EOF
  :WinNT
  @"#{File.basename(Gem.ruby).chomp('"')}" "%~dpn0" %*
  TEXT
          end

          install bin_cmd_file, "#{dest_file}.bat", :mode => prog_mode
        ensure
          rm bin_cmd_file
        end
      end
    end
  end

  def shebang
    if options[:env_shebang]
      ruby_name = RbConfig::CONFIG['ruby_install_name']
      @env_path ||= ENV_PATHS.find {|env_path| File.executable? env_path }
      "#!#{@env_path} #{ruby_name}\n"
    else
      "#!#{Gem.ruby}\n"
    end
  end

  def install_lib(lib_dir)
    libs = { 'RubyGems' => 'lib' }
    libs['Bundler'] = 'bundler/lib'
    libs.each do |tool, path|
      say "Installing #{tool}" if @verbose

      lib_files = files_in path

      Dir.chdir path do
        install_file_list(lib_files, lib_dir)
      end
    end
  end

  def install_rdoc
    gem_doc_dir = File.join Gem.dir, 'doc'
    rubygems_name = "rubygems-#{Gem::VERSION}"
    rubygems_doc_dir = File.join gem_doc_dir, rubygems_name

    begin
      Gem.ensure_gem_subdirectories Gem.dir
    rescue SystemCallError
      # ignore
    end

    if File.writable? gem_doc_dir and
       (not File.exist? rubygems_doc_dir or
        File.writable? rubygems_doc_dir)
      say "Removing old RubyGems RDoc and ri" if @verbose
      Dir[File.join(Gem.dir, 'doc', 'rubygems-[0-9]*')].each do |dir|
        rm_rf dir
      end

      require_relative '../rdoc'

      fake_spec = Gem::Specification.new 'rubygems', Gem::VERSION
      def fake_spec.full_gem_path
        File.expand_path '../../../..', __FILE__
      end

      generate_ri   = options[:document].include? 'ri'
      generate_rdoc = options[:document].include? 'rdoc'

      rdoc = Gem::RDoc.new fake_spec, generate_rdoc, generate_ri
      rdoc.generate

      return true
    elsif @verbose
      say "Skipping RDoc generation, #{gem_doc_dir} not writable"
      say "Set the GEM_HOME environment variable if you want RDoc generated"
    end

    return false
  end

  def install_default_bundler_gem(bin_dir)
    specs_dir = File.join(default_dir, "specifications", "default")
    mkdir_p specs_dir, :mode => 0755

    bundler_spec = Dir.chdir("bundler") { Gem::Specification.load("bundler.gemspec") }

    # Remove bundler-*.gemspec in default specification directory.
    Dir.entries(specs_dir).
      select {|gs| gs.start_with?("bundler-") }.
      each {|gs| File.delete(File.join(specs_dir, gs)) }

    default_spec_path = File.join(specs_dir, "#{bundler_spec.full_name}.gemspec")
    Gem.write_binary(default_spec_path, bundler_spec.to_ruby)

    bundler_spec = Gem::Specification.load(default_spec_path)

    # The base_dir value for a specification is inferred by walking up from the
    # folder where the spec was `loaded_from`. In the case of default gems, we
    # walk up two levels, because they live at `specifications/default/`, whereas
    # in the case of regular gems we walk up just one level because they live at
    # `specifications/`. However, in this case, the gem we are installing is
    # misdetected as a regular gem, when it's a default gem in reality. This is
    # because when there's a `:destdir`, the `loaded_from` path has changed and
    # doesn't match `Gem.default_specifications_dir` which is the criteria to
    # tag a gem as a default gem. So, in that case, write the correct
    # `@base_dir` directly.
    bundler_spec.instance_variable_set(:@base_dir, File.dirname(File.dirname(specs_dir)))

    # Remove gemspec that was same version of vendored bundler.
    normal_gemspec = File.join(default_dir, "specifications", "bundler-#{bundler_spec.version}.gemspec")
    if File.file? normal_gemspec
      File.delete normal_gemspec
    end

    # Remove gem files that were same version of vendored bundler.
    if File.directory? bundler_spec.gems_dir
      Dir.entries(bundler_spec.gems_dir).
        select {|default_gem| File.basename(default_gem) == "bundler-#{bundler_spec.version}" }.
        each {|default_gem| rm_r File.join(bundler_spec.gems_dir, default_gem) }
    end

    bundler_bin_dir = bundler_spec.bin_dir
    mkdir_p bundler_bin_dir, :mode => 0755
    bundler_spec.executables.each do |e|
      cp File.join("bundler", bundler_spec.bindir, e), File.join(bundler_bin_dir, e)
    end

    require_relative '../installer'

    Dir.chdir("bundler") do
      built_gem = Gem::Package.build(bundler_spec)
      begin
        Gem::Installer.at(
          built_gem,
          env_shebang: options[:env_shebang],
          format_executable: options[:format_executable],
          force: options[:force],
          install_as_default: true,
          bin_dir: bin_dir,
          install_dir: default_dir,
          wrappers: true
        ).install
      ensure
        FileUtils.rm_f built_gem
      end
    end

    bundler_spec.executables.each {|executable| bin_file_names << target_bin_path(bin_dir, executable) }

    say "Bundler #{bundler_spec.version} installed"
  end

  def make_destination_dirs
    lib_dir, bin_dir = Gem.default_rubygems_dirs

    unless lib_dir
      lib_dir, bin_dir = generate_default_dirs
    end

    mkdir_p lib_dir, :mode => 0755
    mkdir_p bin_dir, :mode => 0755

    return lib_dir, bin_dir
  end

  def generate_default_man_dir
    prefix = options[:prefix]

    if prefix.empty?
      man_dir = RbConfig::CONFIG['mandir']
      return unless man_dir
    else
      man_dir = File.join prefix, 'man'
    end

    prepend_destdir_if_present(man_dir)
  end

  def generate_default_dirs
    prefix = options[:prefix]
    site_or_vendor = options[:site_or_vendor]

    if prefix.empty?
      lib_dir = RbConfig::CONFIG[site_or_vendor]
      bin_dir = RbConfig::CONFIG['bindir']
    else
      # Apple installed RubyGems into libdir, and RubyGems <= 1.1.0 gets
      # confused about installation location, so switch back to
      # sitelibdir/vendorlibdir.
      if defined?(APPLE_GEM_HOME) and
        # just in case Apple and RubyGems don't get this patched up proper.
        (prefix == RbConfig::CONFIG['libdir'] or
         # this one is important
         prefix == File.join(RbConfig::CONFIG['libdir'], 'ruby'))
        lib_dir = RbConfig::CONFIG[site_or_vendor]
        bin_dir = RbConfig::CONFIG['bindir']
      else
        lib_dir = File.join prefix, 'lib'
        bin_dir = File.join prefix, 'bin'
      end
    end

    [prepend_destdir_if_present(lib_dir), prepend_destdir_if_present(bin_dir)]
  end

  def files_in(dir)
    Dir.chdir dir do
      Dir.glob(File.join('**', '*'), File::FNM_DOTMATCH).
        select{|f| !File.directory?(f) }
    end
  end

  def remove_old_bin_files(bin_dir)
    old_bin_files = {
      'gem_mirror' => 'gem mirror',
      'gem_server' => 'gem server',
      'gemlock' => 'gem lock',
      'gemri' => 'ri',
      'gemwhich' => 'gem which',
      'index_gem_repository.rb' => 'gem generate_index',
    }

    old_bin_files.each do |old_bin_file, new_name|
      old_bin_path = File.join bin_dir, old_bin_file
      next unless File.exist? old_bin_path

      deprecation_message = "`#{old_bin_file}` has been deprecated. Use `#{new_name}` instead."

      File.open old_bin_path, 'w' do |fp|
        fp.write <<-EOF
#!#{Gem.ruby}

abort "#{deprecation_message}"
    EOF
      end

      next unless Gem.win_platform?

      File.open "#{old_bin_path}.bat", 'w' do |fp|
        fp.puts %(@ECHO.#{deprecation_message})
      end
    end
  end

  def remove_old_lib_files(lib_dir)
    lib_dirs = { File.join(lib_dir, 'rubygems') => 'lib/rubygems' }
    lib_dirs[File.join(lib_dir, 'bundler')] = 'bundler/lib/bundler'
    lib_dirs.each do |old_lib_dir, new_lib_dir|
      lib_files = files_in(new_lib_dir)

      old_lib_files = files_in(old_lib_dir)

      to_remove = old_lib_files - lib_files

      gauntlet_rubygems = File.join(lib_dir, 'gauntlet_rubygems.rb')
      to_remove << gauntlet_rubygems if File.exist? gauntlet_rubygems

      to_remove.delete_if do |file|
        file.start_with? 'defaults'
      end

      remove_file_list(to_remove, old_lib_dir)
    end
  end

  def remove_old_man_files(old_man_dir)
    old_man1_dir = "#{old_man_dir}/man1"

    if File.exist?(old_man1_dir)
      man1_to_remove = Dir.chdir(old_man1_dir) { Dir["bundle*.1{,.txt,.ronn}"] }

      remove_file_list(man1_to_remove, old_man1_dir)
    end

    old_man5_dir = "#{old_man_dir}/man5"

    if File.exist?(old_man5_dir)
      man5_to_remove = Dir.chdir(old_man5_dir) { Dir["gemfile.5{,.txt,.ronn}"] }

      remove_file_list(man5_to_remove, old_man5_dir)
    end
  end

  def show_release_notes
    release_notes = File.join Dir.pwd, 'CHANGELOG.md'

    release_notes =
      if File.exist? release_notes
        history = File.read release_notes

        history.force_encoding Encoding::UTF_8

        text = history.split(HISTORY_HEADER)
        text.shift # correct an off-by-one generated by split
        version_lines = history.scan(HISTORY_HEADER)
        versions = history.scan(VERSION_MATCHER).flatten.map do |x|
          Gem::Version.new(x)
        end

        history_string = ""

        until versions.length == 0 or
              versions.shift <= options[:previous_version] do
          history_string += version_lines.shift + text.shift
        end

        history_string
      else
        "Oh-no! Unable to find release notes!"
      end

    say release_notes
  end

  def uninstall_old_gemcutter
    require_relative '../uninstaller'

    ui = Gem::Uninstaller.new('gemcutter', :all => true, :ignore => true,
                              :version => '< 0.4')
    ui.uninstall
  rescue Gem::InstallError
  end

  def regenerate_binstubs(bindir)
    require_relative "pristine_command"
    say "Regenerating binstubs"

    args = %w[--all --only-executables --silent]
    args << "--bindir=#{bindir}"
    if options[:env_shebang]
      args << "--env-shebang"
    end

    command = Gem::Commands::PristineCommand.new
    command.invoke(*args)
  end

  def regenerate_plugins(bindir)
    require_relative "pristine_command"
    say "Regenerating plugins"

    args = %w[--all --only-plugins --silent]
    args << "--bindir=#{bindir}"
    args << "--install-dir=#{default_dir}"

    command = Gem::Commands::PristineCommand.new
    command.invoke(*args)
  end

  private

  def default_dir
    prefix = options[:prefix]

    if prefix.empty?
      dir = Gem.default_dir
    else
      dir = prefix
    end

    prepend_destdir_if_present(dir)
  end

  def prepend_destdir_if_present(path)
    destdir = options[:destdir]
    return path if destdir.empty?

    File.join(options[:destdir], path.gsub(/^[a-zA-Z]:/, ''))
  end

  def install_file_list(files, dest_dir)
    files.each do |file|
      install_file file, dest_dir
    end
  end

  def install_file(file, dest_dir)
    dest_file = File.join dest_dir, file
    dest_dir = File.dirname dest_file
    unless File.directory? dest_dir
      mkdir_p dest_dir, :mode => 0755
    end

    install file, dest_file, :mode => options[:data_mode] || 0644
  end

  def remove_file_list(files, dir)
    Dir.chdir dir do
      files.each do |file|
        FileUtils.rm_f file

        warn "unable to remove old file #{file} please remove it by hand" if
          File.exist? file
      end
    end
  end

  def target_bin_path(bin_dir, bin_file)
    bin_file_formatted = if options[:format_executable]
                           Gem.default_exec_format % bin_file
                         else
                           bin_file
                         end
    File.join bin_dir, bin_file_formatted
  end

  def bin_file_names
    @bin_file_names ||= []
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../local_remote_options'
require_relative '../gemcutter_utilities'
require_relative '../package'

class Gem::Commands::PushCommand < Gem::Command
  include Gem::LocalRemoteOptions
  include Gem::GemcutterUtilities

  def description # :nodoc:
    <<-EOF
The push command uploads a gem to the push server (the default is
https://rubygems.org) and adds it to the index.

The gem can be removed from the index and deleted from the server using the yank
command.  For further discussion see the help for the yank command.

The push command will use ~/.gem/credentials to authenticate to a server, but you can use the RubyGems environment variable GEM_HOST_API_KEY to set the api key to authenticate.
    EOF
  end

  def arguments # :nodoc:
    "GEM       built gem to push up"
  end

  def usage # :nodoc:
    "#{program_name} GEM"
  end

  def initialize
    super 'push', 'Push a gem up to the gem server', :host => self.host

    @user_defined_host = false

    add_proxy_option
    add_key_option
    add_otp_option

    add_option('--host HOST',
               'Push to another gemcutter-compatible host',
               '  (e.g. https://rubygems.org)') do |value, options|
      options[:host] = value
      @user_defined_host = true
    end

    @host = nil
  end

  def execute
    gem_name = get_one_gem_name
    default_gem_server, push_host = get_hosts_for(gem_name)

    @host = if @user_defined_host
              options[:host]
            elsif default_gem_server
              default_gem_server
            elsif push_host
              push_host
            else
              options[:host]
            end

    sign_in @host, scope: get_push_scope

    send_gem(gem_name)
  end

  def send_gem(name)
    args = [:post, "api/v1/gems"]

    _, push_host = get_hosts_for(name)

    @host ||= push_host

    # Always include @host, even if it's nil
    args += [ @host, push_host ]

    say "Pushing gem to #{@host || Gem.host}..."

    response = send_push_request(name, args)

    with_response response
  end

  private

  def send_push_request(name, args)
    rubygems_api_request(*args, scope: get_push_scope) do |request|
      request.body = Gem.read_binary name
      request.add_field "Content-Length", request.body.size
      request.add_field "Content-Type",   "application/octet-stream"
      request.add_field "Authorization",  api_key
    end
  end

  def get_hosts_for(name)
    gem_metadata = Gem::Package.new(name).spec.metadata

    [
      gem_metadata["default_gem_server"],
      gem_metadata["allowed_push_host"],
    ]
  end

  def get_push_scope
    :push_rubygem
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../query_utils'

##
# Searches for gems starting with the supplied argument.

class Gem::Commands::ListCommand < Gem::Command
  include Gem::QueryUtils

  def initialize
    super 'list', 'Display local gems whose name matches REGEXP',
         :name => //, :domain => :local, :details => false, :versions => true,
         :installed => nil, :version => Gem::Requirement.default

    add_query_options
  end

  def arguments # :nodoc:
    "REGEXP        regexp to look for in gem name"
  end

  def defaults_str # :nodoc:
    "--local --no-details"
  end

  def description # :nodoc:
    <<-EOF
The list command is used to view the gems you have installed locally.

The --details option displays additional details including the summary, the
homepage, the author, the locations of different versions of the gem.

To search for remote gems use the search command.
    EOF
  end

  def usage # :nodoc:
    "#{program_name} [REGEXP ...]"
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../version_option'

class Gem::Commands::OpenCommand < Gem::Command
  include Gem::VersionOption

  def initialize
    super 'open', 'Open gem sources in editor'

    add_option('-e', '--editor COMMAND', String,
               "Prepends COMMAND to gem path. Could be used to specify editor.") do |command, options|
      options[:editor] = command || get_env_editor
    end
    add_option('-v', '--version VERSION', String,
               "Opens specific gem version") do |version|
      options[:version] = version
    end
  end

  def arguments # :nodoc:
    "GEMNAME     name of gem to open in editor"
  end

  def defaults_str # :nodoc:
    "-e #{get_env_editor}"
  end

  def description # :nodoc:
    <<-EOF
        The open command opens gem in editor and changes current path
        to gem's source directory.
        Editor command can be specified with -e option, otherwise rubygems
        will look for editor in $EDITOR, $VISUAL and $GEM_EDITOR variables.
    EOF
  end

  def usage # :nodoc:
    "#{program_name} [-e COMMAND] GEMNAME"
  end

  def get_env_editor
    ENV['GEM_EDITOR'] ||
      ENV['VISUAL'] ||
      ENV['EDITOR'] ||
      'vi'
  end

  def execute
    @version = options[:version] || Gem::Requirement.default
    @editor  = options[:editor] || get_env_editor

    found = open_gem(get_one_gem_name)

    terminate_interaction 1 unless found
  end

  def open_gem(name)
    spec = spec_for name

    return false unless spec

    if spec.default_gem?
      say "'#{name}' is a default gem and can't be opened."
      return false
    end

    open_editor(spec.full_gem_path)
  end

  def open_editor(path)
    Dir.chdir(path) do
      system(*@editor.split(/\s+/) + [path])
    end
  end

  def spec_for(name)
    spec = Gem::Specification.find_all_by_name(name, @version).first

    return spec if spec

    say "Unable to find gem '#{name}'"
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../version_option'
require_relative '../uninstaller'
require 'fileutils'

##
# Gem uninstaller command line tool
#
# See `gem help uninstall`

class Gem::Commands::UninstallCommand < Gem::Command
  include Gem::VersionOption

  def initialize
    super 'uninstall', 'Uninstall gems from the local repository',
          :version => Gem::Requirement.default, :user_install => true,
          :check_dev => false, :vendor => false

    add_option('-a', '--[no-]all',
      'Uninstall all matching versions'
    ) do |value, options|
      options[:all] = value
    end

    add_option('-I', '--[no-]ignore-dependencies',
               'Ignore dependency requirements while',
               'uninstalling') do |value, options|
      options[:ignore] = value
    end

    add_option('-D', '--[no-]check-development',
               'Check development dependencies while uninstalling',
               '(default: false)') do |value, options|
      options[:check_dev] = value
    end

    add_option('-x', '--[no-]executables',
                 'Uninstall applicable executables without',
                 'confirmation') do |value, options|
      options[:executables] = value
    end

    add_option('-i', '--install-dir DIR',
               'Directory to uninstall gem from') do |value, options|
      options[:install_dir] = File.expand_path(value)
    end

    add_option('-n', '--bindir DIR',
               'Directory to remove executables from') do |value, options|
      options[:bin_dir] = File.expand_path(value)
    end

    add_option('--[no-]user-install',
               'Uninstall from user\'s home directory',
               'in addition to GEM_HOME.') do |value, options|
      options[:user_install] = value
    end

    add_option('--[no-]format-executable',
               'Assume executable names match Ruby\'s prefix and suffix.') do |value, options|
      options[:format_executable] = value
    end

    add_option('--[no-]force',
               'Uninstall all versions of the named gems',
               'ignoring dependencies') do |value, options|
      options[:force] = value
    end

    add_option('--[no-]abort-on-dependent',
               'Prevent uninstalling gems that are',
               'depended on by other gems.') do |value, options|
      options[:abort_on_dependent] = value
    end

    add_version_option
    add_platform_option

    add_option('--vendor',
               'Uninstall gem from the vendor directory.',
               'Only for use by gem repackagers.') do |value, options|
      unless Gem.vendor_dir
        raise Gem::OptionParser::InvalidOption.new 'your platform is not supported'
      end

      alert_warning 'Use your OS package manager to uninstall vendor gems'
      options[:vendor] = true
      options[:install_dir] = Gem.vendor_dir
    end
  end

  def arguments # :nodoc:
    "GEMNAME       name of gem to uninstall"
  end

  def defaults_str # :nodoc:
    "--version '#{Gem::Requirement.default}' --no-force " +
    "--user-install"
  end

  def description # :nodoc:
    <<-EOF
The uninstall command removes a previously installed gem.

RubyGems will ask for confirmation if you are attempting to uninstall a gem
that is a dependency of an existing gem.  You can use the
--ignore-dependencies option to skip this check.
    EOF
  end

  def usage # :nodoc:
    "#{program_name} GEMNAME [GEMNAME ...]"
  end

  def check_version # :nodoc:
    if options[:version] != Gem::Requirement.default and
         get_all_gem_names.size > 1
      alert_error "Can't use --version with multiple gems. You can specify multiple gems with" \
                  " version requirements using `gem uninstall 'my_gem:1.0.0' 'my_other_gem:~>2.0.0'`"
      terminate_interaction 1
    end
  end

  def execute
    check_version

    if options[:all] and not options[:args].empty?
      uninstall_specific
    elsif options[:all]
      uninstall_all
    else
      uninstall_specific
    end
  end

  def uninstall_all
    specs = Gem::Specification.reject {|spec| spec.default_gem? }

    specs.each do |spec|
      options[:version] = spec.version
      uninstall_gem spec.name
    end

    alert "Uninstalled all gems in #{options[:install_dir] || Gem.dir}"
  end

  def uninstall_specific
    deplist = Gem::DependencyList.new
    original_gem_version = {}

    get_all_gem_names_and_versions.each do |name, version|
      original_gem_version[name] = version || options[:version]

      gem_specs = Gem::Specification.find_all_by_name(name, original_gem_version[name])

      say("Gem '#{name}' is not installed") if gem_specs.empty?
      gem_specs.each do |spec|
        deplist.add spec
      end
    end

    deps = deplist.strongly_connected_components.flatten.reverse

    gems_to_uninstall = {}

    deps.each do |dep|
      unless gems_to_uninstall[dep.name]
        gems_to_uninstall[dep.name] = true

        unless original_gem_version[dep.name] == Gem::Requirement.default
          options[:version] = dep.version
        end

        uninstall_gem(dep.name)
      end
    end
  end

  def uninstall_gem(gem_name)
    uninstall(gem_name)
  rescue Gem::GemNotInHomeException => e
    spec = e.spec
    alert("In order to remove #{spec.name}, please execute:\n" +
          "\tgem uninstall #{spec.name} --install-dir=#{spec.installation_path}")
  rescue Gem::UninstallError => e
    spec = e.spec
    alert_error("Error: unable to successfully uninstall '#{spec.name}' which is " +
          "located at '#{spec.full_gem_path}'. This is most likely because" +
          "the current user does not have the appropriate permissions")
    terminate_interaction 1
  end

  def uninstall(gem_name)
    Gem::Uninstaller.new(gem_name, options).uninstall
  end
end
# frozen_string_literal: true
require_relative '../command'
require_relative '../server'
require_relative '../deprecate'

class Gem::Commands::ServerCommand < Gem::Command
  extend Gem::Deprecate
  rubygems_deprecate_command

  def initialize
    super 'server', 'Documentation and gem repository HTTP server',
          :port => 8808, :gemdir => [], :daemon => false

    Gem::OptionParser.accept :Port do |port|
      if port =~ /\A\d+\z/
        port = Integer port
        raise Gem::OptionParser::InvalidArgument, "#{port}: not a port number" if
          port > 65535

        port
      else
        begin
          Socket.getservbyname port
        rescue SocketError
          raise Gem::OptionParser::InvalidArgument, "#{port}: no such named service"
        end
      end
    end

    add_option '-p', '--port=PORT', :Port,
               'port to listen on' do |port, options|
      options[:port] = port
    end

    add_option '-d', '--dir=GEMDIR',
               'directories from which to serve gems',
               'multiple directories may be provided' do |gemdir, options|
      options[:gemdir] << File.expand_path(gemdir)
    end

    add_option '--[no-]daemon', 'run as a daemon' do |daemon, options|
      options[:daemon] = daemon
    end

    add_option '-b', '--bind=HOST,HOST',
               'addresses to bind', Array do |address, options|
      options[:addresses] ||= []
      options[:addresses].push(*address)
    end

    add_option '-l', '--launch[=COMMAND]',
               'launches a browser window',
               "COMMAND defaults to 'start' on Windows",
               "and 'open' on all other platforms" do |launch, options|
      launch ||= Gem.win_platform? ? 'start' : 'open'
      options[:launch] = launch
    end
  end

  def defaults_str # :nodoc:
    "--port 8808 --dir #{Gem.dir} --no-daemon"
  end

  def description # :nodoc:
    <<-EOF
The server command starts up a web server that hosts the RDoc for your
installed gems and can operate as a server for installation of gems on other
machines.

The cache files for installed gems must exist to use the server as a source
for gem installation.

To install gems from a running server, use `gem install GEMNAME --source
http://gem_server_host:8808`

You can set up a shortcut to gem server documentation using the URL:

  http://localhost:8808/rdoc?q=%s - Firefox
  http://localhost:8808/rdoc?q=* - LaunchBar

    EOF
  end

  def execute
    options[:gemdir] = Gem.path if options[:gemdir].empty?
    Gem::Server.run options
  end
end
# frozen_string_literal: true
require_relative '../command'

class Gem::Commands::LockCommand < Gem::Command
  def initialize
    super 'lock', 'Generate a lockdown list of gems',
          :strict => false

    add_option '-s', '--[no-]strict',
               'fail if unable to satisfy a dependency' do |strict, options|
      options[:strict] = strict
    end
  end

  def arguments # :nodoc:
    "GEMNAME       name of gem to lock\nVERSION       version of gem to lock"
  end

  def defaults_str # :nodoc:
    "--no-strict"
  end

  def description # :nodoc:
    <<-EOF
The lock command will generate a list of +gem+ statements that will lock down
the versions for the gem given in the command line.  It will specify exact
versions in the requirements list to ensure that the gems loaded will always
be consistent.  A full recursive search of all effected gems will be
generated.

Example:

  gem lock rails-1.0.0 > lockdown.rb

will produce in lockdown.rb:

  require "rubygems"
  gem 'rails', '= 1.0.0'
  gem 'rake', '= 0.7.0.1'
  gem 'activesupport', '= 1.2.5'
  gem 'activerecord', '= 1.13.2'
  gem 'actionpack', '= 1.11.2'
  gem 'actionmailer', '= 1.1.5'
  gem 'actionwebservice', '= 1.0.0'

Just load lockdown.rb from your application to ensure that the current
versions are loaded.  Make sure that lockdown.rb is loaded *before* any
other require statements.

Notice that rails 1.0.0 only requires that rake 0.6.2 or better be used.
Rake-0.7.0.1 is the most recent version installed that satisfies that, so we
lock it down to the exact version.
    EOF
  end

  def usage # :nodoc:
    "#{program_name} GEMNAME-VERSION [GEMNAME-VERSION ...]"
  end

  def complain(message)
    if options[:strict]
      raise Gem::Exception, message
    else
      say "# #{message}"
    end
  end

  def execute
    say "require 'rubygems'"

    locked = {}

    pending = options[:args]

    until pending.empty? do
      full_name = pending.shift

      spec = Gem::Specification.load spec_path(full_name)

      if spec.nil?
        complain "Could not find gem #{full_name}, try using the full name"
        next
      end

      say "gem '#{spec.name}', '= #{spec.version}'" unless locked[spec.name]
      locked[spec.name] = true

      spec.runtime_dependencies.each do |dep|
        next if locked[dep.name]
        candidates = dep.matching_specs

        if candidates.empty?
          complain "Unable to satisfy '#{dep}' from currently installed gems"
        else
          pending << candidates.last.full_name
        end
      end
    end
  end

  def spec_path(gem_full_name)
    gemspecs = Gem.path.map do |path|
      File.join path, "specifications", "#{gem_full_name}.gemspec"
    end

    gemspecs.find {|path| File.exist? path }
  end
end
# frozen_string_literal: true
require_relative '../command'

class Gem::Commands::WhichCommand < Gem::Command
  def initialize
    super 'which', 'Find the location of a library file you can require',
          :search_gems_first => false, :show_all => false

    add_option '-a', '--[no-]all', 'show all matching files' do |show_all, options|
      options[:show_all] = show_all
    end

    add_option '-g', '--[no-]gems-first',
               'search gems before non-gems' do |gems_first, options|
      options[:search_gems_first] = gems_first
    end
  end

  def arguments # :nodoc:
    "FILE          name of file to find"
  end

  def defaults_str # :nodoc:
    "--no-gems-first --no-all"
  end

  def description # :nodoc:
    <<-EOF
The which command is like the shell which command and shows you where
the file you wish to require lives.

You can use the which command to help determine why you are requiring a
version you did not expect or to look at the content of a file you are
requiring to see why it does not behave as you expect.
    EOF
  end

  def execute
    found = true

    options[:args].each do |arg|
      arg = arg.sub(/#{Regexp.union(*Gem.suffixes)}$/, '')
      dirs = $LOAD_PATH

      spec = Gem::Specification.find_by_path arg

      if spec
        if options[:search_gems_first]
          dirs = spec.full_require_paths + $LOAD_PATH
        else
          dirs = $LOAD_PATH + spec.full_require_paths
        end
      end

      paths = find_paths arg, dirs

      if paths.empty?
        alert_error "Can't find Ruby library file or shared library #{arg}"
        found = false
      else
        say paths
      end
    end

    terminate_interaction 1 unless found
  end

  def find_paths(package_name, dirs)
    result = []

    dirs.each do |dir|
      Gem.suffixes.each do |ext|
        full_path = File.join dir, "#{package_name}#{ext}"
        if File.exist? full_path and not File.directory? full_path
          result << full_path
          return result unless options[:show_all]
        end
      end
    end

    result
  end

  def usage # :nodoc:
    "#{program_name} FILE [FILE ...]"
  end
end
# frozen_string_literal: true
module Gem
  if defined? ::Psych::Visitors
    class NoAliasYAMLTree < Psych::Visitors::YAMLTree
      def self.create
        new({})
      end unless respond_to? :create

      def visit_String(str)
        return super unless str == '=' # or whatever you want

        quote = Psych::Nodes::Scalar::SINGLE_QUOTED
        @emitter.scalar str, nil, nil, false, true, quote
      end

      # Noop this out so there are no anchors
      def register(target, obj)
      end

      # This is ported over from the yaml_tree in 1.9.3
      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

      private :format_time
    end
  end
end
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require_relative 'installer_uninstaller_utils'
require_relative 'exceptions'
require_relative 'deprecate'
require_relative 'package'
require_relative 'ext'
require_relative 'user_interaction'

##
# The installer installs the files contained in the .gem into the Gem.home.
#
# Gem::Installer does the work of putting files in all the right places on the
# filesystem including unpacking the gem into its gem dir, installing the
# gemspec in the specifications dir, storing the cached gem in the cache dir,
# and installing either wrappers or symlinks for executables.
#
# The installer invokes pre and post install hooks.  Hooks can be added either
# through a rubygems_plugin.rb file in an installed gem or via a
# rubygems/defaults/#{RUBY_ENGINE}.rb or rubygems/defaults/operating_system.rb
# file.  See Gem.pre_install and Gem.post_install for details.

class Gem::Installer
  extend Gem::Deprecate

  ##
  # Paths where env(1) might live.  Some systems are broken and have it in
  # /bin

  ENV_PATHS = %w[/usr/bin/env /bin/env].freeze

  ##
  # Deprecated in favor of Gem::Ext::BuildError

  ExtensionBuildError = Gem::Ext::BuildError # :nodoc:

  include Gem::UserInteraction

  include Gem::InstallerUninstallerUtils

  ##
  # The directory a gem's executables will be installed into

  attr_reader :bin_dir

  attr_reader :build_root # :nodoc:

  ##
  # The gem repository the gem will be installed into

  attr_reader :gem_home

  ##
  # The options passed when the Gem::Installer was instantiated.

  attr_reader :options

  ##
  # The gem package instance.

  attr_reader :package

  @path_warning = false

  class << self
    #
    # Changes in rubygems to lazily loading `rubygems/command` (in order to
    # lazily load `optparse` as a side effect) affect bundler's custom installer
    # which uses `Gem::Command` without requiring it (up until bundler 2.2.29).
    # This hook is to compensate for that missing require.
    #
    # TODO: Remove when rubygems no longer supports running on bundler older
    # than 2.2.29.

    def inherited(klass)
      if klass.name == "Bundler::RubyGemsGemInstaller"
        require "rubygems/command"
      end

      super(klass)
    end

    ##
    # True if we've warned about PATH not including Gem.bindir

    attr_accessor :path_warning

    ##
    # Overrides the executable format.
    #
    # This is a sprintf format with a "%s" which will be replaced with the
    # executable name.  It is based off the ruby executable name's difference
    # from "ruby".

    attr_writer :exec_format

    # Defaults to use Ruby's program prefix and suffix.
    def exec_format
      @exec_format ||= Gem.default_exec_format
    end
  end

  ##
  # Construct an installer object for the gem file located at +path+

  def self.at(path, options = {})
    security_policy = options[:security_policy]
    package = Gem::Package.new path, security_policy
    new package, options
  end

  class FakePackage
    attr_accessor :spec

    attr_accessor :dir_mode
    attr_accessor :prog_mode
    attr_accessor :data_mode

    def initialize(spec)
      @spec = spec
    end

    def extract_files(destination_dir, pattern = '*')
      FileUtils.mkdir_p destination_dir

      spec.files.each do |file|
        file = File.join destination_dir, file
        next if File.exist? file
        FileUtils.mkdir_p File.dirname(file)
        File.open file, 'w' do |fp|
          fp.puts "# #{file}"
        end
      end
    end

    def copy_to(path)
    end
  end

  ##
  # Construct an installer object for an ephemeral gem (one where we don't
  # actually have a .gem file, just a spec)

  def self.for_spec(spec, options = {})
    # FIXME: we should have a real Package class for this
    new FakePackage.new(spec), options
  end

  ##
  # Constructs an Installer instance that will install the gem at +package+ which
  # can either be a path or an instance of Gem::Package.  +options+ is a Hash
  # with the following keys:
  #
  # :bin_dir:: Where to put a bin wrapper if needed.
  # :development:: Whether or not development dependencies should be installed.
  # :env_shebang:: Use /usr/bin/env in bin wrappers.
  # :force:: Overrides all version checks and security policy checks, except
  #          for a signed-gems-only policy.
  # :format_executable:: Format the executable the same as the Ruby executable.
  #                      If your Ruby is ruby18, foo_exec will be installed as
  #                      foo_exec18.
  # :ignore_dependencies:: Don't raise if a dependency is missing.
  # :install_dir:: The directory to install the gem into.
  # :security_policy:: Use the specified security policy.  See Gem::Security
  # :user_install:: Indicate that the gem should be unpacked into the users
  #                 personal gem directory.
  # :only_install_dir:: Only validate dependencies against what is in the
  #                     install_dir
  # :wrappers:: Install wrappers if true, symlinks if false.
  # :build_args:: An Array of arguments to pass to the extension builder
  #               process. If not set, then Gem::Command.build_args is used
  # :post_install_message:: Print gem post install message if true

  def initialize(package, options={})
    require 'fileutils'

    @options = options
    @package = package

    process_options

    @package.dir_mode = options[:dir_mode]
    @package.prog_mode = options[:prog_mode]
    @package.data_mode = options[:data_mode]

    if options[:user_install]
      @gem_home = Gem.user_dir
      @bin_dir = Gem.bindir gem_home unless options[:bin_dir]
      @plugins_dir = Gem.plugindir(gem_home)
      check_that_user_bin_dir_is_in_path
    end
  end

  ##
  # Checks if +filename+ exists in +@bin_dir+.
  #
  # If +@force+ is set +filename+ is overwritten.
  #
  # If +filename+ exists and is a RubyGems wrapper for different gem the user
  # is consulted.
  #
  # If +filename+ exists and +@bin_dir+ is Gem.default_bindir (/usr/local) the
  # user is consulted.
  #
  # Otherwise +filename+ is overwritten.

  def check_executable_overwrite(filename) # :nodoc:
    return if @force

    generated_bin = File.join @bin_dir, formatted_program_filename(filename)

    return unless File.exist? generated_bin

    ruby_executable = false
    existing = nil

    File.open generated_bin, 'rb' do |io|
      next unless io.gets =~ /^#!/ # shebang
      io.gets # blankline

      # TODO detect a specially formatted comment instead of trying
      # to run a regexp against Ruby code.
      next unless io.gets =~ /This file was generated by RubyGems/

      ruby_executable = true
      existing = io.read.slice(%r{
          ^\s*(
            gem \s |
            load \s Gem\.bin_path\( |
            load \s Gem\.activate_bin_path\(
          )
          (['"])(.*?)(\2),
        }x, 3)
    end

    return if spec.name == existing

    # somebody has written to RubyGems' directory, overwrite, too bad
    return if Gem.default_bindir != @bin_dir and not ruby_executable

    question = "#{spec.name}'s executable \"#{filename}\" conflicts with ".dup

    if ruby_executable
      question << (existing || 'an unknown executable')

      return if ask_yes_no "#{question}\nOverwrite the executable?", false

      conflict = "installed executable from #{existing}"
    else
      question << generated_bin

      return if ask_yes_no "#{question}\nOverwrite the executable?", false

      conflict = generated_bin
    end

    raise Gem::InstallError,
      "\"#{filename}\" from #{spec.name} conflicts with #{conflict}"
  end

  ##
  # Lazy accessor for the spec's gem directory.

  def gem_dir
    @gem_dir ||= File.join(gem_home, "gems", spec.full_name)
  end

  ##
  # Lazy accessor for the installer's spec.

  def spec
    @package.spec
  rescue Gem::Package::Error => e
    raise Gem::InstallError, "invalid gem: #{e.message}"
  end

  ##
  # Installs the gem and returns a loaded Gem::Specification for the installed
  # gem.
  #
  # The gem will be installed with the following structure:
  #
  #   @gem_home/
  #     cache/<gem-version>.gem #=> a cached copy of the installed gem
  #     gems/<gem-version>/... #=> extracted files
  #     specifications/<gem-version>.gemspec #=> the Gem::Specification

  def install
    pre_install_checks

    run_pre_install_hooks

    # Set loaded_from to ensure extension_dir is correct
    if @options[:install_as_default]
      spec.loaded_from = default_spec_file
    else
      spec.loaded_from = spec_file
    end

    # Completely remove any previous gem files
    FileUtils.rm_rf gem_dir
    FileUtils.rm_rf spec.extension_dir

    dir_mode = options[:dir_mode]
    FileUtils.mkdir_p gem_dir, :mode => dir_mode && 0755

    if @options[:install_as_default]
      extract_bin
      write_default_spec
    else
      extract_files

      build_extensions
      write_build_info_file
      run_post_build_hooks
    end

    generate_bin
    generate_plugins

    unless @options[:install_as_default]
      write_spec
      write_cache_file
    end

    File.chmod(dir_mode, gem_dir) if dir_mode

    say spec.post_install_message if options[:post_install_message] && !spec.post_install_message.nil?

    Gem::Specification.reset

    run_post_install_hooks

    spec

  # TODO This rescue is in the wrong place. What is raising this exception?
  # move this rescue to around the code that actually might raise it.
  rescue Zlib::GzipFile::Error
    raise Gem::InstallError, "gzip error installing #{gem}"
  end

  def run_pre_install_hooks # :nodoc:
    Gem.pre_install_hooks.each do |hook|
      if hook.call(self) == false
        location = " at #{$1}" if hook.inspect =~ /[ @](.*:\d+)/

        message = "pre-install hook#{location} failed for #{spec.full_name}"
        raise Gem::InstallError, message
      end
    end
  end

  def run_post_build_hooks # :nodoc:
    Gem.post_build_hooks.each do |hook|
      if hook.call(self) == false
        FileUtils.rm_rf gem_dir

        location = " at #{$1}" if hook.inspect =~ /[ @](.*:\d+)/

        message = "post-build hook#{location} failed for #{spec.full_name}"
        raise Gem::InstallError, message
      end
    end
  end

  def run_post_install_hooks # :nodoc:
    Gem.post_install_hooks.each do |hook|
      hook.call self
    end
  end

  ##
  #
  # Return an Array of Specifications contained within the gem_home
  # we'll be installing into.

  def installed_specs
    @specs ||= begin
      specs = []

      Gem::Util.glob_files_in_dir("*.gemspec", File.join(gem_home, "specifications")).each do |path|
        spec = Gem::Specification.load path.tap(&Gem::UNTAINT)
        specs << spec if spec
      end

      specs
    end
  end

  ##
  # Ensure that the dependency is satisfied by the current installation of
  # gem.  If it is not an exception is raised.
  #
  # spec       :: Gem::Specification
  # dependency :: Gem::Dependency

  def ensure_dependency(spec, dependency)
    unless installation_satisfies_dependency? dependency
      raise Gem::InstallError, "#{spec.name} requires #{dependency}"
    end
    true
  end

  ##
  # True if the gems in the system satisfy +dependency+.

  def installation_satisfies_dependency?(dependency)
    return true if @options[:development] and dependency.type == :development
    return true if installed_specs.detect {|s| dependency.matches_spec? s }
    return false if @only_install_dir
    not dependency.matching_specs.empty?
  end

  ##
  # Unpacks the gem into the given directory.

  def unpack(directory)
    @gem_dir = directory
    extract_files
  end
  rubygems_deprecate :unpack

  ##
  # The location of the spec file that is installed.
  #

  def spec_file
    File.join gem_home, "specifications", "#{spec.full_name}.gemspec"
  end

  ##
  # The location of the default spec file for default gems.
  #

  def default_spec_file
    File.join gem_home, "specifications", "default", "#{spec.full_name}.gemspec"
  end

  ##
  # Writes the .gemspec specification (in Ruby) to the gem home's
  # specifications directory.

  def write_spec
    spec.installed_by_version = Gem.rubygems_version

    Gem.write_binary(spec_file, spec.to_ruby_for_cache)
  end

  ##
  # Writes the full .gemspec specification (in Ruby) to the gem home's
  # specifications/default directory.

  def write_default_spec
    Gem.write_binary(default_spec_file, spec.to_ruby)
  end

  ##
  # Creates windows .bat files for easy running of commands

  def generate_windows_script(filename, bindir)
    if Gem.win_platform?
      script_name = formatted_program_filename(filename) + ".bat"
      script_path = File.join bindir, File.basename(script_name)
      File.open script_path, 'w' do |file|
        file.puts windows_stub_script(bindir, filename)
      end

      verbose script_path
    end
  end

  def generate_bin # :nodoc:
    return if spec.executables.nil? or spec.executables.empty?

    ensure_writable_dir @bin_dir

    spec.executables.each do |filename|
      filename.tap(&Gem::UNTAINT)
      bin_path = File.join gem_dir, spec.bindir, filename

      unless File.exist? bin_path
        if File.symlink? bin_path
          alert_warning "`#{bin_path}` is dangling symlink pointing to `#{File.readlink bin_path}`"
        else
          alert_warning "`#{bin_path}` does not exist, maybe `gem pristine #{spec.name}` will fix it?"
        end
        next
      end

      mode = File.stat(bin_path).mode
      dir_mode = options[:prog_mode] || (mode | 0111)

      unless dir_mode == mode
        require 'fileutils'
        FileUtils.chmod dir_mode, bin_path
      end

      check_executable_overwrite filename

      if @wrappers
        generate_bin_script filename, @bin_dir
      else
        generate_bin_symlink filename, @bin_dir
      end
    end
  end

  def generate_plugins # :nodoc:
    latest = Gem::Specification.latest_spec_for(spec.name)
    return if latest && latest.version > spec.version

    ensure_writable_dir @plugins_dir

    if spec.plugins.empty?
      remove_plugins_for(spec, @plugins_dir)
    else
      regenerate_plugins_for(spec, @plugins_dir)
    end
  end

  ##
  # Creates the scripts to run the applications in the gem.
  #--
  # The Windows script is generated in addition to the regular one due to a
  # bug or misfeature in the Windows shell's pipe.  See
  # http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/193379

  def generate_bin_script(filename, bindir)
    bin_script_path = File.join bindir, formatted_program_filename(filename)

    require 'fileutils'
    FileUtils.rm_f bin_script_path # prior install may have been --no-wrappers

    File.open bin_script_path, 'wb', 0755 do |file|
      file.print app_script_text(filename)
      file.chmod(options[:prog_mode] || 0755)
    end

    verbose bin_script_path

    generate_windows_script filename, bindir
  end

  ##
  # Creates the symlinks to run the applications in the gem.  Moves
  # the symlink if the gem being installed has a newer version.

  def generate_bin_symlink(filename, bindir)
    src = File.join gem_dir, spec.bindir, filename
    dst = File.join bindir, formatted_program_filename(filename)

    if File.exist? dst
      if File.symlink? dst
        link = File.readlink(dst).split File::SEPARATOR
        cur_version = Gem::Version.create(link[-3].sub(/^.*-/, ''))
        return if spec.version < cur_version
      end
      File.unlink dst
    end

    FileUtils.symlink src, dst, :verbose => Gem.configuration.really_verbose
  rescue NotImplementedError, SystemCallError
    alert_warning "Unable to use symlinks, installing wrapper"
    generate_bin_script filename, bindir
  end

  ##
  # Generates a #! line for +bin_file_name+'s wrapper copying arguments if
  # necessary.
  #
  # If the :custom_shebang config is set, then it is used as a template
  # for how to create the shebang used for to run a gem's executables.
  #
  # The template supports 4 expansions:
  #
  #  $env    the path to the unix env utility
  #  $ruby   the path to the currently running ruby interpreter
  #  $exec   the path to the gem's executable
  #  $name   the name of the gem the executable is for
  #

  def shebang(bin_file_name)
    ruby_name = RbConfig::CONFIG['ruby_install_name'] if @env_shebang
    path = File.join gem_dir, spec.bindir, bin_file_name
    first_line = File.open(path, "rb") {|file| file.gets } || ""

    if first_line.start_with?("#!")
      # Preserve extra words on shebang line, like "-w".  Thanks RPA.
      shebang = first_line.sub(/\A\#!.*?ruby\S*((\s+\S+)+)/, "#!#{Gem.ruby}")
      opts = $1
      shebang.strip! # Avoid nasty ^M issues.
    end

    if which = Gem.configuration[:custom_shebang]
      # replace bin_file_name with "ruby" to avoid endless loops
      which = which.gsub(/ #{bin_file_name}$/," #{RbConfig::CONFIG['ruby_install_name']}")

      which = which.gsub(/\$(\w+)/) do
        case $1
        when "env"
          @env_path ||= ENV_PATHS.find {|env_path| File.executable? env_path }
        when "ruby"
          "#{Gem.ruby}#{opts}"
        when "exec"
          bin_file_name
        when "name"
          spec.name
        end
      end

      "#!#{which}"
    elsif not ruby_name
      "#!#{Gem.ruby}#{opts}"
    elsif opts
      "#!/bin/sh\n'exec' #{ruby_name.dump} '-x' \"$0\" \"$@\"\n#{shebang}"
    else
      # Create a plain shebang line.
      @env_path ||= ENV_PATHS.find {|env_path| File.executable? env_path }
      "#!#{@env_path} #{ruby_name}"
    end
  end

  ##
  # Ensures the Gem::Specification written out for this gem is loadable upon
  # installation.

  def ensure_loadable_spec
    ruby = spec.to_ruby_for_cache
    ruby.tap(&Gem::UNTAINT)

    begin
      eval ruby
    rescue StandardError, SyntaxError => e
      raise Gem::InstallError,
            "The specification for #{spec.full_name} is corrupt (#{e.class})"
    end
  end

  def ensure_dependencies_met # :nodoc:
    deps = spec.runtime_dependencies
    deps |= spec.development_dependencies if @development

    deps.each do |dep_gem|
      ensure_dependency spec, dep_gem
    end
  end

  def process_options # :nodoc:
    @options = {
      :bin_dir      => nil,
      :env_shebang  => false,
      :force        => false,
      :only_install_dir => false,
      :post_install_message => true,
    }.merge options

    @env_shebang         = options[:env_shebang]
    @force               = options[:force]
    @install_dir         = options[:install_dir]
    @gem_home            = options[:install_dir] || Gem.dir
    @plugins_dir         = Gem.plugindir(@gem_home)
    @ignore_dependencies = options[:ignore_dependencies]
    @format_executable   = options[:format_executable]
    @wrappers            = options[:wrappers]
    @only_install_dir    = options[:only_install_dir]

    # If the user has asked for the gem to be installed in a directory that is
    # the system gem directory, then use the system bin directory, else create
    # (or use) a new bin dir under the gem_home.
    @bin_dir             = options[:bin_dir] || Gem.bindir(gem_home)
    @development         = options[:development]
    @build_root          = options[:build_root]

    @build_args = options[:build_args]

    unless @build_root.nil?
      @bin_dir = File.join(@build_root, @bin_dir.gsub(/^[a-zA-Z]:/, ''))
      @gem_home = File.join(@build_root, @gem_home.gsub(/^[a-zA-Z]:/, ''))
      @plugins_dir = File.join(@build_root, @plugins_dir.gsub(/^[a-zA-Z]:/, ''))
      alert_warning "You build with buildroot.\n  Build root: #{@build_root}\n  Bin dir: #{@bin_dir}\n  Gem home: #{@gem_home}\n  Plugins dir: #{@plugins_dir}"
    end
  end

  def check_that_user_bin_dir_is_in_path # :nodoc:
    return if self.class.path_warning

    user_bin_dir = @bin_dir || Gem.bindir(gem_home)
    user_bin_dir = user_bin_dir.tr(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR

    path = ENV['PATH']
    path = path.tr(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR

    if Gem.win_platform?
      path = path.downcase
      user_bin_dir = user_bin_dir.downcase
    end

    path = path.split(File::PATH_SEPARATOR)

    unless path.include? user_bin_dir
      unless !Gem.win_platform? && (path.include? user_bin_dir.sub(ENV['HOME'], '~'))
        alert_warning "You don't have #{user_bin_dir} in your PATH,\n\t  gem executables will not run."
        self.class.path_warning = true
      end
    end
  end

  def verify_gem_home # :nodoc:
    FileUtils.mkdir_p gem_home, :mode => options[:dir_mode] && 0755
    raise Gem::FilePermissionError, gem_home unless File.writable?(gem_home)
  end

  def verify_spec
    unless spec.name =~ Gem::Specification::VALID_NAME_PATTERN
      raise Gem::InstallError, "#{spec} has an invalid name"
    end

    if spec.raw_require_paths.any?{|path| path =~ /\R/ }
      raise Gem::InstallError, "#{spec} has an invalid require_paths"
    end

    if spec.extensions.any?{|ext| ext =~ /\R/ }
      raise Gem::InstallError, "#{spec} has an invalid extensions"
    end

    if spec.platform.to_s =~ /\R/
      raise Gem::InstallError, "#{spec.platform} is an invalid platform"
    end

    unless spec.specification_version.to_s =~ /\A\d+\z/
      raise Gem::InstallError, "#{spec} has an invalid specification_version"
    end

    if spec.dependencies.any? {|dep| dep.type != :runtime && dep.type != :development }
      raise Gem::InstallError, "#{spec} has an invalid dependencies"
    end

    if spec.dependencies.any? {|dep| dep.name =~ /(?:\R|[<>])/ }
      raise Gem::InstallError, "#{spec} has an invalid dependencies"
    end
  end

  ##
  # Return the text for an application file.

  def app_script_text(bin_file_name)
    # note that the `load` lines cannot be indented, as old RG versions match
    # against the beginning of the line
    return <<-TEXT
#{shebang bin_file_name}
#
# This file was generated by RubyGems.
#
# The application '#{spec.name}' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require 'rubygems'
#{gemdeps_load(spec.name)}
version = "#{Gem::Requirement.default_prerelease}"

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('#{spec.name}', '#{bin_file_name}', version)
else
gem #{spec.name.dump}, version
load Gem.bin_path(#{spec.name.dump}, #{bin_file_name.dump}, version)
end
TEXT
  end

  def gemdeps_load(name)
    return '' if name == "bundler"

    <<-TEXT

Gem.use_gemdeps
TEXT
  end

  ##
  # return the stub script text used to launch the true Ruby script

  def windows_stub_script(bindir, bin_file_name)
    rb_config = RbConfig::CONFIG
    rb_topdir = RbConfig::TOPDIR || File.dirname(rb_config["bindir"])

    # get ruby executable file name from RbConfig
    ruby_exe = "#{rb_config['RUBY_INSTALL_NAME']}#{rb_config['EXEEXT']}"
    ruby_exe = "ruby.exe" if ruby_exe.empty?

    if File.exist?(File.join bindir, ruby_exe)
      # stub & ruby.exe within same folder.  Portable
      <<-TEXT
@ECHO OFF
@"%~dp0#{ruby_exe}" "%~dpn0" %*
      TEXT
    elsif bindir.downcase.start_with? rb_topdir.downcase
      # stub within ruby folder, but not standard bin.  Portable
      require 'pathname'
      from = Pathname.new bindir
      to   = Pathname.new "#{rb_topdir}/bin"
      rel  = to.relative_path_from from
      <<-TEXT
@ECHO OFF
@"%~dp0#{rel}/#{ruby_exe}" "%~dpn0" %*
      TEXT
    else
      # outside ruby folder, maybe -user-install or bundler.  Portable, but ruby
      # is dependent on PATH
      <<-TEXT
@ECHO OFF
@#{ruby_exe} "%~dpn0" %*
      TEXT
    end
  end
  ##
  # Builds extensions.  Valid types of extensions are extconf.rb files,
  # configure scripts and rakefiles or mkrf_conf files.

  def build_extensions
    builder = Gem::Ext::Builder.new spec, build_args

    builder.build_extensions
  end

  ##
  # Reads the file index and extracts each file into the gem directory.
  #
  # Ensures that files can't be installed outside the gem directory.

  def extract_files
    @package.extract_files gem_dir
  end

  ##
  # Extracts only the bin/ files from the gem into the gem directory.
  # This is used by default gems to allow a gem-aware stub to function
  # without the full gem installed.

  def extract_bin
    @package.extract_files gem_dir, "#{spec.bindir}/*"
  end

  ##
  # Prefix and suffix the program filename the same as ruby.

  def formatted_program_filename(filename)
    if @format_executable
      self.class.exec_format % File.basename(filename)
    else
      filename
    end
  end

  ##
  #
  # Return the target directory where the gem is to be installed. This
  # directory is not guaranteed to be populated.
  #

  def dir
    gem_dir.to_s
  end

  ##
  # Filename of the gem being installed.

  def gem
    @package.gem.path
  end

  ##
  # Performs various checks before installing the gem such as the install
  # repository is writable and its directories exist, required Ruby and
  # rubygems versions are met and that dependencies are installed.
  #
  # Version and dependency checks are skipped if this install is forced.
  #
  # The dependent check will be skipped if the install is ignoring dependencies.

  def pre_install_checks
    verify_gem_home

    # The name and require_paths must be verified first, since it could contain
    # ruby code that would be eval'ed in #ensure_loadable_spec
    verify_spec

    ensure_loadable_spec

    if options[:install_as_default]
      Gem.ensure_default_gem_subdirectories gem_home
    else
      Gem.ensure_gem_subdirectories gem_home
    end

    return true if @force

    ensure_dependencies_met unless @ignore_dependencies

    true
  end

  ##
  # Writes the file containing the arguments for building this gem's
  # extensions.

  def write_build_info_file
    return if build_args.empty?

    build_info_dir = File.join gem_home, 'build_info'

    dir_mode = options[:dir_mode]
    FileUtils.mkdir_p build_info_dir, :mode => dir_mode && 0755

    build_info_file = File.join build_info_dir, "#{spec.full_name}.info"

    File.open build_info_file, 'w' do |io|
      build_args.each do |arg|
        io.puts arg
      end
    end

    File.chmod(dir_mode, build_info_dir) if dir_mode
  end

  ##
  # Writes the .gem file to the cache directory

  def write_cache_file
    cache_file = File.join gem_home, 'cache', spec.file_name
    @package.copy_to cache_file
  end

  def ensure_writable_dir(dir) # :nodoc:
    begin
      Dir.mkdir dir, *[options[:dir_mode] && 0755].compact
    rescue SystemCallError
      raise unless File.directory? dir
    end

    raise Gem::FilePermissionError.new(dir) unless File.writable? dir
  end

  private

  def build_args
    @build_args ||= begin
                      require_relative "command"
                      Gem::Command.build_args
                    end
  end
end
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require 'uri'
require_relative '../rubygems'

##
# Mixin methods for local and remote Gem::Command options.

module Gem::LocalRemoteOptions

  ##
  # Allows Gem::OptionParser to handle HTTP URIs.

  def accept_uri_http
    Gem::OptionParser.accept URI::HTTP do |value|
      begin
        uri = URI.parse value
      rescue URI::InvalidURIError
        raise Gem::OptionParser::InvalidArgument, value
      end

      valid_uri_schemes = ["http", "https", "file", "s3"]
      unless valid_uri_schemes.include?(uri.scheme)
        msg = "Invalid uri scheme for #{value}\nPreface URLs with one of #{valid_uri_schemes.map{|s| "#{s}://" }}"
        raise ArgumentError, msg
      end

      value
    end
  end

  ##
  # Add local/remote options to the command line parser.

  def add_local_remote_options
    add_option(:"Local/Remote", '-l', '--local',
               'Restrict operations to the LOCAL domain') do |value, options|
      options[:domain] = :local
    end

    add_option(:"Local/Remote", '-r', '--remote',
      'Restrict operations to the REMOTE domain') do |value, options|
      options[:domain] = :remote
    end

    add_option(:"Local/Remote", '-b', '--both',
               'Allow LOCAL and REMOTE operations') do |value, options|
      options[:domain] = :both
    end

    add_bulk_threshold_option
    add_clear_sources_option
    add_source_option
    add_proxy_option
    add_update_sources_option
  end

  ##
  # Add the --bulk-threshold option

  def add_bulk_threshold_option
    add_option(:"Local/Remote", '-B', '--bulk-threshold COUNT',
               "Threshold for switching to bulk",
               "synchronization (default #{Gem.configuration.bulk_threshold})") do
      |value, options|
      Gem.configuration.bulk_threshold = value.to_i
    end
  end

  ##
  # Add the --clear-sources option

  def add_clear_sources_option
    add_option(:"Local/Remote", '--clear-sources',
               'Clear the gem sources') do |value, options|

      Gem.sources = nil
      options[:sources_cleared] = true
    end
  end

  ##
  # Add the --http-proxy option

  def add_proxy_option
    accept_uri_http

    add_option(:"Local/Remote", '-p', '--[no-]http-proxy [URL]', URI::HTTP,
               'Use HTTP proxy for remote operations') do |value, options|
      options[:http_proxy] = (value == false) ? :no_proxy : value
      Gem.configuration[:http_proxy] = options[:http_proxy]
    end
  end

  ##
  # Add the --source option

  def add_source_option
    accept_uri_http

    add_option(:"Local/Remote", '-s', '--source URL', URI::HTTP,
               'Append URL to list of remote gem sources') do |source, options|

      source << '/' if source !~ /\/\z/

      if options.delete :sources_cleared
        Gem.sources = [source]
      else
        Gem.sources << source unless Gem.sources.include?(source)
      end
    end
  end

  ##
  # Add the --update-sources option

  def add_update_sources_option
    add_option(:Deprecated, '-u', '--[no-]update-sources',
               'Update local source cache') do |value, options|
      Gem.configuration.update_sources = value
    end
  end

  ##
  # Is fetching of local and remote information enabled?

  def both?
    options[:domain] == :both
  end

  ##
  # Is local fetching enabled?

  def local?
    options[:domain] == :local || options[:domain] == :both
  end

  ##
  # Is remote fetching enabled?

  def remote?
    options[:domain] == :remote || options[:domain] == :both
  end

end
# frozen_string_literal: true
# This exists just to satisfy bugs in marshal'd gemspecs that
# contain a reference to YAML::PrivateType. We prune these out
# in Specification._load, but if we don't have the constant, Marshal
# blows up.

module Psych # :nodoc:
  class PrivateType # :nodoc:
  end
end
# frozen_string_literal: true
require 'zlib'
require 'erb'
require 'uri'

require_relative '../rubygems'
require_relative 'rdoc'

##
# Gem::Server and allows users to serve gems for consumption by
# `gem --remote-install`.
#
# gem_server starts an HTTP server on the given port and serves the following:
# * "/" - Browsing of gem spec files for installed gems
# * "/specs.#{Gem.marshal_version}.gz" - specs name/version/platform index
# * "/latest_specs.#{Gem.marshal_version}.gz" - latest specs
#   name/version/platform index
# * "/quick/" - Individual gemspecs
# * "/gems" - Direct access to download the installable gems
# * "/rdoc?q=" - Search for installed rdoc documentation
#
# == Usage
#
#   gem_server = Gem::Server.new Gem.dir, 8089, false
#   gem_server.run
#
#--
# TODO Refactor into a real WEBrick servlet to remove code duplication.

class Gem::Server
  attr_reader :spec_dirs

  include ERB::Util
  include Gem::UserInteraction

  SEARCH = <<-ERB.freeze
      <form class="headerSearch" name="headerSearchForm" method="get" action="/rdoc">
        <div id="search" style="float:right">
          <label for="q">Filter/Search</label>
          <input id="q" type="text" style="width:10em" name="q">
          <button type="submit" style="display:none"></button>
        </div>
      </form>
  ERB

  DOC_TEMPLATE = <<-'ERB'.freeze
  <?xml version="1.0" encoding="iso-8859-1"?>
  <!DOCTYPE html
       PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>RubyGems Documentation Index</title>
    <link rel="stylesheet" href="gem-server-rdoc-style.css" type="text/css" media="screen" />
  </head>
  <body>
    <div id="fileHeader">
<%= SEARCH %>
      <h1>RubyGems Documentation Index</h1>
    </div>
    <!-- banner header -->

  <div id="bodyContent">
    <div id="contextContent">
      <div id="description">
        <h1>Summary</h1>
  <p>There are <%=values["gem_count"]%> gems installed:</p>
  <p>
  <%= values["specs"].map { |v| "<a href=\"##{u v["name"]}\">#{h v["name"]}</a>" }.join ', ' %>.
  <h1>Gems</h1>

  <dl>
  <% values["specs"].each do |spec| %>
    <dt>
    <% if spec["first_name_entry"] then %>
      <a name="<%=h spec["name"]%>"></a>
    <% end %>

    <b><%=h spec["name"]%> <%=h spec["version"]%></b>

    <% if spec["ri_installed"] || spec["rdoc_installed"] then %>
      <a href="<%=spec["doc_path"]%>">[rdoc]</a>
    <% else %>
      <span title="rdoc not installed">[rdoc]</span>
    <% end %>

    <% if spec["homepage"] then %>
      <a href="<%=uri_encode spec["homepage"]%>" title="<%=h spec["homepage"]%>">[www]</a>
    <% else %>
      <span title="no homepage available">[www]</span>
    <% end %>

    <% if spec["has_deps"] then %>
     - depends on
      <%= spec["dependencies"].map { |v| "<a href=\"##{u v["name"]}\">#{h v["name"]}</a>" }.join ', ' %>.
    <% end %>
    </dt>
    <dd>
    <%=spec["summary"]%>
    <% if spec["executables"] then %>
      <br/>

      <% if spec["only_one_executable"] then %>
          Executable is
      <% else %>
          Executables are
      <%end%>

      <%= spec["executables"].map { |v| "<span class=\"context-item-name\">#{h v["executable"]}</span>"}.join ', ' %>.

    <%end%>
    <br/>
    <br/>
    </dd>
  <% end %>
  </dl>

      </div>
     </div>
    </div>
  <div id="validator-badges">
    <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
  </div>
  </body>
  </html>
  ERB

  # CSS is copy & paste from rdoc-style.css, RDoc V1.0.1 - 20041108
  RDOC_CSS = <<-CSS.freeze
body {
    font-family: Verdana,Arial,Helvetica,sans-serif;
    font-size:   90%;
    margin: 0;
    margin-left: 40px;
    padding: 0;
    background: white;
}

h1,h2,h3,h4 { margin: 0; color: #efefef; background: transparent; }
h1 { font-size: 150%; }
h2,h3,h4 { margin-top: 1em; }

a { background: #eef; color: #039; text-decoration: none; }
a:hover { background: #039; color: #eef; }

/* Override the base stylesheets Anchor inside a table cell */
td > a {
  background: transparent;
  color: #039;
  text-decoration: none;
}

/* and inside a section title */
.section-title > a {
  background: transparent;
  color: #eee;
  text-decoration: none;
}

/* === Structural elements =================================== */

div#index {
    margin: 0;
    margin-left: -40px;
    padding: 0;
    font-size: 90%;
}


div#index a {
    margin-left: 0.7em;
}

div#index .section-bar {
   margin-left: 0px;
   padding-left: 0.7em;
   background: #ccc;
   font-size: small;
}


div#classHeader, div#fileHeader {
    width: auto;
    color: white;
    padding: 0.5em 1.5em 0.5em 1.5em;
    margin: 0;
    margin-left: -40px;
    border-bottom: 3px solid #006;
}

div#classHeader a, div#fileHeader a {
    background: inherit;
    color: white;
}

div#classHeader td, div#fileHeader td {
    background: inherit;
    color: white;
}


div#fileHeader {
    background: #057;
}

div#classHeader {
    background: #048;
}


.class-name-in-header {
  font-size:  180%;
  font-weight: bold;
}


div#bodyContent {
    padding: 0 1.5em 0 1.5em;
}

div#description {
    padding: 0.5em 1.5em;
    background: #efefef;
    border: 1px dotted #999;
}

div#description h1,h2,h3,h4,h5,h6 {
    color: #125;;
    background: transparent;
}

div#validator-badges {
    text-align: center;
}
div#validator-badges img { border: 0; }

div#copyright {
    color: #333;
    background: #efefef;
    font: 0.75em sans-serif;
    margin-top: 5em;
    margin-bottom: 0;
    padding: 0.5em 2em;
}


/* === Classes =================================== */

table.header-table {
    color: white;
    font-size: small;
}

.type-note {
    font-size: small;
    color: #DEDEDE;
}

.xxsection-bar {
    background: #eee;
    color: #333;
    padding: 3px;
}

.section-bar {
   color: #333;
   border-bottom: 1px solid #999;
    margin-left: -20px;
}


.section-title {
    background: #79a;
    color: #eee;
    padding: 3px;
    margin-top: 2em;
    margin-left: -30px;
    border: 1px solid #999;
}

.top-aligned-row {  vertical-align: top }
.bottom-aligned-row { vertical-align: bottom }

/* --- Context section classes ----------------------- */

.context-row { }
.context-item-name { font-family: monospace; font-weight: bold; color: black; }
.context-item-value { font-size: small; color: #448; }
.context-item-desc { color: #333; padding-left: 2em; }

/* --- Method classes -------------------------- */
.method-detail {
    background: #efefef;
    padding: 0;
    margin-top: 0.5em;
    margin-bottom: 1em;
    border: 1px dotted #ccc;
}
.method-heading {
  color: black;
  background: #ccc;
  border-bottom: 1px solid #666;
  padding: 0.2em 0.5em 0 0.5em;
}
.method-signature { color: black; background: inherit; }
.method-name { font-weight: bold; }
.method-args { font-style: italic; }
.method-description { padding: 0 0.5em 0 0.5em; }

/* --- Source code sections -------------------- */

a.source-toggle { font-size: 90%; }
div.method-source-code {
    background: #262626;
    color: #ffdead;
    margin: 1em;
    padding: 0.5em;
    border: 1px dashed #999;
    overflow: hidden;
}

div.method-source-code pre { color: #ffdead; overflow: hidden; }

/* --- Ruby keyword styles --------------------- */

.standalone-code { background: #221111; color: #ffdead; overflow: hidden; }

.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: #b22222; font-weight: bold; background: transparent; }
.ruby-regexp  { color: #ffa07a; background: transparent; }
.ruby-value   { color: #7fffd4; background: transparent; }
  CSS

  RDOC_NO_DOCUMENTATION = <<-'ERB'.freeze
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Found documentation</title>
    <link rel="stylesheet" href="gem-server-rdoc-style.css" type="text/css" media="screen" />
  </head>
  <body>
    <div id="fileHeader">
<%= SEARCH %>
      <h1>No documentation found</h1>
    </div>

    <div id="bodyContent">
      <div id="contextContent">
        <div id="description">
          <p>No gems matched <%= h query.inspect %></p>

          <p>
            Back to <a href="/">complete gem index</a>
          </p>

        </div>
      </div>
    </div>
    <div id="validator-badges">
      <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
    </div>
  </body>
</html>
  ERB

  RDOC_SEARCH_TEMPLATE = <<-'ERB'.freeze
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Found documentation</title>
    <link rel="stylesheet" href="gem-server-rdoc-style.css" type="text/css" media="screen" />
  </head>
  <body>
    <div id="fileHeader">
<%= SEARCH %>
      <h1>Found documentation</h1>
    </div>
    <!-- banner header -->

    <div id="bodyContent">
      <div id="contextContent">
        <div id="description">
          <h1>Summary</h1>
          <p><%=doc_items.length%> documentation topics found.</p>
          <h1>Topics</h1>

          <dl>
          <% doc_items.each do |doc_item| %>
            <dt>
              <b><%=doc_item[:name]%></b>
              <a href="<%=u doc_item[:url]%>">[rdoc]</a>
            </dt>
            <dd>
              <%=h doc_item[:summary]%>
              <br/>
              <br/>
            </dd>
          <% end %>
          </dl>

          <p>
            Back to <a href="/">complete gem index</a>
          </p>

        </div>
      </div>
    </div>
    <div id="validator-badges">
      <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
    </div>
  </body>
</html>
  ERB

  def self.run(options)
    new(options[:gemdir], options[:port], options[:daemon],
        options[:launch], options[:addresses]).run
  end

  def initialize(gem_dirs, port, daemon, launch = nil, addresses = nil)
    begin
      require 'webrick'
    rescue LoadError
      abort "webrick is not found. You may need to `gem install webrick` to install webrick."
    end

    Gem::RDoc.load_rdoc
    Socket.do_not_reverse_lookup = true

    @gem_dirs  = Array gem_dirs
    @port      = port
    @daemon    = daemon
    @launch    = launch
    @addresses = addresses

    logger  = WEBrick::Log.new nil, WEBrick::BasicLog::FATAL
    @server = WEBrick::HTTPServer.new :DoNotListen => true, :Logger => logger

    @spec_dirs = @gem_dirs.map {|gem_dir| File.join gem_dir, 'specifications' }
    @spec_dirs.reject! {|spec_dir| !File.directory? spec_dir }

    reset_gems

    @have_rdoc_4_plus = nil
  end

  def add_date(res)
    res['date'] = @spec_dirs.map do |spec_dir|
      File.stat(spec_dir).mtime
    end.max
  end

  def uri_encode(str)
    str.gsub(URI::UNSAFE) do |match|
      match.each_byte.map {|c| sprintf('%%%02X', c.ord) }.join
    end
  end

  def doc_root(gem_name)
    if have_rdoc_4_plus?
      "/doc_root/#{u gem_name}/"
    else
      "/doc_root/#{u gem_name}/rdoc/index.html"
    end
  end

  def have_rdoc_4_plus?
    @have_rdoc_4_plus ||=
      Gem::Requirement.new('>= 4.0.0.preview2').satisfied_by? Gem::RDoc.rdoc_version
  end

  def latest_specs(req, res)
    reset_gems

    res['content-type'] = 'application/x-gzip'

    add_date res

    latest_specs = Gem::Specification.latest_specs

    specs = latest_specs.sort.map do |spec|
      platform = spec.original_platform || Gem::Platform::RUBY
      [spec.name, spec.version, platform]
    end

    specs = Marshal.dump specs

    if req.path =~ /\.gz$/
      specs = Gem::Util.gzip specs
      res['content-type'] = 'application/x-gzip'
    else
      res['content-type'] = 'application/octet-stream'
    end

    if req.request_method == 'HEAD'
      res['content-length'] = specs.length
    else
      res.body << specs
    end
  end

  ##
  # Creates server sockets based on the addresses option.  If no addresses
  # were given a server socket for all interfaces is created.

  def listen(addresses = @addresses)
    addresses = [nil] unless addresses

    listeners = 0

    addresses.each do |address|
      begin
        @server.listen address, @port
        @server.listeners[listeners..-1].each do |listener|
          host, port = listener.addr.values_at 2, 1
          host = "[#{host}]" if host =~ /:/ # we don't reverse lookup
          say "Server started at http://#{host}:#{port}"
        end

        listeners = @server.listeners.length
      rescue SystemCallError
        next
      end
    end

    if @server.listeners.empty?
      say "Unable to start a server."
      say "Check for running servers or your --bind and --port arguments"
      terminate_interaction 1
    end
  end

  def prerelease_specs(req, res)
    reset_gems

    res['content-type'] = 'application/x-gzip'

    add_date res

    specs = Gem::Specification.select do |spec|
      spec.version.prerelease?
    end.sort.map do |spec|
      platform = spec.original_platform || Gem::Platform::RUBY
      [spec.name, spec.version, platform]
    end

    specs = Marshal.dump specs

    if req.path =~ /\.gz$/
      specs = Gem::Util.gzip specs
      res['content-type'] = 'application/x-gzip'
    else
      res['content-type'] = 'application/octet-stream'
    end

    if req.request_method == 'HEAD'
      res['content-length'] = specs.length
    else
      res.body << specs
    end
  end

  def quick(req, res)
    reset_gems

    res['content-type'] = 'text/plain'
    add_date res

    case req.request_uri.path
    when %r{^/quick/(Marshal.#{Regexp.escape Gem.marshal_version}/)?(.*?)\.gemspec\.rz$} then
      marshal_format, full_name = $1, $2
      specs = Gem::Specification.find_all_by_full_name(full_name)

      selector = full_name.inspect

      if specs.empty?
        res.status = 404
        res.body = "No gems found matching #{selector}"
      elsif specs.length > 1
        res.status = 500
        res.body = "Multiple gems found matching #{selector}"
      elsif marshal_format
        res['content-type'] = 'application/x-deflate'
        res.body << Gem.deflate(Marshal.dump(specs.first))
      end
    else
      raise WEBrick::HTTPStatus::NotFound, "`#{req.path}' not found."
    end
  end

  def root(req, res)
    reset_gems

    add_date res

    raise WEBrick::HTTPStatus::NotFound, "`#{req.path}' not found." unless
      req.path == '/'

    specs = []
    total_file_count = 0

    Gem::Specification.each do |spec|
      total_file_count += spec.files.size
      deps = spec.dependencies.map do |dep|
        {
          "name"    => dep.name,
          "type"    => dep.type,
          "version" => dep.requirement.to_s,
        }
      end

      deps = deps.sort_by {|dep| [dep["name"].downcase, dep["version"]] }
      deps.last["is_last"] = true unless deps.empty?

      # executables
      executables = spec.executables.sort.collect {|exec| {"executable" => exec} }
      executables = nil if executables.empty?
      executables.last["is_last"] = true if executables

      # Pre-process spec homepage for safety reasons
      begin
        homepage_uri = URI.parse(spec.homepage)
        if [URI::HTTP, URI::HTTPS].member? homepage_uri.class
          homepage_uri = spec.homepage
        else
          homepage_uri = "."
        end
      rescue URI::InvalidURIError
        homepage_uri = "."
      end

      specs << {
        "authors"             => spec.authors.sort.join(", "),
        "date"                => spec.date.to_s,
        "dependencies"        => deps,
        "doc_path"            => doc_root(spec.full_name),
        "executables"         => executables,
        "only_one_executable" => (executables && executables.size == 1),
        "full_name"           => spec.full_name,
        "has_deps"            => !deps.empty?,
        "homepage"            => homepage_uri,
        "name"                => spec.name,
        "rdoc_installed"      => Gem::RDoc.new(spec).rdoc_installed?,
        "ri_installed"        => Gem::RDoc.new(spec).ri_installed?,
        "summary"             => spec.summary,
        "version"             => spec.version.to_s,
      }
    end

    specs << {
      "authors" => "Chad Fowler, Rich Kilmer, Jim Weirich, Eric Hodel and others",
      "dependencies" => [],
      "doc_path" => doc_root("rubygems-#{Gem::VERSION}"),
      "executables" => [{"executable" => 'gem', "is_last" => true}],
      "only_one_executable" => true,
      "full_name" => "rubygems-#{Gem::VERSION}",
      "has_deps" => false,
      "homepage" => "https://guides.rubygems.org/",
      "name" => 'rubygems',
      "ri_installed" => true,
      "summary" => "RubyGems itself",
      "version" => Gem::VERSION,
    }

    specs = specs.sort_by {|spec| [spec["name"].downcase, spec["version"]] }
    specs.last["is_last"] = true

    # tag all specs with first_name_entry
    last_spec = nil
    specs.each do |spec|
      is_first = last_spec.nil? || (last_spec["name"].downcase != spec["name"].downcase)
      spec["first_name_entry"] = is_first
      last_spec = spec
    end

    # create page from template
    template = ERB.new(DOC_TEMPLATE)
    res['content-type'] = 'text/html'

    values = { "gem_count" => specs.size.to_s, "specs" => specs,
               "total_file_count" => total_file_count.to_s }

    # suppress 1.9.3dev warning about unused variable
    values = values

    result = template.result binding
    res.body = result
  end

  ##
  # Can be used for quick navigation to the rdoc documentation.  You can then
  # define a search shortcut for your browser.  E.g. in Firefox connect
  # 'shortcut:rdoc' to http://localhost:8808/rdoc?q=%s template. Then you can
  # directly open the ActionPack documentation by typing 'rdoc actionp'. If
  # there are multiple hits for the search term, they are presented as a list
  # with links.
  #
  # Search algorithm aims for an intuitive search:
  # 1. first try to find the gems and documentation folders which name
  #    starts with the search term
  # 2. search for entries, that *contain* the search term
  # 3. show all the gems
  #
  # If there is only one search hit, user is immediately redirected to the
  # documentation for the particular gem, otherwise a list with results is
  # shown.
  #
  # === Additional trick - install documentation for Ruby core
  #
  # Note: please adjust paths accordingly use for example 'locate yaml.rb' and
  # 'gem environment' to identify directories, that are specific for your
  # local installation
  #
  # 1. install Ruby sources
  #      cd /usr/src
  #      sudo apt-get source ruby
  #
  # 2. generate documentation
  #      rdoc -o /usr/lib/ruby/gems/1.8/doc/core/rdoc \
  #        /usr/lib/ruby/1.8 ruby1.8-1.8.7.72
  #
  # By typing 'rdoc core' you can now access the core documentation

  def rdoc(req, res)
    query = req.query['q']
    show_rdoc_for_pattern("#{query}*", res) && return
    show_rdoc_for_pattern("*#{query}*", res) && return

    template = ERB.new RDOC_NO_DOCUMENTATION

    res['content-type'] = 'text/html'
    res.body = template.result binding
  end

  ##
  # Updates the server to use the latest installed gems.

  def reset_gems # :nodoc:
    Gem::Specification.dirs = @gem_dirs
  end

  ##
  # Returns true and prepares http response, if rdoc for the requested gem
  # name pattern was found.
  #
  # The search is based on the file system content, not on the gems metadata.
  # This allows additional documentation folders like 'core' for the Ruby core
  # documentation - just put it underneath the main doc folder.

  def show_rdoc_for_pattern(pattern, res)
    found_gems = Dir.glob("{#{@gem_dirs.join ','}}/doc/#{pattern}").select do |path|
      File.exist? File.join(path, 'rdoc/index.html')
    end
    case found_gems.length
    when 0
      return false
    when 1
      new_path = File.basename(found_gems[0])
      res.status = 302
      res['Location'] = doc_root new_path
      return true
    else
      doc_items = []
      found_gems.each do |file_name|
        base_name = File.basename(file_name)
        doc_items << {
          :name    => base_name,
          :url     => doc_root(new_path),
          :summary => '',
        }
      end

      template = ERB.new(RDOC_SEARCH_TEMPLATE)
      res['content-type'] = 'text/html'
      result = template.result binding
      res.body = result
      return true
    end
  end

  def run
    listen

    WEBrick::Daemon.start if @daemon

    @server.mount_proc "/specs.#{Gem.marshal_version}", method(:specs)
    @server.mount_proc "/specs.#{Gem.marshal_version}.gz", method(:specs)

    @server.mount_proc "/latest_specs.#{Gem.marshal_version}",
                       method(:latest_specs)
    @server.mount_proc "/latest_specs.#{Gem.marshal_version}.gz",
                       method(:latest_specs)

    @server.mount_proc "/prerelease_specs.#{Gem.marshal_version}",
                       method(:prerelease_specs)
    @server.mount_proc "/prerelease_specs.#{Gem.marshal_version}.gz",
                       method(:prerelease_specs)

    @server.mount_proc "/quick/", method(:quick)

    @server.mount_proc("/gem-server-rdoc-style.css") do |req, res|
      res['content-type'] = 'text/css'
      add_date res
      res.body << RDOC_CSS
    end

    @server.mount_proc "/", method(:root)

    @server.mount_proc "/rdoc", method(:rdoc)

    file_handlers = {
      '/gems' => '/cache/',
    }

    if have_rdoc_4_plus?
      @server.mount '/doc_root', RDoc::Servlet, '/doc_root'
    else
      file_handlers['/doc_root'] = '/doc/'
    end

    @gem_dirs.each do |gem_dir|
      file_handlers.each do |mount_point, mount_dir|
        @server.mount(mount_point, WEBrick::HTTPServlet::FileHandler,
                      File.join(gem_dir, mount_dir), true)
      end
    end

    trap("INT") { @server.shutdown; exit! }
    trap("TERM") { @server.shutdown; exit! }

    launch if @launch

    @server.start
  end

  def specs(req, res)
    reset_gems

    add_date res

    specs = Gem::Specification.sort_by(&:sort_obj).map do |spec|
      platform = spec.original_platform || Gem::Platform::RUBY
      [spec.name, spec.version, platform]
    end

    specs = Marshal.dump specs

    if req.path =~ /\.gz$/
      specs = Gem::Util.gzip specs
      res['content-type'] = 'application/x-gzip'
    else
      res['content-type'] = 'application/octet-stream'
    end

    if req.request_method == 'HEAD'
      res['content-length'] = specs.length
    else
      res.body << specs
    end
  end

  def launch
    listeners = @server.listeners.map{|l| l.addr[2] }

    # TODO: 0.0.0.0 == any, not localhost.
    host = listeners.any?{|l| l == '0.0.0.0' } ? 'localhost' : listeners.first

    say "Launching browser to http://#{host}:#{@port}"

    system("#{@launch} http://#{host}:#{@port}")
  end
end
# frozen_string_literal: true
##
# A semi-compatible DSL for the Bundler Gemfile and Isolate gem dependencies
# files.
#
# To work with both the Bundler Gemfile and Isolate formats this
# implementation takes some liberties to allow compatibility with each, most
# notably in #source.
#
# A basic gem dependencies file will look like the following:
#
#   source 'https://rubygems.org'
#
#   gem 'rails', '3.2.14a
#   gem 'devise', '~> 2.1', '>= 2.1.3'
#   gem 'cancan'
#   gem 'airbrake'
#   gem 'pg'
#
# RubyGems recommends saving this as gem.deps.rb over Gemfile or Isolate.
#
# To install the gems in this Gemfile use `gem install -g` to install it and
# create a lockfile.  The lockfile will ensure that when you make changes to
# your gem dependencies file a minimum amount of change is made to the
# dependencies of your gems.
#
# RubyGems can activate all the gems in your dependencies file at startup
# using the RUBYGEMS_GEMDEPS environment variable or through Gem.use_gemdeps.
# See Gem.use_gemdeps for details and warnings.
#
# See `gem help install` and `gem help gem_dependencies` for further details.

class Gem::RequestSet::GemDependencyAPI
  ENGINE_MAP = { # :nodoc:
    :jruby        => %w[jruby],
    :jruby_18     => %w[jruby],
    :jruby_19     => %w[jruby],
    :maglev       => %w[maglev],
    :mri          => %w[ruby],
    :mri_18       => %w[ruby],
    :mri_19       => %w[ruby],
    :mri_20       => %w[ruby],
    :mri_21       => %w[ruby],
    :rbx          => %w[rbx],
    :truffleruby  => %w[truffleruby],
    :ruby         => %w[ruby rbx maglev truffleruby],
    :ruby_18      => %w[ruby rbx maglev truffleruby],
    :ruby_19      => %w[ruby rbx maglev truffleruby],
    :ruby_20      => %w[ruby rbx maglev truffleruby],
    :ruby_21      => %w[ruby rbx maglev truffleruby],
  }.freeze

  mswin     = Gem::Platform.new 'x86-mswin32'
  mswin64   = Gem::Platform.new 'x64-mswin64'
  x86_mingw = Gem::Platform.new 'x86-mingw32'
  x64_mingw = Gem::Platform.new 'x64-mingw32'

  PLATFORM_MAP = { # :nodoc:
    :jruby        => Gem::Platform::RUBY,
    :jruby_18     => Gem::Platform::RUBY,
    :jruby_19     => Gem::Platform::RUBY,
    :maglev       => Gem::Platform::RUBY,
    :mingw        => x86_mingw,
    :mingw_18     => x86_mingw,
    :mingw_19     => x86_mingw,
    :mingw_20     => x86_mingw,
    :mingw_21     => x86_mingw,
    :mri          => Gem::Platform::RUBY,
    :mri_18       => Gem::Platform::RUBY,
    :mri_19       => Gem::Platform::RUBY,
    :mri_20       => Gem::Platform::RUBY,
    :mri_21       => Gem::Platform::RUBY,
    :mswin        => mswin,
    :mswin_18     => mswin,
    :mswin_19     => mswin,
    :mswin_20     => mswin,
    :mswin_21     => mswin,
    :mswin64      => mswin64,
    :mswin64_19   => mswin64,
    :mswin64_20   => mswin64,
    :mswin64_21   => mswin64,
    :rbx          => Gem::Platform::RUBY,
    :ruby         => Gem::Platform::RUBY,
    :ruby_18      => Gem::Platform::RUBY,
    :ruby_19      => Gem::Platform::RUBY,
    :ruby_20      => Gem::Platform::RUBY,
    :ruby_21      => Gem::Platform::RUBY,
    :truffleruby  => Gem::Platform::RUBY,
    :x64_mingw    => x64_mingw,
    :x64_mingw_20 => x64_mingw,
    :x64_mingw_21 => x64_mingw,
  }.freeze

  gt_eq_0        = Gem::Requirement.new '>= 0'
  tilde_gt_1_8_0 = Gem::Requirement.new '~> 1.8.0'
  tilde_gt_1_9_0 = Gem::Requirement.new '~> 1.9.0'
  tilde_gt_2_0_0 = Gem::Requirement.new '~> 2.0.0'
  tilde_gt_2_1_0 = Gem::Requirement.new '~> 2.1.0'

  VERSION_MAP = { # :nodoc:
    :jruby        => gt_eq_0,
    :jruby_18     => tilde_gt_1_8_0,
    :jruby_19     => tilde_gt_1_9_0,
    :maglev       => gt_eq_0,
    :mingw        => gt_eq_0,
    :mingw_18     => tilde_gt_1_8_0,
    :mingw_19     => tilde_gt_1_9_0,
    :mingw_20     => tilde_gt_2_0_0,
    :mingw_21     => tilde_gt_2_1_0,
    :mri          => gt_eq_0,
    :mri_18       => tilde_gt_1_8_0,
    :mri_19       => tilde_gt_1_9_0,
    :mri_20       => tilde_gt_2_0_0,
    :mri_21       => tilde_gt_2_1_0,
    :mswin        => gt_eq_0,
    :mswin_18     => tilde_gt_1_8_0,
    :mswin_19     => tilde_gt_1_9_0,
    :mswin_20     => tilde_gt_2_0_0,
    :mswin_21     => tilde_gt_2_1_0,
    :mswin64      => gt_eq_0,
    :mswin64_19   => tilde_gt_1_9_0,
    :mswin64_20   => tilde_gt_2_0_0,
    :mswin64_21   => tilde_gt_2_1_0,
    :rbx          => gt_eq_0,
    :ruby         => gt_eq_0,
    :ruby_18      => tilde_gt_1_8_0,
    :ruby_19      => tilde_gt_1_9_0,
    :ruby_20      => tilde_gt_2_0_0,
    :ruby_21      => tilde_gt_2_1_0,
    :truffleruby  => gt_eq_0,
    :x64_mingw    => gt_eq_0,
    :x64_mingw_20 => tilde_gt_2_0_0,
    :x64_mingw_21 => tilde_gt_2_1_0,
  }.freeze

  WINDOWS = { # :nodoc:
    :mingw        => :only,
    :mingw_18     => :only,
    :mingw_19     => :only,
    :mingw_20     => :only,
    :mingw_21     => :only,
    :mri          => :never,
    :mri_18       => :never,
    :mri_19       => :never,
    :mri_20       => :never,
    :mri_21       => :never,
    :mswin        => :only,
    :mswin_18     => :only,
    :mswin_19     => :only,
    :mswin_20     => :only,
    :mswin_21     => :only,
    :mswin64      => :only,
    :mswin64_19   => :only,
    :mswin64_20   => :only,
    :mswin64_21   => :only,
    :rbx          => :never,
    :ruby         => :never,
    :ruby_18      => :never,
    :ruby_19      => :never,
    :ruby_20      => :never,
    :ruby_21      => :never,
    :x64_mingw    => :only,
    :x64_mingw_20 => :only,
    :x64_mingw_21 => :only,
  }.freeze

  ##
  # The gems required by #gem statements in the gem.deps.rb file

  attr_reader :dependencies

  ##
  # A set of gems that are loaded via the +:git+ option to #gem

  attr_reader :git_set # :nodoc:

  ##
  # A Hash containing gem names and files to require from those gems.

  attr_reader :requires

  ##
  # A set of gems that are loaded via the +:path+ option to #gem

  attr_reader :vendor_set # :nodoc:

  ##
  # The groups of gems to exclude from installation

  attr_accessor :without_groups # :nodoc:

  ##
  # Creates a new GemDependencyAPI that will add dependencies to the
  # Gem::RequestSet +set+ based on the dependency API description in +path+.

  def initialize(set, path)
    @set = set
    @path = path

    @current_groups     = nil
    @current_platforms  = nil
    @current_repository = nil
    @dependencies       = {}
    @default_sources    = true
    @git_set            = @set.git_set
    @git_sources        = {}
    @installing         = false
    @requires           = Hash.new {|h, name| h[name] = [] }
    @vendor_set         = @set.vendor_set
    @source_set         = @set.source_set
    @gem_sources        = {}
    @without_groups     = []

    git_source :github do |repo_name|
      repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include? "/"

      "git://github.com/#{repo_name}.git"
    end

    git_source :bitbucket do |repo_name|
      repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include? "/"

      user, = repo_name.split "/", 2

      "https://#{user}@bitbucket.org/#{repo_name}.git"
    end
  end

  ##
  # Adds +dependencies+ to the request set if any of the +groups+ are allowed.
  # This is used for gemspec dependencies.

  def add_dependencies(groups, dependencies) # :nodoc:
    return unless (groups & @without_groups).empty?

    dependencies.each do |dep|
      @set.gem dep.name, *dep.requirement.as_list
    end
  end

  private :add_dependencies

  ##
  # Finds a gemspec with the given +name+ that lives at +path+.

  def find_gemspec(name, path) # :nodoc:
    glob = File.join path, "#{name}.gemspec"

    spec_files = Dir[glob]

    case spec_files.length
    when 1 then
      spec_file = spec_files.first

      spec = Gem::Specification.load spec_file

      return spec if spec

      raise ArgumentError, "invalid gemspec #{spec_file}"
    when 0 then
      raise ArgumentError, "no gemspecs found at #{Dir.pwd}"
    else
      raise ArgumentError,
        "found multiple gemspecs at #{Dir.pwd}, " +
        "use the name: option to specify the one you want"
    end
  end

  ##
  # Changes the behavior of gem dependency file loading to installing mode.
  # In installing mode certain restrictions are ignored such as ruby version
  # mismatch checks.

  def installing=(installing) # :nodoc:
    @installing = installing
  end

  ##
  # Loads the gem dependency file and returns self.

  def load
    instance_eval File.read(@path).tap(&Gem::UNTAINT), @path, 1

    self
  end

  ##
  # :category: Gem Dependencies DSL
  #
  # :call-seq:
  #   gem(name)
  #   gem(name, *requirements)
  #   gem(name, *requirements, options)
  #
  # Specifies a gem dependency with the given +name+ and +requirements+.  You
  # may also supply +options+ following the +requirements+
  #
  # +options+ include:
  #
  # require: ::
  #   RubyGems does not provide any autorequire features so requires in a gem
  #   dependencies file are recorded but ignored.
  #
  #   In bundler the require: option overrides the file to require during
  #   Bundler.require.  By default the name of the dependency is required in
  #   Bundler.  A single file or an Array of files may be given.
  #
  #   To disable requiring any file give +false+:
  #
  #     gem 'rake', require: false
  #
  # group: ::
  #   Place the dependencies in the given dependency group.  A single group or
  #   an Array of groups may be given.
  #
  #   See also #group
  #
  # platform: ::
  #   Only install the dependency on the given platform.  A single platform or
  #   an Array of platforms may be given.
  #
  #   See #platform for a list of platforms available.
  #
  # path: ::
  #   Install this dependency from an unpacked gem in the given directory.
  #
  #     gem 'modified_gem', path: 'vendor/modified_gem'
  #
  # git: ::
  #   Install this dependency from a git repository:
  #
  #     gem 'private_gem', git: git@my.company.example:private_gem.git'
  #
  # gist: ::
  #   Install this dependency from the gist ID:
  #
  #     gem 'bang', gist: '1232884'
  #
  # github: ::
  #   Install this dependency from a github git repository:
  #
  #     gem 'private_gem', github: 'my_company/private_gem'
  #
  # submodules: ::
  #   Set to +true+ to include submodules when fetching the git repository for
  #   git:, gist: and github: dependencies.
  #
  # ref: ::
  #   Use the given commit name or SHA for git:, gist: and github:
  #   dependencies.
  #
  # branch: ::
  #   Use the given branch for git:, gist: and github: dependencies.
  #
  # tag: ::
  #   Use the given tag for git:, gist: and github: dependencies.

  def gem(name, *requirements)
    options = requirements.pop if requirements.last.kind_of?(Hash)
    options ||= {}

    options[:git] = @current_repository if @current_repository

    source_set = false

    source_set ||= gem_path       name, options
    source_set ||= gem_git        name, options
    source_set ||= gem_git_source name, options
    source_set ||= gem_source     name, options

    duplicate = @dependencies.include? name

    @dependencies[name] =
      if requirements.empty? and not source_set
        Gem::Requirement.default
      elsif source_set
        Gem::Requirement.source_set
      else
        Gem::Requirement.create requirements
      end

    return unless gem_platforms name, options

    groups = gem_group name, options

    return unless (groups & @without_groups).empty?

    pin_gem_source name, :default unless source_set

    gem_requires name, options

    if duplicate
      warn <<-WARNING
Gem dependencies file #{@path} requires #{name} more than once.
      WARNING
    end

    @set.gem name, *requirements
  end

  ##
  # Handles the git: option from +options+ for gem +name+.
  #
  # Returns +true+ if the gist or git option was handled.

  def gem_git(name, options) # :nodoc:
    if gist = options.delete(:gist)
      options[:git] = "https://gist.github.com/#{gist}.git"
    end

    return unless repository = options.delete(:git)

    pin_gem_source name, :git, repository

    reference = gem_git_reference options

    submodules = options.delete :submodules

    @git_set.add_git_gem name, repository, reference, submodules

    true
  end

  ##
  # Handles the git options from +options+ for git gem.
  #
  # Returns reference for the git gem.

  def gem_git_reference(options) # :nodoc:
    ref    = options.delete :ref
    branch = options.delete :branch
    tag    = options.delete :tag

    reference = nil
    reference ||= ref
    reference ||= branch
    reference ||= tag
    reference ||= 'master'

    if ref && branch
      warn <<-WARNING
Gem dependencies file #{@path} includes git reference for both ref and branch but only ref is used.
      WARNING
    end
    if (ref || branch) && tag
      warn <<-WARNING
Gem dependencies file #{@path} includes git reference for both ref/branch and tag but only ref/branch is used.
      WARNING
    end

    reference
  end

  private :gem_git

  ##
  # Handles a git gem option from +options+ for gem +name+ for a git source
  # registered through git_source.
  #
  # Returns +true+ if the custom source option was handled.

  def gem_git_source(name, options) # :nodoc:
    return unless git_source = (@git_sources.keys & options.keys).last

    source_callback = @git_sources[git_source]
    source_param = options.delete git_source

    git_url = source_callback.call source_param

    options[:git] = git_url

    gem_git name, options

    true
  end

  private :gem_git_source

  ##
  # Handles the :group and :groups +options+ for the gem with the given
  # +name+.

  def gem_group(name, options) # :nodoc:
    g = options.delete :group
    all_groups = g ? Array(g) : []

    groups = options.delete :groups
    all_groups |= groups if groups

    all_groups |= @current_groups if @current_groups

    all_groups
  end

  private :gem_group

  ##
  # Handles the path: option from +options+ for gem +name+.
  #
  # Returns +true+ if the path option was handled.

  def gem_path(name, options) # :nodoc:
    return unless directory = options.delete(:path)

    pin_gem_source name, :path, directory

    @vendor_set.add_vendor_gem name, directory

    true
  end

  private :gem_path

  ##
  # Handles the source: option from +options+ for gem +name+.
  #
  # Returns +true+ if the source option was handled.

  def gem_source(name, options) # :nodoc:
    return unless source = options.delete(:source)

    pin_gem_source name, :source, source

    @source_set.add_source_gem name, source

    true
  end

  private :gem_source

  ##
  # Handles the platforms: option from +options+.  Returns true if the
  # platform matches the current platform.

  def gem_platforms(name, options) # :nodoc:
    platform_names = Array(options.delete :platform)
    platform_names.concat Array(options.delete :platforms)
    platform_names.concat @current_platforms if @current_platforms

    return true if platform_names.empty?

    platform_names.any? do |platform_name|
      raise ArgumentError, "unknown platform #{platform_name.inspect}" unless
        platform = PLATFORM_MAP[platform_name]

      next false unless Gem::Platform.match_gem? platform, name

      if engines = ENGINE_MAP[platform_name]
        next false unless engines.include? Gem.ruby_engine
      end

      case WINDOWS[platform_name]
      when :only then
        next false unless Gem.win_platform?
      when :never then
        next false if Gem.win_platform?
      end

      VERSION_MAP[platform_name].satisfied_by? Gem.ruby_version
    end
  end

  private :gem_platforms

  ##
  # Records the require: option from +options+ and adds those files, or the
  # default file to the require list for +name+.

  def gem_requires(name, options) # :nodoc:
    if options.include? :require
      if requires = options.delete(:require)
        @requires[name].concat Array requires
      end
    else
      @requires[name] << name
    end
    raise ArgumentError, "Unhandled gem options #{options.inspect}" unless options.empty?
  end

  private :gem_requires

  ##
  # :category: Gem Dependencies DSL
  #
  # Block form for specifying gems from a git +repository+.
  #
  #   git 'https://github.com/rails/rails.git' do
  #     gem 'activesupport'
  #     gem 'activerecord'
  #   end

  def git(repository)
    @current_repository = repository

    yield

  ensure
    @current_repository = nil
  end

  ##
  # Defines a custom git source that uses +name+ to expand git repositories
  # for use in gems built from git repositories.  You must provide a block
  # that accepts a git repository name for expansion.

  def git_source(name, &callback)
    @git_sources[name] = callback
  end

  ##
  # Returns the basename of the file the dependencies were loaded from

  def gem_deps_file # :nodoc:
    File.basename @path
  end

  ##
  # :category: Gem Dependencies DSL
  #
  # Loads dependencies from a gemspec file.
  #
  # +options+ include:
  #
  # name: ::
  #   The name portion of the gemspec file.  Defaults to searching for any
  #   gemspec file in the current directory.
  #
  #     gemspec name: 'my_gem'
  #
  # path: ::
  #   The path the gemspec lives in.  Defaults to the current directory:
  #
  #     gemspec 'my_gem', path: 'gemspecs', name: 'my_gem'
  #
  # development_group: ::
  #   The group to add development dependencies to.  By default this is
  #   :development.  Only one group may be specified.

  def gemspec(options = {})
    name              = options.delete(:name) || '{,*}'
    path              = options.delete(:path) || '.'
    development_group = options.delete(:development_group) || :development

    spec = find_gemspec name, path

    groups = gem_group spec.name, {}

    self_dep = Gem::Dependency.new spec.name, spec.version

    add_dependencies groups, [self_dep]
    add_dependencies groups, spec.runtime_dependencies

    @dependencies[spec.name] = Gem::Requirement.source_set

    spec.dependencies.each do |dep|
      @dependencies[dep.name] = dep.requirement
    end

    groups << development_group

    add_dependencies groups, spec.development_dependencies

    @vendor_set.add_vendor_gem spec.name, path
    gem_requires spec.name, options
  end

  ##
  # :category: Gem Dependencies DSL
  #
  # Block form for placing a dependency in the given +groups+.
  #
  #   group :development do
  #     gem 'debugger'
  #   end
  #
  #   group :development, :test do
  #     gem 'minitest'
  #   end
  #
  # Groups can be excluded at install time using `gem install -g --without
  # development`.  See `gem help install` and `gem help gem_dependencies` for
  # further details.

  def group(*groups)
    @current_groups = groups

    yield

  ensure
    @current_groups = nil
  end

  ##
  # Pins the gem +name+ to the given +source+.  Adding a gem with the same
  # name from a different +source+ will raise an exception.

  def pin_gem_source(name, type = :default, source = nil)
    source_description =
      case type
      when :default then '(default)'
      when :path    then "path: #{source}"
      when :git     then "git: #{source}"
      when :source  then "source: #{source}"
      else               '(unknown)'
      end

    raise ArgumentError,
      "duplicate source #{source_description} for gem #{name}" if
        @gem_sources.fetch(name, source) != source

    @gem_sources[name] = source
  end

  private :pin_gem_source

  ##
  # :category: Gem Dependencies DSL
  #
  # Block form for restricting gems to a set of platforms.
  #
  # The gem dependencies platform is different from Gem::Platform.  A platform
  # gem.deps.rb platform matches on the ruby engine, the ruby version and
  # whether or not windows is allowed.
  #
  # :ruby, :ruby_XY ::
  #   Matches non-windows, non-jruby implementations where X and Y can be used
  #   to match releases in the 1.8, 1.9, 2.0 or 2.1 series.
  #
  # :mri, :mri_XY ::
  #   Matches non-windows C Ruby (Matz Ruby) or only the 1.8, 1.9, 2.0 or
  #   2.1 series.
  #
  # :mingw, :mingw_XY ::
  #   Matches 32 bit C Ruby on MinGW or only the 1.8, 1.9, 2.0 or 2.1 series.
  #
  # :x64_mingw, :x64_mingw_XY ::
  #   Matches 64 bit C Ruby on MinGW or only the 1.8, 1.9, 2.0 or 2.1 series.
  #
  # :mswin, :mswin_XY ::
  #   Matches 32 bit C Ruby on Microsoft Windows or only the 1.8, 1.9, 2.0 or
  #   2.1 series.
  #
  # :mswin64, :mswin64_XY ::
  #   Matches 64 bit C Ruby on Microsoft Windows or only the 1.8, 1.9, 2.0 or
  #   2.1 series.
  #
  # :jruby, :jruby_XY ::
  #   Matches JRuby or JRuby in 1.8 or 1.9 mode.
  #
  # :maglev ::
  #   Matches Maglev
  #
  # :rbx ::
  #   Matches non-windows Rubinius
  #
  # NOTE:  There is inconsistency in what environment a platform matches.  You
  # may need to read the source to know the exact details.

  def platform(*platforms)
    @current_platforms = platforms

    yield

  ensure
    @current_platforms = nil
  end

  ##
  # :category: Gem Dependencies DSL
  #
  # Block form for restricting gems to a particular set of platforms.  See
  # #platform.

  alias :platforms :platform

  ##
  # :category: Gem Dependencies DSL
  #
  # Restricts this gem dependencies file to the given ruby +version+.
  #
  # You may also provide +engine:+ and +engine_version:+ options to restrict
  # this gem dependencies file to a particular ruby engine and its engine
  # version.  This matching is performed by using the RUBY_ENGINE and
  # RUBY_ENGINE_VERSION constants.

  def ruby(version, options = {})
    engine         = options[:engine]
    engine_version = options[:engine_version]

    raise ArgumentError,
          'You must specify engine_version along with the Ruby engine' if
            engine and not engine_version

    return true if @installing

    unless RUBY_VERSION == version
      message = "Your Ruby version is #{RUBY_VERSION}, " +
                "but your #{gem_deps_file} requires #{version}"

      raise Gem::RubyVersionMismatch, message
    end

    if engine and engine != Gem.ruby_engine
      message = "Your Ruby engine is #{Gem.ruby_engine}, " +
                "but your #{gem_deps_file} requires #{engine}"

      raise Gem::RubyVersionMismatch, message
    end

    if engine_version
      if engine_version != RUBY_ENGINE_VERSION
        message =
          "Your Ruby engine version is #{Gem.ruby_engine} #{RUBY_ENGINE_VERSION}, " +
          "but your #{gem_deps_file} requires #{engine} #{engine_version}"

        raise Gem::RubyVersionMismatch, message
      end
    end

    return true
  end

  ##
  # :category: Gem Dependencies DSL
  #
  # Sets +url+ as a source for gems for this dependency API.  RubyGems uses
  # the default configured sources if no source was given.  If a source is set
  # only that source is used.
  #
  # This method differs in behavior from Bundler:
  #
  # * The +:gemcutter+, # +:rubygems+ and +:rubyforge+ sources are not
  #   supported as they are deprecated in bundler.
  # * The +prepend:+ option is not supported.  If you wish to order sources
  #   then list them in your preferred order.

  def source(url)
    Gem.sources.clear if @default_sources

    @default_sources = false

    Gem.sources << url
  end
end
# frozen_string_literal: true
require_relative 'parser'

class Gem::RequestSet::Lockfile::Tokenizer
  Token = Struct.new :type, :value, :column, :line
  EOF   = Token.new :EOF

  def self.from_file(file)
    new File.read(file), file
  end

  def initialize(input, filename = nil, line = 0, pos = 0)
    @line     = line
    @line_pos = pos
    @tokens   = []
    @filename = filename
    tokenize input
  end

  def make_parser(set, platforms)
    Gem::RequestSet::Lockfile::Parser.new self, set, platforms, @filename
  end

  def to_a
    @tokens.map {|token| [token.type, token.value, token.column, token.line] }
  end

  def skip(type)
    @tokens.shift while not @tokens.empty? and peek.type == type
  end

  ##
  # Calculates the column (by byte) and the line of the current token based on
  # +byte_offset+.

  def token_pos(byte_offset) # :nodoc:
    [byte_offset - @line_pos, @line]
  end

  def empty?
    @tokens.empty?
  end

  def unshift(token)
    @tokens.unshift token
  end

  def next_token
    @tokens.shift
  end
  alias :shift :next_token

  def peek
    @tokens.first || EOF
  end

  private

  def tokenize(input)
    require 'strscan'
    s = StringScanner.new input

    until s.eos? do
      pos = s.pos

      pos = s.pos if leading_whitespace = s.scan(/ +/)

      if s.scan(/[<|=>]{7}/)
        message = "your #{@filename} contains merge conflict markers"
        column, line = token_pos pos

        raise Gem::RequestSet::Lockfile::ParseError.new message, column, line, @filename
      end

      @tokens <<
        case
        when s.scan(/\r?\n/) then
          token = Token.new(:newline, nil, *token_pos(pos))
          @line_pos = s.pos
          @line += 1
          token
        when s.scan(/[A-Z]+/) then
          if leading_whitespace
            text = s.matched
            text += s.scan(/[^\s)]*/).to_s # in case of no match
            Token.new(:text, text, *token_pos(pos))
          else
            Token.new(:section, s.matched, *token_pos(pos))
          end
        when s.scan(/([a-z]+):\s/) then
          s.pos -= 1 # rewind for possible newline
          Token.new(:entry, s[1], *token_pos(pos))
        when s.scan(/\(/) then
          Token.new(:l_paren, nil, *token_pos(pos))
        when s.scan(/\)/) then
          Token.new(:r_paren, nil, *token_pos(pos))
        when s.scan(/<=|>=|=|~>|<|>|!=/) then
          Token.new(:requirement, s.matched, *token_pos(pos))
        when s.scan(/,/) then
          Token.new(:comma, nil, *token_pos(pos))
        when s.scan(/!/) then
          Token.new(:bang, nil, *token_pos(pos))
        when s.scan(/[^\s),!]*/) then
          Token.new(:text, s.matched, *token_pos(pos))
        else
          raise "BUG: can't create token for: #{s.string[s.pos..-1].inspect}"
        end
    end

    @tokens
  end
end
# frozen_string_literal: true
class Gem::RequestSet::Lockfile::Parser
  ###
  # Parses lockfiles

  def initialize(tokenizer, set, platforms, filename = nil)
    @tokens    = tokenizer
    @filename  = filename
    @set       = set
    @platforms = platforms
  end

  def parse
    until @tokens.empty? do
      token = get

      case token.type
      when :section then
        @tokens.skip :newline

        case token.value
        when 'DEPENDENCIES' then
          parse_DEPENDENCIES
        when 'GIT' then
          parse_GIT
        when 'GEM' then
          parse_GEM
        when 'PATH' then
          parse_PATH
        when 'PLATFORMS' then
          parse_PLATFORMS
        else
          token = get until @tokens.empty? or peek.first == :section
        end
      else
        raise "BUG: unhandled token #{token.type} (#{token.value.inspect}) at line #{token.line} column #{token.column}"
      end
    end
  end

  ##
  # Gets the next token for a Lockfile

  def get(expected_types = nil, expected_value = nil) # :nodoc:
    token = @tokens.shift

    if expected_types and not Array(expected_types).include? token.type
      unget token

      message = "unexpected token [#{token.type.inspect}, #{token.value.inspect}], " +
                "expected #{expected_types.inspect}"

      raise Gem::RequestSet::Lockfile::ParseError.new message, token.column, token.line, @filename
    end

    if expected_value and expected_value != token.value
      unget token

      message = "unexpected token [#{token.type.inspect}, #{token.value.inspect}], " +
                "expected [#{expected_types.inspect}, " +
                "#{expected_value.inspect}]"

      raise Gem::RequestSet::Lockfile::ParseError.new message, token.column, token.line, @filename
    end

    token
  end

  def parse_DEPENDENCIES # :nodoc:
    while not @tokens.empty? and :text == peek.type do
      token = get :text

      requirements = []

      case peek[0]
      when :bang then
        get :bang

        requirements << pinned_requirement(token.value)
      when :l_paren then
        get :l_paren

        loop do
          op      = get(:requirement).value
          version = get(:text).value

          requirements << "#{op} #{version}"

          break unless peek.type == :comma

          get :comma
        end

        get :r_paren

        if peek[0] == :bang
          requirements.clear
          requirements << pinned_requirement(token.value)

          get :bang
        end
      end

      @set.gem token.value, *requirements

      skip :newline
    end
  end

  def parse_GEM # :nodoc:
    sources = []

    while [:entry, 'remote'] == peek.first(2) do
      get :entry, 'remote'
      data = get(:text).value
      skip :newline

      sources << Gem::Source.new(data)
    end

    sources << Gem::Source.new(Gem::DEFAULT_HOST) if sources.empty?

    get :entry, 'specs'

    skip :newline

    set = Gem::Resolver::LockSet.new sources
    last_specs = nil

    while not @tokens.empty? and :text == peek.type do
      token = get :text
      name = token.value
      column = token.column

      case peek[0]
      when :newline then
        last_specs.each do |spec|
          spec.add_dependency Gem::Dependency.new name if column == 6
        end
      when :l_paren then
        get :l_paren

        token = get [:text, :requirement]
        type = token.type
        data = token.value

        if type == :text and column == 4
          version, platform = data.split '-', 2

          platform =
            platform ? Gem::Platform.new(platform) : Gem::Platform::RUBY

          last_specs = set.add name, version, platform
        else
          dependency = parse_dependency name, data

          last_specs.each do |spec|
            spec.add_dependency dependency
          end
        end

        get :r_paren
      else
        raise "BUG: unknown token #{peek}"
      end

      skip :newline
    end

    @set.sets << set
  end

  def parse_GIT # :nodoc:
    get :entry, 'remote'
    repository = get(:text).value

    skip :newline

    get :entry, 'revision'
    revision = get(:text).value

    skip :newline

    type = peek.type
    value = peek.value
    if type == :entry and %w[branch ref tag].include? value
      get
      get :text

      skip :newline
    end

    get :entry, 'specs'

    skip :newline

    set = Gem::Resolver::GitSet.new
    set.root_dir = @set.install_dir

    last_spec = nil

    while not @tokens.empty? and :text == peek.type do
      token = get :text
      name = token.value
      column = token.column

      case peek[0]
      when :newline then
        last_spec.add_dependency Gem::Dependency.new name if column == 6
      when :l_paren then
        get :l_paren

        token = get [:text, :requirement]
        type = token.type
        data = token.value

        if type == :text and column == 4
          last_spec = set.add_git_spec name, data, repository, revision, true
        else
          dependency = parse_dependency name, data

          last_spec.add_dependency dependency
        end

        get :r_paren
      else
        raise "BUG: unknown token #{peek}"
      end

      skip :newline
    end

    @set.sets << set
  end

  def parse_PATH # :nodoc:
    get :entry, 'remote'
    directory = get(:text).value

    skip :newline

    get :entry, 'specs'

    skip :newline

    set = Gem::Resolver::VendorSet.new
    last_spec = nil

    while not @tokens.empty? and :text == peek.first do
      token = get :text
      name = token.value
      column = token.column

      case peek[0]
      when :newline then
        last_spec.add_dependency Gem::Dependency.new name if column == 6
      when :l_paren then
        get :l_paren

        token = get [:text, :requirement]
        type = token.type
        data = token.value

        if type == :text and column == 4
          last_spec = set.add_vendor_gem name, directory
        else
          dependency = parse_dependency name, data

          last_spec.dependencies << dependency
        end

        get :r_paren
      else
        raise "BUG: unknown token #{peek}"
      end

      skip :newline
    end

    @set.sets << set
  end

  def parse_PLATFORMS # :nodoc:
    while not @tokens.empty? and :text == peek.first do
      name = get(:text).value

      @platforms << name

      skip :newline
    end
  end

  ##
  # Parses the requirements following the dependency +name+ and the +op+ for
  # the first token of the requirements and returns a Gem::Dependency object.

  def parse_dependency(name, op) # :nodoc:
    return Gem::Dependency.new name, op unless peek[0] == :text

    version = get(:text).value

    requirements = ["#{op} #{version}"]

    while peek.type == :comma do
      get :comma
      op      = get(:requirement).value
      version = get(:text).value

      requirements << "#{op} #{version}"
    end

    Gem::Dependency.new name, requirements
  end

  private

  def skip(type) # :nodoc:
    @tokens.skip type
  end

  ##
  # Peeks at the next token for Lockfile

  def peek # :nodoc:
    @tokens.peek
  end

  def pinned_requirement(name) # :nodoc:
    requirement = Gem::Dependency.new name
    specification = @set.sets.flat_map do |set|
      set.find_all(requirement)
    end.compact.first

    specification && specification.version
  end

  ##
  # Ungets the last token retrieved by #get

  def unget(token) # :nodoc:
    @tokens.unshift token
  end
end
# frozen_string_literal: true
##
# Parses a gem.deps.rb.lock file and constructs a LockSet containing the
# dependencies found inside.  If the lock file is missing no LockSet is
# constructed.

class Gem::RequestSet::Lockfile
  ##
  # Raised when a lockfile cannot be parsed

  class ParseError < Gem::Exception
    ##
    # The column where the error was encountered

    attr_reader :column

    ##
    # The line where the error was encountered

    attr_reader :line

    ##
    # The location of the lock file

    attr_reader :path

    ##
    # Raises a ParseError with the given +message+ which was encountered at a
    # +line+ and +column+ while parsing.

    def initialize(message, column, line, path)
      @line   = line
      @column = column
      @path   = path
      super "#{message} (at line #{line} column #{column})"
    end
  end

  ##
  # Creates a new Lockfile for the given +request_set+ and +gem_deps_file+
  # location.

  def self.build(request_set, gem_deps_file, dependencies = nil)
    request_set.resolve
    dependencies ||= requests_to_deps request_set.sorted_requests
    new request_set, gem_deps_file, dependencies
  end

  def self.requests_to_deps(requests) # :nodoc:
    deps = {}

    requests.each do |request|
      spec        = request.spec
      name        = request.name
      requirement = request.request.dependency.requirement

      deps[name] = if [Gem::Resolver::VendorSpecification,
                       Gem::Resolver::GitSpecification].include? spec.class
                     Gem::Requirement.source_set
                   else
                     requirement
                   end
    end

    deps
  end

  ##
  # The platforms for this Lockfile

  attr_reader :platforms

  def initialize(request_set, gem_deps_file, dependencies)
    @set           = request_set
    @dependencies  = dependencies
    @gem_deps_file = File.expand_path(gem_deps_file)
    @gem_deps_dir  = File.dirname(@gem_deps_file)

    if RUBY_VERSION < '2.7'
      @gem_deps_file.untaint unless gem_deps_file.tainted?
    end

    @platforms = []
  end

  def add_DEPENDENCIES(out) # :nodoc:
    out << "DEPENDENCIES"

    out.concat @dependencies.sort_by {|name,| name }.map {|name, requirement|
      "  #{name}#{requirement.for_lockfile}"
    }

    out << nil
  end

  def add_GEM(out, spec_groups) # :nodoc:
    return if spec_groups.empty?

    source_groups = spec_groups.values.flatten.group_by do |request|
      request.spec.source.uri
    end

    source_groups.sort_by {|group,| group.to_s }.map do |group, requests|
      out << "GEM"
      out << "  remote: #{group}"
      out << "  specs:"

      requests.sort_by {|request| request.name }.each do |request|
        next if request.spec.name == 'bundler'
        platform = "-#{request.spec.platform}" unless
          Gem::Platform::RUBY == request.spec.platform

        out << "    #{request.name} (#{request.version}#{platform})"

        request.full_spec.dependencies.sort.each do |dependency|
          next if dependency.type == :development

          requirement = dependency.requirement
          out << "      #{dependency.name}#{requirement.for_lockfile}"
        end
      end
      out << nil
    end
  end

  def add_GIT(out, git_requests)
    return if git_requests.empty?

    by_repository_revision = git_requests.group_by do |request|
      source = request.spec.source
      [source.repository, source.rev_parse]
    end

    by_repository_revision.each do |(repository, revision), requests|
      out << "GIT"
      out << "  remote: #{repository}"
      out << "  revision: #{revision}"
      out << "  specs:"

      requests.sort_by {|request| request.name }.each do |request|
        out << "    #{request.name} (#{request.version})"

        dependencies = request.spec.dependencies.sort_by {|dep| dep.name }
        dependencies.each do |dep|
          out << "      #{dep.name}#{dep.requirement.for_lockfile}"
        end
      end
      out << nil
    end
  end

  def relative_path_from(dest, base) # :nodoc:
    dest = File.expand_path(dest)
    base = File.expand_path(base)

    if dest.index(base) == 0
      offset = dest[base.size + 1..-1]

      return '.' unless offset

      offset
    else
      dest
    end
  end

  def add_PATH(out, path_requests) # :nodoc:
    return if path_requests.empty?

    out << "PATH"
    path_requests.each do |request|
      directory = File.expand_path(request.spec.source.uri)

      out << "  remote: #{relative_path_from directory, @gem_deps_dir}"
      out << "  specs:"
      out << "    #{request.name} (#{request.version})"
    end

    out << nil
  end

  def add_PLATFORMS(out) # :nodoc:
    out << "PLATFORMS"

    platforms = requests.map {|request| request.spec.platform }.uniq

    platforms = platforms.sort_by {|platform| platform.to_s }

    platforms.each do |platform|
      out << "  #{platform}"
    end

    out << nil
  end

  def spec_groups
    requests.group_by {|request| request.spec.class }
  end

  ##
  # The contents of the lock file.

  def to_s
    out = []

    groups = spec_groups

    add_PATH out, groups.delete(Gem::Resolver::VendorSpecification) { [] }

    add_GIT out, groups.delete(Gem::Resolver::GitSpecification) { [] }

    add_GEM out, groups

    add_PLATFORMS out

    add_DEPENDENCIES out

    out.join "\n"
  end

  ##
  # Writes the lock file alongside the gem dependencies file

  def write
    content = to_s

    File.open "#{@gem_deps_file}.lock", 'w' do |io|
      io.write content
    end
  end

  private

  def requests
    @set.sorted_requests
  end
end

require_relative 'lockfile/tokenizer'
# frozen_string_literal: true
##
# A connection "pool" that only manages one connection for now.  Provides
# thread safe `checkout` and `checkin` methods.  The pool consists of one
# connection that corresponds to `http_args`.  This class is private, do not
# use it.

class Gem::Request::HTTPPool # :nodoc:
  attr_reader :cert_files, :proxy_uri

  def initialize(http_args, cert_files, proxy_uri)
    @http_args  = http_args
    @cert_files = cert_files
    @proxy_uri  = proxy_uri
    @queue      = Thread::SizedQueue.new 1
    @queue << nil
  end

  def checkout
    @queue.pop || make_connection
  end

  def checkin(connection)
    @queue.push connection
  end

  def close_all
    until @queue.empty?
      if connection = @queue.pop(true) and connection.started?
        connection.finish
      end
    end
    @queue.push(nil)
  end

  private

  def make_connection
    setup_connection Gem::Request::ConnectionPools.client.new(*@http_args)
  end

  def setup_connection(connection)
    connection.start
    connection
  end
end
# frozen_string_literal: true

class Gem::Request::ConnectionPools # :nodoc:
  @client = Net::HTTP

  class << self
    attr_accessor :client
  end

  def initialize(proxy_uri, cert_files)
    @proxy_uri  = proxy_uri
    @cert_files = cert_files
    @pools      = {}
    @pool_mutex = Thread::Mutex.new
  end

  def pool_for(uri)
    http_args = net_http_args(uri, @proxy_uri)
    key       = http_args + [https?(uri)]
    @pool_mutex.synchronize do
      @pools[key] ||=
        if https? uri
          Gem::Request::HTTPSPool.new(http_args, @cert_files, @proxy_uri)
        else
          Gem::Request::HTTPPool.new(http_args, @cert_files, @proxy_uri)
        end
    end
  end

  def close_all
    @pools.each_value {|pool| pool.close_all }
  end

  private

  ##
  # Returns list of no_proxy entries (if any) from the environment

  def get_no_proxy_from_env
    env_no_proxy = ENV['no_proxy'] || ENV['NO_PROXY']

    return [] if env_no_proxy.nil? or env_no_proxy.empty?

    env_no_proxy.split(/\s*,\s*/)
  end

  def https?(uri)
    uri.scheme.downcase == 'https'
  end

  def no_proxy?(host, env_no_proxy)
    host = host.downcase

    env_no_proxy.any? do |pattern|
      env_no_proxy_pattern = pattern.downcase.dup

      # Remove dot in front of pattern for wildcard matching
      env_no_proxy_pattern[0] = "" if env_no_proxy_pattern[0] == "."

      host_tokens = host.split(".")
      pattern_tokens = env_no_proxy_pattern.split(".")

      intersection = (host_tokens - pattern_tokens) | (pattern_tokens - host_tokens)

      # When we do the split into tokens we miss a dot character, so add it back if we need it
      missing_dot = intersection.length > 0 ? 1 : 0
      start = intersection.join(".").size + missing_dot

      no_proxy_host = host[start..-1]

      env_no_proxy_pattern == no_proxy_host
    end
  end

  def net_http_args(uri, proxy_uri)
    hostname = uri.hostname
    net_http_args = [hostname, uri.port]

    no_proxy = get_no_proxy_from_env

    if proxy_uri and not no_proxy?(hostname, no_proxy)
      proxy_hostname = proxy_uri.respond_to?(:hostname) ? proxy_uri.hostname : proxy_uri.host
      net_http_args + [
        proxy_hostname,
        proxy_uri.port,
        Gem::UriFormatter.new(proxy_uri.user).unescape,
        Gem::UriFormatter.new(proxy_uri.password).unescape,
      ]
    elsif no_proxy? hostname, no_proxy
      net_http_args + [nil, nil]
    else
      net_http_args
    end
  end
end
# frozen_string_literal: true
class Gem::Request::HTTPSPool < Gem::Request::HTTPPool # :nodoc:
  private

  def setup_connection(connection)
    Gem::Request.configure_connection_for_https(connection, @cert_files)
    super
  end
end
# frozen_string_literal: true
module Gem
  DEFAULT_HOST = "https://rubygems.org".freeze

  @post_install_hooks ||= []
  @done_installing_hooks ||= []
  @post_uninstall_hooks ||= []
  @pre_uninstall_hooks  ||= []
  @pre_install_hooks    ||= []

  ##
  # An Array of the default sources that come with RubyGems

  def self.default_sources
    %w[https://rubygems.org/]
  end

  ##
  # Default spec directory path to be used if an alternate value is not
  # specified in the environment

  def self.default_spec_cache_dir
    default_spec_cache_dir = File.join Gem.user_home, '.gem', 'specs'

    unless File.exist?(default_spec_cache_dir)
      default_spec_cache_dir = File.join Gem.data_home, 'gem', 'specs'
    end

    default_spec_cache_dir
  end

  ##
  # Default home directory path to be used if an alternate value is not
  # specified in the environment

  def self.default_dir
    path = if defined? RUBY_FRAMEWORK_VERSION
             [
               File.dirname(RbConfig::CONFIG['sitedir']),
               'Gems',
               RbConfig::CONFIG['ruby_version_dir_name'] || RbConfig::CONFIG['ruby_version']
             ]
           else
             [
               RbConfig::CONFIG['rubylibprefix'],
               'gems',
               RbConfig::CONFIG['ruby_version_dir_name'] || RbConfig::CONFIG['ruby_version']
             ]
           end

    @default_dir ||= File.join(*path)
  end

  ##
  # Returns binary extensions dir for specified RubyGems base dir or nil
  # if such directory cannot be determined.
  #
  # By default, the binary extensions are located side by side with their
  # Ruby counterparts, therefore nil is returned

  def self.default_ext_dir_for(base_dir)
    nil
  end

  ##
  # Paths where RubyGems' .rb files and bin files are installed

  def self.default_rubygems_dirs
    nil # default to standard layout
  end

  ##
  # Path to specification files of default gems.

  def self.default_specifications_dir
    @default_specifications_dir ||= File.join(Gem.default_dir, "specifications", "default")
  end

  ##
  # Finds the user's home directory.
  #--
  # Some comments from the ruby-talk list regarding finding the home
  # directory:
  #
  #   I have HOME, USERPROFILE and HOMEDRIVE + HOMEPATH. Ruby seems
  #   to be depending on HOME in those code samples. I propose that
  #   it should fallback to USERPROFILE and HOMEDRIVE + HOMEPATH (at
  #   least on Win32).
  #++
  #--
  #
  #++

  def self.find_home
    Dir.home.dup
  rescue
    if Gem.win_platform?
      File.expand_path File.join(ENV['HOMEDRIVE'] || ENV['SystemDrive'], '/')
    else
      File.expand_path "/"
    end
  end

  private_class_method :find_home

  ##
  # The home directory for the user.

  def self.user_home
    @user_home ||= find_home.tap(&Gem::UNTAINT)
  end

  ##
  # Path for gems in the user's home directory

  def self.user_dir
    gem_dir = File.join(Gem.user_home, ".gem")
    gem_dir = File.join(Gem.data_home, "gem") unless File.exist?(gem_dir)
    parts = [gem_dir, ruby_engine]
    ruby_version_dir_name = RbConfig::CONFIG['ruby_version_dir_name'] || RbConfig::CONFIG['ruby_version']
    parts << ruby_version_dir_name unless ruby_version_dir_name.empty?
    File.join parts
  end

  ##
  # The path to standard location of the user's configuration directory.

  def self.config_home
    @config_home ||= (ENV["XDG_CONFIG_HOME"] || File.join(Gem.user_home, '.config'))
  end

  ##
  # Finds the user's config file

  def self.find_config_file
    gemrc = File.join Gem.user_home, '.gemrc'
    if File.exist? gemrc
      gemrc
    else
      File.join Gem.config_home, "gem", "gemrc"
    end
  end

  ##
  # The path to standard location of the user's .gemrc file.

  def self.config_file
    @config_file ||= find_config_file.tap(&Gem::UNTAINT)
  end

  ##
  # The path to standard location of the user's cache directory.

  def self.cache_home
    @cache_home ||= (ENV["XDG_CACHE_HOME"] || File.join(Gem.user_home, '.cache'))
  end

  ##
  # The path to standard location of the user's data directory.

  def self.data_home
    @data_home ||= (ENV["XDG_DATA_HOME"] || File.join(Gem.user_home, '.local', 'share'))
  end

  ##
  # How String Gem paths should be split.  Overridable for esoteric platforms.

  def self.path_separator
    File::PATH_SEPARATOR
  end

  ##
  # Default gem load path

  def self.default_path
    path = []
    path << user_dir if user_home && File.exist?(user_home)
    path << default_dir
    path << vendor_dir if vendor_dir and File.directory? vendor_dir
    path
  end

  ##
  # Deduce Ruby's --program-prefix and --program-suffix from its install name

  def self.default_exec_format
    exec_format = RbConfig::CONFIG['ruby_install_name'].sub('ruby', '%s') rescue '%s'

    unless exec_format =~ /%s/
      raise Gem::Exception,
        "[BUG] invalid exec_format #{exec_format.inspect}, no %s"
    end

    exec_format
  end

  ##
  # The default directory for binaries

  def self.default_bindir
    if defined? RUBY_FRAMEWORK_VERSION # mac framework support
      '/usr/local/bin'
    else # generic install
      RbConfig::CONFIG['bindir']
    end
  end

  def self.ruby_engine
    RUBY_ENGINE
  end

  ##
  # The default signing key path

  def self.default_key_path
    default_key_path = File.join Gem.user_home, ".gem", "gem-private_key.pem"

    unless File.exist?(default_key_path)
      default_key_path = File.join Gem.data_home, "gem", "gem-private_key.pem"
    end

    default_key_path
  end

  ##
  # The default signing certificate chain path

  def self.default_cert_path
    default_cert_path = File.join Gem.user_home, ".gem", "gem-public_cert.pem"

    unless File.exist?(default_cert_path)
      default_cert_path = File.join Gem.data_home, "gem", "gem-public_cert.pem"
    end

    default_cert_path
  end

  ##
  # Install extensions into lib as well as into the extension directory.

  def self.install_extension_in_lib # :nodoc:
    true
  end

  ##
  # Directory where vendor gems are installed.

  def self.vendor_dir # :nodoc:
    if vendor_dir = ENV['GEM_VENDOR']
      return vendor_dir.dup
    end

    return nil unless RbConfig::CONFIG.key? 'vendordir'

    File.join RbConfig::CONFIG['vendordir'], 'gems',
              RbConfig::CONFIG['ruby_version_dir_name'] || RbConfig::CONFIG['ruby_version']
  end

  ##
  # Default options for gem commands for Ruby packagers.
  #
  # The options here should be structured as an array of string "gem"
  # command names as keys and a string of the default options as values.
  #
  # Example:
  #
  # def self.operating_system_defaults
  #   {
  #       'install' => '--no-rdoc --no-ri --env-shebang',
  #       'update' => '--no-rdoc --no-ri --env-shebang'
  #   }
  # end

  def self.operating_system_defaults
    {}
  end

  ##
  # Default options for gem commands for Ruby implementers.
  #
  # The options here should be structured as an array of string "gem"
  # command names as keys and a string of the default options as values.
  #
  # Example:
  #
  # def self.platform_defaults
  #   {
  #       'install' => '--no-rdoc --no-ri --env-shebang',
  #       'update' => '--no-rdoc --no-ri --env-shebang'
  #   }
  # end

  def self.platform_defaults
    {}
  end
end
# frozen_string_literal: true
require_relative '../text'

class Gem::Licenses
  extend Gem::Text

  NONSTANDARD = 'Nonstandard'.freeze
  LICENSE_REF = 'LicenseRef-.+'.freeze

  # Software Package Data Exchange (SPDX) standard open-source software
  # license identifiers
  LICENSE_IDENTIFIERS = %w[
    0BSD
    AAL
    ADSL
    AFL-1.1
    AFL-1.2
    AFL-2.0
    AFL-2.1
    AFL-3.0
    AGPL-1.0
    AGPL-1.0-only
    AGPL-1.0-or-later
    AGPL-3.0
    AGPL-3.0-only
    AGPL-3.0-or-later
    AMDPLPA
    AML
    AMPAS
    ANTLR-PD
    ANTLR-PD-fallback
    APAFML
    APL-1.0
    APSL-1.0
    APSL-1.1
    APSL-1.2
    APSL-2.0
    Abstyles
    Adobe-2006
    Adobe-Glyph
    Afmparse
    Aladdin
    Apache-1.0
    Apache-1.1
    Apache-2.0
    Artistic-1.0
    Artistic-1.0-Perl
    Artistic-1.0-cl8
    Artistic-2.0
    BSD-1-Clause
    BSD-2-Clause
    BSD-2-Clause-FreeBSD
    BSD-2-Clause-NetBSD
    BSD-2-Clause-Patent
    BSD-2-Clause-Views
    BSD-3-Clause
    BSD-3-Clause-Attribution
    BSD-3-Clause-Clear
    BSD-3-Clause-LBNL
    BSD-3-Clause-Modification
    BSD-3-Clause-No-Military-License
    BSD-3-Clause-No-Nuclear-License
    BSD-3-Clause-No-Nuclear-License-2014
    BSD-3-Clause-No-Nuclear-Warranty
    BSD-3-Clause-Open-MPI
    BSD-4-Clause
    BSD-4-Clause-Shortened
    BSD-4-Clause-UC
    BSD-Protection
    BSD-Source-Code
    BSL-1.0
    BUSL-1.1
    Bahyph
    Barr
    Beerware
    BitTorrent-1.0
    BitTorrent-1.1
    BlueOak-1.0.0
    Borceux
    C-UDA-1.0
    CAL-1.0
    CAL-1.0-Combined-Work-Exception
    CATOSL-1.1
    CC-BY-1.0
    CC-BY-2.0
    CC-BY-2.5
    CC-BY-3.0
    CC-BY-3.0-AT
    CC-BY-3.0-US
    CC-BY-4.0
    CC-BY-NC-1.0
    CC-BY-NC-2.0
    CC-BY-NC-2.5
    CC-BY-NC-3.0
    CC-BY-NC-4.0
    CC-BY-NC-ND-1.0
    CC-BY-NC-ND-2.0
    CC-BY-NC-ND-2.5
    CC-BY-NC-ND-3.0
    CC-BY-NC-ND-3.0-IGO
    CC-BY-NC-ND-4.0
    CC-BY-NC-SA-1.0
    CC-BY-NC-SA-2.0
    CC-BY-NC-SA-2.5
    CC-BY-NC-SA-3.0
    CC-BY-NC-SA-4.0
    CC-BY-ND-1.0
    CC-BY-ND-2.0
    CC-BY-ND-2.5
    CC-BY-ND-3.0
    CC-BY-ND-4.0
    CC-BY-SA-1.0
    CC-BY-SA-2.0
    CC-BY-SA-2.0-UK
    CC-BY-SA-2.1-JP
    CC-BY-SA-2.5
    CC-BY-SA-3.0
    CC-BY-SA-3.0-AT
    CC-BY-SA-4.0
    CC-PDDC
    CC0-1.0
    CDDL-1.0
    CDDL-1.1
    CDL-1.0
    CDLA-Permissive-1.0
    CDLA-Sharing-1.0
    CECILL-1.0
    CECILL-1.1
    CECILL-2.0
    CECILL-2.1
    CECILL-B
    CECILL-C
    CERN-OHL-1.1
    CERN-OHL-1.2
    CERN-OHL-P-2.0
    CERN-OHL-S-2.0
    CERN-OHL-W-2.0
    CNRI-Jython
    CNRI-Python
    CNRI-Python-GPL-Compatible
    CPAL-1.0
    CPL-1.0
    CPOL-1.02
    CUA-OPL-1.0
    Caldera
    ClArtistic
    Condor-1.1
    Crossword
    CrystalStacker
    Cube
    D-FSL-1.0
    DOC
    DRL-1.0
    DSDP
    Dotseqn
    ECL-1.0
    ECL-2.0
    EFL-1.0
    EFL-2.0
    EPICS
    EPL-1.0
    EPL-2.0
    EUDatagrid
    EUPL-1.0
    EUPL-1.1
    EUPL-1.2
    Entessa
    ErlPL-1.1
    Eurosym
    FSFAP
    FSFUL
    FSFULLR
    FTL
    Fair
    Frameworx-1.0
    FreeBSD-DOC
    FreeImage
    GD
    GFDL-1.1
    GFDL-1.1-invariants-only
    GFDL-1.1-invariants-or-later
    GFDL-1.1-no-invariants-only
    GFDL-1.1-no-invariants-or-later
    GFDL-1.1-only
    GFDL-1.1-or-later
    GFDL-1.2
    GFDL-1.2-invariants-only
    GFDL-1.2-invariants-or-later
    GFDL-1.2-no-invariants-only
    GFDL-1.2-no-invariants-or-later
    GFDL-1.2-only
    GFDL-1.2-or-later
    GFDL-1.3
    GFDL-1.3-invariants-only
    GFDL-1.3-invariants-or-later
    GFDL-1.3-no-invariants-only
    GFDL-1.3-no-invariants-or-later
    GFDL-1.3-only
    GFDL-1.3-or-later
    GL2PS
    GLWTPL
    GPL-1.0
    GPL-1.0+
    GPL-1.0-only
    GPL-1.0-or-later
    GPL-2.0
    GPL-2.0+
    GPL-2.0-only
    GPL-2.0-or-later
    GPL-2.0-with-GCC-exception
    GPL-2.0-with-autoconf-exception
    GPL-2.0-with-bison-exception
    GPL-2.0-with-classpath-exception
    GPL-2.0-with-font-exception
    GPL-3.0
    GPL-3.0+
    GPL-3.0-only
    GPL-3.0-or-later
    GPL-3.0-with-GCC-exception
    GPL-3.0-with-autoconf-exception
    Giftware
    Glide
    Glulxe
    HPND
    HPND-sell-variant
    HTMLTIDY
    HaskellReport
    Hippocratic-2.1
    IBM-pibs
    ICU
    IJG
    IPA
    IPL-1.0
    ISC
    ImageMagick
    Imlib2
    Info-ZIP
    Intel
    Intel-ACPI
    Interbase-1.0
    JPNIC
    JSON
    JasPer-2.0
    LAL-1.2
    LAL-1.3
    LGPL-2.0
    LGPL-2.0+
    LGPL-2.0-only
    LGPL-2.0-or-later
    LGPL-2.1
    LGPL-2.1+
    LGPL-2.1-only
    LGPL-2.1-or-later
    LGPL-3.0
    LGPL-3.0+
    LGPL-3.0-only
    LGPL-3.0-or-later
    LGPLLR
    LPL-1.0
    LPL-1.02
    LPPL-1.0
    LPPL-1.1
    LPPL-1.2
    LPPL-1.3a
    LPPL-1.3c
    Latex2e
    Leptonica
    LiLiQ-P-1.1
    LiLiQ-R-1.1
    LiLiQ-Rplus-1.1
    Libpng
    Linux-OpenIB
    MIT
    MIT-0
    MIT-CMU
    MIT-Modern-Variant
    MIT-advertising
    MIT-enna
    MIT-feh
    MIT-open-group
    MITNFA
    MPL-1.0
    MPL-1.1
    MPL-2.0
    MPL-2.0-no-copyleft-exception
    MS-PL
    MS-RL
    MTLL
    MakeIndex
    MirOS
    Motosoto
    MulanPSL-1.0
    MulanPSL-2.0
    Multics
    Mup
    NAIST-2003
    NASA-1.3
    NBPL-1.0
    NCGL-UK-2.0
    NCSA
    NGPL
    NIST-PD
    NIST-PD-fallback
    NLOD-1.0
    NLPL
    NOSL
    NPL-1.0
    NPL-1.1
    NPOSL-3.0
    NRL
    NTP
    NTP-0
    Naumen
    Net-SNMP
    NetCDF
    Newsletr
    Nokia
    Noweb
    Nunit
    O-UDA-1.0
    OCCT-PL
    OCLC-2.0
    ODC-By-1.0
    ODbL-1.0
    OFL-1.0
    OFL-1.0-RFN
    OFL-1.0-no-RFN
    OFL-1.1
    OFL-1.1-RFN
    OFL-1.1-no-RFN
    OGC-1.0
    OGDL-Taiwan-1.0
    OGL-Canada-2.0
    OGL-UK-1.0
    OGL-UK-2.0
    OGL-UK-3.0
    OGTSL
    OLDAP-1.1
    OLDAP-1.2
    OLDAP-1.3
    OLDAP-1.4
    OLDAP-2.0
    OLDAP-2.0.1
    OLDAP-2.1
    OLDAP-2.2
    OLDAP-2.2.1
    OLDAP-2.2.2
    OLDAP-2.3
    OLDAP-2.4
    OLDAP-2.5
    OLDAP-2.6
    OLDAP-2.7
    OLDAP-2.8
    OML
    OPL-1.0
    OSET-PL-2.1
    OSL-1.0
    OSL-1.1
    OSL-2.0
    OSL-2.1
    OSL-3.0
    OpenSSL
    PDDL-1.0
    PHP-3.0
    PHP-3.01
    PSF-2.0
    Parity-6.0.0
    Parity-7.0.0
    Plexus
    PolyForm-Noncommercial-1.0.0
    PolyForm-Small-Business-1.0.0
    PostgreSQL
    Python-2.0
    QPL-1.0
    Qhull
    RHeCos-1.1
    RPL-1.1
    RPL-1.5
    RPSL-1.0
    RSA-MD
    RSCPL
    Rdisc
    Ruby
    SAX-PD
    SCEA
    SGI-B-1.0
    SGI-B-1.1
    SGI-B-2.0
    SHL-0.5
    SHL-0.51
    SISSL
    SISSL-1.2
    SMLNJ
    SMPPL
    SNIA
    SPL-1.0
    SSH-OpenSSH
    SSH-short
    SSPL-1.0
    SWL
    Saxpath
    Sendmail
    Sendmail-8.23
    SimPL-2.0
    Sleepycat
    Spencer-86
    Spencer-94
    Spencer-99
    StandardML-NJ
    SugarCRM-1.1.3
    TAPR-OHL-1.0
    TCL
    TCP-wrappers
    TMate
    TORQUE-1.1
    TOSL
    TU-Berlin-1.0
    TU-Berlin-2.0
    UCL-1.0
    UPL-1.0
    Unicode-DFS-2015
    Unicode-DFS-2016
    Unicode-TOU
    Unlicense
    VOSTROM
    VSL-1.0
    Vim
    W3C
    W3C-19980720
    W3C-20150513
    WTFPL
    Watcom-1.0
    Wsuipa
    X11
    XFree86-1.1
    XSkat
    Xerox
    Xnet
    YPL-1.0
    YPL-1.1
    ZPL-1.1
    ZPL-2.0
    ZPL-2.1
    Zed
    Zend-2.0
    Zimbra-1.3
    Zimbra-1.4
    Zlib
    blessing
    bzip2-1.0.5
    bzip2-1.0.6
    copyleft-next-0.3.0
    copyleft-next-0.3.1
    curl
    diffmark
    dvipdfm
    eCos-2.0
    eGenix
    etalab-2.0
    gSOAP-1.3b
    gnuplot
    iMatix
    libpng-2.0
    libselinux-1.0
    libtiff
    mpich2
    psfrag
    psutils
    wxWindows
    xinetd
    xpp
    zlib-acknowledgement
  ].freeze

  # exception identifiers
  EXCEPTION_IDENTIFIERS = %w[
    389-exception
    Autoconf-exception-2.0
    Autoconf-exception-3.0
    Bison-exception-2.2
    Bootloader-exception
    CLISP-exception-2.0
    Classpath-exception-2.0
    DigiRule-FOSS-exception
    FLTK-exception
    Fawkes-Runtime-exception
    Font-exception-2.0
    GCC-exception-2.0
    GCC-exception-3.1
    GPL-3.0-linking-exception
    GPL-3.0-linking-source-exception
    GPL-CC-1.0
    LGPL-3.0-linking-exception
    LLVM-exception
    LZMA-exception
    Libtool-exception
    Linux-syscall-note
    Nokia-Qt-exception-1.1
    OCCT-exception-1.0
    OCaml-LGPL-linking-exception
    OpenJDK-assembly-exception-1.0
    PS-or-PDF-font-exception-20170817
    Qt-GPL-exception-1.0
    Qt-LGPL-exception-1.1
    Qwt-exception-1.0
    SHL-2.0
    SHL-2.1
    Swift-exception
    Universal-FOSS-exception-1.0
    WxWindows-exception-3.1
    eCos-exception-2.0
    freertos-exception-2.0
    gnu-javamail-exception
    i2p-gpl-java-exception
    mif-exception
    openvpn-openssl-exception
    u-boot-exception-2.0
  ].freeze

  REGEXP = %r{
    \A
    (?:
      #{Regexp.union(LICENSE_IDENTIFIERS)}
      \+?
      (?:\s WITH \s #{Regexp.union(EXCEPTION_IDENTIFIERS)})?
      | #{NONSTANDARD}
      | #{LICENSE_REF}
    )
    \Z
  }ox.freeze

  def self.match?(license)
    !REGEXP.match(license).nil?
  end

  def self.suggestions(license)
    by_distance = LICENSE_IDENTIFIERS.group_by do |identifier|
      levenshtein_distance(identifier, license)
    end
    lowest = by_distance.keys.min
    return unless lowest < license.size
    by_distance[lowest]
  end
end
# frozen_string_literal: true
module Gem
  class List
    include Enumerable
    attr_accessor :value, :tail

    def initialize(value = nil, tail = nil)
      @value = value
      @tail = tail
    end

    def each
      n = self
      while n
        yield n.value
        n = n.tail
      end
    end

    def to_a
      super.reverse
    end

    def prepend(value)
      List.new value, self
    end

    def pretty_print(q) # :nodoc:
      q.pp to_a
    end

    def self.prepend(list, value)
      return List.new(value) unless list
      List.new value, list
    end
  end
end
# frozen_string_literal: true
# :stopdoc:

#--
# This file contains all sorts of little compatibility hacks that we've
# had to introduce over the years. Quarantining them into one file helps
# us know when we can get rid of them.
#
# Ruby 1.9.x has introduced some things that are awkward, and we need to
# support them, so we define some constants to use later.
#++

# TODO remove at RubyGems 4
module Gem
  RubyGemsVersion = VERSION
  deprecate_constant(:RubyGemsVersion)

  RbConfigPriorities = %w[
    MAJOR
    MINOR
    TEENY
    EXEEXT RUBY_SO_NAME arch bindir datadir libdir ruby_install_name
    ruby_version rubylibprefix sitedir sitelibdir vendordir vendorlibdir
    rubylibdir
  ].freeze

  unless defined?(ConfigMap)
    ##
    # Configuration settings from ::RbConfig
    ConfigMap = Hash.new do |cm, key|
      cm[key] = RbConfig::CONFIG[key.to_s]
    end
    deprecate_constant(:ConfigMap)
  else
    RbConfigPriorities.each do |key|
      ConfigMap[key.to_sym] = RbConfig::CONFIG[key]
    end
  end

end
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require_relative '../rubygems'

##
# Mixin methods for --version and --platform Gem::Command options.

module Gem::VersionOption

  ##
  # Add the --platform option to the option parser.

  def add_platform_option(task = command, *wrap)
    Gem::OptionParser.accept Gem::Platform do |value|
      if value == Gem::Platform::RUBY
        value
      else
        Gem::Platform.new value
      end
    end

    add_option('--platform PLATFORM', Gem::Platform,
               "Specify the platform of gem to #{task}", *wrap) do
                 |value, options|
      unless options[:added_platform]
        Gem.platforms = [Gem::Platform::RUBY]
        options[:added_platform] = true
      end

      Gem.platforms << value unless Gem.platforms.include? value
    end
  end

  ##
  # Add the --prerelease option to the option parser.

  def add_prerelease_option(*wrap)
    add_option("--[no-]prerelease",
               "Allow prerelease versions of a gem", *wrap) do |value, options|
      options[:prerelease] = value
      options[:explicit_prerelease] = true
    end
  end

  ##
  # Add the --version option to the option parser.

  def add_version_option(task = command, *wrap)
    Gem::OptionParser.accept Gem::Requirement do |value|
      Gem::Requirement.new(*value.split(/\s*,\s*/))
    end

    add_option('-v', '--version VERSION', Gem::Requirement,
               "Specify version of gem to #{task}", *wrap) do
                 |value, options|
      # Allow handling for multiple --version operators
      if options[:version] && !options[:version].none?
        options[:version].concat([value])
      else
        options[:version] = value
      end

      explicit_prerelease_set = !options[:explicit_prerelease].nil?
      options[:explicit_prerelease] = false unless explicit_prerelease_set

      options[:prerelease] = value.prerelease? unless
        options[:explicit_prerelease]
    end
  end

  ##
  # Extract platform given on the command line

  def get_platform_from_requirements(requirements)
    Gem.platforms[1].to_s if requirements.key? :added_platform
  end
end
# frozen_string_literal: true

##
# The Uri handles rubygems source URIs.
#

class Gem::Uri
  def initialize(source_uri)
    @parsed_uri = parse(source_uri)
  end

  def redacted
    return self unless valid_uri?

    if token? || oauth_basic?
      with_redacted_user
    elsif password?
      with_redacted_password
    else
      self
    end
  end

  def to_s
    @parsed_uri.to_s
  end

  def redact_credentials_from(text)
    return text unless valid_uri? && password?

    text.sub(password, 'REDACTED')
  end

  def method_missing(method_name, *args, &blk)
    if @parsed_uri.respond_to?(method_name)
      @parsed_uri.send(method_name, *args, &blk)
    else
      super
    end
  end

  def respond_to_missing?(method_name, include_private = false)
    @parsed_uri.respond_to?(method_name, include_private) || super
  end

  protected

  # Add a protected reader for the cloned instance to access the original object's parsed uri
  attr_reader :parsed_uri

  private

  ##
  # Parses the #uri, raising if it's invalid

  def parse!(uri)
    require "uri"

    raise URI::InvalidURIError unless uri

    # Always escape URI's to deal with potential spaces and such
    # It should also be considered that source_uri may already be
    # a valid URI with escaped characters. e.g. "{DESede}" is encoded
    # as "%7BDESede%7D". If this is escaped again the percentage
    # symbols will be escaped.
    begin
      URI.parse(uri)
    rescue URI::InvalidURIError
      URI.parse(URI::DEFAULT_PARSER.escape(uri))
    end
  end

  ##
  # Parses the #uri, returning the original uri if it's invalid

  def parse(uri)
    return uri unless uri.is_a?(String)

    parse!(uri)
  rescue URI::InvalidURIError
    uri
  end

  def with_redacted_user
    clone.tap {|uri| uri.user = 'REDACTED' }
  end

  def with_redacted_password
    clone.tap {|uri| uri.password = 'REDACTED' }
  end

  def valid_uri?
    !@parsed_uri.is_a?(String)
  end

  def password?
    !!password
  end

  def oauth_basic?
    password == 'x-oauth-basic'
  end

  def token?
    !user.nil? && password.nil?
  end

  def initialize_copy(original)
    @parsed_uri = original.parsed_uri.clone
  end
end
# frozen_string_literal: true
require_relative 'remote_fetcher'
require_relative 'user_interaction'
require_relative 'errors'
require_relative 'text'
require_relative 'name_tuple'

##
# SpecFetcher handles metadata updates from remote gem repositories.

class Gem::SpecFetcher
  include Gem::UserInteraction
  include Gem::Text

  ##
  # Cache of latest specs

  attr_reader :latest_specs # :nodoc:

  ##
  # Sources for this SpecFetcher

  attr_reader :sources # :nodoc:

  ##
  # Cache of all released specs

  attr_reader :specs # :nodoc:

  ##
  # Cache of prerelease specs

  attr_reader :prerelease_specs # :nodoc:

  @fetcher = nil

  ##
  # Default fetcher instance.  Use this instead of ::new to reduce object
  # allocation.

  def self.fetcher
    @fetcher ||= new
  end

  def self.fetcher=(fetcher) # :nodoc:
    @fetcher = fetcher
  end

  ##
  # Creates a new SpecFetcher.  Ordinarily you want to use the default fetcher
  # from Gem::SpecFetcher::fetcher which uses the Gem.sources.
  #
  # If you need to retrieve specifications from a different +source+, you can
  # send it as an argument.

  def initialize(sources = nil)
    @sources = sources || Gem.sources

    @update_cache =
      begin
        File.stat(Gem.user_home).uid == Process.uid
      rescue Errno::EACCES, Errno::ENOENT
        false
      end

    @specs = {}
    @latest_specs = {}
    @prerelease_specs = {}

    @caches = {
      :latest => @latest_specs,
      :prerelease => @prerelease_specs,
      :released => @specs,
    }

    @fetcher = Gem::RemoteFetcher.fetcher
  end

  ##
  #
  # Find and fetch gem name tuples that match +dependency+.
  #
  # If +matching_platform+ is false, gems for all platforms are returned.

  def search_for_dependency(dependency, matching_platform=true)
    found = {}

    rejected_specs = {}

    list, errors = available_specs(dependency.identity)

    list.each do |source, specs|
      if dependency.name.is_a?(String) && specs.respond_to?(:bsearch)
        start_index = (0 ... specs.length).bsearch{|i| specs[i].name >= dependency.name }
        end_index   = (0 ... specs.length).bsearch{|i| specs[i].name > dependency.name }
        specs = specs[start_index ... end_index] if start_index && end_index
      end

      found[source] = specs.select do |tup|
        if dependency.match?(tup)
          if matching_platform and !Gem::Platform.match_gem?(tup.platform, tup.name)
            pm = (
              rejected_specs[dependency] ||= \
                Gem::PlatformMismatch.new(tup.name, tup.version))
            pm.add_platform tup.platform
            false
          else
            true
          end
        end
      end
    end

    errors += rejected_specs.values

    tuples = []

    found.each do |source, specs|
      specs.each do |s|
        tuples << [s, source]
      end
    end

    tuples = tuples.sort_by {|x| x[0] }

    return [tuples, errors]
  end

  ##
  # Return all gem name tuples who's names match +obj+

  def detect(type=:complete)
    tuples = []

    list, _ = available_specs(type)
    list.each do |source, specs|
      specs.each do |tup|
        if yield(tup)
          tuples << [tup, source]
        end
      end
    end

    tuples
  end

  ##
  # Find and fetch specs that match +dependency+.
  #
  # If +matching_platform+ is false, gems for all platforms are returned.

  def spec_for_dependency(dependency, matching_platform=true)
    tuples, errors = search_for_dependency(dependency, matching_platform)

    specs = []
    tuples.each do |tup, source|
      begin
        spec = source.fetch_spec(tup)
      rescue Gem::RemoteFetcher::FetchError => e
        errors << Gem::SourceFetchProblem.new(source, e)
      else
        specs << [spec, source]
      end
    end

    return [specs, errors]
  end

  ##
  # Suggests gems based on the supplied +gem_name+. Returns an array of
  # alternative gem names.

  def suggest_gems_from_name(gem_name, type = :latest, num_results = 5)
    gem_name        = gem_name.downcase.tr('_-', '')
    max             = gem_name.size / 2
    names           = available_specs(type).first.values.flatten(1)

    matches = names.map do |n|
      next unless n.match_platform?
      [n.name, 0] if n.name.downcase.tr('_-', '').include?(gem_name)
    end.compact

    if matches.length < num_results
      matches += names.map do |n|
        next unless n.match_platform?
        distance = levenshtein_distance gem_name, n.name.downcase.tr('_-', '')
        next if distance >= max
        return [n.name] if distance == 0
        [n.name, distance]
      end.compact
    end

    matches = if matches.empty? && type != :prerelease
                suggest_gems_from_name gem_name, :prerelease
              else
                matches.uniq.sort_by {|name, dist| dist }
              end

    matches.map {|name, dist| name }.uniq.first(num_results)
  end

  ##
  # Returns a list of gems available for each source in Gem::sources.
  #
  # +type+ can be one of 3 values:
  # :released   => Return the list of all released specs
  # :complete   => Return the list of all specs
  # :latest     => Return the list of only the highest version of each gem
  # :prerelease => Return the list of all prerelease only specs
  #

  def available_specs(type)
    errors = []
    list = {}

    @sources.each_source do |source|
      begin
        names = case type
                when :latest
                  tuples_for source, :latest
                when :released
                  tuples_for source, :released
                when :complete
                  names =
                    tuples_for(source, :prerelease, true) +
                    tuples_for(source, :released)

                  names.sort
                when :abs_latest
                  names =
                    tuples_for(source, :prerelease, true) +
                    tuples_for(source, :latest)

                  names.sort
                when :prerelease
                  tuples_for(source, :prerelease)
                else
                  raise Gem::Exception, "Unknown type - :#{type}"
                end
      rescue Gem::RemoteFetcher::FetchError => e
        errors << Gem::SourceFetchProblem.new(source, e)
      else
        list[source] = names
      end
    end

    [list, errors]
  end

  ##
  # Retrieves NameTuples from +source+ of the given +type+ (:prerelease,
  # etc.).  If +gracefully_ignore+ is true, errors are ignored.

  def tuples_for(source, type, gracefully_ignore=false) # :nodoc:
    @caches[type][source.uri] ||=
      source.load_specs(type).sort_by {|tup| tup.name }
  rescue Gem::RemoteFetcher::FetchError
    raise unless gracefully_ignore
    []
  end
end
Ruby is copyrighted free software by Yukihiro Matsumoto <matz@netlab.jp>.
You can redistribute it and/or modify it under either the terms of the
2-clause BSDL (see the file BSDL), 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.
# frozen_string_literal: false
require_relative 'optparse'
# frozen_string_literal: false
# -*- ruby -*-

require 'rubygems/optparse/lib/optparse'
require 'uri'

Gem::OptionParser.accept(URI) {|s,| URI.parse(s) if s}
# frozen_string_literal: false
require 'rubygems/optparse/lib/optparse'
require 'time'

Gem::OptionParser.accept(Time) do |s,|
  begin
    (Time.httpdate(s) rescue Time.parse(s)) if s
  rescue
    raise Gem::OptionParser::InvalidArgument, s
  end
end
# frozen_string_literal: false
require 'rubygems/optparse/lib/optparse'

class Gem::OptionParser::AC < Gem::OptionParser
  private

  def _check_ac_args(name, block)
    unless /\A\w[-\w]*\z/ =~ name
      raise ArgumentError, name
    end
    unless block
      raise ArgumentError, "no block given", ParseError.filter_backtrace(caller)
    end
  end

  ARG_CONV = proc {|val| val.nil? ? true : val}

  def _ac_arg_enable(prefix, name, help_string, block)
    _check_ac_args(name, block)

    sdesc = []
    ldesc = ["--#{prefix}-#{name}"]
    desc = [help_string]
    q = name.downcase
    ac_block = proc {|val| block.call(ARG_CONV.call(val))}
    enable = Switch::PlacedArgument.new(nil, ARG_CONV, sdesc, ldesc, nil, desc, ac_block)
    disable = Switch::NoArgument.new(nil, proc {false}, sdesc, ldesc, nil, desc, ac_block)
    top.append(enable, [], ["enable-" + q], disable, ['disable-' + q])
    enable
  end

  public

  def ac_arg_enable(name, help_string, &block)
    _ac_arg_enable("enable", name, help_string, block)
  end

  def ac_arg_disable(name, help_string, &block)
    _ac_arg_enable("disable", name, help_string, block)
  end

  def ac_arg_with(name, help_string, &block)
    _check_ac_args(name, block)

    sdesc = []
    ldesc = ["--with-#{name}"]
    desc = [help_string]
    q = name.downcase
    with = Switch::PlacedArgument.new(*search(:atype, String), sdesc, ldesc, nil, desc, block)
    without = Switch::NoArgument.new(nil, proc {}, sdesc, ldesc, nil, desc, block)
    top.append(with, [], ["with-" + q], without, ['without-' + q])
    with
  end
end
# frozen_string_literal: true
require 'rubygems/optparse/lib/optparse'

class Gem::OptionParser
  # :call-seq:
  #   define_by_keywords(options, method, **params)
  #
  # :include: ../../doc/optparse/creates_option.rdoc
  #
  def define_by_keywords(options, meth, **opts)
    meth.parameters.each do |type, name|
      case type
      when :key, :keyreq
        op, cl = *(type == :key ? %w"[ ]" : ["", ""])
        define("--#{name}=#{op}#{name.upcase}#{cl}", *opts[name]) do |o|
          options[name] = o
        end
      end
    end
    options
  end
end
# frozen_string_literal: false
# -*- ruby -*-

require 'shellwords'
require 'rubygems/optparse/lib/optparse'

Gem::OptionParser.accept(Shellwords) {|s,| Shellwords.shellwords(s)}
# frozen_string_literal: false
require 'rubygems/optparse/lib/optparse'
require 'date'

Gem::OptionParser.accept(DateTime) do |s,|
  begin
    DateTime.parse(s) if s
  rescue ArgumentError
    raise Gem::OptionParser::InvalidArgument, s
  end
end
Gem::OptionParser.accept(Date) do |s,|
  begin
    Date.parse(s) if s
  rescue ArgumentError
    raise Gem::OptionParser::InvalidArgument, s
  end
end
# frozen_string_literal: false
# Gem::OptionParser internal utility

class << Gem::OptionParser
  def show_version(*pkgs)
    progname = ARGV.options.program_name
    result = false
    show = proc do |klass, cname, version|
      str = "#{progname}"
      unless klass == ::Object and cname == :VERSION
        version = version.join(".") if Array === version
        str << ": #{klass}" unless klass == Object
        str << " version #{version}"
      end
      [:Release, :RELEASE].find do |rel|
        if klass.const_defined?(rel)
          str << " (#{klass.const_get(rel)})"
        end
      end
      puts str
      result = true
    end
    if pkgs.size == 1 and pkgs[0] == "all"
      self.search_const(::Object, /\AV(?:ERSION|ersion)\z/) do |klass, cname, version|
        unless cname[1] == ?e and klass.const_defined?(:Version)
          show.call(klass, cname.intern, version)
        end
      end
    else
      pkgs.each do |pkg|
        begin
          pkg = pkg.split(/::|\//).inject(::Object) {|m, c| m.const_get(c)}
          v = case
              when pkg.const_defined?(:Version)
                pkg.const_get(n = :Version)
              when pkg.const_defined?(:VERSION)
                pkg.const_get(n = :VERSION)
              else
                n = nil
                "unknown"
              end
          show.call(pkg, n, v)
        rescue NameError
        end
      end
    end
    result
  end

  def each_const(path, base = ::Object)
    path.split(/::|\//).inject(base) do |klass, name|
      raise NameError, path unless Module === klass
      klass.constants.grep(/#{name}/i) do |c|
        klass.const_defined?(c) or next
        klass.const_get(c)
      end
    end
  end

  def search_const(klass, name)
    klasses = [klass]
    while klass = klasses.shift
      klass.constants.each do |cname|
        klass.const_defined?(cname) or next
        const = klass.const_get(cname)
        yield klass, cname, const if name === cname
        klasses << const if Module === const and const != ::Object
      end
    end
  end
end
# frozen_string_literal: true
#
# optparse.rb - command-line option analysis with the Gem::OptionParser class.
#
# Author:: Nobu Nakada
# Documentation:: Nobu Nakada and Gavin Sinclair.
#
# See Gem::OptionParser for documentation.
#


#--
# == Developer Documentation (not for RDoc output)
#
# === Class tree
#
# - Gem::OptionParser:: front end
# - Gem::OptionParser::Switch:: each switches
# - Gem::OptionParser::List:: options list
# - Gem::OptionParser::ParseError:: errors on parsing
#   - Gem::OptionParser::AmbiguousOption
#   - Gem::OptionParser::NeedlessArgument
#   - Gem::OptionParser::MissingArgument
#   - Gem::OptionParser::InvalidOption
#   - Gem::OptionParser::InvalidArgument
#     - Gem::OptionParser::AmbiguousArgument
#
# === Object relationship diagram
#
#   +--------------+
#   | Gem::OptionParser |<>-----+
#   +--------------+       |                      +--------+
#                          |                    ,-| Switch |
#        on_head -------->+---------------+    /  +--------+
#        accept/reject -->| List          |<|>-
#                         |               |<|>-  +----------+
#        on ------------->+---------------+    `-| argument |
#                           :           :        |  class   |
#                         +---------------+      |==========|
#        on_tail -------->|               |      |pattern   |
#                         +---------------+      |----------|
#   Gem::OptionParser.accept ->| DefaultList   |      |converter |
#                reject   |(shared between|      +----------+
#                         | all instances)|
#                         +---------------+
#
#++
#
# == Gem::OptionParser
#
# === New to \Gem::OptionParser?
#
# See the {Tutorial}[./doc/optparse/tutorial_rdoc.html].
#
# === Introduction
#
# Gem::OptionParser is a class for command-line option analysis.  It is much more
# advanced, yet also easier to use, than GetoptLong, and is a more Ruby-oriented
# solution.
#
# === Features
#
# 1. The argument specification and the code to handle it are written in the
#    same place.
# 2. It can output an option summary; you don't need to maintain this string
#    separately.
# 3. Optional and mandatory arguments are specified very gracefully.
# 4. Arguments can be automatically converted to a specified class.
# 5. Arguments can be restricted to a certain set.
#
# All of these features are demonstrated in the examples below.  See
# #make_switch for full documentation.
#
# === Minimal example
#
#   require 'rubygems/optparse/lib/optparse'
#
#   options = {}
#   Gem::OptionParser.new do |parser|
#     parser.banner = "Usage: example.rb [options]"
#
#     parser.on("-v", "--[no-]verbose", "Run verbosely") do |v|
#       options[:verbose] = v
#     end
#   end.parse!
#
#   p options
#   p ARGV
#
# === Generating Help
#
# Gem::OptionParser can be used to automatically generate help for the commands you
# write:
#
#   require 'rubygems/optparse/lib/optparse'
#
#   Options = Struct.new(:name)
#
#   class Parser
#     def self.parse(options)
#       args = Options.new("world")
#
#       opt_parser = Gem::OptionParser.new do |parser|
#         parser.banner = "Usage: example.rb [options]"
#
#         parser.on("-nNAME", "--name=NAME", "Name to say hello to") do |n|
#           args.name = n
#         end
#
#         parser.on("-h", "--help", "Prints this help") do
#           puts parser
#           exit
#         end
#       end
#
#       opt_parser.parse!(options)
#       return args
#     end
#   end
#   options = Parser.parse %w[--help]
#
#   #=>
#      # Usage: example.rb [options]
#      #     -n, --name=NAME                  Name to say hello to
#      #     -h, --help                       Prints this help
#
# === Required Arguments
#
# For options that require an argument, option specification strings may include an
# option name in all caps. If an option is used without the required argument,
# an exception will be raised.
#
#   require 'rubygems/optparse/lib/optparse'
#
#   options = {}
#   Gem::OptionParser.new do |parser|
#     parser.on("-r", "--require LIBRARY",
#               "Require the LIBRARY before executing your script") do |lib|
#       puts "You required #{lib}!"
#     end
#   end.parse!
#
# Used:
#
#   $ ruby optparse-test.rb -r
#   optparse-test.rb:9:in `<main>': missing argument: -r (Gem::OptionParser::MissingArgument)
#   $ ruby optparse-test.rb -r my-library
#   You required my-library!
#
# === Type Coercion
#
# Gem::OptionParser supports the ability to coerce command line arguments
# into objects for us.
#
# Gem::OptionParser comes with a few ready-to-use kinds of  type
# coercion. They are:
#
# - Date  -- Anything accepted by +Date.parse+
# - DateTime -- Anything accepted by +DateTime.parse+
# - Time -- Anything accepted by +Time.httpdate+ or +Time.parse+
# - URI  -- Anything accepted by +URI.parse+
# - Shellwords -- Anything accepted by +Shellwords.shellwords+
# - String -- Any non-empty string
# - Integer -- Any integer. Will convert octal. (e.g. 124, -3, 040)
# - Float -- Any float. (e.g. 10, 3.14, -100E+13)
# - Numeric -- Any integer, float, or rational (1, 3.4, 1/3)
# - DecimalInteger -- Like +Integer+, but no octal format.
# - OctalInteger -- Like +Integer+, but no decimal format.
# - DecimalNumeric -- Decimal integer or float.
# - TrueClass --  Accepts '+, yes, true, -, no, false' and
#   defaults as +true+
# - FalseClass -- Same as +TrueClass+, but defaults to +false+
# - Array -- Strings separated by ',' (e.g. 1,2,3)
# - Regexp -- Regular expressions. Also includes options.
#
# We can also add our own coercions, which we will cover below.
#
# ==== Using Built-in Conversions
#
# As an example, the built-in +Time+ conversion is used. The other built-in
# conversions behave in the same way.
# Gem::OptionParser will attempt to parse the argument
# as a +Time+. If it succeeds, that time will be passed to the
# handler block. Otherwise, an exception will be raised.
#
#   require 'rubygems/optparse/lib/optparse'
#   require 'rubygems/optparse/lib/optparse/time'
#   Gem::OptionParser.new do |parser|
#     parser.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time|
#       p time
#     end
#   end.parse!
#
# Used:
#
#   $ ruby optparse-test.rb  -t nonsense
#   ... invalid argument: -t nonsense (Gem::OptionParser::InvalidArgument)
#   $ ruby optparse-test.rb  -t 10-11-12
#   2010-11-12 00:00:00 -0500
#   $ ruby optparse-test.rb  -t 9:30
#   2014-08-13 09:30:00 -0400
#
# ==== Creating Custom Conversions
#
# The +accept+ method on Gem::OptionParser may be used to create converters.
# It specifies which conversion block to call whenever a class is specified.
# The example below uses it to fetch a +User+ object before the +on+ handler receives it.
#
#   require 'rubygems/optparse/lib/optparse'
#
#   User = Struct.new(:id, :name)
#
#   def find_user id
#     not_found = ->{ raise "No User Found for id #{id}" }
#     [ User.new(1, "Sam"),
#       User.new(2, "Gandalf") ].find(not_found) do |u|
#       u.id == id
#     end
#   end
#
#   op = Gem::OptionParser.new
#   op.accept(User) do |user_id|
#     find_user user_id.to_i
#   end
#
#   op.on("--user ID", User) do |user|
#     puts user
#   end
#
#   op.parse!
#
# Used:
#
#   $ ruby optparse-test.rb --user 1
#   #<struct User id=1, name="Sam">
#   $ ruby optparse-test.rb --user 2
#   #<struct User id=2, name="Gandalf">
#   $ ruby optparse-test.rb --user 3
#   optparse-test.rb:15:in `block in find_user': No User Found for id 3 (RuntimeError)
#
# === Store options to a Hash
#
# The +into+ option of +order+, +parse+ and so on methods stores command line options into a Hash.
#
#   require 'rubygems/optparse/lib/optparse'
#
#   options = {}
#   Gem::OptionParser.new do |parser|
#     parser.on('-a')
#     parser.on('-b NUM', Integer)
#     parser.on('-v', '--verbose')
#   end.parse!(into: options)
#
#   p options
#
# Used:
#
#   $ ruby optparse-test.rb -a
#   {:a=>true}
#   $ ruby optparse-test.rb -a -v
#   {:a=>true, :verbose=>true}
#   $ ruby optparse-test.rb -a -b 100
#   {:a=>true, :b=>100}
#
# === Complete example
#
# The following example is a complete Ruby program.  You can run it and see the
# effect of specifying various options.  This is probably the best way to learn
# the features of +optparse+.
#
#   require 'rubygems/optparse/lib/optparse'
#   require 'rubygems/optparse/lib/optparse/time'
#   require 'ostruct'
#   require 'pp'
#
#   class OptparseExample
#     Version = '1.0.0'
#
#     CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary]
#     CODE_ALIASES = { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
#
#     class ScriptOptions
#       attr_accessor :library, :inplace, :encoding, :transfer_type,
#                     :verbose, :extension, :delay, :time, :record_separator,
#                     :list
#
#       def initialize
#         self.library = []
#         self.inplace = false
#         self.encoding = "utf8"
#         self.transfer_type = :auto
#         self.verbose = false
#       end
#
#       def define_options(parser)
#         parser.banner = "Usage: example.rb [options]"
#         parser.separator ""
#         parser.separator "Specific options:"
#
#         # add additional options
#         perform_inplace_option(parser)
#         delay_execution_option(parser)
#         execute_at_time_option(parser)
#         specify_record_separator_option(parser)
#         list_example_option(parser)
#         specify_encoding_option(parser)
#         optional_option_argument_with_keyword_completion_option(parser)
#         boolean_verbose_option(parser)
#
#         parser.separator ""
#         parser.separator "Common options:"
#         # No argument, shows at tail.  This will print an options summary.
#         # Try it and see!
#         parser.on_tail("-h", "--help", "Show this message") do
#           puts parser
#           exit
#         end
#         # Another typical switch to print the version.
#         parser.on_tail("--version", "Show version") do
#           puts Version
#           exit
#         end
#       end
#
#       def perform_inplace_option(parser)
#         # Specifies an optional option argument
#         parser.on("-i", "--inplace [EXTENSION]",
#                   "Edit ARGV files in place",
#                   "(make backup if EXTENSION supplied)") do |ext|
#           self.inplace = true
#           self.extension = ext || ''
#           self.extension.sub!(/\A\.?(?=.)/, ".")  # Ensure extension begins with dot.
#         end
#       end
#
#       def delay_execution_option(parser)
#         # Cast 'delay' argument to a Float.
#         parser.on("--delay N", Float, "Delay N seconds before executing") do |n|
#           self.delay = n
#         end
#       end
#
#       def execute_at_time_option(parser)
#         # Cast 'time' argument to a Time object.
#         parser.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time|
#           self.time = time
#         end
#       end
#
#       def specify_record_separator_option(parser)
#         # Cast to octal integer.
#         parser.on("-F", "--irs [OCTAL]", Gem::OptionParser::OctalInteger,
#                   "Specify record separator (default \\0)") do |rs|
#           self.record_separator = rs
#         end
#       end
#
#       def list_example_option(parser)
#         # List of arguments.
#         parser.on("--list x,y,z", Array, "Example 'list' of arguments") do |list|
#           self.list = list
#         end
#       end
#
#       def specify_encoding_option(parser)
#         # Keyword completion.  We are specifying a specific set of arguments (CODES
#         # and CODE_ALIASES - notice the latter is a Hash), and the user may provide
#         # the shortest unambiguous text.
#         code_list = (CODE_ALIASES.keys + CODES).join(', ')
#         parser.on("--code CODE", CODES, CODE_ALIASES, "Select encoding",
#                   "(#{code_list})") do |encoding|
#           self.encoding = encoding
#         end
#       end
#
#       def optional_option_argument_with_keyword_completion_option(parser)
#         # Optional '--type' option argument with keyword completion.
#         parser.on("--type [TYPE]", [:text, :binary, :auto],
#                   "Select transfer type (text, binary, auto)") do |t|
#           self.transfer_type = t
#         end
#       end
#
#       def boolean_verbose_option(parser)
#         # Boolean switch.
#         parser.on("-v", "--[no-]verbose", "Run verbosely") do |v|
#           self.verbose = v
#         end
#       end
#     end
#
#     #
#     # Return a structure describing the options.
#     #
#     def parse(args)
#       # The options specified on the command line will be collected in
#       # *options*.
#
#       @options = ScriptOptions.new
#       @args = Gem::OptionParser.new do |parser|
#         @options.define_options(parser)
#         parser.parse!(args)
#       end
#       @options
#     end
#
#     attr_reader :parser, :options
#   end  # class OptparseExample
#
#   example = OptparseExample.new
#   options = example.parse(ARGV)
#   pp options # example.options
#   pp ARGV
#
# === Shell Completion
#
# For modern shells (e.g. bash, zsh, etc.), you can use shell
# completion for command line options.
#
# === Further documentation
#
# The above examples, along with the accompanying
# {Tutorial}[./doc/optparse/tutorial_rdoc.html],
# should be enough to learn how to use this class.
# If you have any questions, file a ticket at http://bugs.ruby-lang.org.
#
class Gem::OptionParser
  Gem::OptionParser::Version = "0.2.0"

  # :stopdoc:
  NoArgument = [NO_ARGUMENT = :NONE, nil].freeze
  RequiredArgument = [REQUIRED_ARGUMENT = :REQUIRED, true].freeze
  OptionalArgument = [OPTIONAL_ARGUMENT = :OPTIONAL, false].freeze
  # :startdoc:

  #
  # Keyword completion module.  This allows partial arguments to be specified
  # and resolved against a list of acceptable values.
  #
  module Completion
    def self.regexp(key, icase)
      Regexp.new('\A' + Regexp.quote(key).gsub(/\w+\b/, '\&\w*'), icase)
    end

    def self.candidate(key, icase = false, pat = nil, &block)
      pat ||= Completion.regexp(key, icase)
      candidates = []
      block.call do |k, *v|
        (if Regexp === k
           kn = ""
           k === key
         else
           kn = defined?(k.id2name) ? k.id2name : k
           pat === kn
         end) or next
        v << k if v.empty?
        candidates << [k, v, kn]
      end
      candidates
    end

    def candidate(key, icase = false, pat = nil)
      Completion.candidate(key, icase, pat, &method(:each))
    end

    public
    def complete(key, icase = false, pat = nil)
      candidates = candidate(key, icase, pat, &method(:each)).sort_by {|k, v, kn| kn.size}
      if candidates.size == 1
        canon, sw, * = candidates[0]
      elsif candidates.size > 1
        canon, sw, cn = candidates.shift
        candidates.each do |k, v, kn|
          next if sw == v
          if String === cn and String === kn
            if cn.rindex(kn, 0)
              canon, sw, cn = k, v, kn
              next
            elsif kn.rindex(cn, 0)
              next
            end
          end
          throw :ambiguous, key
        end
      end
      if canon
        block_given? or return key, *sw
        yield(key, *sw)
      end
    end

    def convert(opt = nil, val = nil, *)
      val
    end
  end


  #
  # Map from option/keyword string to object with completion.
  #
  class OptionMap < Hash
    include Completion
  end


  #
  # Individual switch class.  Not important to the user.
  #
  # Defined within Switch are several Switch-derived classes: NoArgument,
  # RequiredArgument, etc.
  #
  class Switch
    attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block

    #
    # Guesses argument style from +arg+.  Returns corresponding
    # Gem::OptionParser::Switch class (OptionalArgument, etc.).
    #
    def self.guess(arg)
      case arg
      when ""
        t = self
      when /\A=?\[/
        t = Switch::OptionalArgument
      when /\A\s+\[/
        t = Switch::PlacedArgument
      else
        t = Switch::RequiredArgument
      end
      self >= t or incompatible_argument_styles(arg, t)
      t
    end

    def self.incompatible_argument_styles(arg, t)
      raise(ArgumentError, "#{arg}: incompatible argument styles\n  #{self}, #{t}",
            ParseError.filter_backtrace(caller(2)))
    end

    def self.pattern
      NilClass
    end

    def initialize(pattern = nil, conv = nil,
                   short = nil, long = nil, arg = nil,
                   desc = ([] if short or long), block = nil, &_block)
      raise if Array === pattern
      block ||= _block
      @pattern, @conv, @short, @long, @arg, @desc, @block =
        pattern, conv, short, long, arg, desc, block
    end

    #
    # Parses +arg+ and returns rest of +arg+ and matched portion to the
    # argument pattern. Yields when the pattern doesn't match substring.
    #
    def parse_arg(arg) # :nodoc:
      pattern or return nil, [arg]
      unless m = pattern.match(arg)
        yield(InvalidArgument, arg)
        return arg, []
      end
      if String === m
        m = [s = m]
      else
        m = m.to_a
        s = m[0]
        return nil, m unless String === s
      end
      raise InvalidArgument, arg unless arg.rindex(s, 0)
      return nil, m if s.length == arg.length
      yield(InvalidArgument, arg) # didn't match whole arg
      return arg[s.length..-1], m
    end
    private :parse_arg

    #
    # Parses argument, converts and returns +arg+, +block+ and result of
    # conversion. Yields at semi-error condition instead of raising an
    # exception.
    #
    def conv_arg(arg, val = []) # :nodoc:
      if conv
        val = conv.call(*val)
      else
        val = proc {|v| v}.call(*val)
      end
      return arg, block, val
    end
    private :conv_arg

    #
    # Produces the summary text. Each line of the summary is yielded to the
    # block (without newline).
    #
    # +sdone+::  Already summarized short style options keyed hash.
    # +ldone+::  Already summarized long style options keyed hash.
    # +width+::  Width of left side (option part). In other words, the right
    #            side (description part) starts after +width+ columns.
    # +max+::    Maximum width of left side -> the options are filled within
    #            +max+ columns.
    # +indent+:: Prefix string indents all summarized lines.
    #
    def summarize(sdone = {}, ldone = {}, width = 1, max = width - 1, indent = "")
      sopts, lopts = [], [], nil
      @short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
      @long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
      return if sopts.empty? and lopts.empty? # completely hidden

      left = [sopts.join(', ')]
      right = desc.dup

      while s = lopts.shift
        l = left[-1].length + s.length
        l += arg.length if left.size == 1 && arg
        l < max or sopts.empty? or left << +''
        left[-1] << (left[-1].empty? ? ' ' * 4 : ', ') << s
      end

      if arg
        left[0] << (left[1] ? arg.sub(/\A(\[?)=/, '\1') + ',' : arg)
      end
      mlen = left.collect {|ss| ss.length}.max.to_i
      while mlen > width and l = left.shift
        mlen = left.collect {|ss| ss.length}.max.to_i if l.length == mlen
        if l.length < width and (r = right[0]) and !r.empty?
          l = l.to_s.ljust(width) + ' ' + r
          right.shift
        end
        yield(indent + l)
      end

      while begin l = left.shift; r = right.shift; l or r end
        l = l.to_s.ljust(width) + ' ' + r if r and !r.empty?
        yield(indent + l)
      end

      self
    end

    def add_banner(to)  # :nodoc:
      unless @short or @long
        s = desc.join
        to << " [" + s + "]..." unless s.empty?
      end
      to
    end

    def match_nonswitch?(str)  # :nodoc:
      @pattern =~ str unless @short or @long
    end

    #
    # Main name of the switch.
    #
    def switch_name
      (long.first || short.first).sub(/\A-+(?:\[no-\])?/, '')
    end

    def compsys(sdone, ldone)   # :nodoc:
      sopts, lopts = [], []
      @short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
      @long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
      return if sopts.empty? and lopts.empty? # completely hidden

      (sopts+lopts).each do |opt|
        # "(-x -c -r)-l[left justify]"
        if /^--\[no-\](.+)$/ =~ opt
          o = $1
          yield("--#{o}", desc.join(""))
          yield("--no-#{o}", desc.join(""))
        else
          yield("#{opt}", desc.join(""))
        end
      end
    end

    #
    # Switch that takes no arguments.
    #
    class NoArgument < self

      #
      # Raises an exception if any arguments given.
      #
      def parse(arg, argv)
        yield(NeedlessArgument, arg) if arg
        conv_arg(arg)
      end

      def self.incompatible_argument_styles(*)
      end

      def self.pattern
        Object
      end
    end

    #
    # Switch that takes an argument.
    #
    class RequiredArgument < self

      #
      # Raises an exception if argument is not present.
      #
      def parse(arg, argv)
        unless arg
          raise MissingArgument if argv.empty?
          arg = argv.shift
        end
        conv_arg(*parse_arg(arg, &method(:raise)))
      end
    end

    #
    # Switch that can omit argument.
    #
    class OptionalArgument < self

      #
      # Parses argument if given, or uses default value.
      #
      def parse(arg, argv, &error)
        if arg
          conv_arg(*parse_arg(arg, &error))
        else
          conv_arg(arg)
        end
      end
    end

    #
    # Switch that takes an argument, which does not begin with '-'.
    #
    class PlacedArgument < self

      #
      # Returns nil if argument is not present or begins with '-'.
      #
      def parse(arg, argv, &error)
        if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
          return nil, block, nil
        end
        opt = (val = parse_arg(val, &error))[1]
        val = conv_arg(*val)
        if opt and !arg
          argv.shift
        else
          val[0] = nil
        end
        val
      end
    end
  end

  #
  # Simple option list providing mapping from short and/or long option
  # string to Gem::OptionParser::Switch and mapping from acceptable argument to
  # matching pattern and converter pair. Also provides summary feature.
  #
  class List
    # Map from acceptable argument types to pattern and converter pairs.
    attr_reader :atype

    # Map from short style option switches to actual switch objects.
    attr_reader :short

    # Map from long style option switches to actual switch objects.
    attr_reader :long

    # List of all switches and summary string.
    attr_reader :list

    #
    # Just initializes all instance variables.
    #
    def initialize
      @atype = {}
      @short = OptionMap.new
      @long = OptionMap.new
      @list = []
    end

    #
    # See Gem::OptionParser.accept.
    #
    def accept(t, pat = /.*/m, &block)
      if pat
        pat.respond_to?(:match) or
          raise TypeError, "has no `match'", ParseError.filter_backtrace(caller(2))
      else
        pat = t if t.respond_to?(:match)
      end
      unless block
        block = pat.method(:convert).to_proc if pat.respond_to?(:convert)
      end
      @atype[t] = [pat, block]
    end

    #
    # See Gem::OptionParser.reject.
    #
    def reject(t)
      @atype.delete(t)
    end

    #
    # Adds +sw+ according to +sopts+, +lopts+ and +nlopts+.
    #
    # +sw+::     Gem::OptionParser::Switch instance to be added.
    # +sopts+::  Short style option list.
    # +lopts+::  Long style option list.
    # +nlopts+:: Negated long style options list.
    #
    def update(sw, sopts, lopts, nsw = nil, nlopts = nil) # :nodoc:
      sopts.each {|o| @short[o] = sw} if sopts
      lopts.each {|o| @long[o] = sw} if lopts
      nlopts.each {|o| @long[o] = nsw} if nsw and nlopts
      used = @short.invert.update(@long.invert)
      @list.delete_if {|o| Switch === o and !used[o]}
    end
    private :update

    #
    # Inserts +switch+ at the head of the list, and associates short, long
    # and negated long options. Arguments are:
    #
    # +switch+::      Gem::OptionParser::Switch instance to be inserted.
    # +short_opts+::  List of short style options.
    # +long_opts+::   List of long style options.
    # +nolong_opts+:: List of long style options with "no-" prefix.
    #
    #   prepend(switch, short_opts, long_opts, nolong_opts)
    #
    def prepend(*args)
      update(*args)
      @list.unshift(args[0])
    end

    #
    # Appends +switch+ at the tail of the list, and associates short, long
    # and negated long options. Arguments are:
    #
    # +switch+::      Gem::OptionParser::Switch instance to be inserted.
    # +short_opts+::  List of short style options.
    # +long_opts+::   List of long style options.
    # +nolong_opts+:: List of long style options with "no-" prefix.
    #
    #   append(switch, short_opts, long_opts, nolong_opts)
    #
    def append(*args)
      update(*args)
      @list.push(args[0])
    end

    #
    # Searches +key+ in +id+ list. The result is returned or yielded if a
    # block is given. If it isn't found, nil is returned.
    #
    def search(id, key)
      if list = __send__(id)
        val = list.fetch(key) {return nil}
        block_given? ? yield(val) : val
      end
    end

    #
    # Searches list +id+ for +opt+ and the optional patterns for completion
    # +pat+. If +icase+ is true, the search is case insensitive. The result
    # is returned or yielded if a block is given. If it isn't found, nil is
    # returned.
    #
    def complete(id, opt, icase = false, *pat, &block)
      __send__(id).complete(opt, icase, *pat, &block)
    end

    def get_candidates(id)
      yield __send__(id).keys
    end

    #
    # Iterates over each option, passing the option to the +block+.
    #
    def each_option(&block)
      list.each(&block)
    end

    #
    # Creates the summary table, passing each line to the +block+ (without
    # newline). The arguments +args+ are passed along to the summarize
    # method which is called on every option.
    #
    def summarize(*args, &block)
      sum = []
      list.reverse_each do |opt|
        if opt.respond_to?(:summarize) # perhaps Gem::OptionParser::Switch
          s = []
          opt.summarize(*args) {|l| s << l}
          sum.concat(s.reverse)
        elsif !opt or opt.empty?
          sum << ""
        elsif opt.respond_to?(:each_line)
          sum.concat([*opt.each_line].reverse)
        else
          sum.concat([*opt.each].reverse)
        end
      end
      sum.reverse_each(&block)
    end

    def add_banner(to)  # :nodoc:
      list.each do |opt|
        if opt.respond_to?(:add_banner)
          opt.add_banner(to)
        end
      end
      to
    end

    def compsys(*args, &block)  # :nodoc:
      list.each do |opt|
        if opt.respond_to?(:compsys)
          opt.compsys(*args, &block)
        end
      end
    end
  end

  #
  # Hash with completion search feature. See Gem::OptionParser::Completion.
  #
  class CompletingHash < Hash
    include Completion

    #
    # Completion for hash key.
    #
    def match(key)
      *values = fetch(key) {
        raise AmbiguousArgument, catch(:ambiguous) {return complete(key)}
      }
      return key, *values
    end
  end

  # :stopdoc:

  #
  # Enumeration of acceptable argument styles. Possible values are:
  #
  # NO_ARGUMENT::       The switch takes no arguments. (:NONE)
  # REQUIRED_ARGUMENT:: The switch requires an argument. (:REQUIRED)
  # OPTIONAL_ARGUMENT:: The switch requires an optional argument. (:OPTIONAL)
  #
  # Use like --switch=argument (long style) or -Xargument (short style). For
  # short style, only portion matched to argument pattern is treated as
  # argument.
  #
  ArgumentStyle = {}
  NoArgument.each {|el| ArgumentStyle[el] = Switch::NoArgument}
  RequiredArgument.each {|el| ArgumentStyle[el] = Switch::RequiredArgument}
  OptionalArgument.each {|el| ArgumentStyle[el] = Switch::OptionalArgument}
  ArgumentStyle.freeze

  #
  # Switches common used such as '--', and also provides default
  # argument classes
  #
  DefaultList = List.new
  DefaultList.short['-'] = Switch::NoArgument.new {}
  DefaultList.long[''] = Switch::NoArgument.new {throw :terminate}


  COMPSYS_HEADER = <<'XXX'      # :nodoc:

typeset -A opt_args
local context state line

_arguments -s -S \
XXX

  def compsys(to, name = File.basename($0)) # :nodoc:
    to << "#compdef #{name}\n"
    to << COMPSYS_HEADER
    visit(:compsys, {}, {}) {|o, d|
      to << %Q[  "#{o}[#{d.gsub(/[\"\[\]]/, '\\\\\&')}]" \\\n]
    }
    to << "  '*:file:_files' && return 0\n"
  end

  #
  # Default options for ARGV, which never appear in option summary.
  #
  Officious = {}

  #
  # --help
  # Shows option summary.
  #
  Officious['help'] = proc do |parser|
    Switch::NoArgument.new do |arg|
      puts parser.help
      exit
    end
  end

  #
  # --*-completion-bash=WORD
  # Shows candidates for command line completion.
  #
  Officious['*-completion-bash'] = proc do |parser|
    Switch::RequiredArgument.new do |arg|
      puts parser.candidate(arg)
      exit
    end
  end

  #
  # --*-completion-zsh[=NAME:FILE]
  # Creates zsh completion file.
  #
  Officious['*-completion-zsh'] = proc do |parser|
    Switch::OptionalArgument.new do |arg|
      parser.compsys(STDOUT, arg)
      exit
    end
  end

  #
  # --version
  # Shows version string if Version is defined.
  #
  Officious['version'] = proc do |parser|
    Switch::OptionalArgument.new do |pkg|
      if pkg
        begin
          require 'rubygems/optparse/lib/optparse/version'
        rescue LoadError
        else
          show_version(*pkg.split(/,/)) or
            abort("#{parser.program_name}: no version found in package #{pkg}")
          exit
        end
      end
      v = parser.ver or abort("#{parser.program_name}: version unknown")
      puts v
      exit
    end
  end

  # :startdoc:

  #
  # Class methods
  #

  #
  # Initializes a new instance and evaluates the optional block in context
  # of the instance. Arguments +args+ are passed to #new, see there for
  # description of parameters.
  #
  # This method is *deprecated*, its behavior corresponds to the older #new
  # method.
  #
  def self.with(*args, &block)
    opts = new(*args)
    opts.instance_eval(&block)
    opts
  end

  #
  # Returns an incremented value of +default+ according to +arg+.
  #
  def self.inc(arg, default = nil)
    case arg
    when Integer
      arg.nonzero?
    when nil
      default.to_i + 1
    end
  end
  def inc(*args)
    self.class.inc(*args)
  end

  #
  # Initializes the instance and yields itself if called with a block.
  #
  # +banner+:: Banner message.
  # +width+::  Summary width.
  # +indent+:: Summary indent.
  #
  def initialize(banner = nil, width = 32, indent = ' ' * 4)
    @stack = [DefaultList, List.new, List.new]
    @program_name = nil
    @banner = banner
    @summary_width = width
    @summary_indent = indent
    @default_argv = ARGV
    @require_exact = false
    add_officious
    yield self if block_given?
  end

  def add_officious  # :nodoc:
    list = base()
    Officious.each do |opt, block|
      list.long[opt] ||= block.call(self)
    end
  end

  #
  # Terminates option parsing. Optional parameter +arg+ is a string pushed
  # back to be the first non-option argument.
  #
  def terminate(arg = nil)
    self.class.terminate(arg)
  end
  def self.terminate(arg = nil)
    throw :terminate, arg
  end

  @stack = [DefaultList]
  def self.top() DefaultList end

  #
  # Directs to accept specified class +t+. The argument string is passed to
  # the block in which it should be converted to the desired class.
  #
  # +t+::   Argument class specifier, any object including Class.
  # +pat+:: Pattern for argument, defaults to +t+ if it responds to match.
  #
  #   accept(t, pat, &block)
  #
  def accept(*args, &blk) top.accept(*args, &blk) end
  #
  # See #accept.
  #
  def self.accept(*args, &blk) top.accept(*args, &blk) end

  #
  # Directs to reject specified class argument.
  #
  # +t+:: Argument class specifier, any object including Class.
  #
  #   reject(t)
  #
  def reject(*args, &blk) top.reject(*args, &blk) end
  #
  # See #reject.
  #
  def self.reject(*args, &blk) top.reject(*args, &blk) end

  #
  # Instance methods
  #

  # Heading banner preceding summary.
  attr_writer :banner

  # Program name to be emitted in error message and default banner,
  # defaults to $0.
  attr_writer :program_name

  # Width for option list portion of summary. Must be Numeric.
  attr_accessor :summary_width

  # Indentation for summary. Must be String (or have + String method).
  attr_accessor :summary_indent

  # Strings to be parsed in default.
  attr_accessor :default_argv

  # Whether to require that options match exactly (disallows providing
  # abbreviated long option as short option).
  attr_accessor :require_exact

  #
  # Heading banner preceding summary.
  #
  def banner
    unless @banner
      @banner = +"Usage: #{program_name} [options]"
      visit(:add_banner, @banner)
    end
    @banner
  end

  #
  # Program name to be emitted in error message and default banner, defaults
  # to $0.
  #
  def program_name
    @program_name || File.basename($0, '.*')
  end

  # for experimental cascading :-)
  alias set_banner banner=
  alias set_program_name program_name=
  alias set_summary_width summary_width=
  alias set_summary_indent summary_indent=

  # Version
  attr_writer :version
  # Release code
  attr_writer :release

  #
  # Version
  #
  def version
    (defined?(@version) && @version) || (defined?(::Version) && ::Version)
  end

  #
  # Release code
  #
  def release
    (defined?(@release) && @release) || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
  end

  #
  # Returns version string from program_name, version and release.
  #
  def ver
    if v = version
      str = +"#{program_name} #{[v].join('.')}"
      str << " (#{v})" if v = release
      str
    end
  end

  def warn(mesg = $!)
    super("#{program_name}: #{mesg}")
  end

  def abort(mesg = $!)
    super("#{program_name}: #{mesg}")
  end

  #
  # Subject of #on / #on_head, #accept / #reject
  #
  def top
    @stack[-1]
  end

  #
  # Subject of #on_tail.
  #
  def base
    @stack[1]
  end

  #
  # Pushes a new List.
  #
  def new
    @stack.push(List.new)
    if block_given?
      yield self
    else
      self
    end
  end

  #
  # Removes the last List.
  #
  def remove
    @stack.pop
  end

  #
  # Puts option summary into +to+ and returns +to+. Yields each line if
  # a block is given.
  #
  # +to+:: Output destination, which must have method <<. Defaults to [].
  # +width+:: Width of left side, defaults to @summary_width.
  # +max+:: Maximum length allowed for left side, defaults to +width+ - 1.
  # +indent+:: Indentation, defaults to @summary_indent.
  #
  def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
    nl = "\n"
    blk ||= proc {|l| to << (l.index(nl, -1) ? l : l + nl)}
    visit(:summarize, {}, {}, width, max, indent, &blk)
    to
  end

  #
  # Returns option summary string.
  #
  def help; summarize("#{banner}".sub(/\n?\z/, "\n")) end
  alias to_s help

  #
  # Returns option summary list.
  #
  def to_a; summarize("#{banner}".split(/^/)) end

  #
  # Checks if an argument is given twice, in which case an ArgumentError is
  # raised. Called from Gem::OptionParser#switch only.
  #
  # +obj+:: New argument.
  # +prv+:: Previously specified argument.
  # +msg+:: Exception message.
  #
  def notwice(obj, prv, msg) # :nodoc:
    unless !prv or prv == obj
      raise(ArgumentError, "argument #{msg} given twice: #{obj}",
            ParseError.filter_backtrace(caller(2)))
    end
    obj
  end
  private :notwice

  SPLAT_PROC = proc {|*a| a.length <= 1 ? a.first : a} # :nodoc:

  # :call-seq:
  #   make_switch(params, block = nil)
  #
  # :include: ../doc/optparse/creates_option.rdoc
  #
  def make_switch(opts, block = nil)
    short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], []
    ldesc, sdesc, desc, arg = [], [], []
    default_style = Switch::NoArgument
    default_pattern = nil
    klass = nil
    q, a = nil
    has_arg = false

    opts.each do |o|
      # argument class
      next if search(:atype, o) do |pat, c|
        klass = notwice(o, klass, 'type')
        if not_style and not_style != Switch::NoArgument
          not_pattern, not_conv = pat, c
        else
          default_pattern, conv = pat, c
        end
      end

      # directly specified pattern(any object possible to match)
      if (!(String === o || Symbol === o)) and o.respond_to?(:match)
        pattern = notwice(o, pattern, 'pattern')
        if pattern.respond_to?(:convert)
          conv = pattern.method(:convert).to_proc
        else
          conv = SPLAT_PROC
        end
        next
      end

      # anything others
      case o
      when Proc, Method
        block = notwice(o, block, 'block')
      when Array, Hash
        case pattern
        when CompletingHash
        when nil
          pattern = CompletingHash.new
          conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert)
        else
          raise ArgumentError, "argument pattern given twice"
        end
        o.each {|pat, *v| pattern[pat] = v.fetch(0) {pat}}
      when Module
        raise ArgumentError, "unsupported argument type: #{o}", ParseError.filter_backtrace(caller(4))
      when *ArgumentStyle.keys
        style = notwice(ArgumentStyle[o], style, 'style')
      when /^--no-([^\[\]=\s]*)(.+)?/
        q, a = $1, $2
        o = notwice(a ? Object : TrueClass, klass, 'type')
        not_pattern, not_conv = search(:atype, o) unless not_style
        not_style = (not_style || default_style).guess(arg = a) if a
        default_style = Switch::NoArgument
        default_pattern, conv = search(:atype, FalseClass) unless default_pattern
        ldesc << "--no-#{q}"
        (q = q.downcase).tr!('_', '-')
        long << "no-#{q}"
        nolong << q
      when /^--\[no-\]([^\[\]=\s]*)(.+)?/
        q, a = $1, $2
        o = notwice(a ? Object : TrueClass, klass, 'type')
        if a
          default_style = default_style.guess(arg = a)
          default_pattern, conv = search(:atype, o) unless default_pattern
        end
        ldesc << "--[no-]#{q}"
        (o = q.downcase).tr!('_', '-')
        long << o
        not_pattern, not_conv = search(:atype, FalseClass) unless not_style
        not_style = Switch::NoArgument
        nolong << "no-#{o}"
      when /^--([^\[\]=\s]*)(.+)?/
        q, a = $1, $2
        if a
          o = notwice(NilClass, klass, 'type')
          default_style = default_style.guess(arg = a)
          default_pattern, conv = search(:atype, o) unless default_pattern
        end
        ldesc << "--#{q}"
        (o = q.downcase).tr!('_', '-')
        long << o
      when /^-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/
        q, a = $1, $2
        o = notwice(Object, klass, 'type')
        if a
          default_style = default_style.guess(arg = a)
          default_pattern, conv = search(:atype, o) unless default_pattern
        else
          has_arg = true
        end
        sdesc << "-#{q}"
        short << Regexp.new(q)
      when /^-(.)(.+)?/
        q, a = $1, $2
        if a
          o = notwice(NilClass, klass, 'type')
          default_style = default_style.guess(arg = a)
          default_pattern, conv = search(:atype, o) unless default_pattern
        end
        sdesc << "-#{q}"
        short << q
      when /^=/
        style = notwice(default_style.guess(arg = o), style, 'style')
        default_pattern, conv = search(:atype, Object) unless default_pattern
      else
        desc.push(o)
      end
    end

    default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern
    if !(short.empty? and long.empty?)
      if has_arg and default_style == Switch::NoArgument
        default_style = Switch::RequiredArgument
      end
      s = (style || default_style).new(pattern || default_pattern,
                                       conv, sdesc, ldesc, arg, desc, block)
    elsif !block
      if style or pattern
        raise ArgumentError, "no switch given", ParseError.filter_backtrace(caller)
      end
      s = desc
    else
      short << pattern
      s = (style || default_style).new(pattern,
                                       conv, nil, nil, arg, desc, block)
    end
    return s, short, long,
      (not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style),
      nolong
  end

  # :call-seq:
  #   define(*params, &block)
  #
  # :include: ../doc/optparse/creates_option.rdoc
  #
  def define(*opts, &block)
    top.append(*(sw = make_switch(opts, block)))
    sw[0]
  end

  # :call-seq:
  #   on(*params, &block)
  #
  # :include: ../doc/optparse/creates_option.rdoc
  #
  def on(*opts, &block)
    define(*opts, &block)
    self
  end
  alias def_option define

  # :call-seq:
  #   define_head(*params, &block)
  #
  # :include: ../doc/optparse/creates_option.rdoc
  #
  def define_head(*opts, &block)
    top.prepend(*(sw = make_switch(opts, block)))
    sw[0]
  end

  # :call-seq:
  #   on_head(*params, &block)
  #
  # :include: ../doc/optparse/creates_option.rdoc
  #
  # The new option is added at the head of the summary.
  #
  def on_head(*opts, &block)
    define_head(*opts, &block)
    self
  end
  alias def_head_option define_head

  # :call-seq:
  #   define_tail(*params, &block)
  #
  # :include: ../doc/optparse/creates_option.rdoc
  #
  def define_tail(*opts, &block)
    base.append(*(sw = make_switch(opts, block)))
    sw[0]
  end

  #
  # :call-seq:
  #   on_tail(*params, &block)
  #
  # :include: ../doc/optparse/creates_option.rdoc
  #
  # The new option is added at the tail of the summary.
  #
  def on_tail(*opts, &block)
    define_tail(*opts, &block)
    self
  end
  alias def_tail_option define_tail

  #
  # Add separator in summary.
  #
  def separator(string)
    top.append(string, nil, nil)
  end

  #
  # Parses command line arguments +argv+ in order. When a block is given,
  # each non-option argument is yielded. When optional +into+ keyword
  # argument is provided, the parsed option values are stored there via
  # <code>[]=</code> method (so it can be Hash, or OpenStruct, or other
  # similar object).
  #
  # Returns the rest of +argv+ left unparsed.
  #
  def order(*argv, into: nil, &nonopt)
    argv = argv[0].dup if argv.size == 1 and Array === argv[0]
    order!(argv, into: into, &nonopt)
  end

  #
  # Same as #order, but removes switches destructively.
  # Non-option arguments remain in +argv+.
  #
  def order!(argv = default_argv, into: nil, &nonopt)
    setter = ->(name, val) {into[name.to_sym] = val} if into
    parse_in_order(argv, setter, &nonopt)
  end

  def parse_in_order(argv = default_argv, setter = nil, &nonopt)  # :nodoc:
    opt, arg, val, rest = nil
    nonopt ||= proc {|a| throw :terminate, a}
    argv.unshift(arg) if arg = catch(:terminate) {
      while arg = argv.shift
        case arg
        # long option
        when /\A--([^=]*)(?:=(.*))?/m
          opt, rest = $1, $2
          opt.tr!('_', '-')
          begin
            sw, = complete(:long, opt, true)
            if require_exact && !sw.long.include?(arg)
              raise InvalidOption, arg
            end
          rescue ParseError
            raise $!.set_option(arg, true)
          end
          begin
            opt, cb, val = sw.parse(rest, argv) {|*exc| raise(*exc)}
            val = cb.call(val) if cb
            setter.call(sw.switch_name, val) if setter
          rescue ParseError
            raise $!.set_option(arg, rest)
          end

        # short option
        when /\A-(.)((=).*|.+)?/m
          eq, rest, opt = $3, $2, $1
          has_arg, val = eq, rest
          begin
            sw, = search(:short, opt)
            unless sw
              begin
                sw, = complete(:short, opt)
                # short option matched.
                val = arg.delete_prefix('-')
                has_arg = true
              rescue InvalidOption
                raise if require_exact
                # if no short options match, try completion with long
                # options.
                sw, = complete(:long, opt)
                eq ||= !rest
              end
            end
          rescue ParseError
            raise $!.set_option(arg, true)
          end
          begin
            opt, cb, val = sw.parse(val, argv) {|*exc| raise(*exc) if eq}
          rescue ParseError
            raise $!.set_option(arg, arg.length > 2)
          else
            raise InvalidOption, arg if has_arg and !eq and arg == "-#{opt}"
          end
          begin
            argv.unshift(opt) if opt and (!rest or (opt = opt.sub(/\A-*/, '-')) != '-')
            val = cb.call(val) if cb
            setter.call(sw.switch_name, val) if setter
          rescue ParseError
            raise $!.set_option(arg, arg.length > 2)
          end

        # non-option argument
        else
          catch(:prune) do
            visit(:each_option) do |sw0|
              sw = sw0
              sw.block.call(arg) if Switch === sw and sw.match_nonswitch?(arg)
            end
            nonopt.call(arg)
          end
        end
      end

      nil
    }

    visit(:search, :short, nil) {|sw| sw.block.call(*argv) if !sw.pattern}

    argv
  end
  private :parse_in_order

  #
  # Parses command line arguments +argv+ in permutation mode and returns
  # list of non-option arguments. When optional +into+ keyword
  # argument is provided, the parsed option values are stored there via
  # <code>[]=</code> method (so it can be Hash, or OpenStruct, or other
  # similar object).
  #
  def permute(*argv, into: nil)
    argv = argv[0].dup if argv.size == 1 and Array === argv[0]
    permute!(argv, into: into)
  end

  #
  # Same as #permute, but removes switches destructively.
  # Non-option arguments remain in +argv+.
  #
  def permute!(argv = default_argv, into: nil)
    nonopts = []
    order!(argv, into: into, &nonopts.method(:<<))
    argv[0, 0] = nonopts
    argv
  end

  #
  # Parses command line arguments +argv+ in order when environment variable
  # POSIXLY_CORRECT is set, and in permutation mode otherwise.
  # When optional +into+ keyword argument is provided, the parsed option
  # values are stored there via <code>[]=</code> method (so it can be Hash,
  # or OpenStruct, or other similar object).
  #
  def parse(*argv, into: nil)
    argv = argv[0].dup if argv.size == 1 and Array === argv[0]
    parse!(argv, into: into)
  end

  #
  # Same as #parse, but removes switches destructively.
  # Non-option arguments remain in +argv+.
  #
  def parse!(argv = default_argv, into: nil)
    if ENV.include?('POSIXLY_CORRECT')
      order!(argv, into: into)
    else
      permute!(argv, into: into)
    end
  end

  #
  # Wrapper method for getopts.rb.
  #
  #   params = ARGV.getopts("ab:", "foo", "bar:", "zot:Z;zot option")
  #   # params["a"] = true   # -a
  #   # params["b"] = "1"    # -b1
  #   # params["foo"] = "1"  # --foo
  #   # params["bar"] = "x"  # --bar x
  #   # params["zot"] = "z"  # --zot Z
  #
  def getopts(*args)
    argv = Array === args.first ? args.shift : default_argv
    single_options, *long_options = *args

    result = {}

    single_options.scan(/(.)(:)?/) do |opt, val|
      if val
        result[opt] = nil
        define("-#{opt} VAL")
      else
        result[opt] = false
        define("-#{opt}")
      end
    end if single_options

    long_options.each do |arg|
      arg, desc = arg.split(';', 2)
      opt, val = arg.split(':', 2)
      if val
        result[opt] = val.empty? ? nil : val
        define("--#{opt}=#{result[opt] || "VAL"}", *[desc].compact)
      else
        result[opt] = false
        define("--#{opt}", *[desc].compact)
      end
    end

    parse_in_order(argv, result.method(:[]=))
    result
  end

  #
  # See #getopts.
  #
  def self.getopts(*args)
    new.getopts(*args)
  end

  #
  # Traverses @stack, sending each element method +id+ with +args+ and
  # +block+.
  #
  def visit(id, *args, &block) # :nodoc:
    @stack.reverse_each do |el|
      el.__send__(id, *args, &block)
    end
    nil
  end
  private :visit

  #
  # Searches +key+ in @stack for +id+ hash and returns or yields the result.
  #
  def search(id, key) # :nodoc:
    block_given = block_given?
    visit(:search, id, key) do |k|
      return block_given ? yield(k) : k
    end
  end
  private :search

  #
  # Completes shortened long style option switch and returns pair of
  # canonical switch and switch descriptor Gem::OptionParser::Switch.
  #
  # +typ+::   Searching table.
  # +opt+::   Searching key.
  # +icase+:: Search case insensitive if true.
  # +pat+::   Optional pattern for completion.
  #
  def complete(typ, opt, icase = false, *pat) # :nodoc:
    if pat.empty?
      search(typ, opt) {|sw| return [sw, opt]} # exact match or...
    end
    ambiguous = catch(:ambiguous) {
      visit(:complete, typ, opt, icase, *pat) {|o, *sw| return sw}
    }
    exc = ambiguous ? AmbiguousOption : InvalidOption
    raise exc.new(opt, additional: self.method(:additional_message).curry[typ])
  end
  private :complete

  #
  # Returns additional info.
  #
  def additional_message(typ, opt)
    return unless typ and opt and defined?(DidYouMean::SpellChecker)
    all_candidates = []
    visit(:get_candidates, typ) do |candidates|
      all_candidates.concat(candidates)
    end
    all_candidates.select! {|cand| cand.is_a?(String) }
    checker = DidYouMean::SpellChecker.new(dictionary: all_candidates)
    suggestions = all_candidates & checker.correct(opt)
    if DidYouMean.respond_to?(:formatter)
      DidYouMean.formatter.message_for(suggestions)
    else
       "\nDid you mean?  #{suggestions.join("\n               ")}"
    end
  end

  def candidate(word)
    list = []
    case word
    when '-'
      long = short = true
    when /\A--/
      word, arg = word.split(/=/, 2)
      argpat = Completion.regexp(arg, false) if arg and !arg.empty?
      long = true
    when /\A-/
      short = true
    end
    pat = Completion.regexp(word, long)
    visit(:each_option) do |opt|
      next unless Switch === opt
      opts = (long ? opt.long : []) + (short ? opt.short : [])
      opts = Completion.candidate(word, true, pat, &opts.method(:each)).map(&:first) if pat
      if /\A=/ =~ opt.arg
        opts.map! {|sw| sw + "="}
        if arg and CompletingHash === opt.pattern
          if opts = opt.pattern.candidate(arg, false, argpat)
            opts.map!(&:last)
          end
        end
      end
      list.concat(opts)
    end
    list
  end

  #
  # Loads options from file names as +filename+. Does nothing when the file
  # is not present. Returns whether successfully loaded.
  #
  # +filename+ defaults to basename of the program without suffix in a
  # directory ~/.options, then the basename with '.options' suffix
  # under XDG and Haiku standard places.
  #
  def load(filename = nil)
    unless filename
      basename = File.basename($0, '.*')
      return true if load(File.expand_path(basename, '~/.options')) rescue nil
      basename << ".options"
      return [
        # XDG
        ENV['XDG_CONFIG_HOME'],
        '~/.config',
        *ENV['XDG_CONFIG_DIRS']&.split(File::PATH_SEPARATOR),

        # Haiku
        '~/config/settings',
      ].any? {|dir|
        next if !dir or dir.empty?
        load(File.expand_path(basename, dir)) rescue nil
      }
    end
    begin
      parse(*IO.readlines(filename).each {|s| s.chomp!})
      true
    rescue Errno::ENOENT, Errno::ENOTDIR
      false
    end
  end

  #
  # Parses environment variable +env+ or its uppercase with splitting like a
  # shell.
  #
  # +env+ defaults to the basename of the program.
  #
  def environment(env = File.basename($0, '.*'))
    env = ENV[env] || ENV[env.upcase] or return
    require 'shellwords'
    parse(*Shellwords.shellwords(env))
  end

  #
  # Acceptable argument classes
  #

  #
  # Any string and no conversion. This is fall-back.
  #
  accept(Object) {|s,|s or s.nil?}

  accept(NilClass) {|s,|s}

  #
  # Any non-empty string, and no conversion.
  #
  accept(String, /.+/m) {|s,*|s}

  #
  # Ruby/C-like integer, octal for 0-7 sequence, binary for 0b, hexadecimal
  # for 0x, and decimal for others; with optional sign prefix. Converts to
  # Integer.
  #
  decimal = '\d+(?:_\d+)*'
  binary = 'b[01]+(?:_[01]+)*'
  hex = 'x[\da-f]+(?:_[\da-f]+)*'
  octal = "0(?:[0-7]+(?:_[0-7]+)*|#{binary}|#{hex})?"
  integer = "#{octal}|#{decimal}"

  accept(Integer, %r"\A[-+]?(?:#{integer})\z"io) {|s,|
    begin
      Integer(s)
    rescue ArgumentError
      raise Gem::OptionParser::InvalidArgument, s
    end if s
  }

  #
  # Float number format, and converts to Float.
  #
  float = "(?:#{decimal}(?=(.)?)(?:\\.(?:#{decimal})?)?|\\.#{decimal})(?:E[-+]?#{decimal})?"
  floatpat = %r"\A[-+]?#{float}\z"io
  accept(Float, floatpat) {|s,| s.to_f if s}

  #
  # Generic numeric format, converts to Integer for integer format, Float
  # for float format, and Rational for rational format.
  #
  real = "[-+]?(?:#{octal}|#{float})"
  accept(Numeric, /\A(#{real})(?:\/(#{real}))?\z/io) {|s, d, f, n,|
    if n
      Rational(d, n)
    elsif f
      Float(s)
    else
      Integer(s)
    end
  }

  #
  # Decimal integer format, to be converted to Integer.
  #
  DecimalInteger = /\A[-+]?#{decimal}\z/io
  accept(DecimalInteger, DecimalInteger) {|s,|
    begin
      Integer(s, 10)
    rescue ArgumentError
      raise Gem::OptionParser::InvalidArgument, s
    end if s
  }

  #
  # Ruby/C like octal/hexadecimal/binary integer format, to be converted to
  # Integer.
  #
  OctalInteger = /\A[-+]?(?:[0-7]+(?:_[0-7]+)*|0(?:#{binary}|#{hex}))\z/io
  accept(OctalInteger, OctalInteger) {|s,|
    begin
      Integer(s, 8)
    rescue ArgumentError
      raise Gem::OptionParser::InvalidArgument, s
    end if s
  }

  #
  # Decimal integer/float number format, to be converted to Integer for
  # integer format, Float for float format.
  #
  DecimalNumeric = floatpat     # decimal integer is allowed as float also.
  accept(DecimalNumeric, floatpat) {|s, f|
    begin
      if f
        Float(s)
      else
        Integer(s)
      end
    rescue ArgumentError
      raise Gem::OptionParser::InvalidArgument, s
    end if s
  }

  #
  # Boolean switch, which means whether it is present or not, whether it is
  # absent or not with prefix no-, or it takes an argument
  # yes/no/true/false/+/-.
  #
  yesno = CompletingHash.new
  %w[- no false].each {|el| yesno[el] = false}
  %w[+ yes true].each {|el| yesno[el] = true}
  yesno['nil'] = false          # should be nil?
  accept(TrueClass, yesno) {|arg, val| val == nil or val}
  #
  # Similar to TrueClass, but defaults to false.
  #
  accept(FalseClass, yesno) {|arg, val| val != nil and val}

  #
  # List of strings separated by ",".
  #
  accept(Array) do |s, |
    if s
      s = s.split(',').collect {|ss| ss unless ss.empty?}
    end
    s
  end

  #
  # Regular expression with options.
  #
  accept(Regexp, %r"\A/((?:\\.|[^\\])*)/([[:alpha:]]+)?\z|.*") do |all, s, o|
    f = 0
    if o
      f |= Regexp::IGNORECASE if /i/ =~ o
      f |= Regexp::MULTILINE if /m/ =~ o
      f |= Regexp::EXTENDED if /x/ =~ o
      k = o.delete("imx")
      k = nil if k.empty?
    end
    Regexp.new(s || all, f, k)
  end

  #
  # Exceptions
  #

  #
  # Base class of exceptions from Gem::OptionParser.
  #
  class ParseError < RuntimeError
    # Reason which caused the error.
    Reason = 'parse error'

    def initialize(*args, additional: nil)
      @additional = additional
      @arg0, = args
      @args = args
      @reason = nil
    end

    attr_reader :args
    attr_writer :reason
    attr_accessor :additional

    #
    # Pushes back erred argument(s) to +argv+.
    #
    def recover(argv)
      argv[0, 0] = @args
      argv
    end

    def self.filter_backtrace(array)
      unless $DEBUG
        array.delete_if(&%r"\A#{Regexp.quote(__FILE__)}:"o.method(:=~))
      end
      array
    end

    def set_backtrace(array)
      super(self.class.filter_backtrace(array))
    end

    def set_option(opt, eq)
      if eq
        @args[0] = opt
      else
        @args.unshift(opt)
      end
      self
    end

    #
    # Returns error reason. Override this for I18N.
    #
    def reason
      @reason || self.class::Reason
    end

    def inspect
      "#<#{self.class}: #{args.join(' ')}>"
    end

    #
    # Default stringizing method to emit standard error message.
    #
    def message
      "#{reason}: #{args.join(' ')}#{additional[@arg0] if additional}"
    end

    alias to_s message
  end

  #
  # Raises when ambiguously completable string is encountered.
  #
  class AmbiguousOption < ParseError
    const_set(:Reason, 'ambiguous option')
  end

  #
  # Raises when there is an argument for a switch which takes no argument.
  #
  class NeedlessArgument < ParseError
    const_set(:Reason, 'needless argument')
  end

  #
  # Raises when a switch with mandatory argument has no argument.
  #
  class MissingArgument < ParseError
    const_set(:Reason, 'missing argument')
  end

  #
  # Raises when switch is undefined.
  #
  class InvalidOption < ParseError
    const_set(:Reason, 'invalid option')
  end

  #
  # Raises when the given argument does not match required format.
  #
  class InvalidArgument < ParseError
    const_set(:Reason, 'invalid argument')
  end

  #
  # Raises when the given argument word can't be completed uniquely.
  #
  class AmbiguousArgument < InvalidArgument
    const_set(:Reason, 'ambiguous argument')
  end

  #
  # Miscellaneous
  #

  #
  # Extends command line arguments array (ARGV) to parse itself.
  #
  module Arguable

    #
    # Sets Gem::OptionParser object, when +opt+ is +false+ or +nil+, methods
    # Gem::OptionParser::Arguable#options and Gem::OptionParser::Arguable#options= are
    # undefined. Thus, there is no ways to access the Gem::OptionParser object
    # via the receiver object.
    #
    def options=(opt)
      unless @optparse = opt
        class << self
          undef_method(:options)
          undef_method(:options=)
        end
      end
    end

    #
    # Actual Gem::OptionParser object, automatically created if nonexistent.
    #
    # If called with a block, yields the Gem::OptionParser object and returns the
    # result of the block. If an Gem::OptionParser::ParseError exception occurs
    # in the block, it is rescued, a error message printed to STDERR and
    # +nil+ returned.
    #
    def options
      @optparse ||= Gem::OptionParser.new
      @optparse.default_argv = self
      block_given? or return @optparse
      begin
        yield @optparse
      rescue ParseError
        @optparse.warn $!
        nil
      end
    end

    #
    # Parses +self+ destructively in order and returns +self+ containing the
    # rest arguments left unparsed.
    #
    def order!(&blk) options.order!(self, &blk) end

    #
    # Parses +self+ destructively in permutation mode and returns +self+
    # containing the rest arguments left unparsed.
    #
    def permute!() options.permute!(self) end

    #
    # Parses +self+ destructively and returns +self+ containing the
    # rest arguments left unparsed.
    #
    def parse!() options.parse!(self) end

    #
    # Substitution of getopts is possible as follows. Also see
    # Gem::OptionParser#getopts.
    #
    #   def getopts(*args)
    #     ($OPT = ARGV.getopts(*args)).each do |opt, val|
    #       eval "$OPT_#{opt.gsub(/[^A-Za-z0-9_]/, '_')} = val"
    #     end
    #   rescue Gem::OptionParser::ParseError
    #   end
    #
    def getopts(*args)
      options.getopts(self, *args)
    end

    #
    # Initializes instance variable.
    #
    def self.extend_object(obj)
      super
      obj.instance_eval {@optparse = nil}
    end
    def initialize(*args)
      super
      @optparse = nil
    end
  end

  #
  # Acceptable argument classes. Now contains DecimalInteger, OctalInteger
  # and DecimalNumeric. See Acceptable argument classes (in source code).
  #
  module Acceptables
    const_set(:DecimalInteger, Gem::OptionParser::DecimalInteger)
    const_set(:OctalInteger, Gem::OptionParser::OctalInteger)
    const_set(:DecimalNumeric, Gem::OptionParser::DecimalNumeric)
  end
end

# ARGV is arguable by Gem::OptionParser
ARGV.extend(Gem::OptionParser::Arguable)
# frozen_string_literal: true
##
#
# Gem::PathSupport facilitates the GEM_HOME and GEM_PATH environment settings
# to the rest of RubyGems.
#
class Gem::PathSupport
  ##
  # The default system path for managing Gems.
  attr_reader :home

  ##
  # Array of paths to search for Gems.
  attr_reader :path

  ##
  # Directory with spec cache
  attr_reader :spec_cache_dir # :nodoc:

  ##
  #
  # Constructor. Takes a single argument which is to be treated like a
  # hashtable, or defaults to ENV, the system environment.
  #
  def initialize(env)
    @home = env["GEM_HOME"] || Gem.default_dir

    if File::ALT_SEPARATOR
      @home = @home.gsub(File::ALT_SEPARATOR, File::SEPARATOR)
    end

    @home = expand(@home)

    @path = split_gem_path env["GEM_PATH"], @home

    @spec_cache_dir = env["GEM_SPEC_CACHE"] || Gem.default_spec_cache_dir

    @spec_cache_dir = @spec_cache_dir.dup.tap(&Gem::UNTAINT)
  end

  private

  ##
  # Split the Gem search path (as reported by Gem.path).

  def split_gem_path(gpaths, home)
    # FIX: it should be [home, *path], not [*path, home]

    gem_path = []

    if gpaths
      gem_path = gpaths.split(Gem.path_separator)
      # Handle the path_separator being set to a regexp, which will cause
      # end_with? to error
      if gpaths =~ /#{Gem.path_separator}\z/
        gem_path += default_path
      end

      if File::ALT_SEPARATOR
        gem_path.map! do |this_path|
          this_path.gsub File::ALT_SEPARATOR, File::SEPARATOR
        end
      end

      gem_path << home
    else
      gem_path = default_path
    end

    gem_path.map {|path| expand(path) }.uniq
  end

  # Return the default Gem path
  def default_path
    gem_path = Gem.default_path + [@home]

    if defined?(APPLE_GEM_HOME)
      gem_path << APPLE_GEM_HOME
    end
    gem_path
  end

  def expand(path)
    if File.directory?(path)
      File.realpath(path)
    else
      path
    end
  end
end
# frozen_string_literal: true
require_relative '../rubygems'
require_relative 'user_interaction'

##
# A default post-install hook that displays "Successfully installed
# some_gem-1.0"

Gem.post_install do |installer|
  ui = Gem::DefaultUserInteraction.ui
  ui.say "Successfully installed #{installer.spec.full_name}"
end
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require_relative 'user_interaction'
require 'rbconfig'

##
# Gem::ConfigFile RubyGems options and gem command options from gemrc.
#
# gemrc is a YAML file that uses strings to match gem command arguments and
# symbols to match RubyGems options.
#
# Gem command arguments use a String key that matches the command name and
# allow you to specify default arguments:
#
#   install: --no-rdoc --no-ri
#   update: --no-rdoc --no-ri
#
# You can use <tt>gem:</tt> to set default arguments for all commands.
#
# RubyGems options use symbol keys.  Valid options are:
#
# +:backtrace+:: See #backtrace
# +:sources+:: Sets Gem::sources
# +:verbose+:: See #verbose
# +:concurrent_downloads+:: See #concurrent_downloads
#
# gemrc files may exist in various locations and are read and merged in
# the following order:
#
# - system wide (/etc/gemrc)
# - per user (~/.gemrc)
# - per environment (gemrc files listed in the GEMRC environment variable)

class Gem::ConfigFile
  include Gem::UserInteraction

  DEFAULT_BACKTRACE = false
  DEFAULT_BULK_THRESHOLD = 1000
  DEFAULT_VERBOSITY = true
  DEFAULT_UPDATE_SOURCES = true
  DEFAULT_CONCURRENT_DOWNLOADS = 8
  DEFAULT_CERT_EXPIRATION_LENGTH_DAYS = 365
  DEFAULT_IPV4_FALLBACK_ENABLED = false

  ##
  # For Ruby packagers to set configuration defaults.  Set in
  # rubygems/defaults/operating_system.rb

  OPERATING_SYSTEM_DEFAULTS = Gem.operating_system_defaults

  ##
  # For Ruby implementers to set configuration defaults.  Set in
  # rubygems/defaults/#{RUBY_ENGINE}.rb

  PLATFORM_DEFAULTS = Gem.platform_defaults

  # :stopdoc:

  SYSTEM_CONFIG_PATH =
    begin
      require "etc"
      Etc.sysconfdir
    rescue LoadError, NoMethodError
      RbConfig::CONFIG["sysconfdir"] || "/etc"
    end

  # :startdoc:

  SYSTEM_WIDE_CONFIG_FILE = File.join SYSTEM_CONFIG_PATH, 'gemrc'

  ##
  # List of arguments supplied to the config file object.

  attr_reader :args

  ##
  # Where to look for gems (deprecated)

  attr_accessor :path

  ##
  # Where to install gems (deprecated)

  attr_accessor :home

  ##
  # True if we print backtraces on errors.

  attr_writer :backtrace

  ##
  # Bulk threshold value.  If the number of missing gems are above this
  # threshold value, then a bulk download technique is used.  (deprecated)

  attr_accessor :bulk_threshold

  ##
  # Verbose level of output:
  # * false -- No output
  # * true -- Normal output
  # * :loud -- Extra output

  attr_accessor :verbose

  ##
  # Number of gem downloads that should be performed concurrently.

  attr_accessor :concurrent_downloads

  ##
  # True if we want to update the SourceInfoCache every time, false otherwise

  attr_accessor :update_sources

  ##
  # True if we want to force specification of gem server when pushing a gem

  attr_accessor :disable_default_gem_server

  # openssl verify mode value, used for remote https connection

  attr_reader :ssl_verify_mode

  ##
  # Path name of directory or file of openssl CA certificate, used for remote
  # https connection

  attr_accessor :ssl_ca_cert

  ##
  # sources to look for gems
  attr_accessor :sources

  ##
  # Expiration length to sign a certificate

  attr_accessor :cert_expiration_length_days

  ##
  # == Experimental ==
  # Fallback to IPv4 when IPv6 is not reachable or slow (default: false)

  attr_accessor :ipv4_fallback_enabled

  ##
  # Path name of directory or file of openssl client certificate, used for remote https connection with client authentication

  attr_reader :ssl_client_cert

  ##
  # Create the config file object.  +args+ is the list of arguments
  # from the command line.
  #
  # The following command line options are handled early here rather
  # than later at the time most command options are processed.
  #
  # <tt>--config-file</tt>, <tt>--config-file==NAME</tt>::
  #   Obviously these need to be handled by the ConfigFile object to ensure we
  #   get the right config file.
  #
  # <tt>--backtrace</tt>::
  #   Backtrace needs to be turned on early so that errors before normal
  #   option parsing can be properly handled.
  #
  # <tt>--debug</tt>::
  #   Enable Ruby level debug messages.  Handled early for the same reason as
  #   --backtrace.
  #--
  # TODO: parse options upstream, pass in options directly

  def initialize(args)
    set_config_file_name(args)

    @backtrace = DEFAULT_BACKTRACE
    @bulk_threshold = DEFAULT_BULK_THRESHOLD
    @verbose = DEFAULT_VERBOSITY
    @update_sources = DEFAULT_UPDATE_SOURCES
    @concurrent_downloads = DEFAULT_CONCURRENT_DOWNLOADS
    @cert_expiration_length_days = DEFAULT_CERT_EXPIRATION_LENGTH_DAYS
    @ipv4_fallback_enabled = ENV['IPV4_FALLBACK_ENABLED'] == 'true' || DEFAULT_IPV4_FALLBACK_ENABLED

    operating_system_config = Marshal.load Marshal.dump(OPERATING_SYSTEM_DEFAULTS)
    platform_config = Marshal.load Marshal.dump(PLATFORM_DEFAULTS)
    system_config = load_file SYSTEM_WIDE_CONFIG_FILE
    user_config = load_file config_file_name.dup.tap(&Gem::UNTAINT)

    environment_config = (ENV['GEMRC'] || '')
      .split(File::PATH_SEPARATOR).inject({}) do |result, file|
        result.merge load_file file
      end

    @hash = operating_system_config.merge platform_config
    unless args.index '--norc'
      @hash = @hash.merge system_config
      @hash = @hash.merge user_config
      @hash = @hash.merge environment_config
    end

    # HACK these override command-line args, which is bad
    @backtrace                   = @hash[:backtrace]                   if @hash.key? :backtrace
    @bulk_threshold              = @hash[:bulk_threshold]              if @hash.key? :bulk_threshold
    @home                        = @hash[:gemhome]                     if @hash.key? :gemhome
    @path                        = @hash[:gempath]                     if @hash.key? :gempath
    @update_sources              = @hash[:update_sources]              if @hash.key? :update_sources
    @verbose                     = @hash[:verbose]                     if @hash.key? :verbose
    @disable_default_gem_server  = @hash[:disable_default_gem_server]  if @hash.key? :disable_default_gem_server
    @sources                     = @hash[:sources]                     if @hash.key? :sources
    @cert_expiration_length_days = @hash[:cert_expiration_length_days] if @hash.key? :cert_expiration_length_days
    @ipv4_fallback_enabled       = @hash[:ipv4_fallback_enabled]       if @hash.key? :ipv4_fallback_enabled

    @ssl_verify_mode  = @hash[:ssl_verify_mode]  if @hash.key? :ssl_verify_mode
    @ssl_ca_cert      = @hash[:ssl_ca_cert]      if @hash.key? :ssl_ca_cert
    @ssl_client_cert  = @hash[:ssl_client_cert]  if @hash.key? :ssl_client_cert

    @api_keys         = nil
    @rubygems_api_key = nil

    handle_arguments args
  end

  ##
  # Hash of RubyGems.org and alternate API keys

  def api_keys
    load_api_keys unless @api_keys

    @api_keys
  end

  ##
  # Checks the permissions of the credentials file.  If they are not 0600 an
  # error message is displayed and RubyGems aborts.

  def check_credentials_permissions
    return if Gem.win_platform? # windows doesn't write 0600 as 0600
    return unless File.exist? credentials_path

    existing_permissions = File.stat(credentials_path).mode & 0777

    return if existing_permissions == 0600

    alert_error <<-ERROR
Your gem push credentials file located at:

\t#{credentials_path}

has file permissions of 0#{existing_permissions.to_s 8} but 0600 is required.

To fix this error run:

\tchmod 0600 #{credentials_path}

You should reset your credentials at:

\thttps://rubygems.org/profile/edit

if you believe they were disclosed to a third party.
    ERROR

    terminate_interaction 1
  end

  ##
  # Location of RubyGems.org credentials

  def credentials_path
    credentials = File.join Gem.user_home, '.gem', 'credentials'
    if File.exist? credentials
      credentials
    else
      File.join Gem.data_home, "gem", "credentials"
    end
  end

  def load_api_keys
    check_credentials_permissions

    @api_keys = if File.exist? credentials_path
                  load_file(credentials_path)
                else
                  @hash
                end

    if @api_keys.key? :rubygems_api_key
      @rubygems_api_key    = @api_keys[:rubygems_api_key]
      @api_keys[:rubygems] = @api_keys.delete :rubygems_api_key unless
        @api_keys.key? :rubygems
    end
  end

  ##
  # Returns the RubyGems.org API key

  def rubygems_api_key
    load_api_keys unless @rubygems_api_key

    @rubygems_api_key
  end

  ##
  # Sets the RubyGems.org API key to +api_key+

  def rubygems_api_key=(api_key)
    set_api_key :rubygems_api_key, api_key

    @rubygems_api_key = api_key
  end

  ##
  # Set a specific host's API key to +api_key+

  def set_api_key(host, api_key)
    check_credentials_permissions

    config = load_file(credentials_path).merge(host => api_key)

    dirname = File.dirname credentials_path
    require 'fileutils'
    FileUtils.mkdir_p(dirname)

    Gem.load_yaml

    permissions = 0600 & (~File.umask)
    File.open(credentials_path, 'w', permissions) do |f|
      f.write config.to_yaml
    end

    load_api_keys # reload
  end

  ##
  # Remove the +~/.gem/credentials+ file to clear all the current sessions.

  def unset_api_key!
    return false unless File.exist?(credentials_path)

    File.delete(credentials_path)
  end

  def load_file(filename)
    Gem.load_yaml

    yaml_errors = [ArgumentError]
    yaml_errors << Psych::SyntaxError if defined?(Psych::SyntaxError)

    return {} unless filename && !filename.empty? && File.exist?(filename)

    begin
      content = Gem::SafeYAML.load(File.read(filename))
      unless content.kind_of? Hash
        warn "Failed to load #{filename} because it doesn't contain valid YAML hash"
        return {}
      end
      return content
    rescue *yaml_errors => e
      warn "Failed to load #{filename}, #{e}"
    rescue Errno::EACCES
      warn "Failed to load #{filename} due to permissions problem."
    end

    {}
  end

  # True if the backtrace option has been specified, or debug is on.
  def backtrace
    @backtrace or $DEBUG
  end

  # The name of the configuration file.
  def config_file_name
    @config_file_name || Gem.config_file
  end

  # Delegates to @hash
  def each(&block)
    hash = @hash.dup
    hash.delete :update_sources
    hash.delete :verbose
    hash.delete :backtrace
    hash.delete :bulk_threshold

    yield :update_sources, @update_sources
    yield :verbose, @verbose
    yield :backtrace, @backtrace
    yield :bulk_threshold, @bulk_threshold

    yield 'config_file_name', @config_file_name if @config_file_name

    hash.each(&block)
  end

  # Handle the command arguments.
  def handle_arguments(arg_list)
    @args = []

    arg_list.each do |arg|
      case arg
      when /^--(backtrace|traceback)$/ then
        @backtrace = true
      when /^--debug$/ then
        $DEBUG = true

        warn 'NOTE:  Debugging mode prints all exceptions even when rescued'
      else
        @args << arg
      end
    end
  end

  # Really verbose mode gives you extra output.
  def really_verbose
    case verbose
    when true, false, nil then
      false
    else
      true
    end
  end

  # to_yaml only overwrites things you can't override on the command line.
  def to_yaml # :nodoc:
    yaml_hash = {}
    yaml_hash[:backtrace] = @hash.fetch(:backtrace, DEFAULT_BACKTRACE)
    yaml_hash[:bulk_threshold] = @hash.fetch(:bulk_threshold, DEFAULT_BULK_THRESHOLD)
    yaml_hash[:sources] = Gem.sources.to_a
    yaml_hash[:update_sources] = @hash.fetch(:update_sources, DEFAULT_UPDATE_SOURCES)
    yaml_hash[:verbose] = @hash.fetch(:verbose, DEFAULT_VERBOSITY)

    yaml_hash[:concurrent_downloads] =
      @hash.fetch(:concurrent_downloads, DEFAULT_CONCURRENT_DOWNLOADS)

    yaml_hash[:ssl_verify_mode] =
      @hash[:ssl_verify_mode] if @hash.key? :ssl_verify_mode

    yaml_hash[:ssl_ca_cert] =
      @hash[:ssl_ca_cert] if @hash.key? :ssl_ca_cert

    yaml_hash[:ssl_client_cert] =
      @hash[:ssl_client_cert] if @hash.key? :ssl_client_cert

    keys = yaml_hash.keys.map {|key| key.to_s }
    keys << 'debug'
    re = Regexp.union(*keys)

    @hash.each do |key, value|
      key = key.to_s
      next if key =~ re
      yaml_hash[key.to_s] = value
    end

    yaml_hash.to_yaml
  end

  # Writes out this config file, replacing its source.
  def write
    require 'fileutils'
    FileUtils.mkdir_p File.dirname(config_file_name)

    File.open config_file_name, 'w' do |io|
      io.write to_yaml
    end
  end

  # Return the configuration information for +key+.
  def [](key)
    @hash[key.to_s]
  end

  # Set configuration option +key+ to +value+.
  def []=(key, value)
    @hash[key.to_s] = value
  end

  def ==(other) # :nodoc:
    self.class === other and
      @backtrace == other.backtrace and
      @bulk_threshold == other.bulk_threshold and
      @verbose == other.verbose and
      @update_sources == other.update_sources and
      @hash == other.hash
  end

  attr_reader :hash
  protected :hash

  private

  def set_config_file_name(args)
    @config_file_name = ENV["GEMRC"]
    need_config_file_name = false

    args.each do |arg|
      if need_config_file_name
        @config_file_name = arg
        need_config_file_name = false
      elsif arg =~ /^--config-file=(.*)/
        @config_file_name = $1
      elsif arg =~ /^--config-file$/
        need_config_file_name = true
      end
    end
  end
end
# frozen_string_literal: true
require_relative '../rubygems'
require_relative 'request'
require_relative 'request/connection_pools'
require_relative 's3_uri_signer'
require_relative 'uri_formatter'
require_relative 'uri'
require_relative 'user_interaction'

##
# RemoteFetcher handles the details of fetching gems and gem information from
# a remote source.

class Gem::RemoteFetcher
  include Gem::UserInteraction

  ##
  # A FetchError exception wraps up the various possible IO and HTTP failures
  # that could happen while downloading from the internet.

  class FetchError < Gem::Exception
    ##
    # The URI which was being accessed when the exception happened.

    attr_accessor :uri, :original_uri

    def initialize(message, uri)
      uri = Gem::Uri.new(uri)

      super uri.redact_credentials_from(message)

      @original_uri = uri.to_s
      @uri = uri.redacted.to_s
    end

    def to_s # :nodoc:
      "#{super} (#{uri})"
    end
  end

  ##
  # A FetchError that indicates that the reason for not being
  # able to fetch data was that the host could not be contacted

  class UnknownHostError < FetchError
  end
  deprecate_constant(:UnknownHostError)

  @fetcher = nil

  ##
  # Cached RemoteFetcher instance.

  def self.fetcher
    @fetcher ||= self.new Gem.configuration[:http_proxy]
  end

  attr_accessor :headers

  ##
  # Initialize a remote fetcher using the source URI and possible proxy
  # information.
  #
  # +proxy+
  # * [String]: explicit specification of proxy; overrides any environment
  #             variable setting
  # * nil: respect environment variables (HTTP_PROXY, HTTP_PROXY_USER,
  #        HTTP_PROXY_PASS)
  # * <tt>:no_proxy</tt>: ignore environment variables and _don't_ use a proxy
  #
  # +headers+: A set of additional HTTP headers to be sent to the server when
  #            fetching the gem.

  def initialize(proxy=nil, dns=nil, headers={})
    require_relative 'core_ext/tcpsocket_init' if Gem.configuration.ipv4_fallback_enabled
    require 'net/http'
    require 'stringio'
    require 'uri'

    Socket.do_not_reverse_lookup = true

    @proxy = proxy
    @pools = {}
    @pool_lock = Thread::Mutex.new
    @cert_files = Gem::Request.get_cert_files

    @headers = headers
  end

  ##
  # Given a name and requirement, downloads this gem into cache and returns the
  # filename. Returns nil if the gem cannot be located.
  #--
  # Should probably be integrated with #download below, but that will be a
  # larger, more encompassing effort. -erikh

  def download_to_cache(dependency)
    found, _ = Gem::SpecFetcher.fetcher.spec_for_dependency dependency

    return if found.empty?

    spec, source = found.max_by {|(s,_)| s.version }

    download spec, source.uri
  end

  ##
  # Moves the gem +spec+ from +source_uri+ to the cache dir unless it is
  # already there.  If the source_uri is local the gem cache dir copy is
  # always replaced.

  def download(spec, source_uri, install_dir = Gem.dir)
    install_cache_dir = File.join install_dir, "cache"
    cache_dir =
      if Dir.pwd == install_dir # see fetch_command
        install_dir
      elsif File.writable?(install_cache_dir) || (File.writable?(install_dir) && (not File.exist?(install_cache_dir)))
        install_cache_dir
      else
        File.join Gem.user_dir, "cache"
      end

    gem_file_name = File.basename spec.cache_file
    local_gem_path = File.join cache_dir, gem_file_name

    require "fileutils"
    FileUtils.mkdir_p cache_dir rescue nil unless File.exist? cache_dir

    source_uri = Gem::Uri.new(source_uri)

    scheme = source_uri.scheme

    # URI.parse gets confused by MS Windows paths with forward slashes.
    scheme = nil if scheme =~ /^[a-z]$/i

    # REFACTOR: split this up and dispatch on scheme (eg download_http)
    # REFACTOR: be sure to clean up fake fetcher when you do this... cleaner
    case scheme
    when 'http', 'https', 's3' then
      unless File.exist? local_gem_path
        begin
          verbose "Downloading gem #{gem_file_name}"

          remote_gem_path = source_uri + "gems/#{gem_file_name}"

          self.cache_update_path remote_gem_path, local_gem_path
        rescue FetchError
          raise if spec.original_platform == spec.platform

          alternate_name = "#{spec.original_name}.gem"

          verbose "Failed, downloading gem #{alternate_name}"

          remote_gem_path = source_uri + "gems/#{alternate_name}"

          self.cache_update_path remote_gem_path, local_gem_path
        end
      end
    when 'file' then
      begin
        path = source_uri.path
        path = File.dirname(path) if File.extname(path) == '.gem'

        remote_gem_path = Gem::Util.correct_for_windows_path(File.join(path, 'gems', gem_file_name))

        FileUtils.cp(remote_gem_path, local_gem_path)
      rescue Errno::EACCES
        local_gem_path = source_uri.to_s
      end

      verbose "Using local gem #{local_gem_path}"
    when nil then # TODO test for local overriding cache
      source_path = if Gem.win_platform? && source_uri.scheme &&
                       !source_uri.path.include?(':')
                      "#{source_uri.scheme}:#{source_uri.path}"
                    else
                      source_uri.path
                    end

      source_path = Gem::UriFormatter.new(source_path).unescape

      begin
        FileUtils.cp source_path, local_gem_path unless
          File.identical?(source_path, local_gem_path)
      rescue Errno::EACCES
        local_gem_path = source_uri.to_s
      end

      verbose "Using local gem #{local_gem_path}"
    else
      raise ArgumentError, "unsupported URI scheme #{source_uri.scheme}"
    end

    local_gem_path
  end

  ##
  # File Fetcher. Dispatched by +fetch_path+. Use it instead.

  def fetch_file(uri, *_)
    Gem.read_binary Gem::Util.correct_for_windows_path uri.path
  end

  ##
  # HTTP Fetcher. Dispatched by +fetch_path+. Use it instead.

  def fetch_http(uri, last_modified = nil, head = false, depth = 0)
    fetch_type = head ? Net::HTTP::Head : Net::HTTP::Get
    response   = request uri, fetch_type, last_modified do |req|
      headers.each {|k,v| req.add_field(k,v) }
    end

    case response
    when Net::HTTPOK, Net::HTTPNotModified then
      response.uri = uri
      head ? response : response.body
    when Net::HTTPMovedPermanently, Net::HTTPFound, Net::HTTPSeeOther,
         Net::HTTPTemporaryRedirect then
      raise FetchError.new('too many redirects', uri) if depth > 10

      unless location = response['Location']
        raise FetchError.new("redirecting but no redirect location was given", uri)
      end
      location = Gem::Uri.new location

      if https?(uri) && !https?(location)
        raise FetchError.new("redirecting to non-https resource: #{location}", uri)
      end

      fetch_http(location, last_modified, head, depth + 1)
    else
      raise FetchError.new("bad response #{response.message} #{response.code}", uri)
    end
  end

  alias :fetch_https :fetch_http

  ##
  # Downloads +uri+ and returns it as a String.

  def fetch_path(uri, mtime = nil, head = false)
    uri = Gem::Uri.new uri

    unless uri.scheme
      raise ArgumentError, "uri scheme is invalid: #{uri.scheme.inspect}"
    end

    data = send "fetch_#{uri.scheme}", uri, mtime, head

    if data and !head and uri.to_s.end_with?(".gz")
      begin
        data = Gem::Util.gunzip data
      rescue Zlib::GzipFile::Error
        raise FetchError.new("server did not return a valid file", uri)
      end
    end

    data
  rescue Timeout::Error, IOError, SocketError, SystemCallError,
         *(OpenSSL::SSL::SSLError if Gem::HAVE_OPENSSL) => e
    raise FetchError.new("#{e.class}: #{e}", uri)
  end

  def fetch_s3(uri, mtime = nil, head = false)
    begin
      public_uri = s3_uri_signer(uri).sign
    rescue Gem::S3URISigner::ConfigurationError, Gem::S3URISigner::InstanceProfileError => e
      raise FetchError.new(e.message, "s3://#{uri.host}")
    end
    fetch_https public_uri, mtime, head
  end

  # we have our own signing code here to avoid a dependency on the aws-sdk gem
  def s3_uri_signer(uri)
    Gem::S3URISigner.new(uri)
  end

  ##
  # Downloads +uri+ to +path+ if necessary. If no path is given, it just
  # passes the data.

  def cache_update_path(uri, path = nil, update = true)
    mtime = path && File.stat(path).mtime rescue nil

    data = fetch_path(uri, mtime)

    if data == nil # indicates the server returned 304 Not Modified
      return Gem.read_binary(path)
    end

    if update and path
      Gem.write_binary(path, data)
    end

    data
  end

  ##
  # Performs a Net::HTTP request of type +request_class+ on +uri+ returning
  # a Net::HTTP response object.  request maintains a table of persistent
  # connections to reduce connect overhead.

  def request(uri, request_class, last_modified = nil)
    proxy = proxy_for @proxy, uri
    pool  = pools_for(proxy).pool_for uri

    request = Gem::Request.new uri, request_class, last_modified, pool

    request.fetch do |req|
      yield req if block_given?
    end
  end

  def https?(uri)
    uri.scheme.downcase == 'https'
  end

  def close_all
    @pools.each_value {|pool| pool.close_all }
  end

  private

  def proxy_for(proxy, uri)
    Gem::Request.proxy_uri(proxy || Gem::Request.get_proxy_from_env(uri.scheme))
  end

  def pools_for(proxy)
    @pool_lock.synchronize do
      @pools[proxy] ||= Gem::Request::ConnectionPools.new proxy, @cert_files
    end
  end
end
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require_relative 'deprecate'
require_relative 'text'

##
# Module that defines the default UserInteraction.  Any class including this
# module will have access to the +ui+ method that returns the default UI.

module Gem::DefaultUserInteraction

  include Gem::Text

  ##
  # The default UI is a class variable of the singleton class for this
  # module.

  @ui = nil

  ##
  # Return the default UI.

  def self.ui
    @ui ||= Gem::ConsoleUI.new
  end

  ##
  # Set the default UI.  If the default UI is never explicitly set, a simple
  # console based UserInteraction will be used automatically.

  def self.ui=(new_ui)
    @ui = new_ui
  end

  ##
  # Use +new_ui+ for the duration of +block+.

  def self.use_ui(new_ui)
    old_ui = @ui
    @ui = new_ui
    yield
  ensure
    @ui = old_ui
  end

  ##
  # See DefaultUserInteraction::ui

  def ui
    Gem::DefaultUserInteraction.ui
  end

  ##
  # See DefaultUserInteraction::ui=

  def ui=(new_ui)
    Gem::DefaultUserInteraction.ui = new_ui
  end

  ##
  # See DefaultUserInteraction::use_ui

  def use_ui(new_ui, &block)
    Gem::DefaultUserInteraction.use_ui(new_ui, &block)
  end

end

##
# UserInteraction allows RubyGems to interact with the user through standard
# methods that can be replaced with more-specific UI methods for different
# displays.
#
# Since UserInteraction dispatches to a concrete UI class you may need to
# reference other classes for specific behavior such as Gem::ConsoleUI or
# Gem::SilentUI.
#
# Example:
#
#   class X
#     include Gem::UserInteraction
#
#     def get_answer
#       n = ask("What is the meaning of life?")
#     end
#   end

module Gem::UserInteraction

  include Gem::DefaultUserInteraction

  ##
  # Displays an alert +statement+.  Asks a +question+ if given.

  def alert(statement, question = nil)
    ui.alert statement, question
  end

  ##
  # Displays an error +statement+ to the error output location.  Asks a
  # +question+ if given.

  def alert_error(statement, question = nil)
    ui.alert_error statement, question
  end

  ##
  # Displays a warning +statement+ to the warning output location.  Asks a
  # +question+ if given.

  def alert_warning(statement, question = nil)
    ui.alert_warning statement, question
  end

  ##
  # Asks a +question+ and returns the answer.

  def ask(question)
    ui.ask question
  end

  ##
  # Asks for a password with a +prompt+

  def ask_for_password(prompt)
    ui.ask_for_password prompt
  end

  ##
  # Asks a yes or no +question+.  Returns true for yes, false for no.

  def ask_yes_no(question, default = nil)
    ui.ask_yes_no question, default
  end

  ##
  # Asks the user to answer +question+ with an answer from the given +list+.

  def choose_from_list(question, list)
    ui.choose_from_list question, list
  end

  ##
  # Displays the given +statement+ on the standard output (or equivalent).

  def say(statement = '')
    ui.say statement
  end

  ##
  # Terminates the RubyGems process with the given +exit_code+

  def terminate_interaction(exit_code = 0)
    ui.terminate_interaction exit_code
  end

  ##
  # Calls +say+ with +msg+ or the results of the block if really_verbose
  # is true.

  def verbose(msg = nil)
    say(clean_text(msg || yield)) if Gem.configuration.really_verbose
  end
end

##
# Gem::StreamUI implements a simple stream based user interface.

class Gem::StreamUI
  extend Gem::Deprecate

  ##
  # The input stream

  attr_reader :ins

  ##
  # The output stream

  attr_reader :outs

  ##
  # The error stream

  attr_reader :errs

  ##
  # Creates a new StreamUI wrapping +in_stream+ for user input, +out_stream+
  # for standard output, +err_stream+ for error output.  If +usetty+ is true
  # then special operations (like asking for passwords) will use the TTY
  # commands to disable character echo.

  def initialize(in_stream, out_stream, err_stream=STDERR, usetty=true)
    @ins = in_stream
    @outs = out_stream
    @errs = err_stream
    @usetty = usetty
  end

  ##
  # Returns true if TTY methods should be used on this StreamUI.

  def tty?
    @usetty && @ins.tty?
  end

  ##
  # Prints a formatted backtrace to the errors stream if backtraces are
  # enabled.

  def backtrace(exception)
    return unless Gem.configuration.backtrace

    @errs.puts "\t#{exception.backtrace.join "\n\t"}"
  end

  ##
  # Choose from a list of options.  +question+ is a prompt displayed above
  # the list.  +list+ is a list of option strings.  Returns the pair
  # [option_name, option_index].

  def choose_from_list(question, list)
    @outs.puts question

    list.each_with_index do |item, index|
      @outs.puts " #{index + 1}. #{item}"
    end

    @outs.print "> "
    @outs.flush

    result = @ins.gets

    return nil, nil unless result

    result = result.strip.to_i - 1
    return list[result], result
  end

  ##
  # Ask a question.  Returns a true for yes, false for no.  If not connected
  # to a tty, raises an exception if default is nil, otherwise returns
  # default.

  def ask_yes_no(question, default=nil)
    unless tty?
      if default.nil?
        raise Gem::OperationNotSupportedError,
              "Not connected to a tty and no default specified"
      else
        return default
      end
    end

    default_answer = case default
                     when nil
                       'yn'
                     when true
                       'Yn'
                     else
                       'yN'
                     end

    result = nil

    while result.nil? do
      result = case ask "#{question} [#{default_answer}]"
               when /^y/i then true
               when /^n/i then false
               when /^$/  then default
               else            nil
               end
    end

    return result
  end

  ##
  # Ask a question.  Returns an answer if connected to a tty, nil otherwise.

  def ask(question)
    return nil if not tty?

    @outs.print(question + "  ")
    @outs.flush

    result = @ins.gets
    result.chomp! if result
    result
  end

  ##
  # Ask for a password. Does not echo response to terminal.

  def ask_for_password(question)
    return nil if not tty?

    @outs.print(question, "  ")
    @outs.flush

    password = _gets_noecho
    @outs.puts
    password.chomp! if password
    password
  end

  def require_io_console
    @require_io_console ||= begin
      begin
        require 'io/console'
      rescue LoadError
      end
      true
    end
  end

  def _gets_noecho
    require_io_console
    @ins.noecho { @ins.gets }
  end

  ##
  # Display a statement.

  def say(statement="")
    @outs.puts statement
  end

  ##
  # Display an informational alert.  Will ask +question+ if it is not nil.

  def alert(statement, question=nil)
    @outs.puts "INFO:  #{statement}"
    ask(question) if question
  end

  ##
  # Display a warning on stderr.  Will ask +question+ if it is not nil.

  def alert_warning(statement, question=nil)
    @errs.puts "WARNING:  #{statement}"
    ask(question) if question
  end

  ##
  # Display an error message in a location expected to get error messages.
  # Will ask +question+ if it is not nil.

  def alert_error(statement, question=nil)
    @errs.puts "ERROR:  #{statement}"
    ask(question) if question
  end

  ##
  # Terminate the application with exit code +status+, running any exit
  # handlers that might have been defined.

  def terminate_interaction(status = 0)
    close
    raise Gem::SystemExitException, status
  end

  def close
  end

  ##
  # Return a progress reporter object chosen from the current verbosity.

  def progress_reporter(*args)
    case Gem.configuration.verbose
    when nil, false
      SilentProgressReporter.new(@outs, *args)
    when true
      SimpleProgressReporter.new(@outs, *args)
    else
      VerboseProgressReporter.new(@outs, *args)
    end
  end

  ##
  # An absolutely silent progress reporter.

  class SilentProgressReporter
    ##
    # The count of items is never updated for the silent progress reporter.

    attr_reader :count

    ##
    # Creates a silent progress reporter that ignores all input arguments.

    def initialize(out_stream, size, initial_message, terminal_message = nil)
    end

    ##
    # Does not print +message+ when updated as this object has taken a vow of
    # silence.

    def updated(message)
    end

    ##
    # Does not print anything when complete as this object has taken a vow of
    # silence.

    def done
    end
  end

  ##
  # A basic dotted progress reporter.

  class SimpleProgressReporter
    include Gem::DefaultUserInteraction

    ##
    # The number of progress items counted so far.

    attr_reader :count

    ##
    # Creates a new progress reporter that will write to +out_stream+ for
    # +size+ items.  Shows the given +initial_message+ when progress starts
    # and the +terminal_message+ when it is complete.

    def initialize(out_stream, size, initial_message,
                   terminal_message = "complete")
      @out = out_stream
      @total = size
      @count = 0
      @terminal_message = terminal_message

      @out.puts initial_message
    end

    ##
    # Prints out a dot and ignores +message+.

    def updated(message)
      @count += 1
      @out.print "."
      @out.flush
    end

    ##
    # Prints out the terminal message.

    def done
      @out.puts "\n#{@terminal_message}"
    end
  end

  ##
  # A progress reporter that prints out messages about the current progress.

  class VerboseProgressReporter
    include Gem::DefaultUserInteraction

    ##
    # The number of progress items counted so far.

    attr_reader :count

    ##
    # Creates a new progress reporter that will write to +out_stream+ for
    # +size+ items.  Shows the given +initial_message+ when progress starts
    # and the +terminal_message+ when it is complete.

    def initialize(out_stream, size, initial_message,
                   terminal_message = 'complete')
      @out = out_stream
      @total = size
      @count = 0
      @terminal_message = terminal_message

      @out.puts initial_message
    end

    ##
    # Prints out the position relative to the total and the +message+.

    def updated(message)
      @count += 1
      @out.puts "#{@count}/#{@total}: #{message}"
    end

    ##
    # Prints out the terminal message.

    def done
      @out.puts @terminal_message
    end
  end

  ##
  # Return a download reporter object chosen from the current verbosity

  def download_reporter(*args)
    if [nil, false].include?(Gem.configuration.verbose) || !@outs.tty?
      SilentDownloadReporter.new(@outs, *args)
    else
      ThreadedDownloadReporter.new(@outs, *args)
    end
  end

  ##
  # An absolutely silent download reporter.

  class SilentDownloadReporter
    ##
    # The silent download reporter ignores all arguments

    def initialize(out_stream, *args)
    end

    ##
    # The silent download reporter does not display +filename+ or care about
    # +filesize+ because it is silent.

    def fetch(filename, filesize)
    end

    ##
    # Nothing can update the silent download reporter.

    def update(current)
    end

    ##
    # The silent download reporter won't tell you when the download is done.
    # Because it is silent.

    def done
    end
  end

  ##
  # A progress reporter that behaves nicely with threaded downloading.

  class ThreadedDownloadReporter
    MUTEX = Thread::Mutex.new

    ##
    # The current file name being displayed

    attr_reader :file_name

    ##
    # Creates a new threaded download reporter that will display on
    # +out_stream+.  The other arguments are ignored.

    def initialize(out_stream, *args)
      @file_name = nil
      @out = out_stream
    end

    ##
    # Tells the download reporter that the +file_name+ is being fetched.
    # The other arguments are ignored.

    def fetch(file_name, *args)
      if @file_name.nil?
        @file_name = file_name
        locked_puts "Fetching #{@file_name}"
      end
    end

    ##
    # Updates the threaded download reporter for the given number of +bytes+.

    def update(bytes)
      # Do nothing.
    end

    ##
    # Indicates the download is complete.

    def done
      # Do nothing.
    end

    private

    def locked_puts(message)
      MUTEX.synchronize do
        @out.puts message
      end
    end
  end
end

##
# Subclass of StreamUI that instantiates the user interaction using STDIN,
# STDOUT, and STDERR.

class Gem::ConsoleUI < Gem::StreamUI
  ##
  # The Console UI has no arguments as it defaults to reading input from
  # stdin, output to stdout and warnings or errors to stderr.

  def initialize
    super STDIN, STDOUT, STDERR, true
  end
end

##
# SilentUI is a UI choice that is absolutely silent.

class Gem::SilentUI < Gem::StreamUI
  ##
  # The SilentUI has no arguments as it does not use any stream.

  def initialize
    reader, writer = nil, nil

    reader = File.open(IO::NULL, 'r')
    writer = File.open(IO::NULL, 'w')

    super reader, writer, writer, false
  end

  def close
    super
    @ins.close
    @outs.close
  end

  def download_reporter(*args) # :nodoc:
    SilentDownloadReporter.new(@outs, *args)
  end

  def progress_reporter(*args) # :nodoc:
    SilentProgressReporter.new(@outs, *args)
  end
end
# frozen_string_literal: true
require_relative 'user_interaction'

##
# This Gem::StreamUI subclass records input and output to StringIO for
# retrieval during tests.

class Gem::MockGemUi < Gem::StreamUI
  ##
  # Raised when you haven't provided enough input to your MockGemUi

  class InputEOFError < RuntimeError
    def initialize(question)
      super "Out of input for MockGemUi on #{question.inspect}"
    end
  end

  class TermError < RuntimeError
    attr_reader :exit_code

    def initialize(exit_code)
      super
      @exit_code = exit_code
    end
  end
  class SystemExitException < RuntimeError; end

  module TTY

    attr_accessor :tty

    def tty?()
      @tty = true unless defined?(@tty)
      @tty
    end

    def noecho
      yield self
    end
  end

  def initialize(input = "")
    require 'stringio'
    ins = StringIO.new input
    outs = StringIO.new
    errs = StringIO.new

    ins.extend TTY
    outs.extend TTY
    errs.extend TTY

    super ins, outs, errs, true

    @terminated = false
  end

  def ask(question)
    raise InputEOFError, question if @ins.eof?

    super
  end

  def input
    @ins.string
  end

  def output
    @outs.string
  end

  def error
    @errs.string
  end

  def terminated?
    @terminated
  end

  def terminate_interaction(status=0)
    @terminated = true

    raise TermError, status if status != 0
    raise SystemExitException
  end
end
# frozen_string_literal: true

##
# A collection of text-wrangling methods

module Gem::Text

  ##
  # Remove any non-printable characters and make the text suitable for
  # printing.
  def clean_text(text)
    text.gsub(/[\000-\b\v-\f\016-\037\177]/, ".".freeze)
  end

  def truncate_text(text, description, max_length = 100_000)
    raise ArgumentError, "max_length must be positive" unless max_length > 0
    return text if text.size <= max_length
    "Truncating #{description} to #{max_length.to_s.reverse.gsub(/...(?=.)/,'\&,').reverse} characters:\n" + text[0, max_length]
  end

  ##
  # Wraps +text+ to +wrap+ characters and optionally indents by +indent+
  # characters

  def format_text(text, wrap, indent=0)
    result = []
    work = clean_text(text)

    while work.length > wrap do
      if work =~ /^(.{0,#{wrap}})[ \n]/
        result << $1.rstrip
        work.slice!(0, $&.length)
      else
        result << work.slice!(0, wrap)
      end
    end

    result << work if work.length.nonzero?
    result.join("\n").gsub(/^/, " " * indent)
  end

  def min3(a, b, c) # :nodoc:
    if a < b && a < c
      a
    elsif b < c
      b
    else
      c
    end
  end

  # This code is based directly on the Text gem implementation
  # Returns a value representing the "cost" of transforming str1 into str2
  def levenshtein_distance(str1, str2)
    s = str1
    t = str2
    n = s.length
    m = t.length

    return m if (0 == n)
    return n if (0 == m)

    d = (0..m).to_a
    x = nil

    str1.each_char.each_with_index do |char1,i|
      e = i + 1

      str2.each_char.each_with_index do |char2,j|
        cost = (char1 == char2) ? 0 : 1
        x = min3(
             d[j + 1] + 1, # insertion
             e + 1,      # deletion
             d[j] + cost # substitution
           )
        d[j] = e
        e = x
      end

      d[m] = x
    end

    return x
  end
end
# frozen_string_literal: true
require_relative '../rubygems'

begin
  require 'rdoc/rubygems_hook'
  module Gem
    RDoc = ::RDoc::RubygemsHook
  end

  Gem.done_installing(&Gem::RDoc.method(:generation_hook))
rescue LoadError
end
# frozen_string_literal: true
#--
# Copyright (C) 2004 Mauricio Julio Fernández Pradier
# See LICENSE.txt for additional licensing information.
#++
#
# Example using a Gem::Package
#
# Builds a .gem file given a Gem::Specification. A .gem file is a tarball
# which contains a data.tar.gz, metadata.gz, checksums.yaml.gz and possibly
# signatures.
#
#   require 'rubygems'
#   require 'rubygems/package'
#
#   spec = Gem::Specification.new do |s|
#     s.summary = "Ruby based make-like utility."
#     s.name = 'rake'
#     s.version = PKG_VERSION
#     s.requirements << 'none'
#     s.files = PKG_FILES
#     s.description = <<-EOF
#   Rake is a Make-like program implemented in Ruby. Tasks
#   and dependencies are specified in standard Ruby syntax.
#     EOF
#   end
#
#   Gem::Package.build spec
#
# Reads a .gem file.
#
#   require 'rubygems'
#   require 'rubygems/package'
#
#   the_gem = Gem::Package.new(path_to_dot_gem)
#   the_gem.contents # get the files in the gem
#   the_gem.extract_files destination_directory # extract the gem into a directory
#   the_gem.spec # get the spec out of the gem
#   the_gem.verify # check the gem is OK (contains valid gem specification, contains a not corrupt contents archive)
#
# #files are the files in the .gem tar file, not the Ruby files in the gem
# #extract_files and #contents automatically call #verify

require_relative "../rubygems"
require_relative 'security'
require_relative 'user_interaction'

class Gem::Package
  include Gem::UserInteraction

  class Error < Gem::Exception; end

  class FormatError < Error
    attr_reader :path

    def initialize(message, source = nil)
      if source
        @path = source.path

        message = message + " in #{path}" if path
      end

      super message
    end
  end

  class PathError < Error
    def initialize(destination, destination_dir)
      super "installing into parent path %s of %s is not allowed" %
              [destination, destination_dir]
    end
  end

  class SymlinkError < Error
    def initialize(name, destination, destination_dir)
      super "installing symlink '%s' pointing to parent path %s of %s is not allowed" %
              [name, destination, destination_dir]
    end
  end

  class NonSeekableIO < Error; end

  class TooLongFileName < Error; end

  ##
  # Raised when a tar file is corrupt

  class TarInvalidError < Error; end

  attr_accessor :build_time # :nodoc:

  ##
  # Checksums for the contents of the package

  attr_reader :checksums

  ##
  # The files in this package.  This is not the contents of the gem, just the
  # files in the top-level container.

  attr_reader :files

  ##
  # Reference to the gem being packaged.

  attr_reader :gem

  ##
  # The security policy used for verifying the contents of this package.

  attr_accessor :security_policy

  ##
  # Sets the Gem::Specification to use to build this package.

  attr_writer :spec

  ##
  # Permission for directories
  attr_accessor :dir_mode

  ##
  # Permission for program files
  attr_accessor :prog_mode

  ##
  # Permission for other files
  attr_accessor :data_mode

  def self.build(spec, skip_validation = false, strict_validation = false, file_name = nil)
    gem_file = file_name || spec.file_name

    package = new gem_file
    package.spec = spec
    package.build skip_validation, strict_validation

    gem_file
  end

  ##
  # Creates a new Gem::Package for the file at +gem+. +gem+ can also be
  # provided as an IO object.
  #
  # If +gem+ is an existing file in the old format a Gem::Package::Old will be
  # returned.

  def self.new(gem, security_policy = nil)
    gem = if gem.is_a?(Gem::Package::Source)
            gem
          elsif gem.respond_to? :read
            Gem::Package::IOSource.new gem
          else
            Gem::Package::FileSource.new gem
          end

    return super unless Gem::Package == self
    return super unless gem.present?

    return super unless gem.start
    return super unless gem.start.include? 'MD5SUM ='

    Gem::Package::Old.new gem
  end

  ##
  # Extracts the Gem::Specification and raw metadata from the .gem file at
  # +path+.
  #--

  def self.raw_spec(path, security_policy = nil)
    format = new(path, security_policy)
    spec = format.spec

    metadata = nil

    File.open path, Gem.binary_mode do |io|
      tar = Gem::Package::TarReader.new io
      tar.each_entry do |entry|
        case entry.full_name
        when 'metadata' then
          metadata = entry.read
        when 'metadata.gz' then
          metadata = Gem::Util.gunzip entry.read
        end
      end
    end

    return spec, metadata
  end

  ##
  # Creates a new package that will read or write to the file +gem+.

  def initialize(gem, security_policy) # :notnew:
    require 'zlib'

    @gem = gem

    @build_time      = Gem.source_date_epoch
    @checksums       = {}
    @contents        = nil
    @digests         = Hash.new {|h, algorithm| h[algorithm] = {} }
    @files           = nil
    @security_policy = security_policy
    @signatures      = {}
    @signer          = nil
    @spec            = nil
  end

  ##
  # Copies this package to +path+ (if possible)

  def copy_to(path)
    FileUtils.cp @gem.path, path unless File.exist? path
  end

  ##
  # Adds a checksum for each entry in the gem to checksums.yaml.gz.

  def add_checksums(tar)
    Gem.load_yaml

    checksums_by_algorithm = Hash.new {|h, algorithm| h[algorithm] = {} }

    @checksums.each do |name, digests|
      digests.each do |algorithm, digest|
        checksums_by_algorithm[algorithm][name] = digest.hexdigest
      end
    end

    tar.add_file_signed 'checksums.yaml.gz', 0444, @signer do |io|
      gzip_to io do |gz_io|
        YAML.dump checksums_by_algorithm, gz_io
      end
    end
  end

  ##
  # Adds the files listed in the packages's Gem::Specification to data.tar.gz
  # and adds this file to the +tar+.

  def add_contents(tar) # :nodoc:
    digests = tar.add_file_signed 'data.tar.gz', 0444, @signer do |io|
      gzip_to io do |gz_io|
        Gem::Package::TarWriter.new gz_io do |data_tar|
          add_files data_tar
        end
      end
    end

    @checksums['data.tar.gz'] = digests
  end

  ##
  # Adds files included the package's Gem::Specification to the +tar+ file

  def add_files(tar) # :nodoc:
    @spec.files.each do |file|
      stat = File.lstat file

      if stat.symlink?
        tar.add_symlink file, File.readlink(file), stat.mode
      end

      next unless stat.file?

      tar.add_file_simple file, stat.mode, stat.size do |dst_io|
        File.open file, 'rb' do |src_io|
          dst_io.write src_io.read 16384 until src_io.eof?
        end
      end
    end
  end

  ##
  # Adds the package's Gem::Specification to the +tar+ file

  def add_metadata(tar) # :nodoc:
    digests = tar.add_file_signed 'metadata.gz', 0444, @signer do |io|
      gzip_to io do |gz_io|
        gz_io.write @spec.to_yaml
      end
    end

    @checksums['metadata.gz'] = digests
  end

  ##
  # Builds this package based on the specification set by #spec=

  def build(skip_validation = false, strict_validation = false)
    raise ArgumentError, "skip_validation = true and strict_validation = true are incompatible" if skip_validation && strict_validation

    Gem.load_yaml

    @spec.mark_version
    @spec.validate true, strict_validation unless skip_validation

    setup_signer(
      signer_options: {
        expiration_length_days: Gem.configuration.cert_expiration_length_days,
      }
    )

    @gem.with_write_io do |gem_io|
      Gem::Package::TarWriter.new gem_io do |gem|
        add_metadata gem
        add_contents gem
        add_checksums gem
      end
    end

    say <<-EOM
  Successfully built RubyGem
  Name: #{@spec.name}
  Version: #{@spec.version}
  File: #{File.basename @gem.path}
EOM
  ensure
    @signer = nil
  end

  ##
  # A list of file names contained in this gem

  def contents
    return @contents if @contents

    verify unless @spec

    @contents = []

    @gem.with_read_io do |io|
      gem_tar = Gem::Package::TarReader.new io

      gem_tar.each do |entry|
        next unless entry.full_name == 'data.tar.gz'

        open_tar_gz entry do |pkg_tar|
          pkg_tar.each do |contents_entry|
            @contents << contents_entry.full_name
          end
        end

        return @contents
      end
    end
  end

  ##
  # Creates a digest of the TarEntry +entry+ from the digest algorithm set by
  # the security policy.

  def digest(entry) # :nodoc:
    algorithms = if @checksums
                   @checksums.keys
                 else
                   [Gem::Security::DIGEST_NAME].compact
                 end

    algorithms.each do |algorithm|
      digester = Gem::Security.create_digest(algorithm)

      digester << entry.read(16384) until entry.eof?

      entry.rewind

      @digests[algorithm][entry.full_name] = digester
    end

    @digests
  end

  ##
  # Extracts the files in this package into +destination_dir+
  #
  # If +pattern+ is specified, only entries matching that glob will be
  # extracted.

  def extract_files(destination_dir, pattern = "*")
    verify unless @spec

    FileUtils.mkdir_p destination_dir, :mode => dir_mode && 0755

    @gem.with_read_io do |io|
      reader = Gem::Package::TarReader.new io

      reader.each do |entry|
        next unless entry.full_name == 'data.tar.gz'

        extract_tar_gz entry, destination_dir, pattern

        return # ignore further entries
      end
    end
  end

  ##
  # Extracts all the files in the gzipped tar archive +io+ into
  # +destination_dir+.
  #
  # If an entry in the archive contains a relative path above
  # +destination_dir+ or an absolute path is encountered an exception is
  # raised.
  #
  # If +pattern+ is specified, only entries matching that glob will be
  # extracted.

  def extract_tar_gz(io, destination_dir, pattern = "*") # :nodoc:
    directories = []
    open_tar_gz io do |tar|
      tar.each do |entry|
        next unless File.fnmatch pattern, entry.full_name, File::FNM_DOTMATCH

        destination = install_location entry.full_name, destination_dir

        if entry.symlink?
          link_target = entry.header.linkname
          real_destination = link_target.start_with?("/") ? link_target : File.expand_path(link_target, File.dirname(destination))

          raise Gem::Package::SymlinkError.new(entry.full_name, real_destination, destination_dir) unless
            normalize_path(real_destination).start_with? normalize_path(destination_dir + '/')
        end

        FileUtils.rm_rf destination

        mkdir_options = {}
        mkdir_options[:mode] = dir_mode ? 0755 : (entry.header.mode if entry.directory?)
        mkdir =
          if entry.directory?
            destination
          else
            File.dirname destination
          end

        unless directories.include?(mkdir)
          FileUtils.mkdir_p mkdir, **mkdir_options
          directories << mkdir
        end

        File.open destination, 'wb' do |out|
          out.write entry.read
          FileUtils.chmod file_mode(entry.header.mode), destination
        end if entry.file?

        File.symlink(entry.header.linkname, destination) if entry.symlink?

        verbose destination
      end
    end

    if dir_mode
      File.chmod(dir_mode, *directories)
    end
  end

  def file_mode(mode) # :nodoc:
    ((mode & 0111).zero? ? data_mode : prog_mode) || mode
  end

  ##
  # Gzips content written to +gz_io+ to +io+.
  #--
  # Also sets the gzip modification time to the package build time to ease
  # testing.

  def gzip_to(io) # :yields: gz_io
    gz_io = Zlib::GzipWriter.new io, Zlib::BEST_COMPRESSION
    gz_io.mtime = @build_time

    yield gz_io
  ensure
    gz_io.close
  end

  ##
  # Returns the full path for installing +filename+.
  #
  # If +filename+ is not inside +destination_dir+ an exception is raised.

  def install_location(filename, destination_dir) # :nodoc:
    raise Gem::Package::PathError.new(filename, destination_dir) if
      filename.start_with? '/'

    destination_dir = File.realpath(destination_dir)
    destination = File.expand_path(filename, destination_dir)

    raise Gem::Package::PathError.new(destination, destination_dir) unless
      normalize_path(destination).start_with? normalize_path(destination_dir + '/')

    destination.tap(&Gem::UNTAINT)
    destination
  end

  def normalize_path(pathname)
    if Gem.win_platform?
      pathname.downcase
    else
      pathname
    end
  end

  ##
  # Loads a Gem::Specification from the TarEntry +entry+

  def load_spec(entry) # :nodoc:
    case entry.full_name
    when 'metadata' then
      @spec = Gem::Specification.from_yaml entry.read
    when 'metadata.gz' then
      Zlib::GzipReader.wrap(entry, external_encoding: Encoding::UTF_8) do |gzio|
        @spec = Gem::Specification.from_yaml gzio.read
      end
    end
  end

  ##
  # Opens +io+ as a gzipped tar archive

  def open_tar_gz(io) # :nodoc:
    Zlib::GzipReader.wrap io do |gzio|
      tar = Gem::Package::TarReader.new gzio

      yield tar
    end
  end

  ##
  # Reads and loads checksums.yaml.gz from the tar file +gem+

  def read_checksums(gem)
    Gem.load_yaml

    @checksums = gem.seek 'checksums.yaml.gz' do |entry|
      Zlib::GzipReader.wrap entry do |gz_io|
        Gem::SafeYAML.safe_load gz_io.read
      end
    end
  end

  ##
  # Prepares the gem for signing and checksum generation.  If a signing
  # certificate and key are not present only checksum generation is set up.

  def setup_signer(signer_options: {})
    passphrase = ENV['GEM_PRIVATE_KEY_PASSPHRASE']
    if @spec.signing_key
      @signer =
        Gem::Security::Signer.new(
          @spec.signing_key,
          @spec.cert_chain,
          passphrase,
          signer_options
        )

      @spec.signing_key = nil
      @spec.cert_chain = @signer.cert_chain.map {|cert| cert.to_s }
    else
      @signer = Gem::Security::Signer.new nil, nil, passphrase
      @spec.cert_chain = @signer.cert_chain.map {|cert| cert.to_pem } if
        @signer.cert_chain
    end
  end

  ##
  # The spec for this gem.
  #
  # If this is a package for a built gem the spec is loaded from the
  # gem and returned.  If this is a package for a gem being built the provided
  # spec is returned.

  def spec
    verify unless @spec

    @spec
  end

  ##
  # Verifies that this gem:
  #
  # * Contains a valid gem specification
  # * Contains a contents archive
  # * The contents archive is not corrupt
  #
  # After verification the gem specification from the gem is available from
  # #spec

  def verify
    @files     = []
    @spec      = nil

    @gem.with_read_io do |io|
      Gem::Package::TarReader.new io do |reader|
        read_checksums reader

        verify_files reader
      end
    end

    verify_checksums @digests, @checksums

    @security_policy.verify_signatures @spec, @digests, @signatures if
      @security_policy

    true
  rescue Gem::Security::Exception
    @spec = nil
    @files = []
    raise
  rescue Errno::ENOENT => e
    raise Gem::Package::FormatError.new e.message
  rescue Gem::Package::TarInvalidError => e
    raise Gem::Package::FormatError.new e.message, @gem
  end

  ##
  # Verifies the +checksums+ against the +digests+.  This check is not
  # cryptographically secure.  Missing checksums are ignored.

  def verify_checksums(digests, checksums) # :nodoc:
    return unless checksums

    checksums.sort.each do |algorithm, gem_digests|
      gem_digests.sort.each do |file_name, gem_hexdigest|
        computed_digest = digests[algorithm][file_name]

        unless computed_digest.hexdigest == gem_hexdigest
          raise Gem::Package::FormatError.new \
            "#{algorithm} checksum mismatch for #{file_name}", @gem
        end
      end
    end
  end

  ##
  # Verifies +entry+ in a .gem file.

  def verify_entry(entry)
    file_name = entry.full_name
    @files << file_name

    case file_name
    when /\.sig$/ then
      @signatures[$`] = entry.read if @security_policy
      return
    else
      digest entry
    end

    case file_name
    when "metadata", "metadata.gz" then
      load_spec entry
    when 'data.tar.gz' then
      verify_gz entry
    end
  rescue
    warn "Exception while verifying #{@gem.path}"
    raise
  end

  ##
  # Verifies the files of the +gem+

  def verify_files(gem)
    gem.each do |entry|
      verify_entry entry
    end

    unless @spec
      raise Gem::Package::FormatError.new 'package metadata is missing', @gem
    end

    unless @files.include? 'data.tar.gz'
      raise Gem::Package::FormatError.new \
              'package content (data.tar.gz) is missing', @gem
    end

    if duplicates = @files.group_by {|f| f }.select {|k,v| v.size > 1 }.map(&:first) and duplicates.any?
      raise Gem::Security::Exception, "duplicate files in the package: (#{duplicates.map(&:inspect).join(', ')})"
    end
  end

  ##
  # Verifies that +entry+ is a valid gzipped file.

  def verify_gz(entry) # :nodoc:
    Zlib::GzipReader.wrap entry do |gzio|
      gzio.read 16384 until gzio.eof? # gzip checksum verification
    end
  rescue Zlib::GzipFile::Error => e
    raise Gem::Package::FormatError.new(e.message, entry.full_name)
  end
end

require_relative 'package/digest_io'
require_relative 'package/source'
require_relative 'package/file_source'
require_relative 'package/io_source'
require_relative 'package/old'
require_relative 'package/tar_header'
require_relative 'package/tar_reader'
require_relative 'package/tar_reader/entry'
require_relative 'package/tar_writer'
# frozen_string_literal: true
##
# Provides a single method +deprecate+ to be used to declare when
# something is going away.
#
#     class Legacy
#       def self.klass_method
#         # ...
#       end
#
#       def instance_method
#         # ...
#       end
#
#       extend Gem::Deprecate
#       deprecate :instance_method, "X.z", 2011, 4
#
#       class << self
#         extend Gem::Deprecate
#         deprecate :klass_method, :none, 2011, 4
#       end
#     end

module Gem::Deprecate

  def self.skip # :nodoc:
    @skip ||= false
  end

  def self.skip=(v) # :nodoc:
    @skip = v
  end

  ##
  # Temporarily turn off warnings. Intended for tests only.

  def skip_during
    Gem::Deprecate.skip, original = true, Gem::Deprecate.skip
    yield
  ensure
    Gem::Deprecate.skip = original
  end

  def self.next_rubygems_major_version # :nodoc:
    Gem::Version.new(Gem.rubygems_version.segments.first).bump
  end

  ##
  # Simple deprecation method that deprecates +name+ by wrapping it up
  # in a dummy method. It warns on each call to the dummy method
  # telling the user of +repl+ (unless +repl+ is :none) and the
  # year/month that it is planned to go away.

  def deprecate(name, repl, year, month)
    class_eval do
      old = "_deprecated_#{name}"
      alias_method old, name
      define_method name do |*args, &block|
        klass = self.kind_of? Module
        target = klass ? "#{self}." : "#{self.class}#"
        msg = [ "NOTE: #{target}#{name} is deprecated",
                repl == :none ? " with no replacement" : "; use #{repl} instead",
                ". It will be removed on or after %4d-%02d." % [year, month],
                "\n#{target}#{name} called from #{Gem.location_of_caller.join(":")}",
        ]
        warn "#{msg.join}." unless Gem::Deprecate.skip
        send old, *args, &block
      end
      ruby2_keywords name if respond_to?(:ruby2_keywords, true)
    end
  end

  ##
  # Simple deprecation method that deprecates +name+ by wrapping it up
  # in a dummy method. It warns on each call to the dummy method
  # telling the user of +repl+ (unless +repl+ is :none) and the
  # Rubygems version that it is planned to go away.

  def rubygems_deprecate(name, replacement=:none)
    class_eval do
      old = "_deprecated_#{name}"
      alias_method old, name
      define_method name do |*args, &block|
        klass = self.kind_of? Module
        target = klass ? "#{self}." : "#{self.class}#"
        msg = [ "NOTE: #{target}#{name} is deprecated",
                replacement == :none ? " with no replacement" : "; use #{replacement} instead",
                ". It will be removed in Rubygems #{Gem::Deprecate.next_rubygems_major_version}",
                "\n#{target}#{name} called from #{Gem.location_of_caller.join(":")}",
        ]
        warn "#{msg.join}." unless Gem::Deprecate.skip
        send old, *args, &block
      end
      ruby2_keywords name if respond_to?(:ruby2_keywords, true)
    end
  end

  # Deprecation method to deprecate Rubygems commands
  def rubygems_deprecate_command
    class_eval do
      define_method "deprecated?" do
        true
      end

      define_method "deprecation_warning" do
        msg = [ "#{self.command} command is deprecated",
                ". It will be removed in Rubygems #{Gem::Deprecate.next_rubygems_major_version}.\n",
        ]

        alert_warning "#{msg.join}" unless Gem::Deprecate.skip
      end
    end
  end

  module_function :rubygems_deprecate, :rubygems_deprecate_command, :skip_during

end
# frozen_string_literal: true

require_relative 'tsort/lib/tsort'
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require_relative 'exceptions'
require_relative 'openssl'

##
# = Signing gems
#
# The Gem::Security implements cryptographic signatures for gems.  The section
# below is a step-by-step guide to using signed gems and generating your own.
#
# == Walkthrough
#
# === Building your certificate
#
# In order to start signing your gems, you'll need to build a private key and
# a self-signed certificate.  Here's how:
#
#   # build a private key and certificate for yourself:
#   $ gem cert --build you@example.com
#
# This could take anywhere from a few seconds to a minute or two, depending on
# the speed of your computer (public key algorithms aren't exactly the
# speediest crypto algorithms in the world).  When it's finished, you'll see
# the files "gem-private_key.pem" and "gem-public_cert.pem" in the current
# directory.
#
# First things first: Move both files to ~/.gem if you don't already have a
# key and certificate in that directory.  Ensure the file permissions make the
# key unreadable by others (by default the file is saved securely).
#
# Keep your private key hidden; if it's compromised, someone can sign packages
# as you (note: PKI has ways of mitigating the risk of stolen keys; more on
# that later).
#
# === Signing Gems
#
# In RubyGems 2 and newer there is no extra work to sign a gem.  RubyGems will
# automatically find your key and certificate in your home directory and use
# them to sign newly packaged gems.
#
# If your certificate is not self-signed (signed by a third party) RubyGems
# will attempt to load the certificate chain from the trusted certificates.
# Use <code>gem cert --add signing_cert.pem</code> to add your signers as
# trusted certificates.  See below for further information on certificate
# chains.
#
# If you build your gem it will automatically be signed.  If you peek inside
# your gem file, you'll see a couple of new files have been added:
#
#   $ tar tf your-gem-1.0.gem
#   metadata.gz
#   metadata.gz.sig # metadata signature
#   data.tar.gz
#   data.tar.gz.sig # data signature
#   checksums.yaml.gz
#   checksums.yaml.gz.sig # checksums signature
#
# === Manually signing gems
#
# If you wish to store your key in a separate secure location you'll need to
# set your gems up for signing by hand.  To do this, set the
# <code>signing_key</code> and <code>cert_chain</code> in the gemspec before
# packaging your gem:
#
#   s.signing_key = '/secure/path/to/gem-private_key.pem'
#   s.cert_chain = %w[/secure/path/to/gem-public_cert.pem]
#
# When you package your gem with these options set RubyGems will automatically
# load your key and certificate from the secure paths.
#
# === Signed gems and security policies
#
# Now let's verify the signature.  Go ahead and install the gem, but add the
# following options: <code>-P HighSecurity</code>, like this:
#
#   # install the gem with using the security policy "HighSecurity"
#   $ sudo gem install your.gem -P HighSecurity
#
# The <code>-P</code> option sets your security policy -- we'll talk about
# that in just a minute.  Eh, what's this?
#
#   $ gem install -P HighSecurity your-gem-1.0.gem
#   ERROR:  While executing gem ... (Gem::Security::Exception)
#       root cert /CN=you/DC=example is not trusted
#
# The culprit here is the security policy.  RubyGems has several different
# security policies.  Let's take a short break and go over the security
# policies.  Here's a list of the available security policies, and a brief
# description of each one:
#
# * NoSecurity - Well, no security at all.  Signed packages are treated like
#   unsigned packages.
# * LowSecurity - Pretty much no security.  If a package is signed then
#   RubyGems will make sure the signature matches the signing
#   certificate, and that the signing certificate hasn't expired, but
#   that's it.  A malicious user could easily circumvent this kind of
#   security.
# * MediumSecurity - Better than LowSecurity and NoSecurity, but still
#   fallible.  Package contents are verified against the signing
#   certificate, and the signing certificate is checked for validity,
#   and checked against the rest of the certificate chain (if you don't
#   know what a certificate chain is, stay tuned, we'll get to that).
#   The biggest improvement over LowSecurity is that MediumSecurity
#   won't install packages that are signed by untrusted sources.
#   Unfortunately, MediumSecurity still isn't totally secure -- a
#   malicious user can still unpack the gem, strip the signatures, and
#   distribute the gem unsigned.
# * HighSecurity - Here's the bugger that got us into this mess.
#   The HighSecurity policy is identical to the MediumSecurity policy,
#   except that it does not allow unsigned gems.  A malicious user
#   doesn't have a whole lot of options here; they can't modify the
#   package contents without invalidating the signature, and they can't
#   modify or remove signature or the signing certificate chain, or
#   RubyGems will simply refuse to install the package.  Oh well, maybe
#   they'll have better luck causing problems for CPAN users instead :).
#
# The reason RubyGems refused to install your shiny new signed gem was because
# it was from an untrusted source.  Well, your code is infallible (naturally),
# so you need to add yourself as a trusted source:
#
#   # add trusted certificate
#   gem cert --add ~/.gem/gem-public_cert.pem
#
# You've now added your public certificate as a trusted source.  Now you can
# install packages signed by your private key without any hassle.  Let's try
# the install command above again:
#
#   # install the gem with using the HighSecurity policy (and this time
#   # without any shenanigans)
#   $ gem install -P HighSecurity your-gem-1.0.gem
#   Successfully installed your-gem-1.0
#   1 gem installed
#
# This time RubyGems will accept your signed package and begin installing.
#
# While you're waiting for RubyGems to work it's magic, have a look at some of
# the other security commands by running <code>gem help cert</code>:
#
#   Options:
#     -a, --add CERT                   Add a trusted certificate.
#     -l, --list [FILTER]              List trusted certificates where the
#                                      subject contains FILTER
#     -r, --remove FILTER              Remove trusted certificates where the
#                                      subject contains FILTER
#     -b, --build EMAIL_ADDR           Build private key and self-signed
#                                      certificate for EMAIL_ADDR
#     -C, --certificate CERT           Signing certificate for --sign
#     -K, --private-key KEY            Key for --sign or --build
#     -A, --key-algorithm ALGORITHM    Select key algorithm for --build from RSA, DSA, or EC. Defaults to RSA.
#     -s, --sign CERT                  Signs CERT with the key from -K
#                                      and the certificate from -C
#     -d, --days NUMBER_OF_DAYS        Days before the certificate expires
#     -R, --re-sign                    Re-signs the certificate from -C with the key from -K
#
# We've already covered the <code>--build</code> option, and the
# <code>--add</code>, <code>--list</code>, and <code>--remove</code> commands
# seem fairly straightforward; they allow you to add, list, and remove the
# certificates in your trusted certificate list.  But what's with this
# <code>--sign</code> option?
#
# === Certificate chains
#
# To answer that question, let's take a look at "certificate chains", a
# concept I mentioned earlier.  There are a couple of problems with
# self-signed certificates: first of all, self-signed certificates don't offer
# a whole lot of security.  Sure, the certificate says Yukihiro Matsumoto, but
# how do I know it was actually generated and signed by matz himself unless he
# gave me the certificate in person?
#
# The second problem is scalability.  Sure, if there are 50 gem authors, then
# I have 50 trusted certificates, no problem.  What if there are 500 gem
# authors?  1000?  Having to constantly add new trusted certificates is a
# pain, and it actually makes the trust system less secure by encouraging
# RubyGems users to blindly trust new certificates.
#
# Here's where certificate chains come in.  A certificate chain establishes an
# arbitrarily long chain of trust between an issuing certificate and a child
# certificate.  So instead of trusting certificates on a per-developer basis,
# we use the PKI concept of certificate chains to build a logical hierarchy of
# trust.  Here's a hypothetical example of a trust hierarchy based (roughly)
# on geography:
#
#                         --------------------------
#                         | rubygems@rubygems.org |
#                         --------------------------
#                                     |
#                   -----------------------------------
#                   |                                 |
#       ----------------------------    -----------------------------
#       |  seattlerb@seattlerb.org |    | dcrubyists@richkilmer.com |
#       ----------------------------    -----------------------------
#            |                |                 |             |
#     ---------------   ----------------   -----------   --------------
#     |   drbrain   |   |   zenspider  |   | pabs@dc |   | tomcope@dc |
#     ---------------   ----------------   -----------   --------------
#
#
# Now, rather than having 4 trusted certificates (one for drbrain, zenspider,
# pabs@dc, and tomecope@dc), a user could actually get by with one
# certificate, the "rubygems@rubygems.org" certificate.
#
# Here's how it works:
#
# I install "rdoc-3.12.gem", a package signed by "drbrain".  I've never heard
# of "drbrain", but his certificate has a valid signature from the
# "seattle.rb@seattlerb.org" certificate, which in turn has a valid signature
# from the "rubygems@rubygems.org" certificate.  Voila!  At this point, it's
# much more reasonable for me to trust a package signed by "drbrain", because
# I can establish a chain to "rubygems@rubygems.org", which I do trust.
#
# === Signing certificates
#
# The <code>--sign</code> option allows all this to happen.  A developer
# creates their build certificate with the <code>--build</code> option, then
# has their certificate signed by taking it with them to their next regional
# Ruby meetup (in our hypothetical example), and it's signed there by the
# person holding the regional RubyGems signing certificate, which is signed at
# the next RubyConf by the holder of the top-level RubyGems certificate.  At
# each point the issuer runs the same command:
#
#   # sign a certificate with the specified key and certificate
#   # (note that this modifies client_cert.pem!)
#   $ gem cert -K /mnt/floppy/issuer-priv_key.pem -C issuer-pub_cert.pem
#      --sign client_cert.pem
#
# Then the holder of issued certificate (in this case, your buddy "drbrain"),
# can start using this signed certificate to sign RubyGems.  By the way, in
# order to let everyone else know about his new fancy signed certificate,
# "drbrain" would save his newly signed certificate as
# <code>~/.gem/gem-public_cert.pem</code>
#
# Obviously this RubyGems trust infrastructure doesn't exist yet.  Also, in
# the "real world", issuers actually generate the child certificate from a
# certificate request, rather than sign an existing certificate.  And our
# hypothetical infrastructure is missing a certificate revocation system.
# These are that can be fixed in the future...
#
# At this point you should know how to do all of these new and interesting
# things:
#
# * build a gem signing key and certificate
# * adjust your security policy
# * modify your trusted certificate list
# * sign a certificate
#
# == Manually verifying signatures
#
# In case you don't trust RubyGems you can verify gem signatures manually:
#
# 1. Fetch and unpack the gem
#
#      gem fetch some_signed_gem
#      tar -xf some_signed_gem-1.0.gem
#
# 2. Grab the public key from the gemspec
#
#      gem spec some_signed_gem-1.0.gem cert_chain | \
#        ruby -ryaml -e 'puts YAML.load($stdin)' > public_key.crt
#
# 3. Generate a SHA1 hash of the data.tar.gz
#
#      openssl dgst -sha1 < data.tar.gz > my.hash
#
# 4. Verify the signature
#
#      openssl rsautl -verify -inkey public_key.crt -certin \
#        -in data.tar.gz.sig > verified.hash
#
# 5. Compare your hash to the verified hash
#
#      diff -s verified.hash my.hash
#
# 6. Repeat 5 and 6 with metadata.gz
#
# == OpenSSL Reference
#
# The .pem files generated by --build and --sign are PEM files.  Here's a
# couple of useful OpenSSL commands for manipulating them:
#
#   # convert a PEM format X509 certificate into DER format:
#   # (note: Windows .cer files are X509 certificates in DER format)
#   $ openssl x509 -in input.pem -outform der -out output.der
#
#   # print out the certificate in a human-readable format:
#   $ openssl x509 -in input.pem -noout -text
#
# And you can do the same thing with the private key file as well:
#
#   # convert a PEM format RSA key into DER format:
#   $ openssl rsa -in input_key.pem -outform der -out output_key.der
#
#   # print out the key in a human readable format:
#   $ openssl rsa -in input_key.pem -noout -text
#
# == Bugs/TODO
#
# * There's no way to define a system-wide trust list.
# * custom security policies (from a YAML file, etc)
# * Simple method to generate a signed certificate request
# * Support for OCSP, SCVP, CRLs, or some other form of cert status check
#   (list is in order of preference)
# * Support for encrypted private keys
# * Some sort of semi-formal trust hierarchy (see long-winded explanation
#   above)
# * Path discovery (for gem certificate chains that don't have a self-signed
#   root) -- by the way, since we don't have this, THE ROOT OF THE CERTIFICATE
#   CHAIN MUST BE SELF SIGNED if Policy#verify_root is true (and it is for the
#   MediumSecurity and HighSecurity policies)
# * Better explanation of X509 naming (ie, we don't have to use email
#   addresses)
# * Honor AIA field (see note about OCSP above)
# * Honor extension restrictions
# * Might be better to store the certificate chain as a PKCS#7 or PKCS#12
#   file, instead of an array embedded in the metadata.
#
# == Original author
#
# Paul Duncan <pabs@pablotron.org>
# http://pablotron.org/

module Gem::Security

  ##
  # Gem::Security default exception type

  class Exception < Gem::Exception; end

  ##
  # Used internally to select the signing digest from all computed digests

  DIGEST_NAME = 'SHA256' # :nodoc:

  ##
  # Length of keys created by RSA and DSA keys

  RSA_DSA_KEY_LENGTH = 3072

  ##
  # Default algorithm to use when building a key pair

  DEFAULT_KEY_ALGORITHM = 'RSA'

  ##
  # Named curve used for Elliptic Curve

  EC_NAME = 'secp384r1'

  ##
  # Cipher used to encrypt the key pair used to sign gems.
  # Must be in the list returned by OpenSSL::Cipher.ciphers

  KEY_CIPHER = OpenSSL::Cipher.new('AES-256-CBC') if defined?(OpenSSL::Cipher)

  ##
  # One day in seconds

  ONE_DAY = 86400

  ##
  # One year in seconds

  ONE_YEAR = ONE_DAY * 365

  ##
  # The default set of extensions are:
  #
  # * The certificate is not a certificate authority
  # * The key for the certificate may be used for key and data encipherment
  #   and digital signatures
  # * The certificate contains a subject key identifier

  EXTENSIONS = {
    'basicConstraints'     => 'CA:FALSE',
    'keyUsage'             =>
      'keyEncipherment,dataEncipherment,digitalSignature',
    'subjectKeyIdentifier' => 'hash',
  }.freeze

  def self.alt_name_or_x509_entry(certificate, x509_entry)
    alt_name = certificate.extensions.find do |extension|
      extension.oid == "#{x509_entry}AltName"
    end

    return alt_name.value if alt_name

    certificate.send x509_entry
  end

  ##
  # Creates an unsigned certificate for +subject+ and +key+.  The lifetime of
  # the key is from the current time to +age+ which defaults to one year.
  #
  # The +extensions+ restrict the key to the indicated uses.

  def self.create_cert(subject, key, age = ONE_YEAR, extensions = EXTENSIONS,
                       serial = 1)
    cert = OpenSSL::X509::Certificate.new

    cert.public_key = get_public_key(key)
    cert.version    = 2
    cert.serial     = serial

    cert.not_before = Time.now
    cert.not_after  = Time.now + age

    cert.subject    = subject

    ef = OpenSSL::X509::ExtensionFactory.new nil, cert

    cert.extensions = extensions.map do |ext_name, value|
      ef.create_extension ext_name, value
    end

    cert
  end

  ##
  # Gets the right public key from a PKey instance

  def self.get_public_key(key)
    # Ruby 3.0 (Ruby/OpenSSL 2.2) or later
    return OpenSSL::PKey.read(key.public_to_der) if key.respond_to?(:public_to_der)
    return key.public_key unless key.is_a?(OpenSSL::PKey::EC)

    ec_key = OpenSSL::PKey::EC.new(key.group.curve_name)
    ec_key.public_key = key.public_key
    ec_key
  end

  ##
  # In Ruby 2.3 EC doesn't implement the private_key? but not the private? method

  if defined?(OpenSSL::PKey::EC) && Gem::Version.new(String.new(RUBY_VERSION)) < Gem::Version.new("2.4.0")
    OpenSSL::PKey::EC.send(:alias_method, :private?, :private_key?)
  end

  ##
  # Creates a self-signed certificate with an issuer and subject from +email+,
  # a subject alternative name of +email+ and the given +extensions+ for the
  # +key+.

  def self.create_cert_email(email, key, age = ONE_YEAR, extensions = EXTENSIONS)
    subject = email_to_name email

    extensions = extensions.merge "subjectAltName" => "email:#{email}"

    create_cert_self_signed subject, key, age, extensions
  end

  ##
  # Creates a self-signed certificate with an issuer and subject of +subject+
  # and the given +extensions+ for the +key+.

  def self.create_cert_self_signed(subject, key, age = ONE_YEAR,
                                   extensions = EXTENSIONS, serial = 1)
    certificate = create_cert subject, key, age, extensions

    sign certificate, key, certificate, age, extensions, serial
  end

  ##
  # Creates a new digest instance using the specified +algorithm+. The default
  # is SHA256.

  if defined?(OpenSSL::Digest)
    def self.create_digest(algorithm = DIGEST_NAME)
      OpenSSL::Digest.new(algorithm)
    end
  else
    require 'digest'

    def self.create_digest(algorithm = DIGEST_NAME)
      Digest.const_get(algorithm).new
    end
  end

  ##
  # Creates a new key pair of the specified +algorithm+. RSA, DSA, and EC
  # are supported.

  def self.create_key(algorithm)
    if defined?(OpenSSL::PKey)
      case algorithm.downcase
      when 'dsa'
        OpenSSL::PKey::DSA.new(RSA_DSA_KEY_LENGTH)
      when 'rsa'
        OpenSSL::PKey::RSA.new(RSA_DSA_KEY_LENGTH)
      when 'ec'
        if RUBY_VERSION >= "2.4.0"
          OpenSSL::PKey::EC.generate(EC_NAME)
        else
          domain_key = OpenSSL::PKey::EC.new(EC_NAME)
          domain_key.generate_key
          domain_key
        end
      else
        raise Gem::Security::Exception,
        "#{algorithm} algorithm not found. RSA, DSA, and EC algorithms are supported."
      end
    end
  end

  ##
  # Turns +email_address+ into an OpenSSL::X509::Name

  def self.email_to_name(email_address)
    email_address = email_address.gsub(/[^\w@.-]+/i, '_')

    cn, dcs = email_address.split '@'

    dcs = dcs.split '.'

    name = "/CN=#{cn}/#{dcs.map {|dc| "DC=#{dc}" }.join '/'}"

    OpenSSL::X509::Name.parse name
  end

  ##
  # Signs +expired_certificate+ with +private_key+ if the keys match and the
  # expired certificate was self-signed.
  #--
  # TODO increment serial

  def self.re_sign(expired_certificate, private_key, age = ONE_YEAR,
                   extensions = EXTENSIONS)
    raise Gem::Security::Exception,
          "incorrect signing key for re-signing " +
          "#{expired_certificate.subject}" unless
      expired_certificate.check_private_key(private_key)

    unless expired_certificate.subject.to_s ==
           expired_certificate.issuer.to_s
      subject = alt_name_or_x509_entry expired_certificate, :subject
      issuer  = alt_name_or_x509_entry expired_certificate, :issuer

      raise Gem::Security::Exception,
            "#{subject} is not self-signed, contact #{issuer} " +
            "to obtain a valid certificate"
    end

    serial = expired_certificate.serial + 1

    create_cert_self_signed(expired_certificate.subject, private_key, age,
                            extensions, serial)
  end

  ##
  # Resets the trust directory for verifying gems.

  def self.reset
    @trust_dir = nil
  end

  ##
  # Sign the public key from +certificate+ with the +signing_key+ and
  # +signing_cert+, using the Gem::Security::DIGEST_NAME.  Uses the
  # default certificate validity range and extensions.
  #
  # Returns the newly signed certificate.

  def self.sign(certificate, signing_key, signing_cert,
                age = ONE_YEAR, extensions = EXTENSIONS, serial = 1)
    signee_subject = certificate.subject
    signee_key     = certificate.public_key

    alt_name = certificate.extensions.find do |extension|
      extension.oid == 'subjectAltName'
    end

    extensions = extensions.merge 'subjectAltName' => alt_name.value if
      alt_name

    issuer_alt_name = signing_cert.extensions.find do |extension|
      extension.oid == 'subjectAltName'
    end

    extensions = extensions.merge 'issuerAltName' => issuer_alt_name.value if
      issuer_alt_name

    signed = create_cert signee_subject, signee_key, age, extensions, serial
    signed.issuer = signing_cert.subject

    signed.sign signing_key, Gem::Security::DIGEST_NAME
  end

  ##
  # Returns a Gem::Security::TrustDir which wraps the directory where trusted
  # certificates live.

  def self.trust_dir
    return @trust_dir if @trust_dir

    dir = File.join Gem.user_home, '.gem', 'trust'

    @trust_dir ||= Gem::Security::TrustDir.new dir
  end

  ##
  # Enumerates the trusted certificates via Gem::Security::TrustDir.

  def self.trusted_certificates(&block)
    trust_dir.each_certificate(&block)
  end

  ##
  # Writes +pemmable+, which must respond to +to_pem+ to +path+ with the given
  # +permissions+. If passed +cipher+ and +passphrase+ those arguments will be
  # passed to +to_pem+.

  def self.write(pemmable, path, permissions = 0600, passphrase = nil, cipher = KEY_CIPHER)
    path = File.expand_path path

    File.open path, 'wb', permissions do |io|
      if passphrase and cipher
        io.write pemmable.to_pem cipher, passphrase
      else
        io.write pemmable.to_pem
      end
    end

    path
  end

  reset

end

if Gem::HAVE_OPENSSL
  require_relative 'security/policy'
  require_relative 'security/policies'
  require_relative 'security/trust_dir'
end

require_relative 'security/signer'
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require_relative 'command'
require_relative 'user_interaction'
require_relative 'text'

##
# The command manager registers and installs all the individual sub-commands
# supported by the gem command.
#
# Extra commands can be provided by writing a rubygems_plugin.rb
# file in an installed gem.  You should register your command against the
# Gem::CommandManager instance, like this:
#
#   # file rubygems_plugin.rb
#   require 'rubygems/command_manager'
#
#   Gem::CommandManager.instance.register_command :edit
#
# You should put the implementation of your command in rubygems/commands.
#
#   # file rubygems/commands/edit_command.rb
#   class Gem::Commands::EditCommand < Gem::Command
#     # ...
#   end
#
# See Gem::Command for instructions on writing gem commands.

class Gem::CommandManager
  include Gem::Text
  include Gem::UserInteraction

  BUILTIN_COMMANDS = [ # :nodoc:
    :build,
    :cert,
    :check,
    :cleanup,
    :contents,
    :dependency,
    :environment,
    :fetch,
    :generate_index,
    :help,
    :info,
    :install,
    :list,
    :lock,
    :mirror,
    :open,
    :outdated,
    :owner,
    :pristine,
    :push,
    :query,
    :rdoc,
    :search,
    :server,
    :signin,
    :signout,
    :sources,
    :specification,
    :stale,
    :uninstall,
    :unpack,
    :update,
    :which,
    :yank,
  ].freeze

  ALIAS_COMMANDS = {
    'i'      => 'install',
    'login'  => 'signin',
    'logout' => 'signout',
  }.freeze

  ##
  # Return the authoritative instance of the command manager.

  def self.instance
    @command_manager ||= new
  end

  ##
  # Returns self. Allows a CommandManager instance to stand
  # in for the class itself.

  def instance
    self
  end

  ##
  # Reset the authoritative instance of the command manager.

  def self.reset
    @command_manager = nil
  end

  ##
  # Register all the subcommands supported by the gem command.

  def initialize
    require 'timeout'
    @commands = {}

    BUILTIN_COMMANDS.each do |name|
      register_command name
    end
  end

  ##
  # Register the Symbol +command+ as a gem command.

  def register_command(command, obj=false)
    @commands[command] = obj
  end

  ##
  # Unregister the Symbol +command+ as a gem command.

  def unregister_command(command)
    @commands.delete command
  end

  ##
  # Returns a Command instance for +command_name+

  def [](command_name)
    command_name = command_name.intern
    return nil if @commands[command_name].nil?
    @commands[command_name] ||= load_and_instantiate(command_name)
  end

  ##
  # Return a sorted list of all command names as strings.

  def command_names
    @commands.keys.collect {|key| key.to_s }.sort
  end

  ##
  # Run the command specified by +args+.

  def run(args, build_args=nil)
    process_args(args, build_args)
  rescue StandardError, Timeout::Error => ex
    alert_error clean_text("While executing gem ... (#{ex.class})\n    #{ex}")
    ui.backtrace ex

    terminate_interaction(1)
  rescue Interrupt
    alert_error clean_text("Interrupted")
    terminate_interaction(1)
  end

  def process_args(args, build_args=nil)
    if args.empty?
      say Gem::Command::HELP
      terminate_interaction 1
    end

    case args.first
    when '-h', '--help' then
      say Gem::Command::HELP
      terminate_interaction 0
    when '-v', '--version' then
      say Gem::VERSION
      terminate_interaction 0
    when /^-/ then
      alert_error clean_text("Invalid option: #{args.first}. See 'gem --help'.")
      terminate_interaction 1
    else
      cmd_name = args.shift.downcase
      cmd = find_command cmd_name
      cmd.deprecation_warning if cmd.deprecated?
      cmd.invoke_with_build_args args, build_args
    end
  end

  def find_command(cmd_name)
    cmd_name = find_alias_command cmd_name

    possibilities = find_command_possibilities cmd_name

    if possibilities.size > 1
      raise Gem::CommandLineError,
            "Ambiguous command #{cmd_name} matches [#{possibilities.join(', ')}]"
    elsif possibilities.empty?
      raise Gem::CommandLineError, "Unknown command #{cmd_name}"
    end

    self[possibilities.first]
  end

  def find_alias_command(cmd_name)
    alias_name = ALIAS_COMMANDS[cmd_name]
    alias_name ? alias_name : cmd_name
  end

  def find_command_possibilities(cmd_name)
    len = cmd_name.length

    found = command_names.select {|name| cmd_name == name[0, len] }

    exact = found.find {|name| name == cmd_name }

    exact ? [exact] : found
  end

  private

  def load_and_instantiate(command_name)
    command_name = command_name.to_s
    const_name = command_name.capitalize.gsub(/_(.)/) { $1.upcase } << "Command"
    load_error = nil

    begin
      begin
        require "rubygems/commands/#{command_name}_command"
      rescue LoadError => e
        load_error = e
      end
      Gem::Commands.const_get(const_name).new
    rescue Exception => e
      e = load_error if load_error

      alert_error clean_text("Loading command: #{command_name} (#{e.class})\n\t#{e}")
      ui.backtrace e
    end
  end
end
# frozen_string_literal: true
require_relative 'dependency'
require_relative 'exceptions'
require_relative 'util/list'

##
# Given a set of Gem::Dependency objects as +needed+ and a way to query the
# set of available specs via +set+, calculates a set of ActivationRequest
# objects which indicate all the specs that should be activated to meet the
# all the requirements.

class Gem::Resolver
  require_relative 'resolver/molinillo'

  ##
  # If the DEBUG_RESOLVER environment variable is set then debugging mode is
  # enabled for the resolver.  This will display information about the state
  # of the resolver while a set of dependencies is being resolved.

  DEBUG_RESOLVER = !ENV['DEBUG_RESOLVER'].nil?

  ##
  # Set to true if all development dependencies should be considered.

  attr_accessor :development

  ##
  # Set to true if immediate development dependencies should be considered.

  attr_accessor :development_shallow

  ##
  # When true, no dependencies are looked up for requested gems.

  attr_accessor :ignore_dependencies

  ##
  # List of dependencies that could not be found in the configured sources.

  attr_reader :missing

  attr_reader :stats

  ##
  # Hash of gems to skip resolution.  Keyed by gem name, with arrays of
  # gem specifications as values.

  attr_accessor :skip_gems

  ##
  # When a missing dependency, don't stop. Just go on and record what was
  # missing.

  attr_accessor :soft_missing

  ##
  # Combines +sets+ into a ComposedSet that allows specification lookup in a
  # uniform manner.  If one of the +sets+ is itself a ComposedSet its sets are
  # flattened into the result ComposedSet.

  def self.compose_sets(*sets)
    sets.compact!

    sets = sets.map do |set|
      case set
      when Gem::Resolver::BestSet then
        set
      when Gem::Resolver::ComposedSet then
        set.sets
      else
        set
      end
    end.flatten

    case sets.length
    when 0 then
      raise ArgumentError, 'one set in the composition must be non-nil'
    when 1 then
      sets.first
    else
      Gem::Resolver::ComposedSet.new(*sets)
    end
  end

  ##
  # Creates a Resolver that queries only against the already installed gems
  # for the +needed+ dependencies.

  def self.for_current_gems(needed)
    new needed, Gem::Resolver::CurrentSet.new
  end

  ##
  # Create Resolver object which will resolve the tree starting
  # with +needed+ Dependency objects.
  #
  # +set+ is an object that provides where to look for specifications to
  # satisfy the Dependencies. This defaults to IndexSet, which will query
  # rubygems.org.

  def initialize(needed, set = nil)
    @set = set || Gem::Resolver::IndexSet.new
    @needed = needed

    @development         = false
    @development_shallow = false
    @ignore_dependencies = false
    @missing             = []
    @skip_gems           = {}
    @soft_missing        = false
    @stats               = Gem::Resolver::Stats.new
  end

  def explain(stage, *data) # :nodoc:
    return unless DEBUG_RESOLVER

    d = data.map {|x| x.pretty_inspect }.join(", ")
    $stderr.printf "%10s %s\n", stage.to_s.upcase, d
  end

  def explain_list(stage) # :nodoc:
    return unless DEBUG_RESOLVER

    data = yield
    $stderr.printf "%10s (%d entries)\n", stage.to_s.upcase, data.size
    unless data.empty?
      require 'pp'
      PP.pp data, $stderr
    end
  end

  ##
  # Creates an ActivationRequest for the given +dep+ and the last +possible+
  # specification.
  #
  # Returns the Specification and the ActivationRequest

  def activation_request(dep, possible) # :nodoc:
    spec = possible.pop

    explain :activate, [spec.full_name, possible.size]
    explain :possible, possible

    activation_request =
      Gem::Resolver::ActivationRequest.new spec, dep, possible

    return spec, activation_request
  end

  def requests(s, act, reqs=[]) # :nodoc:
    return reqs if @ignore_dependencies

    s.fetch_development_dependencies if @development

    s.dependencies.reverse_each do |d|
      next if d.type == :development and not @development
      next if d.type == :development and @development_shallow and
              act.development?
      next if d.type == :development and @development_shallow and
              act.parent

      reqs << Gem::Resolver::DependencyRequest.new(d, act)
      @stats.requirement!
    end

    @set.prefetch reqs

    @stats.record_requirements reqs

    reqs
  end

  include Molinillo::UI

  def output
    @output ||= debug? ? $stdout : File.open(IO::NULL, 'w')
  end

  def debug?
    DEBUG_RESOLVER
  end

  include Molinillo::SpecificationProvider

  ##
  # Proceed with resolution! Returns an array of ActivationRequest objects.

  def resolve
    locking_dg = Molinillo::DependencyGraph.new
    Molinillo::Resolver.new(self, self).resolve(@needed.map {|d| DependencyRequest.new d, nil }, locking_dg).tsort.map(&:payload).compact
  rescue Molinillo::VersionConflict => e
    conflict = e.conflicts.values.first
    raise Gem::DependencyResolutionError, Conflict.new(conflict.requirement_trees.first.first, conflict.existing, conflict.requirement)
  ensure
    @output.close if defined?(@output) and !debug?
  end

  ##
  # Extracts the specifications that may be able to fulfill +dependency+ and
  # returns those that match the local platform and all those that match.

  def find_possible(dependency) # :nodoc:
    all = @set.find_all dependency

    if (skip_dep_gems = skip_gems[dependency.name]) && !skip_dep_gems.empty?
      matching = all.select do |api_spec|
        skip_dep_gems.any? {|s| api_spec.version == s.version }
      end

      all = matching unless matching.empty?
    end

    matching_platform = select_local_platforms all

    return matching_platform, all
  end

  ##
  # Returns the gems in +specs+ that match the local platform.

  def select_local_platforms(specs) # :nodoc:
    specs.select do |spec|
      Gem::Platform.installable? spec
    end
  end

  def search_for(dependency)
    possibles, all = find_possible(dependency)
    if !@soft_missing && possibles.empty?
      @missing << dependency
      exc = Gem::UnsatisfiableDependencyError.new dependency, all
      exc.errors = @set.errors
      raise exc
    end

    groups = Hash.new {|hash, key| hash[key] = [] }

    # create groups & sources in the same loop
    sources = possibles.map do |spec|
      source = spec.source
      groups[source] << spec
      source
    end.uniq.reverse

    activation_requests = []

    sources.each do |source|
      groups[source].
        sort_by {|spec| [spec.version, Gem::Platform.local =~ spec.platform ? 1 : 0] }.
        map {|spec| ActivationRequest.new spec, dependency }.
        each {|activation_request| activation_requests << activation_request }
    end

    activation_requests
  end

  def dependencies_for(specification)
    return [] if @ignore_dependencies
    spec = specification.spec
    requests(spec, specification)
  end

  def requirement_satisfied_by?(requirement, activated, spec)
    matches_spec = requirement.matches_spec? spec
    return matches_spec if @soft_missing

    matches_spec &&
      spec.spec.required_ruby_version.satisfied_by?(Gem.ruby_version) &&
      spec.spec.required_rubygems_version.satisfied_by?(Gem.rubygems_version)
  end

  def name_for(dependency)
    dependency.name
  end

  def allow_missing?(dependency)
    @missing << dependency
    @soft_missing
  end

  def sort_dependencies(dependencies, activated, conflicts)
    dependencies.sort_by.with_index do |dependency, i|
      name = name_for(dependency)
      [
        activated.vertex_named(name).payload ? 0 : 1,
        amount_constrained(dependency),
        conflicts[name] ? 0 : 1,
        activated.vertex_named(name).payload ? 0 : search_for(dependency).count,
        i, # for stable sort
      ]
    end
  end

  SINGLE_POSSIBILITY_CONSTRAINT_PENALTY = 1_000_000
  private_constant :SINGLE_POSSIBILITY_CONSTRAINT_PENALTY if defined?(private_constant)

  # returns an integer \in (-\infty, 0]
  # a number closer to 0 means the dependency is less constraining
  #
  # dependencies w/ 0 or 1 possibilities (ignoring version requirements)
  # are given very negative values, so they _always_ sort first,
  # before dependencies that are unconstrained
  def amount_constrained(dependency)
    @amount_constrained ||= {}
    @amount_constrained[dependency.name] ||= begin
      name_dependency = Gem::Dependency.new(dependency.name)
      dependency_request_for_name = Gem::Resolver::DependencyRequest.new(name_dependency, dependency.requester)
      all = @set.find_all(dependency_request_for_name).size

      if all <= 1
        all - SINGLE_POSSIBILITY_CONSTRAINT_PENALTY
      else
        search = search_for(dependency).size
        search - all
      end
    end
  end
  private :amount_constrained
end

require_relative 'resolver/activation_request'
require_relative 'resolver/conflict'
require_relative 'resolver/dependency_request'
require_relative 'resolver/requirement_list'
require_relative 'resolver/stats'

require_relative 'resolver/set'
require_relative 'resolver/api_set'
require_relative 'resolver/composed_set'
require_relative 'resolver/best_set'
require_relative 'resolver/current_set'
require_relative 'resolver/git_set'
require_relative 'resolver/index_set'
require_relative 'resolver/installer_set'
require_relative 'resolver/lock_set'
require_relative 'resolver/vendor_set'
require_relative 'resolver/source_set'

require_relative 'resolver/specification'
require_relative 'resolver/spec_specification'
require_relative 'resolver/api_specification'
require_relative 'resolver/git_specification'
require_relative 'resolver/index_specification'
require_relative 'resolver/installed_specification'
require_relative 'resolver/local_specification'
require_relative 'resolver/lock_specification'
require_relative 'resolver/vendor_specification'
# frozen_string_literal: true
##
# A Lock source wraps an installed gem's source and sorts before other sources
# during dependency resolution.  This allows RubyGems to prefer gems from
# dependency lock files.

class Gem::Source::Lock < Gem::Source
  ##
  # The wrapped Gem::Source

  attr_reader :wrapped

  ##
  # Creates a new Lock source that wraps +source+ and moves it earlier in the
  # sort list.

  def initialize(source)
    @wrapped = source
  end

  def <=>(other) # :nodoc:
    case other
    when Gem::Source::Lock then
      @wrapped <=> other.wrapped
    when Gem::Source then
      1
    else
      nil
    end
  end

  def ==(other) # :nodoc:
    0 == (self <=> other)
  end

  def hash # :nodoc:
    @wrapped.hash ^ 3
  end

  ##
  # Delegates to the wrapped source's fetch_spec method.

  def fetch_spec(name_tuple)
    @wrapped.fetch_spec name_tuple
  end

  def uri # :nodoc:
    @wrapped.uri
  end
end
# frozen_string_literal: true
##
# This represents a vendored source that is similar to an installed gem.

class Gem::Source::Vendor < Gem::Source::Installed
  ##
  # Creates a new Vendor source for a gem that was unpacked at +path+.

  def initialize(path)
    @uri = path
  end

  def <=>(other)
    case other
    when Gem::Source::Lock then
      -1
    when Gem::Source::Vendor then
      0
    when Gem::Source then
      1
    else
      nil
    end
  end
end
# frozen_string_literal: true
##
# Represents an installed gem.  This is used for dependency resolution.

class Gem::Source::Installed < Gem::Source
  def initialize # :nodoc:
    @uri = nil
  end

  ##
  # Installed sources sort before all other sources

  def <=>(other)
    case other
    when Gem::Source::Git,
         Gem::Source::Lock,
         Gem::Source::Vendor then
      -1
    when Gem::Source::Installed then
      0
    when Gem::Source then
      1
    else
      nil
    end
  end

  ##
  # We don't need to download an installed gem

  def download(spec, path)
    nil
  end

  def pretty_print(q) # :nodoc:
    q.text '[Installed]'
  end
end
# frozen_string_literal: true
##
# The local source finds gems in the current directory for fulfilling
# dependencies.

class Gem::Source::Local < Gem::Source
  def initialize # :nodoc:
    @specs   = nil
    @api_uri = nil
    @uri     = nil
    @load_specs_names = {}
  end

  ##
  # Local sorts before Gem::Source and after Gem::Source::Installed

  def <=>(other)
    case other
    when Gem::Source::Installed,
         Gem::Source::Lock then
      -1
    when Gem::Source::Local then
      0
    when Gem::Source then
      1
    else
      nil
    end
  end

  def inspect # :nodoc:
    keys = @specs ? @specs.keys.sort : 'NOT LOADED'
    "#<%s specs: %p>" % [self.class, keys]
  end

  def load_specs(type) # :nodoc:
    @load_specs_names[type] ||= begin
      names = []

      @specs = {}

      Dir["*.gem"].each do |file|
        begin
          pkg = Gem::Package.new(file)
        rescue SystemCallError, Gem::Package::FormatError
          # ignore
        else
          tup = pkg.spec.name_tuple
          @specs[tup] = [File.expand_path(file), pkg]

          case type
          when :released
            unless pkg.spec.version.prerelease?
              names << pkg.spec.name_tuple
            end
          when :prerelease
            if pkg.spec.version.prerelease?
              names << pkg.spec.name_tuple
            end
          when :latest
            tup = pkg.spec.name_tuple

            cur = names.find {|x| x.name == tup.name }
            if !cur
              names << tup
            elsif cur.version < tup.version
              names.delete cur
              names << tup
            end
          else
            names << pkg.spec.name_tuple
          end
        end
      end

      names
    end
  end

  def find_gem(gem_name, version = Gem::Requirement.default, # :nodoc:
               prerelease = false)
    load_specs :complete

    found = []

    @specs.each do |n, data|
      if n.name == gem_name
        s = data[1].spec

        if version.satisfied_by?(s.version)
          if prerelease
            found << s
          elsif !s.version.prerelease? || version.prerelease?
            found << s
          end
        end
      end
    end

    found.max_by {|s| s.version }
  end

  def fetch_spec(name) # :nodoc:
    load_specs :complete

    if data = @specs[name]
      data.last.spec
    else
      raise Gem::Exception, "Unable to find spec for #{name.inspect}"
    end
  end

  def download(spec, cache_dir = nil) # :nodoc:
    load_specs :complete

    @specs.each do |name, data|
      return data[0] if data[1].spec == spec
    end

    raise Gem::Exception, "Unable to find file for '#{spec.full_name}'"
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[Local gems:', ']' do
      q.breakable
      q.seplist @specs.keys do |v|
        q.text v.full_name
      end
    end
  end
end
# frozen_string_literal: true
##
# A source representing a single .gem file.  This is used for installation of
# local gems.

class Gem::Source::SpecificFile < Gem::Source
  ##
  # The path to the gem for this specific file.

  attr_reader :path

  ##
  # Creates a new SpecificFile for the gem in +file+

  def initialize(file)
    @uri = nil
    @path = ::File.expand_path(file)

    @package = Gem::Package.new @path
    @spec = @package.spec
    @name = @spec.name_tuple
  end

  ##
  # The Gem::Specification extracted from this .gem.

  attr_reader :spec

  def load_specs(*a) # :nodoc:
    [@name]
  end

  def fetch_spec(name) # :nodoc:
    return @spec if name == @name
    raise Gem::Exception, "Unable to find '#{name}'"
    @spec
  end

  def download(spec, dir = nil) # :nodoc:
    return @path if spec == @spec
    raise Gem::Exception, "Unable to download '#{spec.full_name}'"
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[SpecificFile:', ']' do
      q.breakable
      q.text @path
    end
  end

  ##
  # Orders this source against +other+.
  #
  # If +other+ is a SpecificFile from a different gem name +nil+ is returned.
  #
  # If +other+ is a SpecificFile from the same gem name the versions are
  # compared using Gem::Version#<=>
  #
  # Otherwise Gem::Source#<=> is used.

  def <=>(other)
    case other
    when Gem::Source::SpecificFile then
      return nil if @spec.name != other.spec.name

      @spec.version <=> other.spec.version
    else
      super
    end
  end
end
# frozen_string_literal: true

##
# A git gem for use in a gem dependencies file.
#
# Example:
#
#   source =
#     Gem::Source::Git.new 'rake', 'git@example:rake.git', 'rake-10.1.0', false
#
#   source.specs

class Gem::Source::Git < Gem::Source
  ##
  # The name of the gem created by this git gem.

  attr_reader :name

  ##
  # The commit reference used for checking out this git gem.

  attr_reader :reference

  ##
  # When false the cache for this repository will not be updated.

  attr_accessor :remote

  ##
  # The git repository this gem is sourced from.

  attr_reader :repository

  ##
  # The directory for cache and git gem installation

  attr_accessor :root_dir

  ##
  # Does this repository need submodules checked out too?

  attr_reader :need_submodules

  ##
  # Creates a new git gem source for a gems from loaded from +repository+ at
  # the given +reference+.  The +name+ is only used to track the repository
  # back to a gem dependencies file, it has no real significance as a git
  # repository may contain multiple gems.  If +submodules+ is true, submodules
  # will be checked out when the gem is installed.

  def initialize(name, repository, reference, submodules = false)
    super repository

    @name            = name
    @repository      = repository
    @reference       = reference
    @need_submodules = submodules

    @remote   = true
    @root_dir = Gem.dir
    @git      = ENV['git'] || 'git'
  end

  def <=>(other)
    case other
    when Gem::Source::Git then
      0
    when Gem::Source::Vendor,
         Gem::Source::Lock then
      -1
    when Gem::Source then
      1
    else
      nil
    end
  end

  def ==(other) # :nodoc:
    super and
      @name            == other.name and
      @repository      == other.repository and
      @reference       == other.reference and
      @need_submodules == other.need_submodules
  end

  ##
  # Checks out the files for the repository into the install_dir.

  def checkout # :nodoc:
    cache

    return false unless File.exist? repo_cache_dir

    unless File.exist? install_dir
      system @git, 'clone', '--quiet', '--no-checkout',
             repo_cache_dir, install_dir
    end

    Dir.chdir install_dir do
      system @git, 'fetch', '--quiet', '--force', '--tags', install_dir

      success = system @git, 'reset', '--quiet', '--hard', rev_parse

      if @need_submodules
        _, status = Open3.capture2e(@git, 'submodule', 'update', '--quiet', '--init', '--recursive')

        success &&= status.success?
      end

      success
    end
  end

  ##
  # Creates a local cache repository for the git gem.

  def cache # :nodoc:
    return unless @remote

    if File.exist? repo_cache_dir
      Dir.chdir repo_cache_dir do
        system @git, 'fetch', '--quiet', '--force', '--tags',
               @repository, 'refs/heads/*:refs/heads/*'
      end
    else
      system @git, 'clone', '--quiet', '--bare', '--no-hardlinks',
             @repository, repo_cache_dir
    end
  end

  ##
  # Directory where git gems get unpacked and so-forth.

  def base_dir # :nodoc:
    File.join @root_dir, 'bundler'
  end

  ##
  # A short reference for use in git gem directories

  def dir_shortref # :nodoc:
    rev_parse[0..11]
  end

  ##
  # Nothing to download for git gems

  def download(full_spec, path) # :nodoc:
  end

  ##
  # The directory where the git gem will be installed.

  def install_dir # :nodoc:
    return unless File.exist? repo_cache_dir

    File.join base_dir, 'gems', "#{@name}-#{dir_shortref}"
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[Git: ', ']' do
      q.breakable
      q.text @repository

      q.breakable
      q.text @reference
    end
  end

  ##
  # The directory where the git gem's repository will be cached.

  def repo_cache_dir # :nodoc:
    File.join @root_dir, 'cache', 'bundler', 'git', "#{@name}-#{uri_hash}"
  end

  ##
  # Converts the git reference for the repository into a commit hash.

  def rev_parse # :nodoc:
    hash = nil

    Dir.chdir repo_cache_dir do
      hash = Gem::Util.popen(@git, 'rev-parse', @reference).strip
    end

    raise Gem::Exception,
          "unable to find reference #{@reference} in #{@repository}" unless
            $?.success?

    hash
  end

  ##
  # Loads all gemspecs in the repository

  def specs
    checkout

    return [] unless install_dir

    Dir.chdir install_dir do
      Dir['{,*,*/*}.gemspec'].map do |spec_file|
        directory = File.dirname spec_file
        file      = File.basename spec_file

        Dir.chdir directory do
          spec = Gem::Specification.load file
          if spec
            spec.base_dir = base_dir

            spec.extension_dir =
              File.join base_dir, 'extensions', Gem::Platform.local.to_s,
                Gem.extension_api_version, "#{name}-#{dir_shortref}"

            spec.full_gem_path = File.dirname spec.loaded_from if spec
          end
          spec
        end
      end.compact
    end
  end

  ##
  # A hash for the git gem based on the git repository URI.

  def uri_hash # :nodoc:
    require_relative '../openssl'

    normalized =
      if @repository =~ %r{^\w+://(\w+@)?}
        uri = URI(@repository).normalize.to_s.sub %r{/$},''
        uri.sub(/\A(\w+)/) { $1.downcase }
      else
        @repository
      end

    OpenSSL::Digest::SHA1.hexdigest normalized
  end
end
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require_relative 'package'
require_relative 'installer'

##
# Validator performs various gem file and gem database validation

class Gem::Validator
  include Gem::UserInteraction

  def initialize # :nodoc:
    require 'find'
  end

  private

  def find_files_for_gem(gem_directory)
    installed_files = []

    Find.find gem_directory do |file_name|
      fn = file_name[gem_directory.size..file_name.size - 1].sub(/^\//, "")
      installed_files << fn unless
        fn =~ /CVS/ || fn.empty? || File.directory?(file_name)
    end

    installed_files
  end

  public

  ##
  # Describes a problem with a file in a gem.

  ErrorData = Struct.new :path, :problem do
    def <=>(other) # :nodoc:
      return nil unless self.class === other

      [path, problem] <=> [other.path, other.problem]
    end
  end

  ##
  # Checks the gem directory for the following potential
  # inconsistencies/problems:
  #
  # * Checksum gem itself
  # * For each file in each gem, check consistency of installed versions
  # * Check for files that aren't part of the gem but are in the gems directory
  # * 1 cache - 1 spec - 1 directory.
  #
  # returns a hash of ErrorData objects, keyed on the problem gem's name.
  #--
  # TODO needs further cleanup

  def alien(gems=[])
    errors = Hash.new {|h,k| h[k] = {} }

    Gem::Specification.each do |spec|
      next unless gems.include? spec.name unless gems.empty?
      next if spec.default_gem?

      gem_name      = spec.file_name
      gem_path      = spec.cache_file
      spec_path     = spec.spec_file
      gem_directory = spec.full_gem_path

      unless File.directory? gem_directory
        errors[gem_name][spec.full_name] =
          "Gem registered but doesn't exist at #{gem_directory}"
        next
      end

      unless File.exist? spec_path
        errors[gem_name][spec_path] = "Spec file missing for installed gem"
      end

      begin
        unless File.readable?(gem_path)
          raise Gem::VerificationError, "missing gem file #{gem_path}"
        end

        good, gone, unreadable = nil, nil, nil, nil

        File.open gem_path, Gem.binary_mode do |file|
          package = Gem::Package.new gem_path

          good, gone = package.contents.partition do |file_name|
            File.exist? File.join(gem_directory, file_name)
          end

          gone.sort.each do |path|
            errors[gem_name][path] = "Missing file"
          end

          good, unreadable = good.partition do |file_name|
            File.readable? File.join(gem_directory, file_name)
          end

          unreadable.sort.each do |path|
            errors[gem_name][path] = "Unreadable file"
          end

          good.each do |entry, data|
            begin
              next unless data # HACK `gem check -a mkrf`

              source = File.join gem_directory, entry['path']

              File.open source, Gem.binary_mode do |f|
                unless f.read == data
                  errors[gem_name][entry['path']] = "Modified from original"
                end
              end
            end
          end
        end

        installed_files = find_files_for_gem(gem_directory)
        extras = installed_files - good - unreadable

        extras.each do |extra|
          errors[gem_name][extra] = "Extra file"
        end
      rescue Gem::VerificationError => e
        errors[gem_name][gem_path] = e.message
      end
    end

    errors.each do |name, subhash|
      errors[name] = subhash.map do |path, msg|
        ErrorData.new path, msg
      end.sort
    end

    errors
  end
end
# frozen_string_literal: true

class Gem::Ext::CmakeBuilder < Gem::Ext::Builder
  def self.build(extension, dest_path, results, args=[], lib_dir=nil, cmake_dir=Dir.pwd)
    unless File.exist?(File.join(cmake_dir, 'Makefile'))
      require_relative '../command'
      cmd = ["cmake", ".", "-DCMAKE_INSTALL_PREFIX=#{dest_path}", *Gem::Command.build_args]

      run cmd, results, class_name, cmake_dir
    end

    make dest_path, results, cmake_dir

    results
  end
end
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

class Gem::Ext::ExtConfBuilder < Gem::Ext::Builder
  def self.build(extension, dest_path, results, args=[], lib_dir=nil, extension_dir=Dir.pwd)
    require 'fileutils'
    require 'tempfile'

    tmp_dest = Dir.mktmpdir(".gem.", extension_dir)

    # Some versions of `mktmpdir` return absolute paths, which will break make
    # if the paths contain spaces. However, on Ruby 1.9.x on Windows, relative
    # paths cause all C extension builds to fail.
    #
    # As such, we convert to a relative path unless we are using Ruby 1.9.x on
    # Windows. This means that when using Ruby 1.9.x on Windows, paths with
    # spaces do not work.
    #
    # Details: https://github.com/rubygems/rubygems/issues/977#issuecomment-171544940
    tmp_dest_relative = get_relative_path(tmp_dest.clone, extension_dir)

    Tempfile.open %w[siteconf .rb], extension_dir do |siteconf|
      siteconf.puts "require 'rbconfig'"
      siteconf.puts "dest_path = #{tmp_dest_relative.dump}"
      %w[sitearchdir sitelibdir].each do |dir|
        siteconf.puts "RbConfig::MAKEFILE_CONFIG['#{dir}'] = dest_path"
        siteconf.puts "RbConfig::CONFIG['#{dir}'] = dest_path"
      end

      siteconf.close

      destdir = ENV["DESTDIR"]

      begin
        # workaround for https://github.com/oracle/truffleruby/issues/2115
        siteconf_path = RUBY_ENGINE == "truffleruby" ? siteconf.path.dup : siteconf.path
        require "shellwords"
        cmd = Gem.ruby.shellsplit << "-I" << File.expand_path("../../..", __FILE__) <<
              "-r" << get_relative_path(siteconf_path, extension_dir) << File.basename(extension)
        cmd.push(*args)

        begin
          run(cmd, results, class_name, extension_dir) do |s, r|
            mkmf_log = File.join(extension_dir, 'mkmf.log')
            if File.exist? mkmf_log
              unless s.success?
                r << "To see why this extension failed to compile, please check" \
                  " the mkmf.log which can be found here:\n"
                r << "  " + File.join(dest_path, 'mkmf.log') + "\n"
              end
              FileUtils.mv mkmf_log, dest_path
            end
          end
          siteconf.unlink
        end

        ENV["DESTDIR"] = nil

        make dest_path, results, extension_dir

        if tmp_dest_relative
          full_tmp_dest = File.join(extension_dir, tmp_dest_relative)

          # TODO remove in RubyGems 3
          if Gem.install_extension_in_lib and lib_dir
            FileUtils.mkdir_p lib_dir
            entries = Dir.entries(full_tmp_dest) - %w[. ..]
            entries = entries.map {|entry| File.join full_tmp_dest, entry }
            FileUtils.cp_r entries, lib_dir, :remove_destination => true
          end

          FileUtils::Entry_.new(full_tmp_dest).traverse do |ent|
            destent = ent.class.new(dest_path, ent.rel)
            destent.exist? or FileUtils.mv(ent.path, destent.path)
          end
        end
      ensure
        ENV["DESTDIR"] = destdir
        siteconf.close!
      end
    end

    results
  ensure
    FileUtils.rm_rf tmp_dest if tmp_dest
  end

  private

  def self.get_relative_path(path, base)
    path[0..base.length - 1] = '.' if path.start_with?(base)
    path
  end
end
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require_relative '../user_interaction'

class Gem::Ext::Builder
  include Gem::UserInteraction

  attr_accessor :build_args # :nodoc:

  def self.class_name
    name =~ /Ext::(.*)Builder/
    $1.downcase
  end

  def self.make(dest_path, results, make_dir = Dir.pwd)
    unless File.exist? File.join(make_dir, 'Makefile')
      raise Gem::InstallError, 'Makefile not found'
    end

    # try to find make program from Ruby configure arguments first
    RbConfig::CONFIG['configure_args'] =~ /with-make-prog\=(\w+)/
    make_program_name = ENV['MAKE'] || ENV['make'] || $1
    unless make_program_name
      make_program_name = (/mswin/ =~ RUBY_PLATFORM) ? 'nmake' : 'make'
    end
    make_program = Shellwords.split(make_program_name)

    # The installation of the bundled gems is failed when DESTDIR is empty in mswin platform.
    destdir = (/\bnmake/i !~ make_program_name || ENV['DESTDIR'] && ENV['DESTDIR'] != "") ? 'DESTDIR=%s' % ENV['DESTDIR'] : ''

    ['clean', '', 'install'].each do |target|
      # Pass DESTDIR via command line to override what's in MAKEFLAGS
      cmd = [
        *make_program,
        destdir,
        target,
      ].reject(&:empty?)
      begin
        run(cmd, results, "make #{target}".rstrip, make_dir)
      rescue Gem::InstallError
        raise unless target == 'clean' # ignore clean failure
      end
    end
  end

  def self.run(command, results, command_name = nil, dir = Dir.pwd)
    verbose = Gem.configuration.really_verbose

    begin
      rubygems_gemdeps, ENV['RUBYGEMS_GEMDEPS'] = ENV['RUBYGEMS_GEMDEPS'], nil
      if verbose
        puts("current directory: #{dir}")
        p(command)
      end
      results << "current directory: #{dir}"
      require "shellwords"
      results << command.shelljoin

      require "open3"
      # Set $SOURCE_DATE_EPOCH for the subprocess.
      env = {'SOURCE_DATE_EPOCH' => Gem.source_date_epoch_string}
      output, status = Open3.capture2e(env, *command, :chdir => dir)
      if verbose
        puts output
      else
        results << output
      end
    rescue => error
      raise Gem::InstallError, "#{command_name || class_name} failed#{error.message}"
    ensure
      ENV['RUBYGEMS_GEMDEPS'] = rubygems_gemdeps
    end

    unless status.success?
      results << "Building has failed. See above output for more information on the failure." if verbose
    end

    yield(status, results) if block_given?

    unless status.success?
      exit_reason =
        if status.exited?
          ", exit code #{status.exitstatus}"
        elsif status.signaled?
          ", uncaught signal #{status.termsig}"
        end

      raise Gem::InstallError, "#{command_name || class_name} failed#{exit_reason}"
    end
  end

  ##
  # Creates a new extension builder for +spec+.  If the +spec+ does not yet
  # have build arguments, saved, set +build_args+ which is an ARGV-style
  # array.

  def initialize(spec, build_args = spec.build_args)
    @spec       = spec
    @build_args = build_args
    @gem_dir    = spec.full_gem_path

    @ran_rake = false
  end

  ##
  # Chooses the extension builder class for +extension+

  def builder_for(extension) # :nodoc:
    case extension
    when /extconf/ then
      Gem::Ext::ExtConfBuilder
    when /configure/ then
      Gem::Ext::ConfigureBuilder
    when /rakefile/i, /mkrf_conf/i then
      @ran_rake = true
      Gem::Ext::RakeBuilder
    when /CMakeLists.txt/ then
      Gem::Ext::CmakeBuilder
    else
      build_error("No builder for extension '#{extension}'")
    end
  end

  ##
  # Logs the build +output+, then raises Gem::Ext::BuildError.

  def build_error(output, backtrace = nil) # :nodoc:
    gem_make_out = write_gem_make_out output

    message = <<-EOF
ERROR: Failed to build gem native extension.

    #{output}

Gem files will remain installed in #{@gem_dir} for inspection.
Results logged to #{gem_make_out}
EOF

    raise Gem::Ext::BuildError, message, backtrace
  end

  def build_extension(extension, dest_path) # :nodoc:
    results = []

    builder = builder_for(extension)

    extension_dir =
      File.expand_path File.join(@gem_dir, File.dirname(extension))
    lib_dir = File.join @spec.full_gem_path, @spec.raw_require_paths.first

    begin
      FileUtils.mkdir_p dest_path

      results = builder.build(extension, dest_path,
                              results, @build_args, lib_dir, extension_dir)

      verbose { results.join("\n") }

      write_gem_make_out results.join "\n"
    rescue => e
      results << e.message
      build_error(results.join("\n"), $@)
    end
  end

  ##
  # Builds extensions.  Valid types of extensions are extconf.rb files,
  # configure scripts and rakefiles or mkrf_conf files.

  def build_extensions
    return if @spec.extensions.empty?

    if @build_args.empty?
      say "Building native extensions. This could take a while..."
    else
      say "Building native extensions with: '#{@build_args.join ' '}'"
      say "This could take a while..."
    end

    dest_path = @spec.extension_dir

    require "fileutils"
    FileUtils.rm_f @spec.gem_build_complete_path

    @spec.extensions.each do |extension|
      break if @ran_rake

      build_extension extension, dest_path
    end

    FileUtils.touch @spec.gem_build_complete_path
  end

  ##
  # Writes +output+ to gem_make.out in the extension install directory.

  def write_gem_make_out(output) # :nodoc:
    destination = File.join @spec.extension_dir, 'gem_make.out'

    FileUtils.mkdir_p @spec.extension_dir

    File.open destination, 'wb' do |io|
      io.puts output
    end

    destination
  end
end
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

class Gem::Ext::ConfigureBuilder < Gem::Ext::Builder
  def self.build(extension, dest_path, results, args=[], lib_dir=nil, configure_dir=Dir.pwd)
    unless File.exist?(File.join(configure_dir, 'Makefile'))
      cmd = ["sh", "./configure", "--prefix=#{dest_path}", *args]

      run cmd, results, class_name, configure_dir
    end

    make dest_path, results, configure_dir

    results
  end
end
# frozen_string_literal: true
##
# Raised when there is an error while building extensions.

require_relative '../exceptions'

class Gem::Ext::BuildError < Gem::InstallError
end
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

class Gem::Ext::RakeBuilder < Gem::Ext::Builder
  def self.build(extension, dest_path, results, args=[], lib_dir=nil, extension_dir=Dir.pwd)
    if File.basename(extension) =~ /mkrf_conf/i
      run([Gem.ruby, File.basename(extension), *args], results, class_name, extension_dir)
    end

    rake = ENV['rake']

    if rake
      require "shellwords"
      rake = rake.shellsplit
    else
      begin
        rake = [Gem.ruby, "-I#{File.expand_path("../..", __dir__)}", "-rrubygems", Gem.bin_path('rake', 'rake')]
      rescue Gem::Exception
        rake = [Gem.default_exec_format % 'rake']
      end
    end

    rake_args = ["RUBYARCHDIR=#{dest_path}", "RUBYLIBDIR=#{dest_path}", *args]
    run(rake + rake_args, results, class_name, extension_dir)

    results
  end
end
# frozen_string_literal: true
##
# Supports reading and writing gems from/to a generic IO object.  This is
# useful for other applications built on top of rubygems, such as
# rubygems.org.
#
# This is a private class, do not depend on it directly. Instead, pass an IO
# object to `Gem::Package.new`.

class Gem::Package::IOSource < Gem::Package::Source # :nodoc: all
  attr_reader :io

  def initialize(io)
    @io = io
  end

  def start
    @start ||= begin
      if io.pos > 0
        raise Gem::Package::Error, "Cannot read start unless IO is at start"
      end

      value = io.read 20
      io.rewind
      value
    end
  end

  def present?
    true
  end

  def with_read_io
    yield io
  ensure
    io.rewind
  end

  def with_write_io
    yield io
  ensure
    io.rewind
  end

  def path
  end
end
# frozen_string_literal: true
class Gem::Package::Source # :nodoc:
end
# frozen_string_literal: true
#--
# Copyright (C) 2004 Mauricio Julio Fernández Pradier
# See LICENSE.txt for additional licensing information.
#++

##
# TarReader reads tar files and allows iteration over their items

class Gem::Package::TarReader
  include Enumerable

  ##
  # Raised if the tar IO is not seekable

  class UnexpectedEOF < StandardError; end

  ##
  # Creates a new TarReader on +io+ and yields it to the block, if given.

  def self.new(io)
    reader = super

    return reader unless block_given?

    begin
      yield reader
    ensure
      reader.close
    end

    nil
  end

  ##
  # Creates a new tar file reader on +io+ which needs to respond to #pos,
  # #eof?, #read, #getc and #pos=

  def initialize(io)
    @io = io
    @init_pos = io.pos
  end

  ##
  # Close the tar file

  def close
  end

  ##
  # Iterates over files in the tarball yielding each entry

  def each
    return enum_for __method__ unless block_given?

    use_seek = @io.respond_to?(:seek)

    until @io.eof? do
      header = Gem::Package::TarHeader.from @io
      return if header.empty?

      entry = Gem::Package::TarReader::Entry.new header, @io
      size = entry.header.size

      yield entry

      skip = (512 - (size % 512)) % 512
      pending = size - entry.bytes_read

      if use_seek
        begin
          # avoid reading if the @io supports seeking
          @io.seek pending, IO::SEEK_CUR
          pending = 0
        rescue Errno::EINVAL
        end
      end

      # if seeking isn't supported or failed
      while pending > 0 do
        bytes_read = @io.read([pending, 4096].min).size
        raise UnexpectedEOF if @io.eof?
        pending -= bytes_read
      end

      @io.read skip # discard trailing zeros

      # make sure nobody can use #read, #getc or #rewind anymore
      entry.close
    end
  end

  alias each_entry each

  ##
  # NOTE: Do not call #rewind during #each

  def rewind
    if @init_pos == 0
      @io.rewind
    else
      @io.pos = @init_pos
    end
  end

  ##
  # Seeks through the tar file until it finds the +entry+ with +name+ and
  # yields it.  Rewinds the tar file to the beginning when the block
  # terminates.

  def seek(name) # :yields: entry
    found = find do |entry|
      entry.full_name == name
    end

    return unless found

    return yield found
  ensure
    rewind
  end
end

require_relative 'tar_reader/entry'
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

##
# The format class knows the guts of the ancient .gem file format and provides
# the capability to read such ancient gems.
#
# Please pretend this doesn't exist.

class Gem::Package::Old < Gem::Package
  undef_method :spec=

  ##
  # Creates a new old-format package reader for +gem+.  Old-format packages
  # cannot be written.

  def initialize(gem, security_policy)
    require 'fileutils'
    require 'zlib'
    Gem.load_yaml

    @contents        = nil
    @gem             = gem
    @security_policy = security_policy
    @spec            = nil
  end

  ##
  # A list of file names contained in this gem

  def contents
    verify

    return @contents if @contents

    @gem.with_read_io do |io|
      read_until_dashes io # spec
      header = file_list io

      @contents = header.map {|file| file['path'] }
    end
  end

  ##
  # Extracts the files in this package into +destination_dir+

  def extract_files(destination_dir)
    verify

    errstr = "Error reading files from gem"

    @gem.with_read_io do |io|
      read_until_dashes io # spec
      header = file_list io
      raise Gem::Exception, errstr unless header

      header.each do |entry|
        full_name = entry['path']

        destination = install_location full_name, destination_dir

        file_data = String.new

        read_until_dashes io do |line|
          file_data << line
        end

        file_data = file_data.strip.unpack("m")[0]
        file_data = Zlib::Inflate.inflate file_data

        raise Gem::Package::FormatError, "#{full_name} in #{@gem} is corrupt" if
          file_data.length != entry['size'].to_i

        FileUtils.rm_rf destination

        FileUtils.mkdir_p File.dirname(destination), :mode => dir_mode && 0755

        File.open destination, 'wb', file_mode(entry['mode']) do |out|
          out.write file_data
        end

        verbose destination
      end
    end
  rescue Zlib::DataError
    raise Gem::Exception, errstr
  end

  ##
  # Reads the file list section from the old-format gem +io+

  def file_list(io) # :nodoc:
    header = String.new

    read_until_dashes io do |line|
      header << line
    end

    Gem::SafeYAML.safe_load header
  end

  ##
  # Reads lines until a "---" separator is found

  def read_until_dashes(io) # :nodoc:
    while (line = io.gets) && line.chomp.strip != "---" do
      yield line if block_given?
    end
  end

  ##
  # Skips the Ruby self-install header in +io+.

  def skip_ruby(io) # :nodoc:
    loop do
      line = io.gets

      return if line.chomp == '__END__'
      break unless line
    end

    raise Gem::Exception, "Failed to find end of Ruby script while reading gem"
  end

  ##
  # The specification for this gem

  def spec
    verify

    return @spec if @spec

    yaml = String.new

    @gem.with_read_io do |io|
      skip_ruby io
      read_until_dashes io do |line|
        yaml << line
      end
    end

    begin
      @spec = Gem::Specification.from_yaml yaml
    rescue YAML::SyntaxError
      raise Gem::Exception, "Failed to parse gem specification out of gem file"
    end
  rescue ArgumentError
    raise Gem::Exception, "Failed to parse gem specification out of gem file"
  end

  ##
  # Raises an exception if a security policy that verifies data is active.
  # Old format gems cannot be verified as signed.

  def verify
    return true unless @security_policy

    raise Gem::Security::Exception,
          'old format gems do not contain signatures and cannot be verified' if
      @security_policy.verify_data

    true
  end
end
# frozen_string_literal: true
#--
# Copyright (C) 2004 Mauricio Julio Fernández Pradier
# See LICENSE.txt for additional licensing information.
#++

##
#--
# struct tarfile_entry_posix {
#   char name[100];     # ASCII + (Z unless filled)
#   char mode[8];       # 0 padded, octal, null
#   char uid[8];        # ditto
#   char gid[8];        # ditto
#   char size[12];      # 0 padded, octal, null
#   char mtime[12];     # 0 padded, octal, null
#   char checksum[8];   # 0 padded, octal, null, space
#   char typeflag[1];   # file: "0"  dir: "5"
#   char linkname[100]; # ASCII + (Z unless filled)
#   char magic[6];      # "ustar\0"
#   char version[2];    # "00"
#   char uname[32];     # ASCIIZ
#   char gname[32];     # ASCIIZ
#   char devmajor[8];   # 0 padded, octal, null
#   char devminor[8];   # o padded, octal, null
#   char prefix[155];   # ASCII + (Z unless filled)
# };
#++
# A header for a tar file

class Gem::Package::TarHeader
  ##
  # Fields in the tar header

  FIELDS = [
    :checksum,
    :devmajor,
    :devminor,
    :gid,
    :gname,
    :linkname,
    :magic,
    :mode,
    :mtime,
    :name,
    :prefix,
    :size,
    :typeflag,
    :uid,
    :uname,
    :version,
  ].freeze

  ##
  # Pack format for a tar header

  PACK_FORMAT = 'a100' + # name
                'a8'   + # mode
                'a8'   + # uid
                'a8'   + # gid
                'a12'  + # size
                'a12'  + # mtime
                'a7a'  + # chksum
                'a'    + # typeflag
                'a100' + # linkname
                'a6'   + # magic
                'a2'   + # version
                'a32'  + # uname
                'a32'  + # gname
                'a8'   + # devmajor
                'a8'   + # devminor
                'a155'   # prefix

  ##
  # Unpack format for a tar header

  UNPACK_FORMAT = 'A100' + # name
                  'A8'   + # mode
                  'A8'   + # uid
                  'A8'   + # gid
                  'A12'  + # size
                  'A12'  + # mtime
                  'A8'   + # checksum
                  'A'    + # typeflag
                  'A100' + # linkname
                  'A6'   + # magic
                  'A2'   + # version
                  'A32'  + # uname
                  'A32'  + # gname
                  'A8'   + # devmajor
                  'A8'   + # devminor
                  'A155'   # prefix

  attr_reader(*FIELDS)

  EMPTY_HEADER = ("\0" * 512).freeze # :nodoc:

  ##
  # Creates a tar header from IO +stream+

  def self.from(stream)
    header = stream.read 512
    empty = (EMPTY_HEADER == header)

    fields = header.unpack UNPACK_FORMAT

    new :name     => fields.shift,
        :mode     => strict_oct(fields.shift),
        :uid      => oct_or_256based(fields.shift),
        :gid      => oct_or_256based(fields.shift),
        :size     => strict_oct(fields.shift),
        :mtime    => strict_oct(fields.shift),
        :checksum => strict_oct(fields.shift),
        :typeflag => fields.shift,
        :linkname => fields.shift,
        :magic    => fields.shift,
        :version  => strict_oct(fields.shift),
        :uname    => fields.shift,
        :gname    => fields.shift,
        :devmajor => strict_oct(fields.shift),
        :devminor => strict_oct(fields.shift),
        :prefix   => fields.shift,

        :empty => empty
  end

  def self.strict_oct(str)
    return str.strip.oct if str.strip =~ /\A[0-7]*\z/

    raise ArgumentError, "#{str.inspect} is not an octal string"
  end

  def self.oct_or_256based(str)
    # \x80 flags a positive 256-based number
    # \ff flags a negative 256-based number
    # In case we have a match, parse it as a signed binary value
    # in big-endian order, except that the high-order bit is ignored.
    return str.unpack('N2').last if str =~ /\A[\x80\xff]/n
    strict_oct(str)
  end

  ##
  # Creates a new TarHeader using +vals+

  def initialize(vals)
    unless vals[:name] && vals[:size] && vals[:prefix] && vals[:mode]
      raise ArgumentError, ":name, :size, :prefix and :mode required"
    end

    vals[:uid] ||= 0
    vals[:gid] ||= 0
    vals[:mtime] ||= 0
    vals[:checksum] ||= ""
    vals[:typeflag] = "0" if vals[:typeflag].nil? || vals[:typeflag].empty?
    vals[:magic] ||= "ustar"
    vals[:version] ||= "00"
    vals[:uname] ||= "wheel"
    vals[:gname] ||= "wheel"
    vals[:devmajor] ||= 0
    vals[:devminor] ||= 0

    FIELDS.each do |name|
      instance_variable_set "@#{name}", vals[name]
    end

    @empty = vals[:empty]
  end

  ##
  # Is the tar entry empty?

  def empty?
    @empty
  end

  def ==(other) # :nodoc:
    self.class === other and
    @checksum == other.checksum and
    @devmajor == other.devmajor and
    @devminor == other.devminor and
    @gid      == other.gid      and
    @gname    == other.gname    and
    @linkname == other.linkname and
    @magic    == other.magic    and
    @mode     == other.mode     and
    @mtime    == other.mtime    and
    @name     == other.name     and
    @prefix   == other.prefix   and
    @size     == other.size     and
    @typeflag == other.typeflag and
    @uid      == other.uid      and
    @uname    == other.uname    and
    @version  == other.version
  end

  def to_s # :nodoc:
    update_checksum
    header
  end

  ##
  # Updates the TarHeader's checksum

  def update_checksum
    header = header " " * 8
    @checksum = oct calculate_checksum(header), 6
  end

  private

  def calculate_checksum(header)
    header.unpack("C*").inject {|a, b| a + b }
  end

  def header(checksum = @checksum)
    header = [
      name,
      oct(mode, 7),
      oct(uid, 7),
      oct(gid, 7),
      oct(size, 11),
      oct(mtime, 11),
      checksum,
      " ",
      typeflag,
      linkname,
      magic,
      oct(version, 2),
      uname,
      gname,
      oct(devmajor, 7),
      oct(devminor, 7),
      prefix,
    ]

    header = header.pack PACK_FORMAT

    header << ("\0" * ((512 - header.size) % 512))
  end

  def oct(num, len)
    "%0#{len}o" % num
  end
end
# frozen_string_literal: true
#--
# Copyright (C) 2004 Mauricio Julio Fernández Pradier
# See LICENSE.txt for additional licensing information.
#++

##
# Allows writing of tar files

class Gem::Package::TarWriter
  class FileOverflow < StandardError; end

  ##
  # IO wrapper that allows writing a limited amount of data

  class BoundedStream
    ##
    # Maximum number of bytes that can be written

    attr_reader :limit

    ##
    # Number of bytes written

    attr_reader :written

    ##
    # Wraps +io+ and allows up to +limit+ bytes to be written

    def initialize(io, limit)
      @io = io
      @limit = limit
      @written = 0
    end

    ##
    # Writes +data+ onto the IO, raising a FileOverflow exception if the
    # number of bytes will be more than #limit

    def write(data)
      if data.bytesize + @written > @limit
        raise FileOverflow, "You tried to feed more data than fits in the file."
      end
      @io.write data
      @written += data.bytesize
      data.bytesize
    end
  end

  ##
  # IO wrapper that provides only #write

  class RestrictedStream
    ##
    # Creates a new RestrictedStream wrapping +io+

    def initialize(io)
      @io = io
    end

    ##
    # Writes +data+ onto the IO

    def write(data)
      @io.write data
    end
  end

  ##
  # Creates a new TarWriter, yielding it if a block is given

  def self.new(io)
    writer = super

    return writer unless block_given?

    begin
      yield writer
    ensure
      writer.close
    end

    nil
  end

  ##
  # Creates a new TarWriter that will write to +io+

  def initialize(io)
    @io = io
    @closed = false
  end

  ##
  # Adds file +name+ with permissions +mode+, and yields an IO for writing the
  # file to

  def add_file(name, mode) # :yields: io
    check_closed

    name, prefix = split_name name

    init_pos = @io.pos
    @io.write Gem::Package::TarHeader::EMPTY_HEADER # placeholder for the header

    yield RestrictedStream.new(@io) if block_given?

    size = @io.pos - init_pos - 512

    remainder = (512 - (size % 512)) % 512
    @io.write "\0" * remainder

    final_pos = @io.pos
    @io.pos = init_pos

    header = Gem::Package::TarHeader.new :name => name, :mode => mode,
                                         :size => size, :prefix => prefix,
                                         :mtime => Gem.source_date_epoch

    @io.write header
    @io.pos = final_pos

    self
  end

  ##
  # Adds +name+ with permissions +mode+ to the tar, yielding +io+ for writing
  # the file.  The +digest_algorithm+ is written to a read-only +name+.sum
  # file following the given file contents containing the digest name and
  # hexdigest separated by a tab.
  #
  # The created digest object is returned.

  def add_file_digest(name, mode, digest_algorithms) # :yields: io
    digests = digest_algorithms.map do |digest_algorithm|
      digest = digest_algorithm.new
      digest_name =
        if digest.respond_to? :name
          digest.name
        else
          digest_algorithm.class.name[/::([^:]+)\z/, 1]
        end

      [digest_name, digest]
    end

    digests = Hash[*digests.flatten]

    add_file name, mode do |io|
      Gem::Package::DigestIO.wrap io, digests do |digest_io|
        yield digest_io
      end
    end

    digests
  end

  ##
  # Adds +name+ with permissions +mode+ to the tar, yielding +io+ for writing
  # the file.  The +signer+ is used to add a digest file using its
  # digest_algorithm per add_file_digest and a cryptographic signature in
  # +name+.sig.  If the signer has no key only the checksum file is added.
  #
  # Returns the digest.

  def add_file_signed(name, mode, signer)
    digest_algorithms = [
      signer.digest_algorithm,
      Gem::Security.create_digest('SHA512'),
    ].compact.uniq

    digests = add_file_digest name, mode, digest_algorithms do |io|
      yield io
    end

    signature_digest = digests.values.compact.find do |digest|
      digest_name =
        if digest.respond_to? :name
          digest.name
        else
          digest.class.name[/::([^:]+)\z/, 1]
        end

      digest_name == signer.digest_name
    end

    raise "no #{signer.digest_name} in #{digests.values.compact}" unless signature_digest

    if signer.key
      signature = signer.sign signature_digest.digest

      add_file_simple "#{name}.sig", 0444, signature.length do |io|
        io.write signature
      end
    end

    digests
  end

  ##
  # Add file +name+ with permissions +mode+ +size+ bytes long.  Yields an IO
  # to write the file to.

  def add_file_simple(name, mode, size) # :yields: io
    check_closed

    name, prefix = split_name name

    header = Gem::Package::TarHeader.new(:name => name, :mode => mode,
                                         :size => size, :prefix => prefix,
                                         :mtime => Gem.source_date_epoch).to_s

    @io.write header
    os = BoundedStream.new @io, size

    yield os if block_given?

    min_padding = size - os.written
    @io.write("\0" * min_padding)

    remainder = (512 - (size % 512)) % 512
    @io.write("\0" * remainder)

    self
  end

  ##
  # Adds symlink +name+ with permissions +mode+, linking to +target+.

  def add_symlink(name, target, mode)
    check_closed

    name, prefix = split_name name

    header = Gem::Package::TarHeader.new(:name => name, :mode => mode,
                                         :size => 0, :typeflag => "2",
                                         :linkname => target,
                                         :prefix => prefix,
                                         :mtime => Gem.source_date_epoch).to_s

    @io.write header

    self
  end

  ##
  # Raises IOError if the TarWriter is closed

  def check_closed
    raise IOError, "closed #{self.class}" if closed?
  end

  ##
  # Closes the TarWriter

  def close
    check_closed

    @io.write "\0" * 1024
    flush

    @closed = true
  end

  ##
  # Is the TarWriter closed?

  def closed?
    @closed
  end

  ##
  # Flushes the TarWriter's IO

  def flush
    check_closed

    @io.flush if @io.respond_to? :flush
  end

  ##
  # Creates a new directory in the tar file +name+ with +mode+

  def mkdir(name, mode)
    check_closed

    name, prefix = split_name(name)

    header = Gem::Package::TarHeader.new :name => name, :mode => mode,
                                         :typeflag => "5", :size => 0,
                                         :prefix => prefix,
                                         :mtime => Gem.source_date_epoch

    @io.write header

    self
  end

  ##
  # Splits +name+ into a name and prefix that can fit in the TarHeader

  def split_name(name) # :nodoc:
    if name.bytesize > 256
      raise Gem::Package::TooLongFileName.new("File \"#{name}\" has a too long path (should be 256 or less)")
    end

    prefix = ''
    if name.bytesize > 100
      parts = name.split('/', -1) # parts are never empty here
      name = parts.pop            # initially empty for names with a trailing slash ("foo/.../bar/")
      prefix = parts.join('/')    # if empty, then it's impossible to split (parts is empty too)
      while !parts.empty? && (prefix.bytesize > 155 || name.empty?)
        name = parts.pop + '/' + name
        prefix = parts.join('/')
      end

      if name.bytesize > 100 or prefix.empty?
        raise Gem::Package::TooLongFileName.new("File \"#{prefix}/#{name}\" has a too long name (should be 100 or less)")
      end

      if prefix.bytesize > 155
        raise Gem::Package::TooLongFileName.new("File \"#{prefix}/#{name}\" has a too long base path (should be 155 or less)")
      end
    end

    return name, prefix
  end
end
# frozen_string_literal: true
#++
# Copyright (C) 2004 Mauricio Julio Fernández Pradier
# See LICENSE.txt for additional licensing information.
#--

##
# Class for reading entries out of a tar file

class Gem::Package::TarReader::Entry
  ##
  # Header for this tar entry

  attr_reader :header

  ##
  # Creates a new tar entry for +header+ that will be read from +io+

  def initialize(header, io)
    @closed = false
    @header = header
    @io = io
    @orig_pos = @io.pos
    @read = 0
  end

  def check_closed # :nodoc:
    raise IOError, "closed #{self.class}" if closed?
  end

  ##
  # Number of bytes read out of the tar entry

  def bytes_read
    @read
  end

  ##
  # Closes the tar entry

  def close
    @closed = true
  end

  ##
  # Is the tar entry closed?

  def closed?
    @closed
  end

  ##
  # Are we at the end of the tar entry?

  def eof?
    check_closed

    @read >= @header.size
  end

  ##
  # Full name of the tar entry

  def full_name
    if @header.prefix != ""
      File.join @header.prefix, @header.name
    else
      @header.name
    end
  rescue ArgumentError => e
    raise unless e.message == 'string contains null byte'
    raise Gem::Package::TarInvalidError,
          'tar is corrupt, name contains null byte'
  end

  ##
  # Read one byte from the tar entry

  def getc
    check_closed

    return nil if @read >= @header.size

    ret = @io.getc
    @read += 1 if ret

    ret
  end

  ##
  # Is this tar entry a directory?

  def directory?
    @header.typeflag == "5"
  end

  ##
  # Is this tar entry a file?

  def file?
    @header.typeflag == "0"
  end

  ##
  # Is this tar entry a symlink?

  def symlink?
    @header.typeflag == "2"
  end

  ##
  # The position in the tar entry

  def pos
    check_closed

    bytes_read
  end

  def size
    @header.size
  end

  alias length size

  ##
  # Reads +len+ bytes from the tar file entry, or the rest of the entry if
  # nil

  def read(len = nil)
    check_closed

    return nil if @read >= @header.size

    len ||= @header.size - @read
    max_read = [len, @header.size - @read].min

    ret = @io.read max_read
    @read += ret.size

    ret
  end

  def readpartial(maxlen = nil, outbuf = "".b)
    check_closed

    raise EOFError if @read >= @header.size

    maxlen ||= @header.size - @read
    max_read = [maxlen, @header.size - @read].min

    @io.readpartial(max_read, outbuf)
    @read += outbuf.size

    outbuf
  end

  ##
  # Rewinds to the beginning of the tar file entry

  def rewind
    check_closed

    @io.pos = @orig_pos
    @read = 0
  end
end
# frozen_string_literal: true
##
# IO wrapper that creates digests of contents written to the IO it wraps.

class Gem::Package::DigestIO
  ##
  # Collected digests for wrapped writes.
  #
  #   {
  #     'SHA1'   => #<OpenSSL::Digest: [...]>,
  #     'SHA512' => #<OpenSSL::Digest: [...]>,
  #   }

  attr_reader :digests

  ##
  # Wraps +io+ and updates digest for each of the digest algorithms in
  # the +digests+ Hash.  Returns the digests hash.  Example:
  #
  #   io = StringIO.new
  #   digests = {
  #     'SHA1'   => OpenSSL::Digest.new('SHA1'),
  #     'SHA512' => OpenSSL::Digest.new('SHA512'),
  #   }
  #
  #   Gem::Package::DigestIO.wrap io, digests do |digest_io|
  #     digest_io.write "hello"
  #   end
  #
  #   digests['SHA1'].hexdigest   #=> "aaf4c61d[...]"
  #   digests['SHA512'].hexdigest #=> "9b71d224[...]"

  def self.wrap(io, digests)
    digest_io = new io, digests

    yield digest_io

    return digests
  end

  ##
  # Creates a new DigestIO instance.  Using ::wrap is recommended, see the
  # ::wrap documentation for documentation of +io+ and +digests+.

  def initialize(io, digests)
    @io = io
    @digests = digests
  end

  ##
  # Writes +data+ to the underlying IO and updates the digests

  def write(data)
    result = @io.write data

    @digests.each do |_, digest|
      digest << data
    end

    result
  end
end
# frozen_string_literal: true
##
# The primary source of gems is a file on disk, including all usages
# internal to rubygems.
#
# This is a private class, do not depend on it directly. Instead, pass a path
# object to `Gem::Package.new`.

class Gem::Package::FileSource < Gem::Package::Source # :nodoc: all
  attr_reader :path

  def initialize(path)
    @path = path
  end

  def start
    @start ||= File.read path, 20
  end

  def present?
    File.exist? path
  end

  def with_write_io(&block)
    File.open path, 'wb', &block
  end

  def with_read_io(&block)
    File.open path, 'rb', &block
  end
end
# frozen_string_literal: true

require_relative 'optparse/lib/optparse'
# frozen_string_literal: true
require_relative 'deprecate'

##
# This module contains various utility methods as module methods.

module Gem::Util

  ##
  # Zlib::GzipReader wrapper that unzips +data+.

  def self.gunzip(data)
    require 'zlib'
    require 'stringio'
    data = StringIO.new(data, 'r')

    gzip_reader = begin
                    Zlib::GzipReader.new(data)
                  rescue Zlib::GzipFile::Error => e
                    raise e.class, e.inspect, e.backtrace
                  end

    unzipped = gzip_reader.read
    unzipped.force_encoding Encoding::BINARY
    unzipped
  end

  ##
  # Zlib::GzipWriter wrapper that zips +data+.

  def self.gzip(data)
    require 'zlib'
    require 'stringio'
    zipped = StringIO.new(String.new, 'w')
    zipped.set_encoding Encoding::BINARY

    Zlib::GzipWriter.wrap zipped do |io|
      io.write data
    end

    zipped.string
  end

  ##
  # A Zlib::Inflate#inflate wrapper

  def self.inflate(data)
    require 'zlib'
    Zlib::Inflate.inflate data
  end

  ##
  # This calls IO.popen and reads the result

  def self.popen(*command)
    IO.popen command, &:read
  end

  ##
  # Invokes system, but silences all output.

  def self.silent_system(*command)
    opt = {:out => IO::NULL, :err => [:child, :out]}
    if Hash === command.last
      opt.update(command.last)
      cmds = command[0...-1]
    else
      cmds = command.dup
    end
    system(*(cmds << opt))
  end

  class << self
    extend Gem::Deprecate

    rubygems_deprecate :silent_system
  end

  ##
  # Enumerates the parents of +directory+.

  def self.traverse_parents(directory, &block)
    return enum_for __method__, directory unless block_given?

    here = File.expand_path directory
    loop do
      Dir.chdir here, &block rescue Errno::EACCES

      new_here = File.expand_path('..', here)
      return if new_here == here # toplevel
      here = new_here
    end
  end

  ##
  # Globs for files matching +pattern+ inside of +directory+,
  # returning absolute paths to the matching files.

  def self.glob_files_in_dir(glob, base_path)
    if RUBY_VERSION >= "2.5"
      Dir.glob(glob, base: base_path).map! {|f| File.expand_path(f, base_path) }
    else
      Dir.glob(File.expand_path(glob, base_path))
    end
  end

  ##
  # Corrects +path+ (usually returned by `URI.parse().path` on Windows), that
  # comes with a leading slash.

  def self.correct_for_windows_path(path)
    if path[0].chr == '/' && path[1].chr =~ /[a-z]/i && path[2].chr == ':'
      path[1..-1]
    else
      path
    end
  end

end
# frozen_string_literal: true

autoload :OpenSSL, "openssl"

module Gem
  HAVE_OPENSSL = defined? OpenSSL::SSL # :nodoc:
end
# frozen_string_literal: true

require_relative 'deprecate'

##
# Base exception class for RubyGems.  All exception raised by RubyGems are a
# subclass of this one.
class Gem::Exception < RuntimeError; end

class Gem::CommandLineError < Gem::Exception; end

class Gem::DependencyError < Gem::Exception; end

class Gem::DependencyRemovalException < Gem::Exception; end

##
# Raised by Gem::Resolver when a Gem::Dependency::Conflict reaches the
# toplevel.  Indicates which dependencies were incompatible through #conflict
# and #conflicting_dependencies

class Gem::DependencyResolutionError < Gem::DependencyError
  attr_reader :conflict

  def initialize(conflict)
    @conflict = conflict
    a, b = conflicting_dependencies

    super "conflicting dependencies #{a} and #{b}\n#{@conflict.explanation}"
  end

  def conflicting_dependencies
    @conflict.conflicting_dependencies
  end
end

##
# Raised when attempting to uninstall a gem that isn't in GEM_HOME.

class Gem::GemNotInHomeException < Gem::Exception
  attr_accessor :spec
end

###
# Raised when removing a gem with the uninstall command fails

class Gem::UninstallError < Gem::Exception
  attr_accessor :spec
end

class Gem::DocumentError < Gem::Exception; end

##
# Potentially raised when a specification is validated.
class Gem::EndOfYAMLException < Gem::Exception; end

##
# Signals that a file permission error is preventing the user from
# operating on the given directory.

class Gem::FilePermissionError < Gem::Exception
  attr_reader :directory

  def initialize(directory)
    @directory = directory

    super "You don't have write permissions for the #{directory} directory."
  end
end

##
# Used to raise parsing and loading errors
class Gem::FormatException < Gem::Exception
  attr_accessor :file_path
end

class Gem::GemNotFoundException < Gem::Exception; end

##
# Raised by the DependencyInstaller when a specific gem cannot be found

class Gem::SpecificGemNotFoundException < Gem::GemNotFoundException
  ##
  # Creates a new SpecificGemNotFoundException for a gem with the given +name+
  # and +version+.  Any +errors+ encountered when attempting to find the gem
  # are also stored.

  def initialize(name, version, errors=nil)
    super "Could not find a valid gem '#{name}' (#{version}) locally or in a repository"

    @name = name
    @version = version
    @errors = errors
  end

  ##
  # The name of the gem that could not be found.

  attr_reader :name

  ##
  # The version of the gem that could not be found.

  attr_reader :version

  ##
  # Errors encountered attempting to find the gem.

  attr_reader :errors
end

##
# Raised by Gem::Resolver when dependencies conflict and create the
# inability to find a valid possible spec for a request.

class Gem::ImpossibleDependenciesError < Gem::Exception
  attr_reader :conflicts
  attr_reader :request

  def initialize(request, conflicts)
    @request   = request
    @conflicts = conflicts

    super build_message
  end

  def build_message # :nodoc:
    requester  = @request.requester
    requester  = requester ? requester.spec.full_name : 'The user'
    dependency = @request.dependency

    message = "#{requester} requires #{dependency} but it conflicted:\n".dup

    @conflicts.each do |_, conflict|
      message << conflict.explanation
    end

    message
  end

  def dependency
    @request.dependency
  end
end

class Gem::InstallError < Gem::Exception; end
class Gem::RuntimeRequirementNotMetError < Gem::InstallError
  attr_accessor :suggestion
  def message
    [suggestion, super].compact.join("\n\t")
  end
end

##
# Potentially raised when a specification is validated.
class Gem::InvalidSpecificationException < Gem::Exception; end

class Gem::OperationNotSupportedError < Gem::Exception; end

##
# Signals that a remote operation cannot be conducted, probably due to not
# being connected (or just not finding host).
#--
# TODO: create a method that tests connection to the preferred gems server.
# All code dealing with remote operations will want this.  Failure in that
# method should raise this error.
class Gem::RemoteError < Gem::Exception; end

class Gem::RemoteInstallationCancelled < Gem::Exception; end

class Gem::RemoteInstallationSkipped < Gem::Exception; end

##
# Represents an error communicating via HTTP.
class Gem::RemoteSourceException < Gem::Exception; end

##
# Raised when a gem dependencies file specifies a ruby version that does not
# match the current version.

class Gem::RubyVersionMismatch < Gem::Exception; end

##
# Raised by Gem::Validator when something is not right in a gem.

class Gem::VerificationError < Gem::Exception; end

##
# Raised to indicate that a system exit should occur with the specified
# exit_code

class Gem::SystemExitException < SystemExit
  ##
  # The exit code for the process

  attr_accessor :exit_code

  ##
  # Creates a new SystemExitException with the given +exit_code+

  def initialize(exit_code)
    @exit_code = exit_code

    super "Exiting RubyGems with exit_code #{exit_code}"
  end
end

##
# Raised by Resolver when a dependency requests a gem for which
# there is no spec.

class Gem::UnsatisfiableDependencyError < Gem::DependencyError
  ##
  # The unsatisfiable dependency.  This is a
  # Gem::Resolver::DependencyRequest, not a Gem::Dependency

  attr_reader :dependency

  ##
  # Errors encountered which may have contributed to this exception

  attr_accessor :errors

  ##
  # Creates a new UnsatisfiableDependencyError for the unsatisfiable
  # Gem::Resolver::DependencyRequest +dep+

  def initialize(dep, platform_mismatch=nil)
    if platform_mismatch and !platform_mismatch.empty?
      plats = platform_mismatch.map {|x| x.platform.to_s }.sort.uniq
      super "Unable to resolve dependency: No match for '#{dep}' on this platform. Found: #{plats.join(', ')}"
    else
      if dep.explicit?
        super "Unable to resolve dependency: user requested '#{dep}'"
      else
        super "Unable to resolve dependency: '#{dep.request_context}' requires '#{dep}'"
      end
    end

    @dependency = dep
    @errors     = []
  end

  ##
  # The name of the unresolved dependency

  def name
    @dependency.name
  end

  ##
  # The Requirement of the unresolved dependency (not Version).

  def version
    @dependency.requirement
  end
end

##
# Backwards compatible typo'd exception class for early RubyGems 2.0.x

Gem::UnsatisfiableDepedencyError = Gem::UnsatisfiableDependencyError # :nodoc:
Gem.deprecate_constant :UnsatisfiableDepedencyError
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require 'fileutils'
require_relative '../rubygems'
require_relative 'installer_uninstaller_utils'
require_relative 'dependency_list'
require_relative 'rdoc'
require_relative 'user_interaction'

##
# An Uninstaller.
#
# The uninstaller fires pre and post uninstall hooks.  Hooks can be added
# either through a rubygems_plugin.rb file in an installed gem or via a
# rubygems/defaults/#{RUBY_ENGINE}.rb or rubygems/defaults/operating_system.rb
# file.  See Gem.pre_uninstall and Gem.post_uninstall for details.

class Gem::Uninstaller
  include Gem::UserInteraction

  include Gem::InstallerUninstallerUtils

  ##
  # The directory a gem's executables will be installed into

  attr_reader :bin_dir

  ##
  # The gem repository the gem will be installed into

  attr_reader :gem_home

  ##
  # The Gem::Specification for the gem being uninstalled, only set during
  # #uninstall_gem

  attr_reader :spec

  ##
  # Constructs an uninstaller that will uninstall +gem+

  def initialize(gem, options = {})
    # TODO document the valid options
    @gem                = gem
    @version            = options[:version] || Gem::Requirement.default
    @gem_home           = File.realpath(options[:install_dir] || Gem.dir)
    @plugins_dir        = Gem.plugindir(@gem_home)
    @force_executables  = options[:executables]
    @force_all          = options[:all]
    @force_ignore       = options[:ignore]
    @bin_dir            = options[:bin_dir]
    @format_executable  = options[:format_executable]
    @abort_on_dependent = options[:abort_on_dependent]

    # Indicate if development dependencies should be checked when
    # uninstalling. (default: false)
    #
    @check_dev = options[:check_dev]

    if options[:force]
      @force_all = true
      @force_ignore = true
    end

    # only add user directory if install_dir is not set
    @user_install = false
    @user_install = options[:user_install] unless options[:install_dir]

    # Optimization: populated during #uninstall
    @default_specs_matching_uninstall_params = []
  end

  ##
  # Performs the uninstall of the gem.  This removes the spec, the Gem
  # directory, and the cached .gem file.

  def uninstall
    dependency = Gem::Dependency.new @gem, @version

    list = []

    dirs =
      Gem::Specification.dirs +
      [Gem.default_specifications_dir]

    Gem::Specification.each_spec dirs do |spec|
      next unless dependency.matches_spec? spec

      list << spec
    end

    if list.empty?
      raise Gem::InstallError, "gem #{@gem.inspect} is not installed"
    end

    default_specs, list = list.partition do |spec|
      spec.default_gem?
    end
    warn_cannot_uninstall_default_gems(default_specs - list)
    @default_specs_matching_uninstall_params = default_specs

    list, other_repo_specs = list.partition do |spec|
      @gem_home == spec.base_dir or
        (@user_install and spec.base_dir == Gem.user_dir)
    end

    list.sort!

    if list.empty?
      return unless other_repo_specs.any?

      other_repos = other_repo_specs.map {|spec| spec.base_dir }.uniq

      message = ["#{@gem} is not installed in GEM_HOME, try:"]
      message.concat other_repos.map {|repo|
        "\tgem uninstall -i #{repo} #{@gem}"
      }

      raise Gem::InstallError, message.join("\n")
    elsif @force_all
      remove_all list

    elsif list.size > 1
      gem_names = list.map {|gem| gem.full_name }
      gem_names << "All versions"

      say
      _, index = choose_from_list "Select gem to uninstall:", gem_names

      if index == list.size
        remove_all list
      elsif index >= 0 && index < list.size
        uninstall_gem list[index]
      else
        say "Error: must enter a number [1-#{list.size + 1}]"
      end
    else
      uninstall_gem list.first
    end
  end

  ##
  # Uninstalls gem +spec+

  def uninstall_gem(spec)
    @spec = spec

    unless dependencies_ok? spec
      if abort_on_dependent? || !ask_if_ok(spec)
        raise Gem::DependencyRemovalException,
          "Uninstallation aborted due to dependent gem(s)"
      end
    end

    Gem.pre_uninstall_hooks.each do |hook|
      hook.call self
    end

    remove_executables @spec
    remove_plugins @spec
    remove @spec

    regenerate_plugins

    Gem.post_uninstall_hooks.each do |hook|
      hook.call self
    end

    @spec = nil
  end

  ##
  # Removes installed executables and batch files (windows only) for +spec+.

  def remove_executables(spec)
    return if spec.executables.empty?

    executables = spec.executables.clone

    # Leave any executables created by other installed versions
    # of this gem installed.

    list = Gem::Specification.find_all do |s|
      s.name == spec.name && s.version != spec.version
    end

    list.each do |s|
      s.executables.each do |exe_name|
        executables.delete exe_name
      end
    end

    return if executables.empty?

    executables = executables.map {|exec| formatted_program_filename exec }

    remove = if @force_executables.nil?
               ask_yes_no("Remove executables:\n" +
                          "\t#{executables.join ', '}\n\n" +
                          "in addition to the gem?",
                          true)
             else
               @force_executables
             end

    if remove
      bin_dir = @bin_dir || Gem.bindir(spec.base_dir)

      raise Gem::FilePermissionError, bin_dir unless File.writable? bin_dir

      executables.each do |exe_name|
        say "Removing #{exe_name}"

        exe_file = File.join bin_dir, exe_name

        safe_delete { FileUtils.rm exe_file }
        safe_delete { FileUtils.rm "#{exe_file}.bat" }
      end
    else
      say "Executables and scripts will remain installed."
    end
  end

  ##
  # Removes all gems in +list+.
  #
  # NOTE: removes uninstalled gems from +list+.

  def remove_all(list)
    list.each {|spec| uninstall_gem spec }
  end

  ##
  # spec:: the spec of the gem to be uninstalled

  def remove(spec)
    unless path_ok?(@gem_home, spec) or
           (@user_install and path_ok?(Gem.user_dir, spec))
      e = Gem::GemNotInHomeException.new \
            "Gem '#{spec.full_name}' is not installed in directory #{@gem_home}"
      e.spec = spec

      raise e
    end

    raise Gem::FilePermissionError, spec.base_dir unless
      File.writable?(spec.base_dir)

    safe_delete { FileUtils.rm_r spec.full_gem_path }
    safe_delete { FileUtils.rm_r spec.extension_dir }

    old_platform_name = spec.original_name

    gem = spec.cache_file
    gem = File.join(spec.cache_dir, "#{old_platform_name}.gem") unless
      File.exist? gem

    safe_delete { FileUtils.rm_r gem }

    Gem::RDoc.new(spec).remove

    gemspec = spec.spec_file

    unless File.exist? gemspec
      gemspec = File.join(File.dirname(gemspec), "#{old_platform_name}.gemspec")
    end

    safe_delete { FileUtils.rm_r gemspec }
    announce_deletion_of(spec)

    Gem::Specification.reset
  end

  ##
  # Remove any plugin wrappers for +spec+.

  def remove_plugins(spec) # :nodoc:
    return if spec.plugins.empty?

    remove_plugins_for(spec, @plugins_dir)
  end

  ##
  # Regenerates plugin wrappers after removal.

  def regenerate_plugins
    latest = Gem::Specification.latest_spec_for(@spec.name)
    return if latest.nil?

    regenerate_plugins_for(latest, @plugins_dir)
  end

  ##
  # Is +spec+ in +gem_dir+?

  def path_ok?(gem_dir, spec)
    full_path     = File.join gem_dir, 'gems', spec.full_name
    original_path = File.join gem_dir, 'gems', spec.original_name

    full_path == spec.full_gem_path || original_path == spec.full_gem_path
  end

  ##
  # Returns true if it is OK to remove +spec+ or this is a forced
  # uninstallation.

  def dependencies_ok?(spec) # :nodoc:
    return true if @force_ignore

    deplist = Gem::DependencyList.from_specs
    deplist.ok_to_remove?(spec.full_name, @check_dev)
  end

  ##
  # Should the uninstallation abort if a dependency will go unsatisfied?
  #
  # See ::new.

  def abort_on_dependent? # :nodoc:
    @abort_on_dependent
  end

  ##
  # Asks if it is OK to remove +spec+.  Returns true if it is OK.

  def ask_if_ok(spec) # :nodoc:
    msg = ['']
    msg << 'You have requested to uninstall the gem:'
    msg << "\t#{spec.full_name}"
    msg << ''

    siblings = Gem::Specification.select do |s|
      s.name == spec.name && s.full_name != spec.full_name
    end

    spec.dependent_gems(@check_dev).each do |dep_spec, dep, satlist|
      unless siblings.any? {|s| s.satisfies_requirement? dep }
        msg << "#{dep_spec.name}-#{dep_spec.version} depends on #{dep}"
      end
    end

    msg << 'If you remove this gem, these dependencies will not be met.'
    msg << 'Continue with Uninstall?'
    return ask_yes_no(msg.join("\n"), false)
  end

  ##
  # Returns the formatted version of the executable +filename+

  def formatted_program_filename(filename) # :nodoc:
    # TODO perhaps the installer should leave a small manifest
    # of what it did for us to find rather than trying to recreate
    # it again.
    if @format_executable
      require_relative 'installer'
      Gem::Installer.exec_format % File.basename(filename)
    else
      filename
    end
  end

  def safe_delete(&block)
    block.call
  rescue Errno::ENOENT
    nil
  rescue Errno::EPERM
    e = Gem::UninstallError.new
    e.spec = @spec

    raise e
  end

  private

  def announce_deletion_of(spec)
    name = spec.full_name
    say "Successfully uninstalled #{name}"
    if default_spec_matches?(spec)
      say(
        "There was both a regular copy and a default copy of #{name}. The " \
          "regular copy was successfully uninstalled, but the default copy " \
          "was left around because default gems can't be removed."
      )
    end
  end

  # @return true if the specs of any default gems are `==` to the given `spec`.
  def default_spec_matches?(spec)
    !default_specs_that_match(spec).empty?
  end

  # @return [Array] specs of default gems that are `==` to the given `spec`.
  def default_specs_that_match(spec)
    @default_specs_matching_uninstall_params.select {|default_spec| spec == default_spec }
  end

  def warn_cannot_uninstall_default_gems(specs)
    specs.each do |spec|
      say "Gem #{spec.full_name} cannot be uninstalled because it is a default gem"
    end
  end
end
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require_relative '../rubygems'
require_relative 'security_option'

##
# Mixin methods for install and update options for Gem::Commands

module Gem::InstallUpdateOptions
  include Gem::SecurityOption

  ##
  # Add the install/update options to the option parser.

  def add_install_update_options
    add_option(:"Install/Update", '-i', '--install-dir DIR',
               'Gem repository directory to get installed',
               'gems') do |value, options|
      options[:install_dir] = File.expand_path(value)
    end

    add_option(:"Install/Update", '-n', '--bindir DIR',
               'Directory where executables will be',
               'placed when the gem is installed') do |value, options|
      options[:bin_dir] = File.expand_path(value)
    end

    add_option(:"Install/Update", '--document [TYPES]', Array,
               'Generate documentation for installed gems',
               'List the documentation types you wish to',
               'generate.  For example: rdoc,ri') do |value, options|
      options[:document] = case value
                           when nil   then %w[ri]
                           when false then []
                           else            value
                           end
    end

    add_option(:"Install/Update", '--build-root DIR',
               'Temporary installation root. Useful for building',
               'packages. Do not use this when installing remote gems.') do |value, options|
      options[:build_root] = File.expand_path(value)
    end

    add_option(:"Install/Update", '--vendor',
               'Install gem into the vendor directory.',
               'Only for use by gem repackagers.') do |value, options|
      unless Gem.vendor_dir
        raise Gem::OptionParser::InvalidOption.new 'your platform is not supported'
      end

      options[:vendor] = true
      options[:install_dir] = Gem.vendor_dir
    end

    add_option(:"Install/Update", '-N', '--no-document',
               'Disable documentation generation') do |value, options|
      options[:document] = []
    end

    add_option(:"Install/Update", '-E', '--[no-]env-shebang',
               "Rewrite the shebang line on installed",
               "scripts to use /usr/bin/env") do |value, options|
      options[:env_shebang] = value
    end

    add_option(:"Install/Update", '-f', '--[no-]force',
               'Force gem to install, bypassing dependency',
               'checks') do |value, options|
      options[:force] = value
    end

    add_option(:"Install/Update", '-w', '--[no-]wrappers',
               'Use bin wrappers for executables',
               'Not available on dosish platforms') do |value, options|
      options[:wrappers] = value
    end

    add_security_option

    add_option(:"Install/Update", '--ignore-dependencies',
               'Do not install any required dependent gems') do |value, options|
      options[:ignore_dependencies] = value
    end

    add_option(:"Install/Update", '--[no-]format-executable',
               'Make installed executable names match Ruby.',
               'If Ruby is ruby18, foo_exec will be',
               'foo_exec18') do |value, options|
      options[:format_executable] = value
    end

    add_option(:"Install/Update",       '--[no-]user-install',
               'Install in user\'s home directory instead',
               'of GEM_HOME.') do |value, options|
      options[:user_install] = value
    end

    add_option(:"Install/Update", "--development",
                "Install additional development",
                "dependencies") do |value, options|
      options[:development] = true
      options[:dev_shallow] = true
    end

    add_option(:"Install/Update", "--development-all",
                "Install development dependencies for all",
                "gems (including dev deps themselves)") do |value, options|
      options[:development] = true
      options[:dev_shallow] = false
    end

    add_option(:"Install/Update", "--conservative",
                "Don't attempt to upgrade gems already",
                "meeting version requirement") do |value, options|
      options[:conservative] = true
      options[:minimal_deps] = true
    end

    add_option(:"Install/Update", "--[no-]minimal-deps",
                "Don't upgrade any dependencies that already",
                "meet version requirements") do |value, options|
      options[:minimal_deps] = value
    end

    add_option(:"Install/Update", "--[no-]post-install-message",
                "Print post install message") do |value, options|
      options[:post_install_message] = value
    end

    add_option(:"Install/Update", '-g', '--file [FILE]',
               'Read from a gem dependencies API file and',
               'install the listed gems') do |v,o|
      v = Gem::GEM_DEP_FILES.find do |file|
        File.exist? file
      end unless v

      unless v
        message = v ? v : "(tried #{Gem::GEM_DEP_FILES.join ', '})"

        raise Gem::OptionParser::InvalidArgument,
                "cannot find gem dependencies file #{message}"
      end

      options[:gemdeps] = v
    end

    add_option(:"Install/Update", '--without GROUPS', Array,
               'Omit the named groups (comma separated)',
               'when installing from a gem dependencies',
               'file') do |v,o|
      options[:without_groups].concat v.map {|without| without.intern }
    end

    add_option(:"Install/Update", '--default',
               'Add the gem\'s full specification to',
               'specifications/default and extract only its bin') do |v,o|
      options[:install_as_default] = v
    end

    add_option(:"Install/Update", '--explain',
               'Rather than install the gems, indicate which would',
               'be installed') do |v,o|
      options[:explain] = v
    end

    add_option(:"Install/Update", '--[no-]lock',
               'Create a lock file (when used with -g/--file)') do |v,o|
      options[:lock] = v
    end

    add_option(:"Install/Update", '--[no-]suggestions',
               'Suggest alternates when gems are not found') do |v,o|
      options[:suggest_alternate] = v
    end
  end

  ##
  # Default options for the gem install command.

  def install_update_defaults_str
    '--document=rdoc,ri --wrappers'
  end

end
module Gem

  ###
  # This module is used for safely loading YAML specs from a gem.  The
  # `safe_load` method defined on this module is specifically designed for
  # loading Gem specifications.  For loading other YAML safely, please see
  # Psych.safe_load

  module SafeYAML
    PERMITTED_CLASSES = %w[
      Symbol
      Time
      Date
      Gem::Dependency
      Gem::Platform
      Gem::Requirement
      Gem::Specification
      Gem::Version
      Gem::Version::Requirement
    ].freeze

    PERMITTED_SYMBOLS = %w[
      development
      runtime
    ].freeze

    if ::YAML.respond_to? :safe_load
      def self.safe_load(input)
        if Gem::Version.new(Psych::VERSION) >= Gem::Version.new('3.1.0.pre1')
          ::YAML.safe_load(input, permitted_classes: PERMITTED_CLASSES, permitted_symbols: PERMITTED_SYMBOLS, aliases: true)
        else
          ::YAML.safe_load(input, PERMITTED_CLASSES, PERMITTED_SYMBOLS, true)
        end
      end

      def self.load(input)
        if Gem::Version.new(Psych::VERSION) >= Gem::Version.new('3.1.0.pre1')
          ::YAML.safe_load(input, permitted_classes: [::Symbol])
        else
          ::YAML.safe_load(input, [::Symbol])
        end
      end
    else
      unless Gem::Deprecate.skip
        warn "YAML safe loading is not available. Please upgrade psych to a version that supports safe loading (>= 2.0)."
      end

      def self.safe_load(input, *args)
        ::YAML.load input
      end

      def self.load(input)
        ::YAML.load input
      end
    end
  end
end
module Gem
  class << self

    ##
    # Returns full path of previous but one directory of dir in path
    # E.g. for '/usr/share/ruby', 'ruby', it returns '/usr'

    def previous_but_one_dir_to(path, dir)
      return unless path

      split_path = path.split(File::SEPARATOR)
      File.join(split_path.take_while { |one_dir| one_dir !~ /^#{dir}$/ }[0..-2])
    end
    private :previous_but_one_dir_to

    ##
    # Detects --install-dir option specified on command line.

    def opt_install_dir?
      @opt_install_dir ||= ARGV.include?('--install-dir') || ARGV.include?('-i')
    end
    private :opt_install_dir?

    ##
    # Detects --build-root option specified on command line.

    def opt_build_root?
      @opt_build_root ||= ARGV.include?('--build-root')
    end
    private :opt_build_root?

    ##
    # Tries to detect, if arguments and environment variables suggest that
    # 'gem install' is executed from rpmbuild.

    def rpmbuild?
      @rpmbuild ||= ENV['RPM_PACKAGE_NAME'] && (opt_install_dir? || opt_build_root?)
    end
    private :rpmbuild?

    ##
    # Default gems locations allowed on FHS system (/usr, /usr/share).
    # The locations are derived from directories specified during build
    # configuration.

    def default_locations
      @default_locations ||= {
        :system => previous_but_one_dir_to(RbConfig::CONFIG['vendordir'], RbConfig::CONFIG['RUBY_INSTALL_NAME']),
        :local => previous_but_one_dir_to(RbConfig::CONFIG['sitedir'], RbConfig::CONFIG['RUBY_INSTALL_NAME'])
      }
    end

    ##
    # For each location provides set of directories for binaries (:bin_dir)
    # platform independent (:gem_dir) and dependent (:ext_dir) files.

    def default_dirs
      @libdir ||= case RUBY_PLATFORM
      when 'java'
        RbConfig::CONFIG['datadir']
      else
        RbConfig::CONFIG['libdir']
      end

      @default_dirs ||= default_locations.inject(Hash.new) do |hash, location|
        destination, path = location

        hash[destination] = if path
          {
            :bin_dir => File.join(path, RbConfig::CONFIG['bindir'].split(File::SEPARATOR).last),
            :gem_dir => File.join(path, RbConfig::CONFIG['datadir'].split(File::SEPARATOR).last, 'gems'),
            :ext_dir => File.join(path, @libdir.split(File::SEPARATOR).last, 'gems')
          }
        else
          {
            :bin_dir => '',
            :gem_dir => '',
            :ext_dir => ''
          }
        end

        hash
      end
    end

    ##
    # Remove methods we are going to override. This avoids "method redefined;"
    # warnings otherwise issued by Ruby.

    remove_method :operating_system_defaults if method_defined? :operating_system_defaults
    remove_method :default_dir if method_defined? :default_dir
    remove_method :default_path if method_defined? :default_path
    remove_method :default_ext_dir_for if method_defined? :default_ext_dir_for

    ##
    # Regular user installs into user directory, root manages /usr/local.

    def operating_system_defaults
      unless opt_build_root?
        options = if Process.uid == 0
          "--install-dir=#{Gem.default_dirs[:local][:gem_dir]} --bindir #{Gem.default_dirs[:local][:bin_dir]}"
        end

        {"gem" => options}
      else
        {}
      end
    end

    ##
    # RubyGems default overrides.

    def default_dir
      Gem.default_dirs[:system][:gem_dir]
    end

    def default_path
      path = default_dirs.collect {|location, paths| paths[:gem_dir]}
      path.unshift Gem.user_dir if File.exist? Gem.user_home
      path
    end

    def default_ext_dir_for base_dir
      dir = if rpmbuild?
        build_dir = base_dir.chomp Gem.default_dirs[:system][:gem_dir]
        if build_dir != base_dir
          File.join build_dir, Gem.default_dirs[:system][:ext_dir]
        end
      else
        dirs = Gem.default_dirs.detect {|location, paths| paths[:gem_dir] == base_dir}
        dirs && dirs.last[:ext_dir]
      end
      dir && File.join(dir, RbConfig::CONFIG['RUBY_INSTALL_NAME'])
    end

    # This method should be available since RubyGems 2.2 until RubyGems 3.0.
    # https://github.com/rubygems/rubygems/issues/749
    if method_defined? :install_extension_in_lib
      remove_method :install_extension_in_lib

      def install_extension_in_lib
        false
      end
    end
  end
end
# frozen_string_literal: true
require_relative '../rubygems'
require_relative 'user_interaction'

##
# Cleans up after a partially-failed uninstall or for an invalid
# Gem::Specification.
#
# If a specification was removed by hand this will remove any remaining files.
#
# If a corrupt specification was installed this will clean up warnings by
# removing the bogus specification.

class Gem::Doctor
  include Gem::UserInteraction

  ##
  # Maps a gem subdirectory to the files that are expected to exist in the
  # subdirectory.

  REPOSITORY_EXTENSION_MAP = [ # :nodoc:
    ['specifications', '.gemspec'],
    ['build_info',     '.info'],
    ['cache',          '.gem'],
    ['doc',            ''],
    ['extensions',     ''],
    ['gems',           ''],
    ['plugins',        ''],
  ].freeze

  missing =
    Gem::REPOSITORY_SUBDIRECTORIES.sort -
      REPOSITORY_EXTENSION_MAP.map {|(k,_)| k }.sort

  raise "Update REPOSITORY_EXTENSION_MAP, missing: #{missing.join ', '}" unless
    missing.empty?

  ##
  # Creates a new Gem::Doctor that will clean up +gem_repository+.  Only one
  # gem repository may be cleaned at a time.
  #
  # If +dry_run+ is true no files or directories will be removed.

  def initialize(gem_repository, dry_run = false)
    @gem_repository = gem_repository
    @dry_run        = dry_run

    @installed_specs = nil
  end

  ##
  # Specs installed in this gem repository

  def installed_specs # :nodoc:
    @installed_specs ||= Gem::Specification.map {|s| s.full_name }
  end

  ##
  # Are we doctoring a gem repository?

  def gem_repository?
    not installed_specs.empty?
  end

  ##
  # Cleans up uninstalled files and invalid gem specifications

  def doctor
    @orig_home = Gem.dir
    @orig_path = Gem.path

    say "Checking #{@gem_repository}"

    Gem.use_paths @gem_repository.to_s

    unless gem_repository?
      say 'This directory does not appear to be a RubyGems repository, ' +
          'skipping'
      say
      return
    end

    doctor_children

    say
  ensure
    Gem.use_paths @orig_home, *@orig_path
  end

  ##
  # Cleans up children of this gem repository

  def doctor_children # :nodoc:
    REPOSITORY_EXTENSION_MAP.each do |sub_directory, extension|
      doctor_child sub_directory, extension
    end
  end

  ##
  # Removes files in +sub_directory+ with +extension+

  def doctor_child(sub_directory, extension) # :nodoc:
    directory = File.join(@gem_repository, sub_directory)

    Dir.entries(directory).sort.each do |ent|
      next if ent == "." || ent == ".."

      child = File.join(directory, ent)
      next unless File.exist?(child)

      basename = File.basename(child, extension)
      next if installed_specs.include? basename
      next if /^rubygems-\d/ =~ basename
      next if 'specifications' == sub_directory and 'default' == basename
      next if 'plugins' == sub_directory and Gem.plugin_suffix_regexp =~ basename

      type = File.directory?(child) ? 'directory' : 'file'

      action = if @dry_run
                 'Extra'
               else
                 FileUtils.rm_r(child)
                 'Removed'
               end

      say "#{action} #{type} #{sub_directory}/#{File.basename(child)}"
    end
  rescue Errno::ENOENT
    # ignore
  end
end
# frozen_string_literal: true
require_relative '../rubygems'
require_relative 'package'
require 'tmpdir'

##
# Top level class for building the gem repository index.

class Gem::Indexer
  include Gem::UserInteraction

  ##
  # Build indexes for RubyGems 1.2.0 and newer when true

  attr_accessor :build_modern

  ##
  # Index install location

  attr_reader :dest_directory

  ##
  # Specs index install location

  attr_reader :dest_specs_index

  ##
  # Latest specs index install location

  attr_reader :dest_latest_specs_index

  ##
  # Prerelease specs index install location

  attr_reader :dest_prerelease_specs_index

  ##
  # Index build directory

  attr_reader :directory

  ##
  # Create an indexer that will index the gems in +directory+.

  def initialize(directory, options = {})
    require 'fileutils'
    require 'tmpdir'
    require 'zlib'

    options = { :build_modern => true }.merge options

    @build_modern = options[:build_modern]

    @dest_directory = directory
    @directory = Dir.mktmpdir 'gem_generate_index'

    marshal_name = "Marshal.#{Gem.marshal_version}"

    @master_index = File.join @directory, 'yaml'
    @marshal_index = File.join @directory, marshal_name

    @quick_dir = File.join @directory, 'quick'
    @quick_marshal_dir = File.join @quick_dir, marshal_name
    @quick_marshal_dir_base = File.join "quick", marshal_name # FIX: UGH

    @quick_index = File.join @quick_dir, 'index'
    @latest_index = File.join @quick_dir, 'latest_index'

    @specs_index = File.join @directory, "specs.#{Gem.marshal_version}"
    @latest_specs_index =
      File.join(@directory, "latest_specs.#{Gem.marshal_version}")
    @prerelease_specs_index =
      File.join(@directory, "prerelease_specs.#{Gem.marshal_version}")
    @dest_specs_index =
      File.join(@dest_directory, "specs.#{Gem.marshal_version}")
    @dest_latest_specs_index =
      File.join(@dest_directory, "latest_specs.#{Gem.marshal_version}")
    @dest_prerelease_specs_index =
      File.join(@dest_directory, "prerelease_specs.#{Gem.marshal_version}")

    @files = []
  end

  ##
  # Build various indices

  def build_indices
    specs = map_gems_to_specs gem_file_list
    Gem::Specification._resort! specs
    build_marshal_gemspecs specs
    build_modern_indices specs if @build_modern

    compress_indices
  end

  ##
  # Builds Marshal quick index gemspecs.

  def build_marshal_gemspecs(specs)
    count = specs.count
    progress = ui.progress_reporter count,
                                    "Generating Marshal quick index gemspecs for #{count} gems",
                                    "Complete"

    files = []

    Gem.time 'Generated Marshal quick index gemspecs' do
      specs.each do |spec|
        next if spec.default_gem?
        spec_file_name = "#{spec.original_name}.gemspec.rz"
        marshal_name = File.join @quick_marshal_dir, spec_file_name

        marshal_zipped = Gem.deflate Marshal.dump(spec)

        File.open marshal_name, 'wb' do |io|
          io.write marshal_zipped
        end

        files << marshal_name

        progress.updated spec.original_name
      end

      progress.done
    end

    @files << @quick_marshal_dir

    files
  end

  ##
  # Build a single index for RubyGems 1.2 and newer

  def build_modern_index(index, file, name)
    say "Generating #{name} index"

    Gem.time "Generated #{name} index" do
      File.open(file, 'wb') do |io|
        specs = index.map do |*spec|
          # We have to splat here because latest_specs is an array, while the
          # others are hashes.
          spec = spec.flatten.last
          platform = spec.original_platform

          # win32-api-1.0.4-x86-mswin32-60
          unless String === platform
            alert_warning "Skipping invalid platform in gem: #{spec.full_name}"
            next
          end

          platform = Gem::Platform::RUBY if platform.nil? or platform.empty?
          [spec.name, spec.version, platform]
        end

        specs = compact_specs(specs)
        Marshal.dump(specs, io)
      end
    end
  end

  ##
  # Builds indices for RubyGems 1.2 and newer. Handles full, latest, prerelease

  def build_modern_indices(specs)
    prerelease, released = specs.partition do |s|
      s.version.prerelease?
    end
    latest_specs =
      Gem::Specification._latest_specs specs

    build_modern_index(released.sort, @specs_index, 'specs')
    build_modern_index(latest_specs.sort, @latest_specs_index, 'latest specs')
    build_modern_index(prerelease.sort, @prerelease_specs_index,
                       'prerelease specs')

    @files += [@specs_index,
               "#{@specs_index}.gz",
               @latest_specs_index,
               "#{@latest_specs_index}.gz",
               @prerelease_specs_index,
               "#{@prerelease_specs_index}.gz"]
  end

  def map_gems_to_specs(gems)
    gems.map do |gemfile|
      if File.size(gemfile) == 0
        alert_warning "Skipping zero-length gem: #{gemfile}"
        next
      end

      begin
        spec = Gem::Package.new(gemfile).spec
        spec.loaded_from = gemfile

        spec.abbreviate
        spec.sanitize

        spec
      rescue SignalException
        alert_error "Received signal, exiting"
        raise
      rescue Exception => e
        msg = ["Unable to process #{gemfile}",
               "#{e.message} (#{e.class})",
               "\t#{e.backtrace.join "\n\t"}"].join("\n")
        alert_error msg
      end
    end.compact
  end

  ##
  # Compresses indices on disk
  #--
  # All future files should be compressed using gzip, not deflate

  def compress_indices
    say "Compressing indices"

    Gem.time 'Compressed indices' do
      if @build_modern
        gzip @specs_index
        gzip @latest_specs_index
        gzip @prerelease_specs_index
      end
    end
  end

  ##
  # Compacts Marshal output for the specs index data source by using identical
  # objects as much as possible.

  def compact_specs(specs)
    names = {}
    versions = {}
    platforms = {}

    specs.map do |(name, version, platform)|
      names[name] = name unless names.include? name
      versions[version] = version unless versions.include? version
      platforms[platform] = platform unless platforms.include? platform

      [names[name], versions[version], platforms[platform]]
    end
  end

  ##
  # Compress +filename+ with +extension+.

  def compress(filename, extension)
    data = Gem.read_binary filename

    zipped = Gem.deflate data

    File.open "#{filename}.#{extension}", 'wb' do |io|
      io.write zipped
    end
  end

  ##
  # List of gem file names to index.

  def gem_file_list
    Gem::Util.glob_files_in_dir("*.gem", File.join(@dest_directory, "gems"))
  end

  ##
  # Builds and installs indices.

  def generate_index
    make_temp_directories
    build_indices
    install_indices
  rescue SignalException
  ensure
    FileUtils.rm_rf @directory
  end

  ##
  # Zlib::GzipWriter wrapper that gzips +filename+ on disk.

  def gzip(filename)
    Zlib::GzipWriter.open "#{filename}.gz" do |io|
      io.write Gem.read_binary(filename)
    end
  end

  ##
  # Install generated indices into the destination directory.

  def install_indices
    verbose = Gem.configuration.really_verbose

    say "Moving index into production dir #{@dest_directory}" if verbose

    files = @files
    files.delete @quick_marshal_dir if files.include? @quick_dir

    if files.include? @quick_marshal_dir and not files.include? @quick_dir
      files.delete @quick_marshal_dir

      dst_name = File.join(@dest_directory, @quick_marshal_dir_base)

      FileUtils.mkdir_p File.dirname(dst_name), :verbose => verbose
      FileUtils.rm_rf dst_name, :verbose => verbose
      FileUtils.mv(@quick_marshal_dir, dst_name,
                   :verbose => verbose, :force => true)
    end

    files = files.map do |path|
      path.sub(/^#{Regexp.escape @directory}\/?/, '') # HACK?
    end

    files.each do |file|
      src_name = File.join @directory, file
      dst_name = File.join @dest_directory, file

      FileUtils.rm_rf dst_name, :verbose => verbose
      FileUtils.mv(src_name, @dest_directory,
                   :verbose => verbose, :force => true)
    end
  end

  ##
  # Make directories for index generation

  def make_temp_directories
    FileUtils.rm_rf @directory
    FileUtils.mkdir_p @directory, :mode => 0700
    FileUtils.mkdir_p @quick_marshal_dir
  end

  ##
  # Ensure +path+ and path with +extension+ are identical.

  def paranoid(path, extension)
    data = Gem.read_binary path
    compressed_data = Gem.read_binary "#{path}.#{extension}"

    unless data == Gem::Util.inflate(compressed_data)
      raise "Compressed file #{compressed_path} does not match uncompressed file #{path}"
    end
  end

  ##
  # Perform an in-place update of the repository from newly added gems.

  def update_index
    make_temp_directories

    specs_mtime = File.stat(@dest_specs_index).mtime
    newest_mtime = Time.at 0

    updated_gems = gem_file_list.select do |gem|
      gem_mtime = File.stat(gem).mtime
      newest_mtime = gem_mtime if gem_mtime > newest_mtime
      gem_mtime >= specs_mtime
    end

    if updated_gems.empty?
      say 'No new gems'
      terminate_interaction 0
    end

    specs = map_gems_to_specs updated_gems
    prerelease, released = specs.partition {|s| s.version.prerelease? }

    files = build_marshal_gemspecs specs

    Gem.time 'Updated indexes' do
      update_specs_index released, @dest_specs_index, @specs_index
      update_specs_index released, @dest_latest_specs_index, @latest_specs_index
      update_specs_index(prerelease,
                         @dest_prerelease_specs_index,
                         @prerelease_specs_index)
    end

    compress_indices

    verbose = Gem.configuration.really_verbose

    say "Updating production dir #{@dest_directory}" if verbose

    files << @specs_index
    files << "#{@specs_index}.gz"
    files << @latest_specs_index
    files << "#{@latest_specs_index}.gz"
    files << @prerelease_specs_index
    files << "#{@prerelease_specs_index}.gz"

    files = files.map do |path|
      path.sub(/^#{Regexp.escape @directory}\/?/, '') # HACK?
    end

    files.each do |file|
      src_name = File.join @directory, file
      dst_name = File.join @dest_directory, file # REFACTOR: duped above

      FileUtils.mv src_name, dst_name, :verbose => verbose,
                   :force => true

      File.utime newest_mtime, newest_mtime, dst_name
    end
  end

  ##
  # Combines specs in +index+ and +source+ then writes out a new copy to
  # +dest+.  For a latest index, does not ensure the new file is minimal.

  def update_specs_index(index, source, dest)
    specs_index = Marshal.load Gem.read_binary(source)

    index.each do |spec|
      platform = spec.original_platform
      platform = Gem::Platform::RUBY if platform.nil? or platform.empty?
      specs_index << [spec.name, spec.version, platform]
    end

    specs_index = compact_specs specs_index.uniq.sort

    File.open dest, 'wb' do |io|
      Marshal.dump specs_index, io
    end
  end
end
# frozen_string_literal: true
require_relative '../user_interaction'

##
# A Gem::Security::Policy object encapsulates the settings for verifying
# signed gem files.  This is the base class.  You can either declare an
# instance of this or use one of the preset security policies in
# Gem::Security::Policies.

class Gem::Security::Policy
  include Gem::UserInteraction

  attr_reader :name

  attr_accessor :only_signed
  attr_accessor :only_trusted
  attr_accessor :verify_chain
  attr_accessor :verify_data
  attr_accessor :verify_root
  attr_accessor :verify_signer

  ##
  # Create a new Gem::Security::Policy object with the given mode and
  # options.

  def initialize(name, policy = {}, opt = {})
    @name = name

    @opt = opt

    # Default to security
    @only_signed   = true
    @only_trusted  = true
    @verify_chain  = true
    @verify_data   = true
    @verify_root   = true
    @verify_signer = true

    policy.each_pair do |key, val|
      case key
      when :verify_data   then @verify_data   = val
      when :verify_signer then @verify_signer = val
      when :verify_chain  then @verify_chain  = val
      when :verify_root   then @verify_root   = val
      when :only_trusted  then @only_trusted  = val
      when :only_signed   then @only_signed   = val
      end
    end
  end

  ##
  # Verifies each certificate in +chain+ has signed the following certificate
  # and is valid for the given +time+.

  def check_chain(chain, time)
    raise Gem::Security::Exception, 'missing signing chain' unless chain
    raise Gem::Security::Exception, 'empty signing chain' if chain.empty?

    begin
      chain.each_cons 2 do |issuer, cert|
        check_cert cert, issuer, time
      end

      true
    rescue Gem::Security::Exception => e
      raise Gem::Security::Exception, "invalid signing chain: #{e.message}"
    end
  end

  ##
  # Verifies that +data+ matches the +signature+ created by +public_key+ and
  # the +digest+ algorithm.

  def check_data(public_key, digest, signature, data)
    raise Gem::Security::Exception, "invalid signature" unless
      public_key.verify digest, signature, data.digest

    true
  end

  ##
  # Ensures that +signer+ is valid for +time+ and was signed by the +issuer+.
  # If the +issuer+ is +nil+ no verification is performed.

  def check_cert(signer, issuer, time)
    raise Gem::Security::Exception, 'missing signing certificate' unless
      signer

    message = "certificate #{signer.subject}"

    if not_before = signer.not_before and not_before > time
      raise Gem::Security::Exception,
            "#{message} not valid before #{not_before}"
    end

    if not_after = signer.not_after and not_after < time
      raise Gem::Security::Exception, "#{message} not valid after #{not_after}"
    end

    if issuer and not signer.verify issuer.public_key
      raise Gem::Security::Exception,
            "#{message} was not issued by #{issuer.subject}"
    end

    true
  end

  ##
  # Ensures the public key of +key+ matches the public key in +signer+

  def check_key(signer, key)
    unless signer and key
      return true unless @only_signed

      raise Gem::Security::Exception, 'missing key or signature'
    end

    raise Gem::Security::Exception,
      "certificate #{signer.subject} does not match the signing key" unless
        signer.check_private_key(key)

    true
  end

  ##
  # Ensures the root certificate in +chain+ is self-signed and valid for
  # +time+.

  def check_root(chain, time)
    raise Gem::Security::Exception, 'missing signing chain' unless chain

    root = chain.first

    raise Gem::Security::Exception, 'missing root certificate' unless root

    raise Gem::Security::Exception,
          "root certificate #{root.subject} is not self-signed " +
          "(issuer #{root.issuer})" if
      root.issuer != root.subject

    check_cert root, root, time
  end

  ##
  # Ensures the root of +chain+ has a trusted certificate in +trust_dir+ and
  # the digests of the two certificates match according to +digester+

  def check_trust(chain, digester, trust_dir)
    raise Gem::Security::Exception, 'missing signing chain' unless chain

    root = chain.first

    raise Gem::Security::Exception, 'missing root certificate' unless root

    path = Gem::Security.trust_dir.cert_path root

    unless File.exist? path
      message = "root cert #{root.subject} is not trusted".dup

      message << " (root of signing cert #{chain.last.subject})" if
        chain.length > 1

      raise Gem::Security::Exception, message
    end

    save_cert = OpenSSL::X509::Certificate.new File.read path
    save_dgst = digester.digest save_cert.public_key.to_pem

    pkey_str = root.public_key.to_pem
    cert_dgst = digester.digest pkey_str

    raise Gem::Security::Exception,
          "trusted root certificate #{root.subject} checksum " +
          "does not match signing root certificate checksum" unless
      save_dgst == cert_dgst

    true
  end

  ##
  # Extracts the email or subject from +certificate+

  def subject(certificate) # :nodoc:
    certificate.extensions.each do |extension|
      next unless extension.oid == 'subjectAltName'

      return extension.value
    end

    certificate.subject.to_s
  end

  def inspect # :nodoc:
    ("[Policy: %s - data: %p signer: %p chain: %p root: %p " +
     "signed-only: %p trusted-only: %p]") % [
       @name, @verify_chain, @verify_data, @verify_root, @verify_signer,
       @only_signed, @only_trusted
     ]
  end

  ##
  # For +full_name+, verifies the certificate +chain+ is valid, the +digests+
  # match the signatures +signatures+ created by the signer depending on the
  # +policy+ settings.
  #
  # If +key+ is given it is used to validate the signing certificate.

  def verify(chain, key = nil, digests = {}, signatures = {},
             full_name = '(unknown)')
    if signatures.empty?
      if @only_signed
        raise Gem::Security::Exception,
          "unsigned gems are not allowed by the #{name} policy"
      elsif digests.empty?
        # lack of signatures is irrelevant if there is nothing to check
        # against
      else
        alert_warning "#{full_name} is not signed"
        return
      end
    end

    opt       = @opt
    digester  = Gem::Security.create_digest
    trust_dir = opt[:trust_dir]
    time      = Time.now

    _, signer_digests = digests.find do |algorithm, file_digests|
      file_digests.values.first.name == Gem::Security::DIGEST_NAME
    end

    if @verify_data
      raise Gem::Security::Exception, 'no digests provided (probable bug)' if
        signer_digests.nil? or signer_digests.empty?
    else
      signer_digests = {}
    end

    signer = chain.last

    check_key signer, key if key

    check_cert signer, nil, time if @verify_signer

    check_chain chain, time if @verify_chain

    check_root chain, time if @verify_root

    if @only_trusted
      check_trust chain, digester, trust_dir
    elsif signatures.empty? and digests.empty?
      # trust is irrelevant if there's no signatures to verify
    else
      alert_warning "#{subject signer} is not trusted for #{full_name}"
    end

    signatures.each do |file, _|
      digest = signer_digests[file]

      raise Gem::Security::Exception, "missing digest for #{file}" unless
        digest
    end

    signer_digests.each do |file, digest|
      signature = signatures[file]

      raise Gem::Security::Exception, "missing signature for #{file}" unless
        signature

      check_data signer.public_key, digester, signature, digest if @verify_data
    end

    true
  end

  ##
  # Extracts the certificate chain from the +spec+ and calls #verify to ensure
  # the signatures and certificate chain is valid according to the policy..

  def verify_signatures(spec, digests, signatures)
    chain = spec.cert_chain.map do |cert_pem|
      OpenSSL::X509::Certificate.new cert_pem
    end

    verify chain, nil, digests, signatures, spec.full_name

    true
  end

  alias to_s name # :nodoc:
end
# frozen_string_literal: true
##
# The TrustDir manages the trusted certificates for gem signature
# verification.

class Gem::Security::TrustDir
  ##
  # Default permissions for the trust directory and its contents

  DEFAULT_PERMISSIONS = {
    :trust_dir    => 0700,
    :trusted_cert => 0600,
  }.freeze

  ##
  # The directory where trusted certificates will be stored.

  attr_reader :dir

  ##
  # Creates a new TrustDir using +dir+ where the directory and file
  # permissions will be checked according to +permissions+

  def initialize(dir, permissions = DEFAULT_PERMISSIONS)
    @dir = dir
    @permissions = permissions

    @digester = Gem::Security.create_digest
  end

  ##
  # Returns the path to the trusted +certificate+

  def cert_path(certificate)
    name_path certificate.subject
  end

  ##
  # Enumerates trusted certificates.

  def each_certificate
    return enum_for __method__ unless block_given?

    glob = File.join @dir, '*.pem'

    Dir[glob].each do |certificate_file|
      begin
        certificate = load_certificate certificate_file

        yield certificate, certificate_file
      rescue OpenSSL::X509::CertificateError
        next # HACK warn
      end
    end
  end

  ##
  # Returns the issuer certificate of the given +certificate+ if it exists in
  # the trust directory.

  def issuer_of(certificate)
    path = name_path certificate.issuer

    return unless File.exist? path

    load_certificate path
  end

  ##
  # Returns the path to the trusted certificate with the given ASN.1 +name+

  def name_path(name)
    digest = @digester.hexdigest name.to_s

    File.join @dir, "cert-#{digest}.pem"
  end

  ##
  # Loads the given +certificate_file+

  def load_certificate(certificate_file)
    pem = File.read certificate_file

    OpenSSL::X509::Certificate.new pem
  end

  ##
  # Add a certificate to trusted certificate list.

  def trust_cert(certificate)
    verify

    destination = cert_path certificate

    File.open destination, 'wb', 0600 do |io|
      io.write certificate.to_pem
      io.chmod(@permissions[:trusted_cert])
    end
  end

  ##
  # Make sure the trust directory exists.  If it does exist, make sure it's
  # actually a directory.  If not, then create it with the appropriate
  # permissions.

  def verify
    require 'fileutils'
    if File.exist? @dir
      raise Gem::Security::Exception,
        "trust directory #{@dir} is not a directory" unless
          File.directory? @dir

      FileUtils.chmod 0700, @dir
    else
      FileUtils.mkdir_p @dir, :mode => @permissions[:trust_dir]
    end
  end
end
# frozen_string_literal: true
##
# Basic OpenSSL-based package signing class.

require_relative "../user_interaction"

class Gem::Security::Signer
  include Gem::UserInteraction

  ##
  # The chain of certificates for signing including the signing certificate

  attr_accessor :cert_chain

  ##
  # The private key for the signing certificate

  attr_accessor :key

  ##
  # The digest algorithm used to create the signature

  attr_reader :digest_algorithm

  ##
  # The name of the digest algorithm, used to pull digests out of the hash by
  # name.

  attr_reader :digest_name # :nodoc:

  ##
  # Gem::Security::Signer options

  attr_reader :options

  DEFAULT_OPTIONS = {
    expiration_length_days: 365,
  }.freeze

  ##
  # Attempts to re-sign an expired cert with a given private key
  def self.re_sign_cert(expired_cert, expired_cert_path, private_key)
    return unless expired_cert.not_after < Time.now

    expiry = expired_cert.not_after.strftime('%Y%m%d%H%M%S')
    expired_cert_file = "#{File.basename(expired_cert_path)}.expired.#{expiry}"
    new_expired_cert_path = File.join(Gem.user_home, ".gem", expired_cert_file)

    Gem::Security.write(expired_cert, new_expired_cert_path)

    re_signed_cert = Gem::Security.re_sign(
      expired_cert,
      private_key,
      (Gem::Security::ONE_DAY * Gem.configuration.cert_expiration_length_days)
    )

    Gem::Security.write(re_signed_cert, expired_cert_path)

    yield(expired_cert_path, new_expired_cert_path) if block_given?
  end

  ##
  # Creates a new signer with an RSA +key+ or path to a key, and a certificate
  # +chain+ containing X509 certificates, encoding certificates or paths to
  # certificates.

  def initialize(key, cert_chain, passphrase = nil, options = {})
    @cert_chain = cert_chain
    @key        = key
    @passphrase = passphrase
    @options = DEFAULT_OPTIONS.merge(options)

    unless @key
      default_key = File.join Gem.default_key_path
      @key = default_key if File.exist? default_key
    end

    unless @cert_chain
      default_cert = File.join Gem.default_cert_path
      @cert_chain = [default_cert] if File.exist? default_cert
    end

    @digest_name      = Gem::Security::DIGEST_NAME
    @digest_algorithm = Gem::Security.create_digest(@digest_name)

    if @key && !@key.is_a?(OpenSSL::PKey::PKey)
      @key = OpenSSL::PKey.read(File.read(@key), @passphrase)
    end

    if @cert_chain
      @cert_chain = @cert_chain.compact.map do |cert|
        next cert if OpenSSL::X509::Certificate === cert

        cert = File.read cert if File.exist? cert

        OpenSSL::X509::Certificate.new cert
      end

      load_cert_chain
    end
  end

  ##
  # Extracts the full name of +cert+.  If the certificate has a subjectAltName
  # this value is preferred, otherwise the subject is used.

  def extract_name(cert) # :nodoc:
    subject_alt_name = cert.extensions.find {|e| 'subjectAltName' == e.oid }

    if subject_alt_name
      /\Aemail:/ =~ subject_alt_name.value # rubocop:disable Performance/StartWith

      $' || subject_alt_name.value
    else
      cert.subject
    end
  end

  ##
  # Loads any missing issuers in the cert chain from the trusted certificates.
  #
  # If the issuer does not exist it is ignored as it will be checked later.

  def load_cert_chain # :nodoc:
    return if @cert_chain.empty?

    while @cert_chain.first.issuer.to_s != @cert_chain.first.subject.to_s do
      issuer = Gem::Security.trust_dir.issuer_of @cert_chain.first

      break unless issuer # cert chain is verified later

      @cert_chain.unshift issuer
    end
  end

  ##
  # Sign data with given digest algorithm

  def sign(data)
    return unless @key

    raise Gem::Security::Exception, 'no certs provided' if @cert_chain.empty?

    if @cert_chain.length == 1 and @cert_chain.last.not_after < Time.now
      alert("Your certificate has expired, trying to re-sign it...")

      re_sign_key(
        expiration_length: (Gem::Security::ONE_DAY * options[:expiration_length_days])
      )
    end

    full_name = extract_name @cert_chain.last

    Gem::Security::SigningPolicy.verify @cert_chain, @key, {}, {}, full_name

    @key.sign @digest_algorithm.new, data
  end

  ##
  # Attempts to re-sign the private key if the signing certificate is expired.
  #
  # The key will be re-signed if:
  # * The expired certificate is self-signed
  # * The expired certificate is saved at ~/.gem/gem-public_cert.pem
  #   and the private key is saved at ~/.gem/gem-private_key.pem
  # * There is no file matching the expiry date at
  #   ~/.gem/gem-public_cert.pem.expired.%Y%m%d%H%M%S
  #
  # If the signing certificate can be re-signed the expired certificate will
  # be saved as ~/.gem/gem-public_cert.pem.expired.%Y%m%d%H%M%S where the
  # expiry time (not after) is used for the timestamp.

  def re_sign_key(expiration_length: Gem::Security::ONE_YEAR) # :nodoc:
    old_cert = @cert_chain.last

    disk_cert_path = File.join(Gem.default_cert_path)
    disk_cert = File.read(disk_cert_path) rescue nil

    disk_key_path = File.join(Gem.default_key_path)
    disk_key = OpenSSL::PKey.read(File.read(disk_key_path), @passphrase) rescue nil

    return unless disk_key

    if disk_key.to_pem == @key.to_pem && disk_cert == old_cert.to_pem
      expiry = old_cert.not_after.strftime('%Y%m%d%H%M%S')
      old_cert_file = "gem-public_cert.pem.expired.#{expiry}"
      old_cert_path = File.join(Gem.user_home, ".gem", old_cert_file)

      unless File.exist?(old_cert_path)
        Gem::Security.write(old_cert, old_cert_path)

        cert = Gem::Security.re_sign(old_cert, @key, expiration_length)

        Gem::Security.write(cert, disk_cert_path)

        alert("Your cert: #{disk_cert_path} has been auto re-signed with the key: #{disk_key_path}")
        alert("Your expired cert will be located at: #{old_cert_path}")

        @cert_chain = [cert]
      end
    end
  end
end
# frozen_string_literal: true
module Gem::Security

  ##
  # No security policy: all package signature checks are disabled.

  NoSecurity = Policy.new(
    'No Security',
    :verify_data      => false,
    :verify_signer    => false,
    :verify_chain     => false,
    :verify_root      => false,
    :only_trusted     => false,
    :only_signed      => false
  )

  ##
  # AlmostNo security policy: only verify that the signing certificate is the
  # one that actually signed the data.  Make no attempt to verify the signing
  # certificate chain.
  #
  # This policy is basically useless. better than nothing, but can still be
  # easily spoofed, and is not recommended.

  AlmostNoSecurity = Policy.new(
    'Almost No Security',
    :verify_data      => true,
    :verify_signer    => false,
    :verify_chain     => false,
    :verify_root      => false,
    :only_trusted     => false,
    :only_signed      => false
  )

  ##
  # Low security policy: only verify that the signing certificate is actually
  # the gem signer, and that the signing certificate is valid.
  #
  # This policy is better than nothing, but can still be easily spoofed, and
  # is not recommended.

  LowSecurity = Policy.new(
    'Low Security',
    :verify_data      => true,
    :verify_signer    => true,
    :verify_chain     => false,
    :verify_root      => false,
    :only_trusted     => false,
    :only_signed      => false
  )

  ##
  # Medium security policy: verify the signing certificate, verify the signing
  # certificate chain all the way to the root certificate, and only trust root
  # certificates that we have explicitly allowed trust for.
  #
  # This security policy is reasonable, but it allows unsigned packages, so a
  # malicious person could simply delete the package signature and pass the
  # gem off as unsigned.

  MediumSecurity = Policy.new(
    'Medium Security',
    :verify_data      => true,
    :verify_signer    => true,
    :verify_chain     => true,
    :verify_root      => true,
    :only_trusted     => true,
    :only_signed      => false
  )

  ##
  # High security policy: only allow signed gems to be installed, verify the
  # signing certificate, verify the signing certificate chain all the way to
  # the root certificate, and only trust root certificates that we have
  # explicitly allowed trust for.
  #
  # This security policy is significantly more difficult to bypass, and offers
  # a reasonable guarantee that the contents of the gem have not been altered.

  HighSecurity = Policy.new(
    'High Security',
    :verify_data      => true,
    :verify_signer    => true,
    :verify_chain     => true,
    :verify_root      => true,
    :only_trusted     => true,
    :only_signed      => true
  )

  ##
  # Policy used to verify a certificate and key when signing a gem

  SigningPolicy = Policy.new(
    'Signing Policy',
    :verify_data      => false,
    :verify_signer    => true,
    :verify_chain     => true,
    :verify_root      => true,
    :only_trusted     => false,
    :only_signed      => false
  )

  ##
  # Hash of configured security policies

  Policies = {
    'NoSecurity'       => NoSecurity,
    'AlmostNoSecurity' => AlmostNoSecurity,
    'LowSecurity'      => LowSecurity,
    'MediumSecurity'   => MediumSecurity,
    'HighSecurity'     => HighSecurity,
    # SigningPolicy is not intended for use by `gem -P` so do not list it
  }.freeze

end
# frozen_string_literal: true
##
# BasicSpecification is an abstract class which implements some common code
# used by both Specification and StubSpecification.

class Gem::BasicSpecification
  ##
  # Allows installation of extensions for git: gems.

  attr_writer :base_dir # :nodoc:

  ##
  # Sets the directory where extensions for this gem will be installed.

  attr_writer :extension_dir # :nodoc:

  ##
  # Is this specification ignored for activation purposes?

  attr_writer :ignored # :nodoc:

  ##
  # The path this gemspec was loaded from.  This attribute is not persisted.

  attr_accessor :loaded_from

  ##
  # Allows correct activation of git: and path: gems.

  attr_writer :full_gem_path # :nodoc:

  def initialize
    internal_init
  end

  def self.default_specifications_dir
    Gem.default_specifications_dir
  end

  class << self
    extend Gem::Deprecate
    rubygems_deprecate :default_specifications_dir, "Gem.default_specifications_dir"
  end

  ##
  # The path to the gem.build_complete file within the extension install
  # directory.

  def gem_build_complete_path # :nodoc:
    File.join extension_dir, 'gem.build_complete'
  end

  ##
  # True when the gem has been activated

  def activated?
    raise NotImplementedError
  end

  ##
  # Returns the full path to the base gem directory.
  #
  # eg: /usr/local/lib/ruby/gems/1.8

  def base_dir
    raise NotImplementedError
  end

  ##
  # Return true if this spec can require +file+.

  def contains_requirable_file?(file)
    if @ignored
      return false
    elsif missing_extensions?
      @ignored = true

      if Gem::Platform::RUBY == platform || Gem::Platform.local === platform
        warn "Ignoring #{full_name} because its extensions are not built. " +
          "Try: gem pristine #{name} --version #{version}"
      end

      return false
    end

    have_file? file, Gem.suffixes
  end

  def default_gem?
    loaded_from &&
      File.dirname(loaded_from) == Gem.default_specifications_dir
  end

  ##
  # Returns full path to the directory where gem's extensions are installed.

  def extension_dir
    @extension_dir ||= File.expand_path(File.join(extensions_dir, full_name)).tap(&Gem::UNTAINT)
  end

  ##
  # Returns path to the extensions directory.

  def extensions_dir
    Gem.default_ext_dir_for(base_dir) ||
      File.join(base_dir, 'extensions', Gem::Platform.local.to_s,
                Gem.extension_api_version)
  end

  def find_full_gem_path # :nodoc:
    # TODO: also, shouldn't it default to full_name if it hasn't been written?
    path = File.expand_path File.join(gems_dir, full_name)
    path.tap(&Gem::UNTAINT)
    path
  end

  private :find_full_gem_path

  ##
  # The full path to the gem (install path + full name).

  def full_gem_path
    # TODO: This is a heavily used method by gems, so we'll need
    # to aleast just alias it to #gem_dir rather than remove it.
    @full_gem_path ||= find_full_gem_path
  end

  ##
  # Returns the full name (name-version) of this Gem.  Platform information
  # is included (name-version-platform) if it is specified and not the
  # default Ruby platform.

  def full_name
    if platform == Gem::Platform::RUBY or platform.nil?
      "#{name}-#{version}".dup.tap(&Gem::UNTAINT)
    else
      "#{name}-#{version}-#{platform}".dup.tap(&Gem::UNTAINT)
    end
  end

  ##
  # Full paths in the gem to add to <code>$LOAD_PATH</code> when this gem is
  # activated.

  def full_require_paths
    @full_require_paths ||=
    begin
      full_paths = raw_require_paths.map do |path|
        File.join full_gem_path, path.tap(&Gem::UNTAINT)
      end

      full_paths << extension_dir if have_extensions?

      full_paths
    end
  end

  ##
  # The path to the data directory for this gem.

  def datadir
    # TODO: drop the extra ", gem_name" which is uselessly redundant
    File.expand_path(File.join(gems_dir, full_name, "data", name)).tap(&Gem::UNTAINT)
  end

  ##
  # Full path of the target library file.
  # If the file is not in this gem, return nil.

  def to_fullpath(path)
    if activated?
      @paths_map ||= {}
      @paths_map[path] ||=
      begin
        fullpath = nil
        suffixes = Gem.suffixes
        suffixes.find do |suf|
          full_require_paths.find do |dir|
            File.file?(fullpath = "#{dir}/#{path}#{suf}")
          end
        end ? fullpath : nil
      end
    else
      nil
    end
  end

  ##
  # Returns the full path to this spec's gem directory.
  # eg: /usr/local/lib/ruby/1.8/gems/mygem-1.0

  def gem_dir
    @gem_dir ||= File.expand_path File.join(gems_dir, full_name)
  end

  ##
  # Returns the full path to the gems directory containing this spec's
  # gem directory. eg: /usr/local/lib/ruby/1.8/gems

  def gems_dir
    raise NotImplementedError
  end

  def internal_init # :nodoc:
    @extension_dir = nil
    @full_gem_path = nil
    @gem_dir = nil
    @ignored = nil
  end

  ##
  # Name of the gem

  def name
    raise NotImplementedError
  end

  ##
  # Platform of the gem

  def platform
    raise NotImplementedError
  end

  def raw_require_paths # :nodoc:
    raise NotImplementedError
  end

  ##
  # Paths in the gem to add to <code>$LOAD_PATH</code> when this gem is
  # activated.
  #
  # See also #require_paths=
  #
  # If you have an extension you do not need to add <code>"ext"</code> to the
  # require path, the extension build process will copy the extension files
  # into "lib" for you.
  #
  # The default value is <code>"lib"</code>
  #
  # Usage:
  #
  #   # If all library files are in the root directory...
  #   spec.require_path = '.'

  def require_paths
    return raw_require_paths unless have_extensions?

    [extension_dir].concat raw_require_paths
  end

  ##
  # Returns the paths to the source files for use with analysis and
  # documentation tools.  These paths are relative to full_gem_path.

  def source_paths
    paths = raw_require_paths.dup

    if have_extensions?
      ext_dirs = extensions.map do |extension|
        extension.split(File::SEPARATOR, 2).first
      end.uniq

      paths.concat ext_dirs
    end

    paths.uniq
  end

  ##
  # Return all files in this gem that match for +glob+.

  def matches_for_glob(glob) # TODO: rename?
    glob = File.join(self.lib_dirs_glob, glob)

    Dir[glob].map {|f| f.tap(&Gem::UNTAINT) } # FIX our tests are broken, run w/ SAFE=1
  end

  ##
  # Returns the list of plugins in this spec.

  def plugins
    matches_for_glob("rubygems#{Gem.plugin_suffix_pattern}")
  end

  ##
  # Returns a string usable in Dir.glob to match all requirable paths
  # for this spec.

  def lib_dirs_glob
    dirs = if self.raw_require_paths
             if self.raw_require_paths.size > 1
               "{#{self.raw_require_paths.join(',')}}"
             else
               self.raw_require_paths.first
             end
           else
             "lib" # default value for require_paths for bundler/inline
           end

    "#{self.full_gem_path}/#{dirs}".dup.tap(&Gem::UNTAINT)
  end

  ##
  # Return a Gem::Specification from this gem

  def to_spec
    raise NotImplementedError
  end

  ##
  # Version of the gem

  def version
    raise NotImplementedError
  end

  ##
  # Whether this specification is stubbed - i.e. we have information
  # about the gem from a stub line, without having to evaluate the
  # entire gemspec file.
  def stubbed?
    raise NotImplementedError
  end

  def this; self; end

  private

  def have_extensions?; !extensions.empty?; end

  def have_file?(file, suffixes)
    return true if raw_require_paths.any? do |path|
      base = File.join(gems_dir, full_name, path.tap(&Gem::UNTAINT), file).tap(&Gem::UNTAINT)
      suffixes.any? {|suf| File.file? base + suf }
    end

    if have_extensions?
      base = File.join extension_dir, file
      suffixes.any? {|suf| File.file? base + suf }
    else
      false
    end
  end
end
# frozen_string_literal: true

#--
# tsort.rb - provides a module for topological sorting and strongly connected components.
#++
#

#
# Gem::TSort implements topological sorting using Tarjan's algorithm for
# strongly connected components.
#
# Gem::TSort is designed to be able to be used with any object which can be
# interpreted as a directed graph.
#
# Gem::TSort requires two methods to interpret an object as a graph,
# tsort_each_node and tsort_each_child.
#
# * tsort_each_node is used to iterate for all nodes over a graph.
# * tsort_each_child is used to iterate for child nodes of a given node.
#
# The equality of nodes are defined by eql? and hash since
# Gem::TSort uses Hash internally.
#
# == A Simple Example
#
# The following example demonstrates how to mix the Gem::TSort module into an
# existing class (in this case, Hash). Here, we're treating each key in
# the hash as a node in the graph, and so we simply alias the required
# #tsort_each_node method to Hash's #each_key method. For each key in the
# hash, the associated value is an array of the node's child nodes. This
# choice in turn leads to our implementation of the required #tsort_each_child
# method, which fetches the array of child nodes and then iterates over that
# array using the user-supplied block.
#
#   require 'rubygems/tsort/lib/tsort'
#
#   class Hash
#     include Gem::TSort
#     alias tsort_each_node each_key
#     def tsort_each_child(node, &block)
#       fetch(node).each(&block)
#     end
#   end
#
#   {1=>[2, 3], 2=>[3], 3=>[], 4=>[]}.tsort
#   #=> [3, 2, 1, 4]
#
#   {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}.strongly_connected_components
#   #=> [[4], [2, 3], [1]]
#
# == A More Realistic Example
#
# A very simple `make' like tool can be implemented as follows:
#
#   require 'rubygems/tsort/lib/tsort'
#
#   class Make
#     def initialize
#       @dep = {}
#       @dep.default = []
#     end
#
#     def rule(outputs, inputs=[], &block)
#       triple = [outputs, inputs, block]
#       outputs.each {|f| @dep[f] = [triple]}
#       @dep[triple] = inputs
#     end
#
#     def build(target)
#       each_strongly_connected_component_from(target) {|ns|
#         if ns.length != 1
#           fs = ns.delete_if {|n| Array === n}
#           raise Gem::TSort::Cyclic.new("cyclic dependencies: #{fs.join ', '}")
#         end
#         n = ns.first
#         if Array === n
#           outputs, inputs, block = n
#           inputs_time = inputs.map {|f| File.mtime f}.max
#           begin
#             outputs_time = outputs.map {|f| File.mtime f}.min
#           rescue Errno::ENOENT
#             outputs_time = nil
#           end
#           if outputs_time == nil ||
#              inputs_time != nil && outputs_time <= inputs_time
#             sleep 1 if inputs_time != nil && inputs_time.to_i == Time.now.to_i
#             block.call
#           end
#         end
#       }
#     end
#
#     def tsort_each_child(node, &block)
#       @dep[node].each(&block)
#     end
#     include Gem::TSort
#   end
#
#   def command(arg)
#     print arg, "\n"
#     system arg
#   end
#
#   m = Make.new
#   m.rule(%w[t1]) { command 'date > t1' }
#   m.rule(%w[t2]) { command 'date > t2' }
#   m.rule(%w[t3]) { command 'date > t3' }
#   m.rule(%w[t4], %w[t1 t3]) { command 'cat t1 t3 > t4' }
#   m.rule(%w[t5], %w[t4 t2]) { command 'cat t4 t2 > t5' }
#   m.build('t5')
#
# == Bugs
#
# * 'tsort.rb' is wrong name because this library uses
#   Tarjan's algorithm for strongly connected components.
#   Although 'strongly_connected_components.rb' is correct but too long.
#
# == References
#
# R. E. Tarjan, "Depth First Search and Linear Graph Algorithms",
# <em>SIAM Journal on Computing</em>, Vol. 1, No. 2, pp. 146-160, June 1972.
#

module Gem
  module TSort
    class Cyclic < StandardError
    end

    # Returns a topologically sorted array of nodes.
    # The array is sorted from children to parents, i.e.
    # the first element has no child and the last node has no parent.
    #
    # If there is a cycle, Gem::TSort::Cyclic is raised.
    #
    #   class G
    #     include Gem::TSort
    #     def initialize(g)
    #       @g = g
    #     end
    #     def tsort_each_child(n, &b) @g[n].each(&b) end
    #     def tsort_each_node(&b) @g.each_key(&b) end
    #   end
    #
    #   graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
    #   p graph.tsort #=> [4, 2, 3, 1]
    #
    #   graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
    #   p graph.tsort # raises Gem::TSort::Cyclic
    #
    def tsort
      each_node = method(:tsort_each_node)
      each_child = method(:tsort_each_child)
      Gem::TSort.tsort(each_node, each_child)
    end

    # Returns a topologically sorted array of nodes.
    # The array is sorted from children to parents, i.e.
    # the first element has no child and the last node has no parent.
    #
    # The graph is represented by _each_node_ and _each_child_.
    # _each_node_ should have +call+ method which yields for each node in the graph.
    # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
    #
    # If there is a cycle, Gem::TSort::Cyclic is raised.
    #
    #   g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
    #   each_node = lambda {|&b| g.each_key(&b) }
    #   each_child = lambda {|n, &b| g[n].each(&b) }
    #   p Gem::TSort.tsort(each_node, each_child) #=> [4, 2, 3, 1]
    #
    #   g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
    #   each_node = lambda {|&b| g.each_key(&b) }
    #   each_child = lambda {|n, &b| g[n].each(&b) }
    #   p Gem::TSort.tsort(each_node, each_child) # raises Gem::TSort::Cyclic
    #
    def TSort.tsort(each_node, each_child)
      Gem::TSort.tsort_each(each_node, each_child).to_a
    end

    # The iterator version of the #tsort method.
    # <tt><em>obj</em>.tsort_each</tt> is similar to <tt><em>obj</em>.tsort.each</tt>, but
    # modification of _obj_ during the iteration may lead to unexpected results.
    #
    # #tsort_each returns +nil+.
    # If there is a cycle, Gem::TSort::Cyclic is raised.
    #
    #   class G
    #     include Gem::TSort
    #     def initialize(g)
    #       @g = g
    #     end
    #     def tsort_each_child(n, &b) @g[n].each(&b) end
    #     def tsort_each_node(&b) @g.each_key(&b) end
    #   end
    #
    #   graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
    #   graph.tsort_each {|n| p n }
    #   #=> 4
    #   #   2
    #   #   3
    #   #   1
    #
    def tsort_each(&block) # :yields: node
      each_node = method(:tsort_each_node)
      each_child = method(:tsort_each_child)
      Gem::TSort.tsort_each(each_node, each_child, &block)
    end

    # The iterator version of the Gem::TSort.tsort method.
    #
    # The graph is represented by _each_node_ and _each_child_.
    # _each_node_ should have +call+ method which yields for each node in the graph.
    # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
    #
    #   g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
    #   each_node = lambda {|&b| g.each_key(&b) }
    #   each_child = lambda {|n, &b| g[n].each(&b) }
    #   Gem::TSort.tsort_each(each_node, each_child) {|n| p n }
    #   #=> 4
    #   #   2
    #   #   3
    #   #   1
    #
    def TSort.tsort_each(each_node, each_child) # :yields: node
      return to_enum(__method__, each_node, each_child) unless block_given?

      Gem::TSort.each_strongly_connected_component(each_node, each_child) {|component|
        if component.size == 1
          yield component.first
        else
          raise Cyclic.new("topological sort failed: #{component.inspect}")
        end
      }
    end

    # Returns strongly connected components as an array of arrays of nodes.
    # The array is sorted from children to parents.
    # Each elements of the array represents a strongly connected component.
    #
    #   class G
    #     include Gem::TSort
    #     def initialize(g)
    #       @g = g
    #     end
    #     def tsort_each_child(n, &b) @g[n].each(&b) end
    #     def tsort_each_node(&b) @g.each_key(&b) end
    #   end
    #
    #   graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
    #   p graph.strongly_connected_components #=> [[4], [2], [3], [1]]
    #
    #   graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
    #   p graph.strongly_connected_components #=> [[4], [2, 3], [1]]
    #
    def strongly_connected_components
      each_node = method(:tsort_each_node)
      each_child = method(:tsort_each_child)
      Gem::TSort.strongly_connected_components(each_node, each_child)
    end

    # Returns strongly connected components as an array of arrays of nodes.
    # The array is sorted from children to parents.
    # Each elements of the array represents a strongly connected component.
    #
    # The graph is represented by _each_node_ and _each_child_.
    # _each_node_ should have +call+ method which yields for each node in the graph.
    # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
    #
    #   g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
    #   each_node = lambda {|&b| g.each_key(&b) }
    #   each_child = lambda {|n, &b| g[n].each(&b) }
    #   p Gem::TSort.strongly_connected_components(each_node, each_child)
    #   #=> [[4], [2], [3], [1]]
    #
    #   g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
    #   each_node = lambda {|&b| g.each_key(&b) }
    #   each_child = lambda {|n, &b| g[n].each(&b) }
    #   p Gem::TSort.strongly_connected_components(each_node, each_child)
    #   #=> [[4], [2, 3], [1]]
    #
    def TSort.strongly_connected_components(each_node, each_child)
      Gem::TSort.each_strongly_connected_component(each_node, each_child).to_a
    end

    # The iterator version of the #strongly_connected_components method.
    # <tt><em>obj</em>.each_strongly_connected_component</tt> is similar to
    # <tt><em>obj</em>.strongly_connected_components.each</tt>, but
    # modification of _obj_ during the iteration may lead to unexpected results.
    #
    # #each_strongly_connected_component returns +nil+.
    #
    #   class G
    #     include Gem::TSort
    #     def initialize(g)
    #       @g = g
    #     end
    #     def tsort_each_child(n, &b) @g[n].each(&b) end
    #     def tsort_each_node(&b) @g.each_key(&b) end
    #   end
    #
    #   graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
    #   graph.each_strongly_connected_component {|scc| p scc }
    #   #=> [4]
    #   #   [2]
    #   #   [3]
    #   #   [1]
    #
    #   graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
    #   graph.each_strongly_connected_component {|scc| p scc }
    #   #=> [4]
    #   #   [2, 3]
    #   #   [1]
    #
    def each_strongly_connected_component(&block) # :yields: nodes
      each_node = method(:tsort_each_node)
      each_child = method(:tsort_each_child)
      Gem::TSort.each_strongly_connected_component(each_node, each_child, &block)
    end

    # The iterator version of the Gem::TSort.strongly_connected_components method.
    #
    # The graph is represented by _each_node_ and _each_child_.
    # _each_node_ should have +call+ method which yields for each node in the graph.
    # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
    #
    #   g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
    #   each_node = lambda {|&b| g.each_key(&b) }
    #   each_child = lambda {|n, &b| g[n].each(&b) }
    #   Gem::TSort.each_strongly_connected_component(each_node, each_child) {|scc| p scc }
    #   #=> [4]
    #   #   [2]
    #   #   [3]
    #   #   [1]
    #
    #   g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
    #   each_node = lambda {|&b| g.each_key(&b) }
    #   each_child = lambda {|n, &b| g[n].each(&b) }
    #   Gem::TSort.each_strongly_connected_component(each_node, each_child) {|scc| p scc }
    #   #=> [4]
    #   #   [2, 3]
    #   #   [1]
    #
    def TSort.each_strongly_connected_component(each_node, each_child) # :yields: nodes
      return to_enum(__method__, each_node, each_child) unless block_given?

      id_map = {}
      stack = []
      each_node.call {|node|
        unless id_map.include? node
          Gem::TSort.each_strongly_connected_component_from(node, each_child, id_map, stack) {|c|
            yield c
          }
        end
      }
      nil
    end

    # Iterates over strongly connected component in the subgraph reachable from
    # _node_.
    #
    # Return value is unspecified.
    #
    # #each_strongly_connected_component_from doesn't call #tsort_each_node.
    #
    #   class G
    #     include Gem::TSort
    #     def initialize(g)
    #       @g = g
    #     end
    #     def tsort_each_child(n, &b) @g[n].each(&b) end
    #     def tsort_each_node(&b) @g.each_key(&b) end
    #   end
    #
    #   graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
    #   graph.each_strongly_connected_component_from(2) {|scc| p scc }
    #   #=> [4]
    #   #   [2]
    #
    #   graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
    #   graph.each_strongly_connected_component_from(2) {|scc| p scc }
    #   #=> [4]
    #   #   [2, 3]
    #
    def each_strongly_connected_component_from(node, id_map={}, stack=[], &block) # :yields: nodes
      Gem::TSort.each_strongly_connected_component_from(node, method(:tsort_each_child), id_map, stack, &block)
    end

    # Iterates over strongly connected components in a graph.
    # The graph is represented by _node_ and _each_child_.
    #
    # _node_ is the first node.
    # _each_child_ should have +call+ method which takes a node argument
    # and yields for each child node.
    #
    # Return value is unspecified.
    #
    # #Gem::TSort.each_strongly_connected_component_from is a class method and
    # it doesn't need a class to represent a graph which includes Gem::TSort.
    #
    #   graph = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
    #   each_child = lambda {|n, &b| graph[n].each(&b) }
    #   Gem::TSort.each_strongly_connected_component_from(1, each_child) {|scc|
    #     p scc
    #   }
    #   #=> [4]
    #   #   [2, 3]
    #   #   [1]
    #
    def TSort.each_strongly_connected_component_from(node, each_child, id_map={}, stack=[]) # :yields: nodes
      return to_enum(__method__, node, each_child, id_map, stack) unless block_given?

      minimum_id = node_id = id_map[node] = id_map.size
      stack_length = stack.length
      stack << node

      each_child.call(node) {|child|
        if id_map.include? child
          child_id = id_map[child]
          minimum_id = child_id if child_id && child_id < minimum_id
        else
          sub_minimum_id =
            Gem::TSort.each_strongly_connected_component_from(child, each_child, id_map, stack) {|c|
              yield c
            }
          minimum_id = sub_minimum_id if sub_minimum_id < minimum_id
        end
      }

      if node_id == minimum_id
        component = stack.slice!(stack_length .. -1)
        component.each {|n| id_map[n] = nil}
        yield component
      end

      minimum_id
    end

    # Should be implemented by a extended class.
    #
    # #tsort_each_node is used to iterate for all nodes over a graph.
    #
    def tsort_each_node # :yields: node
      raise NotImplementedError.new
    end

    # Should be implemented by a extended class.
    #
    # #tsort_each_child is used to iterate for child nodes of _node_.
    #
    def tsort_each_child(node) # :yields: child
      raise NotImplementedError.new
    end
  end
end
# frozen_string_literal: true
require_relative '../rubygems'
require_relative 'dependency_list'
require_relative 'package'
require_relative 'installer'
require_relative 'spec_fetcher'
require_relative 'user_interaction'
require_relative 'available_set'
require_relative 'deprecate'

##
# Installs a gem along with all its dependencies from local and remote gems.

class Gem::DependencyInstaller
  include Gem::UserInteraction
  extend Gem::Deprecate

  DEFAULT_OPTIONS = { # :nodoc:
    :env_shebang         => false,
    :document            => %w[ri],
    :domain              => :both, # HACK dup
    :force               => false,
    :format_executable   => false, # HACK dup
    :ignore_dependencies => false,
    :prerelease          => false,
    :security_policy     => nil, # HACK NoSecurity requires OpenSSL. AlmostNo? Low?
    :wrappers            => true,
    :build_args          => nil,
    :build_docs_in_background => false,
    :install_as_default => false,
  }.freeze

  ##
  # Documentation types.  For use by the Gem.done_installing hook

  attr_reader :document

  ##
  # Errors from SpecFetcher while searching for remote specifications

  attr_reader :errors

  ##
  # List of gems installed by #install in alphabetic order

  attr_reader :installed_gems

  ##
  # Creates a new installer instance.
  #
  # Options are:
  # :cache_dir:: Alternate repository path to store .gem files in.
  # :domain:: :local, :remote, or :both.  :local only searches gems in the
  #           current directory.  :remote searches only gems in Gem::sources.
  #           :both searches both.
  # :env_shebang:: See Gem::Installer::new.
  # :force:: See Gem::Installer#install.
  # :format_executable:: See Gem::Installer#initialize.
  # :ignore_dependencies:: Don't install any dependencies.
  # :install_dir:: See Gem::Installer#install.
  # :prerelease:: Allow prerelease versions.  See #install.
  # :security_policy:: See Gem::Installer::new and Gem::Security.
  # :user_install:: See Gem::Installer.new
  # :wrappers:: See Gem::Installer::new
  # :build_args:: See Gem::Installer::new

  def initialize(options = {})
    @only_install_dir = !!options[:install_dir]
    @install_dir = options[:install_dir] || Gem.dir
    @build_root = options[:build_root]

    options = DEFAULT_OPTIONS.merge options

    @bin_dir             = options[:bin_dir]
    @dev_shallow         = options[:dev_shallow]
    @development         = options[:development]
    @document            = options[:document]
    @domain              = options[:domain]
    @env_shebang         = options[:env_shebang]
    @force               = options[:force]
    @format_executable   = options[:format_executable]
    @ignore_dependencies = options[:ignore_dependencies]
    @prerelease          = options[:prerelease]
    @security_policy     = options[:security_policy]
    @user_install        = options[:user_install]
    @wrappers            = options[:wrappers]
    @build_args          = options[:build_args]
    @build_docs_in_background = options[:build_docs_in_background]
    @install_as_default = options[:install_as_default]
    @dir_mode = options[:dir_mode]
    @data_mode = options[:data_mode]
    @prog_mode = options[:prog_mode]

    # Indicates that we should not try to update any deps unless
    # we absolutely must.
    @minimal_deps = options[:minimal_deps]

    @available      = nil
    @installed_gems = []
    @toplevel_specs = nil

    @cache_dir = options[:cache_dir] || @install_dir

    @errors = []
  end

  ##
  # Indicated, based on the requested domain, if local
  # gems should be considered.

  def consider_local?
    @domain == :both or @domain == :local
  end

  ##
  # Indicated, based on the requested domain, if remote
  # gems should be considered.

  def consider_remote?
    @domain == :both or @domain == :remote
  end

  ##
  # Returns a list of pairs of gemspecs and source_uris that match
  # Gem::Dependency +dep+ from both local (Dir.pwd) and remote (Gem.sources)
  # sources.  Gems are sorted with newer gems preferred over older gems, and
  # local gems preferred over remote gems.

  def find_gems_with_sources(dep, best_only=false) # :nodoc:
    set = Gem::AvailableSet.new

    if consider_local?
      sl = Gem::Source::Local.new

      if spec = sl.find_gem(dep.name)
        if dep.matches_spec? spec
          set.add spec, sl
        end
      end
    end

    if consider_remote?
      begin
        # This is pulled from #spec_for_dependency to allow
        # us to filter tuples before fetching specs.
        tuples, errors = Gem::SpecFetcher.fetcher.search_for_dependency dep

        if best_only && !tuples.empty?
          tuples.sort! do |a,b|
            if b[0].version == a[0].version
              if b[0].platform != Gem::Platform::RUBY
                1
              else
                -1
              end
            else
              b[0].version <=> a[0].version
            end
          end
          tuples = [tuples.first]
        end

        specs = []
        tuples.each do |tup, source|
          begin
            spec = source.fetch_spec(tup)
          rescue Gem::RemoteFetcher::FetchError => e
            errors << Gem::SourceFetchProblem.new(source, e)
          else
            specs << [spec, source]
          end
        end

        if @errors
          @errors += errors
        else
          @errors = errors
        end

        set << specs

      rescue Gem::RemoteFetcher::FetchError => e
        # FIX if there is a problem talking to the network, we either need to always tell
        # the user (no really_verbose) or fail hard, not silently tell them that we just
        # couldn't find their requested gem.
        verbose do
          "Error fetching remote data:\t\t#{e.message}\n" \
            "Falling back to local-only install"
        end
        @domain = :local
      end
    end

    set
  end
  rubygems_deprecate :find_gems_with_sources

  def in_background(what) # :nodoc:
    fork_happened = false
    if @build_docs_in_background and Process.respond_to?(:fork)
      begin
        Process.fork do
          yield
        end
        fork_happened = true
        say "#{what} in a background process."
      rescue NotImplementedError
      end
    end
    yield unless fork_happened
  end

  ##
  # Installs the gem +dep_or_name+ and all its dependencies.  Returns an Array
  # of installed gem specifications.
  #
  # If the +:prerelease+ option is set and there is a prerelease for
  # +dep_or_name+ the prerelease version will be installed.
  #
  # Unless explicitly specified as a prerelease dependency, prerelease gems
  # that +dep_or_name+ depend on will not be installed.
  #
  # If c-1.a depends on b-1 and a-1.a and there is a gem b-1.a available then
  # c-1.a, b-1 and a-1.a will be installed.  b-1.a will need to be installed
  # separately.

  def install(dep_or_name, version = Gem::Requirement.default)
    request_set = resolve_dependencies dep_or_name, version

    @installed_gems = []

    options = {
      :bin_dir             => @bin_dir,
      :build_args          => @build_args,
      :document            => @document,
      :env_shebang         => @env_shebang,
      :force               => @force,
      :format_executable   => @format_executable,
      :ignore_dependencies => @ignore_dependencies,
      :prerelease          => @prerelease,
      :security_policy     => @security_policy,
      :user_install        => @user_install,
      :wrappers            => @wrappers,
      :build_root          => @build_root,
      :install_as_default  => @install_as_default,
      :dir_mode            => @dir_mode,
      :data_mode           => @data_mode,
      :prog_mode           => @prog_mode,
    }
    options[:install_dir] = @install_dir if @only_install_dir

    request_set.install options do |_, installer|
      @installed_gems << installer.spec if installer
    end

    @installed_gems.sort!

    # Since this is currently only called for docs, we can be lazy and just say
    # it's documentation. Ideally the hook adder could decide whether to be in
    # the background or not, and what to call it.
    in_background "Installing documentation" do
      Gem.done_installing_hooks.each do |hook|
        hook.call self, @installed_gems
      end
    end unless Gem.done_installing_hooks.empty?

    @installed_gems
  end

  def install_development_deps # :nodoc:
    if @development and @dev_shallow
      :shallow
    elsif @development
      :all
    else
      :none
    end
  end

  def resolve_dependencies(dep_or_name, version) # :nodoc:
    request_set = Gem::RequestSet.new
    request_set.development         = @development
    request_set.development_shallow = @dev_shallow
    request_set.soft_missing = @force
    request_set.prerelease = @prerelease

    installer_set = Gem::Resolver::InstallerSet.new @domain
    installer_set.ignore_installed = (@minimal_deps == false) || @only_install_dir
    installer_set.force = @force

    if consider_local?
      if dep_or_name =~ /\.gem$/ and File.file? dep_or_name
        src = Gem::Source::SpecificFile.new dep_or_name
        installer_set.add_local dep_or_name, src.spec, src
        version = src.spec.version if version == Gem::Requirement.default
      elsif dep_or_name =~ /\.gem$/
        Dir[dep_or_name].each do |name|
          begin
            src = Gem::Source::SpecificFile.new name
            installer_set.add_local dep_or_name, src.spec, src
          rescue Gem::Package::FormatError
          end
        end
        # else This is a dependency. InstallerSet handles this case
      end
    end

    dependency =
      if spec = installer_set.local?(dep_or_name)
        installer_set.remote = nil if spec.dependencies.none?
        Gem::Dependency.new spec.name, version
      elsif String === dep_or_name
        Gem::Dependency.new dep_or_name, version
      else
        dep_or_name
      end

    dependency.prerelease = @prerelease

    request_set.import [dependency]

    installer_set.add_always_install dependency

    request_set.always_install = installer_set.always_install
    request_set.remote = installer_set.consider_remote?

    if @ignore_dependencies
      installer_set.ignore_dependencies = true
      request_set.ignore_dependencies   = true
      request_set.soft_missing          = true
    end

    request_set.resolve installer_set

    @errors.concat request_set.errors

    request_set
  end
end
require_relative 'openssl'

##
# S3URISigner implements AWS SigV4 for S3 Source to avoid a dependency on the aws-sdk-* gems
# More on AWS SigV4: https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html
class Gem::S3URISigner
  class ConfigurationError < Gem::Exception
    def initialize(message)
      super message
    end

    def to_s # :nodoc:
      "#{super}"
    end
  end

  class InstanceProfileError < Gem::Exception
    def initialize(message)
      super message
    end

    def to_s # :nodoc:
      "#{super}"
    end
  end

  attr_accessor :uri

  def initialize(uri)
    @uri = uri
  end

  ##
  # Signs S3 URI using query-params according to the reference: https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html
  def sign(expiration = 86400)
    s3_config = fetch_s3_config

    current_time = Time.now.utc
    date_time = current_time.strftime("%Y%m%dT%H%m%SZ")
    date = date_time[0,8]

    credential_info = "#{date}/#{s3_config.region}/s3/aws4_request"
    canonical_host = "#{uri.host}.s3.#{s3_config.region}.amazonaws.com"

    query_params = generate_canonical_query_params(s3_config, date_time, credential_info, expiration)
    canonical_request = generate_canonical_request(canonical_host, query_params)
    string_to_sign = generate_string_to_sign(date_time, credential_info, canonical_request)
    signature = generate_signature(s3_config, date, string_to_sign)

    URI.parse("https://#{canonical_host}#{uri.path}?#{query_params}&X-Amz-Signature=#{signature}")
  end

  private

  S3Config = Struct.new :access_key_id, :secret_access_key, :security_token, :region

  def generate_canonical_query_params(s3_config, date_time, credential_info, expiration)
    canonical_params = {}
    canonical_params["X-Amz-Algorithm"] = "AWS4-HMAC-SHA256"
    canonical_params["X-Amz-Credential"] = "#{s3_config.access_key_id}/#{credential_info}"
    canonical_params["X-Amz-Date"] = date_time
    canonical_params["X-Amz-Expires"] = expiration.to_s
    canonical_params["X-Amz-SignedHeaders"] = "host"
    canonical_params["X-Amz-Security-Token"] = s3_config.security_token if s3_config.security_token

    # Sorting is required to generate proper signature
    canonical_params.sort.to_h.map do |key, value|
      "#{base64_uri_escape(key)}=#{base64_uri_escape(value)}"
    end.join("&")
  end

  def generate_canonical_request(canonical_host, query_params)
    [
      "GET",
      uri.path,
      query_params,
      "host:#{canonical_host}",
      "", # empty params
      "host",
      "UNSIGNED-PAYLOAD",
    ].join("\n")
  end

  def generate_string_to_sign(date_time, credential_info, canonical_request)
    [
      "AWS4-HMAC-SHA256",
      date_time,
      credential_info,
      OpenSSL::Digest::SHA256.hexdigest(canonical_request),
    ].join("\n")
  end

  def generate_signature(s3_config, date, string_to_sign)
    date_key = OpenSSL::HMAC.digest("sha256", "AWS4" + s3_config.secret_access_key, date)
    date_region_key = OpenSSL::HMAC.digest("sha256", date_key, s3_config.region)
    date_region_service_key = OpenSSL::HMAC.digest("sha256", date_region_key, "s3")
    signing_key = OpenSSL::HMAC.digest("sha256", date_region_service_key, "aws4_request")
    OpenSSL::HMAC.hexdigest("sha256", signing_key, string_to_sign)
  end

  ##
  # Extracts S3 configuration for S3 bucket
  def fetch_s3_config
    return S3Config.new(uri.user, uri.password, nil, "us-east-1") if uri.user && uri.password

    s3_source = Gem.configuration[:s3_source] || Gem.configuration["s3_source"]
    host = uri.host
    raise ConfigurationError.new("no s3_source key exists in .gemrc") unless s3_source

    auth = s3_source[host] || s3_source[host.to_sym]
    raise ConfigurationError.new("no key for host #{host} in s3_source in .gemrc") unless auth

    provider = auth[:provider] || auth["provider"]
    case provider
    when "env"
      id = ENV["AWS_ACCESS_KEY_ID"]
      secret = ENV["AWS_SECRET_ACCESS_KEY"]
      security_token = ENV["AWS_SESSION_TOKEN"]
    when "instance_profile"
      credentials = ec2_metadata_credentials_json
      id = credentials["AccessKeyId"]
      secret = credentials["SecretAccessKey"]
      security_token = credentials["Token"]
    else
      id = auth[:id] || auth["id"]
      secret = auth[:secret] || auth["secret"]
      security_token = auth[:security_token] || auth["security_token"]
    end

    raise ConfigurationError.new("s3_source for #{host} missing id or secret") unless id && secret

    region = auth[:region] || auth["region"] || "us-east-1"
    S3Config.new(id, secret, security_token, region)
  end

  def base64_uri_escape(str)
    str.gsub(/[\+\/=\n]/, BASE64_URI_TRANSLATE)
  end

  def ec2_metadata_credentials_json
    require 'net/http'
    require_relative 'request'
    require_relative 'request/connection_pools'
    require 'json'

    iam_info = ec2_metadata_request(EC2_IAM_INFO)
    # Expected format: arn:aws:iam::<id>:instance-profile/<role_name>
    role_name = iam_info['InstanceProfileArn'].split('/').last
    ec2_metadata_request(EC2_IAM_SECURITY_CREDENTIALS + role_name)
  end

  def ec2_metadata_request(url)
    uri = URI(url)
    @request_pool ||= create_request_pool(uri)
    request = Gem::Request.new(uri, Net::HTTP::Get, nil, @request_pool)
    response = request.fetch

    case response
    when Net::HTTPOK then
      JSON.parse(response.body)
    else
      raise InstanceProfileError.new("Unable to fetch AWS metadata from #{uri}: #{response.message} #{response.code}")
    end
  end

  def create_request_pool(uri)
    proxy_uri = Gem::Request.proxy_uri(Gem::Request.get_proxy_from_env(uri.scheme))
    certs = Gem::Request.get_cert_files
    Gem::Request::ConnectionPools.new(proxy_uri, certs).pool_for(uri)
  end

  BASE64_URI_TRANSLATE = { "+" => "%2B", "/" => "%2F", "=" => "%3D", "\n" => "" }.freeze
  EC2_IAM_INFO = "http://169.254.169.254/latest/meta-data/iam/info".freeze
  EC2_IAM_SECURITY_CREDENTIALS = "http://169.254.169.254/latest/meta-data/iam/security-credentials/".freeze
end
# frozen_string_literal: true
require_relative "version"

##
# A Requirement is a set of one or more version restrictions. It supports a
# few (<tt>=, !=, >, <, >=, <=, ~></tt>) different restriction operators.
#
# See Gem::Version for a description on how versions and requirements work
# together in RubyGems.

class Gem::Requirement
  OPS = { #:nodoc:
    "="  =>  lambda {|v, r| v == r },
    "!=" =>  lambda {|v, r| v != r },
    ">"  =>  lambda {|v, r| v >  r },
    "<"  =>  lambda {|v, r| v <  r },
    ">=" =>  lambda {|v, r| v >= r },
    "<=" =>  lambda {|v, r| v <= r },
    "~>" =>  lambda {|v, r| v >= r && v.release < r.bump },
  }.freeze

  SOURCE_SET_REQUIREMENT = Struct.new(:for_lockfile).new "!" # :nodoc:

  quoted = OPS.keys.map {|k| Regexp.quote k }.join "|"
  PATTERN_RAW = "\\s*(#{quoted})?\\s*(#{Gem::Version::VERSION_PATTERN})\\s*".freeze # :nodoc:

  ##
  # A regular expression that matches a requirement

  PATTERN = /\A#{PATTERN_RAW}\z/.freeze

  ##
  # The default requirement matches any non-prerelease version

  DefaultRequirement = [">=", Gem::Version.new(0)].freeze

  ##
  # The default requirement matches any version

  DefaultPrereleaseRequirement = [">=", Gem::Version.new("0.a")].freeze

  ##
  # Raised when a bad requirement is encountered

  class BadRequirementError < ArgumentError; end

  ##
  # Factory method to create a Gem::Requirement object.  Input may be
  # a Version, a String, or nil.  Intended to simplify client code.
  #
  # If the input is "weird", the default version requirement is
  # returned.

  def self.create(*inputs)
    return new inputs if inputs.length > 1

    input = inputs.shift

    case input
    when Gem::Requirement then
      input
    when Gem::Version, Array then
      new input
    when '!' then
      source_set
    else
      if input.respond_to? :to_str
        new [input.to_str]
      else
        default
      end
    end
  end

  def self.default
    new '>= 0'
  end

  def self.default_prerelease
    new '>= 0.a'
  end

  ###
  # A source set requirement, used for Gemfiles and lockfiles

  def self.source_set # :nodoc:
    SOURCE_SET_REQUIREMENT
  end

  ##
  # Parse +obj+, returning an <tt>[op, version]</tt> pair. +obj+ can
  # be a String or a Gem::Version.
  #
  # If +obj+ is a String, it can be either a full requirement
  # specification, like <tt>">= 1.2"</tt>, or a simple version number,
  # like <tt>"1.2"</tt>.
  #
  #     parse("> 1.0")                 # => [">", Gem::Version.new("1.0")]
  #     parse("1.0")                   # => ["=", Gem::Version.new("1.0")]
  #     parse(Gem::Version.new("1.0")) # => ["=,  Gem::Version.new("1.0")]

  def self.parse(obj)
    return ["=", obj] if Gem::Version === obj

    unless PATTERN =~ obj.to_s
      raise BadRequirementError, "Illformed requirement [#{obj.inspect}]"
    end

    if $1 == ">=" && $2 == "0"
      DefaultRequirement
    elsif $1 == ">=" && $2 == "0.a"
      DefaultPrereleaseRequirement
    else
      [-($1 || "="), Gem::Version.new($2)]
    end
  end

  ##
  # An array of requirement pairs. The first element of the pair is
  # the op, and the second is the Gem::Version.

  attr_reader :requirements #:nodoc:

  ##
  # Constructs a requirement from +requirements+. Requirements can be
  # Strings, Gem::Versions, or Arrays of those. +nil+ and duplicate
  # requirements are ignored. An empty set of +requirements+ is the
  # same as <tt>">= 0"</tt>.

  def initialize(*requirements)
    requirements = requirements.flatten
    requirements.compact!
    requirements.uniq!

    if requirements.empty?
      @requirements = [DefaultRequirement]
    else
      @requirements = requirements.map! {|r| self.class.parse r }
    end
  end

  ##
  # Concatenates the +new+ requirements onto this requirement.

  def concat(new)
    new = new.flatten
    new.compact!
    new.uniq!
    new = new.map {|r| self.class.parse r }

    @requirements.concat new
  end

  ##
  # Formats this requirement for use in a Gem::RequestSet::Lockfile.

  def for_lockfile # :nodoc:
    return if [DefaultRequirement] == @requirements

    list = requirements.sort_by do |_, version|
      version
    end.map do |op, version|
      "#{op} #{version}"
    end.uniq

    " (#{list.join ', '})"
  end

  ##
  # true if this gem has no requirements.

  def none?
    if @requirements.size == 1
      @requirements[0] == DefaultRequirement
    else
      false
    end
  end

  ##
  # true if the requirement is for only an exact version

  def exact?
    return false unless @requirements.size == 1
    @requirements[0][0] == "="
  end

  def as_list # :nodoc:
    requirements.map {|op, version| "#{op} #{version}" }
  end

  def hash # :nodoc:
    requirements.map {|r| r.first == "~>" ? [r[0], r[1].to_s] : r }.sort.hash
  end

  def marshal_dump # :nodoc:
    [@requirements]
  end

  def marshal_load(array) # :nodoc:
    @requirements = array[0]

    raise TypeError, "wrong @requirements" unless Array === @requirements
  end

  def yaml_initialize(tag, vals) # :nodoc:
    vals.each do |ivar, val|
      instance_variable_set "@#{ivar}", val
    end
  end

  def init_with(coder) # :nodoc:
    yaml_initialize coder.tag, coder.map
  end

  def to_yaml_properties # :nodoc:
    ["@requirements"]
  end

  def encode_with(coder) # :nodoc:
    coder.add 'requirements', @requirements
  end

  ##
  # A requirement is a prerelease if any of the versions inside of it
  # are prereleases

  def prerelease?
    requirements.any? {|r| r.last.prerelease? }
  end

  def pretty_print(q) # :nodoc:
    q.group 1, 'Gem::Requirement.new(', ')' do
      q.pp as_list
    end
  end

  ##
  # True if +version+ satisfies this Requirement.

  def satisfied_by?(version)
    raise ArgumentError, "Need a Gem::Version: #{version.inspect}" unless
      Gem::Version === version
    requirements.all? {|op, rv| OPS[op].call version, rv }
  end

  alias :=== :satisfied_by?
  alias :=~ :satisfied_by?

  ##
  # True if the requirement will not always match the latest version.

  def specific?
    return true if @requirements.length > 1 # GIGO, > 1, > 2 is silly

    not %w[> >=].include? @requirements.first.first # grab the operator
  end

  def to_s # :nodoc:
    as_list.join ", "
  end

  def ==(other) # :nodoc:
    return unless Gem::Requirement === other

    # An == check is always necessary
    return false unless _sorted_requirements == other._sorted_requirements

    # An == check is sufficient unless any requirements use ~>
    return true unless _tilde_requirements.any?

    # If any requirements use ~> we use the stricter `#eql?` that also checks
    # that version precision is the same
    _tilde_requirements.eql?(other._tilde_requirements)
  end

  protected

  def _sorted_requirements
    @_sorted_requirements ||= requirements.sort_by(&:to_s)
  end

  def _tilde_requirements
    @_tilde_requirements ||= _sorted_requirements.select {|r| r.first == "~>" }
  end
end

class Gem::Version
  # This is needed for compatibility with older yaml
  # gemspecs.

  Requirement = Gem::Requirement # :nodoc:
end
# frozen_string_literal: true
#--
# This file contains all the various exceptions and other errors that are used
# inside of RubyGems.
#
# DOC: Confirm _all_
#++

module Gem
  ##
  # Raised when RubyGems is unable to load or activate a gem.  Contains the
  # name and version requirements of the gem that either conflicts with
  # already activated gems or that RubyGems is otherwise unable to activate.

  class LoadError < ::LoadError
    # Name of gem
    attr_accessor :name

    # Version requirement of gem
    attr_accessor :requirement
  end

  ##
  # Raised when trying to activate a gem, and that gem does not exist on the
  # system.  Instead of rescuing from this class, make sure to rescue from the
  # superclass Gem::LoadError to catch all types of load errors.
  class MissingSpecError < Gem::LoadError
    def initialize(name, requirement, extra_message=nil)
      @name        = name
      @requirement = requirement
      @extra_message = extra_message
    end

    def message # :nodoc:
      build_message +
        "Checked in 'GEM_PATH=#{Gem.path.join(File::PATH_SEPARATOR)}' #{@extra_message}, execute `gem env` for more information"
    end

    private

    def build_message
      total = Gem::Specification.stubs.size
      "Could not find '#{name}' (#{requirement}) among #{total} total gem(s)\n"
    end
  end

  ##
  # Raised when trying to activate a gem, and the gem exists on the system, but
  # not the requested version. Instead of rescuing from this class, make sure to
  # rescue from the superclass Gem::LoadError to catch all types of load errors.
  class MissingSpecVersionError < MissingSpecError
    attr_reader :specs

    def initialize(name, requirement, specs)
      super(name, requirement)
      @specs = specs
    end

    private

    def build_message
      if name == "bundler" && message = Gem::BundlerVersionFinder.missing_version_message
        return message
      end
      names = specs.map(&:full_name)
      "Could not find '#{name}' (#{requirement}) - did find: [#{names.join ','}]\n"
    end
  end

  # Raised when there are conflicting gem specs loaded

  class ConflictError < LoadError
    ##
    # A Hash mapping conflicting specifications to the dependencies that
    # caused the conflict

    attr_reader :conflicts

    ##
    # The specification that had the conflict

    attr_reader :target

    def initialize(target, conflicts)
      @target    = target
      @conflicts = conflicts
      @name      = target.name

      reason = conflicts.map do |act, dependencies|
        "#{act.full_name} conflicts with #{dependencies.join(", ")}"
      end.join ", "

      # TODO: improve message by saying who activated `con`

      super("Unable to activate #{target.full_name}, because #{reason}")
    end
  end

  class ErrorReason; end

  # Generated when trying to lookup a gem to indicate that the gem
  # was found, but that it isn't usable on the current platform.
  #
  # fetch and install read these and report them to the user to aid
  # in figuring out why a gem couldn't be installed.
  #
  class PlatformMismatch < ErrorReason
    ##
    # the name of the gem
    attr_reader :name

    ##
    # the version
    attr_reader :version

    ##
    # The platforms that are mismatched
    attr_reader :platforms

    def initialize(name, version)
      @name = name
      @version = version
      @platforms = []
    end

    ##
    # append a platform to the list of mismatched platforms.
    #
    # Platforms are added via this instead of injected via the constructor
    # so that we can loop over a list of mismatches and just add them rather
    # than perform some kind of calculation mismatch summary before creation.
    def add_platform(platform)
      @platforms << platform
    end

    ##
    # A wordy description of the error.
    def wordy
      "Found %s (%s), but was for platform%s %s" %
        [@name,
         @version,
         @platforms.size == 1 ? '' : 's',
         @platforms.join(' ,')]
    end
  end

  ##
  # An error that indicates we weren't able to fetch some
  # data from a source

  class SourceFetchProblem < ErrorReason
    ##
    # Creates a new SourceFetchProblem for the given +source+ and +error+.

    def initialize(source, error)
      @source = source
      @error = error
    end

    ##
    # The source that had the fetch problem.

    attr_reader :source

    ##
    # The fetch error which is an Exception subclass.

    attr_reader :error

    ##
    # An English description of the error.

    def wordy
      "Unable to download data from #{Gem::Uri.new(@source.uri).redacted} - #{@error.message}"
    end

    ##
    # The "exception" alias allows you to call raise on a SourceFetchProblem.

    alias exception error
  end
end
# frozen_string_literal: true
##
# Gem::StubSpecification reads the stub: line from the gemspec.  This prevents
# us having to eval the entire gemspec in order to find out certain
# information.

class Gem::StubSpecification < Gem::BasicSpecification
  # :nodoc:
  PREFIX = "# stub: ".freeze

  # :nodoc:
  OPEN_MODE = 'r:UTF-8:-'.freeze

  class StubLine # :nodoc: all
    attr_reader :name, :version, :platform, :require_paths, :extensions,
                :full_name

    NO_EXTENSIONS = [].freeze

    # These are common require paths.
    REQUIRE_PATHS = { # :nodoc:
      'lib'  => 'lib'.freeze,
      'test' => 'test'.freeze,
      'ext'  => 'ext'.freeze,
    }.freeze

    # These are common require path lists.  This hash is used to optimize
    # and consolidate require_path objects.  Most specs just specify "lib"
    # in their require paths, so lets take advantage of that by pre-allocating
    # a require path list for that case.
    REQUIRE_PATH_LIST = { # :nodoc:
      'lib' => ['lib'].freeze,
    }.freeze

    def initialize(data, extensions)
      parts          = data[PREFIX.length..-1].split(" ".freeze, 4)
      @name          = parts[0].freeze
      @version       = if Gem::Version.correct?(parts[1])
                         Gem::Version.new(parts[1])
                       else
                         Gem::Version.new(0)
                       end

      @platform      = Gem::Platform.new parts[2]
      @extensions    = extensions
      @full_name     = if platform == Gem::Platform::RUBY
                         "#{name}-#{version}"
                       else
                         "#{name}-#{version}-#{platform}"
                       end

      path_list = parts.last
      @require_paths = REQUIRE_PATH_LIST[path_list] || path_list.split("\0".freeze).map! do |x|
        REQUIRE_PATHS[x] || x
      end
    end
  end

  def self.default_gemspec_stub(filename, base_dir, gems_dir)
    new filename, base_dir, gems_dir, true
  end

  def self.gemspec_stub(filename, base_dir, gems_dir)
    new filename, base_dir, gems_dir, false
  end

  attr_reader :base_dir, :gems_dir

  def initialize(filename, base_dir, gems_dir, default_gem)
    super()
    filename.tap(&Gem::UNTAINT)

    self.loaded_from = filename
    @data            = nil
    @name            = nil
    @spec            = nil
    @base_dir        = base_dir
    @gems_dir        = gems_dir
    @default_gem     = default_gem
  end

  ##
  # True when this gem has been activated

  def activated?
    @activated ||=
    begin
      loaded = Gem.loaded_specs[name]
      loaded && loaded.version == version
    end
  end

  def default_gem?
    @default_gem
  end

  def build_extensions # :nodoc:
    return if default_gem?
    return if extensions.empty?

    to_spec.build_extensions
  end

  ##
  # If the gemspec contains a stubline, returns a StubLine instance. Otherwise
  # returns the full Gem::Specification.

  def data
    unless @data
      begin
        saved_lineno = $.

        File.open loaded_from, OPEN_MODE do |file|
          begin
            file.readline # discard encoding line
            stubline = file.readline.chomp
            if stubline.start_with?(PREFIX)
              extensions = if /\A#{PREFIX}/ =~ file.readline.chomp
                             $'.split "\0"
                           else
                             StubLine::NO_EXTENSIONS
                           end

              @data = StubLine.new stubline, extensions
            end
          rescue EOFError
          end
        end
      ensure
        $. = saved_lineno
      end
    end

    @data ||= to_spec
  end

  private :data

  def raw_require_paths # :nodoc:
    data.require_paths
  end

  def missing_extensions?
    return false if default_gem?
    return false if extensions.empty?
    return false if File.exist? gem_build_complete_path

    to_spec.missing_extensions?
  end

  ##
  # Name of the gem

  def name
    data.name
  end

  ##
  # Platform of the gem

  def platform
    data.platform
  end

  ##
  # Extensions for this gem

  def extensions
    data.extensions
  end

  ##
  # Version of the gem

  def version
    data.version
  end

  def full_name
    data.full_name
  end

  ##
  # The full Gem::Specification for this gem, loaded from evalling its gemspec

  def to_spec
    @spec ||= if @data
                loaded = Gem.loaded_specs[name]
                loaded if loaded && loaded.version == version
              end

    @spec ||= Gem::Specification.load(loaded_from)
    @spec.ignored = @ignored if @spec

    @spec
  end

  ##
  # Is this StubSpecification valid? i.e. have we found a stub line, OR does
  # the filename contain a valid gemspec?

  def valid?
    data
  end

  ##
  # Is there a stub line present for this StubSpecification?

  def stubbed?
    data.is_a? StubLine
  end
end
# frozen_string_literal: true
require_relative '../rubygems'
require_relative 'user_interaction'

##
# A post-install hook that displays "Successfully installed
# some_gem-1.0 as a default gem"

Gem.post_install do |installer|
  ui = Gem::DefaultUserInteraction.ui
  ui.say "Successfully installed #{installer.spec.full_name} as a default gem"
end
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require_relative '../rubygems'

# forward-declare

module Gem::Security # :nodoc:
  class Policy # :nodoc:
  end
end

##
# Mixin methods for security option for Gem::Commands

module Gem::SecurityOption
  def add_security_option
    Gem::OptionParser.accept Gem::Security::Policy do |value|
      require_relative 'security'

      raise Gem::OptionParser::InvalidArgument, 'OpenSSL not installed' unless
        defined?(Gem::Security::HighSecurity)

      policy = Gem::Security::Policies[value]
      unless policy
        valid = Gem::Security::Policies.keys.sort
        raise Gem::OptionParser::InvalidArgument, "#{value} (#{valid.join ', '} are valid)"
      end
      policy
    end

    add_option(:"Install/Update", '-P', '--trust-policy POLICY',
               Gem::Security::Policy,
               'Specify gem trust policy') do |value, options|
      options[:security_policy] = value
    end
  end
end
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require 'monitor'

module Kernel

  RUBYGEMS_ACTIVATION_MONITOR = Monitor.new # :nodoc:

  # Make sure we have a reference to Ruby's original Kernel#require
  unless defined?(gem_original_require)
    alias gem_original_require require
    private :gem_original_require
  end

  file = Gem::KERNEL_WARN_IGNORES_INTERNAL_ENTRIES ? "<internal:#{__FILE__}>" : __FILE__
  module_eval <<'RUBY', file, __LINE__ + 1
  ##
  # When RubyGems is required, Kernel#require is replaced with our own which
  # is capable of loading gems on demand.
  #
  # When you call <tt>require 'x'</tt>, this is what happens:
  # * If the file can be loaded from the existing Ruby loadpath, it
  #   is.
  # * Otherwise, installed gems are searched for a file that matches.
  #   If it's found in gem 'y', that gem is activated (added to the
  #   loadpath).
  #
  # The normal <tt>require</tt> functionality of returning false if
  # that file has already been loaded is preserved.

  def require(path)
    if RUBYGEMS_ACTIVATION_MONITOR.respond_to?(:mon_owned?)
      monitor_owned = RUBYGEMS_ACTIVATION_MONITOR.mon_owned?
    end
    RUBYGEMS_ACTIVATION_MONITOR.enter

    path = path.to_path if path.respond_to? :to_path

    if spec = Gem.find_unresolved_default_spec(path)
      # Ensure -I beats a default gem
      resolved_path = begin
        rp = nil
        load_path_check_index = Gem.load_path_insert_index - Gem.activated_gem_paths
        Gem.suffixes.each do |s|
          $LOAD_PATH[0...load_path_check_index].each do |lp|
            safe_lp = lp.dup.tap(&Gem::UNTAINT)
            begin
              if File.symlink? safe_lp # for backward compatibility
                next
              end
            rescue SecurityError
              RUBYGEMS_ACTIVATION_MONITOR.exit
              raise
            end

            full_path = File.expand_path(File.join(safe_lp, "#{path}#{s}"))
            if File.file?(full_path)
              rp = full_path
              break
            end
          end
          break if rp
        end
        rp
      end

      begin
        Kernel.send(:gem, spec.name, Gem::Requirement.default_prerelease)
      rescue Exception
        RUBYGEMS_ACTIVATION_MONITOR.exit
        raise
      end unless resolved_path
    end

    # If there are no unresolved deps, then we can use just try
    # normal require handle loading a gem from the rescue below.

    if Gem::Specification.unresolved_deps.empty?
      RUBYGEMS_ACTIVATION_MONITOR.exit
      return gem_original_require(path)
    end

    # If +path+ is for a gem that has already been loaded, don't
    # bother trying to find it in an unresolved gem, just go straight
    # to normal require.
    #--
    # TODO request access to the C implementation of this to speed up RubyGems

    if Gem::Specification.find_active_stub_by_path(path)
      RUBYGEMS_ACTIVATION_MONITOR.exit
      return gem_original_require(path)
    end

    # Attempt to find +path+ in any unresolved gems...

    found_specs = Gem::Specification.find_in_unresolved path

    # If there are no directly unresolved gems, then try and find +path+
    # in any gems that are available via the currently unresolved gems.
    # For example, given:
    #
    #   a => b => c => d
    #
    # If a and b are currently active with c being unresolved and d.rb is
    # requested, then find_in_unresolved_tree will find d.rb in d because
    # it's a dependency of c.
    #
    if found_specs.empty?
      found_specs = Gem::Specification.find_in_unresolved_tree path

      found_specs.each do |found_spec|
        found_spec.activate
      end

    # We found +path+ directly in an unresolved gem. Now we figure out, of
    # the possible found specs, which one we should activate.
    else

      # Check that all the found specs are just different
      # versions of the same gem
      names = found_specs.map(&:name).uniq

      if names.size > 1
        RUBYGEMS_ACTIVATION_MONITOR.exit
        raise Gem::LoadError, "#{path} found in multiple gems: #{names.join ', '}"
      end

      # Ok, now find a gem that has no conflicts, starting
      # at the highest version.
      valid = found_specs.find {|s| !s.has_conflicts? }

      unless valid
        le = Gem::LoadError.new "unable to find a version of '#{names.first}' to activate"
        le.name = names.first
        RUBYGEMS_ACTIVATION_MONITOR.exit
        raise le
      end

      valid.activate
    end

    RUBYGEMS_ACTIVATION_MONITOR.exit
    return gem_original_require(path)
  rescue LoadError => load_error
    RUBYGEMS_ACTIVATION_MONITOR.enter

    begin
      if load_error.path == path and Gem.try_activate(path)
        require_again = true
      end
    ensure
      RUBYGEMS_ACTIVATION_MONITOR.exit
    end

    return gem_original_require(path) if require_again

    raise load_error
  ensure
    if RUBYGEMS_ACTIVATION_MONITOR.respond_to?(:mon_owned?)
      if monitor_owned != (ow = RUBYGEMS_ACTIVATION_MONITOR.mon_owned?)
        STDERR.puts [$$, Thread.current, $!, $!.backtrace].inspect if $!
        raise "CRITICAL: RUBYGEMS_ACTIVATION_MONITOR.owned?: before #{monitor_owned} -> after #{ow}"
      end
    end
  end
RUBY

  private :require

end
# frozen_string_literal: true

# `uplevel` keyword argument of Kernel#warn is available since ruby 2.5.
if RUBY_VERSION >= "2.5" && !Gem::KERNEL_WARN_IGNORES_INTERNAL_ENTRIES

  module Kernel
    rubygems_path = "#{__dir__}/" # Frames to be skipped start with this path.

    original_warn = instance_method(:warn)

    remove_method :warn

    class << self
      remove_method :warn
    end

    module_function define_method(:warn) {|*messages, **kw|
      unless uplevel = kw[:uplevel]
        if Gem.java_platform?
          return original_warn.bind(self).call(*messages)
        else
          return original_warn.bind(self).call(*messages, **kw)
        end
      end

      # Ensure `uplevel` fits a `long`
      uplevel, = [uplevel].pack("l!").unpack("l!")

      if uplevel >= 0
        start = 0
        while uplevel >= 0
          loc, = caller_locations(start, 1)
          unless loc
            # No more backtrace
            start += uplevel
            break
          end

          start += 1

          if path = loc.path
            unless path.start_with?(rubygems_path) or path.start_with?('<internal:')
              # Non-rubygems frames
              uplevel -= 1
            end
          end
        end
        kw[:uplevel] = start
      end

      original_warn.bind(self).call(*messages, **kw)
    }
  end
end
# frozen_string_literal: true
##
# RubyGems adds the #gem method to allow activation of specific gem versions
# and overrides the #require method on Kernel to make gems appear as if they
# live on the <code>$LOAD_PATH</code>.  See the documentation of these methods
# for further detail.

module Kernel

  ##
  # Use Kernel#gem to activate a specific version of +gem_name+.
  #
  # +requirements+ is a list of version requirements that the
  # specified gem must match, most commonly "= example.version.number".  See
  # Gem::Requirement for how to specify a version requirement.
  #
  # If you will be activating the latest version of a gem, there is no need to
  # call Kernel#gem, Kernel#require will do the right thing for you.
  #
  # Kernel#gem returns true if the gem was activated, otherwise false.  If the
  # gem could not be found, didn't match the version requirements, or a
  # different version was already activated, an exception will be raised.
  #
  # Kernel#gem should be called *before* any require statements (otherwise
  # RubyGems may load a conflicting library version).
  #
  # Kernel#gem only loads prerelease versions when prerelease +requirements+
  # are given:
  #
  #   gem 'rake', '>= 1.1.a', '< 2'
  #
  # In older RubyGems versions, the environment variable GEM_SKIP could be
  # used to skip activation of specified gems, for example to test out changes
  # that haven't been installed yet.  Now RubyGems defers to -I and the
  # RUBYLIB environment variable to skip activation of a gem.
  #
  # Example:
  #
  #   GEM_SKIP=libA:libB ruby -I../libA -I../libB ./mycode.rb

  def gem(gem_name, *requirements) # :doc:
    skip_list = (ENV['GEM_SKIP'] || "").split(/:/)
    raise Gem::LoadError, "skipping #{gem_name}" if skip_list.include? gem_name

    if gem_name.kind_of? Gem::Dependency
      unless Gem::Deprecate.skip
        warn "#{Gem.location_of_caller.join ':'}:Warning: Kernel.gem no longer "\
          "accepts a Gem::Dependency object, please pass the name "\
          "and requirements directly"
      end

      requirements = gem_name.requirement
      gem_name = gem_name.name
    end

    dep = Gem::Dependency.new(gem_name, *requirements)

    loaded = Gem.loaded_specs[gem_name]

    return false if loaded && dep.matches_spec?(loaded)

    spec = dep.to_spec

    if spec
      if Gem::LOADED_SPECS_MUTEX.owned?
        spec.activate
      else
        Gem::LOADED_SPECS_MUTEX.synchronize { spec.activate }
      end
    end
  end

  private :gem

end
require 'socket'

module CoreExtensions
  module TCPSocketExt
    def self.prepended(base)
      base.prepend Initializer
    end

    module Initializer
      CONNECTION_TIMEOUT = 5
      IPV4_DELAY_SECONDS = 0.1

      def initialize(host, serv, *rest)
        mutex = Thread::Mutex.new
        addrs = []
        threads = []
        cond_var = Thread::ConditionVariable.new

        Addrinfo.foreach(host, serv, nil, :STREAM) do |addr|
          Thread.report_on_exception = false if defined? Thread.report_on_exception = ()

          threads << Thread.new(addr) do
            # give head start to ipv6 addresses
            sleep IPV4_DELAY_SECONDS if addr.ipv4?

            # raises Errno::ECONNREFUSED when ip:port is unreachable
            Socket.tcp(addr.ip_address, serv, connect_timeout: CONNECTION_TIMEOUT).close
            mutex.synchronize do
              addrs << addr.ip_address
              cond_var.signal
            end
          end
        end

        mutex.synchronize do
          timeout_time = CONNECTION_TIMEOUT + Time.now.to_f
          while addrs.empty? && (remaining_time = timeout_time - Time.now.to_f) > 0
            cond_var.wait(mutex, remaining_time)
          end

          host = addrs.shift unless addrs.empty?
        end

        threads.each {|t| t.kill.join if t.alive? }

        super(host, serv, *rest)
      end
    end
  end
end

TCPSocket.prepend CoreExtensions::TCPSocketExt
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require_relative '../rubygems'
require_relative 'command_manager'
require_relative 'deprecate'

##
# Load additional plugins from $LOAD_PATH

Gem.load_env_plugins rescue nil

##
# Run an instance of the gem program.
#
# Gem::GemRunner is only intended for internal use by RubyGems itself.  It
# does not form any public API and may change at any time for any reason.
#
# If you would like to duplicate functionality of `gem` commands, use the
# classes they call directly.

class Gem::GemRunner
  def initialize
    @command_manager_class = Gem::CommandManager
    @config_file_class = Gem::ConfigFile
  end

  ##
  # Run the gem command with the following arguments.

  def run(args)
    build_args = extract_build_args args

    do_configuration args

    cmd = @command_manager_class.instance

    cmd.command_names.each do |command_name|
      config_args = Gem.configuration[command_name]
      config_args = case config_args
                    when String
                      config_args.split ' '
                    else
                      Array(config_args)
                    end
      Gem::Command.add_specific_extra_args command_name, config_args
    end

    cmd.run Gem.configuration.args, build_args
  end

  ##
  # Separates the build arguments (those following <code>--</code>) from the
  # other arguments in the list.

  def extract_build_args(args) # :nodoc:
    return [] unless offset = args.index('--')

    build_args = args.slice!(offset...args.length)

    build_args.shift

    build_args
  end

  private

  def do_configuration(args)
    Gem.configuration = @config_file_class.new(args)
    Gem.use_paths Gem.configuration[:gemhome], Gem.configuration[:gempath]
    Gem::Command.extra_args = Gem.configuration[:gem]
  end
end

Gem.load_plugins
# frozen_string_literal: true

require_relative 'local_remote_options'
require_relative 'spec_fetcher'
require_relative 'version_option'
require_relative 'text'

module Gem::QueryUtils

  include Gem::Text
  include Gem::LocalRemoteOptions
  include Gem::VersionOption

  def add_query_options
    add_option('-i', '--[no-]installed',
               'Check for installed gem') do |value, options|
      options[:installed] = value
    end

    add_option('-I', 'Equivalent to --no-installed') do |value, options|
      options[:installed] = false
    end

    add_version_option command, "for use with --installed"

    add_option('-d', '--[no-]details',
               'Display detailed information of gem(s)') do |value, options|
      options[:details] = value
    end

    add_option('--[no-]versions',
               'Display only gem names') do |value, options|
      options[:versions] = value
      options[:details] = false unless value
    end

    add_option('-a', '--all',
               'Display all gem versions') do |value, options|
      options[:all] = value
    end

    add_option('-e', '--exact',
               'Name of gem(s) to query on matches the',
               'provided STRING') do |value, options|
      options[:exact] = value
    end

    add_option('--[no-]prerelease',
               'Display prerelease versions') do |value, options|
      options[:prerelease] = value
    end

    add_local_remote_options
  end

  def defaults_str # :nodoc:
    "--local --name-matches // --no-details --versions --no-installed"
  end

  def execute
    gem_names = Array(options[:name])

    if !args.empty?
      gem_names = options[:exact] ? args.map{|arg| /\A#{Regexp.escape(arg)}\Z/ } : args.map{|arg| /#{arg}/i }
    end

    terminate_interaction(check_installed_gems(gem_names)) if check_installed_gems?

    gem_names.each {|n| show_gems(n) }
  end

  private

  def check_installed_gems(gem_names)
    exit_code = 0

    if args.empty? && !gem_name?
      alert_error "You must specify a gem name"
      exit_code = 4
    elsif gem_names.count > 1
      alert_error "You must specify only ONE gem!"
      exit_code = 4
    else
      installed = installed?(gem_names.first, options[:version])
      installed = !installed unless options[:installed]

      say(installed)
      exit_code = 1 if !installed
    end

    exit_code
  end

  def check_installed_gems?
    !options[:installed].nil?
  end

  def gem_name?
    !options[:name].source.empty?
  end

  def prerelease
    options[:prerelease]
  end

  def show_prereleases?
    prerelease.nil? || prerelease
  end

  def args
    options[:args].to_a
  end

  def display_header(type)
    if (ui.outs.tty? and Gem.configuration.verbose) or both?
      say
      say "*** #{type} GEMS ***"
      say
    end
  end

  #Guts of original execute
  def show_gems(name)
    show_local_gems(name)  if local?
    show_remote_gems(name) if remote?
  end

  def show_local_gems(name, req = Gem::Requirement.default)
    display_header("LOCAL")

    specs = Gem::Specification.find_all do |s|
      s.name =~ name and req =~ s.version
    end

    dep = Gem::Deprecate.skip_during { Gem::Dependency.new name, req }
    specs.select! do |s|
      dep.match?(s.name, s.version, show_prereleases?)
    end

    spec_tuples = specs.map do |spec|
      [spec.name_tuple, spec]
    end

    output_query_results(spec_tuples)
  end

  def show_remote_gems(name)
    display_header("REMOTE")

    fetcher = Gem::SpecFetcher.fetcher

    spec_tuples = if name.respond_to?(:source) && name.source.empty?
                    fetcher.detect(specs_type) { true }
                  else
                    fetcher.detect(specs_type) do |name_tuple|
                      name === name_tuple.name
                    end
                  end

    output_query_results(spec_tuples)
  end

  def specs_type
    if options[:all]
      if options[:prerelease]
        :complete
      else
        :released
      end
    elsif options[:prerelease]
      :prerelease
    else
      :latest
    end
  end

  ##
  # Check if gem +name+ version +version+ is installed.

  def installed?(name, req = Gem::Requirement.default)
    Gem::Specification.any? {|s| s.name =~ name and req =~ s.version }
  end

  def output_query_results(spec_tuples)
    output = []
    versions = Hash.new {|h,name| h[name] = [] }

    spec_tuples.each do |spec_tuple, source|
      versions[spec_tuple.name] << [spec_tuple, source]
    end

    versions = versions.sort_by do |(n,_),_|
      n.downcase
    end

    output_versions output, versions

    say output.join(options[:details] ? "\n\n" : "\n")
  end

  def output_versions(output, versions)
    versions.each do |gem_name, matching_tuples|
      matching_tuples = matching_tuples.sort_by {|n,_| n.version }.reverse

      platforms = Hash.new {|h,version| h[version] = [] }

      matching_tuples.each do |n, _|
        platforms[n.version] << n.platform if n.platform
      end

      seen = {}

      matching_tuples.delete_if do |n,_|
        if seen[n.version]
          true
        else
          seen[n.version] = true
          false
        end
      end

      output << clean_text(make_entry(matching_tuples, platforms))
    end
  end

  def entry_details(entry, detail_tuple, specs, platforms)
    return unless options[:details]

    name_tuple, spec = detail_tuple

    spec = spec.fetch_spec(name_tuple)if spec.respond_to?(:fetch_spec)

    entry << "\n"

    spec_platforms   entry, platforms
    spec_authors     entry, spec
    spec_homepage    entry, spec
    spec_license     entry, spec
    spec_loaded_from entry, spec, specs
    spec_summary     entry, spec
  end

  def entry_versions(entry, name_tuples, platforms, specs)
    return unless options[:versions]

    list =
      if platforms.empty? or options[:details]
        name_tuples.map {|n| n.version }.uniq
      else
        platforms.sort.reverse.map do |version, pls|
          out = version.to_s

          if options[:domain] == :local
            default = specs.any? do |s|
              !s.is_a?(Gem::Source) && s.version == version && s.default_gem?
            end
            out = "default: #{out}" if default
          end

          if pls != [Gem::Platform::RUBY]
            platform_list = [pls.delete(Gem::Platform::RUBY), *pls.sort].compact
            out = platform_list.unshift(out).join(' ')
          end

          out
        end
      end

    entry << " (#{list.join ', '})"
  end

  def make_entry(entry_tuples, platforms)
    detail_tuple = entry_tuples.first

    name_tuples, specs = entry_tuples.flatten.partition do |item|
      Gem::NameTuple === item
    end

    entry = [name_tuples.first.name]

    entry_versions(entry, name_tuples, platforms, specs)
    entry_details(entry, detail_tuple, specs, platforms)

    entry.join
  end

  def spec_authors(entry, spec)
    authors = "Author#{spec.authors.length > 1 ? 's' : ''}: ".dup
    authors << spec.authors.join(', ')
    entry << format_text(authors, 68, 4)
  end

  def spec_homepage(entry, spec)
    return if spec.homepage.nil? or spec.homepage.empty?

    entry << "\n" << format_text("Homepage: #{spec.homepage}", 68, 4)
  end

  def spec_license(entry, spec)
    return if spec.license.nil? or spec.license.empty?

    licenses = "License#{spec.licenses.length > 1 ? 's' : ''}: ".dup
    licenses << spec.licenses.join(', ')
    entry << "\n" << format_text(licenses, 68, 4)
  end

  def spec_loaded_from(entry, spec, specs)
    return unless spec.loaded_from

    if specs.length == 1
      default = spec.default_gem? ? ' (default)' : nil
      entry << "\n" << "    Installed at#{default}: #{spec.base_dir}"
    else
      label = 'Installed at'
      specs.each do |s|
        version = s.version.to_s
        version << ', default' if s.default_gem?
        entry << "\n" << "    #{label} (#{version}): #{s.base_dir}"
        label = ' ' * label.length
      end
    end
  end

  def spec_platforms(entry, platforms)
    non_ruby = platforms.any? do |_, pls|
      pls.any? {|pl| pl != Gem::Platform::RUBY }
    end

    return unless non_ruby

    if platforms.length == 1
      title = platforms.values.length == 1 ? 'Platform' : 'Platforms'
      entry << "    #{title}: #{platforms.values.sort.join(', ')}\n"
    else
      entry << "    Platforms:\n"

      sorted_platforms = platforms.sort_by {|version,| version }

      sorted_platforms.each do |version, pls|
        label = "        #{version}: "
        data = format_text pls.sort.join(', '), 68, label.length
        data[0, label.length] = label
        entry << data << "\n"
      end
    end
  end

  def spec_summary(entry, spec)
    summary = truncate_text(spec.summary, "the summary for #{spec.full_name}")
    entry << "\n\n" << format_text(summary, 68, 4)
  end

end
# frozen_string_literal: true
require 'net/http'
require_relative 'user_interaction'

class Gem::Request
  extend Gem::UserInteraction
  include Gem::UserInteraction

  ###
  # Legacy.  This is used in tests.
  def self.create_with_proxy(uri, request_class, last_modified, proxy) # :nodoc:
    cert_files = get_cert_files
    proxy ||= get_proxy_from_env(uri.scheme)
    pool = ConnectionPools.new proxy_uri(proxy), cert_files

    new(uri, request_class, last_modified, pool.pool_for(uri))
  end

  def self.proxy_uri(proxy) # :nodoc:
    require "uri"
    case proxy
    when :no_proxy then nil
    when URI::HTTP then proxy
    else URI.parse(proxy)
    end
  end

  def initialize(uri, request_class, last_modified, pool)
    @uri = uri
    @request_class = request_class
    @last_modified = last_modified
    @requests = Hash.new 0
    @user_agent = user_agent

    @connection_pool = pool
  end

  def proxy_uri; @connection_pool.proxy_uri; end
  def cert_files; @connection_pool.cert_files; end

  def self.get_cert_files
    pattern = File.expand_path("./ssl_certs/*/*.pem", File.dirname(__FILE__))
    Dir.glob(pattern)
  end

  def self.configure_connection_for_https(connection, cert_files)
    raise Gem::Exception.new('OpenSSL is not available. Install OpenSSL and rebuild Ruby (preferred) or use non-HTTPS sources') unless Gem::HAVE_OPENSSL

    connection.use_ssl = true
    connection.verify_mode =
      Gem.configuration.ssl_verify_mode || OpenSSL::SSL::VERIFY_PEER
    store = OpenSSL::X509::Store.new

    if Gem.configuration.ssl_client_cert
      pem = File.read Gem.configuration.ssl_client_cert
      connection.cert = OpenSSL::X509::Certificate.new pem
      connection.key = OpenSSL::PKey::RSA.new pem
    end

    store.set_default_paths
    cert_files.each do |ssl_cert_file|
      store.add_file ssl_cert_file
    end
    if Gem.configuration.ssl_ca_cert
      if File.directory? Gem.configuration.ssl_ca_cert
        store.add_path Gem.configuration.ssl_ca_cert
      else
        store.add_file Gem.configuration.ssl_ca_cert
      end
    end
    connection.cert_store = store

    connection.verify_callback = proc do |preverify_ok, store_context|
      verify_certificate store_context unless preverify_ok

      preverify_ok
    end

    connection
  end

  def self.verify_certificate(store_context)
    depth  = store_context.error_depth
    error  = store_context.error_string
    number = store_context.error
    cert   = store_context.current_cert

    ui.alert_error "SSL verification error at depth #{depth}: #{error} (#{number})"

    extra_message = verify_certificate_message number, cert

    ui.alert_error extra_message if extra_message
  end

  def self.verify_certificate_message(error_number, cert)
    return unless cert
    case error_number
    when OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED then
      require 'time'
      "Certificate #{cert.subject} expired at #{cert.not_after.iso8601}"
    when OpenSSL::X509::V_ERR_CERT_NOT_YET_VALID then
      require 'time'
      "Certificate #{cert.subject} not valid until #{cert.not_before.iso8601}"
    when OpenSSL::X509::V_ERR_CERT_REJECTED then
      "Certificate #{cert.subject} is rejected"
    when OpenSSL::X509::V_ERR_CERT_UNTRUSTED then
      "Certificate #{cert.subject} is not trusted"
    when OpenSSL::X509::V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT then
      "Certificate #{cert.issuer} is not trusted"
    when OpenSSL::X509::V_ERR_INVALID_CA then
      "Certificate #{cert.subject} is an invalid CA certificate"
    when OpenSSL::X509::V_ERR_INVALID_PURPOSE then
      "Certificate #{cert.subject} has an invalid purpose"
    when OpenSSL::X509::V_ERR_SELF_SIGNED_CERT_IN_CHAIN then
      "Root certificate is not trusted (#{cert.subject})"
    when OpenSSL::X509::V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY then
      "You must add #{cert.issuer} to your local trusted store"
    when
      OpenSSL::X509::V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE then
      "Cannot verify certificate issued by #{cert.issuer}"
    end
  end

  ##
  # Creates or an HTTP connection based on +uri+, or retrieves an existing
  # connection, using a proxy if needed.

  def connection_for(uri)
    @connection_pool.checkout
  rescue Gem::HAVE_OPENSSL ? OpenSSL::SSL::SSLError : Errno::EHOSTDOWN,
         Errno::EHOSTDOWN => e
    raise Gem::RemoteFetcher::FetchError.new(e.message, uri)
  end

  def fetch
    request = @request_class.new @uri.request_uri

    unless @uri.nil? || @uri.user.nil? || @uri.user.empty?
      request.basic_auth Gem::UriFormatter.new(@uri.user).unescape,
                         Gem::UriFormatter.new(@uri.password).unescape
    end

    request.add_field 'User-Agent', @user_agent
    request.add_field 'Connection', 'keep-alive'
    request.add_field 'Keep-Alive', '30'

    if @last_modified
      require 'time'
      request.add_field 'If-Modified-Since', @last_modified.httpdate
    end

    yield request if block_given?

    perform_request request
  end

  ##
  # Returns a proxy URI for the given +scheme+ if one is set in the
  # environment variables.

  def self.get_proxy_from_env(scheme = 'http')
    _scheme = scheme.downcase
    _SCHEME = scheme.upcase
    env_proxy = ENV["#{_scheme}_proxy"] || ENV["#{_SCHEME}_PROXY"]

    no_env_proxy = env_proxy.nil? || env_proxy.empty?

    if no_env_proxy
      return (_scheme == 'https' || _scheme == 'http') ?
        :no_proxy : get_proxy_from_env('http')
    end

    require "uri"
    uri = URI(Gem::UriFormatter.new(env_proxy).normalize)

    if uri and uri.user.nil? and uri.password.nil?
      user     = ENV["#{_scheme}_proxy_user"] || ENV["#{_SCHEME}_PROXY_USER"]
      password = ENV["#{_scheme}_proxy_pass"] || ENV["#{_SCHEME}_PROXY_PASS"]

      uri.user     = Gem::UriFormatter.new(user).escape
      uri.password = Gem::UriFormatter.new(password).escape
    end

    uri
  end

  def perform_request(request) # :nodoc:
    connection = connection_for @uri

    retried = false
    bad_response = false

    begin
      @requests[connection.object_id] += 1

      verbose "#{request.method} #{Gem::Uri.new(@uri).redacted}"

      file_name = File.basename(@uri.path)
      # perform download progress reporter only for gems
      if request.response_body_permitted? && file_name =~ /\.gem$/
        reporter = ui.download_reporter
        response = connection.request(request) do |incomplete_response|
          if Net::HTTPOK === incomplete_response
            reporter.fetch(file_name, incomplete_response.content_length)
            downloaded = 0
            data = String.new

            incomplete_response.read_body do |segment|
              data << segment
              downloaded += segment.length
              reporter.update(downloaded)
            end
            reporter.done
            if incomplete_response.respond_to? :body=
              incomplete_response.body = data
            else
              incomplete_response.instance_variable_set(:@body, data)
            end
          end
        end
      else
        response = connection.request request
      end

      verbose "#{response.code} #{response.message}"

    rescue Net::HTTPBadResponse
      verbose "bad response"

      reset connection

      raise Gem::RemoteFetcher::FetchError.new('too many bad responses', @uri) if bad_response

      bad_response = true
      retry
    rescue Net::HTTPFatalError
      verbose "fatal error"

      raise Gem::RemoteFetcher::FetchError.new('fatal error', @uri)
    # HACK work around EOFError bug in Net::HTTP
    # NOTE Errno::ECONNABORTED raised a lot on Windows, and make impossible
    # to install gems.
    rescue EOFError, Timeout::Error,
           Errno::ECONNABORTED, Errno::ECONNRESET, Errno::EPIPE

      requests = @requests[connection.object_id]
      verbose "connection reset after #{requests} requests, retrying"

      raise Gem::RemoteFetcher::FetchError.new('too many connection resets', @uri) if retried

      reset connection

      retried = true
      retry
    end

    response
  ensure
    @connection_pool.checkin connection
  end

  ##
  # Resets HTTP connection +connection+.

  def reset(connection)
    @requests.delete connection.object_id

    connection.finish
    connection.start
  end

  def user_agent
    ua = "RubyGems/#{Gem::VERSION} #{Gem::Platform.local}".dup

    ruby_version = RUBY_VERSION
    ruby_version += 'dev' if RUBY_PATCHLEVEL == -1

    ua << " Ruby/#{ruby_version} (#{RUBY_RELEASE_DATE}"
    if RUBY_PATCHLEVEL >= 0
      ua << " patchlevel #{RUBY_PATCHLEVEL}"
    elsif defined?(RUBY_REVISION)
      ua << " revision #{RUBY_REVISION}"
    end
    ua << ")"

    ua << " #{RUBY_ENGINE}" if RUBY_ENGINE != 'ruby'

    ua
  end
end

require_relative 'request/http_pool'
require_relative 'request/https_pool'
require_relative 'request/connection_pools'
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require_relative 'tsort'
require_relative 'deprecate'

##
# Gem::DependencyList is used for installing and uninstalling gems in the
# correct order to avoid conflicts.
#--
# TODO: It appears that all but topo-sort functionality is being duplicated
# (or is planned to be duplicated) elsewhere in rubygems.  Is the majority of
# this class necessary anymore?  Especially #ok?, #why_not_ok?

class Gem::DependencyList
  attr_reader :specs

  include Enumerable
  include Gem::TSort

  ##
  # Allows enabling/disabling use of development dependencies

  attr_accessor :development

  ##
  # Creates a DependencyList from the current specs.

  def self.from_specs
    list = new
    list.add(*Gem::Specification.to_a)
    list
  end

  ##
  # Creates a new DependencyList.  If +development+ is true, development
  # dependencies will be included.

  def initialize(development = false)
    @specs = []

    @development = development
  end

  ##
  # Adds +gemspecs+ to the dependency list.

  def add(*gemspecs)
    @specs.concat gemspecs
  end

  def clear
    @specs.clear
  end

  ##
  # Return a list of the gem specifications in the dependency list, sorted in
  # order so that no gemspec in the list depends on a gemspec earlier in the
  # list.
  #
  # This is useful when removing gems from a set of installed gems.  By
  # removing them in the returned order, you don't get into as many dependency
  # issues.
  #
  # If there are circular dependencies (yuck!), then gems will be returned in
  # order until only the circular dependents and anything they reference are
  # left.  Then arbitrary gemspecs will be returned until the circular
  # dependency is broken, after which gems will be returned in dependency
  # order again.

  def dependency_order
    sorted = strongly_connected_components.flatten

    result = []
    seen = {}

    sorted.each do |spec|
      if index = seen[spec.name]
        if result[index].version < spec.version
          result[index] = spec
        end
      else
        seen[spec.name] = result.length
        result << spec
      end
    end

    result.reverse
  end

  ##
  # Iterator over dependency_order

  def each(&block)
    dependency_order.each(&block)
  end

  def find_name(full_name)
    @specs.find {|spec| spec.full_name == full_name }
  end

  def inspect # :nodoc:
    "%s %p>" % [super[0..-2], map {|s| s.full_name }]
  end

  ##
  # Are all the dependencies in the list satisfied?

  def ok?
    why_not_ok?(:quick).empty?
  end

  def why_not_ok?(quick = false)
    unsatisfied = Hash.new {|h,k| h[k] = [] }
    each do |spec|
      spec.runtime_dependencies.each do |dep|
        inst = Gem::Specification.any? do |installed_spec|
          dep.name == installed_spec.name and
            dep.requirement.satisfied_by? installed_spec.version
        end

        unless inst or @specs.find {|s| s.satisfies_requirement? dep }
          unsatisfied[spec.name] << dep
          return unsatisfied if quick
        end
      end
    end

    unsatisfied
  end

  ##
  # It is ok to remove a gemspec from the dependency list?
  #
  # If removing the gemspec creates breaks a currently ok dependency, then it
  # is NOT ok to remove the gemspec.

  def ok_to_remove?(full_name, check_dev=true)
    gem_to_remove = find_name full_name

    # If the state is inconsistent, at least don't crash
    return true unless gem_to_remove

    siblings = @specs.find_all do |s|
      s.name == gem_to_remove.name &&
        s.full_name != gem_to_remove.full_name
    end

    deps = []

    @specs.each do |spec|
      check = check_dev ? spec.dependencies : spec.runtime_dependencies

      check.each do |dep|
        deps << dep if gem_to_remove.satisfies_requirement?(dep)
      end
    end

    deps.all? do |dep|
      siblings.any? do |s|
        s.satisfies_requirement? dep
      end
    end
  end

  ##
  # Remove everything in the DependencyList that matches but doesn't
  # satisfy items in +dependencies+ (a hash of gem names to arrays of
  # dependencies).

  def remove_specs_unsatisfied_by(dependencies)
    specs.reject! do |spec|
      dep = dependencies[spec.name]
      dep and not dep.requirement.satisfied_by? spec.version
    end
  end

  ##
  # Removes the gemspec matching +full_name+ from the dependency list

  def remove_by_name(full_name)
    @specs.delete_if {|spec| spec.full_name == full_name }
  end

  ##
  # Return a hash of predecessors.  <tt>result[spec]</tt> is an Array of
  # gemspecs that have a dependency satisfied by the named gemspec.

  def spec_predecessors
    result = Hash.new {|h,k| h[k] = [] }

    specs = @specs.sort.reverse

    specs.each do |spec|
      specs.each do |other|
        next if spec == other

        other.dependencies.each do |dep|
          if spec.satisfies_requirement? dep
            result[spec] << other
          end
        end
      end
    end

    result
  end

  def tsort_each_node(&block)
    @specs.each(&block)
  end

  def tsort_each_child(node)
    specs = @specs.sort.reverse

    dependencies = node.runtime_dependencies
    dependencies.push(*node.development_dependencies) if @development

    dependencies.each do |dep|
      specs.each do |spec|
        if spec.satisfies_requirement? dep
          yield spec
          break
        end
      end
    end
  end

  private

  ##
  # Count the number of gemspecs in the list +specs+ that are not in
  # +ignored+.

  def active_count(specs, ignored)
    specs.count {|spec| ignored[spec.full_name].nil? }
  end
end
# frozen_string_literal: true
require_relative 'remote_fetcher'
require_relative 'text'

##
# Utility methods for using the RubyGems API.

module Gem::GemcutterUtilities

  ERROR_CODE = 1
  API_SCOPES = %i[index_rubygems push_rubygem yank_rubygem add_owner remove_owner access_webhooks show_dashboard].freeze

  include Gem::Text

  attr_writer :host
  attr_writer :scope

  ##
  # Add the --key option

  def add_key_option
    add_option('-k', '--key KEYNAME', Symbol,
               'Use the given API key',
               "from #{Gem.configuration.credentials_path}") do |value,options|
      options[:key] = value
    end
  end

  ##
  # Add the --otp option

  def add_otp_option
    add_option('--otp CODE',
               'Digit code for multifactor authentication',
               'You can also use the environment variable GEM_HOST_OTP_CODE') do |value, options|
      options[:otp] = value
    end
  end

  ##
  # The API key from the command options or from the user's configuration.

  def api_key
    if ENV["GEM_HOST_API_KEY"]
      ENV["GEM_HOST_API_KEY"]
    elsif options[:key]
      verify_api_key options[:key]
    elsif Gem.configuration.api_keys.key?(host)
      Gem.configuration.api_keys[host]
    else
      Gem.configuration.rubygems_api_key
    end
  end

  ##
  # The OTP code from the command options or from the user's configuration.

  def otp
    options[:otp] || ENV["GEM_HOST_OTP_CODE"]
  end

  ##
  # The host to connect to either from the RUBYGEMS_HOST environment variable
  # or from the user's configuration

  def host
    configured_host = Gem.host unless
      Gem.configuration.disable_default_gem_server

    @host ||=
      begin
        env_rubygems_host = ENV['RUBYGEMS_HOST']
        env_rubygems_host = nil if
          env_rubygems_host and env_rubygems_host.empty?

        env_rubygems_host || configured_host
      end
  end

  ##
  # Creates an RubyGems API to +host+ and +path+ with the given HTTP +method+.
  #
  # If +allowed_push_host+ metadata is present, then it will only allow that host.

  def rubygems_api_request(method, path, host = nil, allowed_push_host = nil, scope: nil, &block)
    require 'net/http'

    self.host = host if host
    unless self.host
      alert_error "You must specify a gem server"
      terminate_interaction(ERROR_CODE)
    end

    if allowed_push_host
      allowed_host_uri = URI.parse(allowed_push_host)
      host_uri         = URI.parse(self.host)

      unless (host_uri.scheme == allowed_host_uri.scheme) && (host_uri.host == allowed_host_uri.host)
        alert_error "#{self.host.inspect} is not allowed by the gemspec, which only allows #{allowed_push_host.inspect}"
        terminate_interaction(ERROR_CODE)
      end
    end

    uri = URI.parse "#{self.host}/#{path}"
    response = request_with_otp(method, uri, &block)

    if mfa_unauthorized?(response)
      ask_otp
      response = request_with_otp(method, uri, &block)
    end

    if api_key_forbidden?(response)
      update_scope(scope)
      request_with_otp(method, uri, &block)
    else
      response
    end
  end

  def mfa_unauthorized?(response)
    response.kind_of?(Net::HTTPUnauthorized) && response.body.start_with?('You have enabled multifactor authentication')
  end

  def update_scope(scope)
    sign_in_host        = self.host
    pretty_host         = pretty_host(sign_in_host)
    update_scope_params = { scope => true }

    say "The existing key doesn't have access of #{scope} on #{pretty_host}. Please sign in to update access."

    email    = ask "   Email: "
    password = ask_for_password "Password: "

    response = rubygems_api_request(:put, "api/v1/api_key",
                                    sign_in_host, scope: scope) do |request|
      request.basic_auth email, password
      request["OTP"] = otp if otp
      request.body = URI.encode_www_form({:api_key => api_key }.merge(update_scope_params))
    end

    with_response response do |resp|
      say "Added #{scope} scope to the existing API key"
    end
  end

  ##
  # Signs in with the RubyGems API at +sign_in_host+ and sets the rubygems API
  # key.

  def sign_in(sign_in_host = nil, scope: nil)
    sign_in_host ||= self.host
    return if api_key

    pretty_host = pretty_host(sign_in_host)

    say "Enter your #{pretty_host} credentials."
    say "Don't have an account yet? " +
        "Create one at #{sign_in_host}/sign_up"

    email = ask "   Email: "
    password = ask_for_password "Password: "
    say "\n"

    key_name     = get_key_name(scope)
    scope_params = get_scope_params(scope)

    response = rubygems_api_request(:post, "api/v1/api_key",
                                    sign_in_host, scope: scope) do |request|
      request.basic_auth email, password
      request["OTP"] = otp if otp
      request.body = URI.encode_www_form({ name: key_name }.merge(scope_params))
    end

    with_response response do |resp|
      say "Signed in with API key: #{key_name}."
      set_api_key host, resp.body
    end
  end

  ##
  # Retrieves the pre-configured API key +key+ or terminates interaction with
  # an error.

  def verify_api_key(key)
    if Gem.configuration.api_keys.key? key
      Gem.configuration.api_keys[key]
    else
      alert_error "No such API key. Please add it to your configuration (done automatically on initial `gem push`)."
      terminate_interaction(ERROR_CODE)
    end
  end

  ##
  # If +response+ is an HTTP Success (2XX) response, yields the response if a
  # block was given or shows the response body to the user.
  #
  # If the response was not successful, shows an error to the user including
  # the +error_prefix+ and the response body.

  def with_response(response, error_prefix = nil)
    case response
    when Net::HTTPSuccess then
      if block_given?
        yield response
      else
        say clean_text(response.body)
      end
    else
      message = response.body
      message = "#{error_prefix}: #{message}" if error_prefix

      say clean_text(message)
      terminate_interaction(ERROR_CODE)
    end
  end

  ##
  # Returns true when the user has enabled multifactor authentication from
  # +response+ text and no otp provided by options.

  def set_api_key(host, key)
    if host == Gem::DEFAULT_HOST
      Gem.configuration.rubygems_api_key = key
    else
      Gem.configuration.set_api_key host, key
    end
  end

  private

  def request_with_otp(method, uri, &block)
    request_method = Net::HTTP.const_get method.to_s.capitalize

    Gem::RemoteFetcher.fetcher.request(uri, request_method) do |req|
      req["OTP"] = otp if otp
      block.call(req)
    end
  end

  def ask_otp
    say 'You have enabled multi-factor authentication. Please enter OTP code.'
    options[:otp] = ask 'Code: '
  end

  def pretty_host(host)
    if Gem::DEFAULT_HOST == host
      'RubyGems.org'
    else
      host
    end
  end

  def get_scope_params(scope)
    scope_params = {}

    if scope
      scope_params = { scope => true }
    else
      say "Please select scopes you want to enable for the API key (y/n)"
      API_SCOPES.each do |scope|
        selected = ask "#{scope} [y/N]: "
        scope_params[scope] = true if selected =~ /^[yY](es)?$/
      end
      say "\n"
    end

    scope_params
  end

  def get_key_name(scope)
    hostname = Socket.gethostname || "unknown-host"
    user = ENV["USER"] || ENV["USERNAME"] || "unknown-user"
    ts = Time.now.strftime("%Y%m%d%H%M%S")
    default_key_name = "#{hostname}-#{user}-#{ts}"

    key_name = ask "API Key name [#{default_key_name}]: " unless scope
    if key_name.nil? || key_name.empty?
      default_key_name
    else
      key_name
    end
  end

  def api_key_forbidden?(response)
    response.kind_of?(Net::HTTPForbidden) && response.body.start_with?("The API key doesn't have access")
  end
end
# frozen_string_literal: true
# -*- coding: utf-8 -*-
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require_relative 'deprecate'
require_relative 'basic_specification'
require_relative 'stub_specification'
require_relative 'platform'
require_relative 'requirement'
require_relative 'specification_policy'
require_relative 'util/list'

##
# The Specification class contains the information for a gem.  Typically
# defined in a .gemspec file or a Rakefile, and looks like this:
#
#   Gem::Specification.new do |s|
#     s.name        = 'example'
#     s.version     = '0.1.0'
#     s.licenses    = ['MIT']
#     s.summary     = "This is an example!"
#     s.description = "Much longer explanation of the example!"
#     s.authors     = ["Ruby Coder"]
#     s.email       = 'rubycoder@example.com'
#     s.files       = ["lib/example.rb"]
#     s.homepage    = 'https://rubygems.org/gems/example'
#     s.metadata    = { "source_code_uri" => "https://github.com/example/example" }
#   end
#
# Starting in RubyGems 2.0, a Specification can hold arbitrary
# metadata.  See #metadata for restrictions on the format and size of metadata
# items you may add to a specification.

class Gem::Specification < Gem::BasicSpecification
  extend Gem::Deprecate

  # REFACTOR: Consider breaking out this version stuff into a separate
  # module. There's enough special stuff around it that it may justify
  # a separate class.

  ##
  # The version number of a specification that does not specify one
  # (i.e. RubyGems 0.7 or earlier).

  NONEXISTENT_SPECIFICATION_VERSION = -1

  ##
  # The specification version applied to any new Specification instances
  # created.  This should be bumped whenever something in the spec format
  # changes.
  #
  # Specification Version History:
  #
  #   spec   ruby
  #    ver    ver yyyy-mm-dd description
  #     -1 <0.8.0            pre-spec-version-history
  #      1  0.8.0 2004-08-01 Deprecated "test_suite_file" for "test_files"
  #                          "test_file=x" is a shortcut for "test_files=[x]"
  #      2  0.9.5 2007-10-01 Added "required_rubygems_version"
  #                          Now forward-compatible with future versions
  #      3  1.3.2 2009-01-03 Added Fixnum validation to specification_version
  #      4  1.9.0 2011-06-07 Added metadata
  #--
  # When updating this number, be sure to also update #to_ruby.
  #
  # NOTE RubyGems < 1.2 cannot load specification versions > 2.

  CURRENT_SPECIFICATION_VERSION = 4 # :nodoc:

  ##
  # An informal list of changes to the specification.  The highest-valued
  # key should be equal to the CURRENT_SPECIFICATION_VERSION.

  SPECIFICATION_VERSION_HISTORY = { # :nodoc:
    -1 => ['(RubyGems versions up to and including 0.7 did not have versioned specifications)'],
    1  => [
      'Deprecated "test_suite_file" in favor of the new, but equivalent, "test_files"',
      '"test_file=x" is a shortcut for "test_files=[x]"',
    ],
    2 => [
      'Added "required_rubygems_version"',
      'Now forward-compatible with future versions',
    ],
    3 => [
      'Added Fixnum validation to the specification_version',
    ],
    4 => [
      'Added sandboxed freeform metadata to the specification version.',
    ],
  }.freeze

  MARSHAL_FIELDS = { # :nodoc:
    -1 => 16,
     1 => 16,
     2 => 16,
     3 => 17,
     4 => 18,
  }.freeze

  today = Time.now.utc
  TODAY = Time.utc(today.year, today.month, today.day) # :nodoc:

  @load_cache = {} # :nodoc:
  @load_cache_mutex = Thread::Mutex.new

  VALID_NAME_PATTERN = /\A[a-zA-Z0-9\.\-\_]+\z/.freeze # :nodoc:

  # :startdoc:

  ##
  # List of attribute names: [:name, :version, ...]

  @@required_attributes = [:rubygems_version,
                           :specification_version,
                           :name,
                           :version,
                           :date,
                           :summary,
                           :require_paths]

  ##
  # Map of attribute names to default values.

  @@default_value = {
    :authors                   => [],
    :autorequire               => nil,
    :bindir                    => 'bin',
    :cert_chain                => [],
    :date                      => nil,
    :dependencies              => [],
    :description               => nil,
    :email                     => nil,
    :executables               => [],
    :extensions                => [],
    :extra_rdoc_files          => [],
    :files                     => [],
    :homepage                  => nil,
    :licenses                  => [],
    :metadata                  => {},
    :name                      => nil,
    :platform                  => Gem::Platform::RUBY,
    :post_install_message      => nil,
    :rdoc_options              => [],
    :require_paths             => ['lib'],
    :required_ruby_version     => Gem::Requirement.default,
    :required_rubygems_version => Gem::Requirement.default,
    :requirements              => [],
    :rubygems_version          => Gem::VERSION,
    :signing_key               => nil,
    :specification_version     => CURRENT_SPECIFICATION_VERSION,
    :summary                   => nil,
    :test_files                => [],
    :version                   => nil,
  }.freeze

  # rubocop:disable Style/MutableConstant
  INITIALIZE_CODE_FOR_DEFAULTS = { } # :nodoc:
  # rubocop:enable Style/MutableConstant

  @@default_value.each do |k,v|
    INITIALIZE_CODE_FOR_DEFAULTS[k] = case v
                                      when [], {}, true, false, nil, Numeric, Symbol
                                        v.inspect
                                      when String
                                        v.dump
                                      when Numeric
                                        "default_value(:#{k})"
                                      else
                                        "default_value(:#{k}).dup"
                                      end
  end

  @@attributes = @@default_value.keys.sort_by {|s| s.to_s }
  @@array_attributes = @@default_value.reject {|k,v| v != [] }.keys
  @@nil_attributes, @@non_nil_attributes = @@default_value.keys.partition do |k|
    @@default_value[k].nil?
  end

  def self.clear_specs # :nodoc:
    @@all_specs_mutex.synchronize do
      @@all = nil
      @@stubs = nil
      @@stubs_by_name = {}
      @@spec_with_requirable_file = {}
      @@active_stub_with_requirable_file = {}
    end
  end
  private_class_method :clear_specs

  @@all_specs_mutex = Thread::Mutex.new

  clear_specs

  # Sentinel object to represent "not found" stubs
  NOT_FOUND = Struct.new(:to_spec, :this).new # :nodoc:

  # Tracking removed method calls to warn users during build time.
  REMOVED_METHODS = [:rubyforge_project=].freeze # :nodoc:
  def removed_method_calls
    @removed_method_calls ||= []
  end

  ######################################################################
  # :section: Required gemspec attributes

  ##
  # This gem's name.
  #
  # Usage:
  #
  #   spec.name = 'rake'

  attr_accessor :name

  ##
  # This gem's version.
  #
  # The version string can contain numbers and periods, such as +1.0.0+.
  # A gem is a 'prerelease' gem if the version has a letter in it, such as
  # +1.0.0.pre+.
  #
  # Usage:
  #
  #   spec.version = '0.4.1'

  attr_reader :version

  ##
  # A short summary of this gem's description.  Displayed in `gem list -d`.
  #
  # The #description should be more detailed than the summary.
  #
  # Usage:
  #
  #   spec.summary = "This is a small summary of my gem"

  attr_reader :summary

  ##
  # Files included in this gem.  You cannot append to this accessor, you must
  # assign to it.
  #
  # Only add files you can require to this list, not directories, etc.
  #
  # Directories are automatically stripped from this list when building a gem,
  # other non-files cause an error.
  #
  # Usage:
  #
  #   require 'rake'
  #   spec.files = FileList['lib/**/*.rb',
  #                         'bin/*',
  #                         '[A-Z]*'].to_a
  #
  #   # or without Rake...
  #   spec.files = Dir['lib/**/*.rb'] + Dir['bin/*']
  #   spec.files += Dir['[A-Z]*']
  #   spec.files.reject! { |fn| fn.include? "CVS" }

  def files
    # DO NOT CHANGE TO ||= ! This is not a normal accessor. (yes, it sucks)
    # DOC: Why isn't it normal? Why does it suck? How can we fix this?
    @files = [@files,
              @test_files,
              add_bindir(@executables),
              @extra_rdoc_files,
              @extensions,
             ].flatten.compact.uniq.sort
  end

  ##
  # A list of authors for this gem.
  #
  # Alternatively, a single author can be specified by assigning a string to
  # `spec.author`
  #
  # Usage:
  #
  #   spec.authors = ['John Jones', 'Mary Smith']

  def authors=(value)
    @authors = Array(value).flatten.grep(String)
  end

  ######################################################################
  # :section: Recommended gemspec attributes

  ##
  # The version of Ruby required by this gem
  #
  # Usage:
  #
  #   spec.required_ruby_version = '>= 2.7.0'

  attr_reader :required_ruby_version

  ##
  # A long description of this gem
  #
  # The description should be more detailed than the summary but not
  # excessively long.  A few paragraphs is a recommended length with no
  # examples or formatting.
  #
  # Usage:
  #
  #   spec.description = <<-EOF
  #     Rake is a Make-like program implemented in Ruby. Tasks and
  #     dependencies are specified in standard Ruby syntax.
  #   EOF

  attr_reader :description

  ##
  # A contact email address (or addresses) for this gem
  #
  # Usage:
  #
  #   spec.email = 'john.jones@example.com'
  #   spec.email = ['jack@example.com', 'jill@example.com']

  attr_accessor :email

  ##
  # The URL of this gem's home page
  #
  # Usage:
  #
  #   spec.homepage = 'https://github.com/ruby/rake'

  attr_accessor :homepage

  ##
  # The license for this gem.
  #
  # The license must be no more than 64 characters.
  #
  # This should just be the name of your license. The full text of the license
  # should be inside of the gem (at the top level) when you build it.
  #
  # The simplest way is to specify the standard SPDX ID
  # https://spdx.org/licenses/ for the license.
  # Ideally, you should pick one that is OSI (Open Source Initiative)
  # http://opensource.org/licenses/alphabetical approved.
  #
  # The most commonly used OSI-approved licenses are MIT and Apache-2.0.
  # GitHub also provides a license picker at http://choosealicense.com/.
  #
  # You can also use a custom license file along with your gemspec and specify
  # a LicenseRef-<idstring>, where idstring is the name of the file containing
  # the license text.
  #
  # You should specify a license for your gem so that people know how they are
  # permitted to use it and any restrictions you're placing on it.  Not
  # specifying a license means all rights are reserved; others have no right
  # to use the code for any purpose.
  #
  # You can set multiple licenses with #licenses=
  #
  # Usage:
  #   spec.license = 'MIT'

  def license=(o)
    self.licenses = [o]
  end

  ##
  # The license(s) for the library.
  #
  # Each license must be a short name, no more than 64 characters.
  #
  # This should just be the name of your license. The full
  # text of the license should be inside of the gem when you build it.
  #
  # See #license= for more discussion
  #
  # Usage:
  #   spec.licenses = ['MIT', 'GPL-2.0']

  def licenses=(licenses)
    @licenses = Array licenses
  end

  ##
  # The metadata holds extra data for this gem that may be useful to other
  # consumers and is settable by gem authors.
  #
  # Metadata items have the following restrictions:
  #
  # * The metadata must be a Hash object
  # * All keys and values must be Strings
  # * Keys can be a maximum of 128 bytes and values can be a maximum of 1024
  #   bytes
  # * All strings must be UTF-8, no binary data is allowed
  #
  # You can use metadata to specify links to your gem's homepage, codebase,
  # documentation, wiki, mailing list, issue tracker and changelog.
  #
  #   s.metadata = {
  #     "bug_tracker_uri"   => "https://example.com/user/bestgemever/issues",
  #     "changelog_uri"     => "https://example.com/user/bestgemever/CHANGELOG.md",
  #     "documentation_uri" => "https://www.example.info/gems/bestgemever/0.0.1",
  #     "homepage_uri"      => "https://bestgemever.example.io",
  #     "mailing_list_uri"  => "https://groups.example.com/bestgemever",
  #     "source_code_uri"   => "https://example.com/user/bestgemever",
  #     "wiki_uri"          => "https://example.com/user/bestgemever/wiki"
  #     "funding_uri"       => "https://example.com/donate"
  #   }
  #
  # These links will be used on your gem's page on rubygems.org and must pass
  # validation against following regex.
  #
  #   %r{\Ahttps?:\/\/([^\s:@]+:[^\s:@]*@)?[A-Za-z\d\-]+(\.[A-Za-z\d\-]+)+\.?(:\d{1,5})?([\/?]\S*)?\z}

  attr_accessor :metadata

  ######################################################################
  # :section: Optional gemspec attributes

  ##
  # Singular (alternative) writer for #authors
  #
  # Usage:
  #
  #   spec.author = 'John Jones'

  def author=(o)
    self.authors = [o]
  end

  ##
  # The path in the gem for executable scripts.  Usually 'bin'
  #
  # Usage:
  #
  #   spec.bindir = 'bin'

  attr_accessor :bindir

  ##
  # The certificate chain used to sign this gem.  See Gem::Security for
  # details.

  attr_accessor :cert_chain

  ##
  # A message that gets displayed after the gem is installed.
  #
  # Usage:
  #
  #   spec.post_install_message = "Thanks for installing!"

  attr_accessor :post_install_message

  ##
  # The platform this gem runs on.
  #
  # This is usually Gem::Platform::RUBY or Gem::Platform::CURRENT.
  #
  # Most gems contain pure Ruby code; they should simply leave the default
  # value in place.  Some gems contain C (or other) code to be compiled into a
  # Ruby "extension".  The gem should leave the default value in place unless
  # the code will only compile on a certain type of system.  Some gems consist
  # of pre-compiled code ("binary gems").  It's especially important that they
  # set the platform attribute appropriately.  A shortcut is to set the
  # platform to Gem::Platform::CURRENT, which will cause the gem builder to set
  # the platform to the appropriate value for the system on which the build is
  # being performed.
  #
  # If this attribute is set to a non-default value, it will be included in
  # the filename of the gem when it is built such as:
  # nokogiri-1.6.0-x86-mingw32.gem
  #
  # Usage:
  #
  #   spec.platform = Gem::Platform.local

  def platform=(platform)
    if @original_platform.nil? or
       @original_platform == Gem::Platform::RUBY
      @original_platform = platform
    end

    case platform
    when Gem::Platform::CURRENT then
      @new_platform = Gem::Platform.local
      @original_platform = @new_platform.to_s

    when Gem::Platform then
      @new_platform = platform

    # legacy constants
    when nil, Gem::Platform::RUBY then
      @new_platform = Gem::Platform::RUBY
    when 'mswin32' then # was Gem::Platform::WIN32
      @new_platform = Gem::Platform.new 'x86-mswin32'
    when 'i586-linux' then # was Gem::Platform::LINUX_586
      @new_platform = Gem::Platform.new 'x86-linux'
    when 'powerpc-darwin' then # was Gem::Platform::DARWIN
      @new_platform = Gem::Platform.new 'ppc-darwin'
    else
      @new_platform = Gem::Platform.new platform
    end

    @platform = @new_platform.to_s

    invalidate_memoized_attributes

    @new_platform
  end

  ##
  # Paths in the gem to add to <code>$LOAD_PATH</code> when this gem is
  # activated.
  #--
  # See also #require_paths
  #++
  # If you have an extension you do not need to add <code>"ext"</code> to the
  # require path, the extension build process will copy the extension files
  # into "lib" for you.
  #
  # The default value is <code>"lib"</code>
  #
  # Usage:
  #
  #   # If all library files are in the root directory...
  #   spec.require_paths = ['.']

  def require_paths=(val)
    @require_paths = Array(val)
  end

  ##
  # The RubyGems version required by this gem

  attr_reader :required_rubygems_version

  ##
  # The version of RubyGems used to create this gem.
  #
  # Do not set this, it is set automatically when the gem is packaged.

  attr_accessor :rubygems_version

  ##
  # The key used to sign this gem.  See Gem::Security for details.

  attr_accessor :signing_key

  ##
  # Adds a development dependency named +gem+ with +requirements+ to this
  # gem.
  #
  # Usage:
  #
  #   spec.add_development_dependency 'example', '~> 1.1', '>= 1.1.4'
  #
  # Development dependencies aren't installed by default and aren't
  # activated when a gem is required.

  def add_development_dependency(gem, *requirements)
    add_dependency_with_type(gem, :development, requirements)
  end

  ##
  # Adds a runtime dependency named +gem+ with +requirements+ to this gem.
  #
  # Usage:
  #
  #   spec.add_runtime_dependency 'example', '~> 1.1', '>= 1.1.4'

  def add_runtime_dependency(gem, *requirements)
    if requirements.uniq.size != requirements.size
      warn "WARNING: duplicated #{gem} dependency #{requirements}"
    end

    add_dependency_with_type(gem, :runtime, requirements)
  end

  ##
  # Executables included in the gem.
  #
  # For example, the rake gem has rake as an executable. You don’t specify the
  # full path (as in bin/rake); all application-style files are expected to be
  # found in bindir.  These files must be executable Ruby files.  Files that
  # use bash or other interpreters will not work.
  #
  # Executables included may only be ruby scripts, not scripts for other
  # languages or compiled binaries.
  #
  # Usage:
  #
  #   spec.executables << 'rake'

  def executables
    @executables ||= []
  end

  ##
  # Extensions to build when installing the gem, specifically the paths to
  # extconf.rb-style files used to compile extensions.
  #
  # These files will be run when the gem is installed, causing the C (or
  # whatever) code to be compiled on the user’s machine.
  #
  # Usage:
  #
  #  spec.extensions << 'ext/rmagic/extconf.rb'
  #
  # See Gem::Ext::Builder for information about writing extensions for gems.

  def extensions
    @extensions ||= []
  end

  ##
  # Extra files to add to RDoc such as README or doc/examples.txt
  #
  # When the user elects to generate the RDoc documentation for a gem (typically
  # at install time), all the library files are sent to RDoc for processing.
  # This option allows you to have some non-code files included for a more
  # complete set of documentation.
  #
  # Usage:
  #
  #  spec.extra_rdoc_files = ['README', 'doc/user-guide.txt']

  def extra_rdoc_files
    @extra_rdoc_files ||= []
  end

  ##
  # The version of RubyGems that installed this gem.  Returns
  # <code>Gem::Version.new(0)</code> for gems installed by versions earlier
  # than RubyGems 2.2.0.

  def installed_by_version # :nodoc:
    @installed_by_version ||= Gem::Version.new(0)
  end

  ##
  # Sets the version of RubyGems that installed this gem.  See also
  # #installed_by_version.

  def installed_by_version=(version) # :nodoc:
    @installed_by_version = Gem::Version.new version
  end

  ##
  # Specifies the rdoc options to be used when generating API documentation.
  #
  # Usage:
  #
  #   spec.rdoc_options << '--title' << 'Rake -- Ruby Make' <<
  #     '--main' << 'README' <<
  #     '--line-numbers'

  def rdoc_options
    @rdoc_options ||= []
  end

  ##
  # The version of Ruby required by this gem.  The ruby version can be
  # specified to the patch-level:
  #
  #   $ ruby -v -e 'p Gem.ruby_version'
  #   ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.4.0]
  #   #<Gem::Version "2.0.0.247">
  #
  # Prereleases can also be specified.
  #
  # Usage:
  #
  #  # This gem will work with 1.8.6 or greater...
  #  spec.required_ruby_version = '>= 1.8.6'
  #
  #  # Only with final releases of major version 2 where minor version is at least 3
  #  spec.required_ruby_version = '~> 2.3'
  #
  #  # Only prereleases or final releases after 2.6.0.preview2
  #  spec.required_ruby_version = '> 2.6.0.preview2'
  #
  #  # This gem will work with 2.3.0 or greater, including major version 3, but lesser than 4.0.0
  #  spec.required_ruby_version = '>= 2.3', '< 4'

  def required_ruby_version=(req)
    @required_ruby_version = Gem::Requirement.create req
  end

  ##
  # The RubyGems version required by this gem

  def required_rubygems_version=(req)
    @required_rubygems_version = Gem::Requirement.create req
  end

  ##
  # Lists the external (to RubyGems) requirements that must be met for this gem
  # to work.  It's simply information for the user.
  #
  # Usage:
  #
  #   spec.requirements << 'libmagick, v6.0'
  #   spec.requirements << 'A good graphics card'

  def requirements
    @requirements ||= []
  end

  ##
  # A collection of unit test files.  They will be loaded as unit tests when
  # the user requests a gem to be unit tested.
  #
  # Usage:
  #   spec.test_files = Dir.glob('test/tc_*.rb')
  #   spec.test_files = ['tests/test-suite.rb']

  def test_files=(files) # :nodoc:
    @test_files = Array files
  end

  ######################################################################
  # :section: Specification internals

  ##
  # True when this gemspec has been activated. This attribute is not persisted.

  attr_accessor :activated

  alias :activated? :activated

  ##
  # Autorequire was used by old RubyGems to automatically require a file.
  #
  # Deprecated: It is neither supported nor functional.

  attr_accessor :autorequire # :nodoc:

  ##
  # Sets the default executable for this gem.
  #
  # Deprecated: You must now specify the executable name to  Gem.bin_path.

  attr_writer :default_executable
  rubygems_deprecate :default_executable=

  ##
  # Allows deinstallation of gems with legacy platforms.

  attr_writer :original_platform # :nodoc:

  ##
  # The Gem::Specification version of this gemspec.
  #
  # Do not set this, it is set automatically when the gem is packaged.

  attr_accessor :specification_version

  def self._all # :nodoc:
    @@all_specs_mutex.synchronize { @@all ||= Gem.loaded_specs.values | stubs.map(&:to_spec) }
  end

  def self.clear_load_cache # :nodoc:
    @load_cache_mutex.synchronize do
      @load_cache.clear
    end
  end
  private_class_method :clear_load_cache

  def self.each_gemspec(dirs) # :nodoc:
    dirs.each do |dir|
      Gem::Util.glob_files_in_dir("*.gemspec", dir).each do |path|
        yield path.tap(&Gem::UNTAINT)
      end
    end
  end

  def self.gemspec_stubs_in(dir, pattern)
    Gem::Util.glob_files_in_dir(pattern, dir).map {|path| yield path }.select(&:valid?)
  end
  private_class_method :gemspec_stubs_in

  def self.installed_stubs(dirs, pattern)
    map_stubs(dirs, pattern) do |path, base_dir, gems_dir|
      Gem::StubSpecification.gemspec_stub(path, base_dir, gems_dir)
    end
  end
  private_class_method :installed_stubs

  def self.map_stubs(dirs, pattern) # :nodoc:
    dirs.flat_map do |dir|
      base_dir = File.dirname dir
      gems_dir = File.join base_dir, "gems"
      gemspec_stubs_in(dir, pattern) {|path| yield path, base_dir, gems_dir }
    end
  end
  private_class_method :map_stubs

  def self.each_spec(dirs) # :nodoc:
    each_gemspec(dirs) do |path|
      spec = self.load path
      yield spec if spec
    end
  end

  ##
  # Returns a Gem::StubSpecification for every installed gem

  def self.stubs
    @@stubs ||= begin
      pattern = "*.gemspec"
      stubs = stubs_for_pattern(pattern, false)

      @@stubs_by_name = stubs.select {|s| Gem::Platform.match_spec? s }.group_by(&:name)
      stubs
    end
  end

  ##
  # Returns a Gem::StubSpecification for default gems

  def self.default_stubs(pattern = "*.gemspec")
    base_dir = Gem.default_dir
    gems_dir = File.join base_dir, "gems"
    gemspec_stubs_in(Gem.default_specifications_dir, pattern) do |path|
      Gem::StubSpecification.default_gemspec_stub(path, base_dir, gems_dir)
    end
  end

  ##
  # Returns a Gem::StubSpecification for installed gem named +name+
  # only returns stubs that match Gem.platforms

  def self.stubs_for(name)
    if @@stubs
      @@stubs_by_name[name] || []
    else
      @@stubs_by_name[name] ||= stubs_for_pattern("#{name}-*.gemspec").select do |s|
        s.name == name
      end
    end
  end

  ##
  # Finds stub specifications matching a pattern from the standard locations,
  # optionally filtering out specs not matching the current platform
  #
  def self.stubs_for_pattern(pattern, match_platform = true) # :nodoc:
    installed_stubs = installed_stubs(Gem::Specification.dirs, pattern)
    installed_stubs.select! {|s| Gem::Platform.match_spec? s } if match_platform
    stubs = installed_stubs + default_stubs(pattern)
    stubs = stubs.uniq {|stub| stub.full_name }
    _resort!(stubs)
    stubs
  end

  def self._resort!(specs) # :nodoc:
    specs.sort! do |a, b|
      names = a.name <=> b.name
      next names if names.nonzero?
      versions = b.version <=> a.version
      next versions if versions.nonzero?
      b.platform == Gem::Platform::RUBY ? -1 : 1
    end
  end

  ##
  # Loads the default specifications. It should be called only once.

  def self.load_defaults
    each_spec([Gem.default_specifications_dir]) do |spec|
      # #load returns nil if the spec is bad, so we just ignore
      # it at this stage
      Gem.register_default_spec(spec)
    end
  end

  ##
  # Returns all specifications. This method is discouraged from use.
  # You probably want to use one of the Enumerable methods instead.

  def self.all
    warn "NOTE: Specification.all called from #{caller.first}" unless
      Gem::Deprecate.skip
    _all
  end

  ##
  # Sets the known specs to +specs+. Not guaranteed to work for you in
  # the future. Use at your own risk. Caveat emptor. Doomy doom doom.
  # Etc etc.
  #
  #--
  # Makes +specs+ the known specs
  # Listen, time is a river
  # Winter comes, code breaks
  #
  # -- wilsonb

  def self.all=(specs)
    @@stubs_by_name = specs.group_by(&:name)
    @@all = @@stubs = specs
  end

  ##
  # Return full names of all specs in sorted order.

  def self.all_names
    self._all.map(&:full_name)
  end

  ##
  # Return the list of all array-oriented instance variables.
  #--
  # Not sure why we need to use so much stupid reflection in here...

  def self.array_attributes
    @@array_attributes.dup
  end

  ##
  # Return the list of all instance variables.
  #--
  # Not sure why we need to use so much stupid reflection in here...

  def self.attribute_names
    @@attributes.dup
  end

  ##
  # Return the directories that Specification uses to find specs.

  def self.dirs
    @@dirs ||= Gem.path.collect do |dir|
      File.join dir.dup.tap(&Gem::UNTAINT), "specifications"
    end
  end

  ##
  # Set the directories that Specification uses to find specs. Setting
  # this resets the list of known specs.

  def self.dirs=(dirs)
    self.reset

    @@dirs = Array(dirs).map {|dir| File.join dir, "specifications" }
  end

  extend Enumerable

  ##
  # Enumerate every known spec.  See ::dirs= and ::add_spec to set the list of
  # specs.

  def self.each
    return enum_for(:each) unless block_given?

    self._all.each do |x|
      yield x
    end
  end

  ##
  # Returns every spec that matches +name+ and optional +requirements+.

  def self.find_all_by_name(name, *requirements)
    requirements = Gem::Requirement.default if requirements.empty?

    # TODO: maybe try: find_all { |s| spec === dep }

    Gem::Dependency.new(name, *requirements).matching_specs
  end

  ##
  # Returns every spec that has the given +full_name+

  def self.find_all_by_full_name(full_name)
    stubs.select {|s| s.full_name == full_name }.map(&:to_spec)
  end

  ##
  # Find the best specification matching a +name+ and +requirements+. Raises
  # if the dependency doesn't resolve to a valid specification.

  def self.find_by_name(name, *requirements)
    requirements = Gem::Requirement.default if requirements.empty?

    # TODO: maybe try: find { |s| spec === dep }

    Gem::Dependency.new(name, *requirements).to_spec
  end

  ##
  # Return the best specification that contains the file matching +path+.

  def self.find_by_path(path)
    path = path.dup.freeze
    spec = @@spec_with_requirable_file[path] ||= (stubs.find do |s|
      next unless Gem::BundlerVersionFinder.compatible?(s)
      s.contains_requirable_file? path
    end || NOT_FOUND)
    spec.to_spec
  end

  ##
  # Return the best specification that contains the file matching +path+
  # amongst the specs that are not activated.

  def self.find_inactive_by_path(path)
    stub = stubs.find do |s|
      next if s.activated?
      next unless Gem::BundlerVersionFinder.compatible?(s)
      s.contains_requirable_file? path
    end
    stub && stub.to_spec
  end

  def self.find_active_stub_by_path(path)
    stub = @@active_stub_with_requirable_file[path] ||= (stubs.find do |s|
      s.activated? and s.contains_requirable_file? path
    end || NOT_FOUND)
    stub.this
  end

  ##
  # Return currently unresolved specs that contain the file matching +path+.

  def self.find_in_unresolved(path)
    unresolved_specs.find_all {|spec| spec.contains_requirable_file? path }
  end

  ##
  # Search through all unresolved deps and sub-dependencies and return
  # specs that contain the file matching +path+.

  def self.find_in_unresolved_tree(path)
    unresolved_specs.each do |spec|
      spec.traverse do |from_spec, dep, to_spec, trail|
        if to_spec.has_conflicts? || to_spec.conficts_when_loaded_with?(trail)
          :next
        else
          return trail.reverse if to_spec.contains_requirable_file? path
        end
      end
    end

    []
  end

  def self.unresolved_specs
    unresolved_deps.values.map {|dep| dep.to_specs }.flatten
  end
  private_class_method :unresolved_specs

  ##
  # Special loader for YAML files.  When a Specification object is loaded
  # from a YAML file, it bypasses the normal Ruby object initialization
  # routine (#initialize).  This method makes up for that and deals with
  # gems of different ages.
  #
  # +input+ can be anything that YAML.load() accepts: String or IO.

  def self.from_yaml(input)
    Gem.load_yaml

    input = normalize_yaml_input input
    spec = Gem::SafeYAML.safe_load input

    if spec && spec.class == FalseClass
      raise Gem::EndOfYAMLException
    end

    unless Gem::Specification === spec
      raise Gem::Exception, "YAML data doesn't evaluate to gem specification"
    end

    spec.specification_version ||= NONEXISTENT_SPECIFICATION_VERSION
    spec.reset_nil_attributes_to_default

    spec
  end

  ##
  # Return the latest specs, optionally including prerelease specs if
  # +prerelease+ is true.

  def self.latest_specs(prerelease = false)
    _latest_specs Gem::Specification._all, prerelease
  end

  ##
  # Return the latest installed spec for gem +name+.

  def self.latest_spec_for(name)
    latest_specs(true).find {|installed_spec| installed_spec.name == name }
  end

  def self._latest_specs(specs, prerelease = false) # :nodoc:
    result = {}

    specs.reverse_each do |spec|
      next if spec.version.prerelease? unless prerelease

      result[spec.name] = spec
    end

    result.map(&:last).flatten.sort_by{|tup| tup.name }
  end

  ##
  # Loads Ruby format gemspec from +file+.

  def self.load(file)
    return unless file

    _spec = @load_cache_mutex.synchronize { @load_cache[file] }
    return _spec if _spec

    file = file.dup.tap(&Gem::UNTAINT)
    return unless File.file?(file)

    code = File.read file, :mode => 'r:UTF-8:-'

    code.tap(&Gem::UNTAINT)

    begin
      _spec = eval code, binding, file

      if Gem::Specification === _spec
        _spec.loaded_from = File.expand_path file.to_s
        @load_cache_mutex.synchronize do
          prev = @load_cache[file]
          if prev
            _spec = prev
          else
            @load_cache[file] = _spec
          end
        end
        return _spec
      end

      warn "[#{file}] isn't a Gem::Specification (#{_spec.class} instead)."
    rescue SignalException, SystemExit
      raise
    rescue SyntaxError, Exception => e
      warn "Invalid gemspec in [#{file}]: #{e}"
    end

    nil
  end

  ##
  # Specification attributes that must be non-nil

  def self.non_nil_attributes
    @@non_nil_attributes.dup
  end

  ##
  # Make sure the YAML specification is properly formatted with dashes

  def self.normalize_yaml_input(input)
    result = input.respond_to?(:read) ? input.read : input
    result = "--- " + result unless result.start_with?("--- ")
    result = result.dup
    result.gsub!(/ !!null \n/, " \n")
    # date: 2011-04-26 00:00:00.000000000Z
    # date: 2011-04-26 00:00:00.000000000 Z
    result.gsub!(/^(date: \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+?)Z/, '\1 Z')
    result
  end

  ##
  # Return a list of all outdated local gem names.  This method is HEAVY
  # as it must go fetch specifications from the server.
  #
  # Use outdated_and_latest_version if you wish to retrieve the latest remote
  # version as well.

  def self.outdated
    outdated_and_latest_version.map {|local, _| local.name }
  end

  ##
  # Enumerates the outdated local gems yielding the local specification and
  # the latest remote version.
  #
  # This method may take some time to return as it must check each local gem
  # against the server's index.

  def self.outdated_and_latest_version
    return enum_for __method__ unless block_given?

    # TODO: maybe we should switch to rubygems' version service?
    fetcher = Gem::SpecFetcher.fetcher

    latest_specs(true).each do |local_spec|
      dependency =
        Gem::Dependency.new local_spec.name, ">= #{local_spec.version}"

      remotes, = fetcher.search_for_dependency dependency
      remotes  = remotes.map {|n, _| n.version }

      latest_remote = remotes.sort.last

      yield [local_spec, latest_remote] if
        latest_remote and local_spec.version < latest_remote
    end

    nil
  end

  ##
  # Is +name+ a required attribute?

  def self.required_attribute?(name)
    @@required_attributes.include? name.to_sym
  end

  ##
  # Required specification attributes

  def self.required_attributes
    @@required_attributes.dup
  end

  ##
  # Reset the list of known specs, running pre and post reset hooks
  # registered in Gem.

  def self.reset
    @@dirs = nil
    Gem.pre_reset_hooks.each {|hook| hook.call }
    clear_specs
    clear_load_cache
    unresolved = unresolved_deps
    unless unresolved.empty?
      w = "W" + "ARN"
      warn "#{w}: Unresolved or ambiguous specs during Gem::Specification.reset:"
      unresolved.values.each do |dep|
        warn "      #{dep}"

        versions = find_all_by_name(dep.name)
        unless versions.empty?
          warn "      Available/installed versions of this gem:"
          versions.each {|s| warn "      - #{s.version}" }
        end
      end
      warn "#{w}: Clearing out unresolved specs. Try 'gem cleanup <gem>'"
      warn "Please report a bug if this causes problems."
      unresolved.clear
    end
    Gem.post_reset_hooks.each {|hook| hook.call }
  end

  # DOC: This method needs documented or nodoc'd
  def self.unresolved_deps
    @unresolved_deps ||= Hash.new {|h, n| h[n] = Gem::Dependency.new n }
  end

  ##
  # Load custom marshal format, re-initializing defaults as needed

  def self._load(str)
    Gem.load_yaml

    array = Marshal.load str

    spec = Gem::Specification.new
    spec.instance_variable_set :@specification_version, array[1]

    current_version = CURRENT_SPECIFICATION_VERSION

    field_count = if spec.specification_version > current_version
                    spec.instance_variable_set :@specification_version,
                                               current_version
                    MARSHAL_FIELDS[current_version]
                  else
                    MARSHAL_FIELDS[spec.specification_version]
                  end

    if array.size < field_count
      raise TypeError, "invalid Gem::Specification format #{array.inspect}"
    end

    # Cleanup any YAML::PrivateType. They only show up for an old bug
    # where nil => null, so just convert them to nil based on the type.

    array.map! {|e| e.kind_of?(YAML::PrivateType) ? nil : e }

    spec.instance_variable_set :@rubygems_version,          array[0]
    # spec version
    spec.instance_variable_set :@name,                      array[2]
    spec.instance_variable_set :@version,                   array[3]
    spec.date =                                             array[4]
    spec.instance_variable_set :@summary,                   array[5]
    spec.instance_variable_set :@required_ruby_version,     array[6]
    spec.instance_variable_set :@required_rubygems_version, array[7]
    spec.instance_variable_set :@original_platform,         array[8]
    spec.instance_variable_set :@dependencies,              array[9]
    # offset due to rubyforge_project removal
    spec.instance_variable_set :@email,                     array[11]
    spec.instance_variable_set :@authors,                   array[12]
    spec.instance_variable_set :@description,               array[13]
    spec.instance_variable_set :@homepage,                  array[14]
    spec.instance_variable_set :@has_rdoc,                  array[15]
    spec.instance_variable_set :@new_platform,              array[16]
    spec.instance_variable_set :@platform,                  array[16].to_s
    spec.instance_variable_set :@license,                   array[17]
    spec.instance_variable_set :@metadata,                  array[18]
    spec.instance_variable_set :@loaded,                    false
    spec.instance_variable_set :@activated,                 false

    spec
  end

  def <=>(other) # :nodoc:
    sort_obj <=> other.sort_obj
  end

  def ==(other) # :nodoc:
    self.class === other &&
      name == other.name &&
      version == other.version &&
      platform == other.platform
  end

  ##
  # Dump only crucial instance variables.
  #--
  # MAINTAIN ORDER!
  # (down with the man)

  def _dump(limit)
    Marshal.dump [
      @rubygems_version,
      @specification_version,
      @name,
      @version,
      date,
      @summary,
      @required_ruby_version,
      @required_rubygems_version,
      @original_platform,
      @dependencies,
      '', # rubyforge_project
      @email,
      @authors,
      @description,
      @homepage,
      true, # has_rdoc
      @new_platform,
      @licenses,
      @metadata,
    ]
  end

  ##
  # Activate this spec, registering it as a loaded spec and adding
  # it's lib paths to $LOAD_PATH. Returns true if the spec was
  # activated, false if it was previously activated. Freaks out if
  # there are conflicts upon activation.

  def activate
    other = Gem.loaded_specs[self.name]
    if other
      check_version_conflict other
      return false
    end

    raise_if_conflicts

    activate_dependencies
    add_self_to_load_path

    Gem.loaded_specs[self.name] = self
    @activated = true
    @loaded = true

    return true
  end

  ##
  # Activate all unambiguously resolved runtime dependencies of this
  # spec. Add any ambiguous dependencies to the unresolved list to be
  # resolved later, as needed.

  def activate_dependencies
    unresolved = Gem::Specification.unresolved_deps

    self.runtime_dependencies.each do |spec_dep|
      if loaded = Gem.loaded_specs[spec_dep.name]
        next if spec_dep.matches_spec? loaded

        msg = "can't satisfy '#{spec_dep}', already activated '#{loaded.full_name}'"
        e = Gem::LoadError.new msg
        e.name = spec_dep.name

        raise e
      end

      begin
        specs = spec_dep.to_specs
      rescue Gem::MissingSpecError => e
        raise Gem::MissingSpecError.new(e.name, e.requirement, "at: #{self.spec_file}")
      end

      if specs.size == 1
        specs.first.activate
      else
        name = spec_dep.name
        unresolved[name] = unresolved[name].merge spec_dep
      end
    end

    unresolved.delete self.name
  end

  ##
  # Abbreviate the spec for downloading.  Abbreviated specs are only used for
  # searching, downloading and related activities and do not need deployment
  # specific information (e.g. list of files).  So we abbreviate the spec,
  # making it much smaller for quicker downloads.

  def abbreviate
    self.files = []
    self.test_files = []
    self.rdoc_options = []
    self.extra_rdoc_files = []
    self.cert_chain = []
  end

  ##
  # Sanitize the descriptive fields in the spec.  Sometimes non-ASCII
  # characters will garble the site index.  Non-ASCII characters will
  # be replaced by their XML entity equivalent.

  def sanitize
    self.summary              = sanitize_string(summary)
    self.description          = sanitize_string(description)
    self.post_install_message = sanitize_string(post_install_message)
    self.authors              = authors.collect {|a| sanitize_string(a) }
  end

  ##
  # Sanitize a single string.

  def sanitize_string(string)
    return string unless string

    # HACK the #to_s is in here because RSpec has an Array of Arrays of
    # Strings for authors.  Need a way to disallow bad values on gemspec
    # generation.  (Probably won't happen.)
    string.to_s
  end

  ##
  # Returns an array with bindir attached to each executable in the
  # +executables+ list

  def add_bindir(executables)
    return nil if executables.nil?

    if @bindir
      Array(executables).map {|e| File.join(@bindir, e) }
    else
      executables
    end
  rescue
    return nil
  end

  ##
  # Adds a dependency on gem +dependency+ with type +type+ that requires
  # +requirements+.  Valid types are currently <tt>:runtime</tt> and
  # <tt>:development</tt>.

  def add_dependency_with_type(dependency, type, requirements)
    requirements = if requirements.empty?
                     Gem::Requirement.default
                   else
                     requirements.flatten
                   end

    unless dependency.respond_to?(:name) &&
           dependency.respond_to?(:requirement)
      dependency = Gem::Dependency.new(dependency.to_s, requirements, type)
    end

    dependencies << dependency
  end

  private :add_dependency_with_type

  alias add_dependency add_runtime_dependency

  ##
  # Adds this spec's require paths to LOAD_PATH, in the proper location.

  def add_self_to_load_path
    return if default_gem?

    paths = full_require_paths

    Gem.add_to_load_path(*paths)
  end

  ##
  # Singular reader for #authors.  Returns the first author in the list

  def author
    val = authors and val.first
  end

  ##
  # The list of author names who wrote this gem.
  #
  #   spec.authors = ['Chad Fowler', 'Jim Weirich', 'Rich Kilmer']

  def authors
    @authors ||= []
  end

  ##
  # Returns the full path to installed gem's bin directory.
  #
  # NOTE: do not confuse this with +bindir+, which is just 'bin', not
  # a full path.

  def bin_dir
    @bin_dir ||= File.join gem_dir, bindir
  end

  ##
  # Returns the full path to an executable named +name+ in this gem.

  def bin_file(name)
    File.join bin_dir, name
  end

  ##
  # Returns the build_args used to install the gem

  def build_args
    if File.exist? build_info_file
      build_info = File.readlines build_info_file
      build_info = build_info.map {|x| x.strip }
      build_info.delete ""
      build_info
    else
      []
    end
  end

  ##
  # Builds extensions for this platform if the gem has extensions listed and
  # the gem.build_complete file is missing.

  def build_extensions # :nodoc:
    return if extensions.empty?
    return if default_gem?
    return if File.exist? gem_build_complete_path
    return if !File.writable?(base_dir)
    return if !File.exist?(File.join(base_dir, 'extensions'))

    begin
      # We need to require things in $LOAD_PATH without looking for the
      # extension we are about to build.
      unresolved_deps = Gem::Specification.unresolved_deps.dup
      Gem::Specification.unresolved_deps.clear

      require_relative 'config_file'
      require_relative 'ext'
      require_relative 'user_interaction'

      ui = Gem::SilentUI.new
      Gem::DefaultUserInteraction.use_ui ui do
        builder = Gem::Ext::Builder.new self
        builder.build_extensions
      end
    ensure
      ui.close if ui
      Gem::Specification.unresolved_deps.replace unresolved_deps
    end
  end

  ##
  # Returns the full path to the build info directory

  def build_info_dir
    File.join base_dir, "build_info"
  end

  ##
  # Returns the full path to the file containing the build
  # information generated when the gem was installed

  def build_info_file
    File.join build_info_dir, "#{full_name}.info"
  end

  ##
  # Returns the full path to the cache directory containing this
  # spec's cached gem.

  def cache_dir
    @cache_dir ||= File.join base_dir, "cache"
  end

  ##
  # Returns the full path to the cached gem for this spec.

  def cache_file
    @cache_file ||= File.join cache_dir, "#{full_name}.gem"
  end

  ##
  # Return any possible conflicts against the currently loaded specs.

  def conflicts
    conflicts = {}
    self.runtime_dependencies.each do |dep|
      spec = Gem.loaded_specs[dep.name]
      if spec and not spec.satisfies_requirement? dep
        (conflicts[spec] ||= []) << dep
      end
    end
    env_req = Gem.env_requirement(name)
    (conflicts[self] ||= []) << env_req unless env_req.satisfied_by? version
    conflicts
  end

  ##
  # return true if there will be conflict when spec if loaded together with the list of specs.

  def conficts_when_loaded_with?(list_of_specs) # :nodoc:
    result = list_of_specs.any? do |spec|
      spec.dependencies.any? {|dep| dep.runtime? && (dep.name == name) && !satisfies_requirement?(dep) }
    end
    result
  end

  ##
  # Return true if there are possible conflicts against the currently loaded specs.

  def has_conflicts?
    return true unless Gem.env_requirement(name).satisfied_by?(version)
    self.dependencies.any? do |dep|
      if dep.runtime?
        spec = Gem.loaded_specs[dep.name]
        spec and not spec.satisfies_requirement? dep
      else
        false
      end
    end
  end

  # The date this gem was created.
  #
  # If SOURCE_DATE_EPOCH is set as an environment variable, use that to support
  # reproducible builds; otherwise, default to the current UTC date.
  #
  # Details on SOURCE_DATE_EPOCH:
  # https://reproducible-builds.org/specs/source-date-epoch/

  def date
    @date ||= Time.utc(*Gem.source_date_epoch.utc.to_a[3..5].reverse)
  end

  DateLike = Object.new # :nodoc:
  def DateLike.===(obj) # :nodoc:
    defined?(::Date) and Date === obj
  end

  DateTimeFormat = # :nodoc:
    /\A
     (\d{4})-(\d{2})-(\d{2})
     (\s+ \d{2}:\d{2}:\d{2}\.\d+ \s* (Z | [-+]\d\d:\d\d) )?
     \Z/x.freeze

  ##
  # The date this gem was created
  #
  # DO NOT set this, it is set automatically when the gem is packaged.

  def date=(date)
    # We want to end up with a Time object with one-day resolution.
    # This is the cleanest, most-readable, faster-than-using-Date
    # way to do it.
    @date = case date
            when String then
              if DateTimeFormat =~ date
                Time.utc($1.to_i, $2.to_i, $3.to_i)
              else
                raise(Gem::InvalidSpecificationException,
                      "invalid date format in specification: #{date.inspect}")
              end
            when Time, DateLike then
              Time.utc(date.year, date.month, date.day)
            else
              TODAY
            end
  end

  ##
  # The default executable for this gem.
  #
  # Deprecated: The name of the gem is assumed to be the name of the
  # executable now.  See Gem.bin_path.

  def default_executable # :nodoc:
    if defined?(@default_executable) and @default_executable
      result = @default_executable
    elsif @executables and @executables.size == 1
      result = Array(@executables).first
    else
      result = nil
    end
    result
  end
  rubygems_deprecate :default_executable

  ##
  # The default value for specification attribute +name+

  def default_value(name)
    @@default_value[name]
  end

  ##
  # A list of Gem::Dependency objects this gem depends on.
  #
  # Use #add_dependency or #add_development_dependency to add dependencies to
  # a gem.

  def dependencies
    @dependencies ||= []
  end

  ##
  # Return a list of all gems that have a dependency on this gemspec.  The
  # list is structured with entries that conform to:
  #
  #   [depending_gem, dependency, [list_of_gems_that_satisfy_dependency]]

  def dependent_gems(check_dev=true)
    out = []
    Gem::Specification.each do |spec|
      deps = check_dev ? spec.dependencies : spec.runtime_dependencies
      deps.each do |dep|
        if self.satisfies_requirement?(dep)
          sats = []
          find_all_satisfiers(dep) do |sat|
            sats << sat
          end
          out << [spec, dep, sats]
        end
      end
    end
    out
  end

  ##
  # Returns all specs that matches this spec's runtime dependencies.

  def dependent_specs
    runtime_dependencies.map {|dep| dep.to_specs }.flatten
  end

  ##
  # A detailed description of this gem.  See also #summary

  def description=(str)
    @description = str.to_s
  end

  ##
  # List of dependencies that are used for development

  def development_dependencies
    dependencies.select {|d| d.type == :development }
  end

  ##
  # Returns the full path to this spec's documentation directory.  If +type+
  # is given it will be appended to the end.  For example:
  #
  #   spec.doc_dir      # => "/path/to/gem_repo/doc/a-1"
  #
  #   spec.doc_dir 'ri' # => "/path/to/gem_repo/doc/a-1/ri"

  def doc_dir(type = nil)
    @doc_dir ||= File.join base_dir, 'doc', full_name

    if type
      File.join @doc_dir, type
    else
      @doc_dir
    end
  end

  def encode_with(coder) # :nodoc:
    mark_version

    coder.add 'name', @name
    coder.add 'version', @version
    platform = case @original_platform
               when nil, '' then
                 'ruby'
               when String then
                 @original_platform
               else
                 @original_platform.to_s
               end
    coder.add 'platform', platform

    attributes = @@attributes.map(&:to_s) - %w[name version platform]
    attributes.each do |name|
      coder.add name, instance_variable_get("@#{name}")
    end
  end

  def eql?(other) # :nodoc:
    self.class === other && same_attributes?(other)
  end

  ##
  # Singular accessor for #executables

  def executable
    val = executables and val.first
  end

  ##
  # Singular accessor for #executables

  def executable=(o)
    self.executables = [o]
  end

  ##
  # Sets executables to +value+, ensuring it is an array.

  def executables=(value)
    @executables = Array(value)
  end

  ##
  # Sets extensions to +extensions+, ensuring it is an array.

  def extensions=(extensions)
    @extensions = Array extensions
  end

  ##
  # Sets extra_rdoc_files to +files+, ensuring it is an array.

  def extra_rdoc_files=(files)
    @extra_rdoc_files = Array files
  end

  ##
  # The default (generated) file name of the gem.  See also #spec_name.
  #
  #   spec.file_name # => "example-1.0.gem"

  def file_name
    "#{full_name}.gem"
  end

  ##
  # Sets files to +files+, ensuring it is an array.

  def files=(files)
    @files = Array files
  end

  ##
  # Finds all gems that satisfy +dep+

  def find_all_satisfiers(dep)
    Gem::Specification.each do |spec|
      yield spec if spec.satisfies_requirement? dep
    end
  end

  private :find_all_satisfiers

  ##
  # Creates a duplicate spec without large blobs that aren't used at runtime.

  def for_cache
    spec = dup

    spec.files = nil
    spec.test_files = nil

    spec
  end

  def full_name
    @full_name ||= super
  end

  ##
  # Work around bundler removing my methods

  def gem_dir # :nodoc:
    super
  end

  def gems_dir
    @gems_dir ||= File.join(base_dir, "gems")
  end

  ##
  # Deprecated and ignored, defaults to true.
  #
  # Formerly used to indicate this gem was RDoc-capable.

  def has_rdoc # :nodoc:
    true
  end
  rubygems_deprecate :has_rdoc

  ##
  # Deprecated and ignored.
  #
  # Formerly used to indicate this gem was RDoc-capable.

  def has_rdoc=(ignored) # :nodoc:
    @has_rdoc = true
  end
  rubygems_deprecate :has_rdoc=

  alias :has_rdoc? :has_rdoc # :nodoc:
  rubygems_deprecate :has_rdoc?

  ##
  # True if this gem has files in test_files

  def has_unit_tests? # :nodoc:
    not test_files.empty?
  end

  # :stopdoc:
  alias has_test_suite? has_unit_tests?
  # :startdoc:

  def hash # :nodoc:
    name.hash ^ version.hash
  end

  def init_with(coder) # :nodoc:
    @installed_by_version ||= nil
    yaml_initialize coder.tag, coder.map
  end

  eval <<-RUBY, binding, __FILE__, __LINE__ + 1
    # frozen_string_literal: true

    def set_nil_attributes_to_nil
      #{@@nil_attributes.map {|key| "@#{key} = nil" }.join "; "}
    end
    private :set_nil_attributes_to_nil

    def set_not_nil_attributes_to_default_values
      #{@@non_nil_attributes.map {|key| "@#{key} = #{INITIALIZE_CODE_FOR_DEFAULTS[key]}" }.join ";"}
    end
    private :set_not_nil_attributes_to_default_values
  RUBY

  ##
  # Specification constructor. Assigns the default values to the attributes
  # and yields itself for further initialization.  Optionally takes +name+ and
  # +version+.

  def initialize(name = nil, version = nil)
    super()
    @gems_dir              = nil
    @base_dir              = nil
    @loaded = false
    @activated = false
    @loaded_from = nil
    @original_platform = nil
    @installed_by_version = nil

    set_nil_attributes_to_nil
    set_not_nil_attributes_to_default_values

    @new_platform = Gem::Platform::RUBY

    self.name = name if name
    self.version = version if version

    if platform = Gem.platforms.last and platform != Gem::Platform::RUBY and platform != Gem::Platform.local
      self.platform = platform
    end

    yield self if block_given?
  end

  ##
  # Duplicates array_attributes from +other_spec+ so state isn't shared.

  def initialize_copy(other_spec)
    self.class.array_attributes.each do |name|
      name = :"@#{name}"
      next unless other_spec.instance_variable_defined? name

      begin
        val = other_spec.instance_variable_get(name)
        if val
          instance_variable_set name, val.dup
        elsif Gem.configuration.really_verbose
          warn "WARNING: #{full_name} has an invalid nil value for #{name}"
        end
      rescue TypeError
        e = Gem::FormatException.new \
          "#{full_name} has an invalid value for #{name}"

        e.file_path = loaded_from
        raise e
      end
    end
  end

  def base_dir
    return Gem.dir unless loaded_from
    @base_dir ||= if default_gem?
                    File.dirname File.dirname File.dirname loaded_from
                  else
                    File.dirname File.dirname loaded_from
                  end
  end

  ##
  # Expire memoized instance variables that can incorrectly generate, replace
  # or miss files due changes in certain attributes used to compute them.

  def invalidate_memoized_attributes
    @full_name = nil
    @cache_file = nil
  end

  private :invalidate_memoized_attributes

  def inspect # :nodoc:
    if $DEBUG
      super
    else
      "#{super[0..-2]} #{full_name}>"
    end
  end

  ##
  # Files in the Gem under one of the require_paths

  def lib_files
    @files.select do |file|
      require_paths.any? do |path|
        file.start_with? path
      end
    end
  end

  ##
  # Singular accessor for #licenses

  def license
    licenses.first
  end

  ##
  # Plural accessor for setting licenses
  #
  # See #license= for details

  def licenses
    @licenses ||= []
  end

  def internal_init # :nodoc:
    super
    @bin_dir       = nil
    @cache_dir     = nil
    @cache_file    = nil
    @doc_dir       = nil
    @ri_dir        = nil
    @spec_dir      = nil
    @spec_file     = nil
  end

  ##
  # Sets the rubygems_version to the current RubyGems version.

  def mark_version
    @rubygems_version = Gem::VERSION
  end

  ##
  # Track removed method calls to warn about during build time.
  # Warn about unknown attributes while loading a spec.

  def method_missing(sym, *a, &b) # :nodoc:
    if REMOVED_METHODS.include?(sym)
      removed_method_calls << sym
      return
    end

    if @specification_version > CURRENT_SPECIFICATION_VERSION and
      sym.to_s.end_with?("=")
      warn "ignoring #{sym} loading #{full_name}" if $DEBUG
    else
      super
    end
  end

  ##
  # Is this specification missing its extensions?  When this returns true you
  # probably want to build_extensions

  def missing_extensions?
    return false if extensions.empty?
    return false if default_gem?
    return false if File.exist? gem_build_complete_path

    true
  end

  ##
  # Normalize the list of files so that:
  # * All file lists have redundancies removed.
  # * Files referenced in the extra_rdoc_files are included in the package
  #   file list.

  def normalize
    if defined?(@extra_rdoc_files) and @extra_rdoc_files
      @extra_rdoc_files.uniq!
      @files ||= []
      @files.concat(@extra_rdoc_files)
    end

    @files            = @files.uniq if @files
    @extensions       = @extensions.uniq if @extensions
    @test_files       = @test_files.uniq if @test_files
    @executables      = @executables.uniq if @executables
    @extra_rdoc_files = @extra_rdoc_files.uniq if @extra_rdoc_files
  end

  ##
  # Return a NameTuple that represents this Specification

  def name_tuple
    Gem::NameTuple.new name, version, original_platform
  end

  ##
  # Returns the full name (name-version) of this gemspec using the original
  # platform.  For use with legacy gems.

  def original_name # :nodoc:
    if platform == Gem::Platform::RUBY or platform.nil?
      "#{@name}-#{@version}"
    else
      "#{@name}-#{@version}-#{@original_platform}"
    end
  end

  ##
  # Cruft. Use +platform+.

  def original_platform # :nodoc:
    @original_platform ||= platform
  end

  ##
  # The platform this gem runs on.  See Gem::Platform for details.

  def platform
    @new_platform ||= Gem::Platform::RUBY
  end

  def pretty_print(q) # :nodoc:
    q.group 2, 'Gem::Specification.new do |s|', 'end' do
      q.breakable

      attributes = @@attributes - [:name, :version]
      attributes.unshift :installed_by_version
      attributes.unshift :version
      attributes.unshift :name

      attributes.each do |attr_name|
        current_value = self.send attr_name
        current_value = current_value.sort if %i[files test_files].include? attr_name
        if current_value != default_value(attr_name) or
           self.class.required_attribute? attr_name

          q.text "s.#{attr_name} = "

          if attr_name == :date
            current_value = current_value.utc

            q.text "Time.utc(#{current_value.year}, #{current_value.month}, #{current_value.day})"
          else
            q.pp current_value
          end

          q.breakable
        end
      end
    end
  end

  ##
  # Raise an exception if the version of this spec conflicts with the one
  # that is already loaded (+other+)

  def check_version_conflict(other) # :nodoc:
    return if self.version == other.version

    # This gem is already loaded.  If the currently loaded gem is not in the
    # list of candidate gems, then we have a version conflict.

    msg = "can't activate #{full_name}, already activated #{other.full_name}"

    e = Gem::LoadError.new msg
    e.name = self.name

    raise e
  end

  private :check_version_conflict

  ##
  # Check the spec for possible conflicts and freak out if there are any.

  def raise_if_conflicts # :nodoc:
    if has_conflicts?
      raise Gem::ConflictError.new self, conflicts
    end
  end

  ##
  # Sets rdoc_options to +value+, ensuring it is an array.

  def rdoc_options=(options)
    @rdoc_options = Array options
  end

  ##
  # Singular accessor for #require_paths

  def require_path
    val = require_paths and val.first
  end

  ##
  # Singular accessor for #require_paths

  def require_path=(path)
    self.require_paths = Array(path)
  end

  ##
  # Set requirements to +req+, ensuring it is an array.

  def requirements=(req)
    @requirements = Array req
  end

  def respond_to_missing?(m, include_private = false) # :nodoc:
    false
  end

  ##
  # Returns the full path to this spec's ri directory.

  def ri_dir
    @ri_dir ||= File.join base_dir, 'ri', full_name
  end

  ##
  # Return a string containing a Ruby code representation of the given
  # object.

  def ruby_code(obj)
    case obj
    when String             then obj.dump + ".freeze"
    when Array              then '[' + obj.map {|x| ruby_code x }.join(", ") + ']'
    when Hash               then
      seg = obj.keys.sort.map {|k| "#{k.to_s.dump} => #{obj[k].to_s.dump}" }
      "{ #{seg.join(', ')} }"
    when Gem::Version       then obj.to_s.dump
    when DateLike           then obj.strftime('%Y-%m-%d').dump
    when Time               then obj.strftime('%Y-%m-%d').dump
    when Numeric            then obj.inspect
    when true, false, nil   then obj.inspect
    when Gem::Platform      then "Gem::Platform.new(#{obj.to_a.inspect})"
    when Gem::Requirement   then
      list = obj.as_list
      "Gem::Requirement.new(#{ruby_code(list.size == 1 ? obj.to_s : list)})"
    else raise Gem::Exception, "ruby_code case not handled: #{obj.class}"
    end
  end

  private :ruby_code

  ##
  # List of dependencies that will automatically be activated at runtime.

  def runtime_dependencies
    dependencies.select(&:runtime?)
  end

  ##
  # True if this gem has the same attributes as +other+.

  def same_attributes?(spec)
    @@attributes.all? {|name, default| self.send(name) == spec.send(name) }
  end

  private :same_attributes?

  ##
  # Checks if this specification meets the requirement of +dependency+.

  def satisfies_requirement?(dependency)
    return @name == dependency.name &&
      dependency.requirement.satisfied_by?(@version)
  end

  ##
  # Returns an object you can use to sort specifications in #sort_by.

  def sort_obj
    [@name, @version, @new_platform == Gem::Platform::RUBY ? -1 : 1]
  end

  ##
  # Used by Gem::Resolver to order Gem::Specification objects

  def source # :nodoc:
    Gem::Source::Installed.new
  end

  ##
  # Returns the full path to the directory containing this spec's
  # gemspec file. eg: /usr/local/lib/ruby/gems/1.8/specifications

  def spec_dir
    @spec_dir ||= File.join base_dir, "specifications"
  end

  ##
  # Returns the full path to this spec's gemspec file.
  # eg: /usr/local/lib/ruby/gems/1.8/specifications/mygem-1.0.gemspec

  def spec_file
    @spec_file ||= File.join spec_dir, "#{full_name}.gemspec"
  end

  ##
  # The default name of the gemspec.  See also #file_name
  #
  #   spec.spec_name # => "example-1.0.gemspec"

  def spec_name
    "#{full_name}.gemspec"
  end

  ##
  # A short summary of this gem's description.

  def summary=(str)
    @summary = str.to_s.strip.
      gsub(/(\w-)\n[ \t]*(\w)/, '\1\2').gsub(/\n[ \t]*/, " ") # so. weird.
  end

  ##
  # Singular accessor for #test_files

  def test_file # :nodoc:
    val = test_files and val.first
  end

  ##
  # Singular mutator for #test_files

  def test_file=(file) # :nodoc:
    self.test_files = [file]
  end

  ##
  # Test files included in this gem.  You cannot append to this accessor, you
  # must assign to it.

  def test_files # :nodoc:
    # Handle the possibility that we have @test_suite_file but not
    # @test_files.  This will happen when an old gem is loaded via
    # YAML.
    if defined? @test_suite_file
      @test_files = [@test_suite_file].flatten
      @test_suite_file = nil
    end
    if defined?(@test_files) and @test_files
      @test_files
    else
      @test_files = []
    end
  end

  ##
  # Returns a Ruby code representation of this specification, such that it can
  # be eval'ed and reconstruct the same specification later.  Attributes that
  # still have their default values are omitted.

  def to_ruby
    mark_version
    result = []
    result << "# -*- encoding: utf-8 -*-"
    result << "#{Gem::StubSpecification::PREFIX}#{name} #{version} #{platform} #{raw_require_paths.join("\0")}"
    result << "#{Gem::StubSpecification::PREFIX}#{extensions.join "\0"}" unless
      extensions.empty?
    result << nil
    result << "Gem::Specification.new do |s|"

    result << "  s.name = #{ruby_code name}"
    result << "  s.version = #{ruby_code version}"
    unless platform.nil? or platform == Gem::Platform::RUBY
      result << "  s.platform = #{ruby_code original_platform}"
    end
    result << ""
    result << "  s.required_rubygems_version = #{ruby_code required_rubygems_version} if s.respond_to? :required_rubygems_version="

    if metadata and !metadata.empty?
      result << "  s.metadata = #{ruby_code metadata} if s.respond_to? :metadata="
    end
    result << "  s.require_paths = #{ruby_code raw_require_paths}"

    handled = [
      :dependencies,
      :name,
      :platform,
      :require_paths,
      :required_rubygems_version,
      :specification_version,
      :version,
      :has_rdoc,
      :default_executable,
      :metadata,
      :signing_key,
    ]

    @@attributes.each do |attr_name|
      next if handled.include? attr_name
      current_value = self.send(attr_name)
      if current_value != default_value(attr_name) || self.class.required_attribute?(attr_name)
        result << "  s.#{attr_name} = #{ruby_code current_value}"
      end
    end

    if String === signing_key
      result << "  s.signing_key = #{signing_key.dump}.freeze"
    end

    if @installed_by_version
      result << nil
      result << "  s.installed_by_version = \"#{Gem::VERSION}\" if s.respond_to? :installed_by_version"
    end

    unless dependencies.empty?
      result << nil
      result << "  if s.respond_to? :specification_version then"
      result << "    s.specification_version = #{specification_version}"
      result << "  end"
      result << nil

      result << "  if s.respond_to? :add_runtime_dependency then"

      dependencies.each do |dep|
        req = dep.requirements_list.inspect
        dep.instance_variable_set :@type, :runtime if dep.type.nil? # HACK
        result << "    s.add_#{dep.type}_dependency(%q<#{dep.name}>.freeze, #{req})"
      end

      result << "  else"
      dependencies.each do |dep|
        version_reqs_param = dep.requirements_list.inspect
        result << "    s.add_dependency(%q<#{dep.name}>.freeze, #{version_reqs_param})"
      end
      result << "  end"
    end

    result << "end"
    result << nil

    result.join "\n"
  end

  ##
  # Returns a Ruby lighter-weight code representation of this specification,
  # used for indexing only.
  #
  # See #to_ruby.

  def to_ruby_for_cache
    for_cache.to_ruby
  end

  def to_s # :nodoc:
    "#<Gem::Specification name=#{@name} version=#{@version}>"
  end

  ##
  # Returns self

  def to_spec
    self
  end

  def to_yaml(opts = {}) # :nodoc:
    Gem.load_yaml

    # Because the user can switch the YAML engine behind our
    # back, we have to check again here to make sure that our
    # psych code was properly loaded, and load it if not.
    unless Gem.const_defined?(:NoAliasYAMLTree)
      require_relative 'psych_tree'
    end

    builder = Gem::NoAliasYAMLTree.create
    builder << self
    ast = builder.tree

    require 'stringio'
    io = StringIO.new
    io.set_encoding Encoding::UTF_8

    Psych::Visitors::Emitter.new(io).accept(ast)

    io.string.gsub(/ !!null \n/, " \n")
  end

  ##
  # Recursively walk dependencies of this spec, executing the +block+ for each
  # hop.

  def traverse(trail = [], visited = {}, &block)
    trail.push(self)
    begin
      dependencies.each do |dep|
        next unless dep.runtime?
        dep.matching_specs(true).each do |dep_spec|
          next if visited.has_key?(dep_spec)
          visited[dep_spec] = true
          trail.push(dep_spec)
          begin
            result = block[self, dep, dep_spec, trail]
          ensure
            trail.pop
          end
          unless result == :next
            spec_name = dep_spec.name
            dep_spec.traverse(trail, visited, &block) unless
              trail.any? {|s| s.name == spec_name }
          end
        end
      end
    ensure
      trail.pop
    end
  end

  ##
  # Checks that the specification contains all required fields, and does a
  # very basic sanity check.
  #
  # Raises InvalidSpecificationException if the spec does not pass the
  # checks..

  def validate(packaging = true, strict = false)
    normalize

    validation_policy = Gem::SpecificationPolicy.new(self)
    validation_policy.packaging = packaging
    validation_policy.validate(strict)
  end

  def keep_only_files_and_directories
    @executables.delete_if      {|x| File.directory?(File.join(@bindir, x)) }
    @extensions.delete_if       {|x| File.directory?(x) && !File.symlink?(x) }
    @extra_rdoc_files.delete_if {|x| File.directory?(x) && !File.symlink?(x) }
    @files.delete_if            {|x| File.directory?(x) && !File.symlink?(x) }
    @test_files.delete_if       {|x| File.directory?(x) && !File.symlink?(x) }
  end

  def validate_metadata
    Gem::SpecificationPolicy.new(self).validate_metadata
  end
  rubygems_deprecate :validate_metadata

  def validate_dependencies
    Gem::SpecificationPolicy.new(self).validate_dependencies
  end
  rubygems_deprecate :validate_dependencies

  def validate_permissions
    Gem::SpecificationPolicy.new(self).validate_permissions
  end
  rubygems_deprecate :validate_permissions

  ##
  # Set the version to +version+, potentially also setting
  # required_rubygems_version if +version+ indicates it is a
  # prerelease.

  def version=(version)
    @version = Gem::Version.create(version)
    # skip to set required_ruby_version when pre-released rubygems.
    # It caused to raise CircularDependencyError
    if @version.prerelease? && (@name.nil? || @name.strip != "rubygems")
      self.required_rubygems_version = '> 1.3.1'
    end
    invalidate_memoized_attributes

    return @version
  end

  def stubbed?
    false
  end

  def yaml_initialize(tag, vals) # :nodoc:
    vals.each do |ivar, val|
      case ivar
      when "date"
        # Force Date to go through the extra coerce logic in date=
        self.date = val.tap(&Gem::UNTAINT)
      else
        instance_variable_set "@#{ivar}", val.tap(&Gem::UNTAINT)
      end
    end

    @original_platform = @platform # for backwards compatibility
    self.platform = Gem::Platform.new @platform
  end

  ##
  # Reset nil attributes to their default values to make the spec valid

  def reset_nil_attributes_to_default
    nil_attributes = self.class.non_nil_attributes.find_all do |name|
      !instance_variable_defined?("@#{name}") || instance_variable_get("@#{name}").nil?
    end

    nil_attributes.each do |attribute|
      default = self.default_value attribute

      value = case default
              when Time, Numeric, Symbol, true, false, nil then default
              else default.dup
              end

      instance_variable_set "@#{attribute}", value
    end

    @installed_by_version ||= nil
  end

  def raw_require_paths # :nodoc:
    @require_paths
  end
end
# frozen_string_literal: true
##
# A set which represents the installed gems. Respects
# all the normal settings that control where to look
# for installed gems.

class Gem::Resolver::CurrentSet < Gem::Resolver::Set
  def find_all(req)
    req.dependency.matching_specs
  end
end
# frozen_string_literal: true
require_relative 'molinillo/lib/molinillo'
# frozen_string_literal: true
##
# The Resolver::SpecSpecification contains common functionality for
# Resolver specifications that are backed by a Gem::Specification.

class Gem::Resolver::SpecSpecification < Gem::Resolver::Specification
  ##
  # A SpecSpecification is created for a +set+ for a Gem::Specification in
  # +spec+.  The +source+ is either where the +spec+ came from, or should be
  # loaded from.

  def initialize(set, spec, source = nil)
    @set    = set
    @source = source
    @spec   = spec
  end

  ##
  # The dependencies of the gem for this specification

  def dependencies
    spec.dependencies
  end

  ##
  # The required_ruby_version constraint for this specification

  def required_ruby_version
    spec.required_ruby_version
  end

  ##
  # The required_rubygems_version constraint for this specification

  def required_rubygems_version
    spec.required_rubygems_version
  end

  ##
  # The name and version of the specification.
  #
  # Unlike Gem::Specification#full_name, the platform is not included.

  def full_name
    "#{spec.name}-#{spec.version}"
  end

  ##
  # The name of the gem for this specification

  def name
    spec.name
  end

  ##
  # The platform this gem works on.

  def platform
    spec.platform
  end

  ##
  # The version of the gem for this specification.

  def version
    spec.version
  end
end
# frozen_string_literal: true
##
# Used internally to indicate that a dependency conflicted
# with a spec that would be activated.

class Gem::Resolver::Conflict
  ##
  # The specification that was activated prior to the conflict

  attr_reader :activated

  ##
  # The dependency that is in conflict with the activated gem.

  attr_reader :dependency

  attr_reader :failed_dep # :nodoc:

  ##
  # Creates a new resolver conflict when +dependency+ is in conflict with an
  # already +activated+ specification.

  def initialize(dependency, activated, failed_dep=dependency)
    @dependency = dependency
    @activated = activated
    @failed_dep = failed_dep
  end

  def ==(other) # :nodoc:
    self.class === other and
      @dependency == other.dependency and
      @activated  == other.activated  and
      @failed_dep == other.failed_dep
  end

  ##
  # A string explanation of the conflict.

  def explain
    "<Conflict wanted: #{@failed_dep}, had: #{activated.spec.full_name}>"
  end

  ##
  # Return the 2 dependency objects that conflicted

  def conflicting_dependencies
    [@failed_dep.dependency, @activated.request.dependency]
  end

  ##
  # Explanation of the conflict used by exceptions to print useful messages

  def explanation
    activated   = @activated.spec.full_name
    dependency  = @failed_dep.dependency
    requirement = dependency.requirement
    alternates  = dependency.matching_specs.map {|spec| spec.full_name }

    unless alternates.empty?
      matching = <<-MATCHING.chomp

  Gems matching %s:
    %s
      MATCHING

      matching = matching % [
        dependency,
        alternates.join(', '),
      ]
    end

    explanation = <<-EXPLANATION
  Activated %s
  which does not match conflicting dependency (%s)

  Conflicting dependency chains:
    %s

  versus:
    %s
%s
    EXPLANATION

    explanation % [
      activated, requirement,
      request_path(@activated).reverse.join(", depends on\n    "),
      request_path(@failed_dep).reverse.join(", depends on\n    "),
      matching
    ]
  end

  ##
  # Returns true if the conflicting dependency's name matches +spec+.

  def for_spec?(spec)
    @dependency.name == spec.name
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[Dependency conflict: ', ']' do
      q.breakable

      q.text 'activated '
      q.pp @activated

      q.breakable
      q.text ' dependency '
      q.pp @dependency

      q.breakable
      if @dependency == @failed_dep
        q.text ' failed'
      else
        q.text ' failed dependency '
        q.pp @failed_dep
      end
    end
  end

  ##
  # Path of activations from the +current+ list.

  def request_path(current)
    path = []

    while current do
      case current
      when Gem::Resolver::ActivationRequest then
        path <<
          "#{current.request.dependency}, #{current.spec.version} activated"

        current = current.parent
      when Gem::Resolver::DependencyRequest then
        path << "#{current.dependency}"

        current = current.requester
      else
        raise Gem::Exception, "[BUG] unknown request class #{current.class}"
      end
    end

    path = ['user request (gem command or Gemfile)'] if path.empty?

    path
  end

  ##
  # Return the Specification that listed the dependency

  def requester
    @failed_dep.requester
  end
end
# frozen_string_literal: true
##
# The RequirementList is used to hold the requirements being considered
# while resolving a set of gems.
#
# The RequirementList acts like a queue where the oldest items are removed
# first.

class Gem::Resolver::RequirementList
  include Enumerable

  ##
  # Creates a new RequirementList.

  def initialize
    @exact = []
    @list = []
  end

  def initialize_copy(other) # :nodoc:
    @exact = @exact.dup
    @list = @list.dup
  end

  ##
  # Adds Resolver::DependencyRequest +req+ to this requirements list.

  def add(req)
    if req.requirement.exact?
      @exact.push req
    else
      @list.push req
    end
    req
  end

  ##
  # Enumerates requirements in the list

  def each # :nodoc:
    return enum_for __method__ unless block_given?

    @exact.each do |requirement|
      yield requirement
    end

    @list.each do |requirement|
      yield requirement
    end
  end

  ##
  # How many elements are in the list

  def size
    @exact.size + @list.size
  end

  ##
  # Is the list empty?

  def empty?
    @exact.empty? && @list.empty?
  end

  ##
  # Remove the oldest DependencyRequest from the list.

  def remove
    return @exact.shift unless @exact.empty?
    @list.shift
  end

  ##
  # Returns the oldest five entries from the list.

  def next5
    x = @exact[0,5]
    x + @list[0,5 - x.size]
  end
end
# frozen_string_literal: true
##
# Represents a possible Specification object returned from IndexSet.  Used to
# delay needed to download full Specification objects when only the +name+
# and +version+ are needed.

class Gem::Resolver::IndexSpecification < Gem::Resolver::Specification
  ##
  # An IndexSpecification is created from the index format described in `gem
  # help generate_index`.
  #
  # The +set+ contains other specifications for this (URL) +source+.
  #
  # The +name+, +version+ and +platform+ are the name, version and platform of
  # the gem.

  def initialize(set, name, version, source, platform)
    super()

    @set = set
    @name = name
    @version = version
    @source = source
    @platform = platform.to_s

    @spec = nil
  end

  ##
  # The dependencies of the gem for this specification

  def dependencies
    spec.dependencies
  end

  ##
  # The required_ruby_version constraint for this specification
  #
  # A fallback is included because when generated, some marshalled specs have it
  # set to +nil+.

  def required_ruby_version
    spec.required_ruby_version || Gem::Requirement.default
  end

  ##
  # The required_rubygems_version constraint for this specification
  #
  # A fallback is included because the original version of the specification
  # API didn't include that field, so some marshalled specs in the index have it
  # set to +nil+.

  def required_rubygems_version
    spec.required_rubygems_version || Gem::Requirement.default
  end

  def ==(other)
    self.class === other &&
      @name == other.name &&
      @version == other.version &&
      @platform == other.platform
  end

  def hash
    @name.hash ^ @version.hash ^ @platform.hash
  end

  def inspect # :nodoc:
    '#<%s %s source %s>' % [self.class, full_name, @source]
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[Index specification', ']' do
      q.breakable
      q.text full_name

      unless Gem::Platform::RUBY == @platform
        q.breakable
        q.text @platform.to_s
      end

      q.breakable
      q.text 'source '
      q.pp @source
    end
  end

  ##
  # Fetches a Gem::Specification for this IndexSpecification from the #source.

  def spec # :nodoc:
    @spec ||=
      begin
        tuple = Gem::NameTuple.new @name, @version, @platform

        @source.fetch_spec tuple
      end
  end
end
# frozen_string_literal: true
##
# Resolver sets are used to look up specifications (and their
# dependencies) used in resolution.  This set is abstract.

class Gem::Resolver::Set
  ##
  # Set to true to disable network access for this set

  attr_accessor :remote

  ##
  # Errors encountered when resolving gems

  attr_accessor :errors

  ##
  # When true, allows matching of requests to prerelease gems.

  attr_accessor :prerelease

  def initialize # :nodoc:
    @prerelease = false
    @remote     = true
    @errors     = []
  end

  ##
  # The find_all method must be implemented.  It returns all Resolver
  # Specification objects matching the given DependencyRequest +req+.

  def find_all(req)
    raise NotImplementedError
  end

  ##
  # The #prefetch method may be overridden, but this is not necessary.  This
  # default implementation does nothing, which is suitable for sets where
  # looking up a specification is cheap (such as installed gems).
  #
  # When overridden, the #prefetch method should look up specifications
  # matching +reqs+.

  def prefetch(reqs)
  end

  ##
  # When true, this set is allowed to access the network when looking up
  # specifications or dependencies.

  def remote? # :nodoc:
    @remote
  end
end
# frozen_string_literal: true
##
# A GitSpecification represents a gem that is sourced from a git repository
# and is being loaded through a gem dependencies file through the +git:+
# option.

class Gem::Resolver::GitSpecification < Gem::Resolver::SpecSpecification
  def ==(other) # :nodoc:
    self.class === other and
      @set  == other.set and
      @spec == other.spec and
      @source == other.source
  end

  def add_dependency(dependency) # :nodoc:
    spec.dependencies << dependency
  end

  ##
  # Installing a git gem only involves building the extensions and generating
  # the executables.

  def install(options = {})
    require_relative '../installer'

    installer = Gem::Installer.for_spec spec, options

    yield installer if block_given?

    installer.run_pre_install_hooks
    installer.build_extensions
    installer.run_post_build_hooks
    installer.generate_bin
    installer.run_post_install_hooks
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[GitSpecification', ']' do
      q.breakable
      q.text "name: #{name}"

      q.breakable
      q.text "version: #{version}"

      q.breakable
      q.text 'dependencies:'
      q.breakable
      q.pp dependencies

      q.breakable
      q.text "source:"
      q.breakable
      q.pp @source
    end
  end
end
# frozen_string_literal: true
##
# An InstalledSpecification represents a gem that is already installed
# locally.

class Gem::Resolver::InstalledSpecification < Gem::Resolver::SpecSpecification
  def ==(other) # :nodoc:
    self.class === other and
      @set  == other.set and
      @spec == other.spec
  end

  ##
  # This is a null install as this specification is already installed.
  # +options+ are ignored.

  def install(options = {})
    yield nil
  end

  ##
  # Returns +true+ if this gem is installable for the current platform.

  def installable_platform?
    # BACKCOMPAT If the file is coming out of a specified file, then we
    # ignore the platform. This code can be removed in RG 3.0.
    return true if @source.kind_of? Gem::Source::SpecificFile

    super
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[InstalledSpecification', ']' do
      q.breakable
      q.text "name: #{name}"

      q.breakable
      q.text "version: #{version}"

      q.breakable
      q.text "platform: #{platform}"

      q.breakable
      q.text 'dependencies:'
      q.breakable
      q.pp spec.dependencies
    end
  end

  ##
  # The source for this specification

  def source
    @source ||= Gem::Source::Installed.new
  end
end
# frozen_string_literal: true
##
# The BestSet chooses the best available method to query a remote index.
#
# It combines IndexSet and APISet

class Gem::Resolver::BestSet < Gem::Resolver::ComposedSet
  ##
  # Creates a BestSet for the given +sources+ or Gem::sources if none are
  # specified.  +sources+ must be a Gem::SourceList.

  def initialize(sources = Gem.sources)
    super()

    @sources = sources
  end

  ##
  # Picks which sets to use for the configured sources.

  def pick_sets # :nodoc:
    @sources.each_source do |source|
      @sets << source.dependency_resolver_set
    end
  end

  def find_all(req) # :nodoc:
    pick_sets if @remote and @sets.empty?

    super
  rescue Gem::RemoteFetcher::FetchError => e
    replace_failed_api_set e

    retry
  end

  def prefetch(reqs) # :nodoc:
    pick_sets if @remote and @sets.empty?

    super
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[BestSet', ']' do
      q.breakable
      q.text 'sets:'

      q.breakable
      q.pp @sets
    end
  end

  ##
  # Replaces a failed APISet for the URI in +error+ with an IndexSet.
  #
  # If no matching APISet can be found the original +error+ is raised.
  #
  # The calling method must retry the exception to repeat the lookup.

  def replace_failed_api_set(error) # :nodoc:
    uri = error.original_uri
    uri = URI uri unless URI === uri
    uri = uri + "."

    raise error unless api_set = @sets.find do |set|
      Gem::Resolver::APISet === set and set.dep_uri == uri
    end

    index_set = Gem::Resolver::IndexSet.new api_set.source

    @sets.map! do |set|
      next set unless set == api_set
      index_set
    end
  end
end
# frozen_string_literal: true
##
# A set of gems for installation sourced from remote sources and local .gem
# files

class Gem::Resolver::InstallerSet < Gem::Resolver::Set
  ##
  # List of Gem::Specification objects that must always be installed.

  attr_reader :always_install # :nodoc:

  ##
  # Only install gems in the always_install list

  attr_accessor :ignore_dependencies # :nodoc:

  ##
  # Do not look in the installed set when finding specifications.  This is
  # used by the --install-dir option to `gem install`

  attr_accessor :ignore_installed # :nodoc:

  ##
  # The remote_set looks up remote gems for installation.

  attr_reader :remote_set # :nodoc:

  ##
  # Ignore ruby & rubygems specification constraints.
  #

  attr_accessor :force # :nodoc:

  ##
  # Creates a new InstallerSet that will look for gems in +domain+.

  def initialize(domain)
    super()

    @domain = domain

    @f = Gem::SpecFetcher.fetcher

    @always_install      = []
    @ignore_dependencies = false
    @ignore_installed    = false
    @local               = {}
    @local_source        = Gem::Source::Local.new
    @remote_set          = Gem::Resolver::BestSet.new
    @force               = false
    @specs               = {}
  end

  ##
  # Looks up the latest specification for +dependency+ and adds it to the
  # always_install list.

  def add_always_install(dependency)
    request = Gem::Resolver::DependencyRequest.new dependency, nil

    found = find_all request

    found.delete_if do |s|
      s.version.prerelease? and not s.local?
    end unless dependency.prerelease?

    found = found.select do |s|
      Gem::Source::SpecificFile === s.source or
        Gem::Platform::RUBY == s.platform or
        Gem::Platform.local === s.platform
    end

    found = found.sort_by do |s|
      [s.version, s.platform == Gem::Platform::RUBY ? -1 : 1]
    end

    newest = found.last

    unless @force
      found_matching_metadata = found.reverse.find do |spec|
        metadata_satisfied?(spec)
      end

      if found_matching_metadata.nil?
        if newest
          ensure_required_ruby_version_met(newest.spec)
          ensure_required_rubygems_version_met(newest.spec)
        else
          exc = Gem::UnsatisfiableDependencyError.new request
          exc.errors = errors

          raise exc
        end
      else
        newest = found_matching_metadata
      end
    end

    @always_install << newest.spec
  end

  ##
  # Adds a local gem requested using +dep_name+ with the given +spec+ that can
  # be loaded and installed using the +source+.

  def add_local(dep_name, spec, source)
    @local[dep_name] = [spec, source]
  end

  ##
  # Should local gems should be considered?

  def consider_local? # :nodoc:
    @domain == :both or @domain == :local
  end

  ##
  # Should remote gems should be considered?

  def consider_remote? # :nodoc:
    @domain == :both or @domain == :remote
  end

  ##
  # Errors encountered while resolving gems

  def errors
    @errors + @remote_set.errors
  end

  ##
  # Returns an array of IndexSpecification objects matching DependencyRequest
  # +req+.

  def find_all(req)
    res = []

    dep = req.dependency

    return res if @ignore_dependencies and
              @always_install.none? {|spec| dep.match? spec }

    name = dep.name

    dep.matching_specs.each do |gemspec|
      next if @always_install.any? {|spec| spec.name == gemspec.name }

      res << Gem::Resolver::InstalledSpecification.new(self, gemspec)
    end unless @ignore_installed

    if consider_local?
      matching_local = @local.values.select do |spec, _|
        req.match? spec
      end.map do |spec, source|
        Gem::Resolver::LocalSpecification.new self, spec, source
      end

      res.concat matching_local

      begin
        if local_spec = @local_source.find_gem(name, dep.requirement)
          res << Gem::Resolver::IndexSpecification.new(
            self, local_spec.name, local_spec.version,
            @local_source, local_spec.platform)
        end
      rescue Gem::Package::FormatError
        # ignore
      end
    end

    res.delete_if do |spec|
      spec.version.prerelease? and not dep.prerelease?
    end

    res.concat @remote_set.find_all req if consider_remote?

    res
  end

  def prefetch(reqs)
    @remote_set.prefetch(reqs) if consider_remote?
  end

  def prerelease=(allow_prerelease)
    super

    @remote_set.prerelease = allow_prerelease
  end

  def inspect # :nodoc:
    always_install = @always_install.map {|s| s.full_name }

    '#<%s domain: %s specs: %p always install: %p>' % [
      self.class, @domain, @specs.keys, always_install
    ]
  end

  ##
  # Called from IndexSpecification to get a true Specification
  # object.

  def load_spec(name, ver, platform, source) # :nodoc:
    key = "#{name}-#{ver}-#{platform}"

    @specs.fetch key do
      tuple = Gem::NameTuple.new name, ver, platform

      @specs[key] = source.fetch_spec tuple
    end
  end

  ##
  # Has a local gem for +dep_name+ been added to this set?

  def local?(dep_name) # :nodoc:
    spec, _ = @local[dep_name]

    spec
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[InstallerSet', ']' do
      q.breakable
      q.text "domain: #{@domain}"

      q.breakable
      q.text 'specs: '
      q.pp @specs.keys

      q.breakable
      q.text 'always install: '
      q.pp @always_install
    end
  end

  def remote=(remote) # :nodoc:
    case @domain
    when :local then
      @domain = :both if remote
    when :remote then
      @domain = nil unless remote
    when :both then
      @domain = :local unless remote
    end
  end

  private

  def metadata_satisfied?(spec)
    spec.required_ruby_version.satisfied_by?(Gem.ruby_version) &&
      spec.required_rubygems_version.satisfied_by?(Gem.rubygems_version)
  end

  def ensure_required_ruby_version_met(spec) # :nodoc:
    if rrv = spec.required_ruby_version
      ruby_version = Gem.ruby_version
      unless rrv.satisfied_by? ruby_version
        raise Gem::RuntimeRequirementNotMetError,
          "#{spec.full_name} requires Ruby version #{rrv}. The current ruby version is #{ruby_version}."
      end
    end
  end

  def ensure_required_rubygems_version_met(spec) # :nodoc:
    if rrgv = spec.required_rubygems_version
      unless rrgv.satisfied_by? Gem.rubygems_version
        rg_version = Gem::VERSION
        raise Gem::RuntimeRequirementNotMetError,
          "#{spec.full_name} requires RubyGems version #{rrgv}. The current RubyGems version is #{rg_version}. " +
          "Try 'gem update --system' to update RubyGems itself."
      end
    end
  end
end
# frozen_string_literal: true
##
# The global rubygems pool, available via the rubygems.org API.
# Returns instances of APISpecification.

class Gem::Resolver::APISet < Gem::Resolver::Set
  autoload :GemParser, File.expand_path("api_set/gem_parser", __dir__)

  ##
  # The URI for the dependency API this APISet uses.

  attr_reader :dep_uri # :nodoc:

  ##
  # The Gem::Source that gems are fetched from

  attr_reader :source

  ##
  # The corresponding place to fetch gems.

  attr_reader :uri

  ##
  # Creates a new APISet that will retrieve gems from +uri+ using the RubyGems
  # API URL +dep_uri+ which is described at
  # https://guides.rubygems.org/rubygems-org-api

  def initialize(dep_uri = 'https://index.rubygems.org/info/')
    super()

    dep_uri = URI dep_uri unless URI === dep_uri

    @dep_uri = dep_uri
    @uri     = dep_uri + '..'

    @data   = Hash.new {|h,k| h[k] = [] }
    @source = Gem::Source.new @uri

    @to_fetch = []
  end

  ##
  # Return an array of APISpecification objects matching
  # DependencyRequest +req+.

  def find_all(req)
    res = []

    return res unless @remote

    if @to_fetch.include?(req.name)
      prefetch_now
    end

    versions(req.name).each do |ver|
      if req.dependency.match? req.name, ver[:number], @prerelease
        res << Gem::Resolver::APISpecification.new(self, ver)
      end
    end

    res
  end

  ##
  # A hint run by the resolver to allow the Set to fetch
  # data for DependencyRequests +reqs+.

  def prefetch(reqs)
    return unless @remote
    names = reqs.map {|r| r.dependency.name }
    needed = names - @data.keys - @to_fetch

    @to_fetch += needed
  end

  def prefetch_now # :nodoc:
    needed, @to_fetch = @to_fetch, []

    needed.sort.each do |name|
      versions(name)
    end
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[APISet', ']' do
      q.breakable
      q.text "URI: #{@dep_uri}"

      q.breakable
      q.text 'gem names:'
      q.pp @data.keys
    end
  end

  ##
  # Return data for all versions of the gem +name+.

  def versions(name) # :nodoc:
    if @data.key?(name)
      return @data[name]
    end

    uri = @dep_uri + name
    str = Gem::RemoteFetcher.fetcher.fetch_path uri

    lines(str).each do |ver|
      number, platform, dependencies, requirements = parse_gem(ver)

      platform ||= "ruby"
      dependencies = dependencies.map {|dep_name, reqs| [dep_name, reqs.join(", ")] }
      requirements = requirements.map {|req_name, reqs| [req_name.to_sym, reqs] }.to_h

      @data[name] << { name: name, number: number, platform: platform, dependencies: dependencies, requirements: requirements }
    end

    @data[name]
  end

  private

  def lines(str)
    lines = str.split("\n")
    header = lines.index("---")
    header ? lines[header + 1..-1] : lines
  end

  def parse_gem(string)
    @gem_parser ||= GemParser.new
    @gem_parser.parse(string)
  end
end
# frozen_string_literal: true
##
# The global rubygems pool represented via the traditional
# source index.

class Gem::Resolver::IndexSet < Gem::Resolver::Set
  def initialize(source = nil) # :nodoc:
    super()

    @f =
      if source
        sources = Gem::SourceList.from [source]

        Gem::SpecFetcher.new sources
      else
        Gem::SpecFetcher.fetcher
      end

    @all = Hash.new {|h,k| h[k] = [] }

    list, errors = @f.available_specs :complete

    @errors.concat errors

    list.each do |uri, specs|
      specs.each do |n|
        @all[n.name] << [uri, n]
      end
    end

    @specs = {}
  end

  ##
  # Return an array of IndexSpecification objects matching
  # DependencyRequest +req+.

  def find_all(req)
    res = []

    return res unless @remote

    name = req.dependency.name

    @all[name].each do |uri, n|
      if req.match? n, @prerelease
        res << Gem::Resolver::IndexSpecification.new(
          self, n.name, n.version, uri, n.platform)
      end
    end

    res
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[IndexSet', ']' do
      q.breakable
      q.text 'sources:'
      q.breakable
      q.pp @f.sources

      q.breakable
      q.text 'specs:'

      q.breakable

      names = @all.values.map do |tuples|
        tuples.map do |_, tuple|
          tuple.full_name
        end
      end.flatten

      q.seplist names do |name|
        q.text name
      end
    end
  end
end
This project is licensed under the MIT license.

Copyright (c) 2014 Samuel E. Giddins segiddins@segiddins.me

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.
# frozen_string_literal: true

require_relative 'molinillo/gem_metadata'
require_relative 'molinillo/errors'
require_relative 'molinillo/resolver'
require_relative 'molinillo/modules/ui'
require_relative 'molinillo/modules/specification_provider'

# Gem::Resolver::Molinillo is a generic dependency resolution algorithm.
module Gem::Resolver::Molinillo
end
# frozen_string_literal: true

require_relative '../../../../tsort'

require_relative 'dependency_graph/log'
require_relative 'dependency_graph/vertex'

module Gem::Resolver::Molinillo
  # A directed acyclic graph that is tuned to hold named dependencies
  class DependencyGraph
    include Enumerable

    # Enumerates through the vertices of the graph.
    # @return [Array<Vertex>] The graph's vertices.
    def each
      return vertices.values.each unless block_given?
      vertices.values.each { |v| yield v }
    end

    include Gem::TSort

    # @!visibility private
    alias tsort_each_node each

    # @!visibility private
    def tsort_each_child(vertex, &block)
      vertex.successors.each(&block)
    end

    # Topologically sorts the given vertices.
    # @param [Enumerable<Vertex>] vertices the vertices to be sorted, which must
    #   all belong to the same graph.
    # @return [Array<Vertex>] The sorted vertices.
    def self.tsort(vertices)
      TSort.tsort(
        lambda { |b| vertices.each(&b) },
        lambda { |v, &b| (v.successors & vertices).each(&b) }
      )
    end

    # A directed edge of a {DependencyGraph}
    # @attr [Vertex] origin The origin of the directed edge
    # @attr [Vertex] destination The destination of the directed edge
    # @attr [Object] requirement The requirement the directed edge represents
    Edge = Struct.new(:origin, :destination, :requirement)

    # @return [{String => Vertex}] the vertices of the dependency graph, keyed
    #   by {Vertex#name}
    attr_reader :vertices

    # @return [Log] the op log for this graph
    attr_reader :log

    # Initializes an empty dependency graph
    def initialize
      @vertices = {}
      @log = Log.new
    end

    # Tags the current state of the dependency as the given tag
    # @param  [Object] tag an opaque tag for the current state of the graph
    # @return [Void]
    def tag(tag)
      log.tag(self, tag)
    end

    # Rewinds the graph to the state tagged as `tag`
    # @param  [Object] tag the tag to rewind to
    # @return [Void]
    def rewind_to(tag)
      log.rewind_to(self, tag)
    end

    # Initializes a copy of a {DependencyGraph}, ensuring that all {#vertices}
    # are properly copied.
    # @param [DependencyGraph] other the graph to copy.
    def initialize_copy(other)
      super
      @vertices = {}
      @log = other.log.dup
      traverse = lambda do |new_v, old_v|
        return if new_v.outgoing_edges.size == old_v.outgoing_edges.size
        old_v.outgoing_edges.each do |edge|
          destination = add_vertex(edge.destination.name, edge.destination.payload)
          add_edge_no_circular(new_v, destination, edge.requirement)
          traverse.call(destination, edge.destination)
        end
      end
      other.vertices.each do |name, vertex|
        new_vertex = add_vertex(name, vertex.payload, vertex.root?)
        new_vertex.explicit_requirements.replace(vertex.explicit_requirements)
        traverse.call(new_vertex, vertex)
      end
    end

    # @return [String] a string suitable for debugging
    def inspect
      "#{self.class}:#{vertices.values.inspect}"
    end

    # @param [Hash] options options for dot output.
    # @return [String] Returns a dot format representation of the graph
    def to_dot(options = {})
      edge_label = options.delete(:edge_label)
      raise ArgumentError, "Unknown options: #{options.keys}" unless options.empty?

      dot_vertices = []
      dot_edges = []
      vertices.each do |n, v|
        dot_vertices << "  #{n} [label=\"{#{n}|#{v.payload}}\"]"
        v.outgoing_edges.each do |e|
          label = edge_label ? edge_label.call(e) : e.requirement
          dot_edges << "  #{e.origin.name} -> #{e.destination.name} [label=#{label.to_s.dump}]"
        end
      end

      dot_vertices.uniq!
      dot_vertices.sort!
      dot_edges.uniq!
      dot_edges.sort!

      dot = dot_vertices.unshift('digraph G {').push('') + dot_edges.push('}')
      dot.join("\n")
    end

    # @param [DependencyGraph] other
    # @return [Boolean] whether the two dependency graphs are equal, determined
    #   by a recursive traversal of each {#root_vertices} and its
    #   {Vertex#successors}
    def ==(other)
      return false unless other
      return true if equal?(other)
      vertices.each do |name, vertex|
        other_vertex = other.vertex_named(name)
        return false unless other_vertex
        return false unless vertex.payload == other_vertex.payload
        return false unless other_vertex.successors.to_set == vertex.successors.to_set
      end
    end

    # @param [String] name
    # @param [Object] payload
    # @param [Array<String>] parent_names
    # @param [Object] requirement the requirement that is requiring the child
    # @return [void]
    def add_child_vertex(name, payload, parent_names, requirement)
      root = !parent_names.delete(nil) { true }
      vertex = add_vertex(name, payload, root)
      vertex.explicit_requirements << requirement if root
      parent_names.each do |parent_name|
        parent_vertex = vertex_named(parent_name)
        add_edge(parent_vertex, vertex, requirement)
      end
      vertex
    end

    # Adds a vertex with the given name, or updates the existing one.
    # @param [String] name
    # @param [Object] payload
    # @return [Vertex] the vertex that was added to `self`
    def add_vertex(name, payload, root = false)
      log.add_vertex(self, name, payload, root)
    end

    # Detaches the {#vertex_named} `name` {Vertex} from the graph, recursively
    # removing any non-root vertices that were orphaned in the process
    # @param [String] name
    # @return [Array<Vertex>] the vertices which have been detached
    def detach_vertex_named(name)
      log.detach_vertex_named(self, name)
    end

    # @param [String] name
    # @return [Vertex,nil] the vertex with the given name
    def vertex_named(name)
      vertices[name]
    end

    # @param [String] name
    # @return [Vertex,nil] the root vertex with the given name
    def root_vertex_named(name)
      vertex = vertex_named(name)
      vertex if vertex && vertex.root?
    end

    # Adds a new {Edge} to the dependency graph
    # @param [Vertex] origin
    # @param [Vertex] destination
    # @param [Object] requirement the requirement that this edge represents
    # @return [Edge] the added edge
    def add_edge(origin, destination, requirement)
      if destination.path_to?(origin)
        raise CircularDependencyError.new(path(destination, origin))
      end
      add_edge_no_circular(origin, destination, requirement)
    end

    # Deletes an {Edge} from the dependency graph
    # @param [Edge] edge
    # @return [Void]
    def delete_edge(edge)
      log.delete_edge(self, edge.origin.name, edge.destination.name, edge.requirement)
    end

    # Sets the payload of the vertex with the given name
    # @param [String] name the name of the vertex
    # @param [Object] payload the payload
    # @return [Void]
    def set_payload(name, payload)
      log.set_payload(self, name, payload)
    end

    private

    # Adds a new {Edge} to the dependency graph without checking for
    # circularity.
    # @param (see #add_edge)
    # @return (see #add_edge)
    def add_edge_no_circular(origin, destination, requirement)
      log.add_edge_no_circular(self, origin.name, destination.name, requirement)
    end

    # Returns the path between two vertices
    # @raise [ArgumentError] if there is no path between the vertices
    # @param [Vertex] from
    # @param [Vertex] to
    # @return [Array<Vertex>] the shortest path from `from` to `to`
    def path(from, to)
      distances = Hash.new(vertices.size + 1)
      distances[from.name] = 0
      predecessors = {}
      each do |vertex|
        vertex.successors.each do |successor|
          if distances[successor.name] > distances[vertex.name] + 1
            distances[successor.name] = distances[vertex.name] + 1
            predecessors[successor] = vertex
          end
        end
      end

      path = [to]
      while before = predecessors[to]
        path << before
        to = before
        break if to == from
      end

      unless path.last.equal?(from)
        raise ArgumentError, "There is no path from #{from.name} to #{to.name}"
      end

      path.reverse
    end
  end
end
# frozen_string_literal: true

module Gem::Resolver::Molinillo
  class Resolver
    # A specific resolution from a given {Resolver}
    class Resolution
      # A conflict that the resolution process encountered
      # @attr [Object] requirement the requirement that immediately led to the conflict
      # @attr [{String,Nil=>[Object]}] requirements the requirements that caused the conflict
      # @attr [Object, nil] existing the existing spec that was in conflict with
      #   the {#possibility}
      # @attr [Object] possibility_set the set of specs that was unable to be
      #   activated due to a conflict.
      # @attr [Object] locked_requirement the relevant locking requirement.
      # @attr [Array<Array<Object>>] requirement_trees the different requirement
      #   trees that led to every requirement for the conflicting name.
      # @attr [{String=>Object}] activated_by_name the already-activated specs.
      # @attr [Object] underlying_error an error that has occurred during resolution, and
      #    will be raised at the end of it if no resolution is found.
      Conflict = Struct.new(
        :requirement,
        :requirements,
        :existing,
        :possibility_set,
        :locked_requirement,
        :requirement_trees,
        :activated_by_name,
        :underlying_error
      )

      class Conflict
        # @return [Object] a spec that was unable to be activated due to a conflict
        def possibility
          possibility_set && possibility_set.latest_version
        end
      end

      # A collection of possibility states that share the same dependencies
      # @attr [Array] dependencies the dependencies for this set of possibilities
      # @attr [Array] possibilities the possibilities
      PossibilitySet = Struct.new(:dependencies, :possibilities)

      class PossibilitySet
        # String representation of the possibility set, for debugging
        def to_s
          "[#{possibilities.join(', ')}]"
        end

        # @return [Object] most up-to-date dependency in the possibility set
        def latest_version
          possibilities.last
        end
      end

      # Details of the state to unwind to when a conflict occurs, and the cause of the unwind
      # @attr [Integer] state_index the index of the state to unwind to
      # @attr [Object] state_requirement the requirement of the state we're unwinding to
      # @attr [Array] requirement_tree for the requirement we're relaxing
      # @attr [Array] conflicting_requirements the requirements that combined to cause the conflict
      # @attr [Array] requirement_trees for the conflict
      # @attr [Array] requirements_unwound_to_instead array of unwind requirements that were chosen over this unwind
      UnwindDetails = Struct.new(
        :state_index,
        :state_requirement,
        :requirement_tree,
        :conflicting_requirements,
        :requirement_trees,
        :requirements_unwound_to_instead
      )

      class UnwindDetails
        include Comparable

        # We compare UnwindDetails when choosing which state to unwind to. If
        # two options have the same state_index we prefer the one most
        # removed from a requirement that caused the conflict. Both options
        # would unwind to the same state, but a `grandparent` option will
        # filter out fewer of its possibilities after doing so - where a state
        # is both a `parent` and a `grandparent` to requirements that have
        # caused a conflict this is the correct behaviour.
        # @param [UnwindDetail] other UnwindDetail to be compared
        # @return [Integer] integer specifying ordering
        def <=>(other)
          if state_index > other.state_index
            1
          elsif state_index == other.state_index
            reversed_requirement_tree_index <=> other.reversed_requirement_tree_index
          else
            -1
          end
        end

        # @return [Integer] index of state requirement in reversed requirement tree
        #    (the conflicting requirement itself will be at position 0)
        def reversed_requirement_tree_index
          @reversed_requirement_tree_index ||=
            if state_requirement
              requirement_tree.reverse.index(state_requirement)
            else
              999_999
            end
        end

        # @return [Boolean] where the requirement of the state we're unwinding
        #    to directly caused the conflict. Note: in this case, it is
        #    impossible for the state we're unwinding to to be a parent of
        #    any of the other conflicting requirements (or we would have
        #    circularity)
        def unwinding_to_primary_requirement?
          requirement_tree.last == state_requirement
        end

        # @return [Array] array of sub-dependencies to avoid when choosing a
        #    new possibility for the state we've unwound to. Only relevant for
        #    non-primary unwinds
        def sub_dependencies_to_avoid
          @requirements_to_avoid ||=
            requirement_trees.map do |tree|
              index = tree.index(state_requirement)
              tree[index + 1] if index
            end.compact
        end

        # @return [Array] array of all the requirements that led to the need for
        #    this unwind
        def all_requirements
          @all_requirements ||= requirement_trees.flatten(1)
        end
      end

      # @return [SpecificationProvider] the provider that knows about
      #   dependencies, requirements, specifications, versions, etc.
      attr_reader :specification_provider

      # @return [UI] the UI that knows how to communicate feedback about the
      #   resolution process back to the user
      attr_reader :resolver_ui

      # @return [DependencyGraph] the base dependency graph to which
      #   dependencies should be 'locked'
      attr_reader :base

      # @return [Array] the dependencies that were explicitly required
      attr_reader :original_requested

      # Initializes a new resolution.
      # @param [SpecificationProvider] specification_provider
      #   see {#specification_provider}
      # @param [UI] resolver_ui see {#resolver_ui}
      # @param [Array] requested see {#original_requested}
      # @param [DependencyGraph] base see {#base}
      def initialize(specification_provider, resolver_ui, requested, base)
        @specification_provider = specification_provider
        @resolver_ui = resolver_ui
        @original_requested = requested
        @base = base
        @states = []
        @iteration_counter = 0
        @parents_of = Hash.new { |h, k| h[k] = [] }
      end

      # Resolves the {#original_requested} dependencies into a full dependency
      #   graph
      # @raise [ResolverError] if successful resolution is impossible
      # @return [DependencyGraph] the dependency graph of successfully resolved
      #   dependencies
      def resolve
        start_resolution

        while state
          break if !state.requirement && state.requirements.empty?
          indicate_progress
          if state.respond_to?(:pop_possibility_state) # DependencyState
            debug(depth) { "Creating possibility state for #{requirement} (#{possibilities.count} remaining)" }
            state.pop_possibility_state.tap do |s|
              if s
                states.push(s)
                activated.tag(s)
              end
            end
          end
          process_topmost_state
        end

        resolve_activated_specs
      ensure
        end_resolution
      end

      # @return [Integer] the number of resolver iterations in between calls to
      #   {#resolver_ui}'s {UI#indicate_progress} method
      attr_accessor :iteration_rate
      private :iteration_rate

      # @return [Time] the time at which resolution began
      attr_accessor :started_at
      private :started_at

      # @return [Array<ResolutionState>] the stack of states for the resolution
      attr_accessor :states
      private :states

      private

      # Sets up the resolution process
      # @return [void]
      def start_resolution
        @started_at = Time.now

        push_initial_state

        debug { "Starting resolution (#{@started_at})\nUser-requested dependencies: #{original_requested}" }
        resolver_ui.before_resolution
      end

      def resolve_activated_specs
        activated.vertices.each do |_, vertex|
          next unless vertex.payload

          latest_version = vertex.payload.possibilities.reverse_each.find do |possibility|
            vertex.requirements.all? { |req| requirement_satisfied_by?(req, activated, possibility) }
          end

          activated.set_payload(vertex.name, latest_version)
        end
        activated.freeze
      end

      # Ends the resolution process
      # @return [void]
      def end_resolution
        resolver_ui.after_resolution
        debug do
          "Finished resolution (#{@iteration_counter} steps) " \
          "(Took #{(ended_at = Time.now) - @started_at} seconds) (#{ended_at})"
        end
        debug { 'Unactivated: ' + Hash[activated.vertices.reject { |_n, v| v.payload }].keys.join(', ') } if state
        debug { 'Activated: ' + Hash[activated.vertices.select { |_n, v| v.payload }].keys.join(', ') } if state
      end

      require_relative 'state'
      require_relative 'modules/specification_provider'

      require_relative 'delegates/resolution_state'
      require_relative 'delegates/specification_provider'

      include Gem::Resolver::Molinillo::Delegates::ResolutionState
      include Gem::Resolver::Molinillo::Delegates::SpecificationProvider

      # Processes the topmost available {RequirementState} on the stack
      # @return [void]
      def process_topmost_state
        if possibility
          attempt_to_activate
        else
          create_conflict
          unwind_for_conflict
        end
      rescue CircularDependencyError => underlying_error
        create_conflict(underlying_error)
        unwind_for_conflict
      end

      # @return [Object] the current possibility that the resolution is trying
      #   to activate
      def possibility
        possibilities.last
      end

      # @return [RequirementState] the current state the resolution is
      #   operating upon
      def state
        states.last
      end

      # Creates and pushes the initial state for the resolution, based upon the
      # {#requested} dependencies
      # @return [void]
      def push_initial_state
        graph = DependencyGraph.new.tap do |dg|
          original_requested.each do |requested|
            vertex = dg.add_vertex(name_for(requested), nil, true)
            vertex.explicit_requirements << requested
          end
          dg.tag(:initial_state)
        end

        push_state_for_requirements(original_requested, true, graph)
      end

      # Unwinds the states stack because a conflict has been encountered
      # @return [void]
      def unwind_for_conflict
        details_for_unwind = build_details_for_unwind
        unwind_options = unused_unwind_options
        debug(depth) { "Unwinding for conflict: #{requirement} to #{details_for_unwind.state_index / 2}" }
        conflicts.tap do |c|
          sliced_states = states.slice!((details_for_unwind.state_index + 1)..-1)
          raise_error_unless_state(c)
          activated.rewind_to(sliced_states.first || :initial_state) if sliced_states
          state.conflicts = c
          state.unused_unwind_options = unwind_options
          filter_possibilities_after_unwind(details_for_unwind)
          index = states.size - 1
          @parents_of.each { |_, a| a.reject! { |i| i >= index } }
          state.unused_unwind_options.reject! { |uw| uw.state_index >= index }
        end
      end

      # Raises a VersionConflict error, or any underlying error, if there is no
      # current state
      # @return [void]
      def raise_error_unless_state(conflicts)
        return if state

        error = conflicts.values.map(&:underlying_error).compact.first
        raise error || VersionConflict.new(conflicts, specification_provider)
      end

      # @return [UnwindDetails] Details of the nearest index to which we could unwind
      def build_details_for_unwind
        # Get the possible unwinds for the current conflict
        current_conflict = conflicts[name]
        binding_requirements = binding_requirements_for_conflict(current_conflict)
        unwind_details = unwind_options_for_requirements(binding_requirements)

        last_detail_for_current_unwind = unwind_details.sort.last
        current_detail = last_detail_for_current_unwind

        # Look for past conflicts that could be unwound to affect the
        # requirement tree for the current conflict
        all_reqs = last_detail_for_current_unwind.all_requirements
        all_reqs_size = all_reqs.size
        relevant_unused_unwinds = unused_unwind_options.select do |alternative|
          diff_reqs = all_reqs - alternative.requirements_unwound_to_instead
          next if diff_reqs.size == all_reqs_size
          # Find the highest index unwind whilst looping through
          current_detail = alternative if alternative > current_detail
          alternative
        end

        # Add the current unwind options to the `unused_unwind_options` array.
        # The "used" option will be filtered out during `unwind_for_conflict`.
        state.unused_unwind_options += unwind_details.reject { |detail| detail.state_index == -1 }

        # Update the requirements_unwound_to_instead on any relevant unused unwinds
        relevant_unused_unwinds.each do |d|
          (d.requirements_unwound_to_instead << current_detail.state_requirement).uniq!
        end
        unwind_details.each do |d|
          (d.requirements_unwound_to_instead << current_detail.state_requirement).uniq!
        end

        current_detail
      end

      # @param [Array<Object>] binding_requirements array of requirements that combine to create a conflict
      # @return [Array<UnwindDetails>] array of UnwindDetails that have a chance
      #    of resolving the passed requirements
      def unwind_options_for_requirements(binding_requirements)
        unwind_details = []

        trees = []
        binding_requirements.reverse_each do |r|
          partial_tree = [r]
          trees << partial_tree
          unwind_details << UnwindDetails.new(-1, nil, partial_tree, binding_requirements, trees, [])

          # If this requirement has alternative possibilities, check if any would
          # satisfy the other requirements that created this conflict
          requirement_state = find_state_for(r)
          if conflict_fixing_possibilities?(requirement_state, binding_requirements)
            unwind_details << UnwindDetails.new(
              states.index(requirement_state),
              r,
              partial_tree,
              binding_requirements,
              trees,
              []
            )
          end

          # Next, look at the parent of this requirement, and check if the requirement
          # could have been avoided if an alternative PossibilitySet had been chosen
          parent_r = parent_of(r)
          next if parent_r.nil?
          partial_tree.unshift(parent_r)
          requirement_state = find_state_for(parent_r)
          if requirement_state.possibilities.any? { |set| !set.dependencies.include?(r) }
            unwind_details << UnwindDetails.new(
              states.index(requirement_state),
              parent_r,
              partial_tree,
              binding_requirements,
              trees,
              []
            )
          end

          # Finally, look at the grandparent and up of this requirement, looking
          # for any possibilities that wouldn't create their parent requirement
          grandparent_r = parent_of(parent_r)
          until grandparent_r.nil?
            partial_tree.unshift(grandparent_r)
            requirement_state = find_state_for(grandparent_r)
            if requirement_state.possibilities.any? { |set| !set.dependencies.include?(parent_r) }
              unwind_details << UnwindDetails.new(
                states.index(requirement_state),
                grandparent_r,
                partial_tree,
                binding_requirements,
                trees,
                []
              )
            end
            parent_r = grandparent_r
            grandparent_r = parent_of(parent_r)
          end
        end

        unwind_details
      end

      # @param [DependencyState] state
      # @param [Array] binding_requirements array of requirements
      # @return [Boolean] whether or not the given state has any possibilities
      #    that could satisfy the given requirements
      def conflict_fixing_possibilities?(state, binding_requirements)
        return false unless state

        state.possibilities.any? do |possibility_set|
          possibility_set.possibilities.any? do |poss|
            possibility_satisfies_requirements?(poss, binding_requirements)
          end
        end
      end

      # Filter's a state's possibilities to remove any that would not fix the
      # conflict we've just rewound from
      # @param [UnwindDetails] unwind_details details of the conflict just
      #   unwound from
      # @return [void]
      def filter_possibilities_after_unwind(unwind_details)
        return unless state && !state.possibilities.empty?

        if unwind_details.unwinding_to_primary_requirement?
          filter_possibilities_for_primary_unwind(unwind_details)
        else
          filter_possibilities_for_parent_unwind(unwind_details)
        end
      end

      # Filter's a state's possibilities to remove any that would not satisfy
      # the requirements in the conflict we've just rewound from
      # @param [UnwindDetails] unwind_details details of the conflict just unwound from
      # @return [void]
      def filter_possibilities_for_primary_unwind(unwind_details)
        unwinds_to_state = unused_unwind_options.select { |uw| uw.state_index == unwind_details.state_index }
        unwinds_to_state << unwind_details
        unwind_requirement_sets = unwinds_to_state.map(&:conflicting_requirements)

        state.possibilities.reject! do |possibility_set|
          possibility_set.possibilities.none? do |poss|
            unwind_requirement_sets.any? do |requirements|
              possibility_satisfies_requirements?(poss, requirements)
            end
          end
        end
      end

      # @param [Object] possibility a single possibility
      # @param [Array] requirements an array of requirements
      # @return [Boolean] whether the possibility satisfies all of the
      #    given requirements
      def possibility_satisfies_requirements?(possibility, requirements)
        name = name_for(possibility)

        activated.tag(:swap)
        activated.set_payload(name, possibility) if activated.vertex_named(name)
        satisfied = requirements.all? { |r| requirement_satisfied_by?(r, activated, possibility) }
        activated.rewind_to(:swap)

        satisfied
      end

      # Filter's a state's possibilities to remove any that would (eventually)
      # create a requirement in the conflict we've just rewound from
      # @param [UnwindDetails] unwind_details details of the conflict just unwound from
      # @return [void]
      def filter_possibilities_for_parent_unwind(unwind_details)
        unwinds_to_state = unused_unwind_options.select { |uw| uw.state_index == unwind_details.state_index }
        unwinds_to_state << unwind_details

        primary_unwinds = unwinds_to_state.select(&:unwinding_to_primary_requirement?).uniq
        parent_unwinds = unwinds_to_state.uniq - primary_unwinds

        allowed_possibility_sets = primary_unwinds.flat_map do |unwind|
          states[unwind.state_index].possibilities.select do |possibility_set|
            possibility_set.possibilities.any? do |poss|
              possibility_satisfies_requirements?(poss, unwind.conflicting_requirements)
            end
          end
        end

        requirements_to_avoid = parent_unwinds.flat_map(&:sub_dependencies_to_avoid)

        state.possibilities.reject! do |possibility_set|
          !allowed_possibility_sets.include?(possibility_set) &&
            (requirements_to_avoid - possibility_set.dependencies).empty?
        end
      end

      # @param [Conflict] conflict
      # @return [Array] minimal array of requirements that would cause the passed
      #    conflict to occur.
      def binding_requirements_for_conflict(conflict)
        return [conflict.requirement] if conflict.possibility.nil?

        possible_binding_requirements = conflict.requirements.values.flatten(1).uniq

        # When there's a `CircularDependency` error the conflicting requirement
        # (the one causing the circular) won't be `conflict.requirement`
        # (which won't be for the right state, because we won't have created it,
        # because it's circular).
        # We need to make sure we have that requirement in the conflict's list,
        # otherwise we won't be able to unwind properly, so we just return all
        # the requirements for the conflict.
        return possible_binding_requirements if conflict.underlying_error

        possibilities = search_for(conflict.requirement)

        # If all the requirements together don't filter out all possibilities,
        # then the only two requirements we need to consider are the initial one
        # (where the dependency's version was first chosen) and the last
        if binding_requirement_in_set?(nil, possible_binding_requirements, possibilities)
          return [conflict.requirement, requirement_for_existing_name(name_for(conflict.requirement))].compact
        end

        # Loop through the possible binding requirements, removing each one
        # that doesn't bind. Use a `reverse_each` as we want the earliest set of
        # binding requirements, and don't use `reject!` as we wish to refine the
        # array *on each iteration*.
        binding_requirements = possible_binding_requirements.dup
        possible_binding_requirements.reverse_each do |req|
          next if req == conflict.requirement
          unless binding_requirement_in_set?(req, binding_requirements, possibilities)
            binding_requirements -= [req]
          end
        end

        binding_requirements
      end

      # @param [Object] requirement we wish to check
      # @param [Array] possible_binding_requirements array of requirements
      # @param [Array] possibilities array of possibilities the requirements will be used to filter
      # @return [Boolean] whether or not the given requirement is required to filter
      #    out all elements of the array of possibilities.
      def binding_requirement_in_set?(requirement, possible_binding_requirements, possibilities)
        possibilities.any? do |poss|
          possibility_satisfies_requirements?(poss, possible_binding_requirements - [requirement])
        end
      end

      # @param [Object] requirement
      # @return [Object] the requirement that led to `requirement` being added
      #   to the list of requirements.
      def parent_of(requirement)
        return unless requirement
        return unless index = @parents_of[requirement].last
        return unless parent_state = @states[index]
        parent_state.requirement
      end

      # @param [String] name
      # @return [Object] the requirement that led to a version of a possibility
      #   with the given name being activated.
      def requirement_for_existing_name(name)
        return nil unless vertex = activated.vertex_named(name)
        return nil unless vertex.payload
        states.find { |s| s.name == name }.requirement
      end

      # @param [Object] requirement
      # @return [ResolutionState] the state whose `requirement` is the given
      #   `requirement`.
      def find_state_for(requirement)
        return nil unless requirement
        states.find { |i| requirement == i.requirement }
      end

      # @param [Object] underlying_error
      # @return [Conflict] a {Conflict} that reflects the failure to activate
      #   the {#possibility} in conjunction with the current {#state}
      def create_conflict(underlying_error = nil)
        vertex = activated.vertex_named(name)
        locked_requirement = locked_requirement_named(name)

        requirements = {}
        unless vertex.explicit_requirements.empty?
          requirements[name_for_explicit_dependency_source] = vertex.explicit_requirements
        end
        requirements[name_for_locking_dependency_source] = [locked_requirement] if locked_requirement
        vertex.incoming_edges.each do |edge|
          (requirements[edge.origin.payload.latest_version] ||= []).unshift(edge.requirement)
        end

        activated_by_name = {}
        activated.each { |v| activated_by_name[v.name] = v.payload.latest_version if v.payload }
        conflicts[name] = Conflict.new(
          requirement,
          requirements,
          vertex.payload && vertex.payload.latest_version,
          possibility,
          locked_requirement,
          requirement_trees,
          activated_by_name,
          underlying_error
        )
      end

      # @return [Array<Array<Object>>] The different requirement
      #   trees that led to every requirement for the current spec.
      def requirement_trees
        vertex = activated.vertex_named(name)
        vertex.requirements.map { |r| requirement_tree_for(r) }
      end

      # @param [Object] requirement
      # @return [Array<Object>] the list of requirements that led to
      #   `requirement` being required.
      def requirement_tree_for(requirement)
        tree = []
        while requirement
          tree.unshift(requirement)
          requirement = parent_of(requirement)
        end
        tree
      end

      # Indicates progress roughly once every second
      # @return [void]
      def indicate_progress
        @iteration_counter += 1
        @progress_rate ||= resolver_ui.progress_rate
        if iteration_rate.nil?
          if Time.now - started_at >= @progress_rate
            self.iteration_rate = @iteration_counter
          end
        end

        if iteration_rate && (@iteration_counter % iteration_rate) == 0
          resolver_ui.indicate_progress
        end
      end

      # Calls the {#resolver_ui}'s {UI#debug} method
      # @param [Integer] depth the depth of the {#states} stack
      # @param [Proc] block a block that yields a {#to_s}
      # @return [void]
      def debug(depth = 0, &block)
        resolver_ui.debug(depth, &block)
      end

      # Attempts to activate the current {#possibility}
      # @return [void]
      def attempt_to_activate
        debug(depth) { 'Attempting to activate ' + possibility.to_s }
        existing_vertex = activated.vertex_named(name)
        if existing_vertex.payload
          debug(depth) { "Found existing spec (#{existing_vertex.payload})" }
          attempt_to_filter_existing_spec(existing_vertex)
        else
          latest = possibility.latest_version
          possibility.possibilities.select! do |possibility|
            requirement_satisfied_by?(requirement, activated, possibility)
          end
          if possibility.latest_version.nil?
            # ensure there's a possibility for better error messages
            possibility.possibilities << latest if latest
            create_conflict
            unwind_for_conflict
          else
            activate_new_spec
          end
        end
      end

      # Attempts to update the existing vertex's `PossibilitySet` with a filtered version
      # @return [void]
      def attempt_to_filter_existing_spec(vertex)
        filtered_set = filtered_possibility_set(vertex)
        if !filtered_set.possibilities.empty?
          activated.set_payload(name, filtered_set)
          new_requirements = requirements.dup
          push_state_for_requirements(new_requirements, false)
        else
          create_conflict
          debug(depth) { "Unsatisfied by existing spec (#{vertex.payload})" }
          unwind_for_conflict
        end
      end

      # Generates a filtered version of the existing vertex's `PossibilitySet` using the
      # current state's `requirement`
      # @param [Object] vertex existing vertex
      # @return [PossibilitySet] filtered possibility set
      def filtered_possibility_set(vertex)
        PossibilitySet.new(vertex.payload.dependencies, vertex.payload.possibilities & possibility.possibilities)
      end

      # @param [String] requirement_name the spec name to search for
      # @return [Object] the locked spec named `requirement_name`, if one
      #   is found on {#base}
      def locked_requirement_named(requirement_name)
        vertex = base.vertex_named(requirement_name)
        vertex && vertex.payload
      end

      # Add the current {#possibility} to the dependency graph of the current
      # {#state}
      # @return [void]
      def activate_new_spec
        conflicts.delete(name)
        debug(depth) { "Activated #{name} at #{possibility}" }
        activated.set_payload(name, possibility)
        require_nested_dependencies_for(possibility)
      end

      # Requires the dependencies that the recently activated spec has
      # @param [Object] possibility_set the PossibilitySet that has just been
      #   activated
      # @return [void]
      def require_nested_dependencies_for(possibility_set)
        nested_dependencies = dependencies_for(possibility_set.latest_version)
        debug(depth) { "Requiring nested dependencies (#{nested_dependencies.join(', ')})" }
        nested_dependencies.each do |d|
          activated.add_child_vertex(name_for(d), nil, [name_for(possibility_set.latest_version)], d)
          parent_index = states.size - 1
          parents = @parents_of[d]
          parents << parent_index if parents.empty?
        end

        push_state_for_requirements(requirements + nested_dependencies, !nested_dependencies.empty?)
      end

      # Pushes a new {DependencyState} that encapsulates both existing and new
      # requirements
      # @param [Array] new_requirements
      # @param [Boolean] requires_sort
      # @param [Object] new_activated
      # @return [void]
      def push_state_for_requirements(new_requirements, requires_sort = true, new_activated = activated)
        new_requirements = sort_dependencies(new_requirements.uniq, new_activated, conflicts) if requires_sort
        new_requirement = nil
        loop do
          new_requirement = new_requirements.shift
          break if new_requirement.nil? || states.none? { |s| s.requirement == new_requirement }
        end
        new_name = new_requirement ? name_for(new_requirement) : ''.freeze
        possibilities = possibilities_for_requirement(new_requirement)
        handle_missing_or_push_dependency_state DependencyState.new(
          new_name, new_requirements, new_activated,
          new_requirement, possibilities, depth, conflicts.dup, unused_unwind_options.dup
        )
      end

      # Checks a proposed requirement with any existing locked requirement
      # before generating an array of possibilities for it.
      # @param [Object] requirement the proposed requirement
      # @param [Object] activated
      # @return [Array] possibilities
      def possibilities_for_requirement(requirement, activated = self.activated)
        return [] unless requirement
        if locked_requirement_named(name_for(requirement))
          return locked_requirement_possibility_set(requirement, activated)
        end

        group_possibilities(search_for(requirement))
      end

      # @param [Object] requirement the proposed requirement
      # @param [Object] activated
      # @return [Array] possibility set containing only the locked requirement, if any
      def locked_requirement_possibility_set(requirement, activated = self.activated)
        all_possibilities = search_for(requirement)
        locked_requirement = locked_requirement_named(name_for(requirement))

        # Longwinded way to build a possibilities array with either the locked
        # requirement or nothing in it. Required, since the API for
        # locked_requirement isn't guaranteed.
        locked_possibilities = all_possibilities.select do |possibility|
          requirement_satisfied_by?(locked_requirement, activated, possibility)
        end

        group_possibilities(locked_possibilities)
      end

      # Build an array of PossibilitySets, with each element representing a group of
      # dependency versions that all have the same sub-dependency version constraints
      # and are contiguous.
      # @param [Array] possibilities an array of possibilities
      # @return [Array<PossibilitySet>] an array of possibility sets
      def group_possibilities(possibilities)
        possibility_sets = []
        current_possibility_set = nil

        possibilities.reverse_each do |possibility|
          dependencies = dependencies_for(possibility)
          if current_possibility_set && dependencies_equal?(current_possibility_set.dependencies, dependencies)
            current_possibility_set.possibilities.unshift(possibility)
          else
            possibility_sets.unshift(PossibilitySet.new(dependencies, [possibility]))
            current_possibility_set = possibility_sets.first
          end
        end

        possibility_sets
      end

      # Pushes a new {DependencyState}.
      # If the {#specification_provider} says to
      # {SpecificationProvider#allow_missing?} that particular requirement, and
      # there are no possibilities for that requirement, then `state` is not
      # pushed, and the vertex in {#activated} is removed, and we continue
      # resolving the remaining requirements.
      # @param [DependencyState] state
      # @return [void]
      def handle_missing_or_push_dependency_state(state)
        if state.requirement && state.possibilities.empty? && allow_missing?(state.requirement)
          state.activated.detach_vertex_named(state.name)
          push_state_for_requirements(state.requirements.dup, false, state.activated)
        else
          states.push(state).tap { activated.tag(state) }
        end
      end
    end
  end
end
# frozen_string_literal: true

require_relative 'action'
module Gem::Resolver::Molinillo
  class DependencyGraph
    # @!visibility private
    # (see DependencyGraph#add_edge_no_circular)
    class AddEdgeNoCircular < Action
      # @!group Action

      # (see Action.action_name)
      def self.action_name
        :add_vertex
      end

      # (see Action#up)
      def up(graph)
        edge = make_edge(graph)
        edge.origin.outgoing_edges << edge
        edge.destination.incoming_edges << edge
        edge
      end

      # (see Action#down)
      def down(graph)
        edge = make_edge(graph)
        delete_first(edge.origin.outgoing_edges, edge)
        delete_first(edge.destination.incoming_edges, edge)
      end

      # @!group AddEdgeNoCircular

      # @return [String] the name of the origin of the edge
      attr_reader :origin

      # @return [String] the name of the destination of the edge
      attr_reader :destination

      # @return [Object] the requirement that the edge represents
      attr_reader :requirement

      # @param  [DependencyGraph] graph the graph to find vertices from
      # @return [Edge] The edge this action adds
      def make_edge(graph)
        Edge.new(graph.vertex_named(origin), graph.vertex_named(destination), requirement)
      end

      # Initialize an action to add an edge to a dependency graph
      # @param [String] origin the name of the origin of the edge
      # @param [String] destination the name of the destination of the edge
      # @param [Object] requirement the requirement that the edge represents
      def initialize(origin, destination, requirement)
        @origin = origin
        @destination = destination
        @requirement = requirement
      end

      private

      def delete_first(array, item)
        return unless index = array.index(item)
        array.delete_at(index)
      end
    end
  end
end
# frozen_string_literal: true

require_relative 'action'
module Gem::Resolver::Molinillo
  class DependencyGraph
    # @!visibility private
    # @see DependencyGraph#set_payload
    class SetPayload < Action # :nodoc:
      # @!group Action

      # (see Action.action_name)
      def self.action_name
        :set_payload
      end

      # (see Action#up)
      def up(graph)
        vertex = graph.vertex_named(name)
        @old_payload = vertex.payload
        vertex.payload = payload
      end

      # (see Action#down)
      def down(graph)
        graph.vertex_named(name).payload = @old_payload
      end

      # @!group SetPayload

      # @return [String] the name of the vertex
      attr_reader :name

      # @return [Object] the payload for the vertex
      attr_reader :payload

      # Initialize an action to add set the payload for a vertex in a dependency
      # graph
      # @param [String] name the name of the vertex
      # @param [Object] payload the payload for the vertex
      def initialize(name, payload)
        @name = name
        @payload = payload
      end
    end
  end
end
# frozen_string_literal: true

module Gem::Resolver::Molinillo
  class DependencyGraph
    # An action that modifies a {DependencyGraph} that is reversible.
    # @abstract
    class Action
      # rubocop:disable Lint/UnusedMethodArgument

      # @return [Symbol] The name of the action.
      def self.action_name
        raise 'Abstract'
      end

      # Performs the action on the given graph.
      # @param  [DependencyGraph] graph the graph to perform the action on.
      # @return [Void]
      def up(graph)
        raise 'Abstract'
      end

      # Reverses the action on the given graph.
      # @param  [DependencyGraph] graph the graph to reverse the action on.
      # @return [Void]
      def down(graph)
        raise 'Abstract'
      end

      # @return [Action,Nil] The previous action
      attr_accessor :previous

      # @return [Action,Nil] The next action
      attr_accessor :next
    end
  end
end
# frozen_string_literal: true

require_relative 'action'
module Gem::Resolver::Molinillo
  class DependencyGraph
    # @!visibility private
    # (see DependencyGraph#delete_edge)
    class DeleteEdge < Action
      # @!group Action

      # (see Action.action_name)
      def self.action_name
        :delete_edge
      end

      # (see Action#up)
      def up(graph)
        edge = make_edge(graph)
        edge.origin.outgoing_edges.delete(edge)
        edge.destination.incoming_edges.delete(edge)
      end

      # (see Action#down)
      def down(graph)
        edge = make_edge(graph)
        edge.origin.outgoing_edges << edge
        edge.destination.incoming_edges << edge
        edge
      end

      # @!group DeleteEdge

      # @return [String] the name of the origin of the edge
      attr_reader :origin_name

      # @return [String] the name of the destination of the edge
      attr_reader :destination_name

      # @return [Object] the requirement that the edge represents
      attr_reader :requirement

      # @param  [DependencyGraph] graph the graph to find vertices from
      # @return [Edge] The edge this action adds
      def make_edge(graph)
        Edge.new(
          graph.vertex_named(origin_name),
          graph.vertex_named(destination_name),
          requirement
        )
      end

      # Initialize an action to add an edge to a dependency graph
      # @param [String] origin_name the name of the origin of the edge
      # @param [String] destination_name the name of the destination of the edge
      # @param [Object] requirement the requirement that the edge represents
      def initialize(origin_name, destination_name, requirement)
        @origin_name = origin_name
        @destination_name = destination_name
        @requirement = requirement
      end
    end
  end
end
# frozen_string_literal: true

require_relative 'action'
module Gem::Resolver::Molinillo
  class DependencyGraph
    # @!visibility private
    # @see DependencyGraph#tag
    class Tag < Action
      # @!group Action

      # (see Action.action_name)
      def self.action_name
        :tag
      end

      # (see Action#up)
      def up(graph)
      end

      # (see Action#down)
      def down(graph)
      end

      # @!group Tag

      # @return [Object] An opaque tag
      attr_reader :tag

      # Initialize an action to tag a state of a dependency graph
      # @param [Object] tag an opaque tag
      def initialize(tag)
        @tag = tag
      end
    end
  end
end
# frozen_string_literal: true

require_relative 'action'
module Gem::Resolver::Molinillo
  class DependencyGraph
    # @!visibility private
    # @see DependencyGraph#detach_vertex_named
    class DetachVertexNamed < Action
      # @!group Action

      # (see Action#name)
      def self.action_name
        :add_vertex
      end

      # (see Action#up)
      def up(graph)
        return [] unless @vertex = graph.vertices.delete(name)

        removed_vertices = [@vertex]
        @vertex.outgoing_edges.each do |e|
          v = e.destination
          v.incoming_edges.delete(e)
          if !v.root? && v.incoming_edges.empty?
            removed_vertices.concat graph.detach_vertex_named(v.name)
          end
        end

        @vertex.incoming_edges.each do |e|
          v = e.origin
          v.outgoing_edges.delete(e)
        end

        removed_vertices
      end

      # (see Action#down)
      def down(graph)
        return unless @vertex
        graph.vertices[@vertex.name] = @vertex
        @vertex.outgoing_edges.each do |e|
          e.destination.incoming_edges << e
        end
        @vertex.incoming_edges.each do |e|
          e.origin.outgoing_edges << e
        end
      end

      # @!group DetachVertexNamed

      # @return [String] the name of the vertex to detach
      attr_reader :name

      # Initialize an action to detach a vertex from a dependency graph
      # @param [String] name the name of the vertex to detach
      def initialize(name)
        @name = name
      end
    end
  end
end
# frozen_string_literal: true

require_relative 'action'
module Gem::Resolver::Molinillo
  class DependencyGraph
    # @!visibility private
    # (see DependencyGraph#add_vertex)
    class AddVertex < Action # :nodoc:
      # @!group Action

      # (see Action.action_name)
      def self.action_name
        :add_vertex
      end

      # (see Action#up)
      def up(graph)
        if existing = graph.vertices[name]
          @existing_payload = existing.payload
          @existing_root = existing.root
        end
        vertex = existing || Vertex.new(name, payload)
        graph.vertices[vertex.name] = vertex
        vertex.payload ||= payload
        vertex.root ||= root
        vertex
      end

      # (see Action#down)
      def down(graph)
        if defined?(@existing_payload)
          vertex = graph.vertices[name]
          vertex.payload = @existing_payload
          vertex.root = @existing_root
        else
          graph.vertices.delete(name)
        end
      end

      # @!group AddVertex

      # @return [String] the name of the vertex
      attr_reader :name

      # @return [Object] the payload for the vertex
      attr_reader :payload

      # @return [Boolean] whether the vertex is root or not
      attr_reader :root

      # Initialize an action to add a vertex to a dependency graph
      # @param [String] name the name of the vertex
      # @param [Object] payload the payload for the vertex
      # @param [Boolean] root whether the vertex is root or not
      def initialize(name, payload, root)
        @name = name
        @payload = payload
        @root = root
      end
    end
  end
end
# frozen_string_literal: true

require_relative 'add_edge_no_circular'
require_relative 'add_vertex'
require_relative 'delete_edge'
require_relative 'detach_vertex_named'
require_relative 'set_payload'
require_relative 'tag'

module Gem::Resolver::Molinillo
  class DependencyGraph
    # A log for dependency graph actions
    class Log
      # Initializes an empty log
      def initialize
        @current_action = @first_action = nil
      end

      # @!macro [new] action
      #   {include:DependencyGraph#$0}
      #   @param [Graph] graph the graph to perform the action on
      #   @param (see DependencyGraph#$0)
      #   @return (see DependencyGraph#$0)

      # @macro action
      def tag(graph, tag)
        push_action(graph, Tag.new(tag))
      end

      # @macro action
      def add_vertex(graph, name, payload, root)
        push_action(graph, AddVertex.new(name, payload, root))
      end

      # @macro action
      def detach_vertex_named(graph, name)
        push_action(graph, DetachVertexNamed.new(name))
      end

      # @macro action
      def add_edge_no_circular(graph, origin, destination, requirement)
        push_action(graph, AddEdgeNoCircular.new(origin, destination, requirement))
      end

      # {include:DependencyGraph#delete_edge}
      # @param [Graph] graph the graph to perform the action on
      # @param [String] origin_name
      # @param [String] destination_name
      # @param [Object] requirement
      # @return (see DependencyGraph#delete_edge)
      def delete_edge(graph, origin_name, destination_name, requirement)
        push_action(graph, DeleteEdge.new(origin_name, destination_name, requirement))
      end

      # @macro action
      def set_payload(graph, name, payload)
        push_action(graph, SetPayload.new(name, payload))
      end

      # Pops the most recent action from the log and undoes the action
      # @param [DependencyGraph] graph
      # @return [Action] the action that was popped off the log
      def pop!(graph)
        return unless action = @current_action
        unless @current_action = action.previous
          @first_action = nil
        end
        action.down(graph)
        action
      end

      extend Enumerable

      # @!visibility private
      # Enumerates each action in the log
      # @yield [Action]
      def each
        return enum_for unless block_given?
        action = @first_action
        loop do
          break unless action
          yield action
          action = action.next
        end
        self
      end

      # @!visibility private
      # Enumerates each action in the log in reverse order
      # @yield [Action]
      def reverse_each
        return enum_for(:reverse_each) unless block_given?
        action = @current_action
        loop do
          break unless action
          yield action
          action = action.previous
        end
        self
      end

      # @macro action
      def rewind_to(graph, tag)
        loop do
          action = pop!(graph)
          raise "No tag #{tag.inspect} found" unless action
          break if action.class.action_name == :tag && action.tag == tag
        end
      end

      private

      # Adds the given action to the log, running the action
      # @param [DependencyGraph] graph
      # @param [Action] action
      # @return The value returned by `action.up`
      def push_action(graph, action)
        action.previous = @current_action
        @current_action.next = action if @current_action
        @current_action = action
        @first_action ||= action
        action.up(graph)
      end
    end
  end
end
# frozen_string_literal: true

module Gem::Resolver::Molinillo
  class DependencyGraph
    # A vertex in a {DependencyGraph} that encapsulates a {#name} and a
    # {#payload}
    class Vertex
      # @return [String] the name of the vertex
      attr_accessor :name

      # @return [Object] the payload the vertex holds
      attr_accessor :payload

      # @return [Array<Object>] the explicit requirements that required
      #   this vertex
      attr_reader :explicit_requirements

      # @return [Boolean] whether the vertex is considered a root vertex
      attr_accessor :root
      alias root? root

      # Initializes a vertex with the given name and payload.
      # @param [String] name see {#name}
      # @param [Object] payload see {#payload}
      def initialize(name, payload)
        @name = name.frozen? ? name : name.dup.freeze
        @payload = payload
        @explicit_requirements = []
        @outgoing_edges = []
        @incoming_edges = []
      end

      # @return [Array<Object>] all of the requirements that required
      #   this vertex
      def requirements
        (incoming_edges.map(&:requirement) + explicit_requirements).uniq
      end

      # @return [Array<Edge>] the edges of {#graph} that have `self` as their
      #   {Edge#origin}
      attr_accessor :outgoing_edges

      # @return [Array<Edge>] the edges of {#graph} that have `self` as their
      #   {Edge#destination}
      attr_accessor :incoming_edges

      # @return [Array<Vertex>] the vertices of {#graph} that have an edge with
      #   `self` as their {Edge#destination}
      def predecessors
        incoming_edges.map(&:origin)
      end

      # @return [Set<Vertex>] the vertices of {#graph} where `self` is a
      #   {#descendent?}
      def recursive_predecessors
        _recursive_predecessors
      end

      # @param [Set<Vertex>] vertices the set to add the predecessors to
      # @return [Set<Vertex>] the vertices of {#graph} where `self` is a
      #   {#descendent?}
      def _recursive_predecessors(vertices = new_vertex_set)
        incoming_edges.each do |edge|
          vertex = edge.origin
          next unless vertices.add?(vertex)
          vertex._recursive_predecessors(vertices)
        end

        vertices
      end
      protected :_recursive_predecessors

      # @return [Array<Vertex>] the vertices of {#graph} that have an edge with
      #   `self` as their {Edge#origin}
      def successors
        outgoing_edges.map(&:destination)
      end

      # @return [Set<Vertex>] the vertices of {#graph} where `self` is an
      #   {#ancestor?}
      def recursive_successors
        _recursive_successors
      end

      # @param [Set<Vertex>] vertices the set to add the successors to
      # @return [Set<Vertex>] the vertices of {#graph} where `self` is an
      #   {#ancestor?}
      def _recursive_successors(vertices = new_vertex_set)
        outgoing_edges.each do |edge|
          vertex = edge.destination
          next unless vertices.add?(vertex)
          vertex._recursive_successors(vertices)
        end

        vertices
      end
      protected :_recursive_successors

      # @return [String] a string suitable for debugging
      def inspect
        "#{self.class}:#{name}(#{payload.inspect})"
      end

      # @return [Boolean] whether the two vertices are equal, determined
      #   by a recursive traversal of each {Vertex#successors}
      def ==(other)
        return true if equal?(other)
        shallow_eql?(other) &&
          successors.to_set == other.successors.to_set
      end

      # @param  [Vertex] other the other vertex to compare to
      # @return [Boolean] whether the two vertices are equal, determined
      #   solely by {#name} and {#payload} equality
      def shallow_eql?(other)
        return true if equal?(other)
        other &&
          name == other.name &&
          payload == other.payload
      end

      alias eql? ==

      # @return [Fixnum] a hash for the vertex based upon its {#name}
      def hash
        name.hash
      end

      # Is there a path from `self` to `other` following edges in the
      # dependency graph?
      # @return whether there is a path following edges within this {#graph}
      def path_to?(other)
        _path_to?(other)
      end

      alias descendent? path_to?

      # @param [Vertex] other the vertex to check if there's a path to
      # @param [Set<Vertex>] visited the vertices of {#graph} that have been visited
      # @return [Boolean] whether there is a path to `other` from `self`
      def _path_to?(other, visited = new_vertex_set)
        return false unless visited.add?(self)
        return true if equal?(other)
        successors.any? { |v| v._path_to?(other, visited) }
      end
      protected :_path_to?

      # Is there a path from `other` to `self` following edges in the
      # dependency graph?
      # @return whether there is a path following edges within this {#graph}
      def ancestor?(other)
        other.path_to?(self)
      end

      alias is_reachable_from? ancestor?

      def new_vertex_set
        require 'set'
        Set.new
      end
      private :new_vertex_set
    end
  end
end
# frozen_string_literal: true

require_relative 'dependency_graph'

module Gem::Resolver::Molinillo
  # This class encapsulates a dependency resolver.
  # The resolver is responsible for determining which set of dependencies to
  # activate, with feedback from the {#specification_provider}
  #
  #
  class Resolver
    require_relative 'resolution'

    # @return [SpecificationProvider] the specification provider used
    #   in the resolution process
    attr_reader :specification_provider

    # @return [UI] the UI module used to communicate back to the user
    #   during the resolution process
    attr_reader :resolver_ui

    # Initializes a new resolver.
    # @param  [SpecificationProvider] specification_provider
    #   see {#specification_provider}
    # @param  [UI] resolver_ui
    #   see {#resolver_ui}
    def initialize(specification_provider, resolver_ui)
      @specification_provider = specification_provider
      @resolver_ui = resolver_ui
    end

    # Resolves the requested dependencies into a {DependencyGraph},
    # locking to the base dependency graph (if specified)
    # @param [Array] requested an array of 'requested' dependencies that the
    #   {#specification_provider} can understand
    # @param [DependencyGraph,nil] base the base dependency graph to which
    #   dependencies should be 'locked'
    def resolve(requested, base = DependencyGraph.new)
      Resolution.new(specification_provider,
                     resolver_ui,
                     requested,
                     base).
        resolve
    end
  end
end
# frozen_string_literal: true

module Gem::Resolver::Molinillo
  # An error that occurred during the resolution process
  class ResolverError < StandardError; end

  # An error caused by searching for a dependency that is completely unknown,
  # i.e. has no versions available whatsoever.
  class NoSuchDependencyError < ResolverError
    # @return [Object] the dependency that could not be found
    attr_accessor :dependency

    # @return [Array<Object>] the specifications that depended upon {#dependency}
    attr_accessor :required_by

    # Initializes a new error with the given missing dependency.
    # @param [Object] dependency @see {#dependency}
    # @param [Array<Object>] required_by @see {#required_by}
    def initialize(dependency, required_by = [])
      @dependency = dependency
      @required_by = required_by.uniq
      super()
    end

    # The error message for the missing dependency, including the specifications
    # that had this dependency.
    def message
      sources = required_by.map { |r| "`#{r}`" }.join(' and ')
      message = "Unable to find a specification for `#{dependency}`"
      message += " depended upon by #{sources}" unless sources.empty?
      message
    end
  end

  # An error caused by attempting to fulfil a dependency that was circular
  #
  # @note This exception will be thrown if and only if a {Vertex} is added to a
  #   {DependencyGraph} that has a {DependencyGraph::Vertex#path_to?} an
  #   existing {DependencyGraph::Vertex}
  class CircularDependencyError < ResolverError
    # [Set<Object>] the dependencies responsible for causing the error
    attr_reader :dependencies

    # Initializes a new error with the given circular vertices.
    # @param [Array<DependencyGraph::Vertex>] vertices the vertices in the dependency
    #   that caused the error
    def initialize(vertices)
      super "There is a circular dependency between #{vertices.map(&:name).join(' and ')}"
      @dependencies = vertices.map { |vertex| vertex.payload.possibilities.last }.to_set
    end
  end

  # An error caused by conflicts in version
  class VersionConflict < ResolverError
    # @return [{String => Resolution::Conflict}] the conflicts that caused
    #   resolution to fail
    attr_reader :conflicts

    # @return [SpecificationProvider] the specification provider used during
    #   resolution
    attr_reader :specification_provider

    # Initializes a new error with the given version conflicts.
    # @param [{String => Resolution::Conflict}] conflicts see {#conflicts}
    # @param [SpecificationProvider] specification_provider see {#specification_provider}
    def initialize(conflicts, specification_provider)
      pairs = []
      conflicts.values.flat_map(&:requirements).each do |conflicting|
        conflicting.each do |source, conflict_requirements|
          conflict_requirements.each do |c|
            pairs << [c, source]
          end
        end
      end

      super "Unable to satisfy the following requirements:\n\n" \
        "#{pairs.map { |r, d| "- `#{r}` required by `#{d}`" }.join("\n")}"

      @conflicts = conflicts
      @specification_provider = specification_provider
    end

    require_relative 'delegates/specification_provider'
    include Delegates::SpecificationProvider

    # @return [String] An error message that includes requirement trees,
    #   which is much more detailed & customizable than the default message
    # @param [Hash] opts the options to create a message with.
    # @option opts [String] :solver_name The user-facing name of the solver
    # @option opts [String] :possibility_type The generic name of a possibility
    # @option opts [Proc] :reduce_trees A proc that reduced the list of requirement trees
    # @option opts [Proc] :printable_requirement A proc that pretty-prints requirements
    # @option opts [Proc] :additional_message_for_conflict A proc that appends additional
    #   messages for each conflict
    # @option opts [Proc] :version_for_spec A proc that returns the version number for a
    #   possibility
    def message_with_trees(opts = {})
      solver_name = opts.delete(:solver_name) { self.class.name.split('::').first }
      possibility_type = opts.delete(:possibility_type) { 'possibility named' }
      reduce_trees = opts.delete(:reduce_trees) { proc { |trees| trees.uniq.sort_by(&:to_s) } }
      printable_requirement = opts.delete(:printable_requirement) { proc { |req| req.to_s } }
      additional_message_for_conflict = opts.delete(:additional_message_for_conflict) { proc {} }
      version_for_spec = opts.delete(:version_for_spec) { proc(&:to_s) }
      incompatible_version_message_for_conflict = opts.delete(:incompatible_version_message_for_conflict) do
        proc do |name, _conflict|
          %(#{solver_name} could not find compatible versions for #{possibility_type} "#{name}":)
        end
      end

      conflicts.sort.reduce(''.dup) do |o, (name, conflict)|
        o << "\n" << incompatible_version_message_for_conflict.call(name, conflict) << "\n"
        if conflict.locked_requirement
          o << %(  In snapshot (#{name_for_locking_dependency_source}):\n)
          o << %(    #{printable_requirement.call(conflict.locked_requirement)}\n)
          o << %(\n)
        end
        o << %(  In #{name_for_explicit_dependency_source}:\n)
        trees = reduce_trees.call(conflict.requirement_trees)

        o << trees.map do |tree|
          t = ''.dup
          depth = 2
          tree.each do |req|
            t << '  ' * depth << printable_requirement.call(req)
            unless tree.last == req
              if spec = conflict.activated_by_name[name_for(req)]
                t << %( was resolved to #{version_for_spec.call(spec)}, which)
              end
              t << %( depends on)
            end
            t << %(\n)
            depth += 1
          end
          t
        end.join("\n")

        additional_message_for_conflict.call(o, name, conflict)

        o
      end.strip
    end
  end
end
# frozen_string_literal: true

module Gem::Resolver::Molinillo
  # @!visibility private
  module Delegates
    # Delegates all {Gem::Resolver::Molinillo::ResolutionState} methods to a `#state` property.
    module ResolutionState
      # (see Gem::Resolver::Molinillo::ResolutionState#name)
      def name
        current_state = state || Gem::Resolver::Molinillo::ResolutionState.empty
        current_state.name
      end

      # (see Gem::Resolver::Molinillo::ResolutionState#requirements)
      def requirements
        current_state = state || Gem::Resolver::Molinillo::ResolutionState.empty
        current_state.requirements
      end

      # (see Gem::Resolver::Molinillo::ResolutionState#activated)
      def activated
        current_state = state || Gem::Resolver::Molinillo::ResolutionState.empty
        current_state.activated
      end

      # (see Gem::Resolver::Molinillo::ResolutionState#requirement)
      def requirement
        current_state = state || Gem::Resolver::Molinillo::ResolutionState.empty
        current_state.requirement
      end

      # (see Gem::Resolver::Molinillo::ResolutionState#possibilities)
      def possibilities
        current_state = state || Gem::Resolver::Molinillo::ResolutionState.empty
        current_state.possibilities
      end

      # (see Gem::Resolver::Molinillo::ResolutionState#depth)
      def depth
        current_state = state || Gem::Resolver::Molinillo::ResolutionState.empty
        current_state.depth
      end

      # (see Gem::Resolver::Molinillo::ResolutionState#conflicts)
      def conflicts
        current_state = state || Gem::Resolver::Molinillo::ResolutionState.empty
        current_state.conflicts
      end

      # (see Gem::Resolver::Molinillo::ResolutionState#unused_unwind_options)
      def unused_unwind_options
        current_state = state || Gem::Resolver::Molinillo::ResolutionState.empty
        current_state.unused_unwind_options
      end
    end
  end
end
# frozen_string_literal: true

module Gem::Resolver::Molinillo
  module Delegates
    # Delegates all {Gem::Resolver::Molinillo::SpecificationProvider} methods to a
    # `#specification_provider` property.
    module SpecificationProvider
      # (see Gem::Resolver::Molinillo::SpecificationProvider#search_for)
      def search_for(dependency)
        with_no_such_dependency_error_handling do
          specification_provider.search_for(dependency)
        end
      end

      # (see Gem::Resolver::Molinillo::SpecificationProvider#dependencies_for)
      def dependencies_for(specification)
        with_no_such_dependency_error_handling do
          specification_provider.dependencies_for(specification)
        end
      end

      # (see Gem::Resolver::Molinillo::SpecificationProvider#requirement_satisfied_by?)
      def requirement_satisfied_by?(requirement, activated, spec)
        with_no_such_dependency_error_handling do
          specification_provider.requirement_satisfied_by?(requirement, activated, spec)
        end
      end

      # (see Gem::Resolver::Molinillo::SpecificationProvider#dependencies_equal?)
      def dependencies_equal?(dependencies, other_dependencies)
        with_no_such_dependency_error_handling do
          specification_provider.dependencies_equal?(dependencies, other_dependencies)
        end
      end

      # (see Gem::Resolver::Molinillo::SpecificationProvider#name_for)
      def name_for(dependency)
        with_no_such_dependency_error_handling do
          specification_provider.name_for(dependency)
        end
      end

      # (see Gem::Resolver::Molinillo::SpecificationProvider#name_for_explicit_dependency_source)
      def name_for_explicit_dependency_source
        with_no_such_dependency_error_handling do
          specification_provider.name_for_explicit_dependency_source
        end
      end

      # (see Gem::Resolver::Molinillo::SpecificationProvider#name_for_locking_dependency_source)
      def name_for_locking_dependency_source
        with_no_such_dependency_error_handling do
          specification_provider.name_for_locking_dependency_source
        end
      end

      # (see Gem::Resolver::Molinillo::SpecificationProvider#sort_dependencies)
      def sort_dependencies(dependencies, activated, conflicts)
        with_no_such_dependency_error_handling do
          specification_provider.sort_dependencies(dependencies, activated, conflicts)
        end
      end

      # (see Gem::Resolver::Molinillo::SpecificationProvider#allow_missing?)
      def allow_missing?(dependency)
        with_no_such_dependency_error_handling do
          specification_provider.allow_missing?(dependency)
        end
      end

      private

      # Ensures any raised {NoSuchDependencyError} has its
      # {NoSuchDependencyError#required_by} set.
      # @yield
      def with_no_such_dependency_error_handling
        yield
      rescue NoSuchDependencyError => error
        if state
          vertex = activated.vertex_named(name_for(error.dependency))
          error.required_by += vertex.incoming_edges.map { |e| e.origin.name }
          error.required_by << name_for_explicit_dependency_source unless vertex.explicit_requirements.empty?
        end
        raise
      end
    end
  end
end
# frozen_string_literal: true

module Gem::Resolver::Molinillo
  # The version of Gem::Resolver::Molinillo.
  VERSION = '0.7.0'.freeze
end
# frozen_string_literal: true

module Gem::Resolver::Molinillo
  # Conveys information about the resolution process to a user.
  module UI
    # The {IO} object that should be used to print output. `STDOUT`, by default.
    #
    # @return [IO]
    def output
      STDOUT
    end

    # Called roughly every {#progress_rate}, this method should convey progress
    # to the user.
    #
    # @return [void]
    def indicate_progress
      output.print '.' unless debug?
    end

    # How often progress should be conveyed to the user via
    # {#indicate_progress}, in seconds. A third of a second, by default.
    #
    # @return [Float]
    def progress_rate
      0.33
    end

    # Called before resolution begins.
    #
    # @return [void]
    def before_resolution
      output.print 'Resolving dependencies...'
    end

    # Called after resolution ends (either successfully or with an error).
    # By default, prints a newline.
    #
    # @return [void]
    def after_resolution
      output.puts
    end

    # Conveys debug information to the user.
    #
    # @param [Integer] depth the current depth of the resolution process.
    # @return [void]
    def debug(depth = 0)
      if debug?
        debug_info = yield
        debug_info = debug_info.inspect unless debug_info.is_a?(String)
        debug_info = debug_info.split("\n").map { |s| ":#{depth.to_s.rjust 4}: #{s}" }
        output.puts debug_info
      end
    end

    # Whether or not debug messages should be printed.
    # By default, whether or not the `MOLINILLO_DEBUG` environment variable is
    # set.
    #
    # @return [Boolean]
    def debug?
      return @debug_mode if defined?(@debug_mode)
      @debug_mode = ENV['MOLINILLO_DEBUG']
    end
  end
end
# frozen_string_literal: true

module Gem::Resolver::Molinillo
  # Provides information about specifications and dependencies to the resolver,
  # allowing the {Resolver} class to remain generic while still providing power
  # and flexibility.
  #
  # This module contains the methods that users of Gem::Resolver::Molinillo must to implement,
  # using knowledge of their own model classes.
  module SpecificationProvider
    # Search for the specifications that match the given dependency.
    # The specifications in the returned array will be considered in reverse
    # order, so the latest version ought to be last.
    # @note This method should be 'pure', i.e. the return value should depend
    #   only on the `dependency` parameter.
    #
    # @param [Object] dependency
    # @return [Array<Object>] the specifications that satisfy the given
    #   `dependency`.
    def search_for(dependency)
      []
    end

    # Returns the dependencies of `specification`.
    # @note This method should be 'pure', i.e. the return value should depend
    #   only on the `specification` parameter.
    #
    # @param [Object] specification
    # @return [Array<Object>] the dependencies that are required by the given
    #   `specification`.
    def dependencies_for(specification)
      []
    end

    # Determines whether the given `requirement` is satisfied by the given
    # `spec`, in the context of the current `activated` dependency graph.
    #
    # @param [Object] requirement
    # @param [DependencyGraph] activated the current dependency graph in the
    #   resolution process.
    # @param [Object] spec
    # @return [Boolean] whether `requirement` is satisfied by `spec` in the
    #   context of the current `activated` dependency graph.
    def requirement_satisfied_by?(requirement, activated, spec)
      true
    end

    # Determines whether two arrays of dependencies are equal, and thus can be
    # grouped.
    #
    # @param [Array<Object>] dependencies
    # @param [Array<Object>] other_dependencies
    # @return [Boolean] whether `dependencies` and `other_dependencies` should
    #   be considered equal.
    def dependencies_equal?(dependencies, other_dependencies)
      dependencies == other_dependencies
    end

    # Returns the name for the given `dependency`.
    # @note This method should be 'pure', i.e. the return value should depend
    #   only on the `dependency` parameter.
    #
    # @param [Object] dependency
    # @return [String] the name for the given `dependency`.
    def name_for(dependency)
      dependency.to_s
    end

    # @return [String] the name of the source of explicit dependencies, i.e.
    #   those passed to {Resolver#resolve} directly.
    def name_for_explicit_dependency_source
      'user-specified dependency'
    end

    # @return [String] the name of the source of 'locked' dependencies, i.e.
    #   those passed to {Resolver#resolve} directly as the `base`
    def name_for_locking_dependency_source
      'Lockfile'
    end

    # Sort dependencies so that the ones that are easiest to resolve are first.
    # Easiest to resolve is (usually) defined by:
    #   1) Is this dependency already activated?
    #   2) How relaxed are the requirements?
    #   3) Are there any conflicts for this dependency?
    #   4) How many possibilities are there to satisfy this dependency?
    #
    # @param [Array<Object>] dependencies
    # @param [DependencyGraph] activated the current dependency graph in the
    #   resolution process.
    # @param [{String => Array<Conflict>}] conflicts
    # @return [Array<Object>] a sorted copy of `dependencies`.
    def sort_dependencies(dependencies, activated, conflicts)
      dependencies.sort_by do |dependency|
        name = name_for(dependency)
        [
          activated.vertex_named(name).payload ? 0 : 1,
          conflicts[name] ? 0 : 1,
        ]
      end
    end

    # Returns whether this dependency, which has no possible matching
    # specifications, can safely be ignored.
    #
    # @param [Object] dependency
    # @return [Boolean] whether this dependency can safely be skipped.
    def allow_missing?(dependency)
      false
    end
  end
end
# frozen_string_literal: true

module Gem::Resolver::Molinillo
  # A state that a {Resolution} can be in
  # @attr [String] name the name of the current requirement
  # @attr [Array<Object>] requirements currently unsatisfied requirements
  # @attr [DependencyGraph] activated the graph of activated dependencies
  # @attr [Object] requirement the current requirement
  # @attr [Object] possibilities the possibilities to satisfy the current requirement
  # @attr [Integer] depth the depth of the resolution
  # @attr [Hash] conflicts unresolved conflicts, indexed by dependency name
  # @attr [Array<UnwindDetails>] unused_unwind_options unwinds for previous conflicts that weren't explored
  ResolutionState = Struct.new(
    :name,
    :requirements,
    :activated,
    :requirement,
    :possibilities,
    :depth,
    :conflicts,
    :unused_unwind_options
  )

  class ResolutionState
    # Returns an empty resolution state
    # @return [ResolutionState] an empty state
    def self.empty
      new(nil, [], DependencyGraph.new, nil, nil, 0, {}, [])
    end
  end

  # A state that encapsulates a set of {#requirements} with an {Array} of
  # possibilities
  class DependencyState < ResolutionState
    # Removes a possibility from `self`
    # @return [PossibilityState] a state with a single possibility,
    #  the possibility that was removed from `self`
    def pop_possibility_state
      PossibilityState.new(
        name,
        requirements.dup,
        activated,
        requirement,
        [possibilities.pop],
        depth + 1,
        conflicts.dup,
        unused_unwind_options.dup
      ).tap do |state|
        state.activated.tag(state)
      end
    end
  end

  # A state that encapsulates a single possibility to fulfill the given
  # {#requirement}
  class PossibilityState < ResolutionState
  end
end
# frozen_string_literal: true
##
# A ComposedSet allows multiple sets to be queried like a single set.
#
# To create a composed set with any number of sets use:
#
#   Gem::Resolver.compose_sets set1, set2
#
# This method will eliminate nesting of composed sets.

class Gem::Resolver::ComposedSet < Gem::Resolver::Set
  attr_reader :sets # :nodoc:

  ##
  # Creates a new ComposedSet containing +sets+.  Use
  # Gem::Resolver::compose_sets instead.

  def initialize(*sets)
    super()

    @sets = sets
  end

  ##
  # When +allow_prerelease+ is set to +true+ prereleases gems are allowed to
  # match dependencies.

  def prerelease=(allow_prerelease)
    super

    sets.each do |set|
      set.prerelease = allow_prerelease
    end
  end

  ##
  # Sets the remote network access for all composed sets.

  def remote=(remote)
    super

    @sets.each {|set| set.remote = remote }
  end

  def errors
    @errors + @sets.map {|set| set.errors }.flatten
  end

  ##
  # Finds all specs matching +req+ in all sets.

  def find_all(req)
    @sets.map do |s|
      s.find_all req
    end.flatten
  end

  ##
  # Prefetches +reqs+ in all sets.

  def prefetch(reqs)
    @sets.each {|s| s.prefetch(reqs) }
  end
end
# frozen_string_literal: true
##
# A VendorSet represents gems that have been unpacked into a specific
# directory that contains a gemspec.
#
# This is used for gem dependency file support.
#
# Example:
#
#   set = Gem::Resolver::VendorSet.new
#
#   set.add_vendor_gem 'rake', 'vendor/rake'
#
# The directory vendor/rake must contain an unpacked rake gem along with a
# rake.gemspec (watching the given name).

class Gem::Resolver::VendorSet < Gem::Resolver::Set
  ##
  # The specifications for this set.

  attr_reader :specs # :nodoc:

  def initialize # :nodoc:
    super()

    @directories = {}
    @specs       = {}
  end

  ##
  # Adds a specification to the set with the given +name+ which has been
  # unpacked into the given +directory+.

  def add_vendor_gem(name, directory) # :nodoc:
    gemspec = File.join directory, "#{name}.gemspec"

    spec = Gem::Specification.load gemspec

    raise Gem::GemNotFoundException,
          "unable to find #{gemspec} for gem #{name}" unless spec

    spec.full_gem_path = File.expand_path directory

    @specs[spec.name]  = spec
    @directories[spec] = directory

    spec
  end

  ##
  # Returns an Array of VendorSpecification objects matching the
  # DependencyRequest +req+.

  def find_all(req)
    @specs.values.select do |spec|
      req.match? spec
    end.map do |spec|
      source = Gem::Source::Vendor.new @directories[spec]
      Gem::Resolver::VendorSpecification.new self, spec, source
    end
  end

  ##
  # Loads a spec with the given +name+. +version+, +platform+ and +source+ are
  # ignored.

  def load_spec(name, version, platform, source) # :nodoc:
    @specs.fetch name
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[VendorSet', ']' do
      next if @directories.empty?
      q.breakable

      dirs = @directories.map do |spec, directory|
        "#{spec.full_name}: #{directory}"
      end

      q.seplist dirs do |dir|
        q.text dir
      end
    end
  end
end
# frozen_string_literal: true
##
# A GitSet represents gems that are sourced from git repositories.
#
# This is used for gem dependency file support.
#
# Example:
#
#   set = Gem::Resolver::GitSet.new
#   set.add_git_gem 'rake', 'git://example/rake.git', tag: 'rake-10.1.0'

class Gem::Resolver::GitSet < Gem::Resolver::Set
  ##
  # The root directory for git gems in this set.  This is usually Gem.dir, the
  # installation directory for regular gems.

  attr_accessor :root_dir

  ##
  # Contains repositories needing submodules

  attr_reader :need_submodules # :nodoc:

  ##
  # A Hash containing git gem names for keys and a Hash of repository and
  # git commit reference as values.

  attr_reader :repositories # :nodoc:

  ##
  # A hash of gem names to Gem::Resolver::GitSpecifications

  attr_reader :specs # :nodoc:

  def initialize # :nodoc:
    super()

    @git             = ENV['git'] || 'git'
    @need_submodules = {}
    @repositories    = {}
    @root_dir        = Gem.dir
    @specs           = {}
  end

  def add_git_gem(name, repository, reference, submodules) # :nodoc:
    @repositories[name] = [repository, reference]
    @need_submodules[repository] = submodules
  end

  ##
  # Adds and returns a GitSpecification with the given +name+ and +version+
  # which came from a +repository+ at the given +reference+.  If +submodules+
  # is true they are checked out along with the repository.
  #
  # This fills in the prefetch information as enough information about the gem
  # is present in the arguments.

  def add_git_spec(name, version, repository, reference, submodules) # :nodoc:
    add_git_gem name, repository, reference, submodules

    source = Gem::Source::Git.new name, repository, reference
    source.root_dir = @root_dir

    spec = Gem::Specification.new do |s|
      s.name    = name
      s.version = version
    end

    git_spec = Gem::Resolver::GitSpecification.new self, spec, source

    @specs[spec.name] = git_spec

    git_spec
  end

  ##
  # Finds all git gems matching +req+

  def find_all(req)
    prefetch nil

    specs.values.select do |spec|
      req.match? spec
    end
  end

  ##
  # Prefetches specifications from the git repositories in this set.

  def prefetch(reqs)
    return unless @specs.empty?

    @repositories.each do |name, (repository, reference)|
      source = Gem::Source::Git.new name, repository, reference
      source.root_dir = @root_dir
      source.remote = @remote

      source.specs.each do |spec|
        git_spec = Gem::Resolver::GitSpecification.new self, spec, source

        @specs[spec.name] = git_spec
      end
    end
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[GitSet', ']' do
      next if @repositories.empty?
      q.breakable

      repos = @repositories.map do |name, (repository, reference)|
        "#{name}: #{repository}@#{reference}"
      end

      q.seplist repos do |repo|
        q.text repo
      end
    end
  end
end
# frozen_string_literal: true
##
# A LocalSpecification comes from a .gem file on the local filesystem.

class Gem::Resolver::LocalSpecification < Gem::Resolver::SpecSpecification
  ##
  # Returns +true+ if this gem is installable for the current platform.

  def installable_platform?
    return true if @source.kind_of? Gem::Source::SpecificFile

    super
  end

  def local? # :nodoc:
    true
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[LocalSpecification', ']' do
      q.breakable
      q.text "name: #{name}"

      q.breakable
      q.text "version: #{version}"

      q.breakable
      q.text "platform: #{platform}"

      q.breakable
      q.text 'dependencies:'
      q.breakable
      q.pp dependencies

      q.breakable
      q.text "source: #{@source.path}"
    end
  end
end
# frozen_string_literal: true
##
# Represents a specification retrieved via the rubygems.org API.
#
# This is used to avoid loading the full Specification object when all we need
# is the name, version, and dependencies.

class Gem::Resolver::APISpecification < Gem::Resolver::Specification
  ##
  # We assume that all instances of this class are immutable;
  # so avoid duplicated generation for performance.
  @@cache = {}
  def self.new(set, api_data)
    cache_key = [set, api_data]
    cache = @@cache[cache_key]
    return cache if cache
    @@cache[cache_key] = super
  end

  ##
  # Creates an APISpecification for the given +set+ from the rubygems.org
  # +api_data+.
  #
  # See https://guides.rubygems.org/rubygems-org-api/#misc_methods for the
  # format of the +api_data+.

  def initialize(set, api_data)
    super()

    @set = set
    @name = api_data[:name]
    @version = Gem::Version.new(api_data[:number]).freeze
    @platform = Gem::Platform.new(api_data[:platform]).freeze
    @original_platform = api_data[:platform].freeze
    @dependencies = api_data[:dependencies].map do |name, ver|
      Gem::Dependency.new(name, ver.split(/\s*,\s*/)).freeze
    end.freeze
    @required_ruby_version = Gem::Requirement.new(api_data.dig(:requirements, :ruby)).freeze
    @required_rubygems_version = Gem::Requirement.new(api_data.dig(:requirements, :rubygems)).freeze
  end

  def ==(other) # :nodoc:
    self.class === other and
      @set          == other.set and
      @name         == other.name and
      @version      == other.version and
      @platform     == other.platform
  end

  def hash
    @set.hash ^ @name.hash ^ @version.hash ^ @platform.hash
  end

  def fetch_development_dependencies # :nodoc:
    spec = source.fetch_spec Gem::NameTuple.new @name, @version, @platform

    @dependencies = spec.dependencies
  end

  def installable_platform? # :nodoc:
    Gem::Platform.match_gem? @platform, @name
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[APISpecification', ']' do
      q.breakable
      q.text "name: #{name}"

      q.breakable
      q.text "version: #{version}"

      q.breakable
      q.text "platform: #{platform}"

      q.breakable
      q.text 'dependencies:'
      q.breakable
      q.pp @dependencies

      q.breakable
      q.text "set uri: #{@set.dep_uri}"
    end
  end

  ##
  # Fetches a Gem::Specification for this APISpecification.

  def spec # :nodoc:
    @spec ||=
      begin
        tuple = Gem::NameTuple.new @name, @version, @platform
        source.fetch_spec tuple
      rescue Gem::RemoteFetcher::FetchError
        raise if @original_platform == @platform

        tuple = Gem::NameTuple.new @name, @version, @original_platform
        source.fetch_spec tuple
      end
  end

  def source # :nodoc:
    @set.source
  end
end
# frozen_string_literal: true
##
# A set of gems from a gem dependencies lockfile.

class Gem::Resolver::LockSet < Gem::Resolver::Set
  attr_reader :specs # :nodoc:

  ##
  # Creates a new LockSet from the given +sources+

  def initialize(sources)
    super()

    @sources = sources.map do |source|
      Gem::Source::Lock.new source
    end

    @specs = []
  end

  ##
  # Creates a new IndexSpecification in this set using the given +name+,
  # +version+ and +platform+.
  #
  # The specification's set will be the current set, and the source will be
  # the current set's source.

  def add(name, version, platform) # :nodoc:
    version = Gem::Version.new version
    specs = [
      Gem::Resolver::LockSpecification.new(self, name, version, @sources, platform),
    ]

    @specs.concat specs

    specs
  end

  ##
  # Returns an Array of IndexSpecification objects matching the
  # DependencyRequest +req+.

  def find_all(req)
    @specs.select do |spec|
      req.match? spec
    end
  end

  ##
  # Loads a Gem::Specification with the given +name+, +version+ and
  # +platform+.  +source+ is ignored.

  def load_spec(name, version, platform, source) # :nodoc:
    dep = Gem::Dependency.new name, version

    found = @specs.find do |spec|
      dep.matches_spec? spec and spec.platform == platform
    end

    tuple = Gem::NameTuple.new found.name, found.version, found.platform

    found.source.fetch_spec tuple
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[LockSet', ']' do
      q.breakable
      q.text 'source:'

      q.breakable
      q.pp @source

      q.breakable
      q.text 'specs:'

      q.breakable
      q.pp @specs.map {|spec| spec.full_name }
    end
  end
end
# frozen_string_literal: true
class Gem::Resolver::Stats
  def initialize
    @max_depth = 0
    @max_requirements = 0
    @requirements = 0
    @backtracking = 0
    @iterations = 0
  end

  def record_depth(stack)
    if stack.size > @max_depth
      @max_depth = stack.size
    end
  end

  def record_requirements(reqs)
    if reqs.size > @max_requirements
      @max_requirements = reqs.size
    end
  end

  def requirement!
    @requirements += 1
  end

  def backtracking!
    @backtracking += 1
  end

  def iteration!
    @iterations += 1
  end

  PATTERN = "%20s: %d\n".freeze

  def display
    $stdout.puts "=== Resolver Statistics ==="
    $stdout.printf PATTERN, "Max Depth", @max_depth
    $stdout.printf PATTERN, "Total Requirements", @requirements
    $stdout.printf PATTERN, "Max Requirements", @max_requirements
    $stdout.printf PATTERN, "Backtracking #", @backtracking
    $stdout.printf PATTERN, "Iteration #", @iterations
  end
end
# frozen_string_literal: true

class Gem::Resolver::APISet::GemParser
  def parse(line)
    version_and_platform, rest = line.split(" ", 2)
    version, platform = version_and_platform.split("-", 2)
    dependencies, requirements = rest.split("|", 2).map {|s| s.split(",") } if rest
    dependencies = dependencies ? dependencies.map {|d| parse_dependency(d) } : []
    requirements = requirements ? requirements.map {|d| parse_dependency(d) } : []
    [version, platform, dependencies, requirements]
  end

  private

  def parse_dependency(string)
    dependency = string.split(":")
    dependency[-1] = dependency[-1].split("&") if dependency.size > 1
    dependency
  end
end
# frozen_string_literal: true
##
# The LockSpecification comes from a lockfile (Gem::RequestSet::Lockfile).
#
# A LockSpecification's dependency information is pre-filled from the
# lockfile.

class Gem::Resolver::LockSpecification < Gem::Resolver::Specification
  attr_reader :sources

  def initialize(set, name, version, sources, platform)
    super()

    @name     = name
    @platform = platform
    @set      = set
    @source   = sources.first
    @sources  = sources
    @version  = version

    @dependencies = []
    @spec         = nil
  end

  ##
  # This is a null install as a locked specification is considered installed.
  # +options+ are ignored.

  def install(options = {})
    destination = options[:install_dir] || Gem.dir

    if File.exist? File.join(destination, 'specifications', spec.spec_name)
      yield nil
      return
    end

    super
  end

  ##
  # Adds +dependency+ from the lockfile to this specification

  def add_dependency(dependency) # :nodoc:
    @dependencies << dependency
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[LockSpecification', ']' do
      q.breakable
      q.text "name: #{@name}"

      q.breakable
      q.text "version: #{@version}"

      unless @platform == Gem::Platform::RUBY
        q.breakable
        q.text "platform: #{@platform}"
      end

      unless @dependencies.empty?
        q.breakable
        q.text 'dependencies:'
        q.breakable
        q.pp @dependencies
      end
    end
  end

  ##
  # A specification constructed from the lockfile is returned

  def spec
    @spec ||= Gem::Specification.find do |spec|
      spec.name == @name and spec.version == @version
    end

    @spec ||= Gem::Specification.new do |s|
      s.name     = @name
      s.version  = @version
      s.platform = @platform

      s.dependencies.concat @dependencies
    end
  end
end
# frozen_string_literal: true
##
# Used Internally. Wraps a Dependency object to also track which spec
# contained the Dependency.

class Gem::Resolver::DependencyRequest
  ##
  # The wrapped Gem::Dependency

  attr_reader :dependency

  ##
  # The request for this dependency.

  attr_reader :requester

  ##
  # Creates a new DependencyRequest for +dependency+ from +requester+.
  # +requester may be nil if the request came from a user.

  def initialize(dependency, requester)
    @dependency = dependency
    @requester  = requester
  end

  def ==(other) # :nodoc:
    case other
    when Gem::Dependency
      @dependency == other
    when Gem::Resolver::DependencyRequest
      @dependency == other.dependency
    else
      false
    end
  end

  ##
  # Is this dependency a development dependency?

  def development?
    @dependency.type == :development
  end

  ##
  # Does this dependency request match +spec+?
  #
  # NOTE:  #match? only matches prerelease versions when #dependency is a
  # prerelease dependency.

  def match?(spec, allow_prerelease = false)
    @dependency.match? spec, nil, allow_prerelease
  end

  ##
  # Does this dependency request match +spec+?
  #
  # NOTE:  #matches_spec? matches prerelease versions.  See also #match?

  def matches_spec?(spec)
    @dependency.matches_spec? spec
  end

  ##
  # The name of the gem this dependency request is requesting.

  def name
    @dependency.name
  end

  def type
    @dependency.type
  end

  ##
  # Indicate that the request is for a gem explicitly requested by the user

  def explicit?
    @requester.nil?
  end

  ##
  # Indicate that the request is for a gem requested as a dependency of
  # another gem

  def implicit?
    !explicit?
  end

  ##
  # Return a String indicating who caused this request to be added (only
  # valid for implicit requests)

  def request_context
    @requester ? @requester.request : "(unknown)"
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[Dependency request ', ']' do
      q.breakable
      q.text @dependency.to_s

      q.breakable
      q.text ' requested by '
      q.pp @requester
    end
  end

  ##
  # The version requirement for this dependency request

  def requirement
    @dependency.requirement
  end

  def to_s # :nodoc:
    @dependency.to_s
  end
end
# frozen_string_literal: true
##
# Specifies a Specification object that should be activated.  Also contains a
# dependency that was used to introduce this activation.

class Gem::Resolver::ActivationRequest
  ##
  # The parent request for this activation request.

  attr_reader :request

  ##
  # The specification to be activated.

  attr_reader :spec

  ##
  # Creates a new ActivationRequest that will activate +spec+.  The parent
  # +request+ is used to provide diagnostics in case of conflicts.

  def initialize(spec, request)
    @spec = spec
    @request = request
  end

  def ==(other) # :nodoc:
    case other
    when Gem::Specification
      @spec == other
    when Gem::Resolver::ActivationRequest
      @spec == other.spec
    else
      false
    end
  end

  def eql?(other)
    self == other
  end

  def hash
    @spec.hash
  end

  ##
  # Is this activation request for a development dependency?

  def development?
    @request.development?
  end

  ##
  # Downloads a gem at +path+ and returns the file path.

  def download(path)
    Gem.ensure_gem_subdirectories path

    if @spec.respond_to? :sources
      exception = nil
      path = @spec.sources.find do |source|
        begin
          source.download full_spec, path
        rescue exception
        end
      end
      return path      if path
      raise  exception if exception

    elsif @spec.respond_to? :source
      source = @spec.source
      source.download full_spec, path

    else
      source = Gem.sources.first
      source.download full_spec, path
    end
  end

  ##
  # The full name of the specification to be activated.

  def full_name
    name_tuple.full_name
  end

  alias_method :to_s, :full_name

  ##
  # The Gem::Specification for this activation request.

  def full_spec
    Gem::Specification === @spec ? @spec : @spec.spec
  end

  def inspect # :nodoc:
    '#<%s for %p from %s>' % [
      self.class, @spec, @request
    ]
  end

  ##
  # True if the requested gem has already been installed.

  def installed?
    case @spec
    when Gem::Resolver::VendorSpecification then
      true
    else
      this_spec = full_spec

      Gem::Specification.any? do |s|
        s == this_spec
      end
    end
  end

  ##
  # The name of this activation request's specification

  def name
    @spec.name
  end

  ##
  # Return the ActivationRequest that contained the dependency
  # that we were activated for.

  def parent
    @request.requester
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[Activation request', ']' do
      q.breakable
      q.pp @spec

      q.breakable
      q.text ' for '
      q.pp @request
    end
  end

  ##
  # The version of this activation request's specification

  def version
    @spec.version
  end

  ##
  # The platform of this activation request's specification

  def platform
    @spec.platform
  end

  private

  def name_tuple
    @name_tuple ||= Gem::NameTuple.new(name, version, platform)
  end
end
# frozen_string_literal: true
##
# A Resolver::Specification contains a subset of the information
# contained in a Gem::Specification.  Only the information necessary for
# dependency resolution in the resolver is included.

class Gem::Resolver::Specification
  ##
  # The dependencies of the gem for this specification

  attr_reader :dependencies

  ##
  # The name of the gem for this specification

  attr_reader :name

  ##
  # The platform this gem works on.

  attr_reader :platform

  ##
  # The set this specification came from.

  attr_reader :set

  ##
  # The source for this specification

  attr_reader :source

  ##
  # The Gem::Specification for this Resolver::Specification.
  #
  # Implementers, note that #install updates @spec, so be sure to cache the
  # Gem::Specification in @spec when overriding.

  attr_reader :spec

  ##
  # The version of the gem for this specification.

  attr_reader :version

  ##
  # The required_ruby_version constraint for this specification.

  attr_reader :required_ruby_version

  ##
  # The required_ruby_version constraint for this specification.

  attr_reader :required_rubygems_version

  ##
  # Sets default instance variables for the specification.

  def initialize
    @dependencies = nil
    @name         = nil
    @platform     = nil
    @set          = nil
    @source       = nil
    @version      = nil
    @required_ruby_version = Gem::Requirement.default
    @required_rubygems_version = Gem::Requirement.default
  end

  ##
  # Fetches development dependencies if the source does not provide them by
  # default (see APISpecification).

  def fetch_development_dependencies # :nodoc:
  end

  ##
  # The name and version of the specification.
  #
  # Unlike Gem::Specification#full_name, the platform is not included.

  def full_name
    "#{@name}-#{@version}"
  end

  ##
  # Installs this specification using the Gem::Installer +options+.  The
  # install method yields a Gem::Installer instance, which indicates the
  # gem will be installed, or +nil+, which indicates the gem is already
  # installed.
  #
  # After installation #spec is updated to point to the just-installed
  # specification.

  def install(options = {})
    require_relative '../installer'

    gem = download options

    installer = Gem::Installer.at gem, options

    yield installer if block_given?

    @spec = installer.install
  end

  def download(options)
    dir = options[:install_dir] || Gem.dir

    Gem.ensure_gem_subdirectories dir

    source.download spec, dir
  end

  ##
  # Returns true if this specification is installable on this platform.

  def installable_platform?
    Gem::Platform.match_spec? spec
  end

  def local? # :nodoc:
    false
  end
end
##
# The SourceSet chooses the best available method to query a remote index.
#
# Kind off like BestSet but filters the sources for gems

class Gem::Resolver::SourceSet < Gem::Resolver::Set
  ##
  # Creates a SourceSet for the given +sources+ or Gem::sources if none are
  # specified.  +sources+ must be a Gem::SourceList.

  def initialize
    super()

    @links = {}
    @sets  = {}
  end

  def find_all(req) # :nodoc:
    if set = get_set(req.dependency.name)
      set.find_all req
    else
      []
    end
  end

  # potentially no-op
  def prefetch(reqs) # :nodoc:
    reqs.each do |req|
      if set = get_set(req.dependency.name)
        set.prefetch reqs
      end
    end
  end

  def add_source_gem(name, source)
    @links[name] = source
  end

  private

  def get_set(name)
    link = @links[name]
    @sets[link] ||= Gem::Source.new(link).dependency_resolver_set if link
  end
end
# frozen_string_literal: true
##
# A VendorSpecification represents a gem that has been unpacked into a project
# and is being loaded through a gem dependencies file through the +path:+
# option.

class Gem::Resolver::VendorSpecification < Gem::Resolver::SpecSpecification
  def ==(other) # :nodoc:
    self.class === other and
      @set  == other.set and
      @spec == other.spec and
      @source == other.source
  end

  ##
  # This is a null install as this gem was unpacked into a directory.
  # +options+ are ignored.

  def install(options = {})
    yield nil
  end
end
# frozen_string_literal: true
##
# The Dependency class holds a Gem name and a Gem::Requirement.

class Gem::Dependency
  ##
  # Valid dependency types.
  #--
  # When this list is updated, be sure to change
  # Gem::Specification::CURRENT_SPECIFICATION_VERSION as well.
  #
  # REFACTOR: This type of constant, TYPES, indicates we might want
  # two classes, used via inheritance or duck typing.

  TYPES = [
    :development,
    :runtime,
  ].freeze

  ##
  # Dependency name or regular expression.

  attr_accessor :name

  ##
  # Allows you to force this dependency to be a prerelease.

  attr_writer :prerelease

  ##
  # Constructs a dependency with +name+ and +requirements+. The last
  # argument can optionally be the dependency type, which defaults to
  # <tt>:runtime</tt>.

  def initialize(name, *requirements)
    case name
    when String then # ok
    when Regexp then
      msg = ["NOTE: Dependency.new w/ a regexp is deprecated.",
             "Dependency.new called from #{Gem.location_of_caller.join(":")}"]
      warn msg.join("\n") unless Gem::Deprecate.skip
    else
      raise ArgumentError,
            "dependency name must be a String, was #{name.inspect}"
    end

    type         = Symbol === requirements.last ? requirements.pop : :runtime
    requirements = requirements.first if 1 == requirements.length # unpack

    unless TYPES.include? type
      raise ArgumentError, "Valid types are #{TYPES.inspect}, " +
                           "not #{type.inspect}"
    end

    @name        = name
    @requirement = Gem::Requirement.create requirements
    @type        = type
    @prerelease  = false

    # This is for Marshal backwards compatibility. See the comments in
    # +requirement+ for the dirty details.

    @version_requirements = @requirement
  end

  ##
  # A dependency's hash is the XOR of the hashes of +name+, +type+,
  # and +requirement+.

  def hash # :nodoc:
    name.hash ^ type.hash ^ requirement.hash
  end

  def inspect # :nodoc:
    if prerelease?
      "<%s type=%p name=%p requirements=%p prerelease=ok>" %
        [self.class, self.type, self.name, requirement.to_s]
    else
      "<%s type=%p name=%p requirements=%p>" %
        [self.class, self.type, self.name, requirement.to_s]
    end
  end

  ##
  # Does this dependency require a prerelease?

  def prerelease?
    @prerelease || requirement.prerelease?
  end

  ##
  # Is this dependency simply asking for the latest version
  # of a gem?

  def latest_version?
    @requirement.none?
  end

  def pretty_print(q) # :nodoc:
    q.group 1, 'Gem::Dependency.new(', ')' do
      q.pp name
      q.text ','
      q.breakable

      q.pp requirement

      q.text ','
      q.breakable

      q.pp type
    end
  end

  ##
  # What does this dependency require?

  def requirement
    return @requirement if defined?(@requirement) and @requirement

    # @version_requirements and @version_requirement are legacy ivar
    # names, and supported here because older gems need to keep
    # working and Dependency doesn't implement marshal_dump and
    # marshal_load. In a happier world, this would be an
    # attr_accessor. The horrifying instance_variable_get you see
    # below is also the legacy of some old restructurings.
    #
    # Note also that because of backwards compatibility (loading new
    # gems in an old RubyGems installation), we can't add explicit
    # marshaling to this class until we want to make a big
    # break. Maybe 2.0.
    #
    # Children, define explicit marshal and unmarshal behavior for
    # public classes. Marshal formats are part of your public API.

    # REFACTOR: See above

    if defined?(@version_requirement) && @version_requirement
      version = @version_requirement.instance_variable_get :@version
      @version_requirement = nil
      @version_requirements = Gem::Requirement.new version
    end

    @requirement = @version_requirements if defined?(@version_requirements)
  end

  def requirements_list
    requirement.as_list
  end

  def to_s # :nodoc:
    if type != :runtime
      "#{name} (#{requirement}, #{type})"
    else
      "#{name} (#{requirement})"
    end
  end

  ##
  # Dependency type.

  def type
    @type ||= :runtime
  end

  def runtime?
    @type == :runtime || !@type
  end

  def ==(other) # :nodoc:
    Gem::Dependency === other &&
      self.name        == other.name &&
      self.type        == other.type &&
      self.requirement == other.requirement
  end

  ##
  # Dependencies are ordered by name.

  def <=>(other)
    self.name <=> other.name
  end

  ##
  # Uses this dependency as a pattern to compare to +other+. This
  # dependency will match if the name matches the other's name, and
  # other has only an equal version requirement that satisfies this
  # dependency.

  def =~(other)
    unless Gem::Dependency === other
      return unless other.respond_to?(:name) && other.respond_to?(:version)
      other = Gem::Dependency.new other.name, other.version
    end

    return false unless name === other.name

    reqs = other.requirement.requirements

    return false unless reqs.length == 1
    return false unless reqs.first.first == '='

    version = reqs.first.last

    requirement.satisfied_by? version
  end

  alias === =~

  ##
  # :call-seq:
  #   dep.match? name          => true or false
  #   dep.match? name, version => true or false
  #   dep.match? spec          => true or false
  #
  # Does this dependency match the specification described by +name+ and
  # +version+ or match +spec+?
  #
  # NOTE:  Unlike #matches_spec? this method does not return true when the
  # version is a prerelease version unless this is a prerelease dependency.

  def match?(obj, version=nil, allow_prerelease=false)
    if !version
      name = obj.name
      version = obj.version
    else
      name = obj
    end

    return false unless self.name === name

    version = Gem::Version.new version

    return true if requirement.none? and not version.prerelease?
    return false if version.prerelease? and
                    not allow_prerelease and
                    not prerelease?

    requirement.satisfied_by? version
  end

  ##
  # Does this dependency match +spec+?
  #
  # NOTE:  This is not a convenience method.  Unlike #match? this method
  # returns true when +spec+ is a prerelease version even if this dependency
  # is not a prerelease dependency.

  def matches_spec?(spec)
    return false unless name === spec.name
    return true  if requirement.none?

    requirement.satisfied_by?(spec.version)
  end

  ##
  # Merges the requirements of +other+ into this dependency

  def merge(other)
    unless name == other.name
      raise ArgumentError,
            "#{self} and #{other} have different names"
    end

    default = Gem::Requirement.default
    self_req = self.requirement
    other_req = other.requirement

    return self.class.new name, self_req  if other_req == default
    return self.class.new name, other_req if self_req  == default

    self.class.new name, self_req.as_list.concat(other_req.as_list)
  end

  def matching_specs(platform_only = false)
    env_req = Gem.env_requirement(name)
    matches = Gem::Specification.stubs_for(name).find_all do |spec|
      requirement.satisfied_by?(spec.version) && env_req.satisfied_by?(spec.version)
    end.map(&:to_spec)

    Gem::BundlerVersionFinder.filter!(matches) if filters_bundler?

    if platform_only
      matches.reject! do |spec|
        spec.nil? || !Gem::Platform.match_spec?(spec)
      end
    end

    matches
  end

  ##
  # True if the dependency will not always match the latest version.

  def specific?
    @requirement.specific?
  end

  def filters_bundler?
    name == "bundler".freeze && !specific?
  end

  def to_specs
    matches = matching_specs true

    # TODO: check Gem.activated_spec[self.name] in case matches falls outside

    if matches.empty?
      specs = Gem::Specification.stubs_for name

      if specs.empty?
        raise Gem::MissingSpecError.new name, requirement
      else
        raise Gem::MissingSpecVersionError.new name, requirement, specs
      end
    end

    # TODO: any other resolver validations should go here

    matches
  end

  def to_spec
    matches = self.to_specs.compact

    active = matches.find {|spec| spec.activated? }
    return active if active

    return matches.first if prerelease?

    # Move prereleases to the end of the list for >= 0 requirements
    pre, matches = matches.partition {|spec| spec.version.prerelease? }
    matches += pre if requirement == Gem::Requirement.default

    matches.first
  end

  def identity
    if prerelease?
      if specific?
        :complete
      else
        :abs_latest
      end
    elsif latest_version?
      :latest
    else
      :released
    end
  end
end
# frozen_string_literal: true

##
# The SourceList represents the sources rubygems has been configured to use.
# A source may be created from an array of sources:
#
#   Gem::SourceList.from %w[https://rubygems.example https://internal.example]
#
# Or by adding them:
#
#   sources = Gem::SourceList.new
#   sources << 'https://rubygems.example'
#
# The most common way to get a SourceList is Gem.sources.

class Gem::SourceList
  include Enumerable

  ##
  # Creates a new SourceList

  def initialize
    @sources = []
  end

  ##
  # The sources in this list

  attr_reader :sources

  ##
  # Creates a new SourceList from an array of sources.

  def self.from(ary)
    list = new

    list.replace ary

    return list
  end

  def initialize_copy(other) # :nodoc:
    @sources = @sources.dup
  end

  ##
  # Appends +obj+ to the source list which may be a Gem::Source, URI or URI
  # String.

  def <<(obj)
    require "uri"

    src = case obj
          when URI
            Gem::Source.new(obj)
          when Gem::Source
            obj
          else
            Gem::Source.new(URI.parse(obj))
          end

    @sources << src unless @sources.include?(src)
    src
  end

  ##
  # Replaces this SourceList with the sources in +other+  See #<< for
  # acceptable items in +other+.

  def replace(other)
    clear

    other.each do |x|
      self << x
    end

    self
  end

  ##
  # Removes all sources from the SourceList.

  def clear
    @sources.clear
  end

  ##
  # Yields each source URI in the list.

  def each
    @sources.each {|s| yield s.uri.to_s }
  end

  ##
  # Yields each source in the list.

  def each_source(&b)
    @sources.each(&b)
  end

  ##
  # Returns true if there are no sources in this SourceList.

  def empty?
    @sources.empty?
  end

  def ==(other) # :nodoc:
    to_a == other
  end

  ##
  # Returns an Array of source URI Strings.

  def to_a
    @sources.map {|x| x.uri.to_s }
  end

  alias_method :to_ary, :to_a

  ##
  # Returns the first source in the list.

  def first
    @sources.first
  end

  ##
  # Returns true if this source list includes +other+ which may be a
  # Gem::Source or a source URI.

  def include?(other)
    if other.kind_of? Gem::Source
      @sources.include? other
    else
      @sources.find {|x| x.uri.to_s == other.to_s }
    end
  end

  ##
  # Deletes +source+ from the source list which may be a Gem::Source or a URI.

  def delete(source)
    if source.kind_of? Gem::Source
      @sources.delete source
    else
      @sources.delete_if {|x| x.uri.to_s == source.to_s }
    end
  end
end
# frozen_string_literal: true

##
# The UriFormatter handles URIs from user-input and escaping.
#
#   uf = Gem::UriFormatter.new 'example.com'
#
#   p uf.normalize #=> 'http://example.com'

class Gem::UriFormatter
  ##
  # The URI to be formatted.

  attr_reader :uri

  ##
  # Creates a new URI formatter for +uri+.

  def initialize(uri)
    require 'cgi'

    @uri = uri
  end

  ##
  # Escapes the #uri for use as a CGI parameter

  def escape
    return unless @uri
    CGI.escape @uri
  end

  ##
  # Normalize the URI by adding "http://" if it is missing.

  def normalize
    (@uri =~ /^(https?|ftp|file):/i) ? @uri : "http://#{@uri}"
  end

  ##
  # Unescapes the #uri which came from a CGI parameter

  def unescape
    return unless @uri
    CGI.unescape @uri
  end
end
# frozen_string_literal: true
require_relative 'tsort'

##
# A RequestSet groups a request to activate a set of dependencies.
#
#   nokogiri = Gem::Dependency.new 'nokogiri', '~> 1.6'
#   pg = Gem::Dependency.new 'pg', '~> 0.14'
#
#   set = Gem::RequestSet.new nokogiri, pg
#
#   requests = set.resolve
#
#   p requests.map { |r| r.full_name }
#   #=> ["nokogiri-1.6.0", "mini_portile-0.5.1", "pg-0.17.0"]

class Gem::RequestSet
  include Gem::TSort

  ##
  # Array of gems to install even if already installed

  attr_accessor :always_install

  attr_reader :dependencies

  attr_accessor :development

  ##
  # Errors fetching gems during resolution.

  attr_reader :errors

  ##
  # Set to true if you want to install only direct development dependencies.

  attr_accessor :development_shallow

  ##
  # The set of git gems imported via load_gemdeps.

  attr_reader :git_set # :nodoc:

  ##
  # When true, dependency resolution is not performed, only the requested gems
  # are installed.

  attr_accessor :ignore_dependencies

  attr_reader :install_dir # :nodoc:

  ##
  # If true, allow dependencies to match prerelease gems.

  attr_accessor :prerelease

  ##
  # When false no remote sets are used for resolving gems.

  attr_accessor :remote

  attr_reader :resolver # :nodoc:

  ##
  # Sets used for resolution

  attr_reader :sets # :nodoc:

  ##
  # Treat missing dependencies as silent errors

  attr_accessor :soft_missing

  ##
  # The set of vendor gems imported via load_gemdeps.

  attr_reader :vendor_set # :nodoc:

  ##
  # The set of source gems imported via load_gemdeps.

  attr_reader :source_set

  ##
  # Creates a RequestSet for a list of Gem::Dependency objects, +deps+.  You
  # can then #resolve and #install the resolved list of dependencies.
  #
  #   nokogiri = Gem::Dependency.new 'nokogiri', '~> 1.6'
  #   pg = Gem::Dependency.new 'pg', '~> 0.14'
  #
  #   set = Gem::RequestSet.new nokogiri, pg

  def initialize(*deps)
    @dependencies = deps

    @always_install      = []
    @conservative        = false
    @dependency_names    = {}
    @development         = false
    @development_shallow = false
    @errors              = []
    @git_set             = nil
    @ignore_dependencies = false
    @install_dir         = Gem.dir
    @prerelease          = false
    @remote              = true
    @requests            = []
    @sets                = []
    @soft_missing        = false
    @sorted              = nil
    @specs               = nil
    @vendor_set          = nil
    @source_set          = nil

    yield self if block_given?
  end

  ##
  # Declare that a gem of name +name+ with +reqs+ requirements is needed.

  def gem(name, *reqs)
    if dep = @dependency_names[name]
      dep.requirement.concat reqs
    else
      dep = Gem::Dependency.new name, *reqs
      @dependency_names[name] = dep
      @dependencies << dep
    end
  end

  ##
  # Add +deps+ Gem::Dependency objects to the set.

  def import(deps)
    @dependencies.concat deps
  end

  ##
  # Installs gems for this RequestSet using the Gem::Installer +options+.
  #
  # If a +block+ is given an activation +request+ and +installer+ are yielded.
  # The +installer+ will be +nil+ if a gem matching the request was already
  # installed.

  def install(options, &block) # :yields: request, installer
    if dir = options[:install_dir]
      requests = install_into dir, false, options, &block
      return requests
    end

    @prerelease = options[:prerelease]

    requests = []
    download_queue = Thread::Queue.new

    # Create a thread-safe list of gems to download
    sorted_requests.each do |req|
      download_queue << req
    end

    # Create N threads in a pool, have them download all the gems
    threads = Gem.configuration.concurrent_downloads.times.map do
      # When a thread pops this item, it knows to stop running. The symbol
      # is queued here so that there will be one symbol per thread.
      download_queue << :stop

      Thread.new do
        # The pop method will block waiting for items, so the only way
        # to stop a thread from running is to provide a final item that
        # means the thread should stop.
        while req = download_queue.pop
          break if req == :stop
          req.spec.download options unless req.installed?
        end
      end
    end

    # Wait for all the downloads to finish before continuing
    threads.each(&:value)

    # Install requested gems after they have been downloaded
    sorted_requests.each do |req|
      if req.installed?
        req.spec.spec.build_extensions

        if @always_install.none? {|spec| spec == req.spec.spec }
          yield req, nil if block_given?
          next
        end
      end

      spec =
        begin
          req.spec.install options do |installer|
            yield req, installer if block_given?
          end
        rescue Gem::RuntimeRequirementNotMetError => e
          suggestion = "There are no versions of #{req.request} compatible with your Ruby & RubyGems"
          suggestion += ". Maybe try installing an older version of the gem you're looking for?" unless @always_install.include?(req.spec.spec)
          e.suggestion = suggestion
          raise
        end

      requests << spec
    end

    return requests if options[:gemdeps]

    install_hooks requests, options

    requests
  end

  ##
  # Installs from the gem dependencies files in the +:gemdeps+ option in
  # +options+, yielding to the +block+ as in #install.
  #
  # If +:without_groups+ is given in the +options+, those groups in the gem
  # dependencies file are not used.  See Gem::Installer for other +options+.

  def install_from_gemdeps(options, &block)
    gemdeps = options[:gemdeps]

    @install_dir = options[:install_dir] || Gem.dir
    @prerelease  = options[:prerelease]
    @remote      = options[:domain] != :local
    @conservative = true if options[:conservative]

    gem_deps_api = load_gemdeps gemdeps, options[:without_groups], true

    resolve

    if options[:explain]
      puts "Gems to install:"

      sorted_requests.each do |spec|
        puts "  #{spec.full_name}"
      end

      if Gem.configuration.really_verbose
        @resolver.stats.display
      end
    else
      installed = install options, &block

      if options.fetch :lock, true
        lockfile =
          Gem::RequestSet::Lockfile.build self, gemdeps, gem_deps_api.dependencies
        lockfile.write
      end

      installed
    end
  end

  def install_into(dir, force = true, options = {})
    gem_home, ENV['GEM_HOME'] = ENV['GEM_HOME'], dir

    existing = force ? [] : specs_in(dir)
    existing.delete_if {|s| @always_install.include? s }

    dir = File.expand_path dir

    installed = []

    options[:development] = false
    options[:install_dir] = dir
    options[:only_install_dir] = true
    @prerelease = options[:prerelease]

    sorted_requests.each do |request|
      spec = request.spec

      if existing.find {|s| s.full_name == spec.full_name }
        yield request, nil if block_given?
        next
      end

      spec.install options do |installer|
        yield request, installer if block_given?
      end

      installed << request
    end

    install_hooks installed, options

    installed
  ensure
    ENV['GEM_HOME'] = gem_home
  end

  ##
  # Call hooks on installed gems

  def install_hooks(requests, options)
    specs = requests.map do |request|
      case request
      when Gem::Resolver::ActivationRequest then
        request.spec.spec
      else
        request
      end
    end

    require_relative "dependency_installer"
    inst = Gem::DependencyInstaller.new options
    inst.installed_gems.replace specs

    Gem.done_installing_hooks.each do |hook|
      hook.call inst, specs
    end unless Gem.done_installing_hooks.empty?
  end

  ##
  # Load a dependency management file.

  def load_gemdeps(path, without_groups = [], installing = false)
    @git_set    = Gem::Resolver::GitSet.new
    @vendor_set = Gem::Resolver::VendorSet.new
    @source_set = Gem::Resolver::SourceSet.new

    @git_set.root_dir = @install_dir

    lock_file = "#{File.expand_path(path)}.lock".dup.tap(&Gem::UNTAINT)
    begin
      tokenizer = Gem::RequestSet::Lockfile::Tokenizer.from_file lock_file
      parser = tokenizer.make_parser self, []
      parser.parse
    rescue Errno::ENOENT
    end

    gf = Gem::RequestSet::GemDependencyAPI.new self, path
    gf.installing = installing
    gf.without_groups = without_groups if without_groups
    gf.load
  end

  def pretty_print(q) # :nodoc:
    q.group 2, '[RequestSet:', ']' do
      q.breakable

      if @remote
        q.text 'remote'
        q.breakable
      end

      if @prerelease
        q.text 'prerelease'
        q.breakable
      end

      if @development_shallow
        q.text 'shallow development'
        q.breakable
      elsif @development
        q.text 'development'
        q.breakable
      end

      if @soft_missing
        q.text 'soft missing'
      end

      q.group 2, '[dependencies:', ']' do
        q.breakable
        @dependencies.map do |dep|
          q.text dep.to_s
          q.breakable
        end
      end

      q.breakable
      q.text 'sets:'

      q.breakable
      q.pp @sets.map {|set| set.class }
    end
  end

  ##
  # Resolve the requested dependencies and return an Array of Specification
  # objects to be activated.

  def resolve(set = Gem::Resolver::BestSet.new)
    @sets << set
    @sets << @git_set
    @sets << @vendor_set
    @sets << @source_set

    set = Gem::Resolver.compose_sets(*@sets)
    set.remote = @remote
    set.prerelease = @prerelease

    resolver = Gem::Resolver.new @dependencies, set
    resolver.development         = @development
    resolver.development_shallow = @development_shallow
    resolver.ignore_dependencies = @ignore_dependencies
    resolver.soft_missing        = @soft_missing

    if @conservative
      installed_gems = {}
      Gem::Specification.find_all do |spec|
        (installed_gems[spec.name] ||= []) << spec
      end
      resolver.skip_gems = installed_gems
    end

    @resolver = resolver

    @requests = resolver.resolve

    @errors = set.errors

    @requests
  end

  ##
  # Resolve the requested dependencies against the gems available via Gem.path
  # and return an Array of Specification objects to be activated.

  def resolve_current
    resolve Gem::Resolver::CurrentSet.new
  end

  def sorted_requests
    @sorted ||= strongly_connected_components.flatten
  end

  def specs
    @specs ||= @requests.map {|r| r.full_spec }
  end

  def specs_in(dir)
    Gem::Util.glob_files_in_dir("*.gemspec", File.join(dir, "specifications")).map do |g|
      Gem::Specification.load g
    end
  end

  def tsort_each_node(&block) # :nodoc:
    @requests.each(&block)
  end

  def tsort_each_child(node) # :nodoc:
    node.spec.dependencies.each do |dep|
      next if dep.type == :development and not @development

      match = @requests.find do |r|
        dep.match? r.spec.name, r.spec.version, @prerelease
      end

      unless match
        next if dep.type == :development and @development_shallow
        next if @soft_missing
        raise Gem::DependencyError,
              "Unresolved dependency found during sorting - #{dep} (requested by #{node.spec.full_name})"
      end

      yield match
    end
  end
end

require_relative 'request_set/gem_dependency_api'
require_relative 'request_set/lockfile'
require_relative 'request_set/lockfile/tokenizer'
# frozen_string_literal: true
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require_relative 'optparse'
require_relative 'requirement'
require_relative 'user_interaction'

##
# Base class for all Gem commands.  When creating a new gem command, define
# #initialize, #execute, #arguments, #defaults_str, #description and #usage
# (as appropriate).  See the above mentioned methods for details.
#
# A very good example to look at is Gem::Commands::ContentsCommand

class Gem::Command
  include Gem::UserInteraction

  Gem::OptionParser.accept Symbol do |value|
    value.to_sym
  end

  ##
  # The name of the command.

  attr_reader :command

  ##
  # The options for the command.

  attr_reader :options

  ##
  # The default options for the command.

  attr_accessor :defaults

  ##
  # The name of the command for command-line invocation.

  attr_accessor :program_name

  ##
  # A short description of the command.

  attr_accessor :summary

  ##
  # Arguments used when building gems

  def self.build_args
    @build_args ||= []
  end

  def self.build_args=(value)
    @build_args = value
  end

  def self.common_options
    @common_options ||= []
  end

  def self.add_common_option(*args, &handler)
    Gem::Command.common_options << [args, handler]
  end

  def self.extra_args
    @extra_args ||= []
  end

  def self.extra_args=(value)
    case value
    when Array
      @extra_args = value
    when String
      @extra_args = value.split(' ')
    end
  end

  ##
  # Return an array of extra arguments for the command.  The extra arguments
  # come from the gem configuration file read at program startup.

  def self.specific_extra_args(cmd)
    specific_extra_args_hash[cmd]
  end

  ##
  # Add a list of extra arguments for the given command.  +args+ may be an
  # array or a string to be split on white space.

  def self.add_specific_extra_args(cmd,args)
    args = args.split(/\s+/) if args.kind_of? String
    specific_extra_args_hash[cmd] = args
  end

  ##
  # Accessor for the specific extra args hash (self initializing).

  def self.specific_extra_args_hash
    @specific_extra_args_hash ||= Hash.new do |h,k|
      h[k] = Array.new
    end
  end

  ##
  # Initializes a generic gem command named +command+.  +summary+ is a short
  # description displayed in `gem help commands`.  +defaults+ are the default
  # options.  Defaults should be mirrored in #defaults_str, unless there are
  # none.
  #
  # When defining a new command subclass, use add_option to add command-line
  # switches.
  #
  # Unhandled arguments (gem names, files, etc.) are left in
  # <tt>options[:args]</tt>.

  def initialize(command, summary=nil, defaults={})
    @command = command
    @summary = summary
    @program_name = "gem #{command}"
    @defaults = defaults
    @options = defaults.dup
    @option_groups = Hash.new {|h,k| h[k] = [] }
    @deprecated_options = { command => {} }
    @parser = nil
    @when_invoked = nil
  end

  ##
  # True if +long+ begins with the characters from +short+.

  def begins?(long, short)
    return false if short.nil?
    long[0, short.length] == short
  end

  ##
  # Override to provide command handling.
  #
  # #options will be filled in with your parsed options, unparsed options will
  # be left in <tt>options[:args]</tt>.
  #
  # See also: #get_all_gem_names, #get_one_gem_name,
  # #get_one_optional_argument

  def execute
    raise Gem::Exception, "generic command has no actions"
  end

  ##
  # Display to the user that a gem couldn't be found and reasons why
  #--

  def show_lookup_failure(gem_name, version, errors, suppress_suggestions = false, required_by = nil)
    gem = "'#{gem_name}' (#{version})"
    msg = String.new "Could not find a valid gem #{gem}"

    if errors and !errors.empty?
      msg << ", here is why:\n"
      errors.each {|x| msg << "          #{x.wordy}\n" }
    else
      if required_by and gem != required_by
        msg << " (required by #{required_by}) in any repository"
      else
        msg << " in any repository"
      end
    end

    alert_error msg

    unless suppress_suggestions
      suggestions = Gem::SpecFetcher.fetcher.suggest_gems_from_name(gem_name, :latest, 10)
      unless suggestions.empty?
        alert_error "Possible alternatives: #{suggestions.join(", ")}"
      end
    end
  end

  ##
  # Get all gem names from the command line.

  def get_all_gem_names
    args = options[:args]

    if args.nil? or args.empty?
      raise Gem::CommandLineError,
            "Please specify at least one gem name (e.g. gem build GEMNAME)"
    end

    args.select {|arg| arg !~ /^-/ }
  end

  ##
  # Get all [gem, version] from the command line.
  #
  # An argument in the form gem:ver is pull apart into the gen name and version,
  # respectively.
  def get_all_gem_names_and_versions
    get_all_gem_names.map do |name|
      if /\A(.*):(#{Gem::Requirement::PATTERN_RAW})\z/ =~ name
        [$1, $2]
      else
        [name]
      end
    end
  end

  ##
  # Get a single gem name from the command line.  Fail if there is no gem name
  # or if there is more than one gem name given.

  def get_one_gem_name
    args = options[:args]

    if args.nil? or args.empty?
      raise Gem::CommandLineError,
            "Please specify a gem name on the command line (e.g. gem build GEMNAME)"
    end

    if args.size > 1
      raise Gem::CommandLineError,
            "Too many gem names (#{args.join(', ')}); please specify only one"
    end

    args.first
  end

  ##
  # Get a single optional argument from the command line.  If more than one
  # argument is given, return only the first. Return nil if none are given.

  def get_one_optional_argument
    args = options[:args] || []
    args.first
  end

  ##
  # Override to provide details of the arguments a command takes.  It should
  # return a left-justified string, one argument per line.
  #
  # For example:
  #
  #   def usage
  #     "#{program_name} FILE [FILE ...]"
  #   end
  #
  #   def arguments
  #     "FILE          name of file to find"
  #   end

  def arguments
    ""
  end

  ##
  # Override to display the default values of the command options. (similar to
  # +arguments+, but displays the default values).
  #
  # For example:
  #
  #   def defaults_str
  #     --no-gems-first --no-all
  #   end

  def defaults_str
    ""
  end

  ##
  # Override to display a longer description of what this command does.

  def description
    nil
  end

  ##
  # Override to display the usage for an individual gem command.
  #
  # The text "[options]" is automatically appended to the usage text.

  def usage
    program_name
  end

  ##
  # Display the help message for the command.

  def show_help
    parser.program_name = usage
    say parser
  end

  ##
  # Invoke the command with the given list of arguments.

  def invoke(*args)
    invoke_with_build_args args, nil
  end

  ##
  # Invoke the command with the given list of normal arguments
  # and additional build arguments.

  def invoke_with_build_args(args, build_args)
    handle_options args

    options[:build_args] = build_args

    if options[:silent]
      old_ui = self.ui
      self.ui = ui = Gem::SilentUI.new
    end

    if options[:help]
      show_help
    elsif @when_invoked
      @when_invoked.call options
    else
      execute
    end
  ensure
    if ui
      self.ui = old_ui
      ui.close
    end
  end

  ##
  # Call the given block when invoked.
  #
  # Normal command invocations just executes the +execute+ method of the
  # command.  Specifying an invocation block allows the test methods to
  # override the normal action of a command to determine that it has been
  # invoked correctly.

  def when_invoked(&block)
    @when_invoked = block
  end

  ##
  # Add a command-line option and handler to the command.
  #
  # See Gem::OptionParser#make_switch for an explanation of +opts+.
  #
  # +handler+ will be called with two values, the value of the argument and
  # the options hash.
  #
  # If the first argument of add_option is a Symbol, it's used to group
  # options in output.  See `gem help list` for an example.

  def add_option(*opts, &handler) # :yields: value, options
    group_name = Symbol === opts.first ? opts.shift : :options

    raise "Do not pass an empty string in opts" if opts.include?("")

    @option_groups[group_name] << [opts, handler]
  end

  ##
  # Remove previously defined command-line argument +name+.

  def remove_option(name)
    @option_groups.each do |_, option_list|
      option_list.reject! {|args, _| args.any? {|x| x.is_a?(String) && x =~ /^#{name}/ } }
    end
  end

  ##
  # Mark a command-line option as deprecated, and optionally specify a
  # deprecation horizon.
  #
  # Note that with the current implementation, every version of the option needs
  # to be explicitly deprecated, so to deprecate an option defined as
  #
  #   add_option('-t', '--[no-]test', 'Set test mode') do |value, options|
  #     # ... stuff ...
  #   end
  #
  # you would need to explicitly add a call to `deprecate_option` for every
  # version of the option you want to deprecate, like
  #
  #   deprecate_option('-t')
  #   deprecate_option('--test')
  #   deprecate_option('--no-test')

  def deprecate_option(name, version: nil, extra_msg: nil)
    @deprecated_options[command].merge!({ name => { "rg_version_to_expire" => version, "extra_msg" => extra_msg } })
  end

  def check_deprecated_options(options)
    options.each do |option|
      if option_is_deprecated?(option)
        deprecation = @deprecated_options[command][option]
        version_to_expire = deprecation["rg_version_to_expire"]

        deprecate_option_msg = if version_to_expire
                                 "The \"#{option}\" option has been deprecated and will be removed in Rubygems #{version_to_expire}."
                               else
                                 "The \"#{option}\" option has been deprecated and will be removed in future versions of Rubygems."
                               end

        extra_msg = deprecation["extra_msg"]

        deprecate_option_msg += " #{extra_msg}" if extra_msg

        alert_warning(deprecate_option_msg)
      end
    end
  end

  ##
  # Merge a set of command options with the set of default options (without
  # modifying the default option hash).

  def merge_options(new_options)
    @options = @defaults.clone
    new_options.each {|k,v| @options[k] = v }
  end

  ##
  # True if the command handles the given argument list.

  def handles?(args)
    begin
      parser.parse!(args.dup)
      return true
    rescue
      return false
    end
  end

  ##
  # Handle the given list of arguments by parsing them and recording the
  # results.

  def handle_options(args)
    args = add_extra_args(args)
    check_deprecated_options(args)
    @options = Marshal.load Marshal.dump @defaults # deep copy
    parser.parse!(args)
    @options[:args] = args
  end

  ##
  # Adds extra args from ~/.gemrc

  def add_extra_args(args)
    result = []

    s_extra = Gem::Command.specific_extra_args(@command)
    extra = Gem::Command.extra_args + s_extra

    until extra.empty? do
      ex = []
      ex << extra.shift
      ex << extra.shift if extra.first.to_s =~ /^[^-]/ # rubocop:disable Performance/StartWith
      result << ex if handles?(ex)
    end

    result.flatten!
    result.concat(args)
    result
  end

  def deprecated?
    false
  end

  private

  def option_is_deprecated?(option)
    @deprecated_options[command].has_key?(option)
  end

  def add_parser_description # :nodoc:
    return unless description

    formatted = description.split("\n\n").map do |chunk|
      wrap chunk, 80 - 4
    end.join "\n"

    @parser.separator nil
    @parser.separator "  Description:"
    formatted.split("\n").each do |line|
      @parser.separator "    #{line.rstrip}"
    end
  end

  def add_parser_options # :nodoc:
    @parser.separator nil

    regular_options = @option_groups.delete :options

    configure_options "", regular_options

    @option_groups.sort_by {|n,_| n.to_s }.each do |group_name, option_list|
      @parser.separator nil
      configure_options group_name, option_list
    end
  end

  ##
  # Adds a section with +title+ and +content+ to the parser help view.  Used
  # for adding command arguments and default arguments.

  def add_parser_run_info(title, content)
    return if content.empty?

    @parser.separator nil
    @parser.separator "  #{title}:"
    content.split(/\n/).each do |line|
      @parser.separator "    #{line}"
    end
  end

  def add_parser_summary # :nodoc:
    return unless @summary

    @parser.separator nil
    @parser.separator "  Summary:"
    wrap(@summary, 80 - 4).split("\n").each do |line|
      @parser.separator "    #{line.strip}"
    end
  end

  ##
  # Create on demand parser.

  def parser
    create_option_parser if @parser.nil?
    @parser
  end

  ##
  # Creates an option parser and fills it in with the help info for the
  # command.

  def create_option_parser
    @parser = Gem::OptionParser.new

    add_parser_options

    @parser.separator nil
    configure_options "Common", Gem::Command.common_options

    add_parser_run_info "Arguments", arguments
    add_parser_summary
    add_parser_description
    add_parser_run_info "Defaults", defaults_str
  end

  def configure_options(header, option_list)
    return if option_list.nil? or option_list.empty?

    header = header.to_s.empty? ? '' : "#{header} "
    @parser.separator "  #{header}Options:"

    option_list.each do |args, handler|
      @parser.on(*args) do |value|
        handler.call(value, @options)
      end
    end

    @parser.separator ''
  end

  ##
  # Wraps +text+ to +width+

  def wrap(text, width) # :doc:
    text.gsub(/(.{1,#{width}})( +|$\n?)|(.{1,#{width}})/, "\\1\\3\n")
  end

  # ----------------------------------------------------------------
  # Add the options common to all commands.

  add_common_option('-h', '--help',
                    'Get help on this command') do |value, options|
    options[:help] = true
  end

  add_common_option('-V', '--[no-]verbose',
                    'Set the verbose level of output') do |value, options|
    # Set us to "really verbose" so the progress meter works
    if Gem.configuration.verbose and value
      Gem.configuration.verbose = 1
    else
      Gem.configuration.verbose = value
    end
  end

  add_common_option('-q', '--quiet', 'Silence command progress meter') do |value, options|
    Gem.configuration.verbose = false
  end

  add_common_option("--silent",
                    "Silence RubyGems output") do |value, options|
    options[:silent] = true
  end

  # Backtrace and config-file are added so they show up in the help
  # commands.  Both options are actually handled before the other
  # options get parsed.

  add_common_option('--config-file FILE',
                    'Use this config file instead of default') do
  end

  add_common_option('--backtrace',
                    'Show stack backtrace on errors') do
  end

  add_common_option('--debug',
                    'Turn on Ruby debugging') do
  end

  add_common_option('--norc',
                    'Avoid loading any .gemrc file') do
  end

  # :stopdoc:

  HELP = <<-HELP.freeze
RubyGems is a package manager for Ruby.

  Usage:
    gem -h/--help
    gem -v/--version
    gem command [arguments...] [options...]

  Examples:
    gem install rake
    gem list --local
    gem build package.gemspec
    gem push package-0.0.1.gem
    gem help install

  Further help:
    gem help commands            list all 'gem' commands
    gem help examples            show some examples of usage
    gem help gem_dependencies    gem dependencies file guide
    gem help platforms           gem platforms guide
    gem help <COMMAND>           show help on COMMAND
                                   (e.g. 'gem help install')
    gem server                   present a web page at
                                 http://localhost:8808/
                                 with info about installed gems
  Further information:
    https://guides.rubygems.org
  HELP

  # :startdoc:
end

##
# \Commands will be placed in this namespace

module Gem::Commands
end
# frozen_string_literal: true
##
#
# Represents a gem of name +name+ at +version+ of +platform+. These
# wrap the data returned from the indexes.

class Gem::NameTuple
  def initialize(name, version, platform="ruby")
    @name = name
    @version = version

    unless platform.kind_of? Gem::Platform
      platform = "ruby" if !platform or platform.empty?
    end

    @platform = platform
  end

  attr_reader :name, :version, :platform

  ##
  # Turn an array of [name, version, platform] into an array of
  # NameTuple objects.

  def self.from_list(list)
    list.map {|t| new(*t) }
  end

  ##
  # Turn an array of NameTuple objects back into an array of
  # [name, version, platform] tuples.

  def self.to_basic(list)
    list.map {|t| t.to_a }
  end

  ##
  # A null NameTuple, ie name=nil, version=0

  def self.null
    new nil, Gem::Version.new(0), nil
  end

  ##
  # Returns the full name (name-version) of this Gem.  Platform information is
  # included if it is not the default Ruby platform.  This mimics the behavior
  # of Gem::Specification#full_name.

  def full_name
    case @platform
    when nil, 'ruby', ''
      "#{@name}-#{@version}"
    else
      "#{@name}-#{@version}-#{@platform}"
    end.dup.tap(&Gem::UNTAINT)
  end

  ##
  # Indicate if this NameTuple matches the current platform.

  def match_platform?
    Gem::Platform.match_gem? @platform, @name
  end

  ##
  # Indicate if this NameTuple is for a prerelease version.
  def prerelease?
    @version.prerelease?
  end

  ##
  # Return the name that the gemspec file would be

  def spec_name
    "#{full_name}.gemspec"
  end

  ##
  # Convert back to the [name, version, platform] tuple

  def to_a
    [@name, @version, @platform]
  end

  def inspect # :nodoc:
    "#<Gem::NameTuple #{@name}, #{@version}, #{@platform}>"
  end

  alias to_s inspect # :nodoc:

  def <=>(other)
    [@name, @version, @platform == Gem::Platform::RUBY ? -1 : 1] <=>
      [other.name, other.version,
       other.platform == Gem::Platform::RUBY ? -1 : 1]
  end

  include Comparable

  ##
  # Compare with +other+. Supports another NameTuple or an Array
  # in the [name, version, platform] format.

  def ==(other)
    case other
    when self.class
      @name == other.name and
        @version == other.version and
        @platform == other.platform
    when Array
      to_a == other
    else
      false
    end
  end

  alias_method :eql?, :==

  def hash
    to_a.hash
  end
end
# frozen_string_literal: true
##
# The Version class processes string versions into comparable
# values. A version string should normally be a series of numbers
# separated by periods. Each part (digits separated by periods) is
# considered its own number, and these are used for sorting. So for
# instance, 3.10 sorts higher than 3.2 because ten is greater than
# two.
#
# If any part contains letters (currently only a-z are supported) then
# that version is considered prerelease. Versions with a prerelease
# part in the Nth part sort less than versions with N-1
# parts. Prerelease parts are sorted alphabetically using the normal
# Ruby string sorting rules. If a prerelease part contains both
# letters and numbers, it will be broken into multiple parts to
# provide expected sort behavior (1.0.a10 becomes 1.0.a.10, and is
# greater than 1.0.a9).
#
# Prereleases sort between real releases (newest to oldest):
#
# 1. 1.0
# 2. 1.0.b1
# 3. 1.0.a.2
# 4. 0.9
#
# If you want to specify a version restriction that includes both prereleases
# and regular releases of the 1.x series this is the best way:
#
#   s.add_dependency 'example', '>= 1.0.0.a', '< 2.0.0'
#
# == How Software Changes
#
# Users expect to be able to specify a version constraint that gives them
# some reasonable expectation that new versions of a library will work with
# their software if the version constraint is true, and not work with their
# software if the version constraint is false.  In other words, the perfect
# system will accept all compatible versions of the library and reject all
# incompatible versions.
#
# Libraries change in 3 ways (well, more than 3, but stay focused here!).
#
# 1. The change may be an implementation detail only and have no effect on
#    the client software.
# 2. The change may add new features, but do so in a way that client software
#    written to an earlier version is still compatible.
# 3. The change may change the public interface of the library in such a way
#    that old software is no longer compatible.
#
# Some examples are appropriate at this point.  Suppose I have a Stack class
# that supports a <tt>push</tt> and a <tt>pop</tt> method.
#
# === Examples of Category 1 changes:
#
# * Switch from an array based implementation to a linked-list based
#   implementation.
# * Provide an automatic (and transparent) backing store for large stacks.
#
# === Examples of Category 2 changes might be:
#
# * Add a <tt>depth</tt> method to return the current depth of the stack.
# * Add a <tt>top</tt> method that returns the current top of stack (without
#   changing the stack).
# * Change <tt>push</tt> so that it returns the item pushed (previously it
#   had no usable return value).
#
# === Examples of Category 3 changes might be:
#
# * Changes <tt>pop</tt> so that it no longer returns a value (you must use
#   <tt>top</tt> to get the top of the stack).
# * Rename the methods to <tt>push_item</tt> and <tt>pop_item</tt>.
#
# == RubyGems Rational Versioning
#
# * Versions shall be represented by three non-negative integers, separated
#   by periods (e.g. 3.1.4).  The first integers is the "major" version
#   number, the second integer is the "minor" version number, and the third
#   integer is the "build" number.
#
# * A category 1 change (implementation detail) will increment the build
#   number.
#
# * A category 2 change (backwards compatible) will increment the minor
#   version number and reset the build number.
#
# * A category 3 change (incompatible) will increment the major build number
#   and reset the minor and build numbers.
#
# * Any "public" release of a gem should have a different version.  Normally
#   that means incrementing the build number.  This means a developer can
#   generate builds all day long, but as soon as they make a public release,
#   the version must be updated.
#
# === Examples
#
# Let's work through a project lifecycle using our Stack example from above.
#
# Version 0.0.1:: The initial Stack class is release.
# Version 0.0.2:: Switched to a linked=list implementation because it is
#                 cooler.
# Version 0.1.0:: Added a <tt>depth</tt> method.
# Version 1.0.0:: Added <tt>top</tt> and made <tt>pop</tt> return nil
#                 (<tt>pop</tt> used to return the  old top item).
# Version 1.1.0:: <tt>push</tt> now returns the value pushed (it used it
#                 return nil).
# Version 1.1.1:: Fixed a bug in the linked list implementation.
# Version 1.1.2:: Fixed a bug introduced in the last fix.
#
# Client A needs a stack with basic push/pop capability.  They write to the
# original interface (no <tt>top</tt>), so their version constraint looks like:
#
#   gem 'stack', '>= 0.0'
#
# Essentially, any version is OK with Client A.  An incompatible change to
# the library will cause them grief, but they are willing to take the chance
# (we call Client A optimistic).
#
# Client B is just like Client A except for two things: (1) They use the
# <tt>depth</tt> method and (2) they are worried about future
# incompatibilities, so they write their version constraint like this:
#
#   gem 'stack', '~> 0.1'
#
# The <tt>depth</tt> method was introduced in version 0.1.0, so that version
# or anything later is fine, as long as the version stays below version 1.0
# where incompatibilities are introduced.  We call Client B pessimistic
# because they are worried about incompatible future changes (it is OK to be
# pessimistic!).
#
# == Preventing Version Catastrophe:
#
# From: http://blog.zenspider.com/2008/10/rubygems-howto-preventing-cata.html
#
# Let's say you're depending on the fnord gem version 2.y.z. If you
# specify your dependency as ">= 2.0.0" then, you're good, right? What
# happens if fnord 3.0 comes out and it isn't backwards compatible
# with 2.y.z? Your stuff will break as a result of using ">=". The
# better route is to specify your dependency with an "approximate" version
# specifier ("~>"). They're a tad confusing, so here is how the dependency
# specifiers work:
#
#   Specification From  ... To (exclusive)
#   ">= 3.0"      3.0   ... &infin;
#   "~> 3.0"      3.0   ... 4.0
#   "~> 3.0.0"    3.0.0 ... 3.1
#   "~> 3.5"      3.5   ... 4.0
#   "~> 3.5.0"    3.5.0 ... 3.6
#   "~> 3"        3.0   ... 4.0
#
# For the last example, single-digit versions are automatically extended with
# a zero to give a sensible result.

class Gem::Version
  autoload :Requirement, File.expand_path('requirement', __dir__)

  include Comparable

  VERSION_PATTERN = '[0-9]+(?>\.[0-9a-zA-Z]+)*(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?'.freeze # :nodoc:
  ANCHORED_VERSION_PATTERN = /\A\s*(#{VERSION_PATTERN})?\s*\z/.freeze # :nodoc:

  ##
  # A string representation of this Version.

  def version
    @version.dup
  end

  alias to_s version

  ##
  # True if the +version+ string matches RubyGems' requirements.

  def self.correct?(version)
    unless Gem::Deprecate.skip
      warn "nil versions are discouraged and will be deprecated in Rubygems 4" if version.nil?
    end

    !!(version.to_s =~ ANCHORED_VERSION_PATTERN)
  end

  ##
  # Factory method to create a Version object. Input may be a Version
  # or a String. Intended to simplify client code.
  #
  #   ver1 = Version.create('1.3.17')   # -> (Version object)
  #   ver2 = Version.create(ver1)       # -> (ver1)
  #   ver3 = Version.create(nil)        # -> nil

  def self.create(input)
    if self === input # check yourself before you wreck yourself
      input
    elsif input.nil?
      nil
    else
      new input
    end
  end

  @@all = {}
  @@bump = {}
  @@release = {}

  def self.new(version) # :nodoc:
    return super unless Gem::Version == self

    @@all[version] ||= super
  end

  ##
  # Constructs a Version from the +version+ string.  A version string is a
  # series of digits or ASCII letters separated by dots.

  def initialize(version)
    unless self.class.correct?(version)
      raise ArgumentError, "Malformed version number string #{version}"
    end

    # If version is an empty string convert it to 0
    version = 0 if version.is_a?(String) && version =~ /\A\s*\Z/

    @version = version.to_s.strip.gsub("-",".pre.")
    @segments = nil
  end

  ##
  # Return a new version object where the next to the last revision
  # number is one greater (e.g., 5.3.1 => 5.4).
  #
  # Pre-release (alpha) parts, e.g, 5.3.1.b.2 => 5.4, are ignored.

  def bump
    @@bump[self] ||= begin
                       segments = self.segments
                       segments.pop while segments.any? {|s| String === s }
                       segments.pop if segments.size > 1

                       segments[-1] = segments[-1].succ
                       self.class.new segments.join(".")
                     end
  end

  ##
  # A Version is only eql? to another version if it's specified to the
  # same precision. Version "1.0" is not the same as version "1".

  def eql?(other)
    self.class === other and @version == other._version
  end

  def hash # :nodoc:
    canonical_segments.hash
  end

  def init_with(coder) # :nodoc:
    yaml_initialize coder.tag, coder.map
  end

  def inspect # :nodoc:
    "#<#{self.class} #{version.inspect}>"
  end

  ##
  # Dump only the raw version string, not the complete object. It's a
  # string for backwards (RubyGems 1.3.5 and earlier) compatibility.

  def marshal_dump
    [version]
  end

  ##
  # Load custom marshal format. It's a string for backwards (RubyGems
  # 1.3.5 and earlier) compatibility.

  def marshal_load(array)
    initialize array[0]
  end

  def yaml_initialize(tag, map) # :nodoc:
    @version = map['version']
    @segments = nil
    @hash = nil
  end

  def to_yaml_properties # :nodoc:
    ["@version"]
  end

  def encode_with(coder) # :nodoc:
    coder.add 'version', @version
  end

  ##
  # A version is considered a prerelease if it contains a letter.

  def prerelease?
    unless instance_variable_defined? :@prerelease
      @prerelease = !!(@version =~ /[a-zA-Z]/)
    end
    @prerelease
  end

  def pretty_print(q) # :nodoc:
    q.text "Gem::Version.new(#{version.inspect})"
  end

  ##
  # The release for this version (e.g. 1.2.0.a -> 1.2.0).
  # Non-prerelease versions return themselves.

  def release
    @@release[self] ||= if prerelease?
                          segments = self.segments
                          segments.pop while segments.any? {|s| String === s }
                          self.class.new segments.join('.')
                        else
                          self
                        end
  end

  def segments # :nodoc:
    _segments.dup
  end

  ##
  # A recommended version for use with a ~> Requirement.

  def approximate_recommendation
    segments = self.segments

    segments.pop    while segments.any? {|s| String === s }
    segments.pop    while segments.size > 2
    segments.push 0 while segments.size < 2

    recommendation = "~> #{segments.join(".")}"
    recommendation += ".a" if prerelease?
    recommendation
  end

  ##
  # Compares this version with +other+ returning -1, 0, or 1 if the
  # other version is larger, the same, or smaller than this
  # one. Attempts to compare to something that's not a
  # <tt>Gem::Version</tt> return +nil+.

  def <=>(other)
    return unless Gem::Version === other
    return 0 if @version == other._version || canonical_segments == other.canonical_segments

    lhsegments = canonical_segments
    rhsegments = other.canonical_segments

    lhsize = lhsegments.size
    rhsize = rhsegments.size
    limit  = (lhsize > rhsize ? lhsize : rhsize) - 1

    i = 0

    while i <= limit
      lhs, rhs = lhsegments[i] || 0, rhsegments[i] || 0
      i += 1

      next      if lhs == rhs
      return -1 if String  === lhs && Numeric === rhs
      return  1 if Numeric === lhs && String  === rhs

      return lhs <=> rhs
    end

    return 0
  end

  def canonical_segments
    @canonical_segments ||=
      _split_segments.map! do |segments|
        segments.reverse_each.drop_while {|s| s == 0 }.reverse
      end.reduce(&:concat)
  end

  def freeze
    prerelease?
    canonical_segments
    super
  end

  protected

  def _version
    @version
  end

  def _segments
    # segments is lazy so it can pick up version values that come from
    # old marshaled versions, which don't go through marshal_load.
    # since this version object is cached in @@all, its @segments should be frozen

    @segments ||= @version.scan(/[0-9]+|[a-z]+/i).map do |s|
      /^\d+$/ =~ s ? s.to_i : s
    end.freeze
  end

  def _split_segments
    string_start = _segments.index {|s| s.is_a?(String) }
    string_segments = segments
    numeric_segments = string_segments.slice!(0, string_start || string_segments.size)
    return numeric_segments, string_segments
  end
end
# frozen_string_literal: true

module Gem::BundlerVersionFinder
  def self.bundler_version
    version, _ = bundler_version_with_reason

    return unless version

    Gem::Version.new(version)
  end

  def self.bundler_version_with_reason
    if v = ENV["BUNDLER_VERSION"]
      return [v, "`$BUNDLER_VERSION`"]
    end
    if v = bundle_update_bundler_version
      return if v == true
      return [v, "`bundle update --bundler`"]
    end
    v, lockfile = lockfile_version
    if v
      return [v, "your #{lockfile}"]
    end
  end

  def self.missing_version_message
    return unless vr = bundler_version_with_reason
    <<-EOS
Could not find 'bundler' (#{vr.first}) required by #{vr.last}.
To update to the latest version installed on your system, run `bundle update --bundler`.
To install the missing version, run `gem install bundler:#{vr.first}`
    EOS
  end

  def self.compatible?(spec)
    return true unless spec.name == "bundler".freeze
    return true unless bundler_version = self.bundler_version

    spec.version.segments.first == bundler_version.segments.first
  end

  def self.filter!(specs)
    return unless bundler_version = self.bundler_version

    specs.reject! {|spec| spec.version.segments.first != bundler_version.segments.first }

    exact_match_index = specs.find_index {|spec| spec.version == bundler_version }
    return unless exact_match_index

    specs.unshift(specs.delete_at(exact_match_index))
  end

  def self.bundle_update_bundler_version
    return unless File.basename($0) == "bundle".freeze
    return unless "update".start_with?(ARGV.first || " ")
    bundler_version = nil
    update_index = nil
    ARGV.each_with_index do |a, i|
      if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN
        bundler_version = a
      end
      next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/
      bundler_version = $1 || true
      update_index = i
    end
    bundler_version
  end
  private_class_method :bundle_update_bundler_version

  def self.lockfile_version
    return unless lockfile = lockfile_contents
    lockfile, contents = lockfile
    lockfile ||= "lockfile"
    regexp = /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/
    return unless contents =~ regexp
    [$1, lockfile]
  end
  private_class_method :lockfile_version

  def self.lockfile_contents
    gemfile = ENV["BUNDLE_GEMFILE"]
    gemfile = nil if gemfile && gemfile.empty?

    unless gemfile
      begin
        Gem::Util.traverse_parents(Dir.pwd) do |directory|
          next unless gemfile = Gem::GEM_DEP_FILES.find {|f| File.file?(f.tap(&Gem::UNTAINT)) }

          gemfile = File.join directory, gemfile
          break
        end
      rescue Errno::ENOENT
        return
      end
    end

    return unless gemfile

    lockfile = case gemfile
               when "gems.rb" then "gems.locked"
               else "#{gemfile}.lock"
               end.dup.tap(&Gem::UNTAINT)

    return unless File.file?(lockfile)

    [lockfile, File.read(lockfile)]
  end
  private_class_method :lockfile_contents
end
# frozen_string_literal: true
# Copyright (c) 2003, 2004 Jim Weirich, 2009 Eric Hodel
#
# 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_relative '../rubygems'
require_relative 'package'
require 'rake/packagetask'

##
# Create a package based upon a Gem::Specification.  Gem packages, as well as
# zip files and tar/gzipped packages can be produced by this task.
#
# In addition to the Rake targets generated by Rake::PackageTask, a
# Gem::PackageTask will also generate the following tasks:
#
# [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.gem"</b>]
#   Create a RubyGems package with the given name and version.
#
# Example using a Gem::Specification:
#
#   require 'rubygems'
#   require 'rubygems/package_task'
#
#   spec = Gem::Specification.new do |s|
#     s.summary = "Ruby based make-like utility."
#     s.name = 'rake'
#     s.version = PKG_VERSION
#     s.requirements << 'none'
#     s.files = PKG_FILES
#     s.description = <<-EOF
#   Rake is a Make-like program implemented in Ruby. Tasks
#   and dependencies are specified in standard Ruby syntax.
#     EOF
#   end
#
#   Gem::PackageTask.new(spec) do |pkg|
#     pkg.need_zip = true
#     pkg.need_tar = true
#   end

class Gem::PackageTask < Rake::PackageTask
  ##
  # Ruby Gem::Specification containing the metadata for this package.  The
  # name, version and package_files are automatically determined from the
  # gemspec and don't need to be explicitly provided.

  attr_accessor :gem_spec

  ##
  # Create a Gem Package task library.  Automatically define the gem if a
  # block is given.  If no block is supplied, then #define needs to be called
  # to define the task.

  def initialize(gem_spec)
    init gem_spec
    yield self if block_given?
    define if block_given?
  end

  ##
  # Initialization tasks without the "yield self" or define operations.

  def init(gem)
    super gem.full_name, :noversion
    @gem_spec = gem
    @package_files += gem_spec.files if gem_spec.files
    @fileutils_output = $stdout
  end

  ##
  # Create the Rake tasks and actions specified by this Gem::PackageTask.
  # (+define+ is automatically called if a block is given to +new+).

  def define
    super

    gem_file = File.basename gem_spec.cache_file
    gem_path = File.join package_dir, gem_file
    gem_dir  = File.join package_dir, gem_spec.full_name

    task :package => [:gem]

    directory package_dir
    directory gem_dir

    desc "Build the gem file #{gem_file}"
    task :gem => [gem_path]

    trace = Rake.application.options.trace
    Gem.configuration.verbose = trace

    file gem_path => [package_dir, gem_dir] + @gem_spec.files do
      chdir(gem_dir) do
        when_writing "Creating #{gem_spec.file_name}" do
          Gem::Package.build gem_spec

          verbose trace do
            mv gem_file, '..'
          end
        end
      end
    end
  end
end
require_relative 'user_interaction'

class Gem::SpecificationPolicy
  include Gem::UserInteraction

  VALID_NAME_PATTERN = /\A[a-zA-Z0-9\.\-\_]+\z/.freeze # :nodoc:

  SPECIAL_CHARACTERS = /\A[#{Regexp.escape('.-_')}]+/.freeze # :nodoc:

  VALID_URI_PATTERN = %r{\Ahttps?:\/\/([^\s:@]+:[^\s:@]*@)?[A-Za-z\d\-]+(\.[A-Za-z\d\-]+)+\.?(:\d{1,5})?([\/?]\S*)?\z}.freeze # :nodoc:

  METADATA_LINK_KEYS = %w[
    bug_tracker_uri
    changelog_uri
    documentation_uri
    homepage_uri
    mailing_list_uri
    source_code_uri
    wiki_uri
    funding_uri
  ].freeze # :nodoc:

  def initialize(specification)
    @warnings = 0

    @specification = specification
  end

  ##
  # If set to true, run packaging-specific checks, as well.

  attr_accessor :packaging

  ##
  # Does a sanity check on the specification.
  #
  # Raises InvalidSpecificationException if the spec does not pass the
  # checks.
  #
  # It also performs some validations that do not raise but print warning
  # messages instead.

  def validate(strict = false)
    validate_required!

    validate_optional(strict) if packaging || strict

    true
  end

  ##
  # Does a sanity check on the specification.
  #
  # Raises InvalidSpecificationException if the spec does not pass the
  # checks.
  #
  # Only runs checks that are considered necessary for the specification to be
  # functional.

  def validate_required!
    validate_nil_attributes

    validate_rubygems_version

    validate_required_attributes

    validate_name

    validate_require_paths

    @specification.keep_only_files_and_directories

    validate_non_files

    validate_self_inclusion_in_files_list

    validate_specification_version

    validate_platform

    validate_array_attributes

    validate_authors_field

    validate_metadata

    validate_licenses_length

    validate_lazy_metadata

    validate_duplicate_dependencies
  end

  def validate_optional(strict)
    validate_licenses

    validate_permissions

    validate_values

    validate_dependencies

    validate_extensions

    validate_removed_attributes

    if @warnings > 0
      if strict
        error "specification has warnings"
      else
        alert_warning help_text
      end
    end
  end

  ##
  # Implementation for Specification#validate_metadata

  def validate_metadata
    metadata = @specification.metadata

    unless Hash === metadata
      error 'metadata must be a hash'
    end

    metadata.each do |key, value|
      entry = "metadata['#{key}']"
      if !key.kind_of?(String)
        error "metadata keys must be a String"
      end

      if key.size > 128
        error "metadata key is too large (#{key.size} > 128)"
      end

      if !value.kind_of?(String)
        error "#{entry} value must be a String"
      end

      if value.size > 1024
        error "#{entry} value is too large (#{value.size} > 1024)"
      end

      if METADATA_LINK_KEYS.include? key
        if value !~ VALID_URI_PATTERN
          error "#{entry} has invalid link: #{value.inspect}"
        end
      end
    end
  end

  ##
  # Checks that no duplicate dependencies are specified.

  def validate_duplicate_dependencies # :nodoc:
    # NOTE: see REFACTOR note in Gem::Dependency about types - this might be brittle
    seen = Gem::Dependency::TYPES.inject({}) {|types, type| types.merge({ type => {}}) }

    error_messages = []
    @specification.dependencies.each do |dep|
      if prev = seen[dep.type][dep.name]
        error_messages << <<-MESSAGE
duplicate dependency on #{dep}, (#{prev.requirement}) use:
    add_#{dep.type}_dependency '#{dep.name}', '#{dep.requirement}', '#{prev.requirement}'
        MESSAGE
      end

      seen[dep.type][dep.name] = dep
    end
    if error_messages.any?
      error error_messages.join
    end
  end

  ##
  # Checks that dependencies use requirements as we recommend.  Warnings are
  # issued when dependencies are open-ended or overly strict for semantic
  # versioning.

  def validate_dependencies # :nodoc:
    warning_messages = []
    @specification.dependencies.each do |dep|
      prerelease_dep = dep.requirements_list.any? do |req|
        Gem::Requirement.new(req).prerelease?
      end

      warning_messages << "prerelease dependency on #{dep} is not recommended" if
          prerelease_dep && !@specification.version.prerelease?

      open_ended = dep.requirement.requirements.all? do |op, version|
        not version.prerelease? and (op == '>' or op == '>=')
      end

      if open_ended
        op, dep_version = dep.requirement.requirements.first

        segments = dep_version.segments

        base = segments.first 2

        recommendation = if (op == '>' || op == '>=') && segments == [0]
                           "  use a bounded requirement, such as '~> x.y'"
                         else
                           bugfix = if op == '>'
                                      ", '> #{dep_version}'"
                                    elsif op == '>=' and base != segments
                                      ", '>= #{dep_version}'"
                                    end

                           "  if #{dep.name} is semantically versioned, use:\n" \
                           "    add_#{dep.type}_dependency '#{dep.name}', '~> #{base.join '.'}'#{bugfix}"
                         end

        warning_messages << ["open-ended dependency on #{dep} is not recommended", recommendation].join("\n") + "\n"
      end
    end
    if warning_messages.any?
      warning_messages.each {|warning_message| warning warning_message }
    end
  end

  ##
  # Issues a warning for each file to be packaged which is world-readable.
  #
  # Implementation for Specification#validate_permissions

  def validate_permissions
    return if Gem.win_platform?

    @specification.files.each do |file|
      next unless File.file?(file)
      next if File.stat(file).mode & 0444 == 0444
      warning "#{file} is not world-readable"
    end

    @specification.executables.each do |name|
      exec = File.join @specification.bindir, name
      next unless File.file?(exec)
      next if File.stat(exec).executable?
      warning "#{exec} is not executable"
    end
  end

  private

  def validate_nil_attributes
    nil_attributes = Gem::Specification.non_nil_attributes.select do |attrname|
      @specification.instance_variable_get("@#{attrname}").nil?
    end
    return if nil_attributes.empty?
    error "#{nil_attributes.join ', '} must not be nil"
  end

  def validate_rubygems_version
    return unless packaging

    rubygems_version = @specification.rubygems_version

    return if rubygems_version == Gem::VERSION

    error "expected RubyGems version #{Gem::VERSION}, was #{rubygems_version}"
  end

  def validate_required_attributes
    Gem::Specification.required_attributes.each do |symbol|
      unless @specification.send symbol
        error "missing value for attribute #{symbol}"
      end
    end
  end

  def validate_name
    name = @specification.name

    if !name.is_a?(String)
      error "invalid value for attribute name: \"#{name.inspect}\" must be a string"
    elsif name !~ /[a-zA-Z]/
      error "invalid value for attribute name: #{name.dump} must include at least one letter"
    elsif name !~ VALID_NAME_PATTERN
      error "invalid value for attribute name: #{name.dump} can only include letters, numbers, dashes, and underscores"
    elsif name =~ SPECIAL_CHARACTERS
      error "invalid value for attribute name: #{name.dump} can not begin with a period, dash, or underscore"
    end
  end

  def validate_require_paths
    return unless @specification.raw_require_paths.empty?

    error 'specification must have at least one require_path'
  end

  def validate_non_files
    return unless packaging

    non_files = @specification.files.reject {|x| File.file?(x) || File.symlink?(x) }

    unless non_files.empty?
      error "[\"#{non_files.join "\", \""}\"] are not files"
    end
  end

  def validate_self_inclusion_in_files_list
    file_name = @specification.file_name

    return unless @specification.files.include?(file_name)

    error "#{@specification.full_name} contains itself (#{file_name}), check your files list"
  end

  def validate_specification_version
    return if @specification.specification_version.is_a?(Integer)

    error 'specification_version must be an Integer (did you mean version?)'
  end

  def validate_platform
    platform = @specification.platform

    case platform
    when Gem::Platform, Gem::Platform::RUBY # ok
    else
      error "invalid platform #{platform.inspect}, see Gem::Platform"
    end
  end

  def validate_array_attributes
    Gem::Specification.array_attributes.each do |field|
      validate_array_attribute(field)
    end
  end

  def validate_array_attribute(field)
    val = @specification.send(field)
    klass = case field
            when :dependencies then
              Gem::Dependency
            else
              String
            end

    unless Array === val and val.all? {|x| x.kind_of?(klass) }
      error "#{field} must be an Array of #{klass}"
    end
  end

  def validate_authors_field
    return unless @specification.authors.empty?

    error "authors may not be empty"
  end

  def validate_licenses_length
    licenses = @specification.licenses

    licenses.each do |license|
      if license.length > 64
        error "each license must be 64 characters or less"
      end
    end
  end

  def validate_licenses
    licenses = @specification.licenses

    licenses.each do |license|
      if !Gem::Licenses.match?(license)
        suggestions = Gem::Licenses.suggestions(license)
        message = <<-WARNING
license value '#{license}' is invalid.  Use a license identifier from
http://spdx.org/licenses or '#{Gem::Licenses::NONSTANDARD}' for a nonstandard license.
        WARNING
        message += "Did you mean #{suggestions.map {|s| "'#{s}'" }.join(', ')}?\n" unless suggestions.nil?
        warning(message)
      end
    end

    warning <<-WARNING if licenses.empty?
licenses is empty, but is recommended.  Use a license identifier from
http://spdx.org/licenses or '#{Gem::Licenses::NONSTANDARD}' for a nonstandard license.
    WARNING
  end

  LAZY = '"FIxxxXME" or "TOxxxDO"'.gsub(/xxx/, '')
  LAZY_PATTERN = /\AFI XME|\ATO DO/x.freeze
  HOMEPAGE_URI_PATTERN = /\A[a-z][a-z\d+.-]*:/i.freeze

  def validate_lazy_metadata
    unless @specification.authors.grep(LAZY_PATTERN).empty?
      error "#{LAZY} is not an author"
    end

    unless Array(@specification.email).grep(LAZY_PATTERN).empty?
      error "#{LAZY} is not an email"
    end

    if @specification.description =~ LAZY_PATTERN
      error "#{LAZY} is not a description"
    end

    if @specification.summary =~ LAZY_PATTERN
      error "#{LAZY} is not a summary"
    end

    homepage = @specification.homepage

    # Make sure a homepage is valid HTTP/HTTPS URI
    if homepage and not homepage.empty?
      require 'uri'
      begin
        homepage_uri = URI.parse(homepage)
        unless [URI::HTTP, URI::HTTPS].member? homepage_uri.class
          error "\"#{homepage}\" is not a valid HTTP URI"
        end
      rescue URI::InvalidURIError
        error "\"#{homepage}\" is not a valid HTTP URI"
      end
    end
  end

  def validate_values
    %w[author homepage summary files].each do |attribute|
      validate_attribute_present(attribute)
    end

    if @specification.description == @specification.summary
      warning "description and summary are identical"
    end

    # TODO: raise at some given date
    warning "deprecated autorequire specified" if @specification.autorequire

    @specification.executables.each do |executable|
      validate_shebang_line_in(executable)
    end

    @specification.files.select {|f| File.symlink?(f) }.each do |file|
      warning "#{file} is a symlink, which is not supported on all platforms"
    end
  end

  def validate_attribute_present(attribute)
    value = @specification.send attribute
    warning("no #{attribute} specified") if value.nil? || value.empty?
  end

  def validate_shebang_line_in(executable)
    executable_path = File.join(@specification.bindir, executable)
    return if File.read(executable_path, 2) == '#!'

    warning "#{executable_path} is missing #! line"
  end

  def validate_removed_attributes # :nodoc:
    @specification.removed_method_calls.each do |attr|
      warning("#{attr} is deprecated and ignored. Please remove this from your gemspec to ensure that your gem continues to build in the future.")
    end
  end

  def validate_extensions # :nodoc:
    require_relative 'ext'
    builder = Gem::Ext::Builder.new(@specification)

    rake_extension = @specification.extensions.any? {|s| builder.builder_for(s) == Gem::Ext::RakeBuilder }
    rake_dependency = @specification.dependencies.any? {|d| d.name == 'rake' }

    warning <<-WARNING if rake_extension && !rake_dependency
You have specified rake based extension, but rake is not added as dependency. It is recommended to add rake as a dependency in gemspec since there's no guarantee rake will be already installed.
    WARNING
  end

  def warning(statement) # :nodoc:
    @warnings += 1

    alert_warning statement
  end

  def error(statement) # :nodoc:
    raise Gem::InvalidSpecificationException, statement
  ensure
    alert_warning help_text
  end

  def help_text # :nodoc:
    "See https://guides.rubygems.org/specification-reference/ for help"
  end
end
# frozen_string_literal: true
require_relative "deprecate"

##
# Available list of platforms for targeting Gem installations.
#
# See `gem help platform` for information on platform matching.

class Gem::Platform
  @local = nil

  attr_accessor :cpu, :os, :version

  def self.local
    arch = RbConfig::CONFIG['arch']
    arch = "#{arch}_60" if arch =~ /mswin(?:32|64)$/
    @local ||= new(arch)
  end

  def self.match(platform)
    match_platforms?(platform, Gem.platforms)
  end

  def self.match_platforms?(platform, platforms)
    platforms.any? do |local_platform|
      platform.nil? or
        local_platform == platform or
        (local_platform != Gem::Platform::RUBY and local_platform =~ platform)
    end
  end
  private_class_method :match_platforms?

  def self.match_spec?(spec)
    match_gem?(spec.platform, spec.name)
  end

  def self.match_gem?(platform, gem_name)
    # Note: this method might be redefined by Ruby implementations to
    # customize behavior per RUBY_ENGINE, gem_name or other criteria.
    match_platforms?(platform, Gem.platforms)
  end

  def self.installable?(spec)
    if spec.respond_to? :installable_platform?
      spec.installable_platform?
    else
      match_spec? spec
    end
  end

  def self.new(arch) # :nodoc:
    case arch
    when Gem::Platform::CURRENT then
      Gem::Platform.local
    when Gem::Platform::RUBY, nil, '' then
      Gem::Platform::RUBY
    else
      super
    end
  end

  def initialize(arch)
    case arch
    when Array then
      @cpu, @os, @version = arch
    when String then
      arch = arch.split '-'

      if arch.length > 2 and arch.last !~ /\d/ # reassemble x86-linux-gnu
        extra = arch.pop
        arch.last << "-#{extra}"
      end

      cpu = arch.shift

      @cpu = case cpu
             when /i\d86/ then 'x86'
             else cpu
             end

      if arch.length == 2 and arch.last =~ /^\d+(\.\d+)?$/ # for command-line
        @os, @version = arch
        return
      end

      os, = arch
      @cpu, os = nil, cpu if os.nil? # legacy jruby

      @os, @version = case os
                      when /aix(\d+)?/ then             [ 'aix',       $1  ]
                      when /cygwin/ then                [ 'cygwin',    nil ]
                      when /darwin(\d+)?/ then          [ 'darwin',    $1  ]
                      when /^macruby$/ then             [ 'macruby',   nil ]
                      when /freebsd(\d+)?/ then         [ 'freebsd',   $1  ]
                      when /hpux(\d+)?/ then            [ 'hpux',      $1  ]
                      when /^java$/, /^jruby$/ then     [ 'java',      nil ]
                      when /^java([\d.]*)/ then         [ 'java',      $1  ]
                      when /^dalvik(\d+)?$/ then        [ 'dalvik',    $1  ]
                      when /^dotnet$/ then              [ 'dotnet',    nil ]
                      when /^dotnet([\d.]*)/ then       [ 'dotnet',    $1  ]
                      when /linux-?((?!gnu)\w+)?/ then  [ 'linux',     $1  ]
                      when /mingw32/ then               [ 'mingw32',   nil ]
                      when /mingw-?(\w+)?/ then         [ 'mingw',     $1  ]
                      when /(mswin\d+)(\_(\d+))?/ then
                        os, version = $1, $3
                        @cpu = 'x86' if @cpu.nil? and os =~ /32$/
                        [os, version]
                      when /netbsdelf/ then             [ 'netbsdelf', nil ]
                      when /openbsd(\d+\.\d+)?/ then    [ 'openbsd',   $1  ]
                      when /bitrig(\d+\.\d+)?/ then     [ 'bitrig',    $1  ]
                      when /solaris(\d+\.\d+)?/ then    [ 'solaris',   $1  ]
                      # test
                      when /^(\w+_platform)(\d+)?/ then [ $1,          $2  ]
                      else                              [ 'unknown',   nil ]
                      end
    when Gem::Platform then
      @cpu = arch.cpu
      @os = arch.os
      @version = arch.version
    else
      raise ArgumentError, "invalid argument #{arch.inspect}"
    end
  end

  def to_a
    [@cpu, @os, @version]
  end

  def to_s
    to_a.compact.join '-'
  end

  ##
  # Is +other+ equal to this platform?  Two platforms are equal if they have
  # the same CPU, OS and version.

  def ==(other)
    self.class === other and to_a == other.to_a
  end

  alias :eql? :==

  def hash # :nodoc:
    to_a.hash
  end

  ##
  # Does +other+ match this platform?  Two platforms match if they have the
  # same CPU, or either has a CPU of 'universal', they have the same OS, and
  # they have the same version, or either has no version.
  #
  # Additionally, the platform will match if the local CPU is 'arm' and the
  # other CPU starts with "arm" (for generic ARM family support).

  def ===(other)
    return nil unless Gem::Platform === other

    # cpu
    ([nil,'universal'].include?(@cpu) or [nil, 'universal'].include?(other.cpu) or @cpu == other.cpu or
    (@cpu == 'arm' and other.cpu.start_with?("arm"))) and

    # os
    @os == other.os and

    # version
    (@version.nil? or other.version.nil? or @version == other.version)
  end

  ##
  # Does +other+ match this platform?  If +other+ is a String it will be
  # converted to a Gem::Platform first.  See #=== for matching rules.

  def =~(other)
    case other
    when Gem::Platform then # nop
    when String then
      # This data is from http://gems.rubyforge.org/gems/yaml on 19 Aug 2007
      other = case other
              when /^i686-darwin(\d)/     then ['x86',       'darwin',  $1    ]
              when /^i\d86-linux/         then ['x86',       'linux',   nil   ]
              when 'java', 'jruby'        then [nil,         'java',    nil   ]
              when /^dalvik(\d+)?$/       then [nil,         'dalvik',  $1    ]
              when /dotnet(\-(\d+\.\d+))?/ then ['universal','dotnet',  $2    ]
              when /mswin32(\_(\d+))?/    then ['x86',       'mswin32', $2    ]
              when /mswin64(\_(\d+))?/    then ['x64',       'mswin64', $2    ]
              when 'powerpc-darwin'       then ['powerpc',   'darwin',  nil   ]
              when /powerpc-darwin(\d)/   then ['powerpc',   'darwin',  $1    ]
              when /sparc-solaris2.8/     then ['sparc',     'solaris', '2.8' ]
              when /universal-darwin(\d)/ then ['universal', 'darwin',  $1    ]
              else                             other
              end

      other = Gem::Platform.new other
    else
      return nil
    end

    self === other
  end

  ##
  # A pure-Ruby gem that may use Gem::Specification#extensions to build
  # binary files.

  RUBY = 'ruby'.freeze

  ##
  # A platform-specific gem that is built for the packaging Ruby's platform.
  # This will be replaced with Gem::Platform::local.

  CURRENT = 'current'.freeze
end
# 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 <tt>options</tt> are:
#
# <tt>:force</tt> :: forced operation (rewrite files if exist, remove
#                    directories if not empty, etc.);
# <tt>:verbose</tt> :: print command to be run, in bash syntax, before
#                      performing it;
# <tt>:preserve</tt> :: preserve object's group, user and modification
#                       time on copying;
# <tt>:noop</tt> :: no changes are made (usable in combination with
#                   <tt>:verbose</tt> 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 <tt>:verbose</tt> 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 <tt>:noop</tt> 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 <tt>:noop</tt> and
# <tt>:verbose</tt> flags to methods in FileUtils.
#
module FileUtils
  VERSION = "1.5.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)

      # optimize for the most common case
      begin
        fu_mkdir path, mode
        next
      rescue SystemCallError
        next if File.directory?(path)
      end

      stack = []
      until path == stack.last   # dirname("/")=="/", dirname("C:/")=="C:/"
        stack.push path
        path = File.dirname(path)
        break if File.directory?(path)
      end
      stack.pop if path == stack.last   # root directory should exist
      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 <tt>force</tt> 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 <tt>secure: false</tt>.
  #
  # 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)

    if RUBY_VERSION > "2.4"
      sa = String.new(capacity: bsize)
      sb = String.new(capacity: bsize)
    else
      sa = String.new
      sb = String.new
    end

    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 = if Dir.respond_to?(:children)
        Dir.children(path, **opts)
      else
        Dir.entries(path(), **opts)
           .reject {|n| n == '.' or n == '..' }
      end

      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 <tt>:verbose</tt> 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 <tt>:noop</tt> 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 <tt>:noop</tt> and <tt>:verbose</tt> 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
# frozen_string_literal: false
require 'syslog'
require 'logger'

##
# Syslog::Logger is a Logger work-alike that logs via syslog instead of to a
# file.  You can use Syslog::Logger to aggregate logs between multiple
# machines.
#
# By default, Syslog::Logger uses the program name 'ruby', but this can be
# changed via the first argument to Syslog::Logger.new.
#
# NOTE! You can only set the Syslog::Logger program name when you initialize
# Syslog::Logger for the first time.  This is a limitation of the way
# Syslog::Logger uses syslog (and in some ways, a limitation of the way
# syslog(3) works).  Attempts to change Syslog::Logger's program name after
# the first initialization will be ignored.
#
# === Example
#
# The following will log to syslogd on your local machine:
#
#   require 'syslog/logger'
#
#   log = Syslog::Logger.new 'my_program'
#   log.info 'this line will be logged via syslog(3)'
#
# Also the facility may be set to specify the facility level which will be used:
#
#   log.info 'this line will be logged using Syslog default facility level'
#
#   log_local1 = Syslog::Logger.new 'my_program', Syslog::LOG_LOCAL1
#   log_local1.info 'this line will be logged using local1 facility level'
#
#
# You may need to perform some syslog.conf setup first.  For a BSD machine add
# the following lines to /etc/syslog.conf:
#
#  !my_program
#  *.*                                             /var/log/my_program.log
#
# Then touch /var/log/my_program.log and signal syslogd with a HUP
# (killall -HUP syslogd, on FreeBSD).
#
# If you wish to have logs automatically roll over and archive, see the
# newsyslog.conf(5) and newsyslog(8) man pages.

class Syslog::Logger
  # Default formatter for log messages.
  class Formatter
    def call severity, time, progname, msg
      clean msg
    end

    private

    ##
    # Clean up messages so they're nice and pretty.

    def clean message
      message = message.to_s.strip
      message.gsub!(/\e\[[0-9;]*m/, '') # remove useless ansi color codes
      return message
    end
  end

  ##
  # The version of Syslog::Logger you are using.

  VERSION = '2.1.0'

  ##
  # Maps Logger warning types to syslog(3) warning types.
  #
  # Messages from Ruby applications are not considered as critical as messages
  # from other system daemons using syslog(3), so most messages are reduced by
  # one level.  For example, a fatal message for Ruby's Logger is considered
  # an error for syslog(3).

  LEVEL_MAP = {
    ::Logger::UNKNOWN => Syslog::LOG_ALERT,
    ::Logger::FATAL   => Syslog::LOG_ERR,
    ::Logger::ERROR   => Syslog::LOG_WARNING,
    ::Logger::WARN    => Syslog::LOG_NOTICE,
    ::Logger::INFO    => Syslog::LOG_INFO,
    ::Logger::DEBUG   => Syslog::LOG_DEBUG,
  }

  ##
  # Returns the internal Syslog object that is initialized when the
  # first instance is created.

  def self.syslog
    @@syslog
  end

  ##
  # Specifies the internal Syslog object to be used.

  def self.syslog= syslog
    @@syslog = syslog
  end

  ##
  # Builds a methods for level +meth+.

  def self.make_methods meth
    level = ::Logger.const_get(meth.upcase)
    eval <<-EOM, nil, __FILE__, __LINE__ + 1
      def #{meth}(message = nil, &block)
        add(#{level}, message, &block)
      end

      def #{meth}?
        level <= #{level}
      end
    EOM
  end

  ##
  # :method: unknown
  #
  # Logs a +message+ at the unknown (syslog alert) log level, or logs the
  # message returned from the block.

  ##
  # :method: fatal
  #
  # Logs a +message+ at the fatal (syslog err) log level, or logs the message
  # returned from the block.

  ##
  # :method: error
  #
  # Logs a +message+ at the error (syslog warning) log level, or logs the
  # message returned from the block.

  ##
  # :method: warn
  #
  # Logs a +message+ at the warn (syslog notice) log level, or logs the
  # message returned from the block.

  ##
  # :method: info
  #
  # Logs a +message+ at the info (syslog info) log level, or logs the message
  # returned from the block.

  ##
  # :method: debug
  #
  # Logs a +message+ at the debug (syslog debug) log level, or logs the
  # message returned from the block.

  Logger::Severity::constants.each do |severity|
    make_methods severity.downcase
  end

  ##
  # Log level for Logger compatibility.

  attr_accessor :level

  # Logging formatter, as a +Proc+ that will take four arguments and
  # return the formatted message. The arguments are:
  #
  # +severity+:: The Severity of the log message.
  # +time+:: A Time instance representing when the message was logged.
  # +progname+:: The #progname configured, or passed to the logger method.
  # +msg+:: The _Object_ the user passed to the log message; not necessarily a
  #         String.
  #
  # The block should return an Object that can be written to the logging
  # device via +write+.  The default formatter is used when no formatter is
  # set.
  attr_accessor :formatter

  ##
  # The facility argument is used to specify what type of program is logging the message.

  attr_accessor :facility

  ##
  # Fills in variables for Logger compatibility.  If this is the first
  # instance of Syslog::Logger, +program_name+ may be set to change the logged
  # program name. The +facility+ may be set to specify the facility level which will be used.
  #
  # Due to the way syslog works, only one program name may be chosen.

  def initialize program_name = 'ruby', facility = nil
    @level = ::Logger::DEBUG
    @formatter = Formatter.new

    @@syslog ||= Syslog.open(program_name)

    @facility = (facility || @@syslog.facility)
  end

  ##
  # Almost duplicates Logger#add.  +progname+ is ignored.

  def add severity, message = nil, progname = nil, &block
    severity ||= ::Logger::UNKNOWN
    level <= severity and
      @@syslog.log( (LEVEL_MAP[severity] | @facility), '%s', formatter.call(severity, Time.now, progname, (message || block.call)) )
    true
  end
end
# frozen_string_literal: true
=begin
= Info
  'OpenSSL for Ruby 2' project
  Copyright (C) 2001 GOTOU YUUZOU <gotoyuzo@notwork.org>
  All rights reserved.

= Licence
  This program is licensed under the same licence as Ruby.
  (See the file 'LICENCE'.)
=end

require "openssl/buffering"
require "io/nonblock"
require "ipaddr"
require "socket"

module OpenSSL
  module SSL
    class SSLContext
      DEFAULT_PARAMS = { # :nodoc:
        :min_version => OpenSSL::SSL::TLS1_VERSION,
        :verify_mode => OpenSSL::SSL::VERIFY_PEER,
        :verify_hostname => true,
        :options => -> {
          opts = OpenSSL::SSL::OP_ALL
          opts &= ~OpenSSL::SSL::OP_DONT_INSERT_EMPTY_FRAGMENTS
          opts |= OpenSSL::SSL::OP_NO_COMPRESSION
          opts
        }.call
      }

      if defined?(OpenSSL::PKey::DH)
        DEFAULT_2048 = OpenSSL::PKey::DH.new <<-_end_of_pem_
-----BEGIN DH PARAMETERS-----
MIIBCAKCAQEA7E6kBrYiyvmKAMzQ7i8WvwVk9Y/+f8S7sCTN712KkK3cqd1jhJDY
JbrYeNV3kUIKhPxWHhObHKpD1R84UpL+s2b55+iMd6GmL7OYmNIT/FccKhTcveab
VBmZT86BZKYyf45hUF9FOuUM9xPzuK3Vd8oJQvfYMCd7LPC0taAEljQLR4Edf8E6
YoaOffgTf5qxiwkjnlVZQc3whgnEt9FpVMvQ9eknyeGB5KHfayAc3+hUAvI3/Cr3
1bNveX5wInh5GDx1FGhKBZ+s1H+aedudCm7sCgRwv8lKWYGiHzObSma8A86KG+MD
7Lo5JquQ3DlBodj3IDyPrxIv96lvRPFtAwIBAg==
-----END DH PARAMETERS-----
        _end_of_pem_
        private_constant :DEFAULT_2048

        DEFAULT_TMP_DH_CALLBACK = lambda { |ctx, is_export, keylen| # :nodoc:
          warn "using default DH parameters." if $VERBOSE
          DEFAULT_2048
        }
      end

      if !(OpenSSL::OPENSSL_VERSION.start_with?("OpenSSL") &&
           OpenSSL::OPENSSL_VERSION_NUMBER >= 0x10100000)
        DEFAULT_PARAMS.merge!(
          ciphers: %w{
            ECDHE-ECDSA-AES128-GCM-SHA256
            ECDHE-RSA-AES128-GCM-SHA256
            ECDHE-ECDSA-AES256-GCM-SHA384
            ECDHE-RSA-AES256-GCM-SHA384
            DHE-RSA-AES128-GCM-SHA256
            DHE-DSS-AES128-GCM-SHA256
            DHE-RSA-AES256-GCM-SHA384
            DHE-DSS-AES256-GCM-SHA384
            ECDHE-ECDSA-AES128-SHA256
            ECDHE-RSA-AES128-SHA256
            ECDHE-ECDSA-AES128-SHA
            ECDHE-RSA-AES128-SHA
            ECDHE-ECDSA-AES256-SHA384
            ECDHE-RSA-AES256-SHA384
            ECDHE-ECDSA-AES256-SHA
            ECDHE-RSA-AES256-SHA
            DHE-RSA-AES128-SHA256
            DHE-RSA-AES256-SHA256
            DHE-RSA-AES128-SHA
            DHE-RSA-AES256-SHA
            DHE-DSS-AES128-SHA256
            DHE-DSS-AES256-SHA256
            DHE-DSS-AES128-SHA
            DHE-DSS-AES256-SHA
            AES128-GCM-SHA256
            AES256-GCM-SHA384
            AES128-SHA256
            AES256-SHA256
            AES128-SHA
            AES256-SHA
          }.join(":"),
        )
      end

      DEFAULT_CERT_STORE = OpenSSL::X509::Store.new # :nodoc:
      DEFAULT_CERT_STORE.set_default_paths
      DEFAULT_CERT_STORE.flags = OpenSSL::X509::V_FLAG_CRL_CHECK_ALL

      # A callback invoked when DH parameters are required.
      #
      # The callback is invoked with the Session for the key exchange, an
      # flag indicating the use of an export cipher and the keylength
      # required.
      #
      # The callback must return an OpenSSL::PKey::DH instance of the correct
      # key length.

      attr_accessor :tmp_dh_callback

      # A callback invoked at connect time to distinguish between multiple
      # server names.
      #
      # The callback is invoked with an SSLSocket and a server name.  The
      # callback must return an SSLContext for the server name or nil.
      attr_accessor :servername_cb

      # call-seq:
      #    SSLContext.new           -> ctx
      #    SSLContext.new(:TLSv1)   -> ctx
      #    SSLContext.new("SSLv23") -> ctx
      #
      # Creates a new SSL context.
      #
      # If an argument is given, #ssl_version= is called with the value. Note
      # that this form is deprecated. New applications should use #min_version=
      # and #max_version= as necessary.
      def initialize(version = nil)
        self.options |= OpenSSL::SSL::OP_ALL
        self.ssl_version = version if version
      end

      ##
      # call-seq:
      #   ctx.set_params(params = {}) -> params
      #
      # Sets saner defaults optimized for the use with HTTP-like protocols.
      #
      # If a Hash _params_ is given, the parameters are overridden with it.
      # The keys in _params_ must be assignment methods on SSLContext.
      #
      # If the verify_mode is not VERIFY_NONE and ca_file, ca_path and
      # cert_store are not set then the system default certificate store is
      # used.
      def set_params(params={})
        params = DEFAULT_PARAMS.merge(params)
        self.options = params.delete(:options) # set before min_version/max_version
        params.each{|name, value| self.__send__("#{name}=", value) }
        if self.verify_mode != OpenSSL::SSL::VERIFY_NONE
          unless self.ca_file or self.ca_path or self.cert_store
            self.cert_store = DEFAULT_CERT_STORE
          end
        end
        return params
      end

      # call-seq:
      #    ctx.min_version = OpenSSL::SSL::TLS1_2_VERSION
      #    ctx.min_version = :TLS1_2
      #    ctx.min_version = nil
      #
      # Sets the lower bound on the supported SSL/TLS protocol version. The
      # version may be specified by an integer constant named
      # OpenSSL::SSL::*_VERSION, a Symbol, or +nil+ which means "any version".
      #
      # Be careful that you don't overwrite OpenSSL::SSL::OP_NO_{SSL,TLS}v*
      # options by #options= once you have called #min_version= or
      # #max_version=.
      #
      # === Example
      #   ctx = OpenSSL::SSL::SSLContext.new
      #   ctx.min_version = OpenSSL::SSL::TLS1_1_VERSION
      #   ctx.max_version = OpenSSL::SSL::TLS1_2_VERSION
      #
      #   sock = OpenSSL::SSL::SSLSocket.new(tcp_sock, ctx)
      #   sock.connect # Initiates a connection using either TLS 1.1 or TLS 1.2
      def min_version=(version)
        set_minmax_proto_version(version, @max_proto_version ||= nil)
        @min_proto_version = version
      end

      # call-seq:
      #    ctx.max_version = OpenSSL::SSL::TLS1_2_VERSION
      #    ctx.max_version = :TLS1_2
      #    ctx.max_version = nil
      #
      # Sets the upper bound of the supported SSL/TLS protocol version. See
      # #min_version= for the possible values.
      def max_version=(version)
        set_minmax_proto_version(@min_proto_version ||= nil, version)
        @max_proto_version = version
      end

      # call-seq:
      #    ctx.ssl_version = :TLSv1
      #    ctx.ssl_version = "SSLv23"
      #
      # Sets the SSL/TLS protocol version for the context. This forces
      # connections to use only the specified protocol version. This is
      # deprecated and only provided for backwards compatibility. Use
      # #min_version= and #max_version= instead.
      #
      # === History
      # As the name hints, this used to call the SSL_CTX_set_ssl_version()
      # function which sets the SSL method used for connections created from
      # the context. As of Ruby/OpenSSL 2.1, this accessor method is
      # implemented to call #min_version= and #max_version= instead.
      def ssl_version=(meth)
        meth = meth.to_s if meth.is_a?(Symbol)
        if /(?<type>_client|_server)\z/ =~ meth
          meth = $`
          if $VERBOSE
            warn "#{caller(1, 1)[0]}: method type #{type.inspect} is ignored"
          end
        end
        version = METHODS_MAP[meth.intern] or
          raise ArgumentError, "unknown SSL method `%s'" % meth
        set_minmax_proto_version(version, version)
        @min_proto_version = @max_proto_version = version
      end

      METHODS_MAP = {
        SSLv23: 0,
        SSLv2: OpenSSL::SSL::SSL2_VERSION,
        SSLv3: OpenSSL::SSL::SSL3_VERSION,
        TLSv1: OpenSSL::SSL::TLS1_VERSION,
        TLSv1_1: OpenSSL::SSL::TLS1_1_VERSION,
        TLSv1_2: OpenSSL::SSL::TLS1_2_VERSION,
      }.freeze
      private_constant :METHODS_MAP

      # The list of available SSL/TLS methods. This constant is only provided
      # for backwards compatibility.
      METHODS = METHODS_MAP.flat_map { |name,|
        [name, :"#{name}_client", :"#{name}_server"]
      }.freeze
      deprecate_constant :METHODS
    end

    module SocketForwarder
      # The file descriptor for the socket.
      def fileno
        to_io.fileno
      end

      def addr
        to_io.addr
      end

      def peeraddr
        to_io.peeraddr
      end

      def setsockopt(level, optname, optval)
        to_io.setsockopt(level, optname, optval)
      end

      def getsockopt(level, optname)
        to_io.getsockopt(level, optname)
      end

      def fcntl(*args)
        to_io.fcntl(*args)
      end

      def closed?
        to_io.closed?
      end

      def do_not_reverse_lookup=(flag)
        to_io.do_not_reverse_lookup = flag
      end
    end

    def verify_certificate_identity(cert, hostname)
      should_verify_common_name = true
      cert.extensions.each{|ext|
        next if ext.oid != "subjectAltName"
        ostr = OpenSSL::ASN1.decode(ext.to_der).value.last
        sequence = OpenSSL::ASN1.decode(ostr.value)
        sequence.value.each{|san|
          case san.tag
          when 2 # dNSName in GeneralName (RFC5280)
            should_verify_common_name = false
            return true if verify_hostname(hostname, san.value)
          when 7 # iPAddress in GeneralName (RFC5280)
            should_verify_common_name = false
            if san.value.size == 4 || san.value.size == 16
              begin
                return true if san.value == IPAddr.new(hostname).hton
              rescue IPAddr::InvalidAddressError
              end
            end
          end
        }
      }
      if should_verify_common_name
        cert.subject.to_a.each{|oid, value|
          if oid == "CN"
            return true if verify_hostname(hostname, value)
          end
        }
      end
      return false
    end
    module_function :verify_certificate_identity

    def verify_hostname(hostname, san) # :nodoc:
      # RFC 5280, IA5String is limited to the set of ASCII characters
      return false unless san.ascii_only?
      return false unless hostname.ascii_only?

      # See RFC 6125, section 6.4.1
      # Matching is case-insensitive.
      san_parts = san.downcase.split(".")

      # TODO: this behavior should probably be more strict
      return san == hostname if san_parts.size < 2

      # Matching is case-insensitive.
      host_parts = hostname.downcase.split(".")

      # RFC 6125, section 6.4.3, subitem 2.
      # If the wildcard character is the only character of the left-most
      # label in the presented identifier, the client SHOULD NOT compare
      # against anything but the left-most label of the reference
      # identifier (e.g., *.example.com would match foo.example.com but
      # not bar.foo.example.com or example.com).
      return false unless san_parts.size == host_parts.size

      # RFC 6125, section 6.4.3, subitem 1.
      # The client SHOULD NOT attempt to match a presented identifier in
      # which the wildcard character comprises a label other than the
      # left-most label (e.g., do not match bar.*.example.net).
      return false unless verify_wildcard(host_parts.shift, san_parts.shift)

      san_parts.join(".") == host_parts.join(".")
    end
    module_function :verify_hostname

    def verify_wildcard(domain_component, san_component) # :nodoc:
      parts = san_component.split("*", -1)

      return false if parts.size > 2
      return san_component == domain_component if parts.size == 1

      # RFC 6125, section 6.4.3, subitem 3.
      # The client SHOULD NOT attempt to match a presented identifier
      # where the wildcard character is embedded within an A-label or
      # U-label of an internationalized domain name.
      return false if domain_component.start_with?("xn--") && san_component != "*"

      parts[0].length + parts[1].length < domain_component.length &&
      domain_component.start_with?(parts[0]) &&
      domain_component.end_with?(parts[1])
    end
    module_function :verify_wildcard

    class SSLSocket
      include Buffering
      include SocketForwarder

      attr_reader :hostname

      # The underlying IO object.
      attr_reader :io
      alias :to_io :io

      # The SSLContext object used in this connection.
      attr_reader :context

      # Whether to close the underlying socket as well, when the SSL/TLS
      # connection is shut down. This defaults to +false+.
      attr_accessor :sync_close

      # call-seq:
      #    ssl.sysclose => nil
      #
      # Sends "close notify" to the peer and tries to shut down the SSL
      # connection gracefully.
      #
      # If sync_close is set to +true+, the underlying IO is also closed.
      def sysclose
        return if closed?
        stop
        io.close if sync_close
      end

      # call-seq:
      #   ssl.post_connection_check(hostname) -> true
      #
      # Perform hostname verification following RFC 6125.
      #
      # This method MUST be called after calling #connect to ensure that the
      # hostname of a remote peer has been verified.
      def post_connection_check(hostname)
        if peer_cert.nil?
          msg = "Peer verification enabled, but no certificate received."
          if using_anon_cipher?
            msg += " Anonymous cipher suite #{cipher[0]} was negotiated. " \
                   "Anonymous suites must be disabled to use peer verification."
          end
          raise SSLError, msg
        end

        unless OpenSSL::SSL.verify_certificate_identity(peer_cert, hostname)
          raise SSLError, "hostname \"#{hostname}\" does not match the server certificate"
        end
        return true
      end

      # call-seq:
      #   ssl.session -> aSession
      #
      # Returns the SSLSession object currently used, or nil if the session is
      # not established.
      def session
        SSL::Session.new(self)
      rescue SSL::Session::SessionError
        nil
      end

      private

      def using_anon_cipher?
        ctx = OpenSSL::SSL::SSLContext.new
        ctx.ciphers = "aNULL"
        ctx.ciphers.include?(cipher)
      end

      def client_cert_cb
        @context.client_cert_cb
      end

      def tmp_dh_callback
        @context.tmp_dh_callback || OpenSSL::SSL::SSLContext::DEFAULT_TMP_DH_CALLBACK
      end

      def tmp_ecdh_callback
        @context.tmp_ecdh_callback
      end

      def session_new_cb
        @context.session_new_cb
      end

      def session_get_cb
        @context.session_get_cb
      end

      class << self

        # call-seq:
        #   open(remote_host, remote_port, local_host=nil, local_port=nil, context: nil)
        #
        # Creates a new instance of SSLSocket.
        # _remote\_host_ and _remote\_port_ are used to open TCPSocket.
        # If _local\_host_ and _local\_port_ are specified,
        # then those parameters are used on the local end to establish the connection.
        # If _context_ is provided,
        # the SSL Sockets initial params will be taken from the context.
        #
        # === Examples
        #
        #   sock = OpenSSL::SSL::SSLSocket.open('localhost', 443)
        #   sock.connect # Initiates a connection to localhost:443
        #
        # with SSLContext:
        #
        #   ctx = OpenSSL::SSL::SSLContext.new
        #   sock = OpenSSL::SSL::SSLSocket.open('localhost', 443, context: ctx)
        #   sock.connect # Initiates a connection to localhost:443 with SSLContext
        def open(remote_host, remote_port, local_host=nil, local_port=nil, context: nil)
          sock = ::TCPSocket.open(remote_host, remote_port, local_host, local_port)
          if context.nil?
            return OpenSSL::SSL::SSLSocket.new(sock)
          else
            return OpenSSL::SSL::SSLSocket.new(sock, context)
          end
        end
      end
    end

    ##
    # SSLServer represents a TCP/IP server socket with Secure Sockets Layer.
    class SSLServer
      include SocketForwarder
      # When true then #accept works exactly the same as TCPServer#accept
      attr_accessor :start_immediately

      # Creates a new instance of SSLServer.
      # * _srv_ is an instance of TCPServer.
      # * _ctx_ is an instance of OpenSSL::SSL::SSLContext.
      def initialize(svr, ctx)
        @svr = svr
        @ctx = ctx
        unless ctx.session_id_context
          # see #6137 - session id may not exceed 32 bytes
          prng = ::Random.new($0.hash)
          session_id = prng.bytes(16).unpack('H*')[0]
          @ctx.session_id_context = session_id
        end
        @start_immediately = true
      end

      # Returns the TCPServer passed to the SSLServer when initialized.
      def to_io
        @svr
      end

      # See TCPServer#listen for details.
      def listen(backlog=Socket::SOMAXCONN)
        @svr.listen(backlog)
      end

      # See BasicSocket#shutdown for details.
      def shutdown(how=Socket::SHUT_RDWR)
        @svr.shutdown(how)
      end

      # Works similar to TCPServer#accept.
      def accept
        # Socket#accept returns [socket, addrinfo].
        # TCPServer#accept returns a socket.
        # The following comma strips addrinfo.
        sock, = @svr.accept
        begin
          ssl = OpenSSL::SSL::SSLSocket.new(sock, @ctx)
          ssl.sync_close = true
          ssl.accept if @start_immediately
          ssl
        rescue Exception => ex
          if ssl
            ssl.close
          else
            sock.close
          end
          raise ex
        end
      end

      # See IO#close for details.
      def close
        @svr.close
      end
    end
  end
end
# frozen_string_literal: true
=begin
= Ruby-space definitions that completes C-space funcs for Config

= Info
  Copyright (C) 2010  Hiroshi Nakamura <nahi@ruby-lang.org>

= Licence
  This program is licensed under the same licence as Ruby.
  (See the file 'LICENCE'.)

=end

require 'stringio'

module OpenSSL
  ##
  # = OpenSSL::Config
  #
  # Configuration for the openssl library.
  #
  # Many system's installation of openssl library will depend on your system
  # configuration. See the value of OpenSSL::Config::DEFAULT_CONFIG_FILE for
  # the location of the file for your host.
  #
  # See also http://www.openssl.org/docs/apps/config.html
  class Config
    include Enumerable

    class << self

      ##
      # Parses a given _string_ as a blob that contains configuration for
      # OpenSSL.
      #
      # If the source of the IO is a file, then consider using #parse_config.
      def parse(string)
        c = new()
        parse_config(StringIO.new(string)).each do |section, hash|
          c.set_section(section, hash)
        end
        c
      end

      ##
      # load is an alias to ::new
      alias load new

      ##
      # Parses the configuration data read from _io_, see also #parse.
      #
      # Raises a ConfigError on invalid configuration data.
      def parse_config(io)
        begin
          parse_config_lines(io)
        rescue => error
          raise ConfigError, "error in line #{io.lineno}: " + error.message
        end
      end

      def get_key_string(data, section, key) # :nodoc:
        if v = data[section] && data[section][key]
          return v
        elsif section == 'ENV'
          if v = ENV[key]
            return v
          end
        end
        if v = data['default'] && data['default'][key]
          return v
        end
      end

    private

      def parse_config_lines(io)
        section = 'default'
        data = {section => {}}
        io_stack = [io]
        while definition = get_definition(io_stack)
          definition = clear_comments(definition)
          next if definition.empty?
          case definition
          when /\A\[/
            if /\[([^\]]*)\]/ =~ definition
              section = $1.strip
              data[section] ||= {}
            else
              raise ConfigError, "missing close square bracket"
            end
          when /\A\.include (\s*=\s*)?(.+)\z/
            path = $2
            if File.directory?(path)
              files = Dir.glob(File.join(path, "*.{cnf,conf}"), File::FNM_EXTGLOB)
            else
              files = [path]
            end

            files.each do |filename|
              begin
                io_stack << StringIO.new(File.read(filename))
              rescue
                raise ConfigError, "could not include file '%s'" % filename
              end
            end
          when /\A([^:\s]*)(?:::([^:\s]*))?\s*=(.*)\z/
            if $2
              section = $1
              key = $2
            else
              key = $1
            end
            value = unescape_value(data, section, $3)
            (data[section] ||= {})[key] = value.strip
          else
            raise ConfigError, "missing equal sign"
          end
        end
        data
      end

      # escape with backslash
      QUOTE_REGEXP_SQ = /\A([^'\\]*(?:\\.[^'\\]*)*)'/
      # escape with backslash and doubled dq
      QUOTE_REGEXP_DQ = /\A([^"\\]*(?:""[^"\\]*|\\.[^"\\]*)*)"/
      # escaped char map
      ESCAPE_MAP = {
        "r" => "\r",
        "n" => "\n",
        "b" => "\b",
        "t" => "\t",
      }

      def unescape_value(data, section, value)
        scanned = []
        while m = value.match(/['"\\$]/)
          scanned << m.pre_match
          c = m[0]
          value = m.post_match
          case c
          when "'"
            if m = value.match(QUOTE_REGEXP_SQ)
              scanned << m[1].gsub(/\\(.)/, '\\1')
              value = m.post_match
            else
              break
            end
          when '"'
            if m = value.match(QUOTE_REGEXP_DQ)
              scanned << m[1].gsub(/""/, '').gsub(/\\(.)/, '\\1')
              value = m.post_match
            else
              break
            end
          when "\\"
            c = value.slice!(0, 1)
            scanned << (ESCAPE_MAP[c] || c)
          when "$"
            ref, value = extract_reference(value)
            refsec = section
            if ref.index('::')
              refsec, ref = ref.split('::', 2)
            end
            if v = get_key_string(data, refsec, ref)
              scanned << v
            else
              raise ConfigError, "variable has no value"
            end
          else
            raise 'must not reaced'
          end
        end
        scanned << value
        scanned.join
      end

      def extract_reference(value)
        rest = ''
        if m = value.match(/\(([^)]*)\)|\{([^}]*)\}/)
          value = m[1] || m[2]
          rest = m.post_match
        elsif [?(, ?{].include?(value[0])
          raise ConfigError, "no close brace"
        end
        if m = value.match(/[a-zA-Z0-9_]*(?:::[a-zA-Z0-9_]*)?/)
          return m[0], m.post_match + rest
        else
          raise
        end
      end

      def clear_comments(line)
        # FCOMMENT
        if m = line.match(/\A([\t\n\f ]*);.*\z/)
          return m[1]
        end
        # COMMENT
        scanned = []
        while m = line.match(/[#'"\\]/)
          scanned << m.pre_match
          c = m[0]
          line = m.post_match
          case c
          when '#'
            line = nil
            break
          when "'", '"'
            regexp = (c == "'") ? QUOTE_REGEXP_SQ : QUOTE_REGEXP_DQ
            scanned << c
            if m = line.match(regexp)
              scanned << m[0]
              line = m.post_match
            else
              scanned << line
              line = nil
              break
            end
          when "\\"
            scanned << c
            scanned << line.slice!(0, 1)
          else
            raise 'must not reaced'
          end
        end
        scanned << line
        scanned.join
      end

      def get_definition(io_stack)
        if line = get_line(io_stack)
          while /[^\\]\\\z/ =~ line
            if extra = get_line(io_stack)
              line += extra
            else
              break
            end
          end
          return line.strip
        end
      end

      def get_line(io_stack)
        while io = io_stack.last
          if line = io.gets
            return line.gsub(/[\r\n]*/, '')
          end
          io_stack.pop
        end
      end
    end

    ##
    # Creates an instance of OpenSSL's configuration class.
    #
    # This can be used in contexts like OpenSSL::X509::ExtensionFactory.config=
    #
    # If the optional _filename_ parameter is provided, then it is read in and
    # parsed via #parse_config.
    #
    # This can raise IO exceptions based on the access, or availability of the
    # file. A ConfigError exception may be raised depending on the validity of
    # the data being configured.
    #
    def initialize(filename = nil)
      @data = {}
      if filename
        File.open(filename.to_s) do |file|
          Config.parse_config(file).each do |section, hash|
            set_section(section, hash)
          end
        end
      end
    end

    ##
    # Gets the value of _key_ from the given _section_
    #
    # Given the following configurating file being loaded:
    #
    #   config = OpenSSL::Config.load('foo.cnf')
    #     #=> #<OpenSSL::Config sections=["default"]>
    #   puts config.to_s
    #     #=> [ default ]
    #     #   foo=bar
    #
    # You can get a specific value from the config if you know the _section_
    # and _key_ like so:
    #
    #   config.get_value('default','foo')
    #     #=> "bar"
    #
    def get_value(section, key)
      if section.nil?
        raise TypeError.new('nil not allowed')
      end
      section = 'default' if section.empty?
      get_key_string(section, key)
    end

    ##
    #
    # *Deprecated*
    #
    # Use #get_value instead
    def value(arg1, arg2 = nil) # :nodoc:
      warn('Config#value is deprecated; use Config#get_value')
      if arg2.nil?
        section, key = 'default', arg1
      else
        section, key = arg1, arg2
      end
      section ||= 'default'
      section = 'default' if section.empty?
      get_key_string(section, key)
    end

    ##
    # *Deprecated in v2.2.0*. This method will be removed in a future release.
    #
    # Set the target _key_ with a given _value_ under a specific _section_.
    #
    # Given the following configurating file being loaded:
    #
    #   config = OpenSSL::Config.load('foo.cnf')
    #     #=> #<OpenSSL::Config sections=["default"]>
    #   puts config.to_s
    #     #=> [ default ]
    #     #   foo=bar
    #
    # You can set the value of _foo_ under the _default_ section to a new
    # value:
    #
    #   config.add_value('default', 'foo', 'buzz')
    #     #=> "buzz"
    #   puts config.to_s
    #     #=> [ default ]
    #     #   foo=buzz
    #
    def add_value(section, key, value)
      check_modify
      (@data[section] ||= {})[key] = value
    end

    ##
    # Get a specific _section_ from the current configuration
    #
    # Given the following configurating file being loaded:
    #
    #   config = OpenSSL::Config.load('foo.cnf')
    #     #=> #<OpenSSL::Config sections=["default"]>
    #   puts config.to_s
    #     #=> [ default ]
    #     #   foo=bar
    #
    # You can get a hash of the specific section like so:
    #
    #   config['default']
    #     #=> {"foo"=>"bar"}
    #
    def [](section)
      @data[section] || {}
    end

    ##
    # Deprecated
    #
    # Use #[] instead
    def section(name) # :nodoc:
      warn('Config#section is deprecated; use Config#[]')
      @data[name] || {}
    end

    ##
    # *Deprecated in v2.2.0*. This method will be removed in a future release.
    #
    # Sets a specific _section_ name with a Hash _pairs_.
    #
    # Given the following configuration being created:
    #
    #   config = OpenSSL::Config.new
    #     #=> #<OpenSSL::Config sections=[]>
    #   config['default'] = {"foo"=>"bar","baz"=>"buz"}
    #     #=> {"foo"=>"bar", "baz"=>"buz"}
    #   puts config.to_s
    #     #=> [ default ]
    #     #   foo=bar
    #     #   baz=buz
    #
    # It's important to note that this will essentially merge any of the keys
    # in _pairs_ with the existing _section_. For example:
    #
    #   config['default']
    #     #=> {"foo"=>"bar", "baz"=>"buz"}
    #   config['default'] = {"foo" => "changed"}
    #     #=> {"foo"=>"changed"}
    #   config['default']
    #     #=> {"foo"=>"changed", "baz"=>"buz"}
    #
    def []=(section, pairs)
      check_modify
      set_section(section, pairs)
    end

    def set_section(section, pairs) # :nodoc:
      hash = @data[section] ||= {}
      pairs.each do |key, value|
        hash[key] = value
      end
    end

    ##
    # Get the names of all sections in the current configuration
    def sections
      @data.keys
    end

    ##
    # Get the parsable form of the current configuration
    #
    # Given the following configuration being created:
    #
    #   config = OpenSSL::Config.new
    #     #=> #<OpenSSL::Config sections=[]>
    #   config['default'] = {"foo"=>"bar","baz"=>"buz"}
    #     #=> {"foo"=>"bar", "baz"=>"buz"}
    #   puts config.to_s
    #     #=> [ default ]
    #     #   foo=bar
    #     #   baz=buz
    #
    # You can parse get the serialized configuration using #to_s and then parse
    # it later:
    #
    #   serialized_config = config.to_s
    #   # much later...
    #   new_config = OpenSSL::Config.parse(serialized_config)
    #     #=> #<OpenSSL::Config sections=["default"]>
    #   puts new_config
    #     #=> [ default ]
    #         foo=bar
    #         baz=buz
    #
    def to_s
      ary = []
      @data.keys.sort.each do |section|
        ary << "[ #{section} ]\n"
        @data[section].keys.each do |key|
          ary << "#{key}=#{@data[section][key]}\n"
        end
        ary << "\n"
      end
      ary.join
    end

    ##
    # For a block.
    #
    # Receive the section and its pairs for the current configuration.
    #
    #   config.each do |section, key, value|
    #     # ...
    #   end
    #
    def each
      @data.each do |section, hash|
        hash.each do |key, value|
          yield [section, key, value]
        end
      end
    end

    ##
    # String representation of this configuration object, including the class
    # name and its sections.
    def inspect
      "#<#{self.class.name} sections=#{sections.inspect}>"
    end

  protected

    def data # :nodoc:
      @data
    end

  private

    def initialize_copy(other)
      @data = other.data.dup
    end

    def check_modify
      warn "#{caller(2, 1)[0]}: warning: do not modify OpenSSL::Config; this " \
        "method is deprecated and will be removed in a future release."
      raise TypeError.new("Insecure: can't modify OpenSSL config") if frozen?
    end

    def get_key_string(section, key)
      Config.get_key_string(@data, section, key)
    end
  end
end
# frozen_string_literal: true
#--
# Ruby/OpenSSL Project
# Copyright (C) 2017 Ruby/OpenSSL Project Authors
#++

module OpenSSL
  module PKCS5
    module_function

    # OpenSSL::PKCS5.pbkdf2_hmac has been renamed to OpenSSL::KDF.pbkdf2_hmac.
    # This method is provided for backwards compatibility.
    def pbkdf2_hmac(pass, salt, iter, keylen, digest)
      OpenSSL::KDF.pbkdf2_hmac(pass, salt: salt, iterations: iter,
                               length: keylen, hash: digest)
    end

    def pbkdf2_hmac_sha1(pass, salt, iter, keylen)
      pbkdf2_hmac(pass, salt, iter, keylen, "sha1")
    end
  end
end
# frozen_string_literal: true
#--
# = Ruby-space definitions to add DER (de)serialization to classes
#
# = Info
# 'OpenSSL for Ruby 2' project
# Copyright (C) 2002  Michal Rokos <m.rokos@sh.cvut.cz>
# All rights reserved.
#
# = Licence
# This program is licensed under the same licence as Ruby.
# (See the file 'LICENCE'.)
#++
module OpenSSL
  module Marshal
    def self.included(base)
      base.extend(ClassMethods)
    end

    module ClassMethods
      def _load(string)
        new(string)
      end
    end

    def _dump(_level)
      to_der
    end
  end
end
# frozen_string_literal: true
#--
#
# = Ruby-space definitions that completes C-space funcs for BN
#
# = Info
# 'OpenSSL for Ruby 2' project
# Copyright (C) 2002  Michal Rokos <m.rokos@sh.cvut.cz>
# All rights reserved.
#
# = Licence
# This program is licensed under the same licence as Ruby.
# (See the file 'LICENCE'.)
#++

module OpenSSL
  class BN
    include Comparable

    def pretty_print(q)
      q.object_group(self) {
        q.text ' '
        q.text to_i.to_s
      }
    end
  end # BN
end # OpenSSL

##
#--
# Add double dispatch to Integer
#++
class Integer
  # Casts an Integer as an OpenSSL::BN
  #
  # See `man bn` for more info.
  def to_bn
    OpenSSL::BN::new(self)
  end
end # Integer
# frozen_string_literal: true
#--
# = Ruby-space definitions that completes C-space funcs for X509 and subclasses
#
# = Info
# 'OpenSSL for Ruby 2' project
# Copyright (C) 2002  Michal Rokos <m.rokos@sh.cvut.cz>
# All rights reserved.
#
# = Licence
# This program is licensed under the same licence as Ruby.
# (See the file 'LICENCE'.)
#++

require_relative 'marshal'

module OpenSSL
  module X509
    class ExtensionFactory
      def create_extension(*arg)
        if arg.size > 1
          create_ext(*arg)
        else
          send("create_ext_from_"+arg[0].class.name.downcase, arg[0])
        end
      end

      def create_ext_from_array(ary)
        raise ExtensionError, "unexpected array form" if ary.size > 3
        create_ext(ary[0], ary[1], ary[2])
      end

      def create_ext_from_string(str) # "oid = critical, value"
        oid, value = str.split(/=/, 2)
        oid.strip!
        value.strip!
        create_ext(oid, value)
      end

      def create_ext_from_hash(hash)
        create_ext(hash["oid"], hash["value"], hash["critical"])
      end
    end

    class Extension
      include OpenSSL::Marshal

      def ==(other)
        return false unless Extension === other
        to_der == other.to_der
      end

      def to_s # "oid = critical, value"
        str = self.oid
        str << " = "
        str << "critical, " if self.critical?
        str << self.value.gsub(/\n/, ", ")
      end

      def to_h # {"oid"=>sn|ln, "value"=>value, "critical"=>true|false}
        {"oid"=>self.oid,"value"=>self.value,"critical"=>self.critical?}
      end

      def to_a
        [ self.oid, self.value, self.critical? ]
      end

      module Helpers
        def find_extension(oid)
          extensions.find { |e| e.oid == oid }
        end
      end

      module SubjectKeyIdentifier
        include Helpers

        # Get the subject's key identifier from the subjectKeyIdentifier
        # exteension, as described in RFC5280 Section 4.2.1.2.
        #
        # Returns the binary String key identifier or nil or raises
        # ASN1::ASN1Error.
        def subject_key_identifier
          ext = find_extension("subjectKeyIdentifier")
          return nil if ext.nil?

          ski_asn1 = ASN1.decode(ext.value_der)
          if ext.critical? || ski_asn1.tag_class != :UNIVERSAL || ski_asn1.tag != ASN1::OCTET_STRING
            raise ASN1::ASN1Error, "invalid extension"
          end

          ski_asn1.value
        end
      end

      module AuthorityKeyIdentifier
        include Helpers

        # Get the issuing certificate's key identifier from the
        # authorityKeyIdentifier extension, as described in RFC5280
        # Section 4.2.1.1
        #
        # Returns the binary String keyIdentifier or nil or raises
        # ASN1::ASN1Error.
        def authority_key_identifier
          ext = find_extension("authorityKeyIdentifier")
          return nil if ext.nil?

          aki_asn1 = ASN1.decode(ext.value_der)
          if ext.critical? || aki_asn1.tag_class != :UNIVERSAL || aki_asn1.tag != ASN1::SEQUENCE
            raise ASN1::ASN1Error, "invalid extension"
          end

          key_id = aki_asn1.value.find do |v|
            v.tag_class == :CONTEXT_SPECIFIC && v.tag == 0
          end

          key_id.nil? ? nil : key_id.value
        end
      end

      module CRLDistributionPoints
        include Helpers

        # Get the distributionPoint fullName URI from the certificate's CRL
        # distribution points extension, as described in RFC5280 Section
        # 4.2.1.13
        #
        # Returns an array of strings or nil or raises ASN1::ASN1Error.
        def crl_uris
          ext = find_extension("crlDistributionPoints")
          return nil if ext.nil?

          cdp_asn1 = ASN1.decode(ext.value_der)
          if cdp_asn1.tag_class != :UNIVERSAL || cdp_asn1.tag != ASN1::SEQUENCE
            raise ASN1::ASN1Error, "invalid extension"
          end

          crl_uris = cdp_asn1.map do |crl_distribution_point|
            distribution_point = crl_distribution_point.value.find do |v|
              v.tag_class == :CONTEXT_SPECIFIC && v.tag == 0
            end
            full_name = distribution_point&.value&.find do |v|
              v.tag_class == :CONTEXT_SPECIFIC && v.tag == 0
            end
            full_name&.value&.find do |v|
              v.tag_class == :CONTEXT_SPECIFIC && v.tag == 6 # uniformResourceIdentifier
            end
          end

          crl_uris&.map(&:value)
        end
      end

      module AuthorityInfoAccess
        include Helpers

        # Get the information and services for the issuer from the certificate's
        # authority information access extension exteension, as described in RFC5280
        # Section 4.2.2.1.
        #
        # Returns an array of strings or nil or raises ASN1::ASN1Error.
        def ca_issuer_uris
          aia_asn1 = parse_aia_asn1
          return nil if aia_asn1.nil?

          ca_issuer = aia_asn1.value.select do |authority_info_access|
            authority_info_access.value.first.value == "caIssuers"
          end

          ca_issuer&.map(&:value)&.map(&:last)&.map(&:value)
        end

        # Get the URIs for OCSP from the certificate's authority information access
        # extension exteension, as described in RFC5280 Section 4.2.2.1.
        #
        # Returns an array of strings or nil or raises ASN1::ASN1Error.
        def ocsp_uris
          aia_asn1 = parse_aia_asn1
          return nil if aia_asn1.nil?

          ocsp = aia_asn1.value.select do |authority_info_access|
            authority_info_access.value.first.value == "OCSP"
          end

          ocsp&.map(&:value)&.map(&:last)&.map(&:value)
        end

        private

          def parse_aia_asn1
            ext = find_extension("authorityInfoAccess")
            return nil if ext.nil?

            aia_asn1 = ASN1.decode(ext.value_der)
            if ext.critical? || aia_asn1.tag_class != :UNIVERSAL || aia_asn1.tag != ASN1::SEQUENCE
              raise ASN1::ASN1Error, "invalid extension"
            end

            aia_asn1
          end
      end
    end

    class Name
      include OpenSSL::Marshal

      module RFC2253DN
        Special = ',=+<>#;'
        HexChar = /[0-9a-fA-F]/
        HexPair = /#{HexChar}#{HexChar}/
        HexString = /#{HexPair}+/
        Pair = /\\(?:[#{Special}]|\\|"|#{HexPair})/
        StringChar = /[^\\"#{Special}]/
        QuoteChar = /[^\\"]/
        AttributeType = /[a-zA-Z][0-9a-zA-Z]*|[0-9]+(?:\.[0-9]+)*/
        AttributeValue = /
          (?!["#])((?:#{StringChar}|#{Pair})*)|
          \#(#{HexString})|
          "((?:#{QuoteChar}|#{Pair})*)"
        /x
        TypeAndValue = /\A(#{AttributeType})=#{AttributeValue}/

        module_function

        def expand_pair(str)
          return nil unless str
          return str.gsub(Pair){
            pair = $&
            case pair.size
            when 2 then pair[1,1]
            when 3 then Integer("0x#{pair[1,2]}").chr
            else raise OpenSSL::X509::NameError, "invalid pair: #{str}"
            end
          }
        end

        def expand_hexstring(str)
          return nil unless str
          der = str.gsub(HexPair){$&.to_i(16).chr }
          a1 = OpenSSL::ASN1.decode(der)
          return a1.value, a1.tag
        end

        def expand_value(str1, str2, str3)
          value = expand_pair(str1)
          value, tag = expand_hexstring(str2) unless value
          value = expand_pair(str3) unless value
          return value, tag
        end

        def scan(dn)
          str = dn
          ary = []
          while true
            if md = TypeAndValue.match(str)
              remain = md.post_match
              type = md[1]
              value, tag = expand_value(md[2], md[3], md[4]) rescue nil
              if value
                type_and_value = [type, value]
                type_and_value.push(tag) if tag
                ary.unshift(type_and_value)
                if remain.length > 2 && remain[0] == ?,
                  str = remain[1..-1]
                  next
                elsif remain.length > 2 && remain[0] == ?+
                  raise OpenSSL::X509::NameError,
                    "multi-valued RDN is not supported: #{dn}"
                elsif remain.empty?
                  break
                end
              end
            end
            msg_dn = dn[0, dn.length - str.length] + " =>" + str
            raise OpenSSL::X509::NameError, "malformed RDN: #{msg_dn}"
          end
          return ary
        end
      end

      class << self
        def parse_rfc2253(str, template=OBJECT_TYPE_TEMPLATE)
          ary = OpenSSL::X509::Name::RFC2253DN.scan(str)
          self.new(ary, template)
        end

        def parse_openssl(str, template=OBJECT_TYPE_TEMPLATE)
          if str.start_with?("/")
            # /A=B/C=D format
            ary = str[1..-1].split("/").map { |i| i.split("=", 2) }
          else
            # Comma-separated
            ary = str.split(",").map { |i| i.strip.split("=", 2) }
          end
          self.new(ary, template)
        end

        alias parse parse_openssl
      end

      def pretty_print(q)
        q.object_group(self) {
          q.text ' '
          q.text to_s(OpenSSL::X509::Name::RFC2253)
        }
      end
    end

    class Attribute
      include OpenSSL::Marshal

      def ==(other)
        return false unless Attribute === other
        to_der == other.to_der
      end
    end

    class StoreContext
      def cleanup
        warn "(#{caller.first}) OpenSSL::X509::StoreContext#cleanup is deprecated with no replacement" if $VERBOSE
      end
    end

    class Certificate
      include OpenSSL::Marshal
      include Extension::SubjectKeyIdentifier
      include Extension::AuthorityKeyIdentifier
      include Extension::CRLDistributionPoints
      include Extension::AuthorityInfoAccess

      def pretty_print(q)
        q.object_group(self) {
          q.breakable
          q.text 'subject='; q.pp self.subject; q.text ','; q.breakable
          q.text 'issuer='; q.pp self.issuer; q.text ','; q.breakable
          q.text 'serial='; q.pp self.serial; q.text ','; q.breakable
          q.text 'not_before='; q.pp self.not_before; q.text ','; q.breakable
          q.text 'not_after='; q.pp self.not_after
        }
      end
    end

    class CRL
      include OpenSSL::Marshal
      include Extension::AuthorityKeyIdentifier

      def ==(other)
        return false unless CRL === other
        to_der == other.to_der
      end
    end

    class Revoked
      def ==(other)
        return false unless Revoked === other
        to_der == other.to_der
      end
    end

    class Request
      include OpenSSL::Marshal

      def ==(other)
        return false unless Request === other
        to_der == other.to_der
      end
    end
  end
end
# frozen_string_literal: true

module OpenSSL
  class HMAC
    # Securely compare with another HMAC instance in constant time.
    def ==(other)
      return false unless HMAC === other
      return false unless self.digest.bytesize == other.digest.bytesize

      OpenSSL.fixed_length_secure_compare(self.digest, other.digest)
    end

    class << self
      # :call-seq:
      #    HMAC.digest(digest, key, data) -> aString
      #
      # Returns the authentication code as a binary string. The _digest_ parameter
      # specifies the digest algorithm to use. This may be a String representing
      # the algorithm name or an instance of OpenSSL::Digest.
      #
      # === Example
      #  key = 'key'
      #  data = 'The quick brown fox jumps over the lazy dog'
      #
      #  hmac = OpenSSL::HMAC.digest('SHA1', key, data)
      #  #=> "\xDE|\x9B\x85\xB8\xB7\x8A\xA6\xBC\x8Az6\xF7\n\x90p\x1C\x9D\xB4\xD9"
      def digest(digest, key, data)
        hmac = new(key, digest)
        hmac << data
        hmac.digest
      end

      # :call-seq:
      #    HMAC.hexdigest(digest, key, data) -> aString
      #
      # Returns the authentication code as a hex-encoded string. The _digest_
      # parameter specifies the digest algorithm to use. This may be a String
      # representing the algorithm name or an instance of OpenSSL::Digest.
      #
      # === Example
      #  key = 'key'
      #  data = 'The quick brown fox jumps over the lazy dog'
      #
      #  hmac = OpenSSL::HMAC.hexdigest('SHA1', key, data)
      #  #=> "de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9"
      def hexdigest(digest, key, data)
        hmac = new(key, digest)
        hmac << data
        hmac.hexdigest
      end
    end
  end
end
# frozen_string_literal: true
#--
# = Ruby-space predefined Digest subclasses
#
# = Info
# 'OpenSSL for Ruby 2' project
# Copyright (C) 2002  Michal Rokos <m.rokos@sh.cvut.cz>
# All rights reserved.
#
# = Licence
# This program is licensed under the same licence as Ruby.
# (See the file 'LICENCE'.)
#++

module OpenSSL
  class Digest

    # Return the hash value computed with _name_ Digest. _name_ is either the
    # long name or short name of a supported digest algorithm.
    #
    # === Examples
    #
    #   OpenSSL::Digest.digest("SHA256", "abc")
    #
    # which is equivalent to:
    #
    #   OpenSSL::Digest.digest('SHA256', "abc")

    def self.digest(name, data)
      super(data, name)
    end

    %w(MD4 MD5 RIPEMD160 SHA1 SHA224 SHA256 SHA384 SHA512).each do |name|
      klass = Class.new(self) {
        define_method(:initialize, ->(data = nil) {super(name, data)})
      }

      singleton = (class << klass; self; end)

      singleton.class_eval{
        define_method(:digest) {|data| new.digest(data)}
        define_method(:hexdigest) {|data| new.hexdigest(data)}
      }

      const_set(name.tr('-', '_'), klass)
    end

    # Deprecated.
    #
    # This class is only provided for backwards compatibility.
    # Use OpenSSL::Digest instead.
    class Digest < Digest; end # :nodoc:
    deprecate_constant :Digest

  end # Digest

  # Returns a Digest subclass by _name_
  #
  #   require 'openssl'
  #
  #   OpenSSL::Digest("MD5")
  #   # => OpenSSL::Digest::MD5
  #
  #   Digest("Foo")
  #   # => NameError: wrong constant name Foo

  def Digest(name)
    OpenSSL::Digest.const_get(name)
  end

  module_function :Digest

end # OpenSSL
# coding: binary
# frozen_string_literal: true
#--
#= Info
#  'OpenSSL for Ruby 2' project
#  Copyright (C) 2001 GOTOU YUUZOU <gotoyuzo@notwork.org>
#  All rights reserved.
#
#= Licence
#  This program is licensed under the same licence as Ruby.
#  (See the file 'LICENCE'.)
#++

##
# OpenSSL IO buffering mix-in module.
#
# This module allows an OpenSSL::SSL::SSLSocket to behave like an IO.
#
# You typically won't use this module directly, you can see it implemented in
# OpenSSL::SSL::SSLSocket.

module OpenSSL::Buffering
  include Enumerable

  # A buffer which will retain binary encoding.
  class Buffer < String
    BINARY = Encoding::BINARY

    def initialize
      super

      force_encoding(BINARY)
    end

    def << string
      if string.encoding == BINARY
        super(string)
      else
        super(string.b)
      end

      return self
    end

    alias concat <<
  end

  ##
  # The "sync mode" of the SSLSocket.
  #
  # See IO#sync for full details.

  attr_accessor :sync

  ##
  # Default size to read from or write to the SSLSocket for buffer operations.

  BLOCK_SIZE = 1024*16

  ##
  # Creates an instance of OpenSSL's buffering IO module.

  def initialize(*)
    super
    @eof = false
    @rbuffer = Buffer.new
    @sync = @io.sync
  end

  #
  # for reading.
  #
  private

  ##
  # Fills the buffer from the underlying SSLSocket

  def fill_rbuff
    begin
      @rbuffer << self.sysread(BLOCK_SIZE)
    rescue Errno::EAGAIN
      retry
    rescue EOFError
      @eof = true
    end
  end

  ##
  # Consumes _size_ bytes from the buffer

  def consume_rbuff(size=nil)
    if @rbuffer.empty?
      nil
    else
      size = @rbuffer.size unless size
      ret = @rbuffer[0, size]
      @rbuffer[0, size] = ""
      ret
    end
  end

  public

  ##
  # Reads _size_ bytes from the stream.  If _buf_ is provided it must
  # reference a string which will receive the data.
  #
  # See IO#read for full details.

  def read(size=nil, buf=nil)
    if size == 0
      if buf
        buf.clear
        return buf
      else
        return ""
      end
    end
    until @eof
      break if size && size <= @rbuffer.size
      fill_rbuff
    end
    ret = consume_rbuff(size) || ""
    if buf
      buf.replace(ret)
      ret = buf
    end
    (size && ret.empty?) ? nil : ret
  end

  ##
  # Reads at most _maxlen_ bytes from the stream.  If _buf_ is provided it
  # must reference a string which will receive the data.
  #
  # See IO#readpartial for full details.

  def readpartial(maxlen, buf=nil)
    if maxlen == 0
      if buf
        buf.clear
        return buf
      else
        return ""
      end
    end
    if @rbuffer.empty?
      begin
        return sysread(maxlen, buf)
      rescue Errno::EAGAIN
        retry
      end
    end
    ret = consume_rbuff(maxlen)
    if buf
      buf.replace(ret)
      ret = buf
    end
    ret
  end

  ##
  # Reads at most _maxlen_ bytes in the non-blocking manner.
  #
  # When no data can be read without blocking it raises
  # OpenSSL::SSL::SSLError extended by IO::WaitReadable or IO::WaitWritable.
  #
  # IO::WaitReadable means SSL needs to read internally so read_nonblock
  # should be called again when the underlying IO is readable.
  #
  # IO::WaitWritable means SSL needs to write internally so read_nonblock
  # should be called again after the underlying IO is writable.
  #
  # OpenSSL::Buffering#read_nonblock needs two rescue clause as follows:
  #
  #   # emulates blocking read (readpartial).
  #   begin
  #     result = ssl.read_nonblock(maxlen)
  #   rescue IO::WaitReadable
  #     IO.select([io])
  #     retry
  #   rescue IO::WaitWritable
  #     IO.select(nil, [io])
  #     retry
  #   end
  #
  # Note that one reason that read_nonblock writes to the underlying IO is
  # when the peer requests a new TLS/SSL handshake.  See openssl the FAQ for
  # more details.  http://www.openssl.org/support/faq.html
  #
  # By specifying a keyword argument _exception_ to +false+, you can indicate
  # that read_nonblock should not raise an IO::Wait*able exception, but
  # return the symbol +:wait_writable+ or +:wait_readable+ instead. At EOF,
  # it will return +nil+ instead of raising EOFError.

  def read_nonblock(maxlen, buf=nil, exception: true)
    if maxlen == 0
      if buf
        buf.clear
        return buf
      else
        return ""
      end
    end
    if @rbuffer.empty?
      return sysread_nonblock(maxlen, buf, exception: exception)
    end
    ret = consume_rbuff(maxlen)
    if buf
      buf.replace(ret)
      ret = buf
    end
    ret
  end

  ##
  # Reads the next "line" from the stream.  Lines are separated by _eol_.  If
  # _limit_ is provided the result will not be longer than the given number of
  # bytes.
  #
  # _eol_ may be a String or Regexp.
  #
  # Unlike IO#gets the line read will not be assigned to +$_+.
  #
  # Unlike IO#gets the separator must be provided if a limit is provided.

  def gets(eol=$/, limit=nil)
    idx = @rbuffer.index(eol)
    until @eof
      break if idx
      fill_rbuff
      idx = @rbuffer.index(eol)
    end
    if eol.is_a?(Regexp)
      size = idx ? idx+$&.size : nil
    else
      size = idx ? idx+eol.size : nil
    end
    if size && limit && limit >= 0
      size = [size, limit].min
    end
    consume_rbuff(size)
  end

  ##
  # Executes the block for every line in the stream where lines are separated
  # by _eol_.
  #
  # See also #gets

  def each(eol=$/)
    while line = self.gets(eol)
      yield line
    end
  end
  alias each_line each

  ##
  # Reads lines from the stream which are separated by _eol_.
  #
  # See also #gets

  def readlines(eol=$/)
    ary = []
    while line = self.gets(eol)
      ary << line
    end
    ary
  end

  ##
  # Reads a line from the stream which is separated by _eol_.
  #
  # Raises EOFError if at end of file.

  def readline(eol=$/)
    raise EOFError if eof?
    gets(eol)
  end

  ##
  # Reads one character from the stream.  Returns nil if called at end of
  # file.

  def getc
    read(1)
  end

  ##
  # Calls the given block once for each byte in the stream.

  def each_byte # :yields: byte
    while c = getc
      yield(c.ord)
    end
  end

  ##
  # Reads a one-character string from the stream.  Raises an EOFError at end
  # of file.

  def readchar
    raise EOFError if eof?
    getc
  end

  ##
  # Pushes character _c_ back onto the stream such that a subsequent buffered
  # character read will return it.
  #
  # Unlike IO#getc multiple bytes may be pushed back onto the stream.
  #
  # Has no effect on unbuffered reads (such as #sysread).

  def ungetc(c)
    @rbuffer[0,0] = c.chr
  end

  ##
  # Returns true if the stream is at file which means there is no more data to
  # be read.

  def eof?
    fill_rbuff if !@eof && @rbuffer.empty?
    @eof && @rbuffer.empty?
  end
  alias eof eof?

  #
  # for writing.
  #
  private

  ##
  # Writes _s_ to the buffer.  When the buffer is full or #sync is true the
  # buffer is flushed to the underlying socket.

  def do_write(s)
    @wbuffer = Buffer.new unless defined? @wbuffer
    @wbuffer << s
    @wbuffer.force_encoding(Encoding::BINARY)
    @sync ||= false
    if @sync or @wbuffer.size > BLOCK_SIZE
      until @wbuffer.empty?
        begin
          nwrote = syswrite(@wbuffer)
        rescue Errno::EAGAIN
          retry
        end
        @wbuffer[0, nwrote] = ""
      end
    end
  end

  public

  ##
  # Writes _s_ to the stream.  If the argument is not a String it will be
  # converted using +.to_s+ method.  Returns the number of bytes written.

  def write(*s)
    s.inject(0) do |written, str|
      do_write(str)
      written + str.bytesize
    end
  end

  ##
  # Writes _s_ in the non-blocking manner.
  #
  # If there is buffered data, it is flushed first.  This may block.
  #
  # write_nonblock returns number of bytes written to the SSL connection.
  #
  # When no data can be written without blocking it raises
  # OpenSSL::SSL::SSLError extended by IO::WaitReadable or IO::WaitWritable.
  #
  # IO::WaitReadable means SSL needs to read internally so write_nonblock
  # should be called again after the underlying IO is readable.
  #
  # IO::WaitWritable means SSL needs to write internally so write_nonblock
  # should be called again after underlying IO is writable.
  #
  # So OpenSSL::Buffering#write_nonblock needs two rescue clause as follows.
  #
  #   # emulates blocking write.
  #   begin
  #     result = ssl.write_nonblock(str)
  #   rescue IO::WaitReadable
  #     IO.select([io])
  #     retry
  #   rescue IO::WaitWritable
  #     IO.select(nil, [io])
  #     retry
  #   end
  #
  # Note that one reason that write_nonblock reads from the underlying IO
  # is when the peer requests a new TLS/SSL handshake.  See the openssl FAQ
  # for more details.  http://www.openssl.org/support/faq.html
  #
  # By specifying a keyword argument _exception_ to +false+, you can indicate
  # that write_nonblock should not raise an IO::Wait*able exception, but
  # return the symbol +:wait_writable+ or +:wait_readable+ instead.

  def write_nonblock(s, exception: true)
    flush
    syswrite_nonblock(s, exception: exception)
  end

  ##
  # Writes _s_ to the stream.  _s_ will be converted to a String using
  # +.to_s+ method.

  def <<(s)
    do_write(s)
    self
  end

  ##
  # Writes _args_ to the stream along with a record separator.
  #
  # See IO#puts for full details.

  def puts(*args)
    s = Buffer.new
    if args.empty?
      s << "\n"
    end
    args.each{|arg|
      s << arg.to_s
      s.sub!(/(?<!\n)\z/, "\n")
    }
    do_write(s)
    nil
  end

  ##
  # Writes _args_ to the stream.
  #
  # See IO#print for full details.

  def print(*args)
    s = Buffer.new
    args.each{ |arg| s << arg.to_s }
    do_write(s)
    nil
  end

  ##
  # Formats and writes to the stream converting parameters under control of
  # the format string.
  #
  # See Kernel#sprintf for format string details.

  def printf(s, *args)
    do_write(s % args)
    nil
  end

  ##
  # Flushes buffered data to the SSLSocket.

  def flush
    osync = @sync
    @sync = true
    do_write ""
    return self
  ensure
    @sync = osync
  end

  ##
  # Closes the SSLSocket and flushes any unwritten data.

  def close
    flush rescue nil
    sysclose
  end
end
# frozen_string_literal: true
#--
# = Ruby-space predefined Cipher subclasses
#
# = Info
# 'OpenSSL for Ruby 2' project
# Copyright (C) 2002  Michal Rokos <m.rokos@sh.cvut.cz>
# All rights reserved.
#
# = Licence
# This program is licensed under the same licence as Ruby.
# (See the file 'LICENCE'.)
#++

module OpenSSL
  class Cipher
    %w(AES CAST5 BF DES IDEA RC2 RC4 RC5).each{|name|
      klass = Class.new(Cipher){
        define_method(:initialize){|*args|
          cipher_name = args.inject(name){|n, arg| "#{n}-#{arg}" }
          super(cipher_name.downcase)
        }
      }
      const_set(name, klass)
    }

    %w(128 192 256).each{|keylen|
      klass = Class.new(Cipher){
        define_method(:initialize){|mode = "CBC"|
          super("aes-#{keylen}-#{mode}".downcase)
        }
      }
      const_set("AES#{keylen}", klass)
    }

    # call-seq:
    #   cipher.random_key -> key
    #
    # Generate a random key with OpenSSL::Random.random_bytes and sets it to
    # the cipher, and returns it.
    #
    # You must call #encrypt or #decrypt before calling this method.
    def random_key
      str = OpenSSL::Random.random_bytes(self.key_len)
      self.key = str
    end

    # call-seq:
    #   cipher.random_iv -> iv
    #
    # Generate a random IV with OpenSSL::Random.random_bytes and sets it to the
    # cipher, and returns it.
    #
    # You must call #encrypt or #decrypt before calling this method.
    def random_iv
      str = OpenSSL::Random.random_bytes(self.iv_len)
      self.iv = str
    end

    # Deprecated.
    #
    # This class is only provided for backwards compatibility.
    # Use OpenSSL::Cipher.
    class Cipher < Cipher; end
    deprecate_constant :Cipher
  end # Cipher
end # OpenSSL
# frozen_string_literal: true

module OpenSSL
  VERSION = "2.2.2"
end
# frozen_string_literal: true
#--
# Ruby/OpenSSL Project
# Copyright (C) 2017 Ruby/OpenSSL Project Authors
#++

require_relative 'marshal'

module OpenSSL::PKey
  class DH
    include OpenSSL::Marshal

    # :call-seq:
    #    dh.public_key -> dhnew
    #
    # Returns a new DH instance that carries just the \DH parameters.
    #
    # Contrary to the method name, the returned DH object contains only
    # parameters and not the public key.
    #
    # This method is provided for backwards compatibility. In most cases, there
    # is no need to call this method.
    #
    # For the purpose of re-generating the key pair while keeping the
    # parameters, check OpenSSL::PKey.generate_key.
    #
    # Example:
    #   # OpenSSL::PKey::DH.generate by default generates a random key pair
    #   dh1 = OpenSSL::PKey::DH.generate(2048)
    #   p dh1.priv_key #=> #<OpenSSL::BN 1288347...>
    #   dhcopy = dh1.public_key
    #   p dhcopy.priv_key #=> nil
    def public_key
      DH.new(to_der)
    end

    # :call-seq:
    #    dh.compute_key(pub_bn) -> string
    #
    # Returns a String containing a shared secret computed from the other
    # party's public value.
    #
    # This method is provided for backwards compatibility, and calls #derive
    # internally.
    #
    # === Parameters
    # * _pub_bn_ is a OpenSSL::BN, *not* the DH instance returned by
    #   DH#public_key as that contains the DH parameters only.
    def compute_key(pub_bn)
      # FIXME: This is constructing an X.509 SubjectPublicKeyInfo and is very
      # inefficient
      obj = OpenSSL::ASN1.Sequence([
        OpenSSL::ASN1.Sequence([
          OpenSSL::ASN1.ObjectId("dhKeyAgreement"),
          OpenSSL::ASN1.Sequence([
            OpenSSL::ASN1.Integer(p),
            OpenSSL::ASN1.Integer(g),
          ]),
        ]),
        OpenSSL::ASN1.BitString(OpenSSL::ASN1.Integer(pub_bn).to_der),
      ])
      derive(OpenSSL::PKey.read(obj.to_der))
    end

    # :call-seq:
    #    dh.generate_key! -> self
    #
    # Generates a private and public key unless a private key already exists.
    # If this DH instance was generated from public \DH parameters (e.g. by
    # encoding the result of DH#public_key), then this method needs to be
    # called first in order to generate the per-session keys before performing
    # the actual key exchange.
    #
    # <b>Deprecated in version 3.0</b>. This method is incompatible with
    # OpenSSL 3.0.0 or later.
    #
    # See also OpenSSL::PKey.generate_key.
    #
    # Example:
    #   # DEPRECATED USAGE: This will not work on OpenSSL 3.0 or later
    #   dh0 = OpenSSL::PKey::DH.new(2048)
    #   dh = dh0.public_key # #public_key only copies the DH parameters (contrary to the name)
    #   dh.generate_key!
    #   puts dh.private? # => true
    #   puts dh0.pub_key == dh.pub_key #=> false
    #
    #   # With OpenSSL::PKey.generate_key
    #   dh0 = OpenSSL::PKey::DH.new(2048)
    #   dh = OpenSSL::PKey.generate_key(dh0)
    #   puts dh0.pub_key == dh.pub_key #=> false
    def generate_key!
      if OpenSSL::OPENSSL_VERSION_NUMBER >= 0x30000000
        raise DHError, "OpenSSL::PKey::DH is immutable on OpenSSL 3.0; " \
        "use OpenSSL::PKey.generate_key instead"
      end

      unless priv_key
        tmp = OpenSSL::PKey.generate_key(self)
        set_key(tmp.pub_key, tmp.priv_key)
      end
      self
    end

    class << self
      # :call-seq:
      #    DH.generate(size, generator = 2) -> dh
      #
      # Creates a new DH instance from scratch by generating random parameters
      # and a key pair.
      #
      # See also OpenSSL::PKey.generate_parameters and
      # OpenSSL::PKey.generate_key.
      #
      # +size+::
      #   The desired key size in bits.
      # +generator+::
      #   The generator.
      def generate(size, generator = 2, &blk)
        dhparams = OpenSSL::PKey.generate_parameters("DH", {
          "dh_paramgen_prime_len" => size,
          "dh_paramgen_generator" => generator,
        }, &blk)
        OpenSSL::PKey.generate_key(dhparams)
      end

      # Handle DH.new(size, generator) form here; new(str) and new() forms
      # are handled by #initialize
      def new(*args, &blk) # :nodoc:
        if args[0].is_a?(Integer)
          generate(*args, &blk)
        else
          super
        end
      end
    end
  end

  class DSA
    include OpenSSL::Marshal

    # :call-seq:
    #    dsa.public_key -> dsanew
    #
    # Returns a new DSA instance that carries just the \DSA parameters and the
    # public key.
    #
    # This method is provided for backwards compatibility. In most cases, there
    # is no need to call this method.
    #
    # For the purpose of serializing the public key, to PEM or DER encoding of
    # X.509 SubjectPublicKeyInfo format, check PKey#public_to_pem and
    # PKey#public_to_der.
    def public_key
      OpenSSL::PKey.read(public_to_der)
    end

    class << self
      # :call-seq:
      #    DSA.generate(size) -> dsa
      #
      # Creates a new DSA instance by generating a private/public key pair
      # from scratch.
      #
      # See also OpenSSL::PKey.generate_parameters and
      # OpenSSL::PKey.generate_key.
      #
      # +size+::
      #   The desired key size in bits.
      def generate(size, &blk)
        dsaparams = OpenSSL::PKey.generate_parameters("DSA", {
          "dsa_paramgen_bits" => size,
        }, &blk)
        OpenSSL::PKey.generate_key(dsaparams)
      end

      # Handle DSA.new(size) form here; new(str) and new() forms
      # are handled by #initialize
      def new(*args, &blk) # :nodoc:
        if args[0].is_a?(Integer)
          generate(*args, &blk)
        else
          super
        end
      end
    end

    # :call-seq:
    #    dsa.syssign(string) -> string
    #
    # Computes and returns the \DSA signature of +string+, where +string+ is
    # expected to be an already-computed message digest of the original input
    # data. The signature is issued using the private key of this DSA instance.
    #
    # <b>Deprecated in version 3.0</b>.
    # Consider using PKey::PKey#sign_raw and PKey::PKey#verify_raw instead.
    #
    # +string+::
    #   A message digest of the original input data to be signed.
    #
    # Example:
    #   dsa = OpenSSL::PKey::DSA.new(2048)
    #   doc = "Sign me"
    #   digest = OpenSSL::Digest.digest('SHA1', doc)
    #
    #   # With legacy #syssign and #sysverify:
    #   sig = dsa.syssign(digest)
    #   p dsa.sysverify(digest, sig) #=> true
    #
    #   # With #sign_raw and #verify_raw:
    #   sig = dsa.sign_raw(nil, digest)
    #   p dsa.verify_raw(nil, sig, digest) #=> true
    def syssign(string)
      q or raise OpenSSL::PKey::DSAError, "incomplete DSA"
      private? or raise OpenSSL::PKey::DSAError, "Private DSA key needed!"
      begin
        sign_raw(nil, string)
      rescue OpenSSL::PKey::PKeyError
        raise OpenSSL::PKey::DSAError, $!.message
      end
    end

    # :call-seq:
    #    dsa.sysverify(digest, sig) -> true | false
    #
    # Verifies whether the signature is valid given the message digest input.
    # It does so by validating +sig+ using the public key of this DSA instance.
    #
    # <b>Deprecated in version 3.0</b>.
    # Consider using PKey::PKey#sign_raw and PKey::PKey#verify_raw instead.
    #
    # +digest+::
    #   A message digest of the original input data to be signed.
    # +sig+::
    #   A \DSA signature value.
    def sysverify(digest, sig)
      verify_raw(nil, sig, digest)
    rescue OpenSSL::PKey::PKeyError
      raise OpenSSL::PKey::DSAError, $!.message
    end
  end

  if defined?(EC)
  class EC
    include OpenSSL::Marshal

    # :call-seq:
    #    key.dsa_sign_asn1(data) -> String
    #
    # <b>Deprecated in version 3.0</b>.
    # Consider using PKey::PKey#sign_raw and PKey::PKey#verify_raw instead.
    def dsa_sign_asn1(data)
      sign_raw(nil, data)
    rescue OpenSSL::PKey::PKeyError
      raise OpenSSL::PKey::ECError, $!.message
    end

    # :call-seq:
    #    key.dsa_verify_asn1(data, sig) -> true | false
    #
    # <b>Deprecated in version 3.0</b>.
    # Consider using PKey::PKey#sign_raw and PKey::PKey#verify_raw instead.
    def dsa_verify_asn1(data, sig)
      verify_raw(nil, sig, data)
    rescue OpenSSL::PKey::PKeyError
      raise OpenSSL::PKey::ECError, $!.message
    end

    # :call-seq:
    #    ec.dh_compute_key(pubkey) -> string
    #
    # Derives a shared secret by ECDH. _pubkey_ must be an instance of
    # OpenSSL::PKey::EC::Point and must belong to the same group.
    #
    # This method is provided for backwards compatibility, and calls #derive
    # internally.
    def dh_compute_key(pubkey)
      obj = OpenSSL::ASN1.Sequence([
        OpenSSL::ASN1.Sequence([
          OpenSSL::ASN1.ObjectId("id-ecPublicKey"),
          group.to_der,
        ]),
        OpenSSL::ASN1.BitString(pubkey.to_octet_string(:uncompressed)),
      ])
      derive(OpenSSL::PKey.read(obj.to_der))
    end
  end

  class EC::Point
    # :call-seq:
    #    point.to_bn([conversion_form]) -> OpenSSL::BN
    #
    # Returns the octet string representation of the EC point as an instance of
    # OpenSSL::BN.
    #
    # If _conversion_form_ is not given, the _point_conversion_form_ attribute
    # set to the group is used.
    #
    # See #to_octet_string for more information.
    def to_bn(conversion_form = group.point_conversion_form)
      OpenSSL::BN.new(to_octet_string(conversion_form), 2)
    end
  end
  end

  class RSA
    include OpenSSL::Marshal

    # :call-seq:
    #    rsa.public_key -> rsanew
    #
    # Returns a new RSA instance that carries just the public key components.
    #
    # This method is provided for backwards compatibility. In most cases, there
    # is no need to call this method.
    #
    # For the purpose of serializing the public key, to PEM or DER encoding of
    # X.509 SubjectPublicKeyInfo format, check PKey#public_to_pem and
    # PKey#public_to_der.
    def public_key
      OpenSSL::PKey.read(public_to_der)
    end

    class << self
      # :call-seq:
      #    RSA.generate(size, exponent = 65537) -> RSA
      #
      # Generates an \RSA keypair.
      #
      # See also OpenSSL::PKey.generate_key.
      #
      # +size+::
      #   The desired key size in bits.
      # +exponent+::
      #   An odd Integer, normally 3, 17, or 65537.
      def generate(size, exp = 0x10001, &blk)
        OpenSSL::PKey.generate_key("RSA", {
          "rsa_keygen_bits" => size,
          "rsa_keygen_pubexp" => exp,
        }, &blk)
      end

      # Handle RSA.new(size, exponent) form here; new(str) and new() forms
      # are handled by #initialize
      def new(*args, &blk) # :nodoc:
        if args[0].is_a?(Integer)
          generate(*args, &blk)
        else
          super
        end
      end
    end

    # :call-seq:
    #    rsa.private_encrypt(string)          -> String
    #    rsa.private_encrypt(string, padding) -> String
    #
    # Encrypt +string+ with the private key.  +padding+ defaults to
    # PKCS1_PADDING. The encrypted string output can be decrypted using
    # #public_decrypt.
    #
    # <b>Deprecated in version 3.0</b>.
    # Consider using PKey::PKey#sign_raw and PKey::PKey#verify_raw, and
    # PKey::PKey#verify_recover instead.
    def private_encrypt(string, padding = PKCS1_PADDING)
      n or raise OpenSSL::PKey::RSAError, "incomplete RSA"
      private? or raise OpenSSL::PKey::RSAError, "private key needed."
      begin
        sign_raw(nil, string, {
          "rsa_padding_mode" => translate_padding_mode(padding),
        })
      rescue OpenSSL::PKey::PKeyError
        raise OpenSSL::PKey::RSAError, $!.message
      end
    end

    # :call-seq:
    #    rsa.public_decrypt(string)          -> String
    #    rsa.public_decrypt(string, padding) -> String
    #
    # Decrypt +string+, which has been encrypted with the private key, with the
    # public key.  +padding+ defaults to PKCS1_PADDING.
    #
    # <b>Deprecated in version 3.0</b>.
    # Consider using PKey::PKey#sign_raw and PKey::PKey#verify_raw, and
    # PKey::PKey#verify_recover instead.
    def public_decrypt(string, padding = PKCS1_PADDING)
      n or raise OpenSSL::PKey::RSAError, "incomplete RSA"
      begin
        verify_recover(nil, string, {
          "rsa_padding_mode" => translate_padding_mode(padding),
        })
      rescue OpenSSL::PKey::PKeyError
        raise OpenSSL::PKey::RSAError, $!.message
      end
    end

    # :call-seq:
    #    rsa.public_encrypt(string)          -> String
    #    rsa.public_encrypt(string, padding) -> String
    #
    # Encrypt +string+ with the public key.  +padding+ defaults to
    # PKCS1_PADDING. The encrypted string output can be decrypted using
    # #private_decrypt.
    #
    # <b>Deprecated in version 3.0</b>.
    # Consider using PKey::PKey#encrypt and PKey::PKey#decrypt instead.
    def public_encrypt(data, padding = PKCS1_PADDING)
      n or raise OpenSSL::PKey::RSAError, "incomplete RSA"
      begin
        encrypt(data, {
          "rsa_padding_mode" => translate_padding_mode(padding),
        })
      rescue OpenSSL::PKey::PKeyError
        raise OpenSSL::PKey::RSAError, $!.message
      end
    end

    # :call-seq:
    #    rsa.private_decrypt(string)          -> String
    #    rsa.private_decrypt(string, padding) -> String
    #
    # Decrypt +string+, which has been encrypted with the public key, with the
    # private key. +padding+ defaults to PKCS1_PADDING.
    #
    # <b>Deprecated in version 3.0</b>.
    # Consider using PKey::PKey#encrypt and PKey::PKey#decrypt instead.
    def private_decrypt(data, padding = PKCS1_PADDING)
      n or raise OpenSSL::PKey::RSAError, "incomplete RSA"
      private? or raise OpenSSL::PKey::RSAError, "private key needed."
      begin
        decrypt(data, {
          "rsa_padding_mode" => translate_padding_mode(padding),
        })
      rescue OpenSSL::PKey::PKeyError
        raise OpenSSL::PKey::RSAError, $!.message
      end
    end

    PKCS1_PADDING = 1
    SSLV23_PADDING = 2
    NO_PADDING = 3
    PKCS1_OAEP_PADDING = 4

    private def translate_padding_mode(num)
      case num
      when PKCS1_PADDING
        "pkcs1"
      when SSLV23_PADDING
        "sslv23"
      when NO_PADDING
        "none"
      when PKCS1_OAEP_PADDING
        "oaep"
      else
        raise OpenSSL::PKey::PKeyError, "unsupported padding mode"
      end
    end
  end
end
# frozen_string_literal: true
#--
# Copyright (c) 2001,2003 Akinori MUSHA <knu@iDaemons.org>
#
# All rights reserved.  You can redistribute and/or modify it under
# the same terms as Ruby.
#
# $Idaemons: /home/cvs/rb/abbrev.rb,v 1.2 2001/05/30 09:37:45 knu Exp $
# $RoughId: abbrev.rb,v 1.4 2003/10/14 19:45:42 knu Exp $
# $Id$
#++

##
# Calculates the set of unambiguous abbreviations for a given set of strings.
#
#   require 'abbrev'
#   require 'pp'
#
#   pp Abbrev.abbrev(['ruby'])
#   #=>  {"ruby"=>"ruby", "rub"=>"ruby", "ru"=>"ruby", "r"=>"ruby"}
#
#   pp Abbrev.abbrev(%w{ ruby rules })
#
# _Generates:_
#   { "ruby"  =>  "ruby",
#     "rub"   =>  "ruby",
#     "rules" =>  "rules",
#     "rule"  =>  "rules",
#     "rul"   =>  "rules" }
#
# It also provides an array core extension, Array#abbrev.
#
#   pp %w{ summer winter }.abbrev
#
# _Generates:_
#   { "summer"  => "summer",
#     "summe"   => "summer",
#     "summ"    => "summer",
#     "sum"     => "summer",
#     "su"      => "summer",
#     "s"       => "summer",
#     "winter"  => "winter",
#     "winte"   => "winter",
#     "wint"    => "winter",
#     "win"     => "winter",
#     "wi"      => "winter",
#     "w"       => "winter" }

module Abbrev

  # Given a set of strings, calculate the set of unambiguous abbreviations for
  # those strings, and return a hash where the keys are all the possible
  # abbreviations and the values are the full strings.
  #
  # Thus, given +words+ is "car" and "cone", the keys pointing to "car" would
  # be "ca" and "car", while those pointing to "cone" would be "co", "con", and
  # "cone".
  #
  #   require 'abbrev'
  #
  #   Abbrev.abbrev(%w{ car cone })
  #   #=> {"ca"=>"car", "con"=>"cone", "co"=>"cone", "car"=>"car", "cone"=>"cone"}
  #
  # The optional +pattern+ parameter is a pattern or a string. Only input
  # strings that match the pattern or start with the string are included in the
  # output hash.
  #
  #   Abbrev.abbrev(%w{car box cone crab}, /b/)
  #   #=> {"box"=>"box", "bo"=>"box", "b"=>"box", "crab" => "crab"}
  #
  #   Abbrev.abbrev(%w{car box cone}, 'ca')
  #   #=> {"car"=>"car", "ca"=>"car"}
  def abbrev(words, pattern = nil)
    table = {}
    seen = Hash.new(0)

    if pattern.is_a?(String)
      pattern = /\A#{Regexp.quote(pattern)}/  # regard as a prefix
    end

    words.each do |word|
      next if word.empty?
      word.size.downto(1) { |len|
        abbrev = word[0...len]

        next if pattern && pattern !~ abbrev

        case seen[abbrev] += 1
        when 1
          table[abbrev] = word
        when 2
          table.delete(abbrev)
        else
          break
        end
      }
    end

    words.each do |word|
      next if pattern && pattern !~ word

      table[word] = word
    end

    table
  end

  module_function :abbrev
end

class Array
  # Calculates the set of unambiguous abbreviations for the strings in +self+.
  #
  #   require 'abbrev'
  #   %w{ car cone }.abbrev
  #   #=> {"car"=>"car", "ca"=>"car", "cone"=>"cone", "con"=>"cone", "co"=>"cone"}
  #
  # The optional +pattern+ parameter is a pattern or a string. Only input
  # strings that match the pattern or start with the string are included in the
  # output hash.
  #
  #   %w{ fast boat day }.abbrev(/^.a/)
  #   #=> {"fast"=>"fast", "fas"=>"fast", "fa"=>"fast", "day"=>"day", "da"=>"day"}
  #
  #   Abbrev.abbrev(%w{car box cone}, "ca")
  #   #=> {"car"=>"car", "ca"=>"car"}
  #
  # See also Abbrev.abbrev
  def abbrev(pattern = nil)
    Abbrev::abbrev(self, pattern)
  end
end
require "coverage.so"

module Coverage
  def self.line_stub(file)
    lines = File.foreach(file).map { nil }
    iseqs = [RubyVM::InstructionSequence.compile_file(file)]
    until iseqs.empty?
      iseq = iseqs.pop
      iseq.trace_points.each {|n, type| lines[n - 1] = 0 if type == :line }
      iseq.each_child {|child| iseqs << child }
    end
    lines
  end
end
class Reline::Config
  attr_reader :test_mode

  KEYSEQ_PATTERN = /\\(?:C|Control)-[A-Za-z_]|\\(?:M|Meta)-[0-9A-Za-z_]|\\(?:C|Control)-(?:M|Meta)-[A-Za-z_]|\\(?:M|Meta)-(?:C|Control)-[A-Za-z_]|\\e|\\[\\\"\'abdfnrtv]|\\\d{1,3}|\\x\h{1,2}|./

  class InvalidInputrc < RuntimeError
    attr_accessor :file, :lineno
  end

  VARIABLE_NAMES = %w{
    bind-tty-special-chars
    blink-matching-paren
    byte-oriented
    completion-ignore-case
    convert-meta
    disable-completion
    enable-keypad
    expand-tilde
    history-preserve-point
    history-size
    horizontal-scroll-mode
    input-meta
    keyseq-timeout
    mark-directories
    mark-modified-lines
    mark-symlinked-directories
    match-hidden-files
    meta-flag
    output-meta
    page-completions
    prefer-visible-bell
    print-completions-horizontally
    show-all-if-ambiguous
    show-all-if-unmodified
    visible-stats
    show-mode-in-prompt
    vi-cmd-mode-string
    vi-ins-mode-string
    emacs-mode-string
    enable-bracketed-paste
    isearch-terminators
  }
  VARIABLE_NAME_SYMBOLS = VARIABLE_NAMES.map { |v| :"#{v.tr(?-, ?_)}" }
  VARIABLE_NAME_SYMBOLS.each do |v|
    attr_accessor v
  end

  def initialize
    @additional_key_bindings = {} # from inputrc
    @default_key_bindings = {} # environment-dependent
    @skip_section = nil
    @if_stack = nil
    @editing_mode_label = :emacs
    @keymap_label = :emacs
    @key_actors = {}
    @key_actors[:emacs] = Reline::KeyActor::Emacs.new
    @key_actors[:vi_insert] = Reline::KeyActor::ViInsert.new
    @key_actors[:vi_command] = Reline::KeyActor::ViCommand.new
    @vi_cmd_mode_string = '(cmd)'
    @vi_ins_mode_string = '(ins)'
    @emacs_mode_string = '@'
    # https://tiswww.case.edu/php/chet/readline/readline.html#IDX25
    @history_size = -1 # unlimited
    @keyseq_timeout = 500
    @test_mode = false
  end

  def reset
    if editing_mode_is?(:vi_command)
      @editing_mode_label = :vi_insert
    end
    @additional_key_bindings = {}
    @default_key_bindings = {}
  end

  def editing_mode
    @key_actors[@editing_mode_label]
  end

  def editing_mode=(val)
    @editing_mode_label = val
  end

  def editing_mode_is?(*val)
    (val.respond_to?(:any?) ? val : [val]).any?(@editing_mode_label)
  end

  def keymap
    @key_actors[@keymap_label]
  end

  def inputrc_path
    case ENV['INPUTRC']
    when nil, ''
    else
      return File.expand_path(ENV['INPUTRC'])
    end

    # In the XDG Specification, if ~/.config/readline/inputrc exists, then
    # ~/.inputrc should not be read, but for compatibility with GNU Readline,
    # if ~/.inputrc exists, then it is given priority.
    home_rc_path = File.expand_path('~/.inputrc')
    return home_rc_path if File.exist?(home_rc_path)

    case path = ENV['XDG_CONFIG_HOME']
    when nil, ''
    else
      path = File.join(path, 'readline/inputrc')
      return path if File.exist?(path) and path == File.expand_path(path)
    end

    path = File.expand_path('~/.config/readline/inputrc')
    return path if File.exist?(path)

    return home_rc_path
  end

  def read(file = nil)
    file ||= inputrc_path
    begin
      if file.respond_to?(:readlines)
        lines = file.readlines
      else
        lines = File.readlines(file)
      end
    rescue Errno::ENOENT
      return nil
    end

    read_lines(lines, file)
    self
  rescue InvalidInputrc => e
    warn e.message
    nil
  end

  def key_bindings
    # override @default_key_bindings with @additional_key_bindings
    @default_key_bindings.merge(@additional_key_bindings)
  end

  def add_default_key_binding(keystroke, target)
    @default_key_bindings[keystroke] = target
  end

  def reset_default_key_bindings
    @default_key_bindings = {}
  end

  def read_lines(lines, file = nil)
    conditions = [@skip_section, @if_stack]
    @skip_section = nil
    @if_stack = []

    lines.each_with_index do |line, no|
      next if line.match(/\A\s*#/)

      no += 1

      line = line.chomp.lstrip
      if line.start_with?('$')
        handle_directive(line[1..-1], file, no)
        next
      end

      next if @skip_section

      case line
      when /^set +([^ ]+) +([^ ]+)/i
        var, value = $1.downcase, $2
        bind_variable(var, value)
        next
      when /\s*("#{KEYSEQ_PATTERN}+")\s*:\s*(.*)\s*$/o
        key, func_name = $1, $2
        keystroke, func = bind_key(key, func_name)
        next unless keystroke
        @additional_key_bindings[keystroke] = func
      end
    end
    unless @if_stack.empty?
      raise InvalidInputrc, "#{file}:#{@if_stack.last[1]}: unclosed if"
    end
  ensure
    @skip_section, @if_stack = conditions
  end

  def handle_directive(directive, file, no)
    directive, args = directive.split(' ')
    case directive
    when 'if'
      condition = false
      case args
      when 'mode'
      when 'term'
      when 'version'
      else # application name
        condition = true if args == 'Ruby'
        condition = true if args == 'Reline'
      end
      @if_stack << [file, no, @skip_section]
      @skip_section = !condition
    when 'else'
      if @if_stack.empty?
        raise InvalidInputrc, "#{file}:#{no}: unmatched else"
      end
      @skip_section = !@skip_section
    when 'endif'
      if @if_stack.empty?
        raise InvalidInputrc, "#{file}:#{no}: unmatched endif"
      end
      @skip_section = @if_stack.pop
    when 'include'
      read(args)
    end
  end

  def bind_variable(name, value)
    case name
    when 'history-size'
      begin
        @history_size = Integer(value)
      rescue ArgumentError
        @history_size = 500
      end
    when 'bell-style'
      @bell_style =
        case value
        when 'none', 'off'
          :none
        when 'audible', 'on'
          :audible
        when 'visible'
          :visible
        else
          :audible
        end
    when 'comment-begin'
      @comment_begin = value.dup
    when 'completion-query-items'
      @completion_query_items = value.to_i
    when 'isearch-terminators'
      @isearch_terminators = retrieve_string(value)
    when 'editing-mode'
      case value
      when 'emacs'
        @editing_mode_label = :emacs
        @keymap_label = :emacs
      when 'vi'
        @editing_mode_label = :vi_insert
        @keymap_label = :vi_insert
      end
    when 'keymap'
      case value
      when 'emacs', 'emacs-standard', 'emacs-meta', 'emacs-ctlx'
        @keymap_label = :emacs
      when 'vi', 'vi-move', 'vi-command'
        @keymap_label = :vi_command
      when 'vi-insert'
        @keymap_label = :vi_insert
      end
    when 'keyseq-timeout'
      @keyseq_timeout = value.to_i
    when 'show-mode-in-prompt'
      case value
      when 'off'
        @show_mode_in_prompt = false
      when 'on'
        @show_mode_in_prompt = true
      else
        @show_mode_in_prompt = false
      end
    when 'vi-cmd-mode-string'
      @vi_cmd_mode_string = retrieve_string(value)
    when 'vi-ins-mode-string'
      @vi_ins_mode_string = retrieve_string(value)
    when 'emacs-mode-string'
      @emacs_mode_string = retrieve_string(value)
    when *VARIABLE_NAMES then
      variable_name = :"@#{name.tr(?-, ?_)}"
      instance_variable_set(variable_name, value.nil? || value == '1' || value == 'on')
    end
  end

  def retrieve_string(str)
    if str =~ /\A"(.*)"\z/
      parse_keyseq($1).map(&:chr).join
    else
      parse_keyseq(str).map(&:chr).join
    end
  end

  def bind_key(key, func_name)
    if key =~ /\A"(.*)"\z/
      keyseq = parse_keyseq($1)
    else
      keyseq = nil
    end
    if func_name =~ /"(.*)"/
      func = parse_keyseq($1)
    else
      func = func_name.tr(?-, ?_).to_sym # It must be macro.
    end
    [keyseq, func]
  end

  def key_notation_to_code(notation)
    case notation
    when /\\(?:C|Control)-([A-Za-z_])/
      (1 + $1.downcase.ord - ?a.ord)
    when /\\(?:M|Meta)-([0-9A-Za-z_])/
      modified_key = $1
      case $1
      when /[0-9]/
        ?\M-0.bytes.first + (modified_key.ord - ?0.ord)
      when /[A-Z]/
        ?\M-A.bytes.first + (modified_key.ord - ?A.ord)
      when /[a-z]/
        ?\M-a.bytes.first + (modified_key.ord - ?a.ord)
      end
    when /\\(?:C|Control)-(?:M|Meta)-[A-Za-z_]/, /\\(?:M|Meta)-(?:C|Control)-[A-Za-z_]/
    # 129 M-^A
    when /\\(\d{1,3})/ then $1.to_i(8) # octal
    when /\\x(\h{1,2})/ then $1.to_i(16) # hexadecimal
    when "\\e" then ?\e.ord
    when "\\\\" then ?\\.ord
    when "\\\"" then ?".ord
    when "\\'" then ?'.ord
    when "\\a" then ?\a.ord
    when "\\b" then ?\b.ord
    when "\\d" then ?\d.ord
    when "\\f" then ?\f.ord
    when "\\n" then ?\n.ord
    when "\\r" then ?\r.ord
    when "\\t" then ?\t.ord
    when "\\v" then ?\v.ord
    else notation.ord
    end
  end

  def parse_keyseq(str)
    ret = []
    str.scan(KEYSEQ_PATTERN) do
      ret << key_notation_to_code($&)
    end
    ret
  end
end
require 'fiddle/import'

class Reline::Windows
  def self.encoding
    Encoding::UTF_8
  end

  def self.win?
    true
  end

  def self.win_legacy_console?
    @@legacy_console
  end

  RAW_KEYSTROKE_CONFIG = {
    [224, 72] => :ed_prev_history, # ↑
    [224, 80] => :ed_next_history, # ↓
    [224, 77] => :ed_next_char,    # →
    [224, 75] => :ed_prev_char,    # ←
    [224, 83] => :key_delete,      # Del
    [224, 71] => :ed_move_to_beg,  # Home
    [224, 79] => :ed_move_to_end,  # End
    [  0, 41] => :ed_unassigned,   # input method on/off
    [  0, 72] => :ed_prev_history, # ↑
    [  0, 80] => :ed_next_history, # ↓
    [  0, 77] => :ed_next_char,    # →
    [  0, 75] => :ed_prev_char,    # ←
    [  0, 83] => :key_delete,      # Del
    [  0, 71] => :ed_move_to_beg,  # Home
    [  0, 79] => :ed_move_to_end   # End
  }

  if defined? JRUBY_VERSION
    require 'win32api'
  else
    class Win32API
      DLL = {}
      TYPEMAP = {"0" => Fiddle::TYPE_VOID, "S" => Fiddle::TYPE_VOIDP, "I" => Fiddle::TYPE_LONG}
      POINTER_TYPE = Fiddle::SIZEOF_VOIDP == Fiddle::SIZEOF_LONG_LONG ? 'q*' : 'l!*'

      WIN32_TYPES = "VPpNnLlIi"
      DL_TYPES = "0SSI"

      def initialize(dllname, func, import, export = "0", calltype = :stdcall)
        @proto = [import].join.tr(WIN32_TYPES, DL_TYPES).sub(/^(.)0*$/, '\1')
        import = @proto.chars.map {|win_type| TYPEMAP[win_type.tr(WIN32_TYPES, DL_TYPES)]}
        export = TYPEMAP[export.tr(WIN32_TYPES, DL_TYPES)]
        calltype = Fiddle::Importer.const_get(:CALL_TYPE_TO_ABI)[calltype]

        handle = DLL[dllname] ||=
                 begin
                   Fiddle.dlopen(dllname)
                 rescue Fiddle::DLError
                   raise unless File.extname(dllname).empty?
                   Fiddle.dlopen(dllname + ".dll")
                 end

        @func = Fiddle::Function.new(handle[func], import, export, calltype)
      rescue Fiddle::DLError => e
        raise LoadError, e.message, e.backtrace
      end

      def call(*args)
        import = @proto.split("")
        args.each_with_index do |x, i|
          args[i], = [x == 0 ? nil : x].pack("p").unpack(POINTER_TYPE) if import[i] == "S"
          args[i], = [x].pack("I").unpack("i") if import[i] == "I"
        end
        ret, = @func.call(*args)
        return ret || 0
      end
    end
  end

  VK_MENU = 0x12
  VK_LMENU = 0xA4
  VK_CONTROL = 0x11
  VK_SHIFT = 0x10
  STD_INPUT_HANDLE = -10
  STD_OUTPUT_HANDLE = -11
  WINDOW_BUFFER_SIZE_EVENT = 0x04
  FILE_TYPE_PIPE = 0x0003
  FILE_NAME_INFO = 2
  @@getwch = Win32API.new('msvcrt', '_getwch', [], 'I')
  @@kbhit = Win32API.new('msvcrt', '_kbhit', [], 'I')
  @@GetKeyState = Win32API.new('user32', 'GetKeyState', ['L'], 'L')
  @@GetConsoleScreenBufferInfo = Win32API.new('kernel32', 'GetConsoleScreenBufferInfo', ['L', 'P'], 'L')
  @@SetConsoleCursorPosition = Win32API.new('kernel32', 'SetConsoleCursorPosition', ['L', 'L'], 'L')
  @@GetStdHandle = Win32API.new('kernel32', 'GetStdHandle', ['L'], 'L')
  @@FillConsoleOutputCharacter = Win32API.new('kernel32', 'FillConsoleOutputCharacter', ['L', 'L', 'L', 'L', 'P'], 'L')
  @@ScrollConsoleScreenBuffer = Win32API.new('kernel32', 'ScrollConsoleScreenBuffer', ['L', 'P', 'P', 'L', 'P'], 'L')
  @@hConsoleHandle = @@GetStdHandle.call(STD_OUTPUT_HANDLE)
  @@hConsoleInputHandle = @@GetStdHandle.call(STD_INPUT_HANDLE)
  @@GetNumberOfConsoleInputEvents = Win32API.new('kernel32', 'GetNumberOfConsoleInputEvents', ['L', 'P'], 'L')
  @@ReadConsoleInput = Win32API.new('kernel32', 'ReadConsoleInput', ['L', 'P', 'L', 'P'], 'L')
  @@GetFileType = Win32API.new('kernel32', 'GetFileType', ['L'], 'L')
  @@GetFileInformationByHandleEx = Win32API.new('kernel32', 'GetFileInformationByHandleEx', ['L', 'I', 'P', 'L'], 'I')
  @@FillConsoleOutputAttribute = Win32API.new('kernel32', 'FillConsoleOutputAttribute', ['L', 'L', 'L', 'L', 'P'], 'L')

  @@GetConsoleMode = Win32API.new('kernel32', 'GetConsoleMode', ['L', 'P'], 'L')
  @@SetConsoleMode = Win32API.new('kernel32', 'SetConsoleMode', ['L', 'L'], 'L')
  ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4

  private_class_method def self.getconsolemode
    mode = "\000\000\000\000"
    @@GetConsoleMode.call(@@hConsoleHandle, mode)
    mode.unpack1('L')
  end

  private_class_method def self.setconsolemode(mode)
    @@SetConsoleMode.call(@@hConsoleHandle, mode)
  end

  @@legacy_console = (getconsolemode() & ENABLE_VIRTUAL_TERMINAL_PROCESSING == 0)
  #if @@legacy_console
  #  setconsolemode(getconsolemode() | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
  #  @@legacy_console = (getconsolemode() & ENABLE_VIRTUAL_TERMINAL_PROCESSING == 0)
  #end

  @@input_buf = []
  @@output_buf = []

  def self.msys_tty?(io=@@hConsoleInputHandle)
    # check if fd is a pipe
    if @@GetFileType.call(io) != FILE_TYPE_PIPE
      return false
    end

    bufsize = 1024
    p_buffer = "\0" * bufsize
    res = @@GetFileInformationByHandleEx.call(io, FILE_NAME_INFO, p_buffer, bufsize - 2)
    return false if res == 0

    # get pipe name: p_buffer layout is:
    #   struct _FILE_NAME_INFO {
    #     DWORD FileNameLength;
    #     WCHAR FileName[1];
    #   } FILE_NAME_INFO
    len = p_buffer[0, 4].unpack("L")[0]
    name = p_buffer[4, len].encode(Encoding::UTF_8, Encoding::UTF_16LE, invalid: :replace)

    # Check if this could be a MSYS2 pty pipe ('\msys-XXXX-ptyN-XX')
    # or a cygwin pty pipe ('\cygwin-XXXX-ptyN-XX')
    name =~ /(msys-|cygwin-).*-pty/ ? true : false
  end

  def self.getwch
    unless @@input_buf.empty?
      return @@input_buf.shift
    end
    while @@kbhit.call == 0
      sleep(0.001)
    end
    until @@kbhit.call == 0
      ret = @@getwch.call
      if ret == 0 or ret == 0xE0
        @@input_buf << ret
        ret = @@getwch.call
        @@input_buf << ret
        return @@input_buf.shift
      end
      begin
        bytes = ret.chr(Encoding::UTF_8).bytes
        @@input_buf.push(*bytes)
      rescue Encoding::UndefinedConversionError
        @@input_buf << ret
        @@input_buf << @@getwch.call if ret == 224
      end
    end
    @@input_buf.shift
  end

  def self.getc
    num_of_events = 0.chr * 8
    while @@GetNumberOfConsoleInputEvents.(@@hConsoleInputHandle, num_of_events) != 0 and num_of_events.unpack('L').first > 0
      input_record = 0.chr * 18
      read_event = 0.chr * 4
      if @@ReadConsoleInput.(@@hConsoleInputHandle, input_record, 1, read_event) != 0
        event = input_record[0, 2].unpack('s*').first
        if event == WINDOW_BUFFER_SIZE_EVENT
          @@winch_handler.()
        end
      end
    end
    unless @@output_buf.empty?
      return @@output_buf.shift
    end
    input = getwch
    meta = (@@GetKeyState.call(VK_LMENU) & 0x80) != 0
    control = (@@GetKeyState.call(VK_CONTROL) & 0x80) != 0
    shift = (@@GetKeyState.call(VK_SHIFT) & 0x80) != 0
    force_enter = !input.instance_of?(Array) && (control or shift) && input == 0x0D
    if force_enter
      # It's treated as Meta+Enter on Windows
      @@output_buf.push("\e".ord)
      @@output_buf.push(input)
    else
      case input
      when 0x00
        meta = false
        @@output_buf.push(input)
        input = getwch
        @@output_buf.push(*input)
      when 0xE0
        @@output_buf.push(input)
        input = getwch
        @@output_buf.push(*input)
      when 0x03
        @@output_buf.push(input)
      else
        @@output_buf.push(input)
      end
    end
    if meta
      "\e".ord
    else
      @@output_buf.shift
    end
  end

  def self.ungetc(c)
    @@output_buf.unshift(c)
  end

  def self.in_pasting?
    not self.empty_buffer?
  end

  def self.empty_buffer?
    if not @@input_buf.empty?
      false
    elsif @@kbhit.call == 0
      true
    else
      false
    end
  end

  def self.get_screen_size
    csbi = 0.chr * 22
    @@GetConsoleScreenBufferInfo.call(@@hConsoleHandle, csbi)
    csbi[0, 4].unpack('SS').reverse
  end

  def self.cursor_pos
    csbi = 0.chr * 22
    @@GetConsoleScreenBufferInfo.call(@@hConsoleHandle, csbi)
    x = csbi[4, 2].unpack('s*').first
    y = csbi[6, 2].unpack('s*').first
    Reline::CursorPos.new(x, y)
  end

  def self.move_cursor_column(val)
    @@SetConsoleCursorPosition.call(@@hConsoleHandle, cursor_pos.y * 65536 + val)
  end

  def self.move_cursor_up(val)
    if val > 0
      y = cursor_pos.y - val
      y = 0 if y < 0
      @@SetConsoleCursorPosition.call(@@hConsoleHandle, y * 65536 + cursor_pos.x)
    elsif val < 0
      move_cursor_down(-val)
    end
  end

  def self.move_cursor_down(val)
    if val > 0
      screen_height = get_screen_size.first
      y = cursor_pos.y + val
      y = screen_height - 1 if y > (screen_height - 1)
      @@SetConsoleCursorPosition.call(@@hConsoleHandle, (cursor_pos.y + val) * 65536 + cursor_pos.x)
    elsif val < 0
      move_cursor_up(-val)
    end
  end

  def self.erase_after_cursor
    csbi = 0.chr * 24
    @@GetConsoleScreenBufferInfo.call(@@hConsoleHandle, csbi)
    cursor = csbi[4, 4].unpack('L').first
    written = 0.chr * 4
    @@FillConsoleOutputCharacter.call(@@hConsoleHandle, 0x20, get_screen_size.last - cursor_pos.x, cursor, written)
    @@FillConsoleOutputAttribute.call(@@hConsoleHandle, 0, get_screen_size.last - cursor_pos.x, cursor, written)
  end

  def self.scroll_down(val)
    return if val.zero?
    screen_height = get_screen_size.first
    val = screen_height - 1 if val > (screen_height - 1)
    scroll_rectangle = [0, val, get_screen_size.last, get_screen_size.first].pack('s4')
    destination_origin = 0 # y * 65536 + x
    fill = [' '.ord, 0].pack('SS')
    @@ScrollConsoleScreenBuffer.call(@@hConsoleHandle, scroll_rectangle, nil, destination_origin, fill)
  end

  def self.clear_screen
    csbi = 0.chr * 22
    return if @@GetConsoleScreenBufferInfo.call(@@hConsoleHandle, csbi) == 0
    buffer_width = csbi[0, 2].unpack('S').first
    attributes = csbi[8, 2].unpack('S').first
    _window_left, window_top, _window_right, window_bottom = *csbi[10,8].unpack('S*')
    fill_length = buffer_width * (window_bottom - window_top + 1)
    screen_topleft = window_top * 65536
    written = 0.chr * 4
    @@FillConsoleOutputCharacter.call(@@hConsoleHandle, 0x20, fill_length, screen_topleft, written)
    @@FillConsoleOutputAttribute.call(@@hConsoleHandle, attributes, fill_length, screen_topleft, written)
    @@SetConsoleCursorPosition.call(@@hConsoleHandle, screen_topleft)
  end

  def self.set_screen_size(rows, columns)
    raise NotImplementedError
  end

  def self.set_winch_handler(&handler)
    @@winch_handler = handler
  end

  def self.prep
    # do nothing
    nil
  end

  def self.deprep(otio)
    # do nothing
  end
end
class Reline::KillRing
  include Enumerable

  module State
    FRESH = :fresh
    CONTINUED = :continued
    PROCESSED = :processed
    YANK = :yank
  end

  RingPoint = Struct.new(:backward, :forward, :str) do
    def initialize(str)
      super(nil, nil, str)
    end

    def ==(other)
      object_id == other.object_id
    end
  end

  class RingBuffer
    attr_reader :size
    attr_reader :head

    def initialize(max = 1024)
      @max = max
      @size = 0
      @head = nil # reading head of ring-shaped tape
    end

    def <<(point)
      if @size.zero?
        @head = point
        @head.backward = @head
        @head.forward = @head
        @size = 1
      elsif @size >= @max
        tail = @head.forward
        new_tail = tail.forward
        @head.forward = point
        point.backward = @head
        new_tail.backward = point
        point.forward = new_tail
        @head = point
      else
        tail = @head.forward
        @head.forward = point
        point.backward = @head
        tail.backward = point
        point.forward = tail
        @head = point
        @size += 1
      end
    end

    def empty?
      @size.zero?
    end
  end

  def initialize(max = 1024)
    @ring = RingBuffer.new(max)
    @ring_pointer = nil
    @buffer = nil
    @state = State::FRESH
  end

  def append(string, before_p = false)
    case @state
    when State::FRESH, State::YANK
      @ring << RingPoint.new(string)
      @state = State::CONTINUED
    when State::CONTINUED, State::PROCESSED
      if before_p
        @ring.head.str.prepend(string)
      else
        @ring.head.str.concat(string)
      end
      @state = State::CONTINUED
    end
  end

  def process
    case @state
    when State::FRESH
      # nothing to do
    when State::CONTINUED
      @state = State::PROCESSED
    when State::PROCESSED
      @state = State::FRESH
    when State::YANK
      # nothing to do
    end
  end

  def yank
    unless @ring.empty?
      @state = State::YANK
      @ring_pointer = @ring.head
      @ring_pointer.str
    else
      nil
    end
  end

  def yank_pop
    if @state == State::YANK
      prev_yank = @ring_pointer.str
      @ring_pointer = @ring_pointer.backward
      [@ring_pointer.str, prev_yank]
    else
      nil
    end
  end

  def each
    start = head = @ring.head
    loop do
      break if head.nil?
      yield head.str
      head = head.backward
      break if head == start
    end
  end
end
class Reline::Unicode
  EscapedPairs = {
    0x00 => '^@',
    0x01 => '^A', # C-a
    0x02 => '^B',
    0x03 => '^C',
    0x04 => '^D',
    0x05 => '^E',
    0x06 => '^F',
    0x07 => '^G',
    0x08 => '^H', # Backspace
    0x09 => '^I',
    0x0A => '^J',
    0x0B => '^K',
    0x0C => '^L',
    0x0D => '^M', # Enter
    0x0E => '^N',
    0x0F => '^O',
    0x10 => '^P',
    0x11 => '^Q',
    0x12 => '^R',
    0x13 => '^S',
    0x14 => '^T',
    0x15 => '^U',
    0x16 => '^V',
    0x17 => '^W',
    0x18 => '^X',
    0x19 => '^Y',
    0x1A => '^Z', # C-z
    0x1B => '^[', # C-[ C-3
    0x1D => '^]', # C-]
    0x1E => '^^', # C-~ C-6
    0x1F => '^_', # C-_ C-7
    0x7F => '^?', # C-? C-8
  }
  EscapedChars = EscapedPairs.keys.map(&:chr)

  NON_PRINTING_START = "\1"
  NON_PRINTING_END = "\2"
  CSI_REGEXP = /\e\[[\d;]*[ABCDEFGHJKSTfminsuhl]/
  OSC_REGEXP = /\e\]\d+(?:;[^;]+)*\a/
  WIDTH_SCANNER = /\G(?:(#{NON_PRINTING_START})|(#{NON_PRINTING_END})|(#{CSI_REGEXP})|(#{OSC_REGEXP})|(\X))/o
  NON_PRINTING_START_INDEX = 0
  NON_PRINTING_END_INDEX = 1
  CSI_REGEXP_INDEX = 2
  OSC_REGEXP_INDEX = 3
  GRAPHEME_CLUSTER_INDEX = 4

  def self.get_mbchar_byte_size_by_first_char(c)
    # Checks UTF-8 character byte size
    case c.ord
    # 0b0xxxxxxx
    when ->(code) { (code ^ 0b10000000).allbits?(0b10000000) } then 1
    # 0b110xxxxx
    when ->(code) { (code ^ 0b00100000).allbits?(0b11100000) } then 2
    # 0b1110xxxx
    when ->(code) { (code ^ 0b00010000).allbits?(0b11110000) } then 3
    # 0b11110xxx
    when ->(code) { (code ^ 0b00001000).allbits?(0b11111000) } then 4
    # 0b111110xx
    when ->(code) { (code ^ 0b00000100).allbits?(0b11111100) } then 5
    # 0b1111110x
    when ->(code) { (code ^ 0b00000010).allbits?(0b11111110) } then 6
    # successor of mbchar
    else 0
    end
  end

  def self.escape_for_print(str)
    str.chars.map! { |gr|
      escaped = EscapedPairs[gr.ord]
      if escaped && gr != -"\n" && gr != -"\t"
        escaped
      else
        gr
      end
    }.join
  end

  require 'reline/unicode/east_asian_width'

  MBCharWidthRE = /
    (?<width_2_1>
      [#{ EscapedChars.map {|c| "\\x%02x" % c.ord }.join }] (?# ^ + char, such as ^M, ^H, ^[, ...)
    )
  | (?<width_3>^\u{2E3B}) (?# THREE-EM DASH)
  | (?<width_0>^\p{M})
  | (?<width_2_2>
      #{ EastAsianWidth::TYPE_F }
    | #{ EastAsianWidth::TYPE_W }
    )
  | (?<width_1>
      #{ EastAsianWidth::TYPE_H }
    | #{ EastAsianWidth::TYPE_NA }
    | #{ EastAsianWidth::TYPE_N }
    )
  | (?<ambiguous_width>
      #{EastAsianWidth::TYPE_A}
    )
  /x

  def self.get_mbchar_width(mbchar)
    ord = mbchar.ord
    if (0x00 <= ord and ord <= 0x1F)
      return 2
    elsif (0x20 <= ord and ord <= 0x7E)
      return 1
    end
    m = mbchar.encode(Encoding::UTF_8).match(MBCharWidthRE)
    case
    when m.nil? then 1 # TODO should be U+FFFD � REPLACEMENT CHARACTER
    when m[:width_2_1], m[:width_2_2] then 2
    when m[:width_3] then 3
    when m[:width_0] then 0
    when m[:width_1] then 1
    when m[:ambiguous_width] then Reline.ambiguous_width
    else
      nil
    end
  end

  def self.calculate_width(str, allow_escape_code = false)
    if allow_escape_code
      width = 0
      rest = str.encode(Encoding::UTF_8)
      in_zero_width = false
      rest.scan(WIDTH_SCANNER) do |gc|
        case
        when gc[NON_PRINTING_START_INDEX]
          in_zero_width = true
        when gc[NON_PRINTING_END_INDEX]
          in_zero_width = false
        when gc[CSI_REGEXP_INDEX], gc[OSC_REGEXP_INDEX]
        when gc[GRAPHEME_CLUSTER_INDEX]
          gc = gc[GRAPHEME_CLUSTER_INDEX]
          unless in_zero_width
            width += get_mbchar_width(gc)
          end
        end
      end
      width
    else
      str.encode(Encoding::UTF_8).grapheme_clusters.inject(0) { |w, gc|
        w + get_mbchar_width(gc)
      }
    end
  end

  def self.split_by_width(str, max_width, encoding = str.encoding)
    lines = [String.new(encoding: encoding)]
    height = 1
    width = 0
    rest = str.encode(Encoding::UTF_8)
    in_zero_width = false
    rest.scan(WIDTH_SCANNER) do |gc|
      case
      when gc[NON_PRINTING_START_INDEX]
        in_zero_width = true
      when gc[NON_PRINTING_END_INDEX]
        in_zero_width = false
      when gc[CSI_REGEXP_INDEX]
        lines.last << gc[CSI_REGEXP_INDEX]
      when gc[OSC_REGEXP_INDEX]
        lines.last << gc[OSC_REGEXP_INDEX]
      when gc[GRAPHEME_CLUSTER_INDEX]
        gc = gc[GRAPHEME_CLUSTER_INDEX]
        unless in_zero_width
          mbchar_width = get_mbchar_width(gc)
          if (width += mbchar_width) > max_width
            width = mbchar_width
            lines << nil
            lines << String.new(encoding: encoding)
            height += 1
          end
        end
        lines.last << gc
      end
    end
    # The cursor moves to next line in first
    if width == max_width
      lines << nil
      lines << String.new(encoding: encoding)
      height += 1
    end
    [lines, height]
  end

  def self.get_next_mbchar_size(line, byte_pointer)
    grapheme = line.byteslice(byte_pointer..-1).grapheme_clusters.first
    grapheme ? grapheme.bytesize : 0
  end

  def self.get_prev_mbchar_size(line, byte_pointer)
    if byte_pointer.zero?
      0
    else
      grapheme = line.byteslice(0..(byte_pointer - 1)).grapheme_clusters.last
      grapheme ? grapheme.bytesize : 0
    end
  end

  def self.em_forward_word(line, byte_pointer)
    width = 0
    byte_size = 0
    while line.bytesize > (byte_pointer + byte_size)
      size = get_next_mbchar_size(line, byte_pointer + byte_size)
      mbchar = line.byteslice(byte_pointer + byte_size, size)
      break if mbchar.encode(Encoding::UTF_8) =~ /\p{Word}/
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    while line.bytesize > (byte_pointer + byte_size)
      size = get_next_mbchar_size(line, byte_pointer + byte_size)
      mbchar = line.byteslice(byte_pointer + byte_size, size)
      break if mbchar.encode(Encoding::UTF_8) =~ /\P{Word}/
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    [byte_size, width]
  end

  def self.em_forward_word_with_capitalization(line, byte_pointer)
    width = 0
    byte_size = 0
    new_str = String.new
    while line.bytesize > (byte_pointer + byte_size)
      size = get_next_mbchar_size(line, byte_pointer + byte_size)
      mbchar = line.byteslice(byte_pointer + byte_size, size)
      break if mbchar.encode(Encoding::UTF_8) =~ /\p{Word}/
      new_str += mbchar
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    first = true
    while line.bytesize > (byte_pointer + byte_size)
      size = get_next_mbchar_size(line, byte_pointer + byte_size)
      mbchar = line.byteslice(byte_pointer + byte_size, size)
      break if mbchar.encode(Encoding::UTF_8) =~ /\P{Word}/
      if first
        new_str += mbchar.upcase
        first = false
      else
        new_str += mbchar.downcase
      end
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    [byte_size, width, new_str]
  end

  def self.em_backward_word(line, byte_pointer)
    width = 0
    byte_size = 0
    while 0 < (byte_pointer - byte_size)
      size = get_prev_mbchar_size(line, byte_pointer - byte_size)
      mbchar = line.byteslice(byte_pointer - byte_size - size, size)
      break if mbchar.encode(Encoding::UTF_8) =~ /\p{Word}/
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    while 0 < (byte_pointer - byte_size)
      size = get_prev_mbchar_size(line, byte_pointer - byte_size)
      mbchar = line.byteslice(byte_pointer - byte_size - size, size)
      break if mbchar.encode(Encoding::UTF_8) =~ /\P{Word}/
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    [byte_size, width]
  end

  def self.em_big_backward_word(line, byte_pointer)
    width = 0
    byte_size = 0
    while 0 < (byte_pointer - byte_size)
      size = get_prev_mbchar_size(line, byte_pointer - byte_size)
      mbchar = line.byteslice(byte_pointer - byte_size - size, size)
      break if mbchar =~ /\S/
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    while 0 < (byte_pointer - byte_size)
      size = get_prev_mbchar_size(line, byte_pointer - byte_size)
      mbchar = line.byteslice(byte_pointer - byte_size - size, size)
      break if mbchar =~ /\s/
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    [byte_size, width]
  end

  def self.ed_transpose_words(line, byte_pointer)
    right_word_start = nil
    size = get_next_mbchar_size(line, byte_pointer)
    mbchar = line.byteslice(byte_pointer, size)
    if size.zero?
      # ' aaa bbb [cursor]'
      byte_size = 0
      while 0 < (byte_pointer + byte_size)
        size = get_prev_mbchar_size(line, byte_pointer + byte_size)
        mbchar = line.byteslice(byte_pointer + byte_size - size, size)
        break if mbchar.encode(Encoding::UTF_8) =~ /\p{Word}/
        byte_size -= size
      end
      while 0 < (byte_pointer + byte_size)
        size = get_prev_mbchar_size(line, byte_pointer + byte_size)
        mbchar = line.byteslice(byte_pointer + byte_size - size, size)
        break if mbchar.encode(Encoding::UTF_8) =~ /\P{Word}/
        byte_size -= size
      end
      right_word_start = byte_pointer + byte_size
      byte_size = 0
      while line.bytesize > (byte_pointer + byte_size)
        size = get_next_mbchar_size(line, byte_pointer + byte_size)
        mbchar = line.byteslice(byte_pointer + byte_size, size)
        break if mbchar.encode(Encoding::UTF_8) =~ /\P{Word}/
        byte_size += size
      end
      after_start = byte_pointer + byte_size
    elsif mbchar.encode(Encoding::UTF_8) =~ /\p{Word}/
      # ' aaa bb[cursor]b'
      byte_size = 0
      while 0 < (byte_pointer + byte_size)
        size = get_prev_mbchar_size(line, byte_pointer + byte_size)
        mbchar = line.byteslice(byte_pointer + byte_size - size, size)
        break if mbchar.encode(Encoding::UTF_8) =~ /\P{Word}/
        byte_size -= size
      end
      right_word_start = byte_pointer + byte_size
      byte_size = 0
      while line.bytesize > (byte_pointer + byte_size)
        size = get_next_mbchar_size(line, byte_pointer + byte_size)
        mbchar = line.byteslice(byte_pointer + byte_size, size)
        break if mbchar.encode(Encoding::UTF_8) =~ /\P{Word}/
        byte_size += size
      end
      after_start = byte_pointer + byte_size
    else
      byte_size = 0
      while (line.bytesize - 1) > (byte_pointer + byte_size)
        size = get_next_mbchar_size(line, byte_pointer + byte_size)
        mbchar = line.byteslice(byte_pointer + byte_size, size)
        break if mbchar.encode(Encoding::UTF_8) =~ /\p{Word}/
        byte_size += size
      end
      if (byte_pointer + byte_size) == (line.bytesize - 1)
        # ' aaa bbb [cursor] '
        after_start = line.bytesize
        while 0 < (byte_pointer + byte_size)
          size = get_prev_mbchar_size(line, byte_pointer + byte_size)
          mbchar = line.byteslice(byte_pointer + byte_size - size, size)
          break if mbchar.encode(Encoding::UTF_8) =~ /\p{Word}/
          byte_size -= size
        end
        while 0 < (byte_pointer + byte_size)
          size = get_prev_mbchar_size(line, byte_pointer + byte_size)
          mbchar = line.byteslice(byte_pointer + byte_size - size, size)
          break if mbchar.encode(Encoding::UTF_8) =~ /\P{Word}/
          byte_size -= size
        end
        right_word_start = byte_pointer + byte_size
      else
        # ' aaa [cursor] bbb '
        right_word_start = byte_pointer + byte_size
        while line.bytesize > (byte_pointer + byte_size)
          size = get_next_mbchar_size(line, byte_pointer + byte_size)
          mbchar = line.byteslice(byte_pointer + byte_size, size)
          break if mbchar.encode(Encoding::UTF_8) =~ /\P{Word}/
          byte_size += size
        end
        after_start = byte_pointer + byte_size
      end
    end
    byte_size = right_word_start - byte_pointer
    while 0 < (byte_pointer + byte_size)
      size = get_prev_mbchar_size(line, byte_pointer + byte_size)
      mbchar = line.byteslice(byte_pointer + byte_size - size, size)
      break if mbchar.encode(Encoding::UTF_8) =~ /\p{Word}/
      byte_size -= size
    end
    middle_start = byte_pointer + byte_size
    byte_size = middle_start - byte_pointer
    while 0 < (byte_pointer + byte_size)
      size = get_prev_mbchar_size(line, byte_pointer + byte_size)
      mbchar = line.byteslice(byte_pointer + byte_size - size, size)
      break if mbchar.encode(Encoding::UTF_8) =~ /\P{Word}/
      byte_size -= size
    end
    left_word_start = byte_pointer + byte_size
    [left_word_start, middle_start, right_word_start, after_start]
  end

  def self.vi_big_forward_word(line, byte_pointer)
    width = 0
    byte_size = 0
    while (line.bytesize - 1) > (byte_pointer + byte_size)
      size = get_next_mbchar_size(line, byte_pointer + byte_size)
      mbchar = line.byteslice(byte_pointer + byte_size, size)
      break if mbchar =~ /\s/
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    while (line.bytesize - 1) > (byte_pointer + byte_size)
      size = get_next_mbchar_size(line, byte_pointer + byte_size)
      mbchar = line.byteslice(byte_pointer + byte_size, size)
      break if mbchar =~ /\S/
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    [byte_size, width]
  end

  def self.vi_big_forward_end_word(line, byte_pointer)
    if (line.bytesize - 1) > byte_pointer
      size = get_next_mbchar_size(line, byte_pointer)
      mbchar = line.byteslice(byte_pointer, size)
      width = get_mbchar_width(mbchar)
      byte_size = size
    else
      return [0, 0]
    end
    while (line.bytesize - 1) > (byte_pointer + byte_size)
      size = get_next_mbchar_size(line, byte_pointer + byte_size)
      mbchar = line.byteslice(byte_pointer + byte_size, size)
      break if mbchar =~ /\S/
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    prev_width = width
    prev_byte_size = byte_size
    while line.bytesize > (byte_pointer + byte_size)
      size = get_next_mbchar_size(line, byte_pointer + byte_size)
      mbchar = line.byteslice(byte_pointer + byte_size, size)
      break if mbchar =~ /\s/
      prev_width = width
      prev_byte_size = byte_size
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    [prev_byte_size, prev_width]
  end

  def self.vi_big_backward_word(line, byte_pointer)
    width = 0
    byte_size = 0
    while 0 < (byte_pointer - byte_size)
      size = get_prev_mbchar_size(line, byte_pointer - byte_size)
      mbchar = line.byteslice(byte_pointer - byte_size - size, size)
      break if mbchar =~ /\S/
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    while 0 < (byte_pointer - byte_size)
      size = get_prev_mbchar_size(line, byte_pointer - byte_size)
      mbchar = line.byteslice(byte_pointer - byte_size - size, size)
      break if mbchar =~ /\s/
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    [byte_size, width]
  end

  def self.vi_forward_word(line, byte_pointer, drop_terminate_spaces = false)
    if line.bytesize > byte_pointer
      size = get_next_mbchar_size(line, byte_pointer)
      mbchar = line.byteslice(byte_pointer, size)
      if mbchar =~ /\w/
        started_by = :word
      elsif mbchar =~ /\s/
        started_by = :space
      else
        started_by = :non_word_printable
      end
      width = get_mbchar_width(mbchar)
      byte_size = size
    else
      return [0, 0]
    end
    while line.bytesize > (byte_pointer + byte_size)
      size = get_next_mbchar_size(line, byte_pointer + byte_size)
      mbchar = line.byteslice(byte_pointer + byte_size, size)
      case started_by
      when :word
        break if mbchar =~ /\W/
      when :space
        break if mbchar =~ /\S/
      when :non_word_printable
        break if mbchar =~ /\w|\s/
      end
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    return [byte_size, width] if drop_terminate_spaces
    while line.bytesize > (byte_pointer + byte_size)
      size = get_next_mbchar_size(line, byte_pointer + byte_size)
      mbchar = line.byteslice(byte_pointer + byte_size, size)
      break if mbchar =~ /\S/
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    [byte_size, width]
  end

  def self.vi_forward_end_word(line, byte_pointer)
    if (line.bytesize - 1) > byte_pointer
      size = get_next_mbchar_size(line, byte_pointer)
      mbchar = line.byteslice(byte_pointer, size)
      if mbchar =~ /\w/
        started_by = :word
      elsif mbchar =~ /\s/
        started_by = :space
      else
        started_by = :non_word_printable
      end
      width = get_mbchar_width(mbchar)
      byte_size = size
    else
      return [0, 0]
    end
    if (line.bytesize - 1) > (byte_pointer + byte_size)
      size = get_next_mbchar_size(line, byte_pointer + byte_size)
      mbchar = line.byteslice(byte_pointer + byte_size, size)
      if mbchar =~ /\w/
        second = :word
      elsif mbchar =~ /\s/
        second = :space
      else
        second = :non_word_printable
      end
      second_width = get_mbchar_width(mbchar)
      second_byte_size = size
    else
      return [byte_size, width]
    end
    if second == :space
      width += second_width
      byte_size += second_byte_size
      while (line.bytesize - 1) > (byte_pointer + byte_size)
        size = get_next_mbchar_size(line, byte_pointer + byte_size)
        mbchar = line.byteslice(byte_pointer + byte_size, size)
        if mbchar =~ /\S/
          if mbchar =~ /\w/
            started_by = :word
          else
            started_by = :non_word_printable
          end
          break
        end
        width += get_mbchar_width(mbchar)
        byte_size += size
      end
    else
      case [started_by, second]
      when [:word, :non_word_printable], [:non_word_printable, :word]
        started_by = second
      else
        width += second_width
        byte_size += second_byte_size
        started_by = second
      end
    end
    prev_width = width
    prev_byte_size = byte_size
    while line.bytesize > (byte_pointer + byte_size)
      size = get_next_mbchar_size(line, byte_pointer + byte_size)
      mbchar = line.byteslice(byte_pointer + byte_size, size)
      case started_by
      when :word
        break if mbchar =~ /\W/
      when :non_word_printable
        break if mbchar =~ /[\w\s]/
      end
      prev_width = width
      prev_byte_size = byte_size
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    [prev_byte_size, prev_width]
  end

  def self.vi_backward_word(line, byte_pointer)
    width = 0
    byte_size = 0
    while 0 < (byte_pointer - byte_size)
      size = get_prev_mbchar_size(line, byte_pointer - byte_size)
      mbchar = line.byteslice(byte_pointer - byte_size - size, size)
      if mbchar =~ /\S/
        if mbchar =~ /\w/
          started_by = :word
        else
          started_by = :non_word_printable
        end
        break
      end
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    while 0 < (byte_pointer - byte_size)
      size = get_prev_mbchar_size(line, byte_pointer - byte_size)
      mbchar = line.byteslice(byte_pointer - byte_size - size, size)
      case started_by
      when :word
        break if mbchar =~ /\W/
      when :non_word_printable
        break if mbchar =~ /[\w\s]/
      end
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    [byte_size, width]
  end

  def self.vi_first_print(line)
    width = 0
    byte_size = 0
    while (line.bytesize - 1) > byte_size
      size = get_next_mbchar_size(line, byte_size)
      mbchar = line.byteslice(byte_size, size)
      if mbchar =~ /\S/
        break
      end
      width += get_mbchar_width(mbchar)
      byte_size += size
    end
    [byte_size, width]
  end
end
require 'timeout'

class Reline::GeneralIO
  def self.reset
    @@pasting = false
  end

  def self.encoding
    RUBY_PLATFORM =~ /mswin|mingw/ ? Encoding::UTF_8 : Encoding::default_external
  end

  def self.win?
    false
  end

  RAW_KEYSTROKE_CONFIG = {}

  @@buf = []

  def self.input=(val)
    @@input = val
  end

  def self.getc
    unless @@buf.empty?
      return @@buf.shift
    end
    c = nil
    loop do
      result = select([@@input], [], [], 0.1)
      next if result.nil?
      c = @@input.read(1)
      break
    end
    c&.ord
  end

  def self.ungetc(c)
    @@buf.unshift(c)
  end

  def self.get_screen_size
    [1, 1]
  end

  def self.cursor_pos
    Reline::CursorPos.new(1, 1)
  end

  def self.move_cursor_column(val)
  end

  def self.move_cursor_up(val)
  end

  def self.move_cursor_down(val)
  end

  def self.erase_after_cursor
  end

  def self.scroll_down(val)
  end

  def self.clear_screen
  end

  def self.set_screen_size(rows, columns)
  end

  def self.set_winch_handler(&handler)
  end

  @@pasting = false

  def self.in_pasting?
    @@pasting
  end

  def self.start_pasting
    @@pasting = true
  end

  def self.finish_pasting
    @@pasting = false
  end

  def self.prep
  end

  def self.deprep(otio)
  end
end
module Reline::KeyActor
end

require 'reline/key_actor/base'
require 'reline/key_actor/emacs'
require 'reline/key_actor/vi_command'
require 'reline/key_actor/vi_insert'
class Reline::History < Array
  def initialize(config)
    @config = config
  end

  def to_s
    'HISTORY'
  end

  def delete_at(index)
    index = check_index(index)
    super(index)
  end

  def [](index)
    index = check_index(index) unless index.is_a?(Range)
    super(index)
  end

  def []=(index, val)
    index = check_index(index)
    super(index, String.new(val, encoding: Reline.encoding_system_needs))
  end

  def concat(*val)
    val.each do |v|
      push(*v)
    end
  end

  def push(*val)
    # If history_size is zero, all histories are dropped.
    return self if @config.history_size.zero?
    # If history_size is negative, history size is unlimited.
    if @config.history_size.positive?
      diff = size + val.size - @config.history_size
      if diff > 0
        if diff <= size
          shift(diff)
        else
          diff -= size
          clear
          val.shift(diff)
        end
      end
    end
    super(*(val.map{ |v|
      String.new(v, encoding: Reline.encoding_system_needs)
    }))
  end

  def <<(val)
    # If history_size is zero, all histories are dropped.
    return self if @config.history_size.zero?
    # If history_size is negative, history size is unlimited.
    if @config.history_size.positive?
      shift if size + 1 > @config.history_size
    end
    super(String.new(val, encoding: Reline.encoding_system_needs))
  end

  private def check_index(index)
    index += size if index < 0
    if index < -2147483648 or 2147483647 < index
      raise RangeError.new("integer #{index} too big to convert to `int'")
    end
    # If history_size is negative, history size is unlimited.
    if @config.history_size.positive?
      if index < -@config.history_size or @config.history_size < index
        raise RangeError.new("index=<#{index}>")
      end
    end
    raise IndexError.new("index=<#{index}>") if index < 0 or size <= index
    index
  end
end
require 'io/console'
require 'timeout'

class Reline::ANSI
  def self.encoding
    Encoding.default_external
  end

  def self.win?
    false
  end

  RAW_KEYSTROKE_CONFIG = {
    # Console (80x25)
    [27, 91, 49, 126] => :ed_move_to_beg, # Home
    [27, 91, 52, 126] => :ed_move_to_end, # End
    [27, 91, 51, 126] => :key_delete,     # Del
    [27, 91, 65] => :ed_prev_history,     # ↑
    [27, 91, 66] => :ed_next_history,     # ↓
    [27, 91, 67] => :ed_next_char,        # →
    [27, 91, 68] => :ed_prev_char,        # ←

    # KDE
    [27, 91, 72] => :ed_move_to_beg,      # Home
    [27, 91, 70] => :ed_move_to_end,      # End
    # Del is 0x08
    [27, 71, 65] => :ed_prev_history,     # ↑
    [27, 71, 66] => :ed_next_history,     # ↓
    [27, 71, 67] => :ed_next_char,        # →
    [27, 71, 68] => :ed_prev_char,        # ←

    # urxvt / exoterm
    [27, 91, 55, 126] => :ed_move_to_beg, # Home
    [27, 91, 56, 126] => :ed_move_to_end, # End

    # GNOME
    [27, 79, 72] => :ed_move_to_beg,      # Home
    [27, 79, 70] => :ed_move_to_end,      # End
    # Del is 0x08
    # Arrow keys are the same of KDE

    # iTerm2
    [27, 27, 91, 67] => :em_next_word,    # Option+→
    [27, 27, 91, 68] => :ed_prev_word,    # Option+←
    [195, 166] => :em_next_word,          # Option+f
    [195, 162] => :ed_prev_word,          # Option+b

    # others
    [27, 32] => :em_set_mark,             # M-<space>
    [24, 24] => :em_exchange_mark,        # C-x C-x TODO also add Windows
    [27, 91, 49, 59, 53, 67] => :em_next_word, # Ctrl+→
    [27, 91, 49, 59, 53, 68] => :ed_prev_word, # Ctrl+←

    [27, 79, 65] => :ed_prev_history,     # ↑
    [27, 79, 66] => :ed_next_history,     # ↓
    [27, 79, 67] => :ed_next_char,        # →
    [27, 79, 68] => :ed_prev_char,        # ←
  }

  @@input = STDIN
  def self.input=(val)
    @@input = val
  end

  @@output = STDOUT
  def self.output=(val)
    @@output = val
  end

  @@buf = []
  def self.inner_getc
    unless @@buf.empty?
      return @@buf.shift
    end
    until c = @@input.raw(intr: true, &:getbyte)
      sleep 0.1
    end
    (c == 0x16 && @@input.raw(min: 0, tim: 0, &:getbyte)) || c
  rescue Errno::EIO
    # Maybe the I/O has been closed.
    nil
  end

  @@in_bracketed_paste_mode = false
  START_BRACKETED_PASTE = String.new("\e[200~,", encoding: Encoding::ASCII_8BIT)
  END_BRACKETED_PASTE = String.new("\e[200~.", encoding: Encoding::ASCII_8BIT)
  def self.getc_with_bracketed_paste
    buffer = String.new(encoding: Encoding::ASCII_8BIT)
    buffer << inner_getc
    while START_BRACKETED_PASTE.start_with?(buffer) or END_BRACKETED_PASTE.start_with?(buffer) do
      if START_BRACKETED_PASTE == buffer
        @@in_bracketed_paste_mode = true
        return inner_getc
      elsif END_BRACKETED_PASTE == buffer
        @@in_bracketed_paste_mode = false
        ungetc(-1)
        return inner_getc
      end
      begin
        succ_c = nil
        Timeout.timeout(Reline.core.config.keyseq_timeout * 100) {
          succ_c = inner_getc
        }
      rescue Timeout::Error
        break
      else
        buffer << succ_c
      end
    end
    buffer.bytes.reverse_each do |ch|
      ungetc ch
    end
    inner_getc
  end

  def self.getc
    if Reline.core.config.enable_bracketed_paste
      getc_with_bracketed_paste
    else
      inner_getc
    end
  end

  def self.in_pasting?
    @@in_bracketed_paste_mode or (not Reline::IOGate.empty_buffer?)
  end

  def self.empty_buffer?
    unless @@buf.empty?
      return false
    end
    rs, = IO.select([@@input], [], [], 0.00001)
    if rs and rs[0]
      false
    else
      true
    end
  end

  def self.ungetc(c)
    @@buf.unshift(c)
  end

  def self.retrieve_keybuffer
    begin
      result = select([@@input], [], [], 0.001)
      return if result.nil?
      str = @@input.read_nonblock(1024)
      str.bytes.each do |c|
        @@buf.push(c)
      end
    rescue EOFError
    end
  end

  def self.get_screen_size
    s = @@input.winsize
    return s if s[0] > 0 && s[1] > 0
    s = [ENV["LINES"].to_i, ENV["COLUMNS"].to_i]
    return s if s[0] > 0 && s[1] > 0
    [24, 80]
  rescue Errno::ENOTTY
    [24, 80]
  end

  def self.set_screen_size(rows, columns)
    @@input.winsize = [rows, columns]
    self
  rescue Errno::ENOTTY
    self
  end

  def self.cursor_pos
    begin
      res = +''
      m = nil
      @@input.raw do |stdin|
        @@output << "\e[6n"
        @@output.flush
        loop do
          c = stdin.getc
          next if c.nil?
          res << c
          m = res.match(/\e\[(?<row>\d+);(?<column>\d+)R/)
          break if m
        end
        (m.pre_match + m.post_match).chars.reverse_each do |ch|
          stdin.ungetc ch
        end
      end
      column = m[:column].to_i - 1
      row = m[:row].to_i - 1
    rescue Errno::ENOTTY
      begin
        buf = @@output.pread(@@output.pos, 0)
        row = buf.count("\n")
        column = buf.rindex("\n") ? (buf.size - buf.rindex("\n")) - 1 : 0
      rescue Errno::ESPIPE
        # Just returns column 1 for ambiguous width because this I/O is not
        # tty and can't seek.
        row = 0
        column = 1
      end
    end
    Reline::CursorPos.new(column, row)
  end

  def self.move_cursor_column(x)
    @@output.write "\e[#{x + 1}G"
  end

  def self.move_cursor_up(x)
    if x > 0
      @@output.write "\e[#{x}A" if x > 0
    elsif x < 0
      move_cursor_down(-x)
    end
  end

  def self.move_cursor_down(x)
    if x > 0
      @@output.write "\e[#{x}B" if x > 0
    elsif x < 0
      move_cursor_up(-x)
    end
  end

  def self.erase_after_cursor
    @@output.write "\e[K"
  end

  def self.scroll_down(x)
    return if x.zero?
    @@output.write "\e[#{x}S"
  end

  def self.clear_screen
    @@output.write "\e[2J"
    @@output.write "\e[1;1H"
  end

  @@old_winch_handler = nil
  def self.set_winch_handler(&handler)
    @@old_winch_handler = Signal.trap('WINCH', &handler)
  end

  def self.prep
    retrieve_keybuffer
    int_handle = Signal.trap('INT', 'IGNORE')
    Signal.trap('INT', int_handle)
    nil
  end

  def self.deprep(otio)
    int_handle = Signal.trap('INT', 'IGNORE')
    Signal.trap('INT', int_handle)
    Signal.trap('WINCH', @@old_winch_handler) if @@old_winch_handler
  end
end
class Reline::KeyStroke
  using Module.new {
    refine Array do
      def start_with?(other)
        other.size <= size && other == self.take(other.size)
      end

      def bytes
        self
      end
    end
  }

  def initialize(config)
    @config = config
  end

  def match_status(input)
    key_mapping.keys.select { |lhs|
      lhs.start_with? input
    }.tap { |it|
      return :matched  if it.size == 1 && (it.max_by(&:size)&.size&.== input.size)
      return :matching if it.size == 1 && (it.max_by(&:size)&.size&.!= input.size)
      return :matched  if it.max_by(&:size)&.size&.< input.size
      return :matching if it.size > 1
    }
    key_mapping.keys.select { |lhs|
      input.start_with? lhs
    }.tap { |it|
      return it.size > 0 ? :matched : :unmatched
    }
  end

  def expand(input)
    lhs = key_mapping.keys.select { |item| input.start_with? item }.sort_by(&:size).reverse.first
    return input unless lhs
    rhs = key_mapping[lhs]

    case rhs
    when String
      rhs_bytes = rhs.bytes
      expand(expand(rhs_bytes) + expand(input.drop(lhs.size)))
    when Symbol
      [rhs] + expand(input.drop(lhs.size))
    when Array
      rhs
    end
  end

  private

  def key_mapping
    @config.key_bindings
  end
end
class Reline::KeyActor::Base
  MAPPING = Array.new(256)

  def get_method(key)
    self.class::MAPPING[key]
  end
end
class Reline::KeyActor::ViInsert < Reline::KeyActor::Base
  MAPPING = [
    #   0 ^@
    :ed_unassigned,
    #   1 ^A
    :ed_insert,
    #   2 ^B
    :ed_insert,
    #   3 ^C
    :ed_insert,
    #   4 ^D
    :vi_list_or_eof,
    #   5 ^E
    :ed_insert,
    #   6 ^F
    :ed_insert,
    #   7 ^G
    :ed_insert,
    #   8 ^H
    :vi_delete_prev_char,
    #   9 ^I
    :ed_insert,
    #  10 ^J
    :ed_newline,
    #  11 ^K
    :ed_insert,
    #  12 ^L
    :ed_insert,
    #  13 ^M
    :ed_newline,
    #  14 ^N
    :ed_insert,
    #  15 ^O
    :ed_insert,
    #  16 ^P
    :ed_insert,
    #  17 ^Q
    :ed_ignore,
    #  18 ^R
    :vi_search_prev,
    #  19 ^S
    :vi_search_next,
    #  20 ^T
    :ed_insert,
    #  21 ^U
    :vi_kill_line_prev,
    #  22 ^V
    :ed_quoted_insert,
    #  23 ^W
    :ed_delete_prev_word,
    #  24 ^X
    :ed_insert,
    #  25 ^Y
    :ed_insert,
    #  26 ^Z
    :ed_insert,
    #  27 ^[
    :vi_command_mode,
    #  28 ^\
    :ed_ignore,
    #  29 ^]
    :ed_insert,
    #  30 ^^
    :ed_insert,
    #  31 ^_
    :ed_insert,
    #  32 SPACE
    :ed_insert,
    #  33 !
    :ed_insert,
    #  34 "
    :ed_insert,
    #  35 #
    :ed_insert,
    #  36 $
    :ed_insert,
    #  37 %
    :ed_insert,
    #  38 &
    :ed_insert,
    #  39 '
    :ed_insert,
    #  40 (
    :ed_insert,
    #  41 )
    :ed_insert,
    #  42 *
    :ed_insert,
    #  43 +
    :ed_insert,
    #  44 ,
    :ed_insert,
    #  45 -
    :ed_insert,
    #  46 .
    :ed_insert,
    #  47 /
    :ed_insert,
    #  48 0
    :ed_insert,
    #  49 1
    :ed_insert,
    #  50 2
    :ed_insert,
    #  51 3
    :ed_insert,
    #  52 4
    :ed_insert,
    #  53 5
    :ed_insert,
    #  54 6
    :ed_insert,
    #  55 7
    :ed_insert,
    #  56 8
    :ed_insert,
    #  57 9
    :ed_insert,
    #  58 :
    :ed_insert,
    #  59 ;
    :ed_insert,
    #  60 <
    :ed_insert,
    #  61 =
    :ed_insert,
    #  62 >
    :ed_insert,
    #  63 ?
    :ed_insert,
    #  64 @
    :ed_insert,
    #  65 A
    :ed_insert,
    #  66 B
    :ed_insert,
    #  67 C
    :ed_insert,
    #  68 D
    :ed_insert,
    #  69 E
    :ed_insert,
    #  70 F
    :ed_insert,
    #  71 G
    :ed_insert,
    #  72 H
    :ed_insert,
    #  73 I
    :ed_insert,
    #  74 J
    :ed_insert,
    #  75 K
    :ed_insert,
    #  76 L
    :ed_insert,
    #  77 M
    :ed_insert,
    #  78 N
    :ed_insert,
    #  79 O
    :ed_insert,
    #  80 P
    :ed_insert,
    #  81 Q
    :ed_insert,
    #  82 R
    :ed_insert,
    #  83 S
    :ed_insert,
    #  84 T
    :ed_insert,
    #  85 U
    :ed_insert,
    #  86 V
    :ed_insert,
    #  87 W
    :ed_insert,
    #  88 X
    :ed_insert,
    #  89 Y
    :ed_insert,
    #  90 Z
    :ed_insert,
    #  91 [
    :ed_insert,
    #  92 \
    :ed_insert,
    #  93 ]
    :ed_insert,
    #  94 ^
    :ed_insert,
    #  95 _
    :ed_insert,
    #  96 `
    :ed_insert,
    #  97 a
    :ed_insert,
    #  98 b
    :ed_insert,
    #  99 c
    :ed_insert,
    # 100 d
    :ed_insert,
    # 101 e
    :ed_insert,
    # 102 f
    :ed_insert,
    # 103 g
    :ed_insert,
    # 104 h
    :ed_insert,
    # 105 i
    :ed_insert,
    # 106 j
    :ed_insert,
    # 107 k
    :ed_insert,
    # 108 l
    :ed_insert,
    # 109 m
    :ed_insert,
    # 110 n
    :ed_insert,
    # 111 o
    :ed_insert,
    # 112 p
    :ed_insert,
    # 113 q
    :ed_insert,
    # 114 r
    :ed_insert,
    # 115 s
    :ed_insert,
    # 116 t
    :ed_insert,
    # 117 u
    :ed_insert,
    # 118 v
    :ed_insert,
    # 119 w
    :ed_insert,
    # 120 x
    :ed_insert,
    # 121 y
    :ed_insert,
    # 122 z
    :ed_insert,
    # 123 {
    :ed_insert,
    # 124 |
    :ed_insert,
    # 125 }
    :ed_insert,
    # 126 ~
    :ed_insert,
    # 127 ^?
    :vi_delete_prev_char,
    # 128 M-^@
    :ed_unassigned,
    # 129 M-^A
    :ed_unassigned,
    # 130 M-^B
    :ed_unassigned,
    # 131 M-^C
    :ed_unassigned,
    # 132 M-^D
    :ed_unassigned,
    # 133 M-^E
    :ed_unassigned,
    # 134 M-^F
    :ed_unassigned,
    # 135 M-^G
    :ed_unassigned,
    # 136 M-^H
    :ed_unassigned,
    # 137 M-^I
    :ed_unassigned,
    # 138 M-^J
    :key_newline,
    # 139 M-^K
    :ed_unassigned,
    # 140 M-^L
    :ed_unassigned,
    # 141 M-^M
    :key_newline,
    # 142 M-^N
    :ed_unassigned,
    # 143 M-^O
    :ed_unassigned,
    # 144 M-^P
    :ed_unassigned,
    # 145 M-^Q
    :ed_unassigned,
    # 146 M-^R
    :ed_unassigned,
    # 147 M-^S
    :ed_unassigned,
    # 148 M-^T
    :ed_unassigned,
    # 149 M-^U
    :ed_unassigned,
    # 150 M-^V
    :ed_unassigned,
    # 151 M-^W
    :ed_unassigned,
    # 152 M-^X
    :ed_unassigned,
    # 153 M-^Y
    :ed_unassigned,
    # 154 M-^Z
    :ed_unassigned,
    # 155 M-^[
    :ed_unassigned,
    # 156 M-^\
    :ed_unassigned,
    # 157 M-^]
    :ed_unassigned,
    # 158 M-^^
    :ed_unassigned,
    # 159 M-^_
    :ed_unassigned,
    # 160 M-SPACE
    :ed_unassigned,
    # 161 M-!
    :ed_unassigned,
    # 162 M-"
    :ed_unassigned,
    # 163 M-#
    :ed_unassigned,
    # 164 M-$
    :ed_unassigned,
    # 165 M-%
    :ed_unassigned,
    # 166 M-&
    :ed_unassigned,
    # 167 M-'
    :ed_unassigned,
    # 168 M-(
    :ed_unassigned,
    # 169 M-)
    :ed_unassigned,
    # 170 M-*
    :ed_unassigned,
    # 171 M-+
    :ed_unassigned,
    # 172 M-,
    :ed_unassigned,
    # 173 M--
    :ed_unassigned,
    # 174 M-.
    :ed_unassigned,
    # 175 M-/
    :ed_unassigned,
    # 176 M-0
    :ed_unassigned,
    # 177 M-1
    :ed_unassigned,
    # 178 M-2
    :ed_unassigned,
    # 179 M-3
    :ed_unassigned,
    # 180 M-4
    :ed_unassigned,
    # 181 M-5
    :ed_unassigned,
    # 182 M-6
    :ed_unassigned,
    # 183 M-7
    :ed_unassigned,
    # 184 M-8
    :ed_unassigned,
    # 185 M-9
    :ed_unassigned,
    # 186 M-:
    :ed_unassigned,
    # 187 M-;
    :ed_unassigned,
    # 188 M-<
    :ed_unassigned,
    # 189 M-=
    :ed_unassigned,
    # 190 M->
    :ed_unassigned,
    # 191 M-?
    :ed_unassigned,
    # 192 M-@
    :ed_unassigned,
    # 193 M-A
    :ed_unassigned,
    # 194 M-B
    :ed_unassigned,
    # 195 M-C
    :ed_unassigned,
    # 196 M-D
    :ed_unassigned,
    # 197 M-E
    :ed_unassigned,
    # 198 M-F
    :ed_unassigned,
    # 199 M-G
    :ed_unassigned,
    # 200 M-H
    :ed_unassigned,
    # 201 M-I
    :ed_unassigned,
    # 202 M-J
    :ed_unassigned,
    # 203 M-K
    :ed_unassigned,
    # 204 M-L
    :ed_unassigned,
    # 205 M-M
    :ed_unassigned,
    # 206 M-N
    :ed_unassigned,
    # 207 M-O
    :ed_unassigned,
    # 208 M-P
    :ed_unassigned,
    # 209 M-Q
    :ed_unassigned,
    # 210 M-R
    :ed_unassigned,
    # 211 M-S
    :ed_unassigned,
    # 212 M-T
    :ed_unassigned,
    # 213 M-U
    :ed_unassigned,
    # 214 M-V
    :ed_unassigned,
    # 215 M-W
    :ed_unassigned,
    # 216 M-X
    :ed_unassigned,
    # 217 M-Y
    :ed_unassigned,
    # 218 M-Z
    :ed_unassigned,
    # 219 M-[
    :ed_unassigned,
    # 220 M-\
    :ed_unassigned,
    # 221 M-]
    :ed_unassigned,
    # 222 M-^
    :ed_unassigned,
    # 223 M-_
    :ed_unassigned,
    # 224 M-`
    :ed_unassigned,
    # 225 M-a
    :ed_unassigned,
    # 226 M-b
    :ed_unassigned,
    # 227 M-c
    :ed_unassigned,
    # 228 M-d
    :ed_unassigned,
    # 229 M-e
    :ed_unassigned,
    # 230 M-f
    :ed_unassigned,
    # 231 M-g
    :ed_unassigned,
    # 232 M-h
    :ed_unassigned,
    # 233 M-i
    :ed_unassigned,
    # 234 M-j
    :ed_unassigned,
    # 235 M-k
    :ed_unassigned,
    # 236 M-l
    :ed_unassigned,
    # 237 M-m
    :ed_unassigned,
    # 238 M-n
    :ed_unassigned,
    # 239 M-o
    :ed_unassigned,
    # 240 M-p
    :ed_unassigned,
    # 241 M-q
    :ed_unassigned,
    # 242 M-r
    :ed_unassigned,
    # 243 M-s
    :ed_unassigned,
    # 244 M-t
    :ed_unassigned,
    # 245 M-u
    :ed_unassigned,
    # 246 M-v
    :ed_unassigned,
    # 247 M-w
    :ed_unassigned,
    # 248 M-x
    :ed_unassigned,
    # 249 M-y
    :ed_unassigned,
    # 250 M-z
    :ed_unassigned,
    # 251 M-{
    :ed_unassigned,
    # 252 M-|
    :ed_unassigned,
    # 253 M-}
    :ed_unassigned,
    # 254 M-~
    :ed_unassigned,
    # 255 M-^?
    :ed_unassigned
    # EOF
  ]
end
class Reline::KeyActor::ViCommand < Reline::KeyActor::Base
  MAPPING = [
    #   0 ^@
    :ed_unassigned,
    #   1 ^A
    :ed_move_to_beg,
    #   2 ^B
    :ed_unassigned,
    #   3 ^C
    :ed_ignore,
    #   4 ^D
    :vi_end_of_transmission,
    #   5 ^E
    :ed_move_to_end,
    #   6 ^F
    :ed_unassigned,
    #   7 ^G
    :ed_unassigned,
    #   8 ^H
    :ed_unassigned,
    #   9 ^I
    :ed_unassigned,
    #  10 ^J
    :ed_newline,
    #  11 ^K
    :ed_kill_line,
    #  12 ^L
    :ed_clear_screen,
    #  13 ^M
    :ed_newline,
    #  14 ^N
    :ed_next_history,
    #  15 ^O
    :ed_ignore,
    #  16 ^P
    :ed_prev_history,
    #  17 ^Q
    :ed_ignore,
    #  18 ^R
    :vi_search_prev,
    #  19 ^S
    :ed_ignore,
    #  20 ^T
    :ed_unassigned,
    #  21 ^U
    :vi_kill_line_prev,
    #  22 ^V
    :ed_quoted_insert,
    #  23 ^W
    :ed_delete_prev_word,
    #  24 ^X
    :ed_unassigned,
    #  25 ^Y
    :ed_unassigned,
    #  26 ^Z
    :ed_unassigned,
    #  27 ^[
    :ed_unassigned,
    #  28 ^\
    :ed_ignore,
    #  29 ^]
    :ed_unassigned,
    #  30 ^^
    :ed_unassigned,
    #  31 ^_
    :ed_unassigned,
    #  32 SPACE
    :ed_next_char,
    #  33 !
    :ed_unassigned,
    #  34 "
    :ed_unassigned,
    #  35 #
    :vi_comment_out,
    #  36 $
    :ed_move_to_end,
    #  37 %
    :vi_match,
    #  38 &
    :ed_unassigned,
    #  39 '
    :ed_unassigned,
    #  40 (
    :ed_unassigned,
    #  41 )
    :ed_unassigned,
    #  42 *
    :ed_unassigned,
    #  43 +
    :ed_next_history,
    #  44 ,
    :vi_repeat_prev_char,
    #  45 -
    :ed_prev_history,
    #  46 .
    :vi_redo,
    #  47 /
    :vi_search_prev,
    #  48 0
    :vi_zero,
    #  49 1
    :ed_argument_digit,
    #  50 2
    :ed_argument_digit,
    #  51 3
    :ed_argument_digit,
    #  52 4
    :ed_argument_digit,
    #  53 5
    :ed_argument_digit,
    #  54 6
    :ed_argument_digit,
    #  55 7
    :ed_argument_digit,
    #  56 8
    :ed_argument_digit,
    #  57 9
    :ed_argument_digit,
    #  58 :
    :ed_command,
    #  59 ;
    :vi_repeat_next_char,
    #  60 <
    :ed_unassigned,
    #  61 =
    :ed_unassigned,
    #  62 >
    :ed_unassigned,
    #  63 ?
    :vi_search_next,
    #  64 @
    :vi_alias,
    #  65 A
    :vi_add_at_eol,
    #  66 B
    :vi_prev_big_word,
    #  67 C
    :vi_change_to_eol,
    #  68 D
    :ed_kill_line,
    #  69 E
    :vi_end_big_word,
    #  70 F
    :vi_prev_char,
    #  71 G
    :vi_to_history_line,
    #  72 H
    :ed_unassigned,
    #  73 I
    :vi_insert_at_bol,
    #  74 J
    :vi_join_lines,
    #  75 K
    :vi_search_prev,
    #  76 L
    :ed_unassigned,
    #  77 M
    :ed_unassigned,
    #  78 N
    :vi_repeat_search_prev,
    #  79 O
    :ed_sequence_lead_in,
    #  80 P
    :vi_paste_prev,
    #  81 Q
    :ed_unassigned,
    #  82 R
    :vi_replace_mode,
    #  83 S
    :vi_substitute_line,
    #  84 T
    :vi_to_prev_char,
    #  85 U
    :vi_undo_line,
    #  86 V
    :ed_unassigned,
    #  87 W
    :vi_next_big_word,
    #  88 X
    :ed_delete_prev_char,
    #  89 Y
    :vi_yank_end,
    #  90 Z
    :ed_unassigned,
    #  91 [
    :ed_sequence_lead_in,
    #  92 \
    :ed_unassigned,
    #  93 ]
    :ed_unassigned,
    #  94 ^
    :vi_first_print,
    #  95 _
    :vi_history_word,
    #  96 `
    :ed_unassigned,
    #  97 a
    :vi_add,
    #  98 b
    :vi_prev_word,
    #  99 c
    :vi_change_meta,
    # 100 d
    :vi_delete_meta,
    # 101 e
    :vi_end_word,
    # 102 f
    :vi_next_char,
    # 103 g
    :ed_unassigned,
    # 104 h
    :ed_prev_char,
    # 105 i
    :vi_insert,
    # 106 j
    :ed_next_history,
    # 107 k
    :ed_prev_history,
    # 108 l
    :ed_next_char,
    # 109 m
    :ed_unassigned,
    # 110 n
    :vi_repeat_search_next,
    # 111 o
    :ed_unassigned,
    # 112 p
    :vi_paste_next,
    # 113 q
    :ed_unassigned,
    # 114 r
    :vi_replace_char,
    # 115 s
    :vi_substitute_char,
    # 116 t
    :vi_to_next_char,
    # 117 u
    :vi_undo,
    # 118 v
    :vi_histedit,
    # 119 w
    :vi_next_word,
    # 120 x
    :ed_delete_next_char,
    # 121 y
    :vi_yank,
    # 122 z
    :ed_unassigned,
    # 123 {
    :ed_unassigned,
    # 124 |
    :vi_to_column,
    # 125 }
    :ed_unassigned,
    # 126 ~
    :vi_change_case,
    # 127 ^?
    :ed_unassigned,
    # 128 M-^@
    :ed_unassigned,
    # 129 M-^A
    :ed_unassigned,
    # 130 M-^B
    :ed_unassigned,
    # 131 M-^C
    :ed_unassigned,
    # 132 M-^D
    :ed_unassigned,
    # 133 M-^E
    :ed_unassigned,
    # 134 M-^F
    :ed_unassigned,
    # 135 M-^G
    :ed_unassigned,
    # 136 M-^H
    :ed_unassigned,
    # 137 M-^I
    :ed_unassigned,
    # 138 M-^J
    :ed_unassigned,
    # 139 M-^K
    :ed_unassigned,
    # 140 M-^L
    :ed_unassigned,
    # 141 M-^M
    :ed_unassigned,
    # 142 M-^N
    :ed_unassigned,
    # 143 M-^O
    :ed_unassigned,
    # 144 M-^P
    :ed_unassigned,
    # 145 M-^Q
    :ed_unassigned,
    # 146 M-^R
    :ed_unassigned,
    # 147 M-^S
    :ed_unassigned,
    # 148 M-^T
    :ed_unassigned,
    # 149 M-^U
    :ed_unassigned,
    # 150 M-^V
    :ed_unassigned,
    # 151 M-^W
    :ed_unassigned,
    # 152 M-^X
    :ed_unassigned,
    # 153 M-^Y
    :ed_unassigned,
    # 154 M-^Z
    :ed_unassigned,
    # 155 M-^[
    :ed_unassigned,
    # 156 M-^\
    :ed_unassigned,
    # 157 M-^]
    :ed_unassigned,
    # 158 M-^^
    :ed_unassigned,
    # 159 M-^_
    :ed_unassigned,
    # 160 M-SPACE
    :ed_unassigned,
    # 161 M-!
    :ed_unassigned,
    # 162 M-"
    :ed_unassigned,
    # 163 M-#
    :ed_unassigned,
    # 164 M-$
    :ed_unassigned,
    # 165 M-%
    :ed_unassigned,
    # 166 M-&
    :ed_unassigned,
    # 167 M-'
    :ed_unassigned,
    # 168 M-(
    :ed_unassigned,
    # 169 M-)
    :ed_unassigned,
    # 170 M-*
    :ed_unassigned,
    # 171 M-+
    :ed_unassigned,
    # 172 M-,
    :ed_unassigned,
    # 173 M--
    :ed_unassigned,
    # 174 M-.
    :ed_unassigned,
    # 175 M-/
    :ed_unassigned,
    # 176 M-0
    :ed_unassigned,
    # 177 M-1
    :ed_unassigned,
    # 178 M-2
    :ed_unassigned,
    # 179 M-3
    :ed_unassigned,
    # 180 M-4
    :ed_unassigned,
    # 181 M-5
    :ed_unassigned,
    # 182 M-6
    :ed_unassigned,
    # 183 M-7
    :ed_unassigned,
    # 184 M-8
    :ed_unassigned,
    # 185 M-9
    :ed_unassigned,
    # 186 M-:
    :ed_unassigned,
    # 187 M-;
    :ed_unassigned,
    # 188 M-<
    :ed_unassigned,
    # 189 M-=
    :ed_unassigned,
    # 190 M->
    :ed_unassigned,
    # 191 M-?
    :ed_unassigned,
    # 192 M-@
    :ed_unassigned,
    # 193 M-A
    :ed_unassigned,
    # 194 M-B
    :ed_unassigned,
    # 195 M-C
    :ed_unassigned,
    # 196 M-D
    :ed_unassigned,
    # 197 M-E
    :ed_unassigned,
    # 198 M-F
    :ed_unassigned,
    # 199 M-G
    :ed_unassigned,
    # 200 M-H
    :ed_unassigned,
    # 201 M-I
    :ed_unassigned,
    # 202 M-J
    :ed_unassigned,
    # 203 M-K
    :ed_unassigned,
    # 204 M-L
    :ed_unassigned,
    # 205 M-M
    :ed_unassigned,
    # 206 M-N
    :ed_unassigned,
    # 207 M-O
    :ed_sequence_lead_in,
    # 208 M-P
    :ed_unassigned,
    # 209 M-Q
    :ed_unassigned,
    # 210 M-R
    :ed_unassigned,
    # 211 M-S
    :ed_unassigned,
    # 212 M-T
    :ed_unassigned,
    # 213 M-U
    :ed_unassigned,
    # 214 M-V
    :ed_unassigned,
    # 215 M-W
    :ed_unassigned,
    # 216 M-X
    :ed_unassigned,
    # 217 M-Y
    :ed_unassigned,
    # 218 M-Z
    :ed_unassigned,
    # 219 M-[
    :ed_sequence_lead_in,
    # 220 M-\
    :ed_unassigned,
    # 221 M-]
    :ed_unassigned,
    # 222 M-^
    :ed_unassigned,
    # 223 M-_
    :ed_unassigned,
    # 224 M-`
    :ed_unassigned,
    # 225 M-a
    :ed_unassigned,
    # 226 M-b
    :ed_unassigned,
    # 227 M-c
    :ed_unassigned,
    # 228 M-d
    :ed_unassigned,
    # 229 M-e
    :ed_unassigned,
    # 230 M-f
    :ed_unassigned,
    # 231 M-g
    :ed_unassigned,
    # 232 M-h
    :ed_unassigned,
    # 233 M-i
    :ed_unassigned,
    # 234 M-j
    :ed_unassigned,
    # 235 M-k
    :ed_unassigned,
    # 236 M-l
    :ed_unassigned,
    # 237 M-m
    :ed_unassigned,
    # 238 M-n
    :ed_unassigned,
    # 239 M-o
    :ed_unassigned,
    # 240 M-p
    :ed_unassigned,
    # 241 M-q
    :ed_unassigned,
    # 242 M-r
    :ed_unassigned,
    # 243 M-s
    :ed_unassigned,
    # 244 M-t
    :ed_unassigned,
    # 245 M-u
    :ed_unassigned,
    # 246 M-v
    :ed_unassigned,
    # 247 M-w
    :ed_unassigned,
    # 248 M-x
    :ed_unassigned,
    # 249 M-y
    :ed_unassigned,
    # 250 M-z
    :ed_unassigned,
    # 251 M-{
    :ed_unassigned,
    # 252 M-|
    :ed_unassigned,
    # 253 M-}
    :ed_unassigned,
    # 254 M-~
    :ed_unassigned,
    # 255 M-^?
    :ed_unassigned
    # EOF
  ]
end

class Reline::KeyActor::Emacs < Reline::KeyActor::Base
  MAPPING = [
    #   0 ^@
    :em_set_mark,
    #   1 ^A
    :ed_move_to_beg,
    #   2 ^B
    :ed_prev_char,
    #   3 ^C
    :ed_ignore,
    #   4 ^D
    :em_delete,
    #   5 ^E
    :ed_move_to_end,
    #   6 ^F
    :ed_next_char,
    #   7 ^G
    :ed_unassigned,
    #   8 ^H
    :em_delete_prev_char,
    #   9 ^I
    :ed_unassigned,
    #  10 ^J
    :ed_newline,
    #  11 ^K
    :ed_kill_line,
    #  12 ^L
    :ed_clear_screen,
    #  13 ^M
    :ed_newline,
    #  14 ^N
    :ed_next_history,
    #  15 ^O
    :ed_ignore,
    #  16 ^P
    :ed_prev_history,
    #  17 ^Q
    :ed_quoted_insert,
    #  18 ^R
    :vi_search_prev,
    #  19 ^S
    :vi_search_next,
    #  20 ^T
    :ed_transpose_chars,
    #  21 ^U
    :em_kill_line,
    #  22 ^V
    :ed_quoted_insert,
    #  23 ^W
    :em_kill_region,
    #  24 ^X
    :ed_sequence_lead_in,
    #  25 ^Y
    :em_yank,
    #  26 ^Z
    :ed_ignore,
    #  27 ^[
    :em_meta_next,
    #  28 ^\
    :ed_ignore,
    #  29 ^]
    :ed_ignore,
    #  30 ^^
    :ed_unassigned,
    #  31 ^_
    :ed_unassigned,
    #  32 SPACE
    :ed_insert,
    #  33 !
    :ed_insert,
    #  34 "
    :ed_insert,
    #  35 #
    :ed_insert,
    #  36 $
    :ed_insert,
    #  37 %
    :ed_insert,
    #  38 &
    :ed_insert,
    #  39 '
    :ed_insert,
    #  40 (
    :ed_insert,
    #  41 )
    :ed_insert,
    #  42 *
    :ed_insert,
    #  43 +
    :ed_insert,
    #  44 ,
    :ed_insert,
    #  45 -
    :ed_insert,
    #  46 .
    :ed_insert,
    #  47 /
    :ed_insert,
    #  48 0
    :ed_digit,
    #  49 1
    :ed_digit,
    #  50 2
    :ed_digit,
    #  51 3
    :ed_digit,
    #  52 4
    :ed_digit,
    #  53 5
    :ed_digit,
    #  54 6
    :ed_digit,
    #  55 7
    :ed_digit,
    #  56 8
    :ed_digit,
    #  57 9
    :ed_digit,
    #  58 :
    :ed_insert,
    #  59 ;
    :ed_insert,
    #  60 <
    :ed_insert,
    #  61 =
    :ed_insert,
    #  62 >
    :ed_insert,
    #  63 ?
    :ed_insert,
    #  64 @
    :ed_insert,
    #  65 A
    :ed_insert,
    #  66 B
    :ed_insert,
    #  67 C
    :ed_insert,
    #  68 D
    :ed_insert,
    #  69 E
    :ed_insert,
    #  70 F
    :ed_insert,
    #  71 G
    :ed_insert,
    #  72 H
    :ed_insert,
    #  73 I
    :ed_insert,
    #  74 J
    :ed_insert,
    #  75 K
    :ed_insert,
    #  76 L
    :ed_insert,
    #  77 M
    :ed_insert,
    #  78 N
    :ed_insert,
    #  79 O
    :ed_insert,
    #  80 P
    :ed_insert,
    #  81 Q
    :ed_insert,
    #  82 R
    :ed_insert,
    #  83 S
    :ed_insert,
    #  84 T
    :ed_insert,
    #  85 U
    :ed_insert,
    #  86 V
    :ed_insert,
    #  87 W
    :ed_insert,
    #  88 X
    :ed_insert,
    #  89 Y
    :ed_insert,
    #  90 Z
    :ed_insert,
    #  91 [
    :ed_insert,
    #  92 \
    :ed_insert,
    #  93 ]
    :ed_insert,
    #  94 ^
    :ed_insert,
    #  95 _
    :ed_insert,
    #  96 `
    :ed_insert,
    #  97 a
    :ed_insert,
    #  98 b
    :ed_insert,
    #  99 c
    :ed_insert,
    # 100 d
    :ed_insert,
    # 101 e
    :ed_insert,
    # 102 f
    :ed_insert,
    # 103 g
    :ed_insert,
    # 104 h
    :ed_insert,
    # 105 i
    :ed_insert,
    # 106 j
    :ed_insert,
    # 107 k
    :ed_insert,
    # 108 l
    :ed_insert,
    # 109 m
    :ed_insert,
    # 110 n
    :ed_insert,
    # 111 o
    :ed_insert,
    # 112 p
    :ed_insert,
    # 113 q
    :ed_insert,
    # 114 r
    :ed_insert,
    # 115 s
    :ed_insert,
    # 116 t
    :ed_insert,
    # 117 u
    :ed_insert,
    # 118 v
    :ed_insert,
    # 119 w
    :ed_insert,
    # 120 x
    :ed_insert,
    # 121 y
    :ed_insert,
    # 122 z
    :ed_insert,
    # 123 {
    :ed_insert,
    # 124 |
    :ed_insert,
    # 125 }
    :ed_insert,
    # 126 ~
    :ed_insert,
    # 127 ^?
    :em_delete_prev_char,
    # 128 M-^@
    :ed_unassigned,
    # 129 M-^A
    :ed_unassigned,
    # 130 M-^B
    :ed_unassigned,
    # 131 M-^C
    :ed_unassigned,
    # 132 M-^D
    :ed_unassigned,
    # 133 M-^E
    :ed_unassigned,
    # 134 M-^F
    :ed_unassigned,
    # 135 M-^G
    :ed_unassigned,
    # 136 M-^H
    :ed_delete_prev_word,
    # 137 M-^I
    :ed_unassigned,
    # 138 M-^J
    :key_newline,
    # 139 M-^K
    :ed_unassigned,
    # 140 M-^L
    :ed_clear_screen,
    # 141 M-^M
    :key_newline,
    # 142 M-^N
    :ed_unassigned,
    # 143 M-^O
    :ed_unassigned,
    # 144 M-^P
    :ed_unassigned,
    # 145 M-^Q
    :ed_unassigned,
    # 146 M-^R
    :ed_unassigned,
    # 147 M-^S
    :ed_unassigned,
    # 148 M-^T
    :ed_unassigned,
    # 149 M-^U
    :ed_unassigned,
    # 150 M-^V
    :ed_unassigned,
    # 151 M-^W
    :ed_unassigned,
    # 152 M-^X
    :ed_unassigned,
    # 153 M-^Y
    :em_yank_pop,
    # 154 M-^Z
    :ed_unassigned,
    # 155 M-^[
    :ed_unassigned,
    # 156 M-^\
    :ed_unassigned,
    # 157 M-^]
    :ed_unassigned,
    # 158 M-^^
    :ed_unassigned,
    # 159 M-^_
    :em_copy_prev_word,
    # 160 M-SPACE
    :ed_unassigned,
    # 161 M-!
    :ed_unassigned,
    # 162 M-"
    :ed_unassigned,
    # 163 M-#
    :ed_unassigned,
    # 164 M-$
    :ed_unassigned,
    # 165 M-%
    :ed_unassigned,
    # 166 M-&
    :ed_unassigned,
    # 167 M-'
    :ed_unassigned,
    # 168 M-(
    :ed_unassigned,
    # 169 M-)
    :ed_unassigned,
    # 170 M-*
    :ed_unassigned,
    # 171 M-+
    :ed_unassigned,
    # 172 M-,
    :ed_unassigned,
    # 173 M--
    :ed_unassigned,
    # 174 M-.
    :ed_unassigned,
    # 175 M-/
    :ed_unassigned,
    # 176 M-0
    :ed_argument_digit,
    # 177 M-1
    :ed_argument_digit,
    # 178 M-2
    :ed_argument_digit,
    # 179 M-3
    :ed_argument_digit,
    # 180 M-4
    :ed_argument_digit,
    # 181 M-5
    :ed_argument_digit,
    # 182 M-6
    :ed_argument_digit,
    # 183 M-7
    :ed_argument_digit,
    # 184 M-8
    :ed_argument_digit,
    # 185 M-9
    :ed_argument_digit,
    # 186 M-:
    :ed_unassigned,
    # 187 M-;
    :ed_unassigned,
    # 188 M-<
    :ed_unassigned,
    # 189 M-=
    :ed_unassigned,
    # 190 M->
    :ed_unassigned,
    # 191 M-?
    :ed_unassigned,
    # 192 M-@
    :ed_unassigned,
    # 193 M-A
    :ed_unassigned,
    # 194 M-B
    :ed_prev_word,
    # 195 M-C
    :em_capitol_case,
    # 196 M-D
    :em_delete_next_word,
    # 197 M-E
    :ed_unassigned,
    # 198 M-F
    :em_next_word,
    # 199 M-G
    :ed_unassigned,
    # 200 M-H
    :ed_unassigned,
    # 201 M-I
    :ed_unassigned,
    # 202 M-J
    :ed_unassigned,
    # 203 M-K
    :ed_unassigned,
    # 204 M-L
    :em_lower_case,
    # 205 M-M
    :ed_unassigned,
    # 206 M-N
    :vi_search_next,
    # 207 M-O
    :ed_sequence_lead_in,
    # 208 M-P
    :vi_search_prev,
    # 209 M-Q
    :ed_unassigned,
    # 210 M-R
    :ed_unassigned,
    # 211 M-S
    :ed_unassigned,
    # 212 M-T
    :ed_unassigned,
    # 213 M-U
    :em_upper_case,
    # 214 M-V
    :ed_unassigned,
    # 215 M-W
    :em_copy_region,
    # 216 M-X
    :ed_command,
    # 217 M-Y
    :ed_unassigned,
    # 218 M-Z
    :ed_unassigned,
    # 219 M-[
    :ed_sequence_lead_in,
    # 220 M-\
    :ed_unassigned,
    # 221 M-]
    :ed_unassigned,
    # 222 M-^
    :ed_unassigned,
    # 223 M-_
    :ed_unassigned,
    # 224 M-`
    :ed_unassigned,
    # 225 M-a
    :ed_unassigned,
    # 226 M-b
    :ed_prev_word,
    # 227 M-c
    :em_capitol_case,
    # 228 M-d
    :em_delete_next_word,
    # 229 M-e
    :ed_unassigned,
    # 230 M-f
    :em_next_word,
    # 231 M-g
    :ed_unassigned,
    # 232 M-h
    :ed_unassigned,
    # 233 M-i
    :ed_unassigned,
    # 234 M-j
    :ed_unassigned,
    # 235 M-k
    :ed_unassigned,
    # 236 M-l
    :em_lower_case,
    # 237 M-m
    :ed_unassigned,
    # 238 M-n
    :vi_search_next,
    # 239 M-o
    :ed_unassigned,
    # 240 M-p
    :vi_search_prev,
    # 241 M-q
    :ed_unassigned,
    # 242 M-r
    :ed_unassigned,
    # 243 M-s
    :ed_unassigned,
    # 244 M-t
    :ed_transpose_words,
    # 245 M-u
    :em_upper_case,
    # 246 M-v
    :ed_unassigned,
    # 247 M-w
    :em_copy_region,
    # 248 M-x
    :ed_command,
    # 249 M-y
    :ed_unassigned,
    # 250 M-z
    :ed_unassigned,
    # 251 M-{
    :ed_unassigned,
    # 252 M-|
    :ed_unassigned,
    # 253 M-}
    :ed_unassigned,
    # 254 M-~
    :ed_unassigned,
    # 255 M-^?
    :ed_delete_prev_word
    # EOF
  ]
end
class Reline::Unicode::EastAsianWidth
  # This is based on EastAsianWidth.txt
  # EastAsianWidth.txt

  # Fullwidth
  TYPE_F = /^[#{ %W(
    \u{3000}
    \u{FF01}-\u{FF60}
    \u{FFE0}-\u{FFE6}
  ).join }]/

  # Halfwidth
  TYPE_H = /^[#{ %W(
    \u{20A9}
    \u{FF61}-\u{FFBE}
    \u{FFC2}-\u{FFC7}
    \u{FFCA}-\u{FFCF}
    \u{FFD2}-\u{FFD7}
    \u{FFDA}-\u{FFDC}
    \u{FFE8}-\u{FFEE}
  ).join }]/

  # Wide
  TYPE_W = /^[#{ %W(
    \u{1100}-\u{115F}
    \u{231A}-\u{231B}
    \u{2329}-\u{232A}
    \u{23E9}-\u{23EC}
    \u{23F0}
    \u{23F3}
    \u{25FD}-\u{25FE}
    \u{2614}-\u{2615}
    \u{2648}-\u{2653}
    \u{267F}
    \u{2693}
    \u{26A1}
    \u{26AA}-\u{26AB}
    \u{26BD}-\u{26BE}
    \u{26C4}-\u{26C5}
    \u{26CE}
    \u{26D4}
    \u{26EA}
    \u{26F2}-\u{26F3}
    \u{26F5}
    \u{26FA}
    \u{26FD}
    \u{2705}
    \u{270A}-\u{270B}
    \u{2728}
    \u{274C}
    \u{274E}
    \u{2753}-\u{2755}
    \u{2757}
    \u{2795}-\u{2797}
    \u{27B0}
    \u{27BF}
    \u{2B1B}-\u{2B1C}
    \u{2B50}
    \u{2B55}
    \u{2E80}-\u{2E99}
    \u{2E9B}-\u{2EF3}
    \u{2F00}-\u{2FD5}
    \u{2FF0}-\u{2FFB}
    \u{3001}-\u{303E}
    \u{3041}-\u{3096}
    \u{3099}-\u{30FF}
    \u{3105}-\u{312F}
    \u{3131}-\u{318E}
    \u{3190}-\u{31E3}
    \u{31F0}-\u{321E}
    \u{3220}-\u{3247}
    \u{3250}-\u{4DBF}
    \u{4E00}-\u{A48C}
    \u{A490}-\u{A4C6}
    \u{A960}-\u{A97C}
    \u{AC00}-\u{D7A3}
    \u{F900}-\u{FAFF}
    \u{FE10}-\u{FE19}
    \u{FE30}-\u{FE52}
    \u{FE54}-\u{FE66}
    \u{FE68}-\u{FE6B}
    \u{16FE0}-\u{16FE4}
    \u{16FF0}-\u{16FF1}
    \u{17000}-\u{187F7}
    \u{18800}-\u{18CD5}
    \u{18D00}-\u{18D08}
    \u{1B000}-\u{1B11E}
    \u{1B150}-\u{1B152}
    \u{1B164}-\u{1B167}
    \u{1B170}-\u{1B2FB}
    \u{1F004}
    \u{1F0CF}
    \u{1F18E}
    \u{1F191}-\u{1F19A}
    \u{1F200}-\u{1F202}
    \u{1F210}-\u{1F23B}
    \u{1F240}-\u{1F248}
    \u{1F250}-\u{1F251}
    \u{1F260}-\u{1F265}
    \u{1F300}-\u{1F320}
    \u{1F32D}-\u{1F335}
    \u{1F337}-\u{1F37C}
    \u{1F37E}-\u{1F393}
    \u{1F3A0}-\u{1F3CA}
    \u{1F3CF}-\u{1F3D3}
    \u{1F3E0}-\u{1F3F0}
    \u{1F3F4}
    \u{1F3F8}-\u{1F43E}
    \u{1F440}
    \u{1F442}-\u{1F4FC}
    \u{1F4FF}-\u{1F53D}
    \u{1F54B}-\u{1F54E}
    \u{1F550}-\u{1F567}
    \u{1F57A}
    \u{1F595}-\u{1F596}
    \u{1F5A4}
    \u{1F5FB}-\u{1F64F}
    \u{1F680}-\u{1F6C5}
    \u{1F6CC}
    \u{1F6D0}-\u{1F6D2}
    \u{1F6D5}-\u{1F6D7}
    \u{1F6EB}-\u{1F6EC}
    \u{1F6F4}-\u{1F6FC}
    \u{1F7E0}-\u{1F7EB}
    \u{1F90C}-\u{1F93A}
    \u{1F93C}-\u{1F945}
    \u{1F947}-\u{1F978}
    \u{1F97A}-\u{1F9CB}
    \u{1F9CD}-\u{1F9FF}
    \u{1FA70}-\u{1FA74}
    \u{1FA78}-\u{1FA7A}
    \u{1FA80}-\u{1FA86}
    \u{1FA90}-\u{1FAA8}
    \u{1FAB0}-\u{1FAB6}
    \u{1FAC0}-\u{1FAC2}
    \u{1FAD0}-\u{1FAD6}
    \u{20000}-\u{2FFFD}
    \u{30000}-\u{3FFFD}
  ).join }]/

  # Narrow
  TYPE_NA = /^[#{ %W(
    \u{0020}-\u{007E}
    \u{00A2}-\u{00A3}
    \u{00A5}-\u{00A6}
    \u{00AC}
    \u{00AF}
    \u{27E6}-\u{27ED}
    \u{2985}-\u{2986}
  ).join }]/

  # Ambiguous
  TYPE_A = /^[#{ %W(
    \u{00A1}
    \u{00A4}
    \u{00A7}-\u{00A8}
    \u{00AA}
    \u{00AD}-\u{00AE}
    \u{00B0}-\u{00B4}
    \u{00B6}-\u{00BA}
    \u{00BC}-\u{00BF}
    \u{00C6}
    \u{00D0}
    \u{00D7}-\u{00D8}
    \u{00DE}-\u{00E1}
    \u{00E6}
    \u{00E8}-\u{00EA}
    \u{00EC}-\u{00ED}
    \u{00F0}
    \u{00F2}-\u{00F3}
    \u{00F7}-\u{00FA}
    \u{00FC}
    \u{00FE}
    \u{0101}
    \u{0111}
    \u{0113}
    \u{011B}
    \u{0126}-\u{0127}
    \u{012B}
    \u{0131}-\u{0133}
    \u{0138}
    \u{013F}-\u{0142}
    \u{0144}
    \u{0148}-\u{014B}
    \u{014D}
    \u{0152}-\u{0153}
    \u{0166}-\u{0167}
    \u{016B}
    \u{01CE}
    \u{01D0}
    \u{01D2}
    \u{01D4}
    \u{01D6}
    \u{01D8}
    \u{01DA}
    \u{01DC}
    \u{0251}
    \u{0261}
    \u{02C4}
    \u{02C7}
    \u{02C9}-\u{02CB}
    \u{02CD}
    \u{02D0}
    \u{02D8}-\u{02DB}
    \u{02DD}
    \u{02DF}
    \u{0300}-\u{036F}
    \u{0391}-\u{03A1}
    \u{03A3}-\u{03A9}
    \u{03B1}-\u{03C1}
    \u{03C3}-\u{03C9}
    \u{0401}
    \u{0410}-\u{044F}
    \u{0451}
    \u{2010}
    \u{2013}-\u{2016}
    \u{2018}-\u{2019}
    \u{201C}-\u{201D}
    \u{2020}-\u{2022}
    \u{2024}-\u{2027}
    \u{2030}
    \u{2032}-\u{2033}
    \u{2035}
    \u{203B}
    \u{203E}
    \u{2074}
    \u{207F}
    \u{2081}-\u{2084}
    \u{20AC}
    \u{2103}
    \u{2105}
    \u{2109}
    \u{2113}
    \u{2116}
    \u{2121}-\u{2122}
    \u{2126}
    \u{212B}
    \u{2153}-\u{2154}
    \u{215B}-\u{215E}
    \u{2160}-\u{216B}
    \u{2170}-\u{2179}
    \u{2189}
    \u{2190}-\u{2199}
    \u{21B8}-\u{21B9}
    \u{21D2}
    \u{21D4}
    \u{21E7}
    \u{2200}
    \u{2202}-\u{2203}
    \u{2207}-\u{2208}
    \u{220B}
    \u{220F}
    \u{2211}
    \u{2215}
    \u{221A}
    \u{221D}-\u{2220}
    \u{2223}
    \u{2225}
    \u{2227}-\u{222C}
    \u{222E}
    \u{2234}-\u{2237}
    \u{223C}-\u{223D}
    \u{2248}
    \u{224C}
    \u{2252}
    \u{2260}-\u{2261}
    \u{2264}-\u{2267}
    \u{226A}-\u{226B}
    \u{226E}-\u{226F}
    \u{2282}-\u{2283}
    \u{2286}-\u{2287}
    \u{2295}
    \u{2299}
    \u{22A5}
    \u{22BF}
    \u{2312}
    \u{2460}-\u{24E9}
    \u{24EB}-\u{254B}
    \u{2550}-\u{2573}
    \u{2580}-\u{258F}
    \u{2592}-\u{2595}
    \u{25A0}-\u{25A1}
    \u{25A3}-\u{25A9}
    \u{25B2}-\u{25B3}
    \u{25B6}-\u{25B7}
    \u{25BC}-\u{25BD}
    \u{25C0}-\u{25C1}
    \u{25C6}-\u{25C8}
    \u{25CB}
    \u{25CE}-\u{25D1}
    \u{25E2}-\u{25E5}
    \u{25EF}
    \u{2605}-\u{2606}
    \u{2609}
    \u{260E}-\u{260F}
    \u{261C}
    \u{261E}
    \u{2640}
    \u{2642}
    \u{2660}-\u{2661}
    \u{2663}-\u{2665}
    \u{2667}-\u{266A}
    \u{266C}-\u{266D}
    \u{266F}
    \u{269E}-\u{269F}
    \u{26BF}
    \u{26C6}-\u{26CD}
    \u{26CF}-\u{26D3}
    \u{26D5}-\u{26E1}
    \u{26E3}
    \u{26E8}-\u{26E9}
    \u{26EB}-\u{26F1}
    \u{26F4}
    \u{26F6}-\u{26F9}
    \u{26FB}-\u{26FC}
    \u{26FE}-\u{26FF}
    \u{273D}
    \u{2776}-\u{277F}
    \u{2B56}-\u{2B59}
    \u{3248}-\u{324F}
    \u{E000}-\u{F8FF}
    \u{FE00}-\u{FE0F}
    \u{FFFD}
    \u{1F100}-\u{1F10A}
    \u{1F110}-\u{1F12D}
    \u{1F130}-\u{1F169}
    \u{1F170}-\u{1F18D}
    \u{1F18F}-\u{1F190}
    \u{1F19B}-\u{1F1AC}
    \u{E0100}-\u{E01EF}
    \u{F0000}-\u{FFFFD}
    \u{100000}-\u{10FFFD}
  ).join }]/

  # Neutral
  TYPE_N = /^[#{ %W(
    \u{0000}-\u{001F}
    \u{007F}-\u{00A0}
    \u{00A9}
    \u{00AB}
    \u{00B5}
    \u{00BB}
    \u{00C0}-\u{00C5}
    \u{00C7}-\u{00CF}
    \u{00D1}-\u{00D6}
    \u{00D9}-\u{00DD}
    \u{00E2}-\u{00E5}
    \u{00E7}
    \u{00EB}
    \u{00EE}-\u{00EF}
    \u{00F1}
    \u{00F4}-\u{00F6}
    \u{00FB}
    \u{00FD}
    \u{00FF}-\u{0100}
    \u{0102}-\u{0110}
    \u{0112}
    \u{0114}-\u{011A}
    \u{011C}-\u{0125}
    \u{0128}-\u{012A}
    \u{012C}-\u{0130}
    \u{0134}-\u{0137}
    \u{0139}-\u{013E}
    \u{0143}
    \u{0145}-\u{0147}
    \u{014C}
    \u{014E}-\u{0151}
    \u{0154}-\u{0165}
    \u{0168}-\u{016A}
    \u{016C}-\u{01CD}
    \u{01CF}
    \u{01D1}
    \u{01D3}
    \u{01D5}
    \u{01D7}
    \u{01D9}
    \u{01DB}
    \u{01DD}-\u{0250}
    \u{0252}-\u{0260}
    \u{0262}-\u{02C3}
    \u{02C5}-\u{02C6}
    \u{02C8}
    \u{02CC}
    \u{02CE}-\u{02CF}
    \u{02D1}-\u{02D7}
    \u{02DC}
    \u{02DE}
    \u{02E0}-\u{02FF}
    \u{0370}-\u{0377}
    \u{037A}-\u{037F}
    \u{0384}-\u{038A}
    \u{038C}
    \u{038E}-\u{0390}
    \u{03AA}-\u{03B0}
    \u{03C2}
    \u{03CA}-\u{0400}
    \u{0402}-\u{040F}
    \u{0450}
    \u{0452}-\u{052F}
    \u{0531}-\u{0556}
    \u{0559}-\u{058A}
    \u{058D}-\u{058F}
    \u{0591}-\u{05C7}
    \u{05D0}-\u{05EA}
    \u{05EF}-\u{05F4}
    \u{0600}-\u{061C}
    \u{061E}-\u{070D}
    \u{070F}-\u{074A}
    \u{074D}-\u{07B1}
    \u{07C0}-\u{07FA}
    \u{07FD}-\u{082D}
    \u{0830}-\u{083E}
    \u{0840}-\u{085B}
    \u{085E}
    \u{0860}-\u{086A}
    \u{08A0}-\u{08B4}
    \u{08B6}-\u{08C7}
    \u{08D3}-\u{0983}
    \u{0985}-\u{098C}
    \u{098F}-\u{0990}
    \u{0993}-\u{09A8}
    \u{09AA}-\u{09B0}
    \u{09B2}
    \u{09B6}-\u{09B9}
    \u{09BC}-\u{09C4}
    \u{09C7}-\u{09C8}
    \u{09CB}-\u{09CE}
    \u{09D7}
    \u{09DC}-\u{09DD}
    \u{09DF}-\u{09E3}
    \u{09E6}-\u{09FE}
    \u{0A01}-\u{0A03}
    \u{0A05}-\u{0A0A}
    \u{0A0F}-\u{0A10}
    \u{0A13}-\u{0A28}
    \u{0A2A}-\u{0A30}
    \u{0A32}-\u{0A33}
    \u{0A35}-\u{0A36}
    \u{0A38}-\u{0A39}
    \u{0A3C}
    \u{0A3E}-\u{0A42}
    \u{0A47}-\u{0A48}
    \u{0A4B}-\u{0A4D}
    \u{0A51}
    \u{0A59}-\u{0A5C}
    \u{0A5E}
    \u{0A66}-\u{0A76}
    \u{0A81}-\u{0A83}
    \u{0A85}-\u{0A8D}
    \u{0A8F}-\u{0A91}
    \u{0A93}-\u{0AA8}
    \u{0AAA}-\u{0AB0}
    \u{0AB2}-\u{0AB3}
    \u{0AB5}-\u{0AB9}
    \u{0ABC}-\u{0AC5}
    \u{0AC7}-\u{0AC9}
    \u{0ACB}-\u{0ACD}
    \u{0AD0}
    \u{0AE0}-\u{0AE3}
    \u{0AE6}-\u{0AF1}
    \u{0AF9}-\u{0AFF}
    \u{0B01}-\u{0B03}
    \u{0B05}-\u{0B0C}
    \u{0B0F}-\u{0B10}
    \u{0B13}-\u{0B28}
    \u{0B2A}-\u{0B30}
    \u{0B32}-\u{0B33}
    \u{0B35}-\u{0B39}
    \u{0B3C}-\u{0B44}
    \u{0B47}-\u{0B48}
    \u{0B4B}-\u{0B4D}
    \u{0B55}-\u{0B57}
    \u{0B5C}-\u{0B5D}
    \u{0B5F}-\u{0B63}
    \u{0B66}-\u{0B77}
    \u{0B82}-\u{0B83}
    \u{0B85}-\u{0B8A}
    \u{0B8E}-\u{0B90}
    \u{0B92}-\u{0B95}
    \u{0B99}-\u{0B9A}
    \u{0B9C}
    \u{0B9E}-\u{0B9F}
    \u{0BA3}-\u{0BA4}
    \u{0BA8}-\u{0BAA}
    \u{0BAE}-\u{0BB9}
    \u{0BBE}-\u{0BC2}
    \u{0BC6}-\u{0BC8}
    \u{0BCA}-\u{0BCD}
    \u{0BD0}
    \u{0BD7}
    \u{0BE6}-\u{0BFA}
    \u{0C00}-\u{0C0C}
    \u{0C0E}-\u{0C10}
    \u{0C12}-\u{0C28}
    \u{0C2A}-\u{0C39}
    \u{0C3D}-\u{0C44}
    \u{0C46}-\u{0C48}
    \u{0C4A}-\u{0C4D}
    \u{0C55}-\u{0C56}
    \u{0C58}-\u{0C5A}
    \u{0C60}-\u{0C63}
    \u{0C66}-\u{0C6F}
    \u{0C77}-\u{0C8C}
    \u{0C8E}-\u{0C90}
    \u{0C92}-\u{0CA8}
    \u{0CAA}-\u{0CB3}
    \u{0CB5}-\u{0CB9}
    \u{0CBC}-\u{0CC4}
    \u{0CC6}-\u{0CC8}
    \u{0CCA}-\u{0CCD}
    \u{0CD5}-\u{0CD6}
    \u{0CDE}
    \u{0CE0}-\u{0CE3}
    \u{0CE6}-\u{0CEF}
    \u{0CF1}-\u{0CF2}
    \u{0D00}-\u{0D0C}
    \u{0D0E}-\u{0D10}
    \u{0D12}-\u{0D44}
    \u{0D46}-\u{0D48}
    \u{0D4A}-\u{0D4F}
    \u{0D54}-\u{0D63}
    \u{0D66}-\u{0D7F}
    \u{0D81}-\u{0D83}
    \u{0D85}-\u{0D96}
    \u{0D9A}-\u{0DB1}
    \u{0DB3}-\u{0DBB}
    \u{0DBD}
    \u{0DC0}-\u{0DC6}
    \u{0DCA}
    \u{0DCF}-\u{0DD4}
    \u{0DD6}
    \u{0DD8}-\u{0DDF}
    \u{0DE6}-\u{0DEF}
    \u{0DF2}-\u{0DF4}
    \u{0E01}-\u{0E3A}
    \u{0E3F}-\u{0E5B}
    \u{0E81}-\u{0E82}
    \u{0E84}
    \u{0E86}-\u{0E8A}
    \u{0E8C}-\u{0EA3}
    \u{0EA5}
    \u{0EA7}-\u{0EBD}
    \u{0EC0}-\u{0EC4}
    \u{0EC6}
    \u{0EC8}-\u{0ECD}
    \u{0ED0}-\u{0ED9}
    \u{0EDC}-\u{0EDF}
    \u{0F00}-\u{0F47}
    \u{0F49}-\u{0F6C}
    \u{0F71}-\u{0F97}
    \u{0F99}-\u{0FBC}
    \u{0FBE}-\u{0FCC}
    \u{0FCE}-\u{0FDA}
    \u{1000}-\u{10C5}
    \u{10C7}
    \u{10CD}
    \u{10D0}-\u{10FF}
    \u{1160}-\u{1248}
    \u{124A}-\u{124D}
    \u{1250}-\u{1256}
    \u{1258}
    \u{125A}-\u{125D}
    \u{1260}-\u{1288}
    \u{128A}-\u{128D}
    \u{1290}-\u{12B0}
    \u{12B2}-\u{12B5}
    \u{12B8}-\u{12BE}
    \u{12C0}
    \u{12C2}-\u{12C5}
    \u{12C8}-\u{12D6}
    \u{12D8}-\u{1310}
    \u{1312}-\u{1315}
    \u{1318}-\u{135A}
    \u{135D}-\u{137C}
    \u{1380}-\u{1399}
    \u{13A0}-\u{13F5}
    \u{13F8}-\u{13FD}
    \u{1400}-\u{169C}
    \u{16A0}-\u{16F8}
    \u{1700}-\u{170C}
    \u{170E}-\u{1714}
    \u{1720}-\u{1736}
    \u{1740}-\u{1753}
    \u{1760}-\u{176C}
    \u{176E}-\u{1770}
    \u{1772}-\u{1773}
    \u{1780}-\u{17DD}
    \u{17E0}-\u{17E9}
    \u{17F0}-\u{17F9}
    \u{1800}-\u{180E}
    \u{1810}-\u{1819}
    \u{1820}-\u{1878}
    \u{1880}-\u{18AA}
    \u{18B0}-\u{18F5}
    \u{1900}-\u{191E}
    \u{1920}-\u{192B}
    \u{1930}-\u{193B}
    \u{1940}
    \u{1944}-\u{196D}
    \u{1970}-\u{1974}
    \u{1980}-\u{19AB}
    \u{19B0}-\u{19C9}
    \u{19D0}-\u{19DA}
    \u{19DE}-\u{1A1B}
    \u{1A1E}-\u{1A5E}
    \u{1A60}-\u{1A7C}
    \u{1A7F}-\u{1A89}
    \u{1A90}-\u{1A99}
    \u{1AA0}-\u{1AAD}
    \u{1AB0}-\u{1AC0}
    \u{1B00}-\u{1B4B}
    \u{1B50}-\u{1B7C}
    \u{1B80}-\u{1BF3}
    \u{1BFC}-\u{1C37}
    \u{1C3B}-\u{1C49}
    \u{1C4D}-\u{1C88}
    \u{1C90}-\u{1CBA}
    \u{1CBD}-\u{1CC7}
    \u{1CD0}-\u{1CFA}
    \u{1D00}-\u{1DF9}
    \u{1DFB}-\u{1F15}
    \u{1F18}-\u{1F1D}
    \u{1F20}-\u{1F45}
    \u{1F48}-\u{1F4D}
    \u{1F50}-\u{1F57}
    \u{1F59}
    \u{1F5B}
    \u{1F5D}
    \u{1F5F}-\u{1F7D}
    \u{1F80}-\u{1FB4}
    \u{1FB6}-\u{1FC4}
    \u{1FC6}-\u{1FD3}
    \u{1FD6}-\u{1FDB}
    \u{1FDD}-\u{1FEF}
    \u{1FF2}-\u{1FF4}
    \u{1FF6}-\u{1FFE}
    \u{2000}-\u{200F}
    \u{2011}-\u{2012}
    \u{2017}
    \u{201A}-\u{201B}
    \u{201E}-\u{201F}
    \u{2023}
    \u{2028}-\u{202F}
    \u{2031}
    \u{2034}
    \u{2036}-\u{203A}
    \u{203C}-\u{203D}
    \u{203F}-\u{2064}
    \u{2066}-\u{2071}
    \u{2075}-\u{207E}
    \u{2080}
    \u{2085}-\u{208E}
    \u{2090}-\u{209C}
    \u{20A0}-\u{20A8}
    \u{20AA}-\u{20AB}
    \u{20AD}-\u{20BF}
    \u{20D0}-\u{20F0}
    \u{2100}-\u{2102}
    \u{2104}
    \u{2106}-\u{2108}
    \u{210A}-\u{2112}
    \u{2114}-\u{2115}
    \u{2117}-\u{2120}
    \u{2123}-\u{2125}
    \u{2127}-\u{212A}
    \u{212C}-\u{2152}
    \u{2155}-\u{215A}
    \u{215F}
    \u{216C}-\u{216F}
    \u{217A}-\u{2188}
    \u{218A}-\u{218B}
    \u{219A}-\u{21B7}
    \u{21BA}-\u{21D1}
    \u{21D3}
    \u{21D5}-\u{21E6}
    \u{21E8}-\u{21FF}
    \u{2201}
    \u{2204}-\u{2206}
    \u{2209}-\u{220A}
    \u{220C}-\u{220E}
    \u{2210}
    \u{2212}-\u{2214}
    \u{2216}-\u{2219}
    \u{221B}-\u{221C}
    \u{2221}-\u{2222}
    \u{2224}
    \u{2226}
    \u{222D}
    \u{222F}-\u{2233}
    \u{2238}-\u{223B}
    \u{223E}-\u{2247}
    \u{2249}-\u{224B}
    \u{224D}-\u{2251}
    \u{2253}-\u{225F}
    \u{2262}-\u{2263}
    \u{2268}-\u{2269}
    \u{226C}-\u{226D}
    \u{2270}-\u{2281}
    \u{2284}-\u{2285}
    \u{2288}-\u{2294}
    \u{2296}-\u{2298}
    \u{229A}-\u{22A4}
    \u{22A6}-\u{22BE}
    \u{22C0}-\u{2311}
    \u{2313}-\u{2319}
    \u{231C}-\u{2328}
    \u{232B}-\u{23E8}
    \u{23ED}-\u{23EF}
    \u{23F1}-\u{23F2}
    \u{23F4}-\u{2426}
    \u{2440}-\u{244A}
    \u{24EA}
    \u{254C}-\u{254F}
    \u{2574}-\u{257F}
    \u{2590}-\u{2591}
    \u{2596}-\u{259F}
    \u{25A2}
    \u{25AA}-\u{25B1}
    \u{25B4}-\u{25B5}
    \u{25B8}-\u{25BB}
    \u{25BE}-\u{25BF}
    \u{25C2}-\u{25C5}
    \u{25C9}-\u{25CA}
    \u{25CC}-\u{25CD}
    \u{25D2}-\u{25E1}
    \u{25E6}-\u{25EE}
    \u{25F0}-\u{25FC}
    \u{25FF}-\u{2604}
    \u{2607}-\u{2608}
    \u{260A}-\u{260D}
    \u{2610}-\u{2613}
    \u{2616}-\u{261B}
    \u{261D}
    \u{261F}-\u{263F}
    \u{2641}
    \u{2643}-\u{2647}
    \u{2654}-\u{265F}
    \u{2662}
    \u{2666}
    \u{266B}
    \u{266E}
    \u{2670}-\u{267E}
    \u{2680}-\u{2692}
    \u{2694}-\u{269D}
    \u{26A0}
    \u{26A2}-\u{26A9}
    \u{26AC}-\u{26BC}
    \u{26C0}-\u{26C3}
    \u{26E2}
    \u{26E4}-\u{26E7}
    \u{2700}-\u{2704}
    \u{2706}-\u{2709}
    \u{270C}-\u{2727}
    \u{2729}-\u{273C}
    \u{273E}-\u{274B}
    \u{274D}
    \u{274F}-\u{2752}
    \u{2756}
    \u{2758}-\u{2775}
    \u{2780}-\u{2794}
    \u{2798}-\u{27AF}
    \u{27B1}-\u{27BE}
    \u{27C0}-\u{27E5}
    \u{27EE}-\u{2984}
    \u{2987}-\u{2B1A}
    \u{2B1D}-\u{2B4F}
    \u{2B51}-\u{2B54}
    \u{2B5A}-\u{2B73}
    \u{2B76}-\u{2B95}
    \u{2B97}-\u{2C2E}
    \u{2C30}-\u{2C5E}
    \u{2C60}-\u{2CF3}
    \u{2CF9}-\u{2D25}
    \u{2D27}
    \u{2D2D}
    \u{2D30}-\u{2D67}
    \u{2D6F}-\u{2D70}
    \u{2D7F}-\u{2D96}
    \u{2DA0}-\u{2DA6}
    \u{2DA8}-\u{2DAE}
    \u{2DB0}-\u{2DB6}
    \u{2DB8}-\u{2DBE}
    \u{2DC0}-\u{2DC6}
    \u{2DC8}-\u{2DCE}
    \u{2DD0}-\u{2DD6}
    \u{2DD8}-\u{2DDE}
    \u{2DE0}-\u{2E52}
    \u{303F}
    \u{4DC0}-\u{4DFF}
    \u{A4D0}-\u{A62B}
    \u{A640}-\u{A6F7}
    \u{A700}-\u{A7BF}
    \u{A7C2}-\u{A7CA}
    \u{A7F5}-\u{A82C}
    \u{A830}-\u{A839}
    \u{A840}-\u{A877}
    \u{A880}-\u{A8C5}
    \u{A8CE}-\u{A8D9}
    \u{A8E0}-\u{A953}
    \u{A95F}
    \u{A980}-\u{A9CD}
    \u{A9CF}-\u{A9D9}
    \u{A9DE}-\u{A9FE}
    \u{AA00}-\u{AA36}
    \u{AA40}-\u{AA4D}
    \u{AA50}-\u{AA59}
    \u{AA5C}-\u{AAC2}
    \u{AADB}-\u{AAF6}
    \u{AB01}-\u{AB06}
    \u{AB09}-\u{AB0E}
    \u{AB11}-\u{AB16}
    \u{AB20}-\u{AB26}
    \u{AB28}-\u{AB2E}
    \u{AB30}-\u{AB6B}
    \u{AB70}-\u{ABED}
    \u{ABF0}-\u{ABF9}
    \u{D7B0}-\u{D7C6}
    \u{D7CB}-\u{D7FB}
    \u{FB00}-\u{FB06}
    \u{FB13}-\u{FB17}
    \u{FB1D}-\u{FB36}
    \u{FB38}-\u{FB3C}
    \u{FB3E}
    \u{FB40}-\u{FB41}
    \u{FB43}-\u{FB44}
    \u{FB46}-\u{FBC1}
    \u{FBD3}-\u{FD3F}
    \u{FD50}-\u{FD8F}
    \u{FD92}-\u{FDC7}
    \u{FDF0}-\u{FDFD}
    \u{FE20}-\u{FE2F}
    \u{FE70}-\u{FE74}
    \u{FE76}-\u{FEFC}
    \u{FEFF}
    \u{FFF9}-\u{FFFC}
    \u{10000}-\u{1000B}
    \u{1000D}-\u{10026}
    \u{10028}-\u{1003A}
    \u{1003C}-\u{1003D}
    \u{1003F}-\u{1004D}
    \u{10050}-\u{1005D}
    \u{10080}-\u{100FA}
    \u{10100}-\u{10102}
    \u{10107}-\u{10133}
    \u{10137}-\u{1018E}
    \u{10190}-\u{1019C}
    \u{101A0}
    \u{101D0}-\u{101FD}
    \u{10280}-\u{1029C}
    \u{102A0}-\u{102D0}
    \u{102E0}-\u{102FB}
    \u{10300}-\u{10323}
    \u{1032D}-\u{1034A}
    \u{10350}-\u{1037A}
    \u{10380}-\u{1039D}
    \u{1039F}-\u{103C3}
    \u{103C8}-\u{103D5}
    \u{10400}-\u{1049D}
    \u{104A0}-\u{104A9}
    \u{104B0}-\u{104D3}
    \u{104D8}-\u{104FB}
    \u{10500}-\u{10527}
    \u{10530}-\u{10563}
    \u{1056F}
    \u{10600}-\u{10736}
    \u{10740}-\u{10755}
    \u{10760}-\u{10767}
    \u{10800}-\u{10805}
    \u{10808}
    \u{1080A}-\u{10835}
    \u{10837}-\u{10838}
    \u{1083C}
    \u{1083F}-\u{10855}
    \u{10857}-\u{1089E}
    \u{108A7}-\u{108AF}
    \u{108E0}-\u{108F2}
    \u{108F4}-\u{108F5}
    \u{108FB}-\u{1091B}
    \u{1091F}-\u{10939}
    \u{1093F}
    \u{10980}-\u{109B7}
    \u{109BC}-\u{109CF}
    \u{109D2}-\u{10A03}
    \u{10A05}-\u{10A06}
    \u{10A0C}-\u{10A13}
    \u{10A15}-\u{10A17}
    \u{10A19}-\u{10A35}
    \u{10A38}-\u{10A3A}
    \u{10A3F}-\u{10A48}
    \u{10A50}-\u{10A58}
    \u{10A60}-\u{10A9F}
    \u{10AC0}-\u{10AE6}
    \u{10AEB}-\u{10AF6}
    \u{10B00}-\u{10B35}
    \u{10B39}-\u{10B55}
    \u{10B58}-\u{10B72}
    \u{10B78}-\u{10B91}
    \u{10B99}-\u{10B9C}
    \u{10BA9}-\u{10BAF}
    \u{10C00}-\u{10C48}
    \u{10C80}-\u{10CB2}
    \u{10CC0}-\u{10CF2}
    \u{10CFA}-\u{10D27}
    \u{10D30}-\u{10D39}
    \u{10E60}-\u{10E7E}
    \u{10E80}-\u{10EA9}
    \u{10EAB}-\u{10EAD}
    \u{10EB0}-\u{10EB1}
    \u{10F00}-\u{10F27}
    \u{10F30}-\u{10F59}
    \u{10FB0}-\u{10FCB}
    \u{10FE0}-\u{10FF6}
    \u{11000}-\u{1104D}
    \u{11052}-\u{1106F}
    \u{1107F}-\u{110C1}
    \u{110CD}
    \u{110D0}-\u{110E8}
    \u{110F0}-\u{110F9}
    \u{11100}-\u{11134}
    \u{11136}-\u{11147}
    \u{11150}-\u{11176}
    \u{11180}-\u{111DF}
    \u{111E1}-\u{111F4}
    \u{11200}-\u{11211}
    \u{11213}-\u{1123E}
    \u{11280}-\u{11286}
    \u{11288}
    \u{1128A}-\u{1128D}
    \u{1128F}-\u{1129D}
    \u{1129F}-\u{112A9}
    \u{112B0}-\u{112EA}
    \u{112F0}-\u{112F9}
    \u{11300}-\u{11303}
    \u{11305}-\u{1130C}
    \u{1130F}-\u{11310}
    \u{11313}-\u{11328}
    \u{1132A}-\u{11330}
    \u{11332}-\u{11333}
    \u{11335}-\u{11339}
    \u{1133B}-\u{11344}
    \u{11347}-\u{11348}
    \u{1134B}-\u{1134D}
    \u{11350}
    \u{11357}
    \u{1135D}-\u{11363}
    \u{11366}-\u{1136C}
    \u{11370}-\u{11374}
    \u{11400}-\u{1145B}
    \u{1145D}-\u{11461}
    \u{11480}-\u{114C7}
    \u{114D0}-\u{114D9}
    \u{11580}-\u{115B5}
    \u{115B8}-\u{115DD}
    \u{11600}-\u{11644}
    \u{11650}-\u{11659}
    \u{11660}-\u{1166C}
    \u{11680}-\u{116B8}
    \u{116C0}-\u{116C9}
    \u{11700}-\u{1171A}
    \u{1171D}-\u{1172B}
    \u{11730}-\u{1173F}
    \u{11800}-\u{1183B}
    \u{118A0}-\u{118F2}
    \u{118FF}-\u{11906}
    \u{11909}
    \u{1190C}-\u{11913}
    \u{11915}-\u{11916}
    \u{11918}-\u{11935}
    \u{11937}-\u{11938}
    \u{1193B}-\u{11946}
    \u{11950}-\u{11959}
    \u{119A0}-\u{119A7}
    \u{119AA}-\u{119D7}
    \u{119DA}-\u{119E4}
    \u{11A00}-\u{11A47}
    \u{11A50}-\u{11AA2}
    \u{11AC0}-\u{11AF8}
    \u{11C00}-\u{11C08}
    \u{11C0A}-\u{11C36}
    \u{11C38}-\u{11C45}
    \u{11C50}-\u{11C6C}
    \u{11C70}-\u{11C8F}
    \u{11C92}-\u{11CA7}
    \u{11CA9}-\u{11CB6}
    \u{11D00}-\u{11D06}
    \u{11D08}-\u{11D09}
    \u{11D0B}-\u{11D36}
    \u{11D3A}
    \u{11D3C}-\u{11D3D}
    \u{11D3F}-\u{11D47}
    \u{11D50}-\u{11D59}
    \u{11D60}-\u{11D65}
    \u{11D67}-\u{11D68}
    \u{11D6A}-\u{11D8E}
    \u{11D90}-\u{11D91}
    \u{11D93}-\u{11D98}
    \u{11DA0}-\u{11DA9}
    \u{11EE0}-\u{11EF8}
    \u{11FB0}
    \u{11FC0}-\u{11FF1}
    \u{11FFF}-\u{12399}
    \u{12400}-\u{1246E}
    \u{12470}-\u{12474}
    \u{12480}-\u{12543}
    \u{13000}-\u{1342E}
    \u{13430}-\u{13438}
    \u{14400}-\u{14646}
    \u{16800}-\u{16A38}
    \u{16A40}-\u{16A5E}
    \u{16A60}-\u{16A69}
    \u{16A6E}-\u{16A6F}
    \u{16AD0}-\u{16AED}
    \u{16AF0}-\u{16AF5}
    \u{16B00}-\u{16B45}
    \u{16B50}-\u{16B59}
    \u{16B5B}-\u{16B61}
    \u{16B63}-\u{16B77}
    \u{16B7D}-\u{16B8F}
    \u{16E40}-\u{16E9A}
    \u{16F00}-\u{16F4A}
    \u{16F4F}-\u{16F87}
    \u{16F8F}-\u{16F9F}
    \u{1BC00}-\u{1BC6A}
    \u{1BC70}-\u{1BC7C}
    \u{1BC80}-\u{1BC88}
    \u{1BC90}-\u{1BC99}
    \u{1BC9C}-\u{1BCA3}
    \u{1D000}-\u{1D0F5}
    \u{1D100}-\u{1D126}
    \u{1D129}-\u{1D1E8}
    \u{1D200}-\u{1D245}
    \u{1D2E0}-\u{1D2F3}
    \u{1D300}-\u{1D356}
    \u{1D360}-\u{1D378}
    \u{1D400}-\u{1D454}
    \u{1D456}-\u{1D49C}
    \u{1D49E}-\u{1D49F}
    \u{1D4A2}
    \u{1D4A5}-\u{1D4A6}
    \u{1D4A9}-\u{1D4AC}
    \u{1D4AE}-\u{1D4B9}
    \u{1D4BB}
    \u{1D4BD}-\u{1D4C3}
    \u{1D4C5}-\u{1D505}
    \u{1D507}-\u{1D50A}
    \u{1D50D}-\u{1D514}
    \u{1D516}-\u{1D51C}
    \u{1D51E}-\u{1D539}
    \u{1D53B}-\u{1D53E}
    \u{1D540}-\u{1D544}
    \u{1D546}
    \u{1D54A}-\u{1D550}
    \u{1D552}-\u{1D6A5}
    \u{1D6A8}-\u{1D7CB}
    \u{1D7CE}-\u{1DA8B}
    \u{1DA9B}-\u{1DA9F}
    \u{1DAA1}-\u{1DAAF}
    \u{1E000}-\u{1E006}
    \u{1E008}-\u{1E018}
    \u{1E01B}-\u{1E021}
    \u{1E023}-\u{1E024}
    \u{1E026}-\u{1E02A}
    \u{1E100}-\u{1E12C}
    \u{1E130}-\u{1E13D}
    \u{1E140}-\u{1E149}
    \u{1E14E}-\u{1E14F}
    \u{1E2C0}-\u{1E2F9}
    \u{1E2FF}
    \u{1E800}-\u{1E8C4}
    \u{1E8C7}-\u{1E8D6}
    \u{1E900}-\u{1E94B}
    \u{1E950}-\u{1E959}
    \u{1E95E}-\u{1E95F}
    \u{1EC71}-\u{1ECB4}
    \u{1ED01}-\u{1ED3D}
    \u{1EE00}-\u{1EE03}
    \u{1EE05}-\u{1EE1F}
    \u{1EE21}-\u{1EE22}
    \u{1EE24}
    \u{1EE27}
    \u{1EE29}-\u{1EE32}
    \u{1EE34}-\u{1EE37}
    \u{1EE39}
    \u{1EE3B}
    \u{1EE42}
    \u{1EE47}
    \u{1EE49}
    \u{1EE4B}
    \u{1EE4D}-\u{1EE4F}
    \u{1EE51}-\u{1EE52}
    \u{1EE54}
    \u{1EE57}
    \u{1EE59}
    \u{1EE5B}
    \u{1EE5D}
    \u{1EE5F}
    \u{1EE61}-\u{1EE62}
    \u{1EE64}
    \u{1EE67}-\u{1EE6A}
    \u{1EE6C}-\u{1EE72}
    \u{1EE74}-\u{1EE77}
    \u{1EE79}-\u{1EE7C}
    \u{1EE7E}
    \u{1EE80}-\u{1EE89}
    \u{1EE8B}-\u{1EE9B}
    \u{1EEA1}-\u{1EEA3}
    \u{1EEA5}-\u{1EEA9}
    \u{1EEAB}-\u{1EEBB}
    \u{1EEF0}-\u{1EEF1}
    \u{1F000}-\u{1F003}
    \u{1F005}-\u{1F02B}
    \u{1F030}-\u{1F093}
    \u{1F0A0}-\u{1F0AE}
    \u{1F0B1}-\u{1F0BF}
    \u{1F0C1}-\u{1F0CE}
    \u{1F0D1}-\u{1F0F5}
    \u{1F10B}-\u{1F10F}
    \u{1F12E}-\u{1F12F}
    \u{1F16A}-\u{1F16F}
    \u{1F1AD}
    \u{1F1E6}-\u{1F1FF}
    \u{1F321}-\u{1F32C}
    \u{1F336}
    \u{1F37D}
    \u{1F394}-\u{1F39F}
    \u{1F3CB}-\u{1F3CE}
    \u{1F3D4}-\u{1F3DF}
    \u{1F3F1}-\u{1F3F3}
    \u{1F3F5}-\u{1F3F7}
    \u{1F43F}
    \u{1F441}
    \u{1F4FD}-\u{1F4FE}
    \u{1F53E}-\u{1F54A}
    \u{1F54F}
    \u{1F568}-\u{1F579}
    \u{1F57B}-\u{1F594}
    \u{1F597}-\u{1F5A3}
    \u{1F5A5}-\u{1F5FA}
    \u{1F650}-\u{1F67F}
    \u{1F6C6}-\u{1F6CB}
    \u{1F6CD}-\u{1F6CF}
    \u{1F6D3}-\u{1F6D4}
    \u{1F6E0}-\u{1F6EA}
    \u{1F6F0}-\u{1F6F3}
    \u{1F700}-\u{1F773}
    \u{1F780}-\u{1F7D8}
    \u{1F800}-\u{1F80B}
    \u{1F810}-\u{1F847}
    \u{1F850}-\u{1F859}
    \u{1F860}-\u{1F887}
    \u{1F890}-\u{1F8AD}
    \u{1F8B0}-\u{1F8B1}
    \u{1F900}-\u{1F90B}
    \u{1F93B}
    \u{1F946}
    \u{1FA00}-\u{1FA53}
    \u{1FA60}-\u{1FA6D}
    \u{1FB00}-\u{1FB92}
    \u{1FB94}-\u{1FBCA}
    \u{1FBF0}-\u{1FBF9}
    \u{E0001}
    \u{E0020}-\u{E007F}
  ).join }]/
end
module Reline
  VERSION = '0.2.5'
end
require 'reline/kill_ring'
require 'reline/unicode'

require 'tempfile'

class Reline::LineEditor
  # TODO: undo
  attr_reader :line
  attr_reader :byte_pointer
  attr_accessor :confirm_multiline_termination_proc
  attr_accessor :completion_proc
  attr_accessor :completion_append_character
  attr_accessor :output_modifier_proc
  attr_accessor :prompt_proc
  attr_accessor :auto_indent_proc
  attr_accessor :pre_input_hook
  attr_accessor :dig_perfect_match_proc
  attr_writer :output

  VI_MOTIONS = %i{
    ed_prev_char
    ed_next_char
    vi_zero
    ed_move_to_beg
    ed_move_to_end
    vi_to_column
    vi_next_char
    vi_prev_char
    vi_next_word
    vi_prev_word
    vi_to_next_char
    vi_to_prev_char
    vi_end_word
    vi_next_big_word
    vi_prev_big_word
    vi_end_big_word
    vi_repeat_next_char
    vi_repeat_prev_char
  }

  module CompletionState
    NORMAL = :normal
    COMPLETION = :completion
    MENU = :menu
    JOURNEY = :journey
    MENU_WITH_PERFECT_MATCH = :menu_with_perfect_match
    PERFECT_MATCH = :perfect_match
  end

  CompletionJourneyData = Struct.new('CompletionJourneyData', :preposing, :postposing, :list, :pointer)
  MenuInfo = Struct.new('MenuInfo', :target, :list)

  PROMPT_LIST_CACHE_TIMEOUT = 0.5

  def initialize(config, encoding)
    @config = config
    @completion_append_character = ''
    reset_variables(encoding: encoding)
  end

  def set_pasting_state(in_pasting)
    @in_pasting = in_pasting
  end

  def simplified_rendering?
    if finished?
      false
    elsif @just_cursor_moving and not @rerender_all
      true
    else
      not @rerender_all and not finished? and @in_pasting
    end
  end

  private def check_mode_string
    mode_string = nil
    if @config.show_mode_in_prompt
      if @config.editing_mode_is?(:vi_command)
        mode_string = @config.vi_cmd_mode_string
      elsif @config.editing_mode_is?(:vi_insert)
        mode_string = @config.vi_ins_mode_string
      elsif @config.editing_mode_is?(:emacs)
        mode_string = @config.emacs_mode_string
      else
        mode_string = '?'
      end
    end
    if mode_string != @prev_mode_string
      @rerender_all = true
    end
    @prev_mode_string = mode_string
    mode_string
  end

  private def check_multiline_prompt(buffer, prompt)
    if @vi_arg
      prompt = "(arg: #{@vi_arg}) "
      @rerender_all = true
    elsif @searching_prompt
      prompt = @searching_prompt
      @rerender_all = true
    else
      prompt = @prompt
    end
    if simplified_rendering?
      mode_string = check_mode_string
      prompt = mode_string + prompt if mode_string
      return [prompt, calculate_width(prompt, true), [prompt] * buffer.size]
    end
    if @prompt_proc
      use_cached_prompt_list = false
      if @cached_prompt_list
        if @just_cursor_moving
          use_cached_prompt_list = true
        elsif Time.now.to_f < (@prompt_cache_time + PROMPT_LIST_CACHE_TIMEOUT) and buffer.size == @cached_prompt_list.size
          use_cached_prompt_list = true
        end
      end
      use_cached_prompt_list = false if @rerender_all
      if use_cached_prompt_list
        prompt_list = @cached_prompt_list
      else
        prompt_list = @cached_prompt_list = @prompt_proc.(buffer)
        @prompt_cache_time = Time.now.to_f
      end
      prompt_list.map!{ prompt } if @vi_arg or @searching_prompt
      prompt_list = [prompt] if prompt_list.empty?
      mode_string = check_mode_string
      prompt_list = prompt_list.map{ |pr| mode_string + pr } if mode_string
      prompt = prompt_list[@line_index]
      prompt = prompt_list[0] if prompt.nil?
      prompt = prompt_list.last if prompt.nil?
      if buffer.size > prompt_list.size
        (buffer.size - prompt_list.size).times do
          prompt_list << prompt_list.last
        end
      end
      prompt_width = calculate_width(prompt, true)
      [prompt, prompt_width, prompt_list]
    else
      mode_string = check_mode_string
      prompt = mode_string + prompt if mode_string
      prompt_width = calculate_width(prompt, true)
      [prompt, prompt_width, nil]
    end
  end

  def reset(prompt = '', encoding:)
    @rest_height = (Reline::IOGate.get_screen_size.first - 1) - Reline::IOGate.cursor_pos.y
    @screen_size = Reline::IOGate.get_screen_size
    @screen_height = @screen_size.first
    reset_variables(prompt, encoding: encoding)
    @old_trap = Signal.trap('SIGINT') {
      if @scroll_partial_screen
        move_cursor_down(@screen_height - (@line_index - @scroll_partial_screen) - 1)
      else
        move_cursor_down(@highest_in_all - @line_index - 1)
      end
      Reline::IOGate.move_cursor_column(0)
      scroll_down(1)
      @old_trap.call if @old_trap.respond_to?(:call) # can also be string, ex: "DEFAULT"
      raise Interrupt
    }
    Reline::IOGate.set_winch_handler do
      @rest_height = (Reline::IOGate.get_screen_size.first - 1) - Reline::IOGate.cursor_pos.y
      old_screen_size = @screen_size
      @screen_size = Reline::IOGate.get_screen_size
      @screen_height = @screen_size.first
      if old_screen_size.last < @screen_size.last # columns increase
        @rerender_all = true
        rerender
      else
        back = 0
        new_buffer = whole_lines
        prompt, prompt_width, prompt_list = check_multiline_prompt(new_buffer, prompt)
        new_buffer.each_with_index do |line, index|
          prompt_width = calculate_width(prompt_list[index], true) if @prompt_proc
          width = prompt_width + calculate_width(line)
          height = calculate_height_by_width(width)
          back += height
        end
        @highest_in_all = back
        @highest_in_this = calculate_height_by_width(prompt_width + @cursor_max)
        @first_line_started_from =
          if @line_index.zero?
            0
          else
            calculate_height_by_lines(@buffer_of_lines[0..(@line_index - 1)], prompt_list || prompt)
          end
        if @prompt_proc
          prompt = prompt_list[@line_index]
          prompt_width = calculate_width(prompt, true)
        end
        calculate_nearest_cursor
        @started_from = calculate_height_by_width(prompt_width + @cursor) - 1
        Reline::IOGate.move_cursor_column((prompt_width + @cursor) % @screen_size.last)
        @highest_in_this = calculate_height_by_width(prompt_width + @cursor_max)
        @rerender_all = true
      end
    end
  end

  def finalize
    Signal.trap('SIGINT', @old_trap)
  end

  def eof?
    @eof
  end

  def reset_variables(prompt = '', encoding:)
    @prompt = prompt
    @mark_pointer = nil
    @encoding = encoding
    @is_multiline = false
    @finished = false
    @cleared = false
    @rerender_all = false
    @history_pointer = nil
    @kill_ring ||= Reline::KillRing.new
    @vi_clipboard = ''
    @vi_arg = nil
    @waiting_proc = nil
    @waiting_operator_proc = nil
    @waiting_operator_vi_arg = nil
    @completion_journey_data = nil
    @completion_state = CompletionState::NORMAL
    @perfect_matched = nil
    @menu_info = nil
    @first_prompt = true
    @searching_prompt = nil
    @first_char = true
    @add_newline_to_end_of_buffer = false
    @just_cursor_moving = nil
    @cached_prompt_list = nil
    @prompt_cache_time = nil
    @eof = false
    @continuous_insertion_buffer = String.new(encoding: @encoding)
    @scroll_partial_screen = nil
    @prev_mode_string = nil
    @drop_terminate_spaces = false
    @in_pasting = false
    @auto_indent_proc = nil
    reset_line
  end

  def reset_line
    @cursor = 0
    @cursor_max = 0
    @byte_pointer = 0
    @buffer_of_lines = [String.new(encoding: @encoding)]
    @line_index = 0
    @previous_line_index = nil
    @line = @buffer_of_lines[0]
    @first_line_started_from = 0
    @move_up = 0
    @started_from = 0
    @highest_in_this = 1
    @highest_in_all = 1
    @line_backup_in_history = nil
    @multibyte_buffer = String.new(encoding: 'ASCII-8BIT')
    @check_new_auto_indent = false
  end

  def multiline_on
    @is_multiline = true
  end

  def multiline_off
    @is_multiline = false
  end

  private def calculate_height_by_lines(lines, prompt)
    result = 0
    prompt_list = prompt.is_a?(Array) ? prompt : nil
    lines.each_with_index { |line, i|
      prompt = prompt_list[i] if prompt_list and prompt_list[i]
      result += calculate_height_by_width(calculate_width(prompt, true) + calculate_width(line))
    }
    result
  end

  private def insert_new_line(cursor_line, next_line)
    @line = cursor_line
    @buffer_of_lines.insert(@line_index + 1, String.new(next_line, encoding: @encoding))
    @previous_line_index = @line_index
    @line_index += 1
    @just_cursor_moving = false
  end

  private def calculate_height_by_width(width)
    width.div(@screen_size.last) + 1
  end

  private def split_by_width(str, max_width)
    Reline::Unicode.split_by_width(str, max_width, @encoding)
  end

  private def scroll_down(val)
    if val <= @rest_height
      Reline::IOGate.move_cursor_down(val)
      @rest_height -= val
    else
      Reline::IOGate.move_cursor_down(@rest_height)
      Reline::IOGate.scroll_down(val - @rest_height)
      @rest_height = 0
    end
  end

  private def move_cursor_up(val)
    if val > 0
      Reline::IOGate.move_cursor_up(val)
      @rest_height += val
    elsif val < 0
      move_cursor_down(-val)
    end
  end

  private def move_cursor_down(val)
    if val > 0
      Reline::IOGate.move_cursor_down(val)
      @rest_height -= val
      @rest_height = 0 if @rest_height < 0
    elsif val < 0
      move_cursor_up(-val)
    end
  end

  private def calculate_nearest_cursor(line_to_calc = @line, cursor = @cursor, started_from = @started_from, byte_pointer = @byte_pointer, update = true)
    new_cursor_max = calculate_width(line_to_calc)
    new_cursor = 0
    new_byte_pointer = 0
    height = 1
    max_width = @screen_size.last
    if @config.editing_mode_is?(:vi_command)
      last_byte_size = Reline::Unicode.get_prev_mbchar_size(line_to_calc, line_to_calc.bytesize)
      if last_byte_size > 0
        last_mbchar = line_to_calc.byteslice(line_to_calc.bytesize - last_byte_size, last_byte_size)
        last_width = Reline::Unicode.get_mbchar_width(last_mbchar)
        end_of_line_cursor = new_cursor_max - last_width
      else
      end_of_line_cursor = new_cursor_max
      end
    else
    end_of_line_cursor = new_cursor_max
    end
    line_to_calc.grapheme_clusters.each do |gc|
      mbchar = gc.encode(Encoding::UTF_8)
      mbchar_width = Reline::Unicode.get_mbchar_width(mbchar)
      now = new_cursor + mbchar_width
      if now > end_of_line_cursor or now > cursor
        break
      end
      new_cursor += mbchar_width
      if new_cursor > max_width * height
        height += 1
      end
      new_byte_pointer += gc.bytesize
    end
    new_started_from = height - 1
    if update
      @cursor = new_cursor
      @cursor_max = new_cursor_max
      @started_from = new_started_from
      @byte_pointer = new_byte_pointer
    else
      [new_cursor, new_cursor_max, new_started_from, new_byte_pointer]
    end
  end

  def rerender_all
    @rerender_all = true
    process_insert(force: true)
    rerender
  end

  def rerender
    return if @line.nil?
    if @menu_info
      scroll_down(@highest_in_all - @first_line_started_from)
      @rerender_all = true
    end
    if @menu_info
      show_menu
      @menu_info = nil
    end
    prompt, prompt_width, prompt_list = check_multiline_prompt(whole_lines, prompt)
    if @cleared
      clear_screen_buffer(prompt, prompt_list, prompt_width)
      @cleared = false
      return
    end
    if @is_multiline and finished? and @scroll_partial_screen
      # Re-output all code higher than the screen when finished.
      Reline::IOGate.move_cursor_up(@first_line_started_from + @started_from - @scroll_partial_screen)
      Reline::IOGate.move_cursor_column(0)
      @scroll_partial_screen = nil
      prompt, prompt_width, prompt_list = check_multiline_prompt(whole_lines, prompt)
      if @previous_line_index
        new_lines = whole_lines(index: @previous_line_index, line: @line)
      else
        new_lines = whole_lines
      end
      modify_lines(new_lines).each_with_index do |line, index|
        @output.write "#{prompt_list ? prompt_list[index] : prompt}#{line}\n"
        Reline::IOGate.erase_after_cursor
      end
      @output.flush
      return
    end
    new_highest_in_this = calculate_height_by_width(prompt_width + calculate_width(@line.nil? ? '' : @line))
    # FIXME: end of logical line sometimes breaks
    rendered = false
    if @add_newline_to_end_of_buffer
      rerender_added_newline(prompt, prompt_width)
      @add_newline_to_end_of_buffer = false
    else
      if @just_cursor_moving and not @rerender_all
        rendered = just_move_cursor
        @just_cursor_moving = false
        return
      elsif @previous_line_index or new_highest_in_this != @highest_in_this
        rerender_changed_current_line
        @previous_line_index = nil
        rendered = true
      elsif @rerender_all
        rerender_all_lines
        @rerender_all = false
        rendered = true
      else
      end
    end
    if @is_multiline
      if finished?
        # Always rerender on finish because output_modifier_proc may return a different output.
        if @previous_line_index
          new_lines = whole_lines(index: @previous_line_index, line: @line)
        else
          new_lines = whole_lines
        end
        line = modify_lines(new_lines)[@line_index]
        prompt, prompt_width, prompt_list = check_multiline_prompt(new_lines, prompt)
        render_partial(prompt, prompt_width, line, @first_line_started_from)
        move_cursor_down(@highest_in_all - (@first_line_started_from + @highest_in_this - 1) - 1)
        scroll_down(1)
        Reline::IOGate.move_cursor_column(0)
        Reline::IOGate.erase_after_cursor
      elsif not rendered
        unless @in_pasting
          line = modify_lines(whole_lines)[@line_index]
          prompt, prompt_width, prompt_list = check_multiline_prompt(whole_lines, prompt)
          render_partial(prompt, prompt_width, line, @first_line_started_from)
        end
      end
      @buffer_of_lines[@line_index] = @line
      @rest_height = 0 if @scroll_partial_screen
    else
      line = modify_lines(whole_lines)[@line_index]
      render_partial(prompt, prompt_width, line, 0)
      if finished?
        scroll_down(1)
        Reline::IOGate.move_cursor_column(0)
        Reline::IOGate.erase_after_cursor
      end
    end
  end

  private def calculate_scroll_partial_screen(highest_in_all, cursor_y)
    if @screen_height < highest_in_all
      old_scroll_partial_screen = @scroll_partial_screen
      if cursor_y == 0
        @scroll_partial_screen = 0
      elsif cursor_y == (highest_in_all - 1)
        @scroll_partial_screen = highest_in_all - @screen_height
      else
        if @scroll_partial_screen
          if cursor_y <= @scroll_partial_screen
            @scroll_partial_screen = cursor_y
          elsif (@scroll_partial_screen + @screen_height - 1) < cursor_y
            @scroll_partial_screen = cursor_y - (@screen_height - 1)
          end
        else
          if cursor_y > (@screen_height - 1)
            @scroll_partial_screen = cursor_y - (@screen_height - 1)
          else
            @scroll_partial_screen = 0
          end
        end
      end
      if @scroll_partial_screen != old_scroll_partial_screen
        @rerender_all = true
      end
    else
      if @scroll_partial_screen
        @rerender_all = true
      end
      @scroll_partial_screen = nil
    end
  end

  private def rerender_added_newline(prompt, prompt_width)
    scroll_down(1)
    @buffer_of_lines[@previous_line_index] = @line
    @line = @buffer_of_lines[@line_index]
    unless @in_pasting
      render_partial(prompt, prompt_width, @line, @first_line_started_from + @started_from + 1, with_control: false)
    end
    @cursor = @cursor_max = calculate_width(@line)
    @byte_pointer = @line.bytesize
    @highest_in_all += @highest_in_this
    @highest_in_this = calculate_height_by_width(prompt_width + @cursor_max)
    @first_line_started_from += @started_from + 1
    @started_from = calculate_height_by_width(prompt_width + @cursor) - 1
    @previous_line_index = nil
  end

  def just_move_cursor
    prompt, prompt_width, prompt_list = check_multiline_prompt(@buffer_of_lines, prompt)
    move_cursor_up(@started_from)
    new_first_line_started_from =
      if @line_index.zero?
        0
      else
        calculate_height_by_lines(@buffer_of_lines[0..(@line_index - 1)], prompt_list || prompt)
      end
    first_line_diff = new_first_line_started_from - @first_line_started_from
    new_cursor, new_cursor_max, new_started_from, new_byte_pointer = calculate_nearest_cursor(@buffer_of_lines[@line_index], @cursor, @started_from, @byte_pointer, false)
    new_started_from = calculate_height_by_width(prompt_width + new_cursor) - 1
    calculate_scroll_partial_screen(@highest_in_all, new_first_line_started_from + new_started_from)
    @previous_line_index = nil
    if @rerender_all
      @line = @buffer_of_lines[@line_index]
      rerender_all_lines
      @rerender_all = false
      true
    else
      @line = @buffer_of_lines[@line_index]
      @first_line_started_from = new_first_line_started_from
      @started_from = new_started_from
      @cursor = new_cursor
      @cursor_max = new_cursor_max
      @byte_pointer = new_byte_pointer
      move_cursor_down(first_line_diff + @started_from)
      Reline::IOGate.move_cursor_column((prompt_width + @cursor) % @screen_size.last)
      false
    end
  end

  private def rerender_changed_current_line
    if @previous_line_index
      new_lines = whole_lines(index: @previous_line_index, line: @line)
    else
      new_lines = whole_lines
    end
    prompt, prompt_width, prompt_list = check_multiline_prompt(new_lines, prompt)
    all_height = calculate_height_by_lines(new_lines, prompt_list || prompt)
    diff = all_height - @highest_in_all
    move_cursor_down(@highest_in_all - @first_line_started_from - @started_from - 1)
    if diff > 0
      scroll_down(diff)
      move_cursor_up(all_height - 1)
    elsif diff < 0
      (-diff).times do
        Reline::IOGate.move_cursor_column(0)
        Reline::IOGate.erase_after_cursor
        move_cursor_up(1)
      end
      move_cursor_up(all_height - 1)
    else
      move_cursor_up(all_height - 1)
    end
    @highest_in_all = all_height
    back = render_whole_lines(new_lines, prompt_list || prompt, prompt_width)
    move_cursor_up(back)
    if @previous_line_index
      @buffer_of_lines[@previous_line_index] = @line
      @line = @buffer_of_lines[@line_index]
    end
    @first_line_started_from =
      if @line_index.zero?
        0
      else
        calculate_height_by_lines(@buffer_of_lines[0..(@line_index - 1)], prompt_list || prompt)
      end
    if @prompt_proc
      prompt = prompt_list[@line_index]
      prompt_width = calculate_width(prompt, true)
    end
    move_cursor_down(@first_line_started_from)
    calculate_nearest_cursor
    @started_from = calculate_height_by_width(prompt_width + @cursor) - 1
    move_cursor_down(@started_from)
    Reline::IOGate.move_cursor_column((prompt_width + @cursor) % @screen_size.last)
    @highest_in_this = calculate_height_by_width(prompt_width + @cursor_max)
  end

  private def rerender_all_lines
    move_cursor_up(@first_line_started_from + @started_from)
    Reline::IOGate.move_cursor_column(0)
    back = 0
    new_buffer = whole_lines
    prompt, prompt_width, prompt_list = check_multiline_prompt(new_buffer, prompt)
    new_buffer.each_with_index do |line, index|
      prompt_width = calculate_width(prompt_list[index], true) if @prompt_proc
      width = prompt_width + calculate_width(line)
      height = calculate_height_by_width(width)
      back += height
    end
    old_highest_in_all = @highest_in_all
    if @line_index.zero?
      new_first_line_started_from = 0
    else
      new_first_line_started_from = calculate_height_by_lines(new_buffer[0..(@line_index - 1)], prompt_list || prompt)
    end
    new_started_from = calculate_height_by_width(prompt_width + @cursor) - 1
    calculate_scroll_partial_screen(back, new_first_line_started_from + new_started_from)
    if @scroll_partial_screen
      move_cursor_up(@first_line_started_from + @started_from)
      scroll_down(@screen_height - 1)
      move_cursor_up(@screen_height)
      Reline::IOGate.move_cursor_column(0)
    elsif back > old_highest_in_all
      scroll_down(back - 1)
      move_cursor_up(back - 1)
    elsif back < old_highest_in_all
      scroll_down(back)
      Reline::IOGate.erase_after_cursor
      (old_highest_in_all - back - 1).times do
        scroll_down(1)
        Reline::IOGate.erase_after_cursor
      end
      move_cursor_up(old_highest_in_all - 1)
    end
    render_whole_lines(new_buffer, prompt_list || prompt, prompt_width)
    if @prompt_proc
      prompt = prompt_list[@line_index]
      prompt_width = calculate_width(prompt, true)
    end
    @highest_in_this = calculate_height_by_width(prompt_width + @cursor_max)
    @highest_in_all = back
    @first_line_started_from = new_first_line_started_from
    @started_from = new_started_from
    if @scroll_partial_screen
      Reline::IOGate.move_cursor_up(@screen_height - (@first_line_started_from + @started_from - @scroll_partial_screen) - 1)
      Reline::IOGate.move_cursor_column((prompt_width + @cursor) % @screen_size.last)
    else
      move_cursor_down(@first_line_started_from + @started_from - back + 1)
      Reline::IOGate.move_cursor_column((prompt_width + @cursor) % @screen_size.last)
    end
  end

  private def render_whole_lines(lines, prompt, prompt_width)
    rendered_height = 0
    modify_lines(lines).each_with_index do |line, index|
      if prompt.is_a?(Array)
        line_prompt = prompt[index]
        prompt_width = calculate_width(line_prompt, true)
      else
        line_prompt = prompt
      end
      height = render_partial(line_prompt, prompt_width, line, rendered_height, with_control: false)
      if index < (lines.size - 1)
        if @scroll_partial_screen
          if (@scroll_partial_screen - height) < rendered_height and (@scroll_partial_screen + @screen_height - 1) >= (rendered_height + height)
            move_cursor_down(1)
          end
        else
          scroll_down(1)
        end
        rendered_height += height
      else
        rendered_height += height - 1
      end
    end
    rendered_height
  end

  private def render_partial(prompt, prompt_width, line_to_render, this_started_from, with_control: true)
    visual_lines, height = split_by_width(line_to_render.nil? ? prompt : prompt + line_to_render, @screen_size.last)
    cursor_up_from_last_line = 0
    # TODO: This logic would be sometimes buggy if this logical line isn't the current @line_index.
    if @scroll_partial_screen
      last_visual_line = this_started_from + (height - 1)
      last_screen_line = @scroll_partial_screen + (@screen_height - 1)
      if (@scroll_partial_screen - this_started_from) >= height
        # Render nothing because this line is before the screen.
        visual_lines = []
      elsif this_started_from > last_screen_line
        # Render nothing because this line is after the screen.
        visual_lines = []
      else
        deleted_lines_before_screen = []
        if @scroll_partial_screen > this_started_from and last_visual_line >= @scroll_partial_screen
          # A part of visual lines are before the screen.
          deleted_lines_before_screen = visual_lines.shift((@scroll_partial_screen - this_started_from) * 2)
          deleted_lines_before_screen.compact!
        end
        if this_started_from <= last_screen_line and last_screen_line < last_visual_line
          # A part of visual lines are after the screen.
          visual_lines.pop((last_visual_line - last_screen_line) * 2)
        end
        move_cursor_up(deleted_lines_before_screen.size - @started_from)
        cursor_up_from_last_line = @started_from - deleted_lines_before_screen.size
      end
    end
    if with_control
      if height > @highest_in_this
        diff = height - @highest_in_this
        scroll_down(diff)
        @highest_in_all += diff
        @highest_in_this = height
        move_cursor_up(diff)
      elsif height < @highest_in_this
        diff = @highest_in_this - height
        @highest_in_all -= diff
        @highest_in_this = height
      end
      move_cursor_up(@started_from)
      @started_from = calculate_height_by_width(prompt_width + @cursor) - 1
      cursor_up_from_last_line = height - 1 - @started_from
    end
    if Reline::Unicode::CSI_REGEXP.match?(prompt + line_to_render)
      @output.write "\e[0m" # clear character decorations
    end
    visual_lines.each_with_index do |line, index|
      Reline::IOGate.move_cursor_column(0)
      if line.nil?
        if calculate_width(visual_lines[index - 1], true) == Reline::IOGate.get_screen_size.last
          # reaches the end of line
          if Reline::IOGate.win? and Reline::IOGate.win_legacy_console?
            # A newline is automatically inserted if a character is rendered at
            # eol on command prompt.
          else
            # When the cursor is at the end of the line and erases characters
            # after the cursor, some terminals delete the character at the
            # cursor position.
            move_cursor_down(1)
            Reline::IOGate.move_cursor_column(0)
          end
        else
          Reline::IOGate.erase_after_cursor
          move_cursor_down(1)
          Reline::IOGate.move_cursor_column(0)
        end
        next
      end
      @output.write line
      if Reline::IOGate.win? and Reline::IOGate.win_legacy_console? and calculate_width(line, true) == Reline::IOGate.get_screen_size.last
        # A newline is automatically inserted if a character is rendered at eol on command prompt.
        @rest_height -= 1 if @rest_height > 0
      end
      @output.flush
      if @first_prompt
        @first_prompt = false
        @pre_input_hook&.call
      end
    end
    unless visual_lines.empty?
      Reline::IOGate.erase_after_cursor
      Reline::IOGate.move_cursor_column(0)
    end
    if with_control
      # Just after rendring, so the cursor is on the last line.
      if finished?
        Reline::IOGate.move_cursor_column(0)
      else
        # Moves up from bottom of lines to the cursor position.
        move_cursor_up(cursor_up_from_last_line)
        # This logic is buggy if a fullwidth char is wrapped because there is only one halfwidth at end of a line.
        Reline::IOGate.move_cursor_column((prompt_width + @cursor) % @screen_size.last)
      end
    end
    height
  end

  private def modify_lines(before)
    return before if before.nil? || before.empty? || simplified_rendering?

    if after = @output_modifier_proc&.call("#{before.join("\n")}\n", complete: finished?)
      after.lines("\n").map { |l| l.chomp('') }
    else
      before
    end
  end

  private def show_menu
    scroll_down(@highest_in_all - @first_line_started_from)
    @rerender_all = true
    @menu_info.list.sort!.each do |item|
      Reline::IOGate.move_cursor_column(0)
      @output.write item
      @output.flush
      scroll_down(1)
    end
    scroll_down(@highest_in_all - 1)
    move_cursor_up(@highest_in_all - 1 - @first_line_started_from)
  end

  private def clear_screen_buffer(prompt, prompt_list, prompt_width)
    Reline::IOGate.clear_screen
    back = 0
    modify_lines(whole_lines).each_with_index do |line, index|
      if @prompt_proc
        pr = prompt_list[index]
        height = render_partial(pr, calculate_width(pr), line, back, with_control: false)
      else
        height = render_partial(prompt, prompt_width, line, back, with_control: false)
      end
      if index < (@buffer_of_lines.size - 1)
        move_cursor_down(height)
        back += height
      end
    end
    move_cursor_up(back)
    move_cursor_down(@first_line_started_from + @started_from)
    @rest_height = (Reline::IOGate.get_screen_size.first - 1) - Reline::IOGate.cursor_pos.y
    Reline::IOGate.move_cursor_column((prompt_width + @cursor) % @screen_size.last)
  end

  def editing_mode
    @config.editing_mode
  end

  private def menu(target, list)
    @menu_info = MenuInfo.new(target, list)
  end

  private def complete_internal_proc(list, is_menu)
    preposing, target, postposing = retrieve_completion_block
    list = list.select { |i|
      if i and not Encoding.compatible?(target.encoding, i.encoding)
        raise Encoding::CompatibilityError, "#{target.encoding.name} is not compatible with #{i.encoding.name}"
      end
      if @config.completion_ignore_case
        i&.downcase&.start_with?(target.downcase)
      else
        i&.start_with?(target)
      end
    }.uniq
    if is_menu
      menu(target, list)
      return nil
    end
    completed = list.inject { |memo, item|
      begin
        memo_mbchars = memo.unicode_normalize.grapheme_clusters
        item_mbchars = item.unicode_normalize.grapheme_clusters
      rescue Encoding::CompatibilityError
        memo_mbchars = memo.grapheme_clusters
        item_mbchars = item.grapheme_clusters
      end
      size = [memo_mbchars.size, item_mbchars.size].min
      result = ''
      size.times do |i|
        if @config.completion_ignore_case
          if memo_mbchars[i].casecmp?(item_mbchars[i])
            result << memo_mbchars[i]
          else
            break
          end
        else
          if memo_mbchars[i] == item_mbchars[i]
            result << memo_mbchars[i]
          else
            break
          end
        end
      end
      result
    }
    [target, preposing, completed, postposing]
  end

  private def complete(list, just_show_list = false)
    case @completion_state
    when CompletionState::NORMAL, CompletionState::JOURNEY
      @completion_state = CompletionState::COMPLETION
    when CompletionState::PERFECT_MATCH
      @dig_perfect_match_proc&.(@perfect_matched)
    end
    if just_show_list
      is_menu = true
    elsif @completion_state == CompletionState::MENU
      is_menu = true
    elsif @completion_state == CompletionState::MENU_WITH_PERFECT_MATCH
      is_menu = true
    else
      is_menu = false
    end
    result = complete_internal_proc(list, is_menu)
    if @completion_state == CompletionState::MENU_WITH_PERFECT_MATCH
      @completion_state = CompletionState::PERFECT_MATCH
    end
    return if result.nil?
    target, preposing, completed, postposing = result
    return if completed.nil?
    if target <= completed and (@completion_state == CompletionState::COMPLETION)
      if list.include?(completed)
        if list.one?
          @completion_state = CompletionState::PERFECT_MATCH
        else
          @completion_state = CompletionState::MENU_WITH_PERFECT_MATCH
        end
        @perfect_matched = completed
      else
        @completion_state = CompletionState::MENU
      end
      if not just_show_list and target < completed
        @line = preposing + completed + completion_append_character.to_s + postposing
        line_to_pointer = preposing + completed + completion_append_character.to_s
        @cursor_max = calculate_width(@line)
        @cursor = calculate_width(line_to_pointer)
        @byte_pointer = line_to_pointer.bytesize
      end
    end
  end

  private def move_completed_list(list, direction)
    case @completion_state
    when CompletionState::NORMAL, CompletionState::COMPLETION,
         CompletionState::MENU, CompletionState::MENU_WITH_PERFECT_MATCH
      @completion_state = CompletionState::JOURNEY
      result = retrieve_completion_block
      return if result.nil?
      preposing, target, postposing = result
      @completion_journey_data = CompletionJourneyData.new(
        preposing, postposing,
        [target] + list.select{ |item| item.start_with?(target) }, 0)
      @completion_state = CompletionState::JOURNEY
    else
      case direction
      when :up
        @completion_journey_data.pointer -= 1
        if @completion_journey_data.pointer < 0
          @completion_journey_data.pointer = @completion_journey_data.list.size - 1
        end
      when :down
        @completion_journey_data.pointer += 1
        if @completion_journey_data.pointer >= @completion_journey_data.list.size
          @completion_journey_data.pointer = 0
        end
      end
      completed = @completion_journey_data.list[@completion_journey_data.pointer]
      @line = @completion_journey_data.preposing + completed + @completion_journey_data.postposing
      line_to_pointer = @completion_journey_data.preposing + completed
      @cursor_max = calculate_width(@line)
      @cursor = calculate_width(line_to_pointer)
      @byte_pointer = line_to_pointer.bytesize
    end
  end

  private def run_for_operators(key, method_symbol, &block)
    if @waiting_operator_proc
      if VI_MOTIONS.include?(method_symbol)
        old_cursor, old_byte_pointer = @cursor, @byte_pointer
        @vi_arg = @waiting_operator_vi_arg if @waiting_operator_vi_arg > 1
        block.(true)
        unless @waiting_proc
          cursor_diff, byte_pointer_diff = @cursor - old_cursor, @byte_pointer - old_byte_pointer
          @cursor, @byte_pointer = old_cursor, old_byte_pointer
          @waiting_operator_proc.(cursor_diff, byte_pointer_diff)
        else
          old_waiting_proc = @waiting_proc
          old_waiting_operator_proc = @waiting_operator_proc
          current_waiting_operator_proc = @waiting_operator_proc
          @waiting_proc = proc { |k|
            old_cursor, old_byte_pointer = @cursor, @byte_pointer
            old_waiting_proc.(k)
            cursor_diff, byte_pointer_diff = @cursor - old_cursor, @byte_pointer - old_byte_pointer
            @cursor, @byte_pointer = old_cursor, old_byte_pointer
            current_waiting_operator_proc.(cursor_diff, byte_pointer_diff)
            @waiting_operator_proc = old_waiting_operator_proc
          }
        end
      else
        # Ignores operator when not motion is given.
        block.(false)
      end
      @waiting_operator_proc = nil
      @waiting_operator_vi_arg = nil
      @vi_arg = nil
    else
      block.(false)
    end
  end

  private def argumentable?(method_obj)
    method_obj and method_obj.parameters.any? { |param| param[0] == :key and param[1] == :arg }
  end

  private def inclusive?(method_obj)
    # If a motion method with the keyword argument "inclusive" follows the
    # operator, it must contain the character at the cursor position.
    method_obj and method_obj.parameters.any? { |param| param[0] == :key and param[1] == :inclusive }
  end

  def wrap_method_call(method_symbol, method_obj, key, with_operator = false)
    if @config.editing_mode_is?(:emacs, :vi_insert) and @waiting_proc.nil? and @waiting_operator_proc.nil?
      not_insertion = method_symbol != :ed_insert
      process_insert(force: not_insertion)
    end
    if @vi_arg and argumentable?(method_obj)
      if with_operator and inclusive?(method_obj)
        method_obj.(key, arg: @vi_arg, inclusive: true)
      else
        method_obj.(key, arg: @vi_arg)
      end
    else
      if with_operator and inclusive?(method_obj)
        method_obj.(key, inclusive: true)
      else
        method_obj.(key)
      end
    end
  end

  private def process_key(key, method_symbol)
    if method_symbol and respond_to?(method_symbol, true)
      method_obj = method(method_symbol)
    else
      method_obj = nil
    end
    if method_symbol and key.is_a?(Symbol)
      if @vi_arg and argumentable?(method_obj)
        run_for_operators(key, method_symbol) do |with_operator|
          wrap_method_call(method_symbol, method_obj, key, with_operator)
        end
      else
        wrap_method_call(method_symbol, method_obj, key) if method_obj
      end
      @kill_ring.process
      @vi_arg = nil
    elsif @vi_arg
      if key.chr =~ /[0-9]/
        ed_argument_digit(key)
      else
        if argumentable?(method_obj)
          run_for_operators(key, method_symbol) do |with_operator|
            wrap_method_call(method_symbol, method_obj, key, with_operator)
          end
        elsif @waiting_proc
          @waiting_proc.(key)
        elsif method_obj
          wrap_method_call(method_symbol, method_obj, key)
        else
          ed_insert(key) unless @config.editing_mode_is?(:vi_command)
        end
        @kill_ring.process
        @vi_arg = nil
      end
    elsif @waiting_proc
      @waiting_proc.(key)
      @kill_ring.process
    elsif method_obj
      if method_symbol == :ed_argument_digit
        wrap_method_call(method_symbol, method_obj, key)
      else
        run_for_operators(key, method_symbol) do |with_operator|
          wrap_method_call(method_symbol, method_obj, key, with_operator)
        end
      end
      @kill_ring.process
    else
      ed_insert(key) unless @config.editing_mode_is?(:vi_command)
    end
  end

  private def normal_char(key)
    method_symbol = method_obj = nil
    if key.combined_char.is_a?(Symbol)
      process_key(key.combined_char, key.combined_char)
      return
    end
    @multibyte_buffer << key.combined_char
    if @multibyte_buffer.size > 1
      if @multibyte_buffer.dup.force_encoding(@encoding).valid_encoding?
        process_key(@multibyte_buffer.dup.force_encoding(@encoding), nil)
        @multibyte_buffer.clear
      else
        # invalid
        return
      end
    else # single byte
      return if key.char >= 128 # maybe, first byte of multi byte
      method_symbol = @config.editing_mode.get_method(key.combined_char)
      if key.with_meta and method_symbol == :ed_unassigned
        # split ESC + key
        method_symbol = @config.editing_mode.get_method("\e".ord)
        process_key("\e".ord, method_symbol)
        method_symbol = @config.editing_mode.get_method(key.char)
        process_key(key.char, method_symbol)
      else
        process_key(key.combined_char, method_symbol)
      end
      @multibyte_buffer.clear
    end
    if @config.editing_mode_is?(:vi_command) and @cursor > 0 and @cursor == @cursor_max
      byte_size = Reline::Unicode.get_prev_mbchar_size(@line, @byte_pointer)
      @byte_pointer -= byte_size
      mbchar = @line.byteslice(@byte_pointer, byte_size)
      width = Reline::Unicode.get_mbchar_width(mbchar)
      @cursor -= width
    end
  end

  def input_key(key)
    @just_cursor_moving = nil
    if key.char.nil?
      if @first_char
        @line = nil
      end
      finish
      return
    end
    old_line = @line.dup
    @first_char = false
    completion_occurs = false
    if @config.editing_mode_is?(:emacs, :vi_insert) and key.char == "\C-i".ord
      unless @config.disable_completion
        result = call_completion_proc
        if result.is_a?(Array)
          completion_occurs = true
          process_insert
          complete(result)
        end
      end
    elsif not @config.disable_completion and @config.editing_mode_is?(:vi_insert) and ["\C-p".ord, "\C-n".ord].include?(key.char)
      unless @config.disable_completion
        result = call_completion_proc
        if result.is_a?(Array)
          completion_occurs = true
          process_insert
          move_completed_list(result, "\C-p".ord == key.char ? :up : :down)
        end
      end
    elsif Symbol === key.char and respond_to?(key.char, true)
      process_key(key.char, key.char)
    else
      normal_char(key)
    end
    unless completion_occurs
      @completion_state = CompletionState::NORMAL
    end
    if not @in_pasting and @just_cursor_moving.nil?
      if @previous_line_index and @buffer_of_lines[@previous_line_index] == @line
        @just_cursor_moving = true
      elsif @previous_line_index.nil? and @buffer_of_lines[@line_index] == @line and old_line == @line
        @just_cursor_moving = true
      else
        @just_cursor_moving = false
      end
    else
      @just_cursor_moving = false
    end
    if @is_multiline and @auto_indent_proc and not simplified_rendering?
      process_auto_indent
    end
  end

  def call_completion_proc
    result = retrieve_completion_block(true)
    preposing, target, postposing = result
    if @completion_proc and target
      argnum = @completion_proc.parameters.inject(0) { |result, item|
        case item.first
        when :req, :opt
          result + 1
        when :rest
          break 3
        end
      }
      case argnum
      when 1
        result = @completion_proc.(target)
      when 2
        result = @completion_proc.(target, preposing)
      when 3..Float::INFINITY
        result = @completion_proc.(target, preposing, postposing)
      end
    end
    Reline.core.instance_variable_set(:@completion_quote_character, nil)
    result
  end

  private def process_auto_indent
    return if not @check_new_auto_indent and @previous_line_index # move cursor up or down
    if @check_new_auto_indent and @previous_line_index and @previous_line_index > 0 and @line_index > @previous_line_index
      # Fix indent of a line when a newline is inserted to the next
      new_lines = whole_lines(index: @previous_line_index, line: @line)
      new_indent = @auto_indent_proc.(new_lines[0..-3].push(''), @line_index - 1, 0, true)
      md = @line.match(/\A */)
      prev_indent = md[0].count(' ')
      @line = ' ' * new_indent + @line.lstrip

      new_indent = nil
      result = @auto_indent_proc.(new_lines[0..-2], @line_index - 1, (new_lines[-2].size + 1), false)
      if result
        new_indent = result
      end
      if new_indent&.>= 0
        @line = ' ' * new_indent + @line.lstrip
      end
    end
    if @previous_line_index
      new_lines = whole_lines(index: @previous_line_index, line: @line)
    else
      new_lines = whole_lines
    end
    new_indent = @auto_indent_proc.(new_lines, @line_index, @byte_pointer, @check_new_auto_indent)
    new_indent = @cursor_max if new_indent&.> @cursor_max
    if new_indent&.>= 0
      md = new_lines[@line_index].match(/\A */)
      prev_indent = md[0].count(' ')
      if @check_new_auto_indent
        @buffer_of_lines[@line_index] = ' ' * new_indent + @buffer_of_lines[@line_index].lstrip
        @cursor = new_indent
        @byte_pointer = new_indent
      else
        @line = ' ' * new_indent + @line.lstrip
        @cursor += new_indent - prev_indent
        @byte_pointer += new_indent - prev_indent
      end
    end
    @check_new_auto_indent = false
  end

  def retrieve_completion_block(set_completion_quote_character = false)
    if Reline.completer_word_break_characters.empty?
      word_break_regexp = nil
    else
      word_break_regexp = /\A[#{Regexp.escape(Reline.completer_word_break_characters)}]/
    end
    if Reline.completer_quote_characters.empty?
      quote_characters_regexp = nil
    else
      quote_characters_regexp = /\A[#{Regexp.escape(Reline.completer_quote_characters)}]/
    end
    before = @line.byteslice(0, @byte_pointer)
    rest = nil
    break_pointer = nil
    quote = nil
    closing_quote = nil
    escaped_quote = nil
    i = 0
    while i < @byte_pointer do
      slice = @line.byteslice(i, @byte_pointer - i)
      unless slice.valid_encoding?
        i += 1
        next
      end
      if quote and slice.start_with?(closing_quote)
        quote = nil
        i += 1
        rest = nil
      elsif quote and slice.start_with?(escaped_quote)
        # skip
        i += 2
      elsif quote_characters_regexp and slice =~ quote_characters_regexp # find new "
        rest = $'
        quote = $&
        closing_quote = /(?!\\)#{Regexp.escape(quote)}/
        escaped_quote = /\\#{Regexp.escape(quote)}/
        i += 1
        break_pointer = i - 1
      elsif word_break_regexp and not quote and slice =~ word_break_regexp
        rest = $'
        i += 1
        before = @line.byteslice(i, @byte_pointer - i)
        break_pointer = i
      else
        i += 1
      end
    end
    postposing = @line.byteslice(@byte_pointer, @line.bytesize - @byte_pointer)
    if rest
      preposing = @line.byteslice(0, break_pointer)
      target = rest
      if set_completion_quote_character and quote
        Reline.core.instance_variable_set(:@completion_quote_character, quote)
        if postposing !~ /(?!\\)#{Regexp.escape(quote)}/ # closing quote
          insert_text(quote)
        end
      end
    else
      preposing = ''
      if break_pointer
        preposing = @line.byteslice(0, break_pointer)
      else
        preposing = ''
      end
      target = before
    end
    if @is_multiline
      if @previous_line_index
        lines = whole_lines(index: @previous_line_index, line: @line)
      else
        lines = whole_lines
      end
      if @line_index > 0
        preposing = lines[0..(@line_index - 1)].join("\n") + "\n" + preposing
      end
      if (lines.size - 1) > @line_index
        postposing = postposing + "\n" + lines[(@line_index + 1)..-1].join("\n")
      end
    end
    [preposing.encode(@encoding), target.encode(@encoding), postposing.encode(@encoding)]
  end

  def confirm_multiline_termination
    temp_buffer = @buffer_of_lines.dup
    if @previous_line_index and @line_index == (@buffer_of_lines.size - 1)
      temp_buffer[@previous_line_index] = @line
    else
      temp_buffer[@line_index] = @line
    end
    @confirm_multiline_termination_proc.(temp_buffer.join("\n") + "\n")
  end

  def insert_text(text)
    width = calculate_width(text)
    if @cursor == @cursor_max
      @line += text
    else
      @line = byteinsert(@line, @byte_pointer, text)
    end
    @byte_pointer += text.bytesize
    @cursor += width
    @cursor_max += width
  end

  def delete_text(start = nil, length = nil)
    if start.nil? and length.nil?
      if @is_multiline
        if @buffer_of_lines.size == 1
          @line&.clear
          @byte_pointer = 0
          @cursor = 0
          @cursor_max = 0
        elsif @line_index == (@buffer_of_lines.size - 1) and @line_index > 0
          @buffer_of_lines.pop
          @line_index -= 1
          @line = @buffer_of_lines[@line_index]
          @byte_pointer = 0
          @cursor = 0
          @cursor_max = calculate_width(@line)
        elsif @line_index < (@buffer_of_lines.size - 1)
          @buffer_of_lines.delete_at(@line_index)
          @line = @buffer_of_lines[@line_index]
          @byte_pointer = 0
          @cursor = 0
          @cursor_max = calculate_width(@line)
        end
      else
        @line&.clear
        @byte_pointer = 0
        @cursor = 0
        @cursor_max = 0
      end
    elsif not start.nil? and not length.nil?
      if @line
        before = @line.byteslice(0, start)
        after = @line.byteslice(start + length, @line.bytesize)
        @line = before + after
        @byte_pointer = @line.bytesize if @byte_pointer > @line.bytesize
        str = @line.byteslice(0, @byte_pointer)
        @cursor = calculate_width(str)
        @cursor_max = calculate_width(@line)
      end
    elsif start.is_a?(Range)
      range = start
      first = range.first
      last = range.last
      last = @line.bytesize - 1 if last > @line.bytesize
      last += @line.bytesize if last < 0
      first += @line.bytesize if first < 0
      range = range.exclude_end? ? first...last : first..last
      @line = @line.bytes.reject.with_index{ |c, i| range.include?(i) }.map{ |c| c.chr(Encoding::ASCII_8BIT) }.join.force_encoding(@encoding)
      @byte_pointer = @line.bytesize if @byte_pointer > @line.bytesize
      str = @line.byteslice(0, @byte_pointer)
      @cursor = calculate_width(str)
      @cursor_max = calculate_width(@line)
    else
      @line = @line.byteslice(0, start)
      @byte_pointer = @line.bytesize if @byte_pointer > @line.bytesize
      str = @line.byteslice(0, @byte_pointer)
      @cursor = calculate_width(str)
      @cursor_max = calculate_width(@line)
    end
  end

  def byte_pointer=(val)
    @byte_pointer = val
    str = @line.byteslice(0, @byte_pointer)
    @cursor = calculate_width(str)
    @cursor_max = calculate_width(@line)
  end

  def whole_lines(index: @line_index, line: @line)
    temp_lines = @buffer_of_lines.dup
    temp_lines[index] = line
    temp_lines
  end

  def whole_buffer
    if @buffer_of_lines.size == 1 and @line.nil?
      nil
    else
      if @previous_line_index
        whole_lines(index: @previous_line_index, line: @line).join("\n")
      else
        whole_lines.join("\n")
      end
    end
  end

  def finished?
    @finished
  end

  def finish
    @finished = true
    @rerender_all = true
    @config.reset
  end

  private def byteslice!(str, byte_pointer, size)
    new_str = str.byteslice(0, byte_pointer)
    new_str << str.byteslice(byte_pointer + size, str.bytesize)
    [new_str, str.byteslice(byte_pointer, size)]
  end

  private def byteinsert(str, byte_pointer, other)
    new_str = str.byteslice(0, byte_pointer)
    new_str << other
    new_str << str.byteslice(byte_pointer, str.bytesize)
    new_str
  end

  private def calculate_width(str, allow_escape_code = false)
    Reline::Unicode.calculate_width(str, allow_escape_code)
  end

  private def key_delete(key)
    if @config.editing_mode_is?(:vi_insert, :emacs)
      ed_delete_next_char(key)
    end
  end

  private def key_newline(key)
    if @is_multiline
      if (@buffer_of_lines.size - 1) == @line_index and @line.bytesize == @byte_pointer
        @add_newline_to_end_of_buffer = true
      end
      next_line = @line.byteslice(@byte_pointer, @line.bytesize - @byte_pointer)
      cursor_line = @line.byteslice(0, @byte_pointer)
      insert_new_line(cursor_line, next_line)
      @cursor = 0
      @check_new_auto_indent = true unless @in_pasting
    end
  end

  private def ed_unassigned(key) end # do nothing

  private def process_insert(force: false)
    return if @continuous_insertion_buffer.empty? or (@in_pasting and not force)
    width = Reline::Unicode.calculate_width(@continuous_insertion_buffer)
    bytesize = @continuous_insertion_buffer.bytesize
    if @cursor == @cursor_max
      @line += @continuous_insertion_buffer
    else
      @line = byteinsert(@line, @byte_pointer, @continuous_insertion_buffer)
    end
    @byte_pointer += bytesize
    @cursor += width
    @cursor_max += width
    @continuous_insertion_buffer.clear
  end

  private def ed_insert(key)
    str = nil
    width = nil
    bytesize = nil
    if key.instance_of?(String)
      begin
        key.encode(Encoding::UTF_8)
      rescue Encoding::UndefinedConversionError
        return
      end
      str = key
      bytesize = key.bytesize
    else
      begin
        key.chr.encode(Encoding::UTF_8)
      rescue Encoding::UndefinedConversionError
        return
      end
      str = key.chr
      bytesize = 1
    end
    if @in_pasting
      @continuous_insertion_buffer << str
      return
    elsif not @continuous_insertion_buffer.empty?
      process_insert
    end
    width = Reline::Unicode.get_mbchar_width(str)
    if @cursor == @cursor_max
      @line += str
    else
      @line = byteinsert(@line, @byte_pointer, str)
    end
    last_byte_size = Reline::Unicode.get_prev_mbchar_size(@line, @byte_pointer)
    @byte_pointer += bytesize
    last_mbchar = @line.byteslice((@byte_pointer - bytesize - last_byte_size), last_byte_size)
    if last_byte_size != 0 and (last_mbchar + str).grapheme_clusters.size == 1
      width = 0
    end
    @cursor += width
    @cursor_max += width
  end
  alias_method :ed_digit, :ed_insert
  alias_method :self_insert, :ed_insert

  private def ed_quoted_insert(str, arg: 1)
    @waiting_proc = proc { |key|
      arg.times do
        if key == "\C-j".ord or key == "\C-m".ord
          key_newline(key)
        else
          ed_insert(key)
        end
      end
      @waiting_proc = nil
    }
  end
  alias_method :quoted_insert, :ed_quoted_insert

  private def ed_next_char(key, arg: 1)
    byte_size = Reline::Unicode.get_next_mbchar_size(@line, @byte_pointer)
    if (@byte_pointer < @line.bytesize)
      mbchar = @line.byteslice(@byte_pointer, byte_size)
      width = Reline::Unicode.get_mbchar_width(mbchar)
      @cursor += width if width
      @byte_pointer += byte_size
    elsif @is_multiline and @config.editing_mode_is?(:emacs) and @byte_pointer == @line.bytesize and @line_index < @buffer_of_lines.size - 1
      next_line = @buffer_of_lines[@line_index + 1]
      @cursor = 0
      @byte_pointer = 0
      @cursor_max = calculate_width(next_line)
      @previous_line_index = @line_index
      @line_index += 1
    end
    arg -= 1
    ed_next_char(key, arg: arg) if arg > 0
  end
  alias_method :forward_char, :ed_next_char

  private def ed_prev_char(key, arg: 1)
    if @cursor > 0
      byte_size = Reline::Unicode.get_prev_mbchar_size(@line, @byte_pointer)
      @byte_pointer -= byte_size
      mbchar = @line.byteslice(@byte_pointer, byte_size)
      width = Reline::Unicode.get_mbchar_width(mbchar)
      @cursor -= width
    elsif @is_multiline and @config.editing_mode_is?(:emacs) and @byte_pointer == 0 and @line_index > 0
      prev_line = @buffer_of_lines[@line_index - 1]
      @cursor = calculate_width(prev_line)
      @byte_pointer = prev_line.bytesize
      @cursor_max = calculate_width(prev_line)
      @previous_line_index = @line_index
      @line_index -= 1
    end
    arg -= 1
    ed_prev_char(key, arg: arg) if arg > 0
  end
  alias_method :backward_char, :ed_prev_char

  private def vi_first_print(key)
    @byte_pointer, @cursor = Reline::Unicode.vi_first_print(@line)
  end

  private def ed_move_to_beg(key)
    @byte_pointer = @cursor = 0
  end
  alias_method :beginning_of_line, :ed_move_to_beg

  private def ed_move_to_end(key)
    @byte_pointer = 0
    @cursor = 0
    byte_size = 0
    while @byte_pointer < @line.bytesize
      byte_size = Reline::Unicode.get_next_mbchar_size(@line, @byte_pointer)
      if byte_size > 0
        mbchar = @line.byteslice(@byte_pointer, byte_size)
        @cursor += Reline::Unicode.get_mbchar_width(mbchar)
      end
      @byte_pointer += byte_size
    end
  end
  alias_method :end_of_line, :ed_move_to_end

  private def generate_searcher
    Fiber.new do |first_key|
      prev_search_key = first_key
      search_word = String.new(encoding: @encoding)
      multibyte_buf = String.new(encoding: 'ASCII-8BIT')
      last_hit = nil
      case first_key
      when "\C-r".ord
        prompt_name = 'reverse-i-search'
      when "\C-s".ord
        prompt_name = 'i-search'
      end
      loop do
        key = Fiber.yield(search_word)
        search_again = false
        case key
        when -1 # determined
          Reline.last_incremental_search = search_word
          break
        when "\C-h".ord, "\C-?".ord
          grapheme_clusters = search_word.grapheme_clusters
          if grapheme_clusters.size > 0
            grapheme_clusters.pop
            search_word = grapheme_clusters.join
          end
        when "\C-r".ord, "\C-s".ord
          search_again = true if prev_search_key == key
          prev_search_key = key
        else
          multibyte_buf << key
          if multibyte_buf.dup.force_encoding(@encoding).valid_encoding?
            search_word << multibyte_buf.dup.force_encoding(@encoding)
            multibyte_buf.clear
          end
        end
        hit = nil
        if not search_word.empty? and @line_backup_in_history&.include?(search_word)
          @history_pointer = nil
          hit = @line_backup_in_history
        else
          if search_again
            if search_word.empty? and Reline.last_incremental_search
              search_word = Reline.last_incremental_search
            end
            if @history_pointer
              case prev_search_key
              when "\C-r".ord
                history_pointer_base = 0
                history = Reline::HISTORY[0..(@history_pointer - 1)]
              when "\C-s".ord
                history_pointer_base = @history_pointer + 1
                history = Reline::HISTORY[(@history_pointer + 1)..-1]
              end
            else
              history_pointer_base = 0
              history = Reline::HISTORY
            end
          elsif @history_pointer
            case prev_search_key
            when "\C-r".ord
              history_pointer_base = 0
              history = Reline::HISTORY[0..@history_pointer]
            when "\C-s".ord
              history_pointer_base = @history_pointer
              history = Reline::HISTORY[@history_pointer..-1]
            end
          else
            history_pointer_base = 0
            history = Reline::HISTORY
          end
          case prev_search_key
          when "\C-r".ord
            hit_index = history.rindex { |item|
              item.include?(search_word)
            }
          when "\C-s".ord
            hit_index = history.index { |item|
              item.include?(search_word)
            }
          end
          if hit_index
            @history_pointer = history_pointer_base + hit_index
            hit = Reline::HISTORY[@history_pointer]
          end
        end
        case prev_search_key
        when "\C-r".ord
          prompt_name = 'reverse-i-search'
        when "\C-s".ord
          prompt_name = 'i-search'
        end
        if hit
          if @is_multiline
            @buffer_of_lines = hit.split("\n")
            @buffer_of_lines = [String.new(encoding: @encoding)] if @buffer_of_lines.empty?
            @line_index = @buffer_of_lines.size - 1
            @line = @buffer_of_lines.last
            @rerender_all = true
            @searching_prompt = "(%s)`%s'" % [prompt_name, search_word]
          else
            @line = hit
            @searching_prompt = "(%s)`%s': %s" % [prompt_name, search_word, hit]
          end
          last_hit = hit
        else
          if @is_multiline
            @rerender_all = true
            @searching_prompt = "(failed %s)`%s'" % [prompt_name, search_word]
          else
            @searching_prompt = "(failed %s)`%s': %s" % [prompt_name, search_word, last_hit]
          end
        end
      end
    end
  end

  private def incremental_search_history(key)
    unless @history_pointer
      if @is_multiline
        @line_backup_in_history = whole_buffer
      else
        @line_backup_in_history = @line
      end
    end
    searcher = generate_searcher
    searcher.resume(key)
    @searching_prompt = "(reverse-i-search)`': "
    termination_keys = ["\C-j".ord]
    termination_keys.concat(@config.isearch_terminators&.chars&.map(&:ord)) if @config.isearch_terminators
    @waiting_proc = ->(k) {
      case k
      when *termination_keys
        if @history_pointer
          buffer = Reline::HISTORY[@history_pointer]
        else
          buffer = @line_backup_in_history
        end
        if @is_multiline
          @buffer_of_lines = buffer.split("\n")
          @buffer_of_lines = [String.new(encoding: @encoding)] if @buffer_of_lines.empty?
          @line_index = @buffer_of_lines.size - 1
          @line = @buffer_of_lines.last
          @rerender_all = true
        else
          @line = buffer
        end
        @searching_prompt = nil
        @waiting_proc = nil
        @cursor_max = calculate_width(@line)
        @cursor = @byte_pointer = 0
        @rerender_all = true
        @cached_prompt_list = nil
        searcher.resume(-1)
      when "\C-g".ord
        if @is_multiline
          @buffer_of_lines = @line_backup_in_history.split("\n")
          @buffer_of_lines = [String.new(encoding: @encoding)] if @buffer_of_lines.empty?
          @line_index = @buffer_of_lines.size - 1
          @line = @buffer_of_lines.last
          @rerender_all = true
        else
          @line = @line_backup_in_history
        end
        @history_pointer = nil
        @searching_prompt = nil
        @waiting_proc = nil
        @line_backup_in_history = nil
        @cursor_max = calculate_width(@line)
        @cursor = @byte_pointer = 0
        @rerender_all = true
      else
        chr = k.is_a?(String) ? k : k.chr(Encoding::ASCII_8BIT)
        if chr.match?(/[[:print:]]/) or k == "\C-h".ord or k == "\C-?".ord or k == "\C-r".ord or k == "\C-s".ord
          searcher.resume(k)
        else
          if @history_pointer
            line = Reline::HISTORY[@history_pointer]
          else
            line = @line_backup_in_history
          end
          if @is_multiline
            @line_backup_in_history = whole_buffer
            @buffer_of_lines = line.split("\n")
            @buffer_of_lines = [String.new(encoding: @encoding)] if @buffer_of_lines.empty?
            @line_index = @buffer_of_lines.size - 1
            @line = @buffer_of_lines.last
            @rerender_all = true
          else
            @line_backup_in_history = @line
            @line = line
          end
          @searching_prompt = nil
          @waiting_proc = nil
          @cursor_max = calculate_width(@line)
          @cursor = @byte_pointer = 0
          @rerender_all = true
          @cached_prompt_list = nil
          searcher.resume(-1)
        end
      end
    }
  end

  private def vi_search_prev(key)
    incremental_search_history(key)
  end
  alias_method :reverse_search_history, :vi_search_prev

  private def vi_search_next(key)
    incremental_search_history(key)
  end
  alias_method :forward_search_history, :vi_search_next

  private def ed_search_prev_history(key, arg: 1)
    history = nil
    h_pointer = nil
    line_no = nil
    substr = @line.slice(0, @byte_pointer)
    if @history_pointer.nil?
      return if not @line.empty? and substr.empty?
      history = Reline::HISTORY
    elsif @history_pointer.zero?
      history = nil
      h_pointer = nil
    else
      history = Reline::HISTORY.slice(0, @history_pointer)
    end
    return if history.nil?
    if @is_multiline
      h_pointer = history.rindex { |h|
        h.split("\n").each_with_index { |l, i|
          if l.start_with?(substr)
            line_no = i
            break
          end
        }
        not line_no.nil?
      }
    else
      h_pointer = history.rindex { |l|
        l.start_with?(substr)
      }
    end
    return if h_pointer.nil?
    @history_pointer = h_pointer
    if @is_multiline
      @buffer_of_lines = Reline::HISTORY[@history_pointer].split("\n")
      @buffer_of_lines = [String.new(encoding: @encoding)] if @buffer_of_lines.empty?
      @line_index = line_no
      @line = @buffer_of_lines[@line_index]
      @rerender_all = true
    else
      @line = Reline::HISTORY[@history_pointer]
    end
    @cursor_max = calculate_width(@line)
    arg -= 1
    ed_search_prev_history(key, arg: arg) if arg > 0
  end
  alias_method :history_search_backward, :ed_search_prev_history

  private def ed_search_next_history(key, arg: 1)
    substr = @line.slice(0, @byte_pointer)
    if @history_pointer.nil?
      return
    elsif @history_pointer == (Reline::HISTORY.size - 1) and not substr.empty?
      return
    end
    history = Reline::HISTORY.slice((@history_pointer + 1)..-1)
    h_pointer = nil
    line_no = nil
    if @is_multiline
      h_pointer = history.index { |h|
        h.split("\n").each_with_index { |l, i|
          if l.start_with?(substr)
            line_no = i
            break
          end
        }
        not line_no.nil?
      }
    else
      h_pointer = history.index { |l|
        l.start_with?(substr)
      }
    end
    h_pointer += @history_pointer + 1 if h_pointer and @history_pointer
    return if h_pointer.nil? and not substr.empty?
    @history_pointer = h_pointer
    if @is_multiline
      if @history_pointer.nil? and substr.empty?
        @buffer_of_lines = []
        @line_index = 0
      else
        @buffer_of_lines = Reline::HISTORY[@history_pointer].split("\n")
        @line_index = line_no
      end
      @buffer_of_lines = [String.new(encoding: @encoding)] if @buffer_of_lines.empty?
      @line = @buffer_of_lines[@line_index]
      @rerender_all = true
    else
      if @history_pointer.nil? and substr.empty?
        @line = ''
      else
        @line = Reline::HISTORY[@history_pointer]
      end
    end
    @cursor_max = calculate_width(@line)
    arg -= 1
    ed_search_next_history(key, arg: arg) if arg > 0
  end
  alias_method :history_search_forward, :ed_search_next_history

  private def ed_prev_history(key, arg: 1)
    if @is_multiline and @line_index > 0
      @previous_line_index = @line_index
      @line_index -= 1
      return
    end
    if Reline::HISTORY.empty?
      return
    end
    if @history_pointer.nil?
      @history_pointer = Reline::HISTORY.size - 1
      if @is_multiline
        @line_backup_in_history = whole_buffer
        @buffer_of_lines = Reline::HISTORY[@history_pointer].split("\n")
        @buffer_of_lines = [String.new(encoding: @encoding)] if @buffer_of_lines.empty?
        @line_index = @buffer_of_lines.size - 1
        @line = @buffer_of_lines.last
        @rerender_all = true
      else
        @line_backup_in_history = @line
        @line = Reline::HISTORY[@history_pointer]
      end
    elsif @history_pointer.zero?
      return
    else
      if @is_multiline
        Reline::HISTORY[@history_pointer] = whole_buffer
        @history_pointer -= 1
        @buffer_of_lines = Reline::HISTORY[@history_pointer].split("\n")
        @buffer_of_lines = [String.new(encoding: @encoding)] if @buffer_of_lines.empty?
        @line_index = @buffer_of_lines.size - 1
        @line = @buffer_of_lines.last
        @rerender_all = true
      else
        Reline::HISTORY[@history_pointer] = @line
        @history_pointer -= 1
        @line = Reline::HISTORY[@history_pointer]
      end
    end
    if @config.editing_mode_is?(:emacs, :vi_insert)
      @cursor_max = @cursor = calculate_width(@line)
      @byte_pointer = @line.bytesize
    elsif @config.editing_mode_is?(:vi_command)
      @byte_pointer = @cursor = 0
      @cursor_max = calculate_width(@line)
    end
    arg -= 1
    ed_prev_history(key, arg: arg) if arg > 0
  end

  private def ed_next_history(key, arg: 1)
    if @is_multiline and @line_index < (@buffer_of_lines.size - 1)
      @previous_line_index = @line_index
      @line_index += 1
      return
    end
    if @history_pointer.nil?
      return
    elsif @history_pointer == (Reline::HISTORY.size - 1)
      if @is_multiline
        @history_pointer = nil
        @buffer_of_lines = @line_backup_in_history.split("\n")
        @buffer_of_lines = [String.new(encoding: @encoding)] if @buffer_of_lines.empty?
        @line_index = 0
        @line = @buffer_of_lines.first
        @rerender_all = true
      else
        @history_pointer = nil
        @line = @line_backup_in_history
      end
    else
      if @is_multiline
        Reline::HISTORY[@history_pointer] = whole_buffer
        @history_pointer += 1
        @buffer_of_lines = Reline::HISTORY[@history_pointer].split("\n")
        @buffer_of_lines = [String.new(encoding: @encoding)] if @buffer_of_lines.empty?
        @line_index = 0
        @line = @buffer_of_lines.first
        @rerender_all = true
      else
        Reline::HISTORY[@history_pointer] = @line
        @history_pointer += 1
        @line = Reline::HISTORY[@history_pointer]
      end
    end
    @line = '' unless @line
    if @config.editing_mode_is?(:emacs, :vi_insert)
      @cursor_max = @cursor = calculate_width(@line)
      @byte_pointer = @line.bytesize
    elsif @config.editing_mode_is?(:vi_command)
      @byte_pointer = @cursor = 0
      @cursor_max = calculate_width(@line)
    end
    arg -= 1
    ed_next_history(key, arg: arg) if arg > 0
  end

  private def ed_newline(key)
    process_insert(force: true)
    if @is_multiline
      if @config.editing_mode_is?(:vi_command)
        if @line_index < (@buffer_of_lines.size - 1)
          ed_next_history(key) # means cursor down
        else
          # should check confirm_multiline_termination to finish?
          finish
        end
      else
        if @line_index == (@buffer_of_lines.size - 1)
          if confirm_multiline_termination
            finish
          else
            key_newline(key)
          end
        else
          # should check confirm_multiline_termination to finish?
          @previous_line_index = @line_index
          @line_index = @buffer_of_lines.size - 1
          finish
        end
      end
    else
      if @history_pointer
        Reline::HISTORY[@history_pointer] = @line
        @history_pointer = nil
      end
      finish
    end
  end

  private def em_delete_prev_char(key)
    if @is_multiline and @cursor == 0 and @line_index > 0
      @buffer_of_lines[@line_index] = @line
      @cursor = calculate_width(@buffer_of_lines[@line_index - 1])
      @byte_pointer = @buffer_of_lines[@line_index - 1].bytesize
      @buffer_of_lines[@line_index - 1] += @buffer_of_lines.delete_at(@line_index)
      @line_index -= 1
      @line = @buffer_of_lines[@line_index]
      @cursor_max = calculate_width(@line)
      @rerender_all = true
    elsif @cursor > 0
      byte_size = Reline::Unicode.get_prev_mbchar_size(@line, @byte_pointer)
      @byte_pointer -= byte_size
      @line, mbchar = byteslice!(@line, @byte_pointer, byte_size)
      width = Reline::Unicode.get_mbchar_width(mbchar)
      @cursor -= width
      @cursor_max -= width
    end
  end
  alias_method :backward_delete_char, :em_delete_prev_char

  private def ed_kill_line(key)
    if @line.bytesize > @byte_pointer
      @line, deleted = byteslice!(@line, @byte_pointer, @line.bytesize - @byte_pointer)
      @byte_pointer = @line.bytesize
      @cursor = @cursor_max = calculate_width(@line)
      @kill_ring.append(deleted)
    elsif @is_multiline and @byte_pointer == @line.bytesize and @buffer_of_lines.size > @line_index + 1
      @cursor = calculate_width(@line)
      @byte_pointer = @line.bytesize
      @line += @buffer_of_lines.delete_at(@line_index + 1)
      @cursor_max = calculate_width(@line)
      @buffer_of_lines[@line_index] = @line
      @rerender_all = true
      @rest_height += 1
    end
  end

  private def em_kill_line(key)
    if @byte_pointer > 0
      @line, deleted = byteslice!(@line, 0, @byte_pointer)
      @byte_pointer = 0
      @kill_ring.append(deleted, true)
      @cursor_max = calculate_width(@line)
      @cursor = 0
    end
  end
  alias_method :kill_line, :em_kill_line

  private def em_delete(key)
    if (not @is_multiline and @line.empty?) or (@is_multiline and @line.empty? and @buffer_of_lines.size == 1)
      @line = nil
      if @buffer_of_lines.size > 1
        scroll_down(@highest_in_all - @first_line_started_from)
      end
      Reline::IOGate.move_cursor_column(0)
      @eof = true
      finish
    elsif @byte_pointer < @line.bytesize
      splitted_last = @line.byteslice(@byte_pointer, @line.bytesize)
      mbchar = splitted_last.grapheme_clusters.first
      width = Reline::Unicode.get_mbchar_width(mbchar)
      @cursor_max -= width
      @line, = byteslice!(@line, @byte_pointer, mbchar.bytesize)
    elsif @is_multiline and @byte_pointer == @line.bytesize and @buffer_of_lines.size > @line_index + 1
      @cursor = calculate_width(@line)
      @byte_pointer = @line.bytesize
      @line += @buffer_of_lines.delete_at(@line_index + 1)
      @cursor_max = calculate_width(@line)
      @buffer_of_lines[@line_index] = @line
      @rerender_all = true
      @rest_height += 1
    end
  end
  alias_method :delete_char, :em_delete

  private def em_delete_or_list(key)
    if @line.empty? or @byte_pointer < @line.bytesize
      em_delete(key)
    else # show completed list
      result = call_completion_proc
      if result.is_a?(Array)
        complete(result, true)
      end
    end
  end
  alias_method :delete_char_or_list, :em_delete_or_list

  private def em_yank(key)
    yanked = @kill_ring.yank
    if yanked
      @line = byteinsert(@line, @byte_pointer, yanked)
      yanked_width = calculate_width(yanked)
      @cursor += yanked_width
      @cursor_max += yanked_width
      @byte_pointer += yanked.bytesize
    end
  end
  alias_method :yank, :em_yank

  private def em_yank_pop(key)
    yanked, prev_yank = @kill_ring.yank_pop
    if yanked
      prev_yank_width = calculate_width(prev_yank)
      @cursor -= prev_yank_width
      @cursor_max -= prev_yank_width
      @byte_pointer -= prev_yank.bytesize
      @line, = byteslice!(@line, @byte_pointer, prev_yank.bytesize)
      @line = byteinsert(@line, @byte_pointer, yanked)
      yanked_width = calculate_width(yanked)
      @cursor += yanked_width
      @cursor_max += yanked_width
      @byte_pointer += yanked.bytesize
    end
  end
  alias_method :yank_pop, :em_yank_pop

  private def ed_clear_screen(key)
    @cleared = true
  end
  alias_method :clear_screen, :ed_clear_screen

  private def em_next_word(key)
    if @line.bytesize > @byte_pointer
      byte_size, width = Reline::Unicode.em_forward_word(@line, @byte_pointer)
      @byte_pointer += byte_size
      @cursor += width
    end
  end
  alias_method :forward_word, :em_next_word

  private def ed_prev_word(key)
    if @byte_pointer > 0
      byte_size, width = Reline::Unicode.em_backward_word(@line, @byte_pointer)
      @byte_pointer -= byte_size
      @cursor -= width
    end
  end
  alias_method :backward_word, :ed_prev_word

  private def em_delete_next_word(key)
    if @line.bytesize > @byte_pointer
      byte_size, width = Reline::Unicode.em_forward_word(@line, @byte_pointer)
      @line, word = byteslice!(@line, @byte_pointer, byte_size)
      @kill_ring.append(word)
      @cursor_max -= width
    end
  end

  private def ed_delete_prev_word(key)
    if @byte_pointer > 0
      byte_size, width = Reline::Unicode.em_backward_word(@line, @byte_pointer)
      @line, word = byteslice!(@line, @byte_pointer - byte_size, byte_size)
      @kill_ring.append(word, true)
      @byte_pointer -= byte_size
      @cursor -= width
      @cursor_max -= width
    end
  end

  private def ed_transpose_chars(key)
    if @byte_pointer > 0
      if @cursor_max > @cursor
        byte_size = Reline::Unicode.get_next_mbchar_size(@line, @byte_pointer)
        mbchar = @line.byteslice(@byte_pointer, byte_size)
        width = Reline::Unicode.get_mbchar_width(mbchar)
        @cursor += width
        @byte_pointer += byte_size
      end
      back1_byte_size = Reline::Unicode.get_prev_mbchar_size(@line, @byte_pointer)
      if (@byte_pointer - back1_byte_size) > 0
        back2_byte_size = Reline::Unicode.get_prev_mbchar_size(@line, @byte_pointer - back1_byte_size)
        back2_pointer = @byte_pointer - back1_byte_size - back2_byte_size
        @line, back2_mbchar = byteslice!(@line, back2_pointer, back2_byte_size)
        @line = byteinsert(@line, @byte_pointer - back2_byte_size, back2_mbchar)
      end
    end
  end
  alias_method :transpose_chars, :ed_transpose_chars

  private def ed_transpose_words(key)
    left_word_start, middle_start, right_word_start, after_start = Reline::Unicode.ed_transpose_words(@line, @byte_pointer)
    before = @line.byteslice(0, left_word_start)
    left_word = @line.byteslice(left_word_start, middle_start - left_word_start)
    middle = @line.byteslice(middle_start, right_word_start - middle_start)
    right_word = @line.byteslice(right_word_start, after_start - right_word_start)
    after = @line.byteslice(after_start, @line.bytesize - after_start)
    return if left_word.empty? or right_word.empty?
    @line = before + right_word + middle + left_word + after
    from_head_to_left_word = before + right_word + middle + left_word
    @byte_pointer = from_head_to_left_word.bytesize
    @cursor = calculate_width(from_head_to_left_word)
  end
  alias_method :transpose_words, :ed_transpose_words

  private def em_capitol_case(key)
    if @line.bytesize > @byte_pointer
      byte_size, _, new_str = Reline::Unicode.em_forward_word_with_capitalization(@line, @byte_pointer)
      before = @line.byteslice(0, @byte_pointer)
      after = @line.byteslice((@byte_pointer + byte_size)..-1)
      @line = before + new_str + after
      @byte_pointer += new_str.bytesize
      @cursor += calculate_width(new_str)
    end
  end
  alias_method :capitalize_word, :em_capitol_case

  private def em_lower_case(key)
    if @line.bytesize > @byte_pointer
      byte_size, = Reline::Unicode.em_forward_word(@line, @byte_pointer)
      part = @line.byteslice(@byte_pointer, byte_size).grapheme_clusters.map { |mbchar|
        mbchar =~ /[A-Z]/ ? mbchar.downcase : mbchar
      }.join
      rest = @line.byteslice((@byte_pointer + byte_size)..-1)
      @line = @line.byteslice(0, @byte_pointer) + part
      @byte_pointer = @line.bytesize
      @cursor = calculate_width(@line)
      @cursor_max = @cursor + calculate_width(rest)
      @line += rest
    end
  end
  alias_method :downcase_word, :em_lower_case

  private def em_upper_case(key)
    if @line.bytesize > @byte_pointer
      byte_size, = Reline::Unicode.em_forward_word(@line, @byte_pointer)
      part = @line.byteslice(@byte_pointer, byte_size).grapheme_clusters.map { |mbchar|
        mbchar =~ /[a-z]/ ? mbchar.upcase : mbchar
      }.join
      rest = @line.byteslice((@byte_pointer + byte_size)..-1)
      @line = @line.byteslice(0, @byte_pointer) + part
      @byte_pointer = @line.bytesize
      @cursor = calculate_width(@line)
      @cursor_max = @cursor + calculate_width(rest)
      @line += rest
    end
  end
  alias_method :upcase_word, :em_upper_case

  private def em_kill_region(key)
    if @byte_pointer > 0
      byte_size, width = Reline::Unicode.em_big_backward_word(@line, @byte_pointer)
      @line, deleted = byteslice!(@line, @byte_pointer - byte_size, byte_size)
      @byte_pointer -= byte_size
      @cursor -= width
      @cursor_max -= width
      @kill_ring.append(deleted, true)
    end
  end
  alias_method :unix_word_rubout, :em_kill_region

  private def copy_for_vi(text)
    if @config.editing_mode_is?(:vi_insert) or @config.editing_mode_is?(:vi_command)
      @vi_clipboard = text
    end
  end

  private def vi_insert(key)
    @config.editing_mode = :vi_insert
  end

  private def vi_add(key)
    @config.editing_mode = :vi_insert
    ed_next_char(key)
  end

  private def vi_command_mode(key)
    ed_prev_char(key)
    @config.editing_mode = :vi_command
  end
  alias_method :vi_movement_mode, :vi_command_mode

  private def vi_next_word(key, arg: 1)
    if @line.bytesize > @byte_pointer
      byte_size, width = Reline::Unicode.vi_forward_word(@line, @byte_pointer, @drop_terminate_spaces)
      @byte_pointer += byte_size
      @cursor += width
    end
    arg -= 1
    vi_next_word(key, arg: arg) if arg > 0
  end

  private def vi_prev_word(key, arg: 1)
    if @byte_pointer > 0
      byte_size, width = Reline::Unicode.vi_backward_word(@line, @byte_pointer)
      @byte_pointer -= byte_size
      @cursor -= width
    end
    arg -= 1
    vi_prev_word(key, arg: arg) if arg > 0
  end

  private def vi_end_word(key, arg: 1, inclusive: false)
    if @line.bytesize > @byte_pointer
      byte_size, width = Reline::Unicode.vi_forward_end_word(@line, @byte_pointer)
      @byte_pointer += byte_size
      @cursor += width
    end
    arg -= 1
    if inclusive and arg.zero?
      byte_size = Reline::Unicode.get_next_mbchar_size(@line, @byte_pointer)
      if byte_size > 0
        c = @line.byteslice(@byte_pointer, byte_size)
        width = Reline::Unicode.get_mbchar_width(c)
        @byte_pointer += byte_size
        @cursor += width
      end
    end
    vi_end_word(key, arg: arg) if arg > 0
  end

  private def vi_next_big_word(key, arg: 1)
    if @line.bytesize > @byte_pointer
      byte_size, width = Reline::Unicode.vi_big_forward_word(@line, @byte_pointer)
      @byte_pointer += byte_size
      @cursor += width
    end
    arg -= 1
    vi_next_big_word(key, arg: arg) if arg > 0
  end

  private def vi_prev_big_word(key, arg: 1)
    if @byte_pointer > 0
      byte_size, width = Reline::Unicode.vi_big_backward_word(@line, @byte_pointer)
      @byte_pointer -= byte_size
      @cursor -= width
    end
    arg -= 1
    vi_prev_big_word(key, arg: arg) if arg > 0
  end

  private def vi_end_big_word(key, arg: 1, inclusive: false)
    if @line.bytesize > @byte_pointer
      byte_size, width = Reline::Unicode.vi_big_forward_end_word(@line, @byte_pointer)
      @byte_pointer += byte_size
      @cursor += width
    end
    arg -= 1
    if inclusive and arg.zero?
      byte_size = Reline::Unicode.get_next_mbchar_size(@line, @byte_pointer)
      if byte_size > 0
        c = @line.byteslice(@byte_pointer, byte_size)
        width = Reline::Unicode.get_mbchar_width(c)
        @byte_pointer += byte_size
        @cursor += width
      end
    end
    vi_end_big_word(key, arg: arg) if arg > 0
  end

  private def vi_delete_prev_char(key)
    if @is_multiline and @cursor == 0 and @line_index > 0
      @buffer_of_lines[@line_index] = @line
      @cursor = calculate_width(@buffer_of_lines[@line_index - 1])
      @byte_pointer = @buffer_of_lines[@line_index - 1].bytesize
      @buffer_of_lines[@line_index - 1] += @buffer_of_lines.delete_at(@line_index)
      @line_index -= 1
      @line = @buffer_of_lines[@line_index]
      @cursor_max = calculate_width(@line)
      @rerender_all = true
    elsif @cursor > 0
      byte_size = Reline::Unicode.get_prev_mbchar_size(@line, @byte_pointer)
      @byte_pointer -= byte_size
      @line, mbchar = byteslice!(@line, @byte_pointer, byte_size)
      width = Reline::Unicode.get_mbchar_width(mbchar)
      @cursor -= width
      @cursor_max -= width
    end
  end

  private def vi_insert_at_bol(key)
    ed_move_to_beg(key)
    @config.editing_mode = :vi_insert
  end

  private def vi_add_at_eol(key)
    ed_move_to_end(key)
    @config.editing_mode = :vi_insert
  end

  private def ed_delete_prev_char(key, arg: 1)
    deleted = ''
    arg.times do
      if @cursor > 0
        byte_size = Reline::Unicode.get_prev_mbchar_size(@line, @byte_pointer)
        @byte_pointer -= byte_size
        @line, mbchar = byteslice!(@line, @byte_pointer, byte_size)
        deleted.prepend(mbchar)
        width = Reline::Unicode.get_mbchar_width(mbchar)
        @cursor -= width
        @cursor_max -= width
      end
    end
    copy_for_vi(deleted)
  end

  private def vi_zero(key)
    @byte_pointer = 0
    @cursor = 0
  end

  private def vi_change_meta(key, arg: 1)
    @drop_terminate_spaces = true
    @waiting_operator_proc = proc { |cursor_diff, byte_pointer_diff|
      if byte_pointer_diff > 0
        @line, cut = byteslice!(@line, @byte_pointer, byte_pointer_diff)
      elsif byte_pointer_diff < 0
        @line, cut = byteslice!(@line, @byte_pointer + byte_pointer_diff, -byte_pointer_diff)
      end
      copy_for_vi(cut)
      @cursor += cursor_diff if cursor_diff < 0
      @cursor_max -= cursor_diff.abs
      @byte_pointer += byte_pointer_diff if byte_pointer_diff < 0
      @config.editing_mode = :vi_insert
      @drop_terminate_spaces = false
    }
    @waiting_operator_vi_arg = arg
  end

  private def vi_delete_meta(key, arg: 1)
    @waiting_operator_proc = proc { |cursor_diff, byte_pointer_diff|
      if byte_pointer_diff > 0
        @line, cut = byteslice!(@line, @byte_pointer, byte_pointer_diff)
      elsif byte_pointer_diff < 0
        @line, cut = byteslice!(@line, @byte_pointer + byte_pointer_diff, -byte_pointer_diff)
      end
      copy_for_vi(cut)
      @cursor += cursor_diff if cursor_diff < 0
      @cursor_max -= cursor_diff.abs
      @byte_pointer += byte_pointer_diff if byte_pointer_diff < 0
    }
    @waiting_operator_vi_arg = arg
  end

  private def vi_yank(key, arg: 1)
    @waiting_operator_proc = proc { |cursor_diff, byte_pointer_diff|
      if byte_pointer_diff > 0
        cut = @line.byteslice(@byte_pointer, byte_pointer_diff)
      elsif byte_pointer_diff < 0
        cut = @line.byteslice(@byte_pointer + byte_pointer_diff, -byte_pointer_diff)
      end
      copy_for_vi(cut)
    }
    @waiting_operator_vi_arg = arg
  end

  private def vi_list_or_eof(key)
    if (not @is_multiline and @line.empty?) or (@is_multiline and @line.empty? and @buffer_of_lines.size == 1)
      @line = nil
      if @buffer_of_lines.size > 1
        scroll_down(@highest_in_all - @first_line_started_from)
      end
      Reline::IOGate.move_cursor_column(0)
      @eof = true
      finish
    else
      ed_newline(key)
    end
  end
  alias_method :vi_end_of_transmission, :vi_list_or_eof
  alias_method :vi_eof_maybe, :vi_list_or_eof

  private def ed_delete_next_char(key, arg: 1)
    byte_size = Reline::Unicode.get_next_mbchar_size(@line, @byte_pointer)
    unless @line.empty? || byte_size == 0
      @line, mbchar = byteslice!(@line, @byte_pointer, byte_size)
      copy_for_vi(mbchar)
      width = Reline::Unicode.get_mbchar_width(mbchar)
      @cursor_max -= width
      if @cursor > 0 and @cursor >= @cursor_max
        byte_size = Reline::Unicode.get_prev_mbchar_size(@line, @byte_pointer)
        mbchar = @line.byteslice(@byte_pointer - byte_size, byte_size)
        width = Reline::Unicode.get_mbchar_width(mbchar)
        @byte_pointer -= byte_size
        @cursor -= width
      end
    end
    arg -= 1
    ed_delete_next_char(key, arg: arg) if arg > 0
  end

  private def vi_to_history_line(key)
    if Reline::HISTORY.empty?
      return
    end
    if @history_pointer.nil?
      @history_pointer = 0
      @line_backup_in_history = @line
      @line = Reline::HISTORY[@history_pointer]
      @cursor_max = calculate_width(@line)
      @cursor = 0
      @byte_pointer = 0
    elsif @history_pointer.zero?
      return
    else
      Reline::HISTORY[@history_pointer] = @line
      @history_pointer = 0
      @line = Reline::HISTORY[@history_pointer]
      @cursor_max = calculate_width(@line)
      @cursor = 0
      @byte_pointer = 0
    end
  end

  private def vi_histedit(key)
    path = Tempfile.open { |fp|
      if @is_multiline
        fp.write whole_lines.join("\n")
      else
        fp.write @line
      end
      fp.path
    }
    system("#{ENV['EDITOR']} #{path}")
    if @is_multiline
      @buffer_of_lines = File.read(path).split("\n")
      @buffer_of_lines = [String.new(encoding: @encoding)] if @buffer_of_lines.empty?
      @line_index = 0
      @line = @buffer_of_lines[@line_index]
      @rerender_all = true
    else
      @line = File.read(path)
    end
    finish
  end

  private def vi_paste_prev(key, arg: 1)
    if @vi_clipboard.size > 0
      @line = byteinsert(@line, @byte_pointer, @vi_clipboard)
      @cursor_max += calculate_width(@vi_clipboard)
      cursor_point = @vi_clipboard.grapheme_clusters[0..-2].join
      @cursor += calculate_width(cursor_point)
      @byte_pointer += cursor_point.bytesize
    end
    arg -= 1
    vi_paste_prev(key, arg: arg) if arg > 0
  end

  private def vi_paste_next(key, arg: 1)
    if @vi_clipboard.size > 0
      byte_size = Reline::Unicode.get_next_mbchar_size(@line, @byte_pointer)
      @line = byteinsert(@line, @byte_pointer + byte_size, @vi_clipboard)
      @cursor_max += calculate_width(@vi_clipboard)
      @cursor += calculate_width(@vi_clipboard)
      @byte_pointer += @vi_clipboard.bytesize
    end
    arg -= 1
    vi_paste_next(key, arg: arg) if arg > 0
  end

  private def ed_argument_digit(key)
    if @vi_arg.nil?
      unless key.chr.to_i.zero?
        @vi_arg = key.chr.to_i
      end
    else
      @vi_arg = @vi_arg * 10 + key.chr.to_i
    end
  end

  private def vi_to_column(key, arg: 0)
    @byte_pointer, @cursor = @line.grapheme_clusters.inject([0, 0]) { |total, gc|
      # total has [byte_size, cursor]
      mbchar_width = Reline::Unicode.get_mbchar_width(gc)
      if (total.last + mbchar_width) >= arg
        break total
      elsif (total.last + mbchar_width) >= @cursor_max
        break total
      else
        total = [total.first + gc.bytesize, total.last + mbchar_width]
        total
      end
    }
  end

  private def vi_replace_char(key, arg: 1)
    @waiting_proc = ->(k) {
      if arg == 1
        byte_size = Reline::Unicode.get_next_mbchar_size(@line, @byte_pointer)
        before = @line.byteslice(0, @byte_pointer)
        remaining_point = @byte_pointer + byte_size
        after = @line.byteslice(remaining_point, @line.bytesize - remaining_point)
        @line = before + k.chr + after
        @cursor_max = calculate_width(@line)
        @waiting_proc = nil
      elsif arg > 1
        byte_size = 0
        arg.times do
          byte_size += Reline::Unicode.get_next_mbchar_size(@line, @byte_pointer + byte_size)
        end
        before = @line.byteslice(0, @byte_pointer)
        remaining_point = @byte_pointer + byte_size
        after = @line.byteslice(remaining_point, @line.bytesize - remaining_point)
        replaced = k.chr * arg
        @line = before + replaced + after
        @byte_pointer += replaced.bytesize
        @cursor += calculate_width(replaced)
        @cursor_max = calculate_width(@line)
        @waiting_proc = nil
      end
    }
  end

  private def vi_next_char(key, arg: 1, inclusive: false)
    @waiting_proc = ->(key_for_proc) { search_next_char(key_for_proc, arg, inclusive: inclusive) }
  end

  private def vi_to_next_char(key, arg: 1, inclusive: false)
    @waiting_proc = ->(key_for_proc) { search_next_char(key_for_proc, arg, need_prev_char: true, inclusive: inclusive) }
  end

  private def search_next_char(key, arg, need_prev_char: false, inclusive: false)
    if key.instance_of?(String)
      inputed_char = key
    else
      inputed_char = key.chr
    end
    prev_total = nil
    total = nil
    found = false
    @line.byteslice(@byte_pointer..-1).grapheme_clusters.each do |mbchar|
      # total has [byte_size, cursor]
      unless total
        # skip cursor point
        width = Reline::Unicode.get_mbchar_width(mbchar)
        total = [mbchar.bytesize, width]
      else
        if inputed_char == mbchar
          arg -= 1
          if arg.zero?
            found = true
            break
          end
        end
        width = Reline::Unicode.get_mbchar_width(mbchar)
        prev_total = total
        total = [total.first + mbchar.bytesize, total.last + width]
      end
    end
    if not need_prev_char and found and total
      byte_size, width = total
      @byte_pointer += byte_size
      @cursor += width
    elsif need_prev_char and found and prev_total
      byte_size, width = prev_total
      @byte_pointer += byte_size
      @cursor += width
    end
    if inclusive
      byte_size = Reline::Unicode.get_next_mbchar_size(@line, @byte_pointer)
      if byte_size > 0
        c = @line.byteslice(@byte_pointer, byte_size)
        width = Reline::Unicode.get_mbchar_width(c)
        @byte_pointer += byte_size
        @cursor += width
      end
    end
    @waiting_proc = nil
  end

  private def vi_prev_char(key, arg: 1)
    @waiting_proc = ->(key_for_proc) { search_prev_char(key_for_proc, arg) }
  end

  private def vi_to_prev_char(key, arg: 1)
    @waiting_proc = ->(key_for_proc) { search_prev_char(key_for_proc, arg, true) }
  end

  private def search_prev_char(key, arg, need_next_char = false)
    if key.instance_of?(String)
      inputed_char = key
    else
      inputed_char = key.chr
    end
    prev_total = nil
    total = nil
    found = false
    @line.byteslice(0..@byte_pointer).grapheme_clusters.reverse_each do |mbchar|
      # total has [byte_size, cursor]
      unless total
        # skip cursor point
        width = Reline::Unicode.get_mbchar_width(mbchar)
        total = [mbchar.bytesize, width]
      else
        if inputed_char == mbchar
          arg -= 1
          if arg.zero?
            found = true
            break
          end
        end
        width = Reline::Unicode.get_mbchar_width(mbchar)
        prev_total = total
        total = [total.first + mbchar.bytesize, total.last + width]
      end
    end
    if not need_next_char and found and total
      byte_size, width = total
      @byte_pointer -= byte_size
      @cursor -= width
    elsif need_next_char and found and prev_total
      byte_size, width = prev_total
      @byte_pointer -= byte_size
      @cursor -= width
    end
    @waiting_proc = nil
  end

  private def vi_join_lines(key, arg: 1)
    if @is_multiline and @buffer_of_lines.size > @line_index + 1
      @cursor = calculate_width(@line)
      @byte_pointer = @line.bytesize
      @line += ' ' + @buffer_of_lines.delete_at(@line_index + 1).lstrip
      @cursor_max = calculate_width(@line)
      @buffer_of_lines[@line_index] = @line
      @rerender_all = true
      @rest_height += 1
    end
    arg -= 1
    vi_join_lines(key, arg: arg) if arg > 0
  end

  private def em_set_mark(key)
    @mark_pointer = [@byte_pointer, @line_index]
  end
  alias_method :set_mark, :em_set_mark

  private def em_exchange_mark(key)
    return unless @mark_pointer
    new_pointer = [@byte_pointer, @line_index]
    @previous_line_index = @line_index
    @byte_pointer, @line_index = @mark_pointer
    @cursor = calculate_width(@line.byteslice(0, @byte_pointer))
    @cursor_max = calculate_width(@line)
    @mark_pointer = new_pointer
  end
  alias_method :exchange_point_and_mark, :em_exchange_mark
end
# frozen_string_literal: true
#
# cgi.rb - cgi support library
#
# Copyright (C) 2000  Network Applied Communication Laboratory, Inc.
#
# Copyright (C) 2000  Information-technology Promotion Agency, Japan
#
# Author: Wakou Aoyama <wakou@ruby-lang.org>
#
# Documentation: Wakou Aoyama (RDoc'd and embellished by William Webber)
#

# == Overview
#
# The Common Gateway Interface (CGI) is a simple protocol for passing an HTTP
# request from a web server to a standalone program, and returning the output
# to the web browser.  Basically, a CGI program is called with the parameters
# of the request passed in either in the environment (GET) or via $stdin
# (POST), and everything it prints to $stdout is returned to the client.
#
# This file holds the CGI class.  This class provides functionality for
# retrieving HTTP request parameters, managing cookies, and generating HTML
# output.
#
# The file CGI::Session provides session management functionality; see that
# class for more details.
#
# See http://www.w3.org/CGI/ for more information on the CGI protocol.
#
# == Introduction
#
# CGI is a large class, providing several categories of methods, many of which
# are mixed in from other modules.  Some of the documentation is in this class,
# some in the modules CGI::QueryExtension and CGI::HtmlExtension.  See
# CGI::Cookie for specific information on handling cookies, and cgi/session.rb
# (CGI::Session) for information on sessions.
#
# For queries, CGI provides methods to get at environmental variables,
# parameters, cookies, and multipart request data.  For responses, CGI provides
# methods for writing output and generating HTML.
#
# Read on for more details.  Examples are provided at the bottom.
#
# == Queries
#
# The CGI class dynamically mixes in parameter and cookie-parsing
# functionality,  environmental variable access, and support for
# parsing multipart requests (including uploaded files) from the
# CGI::QueryExtension module.
#
# === Environmental Variables
#
# The standard CGI environmental variables are available as read-only
# attributes of a CGI object.  The following is a list of these variables:
#
#
#   AUTH_TYPE               HTTP_HOST          REMOTE_IDENT
#   CONTENT_LENGTH          HTTP_NEGOTIATE     REMOTE_USER
#   CONTENT_TYPE            HTTP_PRAGMA        REQUEST_METHOD
#   GATEWAY_INTERFACE       HTTP_REFERER       SCRIPT_NAME
#   HTTP_ACCEPT             HTTP_USER_AGENT    SERVER_NAME
#   HTTP_ACCEPT_CHARSET     PATH_INFO          SERVER_PORT
#   HTTP_ACCEPT_ENCODING    PATH_TRANSLATED    SERVER_PROTOCOL
#   HTTP_ACCEPT_LANGUAGE    QUERY_STRING       SERVER_SOFTWARE
#   HTTP_CACHE_CONTROL      REMOTE_ADDR
#   HTTP_FROM               REMOTE_HOST
#
#
# For each of these variables, there is a corresponding attribute with the
# same name, except all lower case and without a preceding HTTP_.
# +content_length+ and +server_port+ are integers; the rest are strings.
#
# === Parameters
#
# The method #params() returns a hash of all parameters in the request as
# name/value-list pairs, where the value-list is an Array of one or more
# values.  The CGI object itself also behaves as a hash of parameter names
# to values, but only returns a single value (as a String) for each
# parameter name.
#
# For instance, suppose the request contains the parameter
# "favourite_colours" with the multiple values "blue" and "green".  The
# following behavior would occur:
#
#   cgi.params["favourite_colours"]  # => ["blue", "green"]
#   cgi["favourite_colours"]         # => "blue"
#
# If a parameter does not exist, the former method will return an empty
# array, the latter an empty string.  The simplest way to test for existence
# of a parameter is by the #has_key? method.
#
# === Cookies
#
# HTTP Cookies are automatically parsed from the request.  They are available
# from the #cookies() accessor, which returns a hash from cookie name to
# CGI::Cookie object.
#
# === Multipart requests
#
# If a request's method is POST and its content type is multipart/form-data,
# then it may contain uploaded files.  These are stored by the QueryExtension
# module in the parameters of the request.  The parameter name is the name
# attribute of the file input field, as usual.  However, the value is not
# a string, but an IO object, either an IOString for small files, or a
# Tempfile for larger ones.  This object also has the additional singleton
# methods:
#
# #local_path():: the path of the uploaded file on the local filesystem
# #original_filename():: the name of the file on the client computer
# #content_type():: the content type of the file
#
# == Responses
#
# The CGI class provides methods for sending header and content output to
# the HTTP client, and mixes in methods for programmatic HTML generation
# from CGI::HtmlExtension and CGI::TagMaker modules.  The precise version of HTML
# to use for HTML generation is specified at object creation time.
#
# === Writing output
#
# The simplest way to send output to the HTTP client is using the #out() method.
# This takes the HTTP headers as a hash parameter, and the body content
# via a block.  The headers can be generated as a string using the #http_header()
# method.  The output stream can be written directly to using the #print()
# method.
#
# === Generating HTML
#
# Each HTML element has a corresponding method for generating that
# element as a String.  The name of this method is the same as that
# of the element, all lowercase.  The attributes of the element are
# passed in as a hash, and the body as a no-argument block that evaluates
# to a String.  The HTML generation module knows which elements are
# always empty, and silently drops any passed-in body.  It also knows
# which elements require matching closing tags and which don't.  However,
# it does not know what attributes are legal for which elements.
#
# There are also some additional HTML generation methods mixed in from
# the CGI::HtmlExtension module.  These include individual methods for the
# different types of form inputs, and methods for elements that commonly
# take particular attributes where the attributes can be directly specified
# as arguments, rather than via a hash.
#
# === Utility HTML escape and other methods like a function.
#
# There are some utility tool defined in cgi/util.rb .
# And when include, you can use utility methods like a function.
#
# == Examples of use
#
# === Get form values
#
#   require "cgi"
#   cgi = CGI.new
#   value = cgi['field_name']   # <== value string for 'field_name'
#     # if not 'field_name' included, then return "".
#   fields = cgi.keys            # <== array of field names
#
#   # returns true if form has 'field_name'
#   cgi.has_key?('field_name')
#   cgi.has_key?('field_name')
#   cgi.include?('field_name')
#
# CAUTION! cgi['field_name'] returned an Array with the old
# cgi.rb(included in Ruby 1.6)
#
# === Get form values as hash
#
#   require "cgi"
#   cgi = CGI.new
#   params = cgi.params
#
# cgi.params is a hash.
#
#   cgi.params['new_field_name'] = ["value"]  # add new param
#   cgi.params['field_name'] = ["new_value"]  # change value
#   cgi.params.delete('field_name')           # delete param
#   cgi.params.clear                          # delete all params
#
#
# === Save form values to file
#
#   require "pstore"
#   db = PStore.new("query.db")
#   db.transaction do
#     db["params"] = cgi.params
#   end
#
#
# === Restore form values from file
#
#   require "pstore"
#   db = PStore.new("query.db")
#   db.transaction do
#     cgi.params = db["params"]
#   end
#
#
# === Get multipart form values
#
#   require "cgi"
#   cgi = CGI.new
#   value = cgi['field_name']   # <== value string for 'field_name'
#   value.read                  # <== body of value
#   value.local_path            # <== path to local file of value
#   value.original_filename     # <== original filename of value
#   value.content_type          # <== content_type of value
#
# and value has StringIO or Tempfile class methods.
#
# === Get cookie values
#
#   require "cgi"
#   cgi = CGI.new
#   values = cgi.cookies['name']  # <== array of 'name'
#     # if not 'name' included, then return [].
#   names = cgi.cookies.keys      # <== array of cookie names
#
# and cgi.cookies is a hash.
#
# === Get cookie objects
#
#   require "cgi"
#   cgi = CGI.new
#   for name, cookie in cgi.cookies
#     cookie.expires = Time.now + 30
#   end
#   cgi.out("cookie" => cgi.cookies) {"string"}
#
#   cgi.cookies # { "name1" => cookie1, "name2" => cookie2, ... }
#
#   require "cgi"
#   cgi = CGI.new
#   cgi.cookies['name'].expires = Time.now + 30
#   cgi.out("cookie" => cgi.cookies['name']) {"string"}
#
# === Print http header and html string to $DEFAULT_OUTPUT ($>)
#
#   require "cgi"
#   cgi = CGI.new("html4")  # add HTML generation methods
#   cgi.out do
#     cgi.html do
#       cgi.head do
#         cgi.title { "TITLE" }
#       end +
#       cgi.body do
#         cgi.form("ACTION" => "uri") do
#           cgi.p do
#             cgi.textarea("get_text") +
#             cgi.br +
#             cgi.submit
#           end
#         end +
#         cgi.pre do
#           CGI.escapeHTML(
#             "params: #{cgi.params.inspect}\n" +
#             "cookies: #{cgi.cookies.inspect}\n" +
#             ENV.collect do |key, value|
#               "#{key} --> #{value}\n"
#             end.join("")
#           )
#         end
#       end
#     end
#   end
#
#   # add HTML generation methods
#   CGI.new("html3")    # html3.2
#   CGI.new("html4")    # html4.01 (Strict)
#   CGI.new("html4Tr")  # html4.01 Transitional
#   CGI.new("html4Fr")  # html4.01 Frameset
#   CGI.new("html5")    # html5
#
# === Some utility methods
#
#   require 'cgi/util'
#   CGI.escapeHTML('Usage: foo "bar" <baz>')
#
#
# === Some utility methods like a function
#
#   require 'cgi/util'
#   include CGI::Util
#   escapeHTML('Usage: foo "bar" <baz>')
#   h('Usage: foo "bar" <baz>') # alias
#
#

class CGI
  VERSION = "0.2.2"
end

require 'cgi/core'
require 'cgi/cookie'
require 'cgi/util'
CGI.autoload(:HtmlExtension, 'cgi/html')
module DidYouMean
  module Jaro
    module_function

    def distance(str1, str2)
      str1, str2 = str2, str1 if str1.length > str2.length
      length1, length2 = str1.length, str2.length

      m          = 0.0
      t          = 0.0
      range      = (length2 / 2).floor - 1
      range      = 0 if range < 0
      flags1     = 0
      flags2     = 0

      # Avoid duplicating enumerable objects
      str1_codepoints = str1.codepoints
      str2_codepoints = str2.codepoints

      i = 0
      while i < length1
        last = i + range
        j    = (i >= range) ? i - range : 0

        while j <= last
          if flags2[j] == 0 && str1_codepoints[i] == str2_codepoints[j]
            flags2 |= (1 << j)
            flags1 |= (1 << i)
            m += 1
            break
          end

          j += 1
        end

        i += 1
      end

      k = i = 0
      while i < length1
        if flags1[i] != 0
          j = index = k

          k = while j < length2
            index = j
            break(j + 1) if flags2[j] != 0

            j += 1
          end

          t += 1 if str1_codepoints[i] != str2_codepoints[index]
        end

        i += 1
      end
      t = (t / 2).floor

      m == 0 ? 0 : (m / length1 + m / length2 + (m - t) / m) / 3
    end
  end

  module JaroWinkler
    WEIGHT    = 0.1
    THRESHOLD = 0.7

    module_function

    def distance(str1, str2)
      jaro_distance = Jaro.distance(str1, str2)

      if jaro_distance > THRESHOLD
        codepoints2  = str2.codepoints
        prefix_bonus = 0

        i = 0
        str1.each_codepoint do |char1|
          char1 == codepoints2[i] && i < 4 ? prefix_bonus += 1 : break
          i += 1
        end

        jaro_distance + (prefix_bonus * WEIGHT * (1 - jaro_distance))
      else
        jaro_distance
      end
    end
  end
end
# frozen_string_literal: true

module DidYouMean
  # spell checker for a dictionary that has a tree
  # structure, see doc/tree_spell_checker_api.md
  class TreeSpellChecker
    attr_reader :dictionary, :separator, :augment

    def initialize(dictionary:, separator: '/', augment: nil)
      @dictionary = dictionary
      @separator = separator
      @augment = augment
    end

    def correct(input)
      plausibles = plausible_dimensions(input)
      return fall_back_to_normal_spell_check(input) if plausibles.empty?

      suggestions = find_suggestions(input, plausibles)
      return fall_back_to_normal_spell_check(input) if suggestions.empty?

      suggestions
    end

    def dictionary_without_leaves
      @dictionary_without_leaves ||= dictionary.map { |word| word.split(separator)[0..-2] }.uniq
    end

    def tree_depth
      @tree_depth ||= dictionary_without_leaves.max { |a, b| a.size <=> b.size }.size
    end

    def dimensions
      @dimensions ||= tree_depth.times.map do |index|
                        dictionary_without_leaves.map { |element| element[index] }.compact.uniq
                      end
    end

    def find_leaves(path)
      path_with_separator = "#{path}#{separator}"

      dictionary
        .select {|str| str.include?(path_with_separator) }
        .map {|str| str.gsub(path_with_separator, '') }
    end

    def plausible_dimensions(input)
      input.split(separator)[0..-2]
        .map
        .with_index { |element, index| correct_element(dimensions[index], element) if dimensions[index] }
        .compact
    end

    def possible_paths(states)
      states.map { |state| state.join(separator) }
    end

    private

    def find_suggestions(input, plausibles)
      states = plausibles[0].product(*plausibles[1..-1])
      paths  = possible_paths(states)
      leaf   = input.split(separator).last

      find_ideas(paths, leaf)
    end

    def fall_back_to_normal_spell_check(input)
      return [] unless augment

      ::DidYouMean::SpellChecker.new(dictionary: dictionary).correct(input)
    end

    def find_ideas(paths, leaf)
      paths.flat_map do |path|
        names = find_leaves(path)
        ideas = correct_element(names, leaf)

        ideas_to_paths(ideas, leaf, names, path)
      end.compact
    end

    def ideas_to_paths(ideas, leaf, names, path)
      if ideas.empty?
        nil
      elsif names.include?(leaf)
        ["#{path}#{separator}#{leaf}"]
      else
        ideas.map {|str| "#{path}#{separator}#{str}" }
      end
    end

    def correct_element(names, element)
      return names if names.size == 1

      str = normalize(element)

      return [str] if names.include?(str)

      ::DidYouMean::SpellChecker.new(dictionary: names).correct(str)
    end

    def normalize(str)
      str.downcase!
      str.tr!('@', ' ') if str.include?('@')
      str
    end
  end
end
# frozen-string-literal: true

require_relative "levenshtein"
require_relative "jaro_winkler"

module DidYouMean
  class SpellChecker
    def initialize(dictionary:)
      @dictionary = dictionary
    end

    def correct(input)
      input     = normalize(input)
      threshold = input.length > 3 ? 0.834 : 0.77

      words = @dictionary.select { |word| JaroWinkler.distance(normalize(word), input) >= threshold }
      words.reject! { |word| input == word.to_s }
      words.sort_by! { |word| JaroWinkler.distance(word.to_s, input) }
      words.reverse!

      # Correct mistypes
      threshold   = (input.length * 0.25).ceil
      corrections = words.select { |c| Levenshtein.distance(normalize(c), input) <= threshold }

      # Correct misspells
      if corrections.empty?
        corrections = words.select do |word|
          word   = normalize(word)
          length = input.length < word.length ? input.length : word.length

          Levenshtein.distance(word, input) < length
        end.first(1)
      end

      corrections
    end

    private

    def normalize(str_or_symbol) #:nodoc:
      str = str_or_symbol.to_s.downcase
      str.tr!("@", "")
      str
    end
  end
end
# frozen-string-literal: true

module DidYouMean
  # The +DidYouMean::PlainFormatter+ is the basic, default formatter for the
  # gem. The formatter responds to the +message_for+ method and it returns a
  # human readable string.
  class PlainFormatter

    # Returns a human readable string that contains +corrections+. This
    # formatter is designed to be less verbose to not take too much screen
    # space while being helpful enough to the user.
    #
    # @example
    #
    #   formatter = DidYouMean::PlainFormatter.new
    #
    #   # displays suggestions in two lines with the leading empty line
    #   puts formatter.message_for(["methods", "method"])
    #
    #   Did you mean?  methods
    #                   method
    #   # => nil
    #
    #   # displays an empty line
    #   puts formatter.message_for([])
    #
    #   # => nil
    #
    def message_for(corrections)
      corrections.empty? ? "" : "\nDid you mean?  #{corrections.join("\n               ")}"
    end
  end
end
# frozen-string-literal: true

module DidYouMean
  # The +DidYouMean::VerboseFormatter+ uses extra empty lines to make the
  # suggestion stand out more in the error message.
  #
  # In order to activate the verbose formatter,
  #
  # @example
  #
  #   OBject
  #   # => NameError: uninitialized constant OBject
  #   #    Did you mean?  Object
  #
  #   require 'did_you_mean/verbose'
  #
  #   OBject
  #   # => NameError: uninitialized constant OBject
  #   #
  #   #        Did you mean? Object
  #   #
  #
  class VerboseFormatter

    # Returns a human readable string that contains +corrections+. This
    # formatter is designed to be less verbose to not take too much screen
    # space while being helpful enough to the user.
    #
    # @example
    #
    #   formatter = DidYouMean::PlainFormatter.new
    #
    #   puts formatter.message_for(["methods", "method"])
    #
    #
    #       Did you mean? methods
    #                     method
    #
    #   # => nil
    #
    def message_for(corrections)
      return "" if corrections.empty?

      output = "\n\n    Did you mean? ".dup
      output << corrections.join("\n                  ")
      output << "\n "
    end
  end
end
module DidYouMean
  module Correctable
    def original_message
      method(:to_s).super_method.call
    end

    def to_s
      msg = super.dup
      suggestion = DidYouMean.formatter.message_for(corrections)

      msg << suggestion if !msg.end_with?(suggestion)
      msg
    rescue
      super
    end

    def corrections
      @corrections ||= spell_checker.corrections
    end

    def spell_checker
      SPELL_CHECKERS[self.class.to_s].new(self)
    end
  end
end
module DidYouMean
  module Levenshtein # :nodoc:
    # This code is based directly on the Text gem implementation
    # Copyright (c) 2006-2013 Paul Battley, Michael Neumann, Tim Fletcher.
    #
    # Returns a value representing the "cost" of transforming str1 into str2
    def distance(str1, str2)
      n = str1.length
      m = str2.length
      return m if n.zero?
      return n if m.zero?

      d = (0..m).to_a
      x = nil

      # to avoid duplicating an enumerable object, create it outside of the loop
      str2_codepoints = str2.codepoints

      str1.each_codepoint.with_index(1) do |char1, i|
        j = 0
        while j < m
          cost = (char1 == str2_codepoints[j]) ? 0 : 1
          x = min3(
            d[j+1] + 1, # insertion
            i + 1,      # deletion
            d[j] + cost # substitution
          )
          d[j] = i
          i = x

          j += 1
        end
        d[m] = x
      end

      x
    end
    module_function :distance

    private

    # detects the minimum value out of three arguments. This method is
    # faster than `[a, b, c].min` and puts less GC pressure.
    # See https://github.com/ruby/did_you_mean/pull/1 for a performance
    # benchmark.
    def min3(a, b, c)
      if a < b && a < c
        a
      elsif b < c
        b
      else
        c
      end
    end
    module_function :min3
  end
end
warn "Experimental features in the did_you_mean gem has been removed " \
     "and `require \"did_you_mean/experimental\"' has no effect."
module DidYouMean
  VERSION = "1.5.0"
end
require_relative '../did_you_mean'
require_relative 'formatters/verbose_formatter'

DidYouMean.formatter = DidYouMean::VerboseFormatter.new
module DidYouMean
  class NullChecker
    def initialize(*);  end
    def corrections; [] end
  end
end
require_relative 'name_error_checkers/class_name_checker'
require_relative 'name_error_checkers/variable_name_checker'

module DidYouMean
  class << (NameErrorCheckers = Object.new)
    def new(exception)
      case exception.original_message
      when /uninitialized constant/
        ClassNameChecker
      when /undefined local variable or method/,
           /undefined method/,
           /uninitialized class variable/,
           /no member '.*' in struct/
        VariableNameChecker
      else
        NullChecker
      end.new(exception)
    end
  end
end
require_relative "../spell_checker"

module DidYouMean
  class MethodNameChecker
    attr_reader :method_name, :receiver

    NAMES_TO_EXCLUDE = { NilClass => nil.methods }
    NAMES_TO_EXCLUDE.default = []

    # +MethodNameChecker::RB_RESERVED_WORDS+ is the list of reserved words in
    # Ruby that take an argument. Unlike
    # +VariableNameChecker::RB_RESERVED_WORDS+, these reserved words require
    # an argument, and a +NoMethodError+ is raised due to the presence of the
    # argument.
    #
    # The +MethodNameChecker+ will use this list to suggest a reversed word if
    # a +NoMethodError+ is raised and found closest matches.
    #
    # Also see +VariableNameChecker::RB_RESERVED_WORDS+.
    RB_RESERVED_WORDS = %i(
      alias
      case
      def
      defined?
      elsif
      end
      ensure
      for
      rescue
      super
      undef
      unless
      until
      when
      while
      yield
    )

    def initialize(exception)
      @method_name  = exception.name
      @receiver     = exception.receiver
      @private_call = exception.respond_to?(:private_call?) ? exception.private_call? : false
    end

    def corrections
      @corrections ||= begin
                         dictionary = method_names
                         dictionary = RB_RESERVED_WORDS + dictionary if @private_call

                         SpellChecker.new(dictionary: dictionary).correct(method_name) - names_to_exclude
                       end
    end

    def method_names
      if Object === receiver
        method_names = receiver.methods + receiver.singleton_methods
        method_names += receiver.private_methods if @private_call
        method_names.uniq!
        method_names
      else
        []
      end
    end

    def names_to_exclude
      Object === receiver ? NAMES_TO_EXCLUDE[receiver.class] : []
    end
  end
end
# frozen-string-literal: true

require_relative "../spell_checker"
require_relative "../tree_spell_checker"

module DidYouMean
  class RequirePathChecker
    attr_reader :path

    INITIAL_LOAD_PATH = $LOAD_PATH.dup.freeze
    ENV_SPECIFIC_EXT  = ".#{RbConfig::CONFIG["DLEXT"]}"

    private_constant :INITIAL_LOAD_PATH, :ENV_SPECIFIC_EXT

    def self.requireables
      @requireables ||= INITIAL_LOAD_PATH
                          .flat_map {|path| Dir.glob("**/???*{.rb,#{ENV_SPECIFIC_EXT}}", base: path) }
                          .map {|path| path.chomp!(".rb") || path.chomp!(ENV_SPECIFIC_EXT) }
    end

    def initialize(exception)
      @path = exception.path
    end

    def corrections
      @corrections ||= begin
                         threshold     = path.size * 2
                         dictionary    = self.class.requireables.reject {|str| str.size >= threshold }
                         spell_checker = path.include?("/") ? TreeSpellChecker : SpellChecker

                         spell_checker.new(dictionary: dictionary).correct(path).uniq
                       end
    end
  end
end
# frozen-string-literal: true

require_relative "../../spell_checker"

module DidYouMean
  class ClassNameChecker
    attr_reader :class_name

    def initialize(exception)
      @class_name, @receiver, @original_message = exception.name, exception.receiver, exception.original_message
    end

    def corrections
      @corrections ||= SpellChecker.new(dictionary: class_names)
                         .correct(class_name)
                         .map(&:full_name)
                         .reject {|qualified_name| @original_message.include?(qualified_name) }
    end

    def class_names
      scopes.flat_map do |scope|
        scope.constants.map do |c|
          ClassName.new(c, scope == Object ? "" : "#{scope}::")
        end
      end
    end

    def scopes
      @scopes ||= @receiver.to_s.split("::").inject([Object]) do |_scopes, scope|
        _scopes << _scopes.last.const_get(scope)
      end.uniq
    end

    class ClassName < String
      attr :namespace

      def initialize(name, namespace = '')
        super(name.to_s)
        @namespace = namespace
      end

      def full_name
        self.class.new("#{namespace}#{self}")
      end
    end

    private_constant :ClassName
  end
end
# frozen-string-literal: true

require_relative "../../spell_checker"

module DidYouMean
  class VariableNameChecker
    attr_reader :name, :method_names, :lvar_names, :ivar_names, :cvar_names

    NAMES_TO_EXCLUDE = { 'foo' => [:fork, :for] }
    NAMES_TO_EXCLUDE.default = []

    # +VariableNameChecker::RB_RESERVED_WORDS+ is the list of all reserved
    # words in Ruby. They could be declared like methods are, and a typo would
    # cause Ruby to raise a +NameError+ because of the way they are declared.
    #
    # The +:VariableNameChecker+ will use this list to suggest a reversed word
    # if a +NameError+ is raised and found closest matches, excluding:
    #
    #   * +do+
    #   * +if+
    #   * +in+
    #   * +or+
    #
    # Also see +MethodNameChecker::RB_RESERVED_WORDS+.
    RB_RESERVED_WORDS = %i(
      BEGIN
      END
      alias
      and
      begin
      break
      case
      class
      def
      defined?
      else
      elsif
      end
      ensure
      false
      for
      module
      next
      nil
      not
      redo
      rescue
      retry
      return
      self
      super
      then
      true
      undef
      unless
      until
      when
      while
      yield
      __LINE__
      __FILE__
      __ENCODING__
    )

    def initialize(exception)
      @name       = exception.name.to_s.tr("@", "")
      @lvar_names = exception.respond_to?(:local_variables) ? exception.local_variables : []
      receiver    = exception.receiver

      @method_names = receiver.methods + receiver.private_methods
      @ivar_names   = receiver.instance_variables
      @cvar_names   = receiver.class.class_variables
      @cvar_names  += receiver.class_variables if receiver.kind_of?(Module)
    end

    def corrections
      @corrections ||= SpellChecker
                     .new(dictionary: (RB_RESERVED_WORDS + lvar_names + method_names + ivar_names + cvar_names))
                     .correct(name) - NAMES_TO_EXCLUDE[@name]
    end
  end
end
require_relative "../spell_checker"

module DidYouMean
  class KeyErrorChecker
    def initialize(key_error)
      @key = key_error.key
      @keys = key_error.receiver.keys
    end

    def corrections
      @corrections ||= exact_matches.empty? ? SpellChecker.new(dictionary: @keys).correct(@key).map(&:inspect) : exact_matches
    end

    private

    def exact_matches
      @exact_matches ||= @keys.select { |word| @key == word.to_s }.map(&:inspect)
    end
  end
end
begin
  require 'readline.so'
rescue LoadError
  require 'reline' unless defined? Reline
  Readline = Reline
end
# frozen_string_literal: false
require_relative 'optparse'
# frozen_string_literal: true
#
# GetoptLong for Ruby
#
# Copyright (C) 1998, 1999, 2000  Motoyuki Kasahara.
#
# You may redistribute and/or modify this library under the same license
# terms as Ruby.
#
# See GetoptLong for documentation.
#
# Additional documents and the latest version of `getoptlong.rb' can be
# found at http://www.sra.co.jp/people/m-kasahr/ruby/getoptlong/

# The GetoptLong class allows you to parse command line options similarly to
# the GNU getopt_long() C library call. Note, however, that GetoptLong is a
# pure Ruby implementation.
#
# GetoptLong allows for POSIX-style options like <tt>--file</tt> as well
# as single letter options like <tt>-f</tt>
#
# The empty option <tt>--</tt> (two minus symbols) is used to end option
# processing. This can be particularly important if options have optional
# arguments.
#
# Here is a simple example of usage:
#
#     require 'getoptlong'
#
#     opts = GetoptLong.new(
#       [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
#       [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
#       [ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
#     )
#
#     dir = nil
#     name = nil
#     repetitions = 1
#     opts.each do |opt, arg|
#       case opt
#         when '--help'
#           puts <<-EOF
#     hello [OPTION] ... DIR
#
#     -h, --help:
#        show help
#
#     --repeat x, -n x:
#        repeat x times
#
#     --name [name]:
#        greet user by name, if name not supplied default is John
#
#     DIR: The directory in which to issue the greeting.
#           EOF
#         when '--repeat'
#           repetitions = arg.to_i
#         when '--name'
#           if arg == ''
#             name = 'John'
#           else
#             name = arg
#           end
#       end
#     end
#
#     if ARGV.length != 1
#       puts "Missing dir argument (try --help)"
#       exit 0
#     end
#
#     dir = ARGV.shift
#
#     Dir.chdir(dir)
#     for i in (1..repetitions)
#       print "Hello"
#       if name
#         print ", #{name}"
#       end
#       puts
#     end
#
# Example command line:
#
#     hello -n 6 --name -- /tmp
#
class GetoptLong
  # Version.
  VERSION = "0.1.1"

  #
  # Orderings.
  #
  ORDERINGS = [REQUIRE_ORDER = 0, PERMUTE = 1, RETURN_IN_ORDER = 2]

  #
  # Argument flags.
  #
  ARGUMENT_FLAGS = [NO_ARGUMENT = 0, REQUIRED_ARGUMENT = 1,
    OPTIONAL_ARGUMENT = 2]

  #
  # Status codes.
  #
  STATUS_YET, STATUS_STARTED, STATUS_TERMINATED = 0, 1, 2

  #
  # Error types.
  #
  class Error  < StandardError; end
  class AmbiguousOption   < Error; end
  class NeedlessArgument < Error; end
  class MissingArgument  < Error; end
  class InvalidOption    < Error; end

  #
  # Set up option processing.
  #
  # The options to support are passed to new() as an array of arrays.
  # Each sub-array contains any number of String option names which carry
  # the same meaning, and one of the following flags:
  #
  # GetoptLong::NO_ARGUMENT :: Option does not take an argument.
  #
  # GetoptLong::REQUIRED_ARGUMENT :: Option always takes an argument.
  #
  # GetoptLong::OPTIONAL_ARGUMENT :: Option may or may not take an argument.
  #
  # The first option name is considered to be the preferred (canonical) name.
  # Other than that, the elements of each sub-array can be in any order.
  #
  def initialize(*arguments)
    #
    # Current ordering.
    #
    if ENV.include?('POSIXLY_CORRECT')
      @ordering = REQUIRE_ORDER
    else
      @ordering = PERMUTE
    end

    #
    # Hash table of option names.
    # Keys of the table are option names, and their values are canonical
    # names of the options.
    #
    @canonical_names = Hash.new

    #
    # Hash table of argument flags.
    # Keys of the table are option names, and their values are argument
    # flags of the options.
    #
    @argument_flags = Hash.new

    #
    # Whether error messages are output to $stderr.
    #
    @quiet = false

    #
    # Status code.
    #
    @status = STATUS_YET

    #
    # Error code.
    #
    @error = nil

    #
    # Error message.
    #
    @error_message = nil

    #
    # Rest of catenated short options.
    #
    @rest_singles = ''

    #
    # List of non-option-arguments.
    # Append them to ARGV when option processing is terminated.
    #
    @non_option_arguments = Array.new

    if 0 < arguments.length
      set_options(*arguments)
    end
  end

  #
  # Set the handling of the ordering of options and arguments.
  # A RuntimeError is raised if option processing has already started.
  #
  # The supplied value must be a member of GetoptLong::ORDERINGS. It alters
  # the processing of options as follows:
  #
  # <b>REQUIRE_ORDER</b> :
  #
  # Options are required to occur before non-options.
  #
  # Processing of options ends as soon as a word is encountered that has not
  # been preceded by an appropriate option flag.
  #
  # For example, if -a and -b are options which do not take arguments,
  # parsing command line arguments of '-a one -b two' would result in
  # 'one', '-b', 'two' being left in ARGV, and only ('-a', '') being
  # processed as an option/arg pair.
  #
  # This is the default ordering, if the environment variable
  # POSIXLY_CORRECT is set. (This is for compatibility with GNU getopt_long.)
  #
  # <b>PERMUTE</b> :
  #
  # Options can occur anywhere in the command line parsed. This is the
  # default behavior.
  #
  # Every sequence of words which can be interpreted as an option (with or
  # without argument) is treated as an option; non-option words are skipped.
  #
  # For example, if -a does not require an argument and -b optionally takes
  # an argument, parsing '-a one -b two three' would result in ('-a','') and
  # ('-b', 'two') being processed as option/arg pairs, and 'one','three'
  # being left in ARGV.
  #
  # If the ordering is set to PERMUTE but the environment variable
  # POSIXLY_CORRECT is set, REQUIRE_ORDER is used instead. This is for
  # compatibility with GNU getopt_long.
  #
  # <b>RETURN_IN_ORDER</b> :
  #
  # All words on the command line are processed as options. Words not
  # preceded by a short or long option flag are passed as arguments
  # with an option of '' (empty string).
  #
  # For example, if -a requires an argument but -b does not, a command line
  # of '-a one -b two three' would result in option/arg pairs of ('-a', 'one')
  # ('-b', ''), ('', 'two'), ('', 'three') being processed.
  #
  def ordering=(ordering)
    #
    # The method is failed if option processing has already started.
    #
    if @status != STATUS_YET
      set_error(ArgumentError, "argument error")
      raise RuntimeError,
        "invoke ordering=, but option processing has already started"
    end

    #
    # Check ordering.
    #
    if !ORDERINGS.include?(ordering)
      raise ArgumentError, "invalid ordering `#{ordering}'"
    end
    if ordering == PERMUTE && ENV.include?('POSIXLY_CORRECT')
      @ordering = REQUIRE_ORDER
    else
      @ordering = ordering
    end
  end

  #
  # Return ordering.
  #
  attr_reader :ordering

  #
  # Set options. Takes the same argument as GetoptLong.new.
  #
  # Raises a RuntimeError if option processing has already started.
  #
  def set_options(*arguments)
    #
    # The method is failed if option processing has already started.
    #
    if @status != STATUS_YET
      raise RuntimeError,
        "invoke set_options, but option processing has already started"
    end

    #
    # Clear tables of option names and argument flags.
    #
    @canonical_names.clear
    @argument_flags.clear

    arguments.each do |arg|
      if !arg.is_a?(Array)
       raise ArgumentError, "the option list contains non-Array argument"
      end

      #
      # Find an argument flag and it set to `argument_flag'.
      #
      argument_flag = nil
      arg.each do |i|
        if ARGUMENT_FLAGS.include?(i)
          if argument_flag != nil
            raise ArgumentError, "too many argument-flags"
          end
          argument_flag = i
        end
      end

      raise ArgumentError, "no argument-flag" if argument_flag == nil

      canonical_name = nil
      arg.each do |i|
        #
        # Check an option name.
        #
        next if i == argument_flag
        begin
          if !i.is_a?(String) || i !~ /\A-([^-]|-.+)\z/
            raise ArgumentError, "an invalid option `#{i}'"
          end
          if (@canonical_names.include?(i))
            raise ArgumentError, "option redefined `#{i}'"
          end
        rescue
          @canonical_names.clear
          @argument_flags.clear
          raise
        end

        #
        # Register the option (`i') to the `@canonical_names' and
        # `@canonical_names' Hashes.
        #
        if canonical_name == nil
          canonical_name = i
        end
        @canonical_names[i] = canonical_name
        @argument_flags[i] = argument_flag
      end
      raise ArgumentError, "no option name" if canonical_name == nil
    end
    return self
  end

  #
  # Set/Unset `quiet' mode.
  #
  attr_writer :quiet

  #
  # Return the flag of `quiet' mode.
  #
  attr_reader :quiet

  #
  # `quiet?' is an alias of `quiet'.
  #
  alias quiet? quiet

  #
  # Explicitly terminate option processing.
  #
  def terminate
    return nil if @status == STATUS_TERMINATED
    raise RuntimeError, "an error has occurred" if @error != nil

    @status = STATUS_TERMINATED
    @non_option_arguments.reverse_each do |argument|
      ARGV.unshift(argument)
    end

    @canonical_names = nil
    @argument_flags = nil
    @rest_singles = nil
    @non_option_arguments = nil

    return self
  end

  #
  # Returns true if option processing has terminated, false otherwise.
  #
  def terminated?
    return @status == STATUS_TERMINATED
  end

  #
  # Set an error (a protected method).
  #
  def set_error(type, message)
    $stderr.print("#{$0}: #{message}\n") if !@quiet

    @error = type
    @error_message = message
    @canonical_names = nil
    @argument_flags = nil
    @rest_singles = nil
    @non_option_arguments = nil

    raise type, message
  end
  protected :set_error

  #
  # Examine whether an option processing is failed.
  #
  attr_reader :error

  #
  # `error?' is an alias of `error'.
  #
  alias error? error

  # Return the appropriate error message in POSIX-defined format.
  # If no error has occurred, returns nil.
  #
  def error_message
    return @error_message
  end

  #
  # Get next option name and its argument, as an Array of two elements.
  #
  # The option name is always converted to the first (preferred)
  # name given in the original options to GetoptLong.new.
  #
  # Example: ['--option', 'value']
  #
  # Returns nil if the processing is complete (as determined by
  # STATUS_TERMINATED).
  #
  def get
    option_name, option_argument = nil, ''

    #
    # Check status.
    #
    return nil if @error != nil
    case @status
    when STATUS_YET
      @status = STATUS_STARTED
    when STATUS_TERMINATED
      return nil
    end

    #
    # Get next option argument.
    #
    if 0 < @rest_singles.length
      argument = '-' + @rest_singles
    elsif (ARGV.length == 0)
      terminate
      return nil
    elsif @ordering == PERMUTE
      while 0 < ARGV.length && ARGV[0] !~ /\A-./
        @non_option_arguments.push(ARGV.shift)
      end
      if ARGV.length == 0
        terminate
        return nil
      end
      argument = ARGV.shift
    elsif @ordering == REQUIRE_ORDER
      if (ARGV[0] !~ /\A-./)
        terminate
        return nil
      end
      argument = ARGV.shift
    else
      argument = ARGV.shift
    end

    #
    # Check the special argument `--'.
    # `--' indicates the end of the option list.
    #
    if argument == '--' && @rest_singles.length == 0
      terminate
      return nil
    end

    #
    # Check for long and short options.
    #
    if argument =~ /\A(--[^=]+)/ && @rest_singles.length == 0
      #
      # This is a long style option, which start with `--'.
      #
      pattern = $1
      if @canonical_names.include?(pattern)
        option_name = pattern
      else
        #
        # The option `option_name' is not registered in `@canonical_names'.
        # It may be an abbreviated.
        #
        matches = []
        @canonical_names.each_key do |key|
          if key.index(pattern) == 0
            option_name = key
            matches << key
          end
        end
        if 2 <= matches.length
          set_error(AmbiguousOption, "option `#{argument}' is ambiguous between #{matches.join(', ')}")
        elsif matches.length == 0
          set_error(InvalidOption, "unrecognized option `#{argument}'")
        end
      end

      #
      # Check an argument to the option.
      #
      if @argument_flags[option_name] == REQUIRED_ARGUMENT
        if argument =~ /=(.*)/m
          option_argument = $1
        elsif 0 < ARGV.length
          option_argument = ARGV.shift
        else
          set_error(MissingArgument,
                    "option `#{argument}' requires an argument")
        end
      elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
        if argument =~ /=(.*)/m
          option_argument = $1
        elsif 0 < ARGV.length && ARGV[0] !~ /\A-./
          option_argument = ARGV.shift
        else
          option_argument = ''
        end
      elsif argument =~ /=(.*)/m
        set_error(NeedlessArgument,
                  "option `#{option_name}' doesn't allow an argument")
      end

    elsif argument =~ /\A(-(.))(.*)/m
      #
      # This is a short style option, which start with `-' (not `--').
      # Short options may be catenated (e.g. `-l -g' is equivalent to
      # `-lg').
      #
      option_name, ch, @rest_singles = $1, $2, $3

      if @canonical_names.include?(option_name)
        #
        # The option `option_name' is found in `@canonical_names'.
        # Check its argument.
        #
        if @argument_flags[option_name] == REQUIRED_ARGUMENT
          if 0 < @rest_singles.length
            option_argument = @rest_singles
            @rest_singles = ''
          elsif 0 < ARGV.length
            option_argument = ARGV.shift
          else
            # 1003.2 specifies the format of this message.
            set_error(MissingArgument, "option requires an argument -- #{ch}")
          end
        elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
          if 0 < @rest_singles.length
            option_argument = @rest_singles
            @rest_singles = ''
          elsif 0 < ARGV.length && ARGV[0] !~ /\A-./
            option_argument = ARGV.shift
          else
            option_argument = ''
          end
        end
      else
        #
        # This is an invalid option.
        # 1003.2 specifies the format of this message.
        #
        if ENV.include?('POSIXLY_CORRECT')
          set_error(InvalidOption, "invalid option -- #{ch}")
        else
          set_error(InvalidOption, "invalid option -- #{ch}")
        end
      end
    else
      #
      # This is a non-option argument.
      # Only RETURN_IN_ORDER fell into here.
      #
      return '', argument
    end

    return @canonical_names[option_name], option_argument
  end

  #
  # `get_option' is an alias of `get'.
  #
  alias get_option get

  # Iterator version of `get'.
  #
  # The block is called repeatedly with two arguments:
  # The first is the option name.
  # The second is the argument which followed it (if any).
  # Example: ('--opt', 'value')
  #
  # The option name is always converted to the first (preferred)
  # name given in the original options to GetoptLong.new.
  #
  def each
    loop do
      option_name, option_argument = get_option
      break if option_name == nil
      yield option_name, option_argument
    end
  end

  #
  # `each_option' is an alias of `each'.
  #
  alias each_option each
end
# frozen_string_literal: true

require 'prettyprint'

##
# A pretty-printer for Ruby objects.
#
##
# == What PP Does
#
# Standard output by #p returns this:
#   #<PP:0x81fedf0 @genspace=#<Proc:0x81feda0>, @group_queue=#<PrettyPrint::GroupQueue:0x81fed3c @queue=[[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], []]>, @buffer=[], @newline="\n", @group_stack=[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], @buffer_width=0, @indent=0, @maxwidth=79, @output_width=2, @output=#<IO:0x8114ee4>>
#
# Pretty-printed output returns this:
#   #<PP:0x81fedf0
#    @buffer=[],
#    @buffer_width=0,
#    @genspace=#<Proc:0x81feda0>,
#    @group_queue=
#     #<PrettyPrint::GroupQueue:0x81fed3c
#      @queue=
#       [[#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
#        []]>,
#    @group_stack=
#     [#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
#    @indent=0,
#    @maxwidth=79,
#    @newline="\n",
#    @output=#<IO:0x8114ee4>,
#    @output_width=2>
#
##
# == Usage
#
#   pp(obj)             #=> obj
#   pp obj              #=> obj
#   pp(obj1, obj2, ...) #=> [obj1, obj2, ...]
#   pp()                #=> nil
#
# Output <tt>obj(s)</tt> to <tt>$></tt> in pretty printed format.
#
# It returns <tt>obj(s)</tt>.
#
##
# == Output Customization
#
# To define a customized pretty printing function for your classes,
# redefine method <code>#pretty_print(pp)</code> in the class.
#
# <code>#pretty_print</code> takes the +pp+ argument, which is an instance of the PP class.
# The method uses #text, #breakable, #nest, #group and #pp to print the
# object.
#
##
# == Pretty-Print JSON
#
# To pretty-print JSON refer to JSON#pretty_generate.
#
##
# == Author
# Tanaka Akira <akr@fsij.org>

class PP < PrettyPrint
  # Outputs +obj+ to +out+ in pretty printed format of
  # +width+ columns in width.
  #
  # If +out+ is omitted, <code>$></code> is assumed.
  # If +width+ is omitted, 79 is assumed.
  #
  # PP.pp returns +out+.
  def PP.pp(obj, out=$>, width=79)
    q = PP.new(out, width)
    q.guard_inspect_key {q.pp obj}
    q.flush
    #$pp = q
    out << "\n"
  end

  # Outputs +obj+ to +out+ like PP.pp but with no indent and
  # newline.
  #
  # PP.singleline_pp returns +out+.
  def PP.singleline_pp(obj, out=$>)
    q = SingleLine.new(out)
    q.guard_inspect_key {q.pp obj}
    q.flush
    out
  end

  # :stopdoc:
  def PP.mcall(obj, mod, meth, *args, &block)
    mod.instance_method(meth).bind_call(obj, *args, &block)
  end
  # :startdoc:

  if defined? ::Ractor
    class << self
      # Returns the sharing detection flag as a boolean value.
      # It is false (nil) by default.
      def sharing_detection
        Ractor.current[:pp_sharing_detection]
      end
      # Sets the sharing detection flag to b.
      def sharing_detection=(b)
        Ractor.current[:pp_sharing_detection] = b
      end
    end
  else
    @sharing_detection = false
    class << self
      # Returns the sharing detection flag as a boolean value.
      # It is false by default.
      attr_accessor :sharing_detection
    end
  end

  module PPMethods

    # Yields to a block
    # and preserves the previous set of objects being printed.
    def guard_inspect_key
      if Thread.current[:__recursive_key__] == nil
        Thread.current[:__recursive_key__] = {}.compare_by_identity
      end

      if Thread.current[:__recursive_key__][:inspect] == nil
        Thread.current[:__recursive_key__][:inspect] = {}.compare_by_identity
      end

      save = Thread.current[:__recursive_key__][:inspect]

      begin
        Thread.current[:__recursive_key__][:inspect] = {}.compare_by_identity
        yield
      ensure
        Thread.current[:__recursive_key__][:inspect] = save
      end
    end

    # Check whether the object_id +id+ is in the current buffer of objects
    # to be pretty printed. Used to break cycles in chains of objects to be
    # pretty printed.
    def check_inspect_key(id)
      Thread.current[:__recursive_key__] &&
      Thread.current[:__recursive_key__][:inspect] &&
      Thread.current[:__recursive_key__][:inspect].include?(id)
    end

    # Adds the object_id +id+ to the set of objects being pretty printed, so
    # as to not repeat objects.
    def push_inspect_key(id)
      Thread.current[:__recursive_key__][:inspect][id] = true
    end

    # Removes an object from the set of objects being pretty printed.
    def pop_inspect_key(id)
      Thread.current[:__recursive_key__][:inspect].delete id
    end

    # Adds +obj+ to the pretty printing buffer
    # using Object#pretty_print or Object#pretty_print_cycle.
    #
    # Object#pretty_print_cycle is used when +obj+ is already
    # printed, a.k.a the object reference chain has a cycle.
    def pp(obj)
      # If obj is a Delegator then use the object being delegated to for cycle
      # detection
      obj = obj.__getobj__ if defined?(::Delegator) and obj.is_a?(::Delegator)

      if check_inspect_key(obj)
        group {obj.pretty_print_cycle self}
        return
      end

      begin
        push_inspect_key(obj)
        group {obj.pretty_print self}
      ensure
        pop_inspect_key(obj) unless PP.sharing_detection
      end
    end

    # A convenience method which is same as follows:
    #
    #   group(1, '#<' + obj.class.name, '>') { ... }
    def object_group(obj, &block) # :yield:
      group(1, '#<' + obj.class.name, '>', &block)
    end

    # A convenience method, like object_group, but also reformats the Object's
    # object_id.
    def object_address_group(obj, &block)
      str = Kernel.instance_method(:to_s).bind_call(obj)
      str.chomp!('>')
      group(1, str, '>', &block)
    end

    # A convenience method which is same as follows:
    #
    #   text ','
    #   breakable
    def comma_breakable
      text ','
      breakable
    end

    # Adds a separated list.
    # The list is separated by comma with breakable space, by default.
    #
    # #seplist iterates the +list+ using +iter_method+.
    # It yields each object to the block given for #seplist.
    # The procedure +separator_proc+ is called between each yields.
    #
    # If the iteration is zero times, +separator_proc+ is not called at all.
    #
    # If +separator_proc+ is nil or not given,
    # +lambda { comma_breakable }+ is used.
    # If +iter_method+ is not given, :each is used.
    #
    # For example, following 3 code fragments has similar effect.
    #
    #   q.seplist([1,2,3]) {|v| xxx v }
    #
    #   q.seplist([1,2,3], lambda { q.comma_breakable }, :each) {|v| xxx v }
    #
    #   xxx 1
    #   q.comma_breakable
    #   xxx 2
    #   q.comma_breakable
    #   xxx 3
    def seplist(list, sep=nil, iter_method=:each) # :yield: element
      sep ||= lambda { comma_breakable }
      first = true
      list.__send__(iter_method) {|*v|
        if first
          first = false
        else
          sep.call
        end
        RUBY_VERSION >= "3.0" ? yield(*v, **{}) : yield(*v)
      }
    end

    # A present standard failsafe for pretty printing any given Object
    def pp_object(obj)
      object_address_group(obj) {
        seplist(obj.pretty_print_instance_variables, lambda { text ',' }) {|v|
          breakable
          v = v.to_s if Symbol === v
          text v
          text '='
          group(1) {
            breakable ''
            pp(obj.instance_eval(v))
          }
        }
      }
    end

    # A pretty print for a Hash
    def pp_hash(obj)
      group(1, '{', '}') {
        seplist(obj, nil, :each_pair) {|k, v|
          group {
            pp k
            text '=>'
            group(1) {
              breakable ''
              pp v
            }
          }
        }
      }
    end
  end

  include PPMethods

  class SingleLine < PrettyPrint::SingleLine # :nodoc:
    include PPMethods
  end

  module ObjectMixin # :nodoc:
    # 1. specific pretty_print
    # 2. specific inspect
    # 3. generic pretty_print

    # A default pretty printing method for general objects.
    # It calls #pretty_print_instance_variables to list instance variables.
    #
    # If +self+ has a customized (redefined) #inspect method,
    # the result of self.inspect is used but it obviously has no
    # line break hints.
    #
    # This module provides predefined #pretty_print methods for some of
    # the most commonly used built-in classes for convenience.
    def pretty_print(q)
      umethod_method = Object.instance_method(:method)
      begin
        inspect_method = umethod_method.bind_call(self, :inspect)
      rescue NameError
      end
      if inspect_method && inspect_method.owner != Kernel
        q.text self.inspect
      elsif !inspect_method && self.respond_to?(:inspect)
        q.text self.inspect
      else
        q.pp_object(self)
      end
    end

    # A default pretty printing method for general objects that are
    # detected as part of a cycle.
    def pretty_print_cycle(q)
      q.object_address_group(self) {
        q.breakable
        q.text '...'
      }
    end

    # Returns a sorted array of instance variable names.
    #
    # This method should return an array of names of instance variables as symbols or strings as:
    # +[:@a, :@b]+.
    def pretty_print_instance_variables
      instance_variables.sort
    end

    # Is #inspect implementation using #pretty_print.
    # If you implement #pretty_print, it can be used as follows.
    #
    #   alias inspect pretty_print_inspect
    #
    # However, doing this requires that every class that #inspect is called on
    # implement #pretty_print, or a RuntimeError will be raised.
    def pretty_print_inspect
      if Object.instance_method(:method).bind_call(self, :pretty_print).owner == PP::ObjectMixin
        raise "pretty_print is not overridden for #{self.class}"
      end
      PP.singleline_pp(self, ''.dup)
    end
  end
end

class Array # :nodoc:
  def pretty_print(q) # :nodoc:
    q.group(1, '[', ']') {
      q.seplist(self) {|v|
        q.pp v
      }
    }
  end

  def pretty_print_cycle(q) # :nodoc:
    q.text(empty? ? '[]' : '[...]')
  end
end

class Hash # :nodoc:
  def pretty_print(q) # :nodoc:
    q.pp_hash self
  end

  def pretty_print_cycle(q) # :nodoc:
    q.text(empty? ? '{}' : '{...}')
  end
end

class << ENV # :nodoc:
  def pretty_print(q) # :nodoc:
    h = {}
    ENV.keys.sort.each {|k|
      h[k] = ENV[k]
    }
    q.pp_hash h
  end
end

class Struct # :nodoc:
  def pretty_print(q) # :nodoc:
    q.group(1, sprintf("#<struct %s", PP.mcall(self, Kernel, :class).name), '>') {
      q.seplist(PP.mcall(self, Struct, :members), lambda { q.text "," }) {|member|
        q.breakable
        q.text member.to_s
        q.text '='
        q.group(1) {
          q.breakable ''
          q.pp self[member]
        }
      }
    }
  end

  def pretty_print_cycle(q) # :nodoc:
    q.text sprintf("#<struct %s:...>", PP.mcall(self, Kernel, :class).name)
  end
end

class Range # :nodoc:
  def pretty_print(q) # :nodoc:
    q.pp self.begin
    q.breakable ''
    q.text(self.exclude_end? ? '...' : '..')
    q.breakable ''
    q.pp self.end if self.end
  end
end

class String # :nodoc:
  def pretty_print(q) # :nodoc:
    lines = self.lines
    if lines.size > 1
      q.group(0, '', '') do
        q.seplist(lines, lambda { q.text ' +'; q.breakable }) do |v|
          q.pp v
        end
      end
    else
      q.text inspect
    end
  end
end

class File < IO # :nodoc:
  class Stat # :nodoc:
    def pretty_print(q) # :nodoc:
      require 'etc.so'
      q.object_group(self) {
        q.breakable
        q.text sprintf("dev=0x%x", self.dev); q.comma_breakable
        q.text "ino="; q.pp self.ino; q.comma_breakable
        q.group {
          m = self.mode
          q.text sprintf("mode=0%o", m)
          q.breakable
          q.text sprintf("(%s %c%c%c%c%c%c%c%c%c)",
            self.ftype,
            (m & 0400 == 0 ? ?- : ?r),
            (m & 0200 == 0 ? ?- : ?w),
            (m & 0100 == 0 ? (m & 04000 == 0 ? ?- : ?S) :
                             (m & 04000 == 0 ? ?x : ?s)),
            (m & 0040 == 0 ? ?- : ?r),
            (m & 0020 == 0 ? ?- : ?w),
            (m & 0010 == 0 ? (m & 02000 == 0 ? ?- : ?S) :
                             (m & 02000 == 0 ? ?x : ?s)),
            (m & 0004 == 0 ? ?- : ?r),
            (m & 0002 == 0 ? ?- : ?w),
            (m & 0001 == 0 ? (m & 01000 == 0 ? ?- : ?T) :
                             (m & 01000 == 0 ? ?x : ?t)))
        }
        q.comma_breakable
        q.text "nlink="; q.pp self.nlink; q.comma_breakable
        q.group {
          q.text "uid="; q.pp self.uid
          begin
            pw = Etc.getpwuid(self.uid)
          rescue ArgumentError
          end
          if pw
            q.breakable; q.text "(#{pw.name})"
          end
        }
        q.comma_breakable
        q.group {
          q.text "gid="; q.pp self.gid
          begin
            gr = Etc.getgrgid(self.gid)
          rescue ArgumentError
          end
          if gr
            q.breakable; q.text "(#{gr.name})"
          end
        }
        q.comma_breakable
        q.group {
          q.text sprintf("rdev=0x%x", self.rdev)
          if self.rdev_major && self.rdev_minor
            q.breakable
            q.text sprintf('(%d, %d)', self.rdev_major, self.rdev_minor)
          end
        }
        q.comma_breakable
        q.text "size="; q.pp self.size; q.comma_breakable
        q.text "blksize="; q.pp self.blksize; q.comma_breakable
        q.text "blocks="; q.pp self.blocks; q.comma_breakable
        q.group {
          t = self.atime
          q.text "atime="; q.pp t
          q.breakable; q.text "(#{t.tv_sec})"
        }
        q.comma_breakable
        q.group {
          t = self.mtime
          q.text "mtime="; q.pp t
          q.breakable; q.text "(#{t.tv_sec})"
        }
        q.comma_breakable
        q.group {
          t = self.ctime
          q.text "ctime="; q.pp t
          q.breakable; q.text "(#{t.tv_sec})"
        }
      }
    end
  end
end

class MatchData # :nodoc:
  def pretty_print(q) # :nodoc:
    nc = []
    self.regexp.named_captures.each {|name, indexes|
      indexes.each {|i| nc[i] = name }
    }
    q.object_group(self) {
      q.breakable
      q.seplist(0...self.size, lambda { q.breakable }) {|i|
        if i == 0
          q.pp self[i]
        else
          if nc[i]
            q.text nc[i]
          else
            q.pp i
          end
          q.text ':'
          q.pp self[i]
        end
      }
    }
  end
end

class RubyVM::AbstractSyntaxTree::Node
  def pretty_print_children(q, names = [])
    children.zip(names) do |c, n|
      if n
        q.breakable
        q.text "#{n}:"
      end
      q.group(2) do
        q.breakable
        q.pp c
      end
    end
  end

  def pretty_print(q)
    q.group(1, "(#{type}@#{first_lineno}:#{first_column}-#{last_lineno}:#{last_column}", ")") {
      case type
      when :SCOPE
        pretty_print_children(q, %w"tbl args body")
      when :ARGS
        pretty_print_children(q, %w[pre_num pre_init opt first_post post_num post_init rest kw kwrest block])
      when :DEFN
        pretty_print_children(q, %w[mid body])
      when :ARYPTN
        pretty_print_children(q, %w[const pre rest post])
      when :HSHPTN
        pretty_print_children(q, %w[const kw kwrest])
      else
        pretty_print_children(q)
      end
    }
  end
end

class Object < BasicObject # :nodoc:
  include PP::ObjectMixin
end

[Numeric, Symbol, FalseClass, TrueClass, NilClass, Module].each {|c|
  c.class_eval {
    def pretty_print_cycle(q)
      q.text inspect
    end
  }
}

[Numeric, FalseClass, TrueClass, Module].each {|c|
  c.class_eval {
    def pretty_print(q)
      q.text inspect
    end
  }
}

module Kernel
  # Returns a pretty printed object as a string.
  #
  # In order to use this method you must first require the PP module:
  #
  #   require 'pp'
  #
  # See the PP module for more information.
  def pretty_inspect
    PP.pp(self, ''.dup)
  end

  # prints arguments in pretty form.
  #
  # pp returns argument(s).
  def pp(*objs)
    objs.each {|obj|
      PP.pp(obj)
    }
    objs.size <= 1 ? objs.first : objs
  end
  module_function :pp
end
# frozen_string_literal: true
#--
# Methods for generating HTML, parsing CGI-related parameters, and
# generating HTTP responses.
#++
class CGI
  unless const_defined?(:Util)
    module Util
      @@accept_charset = "UTF-8" # :nodoc:
    end
    include Util
    extend Util
  end

  $CGI_ENV = ENV    # for FCGI support

  # String for carriage return
  CR  = "\015"

  # String for linefeed
  LF  = "\012"

  # Standard internet newline sequence
  EOL = CR + LF

  REVISION = '$Id$' #:nodoc:

  # Whether processing will be required in binary vs text
  NEEDS_BINMODE = File::BINARY != 0

  # Path separators in different environments.
  PATH_SEPARATOR = {'UNIX'=>'/', 'WINDOWS'=>'\\', 'MACINTOSH'=>':'}

  # HTTP status codes.
  HTTP_STATUS = {
    "OK"                  => "200 OK",
    "PARTIAL_CONTENT"     => "206 Partial Content",
    "MULTIPLE_CHOICES"    => "300 Multiple Choices",
    "MOVED"               => "301 Moved Permanently",
    "REDIRECT"            => "302 Found",
    "NOT_MODIFIED"        => "304 Not Modified",
    "BAD_REQUEST"         => "400 Bad Request",
    "AUTH_REQUIRED"       => "401 Authorization Required",
    "FORBIDDEN"           => "403 Forbidden",
    "NOT_FOUND"           => "404 Not Found",
    "METHOD_NOT_ALLOWED"  => "405 Method Not Allowed",
    "NOT_ACCEPTABLE"      => "406 Not Acceptable",
    "LENGTH_REQUIRED"     => "411 Length Required",
    "PRECONDITION_FAILED" => "412 Precondition Failed",
    "SERVER_ERROR"        => "500 Internal Server Error",
    "NOT_IMPLEMENTED"     => "501 Method Not Implemented",
    "BAD_GATEWAY"         => "502 Bad Gateway",
    "VARIANT_ALSO_VARIES" => "506 Variant Also Negotiates"
  }

  # :startdoc:

  # Synonym for ENV.
  def env_table
    ENV
  end

  # Synonym for $stdin.
  def stdinput
    $stdin
  end

  # Synonym for $stdout.
  def stdoutput
    $stdout
  end

  private :env_table, :stdinput, :stdoutput

  # Create an HTTP header block as a string.
  #
  # :call-seq:
  #   http_header(content_type_string="text/html")
  #   http_header(headers_hash)
  #
  # Includes the empty line that ends the header block.
  #
  # +content_type_string+::
  #   If this form is used, this string is the <tt>Content-Type</tt>
  # +headers_hash+::
  #   A Hash of header values. The following header keys are recognized:
  #
  #   type:: The Content-Type header.  Defaults to "text/html"
  #   charset:: The charset of the body, appended to the Content-Type header.
  #   nph:: A boolean value.  If true, prepend protocol string and status
  #         code, and date; and sets default values for "server" and
  #         "connection" if not explicitly set.
  #   status::
  #     The HTTP status code as a String, returned as the Status header.  The
  #     values are:
  #
  #     OK:: 200 OK
  #     PARTIAL_CONTENT:: 206 Partial Content
  #     MULTIPLE_CHOICES:: 300 Multiple Choices
  #     MOVED:: 301 Moved Permanently
  #     REDIRECT:: 302 Found
  #     NOT_MODIFIED:: 304 Not Modified
  #     BAD_REQUEST:: 400 Bad Request
  #     AUTH_REQUIRED:: 401 Authorization Required
  #     FORBIDDEN:: 403 Forbidden
  #     NOT_FOUND:: 404 Not Found
  #     METHOD_NOT_ALLOWED:: 405 Method Not Allowed
  #     NOT_ACCEPTABLE:: 406 Not Acceptable
  #     LENGTH_REQUIRED:: 411 Length Required
  #     PRECONDITION_FAILED:: 412 Precondition Failed
  #     SERVER_ERROR:: 500 Internal Server Error
  #     NOT_IMPLEMENTED:: 501 Method Not Implemented
  #     BAD_GATEWAY:: 502 Bad Gateway
  #     VARIANT_ALSO_VARIES:: 506 Variant Also Negotiates
  #
  #   server:: The server software, returned as the Server header.
  #   connection:: The connection type, returned as the Connection header (for
  #                instance, "close".
  #   length:: The length of the content that will be sent, returned as the
  #            Content-Length header.
  #   language:: The language of the content, returned as the Content-Language
  #              header.
  #   expires:: The time on which the current content expires, as a +Time+
  #             object, returned as the Expires header.
  #   cookie::
  #     A cookie or cookies, returned as one or more Set-Cookie headers.  The
  #     value can be the literal string of the cookie; a CGI::Cookie object;
  #     an Array of literal cookie strings or Cookie objects; or a hash all of
  #     whose values are literal cookie strings or Cookie objects.
  #
  #     These cookies are in addition to the cookies held in the
  #     @output_cookies field.
  #
  #   Other headers can also be set; they are appended as key: value.
  #
  # Examples:
  #
  #   http_header
  #     # Content-Type: text/html
  #
  #   http_header("text/plain")
  #     # Content-Type: text/plain
  #
  #   http_header("nph"        => true,
  #               "status"     => "OK",  # == "200 OK"
  #                 # "status"     => "200 GOOD",
  #               "server"     => ENV['SERVER_SOFTWARE'],
  #               "connection" => "close",
  #               "type"       => "text/html",
  #               "charset"    => "iso-2022-jp",
  #                 # Content-Type: text/html; charset=iso-2022-jp
  #               "length"     => 103,
  #               "language"   => "ja",
  #               "expires"    => Time.now + 30,
  #               "cookie"     => [cookie1, cookie2],
  #               "my_header1" => "my_value",
  #               "my_header2" => "my_value")
  #
  # This method does not perform charset conversion.
  def http_header(options='text/html')
    if options.is_a?(String)
      content_type = options
      buf = _header_for_string(content_type)
    elsif options.is_a?(Hash)
      if options.size == 1 && options.has_key?('type')
        content_type = options['type']
        buf = _header_for_string(content_type)
      else
        buf = _header_for_hash(options.dup)
      end
    else
      raise ArgumentError.new("expected String or Hash but got #{options.class}")
    end
    if defined?(MOD_RUBY)
      _header_for_modruby(buf)
      return ''
    else
      buf << EOL    # empty line of separator
      return buf
    end
  end # http_header()

  # This method is an alias for #http_header, when HTML5 tag maker is inactive.
  #
  # NOTE: use #http_header to create HTTP header blocks, this alias is only
  # provided for backwards compatibility.
  #
  # Using #header with the HTML5 tag maker will create a <header> element.
  alias :header :http_header

  def _no_crlf_check(str)
    if str
      str = str.to_s
      raise "A HTTP status or header field must not include CR and LF" if str =~ /[\r\n]/
      str
    else
      nil
    end
  end
  private :_no_crlf_check

  def _header_for_string(content_type) #:nodoc:
    buf = ''.dup
    if nph?()
      buf << "#{_no_crlf_check($CGI_ENV['SERVER_PROTOCOL']) || 'HTTP/1.0'} 200 OK#{EOL}"
      buf << "Date: #{CGI.rfc1123_date(Time.now)}#{EOL}"
      buf << "Server: #{_no_crlf_check($CGI_ENV['SERVER_SOFTWARE'])}#{EOL}"
      buf << "Connection: close#{EOL}"
    end
    buf << "Content-Type: #{_no_crlf_check(content_type)}#{EOL}"
    if @output_cookies
      @output_cookies.each {|cookie| buf << "Set-Cookie: #{_no_crlf_check(cookie)}#{EOL}" }
    end
    return buf
  end # _header_for_string
  private :_header_for_string

  def _header_for_hash(options)  #:nodoc:
    buf = ''.dup
    ## add charset to option['type']
    options['type'] ||= 'text/html'
    charset = options.delete('charset')
    options['type'] += "; charset=#{charset}" if charset
    ## NPH
    options.delete('nph') if defined?(MOD_RUBY)
    if options.delete('nph') || nph?()
      protocol = _no_crlf_check($CGI_ENV['SERVER_PROTOCOL']) || 'HTTP/1.0'
      status = options.delete('status')
      status = HTTP_STATUS[status] || _no_crlf_check(status) || '200 OK'
      buf << "#{protocol} #{status}#{EOL}"
      buf << "Date: #{CGI.rfc1123_date(Time.now)}#{EOL}"
      options['server'] ||= $CGI_ENV['SERVER_SOFTWARE'] || ''
      options['connection'] ||= 'close'
    end
    ## common headers
    status = options.delete('status')
    buf << "Status: #{HTTP_STATUS[status] || _no_crlf_check(status)}#{EOL}" if status
    server = options.delete('server')
    buf << "Server: #{_no_crlf_check(server)}#{EOL}" if server
    connection = options.delete('connection')
    buf << "Connection: #{_no_crlf_check(connection)}#{EOL}" if connection
    type = options.delete('type')
    buf << "Content-Type: #{_no_crlf_check(type)}#{EOL}" #if type
    length = options.delete('length')
    buf << "Content-Length: #{_no_crlf_check(length)}#{EOL}" if length
    language = options.delete('language')
    buf << "Content-Language: #{_no_crlf_check(language)}#{EOL}" if language
    expires = options.delete('expires')
    buf << "Expires: #{CGI.rfc1123_date(expires)}#{EOL}" if expires
    ## cookie
    if cookie = options.delete('cookie')
      case cookie
      when String, Cookie
        buf << "Set-Cookie: #{_no_crlf_check(cookie)}#{EOL}"
      when Array
        arr = cookie
        arr.each {|c| buf << "Set-Cookie: #{_no_crlf_check(c)}#{EOL}" }
      when Hash
        hash = cookie
        hash.each_value {|c| buf << "Set-Cookie: #{_no_crlf_check(c)}#{EOL}" }
      end
    end
    if @output_cookies
      @output_cookies.each {|c| buf << "Set-Cookie: #{_no_crlf_check(c)}#{EOL}" }
    end
    ## other headers
    options.each do |key, value|
      buf << "#{_no_crlf_check(key)}: #{_no_crlf_check(value)}#{EOL}"
    end
    return buf
  end # _header_for_hash
  private :_header_for_hash

  def nph?  #:nodoc:
    return /IIS\/(\d+)/ =~ $CGI_ENV['SERVER_SOFTWARE'] && $1.to_i < 5
  end

  def _header_for_modruby(buf)  #:nodoc:
    request = Apache::request
    buf.scan(/([^:]+): (.+)#{EOL}/o) do |name, value|
      $stderr.printf("name:%s value:%s\n", name, value) if $DEBUG
      case name
      when 'Set-Cookie'
        request.headers_out.add(name, value)
      when /^status$/i
        request.status_line = value
        request.status = value.to_i
      when /^content-type$/i
        request.content_type = value
      when /^content-encoding$/i
        request.content_encoding = value
      when /^location$/i
        request.status = 302 if request.status == 200
        request.headers_out[name] = value
      else
        request.headers_out[name] = value
      end
    end
    request.send_http_header
    return ''
  end
  private :_header_for_modruby

  # Print an HTTP header and body to $DEFAULT_OUTPUT ($>)
  #
  # :call-seq:
  #   cgi.out(content_type_string='text/html')
  #   cgi.out(headers_hash)
  #
  # +content_type_string+::
  #   If a string is passed, it is assumed to be the content type.
  # +headers_hash+::
  #   This is a Hash of headers, similar to that used by #http_header.
  # +block+::
  #   A block is required and should evaluate to the body of the response.
  #
  # <tt>Content-Length</tt> is automatically calculated from the size of
  # the String returned by the content block.
  #
  # If <tt>ENV['REQUEST_METHOD'] == "HEAD"</tt>, then only the header
  # is output (the content block is still required, but it is ignored).
  #
  # If the charset is "iso-2022-jp" or "euc-jp" or "shift_jis" then the
  # content is converted to this charset, and the language is set to "ja".
  #
  # Example:
  #
  #   cgi = CGI.new
  #   cgi.out{ "string" }
  #     # Content-Type: text/html
  #     # Content-Length: 6
  #     #
  #     # string
  #
  #   cgi.out("text/plain") { "string" }
  #     # Content-Type: text/plain
  #     # Content-Length: 6
  #     #
  #     # string
  #
  #   cgi.out("nph"        => true,
  #           "status"     => "OK",  # == "200 OK"
  #           "server"     => ENV['SERVER_SOFTWARE'],
  #           "connection" => "close",
  #           "type"       => "text/html",
  #           "charset"    => "iso-2022-jp",
  #             # Content-Type: text/html; charset=iso-2022-jp
  #           "language"   => "ja",
  #           "expires"    => Time.now + (3600 * 24 * 30),
  #           "cookie"     => [cookie1, cookie2],
  #           "my_header1" => "my_value",
  #           "my_header2" => "my_value") { "string" }
  #      # HTTP/1.1 200 OK
  #      # Date: Sun, 15 May 2011 17:35:54 GMT
  #      # Server: Apache 2.2.0
  #      # Connection: close
  #      # Content-Type: text/html; charset=iso-2022-jp
  #      # Content-Length: 6
  #      # Content-Language: ja
  #      # Expires: Tue, 14 Jun 2011 17:35:54 GMT
  #      # Set-Cookie: foo
  #      # Set-Cookie: bar
  #      # my_header1: my_value
  #      # my_header2: my_value
  #      #
  #      # string
  def out(options = "text/html") # :yield:

    options = { "type" => options } if options.kind_of?(String)
    content = yield
    options["length"] = content.bytesize.to_s
    output = stdoutput
    output.binmode if defined? output.binmode
    output.print http_header(options)
    output.print content unless "HEAD" == env_table['REQUEST_METHOD']
  end


  # Print an argument or list of arguments to the default output stream
  #
  #   cgi = CGI.new
  #   cgi.print    # default:  cgi.print == $DEFAULT_OUTPUT.print
  def print(*options)
    stdoutput.print(*options)
  end

  # Parse an HTTP query string into a hash of key=>value pairs.
  #
  #   params = CGI.parse("query_string")
  #     # {"name1" => ["value1", "value2", ...],
  #     #  "name2" => ["value1", "value2", ...], ... }
  #
  def self.parse(query)
    params = {}
    query.split(/[&;]/).each do |pairs|
      key, value = pairs.split('=',2).collect{|v| CGI.unescape(v) }

      next unless key

      params[key] ||= []
      params[key].push(value) if value
    end

    params.default=[].freeze
    params
  end

  # Maximum content length of post data
  ##MAX_CONTENT_LENGTH  = 2 * 1024 * 1024

  # Maximum number of request parameters when multipart
  MAX_MULTIPART_COUNT = 128

  # Mixin module that provides the following:
  #
  # 1. Access to the CGI environment variables as methods.  See
  #    documentation to the CGI class for a list of these variables.  The
  #    methods are exposed by removing the leading +HTTP_+ (if it exists) and
  #    downcasing the name.  For example, +auth_type+ will return the
  #    environment variable +AUTH_TYPE+, and +accept+ will return the value
  #    for +HTTP_ACCEPT+.
  #
  # 2. Access to cookies, including the cookies attribute.
  #
  # 3. Access to parameters, including the params attribute, and overloading
  #    #[] to perform parameter value lookup by key.
  #
  # 4. The initialize_query method, for initializing the above
  #    mechanisms, handling multipart forms, and allowing the
  #    class to be used in "offline" mode.
  #
  module QueryExtension

    %w[ CONTENT_LENGTH SERVER_PORT ].each do |env|
      define_method(env.delete_prefix('HTTP_').downcase) do
        (val = env_table[env]) && Integer(val)
      end
    end

    %w[ AUTH_TYPE CONTENT_TYPE GATEWAY_INTERFACE PATH_INFO
        PATH_TRANSLATED QUERY_STRING REMOTE_ADDR REMOTE_HOST
        REMOTE_IDENT REMOTE_USER REQUEST_METHOD SCRIPT_NAME
        SERVER_NAME SERVER_PROTOCOL SERVER_SOFTWARE

        HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING
        HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM HTTP_HOST
        HTTP_NEGOTIATE HTTP_PRAGMA HTTP_REFERER HTTP_USER_AGENT ].each do |env|
      define_method(env.delete_prefix('HTTP_').downcase) do
        env_table[env]
      end
    end

    # Get the raw cookies as a string.
    def raw_cookie
      env_table["HTTP_COOKIE"]
    end

    # Get the raw RFC2965 cookies as a string.
    def raw_cookie2
      env_table["HTTP_COOKIE2"]
    end

    # Get the cookies as a hash of cookie-name=>Cookie pairs.
    attr_accessor :cookies

    # Get the parameters as a hash of name=>values pairs, where
    # values is an Array.
    attr_reader :params

    # Get the uploaded files as a hash of name=>values pairs
    attr_reader :files

    # Set all the parameters.
    def params=(hash)
      @params.clear
      @params.update(hash)
    end

    ##
    # Parses multipart form elements according to
    #   http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
    #
    # Returns a hash of multipart form parameters with bodies of type StringIO or
    # Tempfile depending on whether the multipart form element exceeds 10 KB
    #
    #   params[name => body]
    #
    def read_multipart(boundary, content_length)
      ## read first boundary
      stdin = stdinput
      first_line = "--#{boundary}#{EOL}"
      content_length -= first_line.bytesize
      status = stdin.read(first_line.bytesize)
      raise EOFError.new("no content body")  unless status
      raise EOFError.new("bad content body") unless first_line == status
      ## parse and set params
      params = {}
      @files = {}
      boundary_rexp = /--#{Regexp.quote(boundary)}(#{EOL}|--)/
      boundary_size = "#{EOL}--#{boundary}#{EOL}".bytesize
      buf = ''.dup
      bufsize = 10 * 1024
      max_count = MAX_MULTIPART_COUNT
      n = 0
      tempfiles = []
      while true
        (n += 1) < max_count or raise StandardError.new("too many parameters.")
        ## create body (StringIO or Tempfile)
        body = create_body(bufsize < content_length)
        tempfiles << body if defined?(Tempfile) && body.kind_of?(Tempfile)
        class << body
          if method_defined?(:path)
            alias local_path path
          else
            def local_path
              nil
            end
          end
          attr_reader :original_filename, :content_type
        end
        ## find head and boundary
        head = nil
        separator = EOL * 2
        until head && matched = boundary_rexp.match(buf)
          if !head && pos = buf.index(separator)
            len  = pos + EOL.bytesize
            head = buf[0, len]
            buf  = buf[(pos+separator.bytesize)..-1]
          else
            if head && buf.size > boundary_size
              len = buf.size - boundary_size
              body.print(buf[0, len])
              buf[0, len] = ''
            end
            c = stdin.read(bufsize < content_length ? bufsize : content_length)
            raise EOFError.new("bad content body") if c.nil? || c.empty?
            buf << c
            content_length -= c.bytesize
          end
        end
        ## read to end of boundary
        m = matched
        len = m.begin(0)
        s = buf[0, len]
        if s =~ /(\r?\n)\z/
          s = buf[0, len - $1.bytesize]
        end
        body.print(s)
        buf = buf[m.end(0)..-1]
        boundary_end = m[1]
        content_length = -1 if boundary_end == '--'
        ## reset file cursor position
        body.rewind
        ## original filename
        /Content-Disposition:.* filename=(?:"(.*?)"|([^;\r\n]*))/i.match(head)
        filename = $1 || $2 || ''.dup
        filename = CGI.unescape(filename) if unescape_filename?()
        body.instance_variable_set(:@original_filename, filename)
        ## content type
        /Content-Type: (.*)/i.match(head)
        (content_type = $1 || ''.dup).chomp!
        body.instance_variable_set(:@content_type, content_type)
        ## query parameter name
        /Content-Disposition:.* name=(?:"(.*?)"|([^;\r\n]*))/i.match(head)
        name = $1 || $2 || ''
        if body.original_filename.empty?
          value=body.read.dup.force_encoding(@accept_charset)
          body.close! if defined?(Tempfile) && body.kind_of?(Tempfile)
          (params[name] ||= []) << value
          unless value.valid_encoding?
            if @accept_charset_error_block
              @accept_charset_error_block.call(name,value)
            else
              raise InvalidEncoding,"Accept-Charset encoding error"
            end
          end
          class << params[name].last;self;end.class_eval do
            define_method(:read){self}
            define_method(:original_filename){""}
            define_method(:content_type){""}
          end
        else
          (params[name] ||= []) << body
          @files[name]=body
        end
        ## break loop
        break if content_length == -1
      end
      raise EOFError, "bad boundary end of body part" unless boundary_end =~ /--/
      params.default = []
      params
    rescue Exception
      if tempfiles
        tempfiles.each {|t|
          if t.path
            t.close!
          end
        }
      end
      raise
    end # read_multipart
    private :read_multipart
    def create_body(is_large)  #:nodoc:
      if is_large
        require 'tempfile'
        body = Tempfile.new('CGI', encoding: Encoding::ASCII_8BIT)
      else
        begin
          require 'stringio'
          body = StringIO.new("".b)
        rescue LoadError
          require 'tempfile'
          body = Tempfile.new('CGI', encoding: Encoding::ASCII_8BIT)
        end
      end
      body.binmode if defined? body.binmode
      return body
    end
    def unescape_filename?  #:nodoc:
      user_agent = $CGI_ENV['HTTP_USER_AGENT']
      return false unless user_agent
      return /Mac/i.match(user_agent) && /Mozilla/i.match(user_agent) && !/MSIE/i.match(user_agent)
    end

    # offline mode. read name=value pairs on standard input.
    def read_from_cmdline
      require "shellwords"

      string = unless ARGV.empty?
        ARGV.join(' ')
      else
        if STDIN.tty?
          STDERR.print(
            %|(offline mode: enter name=value pairs on standard input)\n|
          )
        end
        array = readlines rescue nil
        if not array.nil?
            array.join(' ').gsub(/\n/n, '')
        else
            ""
        end
      end.gsub(/\\=/n, '%3D').gsub(/\\&/n, '%26')

      words = Shellwords.shellwords(string)

      if words.find{|x| /=/n.match(x) }
        words.join('&')
      else
        words.join('+')
      end
    end
    private :read_from_cmdline

    # A wrapper class to use a StringIO object as the body and switch
    # to a TempFile when the passed threshold is passed.
    # Initialize the data from the query.
    #
    # Handles multipart forms (in particular, forms that involve file uploads).
    # Reads query parameters in the @params field, and cookies into @cookies.
    def initialize_query()
      if ("POST" == env_table['REQUEST_METHOD']) and
        %r|\Amultipart/form-data.*boundary=\"?([^\";,]+)\"?| =~ env_table['CONTENT_TYPE']
        current_max_multipart_length = @max_multipart_length.respond_to?(:call) ? @max_multipart_length.call : @max_multipart_length
        raise StandardError.new("too large multipart data.") if env_table['CONTENT_LENGTH'].to_i > current_max_multipart_length
        boundary = $1.dup
        @multipart = true
        @params = read_multipart(boundary, Integer(env_table['CONTENT_LENGTH']))
      else
        @multipart = false
        @params = CGI.parse(
                    case env_table['REQUEST_METHOD']
                    when "GET", "HEAD"
                      if defined?(MOD_RUBY)
                        Apache::request.args or ""
                      else
                        env_table['QUERY_STRING'] or ""
                      end
                    when "POST"
                      stdinput.binmode if defined? stdinput.binmode
                      stdinput.read(Integer(env_table['CONTENT_LENGTH'])) or ''
                    else
                      read_from_cmdline
                    end.dup.force_encoding(@accept_charset)
                  )
        unless Encoding.find(@accept_charset) == Encoding::ASCII_8BIT
          @params.each do |key,values|
            values.each do |value|
              unless value.valid_encoding?
                if @accept_charset_error_block
                  @accept_charset_error_block.call(key,value)
                else
                  raise InvalidEncoding,"Accept-Charset encoding error"
                end
              end
            end
          end
        end
      end

      @cookies = CGI::Cookie.parse((env_table['HTTP_COOKIE'] or env_table['COOKIE']))
    end
    private :initialize_query

    # Returns whether the form contained multipart/form-data
    def multipart?
      @multipart
    end

    # Get the value for the parameter with a given key.
    #
    # If the parameter has multiple values, only the first will be
    # retrieved; use #params to get the array of values.
    def [](key)
      params = @params[key]
      return '' unless params
      value = params[0]
      if @multipart
        if value
          return value
        elsif defined? StringIO
          StringIO.new("".b)
        else
          Tempfile.new("CGI",encoding: Encoding::ASCII_8BIT)
        end
      else
        str = if value then value.dup else "" end
        str
      end
    end

    # Return all query parameter names as an array of String.
    def keys(*args)
      @params.keys(*args)
    end

    # Returns true if a given query string parameter exists.
    def has_key?(*args)
      @params.has_key?(*args)
    end
    alias key? has_key?
    alias include? has_key?

  end # QueryExtension

  # Exception raised when there is an invalid encoding detected
  class InvalidEncoding < Exception; end

  # @@accept_charset is default accept character set.
  # This default value default is "UTF-8"
  # If you want to change the default accept character set
  # when create a new CGI instance, set this:
  #
  #   CGI.accept_charset = "EUC-JP"
  #
  @@accept_charset="UTF-8" if false # needed for rdoc?

  # Return the accept character set for all new CGI instances.
  def self.accept_charset
    @@accept_charset
  end

  # Set the accept character set for all new CGI instances.
  def self.accept_charset=(accept_charset)
    @@accept_charset=accept_charset
  end

  # Return the accept character set for this CGI instance.
  attr_reader :accept_charset

  # @@max_multipart_length is the maximum length of multipart data.
  # The default value is 128 * 1024 * 1024 bytes
  #
  # The default can be set to something else in the CGI constructor,
  # via the :max_multipart_length key in the option hash.
  #
  # See CGI.new documentation.
  #
  @@max_multipart_length= 128 * 1024 * 1024

  # Create a new CGI instance.
  #
  # :call-seq:
  #   CGI.new(tag_maker) { block }
  #   CGI.new(options_hash = {}) { block }
  #
  #
  # <tt>tag_maker</tt>::
  #   This is the same as using the +options_hash+ form with the value <tt>{
  #   :tag_maker => tag_maker }</tt> Note that it is recommended to use the
  #   +options_hash+ form, since it also allows you specify the charset you
  #   will accept.
  # <tt>options_hash</tt>::
  #   A Hash that recognizes three options:
  #
  #   <tt>:accept_charset</tt>::
  #     specifies encoding of received query string.  If omitted,
  #     <tt>@@accept_charset</tt> is used.  If the encoding is not valid, a
  #     CGI::InvalidEncoding will be raised.
  #
  #     Example. Suppose <tt>@@accept_charset</tt> is "UTF-8"
  #
  #     when not specified:
  #
  #         cgi=CGI.new      # @accept_charset # => "UTF-8"
  #
  #     when specified as "EUC-JP":
  #
  #         cgi=CGI.new(:accept_charset => "EUC-JP") # => "EUC-JP"
  #
  #   <tt>:tag_maker</tt>::
  #     String that specifies which version of the HTML generation methods to
  #     use.  If not specified, no HTML generation methods will be loaded.
  #
  #     The following values are supported:
  #
  #     "html3":: HTML 3.x
  #     "html4":: HTML 4.0
  #     "html4Tr":: HTML 4.0 Transitional
  #     "html4Fr":: HTML 4.0 with Framesets
  #     "html5":: HTML 5
  #
  #   <tt>:max_multipart_length</tt>::
  #     Specifies maximum length of multipart data. Can be an Integer scalar or
  #     a lambda, that will be evaluated when the request is parsed. This
  #     allows more complex logic to be set when determining whether to accept
  #     multipart data (e.g. consult a registered users upload allowance)
  #
  #     Default is 128 * 1024 * 1024 bytes
  #
  #         cgi=CGI.new(:max_multipart_length => 268435456) # simple scalar
  #
  #         cgi=CGI.new(:max_multipart_length => -> {check_filesystem}) # lambda
  #
  # <tt>block</tt>::
  #   If provided, the block is called when an invalid encoding is
  #   encountered. For example:
  #
  #     encoding_errors={}
  #     cgi=CGI.new(:accept_charset=>"EUC-JP") do |name,value|
  #       encoding_errors[name] = value
  #     end
  #
  # Finally, if the CGI object is not created in a standard CGI call
  # environment (that is, it can't locate REQUEST_METHOD in its environment),
  # then it will run in "offline" mode.  In this mode, it reads its parameters
  # from the command line or (failing that) from standard input.  Otherwise,
  # cookies and other parameters are parsed automatically from the standard
  # CGI locations, which varies according to the REQUEST_METHOD.
  def initialize(options = {}, &block) # :yields: name, value
    @accept_charset_error_block = block_given? ? block : nil
    @options={
      :accept_charset=>@@accept_charset,
      :max_multipart_length=>@@max_multipart_length
    }
    case options
    when Hash
      @options.merge!(options)
    when String
      @options[:tag_maker]=options
    end
    @accept_charset=@options[:accept_charset]
    @max_multipart_length=@options[:max_multipart_length]
    if defined?(MOD_RUBY) && !ENV.key?("GATEWAY_INTERFACE")
      Apache.request.setup_cgi_env
    end

    extend QueryExtension
    @multipart = false

    initialize_query()  # set @params, @cookies
    @output_cookies = nil
    @output_hidden = nil

    case @options[:tag_maker]
    when "html3"
      require_relative 'html'
      extend Html3
      extend HtmlExtension
    when "html4"
      require_relative 'html'
      extend Html4
      extend HtmlExtension
    when "html4Tr"
      require_relative 'html'
      extend Html4Tr
      extend HtmlExtension
    when "html4Fr"
      require_relative 'html'
      extend Html4Tr
      extend Html4Fr
      extend HtmlExtension
    when "html5"
      require_relative 'html'
      extend Html5
      extend HtmlExtension
    end
  end

end   # class CGI
# frozen_string_literal: true
class CGI
  # Base module for HTML-generation mixins.
  #
  # Provides methods for code generation for tags following
  # the various DTD element types.
  module TagMaker # :nodoc:

    # Generate code for an element with required start and end tags.
    #
    #   - -
    def nn_element(element, attributes = {})
      s = nOE_element(element, attributes)
      if block_given?
        s << yield.to_s
      end
      s << "</#{element.upcase}>"
    end

    def nn_element_def(attributes = {}, &block)
      nn_element(__callee__, attributes, &block)
    end

    # Generate code for an empty element.
    #
    #   - O EMPTY
    def nOE_element(element, attributes = {})
      attributes={attributes=>nil} if attributes.kind_of?(String)
      s = "<#{element.upcase}".dup
      attributes.each do|name, value|
        next unless value
        s << " "
        s << CGI.escapeHTML(name.to_s)
        if value != true
          s << '="'
          s << CGI.escapeHTML(value.to_s)
          s << '"'
        end
      end
      s << ">"
    end

    def nOE_element_def(attributes = {}, &block)
      nOE_element(__callee__, attributes, &block)
    end


    # Generate code for an element for which the end (and possibly the
    # start) tag is optional.
    #
    #   O O or - O
    def nO_element(element, attributes = {})
      s = nOE_element(element, attributes)
      if block_given?
        s << yield.to_s
        s << "</#{element.upcase}>"
      end
      s
    end

    def nO_element_def(attributes = {}, &block)
      nO_element(__callee__, attributes, &block)
    end

  end # TagMaker


  # Mixin module providing HTML generation methods.
  #
  # For example,
  #   cgi.a("http://www.example.com") { "Example" }
  #     # => "<A HREF=\"http://www.example.com\">Example</A>"
  #
  # Modules Html3, Html4, etc., contain more basic HTML-generation methods
  # (+#title+, +#h1+, etc.).
  #
  # See class CGI for a detailed example.
  #
  module HtmlExtension


    # Generate an Anchor element as a string.
    #
    # +href+ can either be a string, giving the URL
    # for the HREF attribute, or it can be a hash of
    # the element's attributes.
    #
    # The body of the element is the string returned by the no-argument
    # block passed in.
    #
    #   a("http://www.example.com") { "Example" }
    #     # => "<A HREF=\"http://www.example.com\">Example</A>"
    #
    #   a("HREF" => "http://www.example.com", "TARGET" => "_top") { "Example" }
    #     # => "<A HREF=\"http://www.example.com\" TARGET=\"_top\">Example</A>"
    #
    def a(href = "") # :yield:
      attributes = if href.kind_of?(String)
                     { "HREF" => href }
                   else
                     href
                   end
      super(attributes)
    end

    # Generate a Document Base URI element as a String.
    #
    # +href+ can either by a string, giving the base URL for the HREF
    # attribute, or it can be a has of the element's attributes.
    #
    # The passed-in no-argument block is ignored.
    #
    #   base("http://www.example.com/cgi")
    #     # => "<BASE HREF=\"http://www.example.com/cgi\">"
    def base(href = "") # :yield:
      attributes = if href.kind_of?(String)
                     { "HREF" => href }
                   else
                     href
                   end
      super(attributes)
    end

    # Generate a BlockQuote element as a string.
    #
    # +cite+ can either be a string, give the URI for the source of
    # the quoted text, or a hash, giving all attributes of the element,
    # or it can be omitted, in which case the element has no attributes.
    #
    # The body is provided by the passed-in no-argument block
    #
    #   blockquote("http://www.example.com/quotes/foo.html") { "Foo!" }
    #     #=> "<BLOCKQUOTE CITE=\"http://www.example.com/quotes/foo.html\">Foo!</BLOCKQUOTE>
    def blockquote(cite = {})  # :yield:
      attributes = if cite.kind_of?(String)
                     { "CITE" => cite }
                   else
                     cite
                   end
      super(attributes)
    end


    # Generate a Table Caption element as a string.
    #
    # +align+ can be a string, giving the alignment of the caption
    # (one of top, bottom, left, or right).  It can be a hash of
    # all the attributes of the element.  Or it can be omitted.
    #
    # The body of the element is provided by the passed-in no-argument block.
    #
    #   caption("left") { "Capital Cities" }
    #     # => <CAPTION ALIGN=\"left\">Capital Cities</CAPTION>
    def caption(align = {}) # :yield:
      attributes = if align.kind_of?(String)
                     { "ALIGN" => align }
                   else
                     align
                   end
      super(attributes)
    end


    # Generate a Checkbox Input element as a string.
    #
    # The attributes of the element can be specified as three arguments,
    # +name+, +value+, and +checked+.  +checked+ is a boolean value;
    # if true, the CHECKED attribute will be included in the element.
    #
    # Alternatively, the attributes can be specified as a hash.
    #
    #   checkbox("name")
    #     # = checkbox("NAME" => "name")
    #
    #   checkbox("name", "value")
    #     # = checkbox("NAME" => "name", "VALUE" => "value")
    #
    #   checkbox("name", "value", true)
    #     # = checkbox("NAME" => "name", "VALUE" => "value", "CHECKED" => true)
    def checkbox(name = "", value = nil, checked = nil)
      attributes = if name.kind_of?(String)
                     { "TYPE" => "checkbox", "NAME" => name,
                       "VALUE" => value, "CHECKED" => checked }
                   else
                     name["TYPE"] = "checkbox"
                     name
                   end
      input(attributes)
    end

    # Generate a sequence of checkbox elements, as a String.
    #
    # The checkboxes will all have the same +name+ attribute.
    # Each checkbox is followed by a label.
    # There will be one checkbox for each value.  Each value
    # can be specified as a String, which will be used both
    # as the value of the VALUE attribute and as the label
    # for that checkbox.  A single-element array has the
    # same effect.
    #
    # Each value can also be specified as a three-element array.
    # The first element is the VALUE attribute; the second is the
    # label; and the third is a boolean specifying whether this
    # checkbox is CHECKED.
    #
    # Each value can also be specified as a two-element
    # array, by omitting either the value element (defaults
    # to the same as the label), or the boolean checked element
    # (defaults to false).
    #
    #   checkbox_group("name", "foo", "bar", "baz")
    #     # <INPUT TYPE="checkbox" NAME="name" VALUE="foo">foo
    #     # <INPUT TYPE="checkbox" NAME="name" VALUE="bar">bar
    #     # <INPUT TYPE="checkbox" NAME="name" VALUE="baz">baz
    #
    #   checkbox_group("name", ["foo"], ["bar", true], "baz")
    #     # <INPUT TYPE="checkbox" NAME="name" VALUE="foo">foo
    #     # <INPUT TYPE="checkbox" CHECKED NAME="name" VALUE="bar">bar
    #     # <INPUT TYPE="checkbox" NAME="name" VALUE="baz">baz
    #
    #   checkbox_group("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
    #     # <INPUT TYPE="checkbox" NAME="name" VALUE="1">Foo
    #     # <INPUT TYPE="checkbox" CHECKED NAME="name" VALUE="2">Bar
    #     # <INPUT TYPE="checkbox" NAME="name" VALUE="Baz">Baz
    #
    #   checkbox_group("NAME" => "name",
    #                    "VALUES" => ["foo", "bar", "baz"])
    #
    #   checkbox_group("NAME" => "name",
    #                    "VALUES" => [["foo"], ["bar", true], "baz"])
    #
    #   checkbox_group("NAME" => "name",
    #                    "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"])
    def checkbox_group(name = "", *values)
      if name.kind_of?(Hash)
        values = name["VALUES"]
        name = name["NAME"]
      end
      values.collect{|value|
        if value.kind_of?(String)
          checkbox(name, value) + value
        else
          if value[-1] == true || value[-1] == false
            checkbox(name, value[0],  value[-1]) +
            value[-2]
          else
            checkbox(name, value[0]) +
            value[-1]
          end
        end
      }.join
    end


    # Generate an File Upload Input element as a string.
    #
    # The attributes of the element can be specified as three arguments,
    # +name+, +size+, and +maxlength+.  +maxlength+ is the maximum length
    # of the file's _name_, not of the file's _contents_.
    #
    # Alternatively, the attributes can be specified as a hash.
    #
    # See #multipart_form() for forms that include file uploads.
    #
    #   file_field("name")
    #     # <INPUT TYPE="file" NAME="name" SIZE="20">
    #
    #   file_field("name", 40)
    #     # <INPUT TYPE="file" NAME="name" SIZE="40">
    #
    #   file_field("name", 40, 100)
    #     # <INPUT TYPE="file" NAME="name" SIZE="40" MAXLENGTH="100">
    #
    #   file_field("NAME" => "name", "SIZE" => 40)
    #     # <INPUT TYPE="file" NAME="name" SIZE="40">
    def file_field(name = "", size = 20, maxlength = nil)
      attributes = if name.kind_of?(String)
                     { "TYPE" => "file", "NAME" => name,
                       "SIZE" => size.to_s }
                   else
                     name["TYPE"] = "file"
                     name
                   end
      attributes["MAXLENGTH"] = maxlength.to_s if maxlength
      input(attributes)
    end


    # Generate a Form element as a string.
    #
    # +method+ should be either "get" or "post", and defaults to the latter.
    # +action+ defaults to the current CGI script name.  +enctype+
    # defaults to "application/x-www-form-urlencoded".
    #
    # Alternatively, the attributes can be specified as a hash.
    #
    # See also #multipart_form() for forms that include file uploads.
    #
    #   form{ "string" }
    #     # <FORM METHOD="post" ENCTYPE="application/x-www-form-urlencoded">string</FORM>
    #
    #   form("get") { "string" }
    #     # <FORM METHOD="get" ENCTYPE="application/x-www-form-urlencoded">string</FORM>
    #
    #   form("get", "url") { "string" }
    #     # <FORM METHOD="get" ACTION="url" ENCTYPE="application/x-www-form-urlencoded">string</FORM>
    #
    #   form("METHOD" => "post", "ENCTYPE" => "enctype") { "string" }
    #     # <FORM METHOD="post" ENCTYPE="enctype">string</FORM>
    def form(method = "post", action = script_name, enctype = "application/x-www-form-urlencoded")
      attributes = if method.kind_of?(String)
                     { "METHOD" => method, "ACTION" => action,
                       "ENCTYPE" => enctype }
                   else
                     unless method.has_key?("METHOD")
                       method["METHOD"] = "post"
                     end
                     unless method.has_key?("ENCTYPE")
                       method["ENCTYPE"] = enctype
                     end
                     method
                   end
      if block_given?
        body = yield
      else
        body = ""
      end
      if @output_hidden
        body << @output_hidden.collect{|k,v|
          "<INPUT TYPE=\"HIDDEN\" NAME=\"#{k}\" VALUE=\"#{v}\">"
        }.join
      end
      super(attributes){body}
    end

    # Generate a Hidden Input element as a string.
    #
    # The attributes of the element can be specified as two arguments,
    # +name+ and +value+.
    #
    # Alternatively, the attributes can be specified as a hash.
    #
    #   hidden("name")
    #     # <INPUT TYPE="hidden" NAME="name">
    #
    #   hidden("name", "value")
    #     # <INPUT TYPE="hidden" NAME="name" VALUE="value">
    #
    #   hidden("NAME" => "name", "VALUE" => "reset", "ID" => "foo")
    #     # <INPUT TYPE="hidden" NAME="name" VALUE="value" ID="foo">
    def hidden(name = "", value = nil)
      attributes = if name.kind_of?(String)
                     { "TYPE" => "hidden", "NAME" => name, "VALUE" => value }
                   else
                     name["TYPE"] = "hidden"
                     name
                   end
      input(attributes)
    end

    # Generate a top-level HTML element as a string.
    #
    # The attributes of the element are specified as a hash.  The
    # pseudo-attribute "PRETTY" can be used to specify that the generated
    # HTML string should be indented.  "PRETTY" can also be specified as
    # a string as the sole argument to this method.  The pseudo-attribute
    # "DOCTYPE", if given, is used as the leading DOCTYPE SGML tag; it
    # should include the entire text of this tag, including angle brackets.
    #
    # The body of the html element is supplied as a block.
    #
    #   html{ "string" }
    #     # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><HTML>string</HTML>
    #
    #   html("LANG" => "ja") { "string" }
    #     # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><HTML LANG="ja">string</HTML>
    #
    #   html("DOCTYPE" => false) { "string" }
    #     # <HTML>string</HTML>
    #
    #   html("DOCTYPE" => '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">') { "string" }
    #     # <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"><HTML>string</HTML>
    #
    #   html("PRETTY" => "  ") { "<BODY></BODY>" }
    #     # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
    #     # <HTML>
    #     #   <BODY>
    #     #   </BODY>
    #     # </HTML>
    #
    #   html("PRETTY" => "\t") { "<BODY></BODY>" }
    #     # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
    #     # <HTML>
    #     #         <BODY>
    #     #         </BODY>
    #     # </HTML>
    #
    #   html("PRETTY") { "<BODY></BODY>" }
    #     # = html("PRETTY" => "  ") { "<BODY></BODY>" }
    #
    #   html(if $VERBOSE then "PRETTY" end) { "HTML string" }
    #
    def html(attributes = {}) # :yield:
      if nil == attributes
        attributes = {}
      elsif "PRETTY" == attributes
        attributes = { "PRETTY" => true }
      end
      pretty = attributes.delete("PRETTY")
      pretty = "  " if true == pretty
      buf = "".dup

      if attributes.has_key?("DOCTYPE")
        if attributes["DOCTYPE"]
          buf << attributes.delete("DOCTYPE")
        else
          attributes.delete("DOCTYPE")
        end
      else
        buf << doctype
      end

      buf << super(attributes)

      if pretty
        CGI.pretty(buf, pretty)
      else
        buf
      end

    end

    # Generate an Image Button Input element as a string.
    #
    # +src+ is the URL of the image to use for the button.  +name+
    # is the input name.  +alt+ is the alternative text for the image.
    #
    # Alternatively, the attributes can be specified as a hash.
    #
    #   image_button("url")
    #     # <INPUT TYPE="image" SRC="url">
    #
    #   image_button("url", "name", "string")
    #     # <INPUT TYPE="image" SRC="url" NAME="name" ALT="string">
    #
    #   image_button("SRC" => "url", "ALT" => "string")
    #     # <INPUT TYPE="image" SRC="url" ALT="string">
    def image_button(src = "", name = nil, alt = nil)
      attributes = if src.kind_of?(String)
                     { "TYPE" => "image", "SRC" => src, "NAME" => name,
                       "ALT" => alt }
                   else
                     src["TYPE"] = "image"
                     src["SRC"] ||= ""
                     src
                   end
      input(attributes)
    end


    # Generate an Image element as a string.
    #
    # +src+ is the URL of the image.  +alt+ is the alternative text for
    # the image.  +width+ is the width of the image, and +height+ is
    # its height.
    #
    # Alternatively, the attributes can be specified as a hash.
    #
    #   img("src", "alt", 100, 50)
    #     # <IMG SRC="src" ALT="alt" WIDTH="100" HEIGHT="50">
    #
    #   img("SRC" => "src", "ALT" => "alt", "WIDTH" => 100, "HEIGHT" => 50)
    #     # <IMG SRC="src" ALT="alt" WIDTH="100" HEIGHT="50">
    def img(src = "", alt = "", width = nil, height = nil)
      attributes = if src.kind_of?(String)
                     { "SRC" => src, "ALT" => alt }
                   else
                     src
                   end
      attributes["WIDTH"] = width.to_s if width
      attributes["HEIGHT"] = height.to_s if height
      super(attributes)
    end


    # Generate a Form element with multipart encoding as a String.
    #
    # Multipart encoding is used for forms that include file uploads.
    #
    # +action+ is the action to perform.  +enctype+ is the encoding
    # type, which defaults to "multipart/form-data".
    #
    # Alternatively, the attributes can be specified as a hash.
    #
    #   multipart_form{ "string" }
    #     # <FORM METHOD="post" ENCTYPE="multipart/form-data">string</FORM>
    #
    #   multipart_form("url") { "string" }
    #     # <FORM METHOD="post" ACTION="url" ENCTYPE="multipart/form-data">string</FORM>
    def multipart_form(action = nil, enctype = "multipart/form-data")
      attributes = if action == nil
                     { "METHOD" => "post", "ENCTYPE" => enctype }
                   elsif action.kind_of?(String)
                     { "METHOD" => "post", "ACTION" => action,
                       "ENCTYPE" => enctype }
                   else
                     unless action.has_key?("METHOD")
                       action["METHOD"] = "post"
                     end
                     unless action.has_key?("ENCTYPE")
                       action["ENCTYPE"] = enctype
                     end
                     action
                   end
      if block_given?
        form(attributes){ yield }
      else
        form(attributes)
      end
    end


    # Generate a Password Input element as a string.
    #
    # +name+ is the name of the input field.  +value+ is its default
    # value.  +size+ is the size of the input field display.  +maxlength+
    # is the maximum length of the inputted password.
    #
    # Alternatively, attributes can be specified as a hash.
    #
    #   password_field("name")
    #     # <INPUT TYPE="password" NAME="name" SIZE="40">
    #
    #   password_field("name", "value")
    #     # <INPUT TYPE="password" NAME="name" VALUE="value" SIZE="40">
    #
    #   password_field("password", "value", 80, 200)
    #     # <INPUT TYPE="password" NAME="name" VALUE="value" SIZE="80" MAXLENGTH="200">
    #
    #   password_field("NAME" => "name", "VALUE" => "value")
    #     # <INPUT TYPE="password" NAME="name" VALUE="value">
    def password_field(name = "", value = nil, size = 40, maxlength = nil)
      attributes = if name.kind_of?(String)
                     { "TYPE" => "password", "NAME" => name,
                       "VALUE" => value, "SIZE" => size.to_s }
                   else
                     name["TYPE"] = "password"
                     name
                   end
      attributes["MAXLENGTH"] = maxlength.to_s if maxlength
      input(attributes)
    end

    # Generate a Select element as a string.
    #
    # +name+ is the name of the element.  The +values+ are the options that
    # can be selected from the Select menu.  Each value can be a String or
    # a one, two, or three-element Array.  If a String or a one-element
    # Array, this is both the value of that option and the text displayed for
    # it.  If a three-element Array, the elements are the option value, displayed
    # text, and a boolean value specifying whether this option starts as selected.
    # The two-element version omits either the option value (defaults to the same
    # as the display text) or the boolean selected specifier (defaults to false).
    #
    # The attributes and options can also be specified as a hash.  In this
    # case, options are specified as an array of values as described above,
    # with the hash key of "VALUES".
    #
    #   popup_menu("name", "foo", "bar", "baz")
    #     # <SELECT NAME="name">
    #     #   <OPTION VALUE="foo">foo</OPTION>
    #     #   <OPTION VALUE="bar">bar</OPTION>
    #     #   <OPTION VALUE="baz">baz</OPTION>
    #     # </SELECT>
    #
    #   popup_menu("name", ["foo"], ["bar", true], "baz")
    #     # <SELECT NAME="name">
    #     #   <OPTION VALUE="foo">foo</OPTION>
    #     #   <OPTION VALUE="bar" SELECTED>bar</OPTION>
    #     #   <OPTION VALUE="baz">baz</OPTION>
    #     # </SELECT>
    #
    #   popup_menu("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
    #     # <SELECT NAME="name">
    #     #   <OPTION VALUE="1">Foo</OPTION>
    #     #   <OPTION SELECTED VALUE="2">Bar</OPTION>
    #     #   <OPTION VALUE="Baz">Baz</OPTION>
    #     # </SELECT>
    #
    #   popup_menu("NAME" => "name", "SIZE" => 2, "MULTIPLE" => true,
    #               "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"])
    #     # <SELECT NAME="name" MULTIPLE SIZE="2">
    #     #   <OPTION VALUE="1">Foo</OPTION>
    #     #   <OPTION SELECTED VALUE="2">Bar</OPTION>
    #     #   <OPTION VALUE="Baz">Baz</OPTION>
    #     # </SELECT>
    def popup_menu(name = "", *values)

      if name.kind_of?(Hash)
        values   = name["VALUES"]
        size     = name["SIZE"].to_s if name["SIZE"]
        multiple = name["MULTIPLE"]
        name     = name["NAME"]
      else
        size = nil
        multiple = nil
      end

      select({ "NAME" => name, "SIZE" => size,
               "MULTIPLE" => multiple }){
        values.collect{|value|
          if value.kind_of?(String)
            option({ "VALUE" => value }){ value }
          else
            if value[value.size - 1] == true
              option({ "VALUE" => value[0], "SELECTED" => true }){
                value[value.size - 2]
              }
            else
              option({ "VALUE" => value[0] }){
                value[value.size - 1]
              }
            end
          end
        }.join
      }

    end

    # Generates a radio-button Input element.
    #
    # +name+ is the name of the input field.  +value+ is the value of
    # the field if checked.  +checked+ specifies whether the field
    # starts off checked.
    #
    # Alternatively, the attributes can be specified as a hash.
    #
    #   radio_button("name", "value")
    #     # <INPUT TYPE="radio" NAME="name" VALUE="value">
    #
    #   radio_button("name", "value", true)
    #     # <INPUT TYPE="radio" NAME="name" VALUE="value" CHECKED>
    #
    #   radio_button("NAME" => "name", "VALUE" => "value", "ID" => "foo")
    #     # <INPUT TYPE="radio" NAME="name" VALUE="value" ID="foo">
    def radio_button(name = "", value = nil, checked = nil)
      attributes = if name.kind_of?(String)
                     { "TYPE" => "radio", "NAME" => name,
                       "VALUE" => value, "CHECKED" => checked }
                   else
                     name["TYPE"] = "radio"
                     name
                   end
      input(attributes)
    end

    # Generate a sequence of radio button Input elements, as a String.
    #
    # This works the same as #checkbox_group().  However, it is not valid
    # to have more than one radiobutton in a group checked.
    #
    #   radio_group("name", "foo", "bar", "baz")
    #     # <INPUT TYPE="radio" NAME="name" VALUE="foo">foo
    #     # <INPUT TYPE="radio" NAME="name" VALUE="bar">bar
    #     # <INPUT TYPE="radio" NAME="name" VALUE="baz">baz
    #
    #   radio_group("name", ["foo"], ["bar", true], "baz")
    #     # <INPUT TYPE="radio" NAME="name" VALUE="foo">foo
    #     # <INPUT TYPE="radio" CHECKED NAME="name" VALUE="bar">bar
    #     # <INPUT TYPE="radio" NAME="name" VALUE="baz">baz
    #
    #   radio_group("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
    #     # <INPUT TYPE="radio" NAME="name" VALUE="1">Foo
    #     # <INPUT TYPE="radio" CHECKED NAME="name" VALUE="2">Bar
    #     # <INPUT TYPE="radio" NAME="name" VALUE="Baz">Baz
    #
    #   radio_group("NAME" => "name",
    #                 "VALUES" => ["foo", "bar", "baz"])
    #
    #   radio_group("NAME" => "name",
    #                 "VALUES" => [["foo"], ["bar", true], "baz"])
    #
    #   radio_group("NAME" => "name",
    #                 "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"])
    def radio_group(name = "", *values)
      if name.kind_of?(Hash)
        values = name["VALUES"]
        name = name["NAME"]
      end
      values.collect{|value|
        if value.kind_of?(String)
          radio_button(name, value) + value
        else
          if value[-1] == true || value[-1] == false
            radio_button(name, value[0],  value[-1]) +
            value[-2]
          else
            radio_button(name, value[0]) +
            value[-1]
          end
        end
      }.join
    end

    # Generate a reset button Input element, as a String.
    #
    # This resets the values on a form to their initial values.  +value+
    # is the text displayed on the button. +name+ is the name of this button.
    #
    # Alternatively, the attributes can be specified as a hash.
    #
    #   reset
    #     # <INPUT TYPE="reset">
    #
    #   reset("reset")
    #     # <INPUT TYPE="reset" VALUE="reset">
    #
    #   reset("VALUE" => "reset", "ID" => "foo")
    #     # <INPUT TYPE="reset" VALUE="reset" ID="foo">
    def reset(value = nil, name = nil)
      attributes = if (not value) or value.kind_of?(String)
                     { "TYPE" => "reset", "VALUE" => value, "NAME" => name }
                   else
                     value["TYPE"] = "reset"
                     value
                   end
      input(attributes)
    end

    alias scrolling_list popup_menu

    # Generate a submit button Input element, as a String.
    #
    # +value+ is the text to display on the button.  +name+ is the name
    # of the input.
    #
    # Alternatively, the attributes can be specified as a hash.
    #
    #   submit
    #     # <INPUT TYPE="submit">
    #
    #   submit("ok")
    #     # <INPUT TYPE="submit" VALUE="ok">
    #
    #   submit("ok", "button1")
    #     # <INPUT TYPE="submit" VALUE="ok" NAME="button1">
    #
    #   submit("VALUE" => "ok", "NAME" => "button1", "ID" => "foo")
    #     # <INPUT TYPE="submit" VALUE="ok" NAME="button1" ID="foo">
    def submit(value = nil, name = nil)
      attributes = if (not value) or value.kind_of?(String)
                     { "TYPE" => "submit", "VALUE" => value, "NAME" => name }
                   else
                     value["TYPE"] = "submit"
                     value
                   end
      input(attributes)
    end

    # Generate a text field Input element, as a String.
    #
    # +name+ is the name of the input field.  +value+ is its initial
    # value.  +size+ is the size of the input area.  +maxlength+
    # is the maximum length of input accepted.
    #
    # Alternatively, the attributes can be specified as a hash.
    #
    #   text_field("name")
    #     # <INPUT TYPE="text" NAME="name" SIZE="40">
    #
    #   text_field("name", "value")
    #     # <INPUT TYPE="text" NAME="name" VALUE="value" SIZE="40">
    #
    #   text_field("name", "value", 80)
    #     # <INPUT TYPE="text" NAME="name" VALUE="value" SIZE="80">
    #
    #   text_field("name", "value", 80, 200)
    #     # <INPUT TYPE="text" NAME="name" VALUE="value" SIZE="80" MAXLENGTH="200">
    #
    #   text_field("NAME" => "name", "VALUE" => "value")
    #     # <INPUT TYPE="text" NAME="name" VALUE="value">
    def text_field(name = "", value = nil, size = 40, maxlength = nil)
      attributes = if name.kind_of?(String)
                     { "TYPE" => "text", "NAME" => name, "VALUE" => value,
                       "SIZE" => size.to_s }
                   else
                     name["TYPE"] = "text"
                     name
                   end
      attributes["MAXLENGTH"] = maxlength.to_s if maxlength
      input(attributes)
    end

    # Generate a TextArea element, as a String.
    #
    # +name+ is the name of the textarea.  +cols+ is the number of
    # columns and +rows+ is the number of rows in the display.
    #
    # Alternatively, the attributes can be specified as a hash.
    #
    # The body is provided by the passed-in no-argument block
    #
    #   textarea("name")
    #      # = textarea("NAME" => "name", "COLS" => 70, "ROWS" => 10)
    #
    #   textarea("name", 40, 5)
    #      # = textarea("NAME" => "name", "COLS" => 40, "ROWS" => 5)
    def textarea(name = "", cols = 70, rows = 10)  # :yield:
      attributes = if name.kind_of?(String)
                     { "NAME" => name, "COLS" => cols.to_s,
                       "ROWS" => rows.to_s }
                   else
                     name
                   end
      super(attributes)
    end

  end # HtmlExtension


  # Mixin module for HTML version 3 generation methods.
  module Html3 # :nodoc:
    include TagMaker

    # The DOCTYPE declaration for this version of HTML
    def doctype
      %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">|
    end

    instance_method(:nn_element_def).tap do |m|
      # - -
      for element in %w[ A TT I B U STRIKE BIG SMALL SUB SUP EM STRONG
          DFN CODE SAMP KBD VAR CITE FONT ADDRESS DIV CENTER MAP
          APPLET PRE XMP LISTING DL OL UL DIR MENU SELECT TABLE TITLE
          STYLE SCRIPT H1 H2 H3 H4 H5 H6 TEXTAREA FORM BLOCKQUOTE
          CAPTION ]
        define_method(element.downcase, m)
      end
    end

    instance_method(:nOE_element_def).tap do |m|
      # - O EMPTY
      for element in %w[ IMG BASE BASEFONT BR AREA LINK PARAM HR INPUT
          ISINDEX META ]
        define_method(element.downcase, m)
      end
    end

    instance_method(:nO_element_def).tap do |m|
      # O O or - O
      for element in %w[ HTML HEAD BODY P PLAINTEXT DT DD LI OPTION TR
          TH TD ]
        define_method(element.downcase, m)
      end
    end

  end # Html3


  # Mixin module for HTML version 4 generation methods.
  module Html4 # :nodoc:
    include TagMaker

    # The DOCTYPE declaration for this version of HTML
    def doctype
      %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|
    end

    # Initialize the HTML generation methods for this version.
    # - -
    instance_method(:nn_element_def).tap do |m|
      for element in %w[ TT I B BIG SMALL EM STRONG DFN CODE SAMP KBD
        VAR CITE ABBR ACRONYM SUB SUP SPAN BDO ADDRESS DIV MAP OBJECT
        H1 H2 H3 H4 H5 H6 PRE Q INS DEL DL OL UL LABEL SELECT OPTGROUP
        FIELDSET LEGEND BUTTON TABLE TITLE STYLE SCRIPT NOSCRIPT
        TEXTAREA FORM A BLOCKQUOTE CAPTION ]
        define_method(element.downcase, m)
      end
    end

    # - O EMPTY
    instance_method(:nOE_element_def).tap do |m|
      for element in %w[ IMG BASE BR AREA LINK PARAM HR INPUT COL META ]
        define_method(element.downcase, m)
      end
    end

    # O O or - O
    instance_method(:nO_element_def).tap do |m|
      for element in %w[ HTML BODY P DT DD LI OPTION THEAD TFOOT TBODY
          COLGROUP TR TH TD HEAD ]
        define_method(element.downcase, m)
      end
    end

  end # Html4


  # Mixin module for HTML version 4 transitional generation methods.
  module Html4Tr # :nodoc:
    include TagMaker

    # The DOCTYPE declaration for this version of HTML
    def doctype
      %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|
    end

    # Initialise the HTML generation methods for this version.
    # - -
    instance_method(:nn_element_def).tap do |m|
      for element in %w[ TT I B U S STRIKE BIG SMALL EM STRONG DFN
          CODE SAMP KBD VAR CITE ABBR ACRONYM FONT SUB SUP SPAN BDO
          ADDRESS DIV CENTER MAP OBJECT APPLET H1 H2 H3 H4 H5 H6 PRE Q
          INS DEL DL OL UL DIR MENU LABEL SELECT OPTGROUP FIELDSET
          LEGEND BUTTON TABLE IFRAME NOFRAMES TITLE STYLE SCRIPT
          NOSCRIPT TEXTAREA FORM A BLOCKQUOTE CAPTION ]
        define_method(element.downcase, m)
      end
    end

    # - O EMPTY
    instance_method(:nOE_element_def).tap do |m|
      for element in %w[ IMG BASE BASEFONT BR AREA LINK PARAM HR INPUT
          COL ISINDEX META ]
        define_method(element.downcase, m)
      end
    end

    # O O or - O
    instance_method(:nO_element_def).tap do |m|
      for element in %w[ HTML BODY P DT DD LI OPTION THEAD TFOOT TBODY
          COLGROUP TR TH TD HEAD ]
        define_method(element.downcase, m)
      end
    end

  end # Html4Tr


  # Mixin module for generating HTML version 4 with framesets.
  module Html4Fr # :nodoc:
    include TagMaker

    # The DOCTYPE declaration for this version of HTML
    def doctype
      %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">|
    end

    # Initialise the HTML generation methods for this version.
    # - -
    instance_method(:nn_element_def).tap do |m|
      for element in %w[ FRAMESET ]
        define_method(element.downcase, m)
      end
    end

    # - O EMPTY
    instance_method(:nOE_element_def).tap do |m|
      for element in %w[ FRAME ]
        define_method(element.downcase, m)
      end
    end

  end # Html4Fr


  # Mixin module for HTML version 5 generation methods.
  module Html5 # :nodoc:
    include TagMaker

    # The DOCTYPE declaration for this version of HTML
    def doctype
      %|<!DOCTYPE HTML>|
    end

    # Initialise the HTML generation methods for this version.
    # - -
    instance_method(:nn_element_def).tap do |m|
      for element in %w[ SECTION NAV ARTICLE ASIDE HGROUP HEADER
        FOOTER FIGURE FIGCAPTION S TIME U MARK RUBY BDI IFRAME
        VIDEO AUDIO CANVAS DATALIST OUTPUT PROGRESS METER DETAILS
        SUMMARY MENU DIALOG I B SMALL EM STRONG DFN CODE SAMP KBD
        VAR CITE ABBR SUB SUP SPAN BDO ADDRESS DIV MAP OBJECT
        H1 H2 H3 H4 H5 H6 PRE Q INS DEL DL OL UL LABEL SELECT
        FIELDSET LEGEND BUTTON TABLE TITLE STYLE SCRIPT NOSCRIPT
        TEXTAREA FORM A BLOCKQUOTE CAPTION ]
        define_method(element.downcase, m)
      end
    end

    # - O EMPTY
    instance_method(:nOE_element_def).tap do |m|
      for element in %w[ IMG BASE BR AREA LINK PARAM HR INPUT COL META
        COMMAND EMBED KEYGEN SOURCE TRACK WBR ]
        define_method(element.downcase, m)
      end
    end

    # O O or - O
    instance_method(:nO_element_def).tap do |m|
      for element in %w[ HTML HEAD BODY P DT DD LI OPTION THEAD TFOOT TBODY
          OPTGROUP COLGROUP RT RP TR TH TD ]
        define_method(element.downcase, m)
      end
    end

  end # Html5

  class HTML3
    include Html3
    include HtmlExtension
  end

  class HTML4
    include Html4
    include HtmlExtension
  end

  class HTML4Tr
    include Html4Tr
    include HtmlExtension
  end

  class HTML4Fr
    include Html4Tr
    include Html4Fr
    include HtmlExtension
  end

  class HTML5
    include Html5
    include HtmlExtension
  end

end
# frozen_string_literal: true
#
# cgi/session.rb - session support for cgi scripts
#
# Copyright (C) 2001  Yukihiro "Matz" Matsumoto
# Copyright (C) 2000  Network Applied Communication Laboratory, Inc.
# Copyright (C) 2000  Information-technology Promotion Agency, Japan
#
# Author: Yukihiro "Matz" Matsumoto
#
# Documentation: William Webber (william@williamwebber.com)

require 'cgi'
require 'tmpdir'

class CGI

  # == Overview
  #
  # This file provides the CGI::Session class, which provides session
  # support for CGI scripts.  A session is a sequence of HTTP requests
  # and responses linked together and associated with a single client.
  # Information associated with the session is stored
  # on the server between requests.  A session id is passed between client
  # and server with every request and response, transparently
  # to the user.  This adds state information to the otherwise stateless
  # HTTP request/response protocol.
  #
  # == Lifecycle
  #
  # A CGI::Session instance is created from a CGI object.  By default,
  # this CGI::Session instance will start a new session if none currently
  # exists, or continue the current session for this client if one does
  # exist.  The +new_session+ option can be used to either always or
  # never create a new session.  See #new() for more details.
  #
  # #delete() deletes a session from session storage.  It
  # does not however remove the session id from the client.  If the client
  # makes another request with the same id, the effect will be to start
  # a new session with the old session's id.
  #
  # == Setting and retrieving session data.
  #
  # The Session class associates data with a session as key-value pairs.
  # This data can be set and retrieved by indexing the Session instance
  # using '[]', much the same as hashes (although other hash methods
  # are not supported).
  #
  # When session processing has been completed for a request, the
  # session should be closed using the close() method.  This will
  # store the session's state to persistent storage.  If you want
  # to store the session's state to persistent storage without
  # finishing session processing for this request, call the update()
  # method.
  #
  # == Storing session state
  #
  # The caller can specify what form of storage to use for the session's
  # data with the +database_manager+ option to CGI::Session::new.  The
  # following storage classes are provided as part of the standard library:
  #
  # CGI::Session::FileStore:: stores data as plain text in a flat file.  Only
  #                           works with String data.  This is the default
  #                           storage type.
  # CGI::Session::MemoryStore:: stores data in an in-memory hash.  The data
  #                             only persists for as long as the current Ruby
  #                             interpreter instance does.
  # CGI::Session::PStore:: stores data in Marshalled format.  Provided by
  #                        cgi/session/pstore.rb.  Supports data of any type,
  #                        and provides file-locking and transaction support.
  #
  # Custom storage types can also be created by defining a class with
  # the following methods:
  #
  #    new(session, options)
  #    restore  # returns hash of session data.
  #    update
  #    close
  #    delete
  #
  # Changing storage type mid-session does not work.  Note in particular
  # that by default the FileStore and PStore session data files have the
  # same name.  If your application switches from one to the other without
  # making sure that filenames will be different
  # and clients still have old sessions lying around in cookies, then
  # things will break nastily!
  #
  # == Maintaining the session id.
  #
  # Most session state is maintained on the server.  However, a session
  # id must be passed backwards and forwards between client and server
  # to maintain a reference to this session state.
  #
  # The simplest way to do this is via cookies.  The CGI::Session class
  # provides transparent support for session id communication via cookies
  # if the client has cookies enabled.
  #
  # If the client has cookies disabled, the session id must be included
  # as a parameter of all requests sent by the client to the server.  The
  # CGI::Session class in conjunction with the CGI class will transparently
  # add the session id as a hidden input field to all forms generated
  # using the CGI#form() HTML generation method.  No built-in support is
  # provided for other mechanisms, such as URL re-writing.  The caller is
  # responsible for extracting the session id from the session_id
  # attribute and manually encoding it in URLs and adding it as a hidden
  # input to HTML forms created by other mechanisms.  Also, session expiry
  # is not automatically handled.
  #
  # == Examples of use
  #
  # === Setting the user's name
  #
  #   require 'cgi'
  #   require 'cgi/session'
  #   require 'cgi/session/pstore'     # provides CGI::Session::PStore
  #
  #   cgi = CGI.new("html4")
  #
  #   session = CGI::Session.new(cgi,
  #       'database_manager' => CGI::Session::PStore,  # use PStore
  #       'session_key' => '_rb_sess_id',              # custom session key
  #       'session_expires' => Time.now + 30 * 60,     # 30 minute timeout
  #       'prefix' => 'pstore_sid_')                   # PStore option
  #   if cgi.has_key?('user_name') and cgi['user_name'] != ''
  #       # coerce to String: cgi[] returns the
  #       # string-like CGI::QueryExtension::Value
  #       session['user_name'] = cgi['user_name'].to_s
  #   elsif !session['user_name']
  #       session['user_name'] = "guest"
  #   end
  #   session.close
  #
  # === Creating a new session safely
  #
  #   require 'cgi'
  #   require 'cgi/session'
  #
  #   cgi = CGI.new("html4")
  #
  #   # We make sure to delete an old session if one exists,
  #   # not just to free resources, but to prevent the session
  #   # from being maliciously hijacked later on.
  #   begin
  #       session = CGI::Session.new(cgi, 'new_session' => false)
  #       session.delete
  #   rescue ArgumentError  # if no old session
  #   end
  #   session = CGI::Session.new(cgi, 'new_session' => true)
  #   session.close
  #
  class Session

    class NoSession < RuntimeError #:nodoc:
    end

    # The id of this session.
    attr_reader :session_id, :new_session

    def Session::callback(dbman)  #:nodoc:
      Proc.new{
        dbman[0].close unless dbman.empty?
      }
    end

    # Create a new session id.
    #
    # The session id is a secure random number by SecureRandom
    # if possible, otherwise an SHA512 hash based upon the time,
    # a random number, and a constant string.  This routine is
    # used internally for automatically generated session ids.
    def create_new_id
      require 'securerandom'
      begin
        # by OpenSSL, or system provided entropy pool
        session_id = SecureRandom.hex(16)
      rescue NotImplementedError
        # never happens on modern systems
        require 'digest'
        d = Digest('SHA512').new
        now = Time::now
        d.update(now.to_s)
        d.update(String(now.usec))
        d.update(String(rand(0)))
        d.update(String($$))
        d.update('foobar')
        session_id = d.hexdigest[0, 32]
      end
      session_id
    end
    private :create_new_id

    # Create a new CGI::Session object for +request+.
    #
    # +request+ is an instance of the +CGI+ class (see cgi.rb).
    # +option+ is a hash of options for initialising this
    # CGI::Session instance.  The following options are
    # recognised:
    #
    # session_key:: the parameter name used for the session id.
    #               Defaults to '_session_id'.
    # session_id:: the session id to use.  If not provided, then
    #              it is retrieved from the +session_key+ parameter
    #              of the request, or automatically generated for
    #              a new session.
    # new_session:: if true, force creation of a new session.  If not set,
    #               a new session is only created if none currently
    #               exists.  If false, a new session is never created,
    #               and if none currently exists and the +session_id+
    #               option is not set, an ArgumentError is raised.
    # database_manager:: the name of the class providing storage facilities
    #                    for session state persistence.  Built-in support
    #                    is provided for +FileStore+ (the default),
    #                    +MemoryStore+, and +PStore+ (from
    #                    cgi/session/pstore.rb).  See the documentation for
    #                    these classes for more details.
    #
    # The following options are also recognised, but only apply if the
    # session id is stored in a cookie.
    #
    # session_expires:: the time the current session expires, as a
    #                   +Time+ object.  If not set, the session will terminate
    #                   when the user's browser is closed.
    # session_domain:: the hostname domain for which this session is valid.
    #                  If not set, defaults to the hostname of the server.
    # session_secure:: if +true+, this session will only work over HTTPS.
    # session_path:: the path for which this session applies.  Defaults
    #                to the directory of the CGI script.
    #
    # +option+ is also passed on to the session storage class initializer; see
    # the documentation for each session storage class for the options
    # they support.
    #
    # The retrieved or created session is automatically added to +request+
    # as a cookie, and also to its +output_hidden+ table, which is used
    # to add hidden input elements to forms.
    #
    # *WARNING* the +output_hidden+
    # fields are surrounded by a <fieldset> tag in HTML 4 generation, which
    # is _not_ invisible on many browsers; you may wish to disable the
    # use of fieldsets with code similar to the following
    # (see http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-list/37805)
    #
    #   cgi = CGI.new("html4")
    #   class << cgi
    #       undef_method :fieldset
    #   end
    #
    def initialize(request, option={})
      @new_session = false
      session_key = option['session_key'] || '_session_id'
      session_id = option['session_id']
      unless session_id
        if option['new_session']
          session_id = create_new_id
          @new_session = true
        end
      end
      unless session_id
        if request.key?(session_key)
          session_id = request[session_key]
          session_id = session_id.read if session_id.respond_to?(:read)
        end
        unless session_id
          session_id, = request.cookies[session_key]
        end
        unless session_id
          unless option.fetch('new_session', true)
            raise ArgumentError, "session_key `%s' should be supplied"%session_key
          end
          session_id = create_new_id
          @new_session = true
        end
      end
      @session_id = session_id
      dbman = option['database_manager'] || FileStore
      begin
        @dbman = dbman::new(self, option)
      rescue NoSession
        unless option.fetch('new_session', true)
          raise ArgumentError, "invalid session_id `%s'"%session_id
        end
        session_id = @session_id = create_new_id unless session_id
        @new_session=true
        retry
      end
      request.instance_eval do
        @output_hidden = {session_key => session_id} unless option['no_hidden']
        @output_cookies =  [
          Cookie::new("name" => session_key,
          "value" => session_id,
          "expires" => option['session_expires'],
          "domain" => option['session_domain'],
          "secure" => option['session_secure'],
          "path" =>
          if option['session_path']
            option['session_path']
          elsif ENV["SCRIPT_NAME"]
            File::dirname(ENV["SCRIPT_NAME"])
          else
          ""
          end)
        ] unless option['no_cookies']
      end
      @dbprot = [@dbman]
      ObjectSpace::define_finalizer(self, Session::callback(@dbprot))
    end

    # Retrieve the session data for key +key+.
    def [](key)
      @data ||= @dbman.restore
      @data[key]
    end

    # Set the session data for key +key+.
    def []=(key, val)
      @write_lock ||= true
      @data ||= @dbman.restore
      @data[key] = val
    end

    # Store session data on the server.  For some session storage types,
    # this is a no-op.
    def update
      @dbman.update
    end

    # Store session data on the server and close the session storage.
    # For some session storage types, this is a no-op.
    def close
      @dbman.close
      @dbprot.clear
    end

    # Delete the session from storage.  Also closes the storage.
    #
    # Note that the session's data is _not_ automatically deleted
    # upon the session expiring.
    def delete
      @dbman.delete
      @dbprot.clear
    end

    # File-based session storage class.
    #
    # Implements session storage as a flat file of 'key=value' values.
    # This storage type only works directly with String values; the
    # user is responsible for converting other types to Strings when
    # storing and from Strings when retrieving.
    class FileStore
      # Create a new FileStore instance.
      #
      # This constructor is used internally by CGI::Session.  The
      # user does not generally need to call it directly.
      #
      # +session+ is the session for which this instance is being
      # created.  The session id must only contain alphanumeric
      # characters; automatically generated session ids observe
      # this requirement.
      #
      # +option+ is a hash of options for the initializer.  The
      # following options are recognised:
      #
      # tmpdir:: the directory to use for storing the FileStore
      #          file.  Defaults to Dir::tmpdir (generally "/tmp"
      #          on Unix systems).
      # prefix:: the prefix to add to the session id when generating
      #          the filename for this session's FileStore file.
      #          Defaults to "cgi_sid_".
      # suffix:: the prefix to add to the session id when generating
      #          the filename for this session's FileStore file.
      #          Defaults to the empty string.
      #
      # This session's FileStore file will be created if it does
      # not exist, or opened if it does.
      def initialize(session, option={})
        dir = option['tmpdir'] || Dir::tmpdir
        prefix = option['prefix'] || 'cgi_sid_'
        suffix = option['suffix'] || ''
        id = session.session_id
        require 'digest/md5'
        md5 = Digest::MD5.hexdigest(id)[0,16]
        @path = dir+"/"+prefix+md5+suffix
        if File::exist? @path
          @hash = nil
        else
          unless session.new_session
            raise CGI::Session::NoSession, "uninitialized session"
          end
          @hash = {}
        end
      end

      # Restore session state from the session's FileStore file.
      #
      # Returns the session state as a hash.
      def restore
        unless @hash
          @hash = {}
          begin
            lockf = File.open(@path+".lock", "r")
            lockf.flock File::LOCK_SH
            f = File.open(@path, 'r')
            for line in f
              line.chomp!
              k, v = line.split('=',2)
              @hash[CGI.unescape(k)] = Marshal.restore(CGI.unescape(v))
            end
          ensure
            f&.close
            lockf&.close
          end
        end
        @hash
      end

      # Save session state to the session's FileStore file.
      def update
        return unless @hash
        begin
          lockf = File.open(@path+".lock", File::CREAT|File::RDWR, 0600)
          lockf.flock File::LOCK_EX
          f = File.open(@path+".new", File::CREAT|File::TRUNC|File::WRONLY, 0600)
          for k,v in @hash
            f.printf "%s=%s\n", CGI.escape(k), CGI.escape(String(Marshal.dump(v)))
          end
          f.close
          File.rename @path+".new", @path
        ensure
          f&.close
          lockf&.close
        end
      end

      # Update and close the session's FileStore file.
      def close
        update
      end

      # Close and delete the session's FileStore file.
      def delete
        File::unlink @path+".lock" rescue nil
        File::unlink @path+".new" rescue nil
        File::unlink @path rescue nil
      end
    end

    # In-memory session storage class.
    #
    # Implements session storage as a global in-memory hash.  Session
    # data will only persist for as long as the Ruby interpreter
    # instance does.
    class MemoryStore
      GLOBAL_HASH_TABLE = {} #:nodoc:

      # Create a new MemoryStore instance.
      #
      # +session+ is the session this instance is associated with.
      # +option+ is a list of initialisation options.  None are
      # currently recognized.
      def initialize(session, option=nil)
        @session_id = session.session_id
        unless GLOBAL_HASH_TABLE.key?(@session_id)
          unless session.new_session
            raise CGI::Session::NoSession, "uninitialized session"
          end
          GLOBAL_HASH_TABLE[@session_id] = {}
        end
      end

      # Restore session state.
      #
      # Returns session data as a hash.
      def restore
        GLOBAL_HASH_TABLE[@session_id]
      end

      # Update session state.
      #
      # A no-op.
      def update
        # don't need to update; hash is shared
      end

      # Close session storage.
      #
      # A no-op.
      def close
        # don't need to close
      end

      # Delete the session state.
      def delete
        GLOBAL_HASH_TABLE.delete(@session_id)
      end
    end

    # Dummy session storage class.
    #
    # Implements session storage place holder.  No actual storage
    # will be done.
    class NullStore
      # Create a new NullStore instance.
      #
      # +session+ is the session this instance is associated with.
      # +option+ is a list of initialisation options.  None are
      # currently recognised.
      def initialize(session, option=nil)
      end

      # Restore (empty) session state.
      def restore
        {}
      end

      # Update session state.
      #
      # A no-op.
      def update
      end

      # Close session storage.
      #
      # A no-op.
      def close
      end

      # Delete the session state.
      #
      # A no-op.
      def delete
      end
    end
  end
end
# frozen_string_literal: true
require_relative 'util'
class CGI
  # Class representing an HTTP cookie.
  #
  # In addition to its specific fields and methods, a Cookie instance
  # is a delegator to the array of its values.
  #
  # See RFC 2965.
  #
  # == Examples of use
  #   cookie1 = CGI::Cookie.new("name", "value1", "value2", ...)
  #   cookie1 = CGI::Cookie.new("name" => "name", "value" => "value")
  #   cookie1 = CGI::Cookie.new('name'     => 'name',
  #                             'value'    => ['value1', 'value2', ...],
  #                             'path'     => 'path',   # optional
  #                             'domain'   => 'domain', # optional
  #                             'expires'  => Time.now, # optional
  #                             'secure'   => true,     # optional
  #                             'httponly' => true      # optional
  #                             )
  #
  #   cgi.out("cookie" => [cookie1, cookie2]) { "string" }
  #
  #   name     = cookie1.name
  #   values   = cookie1.value
  #   path     = cookie1.path
  #   domain   = cookie1.domain
  #   expires  = cookie1.expires
  #   secure   = cookie1.secure
  #   httponly = cookie1.httponly
  #
  #   cookie1.name     = 'name'
  #   cookie1.value    = ['value1', 'value2', ...]
  #   cookie1.path     = 'path'
  #   cookie1.domain   = 'domain'
  #   cookie1.expires  = Time.now + 30
  #   cookie1.secure   = true
  #   cookie1.httponly = true
  class Cookie < Array
    @@accept_charset="UTF-8" unless defined?(@@accept_charset)

    TOKEN_RE = %r"\A[[!-~]&&[^()<>@,;:\\\"/?=\[\]{}]]+\z"
    PATH_VALUE_RE = %r"\A[[ -~]&&[^;]]*\z"
    DOMAIN_VALUE_RE = %r"\A(?<label>(?!-)[-A-Za-z0-9]+(?<!-))(?:\.\g<label>)*\z"

    # Create a new CGI::Cookie object.
    #
    # :call-seq:
    #   Cookie.new(name_string,*value)
    #   Cookie.new(options_hash)
    #
    # +name_string+::
    #   The name of the cookie; in this form, there is no #domain or
    #   #expiration.  The #path is gleaned from the +SCRIPT_NAME+ environment
    #   variable, and #secure is false.
    # <tt>*value</tt>::
    #   value or list of values of the cookie
    # +options_hash+::
    #   A Hash of options to initialize this Cookie.  Possible options are:
    #
    #   name:: the name of the cookie.  Required.
    #   value:: the cookie's value or list of values.
    #   path:: the path for which this cookie applies.  Defaults to
    #          the value of the +SCRIPT_NAME+ environment variable.
    #   domain:: the domain for which this cookie applies.
    #   expires:: the time at which this cookie expires, as a +Time+ object.
    #   secure:: whether this cookie is a secure cookie or not (default to
    #            false).  Secure cookies are only transmitted to HTTPS
    #            servers.
    #   httponly:: whether this cookie is a HttpOnly cookie or not (default to
    #            false).  HttpOnly cookies are not available to javascript.
    #
    #   These keywords correspond to attributes of the cookie object.
    def initialize(name = "", *value)
      @domain = nil
      @expires = nil
      if name.kind_of?(String)
        self.name = name
        self.path = (%r|\A(.*/)| =~ ENV["SCRIPT_NAME"] ? $1 : "")
        @secure = false
        @httponly = false
        return super(value)
      end

      options = name
      unless options.has_key?("name")
        raise ArgumentError, "`name' required"
      end

      self.name = options["name"]
      value = Array(options["value"])
      # simple support for IE
      self.path = options["path"] || (%r|\A(.*/)| =~ ENV["SCRIPT_NAME"] ? $1 : "")
      self.domain = options["domain"]
      @expires = options["expires"]
      @secure = options["secure"] == true
      @httponly = options["httponly"] == true

      super(value)
    end

    # Name of this cookie, as a +String+
    attr_reader :name
    # Set name of this cookie
    def name=(str)
      if str and !TOKEN_RE.match?(str)
        raise ArgumentError, "invalid name: #{str.dump}"
      end
      @name = str
    end

    # Path for which this cookie applies, as a +String+
    attr_reader :path
    # Set path for which this cookie applies
    def path=(str)
      if str and !PATH_VALUE_RE.match?(str)
        raise ArgumentError, "invalid path: #{str.dump}"
      end
      @path = str
    end

    # Domain for which this cookie applies, as a +String+
    attr_reader :domain
    # Set domain for which this cookie applies
    def domain=(str)
      if str and ((str = str.b).bytesize > 255 or !DOMAIN_VALUE_RE.match?(str))
        raise ArgumentError, "invalid domain: #{str.dump}"
      end
      @domain = str
    end

    # Time at which this cookie expires, as a +Time+
    attr_accessor :expires
    # True if this cookie is secure; false otherwise
    attr_reader :secure
    # True if this cookie is httponly; false otherwise
    attr_reader :httponly

    # Returns the value or list of values for this cookie.
    def value
      self
    end

    # Replaces the value of this cookie with a new value or list of values.
    def value=(val)
      replace(Array(val))
    end

    # Set whether the Cookie is a secure cookie or not.
    #
    # +val+ must be a boolean.
    def secure=(val)
      @secure = val if val == true or val == false
      @secure
    end

    # Set whether the Cookie is a httponly cookie or not.
    #
    # +val+ must be a boolean.
    def httponly=(val)
      @httponly = !!val
    end

    # Convert the Cookie to its string representation.
    def to_s
      val = collect{|v| CGI.escape(v) }.join("&")
      buf = "#{@name}=#{val}".dup
      buf << "; domain=#{@domain}" if @domain
      buf << "; path=#{@path}"     if @path
      buf << "; expires=#{CGI.rfc1123_date(@expires)}" if @expires
      buf << "; secure"            if @secure
      buf << "; HttpOnly"          if @httponly
      buf
    end

    # Parse a raw cookie string into a hash of cookie-name=>Cookie
    # pairs.
    #
    #   cookies = CGI::Cookie.parse("raw_cookie_string")
    #     # { "name1" => cookie1, "name2" => cookie2, ... }
    #
    def self.parse(raw_cookie)
      cookies = Hash.new([])
      return cookies unless raw_cookie

      raw_cookie.split(/;\s?/).each do |pairs|
        name, values = pairs.split('=',2)
        next unless name and values
        values ||= ""
        values = values.split('&').collect{|v| CGI.unescape(v,@@accept_charset) }
        if cookies.has_key?(name)
          values = cookies[name].value + values
        end
        cookies[name] = Cookie.new(name, *values)
      end

      cookies
    end

    # A summary of cookie string.
    def inspect
      "#<CGI::Cookie: #{self.to_s.inspect}>"
    end

  end # class Cookie
end


# frozen_string_literal: true
class CGI
  module Util; end
  include Util
  extend Util
end
module CGI::Util
  @@accept_charset="UTF-8" unless defined?(@@accept_charset)
  # URL-encode a string.
  #   url_encoded_string = CGI.escape("'Stop!' said Fred")
  #      # => "%27Stop%21%27+said+Fred"
  def escape(string)
    encoding = string.encoding
    string.b.gsub(/([^ a-zA-Z0-9_.\-~]+)/) do |m|
      '%' + m.unpack('H2' * m.bytesize).join('%').upcase
    end.tr(' ', '+').force_encoding(encoding)
  end

  # URL-decode a string with encoding(optional).
  #   string = CGI.unescape("%27Stop%21%27+said+Fred")
  #      # => "'Stop!' said Fred"
  def unescape(string,encoding=@@accept_charset)
    str=string.tr('+', ' ').b.gsub(/((?:%[0-9a-fA-F]{2})+)/) do |m|
      [m.delete('%')].pack('H*')
    end.force_encoding(encoding)
    str.valid_encoding? ? str : str.force_encoding(string.encoding)
  end

  # The set of special characters and their escaped values
  TABLE_FOR_ESCAPE_HTML__ = {
    "'" => '&#39;',
    '&' => '&amp;',
    '"' => '&quot;',
    '<' => '&lt;',
    '>' => '&gt;',
  }

  # Escape special characters in HTML, namely '&\"<>
  #   CGI.escapeHTML('Usage: foo "bar" <baz>')
  #      # => "Usage: foo &quot;bar&quot; &lt;baz&gt;"
  def escapeHTML(string)
    enc = string.encoding
    unless enc.ascii_compatible?
      if enc.dummy?
        origenc = enc
        enc = Encoding::Converter.asciicompat_encoding(enc)
        string = enc ? string.encode(enc) : string.b
      end
      table = Hash[TABLE_FOR_ESCAPE_HTML__.map {|pair|pair.map {|s|s.encode(enc)}}]
      string = string.gsub(/#{"['&\"<>]".encode(enc)}/, table)
      string.encode!(origenc) if origenc
      return string
    end
    string.gsub(/['&\"<>]/, TABLE_FOR_ESCAPE_HTML__)
  end

  begin
    require 'cgi/escape'
  rescue LoadError
  end

  # Unescape a string that has been HTML-escaped
  #   CGI.unescapeHTML("Usage: foo &quot;bar&quot; &lt;baz&gt;")
  #      # => "Usage: foo \"bar\" <baz>"
  def unescapeHTML(string)
    enc = string.encoding
    unless enc.ascii_compatible?
      if enc.dummy?
        origenc = enc
        enc = Encoding::Converter.asciicompat_encoding(enc)
        string = enc ? string.encode(enc) : string.b
      end
      string = string.gsub(Regexp.new('&(apos|amp|quot|gt|lt|#[0-9]+|#x[0-9A-Fa-f]+);'.encode(enc))) do
        case $1.encode(Encoding::US_ASCII)
        when 'apos'                then "'".encode(enc)
        when 'amp'                 then '&'.encode(enc)
        when 'quot'                then '"'.encode(enc)
        when 'gt'                  then '>'.encode(enc)
        when 'lt'                  then '<'.encode(enc)
        when /\A#0*(\d+)\z/        then $1.to_i.chr(enc)
        when /\A#x([0-9a-f]+)\z/i  then $1.hex.chr(enc)
        end
      end
      string.encode!(origenc) if origenc
      return string
    end
    return string unless string.include? '&'
    charlimit = case enc
                when Encoding::UTF_8; 0x10ffff
                when Encoding::ISO_8859_1; 256
                else 128
                end
    string.gsub(/&(apos|amp|quot|gt|lt|\#[0-9]+|\#[xX][0-9A-Fa-f]+);/) do
      match = $1.dup
      case match
      when 'apos'                then "'"
      when 'amp'                 then '&'
      when 'quot'                then '"'
      when 'gt'                  then '>'
      when 'lt'                  then '<'
      when /\A#0*(\d+)\z/
        n = $1.to_i
        if n < charlimit
          n.chr(enc)
        else
          "&##{$1};"
        end
      when /\A#x([0-9a-f]+)\z/i
        n = $1.hex
        if n < charlimit
          n.chr(enc)
        else
          "&#x#{$1};"
        end
      else
        "&#{match};"
      end
    end
  end

  # Synonym for CGI.escapeHTML(str)
  alias escape_html escapeHTML

  # Synonym for CGI.unescapeHTML(str)
  alias unescape_html unescapeHTML

  # Escape only the tags of certain HTML elements in +string+.
  #
  # Takes an element or elements or array of elements.  Each element
  # is specified by the name of the element, without angle brackets.
  # This matches both the start and the end tag of that element.
  # The attribute list of the open tag will also be escaped (for
  # instance, the double-quotes surrounding attribute values).
  #
  #   print CGI.escapeElement('<BR><A HREF="url"></A>', "A", "IMG")
  #     # "<BR>&lt;A HREF=&quot;url&quot;&gt;&lt;/A&gt"
  #
  #   print CGI.escapeElement('<BR><A HREF="url"></A>', ["A", "IMG"])
  #     # "<BR>&lt;A HREF=&quot;url&quot;&gt;&lt;/A&gt"
  def escapeElement(string, *elements)
    elements = elements[0] if elements[0].kind_of?(Array)
    unless elements.empty?
      string.gsub(/<\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?>/i) do
        CGI.escapeHTML($&)
      end
    else
      string
    end
  end

  # Undo escaping such as that done by CGI.escapeElement()
  #
  #   print CGI.unescapeElement(
  #           CGI.escapeHTML('<BR><A HREF="url"></A>'), "A", "IMG")
  #     # "&lt;BR&gt;<A HREF="url"></A>"
  #
  #   print CGI.unescapeElement(
  #           CGI.escapeHTML('<BR><A HREF="url"></A>'), ["A", "IMG"])
  #     # "&lt;BR&gt;<A HREF="url"></A>"
  def unescapeElement(string, *elements)
    elements = elements[0] if elements[0].kind_of?(Array)
    unless elements.empty?
      string.gsub(/&lt;\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?&gt;/i) do
        unescapeHTML($&)
      end
    else
      string
    end
  end

  # Synonym for CGI.escapeElement(str)
  alias escape_element escapeElement

  # Synonym for CGI.unescapeElement(str)
  alias unescape_element unescapeElement

  # Abbreviated day-of-week names specified by RFC 822
  RFC822_DAYS = %w[ Sun Mon Tue Wed Thu Fri Sat ]

  # Abbreviated month names specified by RFC 822
  RFC822_MONTHS = %w[ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ]

  # Format a +Time+ object as a String using the format specified by RFC 1123.
  #
  #   CGI.rfc1123_date(Time.now)
  #     # Sat, 01 Jan 2000 00:00:00 GMT
  def rfc1123_date(time)
    t = time.clone.gmtime
    return format("%s, %.2d %s %.4d %.2d:%.2d:%.2d GMT",
                  RFC822_DAYS[t.wday], t.day, RFC822_MONTHS[t.month-1], t.year,
                  t.hour, t.min, t.sec)
  end

  # Prettify (indent) an HTML string.
  #
  # +string+ is the HTML string to indent.  +shift+ is the indentation
  # unit to use; it defaults to two spaces.
  #
  #   print CGI.pretty("<HTML><BODY></BODY></HTML>")
  #     # <HTML>
  #     #   <BODY>
  #     #   </BODY>
  #     # </HTML>
  #
  #   print CGI.pretty("<HTML><BODY></BODY></HTML>", "\t")
  #     # <HTML>
  #     #         <BODY>
  #     #         </BODY>
  #     # </HTML>
  #
  def pretty(string, shift = "  ")
    lines = string.gsub(/(?!\A)<.*?>/m, "\n\\0").gsub(/<.*?>(?!\n)/m, "\\0\n")
    end_pos = 0
    while end_pos = lines.index(/^<\/(\w+)/, end_pos)
      element = $1.dup
      start_pos = lines.rindex(/^\s*<#{element}/i, end_pos)
      lines[start_pos ... end_pos] = "__" + lines[start_pos ... end_pos].gsub(/\n(?!\z)/, "\n" + shift) + "__"
    end
    lines.gsub(/^((?:#{Regexp::quote(shift)})*)__(?=<\/?\w)/, '\1')
  end

  alias h escapeHTML
end
# frozen_string_literal: true
#
# cgi/session/pstore.rb - persistent storage of marshalled session data
#
# Documentation: William Webber (william@williamwebber.com)
#
# == Overview
#
# This file provides the CGI::Session::PStore class, which builds
# persistent of session data on top of the pstore library.  See
# cgi/session.rb for more details on session storage managers.

require_relative '../session'
require 'pstore'

class CGI
  class Session
    # PStore-based session storage class.
    #
    # This builds upon the top-level PStore class provided by the
    # library file pstore.rb.  Session data is marshalled and stored
    # in a file.  File locking and transaction services are provided.
    class PStore
      # Create a new CGI::Session::PStore instance
      #
      # This constructor is used internally by CGI::Session.  The
      # user does not generally need to call it directly.
      #
      # +session+ is the session for which this instance is being
      # created.  The session id must only contain alphanumeric
      # characters; automatically generated session ids observe
      # this requirement.
      #
      # +option+ is a hash of options for the initializer.  The
      # following options are recognised:
      #
      # tmpdir:: the directory to use for storing the PStore
      #          file.  Defaults to Dir::tmpdir (generally "/tmp"
      #          on Unix systems).
      # prefix:: the prefix to add to the session id when generating
      #          the filename for this session's PStore file.
      #          Defaults to the empty string.
      #
      # This session's PStore file will be created if it does
      # not exist, or opened if it does.
      def initialize(session, option={})
        dir = option['tmpdir'] || Dir::tmpdir
        prefix = option['prefix'] || ''
        id = session.session_id
        require 'digest/md5'
        md5 = Digest::MD5.hexdigest(id)[0,16]
        path = dir+"/"+prefix+md5
        if File::exist?(path)
          @hash = nil
        else
          unless session.new_session
            raise CGI::Session::NoSession, "uninitialized session"
          end
          @hash = {}
        end
        @p = ::PStore.new(path)
        @p.transaction do |p|
          File.chmod(0600, p.path)
        end
      end

      # Restore session state from the session's PStore file.
      #
      # Returns the session state as a hash.
      def restore
        unless @hash
          @p.transaction do
            @hash = @p['hash'] || {}
          end
        end
        @hash
      end

      # Save session state to the session's PStore file.
      def update
        @p.transaction do
          @p['hash'] = @hash
        end
      end

      # Update and close the session's PStore file.
      def close
        update
      end

      # Close and delete the session's PStore file.
      def delete
        path = @p.path
        File::unlink path
      end

    end
  end
end
# :enddoc:
require 'bigdecimal.so'
# frozen_string_literal: false
#
# kconv.rb - Kanji Converter.
#
# $Id$
#
# ----
#
# kconv.rb implements the Kconv class for Kanji Converter.  Additionally,
# some methods in String classes are added to allow easy conversion.
#

require 'nkf'

#
# Kanji Converter for Ruby.
#
module Kconv
  #
  # Public Constants
  #

  #Constant of Encoding

  # Auto-Detect
  AUTO = NKF::AUTO
  # ISO-2022-JP
  JIS = NKF::JIS
  # EUC-JP
  EUC = NKF::EUC
  # Shift_JIS
  SJIS = NKF::SJIS
  # BINARY
  BINARY = NKF::BINARY
  # NOCONV
  NOCONV = NKF::NOCONV
  # ASCII
  ASCII = NKF::ASCII
  # UTF-8
  UTF8 = NKF::UTF8
  # UTF-16
  UTF16 = NKF::UTF16
  # UTF-32
  UTF32 = NKF::UTF32
  # UNKNOWN
  UNKNOWN = NKF::UNKNOWN

  #
  # Public Methods
  #

  # call-seq:
  #    Kconv.kconv(str, to_enc, from_enc=nil)
  #
  # Convert <code>str</code> to <code>to_enc</code>.
  # <code>to_enc</code> and <code>from_enc</code> are given as constants of Kconv or Encoding objects.
  def kconv(str, to_enc, from_enc=nil)
    opt = ''
    opt += ' --ic=' + from_enc.to_s if from_enc
    opt += ' --oc=' + to_enc.to_s if to_enc

    ::NKF::nkf(opt, str)
  end
  module_function :kconv

  #
  # Encode to
  #

  # call-seq:
  #    Kconv.tojis(str)   => string
  #
  # Convert <code>str</code> to ISO-2022-JP
  def tojis(str)
    kconv(str, JIS)
  end
  module_function :tojis

  # call-seq:
  #    Kconv.toeuc(str)   => string
  #
  # Convert <code>str</code> to EUC-JP
  def toeuc(str)
    kconv(str, EUC)
  end
  module_function :toeuc

  # call-seq:
  #    Kconv.tosjis(str)   => string
  #
  # Convert <code>str</code> to Shift_JIS
  def tosjis(str)
    kconv(str, SJIS)
  end
  module_function :tosjis

  # call-seq:
  #    Kconv.toutf8(str)   => string
  #
  # Convert <code>str</code> to UTF-8
  def toutf8(str)
    kconv(str, UTF8)
  end
  module_function :toutf8

  # call-seq:
  #    Kconv.toutf16(str)   => string
  #
  # Convert <code>str</code> to UTF-16
  def toutf16(str)
    kconv(str, UTF16)
  end
  module_function :toutf16

  # call-seq:
  #    Kconv.toutf32(str)   => string
  #
  # Convert <code>str</code> to UTF-32
  def toutf32(str)
    kconv(str, UTF32)
  end
  module_function :toutf32

  # call-seq:
  #    Kconv.tolocale   => string
  #
  # Convert <code>self</code> to locale encoding
  def tolocale(str)
    kconv(str, Encoding.locale_charmap)
  end
  module_function :tolocale

  #
  # guess
  #

  # call-seq:
  #    Kconv.guess(str)   => encoding
  #
  # Guess input encoding by NKF.guess
  def guess(str)
    ::NKF::guess(str)
  end
  module_function :guess

  #
  # isEncoding
  #

  # call-seq:
  #    Kconv.iseuc(str)   => true or false
  #
  # Returns whether input encoding is EUC-JP or not.
  #
  # *Note* don't expect this return value is MatchData.
  def iseuc(str)
    str.dup.force_encoding(EUC).valid_encoding?
  end
  module_function :iseuc

  # call-seq:
  #    Kconv.issjis(str)   => true or false
  #
  # Returns whether input encoding is Shift_JIS or not.
  def issjis(str)
    str.dup.force_encoding(SJIS).valid_encoding?
  end
  module_function :issjis

  # call-seq:
  #    Kconv.isjis(str)   => true or false
  #
  # Returns whether input encoding is ISO-2022-JP or not.
  def isjis(str)
    /\A [\t\n\r\x20-\x7E]*
      (?:
        (?:\x1b \x28 I      [\x21-\x7E]*
          |\x1b \x28 J      [\x21-\x7E]*
          |\x1b \x24 @      (?:[\x21-\x7E]{2})*
          |\x1b \x24 B      (?:[\x21-\x7E]{2})*
          |\x1b \x24 \x28 D (?:[\x21-\x7E]{2})*
        )*
        \x1b \x28 B [\t\n\r\x20-\x7E]*
      )*
     \z/nox =~ str.dup.force_encoding('BINARY') ? true : false
  end
  module_function :isjis

  # call-seq:
  #    Kconv.isutf8(str)   => true or false
  #
  # Returns whether input encoding is UTF-8 or not.
  def isutf8(str)
    str.dup.force_encoding(UTF8).valid_encoding?
  end
  module_function :isutf8
end

class String
  # call-seq:
  #    String#kconv(to_enc, from_enc)
  #
  # Convert <code>self</code> to <code>to_enc</code>.
  # <code>to_enc</code> and <code>from_enc</code> are given as constants of Kconv or Encoding objects.
  def kconv(to_enc, from_enc=nil)
    from_enc = self.encoding if !from_enc && self.encoding != Encoding.list[0]
    Kconv::kconv(self, to_enc, from_enc)
  end

  #
  # to Encoding
  #

  # call-seq:
  #    String#tojis   => string
  #
  # Convert <code>self</code> to ISO-2022-JP
  def tojis; Kconv.tojis(self) end

  # call-seq:
  #    String#toeuc   => string
  #
  # Convert <code>self</code> to EUC-JP
  def toeuc; Kconv.toeuc(self) end

  # call-seq:
  #    String#tosjis   => string
  #
  # Convert <code>self</code> to Shift_JIS
  def tosjis; Kconv.tosjis(self) end

  # call-seq:
  #    String#toutf8   => string
  #
  # Convert <code>self</code> to UTF-8
  def toutf8; Kconv.toutf8(self) end

  # call-seq:
  #    String#toutf16   => string
  #
  # Convert <code>self</code> to UTF-16
  def toutf16; Kconv.toutf16(self) end

  # call-seq:
  #    String#toutf32   => string
  #
  # Convert <code>self</code> to UTF-32
  def toutf32; Kconv.toutf32(self) end

  # call-seq:
  #    String#tolocale   => string
  #
  # Convert <code>self</code> to locale encoding
  def tolocale; Kconv.tolocale(self) end

  #
  # is Encoding
  #

  # call-seq:
  #    String#iseuc   => true or false
  #
  # Returns whether <code>self</code>'s encoding is EUC-JP or not.
  def iseuc;	Kconv.iseuc(self) end

  # call-seq:
  #    String#issjis   => true or false
  #
  # Returns whether <code>self</code>'s encoding is Shift_JIS or not.
  def issjis;	Kconv.issjis(self) end

  # call-seq:
  #    String#isjis   => true or false
  #
  # Returns whether <code>self</code>'s encoding is ISO-2022-JP or not.
  def isjis;	Kconv.isjis(self) end

  # call-seq:
  #    String#isutf8   => true or false
  #
  # Returns whether <code>self</code>'s encoding is UTF-8 or not.
  def isutf8;	Kconv.isutf8(self) end
end
# frozen_string_literal: false
#
# = prime.rb
#
# Prime numbers and factorization library.
#
# Copyright::
#   Copyright (c) 1998-2008 Keiju ISHITSUKA(SHL Japan Inc.)
#   Copyright (c) 2008 Yuki Sonoda (Yugui) <yugui@yugui.jp>
#
# Documentation::
#   Yuki Sonoda
#

require "singleton"
require "forwardable"

class Integer
  # Re-composes a prime factorization and returns the product.
  #
  # See Prime#int_from_prime_division for more details.
  def Integer.from_prime_division(pd)
    Prime.int_from_prime_division(pd)
  end

  # Returns the factorization of +self+.
  #
  # See Prime#prime_division for more details.
  def prime_division(generator = Prime::Generator23.new)
    Prime.prime_division(self, generator)
  end

  # Returns true if +self+ is a prime number, else returns false.
  # Not recommended for very big integers (> 10**23).
  def prime?
    return self >= 2 if self <= 3

    if (bases = miller_rabin_bases)
      return miller_rabin_test(bases)
    end

    return true if self == 5
    return false unless 30.gcd(self) == 1
    (7..Integer.sqrt(self)).step(30) do |p|
      return false if
        self%(p)    == 0 || self%(p+4)  == 0 || self%(p+6)  == 0 || self%(p+10) == 0 ||
        self%(p+12) == 0 || self%(p+16) == 0 || self%(p+22) == 0 || self%(p+24) == 0
    end
    true
  end

  MILLER_RABIN_BASES = [
    [2],
    [2,3],
    [31,73],
    [2,3,5],
    [2,3,5,7],
    [2,7,61],
    [2,13,23,1662803],
    [2,3,5,7,11],
    [2,3,5,7,11,13],
    [2,3,5,7,11,13,17],
    [2,3,5,7,11,13,17,19,23],
    [2,3,5,7,11,13,17,19,23,29,31,37],
    [2,3,5,7,11,13,17,19,23,29,31,37,41],
  ].map!(&:freeze).freeze
  private_constant :MILLER_RABIN_BASES

  private def miller_rabin_bases
    # Miller-Rabin's complexity is O(k log^3n).
    # So we can reduce the complexity by reducing the number of bases tested.
    # Using values from https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
    i = case
    when self < 0xffff                            then
      # For small integers, Miller Rabin can be slower
      # There is no mathematical significance to 0xffff
      return nil
  # when self < 2_047                             then 0
    when self < 1_373_653                         then 1
    when self < 9_080_191                         then 2
    when self < 25_326_001                        then 3
    when self < 3_215_031_751                     then 4
    when self < 4_759_123_141                     then 5
    when self < 1_122_004_669_633                 then 6
    when self < 2_152_302_898_747                 then 7
    when self < 3_474_749_660_383                 then 8
    when self < 341_550_071_728_321               then 9
    when self < 3_825_123_056_546_413_051         then 10
    when self < 318_665_857_834_031_151_167_461   then 11
    when self < 3_317_044_064_679_887_385_961_981 then 12
    else return nil
    end
    MILLER_RABIN_BASES[i]
  end

  private def miller_rabin_test(bases)
    return false if even?

    r = 0
    d = self >> 1
    while d.even?
      d >>= 1
      r += 1
    end

    self_minus_1 = self-1
    bases.each do |a|
      x = a.pow(d, self)
      next if x == 1 || x == self_minus_1 || a == self

      return false if r.times do
        x = x.pow(2, self)
        break if x == self_minus_1
      end
    end
    true
  end

  # Iterates the given block over all prime numbers.
  #
  # See +Prime+#each for more details.
  def Integer.each_prime(ubound, &block) # :yields: prime
    Prime.each(ubound, &block)
  end
end

#
# The set of all prime numbers.
#
# == Example
#
#   Prime.each(100) do |prime|
#     p prime  #=> 2, 3, 5, 7, 11, ...., 97
#   end
#
# Prime is Enumerable:
#
#   Prime.first 5 # => [2, 3, 5, 7, 11]
#
# == Retrieving the instance
#
# For convenience, each instance method of +Prime+.instance can be accessed
# as a class method of +Prime+.
#
# e.g.
#   Prime.instance.prime?(2)  #=> true
#   Prime.prime?(2)           #=> true
#
# == Generators
#
# A "generator" provides an implementation of enumerating pseudo-prime
# numbers and it remembers the position of enumeration and upper bound.
# Furthermore, it is an external iterator of prime enumeration which is
# compatible with an Enumerator.
#
# +Prime+::+PseudoPrimeGenerator+ is the base class for generators.
# There are few implementations of generator.
#
# [+Prime+::+EratosthenesGenerator+]
#   Uses Eratosthenes' sieve.
# [+Prime+::+TrialDivisionGenerator+]
#   Uses the trial division method.
# [+Prime+::+Generator23+]
#   Generates all positive integers which are not divisible by either 2 or 3.
#   This sequence is very bad as a pseudo-prime sequence. But this
#   is faster and uses much less memory than the other generators. So,
#   it is suitable for factorizing an integer which is not large but
#   has many prime factors. e.g. for Prime#prime? .

class Prime

  VERSION = "0.1.2"

  include Enumerable
  include Singleton

  class << self
    extend Forwardable
    include Enumerable

    def method_added(method) # :nodoc:
      (class<< self;self;end).def_delegator :instance, method
    end
  end

  # Iterates the given block over all prime numbers.
  #
  # == Parameters
  #
  # +ubound+::
  #   Optional. An arbitrary positive number.
  #   The upper bound of enumeration. The method enumerates
  #   prime numbers infinitely if +ubound+ is nil.
  # +generator+::
  #   Optional. An implementation of pseudo-prime generator.
  #
  # == Return value
  #
  # An evaluated value of the given block at the last time.
  # Or an enumerator which is compatible to an +Enumerator+
  # if no block given.
  #
  # == Description
  #
  # Calls +block+ once for each prime number, passing the prime as
  # a parameter.
  #
  # +ubound+::
  #   Upper bound of prime numbers. The iterator stops after it
  #   yields all prime numbers p <= +ubound+.
  #
  def each(ubound = nil, generator = EratosthenesGenerator.new, &block)
    generator.upper_bound = ubound
    generator.each(&block)
  end

  # Returns true if +obj+ is an Integer and is prime.  Also returns
  # true if +obj+ is a Module that is an ancestor of +Prime+.
  # Otherwise returns false.
  def include?(obj)
    case obj
    when Integer
      prime?(obj)
    when Module
      Module.instance_method(:include?).bind(Prime).call(obj)
    else
      false
    end
  end

  # Returns true if +value+ is a prime number, else returns false.
  # Integer#prime? is much more performant.
  #
  # == Parameters
  #
  # +value+:: an arbitrary integer to be checked.
  # +generator+:: optional. A pseudo-prime generator.
  def prime?(value, generator = Prime::Generator23.new)
    raise ArgumentError, "Expected a prime generator, got #{generator}" unless generator.respond_to? :each
    raise ArgumentError, "Expected an integer, got #{value}" unless value.respond_to?(:integer?) && value.integer?
    return false if value < 2
    generator.each do |num|
      q,r = value.divmod num
      return true if q < num
      return false if r == 0
    end
  end

  # Re-composes a prime factorization and returns the product.
  #
  # For the decomposition:
  #
  #   [[p_1, e_1], [p_2, e_2], ..., [p_n, e_n]],
  #
  # it returns:
  #
  #   p_1**e_1 * p_2**e_2 * ... * p_n**e_n.
  #
  # == Parameters
  # +pd+:: Array of pairs of integers.
  #        Each pair consists of a prime number -- a prime factor --
  #        and a natural number -- its exponent (multiplicity).
  #
  # == Example
  #   Prime.int_from_prime_division([[3, 2], [5, 1]])  #=> 45
  #   3**2 * 5                                         #=> 45
  #
  def int_from_prime_division(pd)
    pd.inject(1){|value, (prime, index)|
      value * prime**index
    }
  end

  # Returns the factorization of +value+.
  #
  # For an arbitrary integer:
  #
  #   p_1**e_1 * p_2**e_2 * ... * p_n**e_n,
  #
  # prime_division returns an array of pairs of integers:
  #
  #   [[p_1, e_1], [p_2, e_2], ..., [p_n, e_n]].
  #
  # Each pair consists of a prime number -- a prime factor --
  # and a natural number -- its exponent (multiplicity).
  #
  # == Parameters
  # +value+:: An arbitrary integer.
  # +generator+:: Optional. A pseudo-prime generator.
  #               +generator+.succ must return the next
  #               pseudo-prime number in ascending order.
  #               It must generate all prime numbers,
  #               but may also generate non-prime numbers, too.
  #
  # === Exceptions
  # +ZeroDivisionError+:: when +value+ is zero.
  #
  # == Example
  #
  #   Prime.prime_division(45)  #=> [[3, 2], [5, 1]]
  #   3**2 * 5                  #=> 45
  #
  def prime_division(value, generator = Prime::Generator23.new)
    raise ZeroDivisionError if value == 0
    if value < 0
      value = -value
      pv = [[-1, 1]]
    else
      pv = []
    end
    generator.each do |prime|
      count = 0
      while (value1, mod = value.divmod(prime)
             mod) == 0
        value = value1
        count += 1
      end
      if count != 0
        pv.push [prime, count]
      end
      break if value1 <= prime
    end
    if value > 1
      pv.push [value, 1]
    end
    pv
  end

  # An abstract class for enumerating pseudo-prime numbers.
  #
  # Concrete subclasses should override succ, next, rewind.
  class PseudoPrimeGenerator
    include Enumerable

    def initialize(ubound = nil)
      @ubound = ubound
    end

    def upper_bound=(ubound)
      @ubound = ubound
    end
    def upper_bound
      @ubound
    end

    # returns the next pseudo-prime number, and move the internal
    # position forward.
    #
    # +PseudoPrimeGenerator+#succ raises +NotImplementedError+.
    def succ
      raise NotImplementedError, "need to define `succ'"
    end

    # alias of +succ+.
    def next
      raise NotImplementedError, "need to define `next'"
    end

    # Rewinds the internal position for enumeration.
    #
    # See +Enumerator+#rewind.
    def rewind
      raise NotImplementedError, "need to define `rewind'"
    end

    # Iterates the given block for each prime number.
    def each
      return self.dup unless block_given?
      if @ubound
        last_value = nil
        loop do
          prime = succ
          break last_value if prime > @ubound
          last_value = yield prime
        end
      else
        loop do
          yield succ
        end
      end
    end

    # see +Enumerator+#with_index.
    def with_index(offset = 0, &block)
      return enum_for(:with_index, offset) { Float::INFINITY } unless block
      return each_with_index(&block) if offset == 0

      each do |prime|
        yield prime, offset
        offset += 1
      end
    end

    # see +Enumerator+#with_object.
    def with_object(obj)
      return enum_for(:with_object, obj) { Float::INFINITY } unless block_given?
      each do |prime|
        yield prime, obj
      end
    end

    def size
      Float::INFINITY
    end
  end

  # An implementation of +PseudoPrimeGenerator+.
  #
  # Uses +EratosthenesSieve+.
  class EratosthenesGenerator < PseudoPrimeGenerator
    def initialize
      @last_prime_index = -1
      super
    end

    def succ
      @last_prime_index += 1
      EratosthenesSieve.instance.get_nth_prime(@last_prime_index)
    end
    def rewind
      initialize
    end
    alias next succ
  end

  # An implementation of +PseudoPrimeGenerator+ which uses
  # a prime table generated by trial division.
  class TrialDivisionGenerator < PseudoPrimeGenerator
    def initialize
      @index = -1
      super
    end

    def succ
      TrialDivision.instance[@index += 1]
    end
    def rewind
      initialize
    end
    alias next succ
  end

  # Generates all integers which are greater than 2 and
  # are not divisible by either 2 or 3.
  #
  # This is a pseudo-prime generator, suitable on
  # checking primality of an integer by brute force
  # method.
  class Generator23 < PseudoPrimeGenerator
    def initialize
      @prime = 1
      @step = nil
      super
    end

    def succ
      if (@step)
        @prime += @step
        @step = 6 - @step
      else
        case @prime
        when 1; @prime = 2
        when 2; @prime = 3
        when 3; @prime = 5; @step = 2
        end
      end
      @prime
    end
    alias next succ
    def rewind
      initialize
    end
  end

  # Internal use. An implementation of prime table by trial division method.
  class TrialDivision
    include Singleton

    def initialize # :nodoc:
      # These are included as class variables to cache them for later uses.  If memory
      #   usage is a problem, they can be put in Prime#initialize as instance variables.

      # There must be no primes between @primes[-1] and @next_to_check.
      @primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
      # @next_to_check % 6 must be 1.
      @next_to_check = 103            # @primes[-1] - @primes[-1] % 6 + 7
      @ulticheck_index = 3            # @primes.index(@primes.reverse.find {|n|
      #   n < Math.sqrt(@@next_to_check) })
      @ulticheck_next_squared = 121   # @primes[@ulticheck_index + 1] ** 2
    end

    # Returns the +index+th prime number.
    #
    # +index+ is a 0-based index.
    def [](index)
      while index >= @primes.length
        # Only check for prime factors up to the square root of the potential primes,
        #   but without the performance hit of an actual square root calculation.
        if @next_to_check + 4 > @ulticheck_next_squared
          @ulticheck_index += 1
          @ulticheck_next_squared = @primes.at(@ulticheck_index + 1) ** 2
        end
        # Only check numbers congruent to one and five, modulo six. All others

        #   are divisible by two or three.  This also allows us to skip checking against
        #   two and three.
        @primes.push @next_to_check if @primes[2..@ulticheck_index].find {|prime| @next_to_check % prime == 0 }.nil?
        @next_to_check += 4
        @primes.push @next_to_check if @primes[2..@ulticheck_index].find {|prime| @next_to_check % prime == 0 }.nil?
        @next_to_check += 2
      end
      @primes[index]
    end
  end

  # Internal use. An implementation of Eratosthenes' sieve
  class EratosthenesSieve
    include Singleton

    def initialize
      @primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
      # @max_checked must be an even number
      @max_checked = @primes.last + 1
    end

    def get_nth_prime(n)
      compute_primes while @primes.size <= n
      @primes[n]
    end

    private
    def compute_primes
      # max_segment_size must be an even number
      max_segment_size = 1e6.to_i
      max_cached_prime = @primes.last
      # do not double count primes if #compute_primes is interrupted
      # by Timeout.timeout
      @max_checked = max_cached_prime + 1 if max_cached_prime > @max_checked

      segment_min = @max_checked
      segment_max = [segment_min + max_segment_size, max_cached_prime * 2].min
      root = Integer.sqrt(segment_max)

      segment = ((segment_min + 1) .. segment_max).step(2).to_a

      (1..Float::INFINITY).each do |sieving|
        prime = @primes[sieving]
        break if prime > root
        composite_index = (-(segment_min + 1 + prime) / 2) % prime
        while composite_index < segment.size do
          segment[composite_index] = nil
          composite_index += prime
        end
      end

      @primes.concat(segment.compact!)

      @max_checked = segment_max
    end
  end
end
# frozen_string_literal: false
# URI is a module providing classes to handle Uniform Resource Identifiers
# (RFC2396[http://tools.ietf.org/html/rfc2396]).
#
# == Features
#
# * Uniform way of handling URIs.
# * Flexibility to introduce custom URI schemes.
# * Flexibility to have an alternate URI::Parser (or just different patterns
#   and regexp's).
#
# == Basic example
#
#   require 'uri'
#
#   uri = URI("http://foo.com/posts?id=30&limit=5#time=1305298413")
#   #=> #<URI::HTTP http://foo.com/posts?id=30&limit=5#time=1305298413>
#
#   uri.scheme    #=> "http"
#   uri.host      #=> "foo.com"
#   uri.path      #=> "/posts"
#   uri.query     #=> "id=30&limit=5"
#   uri.fragment  #=> "time=1305298413"
#
#   uri.to_s      #=> "http://foo.com/posts?id=30&limit=5#time=1305298413"
#
# == Adding custom URIs
#
#   module URI
#     class RSYNC < Generic
#       DEFAULT_PORT = 873
#     end
#     @@schemes['RSYNC'] = RSYNC
#   end
#   #=> URI::RSYNC
#
#   URI.scheme_list
#   #=> {"FILE"=>URI::File, "FTP"=>URI::FTP, "HTTP"=>URI::HTTP,
#   #    "HTTPS"=>URI::HTTPS, "LDAP"=>URI::LDAP, "LDAPS"=>URI::LDAPS,
#   #    "MAILTO"=>URI::MailTo, "RSYNC"=>URI::RSYNC}
#
#   uri = URI("rsync://rsync.foo.com")
#   #=> #<URI::RSYNC rsync://rsync.foo.com>
#
# == RFC References
#
# A good place to view an RFC spec is http://www.ietf.org/rfc.html.
#
# Here is a list of all related RFC's:
# - RFC822[http://tools.ietf.org/html/rfc822]
# - RFC1738[http://tools.ietf.org/html/rfc1738]
# - RFC2255[http://tools.ietf.org/html/rfc2255]
# - RFC2368[http://tools.ietf.org/html/rfc2368]
# - RFC2373[http://tools.ietf.org/html/rfc2373]
# - RFC2396[http://tools.ietf.org/html/rfc2396]
# - RFC2732[http://tools.ietf.org/html/rfc2732]
# - RFC3986[http://tools.ietf.org/html/rfc3986]
#
# == Class tree
#
# - URI::Generic (in uri/generic.rb)
#   - URI::File - (in uri/file.rb)
#   - URI::FTP - (in uri/ftp.rb)
#   - URI::HTTP - (in uri/http.rb)
#     - URI::HTTPS - (in uri/https.rb)
#   - URI::LDAP - (in uri/ldap.rb)
#     - URI::LDAPS - (in uri/ldaps.rb)
#   - URI::MailTo - (in uri/mailto.rb)
# - URI::Parser - (in uri/common.rb)
# - URI::REGEXP - (in uri/common.rb)
#   - URI::REGEXP::PATTERN - (in uri/common.rb)
# - URI::Util - (in uri/common.rb)
# - URI::Escape - (in uri/common.rb)
# - URI::Error - (in uri/common.rb)
#   - URI::InvalidURIError - (in uri/common.rb)
#   - URI::InvalidComponentError - (in uri/common.rb)
#   - URI::BadURIError - (in uri/common.rb)
#
# == Copyright Info
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# Documentation::
#   Akira Yamada <akira@ruby-lang.org>
#   Dmitry V. Sabanin <sdmitry@lrn.ru>
#   Vincent Batts <vbatts@hashbangbash.com>
# License::
#  Copyright (c) 2001 akira yamada <akira@ruby-lang.org>
#  You can redistribute it and/or modify it under the same term as Ruby.
#

module URI
end

require_relative 'uri/version'
require_relative 'uri/common'
require_relative 'uri/generic'
require_relative 'uri/file'
require_relative 'uri/ftp'
require_relative 'uri/http'
require_relative 'uri/https'
require_relative 'uri/ldap'
require_relative 'uri/ldaps'
require_relative 'uri/mailto'
# frozen_string_literal: true
#
# = ostruct.rb: OpenStruct implementation
#
# Author:: Yukihiro Matsumoto
# Documentation:: Gavin Sinclair
#
# OpenStruct allows the creation of data objects with arbitrary attributes.
# See OpenStruct for an example.
#

#
# An OpenStruct is a data structure, similar to a Hash, that allows the
# definition of arbitrary attributes with their accompanying values. This is
# accomplished by using Ruby's metaprogramming to define methods on the class
# itself.
#
# == Examples
#
#   require "ostruct"
#
#   person = OpenStruct.new
#   person.name = "John Smith"
#   person.age  = 70
#
#   person.name      # => "John Smith"
#   person.age       # => 70
#   person.address   # => nil
#
# An OpenStruct employs a Hash internally to store the attributes and values
# and can even be initialized with one:
#
#   australia = OpenStruct.new(:country => "Australia", :capital => "Canberra")
#     # => #<OpenStruct country="Australia", capital="Canberra">
#
# Hash keys with spaces or characters that could normally not be used for
# method calls (e.g. <code>()[]*</code>) will not be immediately available
# on the OpenStruct object as a method for retrieval or assignment, but can
# still be reached through the Object#send method or using [].
#
#   measurements = OpenStruct.new("length (in inches)" => 24)
#   measurements[:"length (in inches)"]       # => 24
#   measurements.send("length (in inches)")   # => 24
#
#   message = OpenStruct.new(:queued? => true)
#   message.queued?                           # => true
#   message.send("queued?=", false)
#   message.queued?                           # => false
#
# Removing the presence of an attribute requires the execution of the
# delete_field method as setting the property value to +nil+ will not
# remove the attribute.
#
#   first_pet  = OpenStruct.new(:name => "Rowdy", :owner => "John Smith")
#   second_pet = OpenStruct.new(:name => "Rowdy")
#
#   first_pet.owner = nil
#   first_pet                 # => #<OpenStruct name="Rowdy", owner=nil>
#   first_pet == second_pet   # => false
#
#   first_pet.delete_field(:owner)
#   first_pet                 # => #<OpenStruct name="Rowdy">
#   first_pet == second_pet   # => true
#
# Ractor compatibility: A frozen OpenStruct with shareable values is itself shareable.
#
# == Caveats
#
# An OpenStruct utilizes Ruby's method lookup structure to find and define the
# necessary methods for properties. This is accomplished through the methods
# method_missing and define_singleton_method.
#
# This should be a consideration if there is a concern about the performance of
# the objects that are created, as there is much more overhead in the setting
# of these properties compared to using a Hash or a Struct.
# Creating an open struct from a small Hash and accessing a few of the
# entries can be 200 times slower than accessing the hash directly.
#
# This is a potential security issue; building OpenStruct from untrusted user data
# (e.g. JSON web request) may be susceptible to a "symbol denial of service" attack
# since the keys create methods and names of methods are never garbage collected.
#
# This may also be the source of incompatibilities between Ruby versions:
#
#   o = OpenStruct.new
#   o.then # => nil in Ruby < 2.6, enumerator for Ruby >= 2.6
#
# Builtin methods may be overwritten this way, which may be a source of bugs
# or security issues:
#
#   o = OpenStruct.new
#   o.methods # => [:to_h, :marshal_load, :marshal_dump, :each_pair, ...
#   o.methods = [:foo, :bar]
#   o.methods # => [:foo, :bar]
#
# To help remedy clashes, OpenStruct uses only protected/private methods ending with `!`
# and defines aliases for builtin public methods by adding a `!`:
#
#   o = OpenStruct.new(make: 'Bentley', class: :luxury)
#   o.class # => :luxury
#   o.class! # => OpenStruct
#
# It is recommended (but not enforced) to not use fields ending in `!`;
# Note that a subclass' methods may not be overwritten, nor can OpenStruct's own methods
# ending with `!`.
#
# For all these reasons, consider not using OpenStruct at all.
#
class OpenStruct
  VERSION = "0.3.1"

  #
  # Creates a new OpenStruct object.  By default, the resulting OpenStruct
  # object will have no attributes.
  #
  # The optional +hash+, if given, will generate attributes and values
  # (can be a Hash, an OpenStruct or a Struct).
  # For example:
  #
  #   require "ostruct"
  #   hash = { "country" => "Australia", :capital => "Canberra" }
  #   data = OpenStruct.new(hash)
  #
  #   data   # => #<OpenStruct country="Australia", capital="Canberra">
  #
  def initialize(hash=nil)
    if hash
      update_to_values!(hash)
    else
      @table = {}
    end
  end

  # Duplicates an OpenStruct object's Hash table.
  private def initialize_clone(orig) # :nodoc:
    super # clones the singleton class for us
    @table = @table.dup unless @table.frozen?
  end

  private def initialize_dup(orig) # :nodoc:
    super
    update_to_values!(@table)
  end

  private def update_to_values!(hash) # :nodoc:
    @table = {}
    hash.each_pair do |k, v|
      set_ostruct_member_value!(k, v)
    end
  end

  #
  # call-seq:
  #   ostruct.to_h                        -> hash
  #   ostruct.to_h {|name, value| block } -> hash
  #
  # Converts the OpenStruct to a hash with keys representing
  # each attribute (as symbols) and their corresponding values.
  #
  # If a block is given, the results of the block on each pair of
  # the receiver will be used as pairs.
  #
  #   require "ostruct"
  #   data = OpenStruct.new("country" => "Australia", :capital => "Canberra")
  #   data.to_h   # => {:country => "Australia", :capital => "Canberra" }
  #   data.to_h {|name, value| [name.to_s, value.upcase] }
  #               # => {"country" => "AUSTRALIA", "capital" => "CANBERRA" }
  #
  def to_h(&block)
    if block
      @table.to_h(&block)
    else
      @table.dup
    end
  end

  #
  # :call-seq:
  #   ostruct.each_pair {|name, value| block }  -> ostruct
  #   ostruct.each_pair                         -> Enumerator
  #
  # Yields all attributes (as symbols) along with the corresponding values
  # or returns an enumerator if no block is given.
  #
  #   require "ostruct"
  #   data = OpenStruct.new("country" => "Australia", :capital => "Canberra")
  #   data.each_pair.to_a   # => [[:country, "Australia"], [:capital, "Canberra"]]
  #
  def each_pair
    return to_enum(__method__) { @table.size } unless block_given?
    @table.each_pair{|p| yield p}
    self
  end

  #
  # Provides marshalling support for use by the Marshal library.
  #
  def marshal_dump # :nodoc:
    @table
  end

  #
  # Provides marshalling support for use by the Marshal library.
  #
  alias_method :marshal_load, :update_to_values! # :nodoc:

  #
  # Used internally to defined properties on the
  # OpenStruct. It does this by using the metaprogramming function
  # define_singleton_method for both the getter method and the setter method.
  #
  def new_ostruct_member!(name) # :nodoc:
    unless @table.key?(name) || is_method_protected!(name)
      define_singleton_method!(name) { @table[name] }
      define_singleton_method!("#{name}=") {|x| @table[name] = x}
    end
  end
  private :new_ostruct_member!

  private def is_method_protected!(name) # :nodoc:
    if !respond_to?(name, true)
      false
    elsif name.end_with?('!')
      true
    else
      method!(name).owner < OpenStruct
    end
  end

  def freeze
    @table.freeze
    super
  end

  private def method_missing(mid, *args) # :nodoc:
    len = args.length
    if mname = mid[/.*(?==\z)/m]
      if len != 1
        raise! ArgumentError, "wrong number of arguments (given #{len}, expected 1)", caller(1)
      end
      set_ostruct_member_value!(mname, args[0])
    elsif len == 0
    else
      begin
        super
      rescue NoMethodError => err
        err.backtrace.shift
        raise!
      end
    end
  end

  #
  # :call-seq:
  #   ostruct[name]  -> object
  #
  # Returns the value of an attribute, or `nil` if there is no such attribute.
  #
  #   require "ostruct"
  #   person = OpenStruct.new("name" => "John Smith", "age" => 70)
  #   person[:age]   # => 70, same as person.age
  #
  def [](name)
    @table[name.to_sym]
  end

  #
  # :call-seq:
  #   ostruct[name] = obj  -> obj
  #
  # Sets the value of an attribute.
  #
  #   require "ostruct"
  #   person = OpenStruct.new("name" => "John Smith", "age" => 70)
  #   person[:age] = 42   # equivalent to person.age = 42
  #   person.age          # => 42
  #
  def []=(name, value)
    name = name.to_sym
    new_ostruct_member!(name)
    @table[name] = value
  end
  alias_method :set_ostruct_member_value!, :[]=
  private :set_ostruct_member_value!

  # :call-seq:
  #   ostruct.dig(name, *identifiers) -> object
  #
  # Finds and returns the object in nested objects
  # that is specified by +name+ and +identifiers+.
  # The nested objects may be instances of various classes.
  # See {Dig Methods}[rdoc-ref:doc/dig_methods.rdoc].
  #
  # Examples:
  #   require "ostruct"
  #   address = OpenStruct.new("city" => "Anytown NC", "zip" => 12345)
  #   person  = OpenStruct.new("name" => "John Smith", "address" => address)
  #   person.dig(:address, "zip") # => 12345
  #   person.dig(:business_address, "zip") # => nil
  def dig(name, *names)
    begin
      name = name.to_sym
    rescue NoMethodError
      raise! TypeError, "#{name} is not a symbol nor a string"
    end
    @table.dig(name, *names)
  end

  #
  # Removes the named field from the object. Returns the value that the field
  # contained if it was defined.
  #
  #   require "ostruct"
  #
  #   person = OpenStruct.new(name: "John", age: 70, pension: 300)
  #
  #   person.delete_field!("age")  # => 70
  #   person                       # => #<OpenStruct name="John", pension=300>
  #
  # Setting the value to +nil+ will not remove the attribute:
  #
  #   person.pension = nil
  #   person                 # => #<OpenStruct name="John", pension=nil>
  #
  def delete_field(name)
    sym = name.to_sym
    begin
      singleton_class.remove_method(sym, "#{sym}=")
    rescue NameError
    end
    @table.delete(sym) do
      raise! NameError.new("no field `#{sym}' in #{self}", sym)
    end
  end

  InspectKey = :__inspect_key__ # :nodoc:

  #
  # Returns a string containing a detailed summary of the keys and values.
  #
  def inspect
    ids = (Thread.current[InspectKey] ||= [])
    if ids.include?(object_id)
      detail = ' ...'
    else
      ids << object_id
      begin
        detail = @table.map do |key, value|
          " #{key}=#{value.inspect}"
        end.join(',')
      ensure
        ids.pop
      end
    end
    ['#<', self.class!, detail, '>'].join
  end
  alias :to_s :inspect

  attr_reader :table # :nodoc:
  alias table! table
  protected :table!

  #
  # Compares this object and +other+ for equality.  An OpenStruct is equal to
  # +other+ when +other+ is an OpenStruct and the two objects' Hash tables are
  # equal.
  #
  #   require "ostruct"
  #   first_pet  = OpenStruct.new("name" => "Rowdy")
  #   second_pet = OpenStruct.new(:name  => "Rowdy")
  #   third_pet  = OpenStruct.new("name" => "Rowdy", :age => nil)
  #
  #   first_pet == second_pet   # => true
  #   first_pet == third_pet    # => false
  #
  def ==(other)
    return false unless other.kind_of?(OpenStruct)
    @table == other.table!
  end

  #
  # Compares this object and +other+ for equality.  An OpenStruct is eql? to
  # +other+ when +other+ is an OpenStruct and the two objects' Hash tables are
  # eql?.
  #
  def eql?(other)
    return false unless other.kind_of?(OpenStruct)
    @table.eql?(other.table!)
  end

  # Computes a hash code for this OpenStruct.
  def hash # :nodoc:
    @table.hash
  end

  #
  # Provides marshalling support for use by the YAML library.
  #
  def encode_with(coder) # :nodoc:
    @table.each_pair do |key, value|
      coder[key.to_s] = value
    end
    if @table.size == 1 && @table.key?(:table) # support for legacy format
      # in the very unlikely case of a single entry called 'table'
      coder['legacy_support!'] = true # add a bogus second entry
    end
  end

  #
  # Provides marshalling support for use by the YAML library.
  #
  def init_with(coder) # :nodoc:
    h = coder.map
    if h.size == 1 # support for legacy format
      key, val = h.first
      if key == 'table'
        h = val
      end
    end
    update_to_values!(h)
  end

  # Make all public methods (builtin or our own) accessible with `!`:
  instance_methods.each do |method|
    new_name = "#{method}!"
    alias_method new_name, method
  end
  # Other builtin private methods we use:
  alias_method :raise!, :raise
  private :raise!
end
# frozen_string_literal: false
#
# = un.rb
#
# Copyright (c) 2003 WATANABE Hirofumi <eban@ruby-lang.org>
#
# This program is free software.
# You can distribute/modify this program under the same terms of Ruby.
#
# == Utilities to replace common UNIX commands in Makefiles etc
#
# == SYNOPSIS
#
#   ruby -run -e cp -- [OPTION] SOURCE DEST
#   ruby -run -e ln -- [OPTION] TARGET LINK_NAME
#   ruby -run -e mv -- [OPTION] SOURCE DEST
#   ruby -run -e rm -- [OPTION] FILE
#   ruby -run -e mkdir -- [OPTION] DIRS
#   ruby -run -e rmdir -- [OPTION] DIRS
#   ruby -run -e install -- [OPTION] SOURCE DEST
#   ruby -run -e chmod -- [OPTION] OCTAL-MODE FILE
#   ruby -run -e touch -- [OPTION] FILE
#   ruby -run -e wait_writable -- [OPTION] FILE
#   ruby -run -e mkmf -- [OPTION] EXTNAME [OPTION]
#   ruby -run -e httpd -- [OPTION] [DocumentRoot]
#   ruby -run -e help [COMMAND]

require "fileutils"
require "optparse"

module FileUtils
#  @fileutils_label = ""
  @fileutils_output = $stdout
end

# :nodoc:
def setup(options = "", *long_options)
  caller = caller_locations(1, 1)[0].label
  opt_hash = {}
  argv = []
  OptionParser.new do |o|
    options.scan(/.:?/) do |s|
      opt_name = s.delete(":").intern
      o.on("-" + s.tr(":", " ")) do |val|
        opt_hash[opt_name] = val
      end
    end
    long_options.each do |s|
      opt_name, arg_name = s.split(/(?=[\s=])/, 2)
      opt_name.delete_prefix!('--')
      s = "--#{opt_name.gsub(/([A-Z]+|[a-z])([A-Z])/, '\1-\2').downcase}#{arg_name}"
      puts "#{opt_name}=>#{s}" if $DEBUG
      opt_name = opt_name.intern
      o.on(s) do |val|
        opt_hash[opt_name] = val
      end
    end
    o.on("-v") do opt_hash[:verbose] = true end
    o.on("--help") do
      UN.help([caller])
      exit
    end
    o.order!(ARGV) do |x|
      if /[*?\[{]/ =~ x
        argv.concat(Dir[x])
      else
        argv << x
      end
    end
  end
  yield argv, opt_hash
end

##
# Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY
#
#   ruby -run -e cp -- [OPTION] SOURCE DEST
#
#   -p          preserve file attributes if possible
#   -r          copy recursively
#   -v          verbose
#

def cp
  setup("pr") do |argv, options|
    cmd = "cp"
    cmd += "_r" if options.delete :r
    options[:preserve] = true if options.delete :p
    dest = argv.pop
    argv = argv[0] if argv.size == 1
    FileUtils.__send__ cmd, argv, dest, **options
  end
end

##
# Create a link to the specified TARGET with LINK_NAME.
#
#   ruby -run -e ln -- [OPTION] TARGET LINK_NAME
#
#   -s          make symbolic links instead of hard links
#   -f          remove existing destination files
#   -v          verbose
#

def ln
  setup("sf") do |argv, options|
    cmd = "ln"
    cmd += "_s" if options.delete :s
    options[:force] = true if options.delete :f
    dest = argv.pop
    argv = argv[0] if argv.size == 1
    FileUtils.__send__ cmd, argv, dest, **options
  end
end

##
# Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.
#
#   ruby -run -e mv -- [OPTION] SOURCE DEST
#
#   -v          verbose
#

def mv
  setup do |argv, options|
    dest = argv.pop
    argv = argv[0] if argv.size == 1
    FileUtils.mv argv, dest, **options
  end
end

##
# Remove the FILE
#
#   ruby -run -e rm -- [OPTION] FILE
#
#   -f          ignore nonexistent files
#   -r          remove the contents of directories recursively
#   -v          verbose
#

def rm
  setup("fr") do |argv, options|
    cmd = "rm"
    cmd += "_r" if options.delete :r
    options[:force] = true if options.delete :f
    FileUtils.__send__ cmd, argv, **options
  end
end

##
# Create the DIR, if they do not already exist.
#
#   ruby -run -e mkdir -- [OPTION] DIR
#
#   -p          no error if existing, make parent directories as needed
#   -v          verbose
#

def mkdir
  setup("p") do |argv, options|
    cmd = "mkdir"
    cmd += "_p" if options.delete :p
    FileUtils.__send__ cmd, argv, **options
  end
end

##
# Remove the DIR.
#
#   ruby -run -e rmdir -- [OPTION] DIR
#
#   -p          remove DIRECTORY and its ancestors.
#   -v          verbose
#

def rmdir
  setup("p") do |argv, options|
    options[:parents] = true if options.delete :p
    FileUtils.rmdir argv, **options
  end
end

##
# Copy SOURCE to DEST.
#
#   ruby -run -e install -- [OPTION] SOURCE DEST
#
#   -p          apply access/modification times of SOURCE files to
#               corresponding destination files
#   -m          set permission mode (as in chmod), instead of 0755
#   -o          set owner user id, instead of the current owner
#   -g          set owner group id, instead of the current group
#   -v          verbose
#

def install
  setup("pm:o:g:") do |argv, options|
    (mode = options.delete :m) and options[:mode] = /\A\d/ =~ mode ? mode.oct : mode
    options[:preserve] = true if options.delete :p
    (owner = options.delete :o) and options[:owner] = owner
    (group = options.delete :g) and options[:group] = group
    dest = argv.pop
    argv = argv[0] if argv.size == 1
    FileUtils.install argv, dest, **options
  end
end

##
# Change the mode of each FILE to OCTAL-MODE.
#
#   ruby -run -e chmod -- [OPTION] OCTAL-MODE FILE
#
#   -v          verbose
#

def chmod
  setup do |argv, options|
    mode = argv.shift
    mode = /\A\d/ =~ mode ? mode.oct : mode
    FileUtils.chmod mode, argv, **options
  end
end

##
# Update the access and modification times of each FILE to the current time.
#
#   ruby -run -e touch -- [OPTION] FILE
#
#   -v          verbose
#

def touch
  setup do |argv, options|
    FileUtils.touch argv, **options
  end
end

##
# Wait until the file becomes writable.
#
#   ruby -run -e wait_writable -- [OPTION] FILE
#
#   -n RETRY    count to retry
#   -w SEC      each wait time in seconds
#   -v          verbose
#

def wait_writable
  setup("n:w:v") do |argv, options|
    verbose = options[:verbose]
    n = options[:n] and n = Integer(n)
    wait = (wait = options[:w]) ? Float(wait) : 0.2
    argv.each do |file|
      begin
        open(file, "r+b")
      rescue Errno::ENOENT
        break
      rescue Errno::EACCES => e
        raise if n and (n -= 1) <= 0
        if verbose
          puts e
          STDOUT.flush
        end
        sleep wait
        retry
      end
    end
  end
end

##
# Create makefile using mkmf.
#
#   ruby -run -e mkmf -- [OPTION] EXTNAME [OPTION]
#
#   -d ARGS     run dir_config
#   -h ARGS     run have_header
#   -l ARGS     run have_library
#   -f ARGS     run have_func
#   -v ARGS     run have_var
#   -t ARGS     run have_type
#   -m ARGS     run have_macro
#   -c ARGS     run have_const
#   --vendor    install to vendor_ruby
#

def mkmf
  setup("d:h:l:f:v:t:m:c:", "vendor") do |argv, options|
    require 'mkmf'
    opt = options[:d] and opt.split(/:/).each {|n| dir_config(*n.split(/,/))}
    opt = options[:h] and opt.split(/:/).each {|n| have_header(*n.split(/,/))}
    opt = options[:l] and opt.split(/:/).each {|n| have_library(*n.split(/,/))}
    opt = options[:f] and opt.split(/:/).each {|n| have_func(*n.split(/,/))}
    opt = options[:v] and opt.split(/:/).each {|n| have_var(*n.split(/,/))}
    opt = options[:t] and opt.split(/:/).each {|n| have_type(*n.split(/,/))}
    opt = options[:m] and opt.split(/:/).each {|n| have_macro(*n.split(/,/))}
    opt = options[:c] and opt.split(/:/).each {|n| have_const(*n.split(/,/))}
    $configure_args["--vendor"] = true if options[:vendor]
    create_makefile(*argv)
  end
end

##
# Run WEBrick HTTP server.
#
#   ruby -run -e httpd -- [OPTION] [DocumentRoot]
#
#   --bind-address=ADDR         address to bind
#   --port=NUM                  listening port number
#   --max-clients=MAX           max number of simultaneous clients
#   --temp-dir=DIR              temporary directory
#   --do-not-reverse-lookup     disable reverse lookup
#   --request-timeout=SECOND    request timeout in seconds
#   --http-version=VERSION      HTTP version
#   --server-name=NAME          name of the server host
#   --server-software=NAME      name and version of the server
#   --ssl-certificate=CERT      The SSL certificate file for the server
#   --ssl-private-key=KEY       The SSL private key file for the server certificate
#   -v                          verbose
#

def httpd
  setup("", "BindAddress=ADDR", "Port=PORT", "MaxClients=NUM", "TempDir=DIR",
        "DoNotReverseLookup", "RequestTimeout=SECOND", "HTTPVersion=VERSION",
        "ServerName=NAME", "ServerSoftware=NAME",
        "SSLCertificate=CERT", "SSLPrivateKey=KEY") do
    |argv, options|
    begin
      require 'webrick'
    rescue LoadError
      abort "webrick is not found. You may need to `gem install webrick` to install webrick."
    end
    opt = options[:RequestTimeout] and options[:RequestTimeout] = opt.to_i
    [:Port, :MaxClients].each do |name|
      opt = options[name] and (options[name] = Integer(opt)) rescue nil
    end
    if cert = options[:SSLCertificate]
      key = options[:SSLPrivateKey] or
        raise "--ssl-private-key option must also be given"
      require 'webrick/https'
      options[:SSLEnable] = true
      options[:SSLCertificate] = OpenSSL::X509::Certificate.new(File.read(cert))
      options[:SSLPrivateKey] = OpenSSL::PKey.read(File.read(key))
      options[:Port] ||= 8443   # HTTPS Alternate
    end
    options[:Port] ||= 8080     # HTTP Alternate
    options[:DocumentRoot] = argv.shift || '.'
    s = WEBrick::HTTPServer.new(options)
    shut = proc {s.shutdown}
    siglist = %w"TERM QUIT"
    siglist.concat(%w"HUP INT") if STDIN.tty?
    siglist &= Signal.list.keys
    siglist.each do |sig|
      Signal.trap(sig, shut)
    end
    s.start
  end
end

##
# Display help message.
#
#   ruby -run -e help [COMMAND]
#

def help
  setup do |argv,|
    UN.help(argv)
  end
end

module UN # :nodoc:
  module_function
  def help(argv, output: $stdout)
    all = argv.empty?
    cmd = nil
    if all
      store = proc {|msg| output << msg}
    else
      messages = {}
      store = proc {|msg| messages[cmd] = msg}
    end
    open(__FILE__) do |me|
      while me.gets("##\n")
        if help = me.gets("\n\n")
          if all or argv.include?(cmd = help[/^#\s*ruby\s.*-e\s+(\w+)/, 1])
            store[help.gsub(/^# ?/, "")]
            break unless all or argv.size > messages.size
          end
        end
      end
    end
    if messages
      argv.each {|arg| output << messages[arg]}
    end
  end
end
module Benchmark
  VERSION = "0.1.1"
end
# frozen_string_literal: true
require 'ripper/core'
require 'ripper/lexer'
require 'ripper/filter'
require 'ripper/sexp'

# Ripper is a Ruby script parser.
#
# You can get information from the parser with event-based style.
# Information such as abstract syntax trees or simple lexical analysis of the
# Ruby program.
#
# == Usage
#
# Ripper provides an easy interface for parsing your program into a symbolic
# expression tree (or S-expression).
#
# Understanding the output of the parser may come as a challenge, it's
# recommended you use PP to format the output for legibility.
#
#   require 'ripper'
#   require 'pp'
#
#   pp Ripper.sexp('def hello(world) "Hello, #{world}!"; end')
#     #=> [:program,
#          [[:def,
#            [:@ident, "hello", [1, 4]],
#            [:paren,
#             [:params, [[:@ident, "world", [1, 10]]], nil, nil, nil, nil, nil, nil]],
#            [:bodystmt,
#             [[:string_literal,
#               [:string_content,
#                [:@tstring_content, "Hello, ", [1, 18]],
#                [:string_embexpr, [[:var_ref, [:@ident, "world", [1, 27]]]]],
#                [:@tstring_content, "!", [1, 33]]]]],
#             nil,
#             nil,
#             nil]]]]
#
# You can see in the example above, the expression starts with +:program+.
#
# From here, a method definition at +:def+, followed by the method's identifier
# <code>:@ident</code>. After the method's identifier comes the parentheses
# +:paren+ and the method parameters under +:params+.
#
# Next is the method body, starting at +:bodystmt+ (+stmt+ meaning statement),
# which contains the full definition of the method.
#
# In our case, we're simply returning a String, so next we have the
# +:string_literal+ expression.
#
# Within our +:string_literal+ you'll notice two <code>@tstring_content</code>,
# this is the literal part for <code>Hello, </code> and <code>!</code>. Between
# the two <code>@tstring_content</code> statements is a +:string_embexpr+,
# where _embexpr_ is an embedded expression. Our expression consists of a local
# variable, or +var_ref+, with the identifier (<code>@ident</code>) of +world+.
#
# == Resources
#
# * {Ruby Inside}[http://www.rubyinside.com/using-ripper-to-see-how-ruby-is-parsing-your-code-5270.html]
#
# == Requirements
#
# * ruby 1.9 (support CVS HEAD only)
# * bison 1.28 or later (Other yaccs do not work)
#
# == License
#
# Ruby License.
#
# - Minero Aoki
# - aamine@loveruby.net
# - http://i.loveruby.net
class Ripper; end
# frozen_string_literal: true

require 'objspace.so'

module ObjectSpace
  class << self
    private :_dump
    private :_dump_all
  end

  module_function

  # call-seq:
  #   ObjectSpace.dump(obj[, output: :string]) # => "{ ... }"
  #   ObjectSpace.dump(obj, output: :file)     # => #<File:/tmp/rubyobj20131125-88733-1xkfmpv.json>
  #   ObjectSpace.dump(obj, output: :stdout)   # => nil
  #
  # Dump the contents of a ruby object as JSON.
  #
  # This method is only expected to work with C Ruby.
  # This is an experimental method and is subject to change.
  # In particular, the function signature and output format are
  # not guaranteed to be compatible in future versions of ruby.
  def dump(obj, output: :string)
    out = case output
    when :file, nil
      require 'tempfile'
      Tempfile.create(%w(rubyobj .json))
    when :stdout
      STDOUT
    when :string
      +''
    when IO
      output
    else
      raise ArgumentError, "wrong output option: #{output.inspect}"
    end

    ret = _dump(obj, out)
    return nil if output == :stdout
    ret
  end


  #  call-seq:
  #    ObjectSpace.dump_all([output: :file]) # => #<File:/tmp/rubyheap20131125-88469-laoj3v.json>
  #    ObjectSpace.dump_all(output: :stdout) # => nil
  #    ObjectSpace.dump_all(output: :string) # => "{...}\n{...}\n..."
  #    ObjectSpace.dump_all(output:
  #      File.open('heap.json','w'))         # => #<File:heap.json>
  #    ObjectSpace.dump_all(output: :string,
  #      since: 42)                          # => "{...}\n{...}\n..."
  #
  #  Dump the contents of the ruby heap as JSON.
  #
  #  _since_ must be a non-negative integer or +nil+.
  #
  #  If _since_ is a positive integer, only objects of that generation and
  #  newer generations are dumped. The current generation can be accessed using
  #  GC::count.
  #
  #  Objects that were allocated without object allocation tracing enabled
  #  are ignored. See ::trace_object_allocations for more information and
  #  examples.
  #
  #  If _since_ is omitted or is +nil+, all objects are dumped.
  #
  #  This method is only expected to work with C Ruby.
  #  This is an experimental method and is subject to change.
  #  In particular, the function signature and output format are
  #  not guaranteed to be compatible in future versions of ruby.
  def dump_all(output: :file, full: false, since: nil)
    out = case output
    when :file, nil
      require 'tempfile'
      Tempfile.create(%w(rubyheap .json))
    when :stdout
      STDOUT
    when :string
      +''
    when IO
      output
    else
      raise ArgumentError, "wrong output option: #{output.inspect}"
    end

    ret = _dump_all(out, full, since)
    return nil if output == :stdout
    ret
  end
end
# frozen_string_literal: false
# -*- ruby -*-

require 'optparse'
require 'uri'

OptionParser.accept(URI) {|s,| URI.parse(s) if s}
# frozen_string_literal: false
require 'optparse'
require 'time'

OptionParser.accept(Time) do |s,|
  begin
    (Time.httpdate(s) rescue Time.parse(s)) if s
  rescue
    raise OptionParser::InvalidArgument, s
  end
end
# frozen_string_literal: false
require 'optparse'

class OptionParser::AC < OptionParser
  private

  def _check_ac_args(name, block)
    unless /\A\w[-\w]*\z/ =~ name
      raise ArgumentError, name
    end
    unless block
      raise ArgumentError, "no block given", ParseError.filter_backtrace(caller)
    end
  end

  ARG_CONV = proc {|val| val.nil? ? true : val}

  def _ac_arg_enable(prefix, name, help_string, block)
    _check_ac_args(name, block)

    sdesc = []
    ldesc = ["--#{prefix}-#{name}"]
    desc = [help_string]
    q = name.downcase
    ac_block = proc {|val| block.call(ARG_CONV.call(val))}
    enable = Switch::PlacedArgument.new(nil, ARG_CONV, sdesc, ldesc, nil, desc, ac_block)
    disable = Switch::NoArgument.new(nil, proc {false}, sdesc, ldesc, nil, desc, ac_block)
    top.append(enable, [], ["enable-" + q], disable, ['disable-' + q])
    enable
  end

  public

  def ac_arg_enable(name, help_string, &block)
    _ac_arg_enable("enable", name, help_string, block)
  end

  def ac_arg_disable(name, help_string, &block)
    _ac_arg_enable("disable", name, help_string, block)
  end

  def ac_arg_with(name, help_string, &block)
    _check_ac_args(name, block)

    sdesc = []
    ldesc = ["--with-#{name}"]
    desc = [help_string]
    q = name.downcase
    with = Switch::PlacedArgument.new(*search(:atype, String), sdesc, ldesc, nil, desc, block)
    without = Switch::NoArgument.new(nil, proc {}, sdesc, ldesc, nil, desc, block)
    top.append(with, [], ["with-" + q], without, ['without-' + q])
    with
  end
end
# frozen_string_literal: true
require 'optparse'

class OptionParser
  # :call-seq:
  #   define_by_keywords(options, method, **params)
  #
  def define_by_keywords(options, meth, **opts)
    meth.parameters.each do |type, name|
      case type
      when :key, :keyreq
        op, cl = *(type == :key ? %w"[ ]" : ["", ""])
        define("--#{name}=#{op}#{name.upcase}#{cl}", *opts[name]) do |o|
          options[name] = o
        end
      end
    end
    options
  end
end
# frozen_string_literal: false
# -*- ruby -*-

require 'shellwords'
require 'optparse'

OptionParser.accept(Shellwords) {|s,| Shellwords.shellwords(s)}
# frozen_string_literal: false
require 'optparse'
require 'date'

OptionParser.accept(DateTime) do |s,|
  begin
    DateTime.parse(s) if s
  rescue ArgumentError
    raise OptionParser::InvalidArgument, s
  end
end
OptionParser.accept(Date) do |s,|
  begin
    Date.parse(s) if s
  rescue ArgumentError
    raise OptionParser::InvalidArgument, s
  end
end
# frozen_string_literal: false
# OptionParser internal utility

class << OptionParser
  def show_version(*pkgs)
    progname = ARGV.options.program_name
    result = false
    show = proc do |klass, cname, version|
      str = "#{progname}"
      unless klass == ::Object and cname == :VERSION
        version = version.join(".") if Array === version
        str << ": #{klass}" unless klass == Object
        str << " version #{version}"
      end
      [:Release, :RELEASE].find do |rel|
        if klass.const_defined?(rel)
          str << " (#{klass.const_get(rel)})"
        end
      end
      puts str
      result = true
    end
    if pkgs.size == 1 and pkgs[0] == "all"
      self.search_const(::Object, /\AV(?:ERSION|ersion)\z/) do |klass, cname, version|
        unless cname[1] == ?e and klass.const_defined?(:Version)
          show.call(klass, cname.intern, version)
        end
      end
    else
      pkgs.each do |pkg|
        begin
          pkg = pkg.split(/::|\//).inject(::Object) {|m, c| m.const_get(c)}
          v = case
              when pkg.const_defined?(:Version)
                pkg.const_get(n = :Version)
              when pkg.const_defined?(:VERSION)
                pkg.const_get(n = :VERSION)
              else
                n = nil
                "unknown"
              end
          show.call(pkg, n, v)
        rescue NameError
        end
      end
    end
    result
  end

  def each_const(path, base = ::Object)
    path.split(/::|\//).inject(base) do |klass, name|
      raise NameError, path unless Module === klass
      klass.constants.grep(/#{name}/i) do |c|
        klass.const_defined?(c) or next
        klass.const_get(c)
      end
    end
  end

  def search_const(klass, name)
    klasses = [klass]
    while klass = klasses.shift
      klass.constants.each do |cname|
        klass.const_defined?(cname) or next
        const = klass.const_get(cname)
        yield klass, cname, const if name === cname
        klasses << const if Module === const and const != ::Object
      end
    end
  end
end
# frozen_string_literal: true
#
# find.rb: the Find module for processing all files under a given directory.
#

#
# The +Find+ module supports the top-down traversal of a set of file paths.
#
# For example, to total the size of all files under your home directory,
# ignoring anything in a "dot" directory (e.g. $HOME/.ssh):
#
#   require 'find'
#
#   total_size = 0
#
#   Find.find(ENV["HOME"]) do |path|
#     if FileTest.directory?(path)
#       if File.basename(path).start_with?('.')
#         Find.prune       # Don't look any further into this directory.
#       else
#         next
#       end
#     else
#       total_size += FileTest.size(path)
#     end
#   end
#
module Find

  #
  # Calls the associated block with the name of every file and directory listed
  # as arguments, then recursively on their subdirectories, and so on.
  #
  # Returns an enumerator if no block is given.
  #
  # See the +Find+ module documentation for an example.
  #
  def find(*paths, ignore_error: true) # :yield: path
    block_given? or return enum_for(__method__, *paths, ignore_error: ignore_error)

    fs_encoding = Encoding.find("filesystem")

    paths.collect!{|d| raise Errno::ENOENT, d unless File.exist?(d); d.dup}.each do |path|
      path = path.to_path if path.respond_to? :to_path
      enc = path.encoding == Encoding::US_ASCII ? fs_encoding : path.encoding
      ps = [path]
      while file = ps.shift
        catch(:prune) do
          yield file.dup
          begin
            s = File.lstat(file)
          rescue Errno::ENOENT, Errno::EACCES, Errno::ENOTDIR, Errno::ELOOP, Errno::ENAMETOOLONG
            raise unless ignore_error
            next
          end
          if s.directory? then
            begin
              fs = Dir.children(file, encoding: enc)
            rescue Errno::ENOENT, Errno::EACCES, Errno::ENOTDIR, Errno::ELOOP, Errno::ENAMETOOLONG
              raise unless ignore_error
              next
            end
            fs.sort!
            fs.reverse_each {|f|
              f = File.join(file, f)
              ps.unshift f
            }
          end
        end
      end
    end
    nil
  end

  #
  # Skips the current file or directory, restarting the loop with the next
  # entry. If the current file is a directory, that directory will not be
  # recursively entered. Meaningful only within the block associated with
  # Find::find.
  #
  # See the +Find+ module documentation for an example.
  #
  def prune
    throw :prune
  end

  module_function :find, :prune
end
# frozen_string_literal: true
#
# = net/ftp.rb - FTP Client Library
#
# Written by Shugo Maeda <shugo@ruby-lang.org>.
#
# Documentation by Gavin Sinclair, sourced from "Programming Ruby" (Hunt/Thomas)
# and "Ruby In a Nutshell" (Matsumoto), used with permission.
#
# This library is distributed under the terms of the Ruby license.
# You can freely distribute/modify this library.
#
# It is included in the Ruby standard library.
#
# See the Net::FTP class for an overview.
#

require "socket"
require "monitor"
require "net/protocol"
require "time"
begin
  require "openssl"
rescue LoadError
end

module Net

  # :stopdoc:
  class FTPError < StandardError; end
  class FTPReplyError < FTPError; end
  class FTPTempError < FTPError; end
  class FTPPermError < FTPError; end
  class FTPProtoError < FTPError; end
  class FTPConnectionError < FTPError; end
  # :startdoc:

  #
  # This class implements the File Transfer Protocol.  If you have used a
  # command-line FTP program, and are familiar with the commands, you will be
  # able to use this class easily.  Some extra features are included to take
  # advantage of Ruby's style and strengths.
  #
  # == Example
  #
  #   require 'net/ftp'
  #
  # === Example 1
  #
  #   ftp = Net::FTP.new('example.com')
  #   ftp.login
  #   files = ftp.chdir('pub/lang/ruby/contrib')
  #   files = ftp.list('n*')
  #   ftp.getbinaryfile('nif.rb-0.91.gz', 'nif.gz', 1024)
  #   ftp.close
  #
  # === Example 2
  #
  #   Net::FTP.open('example.com') do |ftp|
  #     ftp.login
  #     files = ftp.chdir('pub/lang/ruby/contrib')
  #     files = ftp.list('n*')
  #     ftp.getbinaryfile('nif.rb-0.91.gz', 'nif.gz', 1024)
  #   end
  #
  # == Major Methods
  #
  # The following are the methods most likely to be useful to users:
  # - FTP.open
  # - #getbinaryfile
  # - #gettextfile
  # - #putbinaryfile
  # - #puttextfile
  # - #chdir
  # - #nlst
  # - #size
  # - #rename
  # - #delete
  #
  class FTP < Protocol
    include MonitorMixin
    if defined?(OpenSSL::SSL)
      include OpenSSL
      include SSL
    end

    # :stopdoc:
    VERSION = "0.1.2"
    FTP_PORT = 21
    CRLF = "\r\n"
    DEFAULT_BLOCKSIZE = BufferedIO::BUFSIZE
    @@default_passive = true
    # :startdoc:

    # When +true+, transfers are performed in binary mode.  Default: +true+.
    attr_reader :binary

    # When +true+, the connection is in passive mode.  Default: +true+.
    attr_accessor :passive

    # When +true+, use the IP address in PASV responses.  Otherwise, it uses
    # the same IP address for the control connection.  Default: +false+.
    attr_accessor :use_pasv_ip

    # When +true+, all traffic to and from the server is written
    # to +$stdout+.  Default: +false+.
    attr_accessor :debug_mode

    # Sets or retrieves the +resume+ status, which decides whether incomplete
    # transfers are resumed or restarted.  Default: +false+.
    attr_accessor :resume

    # Number of seconds to wait for the connection to open. Any number
    # may be used, including Floats for fractional seconds. If the FTP
    # object cannot open a connection in this many seconds, it raises a
    # Net::OpenTimeout exception. The default value is +nil+.
    attr_accessor :open_timeout

    # Number of seconds to wait for the TLS handshake. Any number
    # may be used, including Floats for fractional seconds. If the FTP
    # object cannot complete the TLS handshake in this many seconds, it
    # raises a Net::OpenTimeout exception. The default value is +nil+.
    # If +ssl_handshake_timeout+ is +nil+, +open_timeout+ is used instead.
    attr_accessor :ssl_handshake_timeout

    # Number of seconds to wait for one block to be read (via one read(2)
    # call). Any number may be used, including Floats for fractional
    # seconds. If the FTP object cannot read data in this many seconds,
    # it raises a Timeout::Error exception. The default value is 60 seconds.
    attr_reader :read_timeout

    # Setter for the read_timeout attribute.
    def read_timeout=(sec)
      @sock.read_timeout = sec
      @read_timeout = sec
    end

    # The server's welcome message.
    attr_reader :welcome

    # The server's last response code.
    attr_reader :last_response_code
    alias lastresp last_response_code

    # The server's last response.
    attr_reader :last_response

    # When +true+, connections are in passive mode per default.
    # Default: +true+.
    def self.default_passive=(value)
      @@default_passive = value
    end

    # When +true+, connections are in passive mode per default.
    # Default: +true+.
    def self.default_passive
      @@default_passive
    end

    #
    # A synonym for <tt>FTP.new</tt>, but with a mandatory host parameter.
    #
    # If a block is given, it is passed the +FTP+ object, which will be closed
    # when the block finishes, or when an exception is raised.
    #
    def FTP.open(host, *args)
      if block_given?
        ftp = new(host, *args)
        begin
          yield ftp
        ensure
          ftp.close
        end
      else
        new(host, *args)
      end
    end

    # :call-seq:
    #    Net::FTP.new(host = nil, options = {})
    #
    # Creates and returns a new +FTP+ object. If a +host+ is given, a connection
    # is made.
    #
    # +options+ is an option hash, each key of which is a symbol.
    #
    # The available options are:
    #
    # port::      Port number (default value is 21)
    # ssl::       If +options+[:ssl] is true, then an attempt will be made
    #             to use SSL (now TLS) to connect to the server.  For this
    #             to work OpenSSL [OSSL] and the Ruby OpenSSL [RSSL]
    #             extensions need to be installed.  If +options+[:ssl] is a
    #             hash, it's passed to OpenSSL::SSL::SSLContext#set_params
    #             as parameters.
    # private_data_connection::  If true, TLS is used for data connections.
    #                            Default: +true+ when +options+[:ssl] is true.
    # username::  Username for login.  If +options+[:username] is the string
    #             "anonymous" and the +options+[:password] is +nil+,
    #             "anonymous@" is used as a password.
    # password::  Password for login.
    # account::   Account information for ACCT.
    # passive::   When +true+, the connection is in passive mode. Default:
    #             +true+.
    # open_timeout::  Number of seconds to wait for the connection to open.
    #                 See Net::FTP#open_timeout for details.  Default: +nil+.
    # read_timeout::  Number of seconds to wait for one block to be read.
    #                 See Net::FTP#read_timeout for details.  Default: +60+.
    # ssl_handshake_timeout::  Number of seconds to wait for the TLS
    #                          handshake.
    #                          See Net::FTP#ssl_handshake_timeout for
    #                          details.  Default: +nil+.
    # use_pasv_ip::  When +true+, use the IP address in PASV responses.
    #                Otherwise, it uses the same IP address for the control
    #                connection.  Default: +false+.
    # debug_mode::  When +true+, all traffic to and from the server is
    #               written to +$stdout+.  Default: +false+.
    #
    def initialize(host = nil, user_or_options = {}, passwd = nil, acct = nil)
      super()
      begin
        options = user_or_options.to_hash
      rescue NoMethodError
        # for backward compatibility
        options = {}
        options[:username] = user_or_options
        options[:password] = passwd
        options[:account] = acct
      end
      @host = nil
      if options[:ssl]
        unless defined?(OpenSSL::SSL)
          raise "SSL extension not installed"
        end
        ssl_params = options[:ssl] == true ? {} : options[:ssl]
        @ssl_context = SSLContext.new
        @ssl_context.set_params(ssl_params)
        if defined?(VerifyCallbackProc)
          @ssl_context.verify_callback = VerifyCallbackProc
        end
        @ssl_context.session_cache_mode =
          OpenSSL::SSL::SSLContext::SESSION_CACHE_CLIENT |
          OpenSSL::SSL::SSLContext::SESSION_CACHE_NO_INTERNAL_STORE
        @ssl_context.session_new_cb = proc {|sock, sess| @ssl_session = sess }
        @ssl_session = nil
        if options[:private_data_connection].nil?
          @private_data_connection = true
        else
          @private_data_connection = options[:private_data_connection]
        end
      else
        @ssl_context = nil
        if options[:private_data_connection]
          raise ArgumentError,
            "private_data_connection can be set to true only when ssl is enabled"
        end
        @private_data_connection = false
      end
      @binary = true
      if options[:passive].nil?
        @passive = @@default_passive
      else
        @passive = options[:passive]
      end
      if options[:debug_mode].nil?
        @debug_mode = false
      else
        @debug_mode = options[:debug_mode]
      end
      @resume = false
      @bare_sock = @sock = NullSocket.new
      @logged_in = false
      @open_timeout = options[:open_timeout]
      @ssl_handshake_timeout = options[:ssl_handshake_timeout]
      @read_timeout = options[:read_timeout] || 60
      @use_pasv_ip = options[:use_pasv_ip] || false
      if host
        connect(host, options[:port] || FTP_PORT)
        if options[:username]
          login(options[:username], options[:password], options[:account])
        end
      end
    end

    # A setter to toggle transfers in binary mode.
    # +newmode+ is either +true+ or +false+
    def binary=(newmode)
      if newmode != @binary
        @binary = newmode
        send_type_command if @logged_in
      end
    end

    # Sends a command to destination host, with the current binary sendmode
    # type.
    #
    # If binary mode is +true+, then "TYPE I" (image) is sent, otherwise "TYPE
    # A" (ascii) is sent.
    def send_type_command # :nodoc:
      if @binary
        voidcmd("TYPE I")
      else
        voidcmd("TYPE A")
      end
    end
    private :send_type_command

    # Toggles transfers in binary mode and yields to a block.
    # This preserves your current binary send mode, but allows a temporary
    # transaction with binary sendmode of +newmode+.
    #
    # +newmode+ is either +true+ or +false+
    def with_binary(newmode) # :nodoc:
      oldmode = binary
      self.binary = newmode
      begin
        yield
      ensure
        self.binary = oldmode
      end
    end
    private :with_binary

    # Obsolete
    def return_code # :nodoc:
      warn("Net::FTP#return_code is obsolete and do nothing", uplevel: 1)
      return "\n"
    end

    # Obsolete
    def return_code=(s) # :nodoc:
      warn("Net::FTP#return_code= is obsolete and do nothing", uplevel: 1)
    end

    # Constructs a socket with +host+ and +port+.
    #
    # If SOCKSSocket is defined and the environment (ENV) defines
    # SOCKS_SERVER, then a SOCKSSocket is returned, else a Socket is
    # returned.
    def open_socket(host, port) # :nodoc:
      if defined? SOCKSSocket and ENV["SOCKS_SERVER"]
        @passive = true
        Timeout.timeout(@open_timeout, OpenTimeout) do
          SOCKSSocket.open(host, port)
        end
      else
        begin
          Socket.tcp host, port, nil, nil, connect_timeout: @open_timeout
        rescue Errno::ETIMEDOUT #raise Net:OpenTimeout instead for compatibility with previous versions
          raise Net::OpenTimeout, "Timeout to open TCP connection to "\
          "#{host}:#{port} (exceeds #{@open_timeout} seconds)"
        end
      end
    end
    private :open_socket

    def start_tls_session(sock)
      ssl_sock = SSLSocket.new(sock, @ssl_context)
      ssl_sock.sync_close = true
      ssl_sock.hostname = @host if ssl_sock.respond_to? :hostname=
      if @ssl_session &&
          Process.clock_gettime(Process::CLOCK_REALTIME) < @ssl_session.time.to_f + @ssl_session.timeout
        # ProFTPD returns 425 for data connections if session is not reused.
        ssl_sock.session = @ssl_session
      end
      ssl_socket_connect(ssl_sock, @ssl_handshake_timeout || @open_timeout)
      if @ssl_context.verify_mode != VERIFY_NONE
        ssl_sock.post_connection_check(@host)
      end
      return ssl_sock
    end
    private :start_tls_session

    #
    # Establishes an FTP connection to host, optionally overriding the default
    # port. If the environment variable +SOCKS_SERVER+ is set, sets up the
    # connection through a SOCKS proxy. Raises an exception (typically
    # <tt>Errno::ECONNREFUSED</tt>) if the connection cannot be established.
    #
    def connect(host, port = FTP_PORT)
      if @debug_mode
        print "connect: ", host, ", ", port, "\n"
      end
      synchronize do
        @host = host
        @bare_sock = open_socket(host, port)
        @sock = BufferedSocket.new(@bare_sock, read_timeout: @read_timeout)
        voidresp
        if @ssl_context
          begin
            voidcmd("AUTH TLS")
            ssl_sock = start_tls_session(@bare_sock)
            @sock = BufferedSSLSocket.new(ssl_sock, read_timeout: @read_timeout)
            if @private_data_connection
              voidcmd("PBSZ 0")
              voidcmd("PROT P")
            end
          rescue OpenSSL::SSL::SSLError, OpenTimeout
            @sock.close
            raise
          end
        end
      end
    end

    #
    # Set the socket used to connect to the FTP server.
    #
    # May raise FTPReplyError if +get_greeting+ is false.
    def set_socket(sock, get_greeting = true)
      synchronize do
        @sock = sock
        if get_greeting
          voidresp
        end
      end
    end

    # If string +s+ includes the PASS command (password), then the contents of
    # the password are cleaned from the string using "*"
    def sanitize(s) # :nodoc:
      if s =~ /^PASS /i
        return s[0, 5] + "*" * (s.length - 5)
      else
        return s
      end
    end
    private :sanitize

    # Ensures that +line+ has a control return / line feed (CRLF) and writes
    # it to the socket.
    def putline(line) # :nodoc:
      if @debug_mode
        print "put: ", sanitize(line), "\n"
      end
      if /[\r\n]/ =~ line
        raise ArgumentError, "A line must not contain CR or LF"
      end
      line = line + CRLF
      @sock.write(line)
    end
    private :putline

    # Reads a line from the sock.  If EOF, then it will raise EOFError
    def getline # :nodoc:
      line = @sock.readline # if get EOF, raise EOFError
      line.sub!(/(\r\n|\n|\r)\z/n, "")
      if @debug_mode
        print "get: ", sanitize(line), "\n"
      end
      return line
    end
    private :getline

    # Receive a section of lines until the response code's match.
    def getmultiline # :nodoc:
      lines = []
      lines << getline
      code = lines.last.slice(/\A([0-9a-zA-Z]{3})-/, 1)
      if code
        delimiter = code + " "
        begin
          lines << getline
        end until lines.last.start_with?(delimiter)
      end
      return lines.join("\n") + "\n"
    end
    private :getmultiline

    # Receives a response from the destination host.
    #
    # Returns the response code or raises FTPTempError, FTPPermError, or
    # FTPProtoError
    def getresp # :nodoc:
      @last_response = getmultiline
      @last_response_code = @last_response[0, 3]
      case @last_response_code
      when /\A[123]/
        return @last_response
      when /\A4/
        raise FTPTempError, @last_response
      when /\A5/
        raise FTPPermError, @last_response
      else
        raise FTPProtoError, @last_response
      end
    end
    private :getresp

    # Receives a response.
    #
    # Raises FTPReplyError if the first position of the response code is not
    # equal 2.
    def voidresp # :nodoc:
      resp = getresp
      if !resp.start_with?("2")
        raise FTPReplyError, resp
      end
    end
    private :voidresp

    #
    # Sends a command and returns the response.
    #
    def sendcmd(cmd)
      synchronize do
        putline(cmd)
        return getresp
      end
    end

    #
    # Sends a command and expect a response beginning with '2'.
    #
    def voidcmd(cmd)
      synchronize do
        putline(cmd)
        voidresp
      end
    end

    # Constructs and send the appropriate PORT (or EPRT) command
    def sendport(host, port) # :nodoc:
      remote_address = @bare_sock.remote_address
      if remote_address.ipv4?
        cmd = "PORT " + (host.split(".") + port.divmod(256)).join(",")
      elsif remote_address.ipv6?
        cmd = sprintf("EPRT |2|%s|%d|", host, port)
      else
        raise FTPProtoError, host
      end
      voidcmd(cmd)
    end
    private :sendport

    # Constructs a TCPServer socket
    def makeport # :nodoc:
      Addrinfo.tcp(@bare_sock.local_address.ip_address, 0).listen
    end
    private :makeport

    # sends the appropriate command to enable a passive connection
    def makepasv # :nodoc:
      if @bare_sock.remote_address.ipv4?
        host, port = parse227(sendcmd("PASV"))
      else
        host, port = parse229(sendcmd("EPSV"))
        #     host, port = parse228(sendcmd("LPSV"))
      end
      return host, port
    end
    private :makepasv

    # Constructs a connection for transferring data
    def transfercmd(cmd, rest_offset = nil) # :nodoc:
      if @passive
        host, port = makepasv
        begin
          conn = open_socket(host, port)
          if @resume and rest_offset
            resp = sendcmd("REST " + rest_offset.to_s)
            if !resp.start_with?("3")
              raise FTPReplyError, resp
            end
          end
          resp = sendcmd(cmd)
          # skip 2XX for some ftp servers
          resp = getresp if resp.start_with?("2")
          if !resp.start_with?("1")
            raise FTPReplyError, resp
          end
        ensure
          conn.close if conn && $!
        end
      else
        sock = makeport
        begin
          addr = sock.local_address
          sendport(addr.ip_address, addr.ip_port)
          if @resume and rest_offset
            resp = sendcmd("REST " + rest_offset.to_s)
            if !resp.start_with?("3")
              raise FTPReplyError, resp
            end
          end
          resp = sendcmd(cmd)
          # skip 2XX for some ftp servers
          resp = getresp if resp.start_with?("2")
          if !resp.start_with?("1")
            raise FTPReplyError, resp
          end
          conn, = sock.accept
          sock.shutdown(Socket::SHUT_WR) rescue nil
          sock.read rescue nil
        ensure
          sock.close
        end
      end
      if @private_data_connection
        return BufferedSSLSocket.new(start_tls_session(conn),
                                     read_timeout: @read_timeout)
      else
        return BufferedSocket.new(conn, read_timeout: @read_timeout)
      end
    end
    private :transfercmd

    #
    # Logs in to the remote host.  The session must have been
    # previously connected.  If +user+ is the string "anonymous" and
    # the +password+ is +nil+, "anonymous@" is used as a password.  If
    # the +acct+ parameter is not +nil+, an FTP ACCT command is sent
    # following the successful login.  Raises an exception on error
    # (typically <tt>Net::FTPPermError</tt>).
    #
    def login(user = "anonymous", passwd = nil, acct = nil)
      if user == "anonymous" and passwd == nil
        passwd = "anonymous@"
      end

      resp = ""
      synchronize do
        resp = sendcmd('USER ' + user)
        if resp.start_with?("3")
          raise FTPReplyError, resp if passwd.nil?
          resp = sendcmd('PASS ' + passwd)
        end
        if resp.start_with?("3")
          raise FTPReplyError, resp if acct.nil?
          resp = sendcmd('ACCT ' + acct)
        end
      end
      if !resp.start_with?("2")
        raise FTPReplyError, resp
      end
      @welcome = resp
      send_type_command
      @logged_in = true
    end

    #
    # Puts the connection into binary (image) mode, issues the given command,
    # and fetches the data returned, passing it to the associated block in
    # chunks of +blocksize+ characters. Note that +cmd+ is a server command
    # (such as "RETR myfile").
    #
    def retrbinary(cmd, blocksize, rest_offset = nil) # :yield: data
      synchronize do
        with_binary(true) do
          begin
            conn = transfercmd(cmd, rest_offset)
            while data = conn.read(blocksize)
              yield(data)
            end
            conn.shutdown(Socket::SHUT_WR) rescue nil
            conn.read_timeout = 1
            conn.read rescue nil
          ensure
            conn.close if conn
          end
          voidresp
        end
      end
    end

    #
    # Puts the connection into ASCII (text) mode, issues the given command, and
    # passes the resulting data, one line at a time, to the associated block. If
    # no block is given, prints the lines. Note that +cmd+ is a server command
    # (such as "RETR myfile").
    #
    def retrlines(cmd) # :yield: line
      synchronize do
        with_binary(false) do
          begin
            conn = transfercmd(cmd)
            while line = conn.gets
              yield(line.sub(/\r?\n\z/, ""), !line.match(/\n\z/).nil?)
            end
            conn.shutdown(Socket::SHUT_WR) rescue nil
            conn.read_timeout = 1
            conn.read rescue nil
          ensure
            conn.close if conn
          end
          voidresp
        end
      end
    end

    #
    # Puts the connection into binary (image) mode, issues the given server-side
    # command (such as "STOR myfile"), and sends the contents of the file named
    # +file+ to the server. If the optional block is given, it also passes it
    # the data, in chunks of +blocksize+ characters.
    #
    def storbinary(cmd, file, blocksize, rest_offset = nil) # :yield: data
      if rest_offset
        file.seek(rest_offset, IO::SEEK_SET)
      end
      synchronize do
        with_binary(true) do
          begin
            conn = transfercmd(cmd)
            while buf = file.read(blocksize)
              conn.write(buf)
              yield(buf) if block_given?
            end
            conn.shutdown(Socket::SHUT_WR) rescue nil
            conn.read_timeout = 1
            conn.read rescue nil
          ensure
            conn.close if conn
          end
          voidresp
        end
      end
    rescue Errno::EPIPE
      # EPIPE, in this case, means that the data connection was unexpectedly
      # terminated.  Rather than just raising EPIPE to the caller, check the
      # response on the control connection.  If getresp doesn't raise a more
      # appropriate exception, re-raise the original exception.
      getresp
      raise
    end

    #
    # Puts the connection into ASCII (text) mode, issues the given server-side
    # command (such as "STOR myfile"), and sends the contents of the file
    # named +file+ to the server, one line at a time. If the optional block is
    # given, it also passes it the lines.
    #
    def storlines(cmd, file) # :yield: line
      synchronize do
        with_binary(false) do
          begin
            conn = transfercmd(cmd)
            while buf = file.gets
              if buf[-2, 2] != CRLF
                buf = buf.chomp + CRLF
              end
              conn.write(buf)
              yield(buf) if block_given?
            end
            conn.shutdown(Socket::SHUT_WR) rescue nil
            conn.read_timeout = 1
            conn.read rescue nil
          ensure
            conn.close if conn
          end
          voidresp
        end
      end
    rescue Errno::EPIPE
      # EPIPE, in this case, means that the data connection was unexpectedly
      # terminated.  Rather than just raising EPIPE to the caller, check the
      # response on the control connection.  If getresp doesn't raise a more
      # appropriate exception, re-raise the original exception.
      getresp
      raise
    end

    #
    # Retrieves +remotefile+ in binary mode, storing the result in +localfile+.
    # If +localfile+ is nil, returns retrieved data.
    # If a block is supplied, it is passed the retrieved data in +blocksize+
    # chunks.
    #
    def getbinaryfile(remotefile, localfile = File.basename(remotefile),
                      blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data
      f = nil
      result = nil
      if localfile
        if @resume
          rest_offset = File.size?(localfile)
          f = File.open(localfile, "a")
        else
          rest_offset = nil
          f = File.open(localfile, "w")
        end
      elsif !block_given?
        result = String.new
      end
      begin
        f&.binmode
        retrbinary("RETR #{remotefile}", blocksize, rest_offset) do |data|
          f&.write(data)
          block&.(data)
          result&.concat(data)
        end
        return result
      ensure
        f&.close
      end
    end

    #
    # Retrieves +remotefile+ in ASCII (text) mode, storing the result in
    # +localfile+.
    # If +localfile+ is nil, returns retrieved data.
    # If a block is supplied, it is passed the retrieved data one
    # line at a time.
    #
    def gettextfile(remotefile, localfile = File.basename(remotefile),
                    &block) # :yield: line
      f = nil
      result = nil
      if localfile
        f = File.open(localfile, "w")
      elsif !block_given?
        result = String.new
      end
      begin
        retrlines("RETR #{remotefile}") do |line, newline|
          l = newline ? line + "\n" : line
          f&.print(l)
          block&.(line, newline)
          result&.concat(l)
        end
        return result
      ensure
        f&.close
      end
    end

    #
    # Retrieves +remotefile+ in whatever mode the session is set (text or
    # binary).  See #gettextfile and #getbinaryfile.
    #
    def get(remotefile, localfile = File.basename(remotefile),
            blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data
      if @binary
        getbinaryfile(remotefile, localfile, blocksize, &block)
      else
        gettextfile(remotefile, localfile, &block)
      end
    end

    #
    # Transfers +localfile+ to the server in binary mode, storing the result in
    # +remotefile+. If a block is supplied, calls it, passing in the transmitted
    # data in +blocksize+ chunks.
    #
    def putbinaryfile(localfile, remotefile = File.basename(localfile),
                      blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data
      if @resume
        begin
          rest_offset = size(remotefile)
        rescue Net::FTPPermError
          rest_offset = nil
        end
      else
        rest_offset = nil
      end
      f = File.open(localfile)
      begin
        f.binmode
        if rest_offset
          storbinary("APPE #{remotefile}", f, blocksize, rest_offset, &block)
        else
          storbinary("STOR #{remotefile}", f, blocksize, rest_offset, &block)
        end
      ensure
        f.close
      end
    end

    #
    # Transfers +localfile+ to the server in ASCII (text) mode, storing the result
    # in +remotefile+. If callback or an associated block is supplied, calls it,
    # passing in the transmitted data one line at a time.
    #
    def puttextfile(localfile, remotefile = File.basename(localfile), &block) # :yield: line
      f = File.open(localfile)
      begin
        storlines("STOR #{remotefile}", f, &block)
      ensure
        f.close
      end
    end

    #
    # Transfers +localfile+ to the server in whatever mode the session is set
    # (text or binary).  See #puttextfile and #putbinaryfile.
    #
    def put(localfile, remotefile = File.basename(localfile),
            blocksize = DEFAULT_BLOCKSIZE, &block)
      if @binary
        putbinaryfile(localfile, remotefile, blocksize, &block)
      else
        puttextfile(localfile, remotefile, &block)
      end
    end

    #
    # Sends the ACCT command.
    #
    # This is a less common FTP command, to send account
    # information if the destination host requires it.
    #
    def acct(account)
      cmd = "ACCT " + account
      voidcmd(cmd)
    end

    #
    # Returns an array of filenames in the remote directory.
    #
    def nlst(dir = nil)
      cmd = "NLST"
      if dir
        cmd = "#{cmd} #{dir}"
      end
      files = []
      retrlines(cmd) do |line|
        files.push(line)
      end
      return files
    end

    #
    # Returns an array of file information in the directory (the output is like
    # `ls -l`).  If a block is given, it iterates through the listing.
    #
    def list(*args, &block) # :yield: line
      cmd = "LIST"
      args.each do |arg|
        cmd = "#{cmd} #{arg}"
      end
      lines = []
      retrlines(cmd) do |line|
        lines << line
      end
      if block
        lines.each(&block)
      end
      return lines
    end
    alias ls list
    alias dir list

    #
    # MLSxEntry represents an entry in responses of MLST/MLSD.
    # Each entry has the facts (e.g., size, last modification time, etc.)
    # and the pathname.
    #
    class MLSxEntry
      attr_reader :facts, :pathname

      def initialize(facts, pathname)
        @facts = facts
        @pathname = pathname
      end

      standard_facts = %w(size modify create type unique perm
                          lang media-type charset)
      standard_facts.each do |factname|
        define_method factname.gsub(/-/, "_") do
          facts[factname]
        end
      end

      #
      # Returns +true+ if the entry is a file (i.e., the value of the type
      # fact is file).
      #
      def file?
        return facts["type"] == "file"
      end

      #
      # Returns +true+ if the entry is a directory (i.e., the value of the
      # type fact is dir, cdir, or pdir).
      #
      def directory?
        if /\A[cp]?dir\z/.match(facts["type"])
          return true
        else
          return false
        end
      end

      #
      # Returns +true+ if the APPE command may be applied to the file.
      #
      def appendable?
        return facts["perm"].include?(?a)
      end

      #
      # Returns +true+ if files may be created in the directory by STOU,
      # STOR, APPE, and RNTO.
      #
      def creatable?
        return facts["perm"].include?(?c)
      end

      #
      # Returns +true+ if the file or directory may be deleted by DELE/RMD.
      #
      def deletable?
        return facts["perm"].include?(?d)
      end

      #
      # Returns +true+ if the directory may be entered by CWD/CDUP.
      #
      def enterable?
        return facts["perm"].include?(?e)
      end

      #
      # Returns +true+ if the file or directory may be renamed by RNFR.
      #
      def renamable?
        return facts["perm"].include?(?f)
      end

      #
      # Returns +true+ if the listing commands, LIST, NLST, and MLSD are
      # applied to the directory.
      #
      def listable?
        return facts["perm"].include?(?l)
      end

      #
      # Returns +true+ if the MKD command may be used to create a new
      # directory within the directory.
      #
      def directory_makable?
        return facts["perm"].include?(?m)
      end

      #
      # Returns +true+ if the objects in the directory may be deleted, or
      # the directory may be purged.
      #
      def purgeable?
        return facts["perm"].include?(?p)
      end

      #
      # Returns +true+ if the RETR command may be applied to the file.
      #
      def readable?
        return facts["perm"].include?(?r)
      end

      #
      # Returns +true+ if the STOR command may be applied to the file.
      #
      def writable?
        return facts["perm"].include?(?w)
      end
    end

    CASE_DEPENDENT_PARSER = ->(value) { value }
    CASE_INDEPENDENT_PARSER = ->(value) { value.downcase }
    DECIMAL_PARSER = ->(value) { value.to_i }
    OCTAL_PARSER = ->(value) { value.to_i(8) }
    TIME_PARSER = ->(value, local = false) {
      unless /\A(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})
            (?<hour>\d{2})(?<min>\d{2})(?<sec>\d{2})
            (?:\.(?<fractions>\d{1,17}))?/x =~ value
        value = value[0, 97] + "..." if value.size > 100
        raise FTPProtoError, "invalid time-val: #{value}"
      end
      usec = ".#{fractions}".to_r * 1_000_000 if fractions
      Time.public_send(local ? :local : :utc, year, month, day, hour, min, sec, usec)
    }
    FACT_PARSERS = Hash.new(CASE_DEPENDENT_PARSER)
    FACT_PARSERS["size"] = DECIMAL_PARSER
    FACT_PARSERS["modify"] = TIME_PARSER
    FACT_PARSERS["create"] = TIME_PARSER
    FACT_PARSERS["type"] = CASE_INDEPENDENT_PARSER
    FACT_PARSERS["unique"] = CASE_DEPENDENT_PARSER
    FACT_PARSERS["perm"] = CASE_INDEPENDENT_PARSER
    FACT_PARSERS["lang"] = CASE_INDEPENDENT_PARSER
    FACT_PARSERS["media-type"] = CASE_INDEPENDENT_PARSER
    FACT_PARSERS["charset"] = CASE_INDEPENDENT_PARSER
    FACT_PARSERS["unix.mode"] = OCTAL_PARSER
    FACT_PARSERS["unix.owner"] = DECIMAL_PARSER
    FACT_PARSERS["unix.group"] = DECIMAL_PARSER
    FACT_PARSERS["unix.ctime"] = TIME_PARSER
    FACT_PARSERS["unix.atime"] = TIME_PARSER

    def parse_mlsx_entry(entry)
      facts, pathname = entry.chomp.split(/ /, 2)
      unless pathname
        raise FTPProtoError, entry
      end
      return MLSxEntry.new(
        facts.scan(/(.*?)=(.*?);/).each_with_object({}) {
          |(factname, value), h|
          name = factname.downcase
          h[name] = FACT_PARSERS[name].(value)
        },
        pathname)
    end
    private :parse_mlsx_entry

    #
    # Returns data (e.g., size, last modification time, entry type, etc.)
    # about the file or directory specified by +pathname+.
    # If +pathname+ is omitted, the current directory is assumed.
    #
    def mlst(pathname = nil)
      cmd = pathname ? "MLST #{pathname}" : "MLST"
      resp = sendcmd(cmd)
      if !resp.start_with?("250")
        raise FTPReplyError, resp
      end
      line = resp.lines[1]
      unless line
        raise FTPProtoError, resp
      end
      entry = line.sub(/\A(250-| *)/, "")
      return parse_mlsx_entry(entry)
    end

    #
    # Returns an array of the entries of the directory specified by
    # +pathname+.
    # Each entry has the facts (e.g., size, last modification time, etc.)
    # and the pathname.
    # If a block is given, it iterates through the listing.
    # If +pathname+ is omitted, the current directory is assumed.
    #
    def mlsd(pathname = nil, &block) # :yield: entry
      cmd = pathname ? "MLSD #{pathname}" : "MLSD"
      entries = []
      retrlines(cmd) do |line|
        entries << parse_mlsx_entry(line)
      end
      if block
        entries.each(&block)
      end
      return entries
    end

    #
    # Renames a file on the server.
    #
    def rename(fromname, toname)
      resp = sendcmd("RNFR #{fromname}")
      if !resp.start_with?("3")
        raise FTPReplyError, resp
      end
      voidcmd("RNTO #{toname}")
    end

    #
    # Deletes a file on the server.
    #
    def delete(filename)
      resp = sendcmd("DELE #{filename}")
      if resp.start_with?("250")
        return
      elsif resp.start_with?("5")
        raise FTPPermError, resp
      else
        raise FTPReplyError, resp
      end
    end

    #
    # Changes the (remote) directory.
    #
    def chdir(dirname)
      if dirname == ".."
        begin
          voidcmd("CDUP")
          return
        rescue FTPPermError => e
          if e.message[0, 3] != "500"
            raise e
          end
        end
      end
      cmd = "CWD #{dirname}"
      voidcmd(cmd)
    end

    def get_body(resp) # :nodoc:
      resp.slice(/\A[0-9a-zA-Z]{3} (.*)$/, 1)
    end
    private :get_body

    #
    # Returns the size of the given (remote) filename.
    #
    def size(filename)
      with_binary(true) do
        resp = sendcmd("SIZE #{filename}")
        if !resp.start_with?("213")
          raise FTPReplyError, resp
        end
        return get_body(resp).to_i
      end
    end

    #
    # Returns the last modification time of the (remote) file.  If +local+ is
    # +true+, it is returned as a local time, otherwise it's a UTC time.
    #
    def mtime(filename, local = false)
      return TIME_PARSER.(mdtm(filename), local)
    end

    #
    # Creates a remote directory.
    #
    def mkdir(dirname)
      resp = sendcmd("MKD #{dirname}")
      return parse257(resp)
    end

    #
    # Removes a remote directory.
    #
    def rmdir(dirname)
      voidcmd("RMD #{dirname}")
    end

    #
    # Returns the current remote directory.
    #
    def pwd
      resp = sendcmd("PWD")
      return parse257(resp)
    end
    alias getdir pwd

    #
    # Returns system information.
    #
    def system
      resp = sendcmd("SYST")
      if !resp.start_with?("215")
        raise FTPReplyError, resp
      end
      return get_body(resp)
    end

    #
    # Aborts the previous command (ABOR command).
    #
    def abort
      line = "ABOR" + CRLF
      print "put: ABOR\n" if @debug_mode
      @sock.send(line, Socket::MSG_OOB)
      resp = getmultiline
      unless ["426", "226", "225"].include?(resp[0, 3])
        raise FTPProtoError, resp
      end
      return resp
    end

    #
    # Returns the status (STAT command).
    #
    # pathname:: when stat is invoked with pathname as a parameter it acts like
    #            list but a lot faster and over the same tcp session.
    #
    def status(pathname = nil)
      line = pathname ? "STAT #{pathname}" : "STAT"
      if /[\r\n]/ =~ line
        raise ArgumentError, "A line must not contain CR or LF"
      end
      print "put: #{line}\n" if @debug_mode
      @sock.send(line + CRLF, Socket::MSG_OOB)
      return getresp
    end

    #
    # Returns the raw last modification time of the (remote) file in the format
    # "YYYYMMDDhhmmss" (MDTM command).
    #
    # Use +mtime+ if you want a parsed Time instance.
    #
    def mdtm(filename)
      resp = sendcmd("MDTM #{filename}")
      if resp.start_with?("213")
        return get_body(resp)
      end
    end

    #
    # Issues the HELP command.
    #
    def help(arg = nil)
      cmd = "HELP"
      if arg
        cmd = cmd + " " + arg
      end
      sendcmd(cmd)
    end

    #
    # Exits the FTP session.
    #
    def quit
      voidcmd("QUIT")
    end

    #
    # Issues a NOOP command.
    #
    # Does nothing except return a response.
    #
    def noop
      voidcmd("NOOP")
    end

    #
    # Issues a SITE command.
    #
    def site(arg)
      cmd = "SITE " + arg
      voidcmd(cmd)
    end

    #
    # Issues a FEAT command
    #
    # Returns an array of supported optional features
    #
    def features
      resp = sendcmd("FEAT")
      if !resp.start_with?("211")
        raise FTPReplyError, resp
      end

      feats = []
      resp.split("\n").each do |line|
        next if !line.start_with?(' ') # skip status lines

        feats << line.strip
      end

      return feats
    end

    #
    # Issues an OPTS command
    # - name Should be the name of the option to set
    # - params is any optional parameters to supply with the option
    #
    # example: option('UTF8', 'ON') => 'OPTS UTF8 ON'
    #
    def option(name, params = nil)
      cmd = "OPTS #{name}"
      cmd += " #{params}" if params

      voidcmd(cmd)
    end

    #
    # Closes the connection.  Further operations are impossible until you open
    # a new connection with #connect.
    #
    def close
      if @sock and not @sock.closed?
        begin
          @sock.shutdown(Socket::SHUT_WR) rescue nil
          orig, self.read_timeout = self.read_timeout, 3
          @sock.read rescue nil
        ensure
          @sock.close
          self.read_timeout = orig
        end
      end
    end

    #
    # Returns +true+ if and only if the connection is closed.
    #
    def closed?
      @sock == nil or @sock.closed?
    end

    # handler for response code 227
    # (Entering Passive Mode (h1,h2,h3,h4,p1,p2))
    #
    # Returns host and port.
    def parse227(resp) # :nodoc:
      if !resp.start_with?("227")
        raise FTPReplyError, resp
      end
      if m = /\((?<host>\d+(?:,\d+){3}),(?<port>\d+,\d+)\)/.match(resp)
        if @use_pasv_ip
          host = parse_pasv_ipv4_host(m["host"])
        else
          host = @bare_sock.remote_address.ip_address
        end
        return host, parse_pasv_port(m["port"])
      else
        raise FTPProtoError, resp
      end
    end
    private :parse227

    # handler for response code 228
    # (Entering Long Passive Mode)
    #
    # Returns host and port.
    def parse228(resp) # :nodoc:
      if !resp.start_with?("228")
        raise FTPReplyError, resp
      end
      if m = /\(4,4,(?<host>\d+(?:,\d+){3}),2,(?<port>\d+,\d+)\)/.match(resp)
        return parse_pasv_ipv4_host(m["host"]), parse_pasv_port(m["port"])
      elsif m = /\(6,16,(?<host>\d+(?:,\d+){15}),2,(?<port>\d+,\d+)\)/.match(resp)
        return parse_pasv_ipv6_host(m["host"]), parse_pasv_port(m["port"])
      else
        raise FTPProtoError, resp
      end
    end
    private :parse228

    def parse_pasv_ipv4_host(s)
      return s.tr(",", ".")
    end
    private :parse_pasv_ipv4_host

    def parse_pasv_ipv6_host(s)
      return s.split(/,/).map { |i|
        "%02x" % i.to_i
      }.each_slice(2).map(&:join).join(":")
    end
    private :parse_pasv_ipv6_host

    def parse_pasv_port(s)
      return s.split(/,/).map(&:to_i).inject { |x, y|
        (x << 8) + y
      }
    end
    private :parse_pasv_port

    # handler for response code 229
    # (Extended Passive Mode Entered)
    #
    # Returns host and port.
    def parse229(resp) # :nodoc:
      if !resp.start_with?("229")
        raise FTPReplyError, resp
      end
      if m = /\((?<d>[!-~])\k<d>\k<d>(?<port>\d+)\k<d>\)/.match(resp)
        return @bare_sock.remote_address.ip_address, m["port"].to_i
      else
        raise FTPProtoError, resp
      end
    end
    private :parse229

    # handler for response code 257
    # ("PATHNAME" created)
    #
    # Returns host and port.
    def parse257(resp) # :nodoc:
      if !resp.start_with?("257")
        raise FTPReplyError, resp
      end
      return resp.slice(/"(([^"]|"")*)"/, 1).to_s.gsub(/""/, '"')
    end
    private :parse257

    # :stopdoc:
    class NullSocket
      def read_timeout=(sec)
      end

      def closed?
        true
      end

      def close
      end

      def method_missing(mid, *args)
        raise FTPConnectionError, "not connected"
      end
    end

    class BufferedSocket < BufferedIO
      [:local_address, :remote_address, :addr, :peeraddr, :send, :shutdown].each do |method|
        define_method(method) { |*args|
          @io.__send__(method, *args)
        }
      end

      def read(len = nil)
        if len
          s = super(len, String.new, true)
          return s.empty? ? nil : s
        else
          result = String.new
          while s = super(DEFAULT_BLOCKSIZE, String.new, true)
            break if s.empty?
            result << s
          end
          return result
        end
      end

      def gets
        line = readuntil("\n", true)
        return line.empty? ? nil : line
      end

      def readline
        line = gets
        if line.nil?
          raise EOFError, "end of file reached"
        end
        return line
      end
    end

    if defined?(OpenSSL::SSL::SSLSocket)
      class BufferedSSLSocket <  BufferedSocket
        def initialize(*args, **options)
          super
          @is_shutdown = false
        end

        def shutdown(*args)
          # SSL_shutdown() will be called from SSLSocket#close, and
          # SSL_shutdown() will send the "close notify" alert to the peer,
          # so shutdown(2) should not be called.
          @is_shutdown = true
        end

        def send(mesg, flags, dest = nil)
          # Ignore flags and dest.
          @io.write(mesg)
        end

        private

        def rbuf_fill
          if @is_shutdown
            raise EOFError, "shutdown has been called"
          else
            super
          end
        end
      end
    end
    # :startdoc:
  end
end


# Documentation comments:
#  - sourced from pickaxe and nutshell, with improvements (hopefully)
# frozen_string_literal: false
=begin

= net/https -- SSL/TLS enhancement for Net::HTTP.

  This file has been merged with net/http.  There is no longer any need to
  require 'net/https' to use HTTPS.

  See Net::HTTP for details on how to make HTTPS connections.

== Info
  'OpenSSL for Ruby 2' project
  Copyright (C) 2001 GOTOU Yuuzou <gotoyuzo@notwork.org>
  All rights reserved.

== Licence
  This program is licensed under the same licence as Ruby.
  (See the file 'LICENCE'.)

=end

require_relative 'http'
require 'openssl'
# frozen_string_literal: false
#
# = net/http.rb
#
# Copyright (c) 1999-2007 Yukihiro Matsumoto
# Copyright (c) 1999-2007 Minero Aoki
# Copyright (c) 2001 GOTOU Yuuzou
#
# Written and maintained by Minero Aoki <aamine@loveruby.net>.
# HTTPS support added by GOTOU Yuuzou <gotoyuzo@notwork.org>.
#
# This file is derived from "http-access.rb".
#
# Documented by Minero Aoki; converted to RDoc by William Webber.
#
# This program is free software. You can re-distribute and/or
# modify this program under the same terms of ruby itself ---
# Ruby Distribution License or GNU General Public License.
#
# See Net::HTTP for an overview and examples.
#

require 'net/protocol'
require 'uri'
autoload :OpenSSL, 'openssl'

module Net   #:nodoc:

  # :stopdoc:
  class HTTPBadResponse < StandardError; end
  class HTTPHeaderSyntaxError < StandardError; end
  # :startdoc:

  # == An HTTP client API for Ruby.
  #
  # Net::HTTP provides a rich library which can be used to build HTTP
  # user-agents.  For more details about HTTP see
  # [RFC2616](http://www.ietf.org/rfc/rfc2616.txt).
  #
  # Net::HTTP is designed to work closely with URI.  URI::HTTP#host,
  # URI::HTTP#port and URI::HTTP#request_uri are designed to work with
  # Net::HTTP.
  #
  # If you are only performing a few GET requests you should try OpenURI.
  #
  # == Simple Examples
  #
  # All examples assume you have loaded Net::HTTP with:
  #
  #   require 'net/http'
  #
  # This will also require 'uri' so you don't need to require it separately.
  #
  # The Net::HTTP methods in the following section do not persist
  # connections.  They are not recommended if you are performing many HTTP
  # requests.
  #
  # === GET
  #
  #   Net::HTTP.get('example.com', '/index.html') # => String
  #
  # === GET by URI
  #
  #   uri = URI('http://example.com/index.html?count=10')
  #   Net::HTTP.get(uri) # => String
  #
  # === GET with Dynamic Parameters
  #
  #   uri = URI('http://example.com/index.html')
  #   params = { :limit => 10, :page => 3 }
  #   uri.query = URI.encode_www_form(params)
  #
  #   res = Net::HTTP.get_response(uri)
  #   puts res.body if res.is_a?(Net::HTTPSuccess)
  #
  # === POST
  #
  #   uri = URI('http://www.example.com/search.cgi')
  #   res = Net::HTTP.post_form(uri, 'q' => 'ruby', 'max' => '50')
  #   puts res.body
  #
  # === POST with Multiple Values
  #
  #   uri = URI('http://www.example.com/search.cgi')
  #   res = Net::HTTP.post_form(uri, 'q' => ['ruby', 'perl'], 'max' => '50')
  #   puts res.body
  #
  # == How to use Net::HTTP
  #
  # The following example code can be used as the basis of an HTTP user-agent
  # which can perform a variety of request types using persistent
  # connections.
  #
  #   uri = URI('http://example.com/some_path?query=string')
  #
  #   Net::HTTP.start(uri.host, uri.port) do |http|
  #     request = Net::HTTP::Get.new uri
  #
  #     response = http.request request # Net::HTTPResponse object
  #   end
  #
  # Net::HTTP::start immediately creates a connection to an HTTP server which
  # is kept open for the duration of the block.  The connection will remain
  # open for multiple requests in the block if the server indicates it
  # supports persistent connections.
  #
  # If you wish to re-use a connection across multiple HTTP requests without
  # automatically closing it you can use ::new and then call #start and
  # #finish manually.
  #
  # The request types Net::HTTP supports are listed below in the section "HTTP
  # Request Classes".
  #
  # For all the Net::HTTP request objects and shortcut request methods you may
  # supply either a String for the request path or a URI from which Net::HTTP
  # will extract the request path.
  #
  # === Response Data
  #
  #   uri = URI('http://example.com/index.html')
  #   res = Net::HTTP.get_response(uri)
  #
  #   # Headers
  #   res['Set-Cookie']            # => String
  #   res.get_fields('set-cookie') # => Array
  #   res.to_hash['set-cookie']    # => Array
  #   puts "Headers: #{res.to_hash.inspect}"
  #
  #   # Status
  #   puts res.code       # => '200'
  #   puts res.message    # => 'OK'
  #   puts res.class.name # => 'HTTPOK'
  #
  #   # Body
  #   puts res.body if res.response_body_permitted?
  #
  # === Following Redirection
  #
  # Each Net::HTTPResponse object belongs to a class for its response code.
  #
  # For example, all 2XX responses are instances of a Net::HTTPSuccess
  # subclass, a 3XX response is an instance of a Net::HTTPRedirection
  # subclass and a 200 response is an instance of the Net::HTTPOK class.  For
  # details of response classes, see the section "HTTP Response Classes"
  # below.
  #
  # Using a case statement you can handle various types of responses properly:
  #
  #   def fetch(uri_str, limit = 10)
  #     # You should choose a better exception.
  #     raise ArgumentError, 'too many HTTP redirects' if limit == 0
  #
  #     response = Net::HTTP.get_response(URI(uri_str))
  #
  #     case response
  #     when Net::HTTPSuccess then
  #       response
  #     when Net::HTTPRedirection then
  #       location = response['location']
  #       warn "redirected to #{location}"
  #       fetch(location, limit - 1)
  #     else
  #       response.value
  #     end
  #   end
  #
  #   print fetch('http://www.ruby-lang.org')
  #
  # === POST
  #
  # A POST can be made using the Net::HTTP::Post request class.  This example
  # creates a URL encoded POST body:
  #
  #   uri = URI('http://www.example.com/todo.cgi')
  #   req = Net::HTTP::Post.new(uri)
  #   req.set_form_data('from' => '2005-01-01', 'to' => '2005-03-31')
  #
  #   res = Net::HTTP.start(uri.hostname, uri.port) do |http|
  #     http.request(req)
  #   end
  #
  #   case res
  #   when Net::HTTPSuccess, Net::HTTPRedirection
  #     # OK
  #   else
  #     res.value
  #   end
  #
  # To send multipart/form-data use Net::HTTPHeader#set_form:
  #
  #   req = Net::HTTP::Post.new(uri)
  #   req.set_form([['upload', File.open('foo.bar')]], 'multipart/form-data')
  #
  # Other requests that can contain a body such as PUT can be created in the
  # same way using the corresponding request class (Net::HTTP::Put).
  #
  # === Setting Headers
  #
  # The following example performs a conditional GET using the
  # If-Modified-Since header.  If the files has not been modified since the
  # time in the header a Not Modified response will be returned.  See RFC 2616
  # section 9.3 for further details.
  #
  #   uri = URI('http://example.com/cached_response')
  #   file = File.stat 'cached_response'
  #
  #   req = Net::HTTP::Get.new(uri)
  #   req['If-Modified-Since'] = file.mtime.rfc2822
  #
  #   res = Net::HTTP.start(uri.hostname, uri.port) {|http|
  #     http.request(req)
  #   }
  #
  #   open 'cached_response', 'w' do |io|
  #     io.write res.body
  #   end if res.is_a?(Net::HTTPSuccess)
  #
  # === Basic Authentication
  #
  # Basic authentication is performed according to
  # [RFC2617](http://www.ietf.org/rfc/rfc2617.txt).
  #
  #   uri = URI('http://example.com/index.html?key=value')
  #
  #   req = Net::HTTP::Get.new(uri)
  #   req.basic_auth 'user', 'pass'
  #
  #   res = Net::HTTP.start(uri.hostname, uri.port) {|http|
  #     http.request(req)
  #   }
  #   puts res.body
  #
  # === Streaming Response Bodies
  #
  # By default Net::HTTP reads an entire response into memory.  If you are
  # handling large files or wish to implement a progress bar you can instead
  # stream the body directly to an IO.
  #
  #   uri = URI('http://example.com/large_file')
  #
  #   Net::HTTP.start(uri.host, uri.port) do |http|
  #     request = Net::HTTP::Get.new uri
  #
  #     http.request request do |response|
  #       open 'large_file', 'w' do |io|
  #         response.read_body do |chunk|
  #           io.write chunk
  #         end
  #       end
  #     end
  #   end
  #
  # === HTTPS
  #
  # HTTPS is enabled for an HTTP connection by Net::HTTP#use_ssl=.
  #
  #   uri = URI('https://secure.example.com/some_path?query=string')
  #
  #   Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http|
  #     request = Net::HTTP::Get.new uri
  #     response = http.request request # Net::HTTPResponse object
  #   end
  #
  # Or if you simply want to make a GET request, you may pass in an URI
  # object that has an HTTPS URL. Net::HTTP automatically turns on TLS
  # verification if the URI object has a 'https' URI scheme.
  #
  #   uri = URI('https://example.com/')
  #   Net::HTTP.get(uri) # => String
  #
  # In previous versions of Ruby you would need to require 'net/https' to use
  # HTTPS. This is no longer true.
  #
  # === Proxies
  #
  # Net::HTTP will automatically create a proxy from the +http_proxy+
  # environment variable if it is present.  To disable use of +http_proxy+,
  # pass +nil+ for the proxy address.
  #
  # You may also create a custom proxy:
  #
  #   proxy_addr = 'your.proxy.host'
  #   proxy_port = 8080
  #
  #   Net::HTTP.new('example.com', nil, proxy_addr, proxy_port).start { |http|
  #     # always proxy via your.proxy.addr:8080
  #   }
  #
  # See Net::HTTP.new for further details and examples such as proxies that
  # require a username and password.
  #
  # === Compression
  #
  # Net::HTTP automatically adds Accept-Encoding for compression of response
  # bodies and automatically decompresses gzip and deflate responses unless a
  # Range header was sent.
  #
  # Compression can be disabled through the Accept-Encoding: identity header.
  #
  # == HTTP Request Classes
  #
  # Here is the HTTP request class hierarchy.
  #
  # * Net::HTTPRequest
  #   * Net::HTTP::Get
  #   * Net::HTTP::Head
  #   * Net::HTTP::Post
  #   * Net::HTTP::Patch
  #   * Net::HTTP::Put
  #   * Net::HTTP::Proppatch
  #   * Net::HTTP::Lock
  #   * Net::HTTP::Unlock
  #   * Net::HTTP::Options
  #   * Net::HTTP::Propfind
  #   * Net::HTTP::Delete
  #   * Net::HTTP::Move
  #   * Net::HTTP::Copy
  #   * Net::HTTP::Mkcol
  #   * Net::HTTP::Trace
  #
  # == HTTP Response Classes
  #
  # Here is HTTP response class hierarchy.  All classes are defined in Net
  # module and are subclasses of Net::HTTPResponse.
  #
  # HTTPUnknownResponse:: For unhandled HTTP extensions
  # HTTPInformation::                    1xx
  #   HTTPContinue::                        100
  #   HTTPSwitchProtocol::                  101
  # HTTPSuccess::                        2xx
  #   HTTPOK::                              200
  #   HTTPCreated::                         201
  #   HTTPAccepted::                        202
  #   HTTPNonAuthoritativeInformation::     203
  #   HTTPNoContent::                       204
  #   HTTPResetContent::                    205
  #   HTTPPartialContent::                  206
  #   HTTPMultiStatus::                     207
  #   HTTPIMUsed::                          226
  # HTTPRedirection::                    3xx
  #   HTTPMultipleChoices::                 300
  #   HTTPMovedPermanently::                301
  #   HTTPFound::                           302
  #   HTTPSeeOther::                        303
  #   HTTPNotModified::                     304
  #   HTTPUseProxy::                        305
  #   HTTPTemporaryRedirect::               307
  # HTTPClientError::                    4xx
  #   HTTPBadRequest::                      400
  #   HTTPUnauthorized::                    401
  #   HTTPPaymentRequired::                 402
  #   HTTPForbidden::                       403
  #   HTTPNotFound::                        404
  #   HTTPMethodNotAllowed::                405
  #   HTTPNotAcceptable::                   406
  #   HTTPProxyAuthenticationRequired::     407
  #   HTTPRequestTimeOut::                  408
  #   HTTPConflict::                        409
  #   HTTPGone::                            410
  #   HTTPLengthRequired::                  411
  #   HTTPPreconditionFailed::              412
  #   HTTPRequestEntityTooLarge::           413
  #   HTTPRequestURITooLong::               414
  #   HTTPUnsupportedMediaType::            415
  #   HTTPRequestedRangeNotSatisfiable::    416
  #   HTTPExpectationFailed::               417
  #   HTTPUnprocessableEntity::             422
  #   HTTPLocked::                          423
  #   HTTPFailedDependency::                424
  #   HTTPUpgradeRequired::                 426
  #   HTTPPreconditionRequired::            428
  #   HTTPTooManyRequests::                 429
  #   HTTPRequestHeaderFieldsTooLarge::     431
  #   HTTPUnavailableForLegalReasons::      451
  # HTTPServerError::                    5xx
  #   HTTPInternalServerError::             500
  #   HTTPNotImplemented::                  501
  #   HTTPBadGateway::                      502
  #   HTTPServiceUnavailable::              503
  #   HTTPGatewayTimeOut::                  504
  #   HTTPVersionNotSupported::             505
  #   HTTPInsufficientStorage::             507
  #   HTTPNetworkAuthenticationRequired::   511
  #
  # There is also the Net::HTTPBadResponse exception which is raised when
  # there is a protocol error.
  #
  class HTTP < Protocol

    # :stopdoc:
    VERSION = "0.1.1"
    Revision = %q$Revision$.split[1]
    HTTPVersion = '1.1'
    begin
      require 'zlib'
      require 'stringio'  #for our purposes (unpacking gzip) lump these together
      HAVE_ZLIB=true
    rescue LoadError
      HAVE_ZLIB=false
    end
    # :startdoc:

    # Turns on net/http 1.2 (Ruby 1.8) features.
    # Defaults to ON in Ruby 1.8 or later.
    def HTTP.version_1_2
      true
    end

    # Returns true if net/http is in version 1.2 mode.
    # Defaults to true.
    def HTTP.version_1_2?
      true
    end

    def HTTP.version_1_1?  #:nodoc:
      false
    end

    class << HTTP
      alias is_version_1_1? version_1_1?   #:nodoc:
      alias is_version_1_2? version_1_2?   #:nodoc:
    end

    #
    # short cut methods
    #

    #
    # Gets the body text from the target and outputs it to $stdout.  The
    # target can either be specified as
    # (+uri+, +headers+), or as (+host+, +path+, +port+ = 80); so:
    #
    #    Net::HTTP.get_print URI('http://www.example.com/index.html')
    #
    # or:
    #
    #    Net::HTTP.get_print 'www.example.com', '/index.html'
    #
    # you can also specify request headers:
    #
    #    Net::HTTP.get_print URI('http://www.example.com/index.html'), { 'Accept' => 'text/html' }
    #
    def HTTP.get_print(uri_or_host, path_or_headers = nil, port = nil)
      get_response(uri_or_host, path_or_headers, port) {|res|
        res.read_body do |chunk|
          $stdout.print chunk
        end
      }
      nil
    end

    # Sends a GET request to the target and returns the HTTP response
    # as a string.  The target can either be specified as
    # (+uri+, +headers+), or as (+host+, +path+, +port+ = 80); so:
    #
    #    print Net::HTTP.get(URI('http://www.example.com/index.html'))
    #
    # or:
    #
    #    print Net::HTTP.get('www.example.com', '/index.html')
    #
    # you can also specify request headers:
    #
    #    Net::HTTP.get(URI('http://www.example.com/index.html'), { 'Accept' => 'text/html' })
    #
    def HTTP.get(uri_or_host, path_or_headers = nil, port = nil)
      get_response(uri_or_host, path_or_headers, port).body
    end

    # Sends a GET request to the target and returns the HTTP response
    # as a Net::HTTPResponse object.  The target can either be specified as
    # (+uri+, +headers+), or as (+host+, +path+, +port+ = 80); so:
    #
    #    res = Net::HTTP.get_response(URI('http://www.example.com/index.html'))
    #    print res.body
    #
    # or:
    #
    #    res = Net::HTTP.get_response('www.example.com', '/index.html')
    #    print res.body
    #
    # you can also specify request headers:
    #
    #    Net::HTTP.get_response(URI('http://www.example.com/index.html'), { 'Accept' => 'text/html' })
    #
    def HTTP.get_response(uri_or_host, path_or_headers = nil, port = nil, &block)
      if path_or_headers && !path_or_headers.is_a?(Hash)
        host = uri_or_host
        path = path_or_headers
        new(host, port || HTTP.default_port).start {|http|
          return http.request_get(path, &block)
        }
      else
        uri = uri_or_host
        headers = path_or_headers
        start(uri.hostname, uri.port,
              :use_ssl => uri.scheme == 'https') {|http|
          return http.request_get(uri, headers, &block)
        }
      end
    end

    # Posts data to the specified URI object.
    #
    # Example:
    #
    #   require 'net/http'
    #   require 'uri'
    #
    #   Net::HTTP.post URI('http://www.example.com/api/search'),
    #                  { "q" => "ruby", "max" => "50" }.to_json,
    #                  "Content-Type" => "application/json"
    #
    def HTTP.post(url, data, header = nil)
      start(url.hostname, url.port,
            :use_ssl => url.scheme == 'https' ) {|http|
        http.post(url, data, header)
      }
    end

    # Posts HTML form data to the specified URI object.
    # The form data must be provided as a Hash mapping from String to String.
    # Example:
    #
    #   { "cmd" => "search", "q" => "ruby", "max" => "50" }
    #
    # This method also does Basic Authentication iff +url+.user exists.
    # But userinfo for authentication is deprecated (RFC3986).
    # So this feature will be removed.
    #
    # Example:
    #
    #   require 'net/http'
    #   require 'uri'
    #
    #   Net::HTTP.post_form URI('http://www.example.com/search.cgi'),
    #                       { "q" => "ruby", "max" => "50" }
    #
    def HTTP.post_form(url, params)
      req = Post.new(url)
      req.form_data = params
      req.basic_auth url.user, url.password if url.user
      start(url.hostname, url.port,
            :use_ssl => url.scheme == 'https' ) {|http|
        http.request(req)
      }
    end

    #
    # HTTP session management
    #

    # The default port to use for HTTP requests; defaults to 80.
    def HTTP.default_port
      http_default_port()
    end

    # The default port to use for HTTP requests; defaults to 80.
    def HTTP.http_default_port
      80
    end

    # The default port to use for HTTPS requests; defaults to 443.
    def HTTP.https_default_port
      443
    end

    def HTTP.socket_type   #:nodoc: obsolete
      BufferedIO
    end

    # :call-seq:
    #   HTTP.start(address, port, p_addr, p_port, p_user, p_pass, &block)
    #   HTTP.start(address, port=nil, p_addr=:ENV, p_port=nil, p_user=nil, p_pass=nil, opt, &block)
    #
    # Creates a new Net::HTTP object, then additionally opens the TCP
    # connection and HTTP session.
    #
    # Arguments are the following:
    # _address_ :: hostname or IP address of the server
    # _port_    :: port of the server
    # _p_addr_  :: address of proxy
    # _p_port_  :: port of proxy
    # _p_user_  :: user of proxy
    # _p_pass_  :: pass of proxy
    # _opt_     :: optional hash
    #
    # _opt_ sets following values by its accessor.
    # The keys are ipaddr, ca_file, ca_path, cert, cert_store, ciphers, keep_alive_timeout,
    # close_on_empty_response, key, open_timeout, read_timeout, write_timeout, ssl_timeout,
    # ssl_version, use_ssl, verify_callback, verify_depth and verify_mode.
    # If you set :use_ssl as true, you can use https and default value of
    # verify_mode is set as OpenSSL::SSL::VERIFY_PEER.
    #
    # If the optional block is given, the newly
    # created Net::HTTP object is passed to it and closed when the
    # block finishes.  In this case, the return value of this method
    # is the return value of the block.  If no block is given, the
    # return value of this method is the newly created Net::HTTP object
    # itself, and the caller is responsible for closing it upon completion
    # using the finish() method.
    def HTTP.start(address, *arg, &block) # :yield: +http+
      arg.pop if opt = Hash.try_convert(arg[-1])
      port, p_addr, p_port, p_user, p_pass = *arg
      p_addr = :ENV if arg.size < 2
      port = https_default_port if !port && opt && opt[:use_ssl]
      http = new(address, port, p_addr, p_port, p_user, p_pass)
      http.ipaddr = opt[:ipaddr] if opt && opt[:ipaddr]

      if opt
        if opt[:use_ssl]
          opt = {verify_mode: OpenSSL::SSL::VERIFY_PEER}.update(opt)
        end
        http.methods.grep(/\A(\w+)=\z/) do |meth|
          key = $1.to_sym
          opt.key?(key) or next
          http.__send__(meth, opt[key])
        end
      end

      http.start(&block)
    end

    class << HTTP
      alias newobj new # :nodoc:
    end

    # Creates a new Net::HTTP object without opening a TCP connection or
    # HTTP session.
    #
    # The +address+ should be a DNS hostname or IP address, the +port+ is the
    # port the server operates on.  If no +port+ is given the default port for
    # HTTP or HTTPS is used.
    #
    # If none of the +p_+ arguments are given, the proxy host and port are
    # taken from the +http_proxy+ environment variable (or its uppercase
    # equivalent) if present.  If the proxy requires authentication you must
    # supply it by hand.  See URI::Generic#find_proxy for details of proxy
    # detection from the environment.  To disable proxy detection set +p_addr+
    # to nil.
    #
    # If you are connecting to a custom proxy, +p_addr+ specifies the DNS name
    # or IP address of the proxy host, +p_port+ the port to use to access the
    # proxy, +p_user+ and +p_pass+ the username and password if authorization
    # is required to use the proxy, and p_no_proxy hosts which do not
    # use the proxy.
    #
    def HTTP.new(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, p_no_proxy = nil)
      http = super address, port

      if proxy_class? then # from Net::HTTP::Proxy()
        http.proxy_from_env = @proxy_from_env
        http.proxy_address  = @proxy_address
        http.proxy_port     = @proxy_port
        http.proxy_user     = @proxy_user
        http.proxy_pass     = @proxy_pass
      elsif p_addr == :ENV then
        http.proxy_from_env = true
      else
        if p_addr && p_no_proxy && !URI::Generic.use_proxy?(p_addr, p_addr, p_port, p_no_proxy)
          p_addr = nil
          p_port = nil
        end
        http.proxy_address = p_addr
        http.proxy_port    = p_port || default_port
        http.proxy_user    = p_user
        http.proxy_pass    = p_pass
      end

      http
    end

    # Creates a new Net::HTTP object for the specified server address,
    # without opening the TCP connection or initializing the HTTP session.
    # The +address+ should be a DNS hostname or IP address.
    def initialize(address, port = nil)
      @address = address
      @port    = (port || HTTP.default_port)
      @ipaddr = nil
      @local_host = nil
      @local_port = nil
      @curr_http_version = HTTPVersion
      @keep_alive_timeout = 2
      @last_communicated = nil
      @close_on_empty_response = false
      @socket  = nil
      @started = false
      @open_timeout = 60
      @read_timeout = 60
      @write_timeout = 60
      @continue_timeout = nil
      @max_retries = 1
      @debug_output = nil

      @proxy_from_env = false
      @proxy_uri      = nil
      @proxy_address  = nil
      @proxy_port     = nil
      @proxy_user     = nil
      @proxy_pass     = nil

      @use_ssl = false
      @ssl_context = nil
      @ssl_session = nil
      @sspi_enabled = false
      SSL_IVNAMES.each do |ivname|
        instance_variable_set ivname, nil
      end
    end

    def inspect
      "#<#{self.class} #{@address}:#{@port} open=#{started?}>"
    end

    # *WARNING* This method opens a serious security hole.
    # Never use this method in production code.
    #
    # Sets an output stream for debugging.
    #
    #   http = Net::HTTP.new(hostname)
    #   http.set_debug_output $stderr
    #   http.start { .... }
    #
    def set_debug_output(output)
      warn 'Net::HTTP#set_debug_output called after HTTP started', uplevel: 1 if started?
      @debug_output = output
    end

    # The DNS host name or IP address to connect to.
    attr_reader :address

    # The port number to connect to.
    attr_reader :port

    # The local host used to establish the connection.
    attr_accessor :local_host

    # The local port used to establish the connection.
    attr_accessor :local_port

    attr_writer :proxy_from_env
    attr_writer :proxy_address
    attr_writer :proxy_port
    attr_writer :proxy_user
    attr_writer :proxy_pass

    # The IP address to connect to/used to connect to
    def ipaddr
      started? ?  @socket.io.peeraddr[3] : @ipaddr
    end

    # Set the IP address to connect to
    def ipaddr=(addr)
      raise IOError, "ipaddr value changed, but session already started" if started?
      @ipaddr = addr
    end

    # Number of seconds to wait for the connection to open. Any number
    # may be used, including Floats for fractional seconds. If the HTTP
    # object cannot open a connection in this many seconds, it raises a
    # Net::OpenTimeout exception. The default value is 60 seconds.
    attr_accessor :open_timeout

    # Number of seconds to wait for one block to be read (via one read(2)
    # call). Any number may be used, including Floats for fractional
    # seconds. If the HTTP object cannot read data in this many seconds,
    # it raises a Net::ReadTimeout exception. The default value is 60 seconds.
    attr_reader :read_timeout

    # Number of seconds to wait for one block to be written (via one write(2)
    # call). Any number may be used, including Floats for fractional
    # seconds. If the HTTP object cannot write data in this many seconds,
    # it raises a Net::WriteTimeout exception. The default value is 60 seconds.
    # Net::WriteTimeout is not raised on Windows.
    attr_reader :write_timeout

    # Maximum number of times to retry an idempotent request in case of
    # Net::ReadTimeout, IOError, EOFError, Errno::ECONNRESET,
    # Errno::ECONNABORTED, Errno::EPIPE, OpenSSL::SSL::SSLError,
    # Timeout::Error.
    # Should be a non-negative integer number. Zero means no retries.
    # The default value is 1.
    def max_retries=(retries)
      retries = retries.to_int
      if retries < 0
        raise ArgumentError, 'max_retries should be non-negative integer number'
      end
      @max_retries = retries
    end

    attr_reader :max_retries

    # Setter for the read_timeout attribute.
    def read_timeout=(sec)
      @socket.read_timeout = sec if @socket
      @read_timeout = sec
    end

    # Setter for the write_timeout attribute.
    def write_timeout=(sec)
      @socket.write_timeout = sec if @socket
      @write_timeout = sec
    end

    # Seconds to wait for 100 Continue response. If the HTTP object does not
    # receive a response in this many seconds it sends the request body. The
    # default value is +nil+.
    attr_reader :continue_timeout

    # Setter for the continue_timeout attribute.
    def continue_timeout=(sec)
      @socket.continue_timeout = sec if @socket
      @continue_timeout = sec
    end

    # Seconds to reuse the connection of the previous request.
    # If the idle time is less than this Keep-Alive Timeout,
    # Net::HTTP reuses the TCP/IP socket used by the previous communication.
    # The default value is 2 seconds.
    attr_accessor :keep_alive_timeout

    # Returns true if the HTTP session has been started.
    def started?
      @started
    end

    alias active? started?   #:nodoc: obsolete

    attr_accessor :close_on_empty_response

    # Returns true if SSL/TLS is being used with HTTP.
    def use_ssl?
      @use_ssl
    end

    # Turn on/off SSL.
    # This flag must be set before starting session.
    # If you change use_ssl value after session started,
    # a Net::HTTP object raises IOError.
    def use_ssl=(flag)
      flag = flag ? true : false
      if started? and @use_ssl != flag
        raise IOError, "use_ssl value changed, but session already started"
      end
      @use_ssl = flag
    end

    SSL_IVNAMES = [
      :@ca_file,
      :@ca_path,
      :@cert,
      :@cert_store,
      :@ciphers,
      :@extra_chain_cert,
      :@key,
      :@ssl_timeout,
      :@ssl_version,
      :@min_version,
      :@max_version,
      :@verify_callback,
      :@verify_depth,
      :@verify_mode,
      :@verify_hostname,
    ]
    SSL_ATTRIBUTES = [
      :ca_file,
      :ca_path,
      :cert,
      :cert_store,
      :ciphers,
      :extra_chain_cert,
      :key,
      :ssl_timeout,
      :ssl_version,
      :min_version,
      :max_version,
      :verify_callback,
      :verify_depth,
      :verify_mode,
      :verify_hostname,
    ]

    # Sets path of a CA certification file in PEM format.
    #
    # The file can contain several CA certificates.
    attr_accessor :ca_file

    # Sets path of a CA certification directory containing certifications in
    # PEM format.
    attr_accessor :ca_path

    # Sets an OpenSSL::X509::Certificate object as client certificate.
    # (This method is appeared in Michal Rokos's OpenSSL extension).
    attr_accessor :cert

    # Sets the X509::Store to verify peer certificate.
    attr_accessor :cert_store

    # Sets the available ciphers.  See OpenSSL::SSL::SSLContext#ciphers=
    attr_accessor :ciphers

    # Sets the extra X509 certificates to be added to the certificate chain.
    # See OpenSSL::SSL::SSLContext#extra_chain_cert=
    attr_accessor :extra_chain_cert

    # Sets an OpenSSL::PKey::RSA or OpenSSL::PKey::DSA object.
    # (This method is appeared in Michal Rokos's OpenSSL extension.)
    attr_accessor :key

    # Sets the SSL timeout seconds.
    attr_accessor :ssl_timeout

    # Sets the SSL version.  See OpenSSL::SSL::SSLContext#ssl_version=
    attr_accessor :ssl_version

    # Sets the minimum SSL version.  See OpenSSL::SSL::SSLContext#min_version=
    attr_accessor :min_version

    # Sets the maximum SSL version.  See OpenSSL::SSL::SSLContext#max_version=
    attr_accessor :max_version

    # Sets the verify callback for the server certification verification.
    attr_accessor :verify_callback

    # Sets the maximum depth for the certificate chain verification.
    attr_accessor :verify_depth

    # Sets the flags for server the certification verification at beginning of
    # SSL/TLS session.
    #
    # OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER are acceptable.
    attr_accessor :verify_mode

    # Sets to check the server certificate is valid for the hostname.
    # See OpenSSL::SSL::SSLContext#verify_hostname=
    attr_accessor :verify_hostname

    # Returns the X.509 certificates the server presented.
    def peer_cert
      if not use_ssl? or not @socket
        return nil
      end
      @socket.io.peer_cert
    end

    # Opens a TCP connection and HTTP session.
    #
    # When this method is called with a block, it passes the Net::HTTP
    # object to the block, and closes the TCP connection and HTTP session
    # after the block has been executed.
    #
    # When called with a block, it returns the return value of the
    # block; otherwise, it returns self.
    #
    def start  # :yield: http
      raise IOError, 'HTTP session already opened' if @started
      if block_given?
        begin
          do_start
          return yield(self)
        ensure
          do_finish
        end
      end
      do_start
      self
    end

    def do_start
      connect
      @started = true
    end
    private :do_start

    def connect
      if proxy? then
        conn_addr = proxy_address
        conn_port = proxy_port
      else
        conn_addr = conn_address
        conn_port = port
      end

      D "opening connection to #{conn_addr}:#{conn_port}..."
      s = Timeout.timeout(@open_timeout, Net::OpenTimeout) {
        begin
          TCPSocket.open(conn_addr, conn_port, @local_host, @local_port)
        rescue => e
          raise e, "Failed to open TCP connection to " +
            "#{conn_addr}:#{conn_port} (#{e.message})"
        end
      }
      s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
      D "opened"
      if use_ssl?
        if proxy?
          plain_sock = BufferedIO.new(s, read_timeout: @read_timeout,
                                      write_timeout: @write_timeout,
                                      continue_timeout: @continue_timeout,
                                      debug_output: @debug_output)
          buf = "CONNECT #{conn_address}:#{@port} HTTP/#{HTTPVersion}\r\n"
          buf << "Host: #{@address}:#{@port}\r\n"
          if proxy_user
            credential = ["#{proxy_user}:#{proxy_pass}"].pack('m0')
            buf << "Proxy-Authorization: Basic #{credential}\r\n"
          end
          buf << "\r\n"
          plain_sock.write(buf)
          HTTPResponse.read_new(plain_sock).value
          # assuming nothing left in buffers after successful CONNECT response
        end

        ssl_parameters = Hash.new
        iv_list = instance_variables
        SSL_IVNAMES.each_with_index do |ivname, i|
          if iv_list.include?(ivname)
            value = instance_variable_get(ivname)
            unless value.nil?
              ssl_parameters[SSL_ATTRIBUTES[i]] = value
            end
          end
        end
        @ssl_context = OpenSSL::SSL::SSLContext.new
        @ssl_context.set_params(ssl_parameters)
        @ssl_context.session_cache_mode =
          OpenSSL::SSL::SSLContext::SESSION_CACHE_CLIENT |
          OpenSSL::SSL::SSLContext::SESSION_CACHE_NO_INTERNAL_STORE
        @ssl_context.session_new_cb = proc {|sock, sess| @ssl_session = sess }
        D "starting SSL for #{conn_addr}:#{conn_port}..."
        s = OpenSSL::SSL::SSLSocket.new(s, @ssl_context)
        s.sync_close = true
        # Server Name Indication (SNI) RFC 3546
        s.hostname = @address if s.respond_to? :hostname=
        if @ssl_session and
           Process.clock_gettime(Process::CLOCK_REALTIME) < @ssl_session.time.to_f + @ssl_session.timeout
          s.session = @ssl_session
        end
        ssl_socket_connect(s, @open_timeout)
        if (@ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE) && @ssl_context.verify_hostname
          s.post_connection_check(@address)
        end
        D "SSL established, protocol: #{s.ssl_version}, cipher: #{s.cipher[0]}"
      end
      @socket = BufferedIO.new(s, read_timeout: @read_timeout,
                               write_timeout: @write_timeout,
                               continue_timeout: @continue_timeout,
                               debug_output: @debug_output)
      on_connect
    rescue => exception
      if s
        D "Conn close because of connect error #{exception}"
        s.close
      end
      raise
    end
    private :connect

    def on_connect
    end
    private :on_connect

    # Finishes the HTTP session and closes the TCP connection.
    # Raises IOError if the session has not been started.
    def finish
      raise IOError, 'HTTP session not yet started' unless started?
      do_finish
    end

    def do_finish
      @started = false
      @socket.close if @socket
      @socket = nil
    end
    private :do_finish

    #
    # proxy
    #

    public

    # no proxy
    @is_proxy_class = false
    @proxy_from_env = false
    @proxy_addr = nil
    @proxy_port = nil
    @proxy_user = nil
    @proxy_pass = nil

    # Creates an HTTP proxy class which behaves like Net::HTTP, but
    # performs all access via the specified proxy.
    #
    # This class is obsolete.  You may pass these same parameters directly to
    # Net::HTTP.new.  See Net::HTTP.new for details of the arguments.
    def HTTP.Proxy(p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil)
      return self unless p_addr

      Class.new(self) {
        @is_proxy_class = true

        if p_addr == :ENV then
          @proxy_from_env = true
          @proxy_address = nil
          @proxy_port    = nil
        else
          @proxy_from_env = false
          @proxy_address = p_addr
          @proxy_port    = p_port || default_port
        end

        @proxy_user = p_user
        @proxy_pass = p_pass
      }
    end

    class << HTTP
      # returns true if self is a class which was created by HTTP::Proxy.
      def proxy_class?
        defined?(@is_proxy_class) ? @is_proxy_class : false
      end

      # Address of proxy host. If Net::HTTP does not use a proxy, nil.
      attr_reader :proxy_address

      # Port number of proxy host. If Net::HTTP does not use a proxy, nil.
      attr_reader :proxy_port

      # User name for accessing proxy. If Net::HTTP does not use a proxy, nil.
      attr_reader :proxy_user

      # User password for accessing proxy. If Net::HTTP does not use a proxy,
      # nil.
      attr_reader :proxy_pass
    end

    # True if requests for this connection will be proxied
    def proxy?
      !!(@proxy_from_env ? proxy_uri : @proxy_address)
    end

    # True if the proxy for this connection is determined from the environment
    def proxy_from_env?
      @proxy_from_env
    end

    # The proxy URI determined from the environment for this connection.
    def proxy_uri # :nodoc:
      return if @proxy_uri == false
      @proxy_uri ||= URI::HTTP.new(
        "http".freeze, nil, address, port, nil, nil, nil, nil, nil
      ).find_proxy || false
      @proxy_uri || nil
    end

    # The address of the proxy server, if one is configured.
    def proxy_address
      if @proxy_from_env then
        proxy_uri&.hostname
      else
        @proxy_address
      end
    end

    # The port of the proxy server, if one is configured.
    def proxy_port
      if @proxy_from_env then
        proxy_uri&.port
      else
        @proxy_port
      end
    end

    # [Bug #12921]
    if /linux|freebsd|darwin/ =~ RUBY_PLATFORM
      ENVIRONMENT_VARIABLE_IS_MULTIUSER_SAFE = true
    else
      ENVIRONMENT_VARIABLE_IS_MULTIUSER_SAFE = false
    end

    # The username of the proxy server, if one is configured.
    def proxy_user
      if ENVIRONMENT_VARIABLE_IS_MULTIUSER_SAFE && @proxy_from_env
        proxy_uri&.user
      else
        @proxy_user
      end
    end

    # The password of the proxy server, if one is configured.
    def proxy_pass
      if ENVIRONMENT_VARIABLE_IS_MULTIUSER_SAFE && @proxy_from_env
        proxy_uri&.password
      else
        @proxy_pass
      end
    end

    alias proxyaddr proxy_address   #:nodoc: obsolete
    alias proxyport proxy_port      #:nodoc: obsolete

    private

    # without proxy, obsolete

    def conn_address # :nodoc:
      @ipaddr || address()
    end

    def conn_port # :nodoc:
      port()
    end

    def edit_path(path)
      if proxy?
        if path.start_with?("ftp://") || use_ssl?
          path
        else
          "http://#{addr_port}#{path}"
        end
      else
        path
      end
    end

    #
    # HTTP operations
    #

    public

    # Retrieves data from +path+ on the connected-to host which may be an
    # absolute path String or a URI to extract the path from.
    #
    # +initheader+ must be a Hash like { 'Accept' => '*/*', ... },
    # and it defaults to an empty hash.
    # If +initheader+ doesn't have the key 'accept-encoding', then
    # a value of "gzip;q=1.0,deflate;q=0.6,identity;q=0.3" is used,
    # so that gzip compression is used in preference to deflate
    # compression, which is used in preference to no compression.
    # Ruby doesn't have libraries to support the compress (Lempel-Ziv)
    # compression, so that is not supported.  The intent of this is
    # to reduce bandwidth by default.   If this routine sets up
    # compression, then it does the decompression also, removing
    # the header as well to prevent confusion.  Otherwise
    # it leaves the body as it found it.
    #
    # This method returns a Net::HTTPResponse object.
    #
    # If called with a block, yields each fragment of the
    # entity body in turn as a string as it is read from
    # the socket.  Note that in this case, the returned response
    # object will *not* contain a (meaningful) body.
    #
    # +dest+ argument is obsolete.
    # It still works but you must not use it.
    #
    # This method never raises an exception.
    #
    #     response = http.get('/index.html')
    #
    #     # using block
    #     File.open('result.txt', 'w') {|f|
    #       http.get('/~foo/') do |str|
    #         f.write str
    #       end
    #     }
    #
    def get(path, initheader = nil, dest = nil, &block) # :yield: +body_segment+
      res = nil
      request(Get.new(path, initheader)) {|r|
        r.read_body dest, &block
        res = r
      }
      res
    end

    # Gets only the header from +path+ on the connected-to host.
    # +header+ is a Hash like { 'Accept' => '*/*', ... }.
    #
    # This method returns a Net::HTTPResponse object.
    #
    # This method never raises an exception.
    #
    #     response = nil
    #     Net::HTTP.start('some.www.server', 80) {|http|
    #       response = http.head('/index.html')
    #     }
    #     p response['content-type']
    #
    def head(path, initheader = nil)
      request(Head.new(path, initheader))
    end

    # Posts +data+ (must be a String) to +path+. +header+ must be a Hash
    # like { 'Accept' => '*/*', ... }.
    #
    # This method returns a Net::HTTPResponse object.
    #
    # If called with a block, yields each fragment of the
    # entity body in turn as a string as it is read from
    # the socket.  Note that in this case, the returned response
    # object will *not* contain a (meaningful) body.
    #
    # +dest+ argument is obsolete.
    # It still works but you must not use it.
    #
    # This method never raises exception.
    #
    #     response = http.post('/cgi-bin/search.rb', 'query=foo')
    #
    #     # using block
    #     File.open('result.txt', 'w') {|f|
    #       http.post('/cgi-bin/search.rb', 'query=foo') do |str|
    #         f.write str
    #       end
    #     }
    #
    # You should set Content-Type: header field for POST.
    # If no Content-Type: field given, this method uses
    # "application/x-www-form-urlencoded" by default.
    #
    def post(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+
      send_entity(path, data, initheader, dest, Post, &block)
    end

    # Sends a PATCH request to the +path+ and gets a response,
    # as an HTTPResponse object.
    def patch(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+
      send_entity(path, data, initheader, dest, Patch, &block)
    end

    def put(path, data, initheader = nil)   #:nodoc:
      request(Put.new(path, initheader), data)
    end

    # Sends a PROPPATCH request to the +path+ and gets a response,
    # as an HTTPResponse object.
    def proppatch(path, body, initheader = nil)
      request(Proppatch.new(path, initheader), body)
    end

    # Sends a LOCK request to the +path+ and gets a response,
    # as an HTTPResponse object.
    def lock(path, body, initheader = nil)
      request(Lock.new(path, initheader), body)
    end

    # Sends a UNLOCK request to the +path+ and gets a response,
    # as an HTTPResponse object.
    def unlock(path, body, initheader = nil)
      request(Unlock.new(path, initheader), body)
    end

    # Sends a OPTIONS request to the +path+ and gets a response,
    # as an HTTPResponse object.
    def options(path, initheader = nil)
      request(Options.new(path, initheader))
    end

    # Sends a PROPFIND request to the +path+ and gets a response,
    # as an HTTPResponse object.
    def propfind(path, body = nil, initheader = {'Depth' => '0'})
      request(Propfind.new(path, initheader), body)
    end

    # Sends a DELETE request to the +path+ and gets a response,
    # as an HTTPResponse object.
    def delete(path, initheader = {'Depth' => 'Infinity'})
      request(Delete.new(path, initheader))
    end

    # Sends a MOVE request to the +path+ and gets a response,
    # as an HTTPResponse object.
    def move(path, initheader = nil)
      request(Move.new(path, initheader))
    end

    # Sends a COPY request to the +path+ and gets a response,
    # as an HTTPResponse object.
    def copy(path, initheader = nil)
      request(Copy.new(path, initheader))
    end

    # Sends a MKCOL request to the +path+ and gets a response,
    # as an HTTPResponse object.
    def mkcol(path, body = nil, initheader = nil)
      request(Mkcol.new(path, initheader), body)
    end

    # Sends a TRACE request to the +path+ and gets a response,
    # as an HTTPResponse object.
    def trace(path, initheader = nil)
      request(Trace.new(path, initheader))
    end

    # Sends a GET request to the +path+.
    # Returns the response as a Net::HTTPResponse object.
    #
    # When called with a block, passes an HTTPResponse object to the block.
    # The body of the response will not have been read yet;
    # the block can process it using HTTPResponse#read_body,
    # if desired.
    #
    # Returns the response.
    #
    # This method never raises Net::* exceptions.
    #
    #     response = http.request_get('/index.html')
    #     # The entity body is already read in this case.
    #     p response['content-type']
    #     puts response.body
    #
    #     # Using a block
    #     http.request_get('/index.html') {|response|
    #       p response['content-type']
    #       response.read_body do |str|   # read body now
    #         print str
    #       end
    #     }
    #
    def request_get(path, initheader = nil, &block) # :yield: +response+
      request(Get.new(path, initheader), &block)
    end

    # Sends a HEAD request to the +path+ and returns the response
    # as a Net::HTTPResponse object.
    #
    # Returns the response.
    #
    # This method never raises Net::* exceptions.
    #
    #     response = http.request_head('/index.html')
    #     p response['content-type']
    #
    def request_head(path, initheader = nil, &block)
      request(Head.new(path, initheader), &block)
    end

    # Sends a POST request to the +path+.
    #
    # Returns the response as a Net::HTTPResponse object.
    #
    # When called with a block, the block is passed an HTTPResponse
    # object.  The body of that response will not have been read yet;
    # the block can process it using HTTPResponse#read_body, if desired.
    #
    # Returns the response.
    #
    # This method never raises Net::* exceptions.
    #
    #     # example
    #     response = http.request_post('/cgi-bin/nice.rb', 'datadatadata...')
    #     p response.status
    #     puts response.body          # body is already read in this case
    #
    #     # using block
    #     http.request_post('/cgi-bin/nice.rb', 'datadatadata...') {|response|
    #       p response.status
    #       p response['content-type']
    #       response.read_body do |str|   # read body now
    #         print str
    #       end
    #     }
    #
    def request_post(path, data, initheader = nil, &block) # :yield: +response+
      request Post.new(path, initheader), data, &block
    end

    def request_put(path, data, initheader = nil, &block)   #:nodoc:
      request Put.new(path, initheader), data, &block
    end

    alias get2   request_get    #:nodoc: obsolete
    alias head2  request_head   #:nodoc: obsolete
    alias post2  request_post   #:nodoc: obsolete
    alias put2   request_put    #:nodoc: obsolete


    # Sends an HTTP request to the HTTP server.
    # Also sends a DATA string if +data+ is given.
    #
    # Returns a Net::HTTPResponse object.
    #
    # This method never raises Net::* exceptions.
    #
    #    response = http.send_request('GET', '/index.html')
    #    puts response.body
    #
    def send_request(name, path, data = nil, header = nil)
      has_response_body = name != 'HEAD'
      r = HTTPGenericRequest.new(name,(data ? true : false),has_response_body,path,header)
      request r, data
    end

    # Sends an HTTPRequest object +req+ to the HTTP server.
    #
    # If +req+ is a Net::HTTP::Post or Net::HTTP::Put request containing
    # data, the data is also sent. Providing data for a Net::HTTP::Head or
    # Net::HTTP::Get request results in an ArgumentError.
    #
    # Returns an HTTPResponse object.
    #
    # When called with a block, passes an HTTPResponse object to the block.
    # The body of the response will not have been read yet;
    # the block can process it using HTTPResponse#read_body,
    # if desired.
    #
    # This method never raises Net::* exceptions.
    #
    def request(req, body = nil, &block)  # :yield: +response+
      unless started?
        start {
          req['connection'] ||= 'close'
          return request(req, body, &block)
        }
      end
      if proxy_user()
        req.proxy_basic_auth proxy_user(), proxy_pass() unless use_ssl?
      end
      req.set_body_internal body
      res = transport_request(req, &block)
      if sspi_auth?(res)
        sspi_auth(req)
        res = transport_request(req, &block)
      end
      res
    end

    private

    # Executes a request which uses a representation
    # and returns its body.
    def send_entity(path, data, initheader, dest, type, &block)
      res = nil
      request(type.new(path, initheader), data) {|r|
        r.read_body dest, &block
        res = r
      }
      res
    end

    IDEMPOTENT_METHODS_ = %w/GET HEAD PUT DELETE OPTIONS TRACE/ # :nodoc:

    def transport_request(req)
      count = 0
      begin
        begin_transport req
        res = catch(:response) {
          begin
            req.exec @socket, @curr_http_version, edit_path(req.path)
          rescue Errno::EPIPE
            # Failure when writing full request, but we can probably
            # still read the received response.
          end

          begin
            res = HTTPResponse.read_new(@socket)
            res.decode_content = req.decode_content
          end while res.kind_of?(HTTPInformation)

          res.uri = req.uri

          res
        }
        res.reading_body(@socket, req.response_body_permitted?) {
          yield res if block_given?
        }
      rescue Net::OpenTimeout
        raise
      rescue Net::ReadTimeout, IOError, EOFError,
             Errno::ECONNRESET, Errno::ECONNABORTED, Errno::EPIPE, Errno::ETIMEDOUT,
             # avoid a dependency on OpenSSL
             defined?(OpenSSL::SSL) ? OpenSSL::SSL::SSLError : IOError,
             Timeout::Error => exception
        if count < max_retries && IDEMPOTENT_METHODS_.include?(req.method)
          count += 1
          @socket.close if @socket
          D "Conn close because of error #{exception}, and retry"
          retry
        end
        D "Conn close because of error #{exception}"
        @socket.close if @socket
        raise
      end

      end_transport req, res
      res
    rescue => exception
      D "Conn close because of error #{exception}"
      @socket.close if @socket
      raise exception
    end

    def begin_transport(req)
      if @socket.closed?
        connect
      elsif @last_communicated
        if @last_communicated + @keep_alive_timeout < Process.clock_gettime(Process::CLOCK_MONOTONIC)
          D 'Conn close because of keep_alive_timeout'
          @socket.close
          connect
        elsif @socket.io.to_io.wait_readable(0) && @socket.eof?
          D "Conn close because of EOF"
          @socket.close
          connect
        end
      end

      if not req.response_body_permitted? and @close_on_empty_response
        req['connection'] ||= 'close'
      end

      req.update_uri address, port, use_ssl?
      req['host'] ||= addr_port()
    end

    def end_transport(req, res)
      @curr_http_version = res.http_version
      @last_communicated = nil
      if @socket.closed?
        D 'Conn socket closed'
      elsif not res.body and @close_on_empty_response
        D 'Conn close'
        @socket.close
      elsif keep_alive?(req, res)
        D 'Conn keep-alive'
        @last_communicated = Process.clock_gettime(Process::CLOCK_MONOTONIC)
      else
        D 'Conn close'
        @socket.close
      end
    end

    def keep_alive?(req, res)
      return false if req.connection_close?
      if @curr_http_version <= '1.0'
        res.connection_keep_alive?
      else   # HTTP/1.1 or later
        not res.connection_close?
      end
    end

    def sspi_auth?(res)
      return false unless @sspi_enabled
      if res.kind_of?(HTTPProxyAuthenticationRequired) and
          proxy? and res["Proxy-Authenticate"].include?("Negotiate")
        begin
          require 'win32/sspi'
          true
        rescue LoadError
          false
        end
      else
        false
      end
    end

    def sspi_auth(req)
      n = Win32::SSPI::NegotiateAuth.new
      req["Proxy-Authorization"] = "Negotiate #{n.get_initial_token}"
      # Some versions of ISA will close the connection if this isn't present.
      req["Connection"] = "Keep-Alive"
      req["Proxy-Connection"] = "Keep-Alive"
      res = transport_request(req)
      authphrase = res["Proxy-Authenticate"]  or return res
      req["Proxy-Authorization"] = "Negotiate #{n.complete_authentication(authphrase)}"
    rescue => err
      raise HTTPAuthenticationError.new('HTTP authentication failed', err)
    end

    #
    # utils
    #

    private

    def addr_port
      addr = address
      addr = "[#{addr}]" if addr.include?(":")
      default_port = use_ssl? ? HTTP.https_default_port : HTTP.http_default_port
      default_port == port ? addr : "#{addr}:#{port}"
    end

    def D(msg)
      return unless @debug_output
      @debug_output << msg
      @debug_output << "\n"
    end
  end

end

require_relative 'http/exceptions'

require_relative 'http/header'

require_relative 'http/generic_request'
require_relative 'http/request'
require_relative 'http/requests'

require_relative 'http/response'
require_relative 'http/responses'

require_relative 'http/proxy_delta'

require_relative 'http/backward'
# frozen_string_literal: true
# = net/smtp.rb
#
# Copyright (c) 1999-2007 Yukihiro Matsumoto.
#
# Copyright (c) 1999-2007 Minero Aoki.
#
# Written & maintained by Minero Aoki <aamine@loveruby.net>.
#
# Documented by William Webber and Minero Aoki.
#
# This program is free software. You can re-distribute and/or
# modify this program under the same terms as Ruby itself.
#
# $Id$
#
# See Net::SMTP for documentation.
#

require 'net/protocol'
require 'digest/md5'
require 'timeout'
begin
  require 'openssl'
rescue LoadError
end

module Net

  # Module mixed in to all SMTP error classes
  module SMTPError
    # This *class* is a module for backward compatibility.
    # In later release, this module becomes a class.
  end

  # Represents an SMTP authentication error.
  class SMTPAuthenticationError < ProtoAuthError
    include SMTPError
  end

  # Represents SMTP error code 4xx, a temporary error.
  class SMTPServerBusy < ProtoServerError
    include SMTPError
  end

  # Represents an SMTP command syntax error (error code 500)
  class SMTPSyntaxError < ProtoSyntaxError
    include SMTPError
  end

  # Represents a fatal SMTP error (error code 5xx, except for 500)
  class SMTPFatalError < ProtoFatalError
    include SMTPError
  end

  # Unexpected reply code returned from server.
  class SMTPUnknownError < ProtoUnknownError
    include SMTPError
  end

  # Command is not supported on server.
  class SMTPUnsupportedCommand < ProtocolError
    include SMTPError
  end

  #
  # == What is This Library?
  #
  # This library provides functionality to send internet
  # mail via SMTP, the Simple Mail Transfer Protocol. For details of
  # SMTP itself, see [RFC2821] (http://www.ietf.org/rfc/rfc2821.txt).
  #
  # == What is This Library NOT?
  #
  # This library does NOT provide functions to compose internet mails.
  # You must create them by yourself. If you want better mail support,
  # try RubyMail or TMail or search for alternatives in
  # {RubyGems.org}[https://rubygems.org/] or {The Ruby
  # Toolbox}[https://www.ruby-toolbox.com/].
  #
  # FYI: the official documentation on internet mail is: [RFC2822] (http://www.ietf.org/rfc/rfc2822.txt).
  #
  # == Examples
  #
  # === Sending Messages
  #
  # You must open a connection to an SMTP server before sending messages.
  # The first argument is the address of your SMTP server, and the second
  # argument is the port number. Using SMTP.start with a block is the simplest
  # way to do this. This way, the SMTP connection is closed automatically
  # after the block is executed.
  #
  #     require 'net/smtp'
  #     Net::SMTP.start('your.smtp.server', 25) do |smtp|
  #       # Use the SMTP object smtp only in this block.
  #     end
  #
  # Replace 'your.smtp.server' with your SMTP server. Normally
  # your system manager or internet provider supplies a server
  # for you.
  #
  # Then you can send messages.
  #
  #     msgstr = <<END_OF_MESSAGE
  #     From: Your Name <your@mail.address>
  #     To: Destination Address <someone@example.com>
  #     Subject: test message
  #     Date: Sat, 23 Jun 2001 16:26:43 +0900
  #     Message-Id: <unique.message.id.string@example.com>
  #
  #     This is a test message.
  #     END_OF_MESSAGE
  #
  #     require 'net/smtp'
  #     Net::SMTP.start('your.smtp.server', 25) do |smtp|
  #       smtp.send_message msgstr,
  #                         'your@mail.address',
  #                         'his_address@example.com'
  #     end
  #
  # === Closing the Session
  #
  # You MUST close the SMTP session after sending messages, by calling
  # the #finish method:
  #
  #     # using SMTP#finish
  #     smtp = Net::SMTP.start('your.smtp.server', 25)
  #     smtp.send_message msgstr, 'from@address', 'to@address'
  #     smtp.finish
  #
  # You can also use the block form of SMTP.start/SMTP#start.  This closes
  # the SMTP session automatically:
  #
  #     # using block form of SMTP.start
  #     Net::SMTP.start('your.smtp.server', 25) do |smtp|
  #       smtp.send_message msgstr, 'from@address', 'to@address'
  #     end
  #
  # I strongly recommend this scheme.  This form is simpler and more robust.
  #
  # === HELO domain
  #
  # In almost all situations, you must provide a third argument
  # to SMTP.start/SMTP#start. This is the domain name which you are on
  # (the host to send mail from). It is called the "HELO domain".
  # The SMTP server will judge whether it should send or reject
  # the SMTP session by inspecting the HELO domain.
  #
  #     Net::SMTP.start('your.smtp.server', 25
  #                     helo: 'mail.from.domain') { |smtp| ... }
  #
  # === SMTP Authentication
  #
  # The Net::SMTP class supports three authentication schemes;
  # PLAIN, LOGIN and CRAM MD5.  (SMTP Authentication: [RFC2554])
  # To use SMTP authentication, pass extra arguments to
  # SMTP.start/SMTP#start.
  #
  #     # PLAIN
  #     Net::SMTP.start('your.smtp.server', 25
  #                     user: 'Your Account', secret: 'Your Password', authtype: :plain)
  #     # LOGIN
  #     Net::SMTP.start('your.smtp.server', 25
  #                     user: 'Your Account', secret: 'Your Password', authtype: :login)
  #
  #     # CRAM MD5
  #     Net::SMTP.start('your.smtp.server', 25
  #                     user: 'Your Account', secret: 'Your Password', authtype: :cram_md5)
  #
  class SMTP < Protocol
    VERSION = "0.2.1"

    Revision = %q$Revision$.split[1]

    # The default SMTP port number, 25.
    def SMTP.default_port
      25
    end

    # The default mail submission port number, 587.
    def SMTP.default_submission_port
      587
    end

    # The default SMTPS port number, 465.
    def SMTP.default_tls_port
      465
    end

    class << self
      alias default_ssl_port default_tls_port
    end

    def SMTP.default_ssl_context(verify_peer=true)
      context = OpenSSL::SSL::SSLContext.new
      context.verify_mode = verify_peer ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
      store = OpenSSL::X509::Store.new
      store.set_default_paths
      context.cert_store = store
      context
    end

    #
    # Creates a new Net::SMTP object.
    #
    # +address+ is the hostname or ip address of your SMTP
    # server.  +port+ is the port to connect to; it defaults to
    # port 25.
    #
    # This method does not open the TCP connection.  You can use
    # SMTP.start instead of SMTP.new if you want to do everything
    # at once.  Otherwise, follow SMTP.new with SMTP#start.
    #
    def initialize(address, port = nil)
      @address = address
      @port = (port || SMTP.default_port)
      @esmtp = true
      @capabilities = nil
      @socket = nil
      @started = false
      @open_timeout = 30
      @read_timeout = 60
      @error_occurred = false
      @debug_output = nil
      @tls = false
      @starttls = :auto
      @ssl_context_tls = nil
      @ssl_context_starttls = nil
    end

    # Provide human-readable stringification of class state.
    def inspect
      "#<#{self.class} #{@address}:#{@port} started=#{@started}>"
    end

    #
    # Set whether to use ESMTP or not.  This should be done before
    # calling #start.  Note that if #start is called in ESMTP mode,
    # and the connection fails due to a ProtocolError, the SMTP
    # object will automatically switch to plain SMTP mode and
    # retry (but not vice versa).
    #
    attr_accessor :esmtp

    # +true+ if the SMTP object uses ESMTP (which it does by default).
    alias :esmtp? :esmtp

    # true if server advertises STARTTLS.
    # You cannot get valid value before opening SMTP session.
    def capable_starttls?
      capable?('STARTTLS')
    end

    def capable?(key)
      return nil unless @capabilities
      @capabilities[key] ? true : false
    end
    private :capable?

    # true if server advertises AUTH PLAIN.
    # You cannot get valid value before opening SMTP session.
    def capable_plain_auth?
      auth_capable?('PLAIN')
    end

    # true if server advertises AUTH LOGIN.
    # You cannot get valid value before opening SMTP session.
    def capable_login_auth?
      auth_capable?('LOGIN')
    end

    # true if server advertises AUTH CRAM-MD5.
    # You cannot get valid value before opening SMTP session.
    def capable_cram_md5_auth?
      auth_capable?('CRAM-MD5')
    end

    def auth_capable?(type)
      return nil unless @capabilities
      return false unless @capabilities['AUTH']
      @capabilities['AUTH'].include?(type)
    end
    private :auth_capable?

    # Returns supported authentication methods on this server.
    # You cannot get valid value before opening SMTP session.
    def capable_auth_types
      return [] unless @capabilities
      return [] unless @capabilities['AUTH']
      @capabilities['AUTH']
    end

    # true if this object uses SMTP/TLS (SMTPS).
    def tls?
      @tls
    end

    alias ssl? tls?

    # Enables SMTP/TLS (SMTPS: SMTP over direct TLS connection) for
    # this object.  Must be called before the connection is established
    # to have any effect.  +context+ is a OpenSSL::SSL::SSLContext object.
    def enable_tls(context = nil)
      raise 'openssl library not installed' unless defined?(OpenSSL)
      raise ArgumentError, "SMTPS and STARTTLS is exclusive" if @starttls == :always
      @tls = true
      @ssl_context_tls = context
    end

    alias enable_ssl enable_tls

    # Disables SMTP/TLS for this object.  Must be called before the
    # connection is established to have any effect.
    def disable_tls
      @tls = false
      @ssl_context_tls = nil
    end

    alias disable_ssl disable_tls

    # Returns truth value if this object uses STARTTLS.
    # If this object always uses STARTTLS, returns :always.
    # If this object uses STARTTLS when the server support TLS, returns :auto.
    def starttls?
      @starttls
    end

    # true if this object uses STARTTLS.
    def starttls_always?
      @starttls == :always
    end

    # true if this object uses STARTTLS when server advertises STARTTLS.
    def starttls_auto?
      @starttls == :auto
    end

    # Enables SMTP/TLS (STARTTLS) for this object.
    # +context+ is a OpenSSL::SSL::SSLContext object.
    def enable_starttls(context = nil)
      raise 'openssl library not installed' unless defined?(OpenSSL)
      raise ArgumentError, "SMTPS and STARTTLS is exclusive" if @tls
      @starttls = :always
      @ssl_context_starttls = context
    end

    # Enables SMTP/TLS (STARTTLS) for this object if server accepts.
    # +context+ is a OpenSSL::SSL::SSLContext object.
    def enable_starttls_auto(context = nil)
      raise 'openssl library not installed' unless defined?(OpenSSL)
      raise ArgumentError, "SMTPS and STARTTLS is exclusive" if @tls
      @starttls = :auto
      @ssl_context_starttls = context
    end

    # Disables SMTP/TLS (STARTTLS) for this object.  Must be called
    # before the connection is established to have any effect.
    def disable_starttls
      @starttls = false
      @ssl_context_starttls = nil
    end

    # The address of the SMTP server to connect to.
    attr_reader :address

    # The port number of the SMTP server to connect to.
    attr_reader :port

    # Seconds to wait while attempting to open a connection.
    # If the connection cannot be opened within this time, a
    # Net::OpenTimeout is raised. The default value is 30 seconds.
    attr_accessor :open_timeout

    # Seconds to wait while reading one block (by one read(2) call).
    # If the read(2) call does not complete within this time, a
    # Net::ReadTimeout is raised. The default value is 60 seconds.
    attr_reader :read_timeout

    # Set the number of seconds to wait until timing-out a read(2)
    # call.
    def read_timeout=(sec)
      @socket.read_timeout = sec if @socket
      @read_timeout = sec
    end

    #
    # WARNING: This method causes serious security holes.
    # Use this method for only debugging.
    #
    # Set an output stream for debug logging.
    # You must call this before #start.
    #
    #   # example
    #   smtp = Net::SMTP.new(addr, port)
    #   smtp.set_debug_output $stderr
    #   smtp.start do |smtp|
    #     ....
    #   end
    #
    def debug_output=(arg)
      @debug_output = arg
    end

    alias set_debug_output debug_output=

    #
    # SMTP session control
    #

    #
    # :call-seq:
    #  start(address, port = nil, helo: 'localhost', user: nil, secret: nil, authtype: nil, tls_verify: true, tls_hostname: nil) { |smtp| ... }
    #  start(address, port = nil, helo = 'localhost', user = nil, secret = nil, authtype = nil) { |smtp| ... }
    #
    # Creates a new Net::SMTP object and connects to the server.
    #
    # This method is equivalent to:
    #
    #   Net::SMTP.new(address, port).start(helo: helo_domain, user: account, secret: password, authtype: authtype, tls_verify: flag, tls_hostname: hostname)
    #
    # === Example
    #
    #     Net::SMTP.start('your.smtp.server') do |smtp|
    #       smtp.send_message msgstr, 'from@example.com', ['dest@example.com']
    #     end
    #
    # === Block Usage
    #
    # If called with a block, the newly-opened Net::SMTP object is yielded
    # to the block, and automatically closed when the block finishes.  If called
    # without a block, the newly-opened Net::SMTP object is returned to
    # the caller, and it is the caller's responsibility to close it when
    # finished.
    #
    # === Parameters
    #
    # +address+ is the hostname or ip address of your smtp server.
    #
    # +port+ is the port to connect to; it defaults to port 25.
    #
    # +helo+ is the _HELO_ _domain_ provided by the client to the
    # server (see overview comments); it defaults to 'localhost'.
    #
    # The remaining arguments are used for SMTP authentication, if required
    # or desired.  +user+ is the account name; +secret+ is your password
    # or other authentication token; and +authtype+ is the authentication
    # type, one of :plain, :login, or :cram_md5.  See the discussion of
    # SMTP Authentication in the overview notes.
    # If +tls_verify+ is true, verify the server's certificate. The default is true.
    # If the hostname in the server certificate is different from +address+,
    # it can be specified with +tls_hostname+.
    #
    # === Errors
    #
    # This method may raise:
    #
    # * Net::SMTPAuthenticationError
    # * Net::SMTPServerBusy
    # * Net::SMTPSyntaxError
    # * Net::SMTPFatalError
    # * Net::SMTPUnknownError
    # * Net::OpenTimeout
    # * Net::ReadTimeout
    # * IOError
    #
    def SMTP.start(address, port = nil, *args, helo: nil,
                   user: nil, secret: nil, password: nil, authtype: nil,
                   tls_verify: true, tls_hostname: nil,
                   &block)
      raise ArgumentError, "wrong number of arguments (given #{args.size + 2}, expected 1..6)" if args.size > 4
      helo ||= args[0] || 'localhost'
      user ||= args[1]
      secret ||= password || args[2]
      authtype ||= args[3]
      new(address, port).start(helo: helo, user: user, secret: secret, authtype: authtype, tls_verify: tls_verify, tls_hostname: tls_hostname, &block)
    end

    # +true+ if the SMTP session has been started.
    def started?
      @started
    end

    #
    # :call-seq:
    #  start(helo: 'localhost', user: nil, secret: nil, authtype: nil, tls_verify: true, tls_hostname: nil) { |smtp| ... }
    #  start(helo = 'localhost', user = nil, secret = nil, authtype = nil) { |smtp| ... }
    #
    # Opens a TCP connection and starts the SMTP session.
    #
    # === Parameters
    #
    # +helo+ is the _HELO_ _domain_ that you'll dispatch mails from; see
    # the discussion in the overview notes.
    #
    # If both of +user+ and +secret+ are given, SMTP authentication
    # will be attempted using the AUTH command.  +authtype+ specifies
    # the type of authentication to attempt; it must be one of
    # :login, :plain, and :cram_md5.  See the notes on SMTP Authentication
    # in the overview.
    # If +tls_verify+ is true, verify the server's certificate. The default is true.
    # If the hostname in the server certificate is different from +address+,
    # it can be specified with +tls_hostname+.
    #
    # === Block Usage
    #
    # When this methods is called with a block, the newly-started SMTP
    # object is yielded to the block, and automatically closed after
    # the block call finishes.  Otherwise, it is the caller's
    # responsibility to close the session when finished.
    #
    # === Example
    #
    # This is very similar to the class method SMTP.start.
    #
    #     require 'net/smtp'
    #     smtp = Net::SMTP.new('smtp.mail.server', 25)
    #     smtp.start(helo: helo_domain, user: account, secret: password, authtype: authtype) do |smtp|
    #       smtp.send_message msgstr, 'from@example.com', ['dest@example.com']
    #     end
    #
    # The primary use of this method (as opposed to SMTP.start)
    # is probably to set debugging (#set_debug_output) or ESMTP
    # (#esmtp=), which must be done before the session is
    # started.
    #
    # === Errors
    #
    # If session has already been started, an IOError will be raised.
    #
    # This method may raise:
    #
    # * Net::SMTPAuthenticationError
    # * Net::SMTPServerBusy
    # * Net::SMTPSyntaxError
    # * Net::SMTPFatalError
    # * Net::SMTPUnknownError
    # * Net::OpenTimeout
    # * Net::ReadTimeout
    # * IOError
    #
    def start(*args, helo: nil,
              user: nil, secret: nil, password: nil, authtype: nil, tls_verify: true, tls_hostname: nil)
      raise ArgumentError, "wrong number of arguments (given #{args.size}, expected 0..4)" if args.size > 4
      helo ||= args[0] || 'localhost'
      user ||= args[1]
      secret ||= password || args[2]
      authtype ||= args[3]
      if @tls && @ssl_context_tls.nil?
        @ssl_context_tls = SMTP.default_ssl_context(tls_verify)
      end
      if @starttls && @ssl_context_starttls.nil?
        @ssl_context_starttls = SMTP.default_ssl_context(tls_verify)
      end
      @tls_hostname = tls_hostname
      if block_given?
        begin
          do_start helo, user, secret, authtype
          return yield(self)
        ensure
          do_finish
        end
      else
        do_start helo, user, secret, authtype
        return self
      end
    end

    # Finishes the SMTP session and closes TCP connection.
    # Raises IOError if not started.
    def finish
      raise IOError, 'not yet started' unless started?
      do_finish
    end

    private

    def tcp_socket(address, port)
      TCPSocket.open address, port
    end

    def do_start(helo_domain, user, secret, authtype)
      raise IOError, 'SMTP session already started' if @started
      if user or secret
        check_auth_method(authtype || DEFAULT_AUTH_TYPE)
        check_auth_args user, secret
      end
      s = Timeout.timeout(@open_timeout, Net::OpenTimeout) do
        tcp_socket(@address, @port)
      end
      logging "Connection opened: #{@address}:#{@port}"
      @socket = new_internet_message_io(tls? ? tlsconnect(s, @ssl_context_tls) : s)
      check_response critical { recv_response() }
      do_helo helo_domain
      if ! tls? and (starttls_always? or (capable_starttls? and starttls_auto?))
        unless capable_starttls?
          raise SMTPUnsupportedCommand,
              "STARTTLS is not supported on this server"
        end
        starttls
        @socket = new_internet_message_io(tlsconnect(s, @ssl_context_starttls))
        # helo response may be different after STARTTLS
        do_helo helo_domain
      end
      authenticate user, secret, (authtype || DEFAULT_AUTH_TYPE) if user
      @started = true
    ensure
      unless @started
        # authentication failed, cancel connection.
        s.close if s
        @socket = nil
      end
    end

    def ssl_socket(socket, context)
      OpenSSL::SSL::SSLSocket.new socket, context
    end

    def tlsconnect(s, context)
      verified = false
      s = ssl_socket(s, context)
      logging "TLS connection started"
      s.sync_close = true
      s.hostname = @tls_hostname || @address if s.respond_to? :hostname=
      ssl_socket_connect(s, @open_timeout)
      if context.verify_mode && context.verify_mode != OpenSSL::SSL::VERIFY_NONE
        s.post_connection_check(@tls_hostname || @address)
      end
      verified = true
      s
    ensure
      s.close unless verified
    end

    def new_internet_message_io(s)
      InternetMessageIO.new(s, read_timeout: @read_timeout,
                            debug_output: @debug_output)
    end

    def do_helo(helo_domain)
      res = @esmtp ? ehlo(helo_domain) : helo(helo_domain)
      @capabilities = res.capabilities
    rescue SMTPError
      if @esmtp
        @esmtp = false
        @error_occurred = false
        retry
      end
      raise
    end

    def do_finish
      quit if @socket and not @socket.closed? and not @error_occurred
    ensure
      @started = false
      @error_occurred = false
      @socket.close if @socket
      @socket = nil
    end

    #
    # Message Sending
    #

    public

    #
    # Sends +msgstr+ as a message.  Single CR ("\r") and LF ("\n") found
    # in the +msgstr+, are converted into the CR LF pair.  You cannot send a
    # binary message with this method. +msgstr+ should include both
    # the message headers and body.
    #
    # +from_addr+ is a String representing the source mail address.
    #
    # +to_addr+ is a String or Strings or Array of Strings, representing
    # the destination mail address or addresses.
    #
    # === Example
    #
    #     Net::SMTP.start('smtp.example.com') do |smtp|
    #       smtp.send_message msgstr,
    #                         'from@example.com',
    #                         ['dest@example.com', 'dest2@example.com']
    #     end
    #
    # === Errors
    #
    # This method may raise:
    #
    # * Net::SMTPServerBusy
    # * Net::SMTPSyntaxError
    # * Net::SMTPFatalError
    # * Net::SMTPUnknownError
    # * Net::ReadTimeout
    # * IOError
    #
    def send_message(msgstr, from_addr, *to_addrs)
      raise IOError, 'closed session' unless @socket
      mailfrom from_addr
      rcptto_list(to_addrs) {data msgstr}
    end

    alias send_mail send_message
    alias sendmail send_message   # obsolete

    #
    # Opens a message writer stream and gives it to the block.
    # The stream is valid only in the block, and has these methods:
    #
    # puts(str = '')::       outputs STR and CR LF.
    # print(str)::           outputs STR.
    # printf(fmt, *args)::   outputs sprintf(fmt,*args).
    # write(str)::           outputs STR and returns the length of written bytes.
    # <<(str)::              outputs STR and returns self.
    #
    # If a single CR ("\r") or LF ("\n") is found in the message,
    # it is converted to the CR LF pair.  You cannot send a binary
    # message with this method.
    #
    # === Parameters
    #
    # +from_addr+ is a String representing the source mail address.
    #
    # +to_addr+ is a String or Strings or Array of Strings, representing
    # the destination mail address or addresses.
    #
    # === Example
    #
    #     Net::SMTP.start('smtp.example.com', 25) do |smtp|
    #       smtp.open_message_stream('from@example.com', ['dest@example.com']) do |f|
    #         f.puts 'From: from@example.com'
    #         f.puts 'To: dest@example.com'
    #         f.puts 'Subject: test message'
    #         f.puts
    #         f.puts 'This is a test message.'
    #       end
    #     end
    #
    # === Errors
    #
    # This method may raise:
    #
    # * Net::SMTPServerBusy
    # * Net::SMTPSyntaxError
    # * Net::SMTPFatalError
    # * Net::SMTPUnknownError
    # * Net::ReadTimeout
    # * IOError
    #
    def open_message_stream(from_addr, *to_addrs, &block)   # :yield: stream
      raise IOError, 'closed session' unless @socket
      mailfrom from_addr
      rcptto_list(to_addrs) {data(&block)}
    end

    alias ready open_message_stream   # obsolete

    #
    # Authentication
    #

    public

    DEFAULT_AUTH_TYPE = :plain

    def authenticate(user, secret, authtype = DEFAULT_AUTH_TYPE)
      check_auth_method authtype
      check_auth_args user, secret
      public_send auth_method(authtype), user, secret
    end

    def auth_plain(user, secret)
      check_auth_args user, secret
      res = critical {
        get_response('AUTH PLAIN ' + base64_encode("\0#{user}\0#{secret}"))
      }
      check_auth_response res
      res
    end

    def auth_login(user, secret)
      check_auth_args user, secret
      res = critical {
        check_auth_continue get_response('AUTH LOGIN')
        check_auth_continue get_response(base64_encode(user))
        get_response(base64_encode(secret))
      }
      check_auth_response res
      res
    end

    def auth_cram_md5(user, secret)
      check_auth_args user, secret
      res = critical {
        res0 = get_response('AUTH CRAM-MD5')
        check_auth_continue res0
        crammed = cram_md5_response(secret, res0.cram_md5_challenge)
        get_response(base64_encode("#{user} #{crammed}"))
      }
      check_auth_response res
      res
    end

    private

    def check_auth_method(type)
      unless respond_to?(auth_method(type), true)
        raise ArgumentError, "wrong authentication type #{type}"
      end
    end

    def auth_method(type)
      "auth_#{type.to_s.downcase}".intern
    end

    def check_auth_args(user, secret, authtype = DEFAULT_AUTH_TYPE)
      unless user
        raise ArgumentError, 'SMTP-AUTH requested but missing user name'
      end
      unless secret
        raise ArgumentError, 'SMTP-AUTH requested but missing secret phrase'
      end
    end

    def base64_encode(str)
      # expects "str" may not become too long
      [str].pack('m0')
    end

    IMASK = 0x36
    OMASK = 0x5c

    # CRAM-MD5: [RFC2195]
    def cram_md5_response(secret, challenge)
      tmp = Digest::MD5.digest(cram_secret(secret, IMASK) + challenge)
      Digest::MD5.hexdigest(cram_secret(secret, OMASK) + tmp)
    end

    CRAM_BUFSIZE = 64

    def cram_secret(secret, mask)
      secret = Digest::MD5.digest(secret) if secret.size > CRAM_BUFSIZE
      buf = secret.ljust(CRAM_BUFSIZE, "\0")
      0.upto(buf.size - 1) do |i|
        buf[i] = (buf[i].ord ^ mask).chr
      end
      buf
    end

    #
    # SMTP command dispatcher
    #

    public

    # Aborts the current mail transaction

    def rset
      getok('RSET')
    end

    def starttls
      getok('STARTTLS')
    end

    def helo(domain)
      getok("HELO #{domain}")
    end

    def ehlo(domain)
      getok("EHLO #{domain}")
    end

    def mailfrom(from_addr)
      getok("MAIL FROM:<#{from_addr}>")
    end

    def rcptto_list(to_addrs)
      raise ArgumentError, 'mail destination not given' if to_addrs.empty?
      ok_users = []
      unknown_users = []
      to_addrs.flatten.each do |addr|
        begin
          rcptto addr
        rescue SMTPAuthenticationError
          unknown_users << addr.dump
        else
          ok_users << addr
        end
      end
      raise ArgumentError, 'mail destination not given' if ok_users.empty?
      ret = yield
      unless unknown_users.empty?
        raise SMTPAuthenticationError, "failed to deliver for #{unknown_users.join(', ')}"
      end
      ret
    end

    def rcptto(to_addr)
      getok("RCPT TO:<#{to_addr}>")
    end

    # This method sends a message.
    # If +msgstr+ is given, sends it as a message.
    # If block is given, yield a message writer stream.
    # You must write message before the block is closed.
    #
    #   # Example 1 (by string)
    #   smtp.data(<<EndMessage)
    #   From: john@example.com
    #   To: betty@example.com
    #   Subject: I found a bug
    #
    #   Check vm.c:58879.
    #   EndMessage
    #
    #   # Example 2 (by block)
    #   smtp.data {|f|
    #     f.puts "From: john@example.com"
    #     f.puts "To: betty@example.com"
    #     f.puts "Subject: I found a bug"
    #     f.puts ""
    #     f.puts "Check vm.c:58879."
    #   }
    #
    def data(msgstr = nil, &block)   #:yield: stream
      if msgstr and block
        raise ArgumentError, "message and block are exclusive"
      end
      unless msgstr or block
        raise ArgumentError, "message or block is required"
      end
      res = critical {
        check_continue get_response('DATA')
        socket_sync_bak = @socket.io.sync
        begin
          @socket.io.sync = false
          if msgstr
            @socket.write_message msgstr
          else
            @socket.write_message_by_block(&block)
          end
        ensure
          @socket.io.flush
          @socket.io.sync = socket_sync_bak
        end
        recv_response()
      }
      check_response res
      res
    end

    def quit
      getok('QUIT')
    end

    private

    def validate_line(line)
      # A bare CR or LF is not allowed in RFC5321.
      if /[\r\n]/ =~ line
        raise ArgumentError, "A line must not contain CR or LF"
      end
    end

    def getok(reqline)
      validate_line reqline
      res = critical {
        @socket.writeline reqline
        recv_response()
      }
      check_response res
      res
    end

    def get_response(reqline)
      validate_line reqline
      @socket.writeline reqline
      recv_response()
    end

    def recv_response
      buf = ''.dup
      while true
        line = @socket.readline
        buf << line << "\n"
        break unless line[3,1] == '-'   # "210-PIPELINING"
      end
      Response.parse(buf)
    end

    def critical
      return Response.parse('200 dummy reply code') if @error_occurred
      begin
        return yield()
      rescue Exception
        @error_occurred = true
        raise
      end
    end

    def check_response(res)
      unless res.success?
        raise res.exception_class, res.message
      end
    end

    def check_continue(res)
      unless res.continue?
        raise SMTPUnknownError, "could not get 3xx (#{res.status}: #{res.string})"
      end
    end

    def check_auth_response(res)
      unless res.success?
        raise SMTPAuthenticationError, res.message
      end
    end

    def check_auth_continue(res)
      unless res.continue?
        raise res.exception_class, res.message
      end
    end

    # This class represents a response received by the SMTP server. Instances
    # of this class are created by the SMTP class; they should not be directly
    # created by the user. For more information on SMTP responses, view
    # {Section 4.2 of RFC 5321}[http://tools.ietf.org/html/rfc5321#section-4.2]
    class Response
      # Parses the received response and separates the reply code and the human
      # readable reply text
      def self.parse(str)
        new(str[0,3], str)
      end

      # Creates a new instance of the Response class and sets the status and
      # string attributes
      def initialize(status, string)
        @status = status
        @string = string
      end

      # The three digit reply code of the SMTP response
      attr_reader :status

      # The human readable reply text of the SMTP response
      attr_reader :string

      # Takes the first digit of the reply code to determine the status type
      def status_type_char
        @status[0, 1]
      end

      # Determines whether the response received was a Positive Completion
      # reply (2xx reply code)
      def success?
        status_type_char() == '2'
      end

      # Determines whether the response received was a Positive Intermediate
      # reply (3xx reply code)
      def continue?
        status_type_char() == '3'
      end

      # The first line of the human readable reply text
      def message
        @string.lines.first
      end

      # Creates a CRAM-MD5 challenge. You can view more information on CRAM-MD5
      # on Wikipedia: https://en.wikipedia.org/wiki/CRAM-MD5
      def cram_md5_challenge
        @string.split(/ /)[1].unpack1('m')
      end

      # Returns a hash of the human readable reply text in the response if it
      # is multiple lines. It does not return the first line. The key of the
      # hash is the first word the value of the hash is an array with each word
      # thereafter being a value in the array
      def capabilities
        return {} unless @string[3, 1] == '-'
        h = {}
        @string.lines.drop(1).each do |line|
          k, *v = line[4..-1].split(' ')
          h[k] = v
        end
        h
      end

      # Determines whether there was an error and raises the appropriate error
      # based on the reply code of the response
      def exception_class
        case @status
        when /\A4/  then SMTPServerBusy
        when /\A50/ then SMTPSyntaxError
        when /\A53/ then SMTPAuthenticationError
        when /\A5/  then SMTPFatalError
        else             SMTPUnknownError
        end
      end
    end

    def logging(msg)
      @debug_output << msg + "\n" if @debug_output
    end

  end   # class SMTP

  SMTPSession = SMTP # :nodoc:

end
# frozen_string_literal: true
#
# = net/protocol.rb
#
#--
# Copyright (c) 1999-2004 Yukihiro Matsumoto
# Copyright (c) 1999-2004 Minero Aoki
#
# written and maintained by Minero Aoki <aamine@loveruby.net>
#
# This program is free software. You can re-distribute and/or
# modify this program under the same terms as Ruby itself,
# Ruby Distribute License or GNU General Public License.
#
# $Id$
#++
#
# WARNING: This file is going to remove.
# Do not rely on the implementation written in this file.
#

require 'socket'
require 'timeout'
require 'io/wait'

module Net # :nodoc:

  class Protocol   #:nodoc: internal use only
    VERSION = "0.1.1"

    private
    def Protocol.protocol_param(name, val)
      module_eval(<<-End, __FILE__, __LINE__ + 1)
        def #{name}
          #{val}
        end
      End
    end

    def ssl_socket_connect(s, timeout)
      if timeout
        while true
          raise Net::OpenTimeout if timeout <= 0
          start = Process.clock_gettime Process::CLOCK_MONOTONIC
          # to_io is required because SSLSocket doesn't have wait_readable yet
          case s.connect_nonblock(exception: false)
          when :wait_readable; s.to_io.wait_readable(timeout)
          when :wait_writable; s.to_io.wait_writable(timeout)
          else; break
          end
          timeout -= Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
        end
      else
        s.connect
      end
    end
  end


  class ProtocolError          < StandardError; end
  class ProtoSyntaxError       < ProtocolError; end
  class ProtoFatalError        < ProtocolError; end
  class ProtoUnknownError      < ProtocolError; end
  class ProtoServerError       < ProtocolError; end
  class ProtoAuthError         < ProtocolError; end
  class ProtoCommandError      < ProtocolError; end
  class ProtoRetriableError    < ProtocolError; end
  ProtocRetryError = ProtoRetriableError

  ##
  # OpenTimeout, a subclass of Timeout::Error, is raised if a connection cannot
  # be created within the open_timeout.

  class OpenTimeout            < Timeout::Error; end

  ##
  # ReadTimeout, a subclass of Timeout::Error, is raised if a chunk of the
  # response cannot be read within the read_timeout.

  class ReadTimeout < Timeout::Error
    def initialize(io = nil)
      @io = io
    end
    attr_reader :io

    def message
      msg = super
      if @io
        msg = "#{msg} with #{@io.inspect}"
      end
      msg
    end
  end

  ##
  # WriteTimeout, a subclass of Timeout::Error, is raised if a chunk of the
  # response cannot be written within the write_timeout.  Not raised on Windows.

  class WriteTimeout < Timeout::Error
    def initialize(io = nil)
      @io = io
    end
    attr_reader :io

    def message
      msg = super
      if @io
        msg = "#{msg} with #{@io.inspect}"
      end
      msg
    end
  end


  class BufferedIO   #:nodoc: internal use only
    def initialize(io, read_timeout: 60, write_timeout: 60, continue_timeout: nil, debug_output: nil)
      @io = io
      @read_timeout = read_timeout
      @write_timeout = write_timeout
      @continue_timeout = continue_timeout
      @debug_output = debug_output
      @rbuf = ''.b
    end

    attr_reader :io
    attr_accessor :read_timeout
    attr_accessor :write_timeout
    attr_accessor :continue_timeout
    attr_accessor :debug_output

    def inspect
      "#<#{self.class} io=#{@io}>"
    end

    def eof?
      @io.eof?
    end

    def closed?
      @io.closed?
    end

    def close
      @io.close
    end

    #
    # Read
    #

    public

    def read(len, dest = ''.b, ignore_eof = false)
      LOG "reading #{len} bytes..."
      read_bytes = 0
      begin
        while read_bytes + @rbuf.size < len
          s = rbuf_consume(@rbuf.size)
          read_bytes += s.size
          dest << s
          rbuf_fill
        end
        s = rbuf_consume(len - read_bytes)
        read_bytes += s.size
        dest << s
      rescue EOFError
        raise unless ignore_eof
      end
      LOG "read #{read_bytes} bytes"
      dest
    end

    def read_all(dest = ''.b)
      LOG 'reading all...'
      read_bytes = 0
      begin
        while true
          s = rbuf_consume(@rbuf.size)
          read_bytes += s.size
          dest << s
          rbuf_fill
        end
      rescue EOFError
        ;
      end
      LOG "read #{read_bytes} bytes"
      dest
    end

    def readuntil(terminator, ignore_eof = false)
      begin
        until idx = @rbuf.index(terminator)
          rbuf_fill
        end
        return rbuf_consume(idx + terminator.size)
      rescue EOFError
        raise unless ignore_eof
        return rbuf_consume(@rbuf.size)
      end
    end

    def readline
      readuntil("\n").chop
    end

    private

    BUFSIZE = 1024 * 16

    def rbuf_fill
      tmp = @rbuf.empty? ? @rbuf : nil
      case rv = @io.read_nonblock(BUFSIZE, tmp, exception: false)
      when String
        return if rv.equal?(tmp)
        @rbuf << rv
        rv.clear
        return
      when :wait_readable
        (io = @io.to_io).wait_readable(@read_timeout) or raise Net::ReadTimeout.new(io)
        # continue looping
      when :wait_writable
        # OpenSSL::Buffering#read_nonblock may fail with IO::WaitWritable.
        # http://www.openssl.org/support/faq.html#PROG10
        (io = @io.to_io).wait_writable(@read_timeout) or raise Net::ReadTimeout.new(io)
        # continue looping
      when nil
        raise EOFError, 'end of file reached'
      end while true
    end

    def rbuf_consume(len)
      if len == @rbuf.size
        s = @rbuf
        @rbuf = ''.b
      else
        s = @rbuf.slice!(0, len)
      end
      @debug_output << %Q[-> #{s.dump}\n] if @debug_output
      s
    end

    #
    # Write
    #

    public

    def write(*strs)
      writing {
        write0(*strs)
      }
    end

    alias << write

    def writeline(str)
      writing {
        write0 str + "\r\n"
      }
    end

    private

    def writing
      @written_bytes = 0
      @debug_output << '<- ' if @debug_output
      yield
      @debug_output << "\n" if @debug_output
      bytes = @written_bytes
      @written_bytes = nil
      bytes
    end

    def write0(*strs)
      @debug_output << strs.map(&:dump).join if @debug_output
      orig_written_bytes = @written_bytes
      strs.each_with_index do |str, i|
        need_retry = true
        case len = @io.write_nonblock(str, exception: false)
        when Integer
          @written_bytes += len
          len -= str.bytesize
          if len == 0
            if strs.size == i+1
              return @written_bytes - orig_written_bytes
            else
              need_retry = false
              # next string
            end
          elsif len < 0
            str = str.byteslice(len, -len)
          else # len > 0
            need_retry = false
            # next string
          end
          # continue looping
        when :wait_writable
          (io = @io.to_io).wait_writable(@write_timeout) or raise Net::WriteTimeout.new(io)
          # continue looping
        end while need_retry
      end
    end

    #
    # Logging
    #

    private

    def LOG_off
      @save_debug_out = @debug_output
      @debug_output = nil
    end

    def LOG_on
      @debug_output = @save_debug_out
    end

    def LOG(msg)
      return unless @debug_output
      @debug_output << msg + "\n"
    end
  end


  class InternetMessageIO < BufferedIO   #:nodoc: internal use only
    def initialize(*, **)
      super
      @wbuf = nil
    end

    #
    # Read
    #

    def each_message_chunk
      LOG 'reading message...'
      LOG_off()
      read_bytes = 0
      while (line = readuntil("\r\n")) != ".\r\n"
        read_bytes += line.size
        yield line.delete_prefix('.')
      end
      LOG_on()
      LOG "read message (#{read_bytes} bytes)"
    end

    # *library private* (cannot handle 'break')
    def each_list_item
      while (str = readuntil("\r\n")) != ".\r\n"
        yield str.chop
      end
    end

    def write_message_0(src)
      prev = @written_bytes
      each_crlf_line(src) do |line|
        write0 dot_stuff(line)
      end
      @written_bytes - prev
    end

    #
    # Write
    #

    def write_message(src)
      LOG "writing message from #{src.class}"
      LOG_off()
      len = writing {
        using_each_crlf_line {
          write_message_0 src
        }
      }
      LOG_on()
      LOG "wrote #{len} bytes"
      len
    end

    def write_message_by_block(&block)
      LOG 'writing message from block'
      LOG_off()
      len = writing {
        using_each_crlf_line {
          begin
            block.call(WriteAdapter.new(self, :write_message_0))
          rescue LocalJumpError
            # allow `break' from writer block
          end
        }
      }
      LOG_on()
      LOG "wrote #{len} bytes"
      len
    end

    private

    def dot_stuff(s)
      s.sub(/\A\./, '..')
    end

    def using_each_crlf_line
      @wbuf = ''.b
      yield
      if not @wbuf.empty?   # unterminated last line
        write0 dot_stuff(@wbuf.chomp) + "\r\n"
      elsif @written_bytes == 0   # empty src
        write0 "\r\n"
      end
      write0 ".\r\n"
      @wbuf = nil
    end

    def each_crlf_line(src)
      buffer_filling(@wbuf, src) do
        while line = @wbuf.slice!(/\A[^\r\n]*(?:\n|\r(?:\n|(?!\z)))/)
          yield line.chomp("\n") + "\r\n"
        end
      end
    end

    def buffer_filling(buf, src)
      case src
      when String    # for speeding up.
        0.step(src.size - 1, 1024) do |i|
          buf << src[i, 1024]
          yield
        end
      when File    # for speeding up.
        while s = src.read(1024)
          buf << s
          yield
        end
      else    # generic reader
        src.each do |str|
          buf << str
          yield if buf.size > 1024
        end
        yield unless buf.empty?
      end
    end
  end


  #
  # The writer adapter class
  #
  class WriteAdapter
    def initialize(socket, method)
      @socket = socket
      @method_id = method
    end

    def inspect
      "#<#{self.class} socket=#{@socket.inspect}>"
    end

    def write(str)
      @socket.__send__(@method_id, str)
    end

    alias print write

    def <<(str)
      write str
      self
    end

    def puts(str = '')
      write str.chomp("\n") + "\n"
    end

    def printf(*args)
      write sprintf(*args)
    end
  end


  class ReadAdapter   #:nodoc: internal use only
    def initialize(block)
      @block = block
    end

    def inspect
      "#<#{self.class}>"
    end

    def <<(str)
      call_block(str, &@block) if @block
    end

    private

    # This method is needed because @block must be called by yield,
    # not Proc#call.  You can see difference when using `break' in
    # the block.
    def call_block(str)
      yield str
    end
  end


  module NetPrivate   #:nodoc: obsolete
    Socket = ::Net::InternetMessageIO
  end

end   # module Net
# frozen_string_literal: true
# = net/pop.rb
#
# Copyright (c) 1999-2007 Yukihiro Matsumoto.
#
# Copyright (c) 1999-2007 Minero Aoki.
#
# Written & maintained by Minero Aoki <aamine@loveruby.net>.
#
# Documented by William Webber and Minero Aoki.
#
# This program is free software. You can re-distribute and/or
# modify this program under the same terms as Ruby itself,
# Ruby Distribute License.
#
# NOTE: You can find Japanese version of this document at:
# http://docs.ruby-lang.org/ja/latest/library/net=2fpop.html
#
#   $Id$
#
# See Net::POP3 for documentation.
#

require 'net/protocol'
require 'digest/md5'
require 'timeout'

begin
  require "openssl"
rescue LoadError
end

module Net

  # Non-authentication POP3 protocol error
  # (reply code "-ERR", except authentication).
  class POPError < ProtocolError; end

  # POP3 authentication error.
  class POPAuthenticationError < ProtoAuthError; end

  # Unexpected response from the server.
  class POPBadResponse < POPError; end

  #
  # == What is This Library?
  #
  # This library provides functionality for retrieving
  # email via POP3, the Post Office Protocol version 3. For details
  # of POP3, see [RFC1939] (http://www.ietf.org/rfc/rfc1939.txt).
  #
  # == Examples
  #
  # === Retrieving Messages
  #
  # This example retrieves messages from the server and deletes them
  # on the server.
  #
  # Messages are written to files named 'inbox/1', 'inbox/2', ....
  # Replace 'pop.example.com' with your POP3 server address, and
  # 'YourAccount' and 'YourPassword' with the appropriate account
  # details.
  #
  #     require 'net/pop'
  #
  #     pop = Net::POP3.new('pop.example.com')
  #     pop.start('YourAccount', 'YourPassword')             # (1)
  #     if pop.mails.empty?
  #       puts 'No mail.'
  #     else
  #       i = 0
  #       pop.each_mail do |m|   # or "pop.mails.each ..."   # (2)
  #         File.open("inbox/#{i}", 'w') do |f|
  #           f.write m.pop
  #         end
  #         m.delete
  #         i += 1
  #       end
  #       puts "#{pop.mails.size} mails popped."
  #     end
  #     pop.finish                                           # (3)
  #
  # 1. Call Net::POP3#start and start POP session.
  # 2. Access messages by using POP3#each_mail and/or POP3#mails.
  # 3. Close POP session by calling POP3#finish or use the block form of #start.
  #
  # === Shortened Code
  #
  # The example above is very verbose. You can shorten the code by using
  # some utility methods. First, the block form of Net::POP3.start can
  # be used instead of POP3.new, POP3#start and POP3#finish.
  #
  #     require 'net/pop'
  #
  #     Net::POP3.start('pop.example.com', 110,
  #                     'YourAccount', 'YourPassword') do |pop|
  #       if pop.mails.empty?
  #         puts 'No mail.'
  #       else
  #         i = 0
  #         pop.each_mail do |m|   # or "pop.mails.each ..."
  #           File.open("inbox/#{i}", 'w') do |f|
  #             f.write m.pop
  #           end
  #           m.delete
  #           i += 1
  #         end
  #         puts "#{pop.mails.size} mails popped."
  #       end
  #     end
  #
  # POP3#delete_all is an alternative for #each_mail and #delete.
  #
  #     require 'net/pop'
  #
  #     Net::POP3.start('pop.example.com', 110,
  #                     'YourAccount', 'YourPassword') do |pop|
  #       if pop.mails.empty?
  #         puts 'No mail.'
  #       else
  #         i = 1
  #         pop.delete_all do |m|
  #           File.open("inbox/#{i}", 'w') do |f|
  #             f.write m.pop
  #           end
  #           i += 1
  #         end
  #       end
  #     end
  #
  # And here is an even shorter example.
  #
  #     require 'net/pop'
  #
  #     i = 0
  #     Net::POP3.delete_all('pop.example.com', 110,
  #                          'YourAccount', 'YourPassword') do |m|
  #       File.open("inbox/#{i}", 'w') do |f|
  #         f.write m.pop
  #       end
  #       i += 1
  #     end
  #
  # === Memory Space Issues
  #
  # All the examples above get each message as one big string.
  # This example avoids this.
  #
  #     require 'net/pop'
  #
  #     i = 1
  #     Net::POP3.delete_all('pop.example.com', 110,
  #                          'YourAccount', 'YourPassword') do |m|
  #       File.open("inbox/#{i}", 'w') do |f|
  #         m.pop do |chunk|    # get a message little by little.
  #           f.write chunk
  #         end
  #         i += 1
  #       end
  #     end
  #
  # === Using APOP
  #
  # The net/pop library supports APOP authentication.
  # To use APOP, use the Net::APOP class instead of the Net::POP3 class.
  # You can use the utility method, Net::POP3.APOP(). For example:
  #
  #     require 'net/pop'
  #
  #     # Use APOP authentication if $isapop == true
  #     pop = Net::POP3.APOP($isapop).new('apop.example.com', 110)
  #     pop.start('YourAccount', 'YourPassword') do |pop|
  #       # Rest of the code is the same.
  #     end
  #
  # === Fetch Only Selected Mail Using 'UIDL' POP Command
  #
  # If your POP server provides UIDL functionality,
  # you can grab only selected mails from the POP server.
  # e.g.
  #
  #     def need_pop?( id )
  #       # determine if we need pop this mail...
  #     end
  #
  #     Net::POP3.start('pop.example.com', 110,
  #                     'Your account', 'Your password') do |pop|
  #       pop.mails.select { |m| need_pop?(m.unique_id) }.each do |m|
  #         do_something(m.pop)
  #       end
  #     end
  #
  # The POPMail#unique_id() method returns the unique-id of the message as a
  # String. Normally the unique-id is a hash of the message.
  #
  class POP3 < Protocol
    # version of this library
    VERSION = "0.1.1"

    #
    # Class Parameters
    #

    # returns the port for POP3
    def POP3.default_port
      default_pop3_port()
    end

    # The default port for POP3 connections, port 110
    def POP3.default_pop3_port
      110
    end

    # The default port for POP3S connections, port 995
    def POP3.default_pop3s_port
      995
    end

    def POP3.socket_type   #:nodoc: obsolete
      Net::InternetMessageIO
    end

    #
    # Utilities
    #

    # Returns the APOP class if +isapop+ is true; otherwise, returns
    # the POP class.  For example:
    #
    #     # Example 1
    #     pop = Net::POP3::APOP($is_apop).new(addr, port)
    #
    #     # Example 2
    #     Net::POP3::APOP($is_apop).start(addr, port) do |pop|
    #       ....
    #     end
    #
    def POP3.APOP(isapop)
      isapop ? APOP : POP3
    end

    # Starts a POP3 session and iterates over each POPMail object,
    # yielding it to the +block+.
    # This method is equivalent to:
    #
    #     Net::POP3.start(address, port, account, password) do |pop|
    #       pop.each_mail do |m|
    #         yield m
    #       end
    #     end
    #
    # This method raises a POPAuthenticationError if authentication fails.
    #
    # === Example
    #
    #     Net::POP3.foreach('pop.example.com', 110,
    #                       'YourAccount', 'YourPassword') do |m|
    #       file.write m.pop
    #       m.delete if $DELETE
    #     end
    #
    def POP3.foreach(address, port = nil,
                     account = nil, password = nil,
                     isapop = false, &block)  # :yields: message
      start(address, port, account, password, isapop) {|pop|
        pop.each_mail(&block)
      }
    end

    # Starts a POP3 session and deletes all messages on the server.
    # If a block is given, each POPMail object is yielded to it before
    # being deleted.
    #
    # This method raises a POPAuthenticationError if authentication fails.
    #
    # === Example
    #
    #     Net::POP3.delete_all('pop.example.com', 110,
    #                          'YourAccount', 'YourPassword') do |m|
    #       file.write m.pop
    #     end
    #
    def POP3.delete_all(address, port = nil,
                        account = nil, password = nil,
                        isapop = false, &block)
      start(address, port, account, password, isapop) {|pop|
        pop.delete_all(&block)
      }
    end

    # Opens a POP3 session, attempts authentication, and quits.
    #
    # This method raises POPAuthenticationError if authentication fails.
    #
    # === Example: normal POP3
    #
    #     Net::POP3.auth_only('pop.example.com', 110,
    #                         'YourAccount', 'YourPassword')
    #
    # === Example: APOP
    #
    #     Net::POP3.auth_only('pop.example.com', 110,
    #                         'YourAccount', 'YourPassword', true)
    #
    def POP3.auth_only(address, port = nil,
                       account = nil, password = nil,
                       isapop = false)
      new(address, port, isapop).auth_only account, password
    end

    # Starts a pop3 session, attempts authentication, and quits.
    # This method must not be called while POP3 session is opened.
    # This method raises POPAuthenticationError if authentication fails.
    def auth_only(account, password)
      raise IOError, 'opening previously opened POP session' if started?
      start(account, password) {
        ;
      }
    end

    #
    # SSL
    #

    @ssl_params = nil

    # :call-seq:
    #    Net::POP.enable_ssl(params = {})
    #
    # Enable SSL for all new instances.
    # +params+ is passed to OpenSSL::SSLContext#set_params.
    def POP3.enable_ssl(*args)
      @ssl_params = create_ssl_params(*args)
    end

    # Constructs proper parameters from arguments
    def POP3.create_ssl_params(verify_or_params = {}, certs = nil)
      begin
        params = verify_or_params.to_hash
      rescue NoMethodError
        params = {}
        params[:verify_mode] = verify_or_params
        if certs
          if File.file?(certs)
            params[:ca_file] = certs
          elsif File.directory?(certs)
            params[:ca_path] = certs
          end
        end
      end
      return params
    end

    # Disable SSL for all new instances.
    def POP3.disable_ssl
      @ssl_params = nil
    end

    # returns the SSL Parameters
    #
    # see also POP3.enable_ssl
    def POP3.ssl_params
      return @ssl_params
    end

    # returns +true+ if POP3.ssl_params is set
    def POP3.use_ssl?
      return !@ssl_params.nil?
    end

    # returns whether verify_mode is enable from POP3.ssl_params
    def POP3.verify
      return @ssl_params[:verify_mode]
    end

    # returns the :ca_file or :ca_path from POP3.ssl_params
    def POP3.certs
      return @ssl_params[:ca_file] || @ssl_params[:ca_path]
    end

    #
    # Session management
    #

    # Creates a new POP3 object and open the connection.  Equivalent to
    #
    #   Net::POP3.new(address, port, isapop).start(account, password)
    #
    # If +block+ is provided, yields the newly-opened POP3 object to it,
    # and automatically closes it at the end of the session.
    #
    # === Example
    #
    #    Net::POP3.start(addr, port, account, password) do |pop|
    #      pop.each_mail do |m|
    #        file.write m.pop
    #        m.delete
    #      end
    #    end
    #
    def POP3.start(address, port = nil,
                   account = nil, password = nil,
                   isapop = false, &block)   # :yield: pop
      new(address, port, isapop).start(account, password, &block)
    end

    # Creates a new POP3 object.
    #
    # +address+ is the hostname or ip address of your POP3 server.
    #
    # The optional +port+ is the port to connect to.
    #
    # The optional +isapop+ specifies whether this connection is going
    # to use APOP authentication; it defaults to +false+.
    #
    # This method does *not* open the TCP connection.
    def initialize(addr, port = nil, isapop = false)
      @address = addr
      @ssl_params = POP3.ssl_params
      @port = port
      @apop = isapop

      @command = nil
      @socket = nil
      @started = false
      @open_timeout = 30
      @read_timeout = 60
      @debug_output = nil

      @mails = nil
      @n_mails = nil
      @n_bytes = nil
    end

    # Does this instance use APOP authentication?
    def apop?
      @apop
    end

    # does this instance use SSL?
    def use_ssl?
      return !@ssl_params.nil?
    end

    # :call-seq:
    #    Net::POP#enable_ssl(params = {})
    #
    # Enables SSL for this instance.  Must be called before the connection is
    # established to have any effect.
    # +params[:port]+ is port to establish the SSL connection on; Defaults to 995.
    # +params+ (except :port) is passed to OpenSSL::SSLContext#set_params.
    def enable_ssl(verify_or_params = {}, certs = nil, port = nil)
      begin
        @ssl_params = verify_or_params.to_hash.dup
        @port = @ssl_params.delete(:port) || @port
      rescue NoMethodError
        @ssl_params = POP3.create_ssl_params(verify_or_params, certs)
        @port = port || @port
      end
    end

    # Disable SSL for all new instances.
    def disable_ssl
      @ssl_params = nil
    end

    # Provide human-readable stringification of class state.
    def inspect
      +"#<#{self.class} #{@address}:#{@port} open=#{@started}>"
    end

    # *WARNING*: This method causes a serious security hole.
    # Use this method only for debugging.
    #
    # Set an output stream for debugging.
    #
    # === Example
    #
    #   pop = Net::POP.new(addr, port)
    #   pop.set_debug_output $stderr
    #   pop.start(account, passwd) do |pop|
    #     ....
    #   end
    #
    def set_debug_output(arg)
      @debug_output = arg
    end

    # The address to connect to.
    attr_reader :address

    # The port number to connect to.
    def port
      return @port || (use_ssl? ? POP3.default_pop3s_port : POP3.default_pop3_port)
    end

    # Seconds to wait until a connection is opened.
    # If the POP3 object cannot open a connection within this time,
    # it raises a Net::OpenTimeout exception. The default value is 30 seconds.
    attr_accessor :open_timeout

    # Seconds to wait until reading one block (by one read(1) call).
    # If the POP3 object cannot complete a read() within this time,
    # it raises a Net::ReadTimeout exception. The default value is 60 seconds.
    attr_reader :read_timeout

    # Set the read timeout.
    def read_timeout=(sec)
      @command.socket.read_timeout = sec if @command
      @read_timeout = sec
    end

    # +true+ if the POP3 session has started.
    def started?
      @started
    end

    alias active? started?   #:nodoc: obsolete

    # Starts a POP3 session.
    #
    # When called with block, gives a POP3 object to the block and
    # closes the session after block call finishes.
    #
    # This method raises a POPAuthenticationError if authentication fails.
    def start(account, password) # :yield: pop
      raise IOError, 'POP session already started' if @started
      if block_given?
        begin
          do_start account, password
          return yield(self)
        ensure
          do_finish
        end
      else
        do_start account, password
        return self
      end
    end

    # internal method for Net::POP3.start
    def do_start(account, password) # :nodoc:
      s = Timeout.timeout(@open_timeout, Net::OpenTimeout) do
        TCPSocket.open(@address, port)
      end
      if use_ssl?
        raise 'openssl library not installed' unless defined?(OpenSSL)
        context = OpenSSL::SSL::SSLContext.new
        context.set_params(@ssl_params)
        s = OpenSSL::SSL::SSLSocket.new(s, context)
        s.hostname = @address
        s.sync_close = true
        ssl_socket_connect(s, @open_timeout)
        if context.verify_mode != OpenSSL::SSL::VERIFY_NONE
          s.post_connection_check(@address)
        end
      end
      @socket = InternetMessageIO.new(s,
                                      read_timeout: @read_timeout,
                                      debug_output: @debug_output)
      logging "POP session started: #{@address}:#{@port} (#{@apop ? 'APOP' : 'POP'})"
      on_connect
      @command = POP3Command.new(@socket)
      if apop?
        @command.apop account, password
      else
        @command.auth account, password
      end
      @started = true
    ensure
      # Authentication failed, clean up connection.
      unless @started
        s.close if s
        @socket = nil
        @command = nil
      end
    end
    private :do_start

    # Does nothing
    def on_connect # :nodoc:
    end
    private :on_connect

    # Finishes a POP3 session and closes TCP connection.
    def finish
      raise IOError, 'POP session not yet started' unless started?
      do_finish
    end

    # nil's out the:
    # - mails
    # - number counter for mails
    # - number counter for bytes
    # - quits the current command, if any
    def do_finish # :nodoc:
      @mails = nil
      @n_mails = nil
      @n_bytes = nil
      @command.quit if @command
    ensure
      @started = false
      @command = nil
      @socket.close if @socket
      @socket = nil
    end
    private :do_finish

    # Returns the current command.
    #
    # Raises IOError if there is no active socket
    def command # :nodoc:
      raise IOError, 'POP session not opened yet' \
                                      if not @socket or @socket.closed?
      @command
    end
    private :command

    #
    # POP protocol wrapper
    #

    # Returns the number of messages on the POP server.
    def n_mails
      return @n_mails if @n_mails
      @n_mails, @n_bytes = command().stat
      @n_mails
    end

    # Returns the total size in bytes of all the messages on the POP server.
    def n_bytes
      return @n_bytes if @n_bytes
      @n_mails, @n_bytes = command().stat
      @n_bytes
    end

    # Returns an array of Net::POPMail objects, representing all the
    # messages on the server.  This array is renewed when the session
    # restarts; otherwise, it is fetched from the server the first time
    # this method is called (directly or indirectly) and cached.
    #
    # This method raises a POPError if an error occurs.
    def mails
      return @mails.dup if @mails
      if n_mails() == 0
        # some popd raises error for LIST on the empty mailbox.
        @mails = []
        return []
      end

      @mails = command().list.map {|num, size|
        POPMail.new(num, size, self, command())
      }
      @mails.dup
    end

    # Yields each message to the passed-in block in turn.
    # Equivalent to:
    #
    #   pop3.mails.each do |popmail|
    #     ....
    #   end
    #
    # This method raises a POPError if an error occurs.
    def each_mail(&block)  # :yield: message
      mails().each(&block)
    end

    alias each each_mail

    # Deletes all messages on the server.
    #
    # If called with a block, yields each message in turn before deleting it.
    #
    # === Example
    #
    #     n = 1
    #     pop.delete_all do |m|
    #       File.open("inbox/#{n}") do |f|
    #         f.write m.pop
    #       end
    #       n += 1
    #     end
    #
    # This method raises a POPError if an error occurs.
    #
    def delete_all # :yield: message
      mails().each do |m|
        yield m if block_given?
        m.delete unless m.deleted?
      end
    end

    # Resets the session.  This clears all "deleted" marks from messages.
    #
    # This method raises a POPError if an error occurs.
    def reset
      command().rset
      mails().each do |m|
        m.instance_eval {
          @deleted = false
        }
      end
    end

    def set_all_uids   #:nodoc: internal use only (called from POPMail#uidl)
      uidl = command().uidl
      @mails.each {|m| m.uid = uidl[m.number] }
    end

    # debugging output for +msg+
    def logging(msg)
      @debug_output << msg + "\n" if @debug_output
    end

  end   # class POP3

  # class aliases
  POP = POP3 # :nodoc:
  POPSession  = POP3 # :nodoc:
  POP3Session = POP3 # :nodoc:

  #
  # This class is equivalent to POP3, except that it uses APOP authentication.
  #
  class APOP < POP3
    # Always returns true.
    def apop?
      true
    end
  end

  # class aliases
  APOPSession = APOP

  #
  # This class represents a message which exists on the POP server.
  # Instances of this class are created by the POP3 class; they should
  # not be directly created by the user.
  #
  class POPMail

    def initialize(num, len, pop, cmd)   #:nodoc:
      @number = num
      @length = len
      @pop = pop
      @command = cmd
      @deleted = false
      @uid = nil
    end

    # The sequence number of the message on the server.
    attr_reader :number

    # The length of the message in octets.
    attr_reader :length
    alias size length

    # Provide human-readable stringification of class state.
    def inspect
      +"#<#{self.class} #{@number}#{@deleted ? ' deleted' : ''}>"
    end

    #
    # This method fetches the message.  If called with a block, the
    # message is yielded to the block one chunk at a time.  If called
    # without a block, the message is returned as a String.  The optional
    # +dest+ argument will be prepended to the returned String; this
    # argument is essentially obsolete.
    #
    # === Example without block
    #
    #     POP3.start('pop.example.com', 110,
    #                'YourAccount', 'YourPassword') do |pop|
    #       n = 1
    #       pop.mails.each do |popmail|
    #         File.open("inbox/#{n}", 'w') do |f|
    #           f.write popmail.pop
    #         end
    #         popmail.delete
    #         n += 1
    #       end
    #     end
    #
    # === Example with block
    #
    #     POP3.start('pop.example.com', 110,
    #                'YourAccount', 'YourPassword') do |pop|
    #       n = 1
    #       pop.mails.each do |popmail|
    #         File.open("inbox/#{n}", 'w') do |f|
    #           popmail.pop do |chunk|            ####
    #             f.write chunk
    #           end
    #         end
    #         n += 1
    #       end
    #     end
    #
    # This method raises a POPError if an error occurs.
    #
    def pop( dest = +'', &block ) # :yield: message_chunk
      if block_given?
        @command.retr(@number, &block)
        nil
      else
        @command.retr(@number) do |chunk|
          dest << chunk
        end
        dest
      end
    end

    alias all pop    #:nodoc: obsolete
    alias mail pop   #:nodoc: obsolete

    # Fetches the message header and +lines+ lines of body.
    #
    # The optional +dest+ argument is obsolete.
    #
    # This method raises a POPError if an error occurs.
    def top(lines, dest = +'')
      @command.top(@number, lines) do |chunk|
        dest << chunk
      end
      dest
    end

    # Fetches the message header.
    #
    # The optional +dest+ argument is obsolete.
    #
    # This method raises a POPError if an error occurs.
    def header(dest = +'')
      top(0, dest)
    end

    # Marks a message for deletion on the server.  Deletion does not
    # actually occur until the end of the session; deletion may be
    # cancelled for _all_ marked messages by calling POP3#reset().
    #
    # This method raises a POPError if an error occurs.
    #
    # === Example
    #
    #     POP3.start('pop.example.com', 110,
    #                'YourAccount', 'YourPassword') do |pop|
    #       n = 1
    #       pop.mails.each do |popmail|
    #         File.open("inbox/#{n}", 'w') do |f|
    #           f.write popmail.pop
    #         end
    #         popmail.delete         ####
    #         n += 1
    #       end
    #     end
    #
    def delete
      @command.dele @number
      @deleted = true
    end

    alias delete! delete    #:nodoc: obsolete

    # True if the mail has been deleted.
    def deleted?
      @deleted
    end

    # Returns the unique-id of the message.
    # Normally the unique-id is a hash string of the message.
    #
    # This method raises a POPError if an error occurs.
    def unique_id
      return @uid if @uid
      @pop.set_all_uids
      @uid
    end

    alias uidl unique_id

    def uid=(uid)   #:nodoc: internal use only
      @uid = uid
    end

  end   # class POPMail


  class POP3Command   #:nodoc: internal use only

    def initialize(sock)
      @socket = sock
      @error_occurred = false
      res = check_response(critical { recv_response() })
      @apop_stamp = res.slice(/<[!-~]+@[!-~]+>/)
    end

    attr_reader :socket

    def inspect
      +"#<#{self.class} socket=#{@socket}>"
    end

    def auth(account, password)
      check_response_auth(critical {
        check_response_auth(get_response('USER %s', account))
        get_response('PASS %s', password)
      })
    end

    def apop(account, password)
      raise POPAuthenticationError, 'not APOP server; cannot login' \
                                                      unless @apop_stamp
      check_response_auth(critical {
        get_response('APOP %s %s',
                     account,
                     Digest::MD5.hexdigest(@apop_stamp + password))
      })
    end

    def list
      critical {
        getok 'LIST'
        list = []
        @socket.each_list_item do |line|
          m = /\A(\d+)[ \t]+(\d+)/.match(line) or
                  raise POPBadResponse, "bad response: #{line}"
          list.push  [m[1].to_i, m[2].to_i]
        end
        return list
      }
    end

    def stat
      res = check_response(critical { get_response('STAT') })
      m = /\A\+OK\s+(\d+)\s+(\d+)/.match(res) or
              raise POPBadResponse, "wrong response format: #{res}"
      [m[1].to_i, m[2].to_i]
    end

    def rset
      check_response(critical { get_response('RSET') })
    end

    def top(num, lines = 0, &block)
      critical {
        getok('TOP %d %d', num, lines)
        @socket.each_message_chunk(&block)
      }
    end

    def retr(num, &block)
      critical {
        getok('RETR %d', num)
        @socket.each_message_chunk(&block)
      }
    end

    def dele(num)
      check_response(critical { get_response('DELE %d', num) })
    end

    def uidl(num = nil)
      if num
        res = check_response(critical { get_response('UIDL %d', num) })
        return res.split(/ /)[1]
      else
        critical {
          getok('UIDL')
          table = {}
          @socket.each_list_item do |line|
            num, uid = line.split(' ')
            table[num.to_i] = uid
          end
          return table
        }
      end
    end

    def quit
      check_response(critical { get_response('QUIT') })
    end

    private

    def getok(fmt, *fargs)
      @socket.writeline sprintf(fmt, *fargs)
      check_response(recv_response())
    end

    def get_response(fmt, *fargs)
      @socket.writeline sprintf(fmt, *fargs)
      recv_response()
    end

    def recv_response
      @socket.readline
    end

    def check_response(res)
      raise POPError, res unless /\A\+OK/i =~ res
      res
    end

    def check_response_auth(res)
      raise POPAuthenticationError, res unless /\A\+OK/i =~ res
      res
    end

    def critical
      return '+OK dummy ok response' if @error_occurred
      begin
        return yield()
      rescue Exception
        @error_occurred = true
        raise
      end
    end

  end   # class POP3Command

end   # module Net
# frozen_string_literal: true
#
# = net/imap.rb
#
# Copyright (C) 2000  Shugo Maeda <shugo@ruby-lang.org>
#
# This library is distributed under the terms of the Ruby license.
# You can freely distribute/modify this library.
#
# Documentation: Shugo Maeda, with RDoc conversion and overview by William
# Webber.
#
# See Net::IMAP for documentation.
#


require "socket"
require "monitor"
require "digest/md5"
require "strscan"
require 'net/protocol'
begin
  require "openssl"
rescue LoadError
end

module Net

  #
  # Net::IMAP implements Internet Message Access Protocol (IMAP) client
  # functionality.  The protocol is described in [IMAP].
  #
  # == IMAP Overview
  #
  # An IMAP client connects to a server, and then authenticates
  # itself using either #authenticate() or #login().  Having
  # authenticated itself, there is a range of commands
  # available to it.  Most work with mailboxes, which may be
  # arranged in an hierarchical namespace, and each of which
  # contains zero or more messages.  How this is implemented on
  # the server is implementation-dependent; on a UNIX server, it
  # will frequently be implemented as files in mailbox format
  # within a hierarchy of directories.
  #
  # To work on the messages within a mailbox, the client must
  # first select that mailbox, using either #select() or (for
  # read-only access) #examine().  Once the client has successfully
  # selected a mailbox, they enter _selected_ state, and that
  # mailbox becomes the _current_ mailbox, on which mail-item
  # related commands implicitly operate.
  #
  # Messages have two sorts of identifiers: message sequence
  # numbers and UIDs.
  #
  # Message sequence numbers number messages within a mailbox
  # from 1 up to the number of items in the mailbox.  If a new
  # message arrives during a session, it receives a sequence
  # number equal to the new size of the mailbox.  If messages
  # are expunged from the mailbox, remaining messages have their
  # sequence numbers "shuffled down" to fill the gaps.
  #
  # UIDs, on the other hand, are permanently guaranteed not to
  # identify another message within the same mailbox, even if
  # the existing message is deleted.  UIDs are required to
  # be assigned in ascending (but not necessarily sequential)
  # order within a mailbox; this means that if a non-IMAP client
  # rearranges the order of mailitems within a mailbox, the
  # UIDs have to be reassigned.  An IMAP client thus cannot
  # rearrange message orders.
  #
  # == Examples of Usage
  #
  # === List sender and subject of all recent messages in the default mailbox
  #
  #   imap = Net::IMAP.new('mail.example.com')
  #   imap.authenticate('LOGIN', 'joe_user', 'joes_password')
  #   imap.examine('INBOX')
  #   imap.search(["RECENT"]).each do |message_id|
  #     envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
  #     puts "#{envelope.from[0].name}: \t#{envelope.subject}"
  #   end
  #
  # === Move all messages from April 2003 from "Mail/sent-mail" to "Mail/sent-apr03"
  #
  #   imap = Net::IMAP.new('mail.example.com')
  #   imap.authenticate('LOGIN', 'joe_user', 'joes_password')
  #   imap.select('Mail/sent-mail')
  #   if not imap.list('Mail/', 'sent-apr03')
  #     imap.create('Mail/sent-apr03')
  #   end
  #   imap.search(["BEFORE", "30-Apr-2003", "SINCE", "1-Apr-2003"]).each do |message_id|
  #     imap.copy(message_id, "Mail/sent-apr03")
  #     imap.store(message_id, "+FLAGS", [:Deleted])
  #   end
  #   imap.expunge
  #
  # == Thread Safety
  #
  # Net::IMAP supports concurrent threads. For example,
  #
  #   imap = Net::IMAP.new("imap.foo.net", "imap2")
  #   imap.authenticate("cram-md5", "bar", "password")
  #   imap.select("inbox")
  #   fetch_thread = Thread.start { imap.fetch(1..-1, "UID") }
  #   search_result = imap.search(["BODY", "hello"])
  #   fetch_result = fetch_thread.value
  #   imap.disconnect
  #
  # This script invokes the FETCH command and the SEARCH command concurrently.
  #
  # == Errors
  #
  # An IMAP server can send three different types of responses to indicate
  # failure:
  #
  # NO:: the attempted command could not be successfully completed.  For
  #      instance, the username/password used for logging in are incorrect;
  #      the selected mailbox does not exist; etc.
  #
  # BAD:: the request from the client does not follow the server's
  #       understanding of the IMAP protocol.  This includes attempting
  #       commands from the wrong client state; for instance, attempting
  #       to perform a SEARCH command without having SELECTed a current
  #       mailbox.  It can also signal an internal server
  #       failure (such as a disk crash) has occurred.
  #
  # BYE:: the server is saying goodbye.  This can be part of a normal
  #       logout sequence, and can be used as part of a login sequence
  #       to indicate that the server is (for some reason) unwilling
  #       to accept your connection.  As a response to any other command,
  #       it indicates either that the server is shutting down, or that
  #       the server is timing out the client connection due to inactivity.
  #
  # These three error response are represented by the errors
  # Net::IMAP::NoResponseError, Net::IMAP::BadResponseError, and
  # Net::IMAP::ByeResponseError, all of which are subclasses of
  # Net::IMAP::ResponseError.  Essentially, all methods that involve
  # sending a request to the server can generate one of these errors.
  # Only the most pertinent instances have been documented below.
  #
  # Because the IMAP class uses Sockets for communication, its methods
  # are also susceptible to the various errors that can occur when
  # working with sockets.  These are generally represented as
  # Errno errors.  For instance, any method that involves sending a
  # request to the server and/or receiving a response from it could
  # raise an Errno::EPIPE error if the network connection unexpectedly
  # goes down.  See the socket(7), ip(7), tcp(7), socket(2), connect(2),
  # and associated man pages.
  #
  # Finally, a Net::IMAP::DataFormatError is thrown if low-level data
  # is found to be in an incorrect format (for instance, when converting
  # between UTF-8 and UTF-16), and Net::IMAP::ResponseParseError is
  # thrown if a server response is non-parseable.
  #
  #
  # == References
  #
  # [[IMAP]]
  #    M. Crispin, "INTERNET MESSAGE ACCESS PROTOCOL - VERSION 4rev1",
  #    RFC 2060, December 1996.  (Note: since obsoleted by RFC 3501)
  #
  # [[LANGUAGE-TAGS]]
  #    Alvestrand, H., "Tags for the Identification of
  #    Languages", RFC 1766, March 1995.
  #
  # [[MD5]]
  #    Myers, J., and M. Rose, "The Content-MD5 Header Field", RFC
  #    1864, October 1995.
  #
  # [[MIME-IMB]]
  #    Freed, N., and N. Borenstein, "MIME (Multipurpose Internet
  #    Mail Extensions) Part One: Format of Internet Message Bodies", RFC
  #    2045, November 1996.
  #
  # [[RFC-822]]
  #    Crocker, D., "Standard for the Format of ARPA Internet Text
  #    Messages", STD 11, RFC 822, University of Delaware, August 1982.
  #
  # [[RFC-2087]]
  #    Myers, J., "IMAP4 QUOTA extension", RFC 2087, January 1997.
  #
  # [[RFC-2086]]
  #    Myers, J., "IMAP4 ACL extension", RFC 2086, January 1997.
  #
  # [[RFC-2195]]
  #    Klensin, J., Catoe, R., and Krumviede, P., "IMAP/POP AUTHorize Extension
  #    for Simple Challenge/Response", RFC 2195, September 1997.
  #
  # [[SORT-THREAD-EXT]]
  #    Crispin, M., "INTERNET MESSAGE ACCESS PROTOCOL - SORT and THREAD
  #    Extensions", draft-ietf-imapext-sort, May 2003.
  #
  # [[OSSL]]
  #    http://www.openssl.org
  #
  # [[RSSL]]
  #    http://savannah.gnu.org/projects/rubypki
  #
  # [[UTF7]]
  #    Goldsmith, D. and Davis, M., "UTF-7: A Mail-Safe Transformation Format of
  #    Unicode", RFC 2152, May 1997.
  #
  class IMAP < Protocol
    VERSION = "0.1.1"

    include MonitorMixin
    if defined?(OpenSSL::SSL)
      include OpenSSL
      include SSL
    end

    #  Returns an initial greeting response from the server.
    attr_reader :greeting

    # Returns recorded untagged responses.  For example:
    #
    #   imap.select("inbox")
    #   p imap.responses["EXISTS"][-1]
    #   #=> 2
    #   p imap.responses["UIDVALIDITY"][-1]
    #   #=> 968263756
    attr_reader :responses

    # Returns all response handlers.
    attr_reader :response_handlers

    # Seconds to wait until a connection is opened.
    # If the IMAP object cannot open a connection within this time,
    # it raises a Net::OpenTimeout exception. The default value is 30 seconds.
    attr_reader :open_timeout

    # The thread to receive exceptions.
    attr_accessor :client_thread

    # Flag indicating a message has been seen.
    SEEN = :Seen

    # Flag indicating a message has been answered.
    ANSWERED = :Answered

    # Flag indicating a message has been flagged for special or urgent
    # attention.
    FLAGGED = :Flagged

    # Flag indicating a message has been marked for deletion.  This
    # will occur when the mailbox is closed or expunged.
    DELETED = :Deleted

    # Flag indicating a message is only a draft or work-in-progress version.
    DRAFT = :Draft

    # Flag indicating that the message is "recent," meaning that this
    # session is the first session in which the client has been notified
    # of this message.
    RECENT = :Recent

    # Flag indicating that a mailbox context name cannot contain
    # children.
    NOINFERIORS = :Noinferiors

    # Flag indicating that a mailbox is not selected.
    NOSELECT = :Noselect

    # Flag indicating that a mailbox has been marked "interesting" by
    # the server; this commonly indicates that the mailbox contains
    # new messages.
    MARKED = :Marked

    # Flag indicating that the mailbox does not contains new messages.
    UNMARKED = :Unmarked

    # Returns the debug mode.
    def self.debug
      return @@debug
    end

    # Sets the debug mode.
    def self.debug=(val)
      return @@debug = val
    end

    # Returns the max number of flags interned to symbols.
    def self.max_flag_count
      return @@max_flag_count
    end

    # Sets the max number of flags interned to symbols.
    def self.max_flag_count=(count)
      @@max_flag_count = count
    end

    # Adds an authenticator for Net::IMAP#authenticate.  +auth_type+
    # is the type of authentication this authenticator supports
    # (for instance, "LOGIN").  The +authenticator+ is an object
    # which defines a process() method to handle authentication with
    # the server.  See Net::IMAP::LoginAuthenticator,
    # Net::IMAP::CramMD5Authenticator, and Net::IMAP::DigestMD5Authenticator
    # for examples.
    #
    #
    # If +auth_type+ refers to an existing authenticator, it will be
    # replaced by the new one.
    def self.add_authenticator(auth_type, authenticator)
      @@authenticators[auth_type] = authenticator
    end

    # The default port for IMAP connections, port 143
    def self.default_port
      return PORT
    end

    # The default port for IMAPS connections, port 993
    def self.default_tls_port
      return SSL_PORT
    end

    class << self
      alias default_imap_port default_port
      alias default_imaps_port default_tls_port
      alias default_ssl_port default_tls_port
    end

    # Disconnects from the server.
    def disconnect
      return if disconnected?
      begin
        begin
          # try to call SSL::SSLSocket#io.
          @sock.io.shutdown
        rescue NoMethodError
          # @sock is not an SSL::SSLSocket.
          @sock.shutdown
        end
      rescue Errno::ENOTCONN
        # ignore `Errno::ENOTCONN: Socket is not connected' on some platforms.
      rescue Exception => e
        @receiver_thread.raise(e)
      end
      @receiver_thread.join
      synchronize do
        @sock.close
      end
      raise e if e
    end

    # Returns true if disconnected from the server.
    def disconnected?
      return @sock.closed?
    end

    # Sends a CAPABILITY command, and returns an array of
    # capabilities that the server supports.  Each capability
    # is a string.  See [IMAP] for a list of possible
    # capabilities.
    #
    # Note that the Net::IMAP class does not modify its
    # behaviour according to the capabilities of the server;
    # it is up to the user of the class to ensure that
    # a certain capability is supported by a server before
    # using it.
    def capability
      synchronize do
        send_command("CAPABILITY")
        return @responses.delete("CAPABILITY")[-1]
      end
    end

    # Sends a NOOP command to the server. It does nothing.
    def noop
      send_command("NOOP")
    end

    # Sends a LOGOUT command to inform the server that the client is
    # done with the connection.
    def logout
      send_command("LOGOUT")
    end

    # Sends a STARTTLS command to start TLS session.
    def starttls(options = {}, verify = true)
      send_command("STARTTLS") do |resp|
        if resp.kind_of?(TaggedResponse) && resp.name == "OK"
          begin
            # for backward compatibility
            certs = options.to_str
            options = create_ssl_params(certs, verify)
          rescue NoMethodError
          end
          start_tls_session(options)
        end
      end
    end

    # Sends an AUTHENTICATE command to authenticate the client.
    # The +auth_type+ parameter is a string that represents
    # the authentication mechanism to be used. Currently Net::IMAP
    # supports the authentication mechanisms:
    #
    #   LOGIN:: login using cleartext user and password.
    #   CRAM-MD5:: login with cleartext user and encrypted password
    #              (see [RFC-2195] for a full description).  This
    #              mechanism requires that the server have the user's
    #              password stored in clear-text password.
    #
    # For both of these mechanisms, there should be two +args+: username
    # and (cleartext) password.  A server may not support one or the other
    # of these mechanisms; check #capability() for a capability of
    # the form "AUTH=LOGIN" or "AUTH=CRAM-MD5".
    #
    # Authentication is done using the appropriate authenticator object:
    # see @@authenticators for more information on plugging in your own
    # authenticator.
    #
    # For example:
    #
    #    imap.authenticate('LOGIN', user, password)
    #
    # A Net::IMAP::NoResponseError is raised if authentication fails.
    def authenticate(auth_type, *args)
      auth_type = auth_type.upcase
      unless @@authenticators.has_key?(auth_type)
        raise ArgumentError,
          format('unknown auth type - "%s"', auth_type)
      end
      authenticator = @@authenticators[auth_type].new(*args)
      send_command("AUTHENTICATE", auth_type) do |resp|
        if resp.instance_of?(ContinuationRequest)
          data = authenticator.process(resp.data.text.unpack("m")[0])
          s = [data].pack("m0")
          send_string_data(s)
          put_string(CRLF)
        end
      end
    end

    # Sends a LOGIN command to identify the client and carries
    # the plaintext +password+ authenticating this +user+.  Note
    # that, unlike calling #authenticate() with an +auth_type+
    # of "LOGIN", #login() does *not* use the login authenticator.
    #
    # A Net::IMAP::NoResponseError is raised if authentication fails.
    def login(user, password)
      send_command("LOGIN", user, password)
    end

    # Sends a SELECT command to select a +mailbox+ so that messages
    # in the +mailbox+ can be accessed.
    #
    # After you have selected a mailbox, you may retrieve the
    # number of items in that mailbox from @responses["EXISTS"][-1],
    # and the number of recent messages from @responses["RECENT"][-1].
    # Note that these values can change if new messages arrive
    # during a session; see #add_response_handler() for a way of
    # detecting this event.
    #
    # A Net::IMAP::NoResponseError is raised if the mailbox does not
    # exist or is for some reason non-selectable.
    def select(mailbox)
      synchronize do
        @responses.clear
        send_command("SELECT", mailbox)
      end
    end

    # Sends a EXAMINE command to select a +mailbox+ so that messages
    # in the +mailbox+ can be accessed.  Behaves the same as #select(),
    # except that the selected +mailbox+ is identified as read-only.
    #
    # A Net::IMAP::NoResponseError is raised if the mailbox does not
    # exist or is for some reason non-examinable.
    def examine(mailbox)
      synchronize do
        @responses.clear
        send_command("EXAMINE", mailbox)
      end
    end

    # Sends a CREATE command to create a new +mailbox+.
    #
    # A Net::IMAP::NoResponseError is raised if a mailbox with that name
    # cannot be created.
    def create(mailbox)
      send_command("CREATE", mailbox)
    end

    # Sends a DELETE command to remove the +mailbox+.
    #
    # A Net::IMAP::NoResponseError is raised if a mailbox with that name
    # cannot be deleted, either because it does not exist or because the
    # client does not have permission to delete it.
    def delete(mailbox)
      send_command("DELETE", mailbox)
    end

    # Sends a RENAME command to change the name of the +mailbox+ to
    # +newname+.
    #
    # A Net::IMAP::NoResponseError is raised if a mailbox with the
    # name +mailbox+ cannot be renamed to +newname+ for whatever
    # reason; for instance, because +mailbox+ does not exist, or
    # because there is already a mailbox with the name +newname+.
    def rename(mailbox, newname)
      send_command("RENAME", mailbox, newname)
    end

    # Sends a SUBSCRIBE command to add the specified +mailbox+ name to
    # the server's set of "active" or "subscribed" mailboxes as returned
    # by #lsub().
    #
    # A Net::IMAP::NoResponseError is raised if +mailbox+ cannot be
    # subscribed to; for instance, because it does not exist.
    def subscribe(mailbox)
      send_command("SUBSCRIBE", mailbox)
    end

    # Sends a UNSUBSCRIBE command to remove the specified +mailbox+ name
    # from the server's set of "active" or "subscribed" mailboxes.
    #
    # A Net::IMAP::NoResponseError is raised if +mailbox+ cannot be
    # unsubscribed from; for instance, because the client is not currently
    # subscribed to it.
    def unsubscribe(mailbox)
      send_command("UNSUBSCRIBE", mailbox)
    end

    # Sends a LIST command, and returns a subset of names from
    # the complete set of all names available to the client.
    # +refname+ provides a context (for instance, a base directory
    # in a directory-based mailbox hierarchy).  +mailbox+ specifies
    # a mailbox or (via wildcards) mailboxes under that context.
    # Two wildcards may be used in +mailbox+: '*', which matches
    # all characters *including* the hierarchy delimiter (for instance,
    # '/' on a UNIX-hosted directory-based mailbox hierarchy); and '%',
    # which matches all characters *except* the hierarchy delimiter.
    #
    # If +refname+ is empty, +mailbox+ is used directly to determine
    # which mailboxes to match.  If +mailbox+ is empty, the root
    # name of +refname+ and the hierarchy delimiter are returned.
    #
    # The return value is an array of +Net::IMAP::MailboxList+. For example:
    #
    #   imap.create("foo/bar")
    #   imap.create("foo/baz")
    #   p imap.list("", "foo/%")
    #   #=> [#<Net::IMAP::MailboxList attr=[:Noselect], delim="/", name="foo/">, \\
    #        #<Net::IMAP::MailboxList attr=[:Noinferiors, :Marked], delim="/", name="foo/bar">, \\
    #        #<Net::IMAP::MailboxList attr=[:Noinferiors], delim="/", name="foo/baz">]
    def list(refname, mailbox)
      synchronize do
        send_command("LIST", refname, mailbox)
        return @responses.delete("LIST")
      end
    end

    # Sends a XLIST command, and returns a subset of names from
    # the complete set of all names available to the client.
    # +refname+ provides a context (for instance, a base directory
    # in a directory-based mailbox hierarchy).  +mailbox+ specifies
    # a mailbox or (via wildcards) mailboxes under that context.
    # Two wildcards may be used in +mailbox+: '*', which matches
    # all characters *including* the hierarchy delimiter (for instance,
    # '/' on a UNIX-hosted directory-based mailbox hierarchy); and '%',
    # which matches all characters *except* the hierarchy delimiter.
    #
    # If +refname+ is empty, +mailbox+ is used directly to determine
    # which mailboxes to match.  If +mailbox+ is empty, the root
    # name of +refname+ and the hierarchy delimiter are returned.
    #
    # The XLIST command is like the LIST command except that the flags
    # returned refer to the function of the folder/mailbox, e.g. :Sent
    #
    # The return value is an array of +Net::IMAP::MailboxList+. For example:
    #
    #   imap.create("foo/bar")
    #   imap.create("foo/baz")
    #   p imap.xlist("", "foo/%")
    #   #=> [#<Net::IMAP::MailboxList attr=[:Noselect], delim="/", name="foo/">, \\
    #        #<Net::IMAP::MailboxList attr=[:Noinferiors, :Marked], delim="/", name="foo/bar">, \\
    #        #<Net::IMAP::MailboxList attr=[:Noinferiors], delim="/", name="foo/baz">]
    def xlist(refname, mailbox)
      synchronize do
        send_command("XLIST", refname, mailbox)
        return @responses.delete("XLIST")
      end
    end

    # Sends the GETQUOTAROOT command along with the specified +mailbox+.
    # This command is generally available to both admin and user.
    # If this mailbox exists, it returns an array containing objects of type
    # Net::IMAP::MailboxQuotaRoot and Net::IMAP::MailboxQuota.
    def getquotaroot(mailbox)
      synchronize do
        send_command("GETQUOTAROOT", mailbox)
        result = []
        result.concat(@responses.delete("QUOTAROOT"))
        result.concat(@responses.delete("QUOTA"))
        return result
      end
    end

    # Sends the GETQUOTA command along with specified +mailbox+.
    # If this mailbox exists, then an array containing a
    # Net::IMAP::MailboxQuota object is returned.  This
    # command is generally only available to server admin.
    def getquota(mailbox)
      synchronize do
        send_command("GETQUOTA", mailbox)
        return @responses.delete("QUOTA")
      end
    end

    # Sends a SETQUOTA command along with the specified +mailbox+ and
    # +quota+.  If +quota+ is nil, then +quota+ will be unset for that
    # mailbox.  Typically one needs to be logged in as a server admin
    # for this to work.  The IMAP quota commands are described in
    # [RFC-2087].
    def setquota(mailbox, quota)
      if quota.nil?
        data = '()'
      else
        data = '(STORAGE ' + quota.to_s + ')'
      end
      send_command("SETQUOTA", mailbox, RawData.new(data))
    end

    # Sends the SETACL command along with +mailbox+, +user+ and the
    # +rights+ that user is to have on that mailbox.  If +rights+ is nil,
    # then that user will be stripped of any rights to that mailbox.
    # The IMAP ACL commands are described in [RFC-2086].
    def setacl(mailbox, user, rights)
      if rights.nil?
        send_command("SETACL", mailbox, user, "")
      else
        send_command("SETACL", mailbox, user, rights)
      end
    end

    # Send the GETACL command along with a specified +mailbox+.
    # If this mailbox exists, an array containing objects of
    # Net::IMAP::MailboxACLItem will be returned.
    def getacl(mailbox)
      synchronize do
        send_command("GETACL", mailbox)
        return @responses.delete("ACL")[-1]
      end
    end

    # Sends a LSUB command, and returns a subset of names from the set
    # of names that the user has declared as being "active" or
    # "subscribed."  +refname+ and +mailbox+ are interpreted as
    # for #list().
    # The return value is an array of +Net::IMAP::MailboxList+.
    def lsub(refname, mailbox)
      synchronize do
        send_command("LSUB", refname, mailbox)
        return @responses.delete("LSUB")
      end
    end

    # Sends a STATUS command, and returns the status of the indicated
    # +mailbox+. +attr+ is a list of one or more attributes whose
    # statuses are to be requested.  Supported attributes include:
    #
    #   MESSAGES:: the number of messages in the mailbox.
    #   RECENT:: the number of recent messages in the mailbox.
    #   UNSEEN:: the number of unseen messages in the mailbox.
    #
    # The return value is a hash of attributes. For example:
    #
    #   p imap.status("inbox", ["MESSAGES", "RECENT"])
    #   #=> {"RECENT"=>0, "MESSAGES"=>44}
    #
    # A Net::IMAP::NoResponseError is raised if status values
    # for +mailbox+ cannot be returned; for instance, because it
    # does not exist.
    def status(mailbox, attr)
      synchronize do
        send_command("STATUS", mailbox, attr)
        return @responses.delete("STATUS")[-1].attr
      end
    end

    # Sends a APPEND command to append the +message+ to the end of
    # the +mailbox+. The optional +flags+ argument is an array of
    # flags initially passed to the new message.  The optional
    # +date_time+ argument specifies the creation time to assign to the
    # new message; it defaults to the current time.
    # For example:
    #
    #   imap.append("inbox", <<EOF.gsub(/\n/, "\r\n"), [:Seen], Time.now)
    #   Subject: hello
    #   From: shugo@ruby-lang.org
    #   To: shugo@ruby-lang.org
    #
    #   hello world
    #   EOF
    #
    # A Net::IMAP::NoResponseError is raised if the mailbox does
    # not exist (it is not created automatically), or if the flags,
    # date_time, or message arguments contain errors.
    def append(mailbox, message, flags = nil, date_time = nil)
      args = []
      if flags
        args.push(flags)
      end
      args.push(date_time) if date_time
      args.push(Literal.new(message))
      send_command("APPEND", mailbox, *args)
    end

    # Sends a CHECK command to request a checkpoint of the currently
    # selected mailbox.  This performs implementation-specific
    # housekeeping; for instance, reconciling the mailbox's
    # in-memory and on-disk state.
    def check
      send_command("CHECK")
    end

    # Sends a CLOSE command to close the currently selected mailbox.
    # The CLOSE command permanently removes from the mailbox all
    # messages that have the \Deleted flag set.
    def close
      send_command("CLOSE")
    end

    # Sends a EXPUNGE command to permanently remove from the currently
    # selected mailbox all messages that have the \Deleted flag set.
    def expunge
      synchronize do
        send_command("EXPUNGE")
        return @responses.delete("EXPUNGE")
      end
    end

    # Sends a SEARCH command to search the mailbox for messages that
    # match the given searching criteria, and returns message sequence
    # numbers.  +keys+ can either be a string holding the entire
    # search string, or a single-dimension array of search keywords and
    # arguments.  The following are some common search criteria;
    # see [IMAP] section 6.4.4 for a full list.
    #
    # <message set>:: a set of message sequence numbers.  ',' indicates
    #                 an interval, ':' indicates a range.  For instance,
    #                 '2,10:12,15' means "2,10,11,12,15".
    #
    # BEFORE <date>:: messages with an internal date strictly before
    #                 <date>.  The date argument has a format similar
    #                 to 8-Aug-2002.
    #
    # BODY <string>:: messages that contain <string> within their body.
    #
    # CC <string>:: messages containing <string> in their CC field.
    #
    # FROM <string>:: messages that contain <string> in their FROM field.
    #
    # NEW:: messages with the \Recent, but not the \Seen, flag set.
    #
    # NOT <search-key>:: negate the following search key.
    #
    # OR <search-key> <search-key>:: "or" two search keys together.
    #
    # ON <date>:: messages with an internal date exactly equal to <date>,
    #             which has a format similar to 8-Aug-2002.
    #
    # SINCE <date>:: messages with an internal date on or after <date>.
    #
    # SUBJECT <string>:: messages with <string> in their subject.
    #
    # TO <string>:: messages with <string> in their TO field.
    #
    # For example:
    #
    #   p imap.search(["SUBJECT", "hello", "NOT", "NEW"])
    #   #=> [1, 6, 7, 8]
    def search(keys, charset = nil)
      return search_internal("SEARCH", keys, charset)
    end

    # Similar to #search(), but returns unique identifiers.
    def uid_search(keys, charset = nil)
      return search_internal("UID SEARCH", keys, charset)
    end

    # Sends a FETCH command to retrieve data associated with a message
    # in the mailbox.
    #
    # The +set+ parameter is a number or a range between two numbers,
    # or an array of those.  The number is a message sequence number,
    # where -1 represents a '*' for use in range notation like 100..-1
    # being interpreted as '100:*'.  Beware that the +exclude_end?+
    # property of a Range object is ignored, and the contents of a
    # range are independent of the order of the range endpoints as per
    # the protocol specification, so 1...5, 5..1 and 5...1 are all
    # equivalent to 1..5.
    #
    # +attr+ is a list of attributes to fetch; see the documentation
    # for Net::IMAP::FetchData for a list of valid attributes.
    #
    # The return value is an array of Net::IMAP::FetchData or nil
    # (instead of an empty array) if there is no matching message.
    #
    # For example:
    #
    #   p imap.fetch(6..8, "UID")
    #   #=> [#<Net::IMAP::FetchData seqno=6, attr={"UID"=>98}>, \\
    #        #<Net::IMAP::FetchData seqno=7, attr={"UID"=>99}>, \\
    #        #<Net::IMAP::FetchData seqno=8, attr={"UID"=>100}>]
    #   p imap.fetch(6, "BODY[HEADER.FIELDS (SUBJECT)]")
    #   #=> [#<Net::IMAP::FetchData seqno=6, attr={"BODY[HEADER.FIELDS (SUBJECT)]"=>"Subject: test\r\n\r\n"}>]
    #   data = imap.uid_fetch(98, ["RFC822.SIZE", "INTERNALDATE"])[0]
    #   p data.seqno
    #   #=> 6
    #   p data.attr["RFC822.SIZE"]
    #   #=> 611
    #   p data.attr["INTERNALDATE"]
    #   #=> "12-Oct-2000 22:40:59 +0900"
    #   p data.attr["UID"]
    #   #=> 98
    def fetch(set, attr, mod = nil)
      return fetch_internal("FETCH", set, attr, mod)
    end

    # Similar to #fetch(), but +set+ contains unique identifiers.
    def uid_fetch(set, attr, mod = nil)
      return fetch_internal("UID FETCH", set, attr, mod)
    end

    # Sends a STORE command to alter data associated with messages
    # in the mailbox, in particular their flags. The +set+ parameter
    # is a number, an array of numbers, or a Range object. Each number
    # is a message sequence number.  +attr+ is the name of a data item
    # to store: 'FLAGS' will replace the message's flag list
    # with the provided one, '+FLAGS' will add the provided flags,
    # and '-FLAGS' will remove them.  +flags+ is a list of flags.
    #
    # The return value is an array of Net::IMAP::FetchData. For example:
    #
    #   p imap.store(6..8, "+FLAGS", [:Deleted])
    #   #=> [#<Net::IMAP::FetchData seqno=6, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\
    #        #<Net::IMAP::FetchData seqno=7, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\
    #        #<Net::IMAP::FetchData seqno=8, attr={"FLAGS"=>[:Seen, :Deleted]}>]
    def store(set, attr, flags)
      return store_internal("STORE", set, attr, flags)
    end

    # Similar to #store(), but +set+ contains unique identifiers.
    def uid_store(set, attr, flags)
      return store_internal("UID STORE", set, attr, flags)
    end

    # Sends a COPY command to copy the specified message(s) to the end
    # of the specified destination +mailbox+. The +set+ parameter is
    # a number, an array of numbers, or a Range object. The number is
    # a message sequence number.
    def copy(set, mailbox)
      copy_internal("COPY", set, mailbox)
    end

    # Similar to #copy(), but +set+ contains unique identifiers.
    def uid_copy(set, mailbox)
      copy_internal("UID COPY", set, mailbox)
    end

    # Sends a MOVE command to move the specified message(s) to the end
    # of the specified destination +mailbox+. The +set+ parameter is
    # a number, an array of numbers, or a Range object. The number is
    # a message sequence number.
    # The IMAP MOVE extension is described in [RFC-6851].
    def move(set, mailbox)
      copy_internal("MOVE", set, mailbox)
    end

    # Similar to #move(), but +set+ contains unique identifiers.
    def uid_move(set, mailbox)
      copy_internal("UID MOVE", set, mailbox)
    end

    # Sends a SORT command to sort messages in the mailbox.
    # Returns an array of message sequence numbers. For example:
    #
    #   p imap.sort(["FROM"], ["ALL"], "US-ASCII")
    #   #=> [1, 2, 3, 5, 6, 7, 8, 4, 9]
    #   p imap.sort(["DATE"], ["SUBJECT", "hello"], "US-ASCII")
    #   #=> [6, 7, 8, 1]
    #
    # See [SORT-THREAD-EXT] for more details.
    def sort(sort_keys, search_keys, charset)
      return sort_internal("SORT", sort_keys, search_keys, charset)
    end

    # Similar to #sort(), but returns an array of unique identifiers.
    def uid_sort(sort_keys, search_keys, charset)
      return sort_internal("UID SORT", sort_keys, search_keys, charset)
    end

    # Adds a response handler. For example, to detect when
    # the server sends a new EXISTS response (which normally
    # indicates new messages being added to the mailbox),
    # add the following handler after selecting the
    # mailbox:
    #
    #   imap.add_response_handler { |resp|
    #     if resp.kind_of?(Net::IMAP::UntaggedResponse) and resp.name == "EXISTS"
    #       puts "Mailbox now has #{resp.data} messages"
    #     end
    #   }
    #
    def add_response_handler(handler = nil, &block)
      raise ArgumentError, "two Procs are passed" if handler && block
      @response_handlers.push(block || handler)
    end

    # Removes the response handler.
    def remove_response_handler(handler)
      @response_handlers.delete(handler)
    end

    # Similar to #search(), but returns message sequence numbers in threaded
    # format, as a Net::IMAP::ThreadMember tree.  The supported algorithms
    # are:
    #
    # ORDEREDSUBJECT:: split into single-level threads according to subject,
    #                  ordered by date.
    # REFERENCES:: split into threads by parent/child relationships determined
    #              by which message is a reply to which.
    #
    # Unlike #search(), +charset+ is a required argument.  US-ASCII
    # and UTF-8 are sample values.
    #
    # See [SORT-THREAD-EXT] for more details.
    def thread(algorithm, search_keys, charset)
      return thread_internal("THREAD", algorithm, search_keys, charset)
    end

    # Similar to #thread(), but returns unique identifiers instead of
    # message sequence numbers.
    def uid_thread(algorithm, search_keys, charset)
      return thread_internal("UID THREAD", algorithm, search_keys, charset)
    end

    # Sends an IDLE command that waits for notifications of new or expunged
    # messages.  Yields responses from the server during the IDLE.
    #
    # Use #idle_done() to leave IDLE.
    #
    # If +timeout+ is given, this method returns after +timeout+ seconds passed.
    # +timeout+ can be used for keep-alive.  For example, the following code
    # checks the connection for each 60 seconds.
    #
    #   loop do
    #     imap.idle(60) do |res|
    #       ...
    #     end
    #   end
    def idle(timeout = nil, &response_handler)
      raise LocalJumpError, "no block given" unless response_handler

      response = nil

      synchronize do
        tag = Thread.current[:net_imap_tag] = generate_tag
        put_string("#{tag} IDLE#{CRLF}")

        begin
          add_response_handler(&response_handler)
          @idle_done_cond = new_cond
          @idle_done_cond.wait(timeout)
          @idle_done_cond = nil
          if @receiver_thread_terminating
            raise @exception || Net::IMAP::Error.new("connection closed")
          end
        ensure
          unless @receiver_thread_terminating
            remove_response_handler(response_handler)
            put_string("DONE#{CRLF}")
            response = get_tagged_response(tag, "IDLE")
          end
        end
      end

      return response
    end

    # Leaves IDLE.
    def idle_done
      synchronize do
        if @idle_done_cond.nil?
          raise Net::IMAP::Error, "not during IDLE"
        end
        @idle_done_cond.signal
      end
    end

    # Decode a string from modified UTF-7 format to UTF-8.
    #
    # UTF-7 is a 7-bit encoding of Unicode [UTF7].  IMAP uses a
    # slightly modified version of this to encode mailbox names
    # containing non-ASCII characters; see [IMAP] section 5.1.3.
    #
    # Net::IMAP does _not_ automatically encode and decode
    # mailbox names to and from UTF-7.
    def self.decode_utf7(s)
      return s.gsub(/&([^-]+)?-/n) {
        if $1
          ($1.tr(",", "/") + "===").unpack1("m").encode(Encoding::UTF_8, Encoding::UTF_16BE)
        else
          "&"
        end
      }
    end

    # Encode a string from UTF-8 format to modified UTF-7.
    def self.encode_utf7(s)
      return s.gsub(/(&)|[^\x20-\x7e]+/) {
        if $1
          "&-"
        else
          base64 = [$&.encode(Encoding::UTF_16BE)].pack("m0")
          "&" + base64.delete("=").tr("/", ",") + "-"
        end
      }.force_encoding("ASCII-8BIT")
    end

    # Formats +time+ as an IMAP-style date.
    def self.format_date(time)
      return time.strftime('%d-%b-%Y')
    end

    # Formats +time+ as an IMAP-style date-time.
    def self.format_datetime(time)
      return time.strftime('%d-%b-%Y %H:%M %z')
    end

    private

    CRLF = "\r\n"      # :nodoc:
    PORT = 143         # :nodoc:
    SSL_PORT = 993   # :nodoc:

    @@debug = false
    @@authenticators = {}
    @@max_flag_count = 10000

    # :call-seq:
    #    Net::IMAP.new(host, options = {})
    #
    # Creates a new Net::IMAP object and connects it to the specified
    # +host+.
    #
    # +options+ is an option hash, each key of which is a symbol.
    #
    # The available options are:
    #
    # port::  Port number (default value is 143 for imap, or 993 for imaps)
    # ssl::   If options[:ssl] is true, then an attempt will be made
    #         to use SSL (now TLS) to connect to the server.  For this to work
    #         OpenSSL [OSSL] and the Ruby OpenSSL [RSSL] extensions need to
    #         be installed.
    #         If options[:ssl] is a hash, it's passed to
    #         OpenSSL::SSL::SSLContext#set_params as parameters.
    # open_timeout:: Seconds to wait until a connection is opened
    #
    # The most common errors are:
    #
    # Errno::ECONNREFUSED:: Connection refused by +host+ or an intervening
    #                       firewall.
    # Errno::ETIMEDOUT:: Connection timed out (possibly due to packets
    #                    being dropped by an intervening firewall).
    # Errno::ENETUNREACH:: There is no route to that network.
    # SocketError:: Hostname not known or other socket error.
    # Net::IMAP::ByeResponseError:: The connected to the host was successful, but
    #                               it immediately said goodbye.
    def initialize(host, port_or_options = {},
                   usessl = false, certs = nil, verify = true)
      super()
      @host = host
      begin
        options = port_or_options.to_hash
      rescue NoMethodError
        # for backward compatibility
        options = {}
        options[:port] = port_or_options
        if usessl
          options[:ssl] = create_ssl_params(certs, verify)
        end
      end
      @port = options[:port] || (options[:ssl] ? SSL_PORT : PORT)
      @tag_prefix = "RUBY"
      @tagno = 0
      @open_timeout = options[:open_timeout] || 30
      @parser = ResponseParser.new
      @sock = tcp_socket(@host, @port)
      begin
        if options[:ssl]
          start_tls_session(options[:ssl])
          @usessl = true
        else
          @usessl = false
        end
        @responses = Hash.new([].freeze)
        @tagged_responses = {}
        @response_handlers = []
        @tagged_response_arrival = new_cond
        @continued_command_tag = nil
        @continuation_request_arrival = new_cond
        @continuation_request_exception = nil
        @idle_done_cond = nil
        @logout_command_tag = nil
        @debug_output_bol = true
        @exception = nil

        @greeting = get_response
        if @greeting.nil?
          raise Error, "connection closed"
        end
        if @greeting.name == "BYE"
          raise ByeResponseError, @greeting
        end

        @client_thread = Thread.current
        @receiver_thread = Thread.start {
          begin
            receive_responses
          rescue Exception
          end
        }
        @receiver_thread_terminating = false
      rescue Exception
        @sock.close
        raise
      end
    end

    def tcp_socket(host, port)
      s = Socket.tcp(host, port, :connect_timeout => @open_timeout)
      s.setsockopt(:SOL_SOCKET, :SO_KEEPALIVE, true)
      s
    rescue Errno::ETIMEDOUT
      raise Net::OpenTimeout, "Timeout to open TCP connection to " +
        "#{host}:#{port} (exceeds #{@open_timeout} seconds)"
    end

    def receive_responses
      connection_closed = false
      until connection_closed
        synchronize do
          @exception = nil
        end
        begin
          resp = get_response
        rescue Exception => e
          synchronize do
            @sock.close
            @exception = e
          end
          break
        end
        unless resp
          synchronize do
            @exception = EOFError.new("end of file reached")
          end
          break
        end
        begin
          synchronize do
            case resp
            when TaggedResponse
              @tagged_responses[resp.tag] = resp
              @tagged_response_arrival.broadcast
              case resp.tag
              when @logout_command_tag
                return
              when @continued_command_tag
                @continuation_request_exception =
                  RESPONSE_ERRORS[resp.name].new(resp)
                @continuation_request_arrival.signal
              end
            when UntaggedResponse
              record_response(resp.name, resp.data)
              if resp.data.instance_of?(ResponseText) &&
                  (code = resp.data.code)
                record_response(code.name, code.data)
              end
              if resp.name == "BYE" && @logout_command_tag.nil?
                @sock.close
                @exception = ByeResponseError.new(resp)
                connection_closed = true
              end
            when ContinuationRequest
              @continuation_request_arrival.signal
            end
            @response_handlers.each do |handler|
              handler.call(resp)
            end
          end
        rescue Exception => e
          @exception = e
          synchronize do
            @tagged_response_arrival.broadcast
            @continuation_request_arrival.broadcast
          end
        end
      end
      synchronize do
        @receiver_thread_terminating = true
        @tagged_response_arrival.broadcast
        @continuation_request_arrival.broadcast
        if @idle_done_cond
          @idle_done_cond.signal
        end
      end
    end

    def get_tagged_response(tag, cmd)
      until @tagged_responses.key?(tag)
        raise @exception if @exception
        @tagged_response_arrival.wait
      end
      resp = @tagged_responses.delete(tag)
      case resp.name
      when /\A(?:OK)\z/ni
        return resp
      when /\A(?:NO)\z/ni
        raise NoResponseError, resp
      when /\A(?:BAD)\z/ni
        raise BadResponseError, resp
      else
        raise UnknownResponseError, resp
      end
    end

    def get_response
      buff = String.new
      while true
        s = @sock.gets(CRLF)
        break unless s
        buff.concat(s)
        if /\{(\d+)\}\r\n/n =~ s
          s = @sock.read($1.to_i)
          buff.concat(s)
        else
          break
        end
      end
      return nil if buff.length == 0
      if @@debug
        $stderr.print(buff.gsub(/^/n, "S: "))
      end
      return @parser.parse(buff)
    end

    def record_response(name, data)
      unless @responses.has_key?(name)
        @responses[name] = []
      end
      @responses[name].push(data)
    end

    def send_command(cmd, *args, &block)
      synchronize do
        args.each do |i|
          validate_data(i)
        end
        tag = generate_tag
        put_string(tag + " " + cmd)
        args.each do |i|
          put_string(" ")
          send_data(i, tag)
        end
        put_string(CRLF)
        if cmd == "LOGOUT"
          @logout_command_tag = tag
        end
        if block
          add_response_handler(&block)
        end
        begin
          return get_tagged_response(tag, cmd)
        ensure
          if block
            remove_response_handler(block)
          end
        end
      end
    end

    def generate_tag
      @tagno += 1
      return format("%s%04d", @tag_prefix, @tagno)
    end

    def put_string(str)
      @sock.print(str)
      if @@debug
        if @debug_output_bol
          $stderr.print("C: ")
        end
        $stderr.print(str.gsub(/\n(?!\z)/n, "\nC: "))
        if /\r\n\z/n.match(str)
          @debug_output_bol = true
        else
          @debug_output_bol = false
        end
      end
    end

    def validate_data(data)
      case data
      when nil
      when String
      when Integer
        NumValidator.ensure_number(data)
      when Array
        if data[0] == 'CHANGEDSINCE'
          NumValidator.ensure_mod_sequence_value(data[1])
        else
          data.each do |i|
            validate_data(i)
          end
        end
      when Time
      when Symbol
      else
        data.validate
      end
    end

    def send_data(data, tag = nil)
      case data
      when nil
        put_string("NIL")
      when String
        send_string_data(data, tag)
      when Integer
        send_number_data(data)
      when Array
        send_list_data(data, tag)
      when Time
        send_time_data(data)
      when Symbol
        send_symbol_data(data)
      else
        data.send_data(self, tag)
      end
    end

    def send_string_data(str, tag = nil)
      case str
      when ""
        put_string('""')
      when /[\x80-\xff\r\n]/n
        # literal
        send_literal(str, tag)
      when /[(){ \x00-\x1f\x7f%*"\\]/n
        # quoted string
        send_quoted_string(str)
      else
        put_string(str)
      end
    end

    def send_quoted_string(str)
      put_string('"' + str.gsub(/["\\]/n, "\\\\\\&") + '"')
    end

    def send_literal(str, tag = nil)
      synchronize do
        put_string("{" + str.bytesize.to_s + "}" + CRLF)
        @continued_command_tag = tag
        @continuation_request_exception = nil
        begin
          @continuation_request_arrival.wait
          e = @continuation_request_exception || @exception
          raise e if e
          put_string(str)
        ensure
          @continued_command_tag = nil
          @continuation_request_exception = nil
        end
      end
    end

    def send_number_data(num)
      put_string(num.to_s)
    end

    def send_list_data(list, tag = nil)
      put_string("(")
      first = true
      list.each do |i|
        if first
          first = false
        else
          put_string(" ")
        end
        send_data(i, tag)
      end
      put_string(")")
    end

    DATE_MONTH = %w(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)

    def send_time_data(time)
      t = time.dup.gmtime
      s = format('"%2d-%3s-%4d %02d:%02d:%02d +0000"',
                 t.day, DATE_MONTH[t.month - 1], t.year,
                 t.hour, t.min, t.sec)
      put_string(s)
    end

    def send_symbol_data(symbol)
      put_string("\\" + symbol.to_s)
    end

    def search_internal(cmd, keys, charset)
      if keys.instance_of?(String)
        keys = [RawData.new(keys)]
      else
        normalize_searching_criteria(keys)
      end
      synchronize do
        if charset
          send_command(cmd, "CHARSET", charset, *keys)
        else
          send_command(cmd, *keys)
        end
        return @responses.delete("SEARCH")[-1]
      end
    end

    def fetch_internal(cmd, set, attr, mod = nil)
      case attr
      when String then
        attr = RawData.new(attr)
      when Array then
        attr = attr.map { |arg|
          arg.is_a?(String) ? RawData.new(arg) : arg
        }
      end

      synchronize do
        @responses.delete("FETCH")
        if mod
          send_command(cmd, MessageSet.new(set), attr, mod)
        else
          send_command(cmd, MessageSet.new(set), attr)
        end
        return @responses.delete("FETCH")
      end
    end

    def store_internal(cmd, set, attr, flags)
      if attr.instance_of?(String)
        attr = RawData.new(attr)
      end
      synchronize do
        @responses.delete("FETCH")
        send_command(cmd, MessageSet.new(set), attr, flags)
        return @responses.delete("FETCH")
      end
    end

    def copy_internal(cmd, set, mailbox)
      send_command(cmd, MessageSet.new(set), mailbox)
    end

    def sort_internal(cmd, sort_keys, search_keys, charset)
      if search_keys.instance_of?(String)
        search_keys = [RawData.new(search_keys)]
      else
        normalize_searching_criteria(search_keys)
      end
      normalize_searching_criteria(search_keys)
      synchronize do
        send_command(cmd, sort_keys, charset, *search_keys)
        return @responses.delete("SORT")[-1]
      end
    end

    def thread_internal(cmd, algorithm, search_keys, charset)
      if search_keys.instance_of?(String)
        search_keys = [RawData.new(search_keys)]
      else
        normalize_searching_criteria(search_keys)
      end
      normalize_searching_criteria(search_keys)
      send_command(cmd, algorithm, charset, *search_keys)
      return @responses.delete("THREAD")[-1]
    end

    def normalize_searching_criteria(keys)
      keys.collect! do |i|
        case i
        when -1, Range, Array
          MessageSet.new(i)
        else
          i
        end
      end
    end

    def create_ssl_params(certs = nil, verify = true)
      params = {}
      if certs
        if File.file?(certs)
          params[:ca_file] = certs
        elsif File.directory?(certs)
          params[:ca_path] = certs
        end
      end
      if verify
        params[:verify_mode] = VERIFY_PEER
      else
        params[:verify_mode] = VERIFY_NONE
      end
      return params
    end

    def start_tls_session(params = {})
      unless defined?(OpenSSL::SSL)
        raise "SSL extension not installed"
      end
      if @sock.kind_of?(OpenSSL::SSL::SSLSocket)
        raise RuntimeError, "already using SSL"
      end
      begin
        params = params.to_hash
      rescue NoMethodError
        params = {}
      end
      context = SSLContext.new
      context.set_params(params)
      if defined?(VerifyCallbackProc)
        context.verify_callback = VerifyCallbackProc
      end
      @sock = SSLSocket.new(@sock, context)
      @sock.sync_close = true
      @sock.hostname = @host if @sock.respond_to? :hostname=
      ssl_socket_connect(@sock, @open_timeout)
      if context.verify_mode != VERIFY_NONE
        @sock.post_connection_check(@host)
      end
    end

    class RawData # :nodoc:
      def send_data(imap, tag)
        imap.__send__(:put_string, @data)
      end

      def validate
      end

      private

      def initialize(data)
        @data = data
      end
    end

    class Atom # :nodoc:
      def send_data(imap, tag)
        imap.__send__(:put_string, @data)
      end

      def validate
      end

      private

      def initialize(data)
        @data = data
      end
    end

    class QuotedString # :nodoc:
      def send_data(imap, tag)
        imap.__send__(:send_quoted_string, @data)
      end

      def validate
      end

      private

      def initialize(data)
        @data = data
      end
    end

    class Literal # :nodoc:
      def send_data(imap, tag)
        imap.__send__(:send_literal, @data, tag)
      end

      def validate
      end

      private

      def initialize(data)
        @data = data
      end
    end

    class MessageSet # :nodoc:
      def send_data(imap, tag)
        imap.__send__(:put_string, format_internal(@data))
      end

      def validate
        validate_internal(@data)
      end

      private

      def initialize(data)
        @data = data
      end

      def format_internal(data)
        case data
        when "*"
          return data
        when Integer
          if data == -1
            return "*"
          else
            return data.to_s
          end
        when Range
          return format_internal(data.first) +
            ":" + format_internal(data.last)
        when Array
          return data.collect {|i| format_internal(i)}.join(",")
        when ThreadMember
          return data.seqno.to_s +
            ":" + data.children.collect {|i| format_internal(i).join(",")}
        end
      end

      def validate_internal(data)
        case data
        when "*"
        when Integer
          NumValidator.ensure_nz_number(data)
        when Range
        when Array
          data.each do |i|
            validate_internal(i)
          end
        when ThreadMember
          data.children.each do |i|
            validate_internal(i)
          end
        else
          raise DataFormatError, data.inspect
        end
      end
    end

    # Common validators of number and nz_number types
    module NumValidator # :nodoc
      class << self
        # Check is passed argument valid 'number' in RFC 3501 terminology
        def valid_number?(num)
          # [RFC 3501]
          # number          = 1*DIGIT
          #                    ; Unsigned 32-bit integer
          #                    ; (0 <= n < 4,294,967,296)
          num >= 0 && num < 4294967296
        end

        # Check is passed argument valid 'nz_number' in RFC 3501 terminology
        def valid_nz_number?(num)
          # [RFC 3501]
          # nz-number       = digit-nz *DIGIT
          #                    ; Non-zero unsigned 32-bit integer
          #                    ; (0 < n < 4,294,967,296)
          num != 0 && valid_number?(num)
        end

        # Check is passed argument valid 'mod_sequence_value' in RFC 4551 terminology
        def valid_mod_sequence_value?(num)
          # mod-sequence-value  = 1*DIGIT
          #                        ; Positive unsigned 64-bit integer
          #                        ; (mod-sequence)
          #                        ; (1 <= n < 18,446,744,073,709,551,615)
          num >= 1 && num < 18446744073709551615
        end

        # Ensure argument is 'number' or raise DataFormatError
        def ensure_number(num)
          return if valid_number?(num)

          msg = "number must be unsigned 32-bit integer: #{num}"
          raise DataFormatError, msg
        end

        # Ensure argument is 'nz_number' or raise DataFormatError
        def ensure_nz_number(num)
          return if valid_nz_number?(num)

          msg = "nz_number must be non-zero unsigned 32-bit integer: #{num}"
          raise DataFormatError, msg
        end

        # Ensure argument is 'mod_sequence_value' or raise DataFormatError
        def ensure_mod_sequence_value(num)
          return if valid_mod_sequence_value?(num)

          msg = "mod_sequence_value must be unsigned 64-bit integer: #{num}"
          raise DataFormatError, msg
        end
      end
    end

    # Net::IMAP::ContinuationRequest represents command continuation requests.
    #
    # The command continuation request response is indicated by a "+" token
    # instead of a tag.  This form of response indicates that the server is
    # ready to accept the continuation of a command from the client.  The
    # remainder of this response is a line of text.
    #
    #   continue_req    ::= "+" SPACE (resp_text / base64)
    #
    # ==== Fields:
    #
    # data:: Returns the data (Net::IMAP::ResponseText).
    #
    # raw_data:: Returns the raw data string.
    ContinuationRequest = Struct.new(:data, :raw_data)

    # Net::IMAP::UntaggedResponse represents untagged responses.
    #
    # Data transmitted by the server to the client and status responses
    # that do not indicate command completion are prefixed with the token
    # "*", and are called untagged responses.
    #
    #   response_data   ::= "*" SPACE (resp_cond_state / resp_cond_bye /
    #                       mailbox_data / message_data / capability_data)
    #
    # ==== Fields:
    #
    # name:: Returns the name, such as "FLAGS", "LIST", or "FETCH".
    #
    # data:: Returns the data such as an array of flag symbols,
    #        a ((<Net::IMAP::MailboxList>)) object.
    #
    # raw_data:: Returns the raw data string.
    UntaggedResponse = Struct.new(:name, :data, :raw_data)

    # Net::IMAP::TaggedResponse represents tagged responses.
    #
    # The server completion result response indicates the success or
    # failure of the operation.  It is tagged with the same tag as the
    # client command which began the operation.
    #
    #   response_tagged ::= tag SPACE resp_cond_state CRLF
    #
    #   tag             ::= 1*<any ATOM_CHAR except "+">
    #
    #   resp_cond_state ::= ("OK" / "NO" / "BAD") SPACE resp_text
    #
    # ==== Fields:
    #
    # tag:: Returns the tag.
    #
    # name:: Returns the name, one of "OK", "NO", or "BAD".
    #
    # data:: Returns the data. See ((<Net::IMAP::ResponseText>)).
    #
    # raw_data:: Returns the raw data string.
    #
    TaggedResponse = Struct.new(:tag, :name, :data, :raw_data)

    # Net::IMAP::ResponseText represents texts of responses.
    # The text may be prefixed by the response code.
    #
    #   resp_text       ::= ["[" resp_text_code "]" SPACE] (text_mime2 / text)
    #                       ;; text SHOULD NOT begin with "[" or "="
    #
    # ==== Fields:
    #
    # code:: Returns the response code. See ((<Net::IMAP::ResponseCode>)).
    #
    # text:: Returns the text.
    #
    ResponseText = Struct.new(:code, :text)

    # Net::IMAP::ResponseCode represents response codes.
    #
    #   resp_text_code  ::= "ALERT" / "PARSE" /
    #                       "PERMANENTFLAGS" SPACE "(" #(flag / "\*") ")" /
    #                       "READ-ONLY" / "READ-WRITE" / "TRYCREATE" /
    #                       "UIDVALIDITY" SPACE nz_number /
    #                       "UNSEEN" SPACE nz_number /
    #                       atom [SPACE 1*<any TEXT_CHAR except "]">]
    #
    # ==== Fields:
    #
    # name:: Returns the name, such as "ALERT", "PERMANENTFLAGS", or "UIDVALIDITY".
    #
    # data:: Returns the data, if it exists.
    #
    ResponseCode = Struct.new(:name, :data)

    # Net::IMAP::MailboxList represents contents of the LIST response.
    #
    #   mailbox_list    ::= "(" #("\Marked" / "\Noinferiors" /
    #                       "\Noselect" / "\Unmarked" / flag_extension) ")"
    #                       SPACE (<"> QUOTED_CHAR <"> / nil) SPACE mailbox
    #
    # ==== Fields:
    #
    # attr:: Returns the name attributes. Each name attribute is a symbol
    #        capitalized by String#capitalize, such as :Noselect (not :NoSelect).
    #
    # delim:: Returns the hierarchy delimiter.
    #
    # name:: Returns the mailbox name.
    #
    MailboxList = Struct.new(:attr, :delim, :name)

    # Net::IMAP::MailboxQuota represents contents of GETQUOTA response.
    # This object can also be a response to GETQUOTAROOT.  In the syntax
    # specification below, the delimiter used with the "#" construct is a
    # single space (SPACE).
    #
    #    quota_list      ::= "(" #quota_resource ")"
    #
    #    quota_resource  ::= atom SPACE number SPACE number
    #
    #    quota_response  ::= "QUOTA" SPACE astring SPACE quota_list
    #
    # ==== Fields:
    #
    # mailbox:: The mailbox with the associated quota.
    #
    # usage:: Current storage usage of the mailbox.
    #
    # quota:: Quota limit imposed on the mailbox.
    #
    MailboxQuota = Struct.new(:mailbox, :usage, :quota)

    # Net::IMAP::MailboxQuotaRoot represents part of the GETQUOTAROOT
    # response. (GETQUOTAROOT can also return Net::IMAP::MailboxQuota.)
    #
    #    quotaroot_response ::= "QUOTAROOT" SPACE astring *(SPACE astring)
    #
    # ==== Fields:
    #
    # mailbox:: The mailbox with the associated quota.
    #
    # quotaroots:: Zero or more quotaroots that affect the quota on the
    #              specified mailbox.
    #
    MailboxQuotaRoot = Struct.new(:mailbox, :quotaroots)

    # Net::IMAP::MailboxACLItem represents the response from GETACL.
    #
    #    acl_data        ::= "ACL" SPACE mailbox *(SPACE identifier SPACE rights)
    #
    #    identifier      ::= astring
    #
    #    rights          ::= astring
    #
    # ==== Fields:
    #
    # user:: Login name that has certain rights to the mailbox
    #        that was specified with the getacl command.
    #
    # rights:: The access rights the indicated user has to the
    #          mailbox.
    #
    MailboxACLItem = Struct.new(:user, :rights, :mailbox)

    # Net::IMAP::StatusData represents the contents of the STATUS response.
    #
    # ==== Fields:
    #
    # mailbox:: Returns the mailbox name.
    #
    # attr:: Returns a hash. Each key is one of "MESSAGES", "RECENT", "UIDNEXT",
    #        "UIDVALIDITY", "UNSEEN". Each value is a number.
    #
    StatusData = Struct.new(:mailbox, :attr)

    # Net::IMAP::FetchData represents the contents of the FETCH response.
    #
    # ==== Fields:
    #
    # seqno:: Returns the message sequence number.
    #         (Note: not the unique identifier, even for the UID command response.)
    #
    # attr:: Returns a hash. Each key is a data item name, and each value is
    #        its value.
    #
    #        The current data items are:
    #
    #        [BODY]
    #           A form of BODYSTRUCTURE without extension data.
    #        [BODY[<section>]<<origin_octet>>]
    #           A string expressing the body contents of the specified section.
    #        [BODYSTRUCTURE]
    #           An object that describes the [MIME-IMB] body structure of a message.
    #           See Net::IMAP::BodyTypeBasic, Net::IMAP::BodyTypeText,
    #           Net::IMAP::BodyTypeMessage, Net::IMAP::BodyTypeMultipart.
    #        [ENVELOPE]
    #           A Net::IMAP::Envelope object that describes the envelope
    #           structure of a message.
    #        [FLAGS]
    #           A array of flag symbols that are set for this message. Flag symbols
    #           are capitalized by String#capitalize.
    #        [INTERNALDATE]
    #           A string representing the internal date of the message.
    #        [RFC822]
    #           Equivalent to BODY[].
    #        [RFC822.HEADER]
    #           Equivalent to BODY.PEEK[HEADER].
    #        [RFC822.SIZE]
    #           A number expressing the [RFC-822] size of the message.
    #        [RFC822.TEXT]
    #           Equivalent to BODY[TEXT].
    #        [UID]
    #           A number expressing the unique identifier of the message.
    #
    FetchData = Struct.new(:seqno, :attr)

    # Net::IMAP::Envelope represents envelope structures of messages.
    #
    # ==== Fields:
    #
    # date:: Returns a string that represents the date.
    #
    # subject:: Returns a string that represents the subject.
    #
    # from:: Returns an array of Net::IMAP::Address that represents the from.
    #
    # sender:: Returns an array of Net::IMAP::Address that represents the sender.
    #
    # reply_to:: Returns an array of Net::IMAP::Address that represents the reply-to.
    #
    # to:: Returns an array of Net::IMAP::Address that represents the to.
    #
    # cc:: Returns an array of Net::IMAP::Address that represents the cc.
    #
    # bcc:: Returns an array of Net::IMAP::Address that represents the bcc.
    #
    # in_reply_to:: Returns a string that represents the in-reply-to.
    #
    # message_id:: Returns a string that represents the message-id.
    #
    Envelope = Struct.new(:date, :subject, :from, :sender, :reply_to,
                          :to, :cc, :bcc, :in_reply_to, :message_id)

    #
    # Net::IMAP::Address represents electronic mail addresses.
    #
    # ==== Fields:
    #
    # name:: Returns the phrase from [RFC-822] mailbox.
    #
    # route:: Returns the route from [RFC-822] route-addr.
    #
    # mailbox:: nil indicates end of [RFC-822] group.
    #           If non-nil and host is nil, returns [RFC-822] group name.
    #           Otherwise, returns [RFC-822] local-part.
    #
    # host:: nil indicates [RFC-822] group syntax.
    #        Otherwise, returns [RFC-822] domain name.
    #
    Address = Struct.new(:name, :route, :mailbox, :host)

    #
    # Net::IMAP::ContentDisposition represents Content-Disposition fields.
    #
    # ==== Fields:
    #
    # dsp_type:: Returns the disposition type.
    #
    # param:: Returns a hash that represents parameters of the Content-Disposition
    #         field.
    #
    ContentDisposition = Struct.new(:dsp_type, :param)

    # Net::IMAP::ThreadMember represents a thread-node returned
    # by Net::IMAP#thread.
    #
    # ==== Fields:
    #
    # seqno:: The sequence number of this message.
    #
    # children:: An array of Net::IMAP::ThreadMember objects for mail
    #            items that are children of this in the thread.
    #
    ThreadMember = Struct.new(:seqno, :children)

    # Net::IMAP::BodyTypeBasic represents basic body structures of messages.
    #
    # ==== Fields:
    #
    # media_type:: Returns the content media type name as defined in [MIME-IMB].
    #
    # subtype:: Returns the content subtype name as defined in [MIME-IMB].
    #
    # param:: Returns a hash that represents parameters as defined in [MIME-IMB].
    #
    # content_id:: Returns a string giving the content id as defined in [MIME-IMB].
    #
    # description:: Returns a string giving the content description as defined in
    #               [MIME-IMB].
    #
    # encoding:: Returns a string giving the content transfer encoding as defined in
    #            [MIME-IMB].
    #
    # size:: Returns a number giving the size of the body in octets.
    #
    # md5:: Returns a string giving the body MD5 value as defined in [MD5].
    #
    # disposition:: Returns a Net::IMAP::ContentDisposition object giving
    #               the content disposition.
    #
    # language:: Returns a string or an array of strings giving the body
    #            language value as defined in [LANGUAGE-TAGS].
    #
    # extension:: Returns extension data.
    #
    # multipart?:: Returns false.
    #
    class BodyTypeBasic < Struct.new(:media_type, :subtype,
                                     :param, :content_id,
                                     :description, :encoding, :size,
                                     :md5, :disposition, :language,
                                     :extension)
      def multipart?
        return false
      end

      # Obsolete: use +subtype+ instead.  Calling this will
      # generate a warning message to +stderr+, then return
      # the value of +subtype+.
      def media_subtype
        warn("media_subtype is obsolete, use subtype instead.\n", uplevel: 1)
        return subtype
      end
    end

    # Net::IMAP::BodyTypeText represents TEXT body structures of messages.
    #
    # ==== Fields:
    #
    # lines:: Returns the size of the body in text lines.
    #
    # And Net::IMAP::BodyTypeText has all fields of Net::IMAP::BodyTypeBasic.
    #
    class BodyTypeText < Struct.new(:media_type, :subtype,
                                    :param, :content_id,
                                    :description, :encoding, :size,
                                    :lines,
                                    :md5, :disposition, :language,
                                    :extension)
      def multipart?
        return false
      end

      # Obsolete: use +subtype+ instead.  Calling this will
      # generate a warning message to +stderr+, then return
      # the value of +subtype+.
      def media_subtype
        warn("media_subtype is obsolete, use subtype instead.\n", uplevel: 1)
        return subtype
      end
    end

    # Net::IMAP::BodyTypeMessage represents MESSAGE/RFC822 body structures of messages.
    #
    # ==== Fields:
    #
    # envelope:: Returns a Net::IMAP::Envelope giving the envelope structure.
    #
    # body:: Returns an object giving the body structure.
    #
    # And Net::IMAP::BodyTypeMessage has all methods of Net::IMAP::BodyTypeText.
    #
    class BodyTypeMessage < Struct.new(:media_type, :subtype,
                                       :param, :content_id,
                                       :description, :encoding, :size,
                                       :envelope, :body, :lines,
                                       :md5, :disposition, :language,
                                       :extension)
      def multipart?
        return false
      end

      # Obsolete: use +subtype+ instead.  Calling this will
      # generate a warning message to +stderr+, then return
      # the value of +subtype+.
      def media_subtype
        warn("media_subtype is obsolete, use subtype instead.\n", uplevel: 1)
        return subtype
      end
    end

    # Net::IMAP::BodyTypeAttachment represents attachment body structures
    # of messages.
    #
    # ==== Fields:
    #
    # media_type:: Returns the content media type name.
    #
    # subtype:: Returns +nil+.
    #
    # param:: Returns a hash that represents parameters.
    #
    # multipart?:: Returns false.
    #
    class BodyTypeAttachment < Struct.new(:media_type, :subtype,
                                          :param)
      def multipart?
        return false
      end
    end

    # Net::IMAP::BodyTypeMultipart represents multipart body structures
    # of messages.
    #
    # ==== Fields:
    #
    # media_type:: Returns the content media type name as defined in [MIME-IMB].
    #
    # subtype:: Returns the content subtype name as defined in [MIME-IMB].
    #
    # parts:: Returns multiple parts.
    #
    # param:: Returns a hash that represents parameters as defined in [MIME-IMB].
    #
    # disposition:: Returns a Net::IMAP::ContentDisposition object giving
    #               the content disposition.
    #
    # language:: Returns a string or an array of strings giving the body
    #            language value as defined in [LANGUAGE-TAGS].
    #
    # extension:: Returns extension data.
    #
    # multipart?:: Returns true.
    #
    class BodyTypeMultipart < Struct.new(:media_type, :subtype,
                                         :parts,
                                         :param, :disposition, :language,
                                         :extension)
      def multipart?
        return true
      end

      # Obsolete: use +subtype+ instead.  Calling this will
      # generate a warning message to +stderr+, then return
      # the value of +subtype+.
      def media_subtype
        warn("media_subtype is obsolete, use subtype instead.\n", uplevel: 1)
        return subtype
      end
    end

    class BodyTypeExtension < Struct.new(:media_type, :subtype,
                                         :params, :content_id,
                                         :description, :encoding, :size)
      def multipart?
        return false
      end
    end

    class ResponseParser # :nodoc:
      def initialize
        @str = nil
        @pos = nil
        @lex_state = nil
        @token = nil
        @flag_symbols = {}
      end

      def parse(str)
        @str = str
        @pos = 0
        @lex_state = EXPR_BEG
        @token = nil
        return response
      end

      private

      EXPR_BEG          = :EXPR_BEG
      EXPR_DATA         = :EXPR_DATA
      EXPR_TEXT         = :EXPR_TEXT
      EXPR_RTEXT        = :EXPR_RTEXT
      EXPR_CTEXT        = :EXPR_CTEXT

      T_SPACE   = :SPACE
      T_NIL     = :NIL
      T_NUMBER  = :NUMBER
      T_ATOM    = :ATOM
      T_QUOTED  = :QUOTED
      T_LPAR    = :LPAR
      T_RPAR    = :RPAR
      T_BSLASH  = :BSLASH
      T_STAR    = :STAR
      T_LBRA    = :LBRA
      T_RBRA    = :RBRA
      T_LITERAL = :LITERAL
      T_PLUS    = :PLUS
      T_PERCENT = :PERCENT
      T_CRLF    = :CRLF
      T_EOF     = :EOF
      T_TEXT    = :TEXT

      BEG_REGEXP = /\G(?:\
(?# 1:  SPACE   )( +)|\
(?# 2:  NIL     )(NIL)(?=[\x80-\xff(){ \x00-\x1f\x7f%*"\\\[\]+])|\
(?# 3:  NUMBER  )(\d+)(?=[\x80-\xff(){ \x00-\x1f\x7f%*"\\\[\]+])|\
(?# 4:  ATOM    )([^\x80-\xff(){ \x00-\x1f\x7f%*"\\\[\]+]+)|\
(?# 5:  QUOTED  )"((?:[^\x00\r\n"\\]|\\["\\])*)"|\
(?# 6:  LPAR    )(\()|\
(?# 7:  RPAR    )(\))|\
(?# 8:  BSLASH  )(\\)|\
(?# 9:  STAR    )(\*)|\
(?# 10: LBRA    )(\[)|\
(?# 11: RBRA    )(\])|\
(?# 12: LITERAL )\{(\d+)\}\r\n|\
(?# 13: PLUS    )(\+)|\
(?# 14: PERCENT )(%)|\
(?# 15: CRLF    )(\r\n)|\
(?# 16: EOF     )(\z))/ni

      DATA_REGEXP = /\G(?:\
(?# 1:  SPACE   )( )|\
(?# 2:  NIL     )(NIL)|\
(?# 3:  NUMBER  )(\d+)|\
(?# 4:  QUOTED  )"((?:[^\x00\r\n"\\]|\\["\\])*)"|\
(?# 5:  LITERAL )\{(\d+)\}\r\n|\
(?# 6:  LPAR    )(\()|\
(?# 7:  RPAR    )(\)))/ni

      TEXT_REGEXP = /\G(?:\
(?# 1:  TEXT    )([^\x00\r\n]*))/ni

      RTEXT_REGEXP = /\G(?:\
(?# 1:  LBRA    )(\[)|\
(?# 2:  TEXT    )([^\x00\r\n]*))/ni

      CTEXT_REGEXP = /\G(?:\
(?# 1:  TEXT    )([^\x00\r\n\]]*))/ni

      Token = Struct.new(:symbol, :value)

      def response
        token = lookahead
        case token.symbol
        when T_PLUS
          result = continue_req
        when T_STAR
          result = response_untagged
        else
          result = response_tagged
        end
        while lookahead.symbol == T_SPACE
          # Ignore trailing space for Microsoft Exchange Server
          shift_token
        end
        match(T_CRLF)
        match(T_EOF)
        return result
      end

      def continue_req
        match(T_PLUS)
        token = lookahead
        if token.symbol == T_SPACE
          shift_token
          return ContinuationRequest.new(resp_text, @str)
        else
          return ContinuationRequest.new(ResponseText.new(nil, ""), @str)
        end
      end

      def response_untagged
        match(T_STAR)
        match(T_SPACE)
        token = lookahead
        if token.symbol == T_NUMBER
          return numeric_response
        elsif token.symbol == T_ATOM
          case token.value
          when /\A(?:OK|NO|BAD|BYE|PREAUTH)\z/ni
            return response_cond
          when /\A(?:FLAGS)\z/ni
            return flags_response
          when /\A(?:LIST|LSUB|XLIST)\z/ni
            return list_response
          when /\A(?:QUOTA)\z/ni
            return getquota_response
          when /\A(?:QUOTAROOT)\z/ni
            return getquotaroot_response
          when /\A(?:ACL)\z/ni
            return getacl_response
          when /\A(?:SEARCH|SORT)\z/ni
            return search_response
          when /\A(?:THREAD)\z/ni
            return thread_response
          when /\A(?:STATUS)\z/ni
            return status_response
          when /\A(?:CAPABILITY)\z/ni
            return capability_response
          else
            return text_response
          end
        else
          parse_error("unexpected token %s", token.symbol)
        end
      end

      def response_tagged
        tag = atom
        match(T_SPACE)
        token = match(T_ATOM)
        name = token.value.upcase
        match(T_SPACE)
        return TaggedResponse.new(tag, name, resp_text, @str)
      end

      def response_cond
        token = match(T_ATOM)
        name = token.value.upcase
        match(T_SPACE)
        return UntaggedResponse.new(name, resp_text, @str)
      end

      def numeric_response
        n = number
        match(T_SPACE)
        token = match(T_ATOM)
        name = token.value.upcase
        case name
        when "EXISTS", "RECENT", "EXPUNGE"
          return UntaggedResponse.new(name, n, @str)
        when "FETCH"
          shift_token
          match(T_SPACE)
          data = FetchData.new(n, msg_att(n))
          return UntaggedResponse.new(name, data, @str)
        end
      end

      def msg_att(n)
        match(T_LPAR)
        attr = {}
        while true
          token = lookahead
          case token.symbol
          when T_RPAR
            shift_token
            break
          when T_SPACE
            shift_token
            next
          end
          case token.value
          when /\A(?:ENVELOPE)\z/ni
            name, val = envelope_data
          when /\A(?:FLAGS)\z/ni
            name, val = flags_data
          when /\A(?:INTERNALDATE)\z/ni
            name, val = internaldate_data
          when /\A(?:RFC822(?:\.HEADER|\.TEXT)?)\z/ni
            name, val = rfc822_text
          when /\A(?:RFC822\.SIZE)\z/ni
            name, val = rfc822_size
          when /\A(?:BODY(?:STRUCTURE)?)\z/ni
            name, val = body_data
          when /\A(?:UID)\z/ni
            name, val = uid_data
          when /\A(?:MODSEQ)\z/ni
            name, val = modseq_data
          else
            parse_error("unknown attribute `%s' for {%d}", token.value, n)
          end
          attr[name] = val
        end
        return attr
      end

      def envelope_data
        token = match(T_ATOM)
        name = token.value.upcase
        match(T_SPACE)
        return name, envelope
      end

      def envelope
        @lex_state = EXPR_DATA
        token = lookahead
        if token.symbol == T_NIL
          shift_token
          result = nil
        else
          match(T_LPAR)
          date = nstring
          match(T_SPACE)
          subject = nstring
          match(T_SPACE)
          from = address_list
          match(T_SPACE)
          sender = address_list
          match(T_SPACE)
          reply_to = address_list
          match(T_SPACE)
          to = address_list
          match(T_SPACE)
          cc = address_list
          match(T_SPACE)
          bcc = address_list
          match(T_SPACE)
          in_reply_to = nstring
          match(T_SPACE)
          message_id = nstring
          match(T_RPAR)
          result = Envelope.new(date, subject, from, sender, reply_to,
                                to, cc, bcc, in_reply_to, message_id)
        end
        @lex_state = EXPR_BEG
        return result
      end

      def flags_data
        token = match(T_ATOM)
        name = token.value.upcase
        match(T_SPACE)
        return name, flag_list
      end

      def internaldate_data
        token = match(T_ATOM)
        name = token.value.upcase
        match(T_SPACE)
        token = match(T_QUOTED)
        return name, token.value
      end

      def rfc822_text
        token = match(T_ATOM)
        name = token.value.upcase
        token = lookahead
        if token.symbol == T_LBRA
          shift_token
          match(T_RBRA)
        end
        match(T_SPACE)
        return name, nstring
      end

      def rfc822_size
        token = match(T_ATOM)
        name = token.value.upcase
        match(T_SPACE)
        return name, number
      end

      def body_data
        token = match(T_ATOM)
        name = token.value.upcase
        token = lookahead
        if token.symbol == T_SPACE
          shift_token
          return name, body
        end
        name.concat(section)
        token = lookahead
        if token.symbol == T_ATOM
          name.concat(token.value)
          shift_token
        end
        match(T_SPACE)
        data = nstring
        return name, data
      end

      def body
        @lex_state = EXPR_DATA
        token = lookahead
        if token.symbol == T_NIL
          shift_token
          result = nil
        else
          match(T_LPAR)
          token = lookahead
          if token.symbol == T_LPAR
            result = body_type_mpart
          else
            result = body_type_1part
          end
          match(T_RPAR)
        end
        @lex_state = EXPR_BEG
        return result
      end

      def body_type_1part
        token = lookahead
        case token.value
        when /\A(?:TEXT)\z/ni
          return body_type_text
        when /\A(?:MESSAGE)\z/ni
          return body_type_msg
        when /\A(?:ATTACHMENT)\z/ni
          return body_type_attachment
        when /\A(?:MIXED)\z/ni
          return body_type_mixed
        else
          return body_type_basic
        end
      end

      def body_type_basic
        mtype, msubtype = media_type
        token = lookahead
        if token.symbol == T_RPAR
          return BodyTypeBasic.new(mtype, msubtype)
        end
        match(T_SPACE)
        param, content_id, desc, enc, size = body_fields
        md5, disposition, language, extension = body_ext_1part
        return BodyTypeBasic.new(mtype, msubtype,
                                 param, content_id,
                                 desc, enc, size,
                                 md5, disposition, language, extension)
      end

      def body_type_text
        mtype, msubtype = media_type
        match(T_SPACE)
        param, content_id, desc, enc, size = body_fields
        match(T_SPACE)
        lines = number
        md5, disposition, language, extension = body_ext_1part
        return BodyTypeText.new(mtype, msubtype,
                                param, content_id,
                                desc, enc, size,
                                lines,
                                md5, disposition, language, extension)
      end

      def body_type_msg
        mtype, msubtype = media_type
        match(T_SPACE)
        param, content_id, desc, enc, size = body_fields

        token = lookahead
        if token.symbol == T_RPAR
          # If this is not message/rfc822, we shouldn't apply the RFC822
          # spec to it.  We should handle anything other than
          # message/rfc822 using multipart extension data [rfc3501] (i.e.
          # the data itself won't be returned, we would have to retrieve it
          # with BODYSTRUCTURE instead of with BODY

          # Also, sometimes a message/rfc822 is included as a large
          # attachment instead of having all of the other details
          # (e.g. attaching a .eml file to an email)
          if msubtype == "RFC822"
            return BodyTypeMessage.new(mtype, msubtype, param, content_id,
                                       desc, enc, size, nil, nil, nil, nil,
                                       nil, nil, nil)
          else
            return BodyTypeExtension.new(mtype, msubtype,
                                         param, content_id,
                                         desc, enc, size)
          end
        end

        match(T_SPACE)
        env = envelope
        match(T_SPACE)
        b = body
        match(T_SPACE)
        lines = number
        md5, disposition, language, extension = body_ext_1part
        return BodyTypeMessage.new(mtype, msubtype,
                                   param, content_id,
                                   desc, enc, size,
                                   env, b, lines,
                                   md5, disposition, language, extension)
      end

      def body_type_attachment
        mtype = case_insensitive_string
        match(T_SPACE)
        param = body_fld_param
        return BodyTypeAttachment.new(mtype, nil, param)
      end

      def body_type_mixed
        mtype = "MULTIPART"
        msubtype = case_insensitive_string
        param, disposition, language, extension = body_ext_mpart
        return BodyTypeBasic.new(mtype, msubtype, param, nil, nil, nil, nil, nil, disposition, language, extension)
      end

      def body_type_mpart
        parts = []
        while true
          token = lookahead
          if token.symbol == T_SPACE
            shift_token
            break
          end
          parts.push(body)
        end
        mtype = "MULTIPART"
        msubtype = case_insensitive_string
        param, disposition, language, extension = body_ext_mpart
        return BodyTypeMultipart.new(mtype, msubtype, parts,
                                     param, disposition, language,
                                     extension)
      end

      def media_type
        mtype = case_insensitive_string
        token = lookahead
        if token.symbol != T_SPACE
          return mtype, nil
        end
        match(T_SPACE)
        msubtype = case_insensitive_string
        return mtype, msubtype
      end

      def body_fields
        param = body_fld_param
        match(T_SPACE)
        content_id = nstring
        match(T_SPACE)
        desc = nstring
        match(T_SPACE)
        enc = case_insensitive_string
        match(T_SPACE)
        size = number
        return param, content_id, desc, enc, size
      end

      def body_fld_param
        token = lookahead
        if token.symbol == T_NIL
          shift_token
          return nil
        end
        match(T_LPAR)
        param = {}
        while true
          token = lookahead
          case token.symbol
          when T_RPAR
            shift_token
            break
          when T_SPACE
            shift_token
          end
          name = case_insensitive_string
          match(T_SPACE)
          val = string
          param[name] = val
        end
        return param
      end

      def body_ext_1part
        token = lookahead
        if token.symbol == T_SPACE
          shift_token
        else
          return nil
        end
        md5 = nstring

        token = lookahead
        if token.symbol == T_SPACE
          shift_token
        else
          return md5
        end
        disposition = body_fld_dsp

        token = lookahead
        if token.symbol == T_SPACE
          shift_token
        else
          return md5, disposition
        end
        language = body_fld_lang

        token = lookahead
        if token.symbol == T_SPACE
          shift_token
        else
          return md5, disposition, language
        end

        extension = body_extensions
        return md5, disposition, language, extension
      end

      def body_ext_mpart
        token = lookahead
        if token.symbol == T_SPACE
          shift_token
        else
          return nil
        end
        param = body_fld_param

        token = lookahead
        if token.symbol == T_SPACE
          shift_token
        else
          return param
        end
        disposition = body_fld_dsp

        token = lookahead
        if token.symbol == T_SPACE
          shift_token
        else
          return param, disposition
        end
        language = body_fld_lang

        token = lookahead
        if token.symbol == T_SPACE
          shift_token
        else
          return param, disposition, language
        end

        extension = body_extensions
        return param, disposition, language, extension
      end

      def body_fld_dsp
        token = lookahead
        if token.symbol == T_NIL
          shift_token
          return nil
        end
        match(T_LPAR)
        dsp_type = case_insensitive_string
        match(T_SPACE)
        param = body_fld_param
        match(T_RPAR)
        return ContentDisposition.new(dsp_type, param)
      end

      def body_fld_lang
        token = lookahead
        if token.symbol == T_LPAR
          shift_token
          result = []
          while true
            token = lookahead
            case token.symbol
            when T_RPAR
              shift_token
              return result
            when T_SPACE
              shift_token
            end
            result.push(case_insensitive_string)
          end
        else
          lang = nstring
          if lang
            return lang.upcase
          else
            return lang
          end
        end
      end

      def body_extensions
        result = []
        while true
          token = lookahead
          case token.symbol
          when T_RPAR
            return result
          when T_SPACE
            shift_token
          end
          result.push(body_extension)
        end
      end

      def body_extension
        token = lookahead
        case token.symbol
        when T_LPAR
          shift_token
          result = body_extensions
          match(T_RPAR)
          return result
        when T_NUMBER
          return number
        else
          return nstring
        end
      end

      def section
        str = String.new
        token = match(T_LBRA)
        str.concat(token.value)
        token = match(T_ATOM, T_NUMBER, T_RBRA)
        if token.symbol == T_RBRA
          str.concat(token.value)
          return str
        end
        str.concat(token.value)
        token = lookahead
        if token.symbol == T_SPACE
          shift_token
          str.concat(token.value)
          token = match(T_LPAR)
          str.concat(token.value)
          while true
            token = lookahead
            case token.symbol
            when T_RPAR
              str.concat(token.value)
              shift_token
              break
            when T_SPACE
              shift_token
              str.concat(token.value)
            end
            str.concat(format_string(astring))
          end
        end
        token = match(T_RBRA)
        str.concat(token.value)
        return str
      end

      def format_string(str)
        case str
        when ""
          return '""'
        when /[\x80-\xff\r\n]/n
          # literal
          return "{" + str.bytesize.to_s + "}" + CRLF + str
        when /[(){ \x00-\x1f\x7f%*"\\]/n
          # quoted string
          return '"' + str.gsub(/["\\]/n, "\\\\\\&") + '"'
        else
          # atom
          return str
        end
      end

      def uid_data
        token = match(T_ATOM)
        name = token.value.upcase
        match(T_SPACE)
        return name, number
      end

      def modseq_data
        token = match(T_ATOM)
        name = token.value.upcase
        match(T_SPACE)
        match(T_LPAR)
        modseq = number
        match(T_RPAR)
        return name, modseq
      end

      def text_response
        token = match(T_ATOM)
        name = token.value.upcase
        match(T_SPACE)
        @lex_state = EXPR_TEXT
        token = match(T_TEXT)
        @lex_state = EXPR_BEG
        return UntaggedResponse.new(name, token.value)
      end

      def flags_response
        token = match(T_ATOM)
        name = token.value.upcase
        match(T_SPACE)
        return UntaggedResponse.new(name, flag_list, @str)
      end

      def list_response
        token = match(T_ATOM)
        name = token.value.upcase
        match(T_SPACE)
        return UntaggedResponse.new(name, mailbox_list, @str)
      end

      def mailbox_list
        attr = flag_list
        match(T_SPACE)
        token = match(T_QUOTED, T_NIL)
        if token.symbol == T_NIL
          delim = nil
        else
          delim = token.value
        end
        match(T_SPACE)
        name = astring
        return MailboxList.new(attr, delim, name)
      end

      def getquota_response
        # If quota never established, get back
        # `NO Quota root does not exist'.
        # If quota removed, get `()' after the
        # folder spec with no mention of `STORAGE'.
        token = match(T_ATOM)
        name = token.value.upcase
        match(T_SPACE)
        mailbox = astring
        match(T_SPACE)
        match(T_LPAR)
        token = lookahead
        case token.symbol
        when T_RPAR
          shift_token
          data = MailboxQuota.new(mailbox, nil, nil)
          return UntaggedResponse.new(name, data, @str)
        when T_ATOM
          shift_token
          match(T_SPACE)
          token = match(T_NUMBER)
          usage = token.value
          match(T_SPACE)
          token = match(T_NUMBER)
          quota = token.value
          match(T_RPAR)
          data = MailboxQuota.new(mailbox, usage, quota)
          return UntaggedResponse.new(name, data, @str)
        else
          parse_error("unexpected token %s", token.symbol)
        end
      end

      def getquotaroot_response
        # Similar to getquota, but only admin can use getquota.
        token = match(T_ATOM)
        name = token.value.upcase
        match(T_SPACE)
        mailbox = astring
        quotaroots = []
        while true
          token = lookahead
          break unless token.symbol == T_SPACE
          shift_token
          quotaroots.push(astring)
        end
        data = MailboxQuotaRoot.new(mailbox, quotaroots)
        return UntaggedResponse.new(name, data, @str)
      end

      def getacl_response
        token = match(T_ATOM)
        name = token.value.upcase
        match(T_SPACE)
        mailbox = astring
        data = []
        token = lookahead
        if token.symbol == T_SPACE
          shift_token
          while true
            token = lookahead
            case token.symbol
            when T_CRLF
              break
            when T_SPACE
              shift_token
            end
            user = astring
            match(T_SPACE)
            rights = astring
            data.push(MailboxACLItem.new(user, rights, mailbox))
          end
        end
        return UntaggedResponse.new(name, data, @str)
      end

      def search_response
        token = match(T_ATOM)
        name = token.value.upcase
        token = lookahead
        if token.symbol == T_SPACE
          shift_token
          data = []
          while true
            token = lookahead
            case token.symbol
            when T_CRLF
              break
            when T_SPACE
              shift_token
            when T_NUMBER
              data.push(number)
            when T_LPAR
              # TODO: include the MODSEQ value in a response
              shift_token
              match(T_ATOM)
              match(T_SPACE)
              match(T_NUMBER)
              match(T_RPAR)
            end
          end
        else
          data = []
        end
        return UntaggedResponse.new(name, data, @str)
      end

      def thread_response
        token = match(T_ATOM)
        name = token.value.upcase
        token = lookahead

        if token.symbol == T_SPACE
          threads = []

          while true
            shift_token
            token = lookahead

            case token.symbol
            when T_LPAR
              threads << thread_branch(token)
            when T_CRLF
              break
            end
          end
        else
          # no member
          threads = []
        end

        return UntaggedResponse.new(name, threads, @str)
      end

      def thread_branch(token)
        rootmember = nil
        lastmember = nil

        while true
          shift_token    # ignore first T_LPAR
          token = lookahead

          case token.symbol
          when T_NUMBER
            # new member
            newmember = ThreadMember.new(number, [])
            if rootmember.nil?
              rootmember = newmember
            else
              lastmember.children << newmember
            end
            lastmember = newmember
          when T_SPACE
            # do nothing
          when T_LPAR
            if rootmember.nil?
              # dummy member
              lastmember = rootmember = ThreadMember.new(nil, [])
            end

            lastmember.children << thread_branch(token)
          when T_RPAR
            break
          end
        end

        return rootmember
      end

      def status_response
        token = match(T_ATOM)
        name = token.value.upcase
        match(T_SPACE)
        mailbox = astring
        match(T_SPACE)
        match(T_LPAR)
        attr = {}
        while true
          token = lookahead
          case token.symbol
          when T_RPAR
            shift_token
            break
          when T_SPACE
            shift_token
          end
          token = match(T_ATOM)
          key = token.value.upcase
          match(T_SPACE)
          val = number
          attr[key] = val
        end
        data = StatusData.new(mailbox, attr)
        return UntaggedResponse.new(name, data, @str)
      end

      def capability_response
        token = match(T_ATOM)
        name = token.value.upcase
        match(T_SPACE)
        data = []
        while true
          token = lookahead
          case token.symbol
          when T_CRLF
            break
          when T_SPACE
            shift_token
            next
          end
          data.push(atom.upcase)
        end
        return UntaggedResponse.new(name, data, @str)
      end

      def resp_text
        @lex_state = EXPR_RTEXT
        token = lookahead
        if token.symbol == T_LBRA
          code = resp_text_code
        else
          code = nil
        end
        token = match(T_TEXT)
        @lex_state = EXPR_BEG
        return ResponseText.new(code, token.value)
      end

      def resp_text_code
        @lex_state = EXPR_BEG
        match(T_LBRA)
        token = match(T_ATOM)
        name = token.value.upcase
        case name
        when /\A(?:ALERT|PARSE|READ-ONLY|READ-WRITE|TRYCREATE|NOMODSEQ)\z/n
          result = ResponseCode.new(name, nil)
        when /\A(?:PERMANENTFLAGS)\z/n
          match(T_SPACE)
          result = ResponseCode.new(name, flag_list)
        when /\A(?:UIDVALIDITY|UIDNEXT|UNSEEN)\z/n
          match(T_SPACE)
          result = ResponseCode.new(name, number)
        else
          token = lookahead
          if token.symbol == T_SPACE
            shift_token
            @lex_state = EXPR_CTEXT
            token = match(T_TEXT)
            @lex_state = EXPR_BEG
            result = ResponseCode.new(name, token.value)
          else
            result = ResponseCode.new(name, nil)
          end
        end
        match(T_RBRA)
        @lex_state = EXPR_RTEXT
        return result
      end

      def address_list
        token = lookahead
        if token.symbol == T_NIL
          shift_token
          return nil
        else
          result = []
          match(T_LPAR)
          while true
            token = lookahead
            case token.symbol
            when T_RPAR
              shift_token
              break
            when T_SPACE
              shift_token
            end
            result.push(address)
          end
          return result
        end
      end

      ADDRESS_REGEXP = /\G\
(?# 1: NAME     )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)") \
(?# 2: ROUTE    )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)") \
(?# 3: MAILBOX  )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)") \
(?# 4: HOST     )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)")\
\)/ni

      def address
        match(T_LPAR)
        if @str.index(ADDRESS_REGEXP, @pos)
          # address does not include literal.
          @pos = $~.end(0)
          name = $1
          route = $2
          mailbox = $3
          host = $4
          for s in [name, route, mailbox, host]
            if s
              s.gsub!(/\\(["\\])/n, "\\1")
            end
          end
        else
          name = nstring
          match(T_SPACE)
          route = nstring
          match(T_SPACE)
          mailbox = nstring
          match(T_SPACE)
          host = nstring
          match(T_RPAR)
        end
        return Address.new(name, route, mailbox, host)
      end

      FLAG_REGEXP = /\
(?# FLAG        )\\([^\x80-\xff(){ \x00-\x1f\x7f%"\\]+)|\
(?# ATOM        )([^\x80-\xff(){ \x00-\x1f\x7f%*"\\]+)/n

      def flag_list
        if @str.index(/\(([^)]*)\)/ni, @pos)
          @pos = $~.end(0)
          return $1.scan(FLAG_REGEXP).collect { |flag, atom|
            if atom
              atom
            else
              symbol = flag.capitalize.intern
              @flag_symbols[symbol] = true
              if @flag_symbols.length > IMAP.max_flag_count
                raise FlagCountError, "number of flag symbols exceeded"
              end
              symbol
            end
          }
        else
          parse_error("invalid flag list")
        end
      end

      def nstring
        token = lookahead
        if token.symbol == T_NIL
          shift_token
          return nil
        else
          return string
        end
      end

      def astring
        token = lookahead
        if string_token?(token)
          return string
        else
          return atom
        end
      end

      def string
        token = lookahead
        if token.symbol == T_NIL
          shift_token
          return nil
        end
        token = match(T_QUOTED, T_LITERAL)
        return token.value
      end

      STRING_TOKENS = [T_QUOTED, T_LITERAL, T_NIL]

      def string_token?(token)
        return STRING_TOKENS.include?(token.symbol)
      end

      def case_insensitive_string
        token = lookahead
        if token.symbol == T_NIL
          shift_token
          return nil
        end
        token = match(T_QUOTED, T_LITERAL)
        return token.value.upcase
      end

      def atom
        result = String.new
        while true
          token = lookahead
          if atom_token?(token)
            result.concat(token.value)
            shift_token
          else
            if result.empty?
              parse_error("unexpected token %s", token.symbol)
            else
              return result
            end
          end
        end
      end

      ATOM_TOKENS = [
        T_ATOM,
        T_NUMBER,
        T_NIL,
        T_LBRA,
        T_RBRA,
        T_PLUS
      ]

      def atom_token?(token)
        return ATOM_TOKENS.include?(token.symbol)
      end

      def number
        token = lookahead
        if token.symbol == T_NIL
          shift_token
          return nil
        end
        token = match(T_NUMBER)
        return token.value.to_i
      end

      def nil_atom
        match(T_NIL)
        return nil
      end

      def match(*args)
        token = lookahead
        unless args.include?(token.symbol)
          parse_error('unexpected token %s (expected %s)',
                      token.symbol.id2name,
                      args.collect {|i| i.id2name}.join(" or "))
        end
        shift_token
        return token
      end

      def lookahead
        unless @token
          @token = next_token
        end
        return @token
      end

      def shift_token
        @token = nil
      end

      def next_token
        case @lex_state
        when EXPR_BEG
          if @str.index(BEG_REGEXP, @pos)
            @pos = $~.end(0)
            if $1
              return Token.new(T_SPACE, $+)
            elsif $2
              return Token.new(T_NIL, $+)
            elsif $3
              return Token.new(T_NUMBER, $+)
            elsif $4
              return Token.new(T_ATOM, $+)
            elsif $5
              return Token.new(T_QUOTED,
                               $+.gsub(/\\(["\\])/n, "\\1"))
            elsif $6
              return Token.new(T_LPAR, $+)
            elsif $7
              return Token.new(T_RPAR, $+)
            elsif $8
              return Token.new(T_BSLASH, $+)
            elsif $9
              return Token.new(T_STAR, $+)
            elsif $10
              return Token.new(T_LBRA, $+)
            elsif $11
              return Token.new(T_RBRA, $+)
            elsif $12
              len = $+.to_i
              val = @str[@pos, len]
              @pos += len
              return Token.new(T_LITERAL, val)
            elsif $13
              return Token.new(T_PLUS, $+)
            elsif $14
              return Token.new(T_PERCENT, $+)
            elsif $15
              return Token.new(T_CRLF, $+)
            elsif $16
              return Token.new(T_EOF, $+)
            else
              parse_error("[Net::IMAP BUG] BEG_REGEXP is invalid")
            end
          else
            @str.index(/\S*/n, @pos)
            parse_error("unknown token - %s", $&.dump)
          end
        when EXPR_DATA
          if @str.index(DATA_REGEXP, @pos)
            @pos = $~.end(0)
            if $1
              return Token.new(T_SPACE, $+)
            elsif $2
              return Token.new(T_NIL, $+)
            elsif $3
              return Token.new(T_NUMBER, $+)
            elsif $4
              return Token.new(T_QUOTED,
                               $+.gsub(/\\(["\\])/n, "\\1"))
            elsif $5
              len = $+.to_i
              val = @str[@pos, len]
              @pos += len
              return Token.new(T_LITERAL, val)
            elsif $6
              return Token.new(T_LPAR, $+)
            elsif $7
              return Token.new(T_RPAR, $+)
            else
              parse_error("[Net::IMAP BUG] DATA_REGEXP is invalid")
            end
          else
            @str.index(/\S*/n, @pos)
            parse_error("unknown token - %s", $&.dump)
          end
        when EXPR_TEXT
          if @str.index(TEXT_REGEXP, @pos)
            @pos = $~.end(0)
            if $1
              return Token.new(T_TEXT, $+)
            else
              parse_error("[Net::IMAP BUG] TEXT_REGEXP is invalid")
            end
          else
            @str.index(/\S*/n, @pos)
            parse_error("unknown token - %s", $&.dump)
          end
        when EXPR_RTEXT
          if @str.index(RTEXT_REGEXP, @pos)
            @pos = $~.end(0)
            if $1
              return Token.new(T_LBRA, $+)
            elsif $2
              return Token.new(T_TEXT, $+)
            else
              parse_error("[Net::IMAP BUG] RTEXT_REGEXP is invalid")
            end
          else
            @str.index(/\S*/n, @pos)
            parse_error("unknown token - %s", $&.dump)
          end
        when EXPR_CTEXT
          if @str.index(CTEXT_REGEXP, @pos)
            @pos = $~.end(0)
            if $1
              return Token.new(T_TEXT, $+)
            else
              parse_error("[Net::IMAP BUG] CTEXT_REGEXP is invalid")
            end
          else
            @str.index(/\S*/n, @pos) #/
            parse_error("unknown token - %s", $&.dump)
          end
        else
          parse_error("invalid @lex_state - %s", @lex_state.inspect)
        end
      end

      def parse_error(fmt, *args)
        if IMAP.debug
          $stderr.printf("@str: %s\n", @str.dump)
          $stderr.printf("@pos: %d\n", @pos)
          $stderr.printf("@lex_state: %s\n", @lex_state)
          if @token
            $stderr.printf("@token.symbol: %s\n", @token.symbol)
            $stderr.printf("@token.value: %s\n", @token.value.inspect)
          end
        end
        raise ResponseParseError, format(fmt, *args)
      end
    end

    # Authenticator for the "LOGIN" authentication type.  See
    # #authenticate().
    class LoginAuthenticator
      def process(data)
        case @state
        when STATE_USER
          @state = STATE_PASSWORD
          return @user
        when STATE_PASSWORD
          return @password
        end
      end

      private

      STATE_USER = :USER
      STATE_PASSWORD = :PASSWORD

      def initialize(user, password)
        @user = user
        @password = password
        @state = STATE_USER
      end
    end
    add_authenticator "LOGIN", LoginAuthenticator

    # Authenticator for the "PLAIN" authentication type.  See
    # #authenticate().
    class PlainAuthenticator
      def process(data)
        return "\0#{@user}\0#{@password}"
      end

      private

      def initialize(user, password)
        @user = user
        @password = password
      end
    end
    add_authenticator "PLAIN", PlainAuthenticator

    # Authenticator for the "CRAM-MD5" authentication type.  See
    # #authenticate().
    class CramMD5Authenticator
      def process(challenge)
        digest = hmac_md5(challenge, @password)
        return @user + " " + digest
      end

      private

      def initialize(user, password)
        @user = user
        @password = password
      end

      def hmac_md5(text, key)
        if key.length > 64
          key = Digest::MD5.digest(key)
        end

        k_ipad = key + "\0" * (64 - key.length)
        k_opad = key + "\0" * (64 - key.length)
        for i in 0..63
          k_ipad[i] = (k_ipad[i].ord ^ 0x36).chr
          k_opad[i] = (k_opad[i].ord ^ 0x5c).chr
        end

        digest = Digest::MD5.digest(k_ipad + text)

        return Digest::MD5.hexdigest(k_opad + digest)
      end
    end
    add_authenticator "CRAM-MD5", CramMD5Authenticator

    # Authenticator for the "DIGEST-MD5" authentication type.  See
    # #authenticate().
    class DigestMD5Authenticator
      def process(challenge)
        case @stage
        when STAGE_ONE
          @stage = STAGE_TWO
          sparams = {}
          c = StringScanner.new(challenge)
          while c.scan(/(?:\s*,)?\s*(\w+)=("(?:[^\\"]+|\\.)*"|[^,]+)\s*/)
            k, v = c[1], c[2]
            if v =~ /^"(.*)"$/
              v = $1
              if v =~ /,/
                v = v.split(',')
              end
            end
            sparams[k] = v
          end

          raise DataFormatError, "Bad Challenge: '#{challenge}'" unless c.rest.size == 0
          raise Error, "Server does not support auth (qop = #{sparams['qop'].join(',')})" unless sparams['qop'].include?("auth")

          response = {
            :nonce => sparams['nonce'],
            :username => @user,
            :realm => sparams['realm'],
            :cnonce => Digest::MD5.hexdigest("%.15f:%.15f:%d" % [Time.now.to_f, rand, Process.pid.to_s]),
            :'digest-uri' => 'imap/' + sparams['realm'],
            :qop => 'auth',
            :maxbuf => 65535,
            :nc => "%08d" % nc(sparams['nonce']),
            :charset => sparams['charset'],
          }

          response[:authzid] = @authname unless @authname.nil?

          # now, the real thing
          a0 = Digest::MD5.digest( [ response.values_at(:username, :realm), @password ].join(':') )

          a1 = [ a0, response.values_at(:nonce,:cnonce) ].join(':')
          a1 << ':' + response[:authzid] unless response[:authzid].nil?

          a2 = "AUTHENTICATE:" + response[:'digest-uri']
          a2 << ":00000000000000000000000000000000" if response[:qop] and response[:qop] =~ /^auth-(?:conf|int)$/

          response[:response] = Digest::MD5.hexdigest(
            [
             Digest::MD5.hexdigest(a1),
             response.values_at(:nonce, :nc, :cnonce, :qop),
             Digest::MD5.hexdigest(a2)
            ].join(':')
          )

          return response.keys.map {|key| qdval(key.to_s, response[key]) }.join(',')
        when STAGE_TWO
          @stage = nil
          # if at the second stage, return an empty string
          if challenge =~ /rspauth=/
            return ''
          else
            raise ResponseParseError, challenge
          end
        else
          raise ResponseParseError, challenge
        end
      end

      def initialize(user, password, authname = nil)
        @user, @password, @authname = user, password, authname
        @nc, @stage = {}, STAGE_ONE
      end

      private

      STAGE_ONE = :stage_one
      STAGE_TWO = :stage_two

      def nc(nonce)
        if @nc.has_key? nonce
          @nc[nonce] = @nc[nonce] + 1
        else
          @nc[nonce] = 1
        end
        return @nc[nonce]
      end

      # some responses need quoting
      def qdval(k, v)
        return if k.nil? or v.nil?
        if %w"username authzid realm nonce cnonce digest-uri qop".include? k
          v.gsub!(/([\\"])/, "\\\1")
          return '%s="%s"' % [k, v]
        else
          return '%s=%s' % [k, v]
        end
      end
    end
    add_authenticator "DIGEST-MD5", DigestMD5Authenticator

    # Superclass of IMAP errors.
    class Error < StandardError
    end

    # Error raised when data is in the incorrect format.
    class DataFormatError < Error
    end

    # Error raised when a response from the server is non-parseable.
    class ResponseParseError < Error
    end

    # Superclass of all errors used to encapsulate "fail" responses
    # from the server.
    class ResponseError < Error

      # The response that caused this error
      attr_accessor :response

      def initialize(response)
        @response = response

        super @response.data.text
      end

    end

    # Error raised upon a "NO" response from the server, indicating
    # that the client command could not be completed successfully.
    class NoResponseError < ResponseError
    end

    # Error raised upon a "BAD" response from the server, indicating
    # that the client command violated the IMAP protocol, or an internal
    # server failure has occurred.
    class BadResponseError < ResponseError
    end

    # Error raised upon a "BYE" response from the server, indicating
    # that the client is not being allowed to login, or has been timed
    # out due to inactivity.
    class ByeResponseError < ResponseError
    end

    # Error raised upon an unknown response from the server.
    class UnknownResponseError < ResponseError
    end

    RESPONSE_ERRORS = Hash.new(ResponseError)
    RESPONSE_ERRORS["NO"] = NoResponseError
    RESPONSE_ERRORS["BAD"] = BadResponseError

    # Error raised when too many flags are interned to symbols.
    class FlagCountError < Error
    end
  end
end
# frozen_string_literal: false
# HTTP response class.
#
# This class wraps together the response header and the response body (the
# entity requested).
#
# It mixes in the HTTPHeader module, which provides access to response
# header values both via hash-like methods and via individual readers.
#
# Note that each possible HTTP response code defines its own
# HTTPResponse subclass. All classes are defined under the Net module.
# Indentation indicates inheritance.  For a list of the classes see Net::HTTP.
#
# Correspondence <code>HTTP code => class</code> is stored in CODE_TO_OBJ
# constant:
#
#    Net::HTTPResponse::CODE_TO_OBJ['404'] #=> Net::HTTPNotFound
#
class Net::HTTPResponse
  class << self
    # true if the response has a body.
    def body_permitted?
      self::HAS_BODY
    end

    def exception_type   # :nodoc: internal use only
      self::EXCEPTION_TYPE
    end

    def read_new(sock)   #:nodoc: internal use only
      httpv, code, msg = read_status_line(sock)
      res = response_class(code).new(httpv, code, msg)
      each_response_header(sock) do |k,v|
        res.add_field k, v
      end
      res
    end

    private

    def read_status_line(sock)
      str = sock.readline
      m = /\AHTTP(?:\/(\d+\.\d+))?\s+(\d\d\d)(?:\s+(.*))?\z/in.match(str) or
        raise Net::HTTPBadResponse, "wrong status line: #{str.dump}"
      m.captures
    end

    def response_class(code)
      CODE_TO_OBJ[code] or
      CODE_CLASS_TO_OBJ[code[0,1]] or
      Net::HTTPUnknownResponse
    end

    def each_response_header(sock)
      key = value = nil
      while true
        line = sock.readuntil("\n", true).sub(/\s+\z/, '')
        break if line.empty?
        if line[0] == ?\s or line[0] == ?\t and value
          value << ' ' unless value.empty?
          value << line.strip
        else
          yield key, value if key
          key, value = line.strip.split(/\s*:\s*/, 2)
          raise Net::HTTPBadResponse, 'wrong header line format' if value.nil?
        end
      end
      yield key, value if key
    end
  end

  # next is to fix bug in RDoc, where the private inside class << self
  # spills out.
  public

  include Net::HTTPHeader

  def initialize(httpv, code, msg)   #:nodoc: internal use only
    @http_version = httpv
    @code         = code
    @message      = msg
    initialize_http_header nil
    @body = nil
    @read = false
    @uri  = nil
    @decode_content = false
  end

  # The HTTP version supported by the server.
  attr_reader :http_version

  # The HTTP result code string. For example, '302'.  You can also
  # determine the response type by examining which response subclass
  # the response object is an instance of.
  attr_reader :code

  # The HTTP result message sent by the server. For example, 'Not Found'.
  attr_reader :message
  alias msg message   # :nodoc: obsolete

  # The URI used to fetch this response.  The response URI is only available
  # if a URI was used to create the request.
  attr_reader :uri

  # Set to true automatically when the request did not contain an
  # Accept-Encoding header from the user.
  attr_accessor :decode_content

  def inspect
    "#<#{self.class} #{@code} #{@message} readbody=#{@read}>"
  end

  #
  # response <-> exception relationship
  #

  def code_type   #:nodoc:
    self.class
  end

  def error!   #:nodoc:
    message = @code
    message += ' ' + @message.dump if @message
    raise error_type().new(message, self)
  end

  def error_type   #:nodoc:
    self.class::EXCEPTION_TYPE
  end

  # Raises an HTTP error if the response is not 2xx (success).
  def value
    error! unless self.kind_of?(Net::HTTPSuccess)
  end

  def uri= uri # :nodoc:
    @uri = uri.dup if uri
  end

  #
  # header (for backward compatibility only; DO NOT USE)
  #

  def response   #:nodoc:
    warn "Net::HTTPResponse#response is obsolete", uplevel: 1 if $VERBOSE
    self
  end

  def header   #:nodoc:
    warn "Net::HTTPResponse#header is obsolete", uplevel: 1 if $VERBOSE
    self
  end

  def read_header   #:nodoc:
    warn "Net::HTTPResponse#read_header is obsolete", uplevel: 1 if $VERBOSE
    self
  end

  #
  # body
  #

  def reading_body(sock, reqmethodallowbody)  #:nodoc: internal use only
    @socket = sock
    @body_exist = reqmethodallowbody && self.class.body_permitted?
    begin
      yield
      self.body   # ensure to read body
    ensure
      @socket = nil
    end
  end

  # Gets the entity body returned by the remote HTTP server.
  #
  # If a block is given, the body is passed to the block, and
  # the body is provided in fragments, as it is read in from the socket.
  #
  # If +dest+ argument is given, response is read into that variable,
  # with <code>dest#<<</code> method (it could be String or IO, or any
  # other object responding to <code><<</code>).
  #
  # Calling this method a second or subsequent time for the same
  # HTTPResponse object will return the value already read.
  #
  #   http.request_get('/index.html') {|res|
  #     puts res.read_body
  #   }
  #
  #   http.request_get('/index.html') {|res|
  #     p res.read_body.object_id   # 538149362
  #     p res.read_body.object_id   # 538149362
  #   }
  #
  #   # using iterator
  #   http.request_get('/index.html') {|res|
  #     res.read_body do |segment|
  #       print segment
  #     end
  #   }
  #
  def read_body(dest = nil, &block)
    if @read
      raise IOError, "#{self.class}\#read_body called twice" if dest or block
      return @body
    end
    to = procdest(dest, block)
    stream_check
    if @body_exist
      read_body_0 to
      @body = to
    else
      @body = nil
    end
    @read = true

    @body
  end

  # Returns the full entity body.
  #
  # Calling this method a second or subsequent time will return the
  # string already read.
  #
  #   http.request_get('/index.html') {|res|
  #     puts res.body
  #   }
  #
  #   http.request_get('/index.html') {|res|
  #     p res.body.object_id   # 538149362
  #     p res.body.object_id   # 538149362
  #   }
  #
  def body
    read_body()
  end

  # Because it may be necessary to modify the body, Eg, decompression
  # this method facilitates that.
  def body=(value)
    @body = value
  end

  alias entity body   #:nodoc: obsolete

  private

  ##
  # Checks for a supported Content-Encoding header and yields an Inflate
  # wrapper for this response's socket when zlib is present.  If the
  # Content-Encoding is not supported or zlib is missing, the plain socket is
  # yielded.
  #
  # If a Content-Range header is present, a plain socket is yielded as the
  # bytes in the range may not be a complete deflate block.

  def inflater # :nodoc:
    return yield @socket unless Net::HTTP::HAVE_ZLIB
    return yield @socket unless @decode_content
    return yield @socket if self['content-range']

    v = self['content-encoding']
    case v&.downcase
    when 'deflate', 'gzip', 'x-gzip' then
      self.delete 'content-encoding'

      inflate_body_io = Inflater.new(@socket)

      begin
        yield inflate_body_io
        success = true
      ensure
        begin
          inflate_body_io.finish
        rescue => err
          # Ignore #finish's error if there is an exception from yield
          raise err if success
        end
      end
    when 'none', 'identity' then
      self.delete 'content-encoding'

      yield @socket
    else
      yield @socket
    end
  end

  def read_body_0(dest)
    inflater do |inflate_body_io|
      if chunked?
        read_chunked dest, inflate_body_io
        return
      end

      @socket = inflate_body_io

      clen = content_length()
      if clen
        @socket.read clen, dest, true   # ignore EOF
        return
      end
      clen = range_length()
      if clen
        @socket.read clen, dest
        return
      end
      @socket.read_all dest
    end
  end

  ##
  # read_chunked reads from +@socket+ for chunk-size, chunk-extension, CRLF,
  # etc. and +chunk_data_io+ for chunk-data which may be deflate or gzip
  # encoded.
  #
  # See RFC 2616 section 3.6.1 for definitions

  def read_chunked(dest, chunk_data_io) # :nodoc:
    total = 0
    while true
      line = @socket.readline
      hexlen = line.slice(/[0-9a-fA-F]+/) or
          raise Net::HTTPBadResponse, "wrong chunk size line: #{line}"
      len = hexlen.hex
      break if len == 0
      begin
        chunk_data_io.read len, dest
      ensure
        total += len
        @socket.read 2   # \r\n
      end
    end
    until @socket.readline.empty?
      # none
    end
  end

  def stream_check
    raise IOError, 'attempt to read body out of block' if @socket.closed?
  end

  def procdest(dest, block)
    raise ArgumentError, 'both arg and block given for HTTP method' if
      dest and block
    if block
      Net::ReadAdapter.new(block)
    else
      dest || ''
    end
  end

  ##
  # Inflater is a wrapper around Net::BufferedIO that transparently inflates
  # zlib and gzip streams.

  class Inflater # :nodoc:

    ##
    # Creates a new Inflater wrapping +socket+

    def initialize socket
      @socket = socket
      # zlib with automatic gzip detection
      @inflate = Zlib::Inflate.new(32 + Zlib::MAX_WBITS)
    end

    ##
    # Finishes the inflate stream.

    def finish
      return if @inflate.total_in == 0
      @inflate.finish
    end

    ##
    # Returns a Net::ReadAdapter that inflates each read chunk into +dest+.
    #
    # This allows a large response body to be inflated without storing the
    # entire body in memory.

    def inflate_adapter(dest)
      if dest.respond_to?(:set_encoding)
        dest.set_encoding(Encoding::ASCII_8BIT)
      elsif dest.respond_to?(:force_encoding)
        dest.force_encoding(Encoding::ASCII_8BIT)
      end
      block = proc do |compressed_chunk|
        @inflate.inflate(compressed_chunk) do |chunk|
          compressed_chunk.clear
          dest << chunk
        end
      end

      Net::ReadAdapter.new(block)
    end

    ##
    # Reads +clen+ bytes from the socket, inflates them, then writes them to
    # +dest+.  +ignore_eof+ is passed down to Net::BufferedIO#read
    #
    # Unlike Net::BufferedIO#read, this method returns more than +clen+ bytes.
    # At this time there is no way for a user of Net::HTTPResponse to read a
    # specific number of bytes from the HTTP response body, so this internal
    # API does not return the same number of bytes as were requested.
    #
    # See https://bugs.ruby-lang.org/issues/6492 for further discussion.

    def read clen, dest, ignore_eof = false
      temp_dest = inflate_adapter(dest)

      @socket.read clen, temp_dest, ignore_eof
    end

    ##
    # Reads the rest of the socket, inflates it, then writes it to +dest+.

    def read_all dest
      temp_dest = inflate_adapter(dest)

      @socket.read_all temp_dest
    end

  end

end

# frozen_string_literal: false
#
# HTTP/1.1 methods --- RFC2616
#

# See Net::HTTPGenericRequest for attributes and methods.
# See Net::HTTP for usage examples.
class Net::HTTP::Get < Net::HTTPRequest
  METHOD = 'GET'
  REQUEST_HAS_BODY  = false
  RESPONSE_HAS_BODY = true
end

# See Net::HTTPGenericRequest for attributes and methods.
# See Net::HTTP for usage examples.
class Net::HTTP::Head < Net::HTTPRequest
  METHOD = 'HEAD'
  REQUEST_HAS_BODY = false
  RESPONSE_HAS_BODY = false
end

# See Net::HTTPGenericRequest for attributes and methods.
# See Net::HTTP for usage examples.
class Net::HTTP::Post < Net::HTTPRequest
  METHOD = 'POST'
  REQUEST_HAS_BODY = true
  RESPONSE_HAS_BODY = true
end

# See Net::HTTPGenericRequest for attributes and methods.
# See Net::HTTP for usage examples.
class Net::HTTP::Put < Net::HTTPRequest
  METHOD = 'PUT'
  REQUEST_HAS_BODY = true
  RESPONSE_HAS_BODY = true
end

# See Net::HTTPGenericRequest for attributes and methods.
# See Net::HTTP for usage examples.
class Net::HTTP::Delete < Net::HTTPRequest
  METHOD = 'DELETE'
  REQUEST_HAS_BODY = false
  RESPONSE_HAS_BODY = true
end

# See Net::HTTPGenericRequest for attributes and methods.
class Net::HTTP::Options < Net::HTTPRequest
  METHOD = 'OPTIONS'
  REQUEST_HAS_BODY = false
  RESPONSE_HAS_BODY = true
end

# See Net::HTTPGenericRequest for attributes and methods.
class Net::HTTP::Trace < Net::HTTPRequest
  METHOD = 'TRACE'
  REQUEST_HAS_BODY = false
  RESPONSE_HAS_BODY = true
end

#
# PATCH method --- RFC5789
#

# See Net::HTTPGenericRequest for attributes and methods.
class Net::HTTP::Patch < Net::HTTPRequest
  METHOD = 'PATCH'
  REQUEST_HAS_BODY = true
  RESPONSE_HAS_BODY = true
end

#
# WebDAV methods --- RFC2518
#

# See Net::HTTPGenericRequest for attributes and methods.
class Net::HTTP::Propfind < Net::HTTPRequest
  METHOD = 'PROPFIND'
  REQUEST_HAS_BODY = true
  RESPONSE_HAS_BODY = true
end

# See Net::HTTPGenericRequest for attributes and methods.
class Net::HTTP::Proppatch < Net::HTTPRequest
  METHOD = 'PROPPATCH'
  REQUEST_HAS_BODY = true
  RESPONSE_HAS_BODY = true
end

# See Net::HTTPGenericRequest for attributes and methods.
class Net::HTTP::Mkcol < Net::HTTPRequest
  METHOD = 'MKCOL'
  REQUEST_HAS_BODY = true
  RESPONSE_HAS_BODY = true
end

# See Net::HTTPGenericRequest for attributes and methods.
class Net::HTTP::Copy < Net::HTTPRequest
  METHOD = 'COPY'
  REQUEST_HAS_BODY = false
  RESPONSE_HAS_BODY = true
end

# See Net::HTTPGenericRequest for attributes and methods.
class Net::HTTP::Move < Net::HTTPRequest
  METHOD = 'MOVE'
  REQUEST_HAS_BODY = false
  RESPONSE_HAS_BODY = true
end

# See Net::HTTPGenericRequest for attributes and methods.
class Net::HTTP::Lock < Net::HTTPRequest
  METHOD = 'LOCK'
  REQUEST_HAS_BODY = true
  RESPONSE_HAS_BODY = true
end

# See Net::HTTPGenericRequest for attributes and methods.
class Net::HTTP::Unlock < Net::HTTPRequest
  METHOD = 'UNLOCK'
  REQUEST_HAS_BODY = true
  RESPONSE_HAS_BODY = true
end

# frozen_string_literal: false
module Net::HTTP::ProxyDelta   #:nodoc: internal use only
  private

  def conn_address
    proxy_address()
  end

  def conn_port
    proxy_port()
  end

  def edit_path(path)
    use_ssl? ? path : "http://#{addr_port()}#{path}"
  end
end

# frozen_string_literal: true

require_relative '../http'

if $0 == __FILE__
  require 'open-uri'
  IO.foreach(__FILE__) do |line|
    puts line
    break if line.start_with?('end')
  end
  puts
  puts "Net::HTTP::STATUS_CODES = {"
  url = "https://www.iana.org/assignments/http-status-codes/http-status-codes-1.csv"
  URI(url).read.each_line do |line|
    code, mes, = line.split(',')
    next if ['(Unused)', 'Unassigned', 'Description'].include?(mes)
    puts "  #{code} => '#{mes}',"
  end
  puts "}"
end

Net::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',
  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',
  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',
  510 => 'Not Extended',
  511 => 'Network Authentication Required',
}
# frozen_string_literal: false
# Net::HTTP exception class.
# You cannot use Net::HTTPExceptions directly; instead, you must use
# its subclasses.
module Net::HTTPExceptions
  def initialize(msg, res)   #:nodoc:
    super msg
    @response = res
  end
  attr_reader :response
  alias data response    #:nodoc: obsolete
end
class Net::HTTPError < Net::ProtocolError
  include Net::HTTPExceptions
end
class Net::HTTPRetriableError < Net::ProtoRetriableError
  include Net::HTTPExceptions
end
class Net::HTTPServerException < Net::ProtoServerError
  # We cannot use the name "HTTPServerError", it is the name of the response.
  include Net::HTTPExceptions
end

# for compatibility
Net::HTTPClientException = Net::HTTPServerException

class Net::HTTPFatalError < Net::ProtoFatalError
  include Net::HTTPExceptions
end

module Net
  deprecate_constant(:HTTPServerException)
end
# frozen_string_literal: true
# :stopdoc:
# https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
class Net::HTTPUnknownResponse < Net::HTTPResponse
  HAS_BODY = true
  EXCEPTION_TYPE = Net::HTTPError
end
class Net::HTTPInformation < Net::HTTPResponse           # 1xx
  HAS_BODY = false
  EXCEPTION_TYPE = Net::HTTPError
end
class Net::HTTPSuccess < Net::HTTPResponse               # 2xx
  HAS_BODY = true
  EXCEPTION_TYPE = Net::HTTPError
end
class Net::HTTPRedirection < Net::HTTPResponse           # 3xx
  HAS_BODY = true
  EXCEPTION_TYPE = Net::HTTPRetriableError
end
class Net::HTTPClientError < Net::HTTPResponse           # 4xx
  HAS_BODY = true
  EXCEPTION_TYPE = Net::HTTPClientException   # for backward compatibility
end
class Net::HTTPServerError < Net::HTTPResponse           # 5xx
  HAS_BODY = true
  EXCEPTION_TYPE = Net::HTTPFatalError    # for backward compatibility
end

class Net::HTTPContinue < Net::HTTPInformation           # 100
  HAS_BODY = false
end
class Net::HTTPSwitchProtocol < Net::HTTPInformation     # 101
  HAS_BODY = false
end
class Net::HTTPProcessing < Net::HTTPInformation         # 102
  HAS_BODY = false
end
class Net::HTTPEarlyHints < Net::HTTPInformation         # 103 - RFC 8297
  HAS_BODY = false
end

class Net::HTTPOK < Net::HTTPSuccess                            # 200
  HAS_BODY = true
end
class Net::HTTPCreated < Net::HTTPSuccess                       # 201
  HAS_BODY = true
end
class Net::HTTPAccepted < Net::HTTPSuccess                      # 202
  HAS_BODY = true
end
class Net::HTTPNonAuthoritativeInformation < Net::HTTPSuccess   # 203
  HAS_BODY = true
end
class Net::HTTPNoContent < Net::HTTPSuccess                     # 204
  HAS_BODY = false
end
class Net::HTTPResetContent < Net::HTTPSuccess                  # 205
  HAS_BODY = false
end
class Net::HTTPPartialContent < Net::HTTPSuccess                # 206
  HAS_BODY = true
end
class Net::HTTPMultiStatus < Net::HTTPSuccess                   # 207 - RFC 4918
  HAS_BODY = true
end
class Net::HTTPAlreadyReported < Net::HTTPSuccess               # 208 - RFC 5842
  HAS_BODY = true
end
class Net::HTTPIMUsed < Net::HTTPSuccess                        # 226 - RFC 3229
  HAS_BODY = true
end

class Net::HTTPMultipleChoices < Net::HTTPRedirection    # 300
  HAS_BODY = true
end
Net::HTTPMultipleChoice = Net::HTTPMultipleChoices
class Net::HTTPMovedPermanently < Net::HTTPRedirection   # 301
  HAS_BODY = true
end
class Net::HTTPFound < Net::HTTPRedirection              # 302
  HAS_BODY = true
end
Net::HTTPMovedTemporarily = Net::HTTPFound
class Net::HTTPSeeOther < Net::HTTPRedirection           # 303
  HAS_BODY = true
end
class Net::HTTPNotModified < Net::HTTPRedirection        # 304
  HAS_BODY = false
end
class Net::HTTPUseProxy < Net::HTTPRedirection           # 305
  HAS_BODY = false
end
# 306 Switch Proxy - no longer unused
class Net::HTTPTemporaryRedirect < Net::HTTPRedirection  # 307
  HAS_BODY = true
end
class Net::HTTPPermanentRedirect < Net::HTTPRedirection  # 308
  HAS_BODY = true
end

class Net::HTTPBadRequest < Net::HTTPClientError                    # 400
  HAS_BODY = true
end
class Net::HTTPUnauthorized < Net::HTTPClientError                  # 401
  HAS_BODY = true
end
class Net::HTTPPaymentRequired < Net::HTTPClientError               # 402
  HAS_BODY = true
end
class Net::HTTPForbidden < Net::HTTPClientError                     # 403
  HAS_BODY = true
end
class Net::HTTPNotFound < Net::HTTPClientError                      # 404
  HAS_BODY = true
end
class Net::HTTPMethodNotAllowed < Net::HTTPClientError              # 405
  HAS_BODY = true
end
class Net::HTTPNotAcceptable < Net::HTTPClientError                 # 406
  HAS_BODY = true
end
class Net::HTTPProxyAuthenticationRequired < Net::HTTPClientError   # 407
  HAS_BODY = true
end
class Net::HTTPRequestTimeout < Net::HTTPClientError                # 408
  HAS_BODY = true
end
Net::HTTPRequestTimeOut = Net::HTTPRequestTimeout
class Net::HTTPConflict < Net::HTTPClientError                      # 409
  HAS_BODY = true
end
class Net::HTTPGone < Net::HTTPClientError                          # 410
  HAS_BODY = true
end
class Net::HTTPLengthRequired < Net::HTTPClientError                # 411
  HAS_BODY = true
end
class Net::HTTPPreconditionFailed < Net::HTTPClientError            # 412
  HAS_BODY = true
end
class Net::HTTPPayloadTooLarge < Net::HTTPClientError               # 413
  HAS_BODY = true
end
Net::HTTPRequestEntityTooLarge = Net::HTTPPayloadTooLarge
class Net::HTTPURITooLong < Net::HTTPClientError                    # 414
  HAS_BODY = true
end
Net::HTTPRequestURITooLong = Net::HTTPURITooLong
Net::HTTPRequestURITooLarge = Net::HTTPRequestURITooLong
class Net::HTTPUnsupportedMediaType < Net::HTTPClientError          # 415
  HAS_BODY = true
end
class Net::HTTPRangeNotSatisfiable < Net::HTTPClientError           # 416
  HAS_BODY = true
end
Net::HTTPRequestedRangeNotSatisfiable = Net::HTTPRangeNotSatisfiable
class Net::HTTPExpectationFailed < Net::HTTPClientError             # 417
  HAS_BODY = true
end
# 418 I'm a teapot - RFC 2324; a joke RFC
# 420 Enhance Your Calm - Twitter
class Net::HTTPMisdirectedRequest < Net::HTTPClientError            # 421 - RFC 7540
  HAS_BODY = true
end
class Net::HTTPUnprocessableEntity < Net::HTTPClientError           # 422 - RFC 4918
  HAS_BODY = true
end
class Net::HTTPLocked < Net::HTTPClientError                        # 423 - RFC 4918
  HAS_BODY = true
end
class Net::HTTPFailedDependency < Net::HTTPClientError              # 424 - RFC 4918
  HAS_BODY = true
end
# 425 Unordered Collection - existed only in draft
class Net::HTTPUpgradeRequired < Net::HTTPClientError               # 426 - RFC 2817
  HAS_BODY = true
end
class Net::HTTPPreconditionRequired < Net::HTTPClientError          # 428 - RFC 6585
  HAS_BODY = true
end
class Net::HTTPTooManyRequests < Net::HTTPClientError               # 429 - RFC 6585
  HAS_BODY = true
end
class Net::HTTPRequestHeaderFieldsTooLarge < Net::HTTPClientError   # 431 - RFC 6585
  HAS_BODY = true
end
class Net::HTTPUnavailableForLegalReasons < Net::HTTPClientError    # 451 - RFC 7725
  HAS_BODY = true
end
# 444 No Response - Nginx
# 449 Retry With - Microsoft
# 450 Blocked by Windows Parental Controls - Microsoft
# 499 Client Closed Request - Nginx

class Net::HTTPInternalServerError < Net::HTTPServerError           # 500
  HAS_BODY = true
end
class Net::HTTPNotImplemented < Net::HTTPServerError                # 501
  HAS_BODY = true
end
class Net::HTTPBadGateway < Net::HTTPServerError                    # 502
  HAS_BODY = true
end
class Net::HTTPServiceUnavailable < Net::HTTPServerError            # 503
  HAS_BODY = true
end
class Net::HTTPGatewayTimeout < Net::HTTPServerError                # 504
  HAS_BODY = true
end
Net::HTTPGatewayTimeOut = Net::HTTPGatewayTimeout
class Net::HTTPVersionNotSupported < Net::HTTPServerError           # 505
  HAS_BODY = true
end
class Net::HTTPVariantAlsoNegotiates < Net::HTTPServerError         # 506
  HAS_BODY = true
end
class Net::HTTPInsufficientStorage < Net::HTTPServerError           # 507 - RFC 4918
  HAS_BODY = true
end
class Net::HTTPLoopDetected < Net::HTTPServerError                  # 508 - RFC 5842
  HAS_BODY = true
end
# 509 Bandwidth Limit Exceeded - Apache bw/limited extension
class Net::HTTPNotExtended < Net::HTTPServerError                   # 510 - RFC 2774
  HAS_BODY = true
end
class Net::HTTPNetworkAuthenticationRequired < Net::HTTPServerError # 511 - RFC 6585
  HAS_BODY = true
end

class Net::HTTPResponse
  CODE_CLASS_TO_OBJ = {
    '1' => Net::HTTPInformation,
    '2' => Net::HTTPSuccess,
    '3' => Net::HTTPRedirection,
    '4' => Net::HTTPClientError,
    '5' => Net::HTTPServerError
  }
  CODE_TO_OBJ = {
    '100' => Net::HTTPContinue,
    '101' => Net::HTTPSwitchProtocol,
    '102' => Net::HTTPProcessing,
    '103' => Net::HTTPEarlyHints,

    '200' => Net::HTTPOK,
    '201' => Net::HTTPCreated,
    '202' => Net::HTTPAccepted,
    '203' => Net::HTTPNonAuthoritativeInformation,
    '204' => Net::HTTPNoContent,
    '205' => Net::HTTPResetContent,
    '206' => Net::HTTPPartialContent,
    '207' => Net::HTTPMultiStatus,
    '208' => Net::HTTPAlreadyReported,
    '226' => Net::HTTPIMUsed,

    '300' => Net::HTTPMultipleChoices,
    '301' => Net::HTTPMovedPermanently,
    '302' => Net::HTTPFound,
    '303' => Net::HTTPSeeOther,
    '304' => Net::HTTPNotModified,
    '305' => Net::HTTPUseProxy,
    '307' => Net::HTTPTemporaryRedirect,
    '308' => Net::HTTPPermanentRedirect,

    '400' => Net::HTTPBadRequest,
    '401' => Net::HTTPUnauthorized,
    '402' => Net::HTTPPaymentRequired,
    '403' => Net::HTTPForbidden,
    '404' => Net::HTTPNotFound,
    '405' => Net::HTTPMethodNotAllowed,
    '406' => Net::HTTPNotAcceptable,
    '407' => Net::HTTPProxyAuthenticationRequired,
    '408' => Net::HTTPRequestTimeout,
    '409' => Net::HTTPConflict,
    '410' => Net::HTTPGone,
    '411' => Net::HTTPLengthRequired,
    '412' => Net::HTTPPreconditionFailed,
    '413' => Net::HTTPPayloadTooLarge,
    '414' => Net::HTTPURITooLong,
    '415' => Net::HTTPUnsupportedMediaType,
    '416' => Net::HTTPRangeNotSatisfiable,
    '417' => Net::HTTPExpectationFailed,
    '421' => Net::HTTPMisdirectedRequest,
    '422' => Net::HTTPUnprocessableEntity,
    '423' => Net::HTTPLocked,
    '424' => Net::HTTPFailedDependency,
    '426' => Net::HTTPUpgradeRequired,
    '428' => Net::HTTPPreconditionRequired,
    '429' => Net::HTTPTooManyRequests,
    '431' => Net::HTTPRequestHeaderFieldsTooLarge,
    '451' => Net::HTTPUnavailableForLegalReasons,

    '500' => Net::HTTPInternalServerError,
    '501' => Net::HTTPNotImplemented,
    '502' => Net::HTTPBadGateway,
    '503' => Net::HTTPServiceUnavailable,
    '504' => Net::HTTPGatewayTimeout,
    '505' => Net::HTTPVersionNotSupported,
    '506' => Net::HTTPVariantAlsoNegotiates,
    '507' => Net::HTTPInsufficientStorage,
    '508' => Net::HTTPLoopDetected,
    '510' => Net::HTTPNotExtended,
    '511' => Net::HTTPNetworkAuthenticationRequired,
  }
end

# :startdoc:
# frozen_string_literal: false
# The HTTPHeader module defines methods for reading and writing
# HTTP headers.
#
# It is used as a mixin by other classes, to provide hash-like
# access to HTTP header values. Unlike raw hash access, HTTPHeader
# provides access via case-insensitive keys. It also provides
# methods for accessing commonly-used HTTP header values in more
# convenient formats.
#
module Net::HTTPHeader
  MAX_KEY_LENGTH = 1024
  MAX_FIELD_LENGTH = 65536

  def initialize_http_header(initheader)
    @header = {}
    return unless initheader
    initheader.each do |key, value|
      warn "net/http: duplicated HTTP header: #{key}", uplevel: 3 if key?(key) and $VERBOSE
      if value.nil?
        warn "net/http: nil HTTP header: #{key}", uplevel: 3 if $VERBOSE
      else
        value = value.strip # raise error for invalid byte sequences
        if key.to_s.bytesize > MAX_KEY_LENGTH
          raise ArgumentError, "too long (#{key.bytesize} bytes) header: #{key[0, 30].inspect}..."
        end
        if value.to_s.bytesize > MAX_FIELD_LENGTH
          raise ArgumentError, "header #{key} has too long field vallue: #{value.bytesize}"
        end
        if value.count("\r\n") > 0
          raise ArgumentError, "header #{key} has field value #{value.inspect}, this cannot include CR/LF"
        end
        @header[key.downcase.to_s] = [value]
      end
    end
  end

  def size   #:nodoc: obsolete
    @header.size
  end

  alias length size   #:nodoc: obsolete

  # Returns the header field corresponding to the case-insensitive key.
  # For example, a key of "Content-Type" might return "text/html"
  def [](key)
    a = @header[key.downcase.to_s] or return nil
    a.join(', ')
  end

  # Sets the header field corresponding to the case-insensitive key.
  def []=(key, val)
    unless val
      @header.delete key.downcase.to_s
      return val
    end
    set_field(key, val)
  end

  # [Ruby 1.8.3]
  # Adds a value to a named header field, instead of replacing its value.
  # Second argument +val+ must be a String.
  # See also #[]=, #[] and #get_fields.
  #
  #   request.add_field 'X-My-Header', 'a'
  #   p request['X-My-Header']              #=> "a"
  #   p request.get_fields('X-My-Header')   #=> ["a"]
  #   request.add_field 'X-My-Header', 'b'
  #   p request['X-My-Header']              #=> "a, b"
  #   p request.get_fields('X-My-Header')   #=> ["a", "b"]
  #   request.add_field 'X-My-Header', 'c'
  #   p request['X-My-Header']              #=> "a, b, c"
  #   p request.get_fields('X-My-Header')   #=> ["a", "b", "c"]
  #
  def add_field(key, val)
    stringified_downcased_key = key.downcase.to_s
    if @header.key?(stringified_downcased_key)
      append_field_value(@header[stringified_downcased_key], val)
    else
      set_field(key, val)
    end
  end

  private def set_field(key, val)
    case val
    when Enumerable
      ary = []
      append_field_value(ary, val)
      @header[key.downcase.to_s] = ary
    else
      val = val.to_s # for compatibility use to_s instead of to_str
      if val.b.count("\r\n") > 0
        raise ArgumentError, 'header field value cannot include CR/LF'
      end
      @header[key.downcase.to_s] = [val]
    end
  end

  private def append_field_value(ary, val)
    case val
    when Enumerable
      val.each{|x| append_field_value(ary, x)}
    else
      val = val.to_s
      if /[\r\n]/n.match?(val.b)
        raise ArgumentError, 'header field value cannot include CR/LF'
      end
      ary.push val
    end
  end

  # [Ruby 1.8.3]
  # Returns an array of header field strings corresponding to the
  # case-insensitive +key+.  This method allows you to get duplicated
  # header fields without any processing.  See also #[].
  #
  #   p response.get_fields('Set-Cookie')
  #     #=> ["session=al98axx; expires=Fri, 31-Dec-1999 23:58:23",
  #          "query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"]
  #   p response['Set-Cookie']
  #     #=> "session=al98axx; expires=Fri, 31-Dec-1999 23:58:23, query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"
  #
  def get_fields(key)
    stringified_downcased_key = key.downcase.to_s
    return nil unless @header[stringified_downcased_key]
    @header[stringified_downcased_key].dup
  end

  # Returns the header field corresponding to the case-insensitive key.
  # Returns the default value +args+, or the result of the block, or
  # raises an IndexError if there's no header field named +key+
  # See Hash#fetch
  def fetch(key, *args, &block)   #:yield: +key+
    a = @header.fetch(key.downcase.to_s, *args, &block)
    a.kind_of?(Array) ? a.join(', ') : a
  end

  # Iterates through the header names and values, passing in the name
  # and value to the code block supplied.
  #
  # Returns an enumerator if no block is given.
  #
  # Example:
  #
  #     response.header.each_header {|key,value| puts "#{key} = #{value}" }
  #
  def each_header   #:yield: +key+, +value+
    block_given? or return enum_for(__method__) { @header.size }
    @header.each do |k,va|
      yield k, va.join(', ')
    end
  end

  alias each each_header

  # Iterates through the header names in the header, passing
  # each header name to the code block.
  #
  # Returns an enumerator if no block is given.
  def each_name(&block)   #:yield: +key+
    block_given? or return enum_for(__method__) { @header.size }
    @header.each_key(&block)
  end

  alias each_key each_name

  # Iterates through the header names in the header, passing
  # capitalized header names to the code block.
  #
  # Note that header names are capitalized systematically;
  # capitalization may not match that used by the remote HTTP
  # server in its response.
  #
  # Returns an enumerator if no block is given.
  def each_capitalized_name  #:yield: +key+
    block_given? or return enum_for(__method__) { @header.size }
    @header.each_key do |k|
      yield capitalize(k)
    end
  end

  # Iterates through header values, passing each value to the
  # code block.
  #
  # Returns an enumerator if no block is given.
  def each_value   #:yield: +value+
    block_given? or return enum_for(__method__) { @header.size }
    @header.each_value do |va|
      yield va.join(', ')
    end
  end

  # Removes a header field, specified by case-insensitive key.
  def delete(key)
    @header.delete(key.downcase.to_s)
  end

  # true if +key+ header exists.
  def key?(key)
    @header.key?(key.downcase.to_s)
  end

  # Returns a Hash consisting of header names and array of values.
  # e.g.
  # {"cache-control" => ["private"],
  #  "content-type" => ["text/html"],
  #  "date" => ["Wed, 22 Jun 2005 22:11:50 GMT"]}
  def to_hash
    @header.dup
  end

  # As for #each_header, except the keys are provided in capitalized form.
  #
  # Note that header names are capitalized systematically;
  # capitalization may not match that used by the remote HTTP
  # server in its response.
  #
  # Returns an enumerator if no block is given.
  def each_capitalized
    block_given? or return enum_for(__method__) { @header.size }
    @header.each do |k,v|
      yield capitalize(k), v.join(', ')
    end
  end

  alias canonical_each each_capitalized

  def capitalize(name)
    name.to_s.split(/-/).map {|s| s.capitalize }.join('-')
  end
  private :capitalize

  # Returns an Array of Range objects which represent the Range:
  # HTTP header field, or +nil+ if there is no such header.
  def range
    return nil unless @header['range']

    value = self['Range']
    # byte-range-set = *( "," OWS ) ( byte-range-spec / suffix-byte-range-spec )
    #   *( OWS "," [ OWS ( byte-range-spec / suffix-byte-range-spec ) ] )
    # corrected collected ABNF
    # http://tools.ietf.org/html/draft-ietf-httpbis-p5-range-19#section-5.4.1
    # http://tools.ietf.org/html/draft-ietf-httpbis-p5-range-19#appendix-C
    # http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-19#section-3.2.5
    unless /\Abytes=((?:,[ \t]*)*(?:\d+-\d*|-\d+)(?:[ \t]*,(?:[ \t]*\d+-\d*|-\d+)?)*)\z/ =~ value
      raise Net::HTTPHeaderSyntaxError, "invalid syntax for byte-ranges-specifier: '#{value}'"
    end

    byte_range_set = $1
    result = byte_range_set.split(/,/).map {|spec|
      m = /(\d+)?\s*-\s*(\d+)?/i.match(spec) or
              raise Net::HTTPHeaderSyntaxError, "invalid byte-range-spec: '#{spec}'"
      d1 = m[1].to_i
      d2 = m[2].to_i
      if m[1] and m[2]
        if d1 > d2
          raise Net::HTTPHeaderSyntaxError, "last-byte-pos MUST greater than or equal to first-byte-pos but '#{spec}'"
        end
        d1..d2
      elsif m[1]
        d1..-1
      elsif m[2]
        -d2..-1
      else
        raise Net::HTTPHeaderSyntaxError, 'range is not specified'
      end
    }
    # if result.empty?
    # byte-range-set must include at least one byte-range-spec or suffix-byte-range-spec
    # but above regexp already denies it.
    if result.size == 1 && result[0].begin == 0 && result[0].end == -1
      raise Net::HTTPHeaderSyntaxError, 'only one suffix-byte-range-spec with zero suffix-length'
    end
    result
  end

  # Sets the HTTP Range: header.
  # Accepts either a Range object as a single argument,
  # or a beginning index and a length from that index.
  # Example:
  #
  #   req.range = (0..1023)
  #   req.set_range 0, 1023
  #
  def set_range(r, e = nil)
    unless r
      @header.delete 'range'
      return r
    end
    r = (r...r+e) if e
    case r
    when Numeric
      n = r.to_i
      rangestr = (n > 0 ? "0-#{n-1}" : "-#{-n}")
    when Range
      first = r.first
      last = r.end
      last -= 1 if r.exclude_end?
      if last == -1
        rangestr = (first > 0 ? "#{first}-" : "-#{-first}")
      else
        raise Net::HTTPHeaderSyntaxError, 'range.first is negative' if first < 0
        raise Net::HTTPHeaderSyntaxError, 'range.last is negative' if last < 0
        raise Net::HTTPHeaderSyntaxError, 'must be .first < .last' if first > last
        rangestr = "#{first}-#{last}"
      end
    else
      raise TypeError, 'Range/Integer is required'
    end
    @header['range'] = ["bytes=#{rangestr}"]
    r
  end

  alias range= set_range

  # Returns an Integer object which represents the HTTP Content-Length:
  # header field, or +nil+ if that field was not provided.
  def content_length
    return nil unless key?('Content-Length')
    len = self['Content-Length'].slice(/\d+/) or
        raise Net::HTTPHeaderSyntaxError, 'wrong Content-Length format'
    len.to_i
  end

  def content_length=(len)
    unless len
      @header.delete 'content-length'
      return nil
    end
    @header['content-length'] = [len.to_i.to_s]
  end

  # Returns "true" if the "transfer-encoding" header is present and
  # set to "chunked".  This is an HTTP/1.1 feature, allowing
  # the content to be sent in "chunks" without at the outset
  # stating the entire content length.
  def chunked?
    return false unless @header['transfer-encoding']
    field = self['Transfer-Encoding']
    (/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false
  end

  # Returns a Range object which represents the value of the Content-Range:
  # header field.
  # For a partial entity body, this indicates where this fragment
  # fits inside the full entity body, as range of byte offsets.
  def content_range
    return nil unless @header['content-range']
    m = %r<bytes\s+(\d+)-(\d+)/(\d+|\*)>i.match(self['Content-Range']) or
        raise Net::HTTPHeaderSyntaxError, 'wrong Content-Range format'
    m[1].to_i .. m[2].to_i
  end

  # The length of the range represented in Content-Range: header.
  def range_length
    r = content_range() or return nil
    r.end - r.begin + 1
  end

  # Returns a content type string such as "text/html".
  # This method returns nil if Content-Type: header field does not exist.
  def content_type
    return nil unless main_type()
    if sub_type()
    then "#{main_type()}/#{sub_type()}"
    else main_type()
    end
  end

  # Returns a content type string such as "text".
  # This method returns nil if Content-Type: header field does not exist.
  def main_type
    return nil unless @header['content-type']
    self['Content-Type'].split(';').first.to_s.split('/')[0].to_s.strip
  end

  # Returns a content type string such as "html".
  # This method returns nil if Content-Type: header field does not exist
  # or sub-type is not given (e.g. "Content-Type: text").
  def sub_type
    return nil unless @header['content-type']
    _, sub = *self['Content-Type'].split(';').first.to_s.split('/')
    return nil unless sub
    sub.strip
  end

  # Any parameters specified for the content type, returned as a Hash.
  # For example, a header of Content-Type: text/html; charset=EUC-JP
  # would result in type_params returning {'charset' => 'EUC-JP'}
  def type_params
    result = {}
    list = self['Content-Type'].to_s.split(';')
    list.shift
    list.each do |param|
      k, v = *param.split('=', 2)
      result[k.strip] = v.strip
    end
    result
  end

  # Sets the content type in an HTTP header.
  # The +type+ should be a full HTTP content type, e.g. "text/html".
  # The +params+ are an optional Hash of parameters to add after the
  # content type, e.g. {'charset' => 'iso-8859-1'}
  def set_content_type(type, params = {})
    @header['content-type'] = [type + params.map{|k,v|"; #{k}=#{v}"}.join('')]
  end

  alias content_type= set_content_type

  # Set header fields and a body from HTML form data.
  # +params+ should be an Array of Arrays or
  # a Hash containing HTML form data.
  # Optional argument +sep+ means data record separator.
  #
  # Values are URL encoded as necessary and the content-type is set to
  # application/x-www-form-urlencoded
  #
  # Example:
  #    http.form_data = {"q" => "ruby", "lang" => "en"}
  #    http.form_data = {"q" => ["ruby", "perl"], "lang" => "en"}
  #    http.set_form_data({"q" => "ruby", "lang" => "en"}, ';')
  #
  def set_form_data(params, sep = '&')
    query = URI.encode_www_form(params)
    query.gsub!(/&/, sep) if sep != '&'
    self.body = query
    self.content_type = 'application/x-www-form-urlencoded'
  end

  alias form_data= set_form_data

  # Set an HTML form data set.
  # +params+ :: The form data to set, which should be an enumerable.
  #             See below for more details.
  # +enctype+ :: The content type to use to encode the form submission,
  #              which should be application/x-www-form-urlencoded or
  #              multipart/form-data.
  # +formopt+ :: An options hash, supporting the following options:
  #              :boundary :: The boundary of the multipart message. If
  #                           not given, a random boundary will be used.
  #              :charset :: The charset of the form submission. All
  #                          field names and values of non-file fields
  #                          should be encoded with this charset.
  #
  # Each item of params should respond to +each+ and yield 2-3 arguments,
  # or an array of 2-3 elements. The arguments yielded should be:
  #  * The name of the field.
  #  * The value of the field, it should be a String or a File or IO-like.
  #  * An options hash, supporting the following options, only
  #    used for file uploads:
  #    :filename :: The name of the file to use.
  #    :content_type :: The content type of the uploaded file.
  #
  # Each item is a file field or a normal field.
  # If +value+ is a File object or the +opt+ hash has a :filename key,
  # the item is treated as a file field.
  #
  # If Transfer-Encoding is set as chunked, this sends the request using
  # chunked encoding. Because chunked encoding is HTTP/1.1 feature,
  # you should confirm that the server supports HTTP/1.1 before using
  # chunked encoding.
  #
  # Example:
  #    req.set_form([["q", "ruby"], ["lang", "en"]])
  #
  #    req.set_form({"f"=>File.open('/path/to/filename')},
  #                 "multipart/form-data",
  #                 charset: "UTF-8",
  #    )
  #
  #    req.set_form([["f",
  #                   File.open('/path/to/filename.bar'),
  #                   {filename: "other-filename.foo"}
  #                 ]],
  #                 "multipart/form-data",
  #    )
  #
  # See also RFC 2388, RFC 2616, HTML 4.01, and HTML5
  #
  def set_form(params, enctype='application/x-www-form-urlencoded', formopt={})
    @body_data = params
    @body = nil
    @body_stream = nil
    @form_option = formopt
    case enctype
    when /\Aapplication\/x-www-form-urlencoded\z/i,
      /\Amultipart\/form-data\z/i
      self.content_type = enctype
    else
      raise ArgumentError, "invalid enctype: #{enctype}"
    end
  end

  # Set the Authorization: header for "Basic" authorization.
  def basic_auth(account, password)
    @header['authorization'] = [basic_encode(account, password)]
  end

  # Set Proxy-Authorization: header for "Basic" authorization.
  def proxy_basic_auth(account, password)
    @header['proxy-authorization'] = [basic_encode(account, password)]
  end

  def basic_encode(account, password)
    'Basic ' + ["#{account}:#{password}"].pack('m0')
  end
  private :basic_encode

  def connection_close?
    token = /(?:\A|,)\s*close\s*(?:\z|,)/i
    @header['connection']&.grep(token) {return true}
    @header['proxy-connection']&.grep(token) {return true}
    false
  end

  def connection_keep_alive?
    token = /(?:\A|,)\s*keep-alive\s*(?:\z|,)/i
    @header['connection']&.grep(token) {return true}
    @header['proxy-connection']&.grep(token) {return true}
    false
  end

end
# frozen_string_literal: false
# HTTP request class.
# This class wraps together the request header and the request path.
# You cannot use this class directly. Instead, you should use one of its
# subclasses: Net::HTTP::Get, Net::HTTP::Post, Net::HTTP::Head.
#
class Net::HTTPRequest < Net::HTTPGenericRequest
  # Creates an HTTP request object for +path+.
  #
  # +initheader+ are the default headers to use.  Net::HTTP adds
  # Accept-Encoding to enable compression of the response body unless
  # Accept-Encoding or Range are supplied in +initheader+.

  def initialize(path, initheader = nil)
    super self.class::METHOD,
          self.class::REQUEST_HAS_BODY,
          self.class::RESPONSE_HAS_BODY,
          path, initheader
  end
end

# frozen_string_literal: false
# for backward compatibility

# :enddoc:

class Net::HTTP
  ProxyMod = ProxyDelta
end

module Net
  HTTPSession = Net::HTTP
end

module Net::NetPrivate
  HTTPRequest = ::Net::HTTPRequest
end

Net::HTTPInformationCode  = Net::HTTPInformation
Net::HTTPSuccessCode      = Net::HTTPSuccess
Net::HTTPRedirectionCode  = Net::HTTPRedirection
Net::HTTPRetriableCode    = Net::HTTPRedirection
Net::HTTPClientErrorCode  = Net::HTTPClientError
Net::HTTPFatalErrorCode   = Net::HTTPClientError
Net::HTTPServerErrorCode  = Net::HTTPServerError
Net::HTTPResponceReceiver = Net::HTTPResponse

# frozen_string_literal: false
# HTTPGenericRequest is the parent of the Net::HTTPRequest class.
# Do not use this directly; use a subclass of Net::HTTPRequest.
#
# Mixes in the Net::HTTPHeader module to provide easier access to HTTP headers.
#
class Net::HTTPGenericRequest

  include Net::HTTPHeader

  def initialize(m, reqbody, resbody, uri_or_path, initheader = nil)
    @method = m
    @request_has_body = reqbody
    @response_has_body = resbody

    if URI === uri_or_path then
      raise ArgumentError, "not an HTTP URI" unless URI::HTTP === uri_or_path
      raise ArgumentError, "no host component for URI" unless uri_or_path.hostname
      @uri = uri_or_path.dup
      host = @uri.hostname.dup
      host << ":".freeze << @uri.port.to_s if @uri.port != @uri.default_port
      @path = uri_or_path.request_uri
      raise ArgumentError, "no HTTP request path given" unless @path
    else
      @uri = nil
      host = nil
      raise ArgumentError, "no HTTP request path given" unless uri_or_path
      raise ArgumentError, "HTTP request path is empty" if uri_or_path.empty?
      @path = uri_or_path.dup
    end

    @decode_content = false

    if @response_has_body and Net::HTTP::HAVE_ZLIB then
      if !initheader ||
         !initheader.keys.any? { |k|
           %w[accept-encoding range].include? k.downcase
         } then
        @decode_content = true
        initheader = initheader ? initheader.dup : {}
        initheader["accept-encoding"] =
          "gzip;q=1.0,deflate;q=0.6,identity;q=0.3"
      end
    end

    initialize_http_header initheader
    self['Accept'] ||= '*/*'
    self['User-Agent'] ||= 'Ruby'
    self['Host'] ||= host if host
    @body = nil
    @body_stream = nil
    @body_data = nil
  end

  attr_reader :method
  attr_reader :path
  attr_reader :uri

  # Automatically set to false if the user sets the Accept-Encoding header.
  # This indicates they wish to handle Content-encoding in responses
  # themselves.
  attr_reader :decode_content

  def inspect
    "\#<#{self.class} #{@method}>"
  end

  ##
  # Don't automatically decode response content-encoding if the user indicates
  # they want to handle it.

  def []=(key, val) # :nodoc:
    @decode_content = false if key.downcase == 'accept-encoding'

    super key, val
  end

  def request_body_permitted?
    @request_has_body
  end

  def response_body_permitted?
    @response_has_body
  end

  def body_exist?
    warn "Net::HTTPRequest#body_exist? is obsolete; use response_body_permitted?", uplevel: 1 if $VERBOSE
    response_body_permitted?
  end

  attr_reader :body

  def body=(str)
    @body = str
    @body_stream = nil
    @body_data = nil
    str
  end

  attr_reader :body_stream

  def body_stream=(input)
    @body = nil
    @body_stream = input
    @body_data = nil
    input
  end

  def set_body_internal(str)   #:nodoc: internal use only
    raise ArgumentError, "both of body argument and HTTPRequest#body set" if str and (@body or @body_stream)
    self.body = str if str
    if @body.nil? && @body_stream.nil? && @body_data.nil? && request_body_permitted?
      self.body = ''
    end
  end

  #
  # write
  #

  def exec(sock, ver, path)   #:nodoc: internal use only
    if @body
      send_request_with_body sock, ver, path, @body
    elsif @body_stream
      send_request_with_body_stream sock, ver, path, @body_stream
    elsif @body_data
      send_request_with_body_data sock, ver, path, @body_data
    else
      write_header sock, ver, path
    end
  end

  def update_uri(addr, port, ssl) # :nodoc: internal use only
    # reflect the connection and @path to @uri
    return unless @uri

    if ssl
      scheme = 'https'.freeze
      klass = URI::HTTPS
    else
      scheme = 'http'.freeze
      klass = URI::HTTP
    end

    if host = self['host']
      host.sub!(/:.*/s, ''.freeze)
    elsif host = @uri.host
    else
     host = addr
    end
    # convert the class of the URI
    if @uri.is_a?(klass)
      @uri.host = host
      @uri.port = port
    else
      @uri = klass.new(
        scheme, @uri.userinfo,
        host, port, nil,
        @uri.path, nil, @uri.query, nil)
    end
  end

  private

  class Chunker #:nodoc:
    def initialize(sock)
      @sock = sock
      @prev = nil
    end

    def write(buf)
      # avoid memcpy() of buf, buf can huge and eat memory bandwidth
      rv = buf.bytesize
      @sock.write("#{rv.to_s(16)}\r\n", buf, "\r\n")
      rv
    end

    def finish
      @sock.write("0\r\n\r\n")
    end
  end

  def send_request_with_body(sock, ver, path, body)
    self.content_length = body.bytesize
    delete 'Transfer-Encoding'
    supply_default_content_type
    write_header sock, ver, path
    wait_for_continue sock, ver if sock.continue_timeout
    sock.write body
  end

  def send_request_with_body_stream(sock, ver, path, f)
    unless content_length() or chunked?
      raise ArgumentError,
          "Content-Length not given and Transfer-Encoding is not `chunked'"
    end
    supply_default_content_type
    write_header sock, ver, path
    wait_for_continue sock, ver if sock.continue_timeout
    if chunked?
      chunker = Chunker.new(sock)
      IO.copy_stream(f, chunker)
      chunker.finish
    else
      # copy_stream can sendfile() to sock.io unless we use SSL.
      # If sock.io is an SSLSocket, copy_stream will hit SSL_write()
      IO.copy_stream(f, sock.io)
    end
  end

  def send_request_with_body_data(sock, ver, path, params)
    if /\Amultipart\/form-data\z/i !~ self.content_type
      self.content_type = 'application/x-www-form-urlencoded'
      return send_request_with_body(sock, ver, path, URI.encode_www_form(params))
    end

    opt = @form_option.dup
    require 'securerandom' unless defined?(SecureRandom)
    opt[:boundary] ||= SecureRandom.urlsafe_base64(40)
    self.set_content_type(self.content_type, boundary: opt[:boundary])
    if chunked?
      write_header sock, ver, path
      encode_multipart_form_data(sock, params, opt)
    else
      require 'tempfile'
      file = Tempfile.new('multipart')
      file.binmode
      encode_multipart_form_data(file, params, opt)
      file.rewind
      self.content_length = file.size
      write_header sock, ver, path
      IO.copy_stream(file, sock)
      file.close(true)
    end
  end

  def encode_multipart_form_data(out, params, opt)
    charset = opt[:charset]
    boundary = opt[:boundary]
    require 'securerandom' unless defined?(SecureRandom)
    boundary ||= SecureRandom.urlsafe_base64(40)
    chunked_p = chunked?

    buf = ''
    params.each do |key, value, h={}|
      key = quote_string(key, charset)
      filename =
        h.key?(:filename) ? h[:filename] :
        value.respond_to?(:to_path) ? File.basename(value.to_path) :
        nil

      buf << "--#{boundary}\r\n"
      if filename
        filename = quote_string(filename, charset)
        type = h[:content_type] || 'application/octet-stream'
        buf << "Content-Disposition: form-data; " \
          "name=\"#{key}\"; filename=\"#{filename}\"\r\n" \
          "Content-Type: #{type}\r\n\r\n"
        if !out.respond_to?(:write) || !value.respond_to?(:read)
          # if +out+ is not an IO or +value+ is not an IO
          buf << (value.respond_to?(:read) ? value.read : value)
        elsif value.respond_to?(:size) && chunked_p
          # if +out+ is an IO and +value+ is a File, use IO.copy_stream
          flush_buffer(out, buf, chunked_p)
          out << "%x\r\n" % value.size if chunked_p
          IO.copy_stream(value, out)
          out << "\r\n" if chunked_p
        else
          # +out+ is an IO, and +value+ is not a File but an IO
          flush_buffer(out, buf, chunked_p)
          1 while flush_buffer(out, value.read(4096), chunked_p)
        end
      else
        # non-file field:
        #   HTML5 says, "The parts of the generated multipart/form-data
        #   resource that correspond to non-file fields must not have a
        #   Content-Type header specified."
        buf << "Content-Disposition: form-data; name=\"#{key}\"\r\n\r\n"
        buf << (value.respond_to?(:read) ? value.read : value)
      end
      buf << "\r\n"
    end
    buf << "--#{boundary}--\r\n"
    flush_buffer(out, buf, chunked_p)
    out << "0\r\n\r\n" if chunked_p
  end

  def quote_string(str, charset)
    str = str.encode(charset, fallback:->(c){'&#%d;'%c.encode("UTF-8").ord}) if charset
    str.gsub(/[\\"]/, '\\\\\&')
  end

  def flush_buffer(out, buf, chunked_p)
    return unless buf
    out << "%x\r\n"%buf.bytesize if chunked_p
    out << buf
    out << "\r\n" if chunked_p
    buf.clear
  end

  def supply_default_content_type
    return if content_type()
    warn 'net/http: Content-Type did not set; using application/x-www-form-urlencoded', uplevel: 1 if $VERBOSE
    set_content_type 'application/x-www-form-urlencoded'
  end

  ##
  # Waits up to the continue timeout for a response from the server provided
  # we're speaking HTTP 1.1 and are expecting a 100-continue response.

  def wait_for_continue(sock, ver)
    if ver >= '1.1' and @header['expect'] and
        @header['expect'].include?('100-continue')
      if sock.io.to_io.wait_readable(sock.continue_timeout)
        res = Net::HTTPResponse.read_new(sock)
        unless res.kind_of?(Net::HTTPContinue)
          res.decode_content = @decode_content
          throw :response, res
        end
      end
    end
  end

  def write_header(sock, ver, path)
    reqline = "#{@method} #{path} HTTP/#{ver}"
    if /[\r\n]/ =~ reqline
      raise ArgumentError, "A Request-Line must not contain CR or LF"
    end
    buf = ""
    buf << reqline << "\r\n"
    each_capitalized do |k,v|
      buf << "#{k}: #{v}\r\n"
    end
    buf << "\r\n"
    sock.write buf
  end

end

# frozen_string_literal: true
# :markup: markdown
#
# set.rb - defines the Set class
#
# Copyright (c) 2002-2020 Akinori MUSHA <knu@iDaemons.org>
#
# Documentation by Akinori MUSHA and Gavin Sinclair.
#
# All rights reserved.  You can redistribute and/or modify it under the same
# terms as Ruby.


##
# This library provides the Set class, which deals with a collection
# of unordered values with no duplicates.  It is a hybrid of Array's
# intuitive inter-operation facilities and Hash's fast lookup.
#
# The method `to_set` is added to Enumerable for convenience.
#
# Set implements a collection of unordered values with no duplicates.
# This is a hybrid of Array's intuitive inter-operation facilities and
# Hash's fast lookup.
#
# Set is easy to use with Enumerable objects (implementing `each`).
# Most of the initializer methods and binary operators accept generic
# Enumerable objects besides sets and arrays.  An Enumerable object
# can be converted to Set using the `to_set` method.
#
# Set uses Hash as storage, so you must note the following points:
#
# * Equality of elements is determined according to Object#eql? and
#   Object#hash.  Use Set#compare_by_identity to make a set compare
#   its elements by their identity.
# * Set assumes that the identity of each element does not change
#   while it is stored.  Modifying an element of a set will render the
#   set to an unreliable state.
# * When a string is to be stored, a frozen copy of the string is
#   stored instead unless the original string is already frozen.
#
# ## Comparison
#
# The comparison operators `<`, `>`, `<=`, and `>=` are implemented as
# shorthand for the {proper_,}{subset?,superset?} methods.  The `<=>`
# operator reflects this order, or return `nil` for sets that both
# have distinct elements (`{x, y}` vs. `{x, z}` for example).
#
# ## Example
#
# ```ruby
# require 'set'
# s1 = Set[1, 2]                        #=> #<Set: {1, 2}>
# s2 = [1, 2].to_set                    #=> #<Set: {1, 2}>
# s1 == s2                              #=> true
# s1.add("foo")                         #=> #<Set: {1, 2, "foo"}>
# s1.merge([2, 6])                      #=> #<Set: {1, 2, "foo", 6}>
# s1.subset?(s2)                        #=> false
# s2.subset?(s1)                        #=> true
# ```
#
# ## Contact
#
# - Akinori MUSHA <<knu@iDaemons.org>> (current maintainer)
#
class Set
  include Enumerable

  # Creates a new set containing the given objects.
  #
  #     Set[1, 2]                   # => #<Set: {1, 2}>
  #     Set[1, 2, 1]                # => #<Set: {1, 2}>
  #     Set[1, 'c', :s]             # => #<Set: {1, "c", :s}>
  def self.[](*ary)
    new(ary)
  end

  # Creates a new set containing the elements of the given enumerable
  # object.
  #
  # If a block is given, the elements of enum are preprocessed by the
  # given block.
  #
  #     Set.new([1, 2])                       #=> #<Set: {1, 2}>
  #     Set.new([1, 2, 1])                    #=> #<Set: {1, 2}>
  #     Set.new([1, 'c', :s])                 #=> #<Set: {1, "c", :s}>
  #     Set.new(1..5)                         #=> #<Set: {1, 2, 3, 4, 5}>
  #     Set.new([1, 2, 3]) { |x| x * x }      #=> #<Set: {1, 4, 9}>
  def initialize(enum = nil, &block) # :yields: o
    @hash ||= Hash.new(false)

    enum.nil? and return

    if block
      do_with_enum(enum) { |o| add(block[o]) }
    else
      merge(enum)
    end
  end

  # Makes the set compare its elements by their identity and returns
  # self.  This method may not be supported by all subclasses of Set.
  def compare_by_identity
    if @hash.respond_to?(:compare_by_identity)
      @hash.compare_by_identity
      self
    else
      raise NotImplementedError, "#{self.class.name}\##{__method__} is not implemented"
    end
  end

  # Returns true if the set will compare its elements by their
  # identity.  Also see Set#compare_by_identity.
  def compare_by_identity?
    @hash.respond_to?(:compare_by_identity?) && @hash.compare_by_identity?
  end

  def do_with_enum(enum, &block) # :nodoc:
    if enum.respond_to?(:each_entry)
      enum.each_entry(&block) if block
    elsif enum.respond_to?(:each)
      enum.each(&block) if block
    else
      raise ArgumentError, "value must be enumerable"
    end
  end
  private :do_with_enum

  # Dup internal hash.
  def initialize_dup(orig)
    super
    @hash = orig.instance_variable_get(:@hash).dup
  end

  if Kernel.instance_method(:initialize_clone).arity != 1
    # Clone internal hash.
    def initialize_clone(orig, **options)
      super
      @hash = orig.instance_variable_get(:@hash).clone(**options)
    end
  else
    # Clone internal hash.
    def initialize_clone(orig)
      super
      @hash = orig.instance_variable_get(:@hash).clone
    end
  end

  def freeze    # :nodoc:
    @hash.freeze
    super
  end

  # Returns the number of elements.
  def size
    @hash.size
  end
  alias length size

  # Returns true if the set contains no elements.
  def empty?
    @hash.empty?
  end

  # Removes all elements and returns self.
  #
  #     set = Set[1, 'c', :s]             #=> #<Set: {1, "c", :s}>
  #     set.clear                         #=> #<Set: {}>
  #     set                               #=> #<Set: {}>
  def clear
    @hash.clear
    self
  end

  # Replaces the contents of the set with the contents of the given
  # enumerable object and returns self.
  #
  #     set = Set[1, 'c', :s]             #=> #<Set: {1, "c", :s}>
  #     set.replace([1, 2])               #=> #<Set: {1, 2}>
  #     set                               #=> #<Set: {1, 2}>
  def replace(enum)
    if enum.instance_of?(self.class)
      @hash.replace(enum.instance_variable_get(:@hash))
      self
    else
      do_with_enum(enum)  # make sure enum is enumerable before calling clear
      clear
      merge(enum)
    end
  end

  # Converts the set to an array.  The order of elements is uncertain.
  #
  #     Set[1, 2].to_a                    #=> [1, 2]
  #     Set[1, 'c', :s].to_a              #=> [1, "c", :s]
  def to_a
    @hash.keys
  end

  # Returns self if no arguments are given.  Otherwise, converts the
  # set to another with `klass.new(self, *args, &block)`.
  #
  # In subclasses, returns `klass.new(self, *args, &block)` unless
  # overridden.
  def to_set(klass = Set, *args, &block)
    return self if instance_of?(Set) && klass == Set && block.nil? && args.empty?
    klass.new(self, *args, &block)
  end

  def flatten_merge(set, seen = Set.new) # :nodoc:
    set.each { |e|
      if e.is_a?(Set)
        if seen.include?(e_id = e.object_id)
          raise ArgumentError, "tried to flatten recursive Set"
        end

        seen.add(e_id)
        flatten_merge(e, seen)
        seen.delete(e_id)
      else
        add(e)
      end
    }

    self
  end
  protected :flatten_merge

  # Returns a new set that is a copy of the set, flattening each
  # containing set recursively.
  def flatten
    self.class.new.flatten_merge(self)
  end

  # Equivalent to Set#flatten, but replaces the receiver with the
  # result in place.  Returns nil if no modifications were made.
  def flatten!
    replace(flatten()) if any? { |e| e.is_a?(Set) }
  end

  # Returns true if the set contains the given object.
  #
  # Note that <code>include?</code> and <code>member?</code> do not test member
  # equality using <code>==</code> as do other Enumerables.
  #
  # See also Enumerable#include?
  def include?(o)
    @hash[o]
  end
  alias member? include?

  # Returns true if the set is a superset of the given set.
  def superset?(set)
    case
    when set.instance_of?(self.class) && @hash.respond_to?(:>=)
      @hash >= set.instance_variable_get(:@hash)
    when set.is_a?(Set)
      size >= set.size && set.all? { |o| include?(o) }
    else
      raise ArgumentError, "value must be a set"
    end
  end
  alias >= superset?

  # Returns true if the set is a proper superset of the given set.
  def proper_superset?(set)
    case
    when set.instance_of?(self.class) && @hash.respond_to?(:>)
      @hash > set.instance_variable_get(:@hash)
    when set.is_a?(Set)
      size > set.size && set.all? { |o| include?(o) }
    else
      raise ArgumentError, "value must be a set"
    end
  end
  alias > proper_superset?

  # Returns true if the set is a subset of the given set.
  def subset?(set)
    case
    when set.instance_of?(self.class) && @hash.respond_to?(:<=)
      @hash <= set.instance_variable_get(:@hash)
    when set.is_a?(Set)
      size <= set.size && all? { |o| set.include?(o) }
    else
      raise ArgumentError, "value must be a set"
    end
  end
  alias <= subset?

  # Returns true if the set is a proper subset of the given set.
  def proper_subset?(set)
    case
    when set.instance_of?(self.class) && @hash.respond_to?(:<)
      @hash < set.instance_variable_get(:@hash)
    when set.is_a?(Set)
      size < set.size && all? { |o| set.include?(o) }
    else
      raise ArgumentError, "value must be a set"
    end
  end
  alias < proper_subset?

  # Returns 0 if the set are equal,
  # -1 / +1 if the set is a proper subset / superset of the given set,
  # or nil if they both have unique elements.
  def <=>(set)
    return unless set.is_a?(Set)

    case size <=> set.size
    when -1 then -1 if proper_subset?(set)
    when +1 then +1 if proper_superset?(set)
    else 0 if self.==(set)
    end
  end

  # Returns true if the set and the given set have at least one
  # element in common.
  #
  #     Set[1, 2, 3].intersect? Set[4, 5]   #=> false
  #     Set[1, 2, 3].intersect? Set[3, 4]   #=> true
  def intersect?(set)
    set.is_a?(Set) or raise ArgumentError, "value must be a set"
    if size < set.size
      any? { |o| set.include?(o) }
    else
      set.any? { |o| include?(o) }
    end
  end

  # Returns true if the set and the given set have no element in
  # common.  This method is the opposite of `intersect?`.
  #
  #     Set[1, 2, 3].disjoint? Set[3, 4]   #=> false
  #     Set[1, 2, 3].disjoint? Set[4, 5]   #=> true
  def disjoint?(set)
    !intersect?(set)
  end

  # Calls the given block once for each element in the set, passing
  # the element as parameter.  Returns an enumerator if no block is
  # given.
  def each(&block)
    block or return enum_for(__method__) { size }
    @hash.each_key(&block)
    self
  end

  # Adds the given object to the set and returns self.  Use `merge` to
  # add many elements at once.
  #
  #     Set[1, 2].add(3)                    #=> #<Set: {1, 2, 3}>
  #     Set[1, 2].add([3, 4])               #=> #<Set: {1, 2, [3, 4]}>
  #     Set[1, 2].add(2)                    #=> #<Set: {1, 2}>
  def add(o)
    @hash[o] = true
    self
  end
  alias << add

  # Adds the given object to the set and returns self.  If the
  # object is already in the set, returns nil.
  #
  #     Set[1, 2].add?(3)                    #=> #<Set: {1, 2, 3}>
  #     Set[1, 2].add?([3, 4])               #=> #<Set: {1, 2, [3, 4]}>
  #     Set[1, 2].add?(2)                    #=> nil
  def add?(o)
    add(o) unless include?(o)
  end

  # Deletes the given object from the set and returns self.  Use
  # `subtract` to delete many items at once.
  def delete(o)
    @hash.delete(o)
    self
  end

  # Deletes the given object from the set and returns self.  If the
  # object is not in the set, returns nil.
  def delete?(o)
    delete(o) if include?(o)
  end

  # Deletes every element of the set for which block evaluates to
  # true, and returns self. Returns an enumerator if no block is
  # given.
  def delete_if
    block_given? or return enum_for(__method__) { size }
    # @hash.delete_if should be faster, but using it breaks the order
    # of enumeration in subclasses.
    select { |o| yield o }.each { |o| @hash.delete(o) }
    self
  end

  # Deletes every element of the set for which block evaluates to
  # false, and returns self. Returns an enumerator if no block is
  # given.
  def keep_if
    block_given? or return enum_for(__method__) { size }
    # @hash.keep_if should be faster, but using it breaks the order of
    # enumeration in subclasses.
    reject { |o| yield o }.each { |o| @hash.delete(o) }
    self
  end

  # Replaces the elements with ones returned by `collect()`.
  # Returns an enumerator if no block is given.
  def collect!
    block_given? or return enum_for(__method__) { size }
    set = self.class.new
    each { |o| set << yield(o) }
    replace(set)
  end
  alias map! collect!

  # Equivalent to Set#delete_if, but returns nil if no changes were
  # made. Returns an enumerator if no block is given.
  def reject!(&block)
    block or return enum_for(__method__) { size }
    n = size
    delete_if(&block)
    self if size != n
  end

  # Equivalent to Set#keep_if, but returns nil if no changes were
  # made. Returns an enumerator if no block is given.
  def select!(&block)
    block or return enum_for(__method__) { size }
    n = size
    keep_if(&block)
    self if size != n
  end

  # Equivalent to Set#select!
  alias filter! select!

  # Merges the elements of the given enumerable object to the set and
  # returns self.
  def merge(enum)
    if enum.instance_of?(self.class)
      @hash.update(enum.instance_variable_get(:@hash))
    else
      do_with_enum(enum) { |o| add(o) }
    end

    self
  end

  # Deletes every element that appears in the given enumerable object
  # and returns self.
  def subtract(enum)
    do_with_enum(enum) { |o| delete(o) }
    self
  end

  # Returns a new set built by merging the set and the elements of the
  # given enumerable object.
  #
  #     Set[1, 2, 3] | Set[2, 4, 5]         #=> #<Set: {1, 2, 3, 4, 5}>
  #     Set[1, 5, 'z'] | (1..6)             #=> #<Set: {1, 5, "z", 2, 3, 4, 6}>
  def |(enum)
    dup.merge(enum)
  end
  alias + |
  alias union |

  # Returns a new set built by duplicating the set, removing every
  # element that appears in the given enumerable object.
  #
  #     Set[1, 3, 5] - Set[1, 5]                #=> #<Set: {3}>
  #     Set['a', 'b', 'z'] - ['a', 'c']         #=> #<Set: {"b", "z"}>
  def -(enum)
    dup.subtract(enum)
  end
  alias difference -

  # Returns a new set containing elements common to the set and the
  # given enumerable object.
  #
  #     Set[1, 3, 5] & Set[3, 2, 1]             #=> #<Set: {3, 1}>
  #     Set['a', 'b', 'z'] & ['a', 'b', 'c']    #=> #<Set: {"a", "b"}>
  def &(enum)
    n = self.class.new
    if enum.is_a?(Set)
      if enum.size > size
        each { |o| n.add(o) if enum.include?(o) }
      else
        enum.each { |o| n.add(o) if include?(o) }
      end
    else
      do_with_enum(enum) { |o| n.add(o) if include?(o) }
    end
    n
  end
  alias intersection &

  # Returns a new set containing elements exclusive between the set
  # and the given enumerable object.  `(set ^ enum)` is equivalent to
  # `((set | enum) - (set & enum))`.
  #
  #     Set[1, 2] ^ Set[2, 3]                   #=> #<Set: {3, 1}>
  #     Set[1, 'b', 'c'] ^ ['b', 'd']           #=> #<Set: {"d", 1, "c"}>
  def ^(enum)
    n = Set.new(enum)
    each { |o| n.add(o) unless n.delete?(o) }
    n
  end

  # Returns true if two sets are equal.  The equality of each couple
  # of elements is defined according to Object#eql?.
  #
  #     Set[1, 2] == Set[2, 1]                       #=> true
  #     Set[1, 3, 5] == Set[1, 5]                    #=> false
  #     Set['a', 'b', 'c'] == Set['a', 'c', 'b']     #=> true
  #     Set['a', 'b', 'c'] == ['a', 'c', 'b']        #=> false
  def ==(other)
    if self.equal?(other)
      true
    elsif other.instance_of?(self.class)
      @hash == other.instance_variable_get(:@hash)
    elsif other.is_a?(Set) && self.size == other.size
      other.all? { |o| @hash.include?(o) }
    else
      false
    end
  end

  def hash      # :nodoc:
    @hash.hash
  end

  def eql?(o)   # :nodoc:
    return false unless o.is_a?(Set)
    @hash.eql?(o.instance_variable_get(:@hash))
  end

  # Resets the internal state after modification to existing elements
  # and returns self.
  #
  # Elements will be reindexed and deduplicated.
  def reset
    if @hash.respond_to?(:rehash)
      @hash.rehash # This should perform frozenness check.
    else
      raise FrozenError, "can't modify frozen #{self.class.name}" if frozen?
    end
    self
  end

  # Returns true if the given object is a member of the set,
  # and false otherwise.
  #
  # Used in case statements:
  #
  #     require 'set'
  #
  #     case :apple
  #     when Set[:potato, :carrot]
  #       "vegetable"
  #     when Set[:apple, :banana]
  #       "fruit"
  #     end
  #     # => "fruit"
  #
  # Or by itself:
  #
  #     Set[1, 2, 3] === 2   #=> true
  #     Set[1, 2, 3] === 4   #=> false
  #
  alias === include?

  # Classifies the set by the return value of the given block and
  # returns a hash of {value => set of elements} pairs.  The block is
  # called once for each element of the set, passing the element as
  # parameter.
  #
  #     require 'set'
  #     files = Set.new(Dir.glob("*.rb"))
  #     hash = files.classify { |f| File.mtime(f).year }
  #     hash       #=> {2000=>#<Set: {"a.rb", "b.rb"}>,
  #                #    2001=>#<Set: {"c.rb", "d.rb", "e.rb"}>,
  #                #    2002=>#<Set: {"f.rb"}>}
  #
  # Returns an enumerator if no block is given.
  def classify # :yields: o
    block_given? or return enum_for(__method__) { size }

    h = {}

    each { |i|
      (h[yield(i)] ||= self.class.new).add(i)
    }

    h
  end

  # Divides the set into a set of subsets according to the commonality
  # defined by the given block.
  #
  # If the arity of the block is 2, elements o1 and o2 are in common
  # if block.call(o1, o2) is true.  Otherwise, elements o1 and o2 are
  # in common if block.call(o1) == block.call(o2).
  #
  #     require 'set'
  #     numbers = Set[1, 3, 4, 6, 9, 10, 11]
  #     set = numbers.divide { |i,j| (i - j).abs == 1 }
  #     set        #=> #<Set: {#<Set: {1}>,
  #                #           #<Set: {11, 9, 10}>,
  #                #           #<Set: {3, 4}>,
  #                #           #<Set: {6}>}>
  #
  # Returns an enumerator if no block is given.
  def divide(&func)
    func or return enum_for(__method__) { size }

    if func.arity == 2
      require 'tsort'

      class << dig = {}         # :nodoc:
        include TSort

        alias tsort_each_node each_key
        def tsort_each_child(node, &block)
          fetch(node).each(&block)
        end
      end

      each { |u|
        dig[u] = a = []
        each{ |v| func.call(u, v) and a << v }
      }

      set = Set.new()
      dig.each_strongly_connected_component { |css|
        set.add(self.class.new(css))
      }
      set
    else
      Set.new(classify(&func).values)
    end
  end

  # Returns a string created by converting each element of the set to a string
  # See also: Array#join
  def join(separator=nil)
    to_a.join(separator)
  end

  InspectKey = :__inspect_key__         # :nodoc:

  # Returns a string containing a human-readable representation of the
  # set ("#<Set: {element1, element2, ...}>").
  def inspect
    ids = (Thread.current[InspectKey] ||= [])

    if ids.include?(object_id)
      return sprintf('#<%s: {...}>', self.class.name)
    end

    ids << object_id
    begin
      return sprintf('#<%s: {%s}>', self.class, to_a.inspect[1..-2])
    ensure
      ids.pop
    end
  end

  alias to_s inspect

  def pretty_print(pp)  # :nodoc:
    pp.text sprintf('#<%s: {', self.class.name)
    pp.nest(1) {
      pp.seplist(self) { |o|
        pp.pp o
      }
    }
    pp.text "}>"
  end

  def pretty_print_cycle(pp)    # :nodoc:
    pp.text sprintf('#<%s: {%s}>', self.class.name, empty? ? '' : '...')
  end
end

module Enumerable
  # Makes a set from the enumerable object with given arguments.
  # Needs to `require "set"` to use this method.
  def to_set(klass = Set, *args, &block)
    klass.new(self, *args, &block)
  end
end

autoload :SortedSet, "#{__dir__}/set/sorted_set"
# frozen_string_literal: false
require 'drb/drb'

# frozen_string_literal: false
#--
# sha2.rb - defines Digest::SHA2 class which wraps up the SHA256,
#           SHA384, and SHA512 classes.
#++
# Copyright (c) 2006 Akinori MUSHA <knu@iDaemons.org>
#
# All rights reserved.  You can redistribute and/or modify it under the same
# terms as Ruby.
#
#   $Id$

require 'digest'
require 'digest/sha2.so'

module Digest
  #
  # A meta digest provider class for SHA256, SHA384 and SHA512.
  #
  # FIPS 180-2 describes SHA2 family of digest algorithms. It defines
  # three algorithms:
  # * one which works on chunks of 512 bits and returns a 256-bit
  #   digest (SHA256),
  # * one which works on chunks of 1024 bits and returns a 384-bit
  #   digest (SHA384),
  # * and one which works on chunks of 1024 bits and returns a 512-bit
  #   digest (SHA512).
  #
  # ==Examples
  #  require 'digest'
  #
  #  # Compute a complete digest
  #  Digest::SHA2.hexdigest 'abc'          # => "ba7816bf8..."
  #  Digest::SHA2.new(256).hexdigest 'abc' # => "ba7816bf8..."
  #  Digest::SHA256.hexdigest 'abc'        # => "ba7816bf8..."
  #
  #  Digest::SHA2.new(384).hexdigest 'abc' # => "cb00753f4..."
  #  Digest::SHA384.hexdigest 'abc'        # => "cb00753f4..."
  #
  #  Digest::SHA2.new(512).hexdigest 'abc' # => "ddaf35a19..."
  #  Digest::SHA512.hexdigest 'abc'        # => "ddaf35a19..."
  #
  #  # Compute digest by chunks
  #  sha2 = Digest::SHA2.new               # =>#<Digest::SHA2:256>
  #  sha2.update "ab"
  #  sha2 << "c"                           # alias for #update
  #  sha2.hexdigest                        # => "ba7816bf8..."
  #
  #  # Use the same object to compute another digest
  #  sha2.reset
  #  sha2 << "message"
  #  sha2.hexdigest                        # => "ab530a13e..."
  #
  class SHA2 < Digest::Class
    # call-seq:
    #   Digest::SHA2.new(bitlen = 256) -> digest_obj
    #
    # Create a new SHA2 hash object with a given bit length.
    #
    # Valid bit lengths are 256, 384 and 512.
    def initialize(bitlen = 256)
      case bitlen
      when 256
        @sha2 = Digest::SHA256.new
      when 384
        @sha2 = Digest::SHA384.new
      when 512
        @sha2 = Digest::SHA512.new
      else
        raise ArgumentError, "unsupported bit length: %s" % bitlen.inspect
      end
      @bitlen = bitlen
    end

    # call-seq:
    #   digest_obj.reset -> digest_obj
    #
    # Reset the digest to the initial state and return self.
    def reset
      @sha2.reset
      self
    end

    # call-seq:
    #   digest_obj.update(string) -> digest_obj
    #   digest_obj << string -> digest_obj
    #
    # Update the digest using a given _string_ and return self.
    def update(str)
      @sha2.update(str)
      self
    end
    alias << update

    def finish # :nodoc:
      @sha2.digest!
    end
    private :finish


    # call-seq:
    #   digest_obj.block_length -> Integer
    #
    # Return the block length of the digest in bytes.
    #
    #   Digest::SHA256.new.block_length * 8
    #   # => 512
    #   Digest::SHA384.new.block_length * 8
    #   # => 1024
    #   Digest::SHA512.new.block_length * 8
    #   # => 1024
    def block_length
      @sha2.block_length
    end

    # call-seq:
    #   digest_obj.digest_length -> Integer
    #
    # Return the length of the hash value (the digest) in bytes.
    #
    #   Digest::SHA256.new.digest_length * 8
    #   # => 256
    #   Digest::SHA384.new.digest_length * 8
    #   # => 384
    #   Digest::SHA512.new.digest_length * 8
    #   # => 512
    #
    # For example, digests produced by Digest::SHA256 will always be 32 bytes
    # (256 bits) in size.
    def digest_length
      @sha2.digest_length
    end

    def initialize_copy(other) # :nodoc:
      @sha2 = other.instance_eval { @sha2.clone }
    end

    def inspect # :nodoc:
      "#<%s:%d %s>" % [self.class.name, @bitlen, hexdigest]
    end
  end
end
# frozen_string_literal: true

#--
# tsort.rb - provides a module for topological sorting and strongly connected components.
#++
#

#
# TSort implements topological sorting using Tarjan's algorithm for
# strongly connected components.
#
# TSort is designed to be able to be used with any object which can be
# interpreted as a directed graph.
#
# TSort requires two methods to interpret an object as a graph,
# tsort_each_node and tsort_each_child.
#
# * tsort_each_node is used to iterate for all nodes over a graph.
# * tsort_each_child is used to iterate for child nodes of a given node.
#
# The equality of nodes are defined by eql? and hash since
# TSort uses Hash internally.
#
# == A Simple Example
#
# The following example demonstrates how to mix the TSort module into an
# existing class (in this case, Hash). Here, we're treating each key in
# the hash as a node in the graph, and so we simply alias the required
# #tsort_each_node method to Hash's #each_key method. For each key in the
# hash, the associated value is an array of the node's child nodes. This
# choice in turn leads to our implementation of the required #tsort_each_child
# method, which fetches the array of child nodes and then iterates over that
# array using the user-supplied block.
#
#   require 'tsort'
#
#   class Hash
#     include TSort
#     alias tsort_each_node each_key
#     def tsort_each_child(node, &block)
#       fetch(node).each(&block)
#     end
#   end
#
#   {1=>[2, 3], 2=>[3], 3=>[], 4=>[]}.tsort
#   #=> [3, 2, 1, 4]
#
#   {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}.strongly_connected_components
#   #=> [[4], [2, 3], [1]]
#
# == A More Realistic Example
#
# A very simple `make' like tool can be implemented as follows:
#
#   require 'tsort'
#
#   class Make
#     def initialize
#       @dep = {}
#       @dep.default = []
#     end
#
#     def rule(outputs, inputs=[], &block)
#       triple = [outputs, inputs, block]
#       outputs.each {|f| @dep[f] = [triple]}
#       @dep[triple] = inputs
#     end
#
#     def build(target)
#       each_strongly_connected_component_from(target) {|ns|
#         if ns.length != 1
#           fs = ns.delete_if {|n| Array === n}
#           raise TSort::Cyclic.new("cyclic dependencies: #{fs.join ', '}")
#         end
#         n = ns.first
#         if Array === n
#           outputs, inputs, block = n
#           inputs_time = inputs.map {|f| File.mtime f}.max
#           begin
#             outputs_time = outputs.map {|f| File.mtime f}.min
#           rescue Errno::ENOENT
#             outputs_time = nil
#           end
#           if outputs_time == nil ||
#              inputs_time != nil && outputs_time <= inputs_time
#             sleep 1 if inputs_time != nil && inputs_time.to_i == Time.now.to_i
#             block.call
#           end
#         end
#       }
#     end
#
#     def tsort_each_child(node, &block)
#       @dep[node].each(&block)
#     end
#     include TSort
#   end
#
#   def command(arg)
#     print arg, "\n"
#     system arg
#   end
#
#   m = Make.new
#   m.rule(%w[t1]) { command 'date > t1' }
#   m.rule(%w[t2]) { command 'date > t2' }
#   m.rule(%w[t3]) { command 'date > t3' }
#   m.rule(%w[t4], %w[t1 t3]) { command 'cat t1 t3 > t4' }
#   m.rule(%w[t5], %w[t4 t2]) { command 'cat t4 t2 > t5' }
#   m.build('t5')
#
# == Bugs
#
# * 'tsort.rb' is wrong name because this library uses
#   Tarjan's algorithm for strongly connected components.
#   Although 'strongly_connected_components.rb' is correct but too long.
#
# == References
#
# R. E. Tarjan, "Depth First Search and Linear Graph Algorithms",
# <em>SIAM Journal on Computing</em>, Vol. 1, No. 2, pp. 146-160, June 1972.
#

module TSort
  class Cyclic < StandardError
  end

  # Returns a topologically sorted array of nodes.
  # The array is sorted from children to parents, i.e.
  # the first element has no child and the last node has no parent.
  #
  # If there is a cycle, TSort::Cyclic is raised.
  #
  #   class G
  #     include TSort
  #     def initialize(g)
  #       @g = g
  #     end
  #     def tsort_each_child(n, &b) @g[n].each(&b) end
  #     def tsort_each_node(&b) @g.each_key(&b) end
  #   end
  #
  #   graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
  #   p graph.tsort #=> [4, 2, 3, 1]
  #
  #   graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
  #   p graph.tsort # raises TSort::Cyclic
  #
  def tsort
    each_node = method(:tsort_each_node)
    each_child = method(:tsort_each_child)
    TSort.tsort(each_node, each_child)
  end

  # Returns a topologically sorted array of nodes.
  # The array is sorted from children to parents, i.e.
  # the first element has no child and the last node has no parent.
  #
  # The graph is represented by _each_node_ and _each_child_.
  # _each_node_ should have +call+ method which yields for each node in the graph.
  # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
  #
  # If there is a cycle, TSort::Cyclic is raised.
  #
  #   g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
  #   each_node = lambda {|&b| g.each_key(&b) }
  #   each_child = lambda {|n, &b| g[n].each(&b) }
  #   p TSort.tsort(each_node, each_child) #=> [4, 2, 3, 1]
  #
  #   g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
  #   each_node = lambda {|&b| g.each_key(&b) }
  #   each_child = lambda {|n, &b| g[n].each(&b) }
  #   p TSort.tsort(each_node, each_child) # raises TSort::Cyclic
  #
  def TSort.tsort(each_node, each_child)
    TSort.tsort_each(each_node, each_child).to_a
  end

  # The iterator version of the #tsort method.
  # <tt><em>obj</em>.tsort_each</tt> is similar to <tt><em>obj</em>.tsort.each</tt>, but
  # modification of _obj_ during the iteration may lead to unexpected results.
  #
  # #tsort_each returns +nil+.
  # If there is a cycle, TSort::Cyclic is raised.
  #
  #   class G
  #     include TSort
  #     def initialize(g)
  #       @g = g
  #     end
  #     def tsort_each_child(n, &b) @g[n].each(&b) end
  #     def tsort_each_node(&b) @g.each_key(&b) end
  #   end
  #
  #   graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
  #   graph.tsort_each {|n| p n }
  #   #=> 4
  #   #   2
  #   #   3
  #   #   1
  #
  def tsort_each(&block) # :yields: node
    each_node = method(:tsort_each_node)
    each_child = method(:tsort_each_child)
    TSort.tsort_each(each_node, each_child, &block)
  end

  # The iterator version of the TSort.tsort method.
  #
  # The graph is represented by _each_node_ and _each_child_.
  # _each_node_ should have +call+ method which yields for each node in the graph.
  # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
  #
  #   g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
  #   each_node = lambda {|&b| g.each_key(&b) }
  #   each_child = lambda {|n, &b| g[n].each(&b) }
  #   TSort.tsort_each(each_node, each_child) {|n| p n }
  #   #=> 4
  #   #   2
  #   #   3
  #   #   1
  #
  def TSort.tsort_each(each_node, each_child) # :yields: node
    return to_enum(__method__, each_node, each_child) unless block_given?

    TSort.each_strongly_connected_component(each_node, each_child) {|component|
      if component.size == 1
        yield component.first
      else
        raise Cyclic.new("topological sort failed: #{component.inspect}")
      end
    }
  end

  # Returns strongly connected components as an array of arrays of nodes.
  # The array is sorted from children to parents.
  # Each elements of the array represents a strongly connected component.
  #
  #   class G
  #     include TSort
  #     def initialize(g)
  #       @g = g
  #     end
  #     def tsort_each_child(n, &b) @g[n].each(&b) end
  #     def tsort_each_node(&b) @g.each_key(&b) end
  #   end
  #
  #   graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
  #   p graph.strongly_connected_components #=> [[4], [2], [3], [1]]
  #
  #   graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
  #   p graph.strongly_connected_components #=> [[4], [2, 3], [1]]
  #
  def strongly_connected_components
    each_node = method(:tsort_each_node)
    each_child = method(:tsort_each_child)
    TSort.strongly_connected_components(each_node, each_child)
  end

  # Returns strongly connected components as an array of arrays of nodes.
  # The array is sorted from children to parents.
  # Each elements of the array represents a strongly connected component.
  #
  # The graph is represented by _each_node_ and _each_child_.
  # _each_node_ should have +call+ method which yields for each node in the graph.
  # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
  #
  #   g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
  #   each_node = lambda {|&b| g.each_key(&b) }
  #   each_child = lambda {|n, &b| g[n].each(&b) }
  #   p TSort.strongly_connected_components(each_node, each_child)
  #   #=> [[4], [2], [3], [1]]
  #
  #   g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
  #   each_node = lambda {|&b| g.each_key(&b) }
  #   each_child = lambda {|n, &b| g[n].each(&b) }
  #   p TSort.strongly_connected_components(each_node, each_child)
  #   #=> [[4], [2, 3], [1]]
  #
  def TSort.strongly_connected_components(each_node, each_child)
    TSort.each_strongly_connected_component(each_node, each_child).to_a
  end

  # The iterator version of the #strongly_connected_components method.
  # <tt><em>obj</em>.each_strongly_connected_component</tt> is similar to
  # <tt><em>obj</em>.strongly_connected_components.each</tt>, but
  # modification of _obj_ during the iteration may lead to unexpected results.
  #
  # #each_strongly_connected_component returns +nil+.
  #
  #   class G
  #     include TSort
  #     def initialize(g)
  #       @g = g
  #     end
  #     def tsort_each_child(n, &b) @g[n].each(&b) end
  #     def tsort_each_node(&b) @g.each_key(&b) end
  #   end
  #
  #   graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
  #   graph.each_strongly_connected_component {|scc| p scc }
  #   #=> [4]
  #   #   [2]
  #   #   [3]
  #   #   [1]
  #
  #   graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
  #   graph.each_strongly_connected_component {|scc| p scc }
  #   #=> [4]
  #   #   [2, 3]
  #   #   [1]
  #
  def each_strongly_connected_component(&block) # :yields: nodes
    each_node = method(:tsort_each_node)
    each_child = method(:tsort_each_child)
    TSort.each_strongly_connected_component(each_node, each_child, &block)
  end

  # The iterator version of the TSort.strongly_connected_components method.
  #
  # The graph is represented by _each_node_ and _each_child_.
  # _each_node_ should have +call+ method which yields for each node in the graph.
  # _each_child_ should have +call+ method which takes a node argument and yields for each child node.
  #
  #   g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}
  #   each_node = lambda {|&b| g.each_key(&b) }
  #   each_child = lambda {|n, &b| g[n].each(&b) }
  #   TSort.each_strongly_connected_component(each_node, each_child) {|scc| p scc }
  #   #=> [4]
  #   #   [2]
  #   #   [3]
  #   #   [1]
  #
  #   g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
  #   each_node = lambda {|&b| g.each_key(&b) }
  #   each_child = lambda {|n, &b| g[n].each(&b) }
  #   TSort.each_strongly_connected_component(each_node, each_child) {|scc| p scc }
  #   #=> [4]
  #   #   [2, 3]
  #   #   [1]
  #
  def TSort.each_strongly_connected_component(each_node, each_child) # :yields: nodes
    return to_enum(__method__, each_node, each_child) unless block_given?

    id_map = {}
    stack = []
    each_node.call {|node|
      unless id_map.include? node
        TSort.each_strongly_connected_component_from(node, each_child, id_map, stack) {|c|
          yield c
        }
      end
    }
    nil
  end

  # Iterates over strongly connected component in the subgraph reachable from
  # _node_.
  #
  # Return value is unspecified.
  #
  # #each_strongly_connected_component_from doesn't call #tsort_each_node.
  #
  #   class G
  #     include TSort
  #     def initialize(g)
  #       @g = g
  #     end
  #     def tsort_each_child(n, &b) @g[n].each(&b) end
  #     def tsort_each_node(&b) @g.each_key(&b) end
  #   end
  #
  #   graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]})
  #   graph.each_strongly_connected_component_from(2) {|scc| p scc }
  #   #=> [4]
  #   #   [2]
  #
  #   graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]})
  #   graph.each_strongly_connected_component_from(2) {|scc| p scc }
  #   #=> [4]
  #   #   [2, 3]
  #
  def each_strongly_connected_component_from(node, id_map={}, stack=[], &block) # :yields: nodes
    TSort.each_strongly_connected_component_from(node, method(:tsort_each_child), id_map, stack, &block)
  end

  # Iterates over strongly connected components in a graph.
  # The graph is represented by _node_ and _each_child_.
  #
  # _node_ is the first node.
  # _each_child_ should have +call+ method which takes a node argument
  # and yields for each child node.
  #
  # Return value is unspecified.
  #
  # #TSort.each_strongly_connected_component_from is a class method and
  # it doesn't need a class to represent a graph which includes TSort.
  #
  #   graph = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}
  #   each_child = lambda {|n, &b| graph[n].each(&b) }
  #   TSort.each_strongly_connected_component_from(1, each_child) {|scc|
  #     p scc
  #   }
  #   #=> [4]
  #   #   [2, 3]
  #   #   [1]
  #
  def TSort.each_strongly_connected_component_from(node, each_child, id_map={}, stack=[]) # :yields: nodes
    return to_enum(__method__, node, each_child, id_map, stack) unless block_given?

    minimum_id = node_id = id_map[node] = id_map.size
    stack_length = stack.length
    stack << node

    each_child.call(node) {|child|
      if id_map.include? child
        child_id = id_map[child]
        minimum_id = child_id if child_id && child_id < minimum_id
      else
        sub_minimum_id =
          TSort.each_strongly_connected_component_from(child, each_child, id_map, stack) {|c|
            yield c
          }
        minimum_id = sub_minimum_id if sub_minimum_id < minimum_id
      end
    }

    if node_id == minimum_id
      component = stack.slice!(stack_length .. -1)
      component.each {|n| id_map[n] = nil}
      yield component
    end

    minimum_id
  end

  # Should be implemented by a extended class.
  #
  # #tsort_each_node is used to iterate for all nodes over a graph.
  #
  def tsort_each_node # :yields: node
    raise NotImplementedError.new
  end

  # Should be implemented by a extended class.
  #
  # #tsort_each_child is used to iterate for child nodes of _node_.
  #
  def tsort_each_child(node) # :yields: child
    raise NotImplementedError.new
  end
end
# encoding: US-ASCII
# frozen_string_literal: true
# = csv.rb -- CSV Reading and Writing
#
# Created by James Edward Gray II on 2005-10-31.
#
# See CSV for documentation.
#
# == Description
#
# Welcome to the new and improved CSV.
#
# This version of the CSV library began its life as FasterCSV. FasterCSV was
# intended as a replacement to Ruby's then standard CSV library. It was
# designed to address concerns users of that library had and it had three
# primary goals:
#
# 1.  Be significantly faster than CSV while remaining a pure Ruby library.
# 2.  Use a smaller and easier to maintain code base. (FasterCSV eventually
#     grew larger, was also but considerably richer in features. The parsing
#     core remains quite small.)
# 3.  Improve on the CSV interface.
#
# Obviously, the last one is subjective. I did try to defer to the original
# interface whenever I didn't have a compelling reason to change it though, so
# hopefully this won't be too radically different.
#
# We must have met our goals because FasterCSV was renamed to CSV and replaced
# the original library as of Ruby 1.9. If you are migrating code from 1.8 or
# earlier, you may have to change your code to comply with the new interface.
#
# == What's the Different From the Old CSV?
#
# I'm sure I'll miss something, but I'll try to mention most of the major
# differences I am aware of, to help others quickly get up to speed:
#
# === \CSV Parsing
#
# * This parser is m17n aware. See CSV for full details.
# * This library has a stricter parser and will throw MalformedCSVErrors on
#   problematic data.
# * This library has a less liberal idea of a line ending than CSV. What you
#   set as the <tt>:row_sep</tt> is law. It can auto-detect your line endings
#   though.
# * The old library returned empty lines as <tt>[nil]</tt>. This library calls
#   them <tt>[]</tt>.
# * This library has a much faster parser.
#
# === Interface
#
# * CSV now uses Hash-style parameters to set options.
# * CSV no longer has generate_row() or parse_row().
# * The old CSV's Reader and Writer classes have been dropped.
# * CSV::open() is now more like Ruby's open().
# * CSV objects now support most standard IO methods.
# * CSV now has a new() method used to wrap objects like String and IO for
#   reading and writing.
# * CSV::generate() is different from the old method.
# * CSV no longer supports partial reads. It works line-by-line.
# * CSV no longer allows the instance methods to override the separators for
#   performance reasons. They must be set in the constructor.
#
# If you use this library and find yourself missing any functionality I have
# trimmed, please {let me know}[mailto:james@grayproductions.net].
#
# == Documentation
#
# See CSV for documentation.
#
# == What is CSV, really?
#
# CSV maintains a pretty strict definition of CSV taken directly from
# {the RFC}[http://www.ietf.org/rfc/rfc4180.txt]. I relax the rules in only one
# place and that is to make using this library easier. CSV will parse all valid
# CSV.
#
# What you don't want to do is to feed CSV invalid data. Because of the way the
# CSV format works, it's common for a parser to need to read until the end of
# the file to be sure a field is invalid. This consumes a lot of time and memory.
#
# Luckily, when working with invalid CSV, Ruby's built-in methods will almost
# always be superior in every way. For example, parsing non-quoted fields is as
# easy as:
#
#   data.split(",")
#
# == Questions and/or Comments
#
# Feel free to email {James Edward Gray II}[mailto:james@grayproductions.net]
# with any questions.

require "forwardable"
require "English"
require "date"
require "stringio"

require_relative "csv/fields_converter"
require_relative "csv/match_p"
require_relative "csv/parser"
require_relative "csv/row"
require_relative "csv/table"
require_relative "csv/writer"

using CSV::MatchP if CSV.const_defined?(:MatchP)

# == \CSV
# \CSV (comma-separated variables) data is a text representation of a table:
# - A _row_ _separator_ delimits table rows.
#   A common row separator is the newline character <tt>"\n"</tt>.
# - A _column_ _separator_ delimits fields in a row.
#   A common column separator is the comma character <tt>","</tt>.
#
# This \CSV \String, with row separator <tt>"\n"</tt>
# and column separator <tt>","</tt>,
# has three rows and two columns:
#   "foo,0\nbar,1\nbaz,2\n"
#
# Despite the name \CSV, a \CSV representation can use different separators.
#
# For more about tables, see the Wikipedia article
# "{Table (information)}[https://en.wikipedia.org/wiki/Table_(information)]",
# especially its section
# "{Simple table}[https://en.wikipedia.org/wiki/Table_(information)#Simple_table]"
#
# == \Class \CSV
#
# Class \CSV provides methods for:
# - Parsing \CSV data from a \String object, a \File (via its file path), or an \IO object.
# - Generating \CSV data to a \String object.
#
# To make \CSV available:
#   require 'csv'
#
# All examples here assume that this has been done.
#
# == Keeping It Simple
#
# A \CSV object has dozens of instance methods that offer fine-grained control
# of parsing and generating \CSV data.
# For many needs, though, simpler approaches will do.
#
# This section summarizes the singleton methods in \CSV
# that allow you to parse and generate without explicitly
# creating \CSV objects.
# For details, follow the links.
#
# === Simple Parsing
#
# Parsing methods commonly return either of:
# - An \Array of Arrays of Strings:
#   - The outer \Array is the entire "table".
#   - Each inner \Array is a row.
#   - Each \String is a field.
# - A CSV::Table object.  For details, see
#   {\CSV with Headers}[#class-CSV-label-CSV+with+Headers].
#
# ==== Parsing a \String
#
# The input to be parsed can be a string:
#   string = "foo,0\nbar,1\nbaz,2\n"
#
# \Method CSV.parse returns the entire \CSV data:
#   CSV.parse(string) # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]
#
# \Method CSV.parse_line returns only the first row:
#   CSV.parse_line(string) # => ["foo", "0"]
#
# \CSV extends class \String with instance method String#parse_csv,
# which also returns only the first row:
#   string.parse_csv # => ["foo", "0"]
#
# ==== Parsing Via a \File Path
#
# The input to be parsed can be in a file:
#   string = "foo,0\nbar,1\nbaz,2\n"
#   path = 't.csv'
#   File.write(path, string)
#
# \Method CSV.read returns the entire \CSV data:
#  CSV.read(path) # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]
#
# \Method CSV.foreach iterates, passing each row to the given block:
#  CSV.foreach(path) do |row|
#    p row
#  end
# Output:
#   ["foo", "0"]
#   ["bar", "1"]
#   ["baz", "2"]
#
# \Method CSV.table returns the entire \CSV data as a CSV::Table object:
#   CSV.table(path) # => #<CSV::Table mode:col_or_row row_count:3>
#
# ==== Parsing from an Open \IO Stream
#
# The input to be parsed can be in an open \IO stream:
#
# \Method CSV.read returns the entire \CSV data:
#   File.open(path) do |file|
#     CSV.read(file)
#   end # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]
#
# As does method CSV.parse:
#   File.open(path) do |file|
#     CSV.parse(file)
#   end # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]
#
# \Method CSV.parse_line returns only the first row:
#   File.open(path) do |file|
#    CSV.parse_line(file)
#   end # => ["foo", "0"]
#
# \Method CSV.foreach iterates, passing each row to the given block:
#   File.open(path) do |file|
#     CSV.foreach(file) do |row|
#       p row
#     end
#   end
# Output:
#   ["foo", "0"]
#   ["bar", "1"]
#   ["baz", "2"]
#
# \Method CSV.table returns the entire \CSV data as a CSV::Table object:
#   File.open(path) do |file|
#     CSV.table(file)
#   end # => #<CSV::Table mode:col_or_row row_count:3>
#
# === Simple Generating
#
# \Method CSV.generate returns a \String;
# this example uses method CSV#<< to append the rows
# that are to be generated:
#   output_string = CSV.generate do |csv|
#     csv << ['foo', 0]
#     csv << ['bar', 1]
#     csv << ['baz', 2]
#   end
#   output_string # => "foo,0\nbar,1\nbaz,2\n"
#
# \Method CSV.generate_line returns a \String containing the single row
# constructed from an \Array:
#   CSV.generate_line(['foo', '0']) # => "foo,0\n"
#
# \CSV extends class \Array with instance method <tt>Array#to_csv</tt>,
# which forms an \Array into a \String:
#   ['foo', '0'].to_csv # => "foo,0\n"
#
# === "Filtering" \CSV
#
# \Method CSV.filter provides a Unix-style filter for \CSV data.
# The input data is processed to form the output data:
#   in_string = "foo,0\nbar,1\nbaz,2\n"
#   out_string = ''
#   CSV.filter(in_string, out_string) do |row|
#     row[0] = row[0].upcase
#     row[1] *= 4
#   end
#   out_string # => "FOO,0000\nBAR,1111\nBAZ,2222\n"
#
# == \CSV Objects
#
# There are three ways to create a \CSV object:
# - \Method CSV.new returns a new \CSV object.
# - \Method CSV.instance returns a new or cached \CSV object.
# - \Method \CSV() also returns a new or cached \CSV object.
#
# === Instance Methods
#
# \CSV has three groups of instance methods:
# - Its own internally defined instance methods.
# - Methods included by module Enumerable.
# - Methods delegated to class IO. See below.
#
# ==== Delegated Methods
#
# For convenience, a CSV object will delegate to many methods in class IO.
# (A few have wrapper "guard code" in \CSV.) You may call:
# * IO#binmode
# * #binmode?
# * IO#close
# * IO#close_read
# * IO#close_write
# * IO#closed?
# * #eof
# * #eof?
# * IO#external_encoding
# * IO#fcntl
# * IO#fileno
# * #flock
# * IO#flush
# * IO#fsync
# * IO#internal_encoding
# * #ioctl
# * IO#isatty
# * #path
# * IO#pid
# * IO#pos
# * IO#pos=
# * IO#reopen
# * #rewind
# * IO#seek
# * #stat
# * IO#string
# * IO#sync
# * IO#sync=
# * IO#tell
# * #to_i
# * #to_io
# * IO#truncate
# * IO#tty?
#
# === Options
#
# The default values for options are:
#   DEFAULT_OPTIONS = {
#     # For both parsing and generating.
#     col_sep:            ",",
#     row_sep:            :auto,
#     quote_char:         '"',
#     # For parsing.
#     field_size_limit:   nil,
#     converters:         nil,
#     unconverted_fields: nil,
#     headers:            false,
#     return_headers:     false,
#     header_converters:  nil,
#     skip_blanks:        false,
#     skip_lines:         nil,
#     liberal_parsing:    false,
#     nil_value:          nil,
#     empty_value:        "",
#     # For generating.
#     write_headers:      nil,
#     quote_empty:        true,
#     force_quotes:       false,
#     write_converters:   nil,
#     write_nil_value:    nil,
#     write_empty_value:  "",
#     strip:              false,
#   }
#
# ==== Options for Parsing
#
# Options for parsing, described in detail below, include:
# - +row_sep+: Specifies the row separator; used to delimit rows.
# - +col_sep+: Specifies the column separator; used to delimit fields.
# - +quote_char+: Specifies the quote character; used to quote fields.
# - +field_size_limit+: Specifies the maximum field size allowed.
# - +converters+: Specifies the field converters to be used.
# - +unconverted_fields+: Specifies whether unconverted fields are to be available.
# - +headers+: Specifies whether data contains headers,
#   or specifies the headers themselves.
# - +return_headers+: Specifies whether headers are to be returned.
# - +header_converters+: Specifies the header converters to be used.
# - +skip_blanks+: Specifies whether blanks lines are to be ignored.
# - +skip_lines+: Specifies how comments lines are to be recognized.
# - +strip+: Specifies whether leading and trailing whitespace are
#   to be stripped from fields..
# - +liberal_parsing+: Specifies whether \CSV should attempt to parse
#   non-compliant data.
# - +nil_value+: Specifies the object that is to be substituted for each null (no-text) field.
# - +empty_value+: Specifies the object that is to be substituted for each empty field.
#
# :include: ../doc/csv/options/common/row_sep.rdoc
#
# :include: ../doc/csv/options/common/col_sep.rdoc
#
# :include: ../doc/csv/options/common/quote_char.rdoc
#
# :include: ../doc/csv/options/parsing/field_size_limit.rdoc
#
# :include: ../doc/csv/options/parsing/converters.rdoc
#
# :include: ../doc/csv/options/parsing/unconverted_fields.rdoc
#
# :include: ../doc/csv/options/parsing/headers.rdoc
#
# :include: ../doc/csv/options/parsing/return_headers.rdoc
#
# :include: ../doc/csv/options/parsing/header_converters.rdoc
#
# :include: ../doc/csv/options/parsing/skip_blanks.rdoc
#
# :include: ../doc/csv/options/parsing/skip_lines.rdoc
#
# :include: ../doc/csv/options/parsing/strip.rdoc
#
# :include: ../doc/csv/options/parsing/liberal_parsing.rdoc
#
# :include: ../doc/csv/options/parsing/nil_value.rdoc
#
# :include: ../doc/csv/options/parsing/empty_value.rdoc
#
# ==== Options for Generating
#
# Options for generating, described in detail below, include:
# - +row_sep+: Specifies the row separator; used to delimit rows.
# - +col_sep+: Specifies the column separator; used to delimit fields.
# - +quote_char+: Specifies the quote character; used to quote fields.
# - +write_headers+: Specifies whether headers are to be written.
# - +force_quotes+: Specifies whether each output field is to be quoted.
# - +quote_empty+: Specifies whether each empty output field is to be quoted.
# - +write_converters+: Specifies the field converters to be used in writing.
# - +write_nil_value+: Specifies the object that is to be substituted for each +nil+-valued field.
# - +write_empty_value+: Specifies the object that is to be substituted for each empty field.
#
# :include: ../doc/csv/options/common/row_sep.rdoc
#
# :include: ../doc/csv/options/common/col_sep.rdoc
#
# :include: ../doc/csv/options/common/quote_char.rdoc
#
# :include: ../doc/csv/options/generating/write_headers.rdoc
#
# :include: ../doc/csv/options/generating/force_quotes.rdoc
#
# :include: ../doc/csv/options/generating/quote_empty.rdoc
#
# :include: ../doc/csv/options/generating/write_converters.rdoc
#
# :include: ../doc/csv/options/generating/write_nil_value.rdoc
#
# :include: ../doc/csv/options/generating/write_empty_value.rdoc
#
# === \CSV with Headers
#
# CSV allows to specify column names of CSV file, whether they are in data, or
# provided separately. If headers are specified, reading methods return an instance
# of CSV::Table, consisting of CSV::Row.
#
#   # Headers are part of data
#   data = CSV.parse(<<~ROWS, headers: true)
#     Name,Department,Salary
#     Bob,Engineering,1000
#     Jane,Sales,2000
#     John,Management,5000
#   ROWS
#
#   data.class      #=> CSV::Table
#   data.first      #=> #<CSV::Row "Name":"Bob" "Department":"Engineering" "Salary":"1000">
#   data.first.to_h #=> {"Name"=>"Bob", "Department"=>"Engineering", "Salary"=>"1000"}
#
#   # Headers provided by developer
#   data = CSV.parse('Bob,Engineering,1000', headers: %i[name department salary])
#   data.first      #=> #<CSV::Row name:"Bob" department:"Engineering" salary:"1000">
#
# === \Converters
#
# By default, each value (field or header) parsed by \CSV is formed into a \String.
# You can use a _field_ _converter_ or  _header_ _converter_
# to intercept and modify the parsed values:
# - See {Field Converters}[#class-CSV-label-Field+Converters].
# - See {Header Converters}[#class-CSV-label-Header+Converters].
#
# Also by default, each value to be written during generation is written 'as-is'.
# You can use a _write_ _converter_ to modify values before writing.
# - See {Write Converters}[#class-CSV-label-Write+Converters].
#
# ==== Specifying \Converters
#
# You can specify converters for parsing or generating in the +options+
# argument to various \CSV methods:
# - Option +converters+ for converting parsed field values.
# - Option +header_converters+ for converting parsed header values.
# - Option +write_converters+ for converting values to be written (generated).
#
# There are three forms for specifying converters:
# - A converter proc: executable code to be used for conversion.
# - A converter name: the name of a stored converter.
# - A converter list: an array of converter procs, converter names, and converter lists.
#
# ===== Converter Procs
#
# This converter proc, +strip_converter+, accepts a value +field+
# and returns <tt>field.strip</tt>:
#   strip_converter = proc {|field| field.strip }
# In this call to <tt>CSV.parse</tt>,
# the keyword argument <tt>converters: string_converter</tt>
# specifies that:
# - \Proc +string_converter+ is to be called for each parsed field.
# - The converter's return value is to replace the +field+ value.
# Example:
#   string = " foo , 0 \n bar , 1 \n baz , 2 \n"
#   array = CSV.parse(string, converters: strip_converter)
#   array # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]
#
# A converter proc can receive a second argument, +field_info+,
# that contains details about the field.
# This modified +strip_converter+ displays its arguments:
#   strip_converter = proc do |field, field_info|
#     p [field, field_info]
#     field.strip
#   end
#   string = " foo , 0 \n bar , 1 \n baz , 2 \n"
#   array = CSV.parse(string, converters: strip_converter)
#   array # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]
# Output:
#  [" foo ", #<struct CSV::FieldInfo index=0, line=1, header=nil>]
#  [" 0 ", #<struct CSV::FieldInfo index=1, line=1, header=nil>]
#  [" bar ", #<struct CSV::FieldInfo index=0, line=2, header=nil>]
#  [" 1 ", #<struct CSV::FieldInfo index=1, line=2, header=nil>]
#  [" baz ", #<struct CSV::FieldInfo index=0, line=3, header=nil>]
#  [" 2 ", #<struct CSV::FieldInfo index=1, line=3, header=nil>]
# Each CSV::Info object shows:
# - The 0-based field index.
# - The 1-based line index.
# - The field header, if any.
#
# ===== Stored \Converters
#
# A converter may be given a name and stored in a structure where
# the parsing methods can find it by name.
#
# The storage structure for field converters is the \Hash CSV::Converters.
# It has several built-in converter procs:
# - <tt>:integer</tt>: converts each \String-embedded integer into a true \Integer.
# - <tt>:float</tt>: converts each \String-embedded float into a true \Float.
# - <tt>:date</tt>: converts each \String-embedded date into a true \Date.
# - <tt>:date_time</tt>: converts each \String-embedded date-time into a true \DateTime
# .
# This example creates a converter proc, then stores it:
#   strip_converter = proc {|field| field.strip }
#   CSV::Converters[:strip] = strip_converter
# Then the parsing method call can refer to the converter
# by its name, <tt>:strip</tt>:
#   string = " foo , 0 \n bar , 1 \n baz , 2 \n"
#   array = CSV.parse(string, converters: :strip)
#   array # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]
#
# The storage structure for header converters is the \Hash CSV::HeaderConverters,
# which works in the same way.
# It also has built-in converter procs:
# - <tt>:downcase</tt>: Downcases each header.
# - <tt>:symbol</tt>: Converts each header to a \Symbol.
#
# There is no such storage structure for write headers.
#
# ===== Converter Lists
#
# A _converter_ _list_ is an \Array that may include any assortment of:
# - Converter procs.
# - Names of stored converters.
# - Nested converter lists.
#
# Examples:
#   numeric_converters = [:integer, :float]
#   date_converters = [:date, :date_time]
#   [numeric_converters, strip_converter]
#   [strip_converter, date_converters, :float]
#
# Like a converter proc, a converter list may be named and stored in either
# \CSV::Converters or CSV::HeaderConverters:
#   CSV::Converters[:custom] = [strip_converter, date_converters, :float]
#   CSV::HeaderConverters[:custom] = [:downcase, :symbol]
#
# There are two built-in converter lists:
#   CSV::Converters[:numeric] # => [:integer, :float]
#   CSV::Converters[:all] # => [:date_time, :numeric]
#
# ==== Field \Converters
#
# With no conversion, all parsed fields in all rows become Strings:
#   string = "foo,0\nbar,1\nbaz,2\n"
#   ary = CSV.parse(string)
#   ary # => # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]
#
# When you specify a field converter, each parsed field is passed to the converter;
# its return value becomes the stored value for the field.
# A converter might, for example, convert an integer embedded in a \String
# into a true \Integer.
# (In fact, that's what built-in field converter +:integer+ does.)
#
# There are three ways to use field \converters.
#
# - Using option {converters}[#class-CSV-label-Option+converters] with a parsing method:
#     ary = CSV.parse(string, converters: :integer)
#     ary # => [0, 1, 2] # => [["foo", 0], ["bar", 1], ["baz", 2]]
# - Using option {converters}[#class-CSV-label-Option+converters] with a new \CSV instance:
#     csv = CSV.new(string, converters: :integer)
#     # Field converters in effect:
#     csv.converters # => [:integer]
#     csv.read # => [["foo", 0], ["bar", 1], ["baz", 2]]
# - Using method #convert to add a field converter to a \CSV instance:
#     csv = CSV.new(string)
#     # Add a converter.
#     csv.convert(:integer)
#     csv.converters # => [:integer]
#     csv.read # => [["foo", 0], ["bar", 1], ["baz", 2]]
#
# Installing a field converter does not affect already-read rows:
#   csv = CSV.new(string)
#   csv.shift # => ["foo", "0"]
#   # Add a converter.
#   csv.convert(:integer)
#   csv.converters # => [:integer]
#   csv.read # => [["bar", 1], ["baz", 2]]
#
# There are additional built-in \converters, and custom \converters are also supported.
#
# ===== Built-In Field \Converters
#
# The built-in field converters are in \Hash CSV::Converters:
# - Each key is a field converter name.
# - Each value is one of:
#   - A \Proc field converter.
#   - An \Array of field converter names.
#
# Display:
#   CSV::Converters.each_pair do |name, value|
#     if value.kind_of?(Proc)
#       p [name, value.class]
#     else
#       p [name, value]
#     end
#   end
# Output:
#   [:integer, Proc]
#   [:float, Proc]
#   [:numeric, [:integer, :float]]
#   [:date, Proc]
#   [:date_time, Proc]
#   [:all, [:date_time, :numeric]]
#
# Each of these converters transcodes values to UTF-8 before attempting conversion.
# If a value cannot be transcoded to UTF-8 the conversion will
# fail and the value will remain unconverted.
#
# Converter +:integer+ converts each field that Integer() accepts:
#   data = '0,1,2,x'
#   # Without the converter
#   csv = CSV.parse_line(data)
#   csv # => ["0", "1", "2", "x"]
#   # With the converter
#   csv = CSV.parse_line(data, converters: :integer)
#   csv # => [0, 1, 2, "x"]
#
# Converter +:float+ converts each field that Float() accepts:
#   data = '1.0,3.14159,x'
#   # Without the converter
#   csv = CSV.parse_line(data)
#   csv # => ["1.0", "3.14159", "x"]
#   # With the converter
#   csv = CSV.parse_line(data, converters: :float)
#   csv # => [1.0, 3.14159, "x"]
#
# Converter +:numeric+ converts with both +:integer+ and +:float+..
#
# Converter +:date+ converts each field that Date::parse accepts:
#   data = '2001-02-03,x'
#   # Without the converter
#   csv = CSV.parse_line(data)
#   csv # => ["2001-02-03", "x"]
#   # With the converter
#   csv = CSV.parse_line(data, converters: :date)
#   csv # => [#<Date: 2001-02-03 ((2451944j,0s,0n),+0s,2299161j)>, "x"]
#
# Converter +:date_time+ converts each field that DateTime::parse accepts:
#   data = '2020-05-07T14:59:00-05:00,x'
#   # Without the converter
#   csv = CSV.parse_line(data)
#   csv # => ["2020-05-07T14:59:00-05:00", "x"]
#   # With the converter
#   csv = CSV.parse_line(data, converters: :date_time)
#   csv # => [#<DateTime: 2020-05-07T14:59:00-05:00 ((2458977j,71940s,0n),-18000s,2299161j)>, "x"]
#
# Converter +:numeric+ converts with both +:date_time+ and +:numeric+..
#
# As seen above, method #convert adds \converters to a \CSV instance,
# and method #converters returns an \Array of the \converters in effect:
#   csv = CSV.new('0,1,2')
#   csv.converters # => []
#   csv.convert(:integer)
#   csv.converters # => [:integer]
#   csv.convert(:date)
#   csv.converters # => [:integer, :date]
#
# ===== Custom Field \Converters
#
# You can define a custom field converter:
#   strip_converter = proc {|field| field.strip }
#   string = " foo , 0 \n bar , 1 \n baz , 2 \n"
#   array = CSV.parse(string, converters: strip_converter)
#   array # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]
# You can register the converter in \Converters \Hash,
# which allows you to refer to it by name:
#   CSV::Converters[:strip] = strip_converter
#   string = " foo , 0 \n bar , 1 \n baz , 2 \n"
#   array = CSV.parse(string, converters: :strip)
#   array # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]
#
# ==== Header \Converters
#
# Header converters operate only on headers (and not on other rows).
#
# There are three ways to use header \converters;
# these examples use built-in header converter +:dowhcase+,
# which downcases each parsed header.
#
# - Option +header_converters+ with a singleton parsing method:
#     string = "Name,Count\nFoo,0\n,Bar,1\nBaz,2"
#     tbl = CSV.parse(string, headers: true, header_converters: :downcase)
#     tbl.class # => CSV::Table
#     tbl.headers # => ["name", "count"]
#
# - Option +header_converters+ with a new \CSV instance:
#     csv = CSV.new(string, header_converters: :downcase)
#     # Header converters in effect:
#     csv.header_converters # => [:downcase]
#     tbl = CSV.parse(string, headers: true)
#     tbl.headers # => ["Name", "Count"]
#
# - Method #header_convert adds a header converter to a \CSV instance:
#     csv = CSV.new(string)
#     # Add a header converter.
#     csv.header_convert(:downcase)
#     csv.header_converters # => [:downcase]
#     tbl = CSV.parse(string, headers: true)
#     tbl.headers # => ["Name", "Count"]
#
# ===== Built-In Header \Converters
#
# The built-in header \converters are in \Hash CSV::HeaderConverters.
# The keys there are the names of the \converters:
#   CSV::HeaderConverters.keys # => [:downcase, :symbol]
#
# Converter +:downcase+ converts each header by downcasing it:
#   string = "Name,Count\nFoo,0\n,Bar,1\nBaz,2"
#   tbl = CSV.parse(string, headers: true, header_converters: :downcase)
#   tbl.class # => CSV::Table
#   tbl.headers # => ["name", "count"]
#
# Converter +:symbol+ converts each header by making it into a \Symbol:
#   string = "Name,Count\nFoo,0\n,Bar,1\nBaz,2"
#   tbl = CSV.parse(string, headers: true, header_converters: :symbol)
#   tbl.headers # => [:name, :count]
# Details:
# - Strips leading and trailing whitespace.
# - Downcases the header.
# - Replaces embedded spaces with underscores.
# - Removes non-word characters.
# - Makes the string into a \Symbol.
#
# ===== Custom Header \Converters
#
# You can define a custom header converter:
#   upcase_converter = proc {|header| header.upcase }
#   string = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
#   table = CSV.parse(string, headers: true, header_converters: upcase_converter)
#   table # => #<CSV::Table mode:col_or_row row_count:4>
#   table.headers # => ["NAME", "VALUE"]
# You can register the converter in \HeaderConverters \Hash,
# which allows you to refer to it by name:
#   CSV::HeaderConverters[:upcase] = upcase_converter
#   table = CSV.parse(string, headers: true, header_converters: :upcase)
#   table # => #<CSV::Table mode:col_or_row row_count:4>
#   table.headers # => ["NAME", "VALUE"]
#
# ===== Write \Converters
#
# When you specify a write converter for generating \CSV,
# each field to be written is passed to the converter;
# its return value becomes the new value for the field.
# A converter might, for example, strip whitespace from a field.
#
# Using no write converter (all fields unmodified):
#   output_string = CSV.generate do |csv|
#     csv << [' foo ', 0]
#     csv << [' bar ', 1]
#     csv << [' baz ', 2]
#   end
#   output_string # => " foo ,0\n bar ,1\n baz ,2\n"
# Using option +write_converters+ with two custom write converters:
#   strip_converter = proc {|field| field.respond_to?(:strip) ? field.strip : field }
#   upcase_converter = proc {|field| field.respond_to?(:upcase) ? field.upcase : field }
#   write_converters = [strip_converter, upcase_converter]
#   output_string = CSV.generate(write_converters: write_converters) do |csv|
#     csv << [' foo ', 0]
#     csv << [' bar ', 1]
#     csv << [' baz ', 2]
#   end
#   output_string # => "FOO,0\nBAR,1\nBAZ,2\n"
#
# === Character Encodings (M17n or Multilingualization)
#
# This new CSV parser is m17n savvy.  The parser works in the Encoding of the IO
# or String object being read from or written to. Your data is never transcoded
# (unless you ask Ruby to transcode it for you) and will literally be parsed in
# the Encoding it is in. Thus CSV will return Arrays or Rows of Strings in the
# Encoding of your data. This is accomplished by transcoding the parser itself
# into your Encoding.
#
# Some transcoding must take place, of course, to accomplish this multiencoding
# support. For example, <tt>:col_sep</tt>, <tt>:row_sep</tt>, and
# <tt>:quote_char</tt> must be transcoded to match your data.  Hopefully this
# makes the entire process feel transparent, since CSV's defaults should just
# magically work for your data. However, you can set these values manually in
# the target Encoding to avoid the translation.
#
# It's also important to note that while all of CSV's core parser is now
# Encoding agnostic, some features are not. For example, the built-in
# converters will try to transcode data to UTF-8 before making conversions.
# Again, you can provide custom converters that are aware of your Encodings to
# avoid this translation. It's just too hard for me to support native
# conversions in all of Ruby's Encodings.
#
# Anyway, the practical side of this is simple: make sure IO and String objects
# passed into CSV have the proper Encoding set and everything should just work.
# CSV methods that allow you to open IO objects (CSV::foreach(), CSV::open(),
# CSV::read(), and CSV::readlines()) do allow you to specify the Encoding.
#
# One minor exception comes when generating CSV into a String with an Encoding
# that is not ASCII compatible. There's no existing data for CSV to use to
# prepare itself and thus you will probably need to manually specify the desired
# Encoding for most of those cases. It will try to guess using the fields in a
# row of output though, when using CSV::generate_line() or Array#to_csv().
#
# I try to point out any other Encoding issues in the documentation of methods
# as they come up.
#
# This has been tested to the best of my ability with all non-"dummy" Encodings
# Ruby ships with. However, it is brave new code and may have some bugs.
# Please feel free to {report}[mailto:james@grayproductions.net] any issues you
# find with it.
#
class CSV

  # The error thrown when the parser encounters illegal CSV formatting.
  class MalformedCSVError < RuntimeError
    attr_reader :line_number
    alias_method :lineno, :line_number
    def initialize(message, line_number)
      @line_number = line_number
      super("#{message} in line #{line_number}.")
    end
  end

  #
  # A FieldInfo Struct contains details about a field's position in the data
  # source it was read from.  CSV will pass this Struct to some blocks that make
  # decisions based on field structure.  See CSV.convert_fields() for an
  # example.
  #
  # <b><tt>index</tt></b>::  The zero-based index of the field in its row.
  # <b><tt>line</tt></b>::   The line of the data source this row is from.
  # <b><tt>header</tt></b>:: The header for the column, when available.
  #
  FieldInfo = Struct.new(:index, :line, :header)

  # A Regexp used to find and convert some common Date formats.
  DateMatcher     = / \A(?: (\w+,?\s+)?\w+\s+\d{1,2},?\s+\d{2,4} |
                            \d{4}-\d{2}-\d{2} )\z /x
  # A Regexp used to find and convert some common DateTime formats.
  DateTimeMatcher =
    / \A(?: (\w+,?\s+)?\w+\s+\d{1,2}\s+\d{1,2}:\d{1,2}:\d{1,2},?\s+\d{2,4} |
            \d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2} |
            # ISO-8601
            \d{4}-\d{2}-\d{2}
              (?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?(?:[+-]\d{2}(?::\d{2})|Z)?)?)?
        )\z /x

  # The encoding used by all converters.
  ConverterEncoding = Encoding.find("UTF-8")

  # A \Hash containing the names and \Procs for the built-in field converters.
  # See {Built-In Field Converters}[#class-CSV-label-Built-In+Field+Converters].
  #
  # This \Hash is intentionally left unfrozen, and may be extended with
  # custom field converters.
  # See {Custom Field Converters}[#class-CSV-label-Custom+Field+Converters].
  Converters  = {
    integer:   lambda { |f|
      Integer(f.encode(ConverterEncoding)) rescue f
    },
    float:     lambda { |f|
      Float(f.encode(ConverterEncoding)) rescue f
    },
    numeric:   [:integer, :float],
    date:      lambda { |f|
      begin
        e = f.encode(ConverterEncoding)
        e.match?(DateMatcher) ? Date.parse(e) : f
      rescue  # encoding conversion or date parse errors
        f
      end
    },
    date_time: lambda { |f|
      begin
        e = f.encode(ConverterEncoding)
        e.match?(DateTimeMatcher) ? DateTime.parse(e) : f
      rescue  # encoding conversion or date parse errors
        f
      end
    },
    all:       [:date_time, :numeric],
  }

  # A \Hash containing the names and \Procs for the built-in header converters.
  # See {Built-In Header Converters}[#class-CSV-label-Built-In+Header+Converters].
  #
  # This \Hash is intentionally left unfrozen, and may be extended with
  # custom field converters.
  # See {Custom Header Converters}[#class-CSV-label-Custom+Header+Converters].
  HeaderConverters = {
    downcase: lambda { |h| h.encode(ConverterEncoding).downcase },
    symbol:   lambda { |h|
      h.encode(ConverterEncoding).downcase.gsub(/[^\s\w]+/, "").strip.
                                           gsub(/\s+/, "_").to_sym
    }
  }
  # Default values for method options.
  DEFAULT_OPTIONS = {
    # For both parsing and generating.
    col_sep:            ",",
    row_sep:            :auto,
    quote_char:         '"',
    # For parsing.
    field_size_limit:   nil,
    converters:         nil,
    unconverted_fields: nil,
    headers:            false,
    return_headers:     false,
    header_converters:  nil,
    skip_blanks:        false,
    skip_lines:         nil,
    liberal_parsing:    false,
    nil_value:          nil,
    empty_value:        "",
    # For generating.
    write_headers:      nil,
    quote_empty:        true,
    force_quotes:       false,
    write_converters:   nil,
    write_nil_value:    nil,
    write_empty_value:  "",
    strip:              false,
  }.freeze

  class << self
    # :call-seq:
    #   instance(string, **options)
    #   instance(io = $stdout, **options)
    #   instance(string, **options) {|csv| ... }
    #   instance(io = $stdout, **options) {|csv| ... }
    #
    # Creates or retrieves cached \CSV objects.
    # For arguments and options, see CSV.new.
    #
    # ---
    #
    # With no block given, returns a \CSV object.
    #
    # The first call to +instance+ creates and caches a \CSV object:
    #   s0 = 's0'
    #   csv0 = CSV.instance(s0)
    #   csv0.class # => CSV
    #
    # Subsequent calls to +instance+ with that _same_ +string+ or +io+
    # retrieve that same cached object:
    #   csv1 = CSV.instance(s0)
    #   csv1.class # => CSV
    #   csv1.equal?(csv0) # => true # Same CSV object
    #
    # A subsequent call to +instance+ with a _different_ +string+ or +io+
    # creates and caches a _different_ \CSV object.
    #   s1 = 's1'
    #   csv2 = CSV.instance(s1)
    #   csv2.equal?(csv0) # => false # Different CSV object
    #
    # All the cached objects remains available:
    #   csv3 = CSV.instance(s0)
    #   csv3.equal?(csv0) # true # Same CSV object
    #   csv4 = CSV.instance(s1)
    #   csv4.equal?(csv2) # true # Same CSV object
    #
    # ---
    #
    # When a block is given, calls the block with the created or retrieved
    # \CSV object; returns the block's return value:
    #   CSV.instance(s0) {|csv| :foo } # => :foo
    def instance(data = $stdout, **options)
      # create a _signature_ for this method call, data object and options
      sig = [data.object_id] +
            options.values_at(*DEFAULT_OPTIONS.keys.sort_by { |sym| sym.to_s })

      # fetch or create the instance for this signature
      @@instances ||= Hash.new
      instance = (@@instances[sig] ||= new(data, **options))

      if block_given?
        yield instance  # run block, if given, returning result
      else
        instance        # or return the instance
      end
    end

    # :call-seq:
    #   filter(**options) {|row| ... }
    #   filter(in_string, **options) {|row| ... }
    #   filter(in_io, **options) {|row| ... }
    #   filter(in_string, out_string, **options) {|row| ... }
    #   filter(in_string, out_io, **options) {|row| ... }
    #   filter(in_io, out_string, **options) {|row| ... }
    #   filter(in_io, out_io, **options) {|row| ... }
    #
    # Reads \CSV input and writes \CSV output.
    #
    # For each input row:
    # - Forms the data into:
    #   - A CSV::Row object, if headers are in use.
    #   - An \Array of Arrays, otherwise.
    # - Calls the block with that object.
    # - Appends the block's return value to the output.
    #
    # Arguments:
    # * \CSV source:
    #   * Argument +in_string+, if given, should be a \String object;
    #     it will be put into a new StringIO object positioned at the beginning.
    #   * Argument +in_io+, if given, should be an IO object that is
    #     open for reading; on return, the IO object will be closed.
    #   * If neither  +in_string+ nor +in_io+ is given,
    #     the input stream defaults to {ARGF}[https://ruby-doc.org/core/ARGF.html].
    # * \CSV output:
    #   * Argument +out_string+, if given, should be a \String object;
    #     it will be put into a new StringIO object positioned at the beginning.
    #   * Argument +out_io+, if given, should be an IO object that is
    #     ppen for writing; on return, the IO object will be closed.
    #   * If neither +out_string+ nor +out_io+ is given,
    #     the output stream defaults to <tt>$stdout</tt>.
    # * Argument +options+ should be keyword arguments.
    #   - Each argument name that is prefixed with +in_+ or +input_+
    #     is stripped of its prefix and is treated as an option
    #     for parsing the input.
    #     Option +input_row_sep+ defaults to <tt>$INPUT_RECORD_SEPARATOR</tt>.
    #   - Each argument name that is prefixed with +out_+ or +output_+
    #     is stripped of its prefix and is treated as an option
    #     for generating the output.
    #     Option +output_row_sep+ defaults to <tt>$INPUT_RECORD_SEPARATOR</tt>.
    #   - Each argument not prefixed as above is treated as an option
    #     both for parsing the input and for generating the output.
    #   - See {Options for Parsing}[#class-CSV-label-Options+for+Parsing]
    #     and {Options for Generating}[#class-CSV-label-Options+for+Generating].
    #
    # Example:
    #   in_string = "foo,0\nbar,1\nbaz,2\n"
    #   out_string = ''
    #   CSV.filter(in_string, out_string) do |row|
    #     row[0] = row[0].upcase
    #     row[1] *= 4
    #   end
    #   out_string # => "FOO,0000\nBAR,1111\nBAZ,2222\n"
    def filter(input=nil, output=nil, **options)
      # parse options for input, output, or both
      in_options, out_options = Hash.new, {row_sep: $INPUT_RECORD_SEPARATOR}
      options.each do |key, value|
        case key.to_s
        when /\Ain(?:put)?_(.+)\Z/
          in_options[$1.to_sym] = value
        when /\Aout(?:put)?_(.+)\Z/
          out_options[$1.to_sym] = value
        else
          in_options[key]  = value
          out_options[key] = value
        end
      end

      # build input and output wrappers
      input  = new(input  || ARGF, **in_options)
      output = new(output || $stdout, **out_options)

      # process headers
      need_manual_header_output =
        (in_options[:headers] and
         out_options[:headers] == true and
         out_options[:write_headers])
      if need_manual_header_output
        first_row = input.shift
        if first_row
          if first_row.is_a?(Row)
            headers = first_row.headers
            yield headers
            output << headers
          end
          yield first_row
          output << first_row
        end
      end

      # read, yield, write
      input.each do |row|
        yield row
        output << row
      end
    end

    #
    # :call-seq:
    #   foreach(path, mode='r', **options) {|row| ... )
    #   foreach(io, mode='r', **options {|row| ... )
    #   foreach(path, mode='r', headers: ..., **options) {|row| ... )
    #   foreach(io, mode='r', headers: ..., **options {|row| ... )
    #   foreach(path, mode='r', **options) -> new_enumerator
    #   foreach(io, mode='r', **options -> new_enumerator
    #
    # Calls the block with each row read from source +path+ or +io+.
    #
    # * Argument +path+, if given, must be the path to a file.
    # :include: ../doc/csv/arguments/io.rdoc
    # * Argument +mode+, if given, must be a \File mode
    #   See {Open Mode}[IO.html#method-c-new-label-Open+Mode].
    # * Arguments <tt>**options</tt> must be keyword options.
    #   See {Options for Parsing}[#class-CSV-label-Options+for+Parsing].
    # * This method optionally accepts an additional <tt>:encoding</tt> option
    #   that you can use to specify the Encoding of the data read from +path+ or +io+.
    #   You must provide this unless your data is in the encoding
    #   given by <tt>Encoding::default_external</tt>.
    #   Parsing will use this to determine how to parse the data.
    #   You may provide a second Encoding to
    #   have the data transcoded as it is read. For example,
    #     encoding: 'UTF-32BE:UTF-8'
    #   would read +UTF-32BE+ data from the file
    #   but transcode it to +UTF-8+ before parsing.
    #
    # ====== Without Option +headers+
    #
    # Without option +headers+, returns each row as an \Array object.
    #
    # These examples assume prior execution of:
    #   string = "foo,0\nbar,1\nbaz,2\n"
    #   path = 't.csv'
    #   File.write(path, string)
    #
    # Read rows from a file at +path+:
    #   CSV.foreach(path) {|row| p row }
    # Output:
    #   ["foo", "0"]
    #   ["bar", "1"]
    #   ["baz", "2"]
    #
    # Read rows from an \IO object:
    #   File.open(path) do |file|
    #     CSV.foreach(file) {|row| p row }
    #   end
    #
    # Output:
    #   ["foo", "0"]
    #   ["bar", "1"]
    #   ["baz", "2"]
    #
    # Returns a new \Enumerator if no block given:
    #   CSV.foreach(path) # => #<Enumerator: CSV:foreach("t.csv", "r")>
    #   CSV.foreach(File.open(path)) # => #<Enumerator: CSV:foreach(#<File:t.csv>, "r")>
    #
    # Issues a warning if an encoding is unsupported:
    #   CSV.foreach(File.open(path), encoding: 'foo:bar') {|row| }
    # Output:
    #   warning: Unsupported encoding foo ignored
    #   warning: Unsupported encoding bar ignored
    #
    # ====== With Option +headers+
    #
    # With {option +headers+}[#class-CSV-label-Option+headers],
    # returns each row as a CSV::Row object.
    #
    # These examples assume prior execution of:
    #   string = "Name,Count\nfoo,0\nbar,1\nbaz,2\n"
    #   path = 't.csv'
    #   File.write(path, string)
    #
    # Read rows from a file at +path+:
    #   CSV.foreach(path, headers: true) {|row| p row }
    #
    # Output:
    #   #<CSV::Row "Name":"foo" "Count":"0">
    #   #<CSV::Row "Name":"bar" "Count":"1">
    #   #<CSV::Row "Name":"baz" "Count":"2">
    #
    # Read rows from an \IO object:
    #   File.open(path) do |file|
    #     CSV.foreach(file, headers: true) {|row| p row }
    #   end
    #
    # Output:
    #   #<CSV::Row "Name":"foo" "Count":"0">
    #   #<CSV::Row "Name":"bar" "Count":"1">
    #   #<CSV::Row "Name":"baz" "Count":"2">
    #
    # ---
    #
    # Raises an exception if +path+ is a \String, but not the path to a readable file:
    #   # Raises Errno::ENOENT (No such file or directory @ rb_sysopen - nosuch.csv):
    #   CSV.foreach('nosuch.csv') {|row| }
    #
    # Raises an exception if +io+ is an \IO object, but not open for reading:
    #   io = File.open(path, 'w') {|row| }
    #   # Raises TypeError (no implicit conversion of nil into String):
    #   CSV.foreach(io) {|row| }
    #
    # Raises an exception if +mode+ is invalid:
    #   # Raises ArgumentError (invalid access mode nosuch):
    #   CSV.foreach(path, 'nosuch') {|row| }
    #
    def foreach(path, mode="r", **options, &block)
      return to_enum(__method__, path, mode, **options) unless block_given?
      open(path, mode, **options) do |csv|
        csv.each(&block)
      end
    end

    #
    # :call-seq:
    #   generate(csv_string, **options) {|csv| ... }
    #   generate(**options) {|csv| ... }
    #
    # * Argument +csv_string+, if given, must be a \String object;
    #   defaults to a new empty \String.
    # * Arguments +options+, if given, should be generating options.
    #   See {Options for Generating}[#class-CSV-label-Options+for+Generating].
    #
    # ---
    #
    # Creates a new \CSV object via <tt>CSV.new(csv_string, **options)</tt>;
    # calls the block with the \CSV object, which the block may modify;
    # returns the \String generated from the \CSV object.
    #
    # Note that a passed \String *is* modified by this method.
    # Pass <tt>csv_string</tt>.dup if the \String must be preserved.
    #
    # This method has one additional option: <tt>:encoding</tt>,
    # which sets the base Encoding for the output if no no +str+ is specified.
    # CSV needs this hint if you plan to output non-ASCII compatible data.
    #
    # ---
    #
    # Add lines:
    #   input_string = "foo,0\nbar,1\nbaz,2\n"
    #   output_string = CSV.generate(input_string) do |csv|
    #     csv << ['bat', 3]
    #     csv << ['bam', 4]
    #   end
    #   output_string # => "foo,0\nbar,1\nbaz,2\nbat,3\nbam,4\n"
    #   input_string # => "foo,0\nbar,1\nbaz,2\nbat,3\nbam,4\n"
    #   output_string.equal?(input_string) # => true # Same string, modified
    #
    # Add lines into new string, preserving old string:
    #   input_string = "foo,0\nbar,1\nbaz,2\n"
    #   output_string = CSV.generate(input_string.dup) do |csv|
    #     csv << ['bat', 3]
    #     csv << ['bam', 4]
    #   end
    #   output_string # => "foo,0\nbar,1\nbaz,2\nbat,3\nbam,4\n"
    #   input_string # => "foo,0\nbar,1\nbaz,2\n"
    #   output_string.equal?(input_string) # => false # Different strings
    #
    # Create lines from nothing:
    #   output_string = CSV.generate do |csv|
    #     csv << ['foo', 0]
    #     csv << ['bar', 1]
    #     csv << ['baz', 2]
    #   end
    #   output_string # => "foo,0\nbar,1\nbaz,2\n"
    #
    # ---
    #
    # Raises an exception if +csv_string+ is not a \String object:
    #   # Raises TypeError (no implicit conversion of Integer into String)
    #   CSV.generate(0)
    #
    def generate(str=nil, **options)
      encoding = options[:encoding]
      # add a default empty String, if none was given
      if str
        str = StringIO.new(str)
        str.seek(0, IO::SEEK_END)
        str.set_encoding(encoding) if encoding
      else
        str = +""
        str.force_encoding(encoding) if encoding
      end
      csv = new(str, **options) # wrap
      yield csv         # yield for appending
      csv.string        # return final String
    end

    # :call-seq:
    #   CSV.generate_line(ary)
    #   CSV.generate_line(ary, **options)
    #
    # Returns the \String created by generating \CSV from +ary+
    # using the specified +options+.
    #
    # Argument +ary+ must be an \Array.
    #
    # Special options:
    # * Option <tt>:row_sep</tt> defaults to <tt>$INPUT_RECORD_SEPARATOR</tt>
    #   (<tt>$/</tt>).:
    #     $INPUT_RECORD_SEPARATOR # => "\n"
    # * This method accepts an additional option, <tt>:encoding</tt>, which sets the base
    #   Encoding for the output. This method will try to guess your Encoding from
    #   the first non-+nil+ field in +row+, if possible, but you may need to use
    #   this parameter as a backup plan.
    #
    # For other +options+,
    # see {Options for Generating}[#class-CSV-label-Options+for+Generating].
    #
    # ---
    #
    # Returns the \String generated from an \Array:
    #   CSV.generate_line(['foo', '0']) # => "foo,0\n"
    #
    # ---
    #
    # Raises an exception if +ary+ is not an \Array:
    #   # Raises NoMethodError (undefined method `find' for :foo:Symbol)
    #   CSV.generate_line(:foo)
    #
    def generate_line(row, **options)
      options = {row_sep: $INPUT_RECORD_SEPARATOR}.merge(options)
      str = +""
      if options[:encoding]
        str.force_encoding(options[:encoding])
      else
        fallback_encoding = nil
        output_encoding = nil
        row.each do |field|
          next unless field.is_a?(String)
          fallback_encoding ||= field.encoding
          next if field.ascii_only?
          output_encoding = field.encoding
          break
        end
        output_encoding ||= fallback_encoding
        if output_encoding
          str.force_encoding(output_encoding)
        end
      end
      (new(str, **options) << row).string
    end

    #
    # :call-seq:
    #   open(file_path, mode = "rb", **options ) -> new_csv
    #   open(io, mode = "rb", **options ) -> new_csv
    #   open(file_path, mode = "rb", **options ) { |csv| ... } -> object
    #   open(io, mode = "rb", **options ) { |csv| ... } -> object
    #
    # possible options elements:
    #   hash form:
    #     :invalid => nil      # raise error on invalid byte sequence (default)
    #     :invalid => :replace # replace invalid byte sequence
    #     :undef => :replace   # replace undefined conversion
    #     :replace => string   # replacement string ("?" or "\uFFFD" if not specified)
    #
    # * Argument +path+, if given, must be the path to a file.
    # :include: ../doc/csv/arguments/io.rdoc
    # * Argument +mode+, if given, must be a \File mode
    #   See {Open Mode}[IO.html#method-c-new-label-Open+Mode].
    # * Arguments <tt>**options</tt> must be keyword options.
    #   See {Options for Generating}[#class-CSV-label-Options+for+Generating].
    # * This method optionally accepts an additional <tt>:encoding</tt> option
    #   that you can use to specify the Encoding of the data read from +path+ or +io+.
    #   You must provide this unless your data is in the encoding
    #   given by <tt>Encoding::default_external</tt>.
    #   Parsing will use this to determine how to parse the data.
    #   You may provide a second Encoding to
    #   have the data transcoded as it is read. For example,
    #     encoding: 'UTF-32BE:UTF-8'
    #   would read +UTF-32BE+ data from the file
    #   but transcode it to +UTF-8+ before parsing.
    #
    # ---
    #
    # These examples assume prior execution of:
    #   string = "foo,0\nbar,1\nbaz,2\n"
    #   path = 't.csv'
    #   File.write(path, string)
    #
    # ---
    #
    # With no block given, returns a new \CSV object.
    #
    # Create a \CSV object using a file path:
    #   csv = CSV.open(path)
    #   csv # => #<CSV io_type:File io_path:"t.csv" encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">
    #
    # Create a \CSV object using an open \File:
    #   csv = CSV.open(File.open(path))
    #   csv # => #<CSV io_type:File io_path:"t.csv" encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">
    #
    # ---
    #
    # With a block given, calls the block with the created \CSV object;
    # returns the block's return value:
    #
    # Using a file path:
    #   csv = CSV.open(path) {|csv| p csv}
    #   csv # => #<CSV io_type:File io_path:"t.csv" encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">
    # Output:
    #   #<CSV io_type:File io_path:"t.csv" encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">
    #
    # Using an open \File:
    #   csv = CSV.open(File.open(path)) {|csv| p csv}
    #   csv # => #<CSV io_type:File io_path:"t.csv" encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">
    # Output:
    #   #<CSV io_type:File io_path:"t.csv" encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">
    #
    # ---
    #
    # Raises an exception if the argument is not a \String object or \IO object:
    #   # Raises TypeError (no implicit conversion of Symbol into String)
    #   CSV.open(:foo)
    def open(filename, mode="r", **options)
      # wrap a File opened with the remaining +args+ with no newline
      # decorator
      file_opts = {universal_newline: false}.merge(options)
      options.delete(:invalid)
      options.delete(:undef)
      options.delete(:replace)

      begin
        f = File.open(filename, mode, **file_opts)
      rescue ArgumentError => e
        raise unless /needs binmode/.match?(e.message) and mode == "r"
        mode = "rb"
        file_opts = {encoding: Encoding.default_external}.merge(file_opts)
        retry
      end
      begin
        csv = new(f, **options)
      rescue Exception
        f.close
        raise
      end

      # handle blocks like Ruby's open(), not like the CSV library
      if block_given?
        begin
          yield csv
        ensure
          csv.close
        end
      else
        csv
      end
    end

    #
    # :call-seq:
    #   parse(string) -> array_of_arrays
    #   parse(io) -> array_of_arrays
    #   parse(string, headers: ..., **options) -> csv_table
    #   parse(io, headers: ..., **options) -> csv_table
    #   parse(string, **options) {|row| ... }
    #   parse(io, **options) {|row| ... }
    #
    # Parses +string+ or +io+ using the specified +options+.
    #
    # - Argument +string+ should be a \String object;
    #   it will be put into a new StringIO object positioned at the beginning.
    # :include: ../doc/csv/arguments/io.rdoc
    # - Argument +options+: see {Options for Parsing}[#class-CSV-label-Options+for+Parsing]
    #
    # ====== Without Option +headers+
    #
    # Without {option +headers+}[#class-CSV-label-Option+headers] case.
    #
    # These examples assume prior execution of:
    #   string = "foo,0\nbar,1\nbaz,2\n"
    #   path = 't.csv'
    #   File.write(path, string)
    #
    # ---
    #
    # With no block given, returns an \Array of Arrays formed from the source.
    #
    # Parse a \String:
    #   a_of_a = CSV.parse(string)
    #   a_of_a # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]
    #
    # Parse an open \File:
    #   a_of_a = File.open(path) do |file|
    #     CSV.parse(file)
    #   end
    #   a_of_a # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]
    #
    # ---
    #
    # With a block given, calls the block with each parsed row:
    #
    # Parse a \String:
    #   CSV.parse(string) {|row| p row }
    #
    # Output:
    #   ["foo", "0"]
    #   ["bar", "1"]
    #   ["baz", "2"]
    #
    # Parse an open \File:
    #   File.open(path) do |file|
    #     CSV.parse(file) {|row| p row }
    #   end
    #
    # Output:
    #   ["foo", "0"]
    #   ["bar", "1"]
    #   ["baz", "2"]
    #
    # ====== With Option +headers+
    #
    # With {option +headers+}[#class-CSV-label-Option+headers] case.
    #
    # These examples assume prior execution of:
    #   string = "Name,Count\nfoo,0\nbar,1\nbaz,2\n"
    #   path = 't.csv'
    #   File.write(path, string)
    #
    # ---
    #
    # With no block given, returns a CSV::Table object formed from the source.
    #
    # Parse a \String:
    #   csv_table = CSV.parse(string, headers: ['Name', 'Count'])
    #   csv_table # => #<CSV::Table mode:col_or_row row_count:5>
    #
    # Parse an open \File:
    #   csv_table = File.open(path) do |file|
    #     CSV.parse(file, headers: ['Name', 'Count'])
    #   end
    #   csv_table # => #<CSV::Table mode:col_or_row row_count:4>
    #
    # ---
    #
    # With a block given, calls the block with each parsed row,
    # which has been formed into a CSV::Row object:
    #
    # Parse a \String:
    #   CSV.parse(string, headers: ['Name', 'Count']) {|row| p row }
    #
    # Output:
    #   # <CSV::Row "Name":"foo" "Count":"0">
    #   # <CSV::Row "Name":"bar" "Count":"1">
    #   # <CSV::Row "Name":"baz" "Count":"2">
    #
    # Parse an open \File:
    #   File.open(path) do |file|
    #     CSV.parse(file, headers: ['Name', 'Count']) {|row| p row }
    #   end
    #
    # Output:
    #   # <CSV::Row "Name":"foo" "Count":"0">
    #   # <CSV::Row "Name":"bar" "Count":"1">
    #   # <CSV::Row "Name":"baz" "Count":"2">
    #
    # ---
    #
    # Raises an exception if the argument is not a \String object or \IO object:
    #   # Raises NoMethodError (undefined method `close' for :foo:Symbol)
    #   CSV.parse(:foo)
    def parse(str, **options, &block)
      csv = new(str, **options)

      return csv.each(&block) if block_given?

      # slurp contents, if no block is given
      begin
        csv.read
      ensure
        csv.close
      end
    end

    # :call-seq:
    #   CSV.parse_line(string) -> new_array or nil
    #   CSV.parse_line(io) -> new_array or nil
    #   CSV.parse_line(string, **options) -> new_array or nil
    #   CSV.parse_line(io, **options) -> new_array or nil
    #   CSV.parse_line(string, headers: true, **options) -> csv_row or nil
    #   CSV.parse_line(io, headers: true, **options) -> csv_row or nil
    #
    # Returns the data created by parsing the first line of +string+ or +io+
    # using the specified +options+.
    #
    # - Argument +string+ should be a \String object;
    #   it will be put into a new StringIO object positioned at the beginning.
    # :include: ../doc/csv/arguments/io.rdoc
    # - Argument +options+: see {Options for Parsing}[#class-CSV-label-Options+for+Parsing]
    #
    # ====== Without Option +headers+
    #
    # Without option +headers+, returns the first row as a new \Array.
    #
    # These examples assume prior execution of:
    #   string = "foo,0\nbar,1\nbaz,2\n"
    #   path = 't.csv'
    #   File.write(path, string)
    #
    # Parse the first line from a \String object:
    #   CSV.parse_line(string) # => ["foo", "0"]
    #
    # Parse the first line from a File object:
    #   File.open(path) do |file|
    #     CSV.parse_line(file) # => ["foo", "0"]
    #   end # => ["foo", "0"]
    #
    # Returns +nil+ if the argument is an empty \String:
    #   CSV.parse_line('') # => nil
    #
    # ====== With Option +headers+
    #
    # With {option +headers+}[#class-CSV-label-Option+headers],
    # returns the first row as a CSV::Row object.
    #
    # These examples assume prior execution of:
    #   string = "Name,Count\nfoo,0\nbar,1\nbaz,2\n"
    #   path = 't.csv'
    #   File.write(path, string)
    #
    # Parse the first line from a \String object:
    #   CSV.parse_line(string, headers: true) # => #<CSV::Row "Name":"foo" "Count":"0">
    #
    # Parse the first line from a File object:
    #   File.open(path) do |file|
    #     CSV.parse_line(file, headers: true)
    #   end # => #<CSV::Row "Name":"foo" "Count":"0">
    #
    # ---
    #
    # Raises an exception if the argument is +nil+:
    #   # Raises ArgumentError (Cannot parse nil as CSV):
    #   CSV.parse_line(nil)
    #
    def parse_line(line, **options)
      new(line, **options).each.first
    end

    #
    # :call-seq:
    #   read(source, **options) -> array_of_arrays
    #   read(source, headers: true, **options) -> csv_table
    #
    # Opens the given +source+ with the given +options+ (see CSV.open),
    # reads the source (see CSV#read), and returns the result,
    # which will be either an \Array of Arrays or a CSV::Table.
    #
    # Without headers:
    #   string = "foo,0\nbar,1\nbaz,2\n"
    #   path = 't.csv'
    #   File.write(path, string)
    #   CSV.read(path) # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]
    #
    # With headers:
    #   string = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   path = 't.csv'
    #   File.write(path, string)
    #   CSV.read(path, headers: true) # => #<CSV::Table mode:col_or_row row_count:4>
    def read(path, **options)
      open(path, **options) { |csv| csv.read }
    end

    # :call-seq:
    #   CSV.readlines(source, **options)
    #
    # Alias for CSV.read.
    def readlines(path, **options)
      read(path, **options)
    end

    # :call-seq:
    #   CSV.table(source, **options)
    #
    # Calls CSV.read with +source+, +options+, and certain default options:
    # - +headers+: +true+
    # - +converbers+: +:numeric+
    # - +header_converters+: +:symbol+
    #
    # Returns a CSV::Table object.
    #
    # Example:
    #   string = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   path = 't.csv'
    #   File.write(path, string)
    #   CSV.table(path) # => #<CSV::Table mode:col_or_row row_count:4>
    def table(path, **options)
      default_options = {
        headers:           true,
        converters:        :numeric,
        header_converters: :symbol,
      }
      options = default_options.merge(options)
      read(path, **options)
    end
  end

  # :call-seq:
  #   CSV.new(string)
  #   CSV.new(io)
  #   CSV.new(string, **options)
  #   CSV.new(io, **options)
  #
  # Returns the new \CSV object created using +string+ or +io+
  # and the specified +options+.
  #
  # - Argument +string+ should be a \String object;
  #   it will be put into a new StringIO object positioned at the beginning.
  # :include: ../doc/csv/arguments/io.rdoc
  # - Argument +options+: See:
  #   * {Options for Parsing}[#class-CSV-label-Options+for+Parsing]
  #   * {Options for Generating}[#class-CSV-label-Options+for+Generating]
  #   For performance reasons, the options cannot be overridden
  #   in a \CSV object, so those specified here will endure.
  #
  # In addition to the \CSV instance methods, several \IO methods are delegated.
  # See {Delegated Methods}[#class-CSV-label-Delegated+Methods].
  #
  # ---
  #
  # Create a \CSV object from a \String object:
  #   csv = CSV.new('foo,0')
  #   csv # => #<CSV io_type:StringIO encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">
  #
  # Create a \CSV object from a \File object:
  #   File.write('t.csv', 'foo,0')
  #   csv = CSV.new(File.open('t.csv'))
  #   csv # => #<CSV io_type:File io_path:"t.csv" encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">
  #
  # ---
  #
  # Raises an exception if the argument is +nil+:
  #   # Raises ArgumentError (Cannot parse nil as CSV):
  #   CSV.new(nil)
  #
  def initialize(data,
                 col_sep: ",",
                 row_sep: :auto,
                 quote_char: '"',
                 field_size_limit: nil,
                 converters: nil,
                 unconverted_fields: nil,
                 headers: false,
                 return_headers: false,
                 write_headers: nil,
                 header_converters: nil,
                 skip_blanks: false,
                 force_quotes: false,
                 skip_lines: nil,
                 liberal_parsing: false,
                 internal_encoding: nil,
                 external_encoding: nil,
                 encoding: nil,
                 nil_value: nil,
                 empty_value: "",
                 quote_empty: true,
                 write_converters: nil,
                 write_nil_value: nil,
                 write_empty_value: "",
                 strip: false)
    raise ArgumentError.new("Cannot parse nil as CSV") if data.nil?

    if data.is_a?(String)
      @io = StringIO.new(data)
      @io.set_encoding(encoding || data.encoding)
    else
      @io = data
    end
    @encoding = determine_encoding(encoding, internal_encoding)

    @base_fields_converter_options = {
      nil_value: nil_value,
      empty_value: empty_value,
    }
    @write_fields_converter_options = {
      nil_value: write_nil_value,
      empty_value: write_empty_value,
    }
    @initial_converters = converters
    @initial_header_converters = header_converters
    @initial_write_converters = write_converters

    @parser_options = {
      column_separator: col_sep,
      row_separator: row_sep,
      quote_character: quote_char,
      field_size_limit: field_size_limit,
      unconverted_fields: unconverted_fields,
      headers: headers,
      return_headers: return_headers,
      skip_blanks: skip_blanks,
      skip_lines: skip_lines,
      liberal_parsing: liberal_parsing,
      encoding: @encoding,
      nil_value: nil_value,
      empty_value: empty_value,
      strip: strip,
    }
    @parser = nil
    @parser_enumerator = nil
    @eof_error = nil

    @writer_options = {
      encoding: @encoding,
      force_encoding: (not encoding.nil?),
      force_quotes: force_quotes,
      headers: headers,
      write_headers: write_headers,
      column_separator: col_sep,
      row_separator: row_sep,
      quote_character: quote_char,
      quote_empty: quote_empty,
    }

    @writer = nil
    writer if @writer_options[:write_headers]
  end

  # :call-seq:
  #   csv.col_sep -> string
  #
  # Returns the encoded column separator; used for parsing and writing;
  # see {Option +col_sep+}[#class-CSV-label-Option+col_sep]:
  #   CSV.new('').col_sep # => ","
  def col_sep
    parser.column_separator
  end

  # :call-seq:
  #   csv.row_sep -> string
  #
  # Returns the encoded row separator; used for parsing and writing;
  # see {Option +row_sep+}[#class-CSV-label-Option+row_sep]:
  #   CSV.new('').row_sep # => "\n"
  def row_sep
    parser.row_separator
  end

  # :call-seq:
  #   csv.quote_char -> character
  #
  # Returns the encoded quote character; used for parsing and writing;
  # see {Option +quote_char+}[#class-CSV-label-Option+quote_char]:
  #   CSV.new('').quote_char # => "\""
  def quote_char
    parser.quote_character
  end

  # :call-seq:
  #   csv.field_size_limit -> integer or nil
  #
  # Returns the limit for field size; used for parsing;
  # see {Option +field_size_limit+}[#class-CSV-label-Option+field_size_limit]:
  #   CSV.new('').field_size_limit # => nil
  def field_size_limit
    parser.field_size_limit
  end

  # :call-seq:
  #   csv.skip_lines -> regexp or nil
  #
  # Returns the \Regexp used to identify comment lines; used for parsing;
  # see {Option +skip_lines+}[#class-CSV-label-Option+skip_lines]:
  #   CSV.new('').skip_lines # => nil
  def skip_lines
    parser.skip_lines
  end

  # :call-seq:
  #   csv.converters -> array
  #
  # Returns an \Array containing field converters;
  # see {Field Converters}[#class-CSV-label-Field+Converters]:
  #   csv = CSV.new('')
  #   csv.converters # => []
  #   csv.convert(:integer)
  #   csv.converters # => [:integer]
  #   csv.convert(proc {|x| x.to_s })
  #   csv.converters
  def converters
    parser_fields_converter.map do |converter|
      name = Converters.rassoc(converter)
      name ? name.first : converter
    end
  end

  # :call-seq:
  #   csv.unconverted_fields? -> object
  #
  # Returns the value that determines whether unconverted fields are to be
  # available; used for parsing;
  # see {Option +unconverted_fields+}[#class-CSV-label-Option+unconverted_fields]:
  #   CSV.new('').unconverted_fields? # => nil
  def unconverted_fields?
    parser.unconverted_fields?
  end

  # :call-seq:
  #   csv.headers -> object
  #
  # Returns the value that determines whether headers are used; used for parsing;
  # see {Option +headers+}[#class-CSV-label-Option+headers]:
  #   CSV.new('').headers # => nil
  def headers
    if @writer
      @writer.headers
    else
      parsed_headers = parser.headers
      return parsed_headers if parsed_headers
      raw_headers = @parser_options[:headers]
      raw_headers = nil if raw_headers == false
      raw_headers
    end
  end

  # :call-seq:
  #   csv.return_headers? -> true or false
  #
  # Returns the value that determines whether headers are to be returned; used for parsing;
  # see {Option +return_headers+}[#class-CSV-label-Option+return_headers]:
  #   CSV.new('').return_headers? # => false
  def return_headers?
    parser.return_headers?
  end

  # :call-seq:
  #   csv.write_headers? -> true or false
  #
  # Returns the value that determines whether headers are to be written; used for generating;
  # see {Option +write_headers+}[#class-CSV-label-Option+write_headers]:
  #   CSV.new('').write_headers? # => nil
  def write_headers?
    @writer_options[:write_headers]
  end

  # :call-seq:
  #   csv.header_converters -> array
  #
  # Returns an \Array containing header converters; used for parsing;
  # see {Header Converters}[#class-CSV-label-Header+Converters]:
  #   CSV.new('').header_converters # => []
  def header_converters
    header_fields_converter.map do |converter|
      name = HeaderConverters.rassoc(converter)
      name ? name.first : converter
    end
  end

  # :call-seq:
  #   csv.skip_blanks? -> true or false
  #
  # Returns the value that determines whether blank lines are to be ignored; used for parsing;
  # see {Option +skip_blanks+}[#class-CSV-label-Option+skip_blanks]:
  #   CSV.new('').skip_blanks? # => false
  def skip_blanks?
    parser.skip_blanks?
  end

  # :call-seq:
  #   csv.force_quotes? -> true or false
  #
  # Returns the value that determines whether all output fields are to be quoted;
  # used for generating;
  # see {Option +force_quotes+}[#class-CSV-label-Option+force_quotes]:
  #   CSV.new('').force_quotes? # => false
  def force_quotes?
    @writer_options[:force_quotes]
  end

  # :call-seq:
  #   csv.liberal_parsing? -> true or false
  #
  # Returns the value that determines whether illegal input is to be handled; used for parsing;
  # see {Option +liberal_parsing+}[#class-CSV-label-Option+liberal_parsing]:
  #   CSV.new('').liberal_parsing? # => false
  def liberal_parsing?
    parser.liberal_parsing?
  end

  # :call-seq:
  #   csv.encoding -> endcoding
  #
  # Returns the encoding used for parsing and generating;
  # see {Character Encodings (M17n or Multilingualization)}[#class-CSV-label-Character+Encodings+-28M17n+or+Multilingualization-29]:
  #   CSV.new('').encoding # => #<Encoding:UTF-8>
  attr_reader :encoding

  # :call-seq:
  #   csv.line_no -> integer
  #
  # Returns the count of the rows parsed or generated.
  #
  # Parsing:
  #   string = "foo,0\nbar,1\nbaz,2\n"
  #   path = 't.csv'
  #   File.write(path, string)
  #   CSV.open(path) do |csv|
  #     csv.each do |row|
  #       p [csv.lineno, row]
  #     end
  #   end
  # Output:
  #   [1, ["foo", "0"]]
  #   [2, ["bar", "1"]]
  #   [3, ["baz", "2"]]
  #
  # Generating:
  #   CSV.generate do |csv|
  #     p csv.lineno; csv << ['foo', 0]
  #     p csv.lineno; csv << ['bar', 1]
  #     p csv.lineno; csv << ['baz', 2]
  #   end
  # Output:
  #   0
  #   1
  #   2
  def lineno
    if @writer
      @writer.lineno
    else
      parser.lineno
    end
  end

  # :call-seq:
  #   csv.line -> array
  #
  # Returns the line most recently read:
  #   string = "foo,0\nbar,1\nbaz,2\n"
  #   path = 't.csv'
  #   File.write(path, string)
  #   CSV.open(path) do |csv|
  #     csv.each do |row|
  #       p [csv.lineno, csv.line]
  #     end
  #   end
  # Output:
  #   [1, "foo,0\n"]
  #   [2, "bar,1\n"]
  #   [3, "baz,2\n"]
  def line
    parser.line
  end

  ### IO and StringIO Delegation ###

  extend Forwardable
  def_delegators :@io, :binmode, :close, :close_read, :close_write,
                       :closed?, :external_encoding, :fcntl,
                       :fileno, :flush, :fsync, :internal_encoding,
                       :isatty, :pid, :pos, :pos=, :reopen,
                       :seek, :string, :sync, :sync=, :tell,
                       :truncate, :tty?

  def binmode?
    if @io.respond_to?(:binmode?)
      @io.binmode?
    else
      false
    end
  end

  def flock(*args)
    raise NotImplementedError unless @io.respond_to?(:flock)
    @io.flock(*args)
  end

  def ioctl(*args)
    raise NotImplementedError unless @io.respond_to?(:ioctl)
    @io.ioctl(*args)
  end

  def path
    @io.path if @io.respond_to?(:path)
  end

  def stat(*args)
    raise NotImplementedError unless @io.respond_to?(:stat)
    @io.stat(*args)
  end

  def to_i
    raise NotImplementedError unless @io.respond_to?(:to_i)
    @io.to_i
  end

  def to_io
    @io.respond_to?(:to_io) ? @io.to_io : @io
  end

  def eof?
    return false if @eof_error
    begin
      parser_enumerator.peek
      false
    rescue MalformedCSVError => error
      @eof_error = error
      false
    rescue StopIteration
      true
    end
  end
  alias_method :eof, :eof?

  # Rewinds the underlying IO object and resets CSV's lineno() counter.
  def rewind
    @parser = nil
    @parser_enumerator = nil
    @eof_error = nil
    @writer.rewind if @writer
    @io.rewind
  end

  ### End Delegation ###

  # :call-seq:
  #   csv << row -> self
  #
  # Appends a row to +self+.
  #
  # - Argument +row+ must be an \Array object or a CSV::Row object.
  # - The output stream must be open for writing.
  #
  # ---
  #
  # Append Arrays:
  #   CSV.generate do |csv|
  #     csv << ['foo', 0]
  #     csv << ['bar', 1]
  #     csv << ['baz', 2]
  #   end # => "foo,0\nbar,1\nbaz,2\n"
  #
  # Append CSV::Rows:
  #   headers = []
  #   CSV.generate do |csv|
  #     csv << CSV::Row.new(headers, ['foo', 0])
  #     csv << CSV::Row.new(headers, ['bar', 1])
  #     csv << CSV::Row.new(headers, ['baz', 2])
  #   end # => "foo,0\nbar,1\nbaz,2\n"
  #
  # Headers in CSV::Row objects are not appended:
  #   headers = ['Name', 'Count']
  #   CSV.generate do |csv|
  #     csv << CSV::Row.new(headers, ['foo', 0])
  #     csv << CSV::Row.new(headers, ['bar', 1])
  #     csv << CSV::Row.new(headers, ['baz', 2])
  #   end # => "foo,0\nbar,1\nbaz,2\n"
  #
  # ---
  #
  # Raises an exception if +row+ is not an \Array or \CSV::Row:
  #   CSV.generate do |csv|
  #     # Raises NoMethodError (undefined method `collect' for :foo:Symbol)
  #     csv << :foo
  #   end
  #
  # Raises an exception if the output stream is not opened for writing:
  #   path = 't.csv'
  #   File.write(path, '')
  #   File.open(path) do |file|
  #     CSV.open(file) do |csv|
  #       # Raises IOError (not opened for writing)
  #       csv << ['foo', 0]
  #     end
  #   end
  def <<(row)
    writer << row
    self
  end
  alias_method :add_row, :<<
  alias_method :puts,    :<<

  # :call-seq:
  #   convert(converter_name) -> array_of_procs
  #   convert {|field, field_info| ... } -> array_of_procs
  #
  # - With no block, installs a field converter (a \Proc).
  # - With a block, defines and installs a custom field converter.
  # - Returns the \Array of installed field converters.
  #
  # - Argument +converter_name+, if given, should be the name
  #   of an existing field converter.
  #
  # See {Field Converters}[#class-CSV-label-Field+Converters].
  # ---
  #
  # With no block, installs a field converter:
  #   csv = CSV.new('')
  #   csv.convert(:integer)
  #   csv.convert(:float)
  #   csv.convert(:date)
  #   csv.converters # => [:integer, :float, :date]
  #
  # ---
  #
  # The block, if given, is called for each field:
  # - Argument +field+ is the field value.
  # - Argument +field_info+ is a CSV::FieldInfo object
  #   containing details about the field.
  #
  # The examples here assume the prior execution of:
  #   string = "foo,0\nbar,1\nbaz,2\n"
  #   path = 't.csv'
  #   File.write(path, string)
  #
  # Example giving a block:
  #   csv = CSV.open(path)
  #   csv.convert {|field, field_info| p [field, field_info]; field.upcase }
  #   csv.read # => [["FOO", "0"], ["BAR", "1"], ["BAZ", "2"]]
  #
  # Output:
  #   ["foo", #<struct CSV::FieldInfo index=0, line=1, header=nil>]
  #   ["0", #<struct CSV::FieldInfo index=1, line=1, header=nil>]
  #   ["bar", #<struct CSV::FieldInfo index=0, line=2, header=nil>]
  #   ["1", #<struct CSV::FieldInfo index=1, line=2, header=nil>]
  #   ["baz", #<struct CSV::FieldInfo index=0, line=3, header=nil>]
  #   ["2", #<struct CSV::FieldInfo index=1, line=3, header=nil>]
  #
  # The block need not return a \String object:
  #   csv = CSV.open(path)
  #   csv.convert {|field, field_info| field.to_sym }
  #   csv.read # => [[:foo, :"0"], [:bar, :"1"], [:baz, :"2"]]
  #
  # If +converter_name+ is given, the block is not called:
  #   csv = CSV.open(path)
  #   csv.convert(:integer) {|field, field_info| fail 'Cannot happen' }
  #   csv.read # => [["foo", 0], ["bar", 1], ["baz", 2]]
  #
  # ---
  #
  # Raises a parse-time exception if +converter_name+ is not the name of a built-in
  # field converter:
  #   csv = CSV.open(path)
  #   csv.convert(:nosuch) => [nil]
  #   # Raises NoMethodError (undefined method `arity' for nil:NilClass)
  #   csv.read
  def convert(name = nil, &converter)
    parser_fields_converter.add_converter(name, &converter)
  end

  # :call-seq:
  #   header_convert(converter_name) -> array_of_procs
  #   header_convert {|header, field_info| ... } -> array_of_procs
  #
  # - With no block, installs a header converter (a \Proc).
  # - With a block, defines and installs a custom header converter.
  # - Returns the \Array of installed header converters.
  #
  # - Argument +converter_name+, if given, should be the name
  #   of an existing header converter.
  #
  # See {Header Converters}[#class-CSV-label-Header+Converters].
  # ---
  #
  # With no block, installs a header converter:
  #   csv = CSV.new('')
  #   csv.header_convert(:symbol)
  #   csv.header_convert(:downcase)
  #   csv.header_converters # => [:symbol, :downcase]
  #
  # ---
  #
  # The block, if given, is called for each header:
  # - Argument +header+ is the header value.
  # - Argument +field_info+ is a CSV::FieldInfo object
  #   containing details about the header.
  #
  # The examples here assume the prior execution of:
  #   string = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
  #   path = 't.csv'
  #   File.write(path, string)
  #
  # Example giving a block:
  #   csv = CSV.open(path, headers: true)
  #   csv.header_convert {|header, field_info| p [header, field_info]; header.upcase }
  #   table = csv.read
  #   table # => #<CSV::Table mode:col_or_row row_count:4>
  #   table.headers # => ["NAME", "VALUE"]
  #
  # Output:
  #   ["Name", #<struct CSV::FieldInfo index=0, line=1, header=nil>]
  #   ["Value", #<struct CSV::FieldInfo index=1, line=1, header=nil>]

  # The block need not return a \String object:
  #   csv = CSV.open(path, headers: true)
  #   csv.header_convert {|header, field_info| header.to_sym }
  #   table = csv.read
  #   table.headers # => [:Name, :Value]
  #
  # If +converter_name+ is given, the block is not called:
  #   csv = CSV.open(path, headers: true)
  #   csv.header_convert(:downcase) {|header, field_info| fail 'Cannot happen' }
  #   table = csv.read
  #   table.headers # => ["name", "value"]
  # ---
  #
  # Raises a parse-time exception if +converter_name+ is not the name of a built-in
  # field converter:
  #   csv = CSV.open(path, headers: true)
  #   csv.header_convert(:nosuch)
  #   # Raises NoMethodError (undefined method `arity' for nil:NilClass)
  #   csv.read
  def header_convert(name = nil, &converter)
    header_fields_converter.add_converter(name, &converter)
  end

  include Enumerable

  # :call-seq:
  #   csv.each -> enumerator
  #   csv.each {|row| ...}
  #
  # Calls the block with each successive row.
  # The data source must be opened for reading.
  #
  # Without headers:
  #   string = "foo,0\nbar,1\nbaz,2\n"
  #   csv = CSV.new(string)
  #   csv.each do |row|
  #     p row
  #   end
  # Output:
  #   ["foo", "0"]
  #   ["bar", "1"]
  #   ["baz", "2"]
  #
  # With headers:
  #   string = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
  #   csv = CSV.new(string, headers: true)
  #   csv.each do |row|
  #     p row
  #   end
  # Output:
  #   <CSV::Row "Name":"foo" "Value":"0">
  #   <CSV::Row "Name":"bar" "Value":"1">
  #   <CSV::Row "Name":"baz" "Value":"2">
  #
  # ---
  #
  # Raises an exception if the source is not opened for reading:
  #   string = "foo,0\nbar,1\nbaz,2\n"
  #   csv = CSV.new(string)
  #   csv.close
  #   # Raises IOError (not opened for reading)
  #   csv.each do |row|
  #     p row
  #   end
  def each(&block)
    parser_enumerator.each(&block)
  end

  # :call-seq:
  #   csv.read -> array or csv_table
  #
  # Forms the remaining rows from +self+ into:
  # - A CSV::Table object, if headers are in use.
  # - An \Array of Arrays, otherwise.
  #
  # The data source must be opened for reading.
  #
  # Without headers:
  #   string = "foo,0\nbar,1\nbaz,2\n"
  #   path = 't.csv'
  #   File.write(path, string)
  #   csv = CSV.open(path)
  #   csv.read # => [["foo", "0"], ["bar", "1"], ["baz", "2"]]
  #
  # With headers:
  #   string = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
  #   path = 't.csv'
  #   File.write(path, string)
  #   csv = CSV.open(path, headers: true)
  #   csv.read # => #<CSV::Table mode:col_or_row row_count:4>
  #
  # ---
  #
  # Raises an exception if the source is not opened for reading:
  #   string = "foo,0\nbar,1\nbaz,2\n"
  #   csv = CSV.new(string)
  #   csv.close
  #   # Raises IOError (not opened for reading)
  #   csv.read
  def read
    rows = to_a
    if parser.use_headers?
      Table.new(rows, headers: parser.headers)
    else
      rows
    end
  end
  alias_method :readlines, :read

  # :call-seq:
  #   csv.header_row? -> true or false
  #
  # Returns +true+ if the next row to be read is a header row\;
  # +false+ otherwise.
  #
  # Without headers:
  #   string = "foo,0\nbar,1\nbaz,2\n"
  #   csv = CSV.new(string)
  #   csv.header_row? # => false
  #
  # With headers:
  #   string = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
  #   csv = CSV.new(string, headers: true)
  #   csv.header_row? # => true
  #   csv.shift # => #<CSV::Row "Name":"foo" "Value":"0">
  #   csv.header_row? # => false
  #
  # ---
  #
  # Raises an exception if the source is not opened for reading:
  #   string = "foo,0\nbar,1\nbaz,2\n"
  #   csv = CSV.new(string)
  #   csv.close
  #   # Raises IOError (not opened for reading)
  #   csv.header_row?
  def header_row?
    parser.header_row?
  end

  # :call-seq:
  #   csv.shift -> array, csv_row, or nil
  #
  # Returns the next row of data as:
  # - An \Array if no headers are used.
  # - A CSV::Row object if headers are used.
  #
  # The data source must be opened for reading.
  #
  # Without headers:
  #   string = "foo,0\nbar,1\nbaz,2\n"
  #   csv = CSV.new(string)
  #   csv.shift # => ["foo", "0"]
  #   csv.shift # => ["bar", "1"]
  #   csv.shift # => ["baz", "2"]
  #   csv.shift # => nil
  #
  # With headers:
  #   string = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
  #   csv = CSV.new(string, headers: true)
  #   csv.shift # => #<CSV::Row "Name":"foo" "Value":"0">
  #   csv.shift # => #<CSV::Row "Name":"bar" "Value":"1">
  #   csv.shift # => #<CSV::Row "Name":"baz" "Value":"2">
  #   csv.shift # => nil
  #
  # ---
  #
  # Raises an exception if the source is not opened for reading:
  #   string = "foo,0\nbar,1\nbaz,2\n"
  #   csv = CSV.new(string)
  #   csv.close
  #   # Raises IOError (not opened for reading)
  #   csv.shift
  def shift
    if @eof_error
      eof_error, @eof_error = @eof_error, nil
      raise eof_error
    end
    begin
      parser_enumerator.next
    rescue StopIteration
      nil
    end
  end
  alias_method :gets,     :shift
  alias_method :readline, :shift

  # :call-seq:
  #   csv.inspect -> string
  #
  # Returns a \String showing certain properties of +self+:
  #   string = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
  #   csv = CSV.new(string, headers: true)
  #   s = csv.inspect
  #   s # => "#<CSV io_type:StringIO encoding:UTF-8 lineno:0 col_sep:\",\" row_sep:\"\\n\" quote_char:\"\\\"\" headers:true>"
  def inspect
    str = ["#<", self.class.to_s, " io_type:"]
    # show type of wrapped IO
    if    @io == $stdout then str << "$stdout"
    elsif @io == $stdin  then str << "$stdin"
    elsif @io == $stderr then str << "$stderr"
    else                      str << @io.class.to_s
    end
    # show IO.path(), if available
    if @io.respond_to?(:path) and (p = @io.path)
      str << " io_path:" << p.inspect
    end
    # show encoding
    str << " encoding:" << @encoding.name
    # show other attributes
    ["lineno", "col_sep", "row_sep", "quote_char"].each do |attr_name|
      if a = __send__(attr_name)
        str << " " << attr_name << ":" << a.inspect
      end
    end
    ["skip_blanks", "liberal_parsing"].each do |attr_name|
      if a = __send__("#{attr_name}?")
        str << " " << attr_name << ":" << a.inspect
      end
    end
    _headers = headers
    str << " headers:" << _headers.inspect if _headers
    str << ">"
    begin
      str.join('')
    rescue  # any encoding error
      str.map do |s|
        e = Encoding::Converter.asciicompat_encoding(s.encoding)
        e ? s.encode(e) : s.force_encoding("ASCII-8BIT")
      end.join('')
    end
  end

  private

  def determine_encoding(encoding, internal_encoding)
    # honor the IO encoding if we can, otherwise default to ASCII-8BIT
    io_encoding = raw_encoding
    return io_encoding if io_encoding

    return Encoding.find(internal_encoding) if internal_encoding

    if encoding
      encoding, = encoding.split(":", 2) if encoding.is_a?(String)
      return Encoding.find(encoding)
    end

    Encoding.default_internal || Encoding.default_external
  end

  def normalize_converters(converters)
    converters ||= []
    unless converters.is_a?(Array)
      converters = [converters]
    end
    converters.collect do |converter|
      case converter
      when Proc # custom code block
        [nil, converter]
      else # by name
        [converter, nil]
      end
    end
  end

  #
  # Processes +fields+ with <tt>@converters</tt>, or <tt>@header_converters</tt>
  # if +headers+ is passed as +true+, returning the converted field set. Any
  # converter that changes the field into something other than a String halts
  # the pipeline of conversion for that field. This is primarily an efficiency
  # shortcut.
  #
  def convert_fields(fields, headers = false)
    if headers
      header_fields_converter.convert(fields, nil, 0)
    else
      parser_fields_converter.convert(fields, @headers, lineno)
    end
  end

  #
  # Returns the encoding of the internal IO object.
  #
  def raw_encoding
    if @io.respond_to? :internal_encoding
      @io.internal_encoding || @io.external_encoding
    elsif @io.respond_to? :encoding
      @io.encoding
    else
      nil
    end
  end

  def parser_fields_converter
    @parser_fields_converter ||= build_parser_fields_converter
  end

  def build_parser_fields_converter
    specific_options = {
      builtin_converters: Converters,
    }
    options = @base_fields_converter_options.merge(specific_options)
    build_fields_converter(@initial_converters, options)
  end

  def header_fields_converter
    @header_fields_converter ||= build_header_fields_converter
  end

  def build_header_fields_converter
    specific_options = {
      builtin_converters: HeaderConverters,
      accept_nil: true,
    }
    options = @base_fields_converter_options.merge(specific_options)
    build_fields_converter(@initial_header_converters, options)
  end

  def writer_fields_converter
    @writer_fields_converter ||= build_writer_fields_converter
  end

  def build_writer_fields_converter
    build_fields_converter(@initial_write_converters,
                           @write_fields_converter_options)
  end

  def build_fields_converter(initial_converters, options)
    fields_converter = FieldsConverter.new(options)
    normalize_converters(initial_converters).each do |name, converter|
      fields_converter.add_converter(name, &converter)
    end
    fields_converter
  end

  def parser
    @parser ||= Parser.new(@io, parser_options)
  end

  def parser_options
    @parser_options.merge(header_fields_converter: header_fields_converter,
                          fields_converter: parser_fields_converter)
  end

  def parser_enumerator
    @parser_enumerator ||= parser.parse
  end

  def writer
    @writer ||= Writer.new(@io, writer_options)
  end

  def writer_options
    @writer_options.merge(header_fields_converter: header_fields_converter,
                          fields_converter: writer_fields_converter)
  end
end

# Passes +args+ to CSV::instance.
#
#   CSV("CSV,data").read
#     #=> [["CSV", "data"]]
#
# If a block is given, the instance is passed the block and the return value
# becomes the return value of the block.
#
#   CSV("CSV,data") { |c|
#     c.read.any? { |a| a.include?("data") }
#   } #=> true
#
#   CSV("CSV,data") { |c|
#     c.read.any? { |a| a.include?("zombies") }
#   } #=> false
#
def CSV(*args, &block)
  CSV.instance(*args, &block)
end

require_relative "csv/version"
require_relative "csv/core_ext/array"
require_relative "csv/core_ext/string"
# frozen_string_literal: false

# The Singleton module implements the Singleton pattern.
#
# == Usage
#
# To use Singleton, include the module in your class.
#
#    class Klass
#       include Singleton
#       # ...
#    end
#
# This ensures that only one instance of Klass can be created.
#
#      a,b = Klass.instance, Klass.instance
#
#      a == b
#      # => true
#
#      Klass.new
#      # => NoMethodError - new is private ...
#
# The instance is created at upon the first call of Klass.instance().
#
#      class OtherKlass
#        include Singleton
#        # ...
#      end
#
#      ObjectSpace.each_object(OtherKlass){}
#      # => 0
#
#      OtherKlass.instance
#      ObjectSpace.each_object(OtherKlass){}
#      # => 1
#
#
# This behavior is preserved under inheritance and cloning.
#
# == Implementation
#
# This above is achieved by:
#
# *  Making Klass.new and Klass.allocate private.
#
# *  Overriding Klass.inherited(sub_klass) and Klass.clone() to ensure that the
#    Singleton properties are kept when inherited and cloned.
#
# *  Providing the Klass.instance() method that returns the same object each
#    time it is called.
#
# *  Overriding Klass._load(str) to call Klass.instance().
#
# *  Overriding Klass#clone and Klass#dup to raise TypeErrors to prevent
#    cloning or duping.
#
# == Singleton and Marshal
#
# By default Singleton's #_dump(depth) returns the empty string. Marshalling by
# default will strip state information, e.g. instance variables from the instance.
# Classes using Singleton can provide custom _load(str) and _dump(depth) methods
# to retain some of the previous state of the instance.
#
#    require 'singleton'
#
#    class Example
#      include Singleton
#      attr_accessor :keep, :strip
#      def _dump(depth)
#        # this strips the @strip information from the instance
#        Marshal.dump(@keep, depth)
#      end
#
#      def self._load(str)
#        instance.keep = Marshal.load(str)
#        instance
#      end
#    end
#
#    a = Example.instance
#    a.keep = "keep this"
#    a.strip = "get rid of this"
#
#    stored_state = Marshal.dump(a)
#
#    a.keep = nil
#    a.strip = nil
#    b = Marshal.load(stored_state)
#    p a == b  #  => true
#    p a.keep  #  => "keep this"
#    p a.strip #  => nil
#
module Singleton
  VERSION = "0.1.1"

  # Raises a TypeError to prevent cloning.
  def clone
    raise TypeError, "can't clone instance of singleton #{self.class}"
  end

  # Raises a TypeError to prevent duping.
  def dup
    raise TypeError, "can't dup instance of singleton #{self.class}"
  end

  # By default, do not retain any state when marshalling.
  def _dump(depth = -1)
    ''
  end

  module SingletonClassMethods # :nodoc:

    def clone # :nodoc:
      Singleton.__init__(super)
    end

    # By default calls instance(). Override to retain singleton state.
    def _load(str)
      instance
    end

    def instance # :nodoc:
      return @singleton__instance__ if @singleton__instance__
      @singleton__mutex__.synchronize {
        return @singleton__instance__ if @singleton__instance__
        @singleton__instance__ = new()
      }
      @singleton__instance__
    end

    private

    def inherited(sub_klass)
      super
      Singleton.__init__(sub_klass)
    end
  end

  class << Singleton # :nodoc:
    def __init__(klass) # :nodoc:
      klass.instance_eval {
        @singleton__instance__ = nil
        @singleton__mutex__ = Thread::Mutex.new
      }
      klass
    end

    private

    # extending an object with Singleton is a bad idea
    undef_method :extend_object

    def append_features(mod)
      #  help out people counting on transitive mixins
      unless mod.instance_of?(Class)
        raise TypeError, "Inclusion of the OO-Singleton module in module #{mod}"
      end
      super
    end

    def included(klass)
      super
      klass.private_class_method :new, :allocate
      klass.extend SingletonClassMethods
      Singleton.__init__(klass)
    end
  end

  ##
  # :singleton-method: _load
  #  By default calls instance(). Override to retain singleton state.

  ##
  # :singleton-method: instance
  #  Returns the singleton instance.
end
# frozen_string_literal: true
# Copyright (C) 2000  Network Applied Communication Laboratory, Inc.
# Copyright (C) 2000  Information-technology Promotion Agency, Japan
# Copyright (C) 2000-2003  NAKAMURA, Hiroshi  <nahi@ruby-lang.org>

if $SAFE > 0
  STDERR.print "-r debug.rb is not available in safe mode\n"
  exit 1
end

require 'tracer'
require 'pp'

class Tracer # :nodoc:
  def Tracer.trace_func(*vars)
    Single.trace_func(*vars)
  end
end

SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__ # :nodoc:

##
# This library provides debugging functionality to Ruby.
#
# To add a debugger to your code, start by requiring +debug+ in your
# program:
#
#   def say(word)
#     require 'debug'
#     puts word
#   end
#
# This will cause Ruby to interrupt execution and show a prompt when the +say+
# method is run.
#
# Once you're inside the prompt, you can start debugging your program.
#
#   (rdb:1) p word
#   "hello"
#
# == Getting help
#
# You can get help at any time by pressing +h+.
#
#   (rdb:1) h
#   Debugger help v.-0.002b
#   Commands
#     b[reak] [file:|class:]<line|method>
#     b[reak] [class.]<line|method>
#                                set breakpoint to some position
#     wat[ch] <expression>       set watchpoint to some expression
#     cat[ch] (<exception>|off)  set catchpoint to an exception
#     b[reak]                    list breakpoints
#     cat[ch]                    show catchpoint
#     del[ete][ nnn]             delete some or all breakpoints
#     disp[lay] <expression>     add expression into display expression list
#     undisp[lay][ nnn]          delete one particular or all display expressions
#     c[ont]                     run until program ends or hit breakpoint
#     s[tep][ nnn]               step (into methods) one line or till line nnn
#     n[ext][ nnn]               go over one line or till line nnn
#     w[here]                    display frames
#     f[rame]                    alias for where
#     l[ist][ (-|nn-mm)]         list program, - lists backwards
#                                nn-mm lists given lines
#     up[ nn]                    move to higher frame
#     down[ nn]                  move to lower frame
#     fin[ish]                   return to outer frame
#     tr[ace] (on|off)           set trace mode of current thread
#     tr[ace] (on|off) all       set trace mode of all threads
#     q[uit]                     exit from debugger
#     v[ar] g[lobal]             show global variables
#     v[ar] l[ocal]              show local variables
#     v[ar] i[nstance] <object>  show instance variables of object
#     v[ar] c[onst] <object>     show constants of object
#     m[ethod] i[nstance] <obj>  show methods of object
#     m[ethod] <class|module>    show instance methods of class or module
#     th[read] l[ist]            list all threads
#     th[read] c[ur[rent]]       show current thread
#     th[read] [sw[itch]] <nnn>  switch thread context to nnn
#     th[read] stop <nnn>        stop thread nnn
#     th[read] resume <nnn>      resume thread nnn
#     p expression               evaluate expression and print its value
#     h[elp]                     print this help
#     <everything else>          evaluate
#
# == Usage
#
# The following is a list of common functionalities that the debugger
# provides.
#
# === Navigating through your code
#
# In general, a debugger is used to find bugs in your program, which
# often means pausing execution and inspecting variables at some point
# in time.
#
# Let's look at an example:
#
#   def my_method(foo)
#     require 'debug'
#     foo = get_foo if foo.nil?
#     raise if foo.nil?
#   end
#
# When you run this program, the debugger will kick in just before the
# +foo+ assignment.
#
#   (rdb:1) p foo
#   nil
#
# In this example, it'd be interesting to move to the next line and
# inspect the value of +foo+ again. You can do that by pressing +n+:
#
#   (rdb:1) n # goes to next line
#   (rdb:1) p foo
#   nil
#
# You now know that the original value of +foo+ was nil, and that it
# still was nil after calling +get_foo+.
#
# Other useful commands for navigating through your code are:
#
# +c+::
#   Runs the program until it either exists or encounters another breakpoint.
#   You usually press +c+ when you are finished debugging your program and
#   want to resume its execution.
# +s+::
#   Steps into method definition. In the previous example, +s+ would take you
#   inside the method definition of +get_foo+.
# +r+::
#   Restart the program.
# +q+::
#   Quit the program.
#
# === Inspecting variables
#
# You can use the debugger to easily inspect both local and global variables.
# We've seen how to inspect local variables before:
#
#   (rdb:1) p my_arg
#   42
#
# You can also pretty print the result of variables or expressions:
#
#   (rdb:1) pp %w{a very long long array containing many words}
#   ["a",
#    "very",
#    "long",
#    ...
#   ]
#
# You can list all local variables with +v l+:
#
#   (rdb:1) v l
#     foo => "hello"
#
# Similarly, you can show all global variables with +v g+:
#
#   (rdb:1) v g
#     all global variables
#
# Finally, you can omit +p+ if you simply want to evaluate a variable or
# expression
#
#   (rdb:1) 5**2
#   25
#
# === Going beyond basics
#
# Ruby Debug provides more advanced functionalities like switching
# between threads, setting breakpoints and watch expressions, and more.
# The full list of commands is available at any time by pressing +h+.
#
# == Staying out of trouble
#
# Make sure you remove every instance of +require 'debug'+ before
# shipping your code. Failing to do so may result in your program
# hanging unpredictably.
#
# Debug is not available in safe mode.

class DEBUGGER__
  MUTEX = Thread::Mutex.new # :nodoc:
  CONTINUATIONS_SUPPORTED = RUBY_ENGINE == 'ruby'

  require 'continuation' if CONTINUATIONS_SUPPORTED

  class Context # :nodoc:
    DEBUG_LAST_CMD = []

    begin
      require 'readline'
      def readline(prompt, hist)
        Readline::readline(prompt, hist)
      end
    rescue LoadError
      def readline(prompt, hist)
        STDOUT.print prompt
        STDOUT.flush
        line = STDIN.gets
        exit unless line
        line.chomp!
        line
      end
      USE_READLINE = false
    end

    def initialize
      if Thread.current == Thread.main
        @stop_next = 1
      else
        @stop_next = 0
      end
      @last_file = nil
      @file = nil
      @line = nil
      @no_step = nil
      @frames = []
      @finish_pos = 0
      @trace = false
      @catch = "StandardError"
      @suspend_next = false
    end

    def stop_next(n=1)
      @stop_next = n
    end

    def set_suspend
      @suspend_next = true
    end

    def clear_suspend
      @suspend_next = false
    end

    def suspend_all
      DEBUGGER__.suspend
    end

    def resume_all
      DEBUGGER__.resume
    end

    def check_suspend
      while MUTEX.synchronize {
          if @suspend_next
            DEBUGGER__.waiting.push Thread.current
            @suspend_next = false
            true
          end
        }
      end
    end

    def trace?
      @trace
    end

    def set_trace(arg)
      @trace = arg
    end

    def stdout
      DEBUGGER__.stdout
    end

    def break_points
      DEBUGGER__.break_points
    end

    def display
      DEBUGGER__.display
    end

    def context(th)
      DEBUGGER__.context(th)
    end

    def set_trace_all(arg)
      DEBUGGER__.set_trace(arg)
    end

    def set_last_thread(th)
      DEBUGGER__.set_last_thread(th)
    end

    def debug_eval(str, binding)
      begin
        eval(str, binding)
      rescue StandardError, ScriptError => e
        at = eval("caller(1)", binding)
        stdout.printf "%s:%s\n", at.shift, e.to_s.sub(/\(eval\):1:(in `.*?':)?/, '')
        for i in at
          stdout.printf "\tfrom %s\n", i
        end
        throw :debug_error
      end
    end

    def debug_silent_eval(str, binding)
      begin
        eval(str, binding)
      rescue StandardError, ScriptError
        nil
      end
    end

    def var_list(ary, binding)
      ary.sort!
      for v in ary
        stdout.printf "  %s => %s\n", v, eval(v.to_s, binding).inspect
      end
    end

    def debug_variable_info(input, binding)
      case input
      when /^\s*g(?:lobal)?\s*$/
        var_list(global_variables, binding)

      when /^\s*l(?:ocal)?\s*$/
        var_list(eval("local_variables", binding), binding)

      when /^\s*i(?:nstance)?\s+/
        obj = debug_eval($', binding)
        var_list(obj.instance_variables, obj.instance_eval{binding()})

      when /^\s*c(?:onst(?:ant)?)?\s+/
        obj = debug_eval($', binding)
        unless obj.kind_of? Module
          stdout.print "Should be Class/Module: ", $', "\n"
        else
          var_list(obj.constants, obj.module_eval{binding()})
        end
      end
    end

    def debug_method_info(input, binding)
      case input
      when /^i(:?nstance)?\s+/
        obj = debug_eval($', binding)

        len = 0
        for v in obj.methods.sort
          len += v.size + 1
          if len > 70
            len = v.size + 1
            stdout.print "\n"
          end
          stdout.print v, " "
        end
        stdout.print "\n"

      else
        obj = debug_eval(input, binding)
        unless obj.kind_of? Module
          stdout.print "Should be Class/Module: ", input, "\n"
        else
          len = 0
          for v in obj.instance_methods(false).sort
            len += v.size + 1
            if len > 70
              len = v.size + 1
              stdout.print "\n"
            end
            stdout.print v, " "
          end
          stdout.print "\n"
        end
      end
    end

    def thnum
      num = DEBUGGER__.instance_eval{@thread_list[Thread.current]}
      unless num
        DEBUGGER__.make_thread_list
        num = DEBUGGER__.instance_eval{@thread_list[Thread.current]}
      end
      num
    end

    def debug_command(file, line, id, binding)
      MUTEX.lock
      if CONTINUATIONS_SUPPORTED
        unless defined?($debugger_restart) and $debugger_restart
          callcc{|c| $debugger_restart = c}
        end
      end
      set_last_thread(Thread.current)
      frame_pos = 0
      binding_file = file
      binding_line = line
      previous_line = nil
      if ENV['EMACS']
        stdout.printf "\032\032%s:%d:\n", binding_file, binding_line
      else
        stdout.printf "%s:%d:%s", binding_file, binding_line,
          line_at(binding_file, binding_line)
      end
      @frames[0] = [binding, file, line, id]
      display_expressions(binding)
      prompt = true
      while prompt and input = readline("(rdb:%d) "%thnum(), true)
        catch(:debug_error) do
          if input == ""
            next unless DEBUG_LAST_CMD[0]
            input = DEBUG_LAST_CMD[0]
            stdout.print input, "\n"
          else
            DEBUG_LAST_CMD[0] = input
          end

          case input
          when /^\s*tr(?:ace)?(?:\s+(on|off))?(?:\s+(all))?$/
            if defined?( $2 )
              if $1 == 'on'
                set_trace_all true
              else
                set_trace_all false
              end
            elsif defined?( $1 )
              if $1 == 'on'
                set_trace true
              else
                set_trace false
              end
            end
            if trace?
              stdout.print "Trace on.\n"
            else
              stdout.print "Trace off.\n"
            end

          when /^\s*b(?:reak)?\s+(?:(.+):)?([^.:]+)$/
            pos = $2
            if $1
              klass = debug_silent_eval($1, binding)
              file = File.expand_path($1)
            end
            if pos =~ /^\d+$/
              pname = pos
              pos = pos.to_i
            else
              pname = pos = pos.intern.id2name
            end
            break_points.push [true, 0, klass || file, pos]
            stdout.printf "Set breakpoint %d at %s:%s\n", break_points.size, klass || file, pname

          when /^\s*b(?:reak)?\s+(.+)[#.]([^.:]+)$/
            pos = $2.intern.id2name
            klass = debug_eval($1, binding)
            break_points.push [true, 0, klass, pos]
            stdout.printf "Set breakpoint %d at %s.%s\n", break_points.size, klass, pos

          when /^\s*wat(?:ch)?\s+(.+)$/
            exp = $1
            break_points.push [true, 1, exp]
            stdout.printf "Set watchpoint %d:%s\n", break_points.size, exp

          when /^\s*b(?:reak)?$/
            if break_points.find{|b| b[1] == 0}
              n = 1
              stdout.print "Breakpoints:\n"
              break_points.each do |b|
                if b[0] and b[1] == 0
                  stdout.printf "  %d %s:%s\n", n, b[2], b[3]
                end
                n += 1
              end
            end
            if break_points.find{|b| b[1] == 1}
              n = 1
              stdout.print "\n"
              stdout.print "Watchpoints:\n"
              for b in break_points
                if b[0] and b[1] == 1
                  stdout.printf "  %d %s\n", n, b[2]
                end
                n += 1
              end
            end
            if break_points.size == 0
              stdout.print "No breakpoints\n"
            else
              stdout.print "\n"
            end

          when /^\s*del(?:ete)?(?:\s+(\d+))?$/
            pos = $1
            unless pos
              input = readline("Clear all breakpoints? (y/n) ", false)
              if input == "y"
                for b in break_points
                  b[0] = false
                end
              end
            else
              pos = pos.to_i
              if break_points[pos-1]
                break_points[pos-1][0] = false
              else
                stdout.printf "Breakpoint %d is not defined\n", pos
              end
            end

          when /^\s*disp(?:lay)?\s+(.+)$/
            exp = $1
            display.push [true, exp]
            stdout.printf "%d: ", display.size
            display_expression(exp, binding)

          when /^\s*disp(?:lay)?$/
            display_expressions(binding)

          when /^\s*undisp(?:lay)?(?:\s+(\d+))?$/
            pos = $1
            unless pos
              input = readline("Clear all expressions? (y/n) ", false)
              if input == "y"
                for d in display
                  d[0] = false
                end
              end
            else
              pos = pos.to_i
              if display[pos-1]
                display[pos-1][0] = false
              else
                stdout.printf "Display expression %d is not defined\n", pos
              end
            end

          when /^\s*c(?:ont)?$/
            prompt = false

          when /^\s*s(?:tep)?(?:\s+(\d+))?$/
            if $1
              lev = $1.to_i
            else
              lev = 1
            end
            @stop_next = lev
            prompt = false

          when /^\s*n(?:ext)?(?:\s+(\d+))?$/
            if $1
              lev = $1.to_i
            else
              lev = 1
            end
            @stop_next = lev
            @no_step = @frames.size - frame_pos
            prompt = false

          when /^\s*w(?:here)?$/, /^\s*f(?:rame)?$/
            display_frames(frame_pos)

          when /^\s*l(?:ist)?(?:\s+(.+))?$/
            if not $1
              b = previous_line ? previous_line + 10 : binding_line - 5
              e = b + 9
            elsif $1 == '-'
              b = previous_line ? previous_line - 10 : binding_line - 5
              e = b + 9
            else
              b, e = $1.split(/[-,]/)
              if e
                b = b.to_i
                e = e.to_i
              else
                b = b.to_i - 5
                e = b + 9
              end
            end
            previous_line = b
            display_list(b, e, binding_file, binding_line)

          when /^\s*up(?:\s+(\d+))?$/
            previous_line = nil
            if $1
              lev = $1.to_i
            else
              lev = 1
            end
            frame_pos += lev
            if frame_pos >= @frames.size
              frame_pos = @frames.size - 1
              stdout.print "At toplevel\n"
            end
            binding, binding_file, binding_line = @frames[frame_pos]
            stdout.print format_frame(frame_pos)

          when /^\s*down(?:\s+(\d+))?$/
            previous_line = nil
            if $1
              lev = $1.to_i
            else
              lev = 1
            end
            frame_pos -= lev
            if frame_pos < 0
              frame_pos = 0
              stdout.print "At stack bottom\n"
            end
            binding, binding_file, binding_line = @frames[frame_pos]
            stdout.print format_frame(frame_pos)

          when /^\s*fin(?:ish)?$/
            if frame_pos == @frames.size
              stdout.print "\"finish\" not meaningful in the outermost frame.\n"
            else
              @finish_pos = @frames.size - frame_pos
              frame_pos = 0
              prompt = false
            end

          when /^\s*cat(?:ch)?(?:\s+(.+))?$/
            if $1
              excn = $1
              if excn == 'off'
                @catch = nil
                stdout.print "Clear catchpoint.\n"
              else
                @catch = excn
                stdout.printf "Set catchpoint %s.\n", @catch
              end
            else
              if @catch
                stdout.printf "Catchpoint %s.\n", @catch
              else
                stdout.print "No catchpoint.\n"
              end
            end

          when /^\s*q(?:uit)?$/
            input = readline("Really quit? (y/n) ", false)
            if input == "y"
              exit!  # exit -> exit!: No graceful way to stop threads...
            end

          when /^\s*v(?:ar)?\s+/
            debug_variable_info($', binding)

          when /^\s*m(?:ethod)?\s+/
            debug_method_info($', binding)

          when /^\s*th(?:read)?\s+/
            if DEBUGGER__.debug_thread_info($', binding) == :cont
              prompt = false
            end

          when /^\s*pp\s+/
            PP.pp(debug_eval($', binding), stdout)

          when /^\s*p\s+/
            stdout.printf "%s\n", debug_eval($', binding).inspect

          when /^\s*r(?:estart)?$/
            if CONTINUATIONS_SUPPORTED
              $debugger_restart.call
            else
              stdout.print "Restart requires continuations.\n"
            end

          when /^\s*h(?:elp)?$/
            debug_print_help()

          else
            v = debug_eval(input, binding)
            stdout.printf "%s\n", v.inspect
          end
        end
      end
      MUTEX.unlock
      resume_all
    end

    def debug_print_help
      stdout.print <<EOHELP
Debugger help v.-0.002b
Commands
  b[reak] [file:|class:]<line|method>
  b[reak] [class.]<line|method>
                             set breakpoint to some position
  wat[ch] <expression>       set watchpoint to some expression
  cat[ch] (<exception>|off)  set catchpoint to an exception
  b[reak]                    list breakpoints
  cat[ch]                    show catchpoint
  del[ete][ nnn]             delete some or all breakpoints
  disp[lay] <expression>     add expression into display expression list
  undisp[lay][ nnn]          delete one particular or all display expressions
  c[ont]                     run until program ends or hit breakpoint
  s[tep][ nnn]               step (into methods) one line or till line nnn
  n[ext][ nnn]               go over one line or till line nnn
  w[here]                    display frames
  f[rame]                    alias for where
  l[ist][ (-|nn-mm)]         list program, - lists backwards
                             nn-mm lists given lines
  up[ nn]                    move to higher frame
  down[ nn]                  move to lower frame
  fin[ish]                   return to outer frame
  tr[ace] (on|off)           set trace mode of current thread
  tr[ace] (on|off) all       set trace mode of all threads
  q[uit]                     exit from debugger
  v[ar] g[lobal]             show global variables
  v[ar] l[ocal]              show local variables
  v[ar] i[nstance] <object>  show instance variables of object
  v[ar] c[onst] <object>     show constants of object
  m[ethod] i[nstance] <obj>  show methods of object
  m[ethod] <class|module>    show instance methods of class or module
  th[read] l[ist]            list all threads
  th[read] c[ur[rent]]       show current thread
  th[read] [sw[itch]] <nnn>  switch thread context to nnn
  th[read] stop <nnn>        stop thread nnn
  th[read] resume <nnn>      resume thread nnn
  pp expression              evaluate expression and pretty_print its value
  p expression               evaluate expression and print its value
  r[estart]                  restart program
  h[elp]                     print this help
  <everything else>          evaluate
EOHELP
    end

    def display_expressions(binding)
      n = 1
      for d in display
        if d[0]
          stdout.printf "%d: ", n
          display_expression(d[1], binding)
        end
        n += 1
      end
    end

    def display_expression(exp, binding)
      stdout.printf "%s = %s\n", exp, debug_silent_eval(exp, binding).to_s
    end

    def frame_set_pos(file, line)
      if @frames[0]
        @frames[0][1] = file
        @frames[0][2] = line
      end
    end

    def display_frames(pos)
      0.upto(@frames.size - 1) do |n|
        if n == pos
          stdout.print "--> "
        else
          stdout.print "    "
        end
        stdout.print format_frame(n)
      end
    end

    def format_frame(pos)
      _, file, line, id = @frames[pos]
      sprintf "#%d %s:%s%s\n", pos + 1, file, line,
        (id ? ":in `#{id.id2name}'" : "")
    end

    def script_lines(file, line)
      unless (lines = SCRIPT_LINES__[file]) and lines != true
        Tracer::Single.get_line(file, line) if File.exist?(file)
        lines = SCRIPT_LINES__[file]
        lines = nil if lines == true
      end
      lines
    end

    def display_list(b, e, file, line)
      if lines = script_lines(file, line)
        stdout.printf "[%d, %d] in %s\n", b, e, file
        b.upto(e) do |n|
          if n > 0 && lines[n-1]
            if n == line
              stdout.printf "=> %d  %s\n", n, lines[n-1].chomp
            else
              stdout.printf "   %d  %s\n", n, lines[n-1].chomp
            end
          end
        end
      else
        stdout.printf "No sourcefile available for %s\n", file
      end
    end

    def line_at(file, line)
      lines = script_lines(file, line)
      if lines and line = lines[line-1]
        return line
      end
      return "\n"
    end

    def debug_funcname(id)
      if id.nil?
        "toplevel"
      else
        id.id2name
      end
    end

    def check_break_points(file, klass, pos, binding, id)
      return false if break_points.empty?
      n = 1
      for b in break_points
        if b[0]           # valid
          if b[1] == 0    # breakpoint
            if (b[2] == file and b[3] == pos) or
                (klass and b[2] == klass and b[3] == pos)
              stdout.printf "Breakpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos
              return true
            end
          elsif b[1] == 1 # watchpoint
            if debug_silent_eval(b[2], binding)
              stdout.printf "Watchpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos
              return true
            end
          end
        end
        n += 1
      end
      return false
    end

    def excn_handle(file, line, id, binding)
      if $!.class <= SystemExit
        set_trace_func nil
        exit
      end

      if @catch and ($!.class.ancestors.find { |e| e.to_s == @catch })
        stdout.printf "%s:%d: `%s' (%s)\n", file, line, $!, $!.class
        fs = @frames.size
        tb = caller(0)[-fs..-1]
        if tb
          for i in tb
            stdout.printf "\tfrom %s\n", i
          end
        end
        suspend_all
        debug_command(file, line, id, binding)
      end
    end

    def trace_func(event, file, line, id, binding, klass)
      Tracer.trace_func(event, file, line, id, binding, klass) if trace?
      context(Thread.current).check_suspend
      @file = file
      @line = line
      case event
      when 'line'
        frame_set_pos(file, line)
        if !@no_step or @frames.size == @no_step
          @stop_next -= 1
          @stop_next = -1 if @stop_next < 0
        elsif @frames.size < @no_step
          @stop_next = 0          # break here before leaving...
        else
          # nothing to do. skipped.
        end
        if @stop_next == 0 or check_break_points(file, nil, line, binding, id)
          @no_step = nil
          suspend_all
          debug_command(file, line, id, binding)
        end

      when 'call'
        @frames.unshift [binding, file, line, id]
        if check_break_points(file, klass, id.id2name, binding, id)
          suspend_all
          debug_command(file, line, id, binding)
        end

      when 'c-call'
        frame_set_pos(file, line)

      when 'class'
        @frames.unshift [binding, file, line, id]

      when 'return', 'end'
        if @frames.size == @finish_pos
          @stop_next = 1
          @finish_pos = 0
        end
        @frames.shift

      when 'raise'
        excn_handle(file, line, id, binding)

      end
      @last_file = file
    end
  end

  trap("INT") { DEBUGGER__.interrupt }
  @last_thread = Thread::main
  @max_thread = 1
  @thread_list = {Thread::main => 1}
  @break_points = []
  @display = []
  @waiting = []
  @stdout = STDOUT

  class << DEBUGGER__
    # Returns the IO used as stdout. Defaults to STDOUT
    def stdout
      @stdout
    end

    # Sets the IO used as stdout. Defaults to STDOUT
    def stdout=(s)
      @stdout = s
    end

    # Returns the display expression list
    #
    # See DEBUGGER__ for more usage
    def display
      @display
    end

    # Returns the list of break points where execution will be stopped.
    #
    # See DEBUGGER__ for more usage
    def break_points
      @break_points
    end

    # Returns the list of waiting threads.
    #
    # When stepping through the traces of a function, thread gets suspended, to
    # be resumed later.
    def waiting
      @waiting
    end

    def set_trace( arg )
      MUTEX.synchronize do
        make_thread_list
        for th, in @thread_list
          context(th).set_trace arg
        end
      end
      arg
    end

    def set_last_thread(th)
      @last_thread = th
    end

    def suspend
      MUTEX.synchronize do
        make_thread_list
        for th, in @thread_list
          next if th == Thread.current
          context(th).set_suspend
        end
      end
      # Schedule other threads to suspend as soon as possible.
      Thread.pass
    end

    def resume
      MUTEX.synchronize do
        make_thread_list
        @thread_list.each do |th,|
          next if th == Thread.current
          context(th).clear_suspend
        end
        waiting.each do |th|
          th.run
        end
        waiting.clear
      end
      # Schedule other threads to restart as soon as possible.
      Thread.pass
    end

    def context(thread=Thread.current)
      c = thread[:__debugger_data__]
      unless c
        thread[:__debugger_data__] = c = Context.new
      end
      c
    end

    def interrupt
      context(@last_thread).stop_next
    end

    def get_thread(num)
      th = @thread_list.key(num)
      unless th
        @stdout.print "No thread ##{num}\n"
        throw :debug_error
      end
      th
    end

    def thread_list(num)
      th = get_thread(num)
      if th == Thread.current
        @stdout.print "+"
      else
        @stdout.print " "
      end
      @stdout.printf "%d ", num
      @stdout.print th.inspect, "\t"
      file = context(th).instance_eval{@file}
      if file
        @stdout.print file,":",context(th).instance_eval{@line}
      end
      @stdout.print "\n"
    end

    # Prints all threads in @thread_list to @stdout. Returns a sorted array of
    # values from the @thread_list hash.
    #
    # While in the debugger you can list all of
    # the threads with: <b>DEBUGGER__.thread_list_all</b>
    #
    #   (rdb:1) DEBUGGER__.thread_list_all
    #   +1 #<Thread:0x007fb2320c03f0 run> debug_me.rb.rb:3
    #    2 #<Thread:0x007fb23218a538 debug_me.rb.rb:3 sleep>
    #    3 #<Thread:0x007fb23218b0f0 debug_me.rb.rb:3 sleep>
    #   [1, 2, 3]
    #
    # Your current thread is indicated by a <b>+</b>
    #
    # Additionally you can list all threads with <b>th l</b>
    #
    #   (rdb:1) th l
    #    +1 #<Thread:0x007f99328c0410 run>  debug_me.rb:3
    #     2 #<Thread:0x007f9932938230 debug_me.rb:3 sleep> debug_me.rb:3
    #     3 #<Thread:0x007f9932938e10 debug_me.rb:3 sleep> debug_me.rb:3
    #
    # See DEBUGGER__ for more usage.

    def thread_list_all
      for th in @thread_list.values.sort
        thread_list(th)
      end
    end

    def make_thread_list
      hash = {}
      for th in Thread::list
        if @thread_list.key? th
          hash[th] = @thread_list[th]
        else
          @max_thread += 1
          hash[th] = @max_thread
        end
      end
      @thread_list = hash
    end

    def debug_thread_info(input, binding)
      case input
      when /^l(?:ist)?/
        make_thread_list
        thread_list_all

      when /^c(?:ur(?:rent)?)?$/
        make_thread_list
        thread_list(@thread_list[Thread.current])

      when /^(?:sw(?:itch)?\s+)?(\d+)/
        make_thread_list
        th = get_thread($1.to_i)
        if th == Thread.current
          @stdout.print "It's the current thread.\n"
        else
          thread_list(@thread_list[th])
          context(th).stop_next
          th.run
          return :cont
        end

      when /^stop\s+(\d+)/
        make_thread_list
        th = get_thread($1.to_i)
        if th == Thread.current
          @stdout.print "It's the current thread.\n"
        elsif th.stop?
          @stdout.print "Already stopped.\n"
        else
          thread_list(@thread_list[th])
          context(th).suspend
        end

      when /^resume\s+(\d+)/
        make_thread_list
        th = get_thread($1.to_i)
        if th == Thread.current
          @stdout.print "It's the current thread.\n"
        elsif !th.stop?
          @stdout.print "Already running."
        else
          thread_list(@thread_list[th])
          th.run
        end
      end
    end
  end

  stdout.printf "Debug.rb\n"
  stdout.printf "Emacs support available.\n\n"
  if defined?(RubyVM::InstructionSequence)
    RubyVM::InstructionSequence.compile_option = {
      trace_instruction: true
    }
  end
  set_trace_func proc { |event, file, line, id, binding, klass, *rest|
    DEBUGGER__.context.trace_func event, file, line, id, binding, klass
  }
end
# frozen_string_literal: true

require 'date'

# :stopdoc:

# = time.rb
#
# When 'time' is required, Time is extended with additional methods for parsing
# and converting Times.
#
# == Features
#
# This library extends the Time class with the following conversions between
# date strings and Time objects:
#
# * date-time defined by {RFC 2822}[http://www.ietf.org/rfc/rfc2822.txt]
# * HTTP-date defined by {RFC 2616}[http://www.ietf.org/rfc/rfc2616.txt]
# * dateTime defined by XML Schema Part 2: Datatypes ({ISO
#   8601}[http://www.iso.org/iso/date_and_time_format])
# * various formats handled by Date._parse
# * custom formats handled by Date._strptime

# :startdoc:

class Time
  class << Time

    #
    # A hash of timezones mapped to hour differences from UTC. The
    # set of time zones corresponds to the ones specified by RFC 2822
    # and ISO 8601.
    #
    ZoneOffset = { # :nodoc:
      'UTC' => 0,
      # ISO 8601
      'Z' => 0,
      # RFC 822
      'UT' => 0, 'GMT' => 0,
      'EST' => -5, 'EDT' => -4,
      'CST' => -6, 'CDT' => -5,
      'MST' => -7, 'MDT' => -6,
      'PST' => -8, 'PDT' => -7,
      # Following definition of military zones is original one.
      # See RFC 1123 and RFC 2822 for the error in RFC 822.
      'A' => +1, 'B' => +2, 'C' => +3, 'D' => +4,  'E' => +5,  'F' => +6,
      'G' => +7, 'H' => +8, 'I' => +9, 'K' => +10, 'L' => +11, 'M' => +12,
      'N' => -1, 'O' => -2, 'P' => -3, 'Q' => -4,  'R' => -5,  'S' => -6,
      'T' => -7, 'U' => -8, 'V' => -9, 'W' => -10, 'X' => -11, 'Y' => -12,
    }

    #
    # Return the number of seconds the specified time zone differs
    # from UTC.
    #
    # Numeric time zones that include minutes, such as
    # <code>-10:00</code> or <code>+1330</code> will work, as will
    # simpler hour-only time zones like <code>-10</code> or
    # <code>+13</code>.
    #
    # Textual time zones listed in ZoneOffset are also supported.
    #
    # If the time zone does not match any of the above, +zone_offset+
    # will check if the local time zone (both with and without
    # potential Daylight Saving \Time changes being in effect) matches
    # +zone+. Specifying a value for +year+ will change the year used
    # to find the local time zone.
    #
    # If +zone_offset+ is unable to determine the offset, nil will be
    # returned.
    #
    #     require 'time'
    #
    #     Time.zone_offset("EST") #=> -18000
    #
    # You must require 'time' to use this method.
    #
    def zone_offset(zone, year=self.now.year)
      off = nil
      zone = zone.upcase
      if /\A([+-])(\d\d)(:?)(\d\d)(?:\3(\d\d))?\z/ =~ zone
        off = ($1 == '-' ? -1 : 1) * (($2.to_i * 60 + $4.to_i) * 60 + $5.to_i)
      elsif zone.match?(/\A[+-]\d\d\z/)
        off = zone.to_i * 3600
      elsif ZoneOffset.include?(zone)
        off = ZoneOffset[zone] * 3600
      elsif ((t = self.local(year, 1, 1)).zone.upcase == zone rescue false)
        off = t.utc_offset
      elsif ((t = self.local(year, 7, 1)).zone.upcase == zone rescue false)
        off = t.utc_offset
      end
      off
    end

    def zone_utc?(zone)
      # * +0000
      #   In RFC 2822, +0000 indicate a time zone at Universal Time.
      #   Europe/Lisbon is "a time zone at Universal Time" in Winter.
      #   Atlantic/Reykjavik is "a time zone at Universal Time".
      #   Africa/Dakar is "a time zone at Universal Time".
      #   So +0000 is a local time such as Europe/London, etc.
      # * GMT
      #   GMT is used as a time zone abbreviation in Europe/London,
      #   Africa/Dakar, etc.
      #   So it is a local time.
      #
      # * -0000, -00:00
      #   In RFC 2822, -0000 the date-time contains no information about the
      #   local time zone.
      #   In RFC 3339, -00:00 is used for the time in UTC is known,
      #   but the offset to local time is unknown.
      #   They are not appropriate for specific time zone such as
      #   Europe/London because time zone neutral,
      #   So -00:00 and -0000 are treated as UTC.
      zone.match?(/\A(?:-00:00|-0000|-00|UTC|Z|UT)\z/i)
    end
    private :zone_utc?

    def force_zone!(t, zone, offset=nil)
      if zone_utc?(zone)
        t.utc
      elsif offset ||= zone_offset(zone)
        # Prefer the local timezone over the fixed offset timezone because
        # the former is a real timezone and latter is an artificial timezone.
        t.localtime
        if t.utc_offset != offset
          # Use the fixed offset timezone only if the local timezone cannot
          # represent the given offset.
          t.localtime(offset)
        end
      else
        t.localtime
      end
    end
    private :force_zone!

    LeapYearMonthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # :nodoc:
    CommonYearMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # :nodoc:
    def month_days(y, m)
      if ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)
        LeapYearMonthDays[m-1]
      else
        CommonYearMonthDays[m-1]
      end
    end
    private :month_days

    def apply_offset(year, mon, day, hour, min, sec, off)
      if off < 0
        off = -off
        off, o = off.divmod(60)
        if o != 0 then sec += o; o, sec = sec.divmod(60); off += o end
        off, o = off.divmod(60)
        if o != 0 then min += o; o, min = min.divmod(60); off += o end
        off, o = off.divmod(24)
        if o != 0 then hour += o; o, hour = hour.divmod(24); off += o end
        if off != 0
          day += off
          days = month_days(year, mon)
          if days and days < day
            mon += 1
            if 12 < mon
              mon = 1
              year += 1
            end
            day = 1
          end
        end
      elsif 0 < off
        off, o = off.divmod(60)
        if o != 0 then sec -= o; o, sec = sec.divmod(60); off -= o end
        off, o = off.divmod(60)
        if o != 0 then min -= o; o, min = min.divmod(60); off -= o end
        off, o = off.divmod(24)
        if o != 0 then hour -= o; o, hour = hour.divmod(24); off -= o end
        if off != 0 then
          day -= off
          if day < 1
            mon -= 1
            if mon < 1
              year -= 1
              mon = 12
            end
            day = month_days(year, mon)
          end
        end
      end
      return year, mon, day, hour, min, sec
    end
    private :apply_offset

    def make_time(date, year, yday, mon, day, hour, min, sec, sec_fraction, zone, now)
      if !year && !yday && !mon && !day && !hour && !min && !sec && !sec_fraction
        raise ArgumentError, "no time information in #{date.inspect}"
      end

      off = nil
      if year || now
        off_year = year || now.year
        off = zone_offset(zone, off_year) if zone
      end

      if yday
        unless (1..366) === yday
          raise ArgumentError, "yday #{yday} out of range"
        end
        mon, day = (yday-1).divmod(31)
        mon += 1
        day += 1
        t = make_time(date, year, nil, mon, day, hour, min, sec, sec_fraction, zone, now)
        diff = yday - t.yday
        return t if diff.zero?
        day += diff
        if day > 28 and day > (mday = month_days(off_year, mon))
          if (mon += 1) > 12
            raise ArgumentError, "yday #{yday} out of range"
          end
          day -= mday
        end
        return make_time(date, year, nil, mon, day, hour, min, sec, sec_fraction, zone, now)
      end

      if now and now.respond_to?(:getlocal)
        if off
          now = now.getlocal(off) if now.utc_offset != off
        else
          now = now.getlocal
        end
      end

      usec = nil
      usec = sec_fraction * 1000000 if sec_fraction

      if now
        begin
          break if year; year = now.year
          break if mon; mon = now.mon
          break if day; day = now.day
          break if hour; hour = now.hour
          break if min; min = now.min
          break if sec; sec = now.sec
          break if sec_fraction; usec = now.tv_usec
        end until true
      end

      year ||= 1970
      mon ||= 1
      day ||= 1
      hour ||= 0
      min ||= 0
      sec ||= 0
      usec ||= 0

      if year != off_year
        off = nil
        off = zone_offset(zone, year) if zone
      end

      if off
        year, mon, day, hour, min, sec =
          apply_offset(year, mon, day, hour, min, sec, off)
        t = self.utc(year, mon, day, hour, min, sec, usec)
        force_zone!(t, zone, off)
        t
      else
        self.local(year, mon, day, hour, min, sec, usec)
      end
    end
    private :make_time

    #
    # Takes a string representation of a Time and attempts to parse it
    # using a heuristic.
    #
    # This method **does not** function as a validator.  If the input
    # string does not match valid formats strictly, you may get a
    # cryptic result.  Should consider to use `Time.strptime` instead
    # of this method as possible.
    #
    #     require 'time'
    #
    #     Time.parse("2010-10-31") #=> 2010-10-31 00:00:00 -0500
    #
    # Any missing pieces of the date are inferred based on the current date.
    #
    #     require 'time'
    #
    #     # assuming the current date is "2011-10-31"
    #     Time.parse("12:00") #=> 2011-10-31 12:00:00 -0500
    #
    # We can change the date used to infer our missing elements by passing a second
    # object that responds to #mon, #day and #year, such as Date, Time or DateTime.
    # We can also use our own object.
    #
    #     require 'time'
    #
    #     class MyDate
    #       attr_reader :mon, :day, :year
    #
    #       def initialize(mon, day, year)
    #         @mon, @day, @year = mon, day, year
    #       end
    #     end
    #
    #     d  = Date.parse("2010-10-28")
    #     t  = Time.parse("2010-10-29")
    #     dt = DateTime.parse("2010-10-30")
    #     md = MyDate.new(10,31,2010)
    #
    #     Time.parse("12:00", d)  #=> 2010-10-28 12:00:00 -0500
    #     Time.parse("12:00", t)  #=> 2010-10-29 12:00:00 -0500
    #     Time.parse("12:00", dt) #=> 2010-10-30 12:00:00 -0500
    #     Time.parse("12:00", md) #=> 2010-10-31 12:00:00 -0500
    #
    # If a block is given, the year described in +date+ is converted
    # by the block.  This is specifically designed for handling two
    # digit years. For example, if you wanted to treat all two digit
    # years prior to 70 as the year 2000+ you could write this:
    #
    #     require 'time'
    #
    #     Time.parse("01-10-31") {|year| year + (year < 70 ? 2000 : 1900)}
    #     #=> 2001-10-31 00:00:00 -0500
    #     Time.parse("70-10-31") {|year| year + (year < 70 ? 2000 : 1900)}
    #     #=> 1970-10-31 00:00:00 -0500
    #
    # If the upper components of the given time are broken or missing, they are
    # supplied with those of +now+.  For the lower components, the minimum
    # values (1 or 0) are assumed if broken or missing.  For example:
    #
    #     require 'time'
    #
    #     # Suppose it is "Thu Nov 29 14:33:20 2001" now and
    #     # your time zone is EST which is GMT-5.
    #     now = Time.parse("Thu Nov 29 14:33:20 2001")
    #     Time.parse("16:30", now)     #=> 2001-11-29 16:30:00 -0500
    #     Time.parse("7/23", now)      #=> 2001-07-23 00:00:00 -0500
    #     Time.parse("Aug 31", now)    #=> 2001-08-31 00:00:00 -0500
    #     Time.parse("Aug 2000", now)  #=> 2000-08-01 00:00:00 -0500
    #
    # Since there are numerous conflicts among locally defined time zone
    # abbreviations all over the world, this method is not intended to
    # understand all of them.  For example, the abbreviation "CST" is
    # used variously as:
    #
    #     -06:00 in America/Chicago,
    #     -05:00 in America/Havana,
    #     +08:00 in Asia/Harbin,
    #     +09:30 in Australia/Darwin,
    #     +10:30 in Australia/Adelaide,
    #     etc.
    #
    # Based on this fact, this method only understands the time zone
    # abbreviations described in RFC 822 and the system time zone, in the
    # order named. (i.e. a definition in RFC 822 overrides the system
    # time zone definition.)  The system time zone is taken from
    # <tt>Time.local(year, 1, 1).zone</tt> and
    # <tt>Time.local(year, 7, 1).zone</tt>.
    # If the extracted time zone abbreviation does not match any of them,
    # it is ignored and the given time is regarded as a local time.
    #
    # ArgumentError is raised if Date._parse cannot extract information from
    # +date+ or if the Time class cannot represent specified date.
    #
    # This method can be used as a fail-safe for other parsing methods as:
    #
    #   Time.rfc2822(date) rescue Time.parse(date)
    #   Time.httpdate(date) rescue Time.parse(date)
    #   Time.xmlschema(date) rescue Time.parse(date)
    #
    # A failure of Time.parse should be checked, though.
    #
    # You must require 'time' to use this method.
    #
    def parse(date, now=self.now)
      comp = !block_given?
      d = Date._parse(date, comp)
      year = d[:year]
      year = yield(year) if year && !comp
      make_time(date, year, d[:yday], d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now)
    end

    #
    # Works similar to +parse+ except that instead of using a
    # heuristic to detect the format of the input string, you provide
    # a second argument that describes the format of the string.
    #
    # If a block is given, the year described in +date+ is converted by the
    # block.  For example:
    #
    #   Time.strptime(...) {|y| y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y}
    #
    # Below is a list of the formatting options:
    #
    # %a :: The abbreviated weekday name ("Sun")
    # %A :: The  full  weekday  name ("Sunday")
    # %b :: The abbreviated month name ("Jan")
    # %B :: The  full  month  name ("January")
    # %c :: The preferred local date and time representation
    # %C :: Century (20 in 2009)
    # %d :: Day of the month (01..31)
    # %D :: Date (%m/%d/%y)
    # %e :: Day of the month, blank-padded ( 1..31)
    # %F :: Equivalent to %Y-%m-%d (the ISO 8601 date format)
    # %g :: The last two digits of the commercial year
    # %G :: The week-based year according to ISO-8601 (week 1 starts on Monday
    #       and includes January 4)
    # %h :: Equivalent to %b
    # %H :: Hour of the day, 24-hour clock (00..23)
    # %I :: Hour of the day, 12-hour clock (01..12)
    # %j :: Day of the year (001..366)
    # %k :: hour, 24-hour clock, blank-padded ( 0..23)
    # %l :: hour, 12-hour clock, blank-padded ( 0..12)
    # %L :: Millisecond of the second (000..999)
    # %m :: Month of the year (01..12)
    # %M :: Minute of the hour (00..59)
    # %n :: Newline (\n)
    # %N :: Fractional seconds digits
    # %p :: Meridian indicator ("AM" or "PM")
    # %P :: Meridian indicator ("am" or "pm")
    # %r :: time, 12-hour (same as %I:%M:%S %p)
    # %R :: time, 24-hour (%H:%M)
    # %s :: Number of seconds since 1970-01-01 00:00:00 UTC.
    # %S :: Second of the minute (00..60)
    # %t :: Tab character (\t)
    # %T :: time, 24-hour (%H:%M:%S)
    # %u :: Day of the week as a decimal, Monday being 1. (1..7)
    # %U :: Week number of the current year, starting with the first Sunday as
    #       the first day of the first week (00..53)
    # %v :: VMS date (%e-%b-%Y)
    # %V :: Week number of year according to ISO 8601 (01..53)
    # %W :: Week  number  of the current year, starting with the first Monday
    #       as the first day of the first week (00..53)
    # %w :: Day of the week (Sunday is 0, 0..6)
    # %x :: Preferred representation for the date alone, no time
    # %X :: Preferred representation for the time alone, no date
    # %y :: Year without a century (00..99)
    # %Y :: Year which may include century, if provided
    # %z :: Time zone as  hour offset from UTC (e.g. +0900)
    # %Z :: Time zone name
    # %% :: Literal "%" character
    # %+ :: date(1) (%a %b %e %H:%M:%S %Z %Y)
    #
    #     require 'time'
    #
    #     Time.strptime("2000-10-31", "%Y-%m-%d") #=> 2000-10-31 00:00:00 -0500
    #
    # You must require 'time' to use this method.
    #
    def strptime(date, format, now=self.now)
      d = Date._strptime(date, format)
      raise ArgumentError, "invalid date or strptime format - `#{date}' `#{format}'" unless d
      if seconds = d[:seconds]
        if sec_fraction = d[:sec_fraction]
          usec = sec_fraction * 1000000
          usec *= -1 if seconds < 0
        else
          usec = 0
        end
        t = Time.at(seconds, usec)
        if zone = d[:zone]
          force_zone!(t, zone)
        end
      else
        year = d[:year]
        year = yield(year) if year && block_given?
        yday = d[:yday]
        if (d[:cwyear] && !year) || ((d[:cwday] || d[:cweek]) && !(d[:mon] && d[:mday]))
          # make_time doesn't deal with cwyear/cwday/cweek
          return Date.strptime(date, format).to_time
        end
        if (d[:wnum0] || d[:wnum1]) && !yday && !(d[:mon] && d[:mday])
          yday = Date.strptime(date, format).yday
        end
        t = make_time(date, year, yday, d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now)
      end
      t
    end

    MonthValue = { # :nodoc:
      'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6,
      'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'OCT' =>10, 'NOV' =>11, 'DEC' =>12
    }

    #
    # Parses +date+ as date-time defined by RFC 2822 and converts it to a Time
    # object.  The format is identical to the date format defined by RFC 822 and
    # updated by RFC 1123.
    #
    # ArgumentError is raised if +date+ is not compliant with RFC 2822
    # or if the Time class cannot represent specified date.
    #
    # See #rfc2822 for more information on this format.
    #
    #     require 'time'
    #
    #     Time.rfc2822("Wed, 05 Oct 2011 22:26:12 -0400")
    #     #=> 2010-10-05 22:26:12 -0400
    #
    # You must require 'time' to use this method.
    #
    def rfc2822(date)
      if /\A\s*
          (?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*,\s*)?
          (\d{1,2})\s+
          (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+
          (\d{2,})\s+
          (\d{2})\s*
          :\s*(\d{2})
          (?:\s*:\s*(\d\d))?\s+
          ([+-]\d{4}|
           UT|GMT|EST|EDT|CST|CDT|MST|MDT|PST|PDT|[A-IK-Z])/ix =~ date
        # Since RFC 2822 permit comments, the regexp has no right anchor.
        day = $1.to_i
        mon = MonthValue[$2.upcase]
        year = $3.to_i
        short_year_p = $3.length <= 3
        hour = $4.to_i
        min = $5.to_i
        sec = $6 ? $6.to_i : 0
        zone = $7

        if short_year_p
          # following year completion is compliant with RFC 2822.
          year = if year < 50
                   2000 + year
                 else
                   1900 + year
                 end
        end

        off = zone_offset(zone)
        year, mon, day, hour, min, sec =
          apply_offset(year, mon, day, hour, min, sec, off)
        t = self.utc(year, mon, day, hour, min, sec)
        force_zone!(t, zone, off)
        t
      else
        raise ArgumentError.new("not RFC 2822 compliant date: #{date.inspect}")
      end
    end
    alias rfc822 rfc2822

    #
    # Parses +date+ as an HTTP-date defined by RFC 2616 and converts it to a
    # Time object.
    #
    # ArgumentError is raised if +date+ is not compliant with RFC 2616 or if
    # the Time class cannot represent specified date.
    #
    # See #httpdate for more information on this format.
    #
    #     require 'time'
    #
    #     Time.httpdate("Thu, 06 Oct 2011 02:26:12 GMT")
    #     #=> 2011-10-06 02:26:12 UTC
    #
    # You must require 'time' to use this method.
    #
    def httpdate(date)
      if date.match?(/\A\s*
          (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\x20
          (\d{2})\x20
          (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
          (\d{4})\x20
          (\d{2}):(\d{2}):(\d{2})\x20
          GMT
          \s*\z/ix)
        self.rfc2822(date).utc
      elsif /\A\s*
             (?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday),\x20
             (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d)\x20
             (\d\d):(\d\d):(\d\d)\x20
             GMT
             \s*\z/ix =~ date
        year = $3.to_i
        if year < 50
          year += 2000
        else
          year += 1900
        end
        self.utc(year, $2, $1.to_i, $4.to_i, $5.to_i, $6.to_i)
      elsif /\A\s*
             (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\x20
             (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
             (\d\d|\x20\d)\x20
             (\d\d):(\d\d):(\d\d)\x20
             (\d{4})
             \s*\z/ix =~ date
        self.utc($6.to_i, MonthValue[$1.upcase], $2.to_i,
                 $3.to_i, $4.to_i, $5.to_i)
      else
        raise ArgumentError.new("not RFC 2616 compliant date: #{date.inspect}")
      end
    end

    #
    # Parses +time+ as a dateTime defined by the XML Schema and converts it to
    # a Time object.  The format is a restricted version of the format defined
    # by ISO 8601.
    #
    # ArgumentError is raised if +time+ is not compliant with the format or if
    # the Time class cannot represent the specified time.
    #
    # See #xmlschema for more information on this format.
    #
    #     require 'time'
    #
    #     Time.xmlschema("2011-10-05T22:26:12-04:00")
    #     #=> 2011-10-05 22:26:12-04:00
    #
    # You must require 'time' to use this method.
    #
    def xmlschema(time)
      if /\A\s*
          (-?\d+)-(\d\d)-(\d\d)
          T
          (\d\d):(\d\d):(\d\d)
          (\.\d+)?
          (Z|[+-]\d\d(?::?\d\d)?)?
          \s*\z/ix =~ time
        year = $1.to_i
        mon = $2.to_i
        day = $3.to_i
        hour = $4.to_i
        min = $5.to_i
        sec = $6.to_i
        usec = 0
        if $7
          usec = Rational($7) * 1000000
        end
        if $8
          zone = $8
          off = zone_offset(zone)
          year, mon, day, hour, min, sec =
            apply_offset(year, mon, day, hour, min, sec, off)
          t = self.utc(year, mon, day, hour, min, sec, usec)
          force_zone!(t, zone, off)
          t
        else
          self.local(year, mon, day, hour, min, sec, usec)
        end
      else
        raise ArgumentError.new("invalid xmlschema format: #{time.inspect}")
      end
    end
    alias iso8601 xmlschema
  end # class << self

  #
  # Returns a string which represents the time as date-time defined by RFC 2822:
  #
  #   day-of-week, DD month-name CCYY hh:mm:ss zone
  #
  # where zone is [+-]hhmm.
  #
  # If +self+ is a UTC time, -0000 is used as zone.
  #
  #     require 'time'
  #
  #     t = Time.now
  #     t.rfc2822  # => "Wed, 05 Oct 2011 22:26:12 -0400"
  #
  # You must require 'time' to use this method.
  #
  def rfc2822
    sprintf('%s, %02d %s %0*d %02d:%02d:%02d ',
      RFC2822_DAY_NAME[wday],
      day, RFC2822_MONTH_NAME[mon-1], year < 0 ? 5 : 4, year,
      hour, min, sec) <<
    if utc?
      '-0000'
    else
      off = utc_offset
      sign = off < 0 ? '-' : '+'
      sprintf('%s%02d%02d', sign, *(off.abs / 60).divmod(60))
    end
  end
  alias rfc822 rfc2822


  RFC2822_DAY_NAME = [ # :nodoc:
    'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
  ]

  RFC2822_MONTH_NAME = [ # :nodoc:
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
  ]

  #
  # Returns a string which represents the time as RFC 1123 date of HTTP-date
  # defined by RFC 2616:
  #
  #   day-of-week, DD month-name CCYY hh:mm:ss GMT
  #
  # Note that the result is always UTC (GMT).
  #
  #     require 'time'
  #
  #     t = Time.now
  #     t.httpdate # => "Thu, 06 Oct 2011 02:26:12 GMT"
  #
  # You must require 'time' to use this method.
  #
  def httpdate
    t = dup.utc
    sprintf('%s, %02d %s %0*d %02d:%02d:%02d GMT',
      RFC2822_DAY_NAME[t.wday],
      t.day, RFC2822_MONTH_NAME[t.mon-1], t.year < 0 ? 5 : 4, t.year,
      t.hour, t.min, t.sec)
  end

  #
  # Returns a string which represents the time as a dateTime defined by XML
  # Schema:
  #
  #   CCYY-MM-DDThh:mm:ssTZD
  #   CCYY-MM-DDThh:mm:ss.sssTZD
  #
  # where TZD is Z or [+-]hh:mm.
  #
  # If self is a UTC time, Z is used as TZD.  [+-]hh:mm is used otherwise.
  #
  # +fractional_digits+ specifies a number of digits to use for fractional
  # seconds.  Its default value is 0.
  #
  #     require 'time'
  #
  #     t = Time.now
  #     t.iso8601  # => "2011-10-05T22:26:12-04:00"
  #
  # You must require 'time' to use this method.
  #
  def xmlschema(fraction_digits=0)
    fraction_digits = fraction_digits.to_i
    s = strftime("%FT%T")
    if fraction_digits > 0
      s << strftime(".%#{fraction_digits}N")
    end
    s << (utc? ? 'Z' : strftime("%:z"))
  end
  alias iso8601 xmlschema
end

# frozen_string_literal: false
require 'socket'
require 'openssl'
require_relative 'drb'
require 'singleton'

module DRb

  # The protocol for DRb over an SSL socket
  #
  # The URI for a DRb socket over SSL is:
  # <code>drbssl://<host>:<port>?<option></code>.  The option is optional
  class DRbSSLSocket < DRbTCPSocket

    # SSLConfig handles the needed SSL information for establishing a
    # DRbSSLSocket connection, including generating the X509 / RSA pair.
    #
    # An instance of this config can be passed to DRbSSLSocket.new,
    # DRbSSLSocket.open and DRbSSLSocket.open_server
    #
    # See DRb::DRbSSLSocket::SSLConfig.new for more details
    class SSLConfig

      # Default values for a SSLConfig instance.
      #
      # See DRb::DRbSSLSocket::SSLConfig.new for more details
      DEFAULT = {
        :SSLCertificate       => nil,
        :SSLPrivateKey        => nil,
        :SSLClientCA          => nil,
        :SSLCACertificatePath => nil,
        :SSLCACertificateFile => nil,
        :SSLTmpDhCallback     => nil,
        :SSLVerifyMode        => ::OpenSSL::SSL::VERIFY_NONE,
        :SSLVerifyDepth       => nil,
        :SSLVerifyCallback    => nil,   # custom verification
        :SSLCertificateStore  => nil,
        # Must specify if you use auto generated certificate.
        :SSLCertName          => nil,   # e.g. [["CN","fqdn.example.com"]]
        :SSLCertComment       => "Generated by Ruby/OpenSSL"
      }

      # Create a new DRb::DRbSSLSocket::SSLConfig instance
      #
      # The DRb::DRbSSLSocket will take either a +config+ Hash or an instance
      # of SSLConfig, and will setup the certificate for its session for the
      # configuration. If want it to generate a generic certificate, the bare
      # minimum is to provide the :SSLCertName
      #
      # === Config options
      #
      # From +config+ Hash:
      #
      # :SSLCertificate ::
      #   An instance of OpenSSL::X509::Certificate.  If this is not provided,
      #   then a generic X509 is generated, with a correspond :SSLPrivateKey
      #
      # :SSLPrivateKey ::
      #   A private key instance, like OpenSSL::PKey::RSA.  This key must be
      #   the key that signed the :SSLCertificate
      #
      # :SSLClientCA ::
      #   An OpenSSL::X509::Certificate, or Array of certificates that will
      #   used as ClientCAs in the SSL Context
      #
      # :SSLCACertificatePath ::
      #   A path to the directory of CA certificates.  The certificates must
      #   be in PEM format.
      #
      # :SSLCACertificateFile ::
      #   A path to a CA certificate file, in PEM format.
      #
      # :SSLTmpDhCallback ::
      #   A DH callback. See OpenSSL::SSL::SSLContext.tmp_dh_callback
      #
      # :SSLVerifyMode ::
      #   This is the SSL verification mode.  See OpenSSL::SSL::VERIFY_* for
      #   available modes.  The default is OpenSSL::SSL::VERIFY_NONE
      #
      # :SSLVerifyDepth ::
      #   Number of CA certificates to walk, when verifying a certificate
      #   chain.
      #
      # :SSLVerifyCallback ::
      #   A callback to be used for additional verification.  See
      #   OpenSSL::SSL::SSLContext.verify_callback
      #
      # :SSLCertificateStore ::
      #   A OpenSSL::X509::Store used for verification of certificates
      #
      # :SSLCertName ::
      #   Issuer name for the certificate.  This is required when generating
      #   the certificate (if :SSLCertificate and :SSLPrivateKey were not
      #   given).  The value of this is to be an Array of pairs:
      #
      #     [["C", "Raleigh"], ["ST","North Carolina"],
      #      ["CN","fqdn.example.com"]]
      #
      #   See also OpenSSL::X509::Name
      #
      # :SSLCertComment ::
      #   A comment to be used for generating the certificate.  The default is
      #   "Generated by Ruby/OpenSSL"
      #
      #
      # === Example
      #
      # These values can be added after the fact, like a Hash.
      #
      #   require 'drb/ssl'
      #   c = DRb::DRbSSLSocket::SSLConfig.new {}
      #   c[:SSLCertificate] =
      #     OpenSSL::X509::Certificate.new(File.read('mycert.crt'))
      #   c[:SSLPrivateKey] = OpenSSL::PKey::RSA.new(File.read('mycert.key'))
      #   c[:SSLVerifyMode] = OpenSSL::SSL::VERIFY_PEER
      #   c[:SSLCACertificatePath] = "/etc/ssl/certs/"
      #   c.setup_certificate
      #
      # or
      #
      #   require 'drb/ssl'
      #   c = DRb::DRbSSLSocket::SSLConfig.new({
      #           :SSLCertName => [["CN" => DRb::DRbSSLSocket.getservername]]
      #           })
      #   c.setup_certificate
      #
      def initialize(config)
        @config  = config
        @cert    = config[:SSLCertificate]
        @pkey    = config[:SSLPrivateKey]
        @ssl_ctx = nil
      end

      # A convenience method to access the values like a Hash
      def [](key);
        @config[key] || DEFAULT[key]
      end

      # Connect to IO +tcp+, with context of the current certificate
      # configuration
      def connect(tcp)
        ssl = ::OpenSSL::SSL::SSLSocket.new(tcp, @ssl_ctx)
        ssl.sync = true
        ssl.connect
        ssl
      end

      # Accept connection to IO +tcp+, with context of the current certificate
      # configuration
      def accept(tcp)
        ssl = OpenSSL::SSL::SSLSocket.new(tcp, @ssl_ctx)
        ssl.sync = true
        ssl.accept
        ssl
      end

      # Ensures that :SSLCertificate and :SSLPrivateKey have been provided
      # or that a new certificate is generated with the other parameters
      # provided.
      def setup_certificate
        if @cert && @pkey
          return
        end

        rsa = OpenSSL::PKey::RSA.new(2048){|p, n|
          next unless self[:verbose]
          case p
          when 0; $stderr.putc "."  # BN_generate_prime
          when 1; $stderr.putc "+"  # BN_generate_prime
          when 2; $stderr.putc "*"  # searching good prime,
                                    # n = #of try,
                                    # but also data from BN_generate_prime
          when 3; $stderr.putc "\n" # found good prime, n==0 - p, n==1 - q,
                                    # but also data from BN_generate_prime
          else;   $stderr.putc "*"  # BN_generate_prime
          end
        }

        cert = OpenSSL::X509::Certificate.new
        cert.version = 3
        cert.serial = 0
        name = OpenSSL::X509::Name.new(self[:SSLCertName])
        cert.subject = name
        cert.issuer = name
        cert.not_before = Time.now
        cert.not_after = Time.now + (365*24*60*60)
        cert.public_key = rsa.public_key

        ef = OpenSSL::X509::ExtensionFactory.new(nil,cert)
        cert.extensions = [
          ef.create_extension("basicConstraints","CA:FALSE"),
          ef.create_extension("subjectKeyIdentifier", "hash") ]
        ef.issuer_certificate = cert
        cert.add_extension(ef.create_extension("authorityKeyIdentifier",
                                               "keyid:always,issuer:always"))
        if comment = self[:SSLCertComment]
          cert.add_extension(ef.create_extension("nsComment", comment))
        end
        cert.sign(rsa, "SHA256")

        @cert = cert
        @pkey = rsa
      end

      # Establish the OpenSSL::SSL::SSLContext with the configuration
      # parameters provided.
      def setup_ssl_context
        ctx = ::OpenSSL::SSL::SSLContext.new
        ctx.cert            = @cert
        ctx.key             = @pkey
        ctx.client_ca       = self[:SSLClientCA]
        ctx.ca_path         = self[:SSLCACertificatePath]
        ctx.ca_file         = self[:SSLCACertificateFile]
        ctx.tmp_dh_callback = self[:SSLTmpDhCallback]
        ctx.verify_mode     = self[:SSLVerifyMode]
        ctx.verify_depth    = self[:SSLVerifyDepth]
        ctx.verify_callback = self[:SSLVerifyCallback]
        ctx.cert_store      = self[:SSLCertificateStore]
        @ssl_ctx = ctx
      end
    end

    # Parse the dRuby +uri+ for an SSL connection.
    #
    # Expects drbssl://...
    #
    # Raises DRbBadScheme or DRbBadURI if +uri+ is not matching or malformed
    def self.parse_uri(uri) # :nodoc:
      if /\Adrbssl:\/\/(.*?):(\d+)(\?(.*))?\z/ =~ uri
        host = $1
        port = $2.to_i
        option = $4
        [host, port, option]
      else
        raise(DRbBadScheme, uri) unless uri.start_with?('drbssl:')
        raise(DRbBadURI, 'can\'t parse uri:' + uri)
      end
    end

    # Return an DRb::DRbSSLSocket instance as a client-side connection,
    # with the SSL connected.  This is called from DRb::start_service or while
    # connecting to a remote object:
    #
    #   DRb.start_service 'drbssl://localhost:0', front, config
    #
    # +uri+ is the URI we are connected to,
    # <code>'drbssl://localhost:0'</code> above, +config+ is our
    # configuration.  Either a Hash or DRb::DRbSSLSocket::SSLConfig
    def self.open(uri, config)
      host, port, = parse_uri(uri)
      soc = TCPSocket.open(host, port)
      ssl_conf = SSLConfig::new(config)
      ssl_conf.setup_ssl_context
      ssl = ssl_conf.connect(soc)
      self.new(uri, ssl, ssl_conf, true)
    end

    # Returns a DRb::DRbSSLSocket instance as a server-side connection, with
    # the SSL connected.  This is called from DRb::start_service or while
    # connecting to a remote object:
    #
    #   DRb.start_service 'drbssl://localhost:0', front, config
    #
    # +uri+ is the URI we are connected to,
    # <code>'drbssl://localhost:0'</code> above, +config+ is our
    # configuration.  Either a Hash or DRb::DRbSSLSocket::SSLConfig
    def self.open_server(uri, config)
      uri = 'drbssl://:0' unless uri
      host, port, = parse_uri(uri)
      if host.size == 0
        host = getservername
        soc = open_server_inaddr_any(host, port)
      else
        soc = TCPServer.open(host, port)
      end
      port = soc.addr[1] if port == 0
      @uri = "drbssl://#{host}:#{port}"

      ssl_conf = SSLConfig.new(config)
      ssl_conf.setup_certificate
      ssl_conf.setup_ssl_context
      self.new(@uri, soc, ssl_conf, false)
    end

    # This is a convenience method to parse +uri+ and separate out any
    # additional options appended in the +uri+.
    #
    # Returns an option-less uri and the option => [uri,option]
    #
    # The +config+ is completely unused, so passing nil is sufficient.
    def self.uri_option(uri, config) # :nodoc:
      host, port, option = parse_uri(uri)
      return "drbssl://#{host}:#{port}", option
    end

    # Create a DRb::DRbSSLSocket instance.
    #
    # +uri+ is the URI we are connected to.
    # +soc+ is the tcp socket we are bound to.
    # +config+ is our configuration. Either a Hash or SSLConfig
    # +is_established+ is a boolean of whether +soc+ is currently established
    #
    # This is called automatically based on the DRb protocol.
    def initialize(uri, soc, config, is_established)
      @ssl = is_established ? soc : nil
      super(uri, soc.to_io, config)
    end

    # Returns the SSL stream
    def stream; @ssl; end # :nodoc:

    # Closes the SSL stream before closing the dRuby connection.
    def close # :nodoc:
      if @ssl
        @ssl.close
        @ssl = nil
      end
      super
    end

    def accept # :nodoc:
      begin
      while true
        soc = accept_or_shutdown
        return nil unless soc
        break if (@acl ? @acl.allow_socket?(soc) : true)
        soc.close
      end
      begin
        ssl = @config.accept(soc)
      rescue Exception
        soc.close
        raise
      end
      self.class.new(uri, ssl, @config, true)
      rescue OpenSSL::SSL::SSLError
        warn("#{$!.message} (#{$!.class})", uplevel: 0) if @config[:verbose]
        retry
      end
    end
  end

  DRbProtocol.add_protocol(DRbSSLSocket)
end
# frozen_string_literal: false
#
# = drb/drb.rb
#
# Distributed Ruby: _dRuby_ version 2.0.4
#
# Copyright (c) 1999-2003 Masatoshi SEKI.  You can redistribute it and/or
# modify it under the same terms as Ruby.
#
# Author:: Masatoshi SEKI
#
# Documentation:: William Webber (william@williamwebber.com)
#
# == Overview
#
# dRuby is a distributed object system for Ruby.  It allows an object in one
# Ruby process to invoke methods on an object in another Ruby process on the
# same or a different machine.
#
# The Ruby standard library contains the core classes of the dRuby package.
# However, the full package also includes access control lists and the
# Rinda tuple-space distributed task management system, as well as a
# large number of samples.  The full dRuby package can be downloaded from
# the dRuby home page (see *References*).
#
# For an introduction and examples of usage see the documentation to the
# DRb module.
#
# == References
#
# [http://www2a.biglobe.ne.jp/~seki/ruby/druby.html]
#    The dRuby home page, in Japanese.  Contains the full dRuby package
#    and links to other Japanese-language sources.
#
# [http://www2a.biglobe.ne.jp/~seki/ruby/druby.en.html]
#    The English version of the dRuby home page.
#
# [http://pragprog.com/book/sidruby/the-druby-book]
#    The dRuby Book: Distributed and Parallel Computing with Ruby
#    by Masatoshi Seki and Makoto Inoue
#
# [http://www.ruby-doc.org/docs/ProgrammingRuby/html/ospace.html]
#   The chapter from *Programming* *Ruby* by Dave Thomas and Andy Hunt
#   which discusses dRuby.
#
# [http://www.clio.ne.jp/home/web-i31s/Flotuard/Ruby/PRC2K_seki/dRuby.en.html]
#   Translation of presentation on Ruby by Masatoshi Seki.

require 'socket'
require 'io/wait'
require 'monitor'
require_relative 'eq'

#
# == Overview
#
# dRuby is a distributed object system for Ruby.  It is written in
# pure Ruby and uses its own protocol.  No add-in services are needed
# beyond those provided by the Ruby runtime, such as TCP sockets.  It
# does not rely on or interoperate with other distributed object
# systems such as CORBA, RMI, or .NET.
#
# dRuby allows methods to be called in one Ruby process upon a Ruby
# object located in another Ruby process, even on another machine.
# References to objects can be passed between processes.  Method
# arguments and return values are dumped and loaded in marshalled
# format.  All of this is done transparently to both the caller of the
# remote method and the object that it is called upon.
#
# An object in a remote process is locally represented by a
# DRb::DRbObject instance.  This acts as a sort of proxy for the
# remote object.  Methods called upon this DRbObject instance are
# forwarded to its remote object.  This is arranged dynamically at run
# time.  There are no statically declared interfaces for remote
# objects, such as CORBA's IDL.
#
# dRuby calls made into a process are handled by a DRb::DRbServer
# instance within that process.  This reconstitutes the method call,
# invokes it upon the specified local object, and returns the value to
# the remote caller.  Any object can receive calls over dRuby.  There
# is no need to implement a special interface, or mixin special
# functionality.  Nor, in the general case, does an object need to
# explicitly register itself with a DRbServer in order to receive
# dRuby calls.
#
# One process wishing to make dRuby calls upon another process must
# somehow obtain an initial reference to an object in the remote
# process by some means other than as the return value of a remote
# method call, as there is initially no remote object reference it can
# invoke a method upon.  This is done by attaching to the server by
# URI.  Each DRbServer binds itself to a URI such as
# 'druby://example.com:8787'.  A DRbServer can have an object attached
# to it that acts as the server's *front* *object*.  A DRbObject can
# be explicitly created from the server's URI.  This DRbObject's
# remote object will be the server's front object.  This front object
# can then return references to other Ruby objects in the DRbServer's
# process.
#
# Method calls made over dRuby behave largely the same as normal Ruby
# method calls made within a process.  Method calls with blocks are
# supported, as are raising exceptions.  In addition to a method's
# standard errors, a dRuby call may also raise one of the
# dRuby-specific errors, all of which are subclasses of DRb::DRbError.
#
# Any type of object can be passed as an argument to a dRuby call or
# returned as its return value.  By default, such objects are dumped
# or marshalled at the local end, then loaded or unmarshalled at the
# remote end.  The remote end therefore receives a copy of the local
# object, not a distributed reference to it; methods invoked upon this
# copy are executed entirely in the remote process, not passed on to
# the local original.  This has semantics similar to pass-by-value.
#
# However, if an object cannot be marshalled, a dRuby reference to it
# is passed or returned instead.  This will turn up at the remote end
# as a DRbObject instance.  All methods invoked upon this remote proxy
# are forwarded to the local object, as described in the discussion of
# DRbObjects.  This has semantics similar to the normal Ruby
# pass-by-reference.
#
# The easiest way to signal that we want an otherwise marshallable
# object to be passed or returned as a DRbObject reference, rather
# than marshalled and sent as a copy, is to include the
# DRb::DRbUndumped mixin module.
#
# dRuby supports calling remote methods with blocks.  As blocks (or
# rather the Proc objects that represent them) are not marshallable,
# the block executes in the local, not the remote, context.  Each
# value yielded to the block is passed from the remote object to the
# local block, then the value returned by each block invocation is
# passed back to the remote execution context to be collected, before
# the collected values are finally returned to the local context as
# the return value of the method invocation.
#
# == Examples of usage
#
# For more dRuby samples, see the +samples+ directory in the full
# dRuby distribution.
#
# === dRuby in client/server mode
#
# This illustrates setting up a simple client-server drb
# system.  Run the server and client code in different terminals,
# starting the server code first.
#
# ==== Server code
#
#   require 'drb/drb'
#
#   # The URI for the server to connect to
#   URI="druby://localhost:8787"
#
#   class TimeServer
#
#     def get_current_time
#       return Time.now
#     end
#
#   end
#
#   # The object that handles requests on the server
#   FRONT_OBJECT=TimeServer.new
#
#   DRb.start_service(URI, FRONT_OBJECT)
#   # Wait for the drb server thread to finish before exiting.
#   DRb.thread.join
#
# ==== Client code
#
#   require 'drb/drb'
#
#   # The URI to connect to
#   SERVER_URI="druby://localhost:8787"
#
#   # Start a local DRbServer to handle callbacks.
#   #
#   # Not necessary for this small example, but will be required
#   # as soon as we pass a non-marshallable object as an argument
#   # to a dRuby call.
#   #
#   # Note: this must be called at least once per process to take any effect.
#   # This is particularly important if your application forks.
#   DRb.start_service
#
#   timeserver = DRbObject.new_with_uri(SERVER_URI)
#   puts timeserver.get_current_time
#
# === Remote objects under dRuby
#
# This example illustrates returning a reference to an object
# from a dRuby call.  The Logger instances live in the server
# process.  References to them are returned to the client process,
# where methods can be invoked upon them.  These methods are
# executed in the server process.
#
# ==== Server code
#
#   require 'drb/drb'
#
#   URI="druby://localhost:8787"
#
#   class Logger
#
#       # Make dRuby send Logger instances as dRuby references,
#       # not copies.
#       include DRb::DRbUndumped
#
#       def initialize(n, fname)
#           @name = n
#           @filename = fname
#       end
#
#       def log(message)
#           File.open(@filename, "a") do |f|
#               f.puts("#{Time.now}: #{@name}: #{message}")
#           end
#       end
#
#   end
#
#   # We have a central object for creating and retrieving loggers.
#   # This retains a local reference to all loggers created.  This
#   # is so an existing logger can be looked up by name, but also
#   # to prevent loggers from being garbage collected.  A dRuby
#   # reference to an object is not sufficient to prevent it being
#   # garbage collected!
#   class LoggerFactory
#
#       def initialize(bdir)
#           @basedir = bdir
#           @loggers = {}
#       end
#
#       def get_logger(name)
#           if !@loggers.has_key? name
#               # make the filename safe, then declare it to be so
#               fname = name.gsub(/[.\/\\\:]/, "_")
#               @loggers[name] = Logger.new(name, @basedir + "/" + fname)
#           end
#           return @loggers[name]
#       end
#
#   end
#
#   FRONT_OBJECT=LoggerFactory.new("/tmp/dlog")
#
#   DRb.start_service(URI, FRONT_OBJECT)
#   DRb.thread.join
#
# ==== Client code
#
#   require 'drb/drb'
#
#   SERVER_URI="druby://localhost:8787"
#
#   DRb.start_service
#
#   log_service=DRbObject.new_with_uri(SERVER_URI)
#
#   ["loga", "logb", "logc"].each do |logname|
#
#       logger=log_service.get_logger(logname)
#
#       logger.log("Hello, world!")
#       logger.log("Goodbye, world!")
#       logger.log("=== EOT ===")
#
#   end
#
# == Security
#
# As with all network services, security needs to be considered when
# using dRuby.  By allowing external access to a Ruby object, you are
# not only allowing outside clients to call the methods you have
# defined for that object, but by default to execute arbitrary Ruby
# code on your server.  Consider the following:
#
#    # !!! UNSAFE CODE !!!
#    ro = DRbObject::new_with_uri("druby://your.server.com:8989")
#    class << ro
#      undef :instance_eval  # force call to be passed to remote object
#    end
#    ro.instance_eval("`rm -rf *`")
#
# The dangers posed by instance_eval and friends are such that a
# DRbServer should only be used when clients are trusted.
#
# A DRbServer can be configured with an access control list to
# selectively allow or deny access from specified IP addresses.  The
# main druby distribution provides the ACL class for this purpose.  In
# general, this mechanism should only be used alongside, rather than
# as a replacement for, a good firewall.
#
# == dRuby internals
#
# dRuby is implemented using three main components: a remote method
# call marshaller/unmarshaller; a transport protocol; and an
# ID-to-object mapper.  The latter two can be directly, and the first
# indirectly, replaced, in order to provide different behaviour and
# capabilities.
#
# Marshalling and unmarshalling of remote method calls is performed by
# a DRb::DRbMessage instance.  This uses the Marshal module to dump
# the method call before sending it over the transport layer, then
# reconstitute it at the other end.  There is normally no need to
# replace this component, and no direct way is provided to do so.
# However, it is possible to implement an alternative marshalling
# scheme as part of an implementation of the transport layer.
#
# The transport layer is responsible for opening client and server
# network connections and forwarding dRuby request across them.
# Normally, it uses DRb::DRbMessage internally to manage marshalling
# and unmarshalling.  The transport layer is managed by
# DRb::DRbProtocol.  Multiple protocols can be installed in
# DRbProtocol at the one time; selection between them is determined by
# the scheme of a dRuby URI.  The default transport protocol is
# selected by the scheme 'druby:', and implemented by
# DRb::DRbTCPSocket.  This uses plain TCP/IP sockets for
# communication.  An alternative protocol, using UNIX domain sockets,
# is implemented by DRb::DRbUNIXSocket in the file drb/unix.rb, and
# selected by the scheme 'drbunix:'.  A sample implementation over
# HTTP can be found in the samples accompanying the main dRuby
# distribution.
#
# The ID-to-object mapping component maps dRuby object ids to the
# objects they refer to, and vice versa.  The implementation to use
# can be specified as part of a DRb::DRbServer's configuration.  The
# default implementation is provided by DRb::DRbIdConv.  It uses an
# object's ObjectSpace id as its dRuby id.  This means that the dRuby
# reference to that object only remains meaningful for the lifetime of
# the object's process and the lifetime of the object within that
# process.  A modified implementation is provided by DRb::TimerIdConv
# in the file drb/timeridconv.rb.  This implementation retains a local
# reference to all objects exported over dRuby for a configurable
# period of time (defaulting to ten minutes), to prevent them being
# garbage-collected within this time.  Another sample implementation
# is provided in sample/name.rb in the main dRuby distribution.  This
# allows objects to specify their own id or "name".  A dRuby reference
# can be made persistent across processes by having each process
# register an object using the same dRuby name.
#
module DRb

  # Superclass of all errors raised in the DRb module.
  class DRbError < RuntimeError; end

  # Error raised when an error occurs on the underlying communication
  # protocol.
  class DRbConnError < DRbError; end

  # Class responsible for converting between an object and its id.
  #
  # This, the default implementation, uses an object's local ObjectSpace
  # __id__ as its id.  This means that an object's identification over
  # drb remains valid only while that object instance remains alive
  # within the server runtime.
  #
  # For alternative mechanisms, see DRb::TimerIdConv in drb/timeridconv.rb
  # and DRbNameIdConv in sample/name.rb in the full drb distribution.
  class DRbIdConv

    # Convert an object reference id to an object.
    #
    # This implementation looks up the reference id in the local object
    # space and returns the object it refers to.
    def to_obj(ref)
      ObjectSpace._id2ref(ref)
    end

    # Convert an object into a reference id.
    #
    # This implementation returns the object's __id__ in the local
    # object space.
    def to_id(obj)
      case obj
      when Object
        obj.nil? ? nil : obj.__id__
      when BasicObject
        obj.__id__
      end
    end
  end

  # Mixin module making an object undumpable or unmarshallable.
  #
  # If an object which includes this module is returned by method
  # called over drb, then the object remains in the server space
  # and a reference to the object is returned, rather than the
  # object being marshalled and moved into the client space.
  module DRbUndumped
    def _dump(dummy)  # :nodoc:
      raise TypeError, 'can\'t dump'
    end
  end

  # Error raised by the DRb module when an attempt is made to refer to
  # the context's current drb server but the context does not have one.
  # See #current_server.
  class DRbServerNotFound < DRbError; end

  # Error raised by the DRbProtocol module when it cannot find any
  # protocol implementation support the scheme specified in a URI.
  class DRbBadURI < DRbError; end

  # Error raised by a dRuby protocol when it doesn't support the
  # scheme specified in a URI.  See DRb::DRbProtocol.
  class DRbBadScheme < DRbError; end

  # An exception wrapping a DRb::DRbUnknown object
  class DRbUnknownError < DRbError

    # Create a new DRbUnknownError for the DRb::DRbUnknown object +unknown+
    def initialize(unknown)
      @unknown = unknown
      super(unknown.name)
    end

    # Get the wrapped DRb::DRbUnknown object.
    attr_reader :unknown

    def self._load(s)  # :nodoc:
      Marshal::load(s)
    end

    def _dump(lv) # :nodoc:
      Marshal::dump(@unknown)
    end
  end

  # An exception wrapping an error object
  class DRbRemoteError < DRbError

    # Creates a new remote error that wraps the Exception +error+
    def initialize(error)
      @reason = error.class.to_s
      super("#{error.message} (#{error.class})")
      set_backtrace(error.backtrace)
    end

    # the class of the error, as a string.
    attr_reader :reason
  end

  # Class wrapping a marshalled object whose type is unknown locally.
  #
  # If an object is returned by a method invoked over drb, but the
  # class of the object is unknown in the client namespace, or
  # the object is a constant unknown in the client namespace, then
  # the still-marshalled object is returned wrapped in a DRbUnknown instance.
  #
  # If this object is passed as an argument to a method invoked over
  # drb, then the wrapped object is passed instead.
  #
  # The class or constant name of the object can be read from the
  # +name+ attribute.  The marshalled object is held in the +buf+
  # attribute.
  class DRbUnknown

    # Create a new DRbUnknown object.
    #
    # +buf+ is a string containing a marshalled object that could not
    # be unmarshalled.  +err+ is the error message that was raised
    # when the unmarshalling failed.  It is used to determine the
    # name of the unmarshalled object.
    def initialize(err, buf)
      case err.to_s
      when /uninitialized constant (\S+)/
        @name = $1
      when /undefined class\/module (\S+)/
        @name = $1
      else
        @name = nil
      end
      @buf = buf
    end

    # The name of the unknown thing.
    #
    # Class name for unknown objects; variable name for unknown
    # constants.
    attr_reader :name

    # Buffer contained the marshalled, unknown object.
    attr_reader :buf

    def self._load(s) # :nodoc:
      begin
        Marshal::load(s)
      rescue NameError, ArgumentError
        DRbUnknown.new($!, s)
      end
    end

    def _dump(lv) # :nodoc:
      @buf
    end

    # Attempt to load the wrapped marshalled object again.
    #
    # If the class of the object is now known locally, the object
    # will be unmarshalled and returned.  Otherwise, a new
    # but identical DRbUnknown object will be returned.
    def reload
      self.class._load(@buf)
    end

    # Create a DRbUnknownError exception containing this object.
    def exception
      DRbUnknownError.new(self)
    end
  end

  # An Array wrapper that can be sent to another server via DRb.
  #
  # All entries in the array will be dumped or be references that point to
  # the local server.

  class DRbArray

    # Creates a new DRbArray that either dumps or wraps all the items in the
    # Array +ary+ so they can be loaded by a remote DRb server.

    def initialize(ary)
      @ary = ary.collect { |obj|
        if obj.kind_of? DRbUndumped
          DRbObject.new(obj)
        else
          begin
            Marshal.dump(obj)
            obj
          rescue
            DRbObject.new(obj)
          end
        end
      }
    end

    def self._load(s) # :nodoc:
      Marshal::load(s)
    end

    def _dump(lv) # :nodoc:
      Marshal.dump(@ary)
    end
  end

  # Handler for sending and receiving drb messages.
  #
  # This takes care of the low-level marshalling and unmarshalling
  # of drb requests and responses sent over the wire between server
  # and client.  This relieves the implementor of a new drb
  # protocol layer with having to deal with these details.
  #
  # The user does not have to directly deal with this object in
  # normal use.
  class DRbMessage
    def initialize(config) # :nodoc:
      @load_limit = config[:load_limit]
      @argc_limit = config[:argc_limit]
    end

    def dump(obj, error=false)  # :nodoc:
      case obj
      when DRbUndumped
        obj = make_proxy(obj, error)
      when Object
        # nothing
      else
        obj = make_proxy(obj, error)
      end
      begin
        str = Marshal::dump(obj)
      rescue
        str = Marshal::dump(make_proxy(obj, error))
      end
      [str.size].pack('N') + str
    end

    def load(soc)  # :nodoc:
      begin
        sz = soc.read(4)        # sizeof (N)
      rescue
        raise(DRbConnError, $!.message, $!.backtrace)
      end
      raise(DRbConnError, 'connection closed') if sz.nil?
      raise(DRbConnError, 'premature header') if sz.size < 4
      sz = sz.unpack('N')[0]
      raise(DRbConnError, "too large packet #{sz}") if @load_limit < sz
      begin
        str = soc.read(sz)
      rescue
        raise(DRbConnError, $!.message, $!.backtrace)
      end
      raise(DRbConnError, 'connection closed') if str.nil?
      raise(DRbConnError, 'premature marshal format(can\'t read)') if str.size < sz
      DRb.mutex.synchronize do
        begin
          Marshal::load(str)
        rescue NameError, ArgumentError
          DRbUnknown.new($!, str)
        end
      end
    end

    def send_request(stream, ref, msg_id, arg, b) # :nodoc:
      ary = []
      ary.push(dump(ref.__drbref))
      ary.push(dump(msg_id.id2name))
      ary.push(dump(arg.length))
      arg.each do |e|
        ary.push(dump(e))
      end
      ary.push(dump(b))
      stream.write(ary.join(''))
    rescue
      raise(DRbConnError, $!.message, $!.backtrace)
    end

    def recv_request(stream) # :nodoc:
      ref = load(stream)
      ro = DRb.to_obj(ref)
      msg = load(stream)
      argc = load(stream)
      raise(DRbConnError, "too many arguments") if @argc_limit < argc
      argv = Array.new(argc, nil)
      argc.times do |n|
        argv[n] = load(stream)
      end
      block = load(stream)
      return ro, msg, argv, block
    end

    def send_reply(stream, succ, result)  # :nodoc:
      stream.write(dump(succ) + dump(result, !succ))
    rescue
      raise(DRbConnError, $!.message, $!.backtrace)
    end

    def recv_reply(stream)  # :nodoc:
      succ = load(stream)
      result = load(stream)
      [succ, result]
    end

    private
    def make_proxy(obj, error=false) # :nodoc:
      if error
        DRbRemoteError.new(obj)
      else
        DRbObject.new(obj)
      end
    end
  end

  # Module managing the underlying network protocol(s) used by drb.
  #
  # By default, drb uses the DRbTCPSocket protocol.  Other protocols
  # can be defined.  A protocol must define the following class methods:
  #
  #   [open(uri, config)] Open a client connection to the server at +uri+,
  #                       using configuration +config+.  Return a protocol
  #                       instance for this connection.
  #   [open_server(uri, config)] Open a server listening at +uri+,
  #                              using configuration +config+.  Return a
  #                              protocol instance for this listener.
  #   [uri_option(uri, config)] Take a URI, possibly containing an option
  #                             component (e.g. a trailing '?param=val'),
  #                             and return a [uri, option] tuple.
  #
  # All of these methods should raise a DRbBadScheme error if the URI
  # does not identify the protocol they support (e.g. "druby:" for
  # the standard Ruby protocol).  This is how the DRbProtocol module,
  # given a URI, determines which protocol implementation serves that
  # protocol.
  #
  # The protocol instance returned by #open_server must have the
  # following methods:
  #
  # [accept] Accept a new connection to the server.  Returns a protocol
  #          instance capable of communicating with the client.
  # [close] Close the server connection.
  # [uri] Get the URI for this server.
  #
  # The protocol instance returned by #open must have the following methods:
  #
  # [send_request (ref, msg_id, arg, b)]
  #      Send a request to +ref+ with the given message id and arguments.
  #      This is most easily implemented by calling DRbMessage.send_request,
  #      providing a stream that sits on top of the current protocol.
  # [recv_reply]
  #      Receive a reply from the server and return it as a [success-boolean,
  #      reply-value] pair.  This is most easily implemented by calling
  #      DRb.recv_reply, providing a stream that sits on top of the
  #      current protocol.
  # [alive?]
  #      Is this connection still alive?
  # [close]
  #      Close this connection.
  #
  # The protocol instance returned by #open_server().accept() must have
  # the following methods:
  #
  # [recv_request]
  #     Receive a request from the client and return a [object, message,
  #     args, block] tuple.  This is most easily implemented by calling
  #     DRbMessage.recv_request, providing a stream that sits on top of
  #     the current protocol.
  # [send_reply(succ, result)]
  #     Send a reply to the client.  This is most easily implemented
  #     by calling DRbMessage.send_reply, providing a stream that sits
  #     on top of the current protocol.
  # [close]
  #     Close this connection.
  #
  # A new protocol is registered with the DRbProtocol module using
  # the add_protocol method.
  #
  # For examples of other protocols, see DRbUNIXSocket in drb/unix.rb,
  # and HTTP0 in sample/http0.rb and sample/http0serv.rb in the full
  # drb distribution.
  module DRbProtocol

    # Add a new protocol to the DRbProtocol module.
    def add_protocol(prot)
      @protocol.push(prot)
    end
    module_function :add_protocol

    # Open a client connection to +uri+ with the configuration +config+.
    #
    # The DRbProtocol module asks each registered protocol in turn to
    # try to open the URI.  Each protocol signals that it does not handle that
    # URI by raising a DRbBadScheme error.  If no protocol recognises the
    # URI, then a DRbBadURI error is raised.  If a protocol accepts the
    # URI, but an error occurs in opening it, a DRbConnError is raised.
    def open(uri, config, first=true)
      @protocol.each do |prot|
        begin
          return prot.open(uri, config)
        rescue DRbBadScheme
        rescue DRbConnError
          raise($!)
        rescue
          raise(DRbConnError, "#{uri} - #{$!.inspect}")
        end
      end
      if first && (config[:auto_load] != false)
        auto_load(uri)
        return open(uri, config, false)
      end
      raise DRbBadURI, 'can\'t parse uri:' + uri
    end
    module_function :open

    # Open a server listening for connections at +uri+ with
    # configuration +config+.
    #
    # The DRbProtocol module asks each registered protocol in turn to
    # try to open a server at the URI.  Each protocol signals that it does
    # not handle that URI by raising a DRbBadScheme error.  If no protocol
    # recognises the URI, then a DRbBadURI error is raised.  If a protocol
    # accepts the URI, but an error occurs in opening it, the underlying
    # error is passed on to the caller.
    def open_server(uri, config, first=true)
      @protocol.each do |prot|
        begin
          return prot.open_server(uri, config)
        rescue DRbBadScheme
        end
      end
      if first && (config[:auto_load] != false)
        auto_load(uri)
        return open_server(uri, config, false)
      end
      raise DRbBadURI, 'can\'t parse uri:' + uri
    end
    module_function :open_server

    # Parse +uri+ into a [uri, option] pair.
    #
    # The DRbProtocol module asks each registered protocol in turn to
    # try to parse the URI.  Each protocol signals that it does not handle that
    # URI by raising a DRbBadScheme error.  If no protocol recognises the
    # URI, then a DRbBadURI error is raised.
    def uri_option(uri, config, first=true)
      @protocol.each do |prot|
        begin
          uri, opt = prot.uri_option(uri, config)
          # opt = nil if opt == ''
          return uri, opt
        rescue DRbBadScheme
        end
      end
      if first && (config[:auto_load] != false)
        auto_load(uri)
        return uri_option(uri, config, false)
      end
      raise DRbBadURI, 'can\'t parse uri:' + uri
    end
    module_function :uri_option

    def auto_load(uri)  # :nodoc:
      if /\Adrb([a-z0-9]+):/ =~ uri
        require("drb/#{$1}") rescue nil
      end
    end
    module_function :auto_load
  end

  # The default drb protocol which communicates over a TCP socket.
  #
  # The DRb TCP protocol URI looks like:
  # <code>druby://<host>:<port>?<option></code>.  The option is optional.

  class DRbTCPSocket
    # :stopdoc:
    private
    def self.parse_uri(uri)
      if /\Adruby:\/\/(.*?):(\d+)(\?(.*))?\z/ =~ uri
        host = $1
        port = $2.to_i
        option = $4
        [host, port, option]
      else
        raise(DRbBadScheme, uri) unless uri.start_with?('druby:')
        raise(DRbBadURI, 'can\'t parse uri:' + uri)
      end
    end

    public

    # Open a client connection to +uri+ (DRb URI string) using configuration
    # +config+.
    #
    # This can raise DRb::DRbBadScheme or DRb::DRbBadURI if +uri+ is not for a
    # recognized protocol.  See DRb::DRbServer.new for information on built-in
    # URI protocols.
    def self.open(uri, config)
      host, port, = parse_uri(uri)
      soc = TCPSocket.open(host, port)
      self.new(uri, soc, config)
    end

    # Returns the hostname of this server
    def self.getservername
      host = Socket::gethostname
      begin
        Socket::getaddrinfo(host, nil,
                                  Socket::AF_UNSPEC,
                                  Socket::SOCK_STREAM,
                                  0,
                                  Socket::AI_PASSIVE)[0][3]
      rescue
        'localhost'
      end
    end

    # For the families available for +host+, returns a TCPServer on +port+.
    # If +port+ is 0 the first available port is used.  IPv4 servers are
    # preferred over IPv6 servers.
    def self.open_server_inaddr_any(host, port)
      infos = Socket::getaddrinfo(host, nil,
                                  Socket::AF_UNSPEC,
                                  Socket::SOCK_STREAM,
                                  0,
                                  Socket::AI_PASSIVE)
      families = Hash[*infos.collect { |af, *_| af }.uniq.zip([]).flatten]
      return TCPServer.open('0.0.0.0', port) if families.has_key?('AF_INET')
      return TCPServer.open('::', port) if families.has_key?('AF_INET6')
      return TCPServer.open(port)
      # :stopdoc:
    end

    # Open a server listening for connections at +uri+ using
    # configuration +config+.
    def self.open_server(uri, config)
      uri = 'druby://:0' unless uri
      host, port, _ = parse_uri(uri)
      config = {:tcp_original_host => host}.update(config)
      if host.size == 0
        host = getservername
        soc = open_server_inaddr_any(host, port)
      else
        soc = TCPServer.open(host, port)
      end
      port = soc.addr[1] if port == 0
      config[:tcp_port] = port
      uri = "druby://#{host}:#{port}"
      self.new(uri, soc, config)
    end

    # Parse +uri+ into a [uri, option] pair.
    def self.uri_option(uri, config)
      host, port, option = parse_uri(uri)
      return "druby://#{host}:#{port}", option
    end

    # Create a new DRbTCPSocket instance.
    #
    # +uri+ is the URI we are connected to.
    # +soc+ is the tcp socket we are bound to.  +config+ is our
    # configuration.
    def initialize(uri, soc, config={})
      @uri = uri
      @socket = soc
      @config = config
      @acl = config[:tcp_acl]
      @msg = DRbMessage.new(config)
      set_sockopt(@socket)
      @shutdown_pipe_r, @shutdown_pipe_w = IO.pipe
    end

    # Get the URI that we are connected to.
    attr_reader :uri

    # Get the address of our TCP peer (the other end of the socket
    # we are bound to.
    def peeraddr
      @socket.peeraddr
    end

    # Get the socket.
    def stream; @socket; end

    # On the client side, send a request to the server.
    def send_request(ref, msg_id, arg, b)
      @msg.send_request(stream, ref, msg_id, arg, b)
    end

    # On the server side, receive a request from the client.
    def recv_request
      @msg.recv_request(stream)
    end

    # On the server side, send a reply to the client.
    def send_reply(succ, result)
      @msg.send_reply(stream, succ, result)
    end

    # On the client side, receive a reply from the server.
    def recv_reply
      @msg.recv_reply(stream)
    end

    public

    # Close the connection.
    #
    # If this is an instance returned by #open_server, then this stops
    # listening for new connections altogether.  If this is an instance
    # returned by #open or by #accept, then it closes this particular
    # client-server session.
    def close
      shutdown
      if @socket
        @socket.close
        @socket = nil
      end
      close_shutdown_pipe
    end

    def close_shutdown_pipe
      @shutdown_pipe_w.close
      @shutdown_pipe_r.close
    end
    private :close_shutdown_pipe

    # On the server side, for an instance returned by #open_server,
    # accept a client connection and return a new instance to handle
    # the server's side of this client-server session.
    def accept
      while true
        s = accept_or_shutdown
        return nil unless s
        break if (@acl ? @acl.allow_socket?(s) : true)
        s.close
      end
      if @config[:tcp_original_host].to_s.size == 0
        uri = "druby://#{s.addr[3]}:#{@config[:tcp_port]}"
      else
        uri = @uri
      end
      self.class.new(uri, s, @config)
    end

    def accept_or_shutdown
      readables, = IO.select([@socket, @shutdown_pipe_r])
      if readables.include? @shutdown_pipe_r
        return nil
      end
      @socket.accept
    end
    private :accept_or_shutdown

    # Graceful shutdown
    def shutdown
      @shutdown_pipe_w.close
    end

    # Check to see if this connection is alive.
    def alive?
      return false unless @socket
      if @socket.to_io.wait_readable(0)
        close
        return false
      end
      true
    end

    def set_sockopt(soc) # :nodoc:
      soc.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
    rescue IOError, Errno::ECONNRESET, Errno::EINVAL
      # closed/shutdown socket, ignore error
    end
  end

  module DRbProtocol
    @protocol = [DRbTCPSocket] # default
  end

  class DRbURIOption  # :nodoc:  I don't understand the purpose of this class...
    def initialize(option)
      @option = option.to_s
    end
    attr_reader :option
    def to_s; @option; end

    def ==(other)
      return false unless DRbURIOption === other
      @option == other.option
    end

    def hash
      @option.hash
    end

    alias eql? ==
  end

  # Object wrapping a reference to a remote drb object.
  #
  # Method calls on this object are relayed to the remote
  # object that this object is a stub for.
  class DRbObject

    # Unmarshall a marshalled DRbObject.
    #
    # If the referenced object is located within the local server, then
    # the object itself is returned.  Otherwise, a new DRbObject is
    # created to act as a stub for the remote referenced object.
    def self._load(s)
      uri, ref = Marshal.load(s)

      if DRb.here?(uri)
        obj = DRb.to_obj(ref)
        return obj
      end

      self.new_with(uri, ref)
    end

    # Creates a DRb::DRbObject given the reference information to the remote
    # host +uri+ and object +ref+.

    def self.new_with(uri, ref)
      it = self.allocate
      it.instance_variable_set(:@uri, uri)
      it.instance_variable_set(:@ref, ref)
      it
    end

    # Create a new DRbObject from a URI alone.
    def self.new_with_uri(uri)
      self.new(nil, uri)
    end

    # Marshall this object.
    #
    # The URI and ref of the object are marshalled.
    def _dump(lv)
      Marshal.dump([@uri, @ref])
    end

    # Create a new remote object stub.
    #
    # +obj+ is the (local) object we want to create a stub for.  Normally
    # this is +nil+.  +uri+ is the URI of the remote object that this
    # will be a stub for.
    def initialize(obj, uri=nil)
      @uri = nil
      @ref = nil
      case obj
      when Object
        is_nil = obj.nil?
      when BasicObject
        is_nil = false
      end

      if is_nil
        return if uri.nil?
        @uri, option = DRbProtocol.uri_option(uri, DRb.config)
        @ref = DRbURIOption.new(option) unless option.nil?
      else
        @uri = uri ? uri : (DRb.uri rescue nil)
        @ref = obj ? DRb.to_id(obj) : nil
      end
    end

    # Get the URI of the remote object.
    def __drburi
      @uri
    end

    # Get the reference of the object, if local.
    def __drbref
      @ref
    end

    undef :to_s
    undef :to_a if respond_to?(:to_a)

    # Routes respond_to? to the referenced remote object.
    def respond_to?(msg_id, priv=false)
      case msg_id
      when :_dump
        true
      when :marshal_dump
        false
      else
        method_missing(:respond_to?, msg_id, priv)
      end
    end

    # Routes method calls to the referenced remote object.
    ruby2_keywords def method_missing(msg_id, *a, &b)
      if DRb.here?(@uri)
        obj = DRb.to_obj(@ref)
        DRb.current_server.check_insecure_method(obj, msg_id)
        return obj.__send__(msg_id, *a, &b)
      end

      succ, result = self.class.with_friend(@uri) do
        DRbConn.open(@uri) do |conn|
          conn.send_message(self, msg_id, a, b)
        end
      end

      if succ
        return result
      elsif DRbUnknown === result
        raise result
      else
        bt = self.class.prepare_backtrace(@uri, result)
        result.set_backtrace(bt + caller)
        raise result
      end
    end

    # Given the +uri+ of another host executes the block provided.
    def self.with_friend(uri) # :nodoc:
      friend = DRb.fetch_server(uri)
      return yield() unless friend

      save = Thread.current['DRb']
      Thread.current['DRb'] = { 'server' => friend }
      return yield
    ensure
      Thread.current['DRb'] = save if friend
    end

    # Returns a modified backtrace from +result+ with the +uri+ where each call
    # in the backtrace came from.
    def self.prepare_backtrace(uri, result) # :nodoc:
      prefix = "(#{uri}) "
      bt = []
      result.backtrace.each do |x|
        break if /`__send__'$/ =~ x
        if /\A\(druby:\/\// =~ x
          bt.push(x)
        else
          bt.push(prefix + x)
        end
      end
      bt
    end

    def pretty_print(q)   # :nodoc:
      q.pp_object(self)
    end

    def pretty_print_cycle(q)   # :nodoc:
      q.object_address_group(self) {
        q.breakable
        q.text '...'
      }
    end
  end

  class ThreadObject
    include MonitorMixin

    def initialize(&blk)
      super()
      @wait_ev = new_cond
      @req_ev = new_cond
      @res_ev = new_cond
      @status = :wait
      @req = nil
      @res = nil
      @thread = Thread.new(self, &blk)
    end

    def alive?
      @thread.alive?
    end

    def kill
      @thread.kill
      @thread.join
    end

    def method_missing(msg, *arg, &blk)
      synchronize do
        @wait_ev.wait_until { @status == :wait }
        @req = [msg] + arg
        @status = :req
        @req_ev.broadcast
        @res_ev.wait_until { @status == :res }
        value = @res
        @req = @res = nil
        @status = :wait
        @wait_ev.broadcast
        return value
      end
    end

    def _execute()
      synchronize do
        @req_ev.wait_until { @status == :req }
        @res = yield(@req)
        @status = :res
        @res_ev.signal
      end
    end
  end

  # Class handling the connection between a DRbObject and the
  # server the real object lives on.
  #
  # This class maintains a pool of connections, to reduce the
  # overhead of starting and closing down connections for each
  # method call.
  #
  # This class is used internally by DRbObject.  The user does
  # not normally need to deal with it directly.
  class DRbConn
    POOL_SIZE = 16  # :nodoc:

    def self.make_pool
      ThreadObject.new do |queue|
        pool = []
        while true
          queue._execute do |message|
            case(message[0])
            when :take then
              remote_uri = message[1]
              conn = nil
              new_pool = []
              pool.each do |c|
                if conn.nil? and c.uri == remote_uri
                  conn = c if c.alive?
                else
                  new_pool.push c
                end
              end
              pool = new_pool
              conn
            when :store then
              conn = message[1]
              pool.unshift(conn)
              pool.pop.close while pool.size > POOL_SIZE
              conn
            else
              nil
            end
          end
        end
      end
    end
    @pool_proxy = nil

    def self.stop_pool
      @pool_proxy&.kill
      @pool_proxy = nil
    end

    def self.open(remote_uri)  # :nodoc:
      begin
        @pool_proxy = make_pool unless @pool_proxy&.alive?

        conn = @pool_proxy.take(remote_uri)
        conn = self.new(remote_uri) unless conn
        succ, result = yield(conn)
        return succ, result

      ensure
        if conn
          if succ
            @pool_proxy.store(conn)
          else
            conn.close
          end
        end
      end
    end

    def initialize(remote_uri)  # :nodoc:
      @uri = remote_uri
      @protocol = DRbProtocol.open(remote_uri, DRb.config)
    end
    attr_reader :uri  # :nodoc:

    def send_message(ref, msg_id, arg, block)  # :nodoc:
      @protocol.send_request(ref, msg_id, arg, block)
      @protocol.recv_reply
    end

    def close  # :nodoc:
      @protocol.close
      @protocol = nil
    end

    def alive?  # :nodoc:
      return false unless @protocol
      @protocol.alive?
    end
  end

  # Class representing a drb server instance.
  #
  # A DRbServer must be running in the local process before any incoming
  # dRuby calls can be accepted, or any local objects can be passed as
  # dRuby references to remote processes, even if those local objects are
  # never actually called remotely. You do not need to start a DRbServer
  # in the local process if you are only making outgoing dRuby calls
  # passing marshalled parameters.
  #
  # Unless multiple servers are being used, the local DRbServer is normally
  # started by calling DRb.start_service.
  class DRbServer
    @@acl = nil
    @@idconv = DRbIdConv.new
    @@secondary_server = nil
    @@argc_limit = 256
    @@load_limit = 0xffffffff
    @@verbose = false

    # Set the default value for the :argc_limit option.
    #
    # See #new().  The initial default value is 256.
    def self.default_argc_limit(argc)
      @@argc_limit = argc
    end

    # Set the default value for the :load_limit option.
    #
    # See #new().  The initial default value is 25 MB.
    def self.default_load_limit(sz)
      @@load_limit = sz
    end

    # Set the default access control list to +acl+.  The default ACL is +nil+.
    #
    # See also DRb::ACL and #new()
    def self.default_acl(acl)
      @@acl = acl
    end

    # Set the default value for the :id_conv option.
    #
    # See #new().  The initial default value is a DRbIdConv instance.
    def self.default_id_conv(idconv)
      @@idconv = idconv
    end

    # Set the default value of the :verbose option.
    #
    # See #new().  The initial default value is false.
    def self.verbose=(on)
      @@verbose = on
    end

    # Get the default value of the :verbose option.
    def self.verbose
      @@verbose
    end

    def self.make_config(hash={})  # :nodoc:
      default_config = {
        :idconv => @@idconv,
        :verbose => @@verbose,
        :tcp_acl => @@acl,
        :load_limit => @@load_limit,
        :argc_limit => @@argc_limit,
      }
      default_config.update(hash)
    end

    # Create a new DRbServer instance.
    #
    # +uri+ is the URI to bind to.  This is normally of the form
    # 'druby://<hostname>:<port>' where <hostname> is a hostname of
    # the local machine.  If nil, then the system's default hostname
    # will be bound to, on a port selected by the system; these value
    # can be retrieved from the +uri+ attribute.  'druby:' specifies
    # the default dRuby transport protocol: another protocol, such
    # as 'drbunix:', can be specified instead.
    #
    # +front+ is the front object for the server, that is, the object
    # to which remote method calls on the server will be passed.  If
    # nil, then the server will not accept remote method calls.
    #
    # If +config_or_acl+ is a hash, it is the configuration to
    # use for this server.  The following options are recognised:
    #
    # :idconv :: an id-to-object conversion object.  This defaults
    #            to an instance of the class DRb::DRbIdConv.
    # :verbose :: if true, all unsuccessful remote calls on objects
    #             in the server will be logged to $stdout. false
    #             by default.
    # :tcp_acl :: the access control list for this server.  See
    #             the ACL class from the main dRuby distribution.
    # :load_limit :: the maximum message size in bytes accepted by
    #                the server.  Defaults to 25 MB (26214400).
    # :argc_limit :: the maximum number of arguments to a remote
    #                method accepted by the server.  Defaults to
    #                256.
    # The default values of these options can be modified on
    # a class-wide basis by the class methods #default_argc_limit,
    # #default_load_limit, #default_acl, #default_id_conv,
    # and #verbose=
    #
    # If +config_or_acl+ is not a hash, but is not nil, it is
    # assumed to be the access control list for this server.
    # See the :tcp_acl option for more details.
    #
    # If no other server is currently set as the primary server,
    # this will become the primary server.
    #
    # The server will immediately start running in its own thread.
    def initialize(uri=nil, front=nil, config_or_acl=nil)
      if Hash === config_or_acl
        config = config_or_acl.dup
      else
        acl = config_or_acl || @@acl
        config = {
          :tcp_acl => acl
        }
      end

      @config = self.class.make_config(config)

      @protocol = DRbProtocol.open_server(uri, @config)
      @uri = @protocol.uri
      @exported_uri = [@uri]

      @front = front
      @idconv = @config[:idconv]

      @grp = ThreadGroup.new
      @thread = run

      DRb.regist_server(self)
    end

    # The URI of this DRbServer.
    attr_reader :uri

    # The main thread of this DRbServer.
    #
    # This is the thread that listens for and accepts connections
    # from clients, not that handles each client's request-response
    # session.
    attr_reader :thread

    # The front object of the DRbServer.
    #
    # This object receives remote method calls made on the server's
    # URI alone, with an object id.
    attr_reader :front

    # The configuration of this DRbServer
    attr_reader :config

    # Set whether to operate in verbose mode.
    #
    # In verbose mode, failed calls are logged to stdout.
    def verbose=(v); @config[:verbose]=v; end

    # Get whether the server is in verbose mode.
    #
    # In verbose mode, failed calls are logged to stdout.
    def verbose; @config[:verbose]; end

    # Is this server alive?
    def alive?
      @thread.alive?
    end

    # Is +uri+ the URI for this server?
    def here?(uri)
      @exported_uri.include?(uri)
    end

    # Stop this server.
    def stop_service
      DRb.remove_server(self)
      if  Thread.current['DRb'] && Thread.current['DRb']['server'] == self
        Thread.current['DRb']['stop_service'] = true
      else
        shutdown
      end
    end

    # Convert a dRuby reference to the local object it refers to.
    def to_obj(ref)
      return front if ref.nil?
      return front[ref.to_s] if DRbURIOption === ref
      @idconv.to_obj(ref)
    end

    # Convert a local object to a dRuby reference.
    def to_id(obj)
      return nil if obj.__id__ == front.__id__
      @idconv.to_id(obj)
    end

    private

    def shutdown
      current = Thread.current
      if @protocol.respond_to? :shutdown
        @protocol.shutdown
      else
        [@thread, *@grp.list].each { |thread|
          thread.kill unless thread == current # xxx: Thread#kill
        }
      end
      @thread.join unless @thread == current
    end

    ##
    # Starts the DRb main loop in a new thread.

    def run
      Thread.start do
        begin
          while main_loop
          end
        ensure
          @protocol.close if @protocol
        end
      end
    end

    # List of insecure methods.
    #
    # These methods are not callable via dRuby.
    INSECURE_METHOD = [
      :__send__
    ]

    # Has a method been included in the list of insecure methods?
    def insecure_method?(msg_id)
      INSECURE_METHOD.include?(msg_id)
    end

    # Coerce an object to a string, providing our own representation if
    # to_s is not defined for the object.
    def any_to_s(obj)
      "#{obj}:#{obj.class}"
    rescue
      Kernel.instance_method(:to_s).bind_call(obj)
    end

    # Check that a method is callable via dRuby.
    #
    # +obj+ is the object we want to invoke the method on. +msg_id+ is the
    # method name, as a Symbol.
    #
    # If the method is an insecure method (see #insecure_method?) a
    # SecurityError is thrown.  If the method is private or undefined,
    # a NameError is thrown.
    def check_insecure_method(obj, msg_id)
      return true if Proc === obj && msg_id == :__drb_yield
      raise(ArgumentError, "#{any_to_s(msg_id)} is not a symbol") unless Symbol == msg_id.class
      raise(SecurityError, "insecure method `#{msg_id}'") if insecure_method?(msg_id)

      case obj
      when Object
        if obj.private_methods.include?(msg_id)
          desc = any_to_s(obj)
          raise NoMethodError, "private method `#{msg_id}' called for #{desc}"
        elsif obj.protected_methods.include?(msg_id)
          desc = any_to_s(obj)
          raise NoMethodError, "protected method `#{msg_id}' called for #{desc}"
        else
          true
        end
      else
        if Kernel.instance_method(:private_methods).bind(obj).call.include?(msg_id)
          desc = any_to_s(obj)
          raise NoMethodError, "private method `#{msg_id}' called for #{desc}"
        elsif Kernel.instance_method(:protected_methods).bind(obj).call.include?(msg_id)
          desc = any_to_s(obj)
          raise NoMethodError, "protected method `#{msg_id}' called for #{desc}"
        else
          true
        end
      end
    end
    public :check_insecure_method

    class InvokeMethod  # :nodoc:
      def initialize(drb_server, client)
        @drb_server = drb_server
        @client = client
      end

      def perform
        @result = nil
        @succ = false
        setup_message

        if @block
          @result = perform_with_block
        else
          @result = perform_without_block
        end
        @succ = true
        case @result
        when Array
          if @msg_id == :to_ary
            @result = DRbArray.new(@result)
          end
        end
        return @succ, @result
      rescue NoMemoryError, SystemExit, SystemStackError, SecurityError
        raise
      rescue Exception
        @result = $!
        return @succ, @result
      end

      private
      def init_with_client
        obj, msg, argv, block = @client.recv_request
        @obj = obj
        @msg_id = msg.intern
        @argv = argv
        @block = block
      end

      def check_insecure_method
        @drb_server.check_insecure_method(@obj, @msg_id)
      end

      def setup_message
        init_with_client
        check_insecure_method
      end

      def perform_without_block
        if Proc === @obj && @msg_id == :__drb_yield
          if @argv.size == 1
            ary = @argv
          else
            ary = [@argv]
          end
          ary.collect(&@obj)[0]
        else
          @obj.__send__(@msg_id, *@argv)
        end
      end

    end

    require_relative 'invokemethod'
    class InvokeMethod
      include InvokeMethod18Mixin
    end

    def error_print(exception)
      exception.backtrace.inject(true) do |first, x|
        if first
          $stderr.puts "#{x}: #{exception} (#{exception.class})"
        else
          $stderr.puts "\tfrom #{x}"
        end
        false
      end
    end

    # The main loop performed by a DRbServer's internal thread.
    #
    # Accepts a connection from a client, and starts up its own
    # thread to handle it.  This thread loops, receiving requests
    # from the client, invoking them on a local object, and
    # returning responses, until the client closes the connection
    # or a local method call fails.
    def main_loop
      client0 = @protocol.accept
      return nil if !client0
      Thread.start(client0) do |client|
        @grp.add Thread.current
        Thread.current['DRb'] = { 'client' => client ,
                                  'server' => self }
        DRb.mutex.synchronize do
          client_uri = client.uri
          @exported_uri << client_uri unless @exported_uri.include?(client_uri)
        end
        loop do
          begin
            succ = false
            invoke_method = InvokeMethod.new(self, client)
            succ, result = invoke_method.perform
            error_print(result) if !succ && verbose
            unless DRbConnError === result && result.message == 'connection closed'
              client.send_reply(succ, result)
            end
          rescue Exception => e
            error_print(e) if verbose
          ensure
            client.close unless succ
            if Thread.current['DRb']['stop_service']
              shutdown
              break
            end
            break unless succ
          end
        end
      end
    end
  end

  @primary_server = nil

  # Start a dRuby server locally.
  #
  # The new dRuby server will become the primary server, even
  # if another server is currently the primary server.
  #
  # +uri+ is the URI for the server to bind to.  If nil,
  # the server will bind to random port on the default local host
  # name and use the default dRuby protocol.
  #
  # +front+ is the server's front object.  This may be nil.
  #
  # +config+ is the configuration for the new server.  This may
  # be nil.
  #
  # See DRbServer::new.
  def start_service(uri=nil, front=nil, config=nil)
    @primary_server = DRbServer.new(uri, front, config)
  end
  module_function :start_service

  # The primary local dRuby server.
  #
  # This is the server created by the #start_service call.
  attr_accessor :primary_server
  module_function :primary_server=, :primary_server

  # Get the 'current' server.
  #
  # In the context of execution taking place within the main
  # thread of a dRuby server (typically, as a result of a remote
  # call on the server or one of its objects), the current
  # server is that server.  Otherwise, the current server is
  # the primary server.
  #
  # If the above rule fails to find a server, a DRbServerNotFound
  # error is raised.
  def current_server
    drb = Thread.current['DRb']
    server = (drb && drb['server']) ? drb['server'] : @primary_server
    raise DRbServerNotFound unless server
    return server
  end
  module_function :current_server

  # Stop the local dRuby server.
  #
  # This operates on the primary server.  If there is no primary
  # server currently running, it is a noop.
  def stop_service
    @primary_server.stop_service if @primary_server
    @primary_server = nil
  end
  module_function :stop_service

  # Get the URI defining the local dRuby space.
  #
  # This is the URI of the current server.  See #current_server.
  def uri
    drb = Thread.current['DRb']
    client = (drb && drb['client'])
    if client
      uri = client.uri
      return uri if uri
    end
    current_server.uri
  end
  module_function :uri

  # Is +uri+ the URI for the current local server?
  def here?(uri)
    current_server.here?(uri) rescue false
    # (current_server.uri rescue nil) == uri
  end
  module_function :here?

  # Get the configuration of the current server.
  #
  # If there is no current server, this returns the default configuration.
  # See #current_server and DRbServer::make_config.
  def config
    current_server.config
  rescue
    DRbServer.make_config
  end
  module_function :config

  # Get the front object of the current server.
  #
  # This raises a DRbServerNotFound error if there is no current server.
  # See #current_server.
  def front
    current_server.front
  end
  module_function :front

  # Convert a reference into an object using the current server.
  #
  # This raises a DRbServerNotFound error if there is no current server.
  # See #current_server.
  def to_obj(ref)
    current_server.to_obj(ref)
  end

  # Get a reference id for an object using the current server.
  #
  # This raises a DRbServerNotFound error if there is no current server.
  # See #current_server.
  def to_id(obj)
    current_server.to_id(obj)
  end
  module_function :to_id
  module_function :to_obj

  # Get the thread of the primary server.
  #
  # This returns nil if there is no primary server.  See #primary_server.
  def thread
    @primary_server ? @primary_server.thread : nil
  end
  module_function :thread

  # Set the default id conversion object.
  #
  # This is expected to be an instance such as DRb::DRbIdConv that responds to
  # #to_id and #to_obj that can convert objects to and from DRb references.
  #
  # See DRbServer#default_id_conv.
  def install_id_conv(idconv)
    DRbServer.default_id_conv(idconv)
  end
  module_function :install_id_conv

  # Set the default ACL to +acl+.
  #
  # See DRb::DRbServer.default_acl.
  def install_acl(acl)
    DRbServer.default_acl(acl)
  end
  module_function :install_acl

  @mutex = Thread::Mutex.new
  def mutex # :nodoc:
    @mutex
  end
  module_function :mutex

  @server = {}
  # Registers +server+ with DRb.
  #
  # This is called when a new DRb::DRbServer is created.
  #
  # If there is no primary server then +server+ becomes the primary server.
  #
  # Example:
  #
  #  require 'drb'
  #
  #  s = DRb::DRbServer.new # automatically calls regist_server
  #  DRb.fetch_server s.uri #=> #<DRb::DRbServer:0x...>
  def regist_server(server)
    @server[server.uri] = server
    mutex.synchronize do
      @primary_server = server unless @primary_server
    end
  end
  module_function :regist_server

  # Removes +server+ from the list of registered servers.
  def remove_server(server)
    @server.delete(server.uri)
    mutex.synchronize do
      if @primary_server == server
        @primary_server = nil
      end
    end
  end
  module_function :remove_server

  # Retrieves the server with the given +uri+.
  #
  # See also regist_server and remove_server.
  def fetch_server(uri)
    @server[uri]
  end
  module_function :fetch_server
end

# :stopdoc:
DRbObject = DRb::DRbObject
DRbUndumped = DRb::DRbUndumped
DRbIdConv = DRb::DRbIdConv
# frozen_string_literal: false
=begin
 external service
        Copyright (c) 2000,2002 Masatoshi SEKI
=end

require_relative 'drb'
require 'monitor'

module DRb
  class ExtServ
    include MonitorMixin
    include DRbUndumped

    def initialize(there, name, server=nil)
      super()
      @server = server || DRb::primary_server
      @name = name
      ro = DRbObject.new(nil, there)
      synchronize do
        @invoker = ro.regist(name, DRbObject.new(self, @server.uri))
      end
    end
    attr_reader :server

    def front
      DRbObject.new(nil, @server.uri)
    end

    def stop_service
      synchronize do
        @invoker.unregist(@name)
        server = @server
        @server = nil
        server.stop_service
        true
      end
    end

    def alive?
      @server ? @server.alive? : false
    end
  end
end
# frozen_string_literal: false
require 'socket'
require_relative 'drb'
require 'tmpdir'

raise(LoadError, "UNIXServer is required") unless defined?(UNIXServer)

module DRb

  # Implements DRb over a UNIX socket
  #
  # DRb UNIX socket URIs look like <code>drbunix:<path>?<option></code>.  The
  # option is optional.

  class DRbUNIXSocket < DRbTCPSocket
    # :stopdoc:
    def self.parse_uri(uri)
      if /\Adrbunix:(.*?)(\?(.*))?\z/ =~ uri
        filename = $1
        option = $3
        [filename, option]
      else
        raise(DRbBadScheme, uri) unless uri.start_with?('drbunix:')
        raise(DRbBadURI, 'can\'t parse uri:' + uri)
      end
    end

    def self.open(uri, config)
      filename, = parse_uri(uri)
      soc = UNIXSocket.open(filename)
      self.new(uri, soc, config)
    end

    def self.open_server(uri, config)
      filename, = parse_uri(uri)
      if filename.size == 0
        soc = temp_server
        filename = soc.path
        uri = 'drbunix:' + soc.path
      else
        soc = UNIXServer.open(filename)
      end
      owner = config[:UNIXFileOwner]
      group = config[:UNIXFileGroup]
      if owner || group
        require 'etc'
        owner = Etc.getpwnam( owner ).uid  if owner
        group = Etc.getgrnam( group ).gid  if group
        File.chown owner, group, filename
      end
      mode = config[:UNIXFileMode]
      File.chmod(mode, filename) if mode

      self.new(uri, soc, config, true)
    end

    def self.uri_option(uri, config)
      filename, option = parse_uri(uri)
      return "drbunix:#{filename}", option
    end

    def initialize(uri, soc, config={}, server_mode = false)
      super(uri, soc, config)
      set_sockopt(@socket)
      @server_mode = server_mode
      @acl = nil
    end

    # import from tempfile.rb
    Max_try = 10
    private
    def self.temp_server
      tmpdir = Dir::tmpdir
      n = 0
      while true
        begin
          tmpname = sprintf('%s/druby%d.%d', tmpdir, $$, n)
          lock = tmpname + '.lock'
          unless File.exist?(tmpname) or File.exist?(lock)
            Dir.mkdir(lock)
            break
          end
        rescue
          raise "cannot generate tempfile `%s'" % tmpname if n >= Max_try
          #sleep(1)
        end
        n += 1
      end
      soc = UNIXServer.new(tmpname)
      Dir.rmdir(lock)
      soc
    end

    public
    def close
      return unless @socket
      shutdown # DRbProtocol#shutdown
      path = @socket.path if @server_mode
      @socket.close
      File.unlink(path) if @server_mode
      @socket = nil
      close_shutdown_pipe
    end

    def accept
      s = accept_or_shutdown
      return nil unless s
      self.class.new(nil, s, @config)
    end

    def set_sockopt(soc)
      # no-op for now
    end
  end

  DRbProtocol.add_protocol(DRbUNIXSocket)
  # :startdoc:
end
# frozen_string_literal: false
require_relative 'drb'
require 'monitor'

module DRb

  # Timer id conversion keeps objects alive for a certain amount of time after
  # their last access.  The default time period is 600 seconds and can be
  # changed upon initialization.
  #
  # To use TimerIdConv:
  #
  #  DRb.install_id_conv TimerIdConv.new 60 # one minute

  class TimerIdConv < DRbIdConv
    class TimerHolder2 # :nodoc:
      include MonitorMixin

      class InvalidIndexError < RuntimeError; end

      def initialize(keeping=600)
        super()
        @sentinel = Object.new
        @gc = {}
        @renew = {}
        @keeping = keeping
        @expires = nil
      end

      def add(obj)
        synchronize do
          rotate
          key = obj.__id__
          @renew[key] = obj
          invoke_keeper
          return key
        end
      end

      def fetch(key)
        synchronize do
          rotate
          obj = peek(key)
          raise InvalidIndexError if obj == @sentinel
          @renew[key] = obj # KeepIt
          return obj
        end
      end

      private
      def peek(key)
        return @renew.fetch(key) { @gc.fetch(key, @sentinel) }
      end

      def invoke_keeper
        return if @expires
        @expires = Time.now + @keeping
        on_gc
      end

      def on_gc
        return unless Thread.main.alive?
        return if @expires.nil?
        Thread.new { rotate } if @expires < Time.now
        ObjectSpace.define_finalizer(Object.new) {on_gc}
      end

      def rotate
        synchronize do
          if @expires &.< Time.now
            @gc = @renew      # GCed
            @renew = {}
            @expires = @gc.empty? ? nil : Time.now + @keeping
          end
        end
      end
    end

    # Creates a new TimerIdConv which will hold objects for +keeping+ seconds.
    def initialize(keeping=600)
      @holder = TimerHolder2.new(keeping)
    end

    def to_obj(ref) # :nodoc:
      return super if ref.nil?
      @holder.fetch(ref)
    rescue TimerHolder2::InvalidIndexError
      raise "invalid reference"
    end

    def to_id(obj) # :nodoc:
      return @holder.add(obj)
    end
  end
end

# DRb.install_id_conv(TimerIdConv.new)
# frozen_string_literal: false
require_relative 'drb'
require 'monitor'

module DRb

  # To use WeakIdConv:
  #
  #  DRb.start_service(nil, nil, {:idconv => DRb::WeakIdConv.new})

  class WeakIdConv < DRbIdConv
    class WeakSet
      include MonitorMixin
      def initialize
        super()
        @immutable = {}
        @map = ObjectSpace::WeakMap.new
      end

      def add(obj)
        synchronize do
          begin
            @map[obj] = self
          rescue ArgumentError
            @immutable[obj.__id__] = obj
          end
          return obj.__id__
        end
      end

      def fetch(ref)
        synchronize do
          @immutable.fetch(ref) {
            @map.each { |key, _|
              return key if key.__id__ == ref
            }
            raise RangeError.new("invalid reference")
          }
        end
      end
    end

    def initialize()
      super()
      @weak_set = WeakSet.new
    end

    def to_obj(ref) # :nodoc:
      return super if ref.nil?
      @weak_set.fetch(ref)
    end

    def to_id(obj) # :nodoc:
      return @weak_set.add(obj)
    end
  end
end

# DRb.install_id_conv(WeakIdConv.new)
# frozen_string_literal: false
require_relative 'drb'
require 'monitor'

module DRb

  # Gateway id conversion forms a gateway between different DRb protocols or
  # networks.
  #
  # The gateway needs to install this id conversion and create servers for
  # each of the protocols or networks it will be a gateway between.  It then
  # needs to create a server that attaches to each of these networks.  For
  # example:
  #
  #   require 'drb/drb'
  #   require 'drb/unix'
  #   require 'drb/gw'
  #
  #   DRb.install_id_conv DRb::GWIdConv.new
  #   gw = DRb::GW.new
  #   s1 = DRb::DRbServer.new 'drbunix:/path/to/gateway', gw
  #   s2 = DRb::DRbServer.new 'druby://example:10000', gw
  #
  #   s1.thread.join
  #   s2.thread.join
  #
  # Each client must register services with the gateway, for example:
  #
  #   DRb.start_service 'drbunix:', nil # an anonymous server
  #   gw = DRbObject.new nil, 'drbunix:/path/to/gateway'
  #   gw[:unix] = some_service
  #   DRb.thread.join

  class GWIdConv < DRbIdConv
    def to_obj(ref) # :nodoc:
      if Array === ref && ref[0] == :DRbObject
        return DRbObject.new_with(ref[1], ref[2])
      end
      super(ref)
    end
  end

  # The GW provides a synchronized store for participants in the gateway to
  # communicate.

  class GW
    include MonitorMixin

    # Creates a new GW

    def initialize
      super()
      @hash = {}
    end

    # Retrieves +key+ from the GW

    def [](key)
      synchronize do
        @hash[key]
      end
    end

    # Stores value +v+ at +key+ in the GW

    def []=(key, v)
      synchronize do
        @hash[key] = v
      end
    end
  end

  class DRbObject # :nodoc:
    def self._load(s)
      uri, ref = Marshal.load(s)
      if DRb.uri == uri
        return ref ? DRb.to_obj(ref) : DRb.front
      end

      self.new_with(DRb.uri, [:DRbObject, uri, ref])
    end

    def _dump(lv)
      if DRb.uri == @uri
        if Array === @ref && @ref[0] == :DRbObject
          Marshal.dump([@ref[1], @ref[2]])
        else
          Marshal.dump([@uri, @ref]) # ??
        end
      else
        Marshal.dump([DRb.uri, [:DRbObject, @uri, @ref]])
      end
    end
  end
end

=begin
DRb.install_id_conv(DRb::GWIdConv.new)

front = DRb::GW.new

s1 = DRb::DRbServer.new('drbunix:/tmp/gw_b_a', front)
s2 = DRb::DRbServer.new('drbunix:/tmp/gw_b_c', front)

s1.thread.join
s2.thread.join
=end

=begin
# foo.rb

require 'drb/drb'

class Foo
  include DRbUndumped
  def initialize(name, peer=nil)
    @name = name
    @peer = peer
  end

  def ping(obj)
    puts "#{@name}: ping: #{obj.inspect}"
    @peer.ping(self) if @peer
  end
end
=end

=begin
# gw_a.rb
require 'drb/unix'
require 'foo'

obj = Foo.new('a')
DRb.start_service("drbunix:/tmp/gw_a", obj)

robj = DRbObject.new_with_uri('drbunix:/tmp/gw_b_a')
robj[:a] = obj

DRb.thread.join
=end

=begin
# gw_c.rb
require 'drb/unix'
require 'foo'

foo = Foo.new('c', nil)

DRb.start_service("drbunix:/tmp/gw_c", nil)

robj = DRbObject.new_with_uri("drbunix:/tmp/gw_b_c")

puts "c->b"
a = robj[:a]
sleep 2

a.ping(foo)

DRb.thread.join
=end

# frozen_string_literal: false
# Copyright (c) 2000,2002,2003 Masatoshi SEKI
#
# acl.rb is copyrighted free software by Masatoshi SEKI.
# You can redistribute it and/or modify it under the same terms as Ruby.

require 'ipaddr'

##
# Simple Access Control Lists.
#
# Access control lists are composed of "allow" and "deny" halves to control
# access.  Use "all" or "*" to match any address.  To match a specific address
# use any address or address mask that IPAddr can understand.
#
# Example:
#
#   list = %w[
#     deny all
#     allow 192.168.1.1
#     allow ::ffff:192.168.1.2
#     allow 192.168.1.3
#   ]
#
#   # From Socket#peeraddr, see also ACL#allow_socket?
#   addr = ["AF_INET", 10, "lc630", "192.168.1.3"]
#
#   acl = ACL.new
#   p acl.allow_addr?(addr) # => true
#
#   acl = ACL.new(list, ACL::DENY_ALLOW)
#   p acl.allow_addr?(addr) # => true

class ACL

  ##
  # The current version of ACL

  VERSION=["2.0.0"]

  ##
  # An entry in an ACL

  class ACLEntry

    ##
    # Creates a new entry using +str+.
    #
    # +str+ may be "*" or "all" to match any address, an IP address string
    # to match a specific address, an IP address mask per IPAddr, or one
    # containing "*" to match part of an IPv4 address.
    #
    # IPAddr::InvalidPrefixError may be raised when an IP network
    # address with an invalid netmask/prefix is given.

    def initialize(str)
      if str == '*' or str == 'all'
        @pat = [:all]
      elsif str.include?('*')
        @pat = [:name, dot_pat(str)]
      else
        begin
          @pat = [:ip, IPAddr.new(str)]
        rescue IPAddr::InvalidPrefixError
          # In this case, `str` shouldn't be a host name pattern
          # because it contains a slash.
          raise
        rescue ArgumentError
          @pat = [:name, dot_pat(str)]
        end
      end
    end

    private

    ##
    # Creates a regular expression to match IPv4 addresses

    def dot_pat_str(str)
      list = str.split('.').collect { |s|
        (s == '*') ? '.+' : s
      }
      list.join("\\.")
    end

    private

    ##
    # Creates a Regexp to match an address.

    def dot_pat(str)
      /\A#{dot_pat_str(str)}\z/
    end

    public

    ##
    # Matches +addr+ against this entry.

    def match(addr)
      case @pat[0]
      when :all
        true
      when :ip
        begin
          ipaddr = IPAddr.new(addr[3])
          ipaddr = ipaddr.ipv4_mapped if @pat[1].ipv6? && ipaddr.ipv4?
        rescue ArgumentError
          return false
        end
        (@pat[1].include?(ipaddr)) ? true : false
      when :name
        (@pat[1] =~ addr[2]) ? true : false
      else
        false
      end
    end
  end

  ##
  # A list of ACLEntry objects.  Used to implement the allow and deny halves
  # of an ACL

  class ACLList

    ##
    # Creates an empty ACLList

    def initialize
      @list = []
    end

    public

    ##
    # Matches +addr+ against each ACLEntry in this list.

    def match(addr)
      @list.each do |e|
        return true if e.match(addr)
      end
      false
    end

    public

    ##
    # Adds +str+ as an ACLEntry in this list

    def add(str)
      @list.push(ACLEntry.new(str))
    end

  end

  ##
  # Default to deny

  DENY_ALLOW = 0

  ##
  # Default to allow

  ALLOW_DENY = 1

  ##
  # Creates a new ACL from +list+ with an evaluation +order+ of DENY_ALLOW or
  # ALLOW_DENY.
  #
  # An ACL +list+ is an Array of "allow" or "deny" and an address or address
  # mask or "all" or "*" to match any address:
  #
  #   %w[
  #     deny all
  #     allow 192.0.2.2
  #     allow 192.0.2.128/26
  #   ]

  def initialize(list=nil, order = DENY_ALLOW)
    @order = order
    @deny = ACLList.new
    @allow = ACLList.new
    install_list(list) if list
  end

  public

  ##
  # Allow connections from Socket +soc+?

  def allow_socket?(soc)
    allow_addr?(soc.peeraddr)
  end

  public

  ##
  # Allow connections from addrinfo +addr+?  It must be formatted like
  # Socket#peeraddr:
  #
  #   ["AF_INET", 10, "lc630", "192.0.2.1"]

  def allow_addr?(addr)
    case @order
    when DENY_ALLOW
      return true if @allow.match(addr)
      return false if @deny.match(addr)
      return true
    when ALLOW_DENY
      return false if @deny.match(addr)
      return true if @allow.match(addr)
      return false
    else
      false
    end
  end

  public

  ##
  # Adds +list+ of ACL entries to this ACL.

  def install_list(list)
    i = 0
    while i < list.size
      permission, domain = list.slice(i,2)
      case permission.downcase
      when 'allow'
        @allow.add(domain)
      when 'deny'
        @deny.add(domain)
      else
        raise "Invalid ACL entry #{list}"
      end
      i += 2
    end
  end

end
# frozen_string_literal: false
require 'observer'

module DRb
  # The Observable module extended to DRb.  See Observable for details.
  module DRbObservable
    include Observable

    # Notifies observers of a change in state.  See also
    # Observable#notify_observers
    def notify_observers(*arg)
      if defined? @observer_state and @observer_state
        if defined? @observer_peers
          @observer_peers.each do |observer, method|
            begin
              observer.__send__(method, *arg)
            rescue
              delete_observer(observer)
            end
          end
        end
        @observer_state = false
      end
    end
  end
end
# frozen_string_literal: false
module DRb
  class DRbObject # :nodoc:
    def ==(other)
      return false unless DRbObject === other
     (@ref == other.__drbref) && (@uri == other.__drburi)
    end

    def hash
      [@uri, @ref].hash
    end

    alias eql? ==
  end
end
module DRb
  VERSION = "2.0.5"
end
# frozen_string_literal: false
# for ruby-1.8.0

module DRb # :nodoc: all
  class DRbServer
    module InvokeMethod18Mixin
      def block_yield(x)
        if x.size == 1 && x[0].class == Array
          x[0] = DRbArray.new(x[0])
        end
        @block.call(*x)
      end

      def perform_with_block
        @obj.__send__(@msg_id, *@argv) do |*x|
          jump_error = nil
          begin
            block_value = block_yield(x)
          rescue LocalJumpError
            jump_error = $!
          end
          if jump_error
            case jump_error.reason
            when :break
              break(jump_error.exit_value)
            else
              raise jump_error
            end
          end
          block_value
        end
      end
    end
  end
end
# frozen_string_literal: false
=begin
 external service manager
        Copyright (c) 2000 Masatoshi SEKI
=end

require_relative 'drb'
require 'monitor'

module DRb
  class ExtServManager
    include DRbUndumped
    include MonitorMixin

    @@command = {}

    def self.command
      @@command
    end

    def self.command=(cmd)
      @@command = cmd
    end

    def initialize
      super()
      @cond = new_cond
      @servers = {}
      @waiting = []
      @queue = Thread::Queue.new
      @thread = invoke_thread
      @uri = nil
    end
    attr_accessor :uri

    def service(name)
      synchronize do
        while true
          server = @servers[name]
          return server if server && server.alive? # server may be `false'
          invoke_service(name)
          @cond.wait
        end
      end
    end

    def regist(name, ro)
      synchronize do
        @servers[name] = ro
        @cond.signal
      end
      self
    end

    def unregist(name)
      synchronize do
        @servers.delete(name)
      end
    end

    private
    def invoke_thread
      Thread.new do
        while name = @queue.pop
          invoke_service_command(name, @@command[name])
        end
      end
    end

    def invoke_service(name)
      @queue.push(name)
    end

    def invoke_service_command(name, command)
      raise "invalid command. name: #{name}" unless command
      synchronize do
        return if @servers.include?(name)
        @servers[name] = false
      end
      uri = @uri || DRb.uri
      if command.respond_to? :to_ary
        command = command.to_ary + [uri, name]
        pid = spawn(*command)
      else
        pid = spawn("#{command} #{uri} #{name}")
      end
      th = Process.detach(pid)
      th[:drb_service] = name
      th
    end
  end
end
# frozen_string_literal: true
#
# optparse.rb - command-line option analysis with the OptionParser class.
#
# Author:: Nobu Nakada
# Documentation:: Nobu Nakada and Gavin Sinclair.
#
# See OptionParser for documentation.
#


#--
# == Developer Documentation (not for RDoc output)
#
# === Class tree
#
# - OptionParser:: front end
# - OptionParser::Switch:: each switches
# - OptionParser::List:: options list
# - OptionParser::ParseError:: errors on parsing
#   - OptionParser::AmbiguousOption
#   - OptionParser::NeedlessArgument
#   - OptionParser::MissingArgument
#   - OptionParser::InvalidOption
#   - OptionParser::InvalidArgument
#     - OptionParser::AmbiguousArgument
#
# === Object relationship diagram
#
#   +--------------+
#   | OptionParser |<>-----+
#   +--------------+       |                      +--------+
#                          |                    ,-| Switch |
#        on_head -------->+---------------+    /  +--------+
#        accept/reject -->| List          |<|>-
#                         |               |<|>-  +----------+
#        on ------------->+---------------+    `-| argument |
#                           :           :        |  class   |
#                         +---------------+      |==========|
#        on_tail -------->|               |      |pattern   |
#                         +---------------+      |----------|
#   OptionParser.accept ->| DefaultList   |      |converter |
#                reject   |(shared between|      +----------+
#                         | all instances)|
#                         +---------------+
#
#++
#
# == OptionParser
#
# === Introduction
#
# OptionParser is a class for command-line option analysis.  It is much more
# advanced, yet also easier to use, than GetoptLong, and is a more Ruby-oriented
# solution.
#
# === Features
#
# 1. The argument specification and the code to handle it are written in the
#    same place.
# 2. It can output an option summary; you don't need to maintain this string
#    separately.
# 3. Optional and mandatory arguments are specified very gracefully.
# 4. Arguments can be automatically converted to a specified class.
# 5. Arguments can be restricted to a certain set.
#
# All of these features are demonstrated in the examples below.  See
# #make_switch for full documentation.
#
# === Minimal example
#
#   require 'optparse'
#
#   options = {}
#   OptionParser.new do |parser|
#     parser.banner = "Usage: example.rb [options]"
#
#     parser.on("-v", "--[no-]verbose", "Run verbosely") do |v|
#       options[:verbose] = v
#     end
#   end.parse!
#
#   p options
#   p ARGV
#
# === Generating Help
#
# OptionParser can be used to automatically generate help for the commands you
# write:
#
#   require 'optparse'
#
#   Options = Struct.new(:name)
#
#   class Parser
#     def self.parse(options)
#       args = Options.new("world")
#
#       opt_parser = OptionParser.new do |parser|
#         parser.banner = "Usage: example.rb [options]"
#
#         parser.on("-nNAME", "--name=NAME", "Name to say hello to") do |n|
#           args.name = n
#         end
#
#         parser.on("-h", "--help", "Prints this help") do
#           puts parser
#           exit
#         end
#       end
#
#       opt_parser.parse!(options)
#       return args
#     end
#   end
#   options = Parser.parse %w[--help]
#
#   #=>
#      # Usage: example.rb [options]
#      #     -n, --name=NAME                  Name to say hello to
#      #     -h, --help                       Prints this help
#
# === Required Arguments
#
# For options that require an argument, option specification strings may include an
# option name in all caps. If an option is used without the required argument,
# an exception will be raised.
#
#   require 'optparse'
#
#   options = {}
#   OptionParser.new do |parser|
#     parser.on("-r", "--require LIBRARY",
#               "Require the LIBRARY before executing your script") do |lib|
#       puts "You required #{lib}!"
#     end
#   end.parse!
#
# Used:
#
#   $ ruby optparse-test.rb -r
#   optparse-test.rb:9:in `<main>': missing argument: -r (OptionParser::MissingArgument)
#   $ ruby optparse-test.rb -r my-library
#   You required my-library!
#
# === Type Coercion
#
# OptionParser supports the ability to coerce command line arguments
# into objects for us.
#
# OptionParser comes with a few ready-to-use kinds of  type
# coercion. They are:
#
# - Date  -- Anything accepted by +Date.parse+
# - DateTime -- Anything accepted by +DateTime.parse+
# - Time -- Anything accepted by +Time.httpdate+ or +Time.parse+
# - URI  -- Anything accepted by +URI.parse+
# - Shellwords -- Anything accepted by +Shellwords.shellwords+
# - String -- Any non-empty string
# - Integer -- Any integer. Will convert octal. (e.g. 124, -3, 040)
# - Float -- Any float. (e.g. 10, 3.14, -100E+13)
# - Numeric -- Any integer, float, or rational (1, 3.4, 1/3)
# - DecimalInteger -- Like +Integer+, but no octal format.
# - OctalInteger -- Like +Integer+, but no decimal format.
# - DecimalNumeric -- Decimal integer or float.
# - TrueClass --  Accepts '+, yes, true, -, no, false' and
#   defaults as +true+
# - FalseClass -- Same as +TrueClass+, but defaults to +false+
# - Array -- Strings separated by ',' (e.g. 1,2,3)
# - Regexp -- Regular expressions. Also includes options.
#
# We can also add our own coercions, which we will cover below.
#
# ==== Using Built-in Conversions
#
# As an example, the built-in +Time+ conversion is used. The other built-in
# conversions behave in the same way.
# OptionParser will attempt to parse the argument
# as a +Time+. If it succeeds, that time will be passed to the
# handler block. Otherwise, an exception will be raised.
#
#   require 'optparse'
#   require 'optparse/time'
#   OptionParser.new do |parser|
#     parser.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time|
#       p time
#     end
#   end.parse!
#
# Used:
#
#   $ ruby optparse-test.rb  -t nonsense
#   ... invalid argument: -t nonsense (OptionParser::InvalidArgument)
#   $ ruby optparse-test.rb  -t 10-11-12
#   2010-11-12 00:00:00 -0500
#   $ ruby optparse-test.rb  -t 9:30
#   2014-08-13 09:30:00 -0400
#
# ==== Creating Custom Conversions
#
# The +accept+ method on OptionParser may be used to create converters.
# It specifies which conversion block to call whenever a class is specified.
# The example below uses it to fetch a +User+ object before the +on+ handler receives it.
#
#   require 'optparse'
#
#   User = Struct.new(:id, :name)
#
#   def find_user id
#     not_found = ->{ raise "No User Found for id #{id}" }
#     [ User.new(1, "Sam"),
#       User.new(2, "Gandalf") ].find(not_found) do |u|
#       u.id == id
#     end
#   end
#
#   op = OptionParser.new
#   op.accept(User) do |user_id|
#     find_user user_id.to_i
#   end
#
#   op.on("--user ID", User) do |user|
#     puts user
#   end
#
#   op.parse!
#
# Used:
#
#   $ ruby optparse-test.rb --user 1
#   #<struct User id=1, name="Sam">
#   $ ruby optparse-test.rb --user 2
#   #<struct User id=2, name="Gandalf">
#   $ ruby optparse-test.rb --user 3
#   optparse-test.rb:15:in `block in find_user': No User Found for id 3 (RuntimeError)
#
# === Store options to a Hash
#
# The +into+ option of +order+, +parse+ and so on methods stores command line options into a Hash.
#
#   require 'optparse'
#
#   params = {}
#   OptionParser.new do |parser|
#     parser.on('-a')
#     parser.on('-b NUM', Integer)
#     parser.on('-v', '--verbose')
#   end.parse!(into: params)
#
#   p params
#
# Used:
#
#   $ ruby optparse-test.rb -a
#   {:a=>true}
#   $ ruby optparse-test.rb -a -v
#   {:a=>true, :verbose=>true}
#   $ ruby optparse-test.rb -a -b 100
#   {:a=>true, :b=>100}
#
# === Complete example
#
# The following example is a complete Ruby program.  You can run it and see the
# effect of specifying various options.  This is probably the best way to learn
# the features of +optparse+.
#
#   require 'optparse'
#   require 'optparse/time'
#   require 'ostruct'
#   require 'pp'
#
#   class OptparseExample
#     Version = '1.0.0'
#
#     CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary]
#     CODE_ALIASES = { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
#
#     class ScriptOptions
#       attr_accessor :library, :inplace, :encoding, :transfer_type,
#                     :verbose, :extension, :delay, :time, :record_separator,
#                     :list
#
#       def initialize
#         self.library = []
#         self.inplace = false
#         self.encoding = "utf8"
#         self.transfer_type = :auto
#         self.verbose = false
#       end
#
#       def define_options(parser)
#         parser.banner = "Usage: example.rb [options]"
#         parser.separator ""
#         parser.separator "Specific options:"
#
#         # add additional options
#         perform_inplace_option(parser)
#         delay_execution_option(parser)
#         execute_at_time_option(parser)
#         specify_record_separator_option(parser)
#         list_example_option(parser)
#         specify_encoding_option(parser)
#         optional_option_argument_with_keyword_completion_option(parser)
#         boolean_verbose_option(parser)
#
#         parser.separator ""
#         parser.separator "Common options:"
#         # No argument, shows at tail.  This will print an options summary.
#         # Try it and see!
#         parser.on_tail("-h", "--help", "Show this message") do
#           puts parser
#           exit
#         end
#         # Another typical switch to print the version.
#         parser.on_tail("--version", "Show version") do
#           puts Version
#           exit
#         end
#       end
#
#       def perform_inplace_option(parser)
#         # Specifies an optional option argument
#         parser.on("-i", "--inplace [EXTENSION]",
#                   "Edit ARGV files in place",
#                   "(make backup if EXTENSION supplied)") do |ext|
#           self.inplace = true
#           self.extension = ext || ''
#           self.extension.sub!(/\A\.?(?=.)/, ".")  # Ensure extension begins with dot.
#         end
#       end
#
#       def delay_execution_option(parser)
#         # Cast 'delay' argument to a Float.
#         parser.on("--delay N", Float, "Delay N seconds before executing") do |n|
#           self.delay = n
#         end
#       end
#
#       def execute_at_time_option(parser)
#         # Cast 'time' argument to a Time object.
#         parser.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time|
#           self.time = time
#         end
#       end
#
#       def specify_record_separator_option(parser)
#         # Cast to octal integer.
#         parser.on("-F", "--irs [OCTAL]", OptionParser::OctalInteger,
#                   "Specify record separator (default \\0)") do |rs|
#           self.record_separator = rs
#         end
#       end
#
#       def list_example_option(parser)
#         # List of arguments.
#         parser.on("--list x,y,z", Array, "Example 'list' of arguments") do |list|
#           self.list = list
#         end
#       end
#
#       def specify_encoding_option(parser)
#         # Keyword completion.  We are specifying a specific set of arguments (CODES
#         # and CODE_ALIASES - notice the latter is a Hash), and the user may provide
#         # the shortest unambiguous text.
#         code_list = (CODE_ALIASES.keys + CODES).join(', ')
#         parser.on("--code CODE", CODES, CODE_ALIASES, "Select encoding",
#                   "(#{code_list})") do |encoding|
#           self.encoding = encoding
#         end
#       end
#
#       def optional_option_argument_with_keyword_completion_option(parser)
#         # Optional '--type' option argument with keyword completion.
#         parser.on("--type [TYPE]", [:text, :binary, :auto],
#                   "Select transfer type (text, binary, auto)") do |t|
#           self.transfer_type = t
#         end
#       end
#
#       def boolean_verbose_option(parser)
#         # Boolean switch.
#         parser.on("-v", "--[no-]verbose", "Run verbosely") do |v|
#           self.verbose = v
#         end
#       end
#     end
#
#     #
#     # Return a structure describing the options.
#     #
#     def parse(args)
#       # The options specified on the command line will be collected in
#       # *options*.
#
#       @options = ScriptOptions.new
#       @args = OptionParser.new do |parser|
#         @options.define_options(parser)
#         parser.parse!(args)
#       end
#       @options
#     end
#
#     attr_reader :parser, :options
#   end  # class OptparseExample
#
#   example = OptparseExample.new
#   options = example.parse(ARGV)
#   pp options # example.options
#   pp ARGV
#
# === Shell Completion
#
# For modern shells (e.g. bash, zsh, etc.), you can use shell
# completion for command line options.
#
# === Further documentation
#
# The above examples should be enough to learn how to use this class.  If you
# have any questions, file a ticket at http://bugs.ruby-lang.org.
#
class OptionParser
  OptionParser::Version = "0.1.1"

  # :stopdoc:
  NoArgument = [NO_ARGUMENT = :NONE, nil].freeze
  RequiredArgument = [REQUIRED_ARGUMENT = :REQUIRED, true].freeze
  OptionalArgument = [OPTIONAL_ARGUMENT = :OPTIONAL, false].freeze
  # :startdoc:

  #
  # Keyword completion module.  This allows partial arguments to be specified
  # and resolved against a list of acceptable values.
  #
  module Completion
    def self.regexp(key, icase)
      Regexp.new('\A' + Regexp.quote(key).gsub(/\w+\b/, '\&\w*'), icase)
    end

    def self.candidate(key, icase = false, pat = nil, &block)
      pat ||= Completion.regexp(key, icase)
      candidates = []
      block.call do |k, *v|
        (if Regexp === k
           kn = ""
           k === key
         else
           kn = defined?(k.id2name) ? k.id2name : k
           pat === kn
         end) or next
        v << k if v.empty?
        candidates << [k, v, kn]
      end
      candidates
    end

    def candidate(key, icase = false, pat = nil)
      Completion.candidate(key, icase, pat, &method(:each))
    end

    public
    def complete(key, icase = false, pat = nil)
      candidates = candidate(key, icase, pat, &method(:each)).sort_by {|k, v, kn| kn.size}
      if candidates.size == 1
        canon, sw, * = candidates[0]
      elsif candidates.size > 1
        canon, sw, cn = candidates.shift
        candidates.each do |k, v, kn|
          next if sw == v
          if String === cn and String === kn
            if cn.rindex(kn, 0)
              canon, sw, cn = k, v, kn
              next
            elsif kn.rindex(cn, 0)
              next
            end
          end
          throw :ambiguous, key
        end
      end
      if canon
        block_given? or return key, *sw
        yield(key, *sw)
      end
    end

    def convert(opt = nil, val = nil, *)
      val
    end
  end


  #
  # Map from option/keyword string to object with completion.
  #
  class OptionMap < Hash
    include Completion
  end


  #
  # Individual switch class.  Not important to the user.
  #
  # Defined within Switch are several Switch-derived classes: NoArgument,
  # RequiredArgument, etc.
  #
  class Switch
    attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block

    #
    # Guesses argument style from +arg+.  Returns corresponding
    # OptionParser::Switch class (OptionalArgument, etc.).
    #
    def self.guess(arg)
      case arg
      when ""
        t = self
      when /\A=?\[/
        t = Switch::OptionalArgument
      when /\A\s+\[/
        t = Switch::PlacedArgument
      else
        t = Switch::RequiredArgument
      end
      self >= t or incompatible_argument_styles(arg, t)
      t
    end

    def self.incompatible_argument_styles(arg, t)
      raise(ArgumentError, "#{arg}: incompatible argument styles\n  #{self}, #{t}",
            ParseError.filter_backtrace(caller(2)))
    end

    def self.pattern
      NilClass
    end

    def initialize(pattern = nil, conv = nil,
                   short = nil, long = nil, arg = nil,
                   desc = ([] if short or long), block = nil, &_block)
      raise if Array === pattern
      block ||= _block
      @pattern, @conv, @short, @long, @arg, @desc, @block =
        pattern, conv, short, long, arg, desc, block
    end

    #
    # Parses +arg+ and returns rest of +arg+ and matched portion to the
    # argument pattern. Yields when the pattern doesn't match substring.
    #
    def parse_arg(arg)
      pattern or return nil, [arg]
      unless m = pattern.match(arg)
        yield(InvalidArgument, arg)
        return arg, []
      end
      if String === m
        m = [s = m]
      else
        m = m.to_a
        s = m[0]
        return nil, m unless String === s
      end
      raise InvalidArgument, arg unless arg.rindex(s, 0)
      return nil, m if s.length == arg.length
      yield(InvalidArgument, arg) # didn't match whole arg
      return arg[s.length..-1], m
    end
    private :parse_arg

    #
    # Parses argument, converts and returns +arg+, +block+ and result of
    # conversion. Yields at semi-error condition instead of raising an
    # exception.
    #
    def conv_arg(arg, val = [])
      if conv
        val = conv.call(*val)
      else
        val = proc {|v| v}.call(*val)
      end
      return arg, block, val
    end
    private :conv_arg

    #
    # Produces the summary text. Each line of the summary is yielded to the
    # block (without newline).
    #
    # +sdone+::  Already summarized short style options keyed hash.
    # +ldone+::  Already summarized long style options keyed hash.
    # +width+::  Width of left side (option part). In other words, the right
    #            side (description part) starts after +width+ columns.
    # +max+::    Maximum width of left side -> the options are filled within
    #            +max+ columns.
    # +indent+:: Prefix string indents all summarized lines.
    #
    def summarize(sdone = {}, ldone = {}, width = 1, max = width - 1, indent = "")
      sopts, lopts = [], [], nil
      @short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
      @long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
      return if sopts.empty? and lopts.empty? # completely hidden

      left = [sopts.join(', ')]
      right = desc.dup

      while s = lopts.shift
        l = left[-1].length + s.length
        l += arg.length if left.size == 1 && arg
        l < max or sopts.empty? or left << +''
        left[-1] << (left[-1].empty? ? ' ' * 4 : ', ') << s
      end

      if arg
        left[0] << (left[1] ? arg.sub(/\A(\[?)=/, '\1') + ',' : arg)
      end
      mlen = left.collect {|ss| ss.length}.max.to_i
      while mlen > width and l = left.shift
        mlen = left.collect {|ss| ss.length}.max.to_i if l.length == mlen
        if l.length < width and (r = right[0]) and !r.empty?
          l = l.to_s.ljust(width) + ' ' + r
          right.shift
        end
        yield(indent + l)
      end

      while begin l = left.shift; r = right.shift; l or r end
        l = l.to_s.ljust(width) + ' ' + r if r and !r.empty?
        yield(indent + l)
      end

      self
    end

    def add_banner(to)  # :nodoc:
      unless @short or @long
        s = desc.join
        to << " [" + s + "]..." unless s.empty?
      end
      to
    end

    def match_nonswitch?(str)  # :nodoc:
      @pattern =~ str unless @short or @long
    end

    #
    # Main name of the switch.
    #
    def switch_name
      (long.first || short.first).sub(/\A-+(?:\[no-\])?/, '')
    end

    def compsys(sdone, ldone)   # :nodoc:
      sopts, lopts = [], []
      @short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
      @long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
      return if sopts.empty? and lopts.empty? # completely hidden

      (sopts+lopts).each do |opt|
        # "(-x -c -r)-l[left justify]"
        if /^--\[no-\](.+)$/ =~ opt
          o = $1
          yield("--#{o}", desc.join(""))
          yield("--no-#{o}", desc.join(""))
        else
          yield("#{opt}", desc.join(""))
        end
      end
    end

    #
    # Switch that takes no arguments.
    #
    class NoArgument < self

      #
      # Raises an exception if any arguments given.
      #
      def parse(arg, argv)
        yield(NeedlessArgument, arg) if arg
        conv_arg(arg)
      end

      def self.incompatible_argument_styles(*)
      end

      def self.pattern
        Object
      end
    end

    #
    # Switch that takes an argument.
    #
    class RequiredArgument < self

      #
      # Raises an exception if argument is not present.
      #
      def parse(arg, argv)
        unless arg
          raise MissingArgument if argv.empty?
          arg = argv.shift
        end
        conv_arg(*parse_arg(arg, &method(:raise)))
      end
    end

    #
    # Switch that can omit argument.
    #
    class OptionalArgument < self

      #
      # Parses argument if given, or uses default value.
      #
      def parse(arg, argv, &error)
        if arg
          conv_arg(*parse_arg(arg, &error))
        else
          conv_arg(arg)
        end
      end
    end

    #
    # Switch that takes an argument, which does not begin with '-'.
    #
    class PlacedArgument < self

      #
      # Returns nil if argument is not present or begins with '-'.
      #
      def parse(arg, argv, &error)
        if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
          return nil, block, nil
        end
        opt = (val = parse_arg(val, &error))[1]
        val = conv_arg(*val)
        if opt and !arg
          argv.shift
        else
          val[0] = nil
        end
        val
      end
    end
  end

  #
  # Simple option list providing mapping from short and/or long option
  # string to OptionParser::Switch and mapping from acceptable argument to
  # matching pattern and converter pair. Also provides summary feature.
  #
  class List
    # Map from acceptable argument types to pattern and converter pairs.
    attr_reader :atype

    # Map from short style option switches to actual switch objects.
    attr_reader :short

    # Map from long style option switches to actual switch objects.
    attr_reader :long

    # List of all switches and summary string.
    attr_reader :list

    #
    # Just initializes all instance variables.
    #
    def initialize
      @atype = {}
      @short = OptionMap.new
      @long = OptionMap.new
      @list = []
    end

    #
    # See OptionParser.accept.
    #
    def accept(t, pat = /.*/m, &block)
      if pat
        pat.respond_to?(:match) or
          raise TypeError, "has no `match'", ParseError.filter_backtrace(caller(2))
      else
        pat = t if t.respond_to?(:match)
      end
      unless block
        block = pat.method(:convert).to_proc if pat.respond_to?(:convert)
      end
      @atype[t] = [pat, block]
    end

    #
    # See OptionParser.reject.
    #
    def reject(t)
      @atype.delete(t)
    end

    #
    # Adds +sw+ according to +sopts+, +lopts+ and +nlopts+.
    #
    # +sw+::     OptionParser::Switch instance to be added.
    # +sopts+::  Short style option list.
    # +lopts+::  Long style option list.
    # +nlopts+:: Negated long style options list.
    #
    def update(sw, sopts, lopts, nsw = nil, nlopts = nil)
      sopts.each {|o| @short[o] = sw} if sopts
      lopts.each {|o| @long[o] = sw} if lopts
      nlopts.each {|o| @long[o] = nsw} if nsw and nlopts
      used = @short.invert.update(@long.invert)
      @list.delete_if {|o| Switch === o and !used[o]}
    end
    private :update

    #
    # Inserts +switch+ at the head of the list, and associates short, long
    # and negated long options. Arguments are:
    #
    # +switch+::      OptionParser::Switch instance to be inserted.
    # +short_opts+::  List of short style options.
    # +long_opts+::   List of long style options.
    # +nolong_opts+:: List of long style options with "no-" prefix.
    #
    #   prepend(switch, short_opts, long_opts, nolong_opts)
    #
    def prepend(*args)
      update(*args)
      @list.unshift(args[0])
    end

    #
    # Appends +switch+ at the tail of the list, and associates short, long
    # and negated long options. Arguments are:
    #
    # +switch+::      OptionParser::Switch instance to be inserted.
    # +short_opts+::  List of short style options.
    # +long_opts+::   List of long style options.
    # +nolong_opts+:: List of long style options with "no-" prefix.
    #
    #   append(switch, short_opts, long_opts, nolong_opts)
    #
    def append(*args)
      update(*args)
      @list.push(args[0])
    end

    #
    # Searches +key+ in +id+ list. The result is returned or yielded if a
    # block is given. If it isn't found, nil is returned.
    #
    def search(id, key)
      if list = __send__(id)
        val = list.fetch(key) {return nil}
        block_given? ? yield(val) : val
      end
    end

    #
    # Searches list +id+ for +opt+ and the optional patterns for completion
    # +pat+. If +icase+ is true, the search is case insensitive. The result
    # is returned or yielded if a block is given. If it isn't found, nil is
    # returned.
    #
    def complete(id, opt, icase = false, *pat, &block)
      __send__(id).complete(opt, icase, *pat, &block)
    end

    def get_candidates(id)
      yield __send__(id).keys
    end

    #
    # Iterates over each option, passing the option to the +block+.
    #
    def each_option(&block)
      list.each(&block)
    end

    #
    # Creates the summary table, passing each line to the +block+ (without
    # newline). The arguments +args+ are passed along to the summarize
    # method which is called on every option.
    #
    def summarize(*args, &block)
      sum = []
      list.reverse_each do |opt|
        if opt.respond_to?(:summarize) # perhaps OptionParser::Switch
          s = []
          opt.summarize(*args) {|l| s << l}
          sum.concat(s.reverse)
        elsif !opt or opt.empty?
          sum << ""
        elsif opt.respond_to?(:each_line)
          sum.concat([*opt.each_line].reverse)
        else
          sum.concat([*opt.each].reverse)
        end
      end
      sum.reverse_each(&block)
    end

    def add_banner(to)  # :nodoc:
      list.each do |opt|
        if opt.respond_to?(:add_banner)
          opt.add_banner(to)
        end
      end
      to
    end

    def compsys(*args, &block)  # :nodoc:
      list.each do |opt|
        if opt.respond_to?(:compsys)
          opt.compsys(*args, &block)
        end
      end
    end
  end

  #
  # Hash with completion search feature. See OptionParser::Completion.
  #
  class CompletingHash < Hash
    include Completion

    #
    # Completion for hash key.
    #
    def match(key)
      *values = fetch(key) {
        raise AmbiguousArgument, catch(:ambiguous) {return complete(key)}
      }
      return key, *values
    end
  end

  # :stopdoc:

  #
  # Enumeration of acceptable argument styles. Possible values are:
  #
  # NO_ARGUMENT::       The switch takes no arguments. (:NONE)
  # REQUIRED_ARGUMENT:: The switch requires an argument. (:REQUIRED)
  # OPTIONAL_ARGUMENT:: The switch requires an optional argument. (:OPTIONAL)
  #
  # Use like --switch=argument (long style) or -Xargument (short style). For
  # short style, only portion matched to argument pattern is treated as
  # argument.
  #
  ArgumentStyle = {}
  NoArgument.each {|el| ArgumentStyle[el] = Switch::NoArgument}
  RequiredArgument.each {|el| ArgumentStyle[el] = Switch::RequiredArgument}
  OptionalArgument.each {|el| ArgumentStyle[el] = Switch::OptionalArgument}
  ArgumentStyle.freeze

  #
  # Switches common used such as '--', and also provides default
  # argument classes
  #
  DefaultList = List.new
  DefaultList.short['-'] = Switch::NoArgument.new {}
  DefaultList.long[''] = Switch::NoArgument.new {throw :terminate}


  COMPSYS_HEADER = <<'XXX'      # :nodoc:

typeset -A opt_args
local context state line

_arguments -s -S \
XXX

  def compsys(to, name = File.basename($0)) # :nodoc:
    to << "#compdef #{name}\n"
    to << COMPSYS_HEADER
    visit(:compsys, {}, {}) {|o, d|
      to << %Q[  "#{o}[#{d.gsub(/[\"\[\]]/, '\\\\\&')}]" \\\n]
    }
    to << "  '*:file:_files' && return 0\n"
  end

  #
  # Default options for ARGV, which never appear in option summary.
  #
  Officious = {}

  #
  # --help
  # Shows option summary.
  #
  Officious['help'] = proc do |parser|
    Switch::NoArgument.new do |arg|
      puts parser.help
      exit
    end
  end

  #
  # --*-completion-bash=WORD
  # Shows candidates for command line completion.
  #
  Officious['*-completion-bash'] = proc do |parser|
    Switch::RequiredArgument.new do |arg|
      puts parser.candidate(arg)
      exit
    end
  end

  #
  # --*-completion-zsh[=NAME:FILE]
  # Creates zsh completion file.
  #
  Officious['*-completion-zsh'] = proc do |parser|
    Switch::OptionalArgument.new do |arg|
      parser.compsys(STDOUT, arg)
      exit
    end
  end

  #
  # --version
  # Shows version string if Version is defined.
  #
  Officious['version'] = proc do |parser|
    Switch::OptionalArgument.new do |pkg|
      if pkg
        begin
          require 'optparse/version'
        rescue LoadError
        else
          show_version(*pkg.split(/,/)) or
            abort("#{parser.program_name}: no version found in package #{pkg}")
          exit
        end
      end
      v = parser.ver or abort("#{parser.program_name}: version unknown")
      puts v
      exit
    end
  end

  # :startdoc:

  #
  # Class methods
  #

  #
  # Initializes a new instance and evaluates the optional block in context
  # of the instance. Arguments +args+ are passed to #new, see there for
  # description of parameters.
  #
  # This method is *deprecated*, its behavior corresponds to the older #new
  # method.
  #
  def self.with(*args, &block)
    opts = new(*args)
    opts.instance_eval(&block)
    opts
  end

  #
  # Returns an incremented value of +default+ according to +arg+.
  #
  def self.inc(arg, default = nil)
    case arg
    when Integer
      arg.nonzero?
    when nil
      default.to_i + 1
    end
  end
  def inc(*args)
    self.class.inc(*args)
  end

  #
  # Initializes the instance and yields itself if called with a block.
  #
  # +banner+:: Banner message.
  # +width+::  Summary width.
  # +indent+:: Summary indent.
  #
  def initialize(banner = nil, width = 32, indent = ' ' * 4)
    @stack = [DefaultList, List.new, List.new]
    @program_name = nil
    @banner = banner
    @summary_width = width
    @summary_indent = indent
    @default_argv = ARGV
    @require_exact = false
    add_officious
    yield self if block_given?
  end

  def add_officious  # :nodoc:
    list = base()
    Officious.each do |opt, block|
      list.long[opt] ||= block.call(self)
    end
  end

  #
  # Terminates option parsing. Optional parameter +arg+ is a string pushed
  # back to be the first non-option argument.
  #
  def terminate(arg = nil)
    self.class.terminate(arg)
  end
  def self.terminate(arg = nil)
    throw :terminate, arg
  end

  @stack = [DefaultList]
  def self.top() DefaultList end

  #
  # Directs to accept specified class +t+. The argument string is passed to
  # the block in which it should be converted to the desired class.
  #
  # +t+::   Argument class specifier, any object including Class.
  # +pat+:: Pattern for argument, defaults to +t+ if it responds to match.
  #
  #   accept(t, pat, &block)
  #
  def accept(*args, &blk) top.accept(*args, &blk) end
  #
  # See #accept.
  #
  def self.accept(*args, &blk) top.accept(*args, &blk) end

  #
  # Directs to reject specified class argument.
  #
  # +t+:: Argument class specifier, any object including Class.
  #
  #   reject(t)
  #
  def reject(*args, &blk) top.reject(*args, &blk) end
  #
  # See #reject.
  #
  def self.reject(*args, &blk) top.reject(*args, &blk) end

  #
  # Instance methods
  #

  # Heading banner preceding summary.
  attr_writer :banner

  # Program name to be emitted in error message and default banner,
  # defaults to $0.
  attr_writer :program_name

  # Width for option list portion of summary. Must be Numeric.
  attr_accessor :summary_width

  # Indentation for summary. Must be String (or have + String method).
  attr_accessor :summary_indent

  # Strings to be parsed in default.
  attr_accessor :default_argv

  # Whether to require that options match exactly (disallows providing
  # abbreviated long option as short option).
  attr_accessor :require_exact

  #
  # Heading banner preceding summary.
  #
  def banner
    unless @banner
      @banner = +"Usage: #{program_name} [options]"
      visit(:add_banner, @banner)
    end
    @banner
  end

  #
  # Program name to be emitted in error message and default banner, defaults
  # to $0.
  #
  def program_name
    @program_name || File.basename($0, '.*')
  end

  # for experimental cascading :-)
  alias set_banner banner=
  alias set_program_name program_name=
  alias set_summary_width summary_width=
  alias set_summary_indent summary_indent=

  # Version
  attr_writer :version
  # Release code
  attr_writer :release

  #
  # Version
  #
  def version
    (defined?(@version) && @version) || (defined?(::Version) && ::Version)
  end

  #
  # Release code
  #
  def release
    (defined?(@release) && @release) || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
  end

  #
  # Returns version string from program_name, version and release.
  #
  def ver
    if v = version
      str = +"#{program_name} #{[v].join('.')}"
      str << " (#{v})" if v = release
      str
    end
  end

  def warn(mesg = $!)
    super("#{program_name}: #{mesg}")
  end

  def abort(mesg = $!)
    super("#{program_name}: #{mesg}")
  end

  #
  # Subject of #on / #on_head, #accept / #reject
  #
  def top
    @stack[-1]
  end

  #
  # Subject of #on_tail.
  #
  def base
    @stack[1]
  end

  #
  # Pushes a new List.
  #
  def new
    @stack.push(List.new)
    if block_given?
      yield self
    else
      self
    end
  end

  #
  # Removes the last List.
  #
  def remove
    @stack.pop
  end

  #
  # Puts option summary into +to+ and returns +to+. Yields each line if
  # a block is given.
  #
  # +to+:: Output destination, which must have method <<. Defaults to [].
  # +width+:: Width of left side, defaults to @summary_width.
  # +max+:: Maximum length allowed for left side, defaults to +width+ - 1.
  # +indent+:: Indentation, defaults to @summary_indent.
  #
  def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
    nl = "\n"
    blk ||= proc {|l| to << (l.index(nl, -1) ? l : l + nl)}
    visit(:summarize, {}, {}, width, max, indent, &blk)
    to
  end

  #
  # Returns option summary string.
  #
  def help; summarize("#{banner}".sub(/\n?\z/, "\n")) end
  alias to_s help

  #
  # Returns option summary list.
  #
  def to_a; summarize("#{banner}".split(/^/)) end

  #
  # Checks if an argument is given twice, in which case an ArgumentError is
  # raised. Called from OptionParser#switch only.
  #
  # +obj+:: New argument.
  # +prv+:: Previously specified argument.
  # +msg+:: Exception message.
  #
  def notwice(obj, prv, msg)
    unless !prv or prv == obj
      raise(ArgumentError, "argument #{msg} given twice: #{obj}",
            ParseError.filter_backtrace(caller(2)))
    end
    obj
  end
  private :notwice

  SPLAT_PROC = proc {|*a| a.length <= 1 ? a.first : a} # :nodoc:

  # :call-seq:
  #   make_switch(params, block = nil)
  #
  # Creates an OptionParser::Switch from the parameters. The parsed argument
  # value is passed to the given block, where it can be processed.
  #
  # See at the beginning of OptionParser for some full examples.
  #
  # +params+ can include the following elements:
  #
  # [Argument style:]
  #   One of the following:
  #     :NONE, :REQUIRED, :OPTIONAL
  #
  # [Argument pattern:]
  #   Acceptable option argument format, must be pre-defined with
  #   OptionParser.accept or OptionParser#accept, or Regexp. This can appear
  #   once or assigned as String if not present, otherwise causes an
  #   ArgumentError. Examples:
  #     Float, Time, Array
  #
  # [Possible argument values:]
  #   Hash or Array.
  #     [:text, :binary, :auto]
  #     %w[iso-2022-jp shift_jis euc-jp utf8 binary]
  #     { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
  #
  # [Long style switch:]
  #   Specifies a long style switch which takes a mandatory, optional or no
  #   argument. It's a string of the following form:
  #     "--switch=MANDATORY" or "--switch MANDATORY"
  #     "--switch[=OPTIONAL]"
  #     "--switch"
  #
  # [Short style switch:]
  #   Specifies short style switch which takes a mandatory, optional or no
  #   argument. It's a string of the following form:
  #     "-xMANDATORY"
  #     "-x[OPTIONAL]"
  #     "-x"
  #   There is also a special form which matches character range (not full
  #   set of regular expression):
  #     "-[a-z]MANDATORY"
  #     "-[a-z][OPTIONAL]"
  #     "-[a-z]"
  #
  # [Argument style and description:]
  #   Instead of specifying mandatory or optional arguments directly in the
  #   switch parameter, this separate parameter can be used.
  #     "=MANDATORY"
  #     "=[OPTIONAL]"
  #
  # [Description:]
  #   Description string for the option.
  #     "Run verbosely"
  #   If you give multiple description strings, each string will be printed
  #   line by line.
  #
  # [Handler:]
  #   Handler for the parsed argument value. Either give a block or pass a
  #   Proc or Method as an argument.
  #
  def make_switch(opts, block = nil)
    short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], []
    ldesc, sdesc, desc, arg = [], [], []
    default_style = Switch::NoArgument
    default_pattern = nil
    klass = nil
    q, a = nil
    has_arg = false

    opts.each do |o|
      # argument class
      next if search(:atype, o) do |pat, c|
        klass = notwice(o, klass, 'type')
        if not_style and not_style != Switch::NoArgument
          not_pattern, not_conv = pat, c
        else
          default_pattern, conv = pat, c
        end
      end

      # directly specified pattern(any object possible to match)
      if (!(String === o || Symbol === o)) and o.respond_to?(:match)
        pattern = notwice(o, pattern, 'pattern')
        if pattern.respond_to?(:convert)
          conv = pattern.method(:convert).to_proc
        else
          conv = SPLAT_PROC
        end
        next
      end

      # anything others
      case o
      when Proc, Method
        block = notwice(o, block, 'block')
      when Array, Hash
        case pattern
        when CompletingHash
        when nil
          pattern = CompletingHash.new
          conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert)
        else
          raise ArgumentError, "argument pattern given twice"
        end
        o.each {|pat, *v| pattern[pat] = v.fetch(0) {pat}}
      when Module
        raise ArgumentError, "unsupported argument type: #{o}", ParseError.filter_backtrace(caller(4))
      when *ArgumentStyle.keys
        style = notwice(ArgumentStyle[o], style, 'style')
      when /^--no-([^\[\]=\s]*)(.+)?/
        q, a = $1, $2
        o = notwice(a ? Object : TrueClass, klass, 'type')
        not_pattern, not_conv = search(:atype, o) unless not_style
        not_style = (not_style || default_style).guess(arg = a) if a
        default_style = Switch::NoArgument
        default_pattern, conv = search(:atype, FalseClass) unless default_pattern
        ldesc << "--no-#{q}"
        (q = q.downcase).tr!('_', '-')
        long << "no-#{q}"
        nolong << q
      when /^--\[no-\]([^\[\]=\s]*)(.+)?/
        q, a = $1, $2
        o = notwice(a ? Object : TrueClass, klass, 'type')
        if a
          default_style = default_style.guess(arg = a)
          default_pattern, conv = search(:atype, o) unless default_pattern
        end
        ldesc << "--[no-]#{q}"
        (o = q.downcase).tr!('_', '-')
        long << o
        not_pattern, not_conv = search(:atype, FalseClass) unless not_style
        not_style = Switch::NoArgument
        nolong << "no-#{o}"
      when /^--([^\[\]=\s]*)(.+)?/
        q, a = $1, $2
        if a
          o = notwice(NilClass, klass, 'type')
          default_style = default_style.guess(arg = a)
          default_pattern, conv = search(:atype, o) unless default_pattern
        end
        ldesc << "--#{q}"
        (o = q.downcase).tr!('_', '-')
        long << o
      when /^-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/
        q, a = $1, $2
        o = notwice(Object, klass, 'type')
        if a
          default_style = default_style.guess(arg = a)
          default_pattern, conv = search(:atype, o) unless default_pattern
        else
          has_arg = true
        end
        sdesc << "-#{q}"
        short << Regexp.new(q)
      when /^-(.)(.+)?/
        q, a = $1, $2
        if a
          o = notwice(NilClass, klass, 'type')
          default_style = default_style.guess(arg = a)
          default_pattern, conv = search(:atype, o) unless default_pattern
        end
        sdesc << "-#{q}"
        short << q
      when /^=/
        style = notwice(default_style.guess(arg = o), style, 'style')
        default_pattern, conv = search(:atype, Object) unless default_pattern
      else
        desc.push(o)
      end
    end

    default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern
    if !(short.empty? and long.empty?)
      if has_arg and default_style == Switch::NoArgument
        default_style = Switch::RequiredArgument
      end
      s = (style || default_style).new(pattern || default_pattern,
                                       conv, sdesc, ldesc, arg, desc, block)
    elsif !block
      if style or pattern
        raise ArgumentError, "no switch given", ParseError.filter_backtrace(caller)
      end
      s = desc
    else
      short << pattern
      s = (style || default_style).new(pattern,
                                       conv, nil, nil, arg, desc, block)
    end
    return s, short, long,
      (not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style),
      nolong
  end

  # :call-seq:
  #   define(*params, &block)
  #
  def define(*opts, &block)
    top.append(*(sw = make_switch(opts, block)))
    sw[0]
  end

  # :call-seq:
  #   on(*params, &block)
  #
  # Add option switch and handler. See #make_switch for an explanation of
  # parameters.
  #
  def on(*opts, &block)
    define(*opts, &block)
    self
  end
  alias def_option define

  # :call-seq:
  #   define_head(*params, &block)
  #
  def define_head(*opts, &block)
    top.prepend(*(sw = make_switch(opts, block)))
    sw[0]
  end

  # :call-seq:
  #   on_head(*params, &block)
  #
  # Add option switch like with #on, but at head of summary.
  #
  def on_head(*opts, &block)
    define_head(*opts, &block)
    self
  end
  alias def_head_option define_head

  # :call-seq:
  #   define_tail(*params, &block)
  #
  def define_tail(*opts, &block)
    base.append(*(sw = make_switch(opts, block)))
    sw[0]
  end

  #
  # :call-seq:
  #   on_tail(*params, &block)
  #
  # Add option switch like with #on, but at tail of summary.
  #
  def on_tail(*opts, &block)
    define_tail(*opts, &block)
    self
  end
  alias def_tail_option define_tail

  #
  # Add separator in summary.
  #
  def separator(string)
    top.append(string, nil, nil)
  end

  #
  # Parses command line arguments +argv+ in order. When a block is given,
  # each non-option argument is yielded. When optional +into+ keyword
  # argument is provided, the parsed option values are stored there via
  # <code>[]=</code> method (so it can be Hash, or OpenStruct, or other
  # similar object).
  #
  # Returns the rest of +argv+ left unparsed.
  #
  def order(*argv, into: nil, &nonopt)
    argv = argv[0].dup if argv.size == 1 and Array === argv[0]
    order!(argv, into: into, &nonopt)
  end

  #
  # Same as #order, but removes switches destructively.
  # Non-option arguments remain in +argv+.
  #
  def order!(argv = default_argv, into: nil, &nonopt)
    setter = ->(name, val) {into[name.to_sym] = val} if into
    parse_in_order(argv, setter, &nonopt)
  end

  def parse_in_order(argv = default_argv, setter = nil, &nonopt)  # :nodoc:
    opt, arg, val, rest = nil
    nonopt ||= proc {|a| throw :terminate, a}
    argv.unshift(arg) if arg = catch(:terminate) {
      while arg = argv.shift
        case arg
        # long option
        when /\A--([^=]*)(?:=(.*))?/m
          opt, rest = $1, $2
          opt.tr!('_', '-')
          begin
            sw, = complete(:long, opt, true)
            if require_exact && !sw.long.include?(arg)
              raise InvalidOption, arg
            end
          rescue ParseError
            raise $!.set_option(arg, true)
          end
          begin
            opt, cb, val = sw.parse(rest, argv) {|*exc| raise(*exc)}
            val = cb.call(val) if cb
            setter.call(sw.switch_name, val) if setter
          rescue ParseError
            raise $!.set_option(arg, rest)
          end

        # short option
        when /\A-(.)((=).*|.+)?/m
          eq, rest, opt = $3, $2, $1
          has_arg, val = eq, rest
          begin
            sw, = search(:short, opt)
            unless sw
              begin
                sw, = complete(:short, opt)
                # short option matched.
                val = arg.delete_prefix('-')
                has_arg = true
              rescue InvalidOption
                raise if require_exact
                # if no short options match, try completion with long
                # options.
                sw, = complete(:long, opt)
                eq ||= !rest
              end
            end
          rescue ParseError
            raise $!.set_option(arg, true)
          end
          begin
            opt, cb, val = sw.parse(val, argv) {|*exc| raise(*exc) if eq}
          rescue ParseError
            raise $!.set_option(arg, arg.length > 2)
          else
            raise InvalidOption, arg if has_arg and !eq and arg == "-#{opt}"
          end
          begin
            argv.unshift(opt) if opt and (!rest or (opt = opt.sub(/\A-*/, '-')) != '-')
            val = cb.call(val) if cb
            setter.call(sw.switch_name, val) if setter
          rescue ParseError
            raise $!.set_option(arg, arg.length > 2)
          end

        # non-option argument
        else
          catch(:prune) do
            visit(:each_option) do |sw0|
              sw = sw0
              sw.block.call(arg) if Switch === sw and sw.match_nonswitch?(arg)
            end
            nonopt.call(arg)
          end
        end
      end

      nil
    }

    visit(:search, :short, nil) {|sw| sw.block.call(*argv) if !sw.pattern}

    argv
  end
  private :parse_in_order

  #
  # Parses command line arguments +argv+ in permutation mode and returns
  # list of non-option arguments. When optional +into+ keyword
  # argument is provided, the parsed option values are stored there via
  # <code>[]=</code> method (so it can be Hash, or OpenStruct, or other
  # similar object).
  #
  def permute(*argv, into: nil)
    argv = argv[0].dup if argv.size == 1 and Array === argv[0]
    permute!(argv, into: into)
  end

  #
  # Same as #permute, but removes switches destructively.
  # Non-option arguments remain in +argv+.
  #
  def permute!(argv = default_argv, into: nil)
    nonopts = []
    order!(argv, into: into, &nonopts.method(:<<))
    argv[0, 0] = nonopts
    argv
  end

  #
  # Parses command line arguments +argv+ in order when environment variable
  # POSIXLY_CORRECT is set, and in permutation mode otherwise.
  # When optional +into+ keyword argument is provided, the parsed option
  # values are stored there via <code>[]=</code> method (so it can be Hash,
  # or OpenStruct, or other similar object).
  #
  def parse(*argv, into: nil)
    argv = argv[0].dup if argv.size == 1 and Array === argv[0]
    parse!(argv, into: into)
  end

  #
  # Same as #parse, but removes switches destructively.
  # Non-option arguments remain in +argv+.
  #
  def parse!(argv = default_argv, into: nil)
    if ENV.include?('POSIXLY_CORRECT')
      order!(argv, into: into)
    else
      permute!(argv, into: into)
    end
  end

  #
  # Wrapper method for getopts.rb.
  #
  #   params = ARGV.getopts("ab:", "foo", "bar:", "zot:Z;zot option")
  #   # params["a"] = true   # -a
  #   # params["b"] = "1"    # -b1
  #   # params["foo"] = "1"  # --foo
  #   # params["bar"] = "x"  # --bar x
  #   # params["zot"] = "z"  # --zot Z
  #
  def getopts(*args)
    argv = Array === args.first ? args.shift : default_argv
    single_options, *long_options = *args

    result = {}

    single_options.scan(/(.)(:)?/) do |opt, val|
      if val
        result[opt] = nil
        define("-#{opt} VAL")
      else
        result[opt] = false
        define("-#{opt}")
      end
    end if single_options

    long_options.each do |arg|
      arg, desc = arg.split(';', 2)
      opt, val = arg.split(':', 2)
      if val
        result[opt] = val.empty? ? nil : val
        define("--#{opt}=#{result[opt] || "VAL"}", *[desc].compact)
      else
        result[opt] = false
        define("--#{opt}", *[desc].compact)
      end
    end

    parse_in_order(argv, result.method(:[]=))
    result
  end

  #
  # See #getopts.
  #
  def self.getopts(*args)
    new.getopts(*args)
  end

  #
  # Traverses @stack, sending each element method +id+ with +args+ and
  # +block+.
  #
  def visit(id, *args, &block)
    @stack.reverse_each do |el|
      el.__send__(id, *args, &block)
    end
    nil
  end
  private :visit

  #
  # Searches +key+ in @stack for +id+ hash and returns or yields the result.
  #
  def search(id, key)
    block_given = block_given?
    visit(:search, id, key) do |k|
      return block_given ? yield(k) : k
    end
  end
  private :search

  #
  # Completes shortened long style option switch and returns pair of
  # canonical switch and switch descriptor OptionParser::Switch.
  #
  # +typ+::   Searching table.
  # +opt+::   Searching key.
  # +icase+:: Search case insensitive if true.
  # +pat+::   Optional pattern for completion.
  #
  def complete(typ, opt, icase = false, *pat)
    if pat.empty?
      search(typ, opt) {|sw| return [sw, opt]} # exact match or...
    end
    ambiguous = catch(:ambiguous) {
      visit(:complete, typ, opt, icase, *pat) {|o, *sw| return sw}
    }
    exc = ambiguous ? AmbiguousOption : InvalidOption
    raise exc.new(opt, additional: self.method(:additional_message).curry[typ])
  end
  private :complete

  #
  # Returns additional info.
  #
  def additional_message(typ, opt)
    return unless typ and opt and defined?(DidYouMean::SpellChecker)
    all_candidates = []
    visit(:get_candidates, typ) do |candidates|
      all_candidates.concat(candidates)
    end
    all_candidates.select! {|cand| cand.is_a?(String) }
    checker = DidYouMean::SpellChecker.new(dictionary: all_candidates)
    DidYouMean.formatter.message_for(all_candidates & checker.correct(opt))
  end

  def candidate(word)
    list = []
    case word
    when '-'
      long = short = true
    when /\A--/
      word, arg = word.split(/=/, 2)
      argpat = Completion.regexp(arg, false) if arg and !arg.empty?
      long = true
    when /\A-/
      short = true
    end
    pat = Completion.regexp(word, long)
    visit(:each_option) do |opt|
      next unless Switch === opt
      opts = (long ? opt.long : []) + (short ? opt.short : [])
      opts = Completion.candidate(word, true, pat, &opts.method(:each)).map(&:first) if pat
      if /\A=/ =~ opt.arg
        opts.map! {|sw| sw + "="}
        if arg and CompletingHash === opt.pattern
          if opts = opt.pattern.candidate(arg, false, argpat)
            opts.map!(&:last)
          end
        end
      end
      list.concat(opts)
    end
    list
  end

  #
  # Loads options from file names as +filename+. Does nothing when the file
  # is not present. Returns whether successfully loaded.
  #
  # +filename+ defaults to basename of the program without suffix in a
  # directory ~/.options, then the basename with '.options' suffix
  # under XDG and Haiku standard places.
  #
  def load(filename = nil)
    unless filename
      basename = File.basename($0, '.*')
      return true if load(File.expand_path(basename, '~/.options')) rescue nil
      basename << ".options"
      return [
        # XDG
        ENV['XDG_CONFIG_HOME'],
        '~/.config',
        *ENV['XDG_CONFIG_DIRS']&.split(File::PATH_SEPARATOR),

        # Haiku
        '~/config/settings',
      ].any? {|dir|
        next if !dir or dir.empty?
        load(File.expand_path(basename, dir)) rescue nil
      }
    end
    begin
      parse(*IO.readlines(filename).each {|s| s.chomp!})
      true
    rescue Errno::ENOENT, Errno::ENOTDIR
      false
    end
  end

  #
  # Parses environment variable +env+ or its uppercase with splitting like a
  # shell.
  #
  # +env+ defaults to the basename of the program.
  #
  def environment(env = File.basename($0, '.*'))
    env = ENV[env] || ENV[env.upcase] or return
    require 'shellwords'
    parse(*Shellwords.shellwords(env))
  end

  #
  # Acceptable argument classes
  #

  #
  # Any string and no conversion. This is fall-back.
  #
  accept(Object) {|s,|s or s.nil?}

  accept(NilClass) {|s,|s}

  #
  # Any non-empty string, and no conversion.
  #
  accept(String, /.+/m) {|s,*|s}

  #
  # Ruby/C-like integer, octal for 0-7 sequence, binary for 0b, hexadecimal
  # for 0x, and decimal for others; with optional sign prefix. Converts to
  # Integer.
  #
  decimal = '\d+(?:_\d+)*'
  binary = 'b[01]+(?:_[01]+)*'
  hex = 'x[\da-f]+(?:_[\da-f]+)*'
  octal = "0(?:[0-7]+(?:_[0-7]+)*|#{binary}|#{hex})?"
  integer = "#{octal}|#{decimal}"

  accept(Integer, %r"\A[-+]?(?:#{integer})\z"io) {|s,|
    begin
      Integer(s)
    rescue ArgumentError
      raise OptionParser::InvalidArgument, s
    end if s
  }

  #
  # Float number format, and converts to Float.
  #
  float = "(?:#{decimal}(?=(.)?)(?:\\.(?:#{decimal})?)?|\\.#{decimal})(?:E[-+]?#{decimal})?"
  floatpat = %r"\A[-+]?#{float}\z"io
  accept(Float, floatpat) {|s,| s.to_f if s}

  #
  # Generic numeric format, converts to Integer for integer format, Float
  # for float format, and Rational for rational format.
  #
  real = "[-+]?(?:#{octal}|#{float})"
  accept(Numeric, /\A(#{real})(?:\/(#{real}))?\z/io) {|s, d, f, n,|
    if n
      Rational(d, n)
    elsif f
      Float(s)
    else
      Integer(s)
    end
  }

  #
  # Decimal integer format, to be converted to Integer.
  #
  DecimalInteger = /\A[-+]?#{decimal}\z/io
  accept(DecimalInteger, DecimalInteger) {|s,|
    begin
      Integer(s, 10)
    rescue ArgumentError
      raise OptionParser::InvalidArgument, s
    end if s
  }

  #
  # Ruby/C like octal/hexadecimal/binary integer format, to be converted to
  # Integer.
  #
  OctalInteger = /\A[-+]?(?:[0-7]+(?:_[0-7]+)*|0(?:#{binary}|#{hex}))\z/io
  accept(OctalInteger, OctalInteger) {|s,|
    begin
      Integer(s, 8)
    rescue ArgumentError
      raise OptionParser::InvalidArgument, s
    end if s
  }

  #
  # Decimal integer/float number format, to be converted to Integer for
  # integer format, Float for float format.
  #
  DecimalNumeric = floatpat     # decimal integer is allowed as float also.
  accept(DecimalNumeric, floatpat) {|s, f|
    begin
      if f
        Float(s)
      else
        Integer(s)
      end
    rescue ArgumentError
      raise OptionParser::InvalidArgument, s
    end if s
  }

  #
  # Boolean switch, which means whether it is present or not, whether it is
  # absent or not with prefix no-, or it takes an argument
  # yes/no/true/false/+/-.
  #
  yesno = CompletingHash.new
  %w[- no false].each {|el| yesno[el] = false}
  %w[+ yes true].each {|el| yesno[el] = true}
  yesno['nil'] = false          # should be nil?
  accept(TrueClass, yesno) {|arg, val| val == nil or val}
  #
  # Similar to TrueClass, but defaults to false.
  #
  accept(FalseClass, yesno) {|arg, val| val != nil and val}

  #
  # List of strings separated by ",".
  #
  accept(Array) do |s, |
    if s
      s = s.split(',').collect {|ss| ss unless ss.empty?}
    end
    s
  end

  #
  # Regular expression with options.
  #
  accept(Regexp, %r"\A/((?:\\.|[^\\])*)/([[:alpha:]]+)?\z|.*") do |all, s, o|
    f = 0
    if o
      f |= Regexp::IGNORECASE if /i/ =~ o
      f |= Regexp::MULTILINE if /m/ =~ o
      f |= Regexp::EXTENDED if /x/ =~ o
      k = o.delete("imx")
      k = nil if k.empty?
    end
    Regexp.new(s || all, f, k)
  end

  #
  # Exceptions
  #

  #
  # Base class of exceptions from OptionParser.
  #
  class ParseError < RuntimeError
    # Reason which caused the error.
    Reason = 'parse error'

    def initialize(*args, additional: nil)
      @additional = additional
      @arg0, = args
      @args = args
      @reason = nil
    end

    attr_reader :args
    attr_writer :reason
    attr_accessor :additional

    #
    # Pushes back erred argument(s) to +argv+.
    #
    def recover(argv)
      argv[0, 0] = @args
      argv
    end

    def self.filter_backtrace(array)
      unless $DEBUG
        array.delete_if(&%r"\A#{Regexp.quote(__FILE__)}:"o.method(:=~))
      end
      array
    end

    def set_backtrace(array)
      super(self.class.filter_backtrace(array))
    end

    def set_option(opt, eq)
      if eq
        @args[0] = opt
      else
        @args.unshift(opt)
      end
      self
    end

    #
    # Returns error reason. Override this for I18N.
    #
    def reason
      @reason || self.class::Reason
    end

    def inspect
      "#<#{self.class}: #{args.join(' ')}>"
    end

    #
    # Default stringizing method to emit standard error message.
    #
    def message
      "#{reason}: #{args.join(' ')}#{additional[@arg0] if additional}"
    end

    alias to_s message
  end

  #
  # Raises when ambiguously completable string is encountered.
  #
  class AmbiguousOption < ParseError
    const_set(:Reason, 'ambiguous option')
  end

  #
  # Raises when there is an argument for a switch which takes no argument.
  #
  class NeedlessArgument < ParseError
    const_set(:Reason, 'needless argument')
  end

  #
  # Raises when a switch with mandatory argument has no argument.
  #
  class MissingArgument < ParseError
    const_set(:Reason, 'missing argument')
  end

  #
  # Raises when switch is undefined.
  #
  class InvalidOption < ParseError
    const_set(:Reason, 'invalid option')
  end

  #
  # Raises when the given argument does not match required format.
  #
  class InvalidArgument < ParseError
    const_set(:Reason, 'invalid argument')
  end

  #
  # Raises when the given argument word can't be completed uniquely.
  #
  class AmbiguousArgument < InvalidArgument
    const_set(:Reason, 'ambiguous argument')
  end

  #
  # Miscellaneous
  #

  #
  # Extends command line arguments array (ARGV) to parse itself.
  #
  module Arguable

    #
    # Sets OptionParser object, when +opt+ is +false+ or +nil+, methods
    # OptionParser::Arguable#options and OptionParser::Arguable#options= are
    # undefined. Thus, there is no ways to access the OptionParser object
    # via the receiver object.
    #
    def options=(opt)
      unless @optparse = opt
        class << self
          undef_method(:options)
          undef_method(:options=)
        end
      end
    end

    #
    # Actual OptionParser object, automatically created if nonexistent.
    #
    # If called with a block, yields the OptionParser object and returns the
    # result of the block. If an OptionParser::ParseError exception occurs
    # in the block, it is rescued, a error message printed to STDERR and
    # +nil+ returned.
    #
    def options
      @optparse ||= OptionParser.new
      @optparse.default_argv = self
      block_given? or return @optparse
      begin
        yield @optparse
      rescue ParseError
        @optparse.warn $!
        nil
      end
    end

    #
    # Parses +self+ destructively in order and returns +self+ containing the
    # rest arguments left unparsed.
    #
    def order!(&blk) options.order!(self, &blk) end

    #
    # Parses +self+ destructively in permutation mode and returns +self+
    # containing the rest arguments left unparsed.
    #
    def permute!() options.permute!(self) end

    #
    # Parses +self+ destructively and returns +self+ containing the
    # rest arguments left unparsed.
    #
    def parse!() options.parse!(self) end

    #
    # Substitution of getopts is possible as follows. Also see
    # OptionParser#getopts.
    #
    #   def getopts(*args)
    #     ($OPT = ARGV.getopts(*args)).each do |opt, val|
    #       eval "$OPT_#{opt.gsub(/[^A-Za-z0-9_]/, '_')} = val"
    #     end
    #   rescue OptionParser::ParseError
    #   end
    #
    def getopts(*args)
      options.getopts(self, *args)
    end

    #
    # Initializes instance variable.
    #
    def self.extend_object(obj)
      super
      obj.instance_eval {@optparse = nil}
    end
    def initialize(*args)
      super
      @optparse = nil
    end
  end

  #
  # Acceptable argument classes. Now contains DecimalInteger, OctalInteger
  # and DecimalNumeric. See Acceptable argument classes (in source code).
  #
  module Acceptables
    const_set(:DecimalInteger, OptionParser::DecimalInteger)
    const_set(:OctalInteger, OptionParser::OctalInteger)
    const_set(:DecimalNumeric, OptionParser::DecimalNumeric)
  end
end

# ARGV is arguable by OptionParser
ARGV.extend(OptionParser::Arguable)

# An alias for OptionParser.
OptParse = OptionParser  # :nodoc:
# frozen_string_literal: false
#
# YAML::Store
#
require 'yaml'
require 'pstore'

# YAML::Store provides the same functionality as PStore, except it uses YAML
# to dump objects instead of Marshal.
#
# == Example
#
#   require 'yaml/store'
#
#   Person = Struct.new :first_name, :last_name
#
#   people = [Person.new("Bob", "Smith"), Person.new("Mary", "Johnson")]
#
#   store = YAML::Store.new "test.store"
#
#   store.transaction do
#     store["people"] = people
#     store["greeting"] = { "hello" => "world" }
#   end
#
# After running the above code, the contents of "test.store" will be:
#
#   ---
#   people:
#   - !ruby/struct:Person
#     first_name: Bob
#     last_name: Smith
#   - !ruby/struct:Person
#     first_name: Mary
#     last_name: Johnson
#   greeting:
#     hello: world

class YAML::Store < PStore

  # :call-seq:
  #   initialize( file_name, yaml_opts = {} )
  #   initialize( file_name, thread_safe = false, yaml_opts = {} )
  #
  # Creates a new YAML::Store object, which will store data in +file_name+.
  # If the file does not already exist, it will be created.
  #
  # YAML::Store objects are always reentrant. But if _thread_safe_ is set to true,
  # then it will become thread-safe at the cost of a minor performance hit.
  #
  # Options passed in through +yaml_opts+ will be used when converting the
  # store to YAML via Hash#to_yaml().
  def initialize( *o )
    @opt = {}
    if o.last.is_a? Hash
      @opt.update(o.pop)
    end
    super(*o)
  end

  # :stopdoc:

  def dump(table)
    table.to_yaml(@opt)
  end

  def load(content)
    table = YAML.load(content)
    if table == false
      {}
    else
      table
    end
  end

  def marshal_dump_supports_canonical_option?
    false
  end

  def empty_marshal_data
    {}.to_yaml(@opt)
  end
  def empty_marshal_checksum
    CHECKSUM_ALGO.digest(empty_marshal_data)
  end
end
# frozen_string_literal: false
require 'yaml'
require 'dbm'

module YAML

# YAML + DBM = YDBM
#
# YAML::DBM provides the same interface as ::DBM.
#
# However, while DBM only allows strings for both keys and values,
# this library allows one to use most Ruby objects for values
# by first converting them to YAML. Keys must be strings.
#
# Conversion to and from YAML is performed automatically.
#
# See the documentation for ::DBM and ::YAML for more information.
class DBM < ::DBM
    VERSION = "0.1" # :nodoc:

    # :call-seq:
    #   ydbm[key] -> value
    #
    # Return value associated with +key+ from database.
    #
    # Returns +nil+ if there is no such +key+.
    #
    # See #fetch for more information.
    def []( key )
        fetch( key )
    end

    # :call-seq:
    #   ydbm[key] = value
    #
    # Set +key+ to +value+ in database.
    #
    # +value+ will be converted to YAML before storage.
    #
    # See #store for more information.
    def []=( key, val )
        store( key, val )
    end

    # :call-seq:
    #   ydbm.fetch( key, ifnone = nil )
    #   ydbm.fetch( key ) { |key| ... }
    #
    # Return value associated with +key+.
    #
    # If there is no value for +key+ and no block is given, returns +ifnone+.
    #
    # Otherwise, calls block passing in the given +key+.
    #
    # See ::DBM#fetch for more information.
    def fetch( keystr, ifnone = nil )
        begin
            val = super( keystr )
            return YAML.load( val ) if String === val
        rescue IndexError
        end
        if block_given?
            yield keystr
        else
            ifnone
        end
    end

    # Deprecated, used YAML::DBM#key instead.
    # ----
    # Note:
    # YAML::DBM#index makes warning from internal of ::DBM#index.
    # It says 'DBM#index is deprecated; use DBM#key', but DBM#key
    # behaves not same as DBM#index.
    #
    def index( keystr )
        super( keystr.to_yaml )
    end

    # :call-seq:
    #   ydbm.key(value) -> string
    #
    # Returns the key for the specified value.
    def key( keystr )
        invert[keystr]
    end

    # :call-seq:
    #   ydbm.values_at(*keys)
    #
    # Returns an array containing the values associated with the given keys.
    def values_at( *keys )
        keys.collect { |k| fetch( k ) }
    end

    # :call-seq:
    #   ydbm.delete(key)
    #
    # Deletes value from database associated with +key+.
    #
    # Returns value or +nil+.
    def delete( key )
        v = super( key )
        if String === v
            v = YAML.load( v )
        end
        v
    end

    # :call-seq:
    #   ydbm.delete_if { |key, value| ... }
    #
    # Calls the given block once for each +key+, +value+ pair in the database.
    # Deletes all entries for which the block returns true.
    #
    # Returns +self+.
    def delete_if # :yields: [key, value]
        del_keys = keys.dup
        del_keys.delete_if { |k| yield( k, fetch( k ) ) == false }
        del_keys.each { |k| delete( k ) }
        self
    end

    # :call-seq:
    #   ydbm.reject { |key, value| ... }
    #
    # Converts the contents of the database to an in-memory Hash, then calls
    # Hash#reject with the specified code block, returning a new Hash.
    def reject
        hsh = self.to_hash
        hsh.reject { |k,v| yield k, v }
    end

    # :call-seq:
    #   ydbm.each_pair { |key, value| ... }
    #
    # Calls the given block once for each +key+, +value+ pair in the database.
    #
    # Returns +self+.
    def each_pair # :yields: [key, value]
        keys.each { |k| yield k, fetch( k ) }
        self
    end

    # :call-seq:
    #   ydbm.each_value { |value| ... }
    #
    # Calls the given block for each value in database.
    #
    # Returns +self+.
    def each_value # :yields: value
        super { |v| yield YAML.load( v ) }
        self
    end

    # :call-seq:
    #   ydbm.values
    #
    # Returns an array of values from the database.
    def values
        super.collect { |v| YAML.load( v ) }
    end

    # :call-seq:
    #   ydbm.has_value?(value)
    #
    # Returns true if specified +value+ is found in the database.
    def has_value?( val )
        each_value { |v| return true if v == val }
        return false
    end

    # :call-seq:
    #   ydbm.invert -> hash
    #
    # Returns a Hash (not a DBM database) created by using each value in the
    # database as a key, with the corresponding key as its value.
    #
    # Note that all values in the hash will be Strings, but the keys will be
    # actual objects.
    def invert
        h = {}
        keys.each { |k| h[ self.fetch( k ) ] = k }
        h
    end

    # :call-seq:
    #   ydbm.replace(hash) -> ydbm
    #
    # Replaces the contents of the database with the contents of the specified
    # object. Takes any object which implements the each_pair method, including
    # Hash and DBM objects.
    def replace( hsh )
        clear
        update( hsh )
    end

    # :call-seq:
    #   ydbm.shift -> [key, value]
    #
    # Removes a [key, value] pair from the database, and returns it.
    # If the database is empty, returns +nil+.
    #
    # The order in which values are removed/returned is not guaranteed.
    def shift
        a = super
        a[1] = YAML.load( a[1] ) if a
        a
    end

    # :call-seq:
    #   ydbm.select { |key, value| ... }
    #   ydbm.select(*keys)
    #
    # If a block is provided, returns a new array containing [key, value] pairs
    # for which the block returns true.
    #
    # Otherwise, same as #values_at
    def select( *keys )
        if block_given?
            self.keys.collect { |k| v = self[k]; [k, v] if yield k, v }.compact
        else
            values_at( *keys )
        end
    end

    # :call-seq:
    #   ydbm.store(key, value) -> value
    #
    # Stores +value+ in database with +key+ as the index. +value+ is converted
    # to YAML before being stored.
    #
    # Returns +value+
    def store( key, val )
        super( key, val.to_yaml )
        val
    end

    # :call-seq:
    #   ydbm.update(hash) -> ydbm
    #
    # Updates the database with multiple values from the specified object.
    # Takes any object which implements the each_pair method, including
    # Hash and DBM objects.
    #
    # Returns +self+.
    def update( hsh )
        hsh.each_pair do |k,v|
            self.store( k, v )
        end
        self
    end

    # :call-seq:
    #   ydbm.to_a -> array
    #
    # Converts the contents of the database to an array of [key, value] arrays,
    # and returns it.
    def to_a
        a = []
        keys.each { |k| a.push [ k, self.fetch( k ) ] }
        a
    end


    # :call-seq:
    #   ydbm.to_hash -> hash
    #
    # Converts the contents of the database to an in-memory Hash object, and
    # returns it.
    def to_hash
        h = {}
        keys.each { |k| h[ k ] = self.fetch( k ) }
        h
    end

    alias :each :each_pair
end

end
# frozen_string_literal: true

class CSV
  # Note: Don't use this class directly. This is an internal class.
  class FieldsConverter
    include Enumerable
    #
    # A CSV::FieldsConverter is a data structure for storing the
    # fields converter properties to be passed as a parameter
    # when parsing a new file (e.g. CSV::Parser.new(@io, parser_options))
    #

    def initialize(options={})
      @converters = []
      @nil_value = options[:nil_value]
      @empty_value = options[:empty_value]
      @empty_value_is_empty_string = (@empty_value == "")
      @accept_nil = options[:accept_nil]
      @builtin_converters = options[:builtin_converters]
      @need_static_convert = need_static_convert?
    end

    def add_converter(name=nil, &converter)
      if name.nil?  # custom converter
        @converters << converter
      else          # named converter
        combo = @builtin_converters[name]
        case combo
        when Array  # combo converter
          combo.each do |sub_name|
            add_converter(sub_name)
          end
        else        # individual named converter
          @converters << combo
        end
      end
    end

    def each(&block)
      @converters.each(&block)
    end

    def empty?
      @converters.empty?
    end

    def convert(fields, headers, lineno)
      return fields unless need_convert?

      fields.collect.with_index do |field, index|
        if field.nil?
          field = @nil_value
        elsif field.is_a?(String) and field.empty?
          field = @empty_value unless @empty_value_is_empty_string
        end
        @converters.each do |converter|
          break if field.nil? and @accept_nil
          if converter.arity == 1  # straight field converter
            field = converter[field]
          else                     # FieldInfo converter
            if headers
              header = headers[index]
            else
              header = nil
            end
            field = converter[field, FieldInfo.new(index, lineno, header)]
          end
          break unless field.is_a?(String)  # short-circuit pipeline for speed
        end
        field  # final state of each field, converted or original
      end
    end

    private
    def need_static_convert?
      not (@nil_value.nil? and @empty_value_is_empty_string)
    end

    def need_convert?
      @need_static_convert or
        (not @converters.empty?)
    end
  end
end
# frozen_string_literal: true

require "forwardable"

class CSV
  #
  # A CSV::Table is a two-dimensional data structure for representing CSV
  # documents. Tables allow you to work with the data by row or column,
  # manipulate the data, and even convert the results back to CSV, if needed.
  #
  # All tables returned by CSV will be constructed from this class, if header
  # row processing is activated.
  #
  class Table
    #
    # Constructs a new CSV::Table from +array_of_rows+, which are expected
    # to be CSV::Row objects. All rows are assumed to have the same headers.
    #
    # The optional +headers+ parameter can be set to Array of headers.
    # If headers aren't set, headers are fetched from CSV::Row objects.
    # Otherwise, headers() method will return headers being set in
    # headers argument.
    #
    # A CSV::Table object supports the following Array methods through
    # delegation:
    #
    # * empty?()
    # * length()
    # * size()
    #
    def initialize(array_of_rows, headers: nil)
      @table = array_of_rows
      @headers = headers
      unless @headers
        if @table.empty?
          @headers = []
        else
          @headers = @table.first.headers
        end
      end

      @mode  = :col_or_row
    end

    # The current access mode for indexing and iteration.
    attr_reader :mode

    # Internal data format used to compare equality.
    attr_reader :table
    protected   :table

    ### Array Delegation ###

    extend Forwardable
    def_delegators :@table, :empty?, :length, :size

    #
    # Returns a duplicate table object, in column mode. This is handy for
    # chaining in a single call without changing the table mode, but be aware
    # that this method can consume a fair amount of memory for bigger data sets.
    #
    # This method returns the duplicate table for chaining. Don't chain
    # destructive methods (like []=()) this way though, since you are working
    # with a duplicate.
    #
    def by_col
      self.class.new(@table.dup).by_col!
    end

    #
    # Switches the mode of this table to column mode. All calls to indexing and
    # iteration methods will work with columns until the mode is changed again.
    #
    # This method returns the table and is safe to chain.
    #
    def by_col!
      @mode = :col

      self
    end

    #
    # Returns a duplicate table object, in mixed mode. This is handy for
    # chaining in a single call without changing the table mode, but be aware
    # that this method can consume a fair amount of memory for bigger data sets.
    #
    # This method returns the duplicate table for chaining.  Don't chain
    # destructive methods (like []=()) this way though, since you are working
    # with a duplicate.
    #
    def by_col_or_row
      self.class.new(@table.dup).by_col_or_row!
    end

    #
    # Switches the mode of this table to mixed mode. All calls to indexing and
    # iteration methods will use the default intelligent indexing system until
    # the mode is changed again. In mixed mode an index is assumed to be a row
    # reference while anything else is assumed to be column access by headers.
    #
    # This method returns the table and is safe to chain.
    #
    def by_col_or_row!
      @mode = :col_or_row

      self
    end

    #
    # Returns a duplicate table object, in row mode.  This is handy for chaining
    # in a single call without changing the table mode, but be aware that this
    # method can consume a fair amount of memory for bigger data sets.
    #
    # This method returns the duplicate table for chaining.  Don't chain
    # destructive methods (like []=()) this way though, since you are working
    # with a duplicate.
    #
    def by_row
      self.class.new(@table.dup).by_row!
    end

    #
    # Switches the mode of this table to row mode. All calls to indexing and
    # iteration methods will work with rows until the mode is changed again.
    #
    # This method returns the table and is safe to chain.
    #
    def by_row!
      @mode = :row

      self
    end

    #
    # Returns the headers for the first row of this table (assumed to match all
    # other rows). The headers Array passed to CSV::Table.new is returned for
    # empty tables.
    #
    def headers
      if @table.empty?
        @headers.dup
      else
        @table.first.headers
      end
    end

    # :call-seq:
    #   table[n] -> row
    #   table[range] -> array_of_rows
    #   table[header] -> array_of_fields
    #
    # Returns data from the table;  does not modify the table.
    #
    # ---
    #
    # The expression <tt>table[n]</tt>, where +n+ is a non-negative \Integer,
    # returns the +n+th row of the table, if that row exists,
    # and if the access mode is <tt>:row</tt> or <tt>:col_or_row</tt>:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   table.by_row! # => #<CSV::Table mode:row row_count:4>
    #   table[1] # => #<CSV::Row "Name":"bar" "Value":"1">
    #   table.by_col_or_row! # => #<CSV::Table mode:col_or_row row_count:4>
    #   table[1] # => #<CSV::Row "Name":"bar" "Value":"1">
    #
    # Counts backward from the last row if +n+ is negative:
    #   table[-1] # => #<CSV::Row "Name":"baz" "Value":"2">
    #
    # Returns +nil+ if +n+ is too large or too small:
    #   table[4] # => nil
    #   table[-4] => nil
    #
    # Raises an exception if the access mode is <tt>:row</tt>
    # and +n+ is not an
    # {Integer-convertible object}[https://docs.ruby-lang.org/en/master/implicit_conversion_rdoc.html#label-Integer-Convertible+Objects].
    #   table.by_row! # => #<CSV::Table mode:row row_count:4>
    #   # Raises TypeError (no implicit conversion of String into Integer):
    #   table['Name']
    #
    # ---
    #
    # The expression <tt>table[range]</tt>, where +range+ is a Range object,
    # returns rows from the table, beginning at row <tt>range.first</tt>,
    # if those rows exist, and if the access mode is <tt>:row</tt> or <tt>:col_or_row</tt>:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   table.by_row! # => #<CSV::Table mode:row row_count:4>
    #   rows = table[1..2] # => #<CSV::Row "Name":"bar" "Value":"1">
    #   rows # => [#<CSV::Row "Name":"bar" "Value":"1">, #<CSV::Row "Name":"baz" "Value":"2">]
    #   table.by_col_or_row! # => #<CSV::Table mode:col_or_row row_count:4>
    #   rows = table[1..2] # => #<CSV::Row "Name":"bar" "Value":"1">
    #   rows # => [#<CSV::Row "Name":"bar" "Value":"1">, #<CSV::Row "Name":"baz" "Value":"2">]
    #
    # If there are too few rows, returns all from <tt>range.first</tt> to the end:
    #   rows = table[1..50] # => #<CSV::Row "Name":"bar" "Value":"1">
    #   rows # => [#<CSV::Row "Name":"bar" "Value":"1">, #<CSV::Row "Name":"baz" "Value":"2">]
    #
    # Special case:  if <tt>range.start == table.size</tt>, returns an empty \Array:
    #   table[table.size..50] # => []
    #
    # If <tt>range.end</tt> is negative, calculates the ending index from the end:
    #   rows = table[0..-1]
    #   rows # => [#<CSV::Row "Name":"foo" "Value":"0">, #<CSV::Row "Name":"bar" "Value":"1">, #<CSV::Row "Name":"baz" "Value":"2">]
    #
    # If <tt>range.start</tt> is negative, calculates the starting index from the end:
    #   rows = table[-1..2]
    #   rows # => [#<CSV::Row "Name":"baz" "Value":"2">]
    #
    # If <tt>range.start</tt> is larger than <tt>table.size</tt>, returns +nil+:
    #   table[4..4] # => nil
    #
    # ---
    #
    # The expression <tt>table[header]</tt>, where +header+ is a \String,
    # returns column values (\Array of \Strings) if the column exists
    # and if the access mode is <tt>:col</tt> or <tt>:col_or_row</tt>:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   table.by_col! # => #<CSV::Table mode:col row_count:4>
    #   table['Name'] # => ["foo", "bar", "baz"]
    #   table.by_col_or_row! # => #<CSV::Table mode:col_or_row row_count:4>
    #   col = table['Name']
    #   col # => ["foo", "bar", "baz"]
    #
    # Modifying the returned column values does not modify the table:
    #   col[0] = 'bat'
    #   col # => ["bat", "bar", "baz"]
    #   table['Name'] # => ["foo", "bar", "baz"]
    #
    # Returns an \Array of +nil+ values if there is no such column:
    #   table['Nosuch'] # => [nil, nil, nil]
    def [](index_or_header)
      if @mode == :row or  # by index
         (@mode == :col_or_row and (index_or_header.is_a?(Integer) or index_or_header.is_a?(Range)))
        @table[index_or_header]
      else                 # by header
        @table.map { |row| row[index_or_header] }
      end
    end

    #
    # In the default mixed mode, this method assigns rows for index access and
    # columns for header access. You can force the index association by first
    # calling by_col!() or by_row!().
    #
    # Rows may be set to an Array of values (which will inherit the table's
    # headers()) or a CSV::Row.
    #
    # Columns may be set to a single value, which is copied to each row of the
    # column, or an Array of values. Arrays of values are assigned to rows top
    # to bottom in row major order. Excess values are ignored and if the Array
    # does not have a value for each row the extra rows will receive a +nil+.
    #
    # Assigning to an existing column or row clobbers the data. Assigning to
    # new columns creates them at the right end of the table.
    #
    def []=(index_or_header, value)
      if @mode == :row or  # by index
         (@mode == :col_or_row and index_or_header.is_a? Integer)
        if value.is_a? Array
          @table[index_or_header] = Row.new(headers, value)
        else
          @table[index_or_header] = value
        end
      else                 # set column
        unless index_or_header.is_a? Integer
          index = @headers.index(index_or_header) || @headers.size
          @headers[index] = index_or_header
        end
        if value.is_a? Array  # multiple values
          @table.each_with_index do |row, i|
            if row.header_row?
              row[index_or_header] = index_or_header
            else
              row[index_or_header] = value[i]
            end
          end
        else                  # repeated value
          @table.each do |row|
            if row.header_row?
              row[index_or_header] = index_or_header
            else
              row[index_or_header] = value
            end
          end
        end
      end
    end

    # :call-seq:
    #   table.values_at(*indexes) -> array_of_rows
    #   table.values_at(*headers) -> array_of_columns_data
    #
    # If the access mode is <tt>:row</tt> or <tt>:col_or_row</tt>,
    # and each argument is either an \Integer or a \Range,
    # returns rows.
    # Otherwise, returns columns data.
    #
    # In either case, the returned values are in the order
    # specified by the arguments.  Arguments may be repeated.
    #
    # ---
    #
    # Returns rows as an \Array of \CSV::Row objects.
    #
    # No argument:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   table.values_at # => []
    #
    # One index:
    #   values = table.values_at(0)
    #   values # => [#<CSV::Row "Name":"foo" "Value":"0">]
    #
    # Two indexes:
    #   values = table.values_at(2, 0)
    #   values # => [#<CSV::Row "Name":"baz" "Value":"2">, #<CSV::Row "Name":"foo" "Value":"0">]
    #
    # One \Range:
    #   values = table.values_at(1..2)
    #   values # => [#<CSV::Row "Name":"bar" "Value":"1">, #<CSV::Row "Name":"baz" "Value":"2">]
    #
    # \Ranges and indexes:
    #   values = table.values_at(0..1, 1..2, 0, 2)
    #   pp values
    # Output:
    #   [#<CSV::Row "Name":"foo" "Value":"0">,
    #    #<CSV::Row "Name":"bar" "Value":"1">,
    #    #<CSV::Row "Name":"bar" "Value":"1">,
    #    #<CSV::Row "Name":"baz" "Value":"2">,
    #    #<CSV::Row "Name":"foo" "Value":"0">,
    #    #<CSV::Row "Name":"baz" "Value":"2">]
    #
    # ---
    #
    # Returns columns data as row Arrays,
    # each consisting of the specified columns data for that row:
    #   values = table.values_at('Name')
    #   values # => [["foo"], ["bar"], ["baz"]]
    #   values = table.values_at('Value', 'Name')
    #   values # => [["0", "foo"], ["1", "bar"], ["2", "baz"]]
    def values_at(*indices_or_headers)
      if @mode == :row or  # by indices
         ( @mode == :col_or_row and indices_or_headers.all? do |index|
                                      index.is_a?(Integer)         or
                                      ( index.is_a?(Range)         and
                                        index.first.is_a?(Integer) and
                                        index.last.is_a?(Integer) )
                                    end )
        @table.values_at(*indices_or_headers)
      else                 # by headers
        @table.map { |row| row.values_at(*indices_or_headers) }
      end
    end

    # :call-seq:
    #   table << row_or_array -> self
    #
    # If +row_or_array+ is a \CSV::Row object,
    # it is appended to the table:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   table << CSV::Row.new(table.headers, ['bat', 3])
    #   table[3] # => #<CSV::Row "Name":"bat" "Value":3>
    #
    # If +row_or_array+ is an \Array, it is used to create a new
    # \CSV::Row object which is then appended to the table:
    #   table << ['bam', 4]
    #   table[4] # => #<CSV::Row "Name":"bam" "Value":4>
    def <<(row_or_array)
      if row_or_array.is_a? Array  # append Array
        @table << Row.new(headers, row_or_array)
      else                         # append Row
        @table << row_or_array
      end

      self # for chaining
    end

    #
    # :call-seq:
    #   table.push(*rows_or_arrays) -> self
    #
    # A shortcut for appending multiple rows. Equivalent to:
    #   rows.each {|row| self << row }
    #
    # Each argument may be either a \CSV::Row object or an \Array:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   rows = [
    #     CSV::Row.new(table.headers, ['bat', 3]),
    #     ['bam', 4]
    #   ]
    #   table.push(*rows)
    #   table[3..4] # => [#<CSV::Row "Name":"bat" "Value":3>, #<CSV::Row "Name":"bam" "Value":4>]
    def push(*rows)
      rows.each { |row| self << row }

      self # for chaining
    end

    # :call-seq:
    #   table.delete(*indexes) -> deleted_values
    #   table.delete(*headers) -> deleted_values
    #
    # If the access mode is <tt>:row</tt> or <tt>:col_or_row</tt>,
    # and each argument is either an \Integer or a \Range,
    # returns deleted rows.
    # Otherwise, returns deleted columns data.
    #
    # In either case, the returned values are in the order
    # specified by the arguments.  Arguments may be repeated.
    #
    # ---
    #
    # Returns rows as an \Array of \CSV::Row objects.
    #
    # One index:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   deleted_values = table.delete(0)
    #   deleted_values # => [#<CSV::Row "Name":"foo" "Value":"0">]
    #
    # Two indexes:
    #   table = CSV.parse(source, headers: true)
    #   deleted_values = table.delete(2, 0)
    #   deleted_values # => [#<CSV::Row "Name":"baz" "Value":"2">, #<CSV::Row "Name":"foo" "Value":"0">]
    #
    # ---
    #
    # Returns columns data as column Arrays.
    #
    # One header:
    #   table = CSV.parse(source, headers: true)
    #   deleted_values = table.delete('Name')
    #   deleted_values # => ["foo", "bar", "baz"]
    #
    # Two headers:
    #   table = CSV.parse(source, headers: true)
    #   deleted_values = table.delete('Value', 'Name')
    #   deleted_values # => [["0", "1", "2"], ["foo", "bar", "baz"]]
    def delete(*indexes_or_headers)
      if indexes_or_headers.empty?
        raise ArgumentError, "wrong number of arguments (given 0, expected 1+)"
      end
      deleted_values = indexes_or_headers.map do |index_or_header|
        if @mode == :row or  # by index
            (@mode == :col_or_row and index_or_header.is_a? Integer)
          @table.delete_at(index_or_header)
        else                 # by header
          if index_or_header.is_a? Integer
            @headers.delete_at(index_or_header)
          else
            @headers.delete(index_or_header)
          end
          @table.map { |row| row.delete(index_or_header).last }
        end
      end
      if indexes_or_headers.size == 1
        deleted_values[0]
      else
        deleted_values
      end
    end

    # Removes rows or columns for which the block returns a truthy value;
    # returns +self+.
    #
    # Removes rows when the access mode is <tt>:row</tt> or <tt>:col_or_row</tt>;
    # calls the block with each \CSV::Row object:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   table.by_row! # => #<CSV::Table mode:row row_count:4>
    #   table.size # => 3
    #   table.delete_if {|row| row['Name'].start_with?('b') }
    #   table.size # => 1
    #
    # Removes columns when the access mode is <tt>:col</tt>;
    # calls the block with each column as a 2-element array
    # containing the header and an \Array of column fields:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   table.by_col! # => #<CSV::Table mode:col row_count:4>
    #   table.headers.size # => 2
    #   table.delete_if {|column_data| column_data[1].include?('2') }
    #   table.headers.size # => 1
    #
    # Returns a new \Enumerator if no block is given:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   table.delete_if # => #<Enumerator: #<CSV::Table mode:col_or_row row_count:4>:delete_if>
    def delete_if(&block)
      return enum_for(__method__) { @mode == :row or @mode == :col_or_row ? size : headers.size } unless block_given?

      if @mode == :row or @mode == :col_or_row  # by index
        @table.delete_if(&block)
      else                                      # by header
        deleted = []
        headers.each do |header|
          deleted << delete(header) if yield([header, self[header]])
        end
      end

      self # for chaining
    end

    include Enumerable

    # Calls the block with each row or column; returns +self+.
    #
    # When the access mode is <tt>:row</tt> or <tt>:col_or_row</tt>,
    # calls the block with each \CSV::Row object:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   table.by_row! # => #<CSV::Table mode:row row_count:4>
    #   table.each {|row| p row }
    # Output:
    #   #<CSV::Row "Name":"foo" "Value":"0">
    #   #<CSV::Row "Name":"bar" "Value":"1">
    #   #<CSV::Row "Name":"baz" "Value":"2">
    #
    # When the access mode is <tt>:col</tt>,
    # calls the block with each column as a 2-element array
    # containing the header and an \Array of column fields:
    #   table.by_col! # => #<CSV::Table mode:col row_count:4>
    #   table.each {|column_data| p column_data }
    # Output:
    #   ["Name", ["foo", "bar", "baz"]]
    #   ["Value", ["0", "1", "2"]]
    #
    # Returns a new \Enumerator if no block is given:
    #   table.each # => #<Enumerator: #<CSV::Table mode:col row_count:4>:each>
    def each(&block)
      return enum_for(__method__) { @mode == :col ? headers.size : size } unless block_given?

      if @mode == :col
        headers.each { |header| yield([header, self[header]]) }
      else
        @table.each(&block)
      end

      self # for chaining
    end

    # Returns +true+ if all each row of +self+ <tt>==</tt>
    # the corresponding row of +other_table+, otherwise, +false+.
    #
    # The access mode does no affect the result.
    #
    # Equal tables:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   other_table = CSV.parse(source, headers: true)
    #   table == other_table # => true
    #
    # Different row count:
    #   other_table.delete(2)
    #   table == other_table # => false
    #
    # Different last row:
    #   other_table << ['bat', 3]
    #   table == other_table # => false
    def ==(other)
      return @table == other.table if other.is_a? CSV::Table
      @table == other
    end

    #
    # Returns the table as an Array of Arrays. Headers will be the first row,
    # then all of the field rows will follow.
    #
    def to_a
      array = [headers]
      @table.each do |row|
        array.push(row.fields) unless row.header_row?
      end

      array
    end

    #
    # Returns the table as a complete CSV String. Headers will be listed first,
    # then all of the field rows.
    #
    # This method assumes you want the Table.headers(), unless you explicitly
    # pass <tt>:write_headers => false</tt>.
    #
    def to_csv(write_headers: true, **options)
      array = write_headers ? [headers.to_csv(**options)] : []
      @table.each do |row|
        array.push(row.fields.to_csv(**options)) unless row.header_row?
      end

      array.join("")
    end
    alias_method :to_s, :to_csv

    #
    # Extracts the nested value specified by the sequence of +index+ or +header+ objects by calling dig at each step,
    # returning nil if any intermediate step is nil.
    #
    def dig(index_or_header, *index_or_headers)
      value = self[index_or_header]
      if value.nil?
        nil
      elsif index_or_headers.empty?
        value
      else
        unless value.respond_to?(:dig)
          raise TypeError, "#{value.class} does not have \#dig method"
        end
        value.dig(*index_or_headers)
      end
    end

    # Shows the mode and size of this table in a US-ASCII String.
    def inspect
      "#<#{self.class} mode:#{@mode} row_count:#{to_a.size}>".encode("US-ASCII")
    end
  end
end
# frozen_string_literal: true

# This provides String#delete_suffix? for Ruby 2.4.
unless String.method_defined?(:delete_suffix)
  class CSV
    module DeleteSuffix
      refine String do
        def delete_suffix(suffix)
          if end_with?(suffix)
            self[0...-suffix.size]
          else
            self
          end
        end
      end
    end
  end
end
# frozen_string_literal: true

require_relative "match_p"
require_relative "row"

using CSV::MatchP if CSV.const_defined?(:MatchP)

class CSV
  # Note: Don't use this class directly. This is an internal class.
  class Writer
    #
    # A CSV::Writer receives an output, prepares the header, format and output.
    # It allows us to write new rows in the object and rewind it.
    #
    attr_reader :lineno
    attr_reader :headers

    def initialize(output, options)
      @output = output
      @options = options
      @lineno = 0
      @fields_converter = nil
      prepare
      if @options[:write_headers] and @headers
        self << @headers
      end
      @fields_converter = @options[:fields_converter]
    end

    #
    # Adds a new row
    #
    def <<(row)
      case row
      when Row
        row = row.fields
      when Hash
        row = @headers.collect {|header| row[header]}
      end

      @headers ||= row if @use_headers
      @lineno += 1

      row = @fields_converter.convert(row, nil, lineno) if @fields_converter

      i = -1
      converted_row = row.collect do |field|
        i += 1
        quote(field, i)
      end
      line = converted_row.join(@column_separator) + @row_separator
      if @output_encoding
        line = line.encode(@output_encoding)
      end
      @output << line

      self
    end

    #
    # Winds back to the beginning
    #
    def rewind
      @lineno = 0
      @headers = nil if @options[:headers].nil?
    end

    private
    def prepare
      @encoding = @options[:encoding]

      prepare_header
      prepare_format
      prepare_output
    end

    def prepare_header
      headers = @options[:headers]
      case headers
      when Array
        @headers = headers
        @use_headers = true
      when String
        @headers = CSV.parse_line(headers,
                                  col_sep: @options[:column_separator],
                                  row_sep: @options[:row_separator],
                                  quote_char: @options[:quote_character])
        @use_headers = true
      when true
        @headers = nil
        @use_headers = true
      else
        @headers = nil
        @use_headers = false
      end
      return unless @headers

      converter = @options[:header_fields_converter]
      @headers = converter.convert(@headers, nil, 0)
      @headers.each do |header|
        header.freeze if header.is_a?(String)
      end
    end

    def prepare_force_quotes_fields(force_quotes)
      @force_quotes_fields = {}
      force_quotes.each do |name_or_index|
        case name_or_index
        when Integer
          index = name_or_index
          @force_quotes_fields[index] = true
        when String, Symbol
          name = name_or_index.to_s
          if @headers.nil?
            message = ":headers is required when you use field name " +
                      "in :force_quotes: " +
                      "#{name_or_index.inspect}: #{force_quotes.inspect}"
            raise ArgumentError, message
          end
          index = @headers.index(name)
          next if index.nil?
          @force_quotes_fields[index] = true
        else
          message = ":force_quotes element must be " +
                    "field index or field name: " +
                    "#{name_or_index.inspect}: #{force_quotes.inspect}"
          raise ArgumentError, message
        end
      end
    end

    def prepare_format
      @column_separator = @options[:column_separator].to_s.encode(@encoding)
      row_separator = @options[:row_separator]
      if row_separator == :auto
        @row_separator = $INPUT_RECORD_SEPARATOR.encode(@encoding)
      else
        @row_separator = row_separator.to_s.encode(@encoding)
      end
      @quote_character = @options[:quote_character]
      force_quotes = @options[:force_quotes]
      if force_quotes.is_a?(Array)
        prepare_force_quotes_fields(force_quotes)
        @force_quotes = false
      elsif force_quotes
        @force_quotes_fields = nil
        @force_quotes = true
      else
        @force_quotes_fields = nil
        @force_quotes = false
      end
      unless @force_quotes
        @quotable_pattern =
          Regexp.new("[\r\n".encode(@encoding) +
                     Regexp.escape(@column_separator) +
                     Regexp.escape(@quote_character.encode(@encoding)) +
                     "]".encode(@encoding))
      end
      @quote_empty = @options.fetch(:quote_empty, true)
    end

    def prepare_output
      @output_encoding = nil
      return unless @output.is_a?(StringIO)

      output_encoding = @output.internal_encoding || @output.external_encoding
      if @encoding != output_encoding
        if @options[:force_encoding]
          @output_encoding = output_encoding
        else
          compatible_encoding = Encoding.compatible?(@encoding, output_encoding)
          if compatible_encoding
            @output.set_encoding(compatible_encoding)
            @output.seek(0, IO::SEEK_END)
          end
        end
      end
    end

    def quote_field(field)
      field = String(field)
      encoded_quote_character = @quote_character.encode(field.encoding)
      encoded_quote_character +
        field.gsub(encoded_quote_character,
                   encoded_quote_character * 2) +
        encoded_quote_character
    end

    def quote(field, i)
      if @force_quotes
        quote_field(field)
      elsif @force_quotes_fields and @force_quotes_fields[i]
        quote_field(field)
      else
        if field.nil?  # represent +nil+ fields as empty unquoted fields
          ""
        else
          field = String(field)  # Stringify fields
          # represent empty fields as empty quoted fields
          if (@quote_empty and field.empty?) or (field.valid_encoding? and @quotable_pattern.match?(field))
            quote_field(field)
          else
            field  # unquoted field
          end
        end
      end
    end
  end
end
# frozen_string_literal: true

require "strscan"

require_relative "delete_suffix"
require_relative "match_p"
require_relative "row"
require_relative "table"

using CSV::DeleteSuffix if CSV.const_defined?(:DeleteSuffix)
using CSV::MatchP if CSV.const_defined?(:MatchP)

class CSV
  # Note: Don't use this class directly. This is an internal class.
  class Parser
    #
    # A CSV::Parser is m17n aware. The parser works in the Encoding of the IO
    # or String object being read from or written to. Your data is never transcoded
    # (unless you ask Ruby to transcode it for you) and will literally be parsed in
    # the Encoding it is in. Thus CSV will return Arrays or Rows of Strings in the
    # Encoding of your data. This is accomplished by transcoding the parser itself
    # into your Encoding.
    #

    # Raised when encoding is invalid.
    class InvalidEncoding < StandardError
    end

    #
    # CSV::Scanner receives a CSV output, scans it and return the content.
    # It also controls the life cycle of the object with its methods +keep_start+,
    # +keep_end+, +keep_back+, +keep_drop+.
    #
    # Uses StringScanner (the official strscan gem). Strscan provides lexical
    # scanning operations on a String. We inherit its object and take advantage
    # on the methods. For more information, please visit:
    # https://ruby-doc.org/stdlib-2.6.1/libdoc/strscan/rdoc/StringScanner.html
    #
    class Scanner < StringScanner
      alias_method :scan_all, :scan

      def initialize(*args)
        super
        @keeps = []
      end

      def each_line(row_separator)
        position = pos
        rest.each_line(row_separator) do |line|
          position += line.bytesize
          self.pos = position
          yield(line)
        end
      end

      def keep_start
        @keeps.push(pos)
      end

      def keep_end
        start = @keeps.pop
        string.byteslice(start, pos - start)
      end

      def keep_back
        self.pos = @keeps.pop
      end

      def keep_drop
        @keeps.pop
      end
    end

    #
    # CSV::InputsScanner receives IO inputs, encoding and the chunk_size.
    # It also controls the life cycle of the object with its methods +keep_start+,
    # +keep_end+, +keep_back+, +keep_drop+.
    #
    # CSV::InputsScanner.scan() tries to match with pattern at the current position.
    # If there's a match, the scanner advances the “scan pointer” and returns the matched string.
    # Otherwise, the scanner returns nil.
    #
    # CSV::InputsScanner.rest() returns the “rest” of the string (i.e. everything after the scan pointer).
    # If there is no more data (eos? = true), it returns "".
    #
    class InputsScanner
      def initialize(inputs, encoding, chunk_size: 8192)
        @inputs = inputs.dup
        @encoding = encoding
        @chunk_size = chunk_size
        @last_scanner = @inputs.empty?
        @keeps = []
        read_chunk
      end

      def each_line(row_separator)
        buffer = nil
        input = @scanner.rest
        position = @scanner.pos
        offset = 0
        n_row_separator_chars = row_separator.size
        while true
          input.each_line(row_separator) do |line|
            @scanner.pos += line.bytesize
            if buffer
              if n_row_separator_chars == 2 and
                buffer.end_with?(row_separator[0]) and
                line.start_with?(row_separator[1])
                buffer << line[0]
                line = line[1..-1]
                position += buffer.bytesize + offset
                @scanner.pos = position
                offset = 0
                yield(buffer)
                buffer = nil
                next if line.empty?
              else
                buffer << line
                line = buffer
                buffer = nil
              end
            end
            if line.end_with?(row_separator)
              position += line.bytesize + offset
              @scanner.pos = position
              offset = 0
              yield(line)
            else
              buffer = line
            end
          end
          break unless read_chunk
          input = @scanner.rest
          position = @scanner.pos
          offset = -buffer.bytesize if buffer
        end
        yield(buffer) if buffer
      end

      def scan(pattern)
        value = @scanner.scan(pattern)
        return value if @last_scanner

        if value
          read_chunk if @scanner.eos?
          return value
        else
          nil
        end
      end

      def scan_all(pattern)
        value = @scanner.scan(pattern)
        return value if @last_scanner

        return nil if value.nil?
        while @scanner.eos? and read_chunk and (sub_value = @scanner.scan(pattern))
          value << sub_value
        end
        value
      end

      def eos?
        @scanner.eos?
      end

      def keep_start
        @keeps.push([@scanner.pos, nil])
      end

      def keep_end
        start, buffer = @keeps.pop
        keep = @scanner.string.byteslice(start, @scanner.pos - start)
        if buffer
          buffer << keep
          keep = buffer
        end
        keep
      end

      def keep_back
        start, buffer = @keeps.pop
        if buffer
          string = @scanner.string
          keep = string.byteslice(start, string.bytesize - start)
          if keep and not keep.empty?
            @inputs.unshift(StringIO.new(keep))
            @last_scanner = false
          end
          @scanner = StringScanner.new(buffer)
        else
          @scanner.pos = start
        end
        read_chunk if @scanner.eos?
      end

      def keep_drop
        @keeps.pop
      end

      def rest
        @scanner.rest
      end

      private
      def read_chunk
        return false if @last_scanner

        unless @keeps.empty?
          keep = @keeps.last
          keep_start = keep[0]
          string = @scanner.string
          keep_data = string.byteslice(keep_start, @scanner.pos - keep_start)
          if keep_data
            keep_buffer = keep[1]
            if keep_buffer
              keep_buffer << keep_data
            else
              keep[1] = keep_data.dup
            end
          end
          keep[0] = 0
        end

        input = @inputs.first
        case input
        when StringIO
          string = input.read
          raise InvalidEncoding unless string.valid_encoding?
          @scanner = StringScanner.new(string)
          @inputs.shift
          @last_scanner = @inputs.empty?
          true
        else
          chunk = input.gets(nil, @chunk_size)
          if chunk
            raise InvalidEncoding unless chunk.valid_encoding?
            @scanner = StringScanner.new(chunk)
            if input.respond_to?(:eof?) and input.eof?
              @inputs.shift
              @last_scanner = @inputs.empty?
            end
            true
          else
            @scanner = StringScanner.new("".encode(@encoding))
            @inputs.shift
            @last_scanner = @inputs.empty?
            if @last_scanner
              false
            else
              read_chunk
            end
          end
        end
      end
    end

    def initialize(input, options)
      @input = input
      @options = options
      @samples = []

      prepare
    end

    def column_separator
      @column_separator
    end

    def row_separator
      @row_separator
    end

    def quote_character
      @quote_character
    end

    def field_size_limit
      @field_size_limit
    end

    def skip_lines
      @skip_lines
    end

    def unconverted_fields?
      @unconverted_fields
    end

    def headers
      @headers
    end

    def header_row?
      @use_headers and @headers.nil?
    end

    def return_headers?
      @return_headers
    end

    def skip_blanks?
      @skip_blanks
    end

    def liberal_parsing?
      @liberal_parsing
    end

    def lineno
      @lineno
    end

    def line
      last_line
    end

    def parse(&block)
      return to_enum(__method__) unless block_given?

      if @return_headers and @headers and @raw_headers
        headers = Row.new(@headers, @raw_headers, true)
        if @unconverted_fields
          headers = add_unconverted_fields(headers, [])
        end
        yield headers
      end

      begin
        @scanner ||= build_scanner
        if quote_character.nil?
          parse_no_quote(&block)
        elsif @need_robust_parsing
          parse_quotable_robust(&block)
        else
          parse_quotable_loose(&block)
        end
      rescue InvalidEncoding
        if @scanner
          ignore_broken_line
          lineno = @lineno
        else
          lineno = @lineno + 1
        end
        message = "Invalid byte sequence in #{@encoding}"
        raise MalformedCSVError.new(message, lineno)
      end
    end

    def use_headers?
      @use_headers
    end

    private
    # A set of tasks to prepare the file in order to parse it
    def prepare
      prepare_variable
      prepare_quote_character
      prepare_backslash
      prepare_skip_lines
      prepare_strip
      prepare_separators
      prepare_quoted
      prepare_unquoted
      prepare_line
      prepare_header
      prepare_parser
    end

    def prepare_variable
      @need_robust_parsing = false
      @encoding = @options[:encoding]
      liberal_parsing = @options[:liberal_parsing]
      if liberal_parsing
        @liberal_parsing = true
        if liberal_parsing.is_a?(Hash)
          @double_quote_outside_quote =
            liberal_parsing[:double_quote_outside_quote]
          @backslash_quote = liberal_parsing[:backslash_quote]
        else
          @double_quote_outside_quote = false
          @backslash_quote = false
        end
        @need_robust_parsing = true
      else
        @liberal_parsing = false
        @backslash_quote = false
      end
      @unconverted_fields = @options[:unconverted_fields]
      @field_size_limit = @options[:field_size_limit]
      @skip_blanks = @options[:skip_blanks]
      @fields_converter = @options[:fields_converter]
      @header_fields_converter = @options[:header_fields_converter]
    end

    def prepare_quote_character
      @quote_character = @options[:quote_character]
      if @quote_character.nil?
        @escaped_quote_character = nil
        @escaped_quote = nil
      else
        @quote_character = @quote_character.to_s.encode(@encoding)
        if @quote_character.length != 1
          message = ":quote_char has to be nil or a single character String"
          raise ArgumentError, message
        end
        @double_quote_character = @quote_character * 2
        @escaped_quote_character = Regexp.escape(@quote_character)
        @escaped_quote = Regexp.new(@escaped_quote_character)
      end
    end

    def prepare_backslash
      return unless @backslash_quote

      @backslash_character = "\\".encode(@encoding)

      @escaped_backslash_character = Regexp.escape(@backslash_character)
      @escaped_backslash = Regexp.new(@escaped_backslash_character)
      if @quote_character.nil?
        @backslash_quote_character = nil
      else
        @backslash_quote_character =
          @backslash_character + @escaped_quote_character
      end
    end

    def prepare_skip_lines
      skip_lines = @options[:skip_lines]
      case skip_lines
      when String
        @skip_lines = skip_lines.encode(@encoding)
      when Regexp, nil
        @skip_lines = skip_lines
      else
        unless skip_lines.respond_to?(:match)
          message =
            ":skip_lines has to respond to \#match: #{skip_lines.inspect}"
          raise ArgumentError, message
        end
        @skip_lines = skip_lines
      end
    end

    def prepare_strip
      @strip = @options[:strip]
      @escaped_strip = nil
      @strip_value = nil
      @rstrip_value = nil
      if @strip.is_a?(String)
        case @strip.length
        when 0
          raise ArgumentError, ":strip must not be an empty String"
        when 1
          # ok
        else
          raise ArgumentError, ":strip doesn't support 2 or more characters yet"
        end
        @strip = @strip.encode(@encoding)
        @escaped_strip = Regexp.escape(@strip)
        if @quote_character
          @strip_value = Regexp.new(@escaped_strip +
                                    "+".encode(@encoding))
          @rstrip_value = Regexp.new(@escaped_strip +
                                     "+\\z".encode(@encoding))
        end
        @need_robust_parsing = true
      elsif @strip
        strip_values = " \t\f\v"
        @escaped_strip = strip_values.encode(@encoding)
        if @quote_character
          @strip_value = Regexp.new("[#{strip_values}]+".encode(@encoding))
          @rstrip_value = Regexp.new("[#{strip_values}]+\\z".encode(@encoding))
        end
        @need_robust_parsing = true
      end
    end

    begin
      StringScanner.new("x").scan("x")
    rescue TypeError
      @@string_scanner_scan_accept_string = false
    else
      @@string_scanner_scan_accept_string = true
    end

    def prepare_separators
      column_separator = @options[:column_separator]
      @column_separator = column_separator.to_s.encode(@encoding)
      if @column_separator.size < 1
        message = ":col_sep must be 1 or more characters: "
        message += column_separator.inspect
        raise ArgumentError, message
      end
      @row_separator =
        resolve_row_separator(@options[:row_separator]).encode(@encoding)

      @escaped_column_separator = Regexp.escape(@column_separator)
      @escaped_first_column_separator = Regexp.escape(@column_separator[0])
      if @column_separator.size > 1
        @column_end = Regexp.new(@escaped_column_separator)
        @column_ends = @column_separator.each_char.collect do |char|
          Regexp.new(Regexp.escape(char))
        end
        @first_column_separators = Regexp.new(@escaped_first_column_separator +
                                              "+".encode(@encoding))
      else
        if @@string_scanner_scan_accept_string
          @column_end = @column_separator
        else
          @column_end = Regexp.new(@escaped_column_separator)
        end
        @column_ends = nil
        @first_column_separators = nil
      end

      escaped_row_separator = Regexp.escape(@row_separator)
      @row_end = Regexp.new(escaped_row_separator)
      if @row_separator.size > 1
        @row_ends = @row_separator.each_char.collect do |char|
          Regexp.new(Regexp.escape(char))
        end
      else
        @row_ends = nil
      end

      @cr = "\r".encode(@encoding)
      @lf = "\n".encode(@encoding)
      @cr_or_lf = Regexp.new("[\r\n]".encode(@encoding))
      @not_line_end = Regexp.new("[^\r\n]+".encode(@encoding))
    end

    def prepare_quoted
      if @quote_character
        @quotes = Regexp.new(@escaped_quote_character +
                             "+".encode(@encoding))
        no_quoted_values = @escaped_quote_character.dup
        if @backslash_quote
          no_quoted_values << @escaped_backslash_character
        end
        @quoted_value = Regexp.new("[^".encode(@encoding) +
                                   no_quoted_values +
                                   "]+".encode(@encoding))
      end
      if @escaped_strip
        @split_column_separator = Regexp.new(@escaped_strip +
                                             "*".encode(@encoding) +
                                             @escaped_column_separator +
                                             @escaped_strip +
                                             "*".encode(@encoding))
      else
        if @column_separator == " ".encode(@encoding)
          @split_column_separator = Regexp.new(@escaped_column_separator)
        else
          @split_column_separator = @column_separator
        end
      end
    end

    def prepare_unquoted
      return if @quote_character.nil?

      no_unquoted_values = "\r\n".encode(@encoding)
      no_unquoted_values << @escaped_first_column_separator
      unless @liberal_parsing
        no_unquoted_values << @escaped_quote_character
      end
      @unquoted_value = Regexp.new("[^".encode(@encoding) +
                                   no_unquoted_values +
                                   "]+".encode(@encoding))
    end

    def resolve_row_separator(separator)
      if separator == :auto
        cr = "\r".encode(@encoding)
        lf = "\n".encode(@encoding)
        if @input.is_a?(StringIO)
          pos = @input.pos
          separator = detect_row_separator(@input.read, cr, lf)
          @input.seek(pos)
        elsif @input.respond_to?(:gets)
          if @input.is_a?(File)
            chunk_size = 32 * 1024
          else
            chunk_size = 1024
          end
          begin
            while separator == :auto
              #
              # if we run out of data, it's probably a single line
              # (ensure will set default value)
              #
              break unless sample = @input.gets(nil, chunk_size)

              # extend sample if we're unsure of the line ending
              if sample.end_with?(cr)
                sample << (@input.gets(nil, 1) || "")
              end

              @samples << sample

              separator = detect_row_separator(sample, cr, lf)
            end
          rescue IOError
            # do nothing:  ensure will set default
          end
        end
        separator = $INPUT_RECORD_SEPARATOR if separator == :auto
      end
      separator.to_s.encode(@encoding)
    end

    def detect_row_separator(sample, cr, lf)
      lf_index = sample.index(lf)
      if lf_index
        cr_index = sample[0, lf_index].index(cr)
      else
        cr_index = sample.index(cr)
      end
      if cr_index and lf_index
        if cr_index + 1 == lf_index
          cr + lf
        elsif cr_index < lf_index
          cr
        else
          lf
        end
      elsif cr_index
        cr
      elsif lf_index
        lf
      else
        :auto
      end
    end

    def prepare_line
      @lineno = 0
      @last_line = nil
      @scanner = nil
    end

    def last_line
      if @scanner
        @last_line ||= @scanner.keep_end
      else
        @last_line
      end
    end

    def prepare_header
      @return_headers = @options[:return_headers]

      headers = @options[:headers]
      case headers
      when Array
        @raw_headers = headers
        @use_headers = true
      when String
        @raw_headers = parse_headers(headers)
        @use_headers = true
      when nil, false
        @raw_headers = nil
        @use_headers = false
      else
        @raw_headers = nil
        @use_headers = true
      end
      if @raw_headers
        @headers = adjust_headers(@raw_headers)
      else
        @headers = nil
      end
    end

    def parse_headers(row)
      CSV.parse_line(row,
                     col_sep:    @column_separator,
                     row_sep:    @row_separator,
                     quote_char: @quote_character)
    end

    def adjust_headers(headers)
      adjusted_headers = @header_fields_converter.convert(headers, nil, @lineno)
      adjusted_headers.each {|h| h.freeze if h.is_a? String}
      adjusted_headers
    end

    def prepare_parser
      @may_quoted = may_quoted?
    end

    def may_quoted?
      return false if @quote_character.nil?

      if @input.is_a?(StringIO)
        pos = @input.pos
        sample = @input.read
        @input.seek(pos)
      else
        return false if @samples.empty?
        sample = @samples.first
      end
      sample[0, 128].index(@quote_character)
    end

    SCANNER_TEST = (ENV["CSV_PARSER_SCANNER_TEST"] == "yes")
    if SCANNER_TEST
      class UnoptimizedStringIO
        def initialize(string)
          @io = StringIO.new(string, "rb:#{string.encoding}")
        end

        def gets(*args)
          @io.gets(*args)
        end

        def each_line(*args, &block)
          @io.each_line(*args, &block)
        end

        def eof?
          @io.eof?
        end
      end

      def build_scanner
        inputs = @samples.collect do |sample|
          UnoptimizedStringIO.new(sample)
        end
        if @input.is_a?(StringIO)
          inputs << UnoptimizedStringIO.new(@input.read)
        else
          inputs << @input
        end
        chunk_size = ENV["CSV_PARSER_SCANNER_TEST_CHUNK_SIZE"] || "1"
        InputsScanner.new(inputs,
                          @encoding,
                          chunk_size: Integer(chunk_size, 10))
      end
    else
      def build_scanner
        string = nil
        if @samples.empty? and @input.is_a?(StringIO)
          string = @input.read
        elsif @samples.size == 1 and @input.respond_to?(:eof?) and @input.eof?
          string = @samples[0]
        end
        if string
          unless string.valid_encoding?
            index = string.lines(@row_separator).index do |line|
              !line.valid_encoding?
            end
            if index
              message = "Invalid byte sequence in #{@encoding}"
              raise MalformedCSVError.new(message, @lineno + index + 1)
            end
          end
          Scanner.new(string)
        else
          inputs = @samples.collect do |sample|
            StringIO.new(sample)
          end
          inputs << @input
          InputsScanner.new(inputs, @encoding)
        end
      end
    end

    def skip_needless_lines
      return unless @skip_lines

      until @scanner.eos?
        @scanner.keep_start
        line = @scanner.scan_all(@not_line_end) || "".encode(@encoding)
        line << @row_separator if parse_row_end
        if skip_line?(line)
          @lineno += 1
          @scanner.keep_drop
        else
          @scanner.keep_back
          return
        end
      end
    end

    def skip_line?(line)
      line = line.delete_suffix(@row_separator)
      case @skip_lines
      when String
        line.include?(@skip_lines)
      when Regexp
        @skip_lines.match?(line)
      else
        @skip_lines.match(line)
      end
    end

    def parse_no_quote(&block)
      @scanner.each_line(@row_separator) do |line|
        next if @skip_lines and skip_line?(line)
        original_line = line
        line = line.delete_suffix(@row_separator)

        if line.empty?
          next if @skip_blanks
          row = []
        else
          line = strip_value(line)
          row = line.split(@split_column_separator, -1)
          n_columns = row.size
          i = 0
          while i < n_columns
            row[i] = nil if row[i].empty?
            i += 1
          end
        end
        @last_line = original_line
        emit_row(row, &block)
      end
    end

    def parse_quotable_loose(&block)
      @scanner.keep_start
      @scanner.each_line(@row_separator) do |line|
        if @skip_lines and skip_line?(line)
          @scanner.keep_drop
          @scanner.keep_start
          next
        end
        original_line = line
        line = line.delete_suffix(@row_separator)

        if line.empty?
          if @skip_blanks
            @scanner.keep_drop
            @scanner.keep_start
            next
          end
          row = []
        elsif line.include?(@cr) or line.include?(@lf)
          @scanner.keep_back
          @need_robust_parsing = true
          return parse_quotable_robust(&block)
        else
          row = line.split(@split_column_separator, -1)
          n_columns = row.size
          i = 0
          while i < n_columns
            column = row[i]
            if column.empty?
              row[i] = nil
            else
              n_quotes = column.count(@quote_character)
              if n_quotes.zero?
                # no quote
              elsif n_quotes == 2 and
                   column.start_with?(@quote_character) and
                   column.end_with?(@quote_character)
                row[i] = column[1..-2]
              else
                @scanner.keep_back
                @need_robust_parsing = true
                return parse_quotable_robust(&block)
              end
            end
            i += 1
          end
        end
        @scanner.keep_drop
        @scanner.keep_start
        @last_line = original_line
        emit_row(row, &block)
      end
      @scanner.keep_drop
    end

    def parse_quotable_robust(&block)
      row = []
      skip_needless_lines
      start_row
      while true
        @quoted_column_value = false
        @unquoted_column_value = false
        @scanner.scan_all(@strip_value) if @strip_value
        value = parse_column_value
        if value
          @scanner.scan_all(@strip_value) if @strip_value
          if @field_size_limit and value.size >= @field_size_limit
            ignore_broken_line
            raise MalformedCSVError.new("Field size exceeded", @lineno)
          end
        end
        if parse_column_end
          row << value
        elsif parse_row_end
          if row.empty? and value.nil?
            emit_row([], &block) unless @skip_blanks
          else
            row << value
            emit_row(row, &block)
            row = []
          end
          skip_needless_lines
          start_row
        elsif @scanner.eos?
          break if row.empty? and value.nil?
          row << value
          emit_row(row, &block)
          break
        else
          if @quoted_column_value
            ignore_broken_line
            message = "Any value after quoted field isn't allowed"
            raise MalformedCSVError.new(message, @lineno)
          elsif @unquoted_column_value and
                (new_line = @scanner.scan(@cr_or_lf))
            ignore_broken_line
            message = "Unquoted fields do not allow new line " +
                      "<#{new_line.inspect}>"
            raise MalformedCSVError.new(message, @lineno)
          elsif @scanner.rest.start_with?(@quote_character)
            ignore_broken_line
            message = "Illegal quoting"
            raise MalformedCSVError.new(message, @lineno)
          elsif (new_line = @scanner.scan(@cr_or_lf))
            ignore_broken_line
            message = "New line must be <#{@row_separator.inspect}> " +
                      "not <#{new_line.inspect}>"
            raise MalformedCSVError.new(message, @lineno)
          else
            ignore_broken_line
            raise MalformedCSVError.new("TODO: Meaningful message",
                                        @lineno)
          end
        end
      end
    end

    def parse_column_value
      if @liberal_parsing
        quoted_value = parse_quoted_column_value
        if quoted_value
          @scanner.scan_all(@strip_value) if @strip_value
          unquoted_value = parse_unquoted_column_value
          if unquoted_value
            if @double_quote_outside_quote
              unquoted_value = unquoted_value.gsub(@quote_character * 2,
                                                   @quote_character)
              if quoted_value.empty? # %Q{""...} case
                return @quote_character + unquoted_value
              end
            end
            @quote_character + quoted_value + @quote_character + unquoted_value
          else
            quoted_value
          end
        else
          parse_unquoted_column_value
        end
      elsif @may_quoted
        parse_quoted_column_value ||
          parse_unquoted_column_value
      else
        parse_unquoted_column_value ||
          parse_quoted_column_value
      end
    end

    def parse_unquoted_column_value
      value = @scanner.scan_all(@unquoted_value)
      return nil unless value

      @unquoted_column_value = true
      if @first_column_separators
        while true
          @scanner.keep_start
          is_column_end = @column_ends.all? do |column_end|
            @scanner.scan(column_end)
          end
          @scanner.keep_back
          break if is_column_end
          sub_separator = @scanner.scan_all(@first_column_separators)
          break if sub_separator.nil?
          value << sub_separator
          sub_value = @scanner.scan_all(@unquoted_value)
          break if sub_value.nil?
          value << sub_value
        end
      end
      value.gsub!(@backslash_quote_character, @quote_character) if @backslash_quote
      if @rstrip_value
        value.gsub!(@rstrip_value, "")
      end
      value
    end

    def parse_quoted_column_value
      quotes = @scanner.scan_all(@quotes)
      return nil unless quotes

      @quoted_column_value = true
      n_quotes = quotes.size
      if (n_quotes % 2).zero?
        quotes[0, (n_quotes - 2) / 2]
      else
        value = quotes[0, (n_quotes - 1) / 2]
        while true
          quoted_value = @scanner.scan_all(@quoted_value)
          value << quoted_value if quoted_value
          if @backslash_quote
            if @scanner.scan(@escaped_backslash)
              if @scanner.scan(@escaped_quote)
                value << @quote_character
              else
                value << @backslash_character
              end
              next
            end
          end

          quotes = @scanner.scan_all(@quotes)
          unless quotes
            ignore_broken_line
            message = "Unclosed quoted field"
            raise MalformedCSVError.new(message, @lineno)
          end
          n_quotes = quotes.size
          if n_quotes == 1
            break
          elsif (n_quotes % 2) == 1
            value << quotes[0, (n_quotes - 1) / 2]
            break
          else
            value << quotes[0, n_quotes / 2]
          end
        end
        value
      end
    end

    def parse_column_end
      return true if @scanner.scan(@column_end)
      return false unless @column_ends

      @scanner.keep_start
      if @column_ends.all? {|column_end| @scanner.scan(column_end)}
        @scanner.keep_drop
        true
      else
        @scanner.keep_back
        false
      end
    end

    def parse_row_end
      return true if @scanner.scan(@row_end)
      return false unless @row_ends
      @scanner.keep_start
      if @row_ends.all? {|row_end| @scanner.scan(row_end)}
        @scanner.keep_drop
        true
      else
        @scanner.keep_back
        false
      end
    end

    def strip_value(value)
      return value unless @strip
      return nil if value.nil?

      case @strip
      when String
        size = value.size
        while value.start_with?(@strip)
          size -= 1
          value = value[1, size]
        end
        while value.end_with?(@strip)
          size -= 1
          value = value[0, size]
        end
      else
        value.strip!
      end
      value
    end

    def ignore_broken_line
      @scanner.scan_all(@not_line_end)
      @scanner.scan_all(@cr_or_lf)
      @lineno += 1
    end

    def start_row
      if @last_line
        @last_line = nil
      else
        @scanner.keep_drop
      end
      @scanner.keep_start
    end

    def emit_row(row, &block)
      @lineno += 1

      raw_row = row
      if @use_headers
        if @headers.nil?
          @headers = adjust_headers(row)
          return unless @return_headers
          row = Row.new(@headers, row, true)
        else
          row = Row.new(@headers,
                        @fields_converter.convert(raw_row, @headers, @lineno))
        end
      else
        # convert fields, if needed...
        row = @fields_converter.convert(raw_row, nil, @lineno)
      end

      # inject unconverted fields and accessor, if requested...
      if @unconverted_fields and not row.respond_to?(:unconverted_fields)
        add_unconverted_fields(row, raw_row)
      end

      yield(row)
    end

    # This method injects an instance variable <tt>unconverted_fields</tt> into
    # +row+ and an accessor method for +row+ called unconverted_fields().  The
    # variable is set to the contents of +fields+.
    def add_unconverted_fields(row, fields)
      class << row
        attr_reader :unconverted_fields
      end
      row.instance_variable_set(:@unconverted_fields, fields)
      row
    end
  end
end
# frozen_string_literal: true

# This provides String#match? and Regexp#match? for Ruby 2.3.
unless String.method_defined?(:match?)
  class CSV
    module MatchP
      refine String do
        def match?(pattern)
          self =~ pattern
        end
      end

      refine Regexp do
        def match?(string)
          self =~ string
        end
      end
    end
  end
end
class Array # :nodoc:
  # Equivalent to CSV::generate_line(self, options)
  #
  #   ["CSV", "data"].to_csv
  #     #=> "CSV,data\n"
  def to_csv(**options)
    CSV.generate_line(self, **options)
  end
end
class String # :nodoc:
  # Equivalent to CSV::parse_line(self, options)
  #
  #   "CSV,data".parse_csv
  #     #=> ["CSV", "data"]
  def parse_csv(**options)
    CSV.parse_line(self, **options)
  end
end
# frozen_string_literal: true

require "forwardable"

class CSV
  #
  # A CSV::Row is part Array and part Hash. It retains an order for the fields
  # and allows duplicates just as an Array would, but also allows you to access
  # fields by name just as you could if they were in a Hash.
  #
  # All rows returned by CSV will be constructed from this class, if header row
  # processing is activated.
  #
  class Row
    #
    # Constructs a new CSV::Row from +headers+ and +fields+, which are expected
    # to be Arrays. If one Array is shorter than the other, it will be padded
    # with +nil+ objects.
    #
    # The optional +header_row+ parameter can be set to +true+ to indicate, via
    # CSV::Row.header_row?() and CSV::Row.field_row?(), that this is a header
    # row. Otherwise, the row assumes to be a field row.
    #
    # A CSV::Row object supports the following Array methods through delegation:
    #
    # * empty?()
    # * length()
    # * size()
    #
    def initialize(headers, fields, header_row = false)
      @header_row = header_row
      headers.each { |h| h.freeze if h.is_a? String }

      # handle extra headers or fields
      @row = if headers.size >= fields.size
        headers.zip(fields)
      else
        fields.zip(headers).each(&:reverse!)
      end
    end

    # Internal data format used to compare equality.
    attr_reader :row
    protected   :row

    ### Array Delegation ###

    extend Forwardable
    def_delegators :@row, :empty?, :length, :size

    def initialize_copy(other)
      super_return_value = super
      @row = @row.collect(&:dup)
      super_return_value
    end

    # :call-seq:
    #   row.header_row? -> true or false
    #
    # Returns +true+ if this is a header row, +false+ otherwise.
    def header_row?
      @header_row
    end

    # :call-seq:
    #   row.field_row? -> true or false
    #
    # Returns +true+ if this is a field row, +false+ otherwise.
    def field_row?
      not header_row?
    end

    # :call-seq:
    #    row.headers
    #
    # Returns the headers for this row:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table.first
    #   row.headers # => ["Name", "Value"]
    def headers
      @row.map(&:first)
    end

    # :call-seq:
    #   field(index)
    #   field(header)
    #   field(header, offset)
    #
    # Returns the field value for the given +index+ or +header+.
    #
    # ---
    #
    # Fetch field value by \Integer index:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.field(0) # => "foo"
    #   row.field(1) # => "bar"
    #
    # Counts backward from the last column if +index+ is negative:
    #   row.field(-1) # => "0"
    #   row.field(-2) # => "foo"
    #
    # Returns +nil+ if +index+ is out of range:
    #   row.field(2) # => nil
    #   row.field(-3) # => nil
    #
    # ---
    #
    # Fetch field value by header (first found):
    #   source = "Name,Name,Name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.field('Name') # => "Foo"
    #
    # Fetch field value by header, ignoring +offset+ leading fields:
    #   source = "Name,Name,Name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.field('Name', 2) # => "Baz"
    #
    # Returns +nil+ if the header does not exist.
    def field(header_or_index, minimum_index = 0)
      # locate the pair
      finder = (header_or_index.is_a?(Integer) || header_or_index.is_a?(Range)) ? :[] : :assoc
      pair   = @row[minimum_index..-1].public_send(finder, header_or_index)

      # return the field if we have a pair
      if pair.nil?
        nil
      else
        header_or_index.is_a?(Range) ? pair.map(&:last) : pair.last
      end
    end
    alias_method :[], :field

    #
    # :call-seq:
    #   fetch(header)
    #   fetch(header, default)
    #   fetch(header) {|row| ... }
    #
    # Returns the field value as specified by +header+.
    #
    # ---
    #
    # With the single argument +header+, returns the field value
    # for that header (first found):
    #   source = "Name,Name,Name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.fetch('Name') # => "Foo"
    #
    # Raises exception +KeyError+ if the header does not exist.
    #
    # ---
    #
    # With arguments +header+ and +default+ given,
    # returns the field value for the header (first found)
    # if the header exists, otherwise returns +default+:
    #   source = "Name,Name,Name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.fetch('Name', '') # => "Foo"
    #   row.fetch(:nosuch, '') # => ""
    #
    # ---
    #
    # With argument +header+ and a block given,
    # returns the field value for the header (first found)
    # if the header exists; otherwise calls the block
    # and returns its return value:
    #   source = "Name,Name,Name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.fetch('Name') {|header| fail 'Cannot happen' } # => "Foo"
    #   row.fetch(:nosuch) {|header| "Header '#{header} not found'" } # => "Header 'nosuch not found'"
    def fetch(header, *varargs)
      raise ArgumentError, "Too many arguments" if varargs.length > 1
      pair = @row.assoc(header)
      if pair
        pair.last
      else
        if block_given?
          yield header
        elsif varargs.empty?
          raise KeyError, "key not found: #{header}"
        else
          varargs.first
        end
      end
    end

    # :call-seq:
    #   row.has_key?(header)
    #
    # Returns +true+ if there is a field with the given +header+,
    # +false+ otherwise.
    def has_key?(header)
      !!@row.assoc(header)
    end
    alias_method :include?, :has_key?
    alias_method :key?,     :has_key?
    alias_method :member?,  :has_key?
    alias_method :header?,  :has_key?

    #
    # :call-seq:
    #   row[index] = value -> value
    #   row[header, offset] = value -> value
    #   row[header] = value -> value
    #
    # Assigns the field value for the given +index+ or +header+;
    # returns +value+.
    #
    # ---
    #
    # Assign field value by \Integer index:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row[0] = 'Bat'
    #   row[1] = 3
    #   row # => #<CSV::Row "Name":"Bat" "Value":3>
    #
    # Counts backward from the last column if +index+ is negative:
    #   row[-1] = 4
    #   row[-2] = 'Bam'
    #   row # => #<CSV::Row "Name":"Bam" "Value":4>
    #
    # Extends the row with <tt>nil:nil</tt> if positive +index+ is not in the row:
    #   row[4] = 5
    #   row # => #<CSV::Row "Name":"bad" "Value":4 nil:nil nil:nil nil:5>
    #
    # Raises IndexError if negative +index+ is too small (too far from zero).
    #
    # ---
    #
    # Assign field value by header (first found):
    #   source = "Name,Name,Name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row['Name'] = 'Bat'
    #   row # => #<CSV::Row "Name":"Bat" "Name":"Bar" "Name":"Baz">
    #
    # Assign field value by header, ignoring +offset+ leading fields:
    #   source = "Name,Name,Name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row['Name', 2] = 4
    #   row # => #<CSV::Row "Name":"Foo" "Name":"Bar" "Name":4>
    #
    # Append new field by (new) header:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row['New'] = 6
    #   row# => #<CSV::Row "Name":"foo" "Value":"0" "New":6>
    def []=(*args)
      value = args.pop

      if args.first.is_a? Integer
        if @row[args.first].nil?  # extending past the end with index
          @row[args.first] = [nil, value]
          @row.map! { |pair| pair.nil? ? [nil, nil] : pair }
        else                      # normal index assignment
          @row[args.first][1] = value
        end
      else
        index = index(*args)
        if index.nil?             # appending a field
          self << [args.first, value]
        else                      # normal header assignment
          @row[index][1] = value
        end
      end
    end

    #
    # :call-seq:
    #   row << [header, value] -> self
    #   row << hash -> self
    #   row << value -> self
    #
    # Adds a field to +self+; returns +self+:
    #
    # If the argument is a 2-element \Array <tt>[header, value]</tt>,
    # a field is added with the given +header+ and +value+:
    #   source = "Name,Name,Name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row << ['NAME', 'Bat']
    #   row # => #<CSV::Row "Name":"Foo" "Name":"Bar" "Name":"Baz" "NAME":"Bat">
    #
    # If the argument is a \Hash, each <tt>key-value</tt> pair is added
    # as a field with header +key+ and value +value+.
    #   source = "Name,Name,Name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row << {NAME: 'Bat', name: 'Bam'}
    #   row # => #<CSV::Row "Name":"Foo" "Name":"Bar" "Name":"Baz" NAME:"Bat" name:"Bam">
    #
    # Otherwise, the given +value+ is added as a field with no header.
    #   source = "Name,Name,Name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row << 'Bag'
    #   row # => #<CSV::Row "Name":"Foo" "Name":"Bar" "Name":"Baz" nil:"Bag">
    def <<(arg)
      if arg.is_a?(Array) and arg.size == 2  # appending a header and name
        @row << arg
      elsif arg.is_a?(Hash)                  # append header and name pairs
        arg.each { |pair| @row << pair }
      else                                   # append field value
        @row << [nil, arg]
      end

      self  # for chaining
    end

    # :call-seq:
    #   row.push(*values) ->self
    #
    # Appends each of the given +values+ to +self+ as a field; returns +self+:
    #   source = "Name,Name,Name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.push('Bat', 'Bam')
    #   row # => #<CSV::Row "Name":"Foo" "Name":"Bar" "Name":"Baz" nil:"Bat" nil:"Bam">
    def push(*args)
      args.each { |arg| self << arg }

      self  # for chaining
    end

    #
    # :call-seq:
    #   delete(index) -> [header, value] or nil
    #   delete(header) -> [header, value] or empty_array
    #   delete(header, offset) -> [header, value] or empty_array
    #
    # Removes a specified field from +self+; returns the 2-element \Array
    # <tt>[header, value]</tt> if the field exists.
    #
    # If an \Integer argument +index+ is given,
    # removes and returns the field at offset +index+,
    # or returns +nil+ if the field does not exist:
    #   source = "Name,Name,Name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.delete(1) # => ["Name", "Bar"]
    #   row.delete(50) # => nil
    #
    # Otherwise, if the single argument +header+ is given,
    # removes and returns the first-found field with the given header,
    # of returns a new empty \Array if the field does not exist:
    #   source = "Name,Name,Name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.delete('Name') # => ["Name", "Foo"]
    #   row.delete('NAME') # => []
    #
    # If argument +header+ and \Integer argument +offset+ are given,
    # removes and returns the first-found field with the given header
    # whose +index+ is at least as large as +offset+:
    #   source = "Name,Name,Name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.delete('Name', 1) # => ["Name", "Bar"]
    #   row.delete('NAME', 1) # => []
    def delete(header_or_index, minimum_index = 0)
      if header_or_index.is_a? Integer                 # by index
        @row.delete_at(header_or_index)
      elsif i = index(header_or_index, minimum_index)  # by header
        @row.delete_at(i)
      else
        [ ]
      end
    end

    # :call-seq:
    #   row.delete_if {|header, value| ... } -> self
    #
    # Removes fields from +self+ as selected by the block; returns +self+.
    #
    # Removes each field for which the block returns a truthy value:
    #   source = "Name,Name,Name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.delete_if {|header, value| value.start_with?('B') } # => true
    #   row # => #<CSV::Row "Name":"Foo">
    #   row.delete_if {|header, value| header.start_with?('B') } # => false
    #
    # If no block is given, returns a new Enumerator:
    #   row.delete_if # => #<Enumerator: #<CSV::Row "Name":"Foo">:delete_if>
    def delete_if(&block)
      return enum_for(__method__) { size } unless block_given?

      @row.delete_if(&block)

      self  # for chaining
    end

    # :call-seq:
    #   self.fields(*specifiers)
    #
    # Returns field values per the given +specifiers+, which may be any mixture of:
    # - \Integer index.
    # - \Range of \Integer indexes.
    # - 2-element \Array containing a header and offset.
    # - Header.
    # - \Range of headers.
    #
    # For +specifier+ in one of the first four cases above,
    # returns the result of <tt>self.field(specifier)</tt>;  see #field.
    #
    # Although there may be any number of +specifiers+,
    # the examples here will illustrate one at a time.
    #
    # When the specifier is an \Integer +index+,
    # returns <tt>self.field(index)</tt>L
    #   source = "Name,Name,Name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.fields(1) # => ["Bar"]
    #
    # When the specifier is a \Range of \Integers +range+,
    # returns <tt>self.field(range)</tt>:
    #   row.fields(1..2) # => ["Bar", "Baz"]
    #
    # When the specifier is a 2-element \Array +array+,
    # returns <tt>self.field(array)</tt>L
    #   row.fields('Name', 1) # => ["Foo", "Bar"]
    #
    # When the specifier is a header +header+,
    # returns <tt>self.field(header)</tt>L
    #   row.fields('Name') # => ["Foo"]
    #
    # When the specifier is a \Range of headers +range+,
    # forms a new \Range +new_range+ from the indexes of
    # <tt>range.start</tt> and <tt>range.end</tt>,
    # and returns <tt>self.field(new_range)</tt>:
    #   source = "Name,NAME,name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.fields('Name'..'NAME') # => ["Foo", "Bar"]
    #
    # Returns all fields if no argument given:
    #   row.fields # => ["Foo", "Bar", "Baz"]
    def fields(*headers_and_or_indices)
      if headers_and_or_indices.empty?  # return all fields--no arguments
        @row.map(&:last)
      else                              # or work like values_at()
        all = []
        headers_and_or_indices.each do |h_or_i|
          if h_or_i.is_a? Range
            index_begin = h_or_i.begin.is_a?(Integer) ? h_or_i.begin :
                                                        index(h_or_i.begin)
            index_end   = h_or_i.end.is_a?(Integer)   ? h_or_i.end :
                                                        index(h_or_i.end)
            new_range   = h_or_i.exclude_end? ? (index_begin...index_end) :
                                                (index_begin..index_end)
            all.concat(fields.values_at(new_range))
          else
            all << field(*Array(h_or_i))
          end
        end
        return all
      end
    end
    alias_method :values_at, :fields

    #
    # :call-seq:
    #   index( header )
    #   index( header, offset )
    #
    # This method will return the index of a field with the provided +header+.
    # The +offset+ can be used to locate duplicate header names, as described in
    # CSV::Row.field().
    #
    def index(header, minimum_index = 0)
      # find the pair
      index = headers[minimum_index..-1].index(header)
      # return the index at the right offset, if we found one
      index.nil? ? nil : index + minimum_index
    end

    #
    # Returns +true+ if +data+ matches a field in this row, and +false+
    # otherwise.
    #
    def field?(data)
      fields.include? data
    end

    include Enumerable

    #
    # Yields each pair of the row as header and field tuples (much like
    # iterating over a Hash). This method returns the row for chaining.
    #
    # If no block is given, an Enumerator is returned.
    #
    # Support for Enumerable.
    #
    def each(&block)
      return enum_for(__method__) { size } unless block_given?

      @row.each(&block)

      self  # for chaining
    end

    alias_method :each_pair, :each

    #
    # Returns +true+ if this row contains the same headers and fields in the
    # same order as +other+.
    #
    def ==(other)
      return @row == other.row if other.is_a? CSV::Row
      @row == other
    end

    # :call-seq:
    #   row.to_h -> hash
    #
    # Returns the new \Hash formed by adding each header-value pair in +self+
    # as a key-value pair in the \Hash.
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.to_h # => {"Name"=>"foo", "Value"=>"0"}
    #
    # Header order is preserved, but repeated headers are ignored:
    #   source = "Name,Name,Name\nFoo,Bar,Baz\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.to_h # => {"Name"=>"Foo"}
    def to_h
      hash = {}
      each do |key, _value|
        hash[key] = self[key] unless hash.key?(key)
      end
      hash
    end
    alias_method :to_hash, :to_h

    alias_method :to_ary, :to_a

    # :call-seq:
    #   row.to_csv -> csv_string
    #
    # Returns the row as a \CSV String. Headers are not included:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.to_csv # => "foo,0\n"
    def to_csv(**options)
      fields.to_csv(**options)
    end
    alias_method :to_s, :to_csv

    # :call-seq:
    #   row.dig(index_or_header, *identifiers) -> object
    #
    # Finds and returns the object in nested object that is specified
    # by +index_or_header+ and +specifiers+.
    #
    # The nested objects may be instances of various classes.
    # See {Dig Methods}[https://docs.ruby-lang.org/en/master/doc/dig_methods_rdoc.html].
    #
    # Examples:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.dig(1) # => "0"
    #   row.dig('Value') # => "0"
    #   row.dig(5) # => nil
    def dig(index_or_header, *indexes)
      value = field(index_or_header)
      if value.nil?
        nil
      elsif indexes.empty?
        value
      else
        unless value.respond_to?(:dig)
          raise TypeError, "#{value.class} does not have \#dig method"
        end
        value.dig(*indexes)
      end
    end

    # :call-seq:
    #   row.inspect -> string
    #
    # Returns an ASCII-compatible \String showing:
    # - Class \CSV::Row.
    # - Header-value pairs.
    # Example:
    #   source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
    #   table = CSV.parse(source, headers: true)
    #   row = table[0]
    #   row.inspect # => "#<CSV::Row \"Name\":\"foo\" \"Value\":\"0\">"
    def inspect
      str = ["#<", self.class.to_s]
      each do |header, field|
        str << " " << (header.is_a?(Symbol) ? header.to_s : header.inspect) <<
               ":" << field.inspect
      end
      str << ">"
      begin
        str.join('')
      rescue  # any encoding error
        str.map do |s|
          e = Encoding::Converter.asciicompat_encoding(s.encoding)
          e ? s.encode(e) : s.force_encoding("ASCII-8BIT")
        end.join('')
      end
    end
  end
end
# frozen_string_literal: true

class CSV
  # The version of the installed library.
  VERSION = "3.1.9"
end
# frozen_string_literal: true
=begin
= Info
  'OpenSSL for Ruby 2' project
  Copyright (C) 2002  Michal Rokos <m.rokos@sh.cvut.cz>
  All rights reserved.

= Licence
  This program is licensed under the same licence as Ruby.
  (See the file 'LICENCE'.)
=end

require 'openssl.so'

require_relative 'openssl/bn'
require_relative 'openssl/pkey'
require_relative 'openssl/cipher'
require_relative 'openssl/config'
require_relative 'openssl/digest'
require_relative 'openssl/hmac'
require_relative 'openssl/x509'
require_relative 'openssl/ssl'
require_relative 'openssl/pkcs5'
require_relative 'openssl/version'

module OpenSSL
  # call-seq:
  #   OpenSSL.secure_compare(string, string) -> boolean
  #
  # Constant time memory comparison. Inputs are hashed using SHA-256 to mask
  # the length of the secret. Returns +true+ if the strings are identical,
  # +false+ otherwise.
  def self.secure_compare(a, b)
    hashed_a = OpenSSL::Digest.digest('SHA256', a)
    hashed_b = OpenSSL::Digest.digest('SHA256', b)
    OpenSSL.fixed_length_secure_compare(hashed_a, hashed_b) && a == b
  end
end
# frozen_string_literal: false
#
#   mutex_m.rb -
#       $Release Version: 3.0$
#       $Revision: 1.7 $
#       Original from mutex.rb
#       by Keiju ISHITSUKA(keiju@ishitsuka.com)
#       modified by matz
#       patched by akira yamada
#
# --

# = mutex_m.rb
#
# When 'mutex_m' is required, any object that extends or includes Mutex_m will
# be treated like a Mutex.
#
# Start by requiring the standard library Mutex_m:
#
#   require "mutex_m.rb"
#
# From here you can extend an object with Mutex instance methods:
#
#   obj = Object.new
#   obj.extend Mutex_m
#
# Or mixin Mutex_m into your module to your class inherit Mutex instance
# methods --- remember to call super() in your class initialize method.
#
#   class Foo
#     include Mutex_m
#     def initialize
#       # ...
#       super()
#     end
#     # ...
#   end
#   obj = Foo.new
#   # this obj can be handled like Mutex
#
module Mutex_m

  VERSION = "0.1.1"

  def Mutex_m.define_aliases(cl) # :nodoc:
    cl.module_eval %q{
      alias locked? mu_locked?
      alias lock mu_lock
      alias unlock mu_unlock
      alias try_lock mu_try_lock
      alias synchronize mu_synchronize
    }
  end

  def Mutex_m.append_features(cl) # :nodoc:
    super
    define_aliases(cl) unless cl.instance_of?(Module)
  end

  def Mutex_m.extend_object(obj) # :nodoc:
    super
    obj.mu_extended
  end

  def mu_extended # :nodoc:
    unless (defined? locked? and
            defined? lock and
            defined? unlock and
            defined? try_lock and
            defined? synchronize)
      Mutex_m.define_aliases(singleton_class)
    end
    mu_initialize
  end

  # See Mutex#synchronize
  def mu_synchronize(&block)
    @_mutex.synchronize(&block)
  end

  # See Mutex#locked?
  def mu_locked?
    @_mutex.locked?
  end

  # See Mutex#try_lock
  def mu_try_lock
    @_mutex.try_lock
  end

  # See Mutex#lock
  def mu_lock
    @_mutex.lock
  end

  # See Mutex#unlock
  def mu_unlock
    @_mutex.unlock
  end

  # See Mutex#sleep
  def sleep(timeout = nil)
    @_mutex.sleep(timeout)
  end

  private

  def mu_initialize # :nodoc:
    @_mutex = Thread::Mutex.new
  end

  def initialize(*args) # :nodoc:
    mu_initialize
    super
  end
  ruby2_keywords(:initialize) if respond_to?(:ruby2_keywords, true)
end
# frozen_string_literal: true

require 'socket'
require 'timeout'
require 'io/wait'

begin
  require 'securerandom'
rescue LoadError
end

# Resolv is a thread-aware DNS resolver library written in Ruby.  Resolv can
# handle multiple DNS requests concurrently without blocking the entire Ruby
# interpreter.
#
# See also resolv-replace.rb to replace the libc resolver with Resolv.
#
# Resolv can look up various DNS resources using the DNS module directly.
#
# Examples:
#
#   p Resolv.getaddress "www.ruby-lang.org"
#   p Resolv.getname "210.251.121.214"
#
#   Resolv::DNS.open do |dns|
#     ress = dns.getresources "www.ruby-lang.org", Resolv::DNS::Resource::IN::A
#     p ress.map(&:address)
#     ress = dns.getresources "ruby-lang.org", Resolv::DNS::Resource::IN::MX
#     p ress.map { |r| [r.exchange.to_s, r.preference] }
#   end
#
#
# == Bugs
#
# * NIS is not supported.
# * /etc/nsswitch.conf is not supported.

class Resolv

  ##
  # Looks up the first IP address for +name+.

  def self.getaddress(name)
    DefaultResolver.getaddress(name)
  end

  ##
  # Looks up all IP address for +name+.

  def self.getaddresses(name)
    DefaultResolver.getaddresses(name)
  end

  ##
  # Iterates over all IP addresses for +name+.

  def self.each_address(name, &block)
    DefaultResolver.each_address(name, &block)
  end

  ##
  # Looks up the hostname of +address+.

  def self.getname(address)
    DefaultResolver.getname(address)
  end

  ##
  # Looks up all hostnames for +address+.

  def self.getnames(address)
    DefaultResolver.getnames(address)
  end

  ##
  # Iterates over all hostnames for +address+.

  def self.each_name(address, &proc)
    DefaultResolver.each_name(address, &proc)
  end

  ##
  # Creates a new Resolv using +resolvers+.

  def initialize(resolvers=[Hosts.new, DNS.new])
    @resolvers = resolvers
  end

  ##
  # Looks up the first IP address for +name+.

  def getaddress(name)
    each_address(name) {|address| return address}
    raise ResolvError.new("no address for #{name}")
  end

  ##
  # Looks up all IP address for +name+.

  def getaddresses(name)
    ret = []
    each_address(name) {|address| ret << address}
    return ret
  end

  ##
  # Iterates over all IP addresses for +name+.

  def each_address(name)
    if AddressRegex =~ name
      yield name
      return
    end
    yielded = false
    @resolvers.each {|r|
      r.each_address(name) {|address|
        yield address.to_s
        yielded = true
      }
      return if yielded
    }
  end

  ##
  # Looks up the hostname of +address+.

  def getname(address)
    each_name(address) {|name| return name}
    raise ResolvError.new("no name for #{address}")
  end

  ##
  # Looks up all hostnames for +address+.

  def getnames(address)
    ret = []
    each_name(address) {|name| ret << name}
    return ret
  end

  ##
  # Iterates over all hostnames for +address+.

  def each_name(address)
    yielded = false
    @resolvers.each {|r|
      r.each_name(address) {|name|
        yield name.to_s
        yielded = true
      }
      return if yielded
    }
  end

  ##
  # Indicates a failure to resolve a name or address.

  class ResolvError < StandardError; end

  ##
  # Indicates a timeout resolving a name or address.

  class ResolvTimeout < Timeout::Error; end

  ##
  # Resolv::Hosts is a hostname resolver that uses the system hosts file.

  class Hosts
    if /mswin|mingw|cygwin/ =~ RUBY_PLATFORM and
      begin
        require 'win32/resolv'
        DefaultFileName = Win32::Resolv.get_hosts_path || IO::NULL
      rescue LoadError
      end
    end
    DefaultFileName ||= '/etc/hosts'

    ##
    # Creates a new Resolv::Hosts, using +filename+ for its data source.

    def initialize(filename = DefaultFileName)
      @filename = filename
      @mutex = Thread::Mutex.new
      @initialized = nil
    end

    def lazy_initialize # :nodoc:
      @mutex.synchronize {
        unless @initialized
          @name2addr = {}
          @addr2name = {}
          File.open(@filename, 'rb') {|f|
            f.each {|line|
              line.sub!(/#.*/, '')
              addr, hostname, *aliases = line.split(/\s+/)
              next unless addr
              @addr2name[addr] = [] unless @addr2name.include? addr
              @addr2name[addr] << hostname
              @addr2name[addr] += aliases
              @name2addr[hostname] = [] unless @name2addr.include? hostname
              @name2addr[hostname] << addr
              aliases.each {|n|
                @name2addr[n] = [] unless @name2addr.include? n
                @name2addr[n] << addr
              }
            }
          }
          @name2addr.each {|name, arr| arr.reverse!}
          @initialized = true
        end
      }
      self
    end

    ##
    # Gets the IP address of +name+ from the hosts file.

    def getaddress(name)
      each_address(name) {|address| return address}
      raise ResolvError.new("#{@filename} has no name: #{name}")
    end

    ##
    # Gets all IP addresses for +name+ from the hosts file.

    def getaddresses(name)
      ret = []
      each_address(name) {|address| ret << address}
      return ret
    end

    ##
    # Iterates over all IP addresses for +name+ retrieved from the hosts file.

    def each_address(name, &proc)
      lazy_initialize
      @name2addr[name]&.each(&proc)
    end

    ##
    # Gets the hostname of +address+ from the hosts file.

    def getname(address)
      each_name(address) {|name| return name}
      raise ResolvError.new("#{@filename} has no address: #{address}")
    end

    ##
    # Gets all hostnames for +address+ from the hosts file.

    def getnames(address)
      ret = []
      each_name(address) {|name| ret << name}
      return ret
    end

    ##
    # Iterates over all hostnames for +address+ retrieved from the hosts file.

    def each_name(address, &proc)
      lazy_initialize
      @addr2name[address]&.each(&proc)
    end
  end

  ##
  # Resolv::DNS is a DNS stub resolver.
  #
  # Information taken from the following places:
  #
  # * STD0013
  # * RFC 1035
  # * ftp://ftp.isi.edu/in-notes/iana/assignments/dns-parameters
  # * etc.

  class DNS

    ##
    # Default DNS Port

    Port = 53

    ##
    # Default DNS UDP packet size

    UDPSize = 512

    ##
    # Creates a new DNS resolver.  See Resolv::DNS.new for argument details.
    #
    # Yields the created DNS resolver to the block, if given, otherwise
    # returns it.

    def self.open(*args)
      dns = new(*args)
      return dns unless block_given?
      begin
        yield dns
      ensure
        dns.close
      end
    end

    ##
    # Creates a new DNS resolver.
    #
    # +config_info+ can be:
    #
    # nil:: Uses /etc/resolv.conf.
    # String:: Path to a file using /etc/resolv.conf's format.
    # Hash:: Must contain :nameserver, :search and :ndots keys.
    # :nameserver_port can be used to specify port number of nameserver address.
    #
    # The value of :nameserver should be an address string or
    # an array of address strings.
    # - :nameserver => '8.8.8.8'
    # - :nameserver => ['8.8.8.8', '8.8.4.4']
    #
    # The value of :nameserver_port should be an array of
    # pair of nameserver address and port number.
    # - :nameserver_port => [['8.8.8.8', 53], ['8.8.4.4', 53]]
    #
    # Example:
    #
    #   Resolv::DNS.new(:nameserver => ['210.251.121.21'],
    #                   :search => ['ruby-lang.org'],
    #                   :ndots => 1)

    def initialize(config_info=nil)
      @mutex = Thread::Mutex.new
      @config = Config.new(config_info)
      @initialized = nil
    end

    # Sets the resolver timeouts.  This may be a single positive number
    # or an array of positive numbers representing timeouts in seconds.
    # If an array is specified, a DNS request will retry and wait for
    # each successive interval in the array until a successful response
    # is received.  Specifying +nil+ reverts to the default timeouts:
    # [ 5, second = 5 * 2 / nameserver_count, 2 * second, 4 * second ]
    #
    # Example:
    #
    #   dns.timeouts = 3
    #
    def timeouts=(values)
      @config.timeouts = values
    end

    def lazy_initialize # :nodoc:
      @mutex.synchronize {
        unless @initialized
          @config.lazy_initialize
          @initialized = true
        end
      }
      self
    end

    ##
    # Closes the DNS resolver.

    def close
      @mutex.synchronize {
        if @initialized
          @initialized = false
        end
      }
    end

    ##
    # Gets the IP address of +name+ from the DNS resolver.
    #
    # +name+ can be a Resolv::DNS::Name or a String.  Retrieved address will
    # be a Resolv::IPv4 or Resolv::IPv6

    def getaddress(name)
      each_address(name) {|address| return address}
      raise ResolvError.new("DNS result has no information for #{name}")
    end

    ##
    # Gets all IP addresses for +name+ from the DNS resolver.
    #
    # +name+ can be a Resolv::DNS::Name or a String.  Retrieved addresses will
    # be a Resolv::IPv4 or Resolv::IPv6

    def getaddresses(name)
      ret = []
      each_address(name) {|address| ret << address}
      return ret
    end

    ##
    # Iterates over all IP addresses for +name+ retrieved from the DNS
    # resolver.
    #
    # +name+ can be a Resolv::DNS::Name or a String.  Retrieved addresses will
    # be a Resolv::IPv4 or Resolv::IPv6

    def each_address(name)
      each_resource(name, Resource::IN::A) {|resource| yield resource.address}
      if use_ipv6?
        each_resource(name, Resource::IN::AAAA) {|resource| yield resource.address}
      end
    end

    def use_ipv6? # :nodoc:
      begin
        list = Socket.ip_address_list
      rescue NotImplementedError
        return true
      end
      list.any? {|a| a.ipv6? && !a.ipv6_loopback? && !a.ipv6_linklocal? }
    end
    private :use_ipv6?

    ##
    # Gets the hostname for +address+ from the DNS resolver.
    #
    # +address+ must be a Resolv::IPv4, Resolv::IPv6 or a String.  Retrieved
    # name will be a Resolv::DNS::Name.

    def getname(address)
      each_name(address) {|name| return name}
      raise ResolvError.new("DNS result has no information for #{address}")
    end

    ##
    # Gets all hostnames for +address+ from the DNS resolver.
    #
    # +address+ must be a Resolv::IPv4, Resolv::IPv6 or a String.  Retrieved
    # names will be Resolv::DNS::Name instances.

    def getnames(address)
      ret = []
      each_name(address) {|name| ret << name}
      return ret
    end

    ##
    # Iterates over all hostnames for +address+ retrieved from the DNS
    # resolver.
    #
    # +address+ must be a Resolv::IPv4, Resolv::IPv6 or a String.  Retrieved
    # names will be Resolv::DNS::Name instances.

    def each_name(address)
      case address
      when Name
        ptr = address
      when IPv4, IPv6
        ptr = address.to_name
      when IPv4::Regex
        ptr = IPv4.create(address).to_name
      when IPv6::Regex
        ptr = IPv6.create(address).to_name
      else
        raise ResolvError.new("cannot interpret as address: #{address}")
      end
      each_resource(ptr, Resource::IN::PTR) {|resource| yield resource.name}
    end

    ##
    # Look up the +typeclass+ DNS resource of +name+.
    #
    # +name+ must be a Resolv::DNS::Name or a String.
    #
    # +typeclass+ should be one of the following:
    #
    # * Resolv::DNS::Resource::IN::A
    # * Resolv::DNS::Resource::IN::AAAA
    # * Resolv::DNS::Resource::IN::ANY
    # * Resolv::DNS::Resource::IN::CNAME
    # * Resolv::DNS::Resource::IN::HINFO
    # * Resolv::DNS::Resource::IN::MINFO
    # * Resolv::DNS::Resource::IN::MX
    # * Resolv::DNS::Resource::IN::NS
    # * Resolv::DNS::Resource::IN::PTR
    # * Resolv::DNS::Resource::IN::SOA
    # * Resolv::DNS::Resource::IN::TXT
    # * Resolv::DNS::Resource::IN::WKS
    #
    # Returned resource is represented as a Resolv::DNS::Resource instance,
    # i.e. Resolv::DNS::Resource::IN::A.

    def getresource(name, typeclass)
      each_resource(name, typeclass) {|resource| return resource}
      raise ResolvError.new("DNS result has no information for #{name}")
    end

    ##
    # Looks up all +typeclass+ DNS resources for +name+.  See #getresource for
    # argument details.

    def getresources(name, typeclass)
      ret = []
      each_resource(name, typeclass) {|resource| ret << resource}
      return ret
    end

    ##
    # Iterates over all +typeclass+ DNS resources for +name+.  See
    # #getresource for argument details.

    def each_resource(name, typeclass, &proc)
      fetch_resource(name, typeclass) {|reply, reply_name|
        extract_resources(reply, reply_name, typeclass, &proc)
      }
    end

    def fetch_resource(name, typeclass)
      lazy_initialize
      begin
        requester = make_udp_requester
      rescue Errno::EACCES
        # fall back to TCP
      end
      senders = {}
      begin
        @config.resolv(name) {|candidate, tout, nameserver, port|
          requester ||= make_tcp_requester(nameserver, port)
          msg = Message.new
          msg.rd = 1
          msg.add_question(candidate, typeclass)
          unless sender = senders[[candidate, nameserver, port]]
            sender = requester.sender(msg, candidate, nameserver, port)
            next if !sender
            senders[[candidate, nameserver, port]] = sender
          end
          reply, reply_name = requester.request(sender, tout)
          case reply.rcode
          when RCode::NoError
            if reply.tc == 1 and not Requester::TCP === requester
              requester.close
              # Retry via TCP:
              requester = make_tcp_requester(nameserver, port)
              senders = {}
              # This will use TCP for all remaining candidates (assuming the
              # current candidate does not already respond successfully via
              # TCP).  This makes sense because we already know the full
              # response will not fit in an untruncated UDP packet.
              redo
            else
              yield(reply, reply_name)
            end
            return
          when RCode::NXDomain
            raise Config::NXDomain.new(reply_name.to_s)
          else
            raise Config::OtherResolvError.new(reply_name.to_s)
          end
        }
      ensure
        requester&.close
      end
    end

    def make_udp_requester # :nodoc:
      nameserver_port = @config.nameserver_port
      if nameserver_port.length == 1
        Requester::ConnectedUDP.new(*nameserver_port[0])
      else
        Requester::UnconnectedUDP.new(*nameserver_port)
      end
    end

    def make_tcp_requester(host, port) # :nodoc:
      return Requester::TCP.new(host, port)
    end

    def extract_resources(msg, name, typeclass) # :nodoc:
      if typeclass < Resource::ANY
        n0 = Name.create(name)
        msg.each_resource {|n, ttl, data|
          yield data if n0 == n
        }
      end
      yielded = false
      n0 = Name.create(name)
      msg.each_resource {|n, ttl, data|
        if n0 == n
          case data
          when typeclass
            yield data
            yielded = true
          when Resource::CNAME
            n0 = data.name
          end
        end
      }
      return if yielded
      msg.each_resource {|n, ttl, data|
        if n0 == n
          case data
          when typeclass
            yield data
          end
        end
      }
    end

    if defined? SecureRandom
      def self.random(arg) # :nodoc:
        begin
          SecureRandom.random_number(arg)
        rescue NotImplementedError
          rand(arg)
        end
      end
    else
      def self.random(arg) # :nodoc:
        rand(arg)
      end
    end

    RequestID = {} # :nodoc:
    RequestIDMutex = Thread::Mutex.new # :nodoc:

    def self.allocate_request_id(host, port) # :nodoc:
      id = nil
      RequestIDMutex.synchronize {
        h = (RequestID[[host, port]] ||= {})
        begin
          id = random(0x0000..0xffff)
        end while h[id]
        h[id] = true
      }
      id
    end

    def self.free_request_id(host, port, id) # :nodoc:
      RequestIDMutex.synchronize {
        key = [host, port]
        if h = RequestID[key]
          h.delete id
          if h.empty?
            RequestID.delete key
          end
        end
      }
    end

    def self.bind_random_port(udpsock, bind_host="0.0.0.0") # :nodoc:
      begin
        port = random(1024..65535)
        udpsock.bind(bind_host, port)
      rescue Errno::EADDRINUSE, # POSIX
             Errno::EACCES, # SunOS: See PRIV_SYS_NFS in privileges(5)
             Errno::EPERM # FreeBSD: security.mac.portacl.port_high is configurable.  See mac_portacl(4).
        retry
      end
    end

    class Requester # :nodoc:
      def initialize
        @senders = {}
        @socks = nil
      end

      def request(sender, tout)
        start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
        timelimit = start + tout
        begin
          sender.send
        rescue Errno::EHOSTUNREACH, # multi-homed IPv6 may generate this
               Errno::ENETUNREACH
          raise ResolvTimeout
        end
        while true
          before_select = Process.clock_gettime(Process::CLOCK_MONOTONIC)
          timeout = timelimit - before_select
          if timeout <= 0
            raise ResolvTimeout
          end
          if @socks.size == 1
            select_result = @socks[0].wait_readable(timeout) ? [ @socks ] : nil
          else
            select_result = IO.select(@socks, nil, nil, timeout)
          end
          if !select_result
            after_select = Process.clock_gettime(Process::CLOCK_MONOTONIC)
            next if after_select < timelimit
            raise ResolvTimeout
          end
          begin
            reply, from = recv_reply(select_result[0])
          rescue Errno::ECONNREFUSED, # GNU/Linux, FreeBSD
                 Errno::ECONNRESET # Windows
            # No name server running on the server?
            # Don't wait anymore.
            raise ResolvTimeout
          end
          begin
            msg = Message.decode(reply)
          rescue DecodeError
            next # broken DNS message ignored
          end
          if sender == sender_for(from, msg)
            break
          else
            # unexpected DNS message ignored
          end
        end
        return msg, sender.data
      end

      def sender_for(addr, msg)
        @senders[[addr,msg.id]]
      end

      def close
        socks = @socks
        @socks = nil
        socks&.each(&:close)
      end

      class Sender # :nodoc:
        def initialize(msg, data, sock)
          @msg = msg
          @data = data
          @sock = sock
        end
      end

      class UnconnectedUDP < Requester # :nodoc:
        def initialize(*nameserver_port)
          super()
          @nameserver_port = nameserver_port
          @initialized = false
          @mutex = Thread::Mutex.new
        end

        def lazy_initialize
          @mutex.synchronize {
            next if @initialized
            @initialized = true
            @socks_hash = {}
            @socks = []
            @nameserver_port.each {|host, port|
              if host.index(':')
                bind_host = "::"
                af = Socket::AF_INET6
              else
                bind_host = "0.0.0.0"
                af = Socket::AF_INET
              end
              next if @socks_hash[bind_host]
              begin
                sock = UDPSocket.new(af)
              rescue Errno::EAFNOSUPPORT
                next # The kernel doesn't support the address family.
              end
              @socks << sock
              @socks_hash[bind_host] = sock
              sock.do_not_reverse_lookup = true
              DNS.bind_random_port(sock, bind_host)
            }
          }
          self
        end

        def recv_reply(readable_socks)
          lazy_initialize
          reply, from = readable_socks[0].recvfrom(UDPSize)
          return reply, [from[3],from[1]]
        end

        def sender(msg, data, host, port=Port)
          host = Addrinfo.ip(host).ip_address
          lazy_initialize
          sock = @socks_hash[host.index(':') ? "::" : "0.0.0.0"]
          return nil if !sock
          service = [host, port]
          id = DNS.allocate_request_id(host, port)
          request = msg.encode
          request[0,2] = [id].pack('n')
          return @senders[[service, id]] =
            Sender.new(request, data, sock, host, port)
        end

        def close
          @mutex.synchronize {
            if @initialized
              super
              @senders.each_key {|service, id|
                DNS.free_request_id(service[0], service[1], id)
              }
              @initialized = false
            end
          }
        end

        class Sender < Requester::Sender # :nodoc:
          def initialize(msg, data, sock, host, port)
            super(msg, data, sock)
            @host = host
            @port = port
          end
          attr_reader :data

          def send
            raise "@sock is nil." if @sock.nil?
            @sock.send(@msg, 0, @host, @port)
          end
        end
      end

      class ConnectedUDP < Requester # :nodoc:
        def initialize(host, port=Port)
          super()
          @host = host
          @port = port
          @mutex = Thread::Mutex.new
          @initialized = false
        end

        def lazy_initialize
          @mutex.synchronize {
            next if @initialized
            @initialized = true
            is_ipv6 = @host.index(':')
            sock = UDPSocket.new(is_ipv6 ? Socket::AF_INET6 : Socket::AF_INET)
            @socks = [sock]
            sock.do_not_reverse_lookup = true
            DNS.bind_random_port(sock, is_ipv6 ? "::" : "0.0.0.0")
            sock.connect(@host, @port)
          }
          self
        end

        def recv_reply(readable_socks)
          lazy_initialize
          reply = readable_socks[0].recv(UDPSize)
          return reply, nil
        end

        def sender(msg, data, host=@host, port=@port)
          lazy_initialize
          unless host == @host && port == @port
            raise RequestError.new("host/port don't match: #{host}:#{port}")
          end
          id = DNS.allocate_request_id(@host, @port)
          request = msg.encode
          request[0,2] = [id].pack('n')
          return @senders[[nil,id]] = Sender.new(request, data, @socks[0])
        end

        def close
          @mutex.synchronize do
            if @initialized
              super
              @senders.each_key {|from, id|
                DNS.free_request_id(@host, @port, id)
              }
              @initialized = false
            end
          end
        end

        class Sender < Requester::Sender # :nodoc:
          def send
            raise "@sock is nil." if @sock.nil?
            @sock.send(@msg, 0)
          end
          attr_reader :data
        end
      end

      class MDNSOneShot < UnconnectedUDP # :nodoc:
        def sender(msg, data, host, port=Port)
          lazy_initialize
          id = DNS.allocate_request_id(host, port)
          request = msg.encode
          request[0,2] = [id].pack('n')
          sock = @socks_hash[host.index(':') ? "::" : "0.0.0.0"]
          return @senders[id] =
            UnconnectedUDP::Sender.new(request, data, sock, host, port)
        end

        def sender_for(addr, msg)
          lazy_initialize
          @senders[msg.id]
        end
      end

      class TCP < Requester # :nodoc:
        def initialize(host, port=Port)
          super()
          @host = host
          @port = port
          sock = TCPSocket.new(@host, @port)
          @socks = [sock]
          @senders = {}
        end

        def recv_reply(readable_socks)
          len = readable_socks[0].read(2).unpack('n')[0]
          reply = @socks[0].read(len)
          return reply, nil
        end

        def sender(msg, data, host=@host, port=@port)
          unless host == @host && port == @port
            raise RequestError.new("host/port don't match: #{host}:#{port}")
          end
          id = DNS.allocate_request_id(@host, @port)
          request = msg.encode
          request[0,2] = [request.length, id].pack('nn')
          return @senders[[nil,id]] = Sender.new(request, data, @socks[0])
        end

        class Sender < Requester::Sender # :nodoc:
          def send
            @sock.print(@msg)
            @sock.flush
          end
          attr_reader :data
        end

        def close
          super
          @senders.each_key {|from,id|
            DNS.free_request_id(@host, @port, id)
          }
        end
      end

      ##
      # Indicates a problem with the DNS request.

      class RequestError < StandardError
      end
    end

    class Config # :nodoc:
      def initialize(config_info=nil)
        @mutex = Thread::Mutex.new
        @config_info = config_info
        @initialized = nil
        @timeouts = nil
      end

      def timeouts=(values)
        if values
          values = Array(values)
          values.each do |t|
            Numeric === t or raise ArgumentError, "#{t.inspect} is not numeric"
            t > 0.0 or raise ArgumentError, "timeout=#{t} must be positive"
          end
          @timeouts = values
        else
          @timeouts = nil
        end
      end

      def Config.parse_resolv_conf(filename)
        nameserver = []
        search = nil
        ndots = 1
        File.open(filename, 'rb') {|f|
          f.each {|line|
            line.sub!(/[#;].*/, '')
            keyword, *args = line.split(/\s+/)
            next unless keyword
            case keyword
            when 'nameserver'
              nameserver += args
            when 'domain'
              next if args.empty?
              search = [args[0]]
            when 'search'
              next if args.empty?
              search = args
            when 'options'
              args.each {|arg|
                case arg
                when /\Andots:(\d+)\z/
                  ndots = $1.to_i
                end
              }
            end
          }
        }
        return { :nameserver => nameserver, :search => search, :ndots => ndots }
      end

      def Config.default_config_hash(filename="/etc/resolv.conf")
        if File.exist? filename
          config_hash = Config.parse_resolv_conf(filename)
        else
          if /mswin|cygwin|mingw|bccwin/ =~ RUBY_PLATFORM
            require 'win32/resolv'
            search, nameserver = Win32::Resolv.get_resolv_info
            config_hash = {}
            config_hash[:nameserver] = nameserver if nameserver
            config_hash[:search] = [search].flatten if search
          end
        end
        config_hash || {}
      end

      def lazy_initialize
        @mutex.synchronize {
          unless @initialized
            @nameserver_port = []
            @search = nil
            @ndots = 1
            case @config_info
            when nil
              config_hash = Config.default_config_hash
            when String
              config_hash = Config.parse_resolv_conf(@config_info)
            when Hash
              config_hash = @config_info.dup
              if String === config_hash[:nameserver]
                config_hash[:nameserver] = [config_hash[:nameserver]]
              end
              if String === config_hash[:search]
                config_hash[:search] = [config_hash[:search]]
              end
            else
              raise ArgumentError.new("invalid resolv configuration: #{@config_info.inspect}")
            end
            if config_hash.include? :nameserver
              @nameserver_port = config_hash[:nameserver].map {|ns| [ns, Port] }
            end
            if config_hash.include? :nameserver_port
              @nameserver_port = config_hash[:nameserver_port].map {|ns, port| [ns, (port || Port)] }
            end
            @search = config_hash[:search] if config_hash.include? :search
            @ndots = config_hash[:ndots] if config_hash.include? :ndots

            if @nameserver_port.empty?
              @nameserver_port << ['0.0.0.0', Port]
            end
            if @search
              @search = @search.map {|arg| Label.split(arg) }
            else
              hostname = Socket.gethostname
              if /\./ =~ hostname
                @search = [Label.split($')]
              else
                @search = [[]]
              end
            end

            if !@nameserver_port.kind_of?(Array) ||
               @nameserver_port.any? {|ns_port|
                  !(Array === ns_port) ||
                  ns_port.length != 2
                  !(String === ns_port[0]) ||
                  !(Integer === ns_port[1])
               }
              raise ArgumentError.new("invalid nameserver config: #{@nameserver_port.inspect}")
            end

            if !@search.kind_of?(Array) ||
               !@search.all? {|ls| ls.all? {|l| Label::Str === l } }
              raise ArgumentError.new("invalid search config: #{@search.inspect}")
            end

            if !@ndots.kind_of?(Integer)
              raise ArgumentError.new("invalid ndots config: #{@ndots.inspect}")
            end

            @initialized = true
          end
        }
        self
      end

      def single?
        lazy_initialize
        if @nameserver_port.length == 1
          return @nameserver_port[0]
        else
          return nil
        end
      end

      def nameserver_port
        @nameserver_port
      end

      def generate_candidates(name)
        candidates = nil
        name = Name.create(name)
        if name.absolute?
          candidates = [name]
        else
          if @ndots <= name.length - 1
            candidates = [Name.new(name.to_a)]
          else
            candidates = []
          end
          candidates.concat(@search.map {|domain| Name.new(name.to_a + domain)})
          fname = Name.create("#{name}.")
          if !candidates.include?(fname)
            candidates << fname
          end
        end
        return candidates
      end

      InitialTimeout = 5

      def generate_timeouts
        ts = [InitialTimeout]
        ts << ts[-1] * 2 / @nameserver_port.length
        ts << ts[-1] * 2
        ts << ts[-1] * 2
        return ts
      end

      def resolv(name)
        candidates = generate_candidates(name)
        timeouts = @timeouts || generate_timeouts
        begin
          candidates.each {|candidate|
            begin
              timeouts.each {|tout|
                @nameserver_port.each {|nameserver, port|
                  begin
                    yield candidate, tout, nameserver, port
                  rescue ResolvTimeout
                  end
                }
              }
              raise ResolvError.new("DNS resolv timeout: #{name}")
            rescue NXDomain
            end
          }
        rescue ResolvError
        end
      end

      ##
      # Indicates no such domain was found.

      class NXDomain < ResolvError
      end

      ##
      # Indicates some other unhandled resolver error was encountered.

      class OtherResolvError < ResolvError
      end
    end

    module OpCode # :nodoc:
      Query = 0
      IQuery = 1
      Status = 2
      Notify = 4
      Update = 5
    end

    module RCode # :nodoc:
      NoError = 0
      FormErr = 1
      ServFail = 2
      NXDomain = 3
      NotImp = 4
      Refused = 5
      YXDomain = 6
      YXRRSet = 7
      NXRRSet = 8
      NotAuth = 9
      NotZone = 10
      BADVERS = 16
      BADSIG = 16
      BADKEY = 17
      BADTIME = 18
      BADMODE = 19
      BADNAME = 20
      BADALG = 21
    end

    ##
    # Indicates that the DNS response was unable to be decoded.

    class DecodeError < StandardError
    end

    ##
    # Indicates that the DNS request was unable to be encoded.

    class EncodeError < StandardError
    end

    module Label # :nodoc:
      def self.split(arg)
        labels = []
        arg.scan(/[^\.]+/) {labels << Str.new($&)}
        return labels
      end

      class Str # :nodoc:
        def initialize(string)
          @string = string
          # case insensivity of DNS labels doesn't apply non-ASCII characters. [RFC 4343]
          # This assumes @string is given in ASCII compatible encoding.
          @downcase = string.b.downcase
        end
        attr_reader :string, :downcase

        def to_s
          return @string
        end

        def inspect
          return "#<#{self.class} #{self}>"
        end

        def ==(other)
          return self.class == other.class && @downcase == other.downcase
        end

        def eql?(other)
          return self == other
        end

        def hash
          return @downcase.hash
        end
      end
    end

    ##
    # A representation of a DNS name.

    class Name

      ##
      # Creates a new DNS name from +arg+.  +arg+ can be:
      #
      # Name:: returns +arg+.
      # String:: Creates a new Name.

      def self.create(arg)
        case arg
        when Name
          return arg
        when String
          return Name.new(Label.split(arg), /\.\z/ =~ arg ? true : false)
        else
          raise ArgumentError.new("cannot interpret as DNS name: #{arg.inspect}")
        end
      end

      def initialize(labels, absolute=true) # :nodoc:
        labels = labels.map {|label|
          case label
          when String then Label::Str.new(label)
          when Label::Str then label
          else
            raise ArgumentError, "unexpected label: #{label.inspect}"
          end
        }
        @labels = labels
        @absolute = absolute
      end

      def inspect # :nodoc:
        "#<#{self.class}: #{self}#{@absolute ? '.' : ''}>"
      end

      ##
      # True if this name is absolute.

      def absolute?
        return @absolute
      end

      def ==(other) # :nodoc:
        return false unless Name === other
        return false unless @absolute == other.absolute?
        return @labels == other.to_a
      end

      alias eql? == # :nodoc:

      ##
      # Returns true if +other+ is a subdomain.
      #
      # Example:
      #
      #   domain = Resolv::DNS::Name.create("y.z")
      #   p Resolv::DNS::Name.create("w.x.y.z").subdomain_of?(domain) #=> true
      #   p Resolv::DNS::Name.create("x.y.z").subdomain_of?(domain) #=> true
      #   p Resolv::DNS::Name.create("y.z").subdomain_of?(domain) #=> false
      #   p Resolv::DNS::Name.create("z").subdomain_of?(domain) #=> false
      #   p Resolv::DNS::Name.create("x.y.z.").subdomain_of?(domain) #=> false
      #   p Resolv::DNS::Name.create("w.z").subdomain_of?(domain) #=> false
      #

      def subdomain_of?(other)
        raise ArgumentError, "not a domain name: #{other.inspect}" unless Name === other
        return false if @absolute != other.absolute?
        other_len = other.length
        return false if @labels.length <= other_len
        return @labels[-other_len, other_len] == other.to_a
      end

      def hash # :nodoc:
        return @labels.hash ^ @absolute.hash
      end

      def to_a # :nodoc:
        return @labels
      end

      def length # :nodoc:
        return @labels.length
      end

      def [](i) # :nodoc:
        return @labels[i]
      end

      ##
      # returns the domain name as a string.
      #
      # The domain name doesn't have a trailing dot even if the name object is
      # absolute.
      #
      # Example:
      #
      #   p Resolv::DNS::Name.create("x.y.z.").to_s #=> "x.y.z"
      #   p Resolv::DNS::Name.create("x.y.z").to_s #=> "x.y.z"

      def to_s
        return @labels.join('.')
      end
    end

    class Message # :nodoc:
      @@identifier = -1

      def initialize(id = (@@identifier += 1) & 0xffff)
        @id = id
        @qr = 0
        @opcode = 0
        @aa = 0
        @tc = 0
        @rd = 0 # recursion desired
        @ra = 0 # recursion available
        @rcode = 0
        @question = []
        @answer = []
        @authority = []
        @additional = []
      end

      attr_accessor :id, :qr, :opcode, :aa, :tc, :rd, :ra, :rcode
      attr_reader :question, :answer, :authority, :additional

      def ==(other)
        return @id == other.id &&
               @qr == other.qr &&
               @opcode == other.opcode &&
               @aa == other.aa &&
               @tc == other.tc &&
               @rd == other.rd &&
               @ra == other.ra &&
               @rcode == other.rcode &&
               @question == other.question &&
               @answer == other.answer &&
               @authority == other.authority &&
               @additional == other.additional
      end

      def add_question(name, typeclass)
        @question << [Name.create(name), typeclass]
      end

      def each_question
        @question.each {|name, typeclass|
          yield name, typeclass
        }
      end

      def add_answer(name, ttl, data)
        @answer << [Name.create(name), ttl, data]
      end

      def each_answer
        @answer.each {|name, ttl, data|
          yield name, ttl, data
        }
      end

      def add_authority(name, ttl, data)
        @authority << [Name.create(name), ttl, data]
      end

      def each_authority
        @authority.each {|name, ttl, data|
          yield name, ttl, data
        }
      end

      def add_additional(name, ttl, data)
        @additional << [Name.create(name), ttl, data]
      end

      def each_additional
        @additional.each {|name, ttl, data|
          yield name, ttl, data
        }
      end

      def each_resource
        each_answer {|name, ttl, data| yield name, ttl, data}
        each_authority {|name, ttl, data| yield name, ttl, data}
        each_additional {|name, ttl, data| yield name, ttl, data}
      end

      def encode
        return MessageEncoder.new {|msg|
          msg.put_pack('nnnnnn',
            @id,
            (@qr & 1) << 15 |
            (@opcode & 15) << 11 |
            (@aa & 1) << 10 |
            (@tc & 1) << 9 |
            (@rd & 1) << 8 |
            (@ra & 1) << 7 |
            (@rcode & 15),
            @question.length,
            @answer.length,
            @authority.length,
            @additional.length)
          @question.each {|q|
            name, typeclass = q
            msg.put_name(name)
            msg.put_pack('nn', typeclass::TypeValue, typeclass::ClassValue)
          }
          [@answer, @authority, @additional].each {|rr|
            rr.each {|r|
              name, ttl, data = r
              msg.put_name(name)
              msg.put_pack('nnN', data.class::TypeValue, data.class::ClassValue, ttl)
              msg.put_length16 {data.encode_rdata(msg)}
            }
          }
        }.to_s
      end

      class MessageEncoder # :nodoc:
        def initialize
          @data = ''.dup
          @names = {}
          yield self
        end

        def to_s
          return @data
        end

        def put_bytes(d)
          @data << d
        end

        def put_pack(template, *d)
          @data << d.pack(template)
        end

        def put_length16
          length_index = @data.length
          @data << "\0\0"
          data_start = @data.length
          yield
          data_end = @data.length
          @data[length_index, 2] = [data_end - data_start].pack("n")
        end

        def put_string(d)
          self.put_pack("C", d.length)
          @data << d
        end

        def put_string_list(ds)
          ds.each {|d|
            self.put_string(d)
          }
        end

        def put_name(d)
          put_labels(d.to_a)
        end

        def put_labels(d)
          d.each_index {|i|
            domain = d[i..-1]
            if idx = @names[domain]
              self.put_pack("n", 0xc000 | idx)
              return
            else
              if @data.length < 0x4000
                @names[domain] = @data.length
              end
              self.put_label(d[i])
            end
          }
          @data << "\0"
        end

        def put_label(d)
          self.put_string(d.to_s)
        end
      end

      def Message.decode(m)
        o = Message.new(0)
        MessageDecoder.new(m) {|msg|
          id, flag, qdcount, ancount, nscount, arcount =
            msg.get_unpack('nnnnnn')
          o.id = id
          o.qr = (flag >> 15) & 1
          o.opcode = (flag >> 11) & 15
          o.aa = (flag >> 10) & 1
          o.tc = (flag >> 9) & 1
          o.rd = (flag >> 8) & 1
          o.ra = (flag >> 7) & 1
          o.rcode = flag & 15
          (1..qdcount).each {
            name, typeclass = msg.get_question
            o.add_question(name, typeclass)
          }
          (1..ancount).each {
            name, ttl, data = msg.get_rr
            o.add_answer(name, ttl, data)
          }
          (1..nscount).each {
            name, ttl, data = msg.get_rr
            o.add_authority(name, ttl, data)
          }
          (1..arcount).each {
            name, ttl, data = msg.get_rr
            o.add_additional(name, ttl, data)
          }
        }
        return o
      end

      class MessageDecoder # :nodoc:
        def initialize(data)
          @data = data
          @index = 0
          @limit = data.bytesize
          yield self
        end

        def inspect
          "\#<#{self.class}: #{@data.byteslice(0, @index).inspect} #{@data.byteslice(@index..-1).inspect}>"
        end

        def get_length16
          len, = self.get_unpack('n')
          save_limit = @limit
          @limit = @index + len
          d = yield(len)
          if @index < @limit
            raise DecodeError.new("junk exists")
          elsif @limit < @index
            raise DecodeError.new("limit exceeded")
          end
          @limit = save_limit
          return d
        end

        def get_bytes(len = @limit - @index)
          raise DecodeError.new("limit exceeded") if @limit < @index + len
          d = @data.byteslice(@index, len)
          @index += len
          return d
        end

        def get_unpack(template)
          len = 0
          template.each_byte {|byte|
            byte = "%c" % byte
            case byte
            when ?c, ?C
              len += 1
            when ?n
              len += 2
            when ?N
              len += 4
            else
              raise StandardError.new("unsupported template: '#{byte.chr}' in '#{template}'")
            end
          }
          raise DecodeError.new("limit exceeded") if @limit < @index + len
          arr = @data.unpack("@#{@index}#{template}")
          @index += len
          return arr
        end

        def get_string
          raise DecodeError.new("limit exceeded") if @limit <= @index
          len = @data.getbyte(@index)
          raise DecodeError.new("limit exceeded") if @limit < @index + 1 + len
          d = @data.byteslice(@index + 1, len)
          @index += 1 + len
          return d
        end

        def get_string_list
          strings = []
          while @index < @limit
            strings << self.get_string
          end
          strings
        end

        def get_name
          return Name.new(self.get_labels)
        end

        def get_labels
          prev_index = @index
          save_index = nil
          d = []
          while true
            raise DecodeError.new("limit exceeded") if @limit <= @index
            case @data.getbyte(@index)
            when 0
              @index += 1
              if save_index
                @index = save_index
              end
              return d
            when 192..255
              idx = self.get_unpack('n')[0] & 0x3fff
              if prev_index <= idx
                raise DecodeError.new("non-backward name pointer")
              end
              prev_index = idx
              if !save_index
                save_index = @index
              end
              @index = idx
            else
              d << self.get_label
            end
          end
        end

        def get_label
          return Label::Str.new(self.get_string)
        end

        def get_question
          name = self.get_name
          type, klass = self.get_unpack("nn")
          return name, Resource.get_class(type, klass)
        end

        def get_rr
          name = self.get_name
          type, klass, ttl = self.get_unpack('nnN')
          typeclass = Resource.get_class(type, klass)
          res = self.get_length16 do
            begin
              typeclass.decode_rdata self
            rescue => e
              raise DecodeError, e.message, e.backtrace
            end
          end
          res.instance_variable_set :@ttl, ttl
          return name, ttl, res
        end
      end
    end

    ##
    # A DNS query abstract class.

    class Query
      def encode_rdata(msg) # :nodoc:
        raise EncodeError.new("#{self.class} is query.")
      end

      def self.decode_rdata(msg) # :nodoc:
        raise DecodeError.new("#{self.class} is query.")
      end
    end

    ##
    # A DNS resource abstract class.

    class Resource < Query

      ##
      # Remaining Time To Live for this Resource.

      attr_reader :ttl

      ClassHash = {} # :nodoc:

      def encode_rdata(msg) # :nodoc:
        raise NotImplementedError.new
      end

      def self.decode_rdata(msg) # :nodoc:
        raise NotImplementedError.new
      end

      def ==(other) # :nodoc:
        return false unless self.class == other.class
        s_ivars = self.instance_variables
        s_ivars.sort!
        s_ivars.delete :@ttl
        o_ivars = other.instance_variables
        o_ivars.sort!
        o_ivars.delete :@ttl
        return s_ivars == o_ivars &&
          s_ivars.collect {|name| self.instance_variable_get name} ==
            o_ivars.collect {|name| other.instance_variable_get name}
      end

      def eql?(other) # :nodoc:
        return self == other
      end

      def hash # :nodoc:
        h = 0
        vars = self.instance_variables
        vars.delete :@ttl
        vars.each {|name|
          h ^= self.instance_variable_get(name).hash
        }
        return h
      end

      def self.get_class(type_value, class_value) # :nodoc:
        return ClassHash[[type_value, class_value]] ||
               Generic.create(type_value, class_value)
      end

      ##
      # A generic resource abstract class.

      class Generic < Resource

        ##
        # Creates a new generic resource.

        def initialize(data)
          @data = data
        end

        ##
        # Data for this generic resource.

        attr_reader :data

        def encode_rdata(msg) # :nodoc:
          msg.put_bytes(data)
        end

        def self.decode_rdata(msg) # :nodoc:
          return self.new(msg.get_bytes)
        end

        def self.create(type_value, class_value) # :nodoc:
          c = Class.new(Generic)
          c.const_set(:TypeValue, type_value)
          c.const_set(:ClassValue, class_value)
          Generic.const_set("Type#{type_value}_Class#{class_value}", c)
          ClassHash[[type_value, class_value]] = c
          return c
        end
      end

      ##
      # Domain Name resource abstract class.

      class DomainName < Resource

        ##
        # Creates a new DomainName from +name+.

        def initialize(name)
          @name = name
        end

        ##
        # The name of this DomainName.

        attr_reader :name

        def encode_rdata(msg) # :nodoc:
          msg.put_name(@name)
        end

        def self.decode_rdata(msg) # :nodoc:
          return self.new(msg.get_name)
        end
      end

      # Standard (class generic) RRs

      ClassValue = nil # :nodoc:

      ##
      # An authoritative name server.

      class NS < DomainName
        TypeValue = 2 # :nodoc:
      end

      ##
      # The canonical name for an alias.

      class CNAME < DomainName
        TypeValue = 5 # :nodoc:
      end

      ##
      # Start Of Authority resource.

      class SOA < Resource

        TypeValue = 6 # :nodoc:

        ##
        # Creates a new SOA record.  See the attr documentation for the
        # details of each argument.

        def initialize(mname, rname, serial, refresh, retry_, expire, minimum)
          @mname = mname
          @rname = rname
          @serial = serial
          @refresh = refresh
          @retry = retry_
          @expire = expire
          @minimum = minimum
        end

        ##
        # Name of the host where the master zone file for this zone resides.

        attr_reader :mname

        ##
        # The person responsible for this domain name.

        attr_reader :rname

        ##
        # The version number of the zone file.

        attr_reader :serial

        ##
        # How often, in seconds, a secondary name server is to check for
        # updates from the primary name server.

        attr_reader :refresh

        ##
        # How often, in seconds, a secondary name server is to retry after a
        # failure to check for a refresh.

        attr_reader :retry

        ##
        # Time in seconds that a secondary name server is to use the data
        # before refreshing from the primary name server.

        attr_reader :expire

        ##
        # The minimum number of seconds to be used for TTL values in RRs.

        attr_reader :minimum

        def encode_rdata(msg) # :nodoc:
          msg.put_name(@mname)
          msg.put_name(@rname)
          msg.put_pack('NNNNN', @serial, @refresh, @retry, @expire, @minimum)
        end

        def self.decode_rdata(msg) # :nodoc:
          mname = msg.get_name
          rname = msg.get_name
          serial, refresh, retry_, expire, minimum = msg.get_unpack('NNNNN')
          return self.new(
            mname, rname, serial, refresh, retry_, expire, minimum)
        end
      end

      ##
      # A Pointer to another DNS name.

      class PTR < DomainName
        TypeValue = 12 # :nodoc:
      end

      ##
      # Host Information resource.

      class HINFO < Resource

        TypeValue = 13 # :nodoc:

        ##
        # Creates a new HINFO running +os+ on +cpu+.

        def initialize(cpu, os)
          @cpu = cpu
          @os = os
        end

        ##
        # CPU architecture for this resource.

        attr_reader :cpu

        ##
        # Operating system for this resource.

        attr_reader :os

        def encode_rdata(msg) # :nodoc:
          msg.put_string(@cpu)
          msg.put_string(@os)
        end

        def self.decode_rdata(msg) # :nodoc:
          cpu = msg.get_string
          os = msg.get_string
          return self.new(cpu, os)
        end
      end

      ##
      # Mailing list or mailbox information.

      class MINFO < Resource

        TypeValue = 14 # :nodoc:

        def initialize(rmailbx, emailbx)
          @rmailbx = rmailbx
          @emailbx = emailbx
        end

        ##
        # Domain name responsible for this mail list or mailbox.

        attr_reader :rmailbx

        ##
        # Mailbox to use for error messages related to the mail list or mailbox.

        attr_reader :emailbx

        def encode_rdata(msg) # :nodoc:
          msg.put_name(@rmailbx)
          msg.put_name(@emailbx)
        end

        def self.decode_rdata(msg) # :nodoc:
          rmailbx = msg.get_string
          emailbx = msg.get_string
          return self.new(rmailbx, emailbx)
        end
      end

      ##
      # Mail Exchanger resource.

      class MX < Resource

        TypeValue= 15 # :nodoc:

        ##
        # Creates a new MX record with +preference+, accepting mail at
        # +exchange+.

        def initialize(preference, exchange)
          @preference = preference
          @exchange = exchange
        end

        ##
        # The preference for this MX.

        attr_reader :preference

        ##
        # The host of this MX.

        attr_reader :exchange

        def encode_rdata(msg) # :nodoc:
          msg.put_pack('n', @preference)
          msg.put_name(@exchange)
        end

        def self.decode_rdata(msg) # :nodoc:
          preference, = msg.get_unpack('n')
          exchange = msg.get_name
          return self.new(preference, exchange)
        end
      end

      ##
      # Unstructured text resource.

      class TXT < Resource

        TypeValue = 16 # :nodoc:

        def initialize(first_string, *rest_strings)
          @strings = [first_string, *rest_strings]
        end

        ##
        # Returns an Array of Strings for this TXT record.

        attr_reader :strings

        ##
        # Returns the concatenated string from +strings+.

        def data
          @strings.join("")
        end

        def encode_rdata(msg) # :nodoc:
          msg.put_string_list(@strings)
        end

        def self.decode_rdata(msg) # :nodoc:
          strings = msg.get_string_list
          return self.new(*strings)
        end
      end

      ##
      # Location resource

      class LOC < Resource

        TypeValue = 29 # :nodoc:

        def initialize(version, ssize, hprecision, vprecision, latitude, longitude, altitude)
          @version    = version
          @ssize      = Resolv::LOC::Size.create(ssize)
          @hprecision = Resolv::LOC::Size.create(hprecision)
          @vprecision = Resolv::LOC::Size.create(vprecision)
          @latitude   = Resolv::LOC::Coord.create(latitude)
          @longitude  = Resolv::LOC::Coord.create(longitude)
          @altitude   = Resolv::LOC::Alt.create(altitude)
        end

        ##
        # Returns the version value for this LOC record which should always be 00

        attr_reader :version

        ##
        # The spherical size of this LOC
        # in meters using scientific notation as 2 integers of XeY

        attr_reader :ssize

        ##
        # The horizontal precision using ssize type values
        # in meters using scientific notation as 2 integers of XeY
        # for precision use value/2 e.g. 2m = +/-1m

        attr_reader :hprecision

        ##
        # The vertical precision using ssize type values
        # in meters using scientific notation as 2 integers of XeY
        # for precision use value/2 e.g. 2m = +/-1m

        attr_reader :vprecision

        ##
        # The latitude for this LOC where 2**31 is the equator
        # in thousandths of an arc second as an unsigned 32bit integer

        attr_reader :latitude

        ##
        # The longitude for this LOC where 2**31 is the prime meridian
        # in thousandths of an arc second as an unsigned 32bit integer

        attr_reader :longitude

        ##
        # The altitude of the LOC above a reference sphere whose surface sits 100km below the WGS84 spheroid
        # in centimeters as an unsigned 32bit integer

        attr_reader :altitude


        def encode_rdata(msg) # :nodoc:
          msg.put_bytes(@version)
          msg.put_bytes(@ssize.scalar)
          msg.put_bytes(@hprecision.scalar)
          msg.put_bytes(@vprecision.scalar)
          msg.put_bytes(@latitude.coordinates)
          msg.put_bytes(@longitude.coordinates)
          msg.put_bytes(@altitude.altitude)
        end

        def self.decode_rdata(msg) # :nodoc:
          version    = msg.get_bytes(1)
          ssize      = msg.get_bytes(1)
          hprecision = msg.get_bytes(1)
          vprecision = msg.get_bytes(1)
          latitude   = msg.get_bytes(4)
          longitude  = msg.get_bytes(4)
          altitude   = msg.get_bytes(4)
          return self.new(
            version,
            Resolv::LOC::Size.new(ssize),
            Resolv::LOC::Size.new(hprecision),
            Resolv::LOC::Size.new(vprecision),
            Resolv::LOC::Coord.new(latitude,"lat"),
            Resolv::LOC::Coord.new(longitude,"lon"),
            Resolv::LOC::Alt.new(altitude)
          )
        end
      end

      ##
      # A Query type requesting any RR.

      class ANY < Query
        TypeValue = 255 # :nodoc:
      end

      ClassInsensitiveTypes = [ # :nodoc:
        NS, CNAME, SOA, PTR, HINFO, MINFO, MX, TXT, LOC, ANY
      ]

      ##
      # module IN contains ARPA Internet specific RRs.

      module IN

        ClassValue = 1 # :nodoc:

        ClassInsensitiveTypes.each {|s|
          c = Class.new(s)
          c.const_set(:TypeValue, s::TypeValue)
          c.const_set(:ClassValue, ClassValue)
          ClassHash[[s::TypeValue, ClassValue]] = c
          self.const_set(s.name.sub(/.*::/, ''), c)
        }

        ##
        # IPv4 Address resource

        class A < Resource
          TypeValue = 1
          ClassValue = IN::ClassValue
          ClassHash[[TypeValue, ClassValue]] = self # :nodoc:

          ##
          # Creates a new A for +address+.

          def initialize(address)
            @address = IPv4.create(address)
          end

          ##
          # The Resolv::IPv4 address for this A.

          attr_reader :address

          def encode_rdata(msg) # :nodoc:
            msg.put_bytes(@address.address)
          end

          def self.decode_rdata(msg) # :nodoc:
            return self.new(IPv4.new(msg.get_bytes(4)))
          end
        end

        ##
        # Well Known Service resource.

        class WKS < Resource
          TypeValue = 11
          ClassValue = IN::ClassValue
          ClassHash[[TypeValue, ClassValue]] = self # :nodoc:

          def initialize(address, protocol, bitmap)
            @address = IPv4.create(address)
            @protocol = protocol
            @bitmap = bitmap
          end

          ##
          # The host these services run on.

          attr_reader :address

          ##
          # IP protocol number for these services.

          attr_reader :protocol

          ##
          # A bit map of enabled services on this host.
          #
          # If protocol is 6 (TCP) then the 26th bit corresponds to the SMTP
          # service (port 25).  If this bit is set, then an SMTP server should
          # be listening on TCP port 25; if zero, SMTP service is not
          # supported.

          attr_reader :bitmap

          def encode_rdata(msg) # :nodoc:
            msg.put_bytes(@address.address)
            msg.put_pack("n", @protocol)
            msg.put_bytes(@bitmap)
          end

          def self.decode_rdata(msg) # :nodoc:
            address = IPv4.new(msg.get_bytes(4))
            protocol, = msg.get_unpack("n")
            bitmap = msg.get_bytes
            return self.new(address, protocol, bitmap)
          end
        end

        ##
        # An IPv6 address record.

        class AAAA < Resource
          TypeValue = 28
          ClassValue = IN::ClassValue
          ClassHash[[TypeValue, ClassValue]] = self # :nodoc:

          ##
          # Creates a new AAAA for +address+.

          def initialize(address)
            @address = IPv6.create(address)
          end

          ##
          # The Resolv::IPv6 address for this AAAA.

          attr_reader :address

          def encode_rdata(msg) # :nodoc:
            msg.put_bytes(@address.address)
          end

          def self.decode_rdata(msg) # :nodoc:
            return self.new(IPv6.new(msg.get_bytes(16)))
          end
        end

        ##
        # SRV resource record defined in RFC 2782
        #
        # These records identify the hostname and port that a service is
        # available at.

        class SRV < Resource
          TypeValue = 33
          ClassValue = IN::ClassValue
          ClassHash[[TypeValue, ClassValue]] = self # :nodoc:

          # Create a SRV resource record.
          #
          # See the documentation for #priority, #weight, #port and #target
          # for +priority+, +weight+, +port and +target+ respectively.

          def initialize(priority, weight, port, target)
            @priority = priority.to_int
            @weight = weight.to_int
            @port = port.to_int
            @target = Name.create(target)
          end

          # The priority of this target host.
          #
          # A client MUST attempt to contact the target host with the
          # lowest-numbered priority it can reach; target hosts with the same
          # priority SHOULD be tried in an order defined by the weight field.
          # The range is 0-65535.  Note that it is not widely implemented and
          # should be set to zero.

          attr_reader :priority

          # A server selection mechanism.
          #
          # The weight field specifies a relative weight for entries with the
          # same priority. Larger weights SHOULD be given a proportionately
          # higher probability of being selected. The range of this number is
          # 0-65535.  Domain administrators SHOULD use Weight 0 when there
          # isn't any server selection to do, to make the RR easier to read
          # for humans (less noisy). Note that it is not widely implemented
          # and should be set to zero.

          attr_reader :weight

          # The port on this target host of this service.
          #
          # The range is 0-65535.

          attr_reader :port

          # The domain name of the target host.
          #
          # A target of "." means that the service is decidedly not available
          # at this domain.

          attr_reader :target

          def encode_rdata(msg) # :nodoc:
            msg.put_pack("n", @priority)
            msg.put_pack("n", @weight)
            msg.put_pack("n", @port)
            msg.put_name(@target)
          end

          def self.decode_rdata(msg) # :nodoc:
            priority, = msg.get_unpack("n")
            weight,   = msg.get_unpack("n")
            port,     = msg.get_unpack("n")
            target    = msg.get_name
            return self.new(priority, weight, port, target)
          end
        end
      end
    end
  end

  ##
  # A Resolv::DNS IPv4 address.

  class IPv4

    ##
    # Regular expression IPv4 addresses must match.

    Regex256 = /0
               |1(?:[0-9][0-9]?)?
               |2(?:[0-4][0-9]?|5[0-5]?|[6-9])?
               |[3-9][0-9]?/x
    Regex = /\A(#{Regex256})\.(#{Regex256})\.(#{Regex256})\.(#{Regex256})\z/

    def self.create(arg)
      case arg
      when IPv4
        return arg
      when Regex
        if (0..255) === (a = $1.to_i) &&
           (0..255) === (b = $2.to_i) &&
           (0..255) === (c = $3.to_i) &&
           (0..255) === (d = $4.to_i)
          return self.new([a, b, c, d].pack("CCCC"))
        else
          raise ArgumentError.new("IPv4 address with invalid value: " + arg)
        end
      else
        raise ArgumentError.new("cannot interpret as IPv4 address: #{arg.inspect}")
      end
    end

    def initialize(address) # :nodoc:
      unless address.kind_of?(String)
        raise ArgumentError, 'IPv4 address must be a string'
      end
      unless address.length == 4
        raise ArgumentError, "IPv4 address expects 4 bytes but #{address.length} bytes"
      end
      @address = address
    end

    ##
    # A String representation of this IPv4 address.

    ##
    # The raw IPv4 address as a String.

    attr_reader :address

    def to_s # :nodoc:
      return sprintf("%d.%d.%d.%d", *@address.unpack("CCCC"))
    end

    def inspect # :nodoc:
      return "#<#{self.class} #{self}>"
    end

    ##
    # Turns this IPv4 address into a Resolv::DNS::Name.

    def to_name
      return DNS::Name.create(
        '%d.%d.%d.%d.in-addr.arpa.' % @address.unpack('CCCC').reverse)
    end

    def ==(other) # :nodoc:
      return @address == other.address
    end

    def eql?(other) # :nodoc:
      return self == other
    end

    def hash # :nodoc:
      return @address.hash
    end
  end

  ##
  # A Resolv::DNS IPv6 address.

  class IPv6

    ##
    # IPv6 address format a:b:c:d:e:f:g:h
    Regex_8Hex = /\A
      (?:[0-9A-Fa-f]{1,4}:){7}
         [0-9A-Fa-f]{1,4}
      \z/x

    ##
    # Compressed IPv6 address format a::b

    Regex_CompressedHex = /\A
      ((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::
      ((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)
      \z/x

    ##
    # IPv4 mapped IPv6 address format a:b:c:d:e:f:w.x.y.z

    Regex_6Hex4Dec = /\A
      ((?:[0-9A-Fa-f]{1,4}:){6,6})
      (\d+)\.(\d+)\.(\d+)\.(\d+)
      \z/x

    ##
    # Compressed IPv4 mapped IPv6 address format a::b:w.x.y.z

    Regex_CompressedHex4Dec = /\A
      ((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::
      ((?:[0-9A-Fa-f]{1,4}:)*)
      (\d+)\.(\d+)\.(\d+)\.(\d+)
      \z/x

    ##
    # IPv6 link local address format fe80:b:c:d:e:f:g:h%em1
    Regex_8HexLinkLocal = /\A
      [Ff][Ee]80
      (?::[0-9A-Fa-f]{1,4}){7}
      %[0-9A-Za-z]+
      \z/x

    ##
    # Compressed IPv6 link local address format fe80::b%em1

    Regex_CompressedHexLinkLocal = /\A
      [Ff][Ee]80:
      (?:
        ((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::
        ((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)
        |
        :((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)
      )?
      :[0-9A-Fa-f]{1,4}%[0-9A-Za-z.]+
      \z/x

    ##
    # A composite IPv6 address Regexp.

    Regex = /
      (?:#{Regex_8Hex}) |
      (?:#{Regex_CompressedHex}) |
      (?:#{Regex_6Hex4Dec}) |
      (?:#{Regex_CompressedHex4Dec}) |
      (?:#{Regex_8HexLinkLocal}) |
      (?:#{Regex_CompressedHexLinkLocal})
      /x

    ##
    # Creates a new IPv6 address from +arg+ which may be:
    #
    # IPv6:: returns +arg+.
    # String:: +arg+ must match one of the IPv6::Regex* constants

    def self.create(arg)
      case arg
      when IPv6
        return arg
      when String
        address = ''.b
        if Regex_8Hex =~ arg
          arg.scan(/[0-9A-Fa-f]+/) {|hex| address << [hex.hex].pack('n')}
        elsif Regex_CompressedHex =~ arg
          prefix = $1
          suffix = $2
          a1 = ''.b
          a2 = ''.b
          prefix.scan(/[0-9A-Fa-f]+/) {|hex| a1 << [hex.hex].pack('n')}
          suffix.scan(/[0-9A-Fa-f]+/) {|hex| a2 << [hex.hex].pack('n')}
          omitlen = 16 - a1.length - a2.length
          address << a1 << "\0" * omitlen << a2
        elsif Regex_6Hex4Dec =~ arg
          prefix, a, b, c, d = $1, $2.to_i, $3.to_i, $4.to_i, $5.to_i
          if (0..255) === a && (0..255) === b && (0..255) === c && (0..255) === d
            prefix.scan(/[0-9A-Fa-f]+/) {|hex| address << [hex.hex].pack('n')}
            address << [a, b, c, d].pack('CCCC')
          else
            raise ArgumentError.new("not numeric IPv6 address: " + arg)
          end
        elsif Regex_CompressedHex4Dec =~ arg
          prefix, suffix, a, b, c, d = $1, $2, $3.to_i, $4.to_i, $5.to_i, $6.to_i
          if (0..255) === a && (0..255) === b && (0..255) === c && (0..255) === d
            a1 = ''.b
            a2 = ''.b
            prefix.scan(/[0-9A-Fa-f]+/) {|hex| a1 << [hex.hex].pack('n')}
            suffix.scan(/[0-9A-Fa-f]+/) {|hex| a2 << [hex.hex].pack('n')}
            omitlen = 12 - a1.length - a2.length
            address << a1 << "\0" * omitlen << a2 << [a, b, c, d].pack('CCCC')
          else
            raise ArgumentError.new("not numeric IPv6 address: " + arg)
          end
        else
          raise ArgumentError.new("not numeric IPv6 address: " + arg)
        end
        return IPv6.new(address)
      else
        raise ArgumentError.new("cannot interpret as IPv6 address: #{arg.inspect}")
      end
    end

    def initialize(address) # :nodoc:
      unless address.kind_of?(String) && address.length == 16
        raise ArgumentError.new('IPv6 address must be 16 bytes')
      end
      @address = address
    end

    ##
    # The raw IPv6 address as a String.

    attr_reader :address

    def to_s # :nodoc:
      address = sprintf("%x:%x:%x:%x:%x:%x:%x:%x", *@address.unpack("nnnnnnnn"))
      unless address.sub!(/(^|:)0(:0)+(:|$)/, '::')
        address.sub!(/(^|:)0(:|$)/, '::')
      end
      return address
    end

    def inspect # :nodoc:
      return "#<#{self.class} #{self}>"
    end

    ##
    # Turns this IPv6 address into a Resolv::DNS::Name.
    #--
    # ip6.arpa should be searched too. [RFC3152]

    def to_name
      return DNS::Name.new(
        @address.unpack("H32")[0].split(//).reverse + ['ip6', 'arpa'])
    end

    def ==(other) # :nodoc:
      return @address == other.address
    end

    def eql?(other) # :nodoc:
      return self == other
    end

    def hash # :nodoc:
      return @address.hash
    end
  end

  ##
  # Resolv::MDNS is a one-shot Multicast DNS (mDNS) resolver.  It blindly
  # makes queries to the mDNS addresses without understanding anything about
  # multicast ports.
  #
  # Information taken form the following places:
  #
  # * RFC 6762

  class MDNS < DNS

    ##
    # Default mDNS Port

    Port = 5353

    ##
    # Default IPv4 mDNS address

    AddressV4 = '224.0.0.251'

    ##
    # Default IPv6 mDNS address

    AddressV6 = 'ff02::fb'

    ##
    # Default mDNS addresses

    Addresses = [
      [AddressV4, Port],
      [AddressV6, Port],
    ]

    ##
    # Creates a new one-shot Multicast DNS (mDNS) resolver.
    #
    # +config_info+ can be:
    #
    # nil::
    #   Uses the default mDNS addresses
    #
    # Hash::
    #   Must contain :nameserver or :nameserver_port like
    #   Resolv::DNS#initialize.

    def initialize(config_info=nil)
      if config_info then
        super({ nameserver_port: Addresses }.merge(config_info))
      else
        super(nameserver_port: Addresses)
      end
    end

    ##
    # Iterates over all IP addresses for +name+ retrieved from the mDNS
    # resolver, provided name ends with "local".  If the name does not end in
    # "local" no records will be returned.
    #
    # +name+ can be a Resolv::DNS::Name or a String.  Retrieved addresses will
    # be a Resolv::IPv4 or Resolv::IPv6

    def each_address(name)
      name = Resolv::DNS::Name.create(name)

      return unless name[-1].to_s == 'local'

      super(name)
    end

    def make_udp_requester # :nodoc:
      nameserver_port = @config.nameserver_port
      Requester::MDNSOneShot.new(*nameserver_port)
    end

  end

  module LOC

    ##
    # A Resolv::LOC::Size

    class Size

      Regex = /^(\d+\.*\d*)[m]$/

      ##
      # Creates a new LOC::Size from +arg+ which may be:
      #
      # LOC::Size:: returns +arg+.
      # String:: +arg+ must match the LOC::Size::Regex constant

      def self.create(arg)
        case arg
        when Size
          return arg
        when String
          scalar = ''
          if Regex =~ arg
            scalar = [(($1.to_f*(1e2)).to_i.to_s[0].to_i*(2**4)+(($1.to_f*(1e2)).to_i.to_s.length-1))].pack("C")
          else
            raise ArgumentError.new("not a properly formed Size string: " + arg)
          end
          return Size.new(scalar)
        else
          raise ArgumentError.new("cannot interpret as Size: #{arg.inspect}")
        end
      end

      def initialize(scalar)
        @scalar = scalar
      end

      ##
      # The raw size

      attr_reader :scalar

      def to_s # :nodoc:
        s = @scalar.unpack("H2").join.to_s
        return ((s[0].to_i)*(10**(s[1].to_i-2))).to_s << "m"
      end

      def inspect # :nodoc:
        return "#<#{self.class} #{self}>"
      end

      def ==(other) # :nodoc:
        return @scalar == other.scalar
      end

      def eql?(other) # :nodoc:
        return self == other
      end

      def hash # :nodoc:
        return @scalar.hash
      end

    end

    ##
    # A Resolv::LOC::Coord

    class Coord

      Regex = /^(\d+)\s(\d+)\s(\d+\.\d+)\s([NESW])$/

      ##
      # Creates a new LOC::Coord from +arg+ which may be:
      #
      # LOC::Coord:: returns +arg+.
      # String:: +arg+ must match the LOC::Coord::Regex constant

      def self.create(arg)
        case arg
        when Coord
          return arg
        when String
          coordinates = ''
          if Regex =~ arg && $1.to_f < 180
            m = $~
            hemi = (m[4][/[NE]/]) || (m[4][/[SW]/]) ? 1 : -1
            coordinates = [ ((m[1].to_i*(36e5)) + (m[2].to_i*(6e4)) +
                             (m[3].to_f*(1e3))) * hemi+(2**31) ].pack("N")
            orientation = m[4][/[NS]/] ? 'lat' : 'lon'
          else
            raise ArgumentError.new("not a properly formed Coord string: " + arg)
          end
          return Coord.new(coordinates,orientation)
        else
          raise ArgumentError.new("cannot interpret as Coord: #{arg.inspect}")
        end
      end

      def initialize(coordinates,orientation)
        unless coordinates.kind_of?(String)
          raise ArgumentError.new("Coord must be a 32bit unsigned integer in hex format: #{coordinates.inspect}")
        end
        unless orientation.kind_of?(String) && orientation[/^lon$|^lat$/]
          raise ArgumentError.new('Coord expects orientation to be a String argument of "lat" or "lon"')
        end
        @coordinates = coordinates
        @orientation = orientation
      end

      ##
      # The raw coordinates

      attr_reader :coordinates

      ## The orientation of the hemisphere as 'lat' or 'lon'

      attr_reader :orientation

      def to_s # :nodoc:
          c = @coordinates.unpack("N").join.to_i
          val      = (c - (2**31)).abs
          fracsecs = (val % 1e3).to_i.to_s
          val      = val / 1e3
          secs     = (val % 60).to_i.to_s
          val      = val / 60
          mins     = (val % 60).to_i.to_s
          degs     = (val / 60).to_i.to_s
          posi = (c >= 2**31)
          case posi
          when true
            hemi = @orientation[/^lat$/] ? "N" : "E"
          else
            hemi = @orientation[/^lon$/] ? "W" : "S"
          end
          return degs << " " << mins << " " << secs << "." << fracsecs << " " << hemi
      end

      def inspect # :nodoc:
        return "#<#{self.class} #{self}>"
      end

      def ==(other) # :nodoc:
        return @coordinates == other.coordinates
      end

      def eql?(other) # :nodoc:
        return self == other
      end

      def hash # :nodoc:
        return @coordinates.hash
      end

    end

    ##
    # A Resolv::LOC::Alt

    class Alt

      Regex = /^([+-]*\d+\.*\d*)[m]$/

      ##
      # Creates a new LOC::Alt from +arg+ which may be:
      #
      # LOC::Alt:: returns +arg+.
      # String:: +arg+ must match the LOC::Alt::Regex constant

      def self.create(arg)
        case arg
        when Alt
          return arg
        when String
          altitude = ''
          if Regex =~ arg
            altitude = [($1.to_f*(1e2))+(1e7)].pack("N")
          else
            raise ArgumentError.new("not a properly formed Alt string: " + arg)
          end
          return Alt.new(altitude)
        else
          raise ArgumentError.new("cannot interpret as Alt: #{arg.inspect}")
        end
      end

      def initialize(altitude)
        @altitude = altitude
      end

      ##
      # The raw altitude

      attr_reader :altitude

      def to_s # :nodoc:
        a = @altitude.unpack("N").join.to_i
        return ((a.to_f/1e2)-1e5).to_s + "m"
      end

      def inspect # :nodoc:
        return "#<#{self.class} #{self}>"
      end

      def ==(other) # :nodoc:
        return @altitude == other.altitude
      end

      def eql?(other) # :nodoc:
        return self == other
      end

      def hash # :nodoc:
        return @altitude.hash
      end

    end

  end

  ##
  # Default resolver to use for Resolv class methods.

  DefaultResolver = self.new

  ##
  # Replaces the resolvers in the default resolver with +new_resolvers+.  This
  # allows resolvers to be changed for resolv-replace.

  def DefaultResolver.replace_resolvers new_resolvers
    @resolvers = new_resolvers
  end

  ##
  # Address Regexp to use for matching IP addresses.

  AddressRegex = /(?:#{IPv4::Regex})|(?:#{IPv6::Regex})/

end

# frozen_string_literal: false
class Matrix
  # Adapted from JAMA: http://math.nist.gov/javanumerics/jama/

  #
  # For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n
  # unit lower triangular matrix L, an n-by-n upper triangular matrix U,
  # and a m-by-m permutation matrix P so that L*U = P*A.
  # If m < n, then L is m-by-m and U is m-by-n.
  #
  # The LUP decomposition with pivoting always exists, even if the matrix is
  # singular, so the constructor will never fail.  The primary use of the
  # LU decomposition is in the solution of square systems of simultaneous
  # linear equations.  This will fail if singular? returns true.
  #

  class LUPDecomposition
    # Returns the lower triangular factor +L+

    include Matrix::ConversionHelper

    def l
      Matrix.build(@row_count, [@column_count, @row_count].min) do |i, j|
        if (i > j)
          @lu[i][j]
        elsif (i == j)
          1
        else
          0
        end
      end
    end

    # Returns the upper triangular factor +U+

    def u
      Matrix.build([@column_count, @row_count].min, @column_count) do |i, j|
        if (i <= j)
          @lu[i][j]
        else
          0
        end
      end
    end

    # Returns the permutation matrix +P+

    def p
      rows = Array.new(@row_count){Array.new(@row_count, 0)}
      @pivots.each_with_index{|p, i| rows[i][p] = 1}
      Matrix.send :new, rows, @row_count
    end

    # Returns +L+, +U+, +P+ in an array

    def to_ary
      [l, u, p]
    end
    alias_method :to_a, :to_ary

    # Returns the pivoting indices

    attr_reader :pivots

    # Returns +true+ if +U+, and hence +A+, is singular.

    def singular?
      @column_count.times do |j|
        if (@lu[j][j] == 0)
          return true
        end
      end
      false
    end

    # Returns the determinant of +A+, calculated efficiently
    # from the factorization.

    def det
      if (@row_count != @column_count)
        raise Matrix::ErrDimensionMismatch
      end
      d = @pivot_sign
      @column_count.times do |j|
        d *= @lu[j][j]
      end
      d
    end
    alias_method :determinant, :det

    # Returns +m+ so that <tt>A*m = b</tt>,
    # or equivalently so that <tt>L*U*m = P*b</tt>
    # +b+ can be a Matrix or a Vector

    def solve b
      if (singular?)
        raise Matrix::ErrNotRegular, "Matrix is singular."
      end
      if b.is_a? Matrix
        if (b.row_count != @row_count)
          raise Matrix::ErrDimensionMismatch
        end

        # Copy right hand side with pivoting
        nx = b.column_count
        m = @pivots.map{|row| b.row(row).to_a}

        # Solve L*Y = P*b
        @column_count.times do |k|
          (k+1).upto(@column_count-1) do |i|
            nx.times do |j|
              m[i][j] -= m[k][j]*@lu[i][k]
            end
          end
        end
        # Solve U*m = Y
        (@column_count-1).downto(0) do |k|
          nx.times do |j|
            m[k][j] = m[k][j].quo(@lu[k][k])
          end
          k.times do |i|
            nx.times do |j|
              m[i][j] -= m[k][j]*@lu[i][k]
            end
          end
        end
        Matrix.send :new, m, nx
      else # same algorithm, specialized for simpler case of a vector
        b = convert_to_array(b)
        if (b.size != @row_count)
          raise Matrix::ErrDimensionMismatch
        end

        # Copy right hand side with pivoting
        m = b.values_at(*@pivots)

        # Solve L*Y = P*b
        @column_count.times do |k|
          (k+1).upto(@column_count-1) do |i|
            m[i] -= m[k]*@lu[i][k]
          end
        end
        # Solve U*m = Y
        (@column_count-1).downto(0) do |k|
          m[k] = m[k].quo(@lu[k][k])
          k.times do |i|
            m[i] -= m[k]*@lu[i][k]
          end
        end
        Vector.elements(m, false)
      end
    end

    def initialize a
      raise TypeError, "Expected Matrix but got #{a.class}" unless a.is_a?(Matrix)
      # Use a "left-looking", dot-product, Crout/Doolittle algorithm.
      @lu = a.to_a
      @row_count = a.row_count
      @column_count = a.column_count
      @pivots = Array.new(@row_count)
      @row_count.times do |i|
         @pivots[i] = i
      end
      @pivot_sign = 1
      lu_col_j = Array.new(@row_count)

      # Outer loop.

      @column_count.times do |j|

        # Make a copy of the j-th column to localize references.

        @row_count.times do |i|
          lu_col_j[i] = @lu[i][j]
        end

        # Apply previous transformations.

        @row_count.times do |i|
          lu_row_i = @lu[i]

          # Most of the time is spent in the following dot product.

          kmax = [i, j].min
          s = 0
          kmax.times do |k|
            s += lu_row_i[k]*lu_col_j[k]
          end

          lu_row_i[j] = lu_col_j[i] -= s
        end

        # Find pivot and exchange if necessary.

        p = j
        (j+1).upto(@row_count-1) do |i|
          if (lu_col_j[i].abs > lu_col_j[p].abs)
            p = i
          end
        end
        if (p != j)
          @column_count.times do |k|
            t = @lu[p][k]; @lu[p][k] = @lu[j][k]; @lu[j][k] = t
          end
          k = @pivots[p]; @pivots[p] = @pivots[j]; @pivots[j] = k
          @pivot_sign = -@pivot_sign
        end

        # Compute multipliers.

        if (j < @row_count && @lu[j][j] != 0)
          (j+1).upto(@row_count-1) do |i|
            @lu[i][j] = @lu[i][j].quo(@lu[j][j])
          end
        end
      end
    end
  end
end
# frozen_string_literal: false
class Matrix
  # Adapted from JAMA: http://math.nist.gov/javanumerics/jama/

  # Eigenvalues and eigenvectors of a real matrix.
  #
  # Computes the eigenvalues and eigenvectors of a matrix A.
  #
  # If A is diagonalizable, this provides matrices V and D
  # such that A = V*D*V.inv, where D is the diagonal matrix with entries
  # equal to the eigenvalues and V is formed by the eigenvectors.
  #
  # If A is symmetric, then V is orthogonal and thus A = V*D*V.t

  class EigenvalueDecomposition

    # Constructs the eigenvalue decomposition for a square matrix +A+
    #
    def initialize(a)
      # @d, @e: Arrays for internal storage of eigenvalues.
      # @v: Array for internal storage of eigenvectors.
      # @h: Array for internal storage of nonsymmetric Hessenberg form.
      raise TypeError, "Expected Matrix but got #{a.class}" unless a.is_a?(Matrix)
      @size = a.row_count
      @d = Array.new(@size, 0)
      @e = Array.new(@size, 0)

      if (@symmetric = a.symmetric?)
        @v = a.to_a
        tridiagonalize
        diagonalize
      else
        @v = Array.new(@size) { Array.new(@size, 0) }
        @h = a.to_a
        @ort = Array.new(@size, 0)
        reduce_to_hessenberg
        hessenberg_to_real_schur
      end
    end

    # Returns the eigenvector matrix +V+
    #
    def eigenvector_matrix
      Matrix.send(:new, build_eigenvectors.transpose)
    end
    alias_method :v, :eigenvector_matrix

    # Returns the inverse of the eigenvector matrix +V+
    #
    def eigenvector_matrix_inv
      r = Matrix.send(:new, build_eigenvectors)
      r = r.transpose.inverse unless @symmetric
      r
    end
    alias_method :v_inv, :eigenvector_matrix_inv

    # Returns the eigenvalues in an array
    #
    def eigenvalues
      values = @d.dup
      @e.each_with_index{|imag, i| values[i] = Complex(values[i], imag) unless imag == 0}
      values
    end

    # Returns an array of the eigenvectors
    #
    def eigenvectors
      build_eigenvectors.map{|ev| Vector.send(:new, ev)}
    end

    # Returns the block diagonal eigenvalue matrix +D+
    #
    def eigenvalue_matrix
      Matrix.diagonal(*eigenvalues)
    end
    alias_method :d, :eigenvalue_matrix

    # Returns [eigenvector_matrix, eigenvalue_matrix, eigenvector_matrix_inv]
    #
    def to_ary
      [v, d, v_inv]
    end
    alias_method :to_a, :to_ary


    private def build_eigenvectors
      # JAMA stores complex eigenvectors in a strange way
      # See http://web.archive.org/web/20111016032731/http://cio.nist.gov/esd/emaildir/lists/jama/msg01021.html
      @e.each_with_index.map do |imag, i|
        if imag == 0
          Array.new(@size){|j| @v[j][i]}
        elsif imag > 0
          Array.new(@size){|j| Complex(@v[j][i], @v[j][i+1])}
        else
          Array.new(@size){|j| Complex(@v[j][i-1], -@v[j][i])}
        end
      end
    end

    # Complex scalar division.

    private def cdiv(xr, xi, yr, yi)
      if (yr.abs > yi.abs)
        r = yi/yr
        d = yr + r*yi
        [(xr + r*xi)/d, (xi - r*xr)/d]
      else
        r = yr/yi
        d = yi + r*yr
        [(r*xr + xi)/d, (r*xi - xr)/d]
      end
    end


    # Symmetric Householder reduction to tridiagonal form.

    private def tridiagonalize

      #  This is derived from the Algol procedures tred2 by
      #  Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
      #  Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
      #  Fortran subroutine in EISPACK.

      @size.times do |j|
        @d[j] = @v[@size-1][j]
      end

      # Householder reduction to tridiagonal form.

      (@size-1).downto(0+1) do |i|

        # Scale to avoid under/overflow.

        scale = 0.0
        h = 0.0
        i.times do |k|
          scale = scale + @d[k].abs
        end
        if (scale == 0.0)
          @e[i] = @d[i-1]
          i.times do |j|
            @d[j] = @v[i-1][j]
            @v[i][j] = 0.0
            @v[j][i] = 0.0
          end
        else

          # Generate Householder vector.

          i.times do |k|
            @d[k] /= scale
            h += @d[k] * @d[k]
          end
          f = @d[i-1]
          g = Math.sqrt(h)
          if (f > 0)
            g = -g
          end
          @e[i] = scale * g
          h -= f * g
          @d[i-1] = f - g
          i.times do |j|
            @e[j] = 0.0
          end

          # Apply similarity transformation to remaining columns.

          i.times do |j|
            f = @d[j]
            @v[j][i] = f
            g = @e[j] + @v[j][j] * f
            (j+1).upto(i-1) do |k|
              g += @v[k][j] * @d[k]
              @e[k] += @v[k][j] * f
            end
            @e[j] = g
          end
          f = 0.0
          i.times do |j|
            @e[j] /= h
            f += @e[j] * @d[j]
          end
          hh = f / (h + h)
          i.times do |j|
            @e[j] -= hh * @d[j]
          end
          i.times do |j|
            f = @d[j]
            g = @e[j]
            j.upto(i-1) do |k|
              @v[k][j] -= (f * @e[k] + g * @d[k])
            end
            @d[j] = @v[i-1][j]
            @v[i][j] = 0.0
          end
        end
        @d[i] = h
      end

      # Accumulate transformations.

      0.upto(@size-1-1) do |i|
        @v[@size-1][i] = @v[i][i]
        @v[i][i] = 1.0
        h = @d[i+1]
        if (h != 0.0)
          0.upto(i) do |k|
            @d[k] = @v[k][i+1] / h
          end
          0.upto(i) do |j|
            g = 0.0
            0.upto(i) do |k|
              g += @v[k][i+1] * @v[k][j]
            end
            0.upto(i) do |k|
              @v[k][j] -= g * @d[k]
            end
          end
        end
        0.upto(i) do |k|
          @v[k][i+1] = 0.0
        end
      end
      @size.times do |j|
        @d[j] = @v[@size-1][j]
        @v[@size-1][j] = 0.0
      end
      @v[@size-1][@size-1] = 1.0
      @e[0] = 0.0
    end


    # Symmetric tridiagonal QL algorithm.

    private def diagonalize
      #  This is derived from the Algol procedures tql2, by
      #  Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
      #  Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
      #  Fortran subroutine in EISPACK.

      1.upto(@size-1) do |i|
        @e[i-1] = @e[i]
      end
      @e[@size-1] = 0.0

      f = 0.0
      tst1 = 0.0
      eps = Float::EPSILON
      @size.times do |l|

        # Find small subdiagonal element

        tst1 = [tst1, @d[l].abs + @e[l].abs].max
        m = l
        while (m < @size) do
          if (@e[m].abs <= eps*tst1)
            break
          end
          m+=1
        end

        # If m == l, @d[l] is an eigenvalue,
        # otherwise, iterate.

        if (m > l)
          iter = 0
          begin
            iter = iter + 1  # (Could check iteration count here.)

            # Compute implicit shift

            g = @d[l]
            p = (@d[l+1] - g) / (2.0 * @e[l])
            r = Math.hypot(p, 1.0)
            if (p < 0)
              r = -r
            end
            @d[l] = @e[l] / (p + r)
            @d[l+1] = @e[l] * (p + r)
            dl1 = @d[l+1]
            h = g - @d[l]
            (l+2).upto(@size-1) do |i|
              @d[i] -= h
            end
            f += h

            # Implicit QL transformation.

            p = @d[m]
            c = 1.0
            c2 = c
            c3 = c
            el1 = @e[l+1]
            s = 0.0
            s2 = 0.0
            (m-1).downto(l) do |i|
              c3 = c2
              c2 = c
              s2 = s
              g = c * @e[i]
              h = c * p
              r = Math.hypot(p, @e[i])
              @e[i+1] = s * r
              s = @e[i] / r
              c = p / r
              p = c * @d[i] - s * g
              @d[i+1] = h + s * (c * g + s * @d[i])

              # Accumulate transformation.

              @size.times do |k|
                h = @v[k][i+1]
                @v[k][i+1] = s * @v[k][i] + c * h
                @v[k][i] = c * @v[k][i] - s * h
              end
            end
            p = -s * s2 * c3 * el1 * @e[l] / dl1
            @e[l] = s * p
            @d[l] = c * p

            # Check for convergence.

          end while (@e[l].abs > eps*tst1)
        end
        @d[l] = @d[l] + f
        @e[l] = 0.0
      end

      # Sort eigenvalues and corresponding vectors.

      0.upto(@size-2) do |i|
        k = i
        p = @d[i]
        (i+1).upto(@size-1) do |j|
          if (@d[j] < p)
            k = j
            p = @d[j]
          end
        end
        if (k != i)
          @d[k] = @d[i]
          @d[i] = p
          @size.times do |j|
            p = @v[j][i]
            @v[j][i] = @v[j][k]
            @v[j][k] = p
          end
        end
      end
    end

    # Nonsymmetric reduction to Hessenberg form.

    private def reduce_to_hessenberg
      #  This is derived from the Algol procedures orthes and ortran,
      #  by Martin and Wilkinson, Handbook for Auto. Comp.,
      #  Vol.ii-Linear Algebra, and the corresponding
      #  Fortran subroutines in EISPACK.

      low = 0
      high = @size-1

      (low+1).upto(high-1) do |m|

        # Scale column.

        scale = 0.0
        m.upto(high) do |i|
          scale = scale + @h[i][m-1].abs
        end
        if (scale != 0.0)

          # Compute Householder transformation.

          h = 0.0
          high.downto(m) do |i|
            @ort[i] = @h[i][m-1]/scale
            h += @ort[i] * @ort[i]
          end
          g = Math.sqrt(h)
          if (@ort[m] > 0)
            g = -g
          end
          h -= @ort[m] * g
          @ort[m] = @ort[m] - g

          # Apply Householder similarity transformation
          # @h = (I-u*u'/h)*@h*(I-u*u')/h)

          m.upto(@size-1) do |j|
            f = 0.0
            high.downto(m) do |i|
              f += @ort[i]*@h[i][j]
            end
            f = f/h
            m.upto(high) do |i|
              @h[i][j] -= f*@ort[i]
            end
          end

          0.upto(high) do |i|
            f = 0.0
            high.downto(m) do |j|
              f += @ort[j]*@h[i][j]
            end
            f = f/h
            m.upto(high) do |j|
              @h[i][j] -= f*@ort[j]
            end
          end
          @ort[m] = scale*@ort[m]
          @h[m][m-1] = scale*g
        end
      end

      # Accumulate transformations (Algol's ortran).

      @size.times do |i|
        @size.times do |j|
          @v[i][j] = (i == j ? 1.0 : 0.0)
        end
      end

      (high-1).downto(low+1) do |m|
        if (@h[m][m-1] != 0.0)
          (m+1).upto(high) do |i|
            @ort[i] = @h[i][m-1]
          end
          m.upto(high) do |j|
            g = 0.0
            m.upto(high) do |i|
              g += @ort[i] * @v[i][j]
            end
            # Double division avoids possible underflow
            g = (g / @ort[m]) / @h[m][m-1]
            m.upto(high) do |i|
              @v[i][j] += g * @ort[i]
            end
          end
        end
      end
    end

    # Nonsymmetric reduction from Hessenberg to real Schur form.

    private def hessenberg_to_real_schur

      #  This is derived from the Algol procedure hqr2,
      #  by Martin and Wilkinson, Handbook for Auto. Comp.,
      #  Vol.ii-Linear Algebra, and the corresponding
      #  Fortran subroutine in EISPACK.

      # Initialize

      nn = @size
      n = nn-1
      low = 0
      high = nn-1
      eps = Float::EPSILON
      exshift = 0.0
      p = q = r = s = z = 0

      # Store roots isolated by balanc and compute matrix norm

      norm = 0.0
      nn.times do |i|
        if (i < low || i > high)
          @d[i] = @h[i][i]
          @e[i] = 0.0
        end
        ([i-1, 0].max).upto(nn-1) do |j|
          norm = norm + @h[i][j].abs
        end
      end

      # Outer loop over eigenvalue index

      iter = 0
      while (n >= low) do

        # Look for single small sub-diagonal element

        l = n
        while (l > low) do
          s = @h[l-1][l-1].abs + @h[l][l].abs
          if (s == 0.0)
            s = norm
          end
          if (@h[l][l-1].abs < eps * s)
            break
          end
          l-=1
        end

        # Check for convergence
        # One root found

        if (l == n)
          @h[n][n] = @h[n][n] + exshift
          @d[n] = @h[n][n]
          @e[n] = 0.0
          n-=1
          iter = 0

        # Two roots found

        elsif (l == n-1)
          w = @h[n][n-1] * @h[n-1][n]
          p = (@h[n-1][n-1] - @h[n][n]) / 2.0
          q = p * p + w
          z = Math.sqrt(q.abs)
          @h[n][n] = @h[n][n] + exshift
          @h[n-1][n-1] = @h[n-1][n-1] + exshift
          x = @h[n][n]

          # Real pair

          if (q >= 0)
            if (p >= 0)
              z = p + z
            else
              z = p - z
            end
            @d[n-1] = x + z
            @d[n] = @d[n-1]
            if (z != 0.0)
              @d[n] = x - w / z
            end
            @e[n-1] = 0.0
            @e[n] = 0.0
            x = @h[n][n-1]
            s = x.abs + z.abs
            p = x / s
            q = z / s
            r = Math.sqrt(p * p+q * q)
            p /= r
            q /= r

            # Row modification

            (n-1).upto(nn-1) do |j|
              z = @h[n-1][j]
              @h[n-1][j] = q * z + p * @h[n][j]
              @h[n][j] = q * @h[n][j] - p * z
            end

            # Column modification

            0.upto(n) do |i|
              z = @h[i][n-1]
              @h[i][n-1] = q * z + p * @h[i][n]
              @h[i][n] = q * @h[i][n] - p * z
            end

            # Accumulate transformations

            low.upto(high) do |i|
              z = @v[i][n-1]
              @v[i][n-1] = q * z + p * @v[i][n]
              @v[i][n] = q * @v[i][n] - p * z
            end

          # Complex pair

          else
            @d[n-1] = x + p
            @d[n] = x + p
            @e[n-1] = z
            @e[n] = -z
          end
          n -= 2
          iter = 0

        # No convergence yet

        else

          # Form shift

          x = @h[n][n]
          y = 0.0
          w = 0.0
          if (l < n)
            y = @h[n-1][n-1]
            w = @h[n][n-1] * @h[n-1][n]
          end

          # Wilkinson's original ad hoc shift

          if (iter == 10)
            exshift += x
            low.upto(n) do |i|
              @h[i][i] -= x
            end
            s = @h[n][n-1].abs + @h[n-1][n-2].abs
            x = y = 0.75 * s
            w = -0.4375 * s * s
          end

          # MATLAB's new ad hoc shift

          if (iter == 30)
             s = (y - x) / 2.0
             s *= s + w
             if (s > 0)
                s = Math.sqrt(s)
                if (y < x)
                  s = -s
                end
                s = x - w / ((y - x) / 2.0 + s)
                low.upto(n) do |i|
                  @h[i][i] -= s
                end
                exshift += s
                x = y = w = 0.964
             end
          end

          iter = iter + 1  # (Could check iteration count here.)

          # Look for two consecutive small sub-diagonal elements

          m = n-2
          while (m >= l) do
            z = @h[m][m]
            r = x - z
            s = y - z
            p = (r * s - w) / @h[m+1][m] + @h[m][m+1]
            q = @h[m+1][m+1] - z - r - s
            r = @h[m+2][m+1]
            s = p.abs + q.abs + r.abs
            p /= s
            q /= s
            r /= s
            if (m == l)
              break
            end
            if (@h[m][m-1].abs * (q.abs + r.abs) <
              eps * (p.abs * (@h[m-1][m-1].abs + z.abs +
              @h[m+1][m+1].abs)))
                break
            end
            m-=1
          end

          (m+2).upto(n) do |i|
            @h[i][i-2] = 0.0
            if (i > m+2)
              @h[i][i-3] = 0.0
            end
          end

          # Double QR step involving rows l:n and columns m:n

          m.upto(n-1) do |k|
            notlast = (k != n-1)
            if (k != m)
              p = @h[k][k-1]
              q = @h[k+1][k-1]
              r = (notlast ? @h[k+2][k-1] : 0.0)
              x = p.abs + q.abs + r.abs
              next if x == 0
              p /= x
              q /= x
              r /= x
            end
            s = Math.sqrt(p * p + q * q + r * r)
            if (p < 0)
              s = -s
            end
            if (s != 0)
              if (k != m)
                @h[k][k-1] = -s * x
              elsif (l != m)
                @h[k][k-1] = -@h[k][k-1]
              end
              p += s
              x = p / s
              y = q / s
              z = r / s
              q /= p
              r /= p

              # Row modification

              k.upto(nn-1) do |j|
                p = @h[k][j] + q * @h[k+1][j]
                if (notlast)
                  p += r * @h[k+2][j]
                  @h[k+2][j] = @h[k+2][j] - p * z
                end
                @h[k][j] = @h[k][j] - p * x
                @h[k+1][j] = @h[k+1][j] - p * y
              end

              # Column modification

              0.upto([n, k+3].min) do |i|
                p = x * @h[i][k] + y * @h[i][k+1]
                if (notlast)
                  p += z * @h[i][k+2]
                  @h[i][k+2] = @h[i][k+2] - p * r
                end
                @h[i][k] = @h[i][k] - p
                @h[i][k+1] = @h[i][k+1] - p * q
              end

              # Accumulate transformations

              low.upto(high) do |i|
                p = x * @v[i][k] + y * @v[i][k+1]
                if (notlast)
                  p += z * @v[i][k+2]
                  @v[i][k+2] = @v[i][k+2] - p * r
                end
                @v[i][k] = @v[i][k] - p
                @v[i][k+1] = @v[i][k+1] - p * q
              end
            end  # (s != 0)
          end  # k loop
        end  # check convergence
      end  # while (n >= low)

      # Backsubstitute to find vectors of upper triangular form

      if (norm == 0.0)
        return
      end

      (nn-1).downto(0) do |k|
        p = @d[k]
        q = @e[k]

        # Real vector

        if (q == 0)
          l = k
          @h[k][k] = 1.0
          (k-1).downto(0) do |i|
            w = @h[i][i] - p
            r = 0.0
            l.upto(k) do |j|
              r += @h[i][j] * @h[j][k]
            end
            if (@e[i] < 0.0)
              z = w
              s = r
            else
              l = i
              if (@e[i] == 0.0)
                if (w != 0.0)
                  @h[i][k] = -r / w
                else
                  @h[i][k] = -r / (eps * norm)
                end

              # Solve real equations

              else
                x = @h[i][i+1]
                y = @h[i+1][i]
                q = (@d[i] - p) * (@d[i] - p) + @e[i] * @e[i]
                t = (x * s - z * r) / q
                @h[i][k] = t
                if (x.abs > z.abs)
                  @h[i+1][k] = (-r - w * t) / x
                else
                  @h[i+1][k] = (-s - y * t) / z
                end
              end

              # Overflow control

              t = @h[i][k].abs
              if ((eps * t) * t > 1)
                i.upto(k) do |j|
                  @h[j][k] = @h[j][k] / t
                end
              end
            end
          end

        # Complex vector

        elsif (q < 0)
          l = n-1

          # Last vector component imaginary so matrix is triangular

          if (@h[n][n-1].abs > @h[n-1][n].abs)
            @h[n-1][n-1] = q / @h[n][n-1]
            @h[n-1][n] = -(@h[n][n] - p) / @h[n][n-1]
          else
            cdivr, cdivi = cdiv(0.0, -@h[n-1][n], @h[n-1][n-1]-p, q)
            @h[n-1][n-1] = cdivr
            @h[n-1][n] = cdivi
          end
          @h[n][n-1] = 0.0
          @h[n][n] = 1.0
          (n-2).downto(0) do |i|
            ra = 0.0
            sa = 0.0
            l.upto(n) do |j|
              ra = ra + @h[i][j] * @h[j][n-1]
              sa = sa + @h[i][j] * @h[j][n]
            end
            w = @h[i][i] - p

            if (@e[i] < 0.0)
              z = w
              r = ra
              s = sa
            else
              l = i
              if (@e[i] == 0)
                cdivr, cdivi = cdiv(-ra, -sa, w, q)
                @h[i][n-1] = cdivr
                @h[i][n] = cdivi
              else

                # Solve complex equations

                x = @h[i][i+1]
                y = @h[i+1][i]
                vr = (@d[i] - p) * (@d[i] - p) + @e[i] * @e[i] - q * q
                vi = (@d[i] - p) * 2.0 * q
                if (vr == 0.0 && vi == 0.0)
                  vr = eps * norm * (w.abs + q.abs +
                  x.abs + y.abs + z.abs)
                end
                cdivr, cdivi = cdiv(x*r-z*ra+q*sa, x*s-z*sa-q*ra, vr, vi)
                @h[i][n-1] = cdivr
                @h[i][n] = cdivi
                if (x.abs > (z.abs + q.abs))
                  @h[i+1][n-1] = (-ra - w * @h[i][n-1] + q * @h[i][n]) / x
                  @h[i+1][n] = (-sa - w * @h[i][n] - q * @h[i][n-1]) / x
                else
                  cdivr, cdivi = cdiv(-r-y*@h[i][n-1], -s-y*@h[i][n], z, q)
                  @h[i+1][n-1] = cdivr
                  @h[i+1][n] = cdivi
                end
              end

              # Overflow control

              t = [@h[i][n-1].abs, @h[i][n].abs].max
              if ((eps * t) * t > 1)
                i.upto(n) do |j|
                  @h[j][n-1] = @h[j][n-1] / t
                  @h[j][n] = @h[j][n] / t
                end
              end
            end
          end
        end
      end

      # Vectors of isolated roots

      nn.times do |i|
        if (i < low || i > high)
          i.upto(nn-1) do |j|
            @v[i][j] = @h[i][j]
          end
        end
      end

      # Back transformation to get eigenvectors of original matrix

      (nn-1).downto(low) do |j|
        low.upto(high) do |i|
          z = 0.0
          low.upto([j, high].min) do |k|
            z += @v[i][k] * @h[k][j]
          end
          @v[i][j] = z
        end
      end
    end

  end
end
# frozen_string_literal: true

class Matrix
  VERSION = "0.3.1"
end
# -*- coding: us-ascii -*-
# frozen_string_literal: true

# == Secure random number generator interface.
#
# This library is an interface to secure random number generators which are
# suitable for generating session keys in HTTP cookies, etc.
#
# You can use this library in your application by requiring it:
#
#   require 'securerandom'
#
# It supports the following secure random number generators:
#
# * openssl
# * /dev/urandom
# * Win32
#
# SecureRandom is extended by the Random::Formatter module which
# defines the following methods:
#
# * alphanumeric
# * base64
# * choose
# * gen_random
# * hex
# * rand
# * random_bytes
# * random_number
# * urlsafe_base64
# * uuid
#
# These methods are usable as class methods of SecureRandom such as
# `SecureRandom.hex`.
#
# === Examples
#
# Generate random hexadecimal strings:
#
#   require 'securerandom'
#
#   SecureRandom.hex(10) #=> "52750b30ffbc7de3b362"
#   SecureRandom.hex(10) #=> "92b15d6c8dc4beb5f559"
#   SecureRandom.hex(13) #=> "39b290146bea6ce975c37cfc23"
#
# Generate random base64 strings:
#
#   SecureRandom.base64(10) #=> "EcmTPZwWRAozdA=="
#   SecureRandom.base64(10) #=> "KO1nIU+p9DKxGg=="
#   SecureRandom.base64(12) #=> "7kJSM/MzBJI+75j8"
#
# Generate random binary strings:
#
#   SecureRandom.random_bytes(10) #=> "\016\t{\370g\310pbr\301"
#   SecureRandom.random_bytes(10) #=> "\323U\030TO\234\357\020\a\337"
#
# Generate alphanumeric strings:
#
#   SecureRandom.alphanumeric(10) #=> "S8baxMJnPl"
#   SecureRandom.alphanumeric(10) #=> "aOxAg8BAJe"
#
# Generate UUIDs:
#
#   SecureRandom.uuid #=> "2d931510-d99f-494a-8c67-87feb05e1594"
#   SecureRandom.uuid #=> "bad85eb9-0713-4da7-8d36-07a8e4b00eab"
#

module SecureRandom
  class << self
    def bytes(n)
      return gen_random(n)
    end

    private

    def gen_random_openssl(n)
      @pid = 0 unless defined?(@pid)
      pid = $$
      unless @pid == pid
        now = Process.clock_gettime(Process::CLOCK_REALTIME, :nanosecond)
        OpenSSL::Random.random_add([now, @pid, pid].join(""), 0.0)
        seed = Random.urandom(16)
        if (seed)
          OpenSSL::Random.random_add(seed, 16)
        end
        @pid = pid
      end
      return OpenSSL::Random.random_bytes(n)
    end

    def gen_random_urandom(n)
      ret = Random.urandom(n)
      unless ret
        raise NotImplementedError, "No random device"
      end
      unless ret.length == n
        raise NotImplementedError, "Unexpected partial read from random device: only #{ret.length} for #{n} bytes"
      end
      ret
    end

    ret = Random.urandom(1)
    if ret.nil?
      begin
        require 'openssl'
      rescue NoMethodError
        raise NotImplementedError, "No random device"
      else
        alias gen_random gen_random_openssl
      end
    else
      alias gen_random gen_random_urandom
    end

    public :gen_random
  end
end

module Random::Formatter

  # SecureRandom.random_bytes generates a random binary string.
  #
  # The argument _n_ specifies the length of the result string.
  #
  # If _n_ is not specified or is nil, 16 is assumed.
  # It may be larger in future.
  #
  # The result may contain any byte: "\x00" - "\xff".
  #
  #   require 'securerandom'
  #
  #   SecureRandom.random_bytes #=> "\xD8\\\xE0\xF4\r\xB2\xFC*WM\xFF\x83\x18\xF45\xB6"
  #   SecureRandom.random_bytes #=> "m\xDC\xFC/\a\x00Uf\xB2\xB2P\xBD\xFF6S\x97"
  #
  # If a secure random number generator is not available,
  # +NotImplementedError+ is raised.
  def random_bytes(n=nil)
    n = n ? n.to_int : 16
    gen_random(n)
  end

  # SecureRandom.hex generates a random hexadecimal string.
  #
  # The argument _n_ specifies the length, in bytes, of the random number to be generated.
  # The length of the resulting hexadecimal string is twice of _n_.
  #
  # If _n_ is not specified or is nil, 16 is assumed.
  # It may be larger in the future.
  #
  # The result may contain 0-9 and a-f.
  #
  #   require 'securerandom'
  #
  #   SecureRandom.hex #=> "eb693ec8252cd630102fd0d0fb7c3485"
  #   SecureRandom.hex #=> "91dc3bfb4de5b11d029d376634589b61"
  #
  # If a secure random number generator is not available,
  # +NotImplementedError+ is raised.
  def hex(n=nil)
    random_bytes(n).unpack("H*")[0]
  end

  # SecureRandom.base64 generates a random base64 string.
  #
  # The argument _n_ specifies the length, in bytes, of the random number
  # to be generated. The length of the result string is about 4/3 of _n_.
  #
  # If _n_ is not specified or is nil, 16 is assumed.
  # It may be larger in the future.
  #
  # The result may contain A-Z, a-z, 0-9, "+", "/" and "=".
  #
  #   require 'securerandom'
  #
  #   SecureRandom.base64 #=> "/2BuBuLf3+WfSKyQbRcc/A=="
  #   SecureRandom.base64 #=> "6BbW0pxO0YENxn38HMUbcQ=="
  #
  # If a secure random number generator is not available,
  # +NotImplementedError+ is raised.
  #
  # See RFC 3548 for the definition of base64.
  def base64(n=nil)
    [random_bytes(n)].pack("m0")
  end

  # SecureRandom.urlsafe_base64 generates a random URL-safe base64 string.
  #
  # The argument _n_ specifies the length, in bytes, of the random number
  # to be generated. The length of the result string is about 4/3 of _n_.
  #
  # If _n_ is not specified or is nil, 16 is assumed.
  # It may be larger in the future.
  #
  # The boolean argument _padding_ specifies the padding.
  # If it is false or nil, padding is not generated.
  # Otherwise padding is generated.
  # By default, padding is not generated because "=" may be used as a URL delimiter.
  #
  # The result may contain A-Z, a-z, 0-9, "-" and "_".
  # "=" is also used if _padding_ is true.
  #
  #   require 'securerandom'
  #
  #   SecureRandom.urlsafe_base64 #=> "b4GOKm4pOYU_-BOXcrUGDg"
  #   SecureRandom.urlsafe_base64 #=> "UZLdOkzop70Ddx-IJR0ABg"
  #
  #   SecureRandom.urlsafe_base64(nil, true) #=> "i0XQ-7gglIsHGV2_BNPrdQ=="
  #   SecureRandom.urlsafe_base64(nil, true) #=> "-M8rLhr7JEpJlqFGUMmOxg=="
  #
  # If a secure random number generator is not available,
  # +NotImplementedError+ is raised.
  #
  # See RFC 3548 for the definition of URL-safe base64.
  def urlsafe_base64(n=nil, padding=false)
    s = [random_bytes(n)].pack("m0")
    s.tr!("+/", "-_")
    s.delete!("=") unless padding
    s
  end

  # SecureRandom.uuid generates a random v4 UUID (Universally Unique IDentifier).
  #
  #   require 'securerandom'
  #
  #   SecureRandom.uuid #=> "2d931510-d99f-494a-8c67-87feb05e1594"
  #   SecureRandom.uuid #=> "bad85eb9-0713-4da7-8d36-07a8e4b00eab"
  #   SecureRandom.uuid #=> "62936e70-1815-439b-bf89-8492855a7e6b"
  #
  # The version 4 UUID is purely random (except the version).
  # It doesn't contain meaningful information such as MAC addresses, timestamps, etc.
  #
  # The result contains 122 random bits (15.25 random bytes).
  #
  # See RFC 4122 for details of UUID.
  #
  def uuid
    ary = random_bytes(16).unpack("NnnnnN")
    ary[2] = (ary[2] & 0x0fff) | 0x4000
    ary[3] = (ary[3] & 0x3fff) | 0x8000
    "%08x-%04x-%04x-%04x-%04x%08x" % ary
  end

  private def gen_random(n)
    self.bytes(n)
  end

  # SecureRandom.choose generates a string that randomly draws from a
  # source array of characters.
  #
  # The argument _source_ specifies the array of characters from which
  # to generate the string.
  # The argument _n_ specifies the length, in characters, of the string to be
  # generated.
  #
  # The result may contain whatever characters are in the source array.
  #
  #   require 'securerandom'
  #
  #   SecureRandom.choose([*'l'..'r'], 16) #=> "lmrqpoonmmlqlron"
  #   SecureRandom.choose([*'0'..'9'], 5)  #=> "27309"
  #
  # If a secure random number generator is not available,
  # +NotImplementedError+ is raised.
  private def choose(source, n)
    size = source.size
    m = 1
    limit = size
    while limit * size <= 0x100000000
      limit *= size
      m += 1
    end
    result = ''.dup
    while m <= n
      rs = random_number(limit)
      is = rs.digits(size)
      (m-is.length).times { is << 0 }
      result << source.values_at(*is).join('')
      n -= m
    end
    if 0 < n
      rs = random_number(limit)
      is = rs.digits(size)
      if is.length < n
        (n-is.length).times { is << 0 }
      else
        is.pop while n < is.length
      end
      result.concat source.values_at(*is).join('')
    end
    result
  end

  ALPHANUMERIC = [*'A'..'Z', *'a'..'z', *'0'..'9']
  # SecureRandom.alphanumeric generates a random alphanumeric string.
  #
  # The argument _n_ specifies the length, in characters, of the alphanumeric
  # 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 A-Z, a-z and 0-9.
  #
  #   require 'securerandom'
  #
  #   SecureRandom.alphanumeric     #=> "2BuBuLf3WfSKyQbR"
  #   SecureRandom.alphanumeric(10) #=> "i6K93NdqiH"
  #
  # If a secure random number generator is not available,
  # +NotImplementedError+ is raised.
  def alphanumeric(n=nil)
    n = 16 if n.nil?
    choose(ALPHANUMERIC, n)
  end
end

SecureRandom.extend(Random::Formatter)
require_relative "did_you_mean/version"
require_relative "did_you_mean/core_ext/name_error"

require_relative "did_you_mean/spell_checker"
require_relative 'did_you_mean/spell_checkers/name_error_checkers'
require_relative 'did_you_mean/spell_checkers/method_name_checker'
require_relative 'did_you_mean/spell_checkers/key_error_checker'
require_relative 'did_you_mean/spell_checkers/null_checker'
require_relative 'did_you_mean/spell_checkers/require_path_checker'
require_relative 'did_you_mean/formatters/plain_formatter'
require_relative 'did_you_mean/tree_spell_checker'

# The +DidYouMean+ gem adds functionality to suggest possible method/class
# names upon errors such as +NameError+ and +NoMethodError+. In Ruby 2.3 or
# later, it is automatically activated during startup.
#
# @example
#
#   methosd
#   # => NameError: undefined local variable or method `methosd' for main:Object
#   #   Did you mean?  methods
#   #                  method
#
#   OBject
#   # => NameError: uninitialized constant OBject
#   #    Did you mean?  Object
#
#   @full_name = "Yuki Nishijima"
#   first_name, last_name = full_name.split(" ")
#   # => NameError: undefined local variable or method `full_name' for main:Object
#   #    Did you mean?  @full_name
#
#   @@full_name = "Yuki Nishijima"
#   @@full_anme
#   # => NameError: uninitialized class variable @@full_anme in Object
#   #    Did you mean?  @@full_name
#
#   full_name = "Yuki Nishijima"
#   full_name.starts_with?("Y")
#   # => NoMethodError: undefined method `starts_with?' for "Yuki Nishijima":String
#   #    Did you mean?  start_with?
#
#   hash = {foo: 1, bar: 2, baz: 3}
#   hash.fetch(:fooo)
#   # => KeyError: key not found: :fooo
#   #    Did you mean?  :foo
#
#
# == Disabling +did_you_mean+
#
# Occasionally, you may want to disable the +did_you_mean+ gem for e.g.
# debugging issues in the error object itself. You can disable it entirely by
# specifying +--disable-did_you_mean+ option to the +ruby+ command:
#
#   $ ruby --disable-did_you_mean -e "1.zeor?"
#   -e:1:in `<main>': undefined method `zeor?' for 1:Integer (NameError)
#
# When you do not have direct access to the +ruby+ command (e.g.
# +rails console+, +irb+), you could applyoptions using the +RUBYOPT+
# environment variable:
#
#   $ RUBYOPT='--disable-did_you_mean' irb
#   irb:0> 1.zeor?
#   # => NoMethodError (undefined method `zeor?' for 1:Integer)
#
#
# == Getting the original error message
#
# Sometimes, you do not want to disable the gem entirely, but need to get the
# original error message without suggestions (e.g. testing). In this case, you
# could use the +#original_message+ method on the error object:
#
#   no_method_error = begin
#                       1.zeor?
#                     rescue NoMethodError => error
#                       error
#                     end
#
#   no_method_error.message
#   # => NoMethodError (undefined method `zeor?' for 1:Integer)
#   #    Did you mean?  zero?
#
#   no_method_error.original_message
#   # => NoMethodError (undefined method `zeor?' for 1:Integer)
#
module DidYouMean
  # Map of error types and spell checker objects.
  SPELL_CHECKERS = Hash.new(NullChecker)

  # Adds +DidYouMean+ functionality to an error using a given spell checker
  def self.correct_error(error_class, spell_checker)
    SPELL_CHECKERS[error_class.name] = spell_checker
    error_class.prepend(Correctable) unless error_class < Correctable
  end

  correct_error NameError, NameErrorCheckers
  correct_error KeyError, KeyErrorChecker
  correct_error NoMethodError, MethodNameChecker
  correct_error LoadError, RequirePathChecker if RUBY_VERSION >= '2.8.0'

  # Returns the currently set formatter. By default, it is set to +DidYouMean::Formatter+.
  def self.formatter
    @@formatter
  end

  # Updates the primary formatter used to format the suggestions.
  def self.formatter=(formatter)
    @@formatter = formatter
  end

  self.formatter = PlainFormatter.new
end
# frozen_string_literal: true

require 'fiddle.so'
require 'fiddle/closure'
require 'fiddle/function'
require 'fiddle/version'

module Fiddle
  if WINDOWS
    # Returns the last win32 +Error+ of the current executing +Thread+ or nil
    # if none
    def self.win32_last_error
      Thread.current[:__FIDDLE_WIN32_LAST_ERROR__]
    end

    # Sets the last win32 +Error+ of the current executing +Thread+ to +error+
    def self.win32_last_error= error
      Thread.current[:__FIDDLE_WIN32_LAST_ERROR__] = error
    end

    # Returns the last win32 socket +Error+ of the current executing
    # +Thread+ or nil if none
    def self.win32_last_socket_error
      Thread.current[:__FIDDLE_WIN32_LAST_SOCKET_ERROR__]
    end

    # Sets the last win32 socket +Error+ of the current executing
    # +Thread+ to +error+
    def self.win32_last_socket_error= error
      Thread.current[:__FIDDLE_WIN32_LAST_SOCKET_ERROR__] = error
    end
  end

  # Returns the last +Error+ of the current executing +Thread+ or nil if none
  def self.last_error
    Thread.current[:__FIDDLE_LAST_ERROR__]
  end

  # Sets the last +Error+ of the current executing +Thread+ to +error+
  def self.last_error= error
    Thread.current[:__DL2_LAST_ERROR__] = error
    Thread.current[:__FIDDLE_LAST_ERROR__] = error
  end

  # call-seq: dlopen(library) => Fiddle::Handle
  #
  # Creates a new handler that opens +library+, and returns an instance of
  # Fiddle::Handle.
  #
  # If +nil+ is given for the +library+, Fiddle::Handle::DEFAULT is used, which
  # is the equivalent to RTLD_DEFAULT. See <code>man 3 dlopen</code> for more.
  #
  #   lib = Fiddle.dlopen(nil)
  #
  # The default is dependent on OS, and provide a handle for all libraries
  # already loaded. For example, in most cases you can use this to access
  # +libc+ functions, or ruby functions like +rb_str_new+.
  #
  # See Fiddle::Handle.new for more.
  def dlopen library
    Fiddle::Handle.new library
  end
  module_function :dlopen

  # Add constants for backwards compat

  RTLD_GLOBAL = Handle::RTLD_GLOBAL # :nodoc:
  RTLD_LAZY   = Handle::RTLD_LAZY   # :nodoc:
  RTLD_NOW    = Handle::RTLD_NOW    # :nodoc:
end
# frozen_string_literal: true
#
# tmpdir - retrieve temporary directory path
#
# $Id$
#

require 'fileutils'
begin
  require 'etc.so'
rescue LoadError # rescue LoadError for miniruby
end

class Dir

  @@systmpdir ||= defined?(Etc.systmpdir) ? Etc.systmpdir : '/tmp'

  ##
  # Returns the operating system's temporary file path.

  def self.tmpdir
    tmp = nil
    ['TMPDIR', 'TMP', 'TEMP', ['system temporary path', @@systmpdir], ['/tmp']*2, ['.']*2].each do |name, dir = ENV[name]|
      next if !dir
      dir = File.expand_path(dir)
      stat = File.stat(dir) rescue next
      case
      when !stat.directory?
        warn "#{name} is not a directory: #{dir}"
      when !stat.writable?
        warn "#{name} is not writable: #{dir}"
      when stat.world_writable? && !stat.sticky?
        warn "#{name} is world-writable: #{dir}"
      else
        tmp = dir
        break
      end
    end
    raise ArgumentError, "could not find a temporary directory" unless tmp
    tmp
  end

  # Dir.mktmpdir creates a temporary directory.
  #
  # The directory is created with 0700 permission.
  # Application should not change the permission to make the temporary directory accessible from other users.
  #
  # The prefix and suffix of the name of the directory is specified by
  # the optional first argument, <i>prefix_suffix</i>.
  # - If it is not specified or nil, "d" is used as the prefix and no suffix is used.
  # - If it is a string, it is used as the prefix and no suffix is used.
  # - If it is an array, first element is used as the prefix and second element is used as a suffix.
  #
  #  Dir.mktmpdir {|dir| dir is ".../d..." }
  #  Dir.mktmpdir("foo") {|dir| dir is ".../foo..." }
  #  Dir.mktmpdir(["foo", "bar"]) {|dir| dir is ".../foo...bar" }
  #
  # The directory is created under Dir.tmpdir or
  # the optional second argument <i>tmpdir</i> if non-nil value is given.
  #
  #  Dir.mktmpdir {|dir| dir is "#{Dir.tmpdir}/d..." }
  #  Dir.mktmpdir(nil, "/var/tmp") {|dir| dir is "/var/tmp/d..." }
  #
  # If a block is given,
  # it is yielded with the path of the directory.
  # The directory and its contents are removed
  # using FileUtils.remove_entry before Dir.mktmpdir returns.
  # The value of the block is returned.
  #
  #  Dir.mktmpdir {|dir|
  #    # use the directory...
  #    open("#{dir}/foo", "w") { ... }
  #  }
  #
  # If a block is not given,
  # The path of the directory is returned.
  # In this case, Dir.mktmpdir doesn't remove the directory.
  #
  #  dir = Dir.mktmpdir
  #  begin
  #    # use the directory...
  #    open("#{dir}/foo", "w") { ... }
  #  ensure
  #    # remove the directory.
  #    FileUtils.remove_entry dir
  #  end
  #
  def self.mktmpdir(prefix_suffix=nil, *rest, **options)
    base = nil
    path = Tmpname.create(prefix_suffix || "d", *rest, **options) {|path, _, _, d|
      base = d
      mkdir(path, 0700)
    }
    if block_given?
      begin
        yield path.dup
      ensure
        unless base
          stat = File.stat(File.dirname(path))
          if stat.world_writable? and !stat.sticky?
            raise ArgumentError, "parent directory is world writable but not sticky"
          end
        end
        FileUtils.remove_entry path
      end
    else
      path
    end
  end

  module Tmpname # :nodoc:
    module_function

    def tmpdir
      Dir.tmpdir
    end

    UNUSABLE_CHARS = "^,-.0-9A-Z_a-z~"

    class << (RANDOM = Random.new)
      MAX = 36**6 # < 0x100000000
      def next
        rand(MAX).to_s(36)
      end
    end
    private_constant :RANDOM

    def create(basename, tmpdir=nil, max_try: nil, **opts)
      origdir = tmpdir
      tmpdir ||= tmpdir()
      n = nil
      prefix, suffix = basename
      prefix = (String.try_convert(prefix) or
                raise ArgumentError, "unexpected prefix: #{prefix.inspect}")
      prefix = prefix.delete(UNUSABLE_CHARS)
      suffix &&= (String.try_convert(suffix) or
                  raise ArgumentError, "unexpected suffix: #{suffix.inspect}")
      suffix &&= suffix.delete(UNUSABLE_CHARS)
      begin
        t = Time.now.strftime("%Y%m%d")
        path = "#{prefix}#{t}-#{$$}-#{RANDOM.next}"\
               "#{n ? %[-#{n}] : ''}#{suffix||''}"
        path = File.join(tmpdir, path)
        yield(path, n, opts, origdir)
      rescue Errno::EEXIST
        n ||= 0
        n += 1
        retry if !max_try or n < max_try
        raise "cannot generate temporary name using `#{basename}' under `#{tmpdir}'"
      end
      path
    end
  end
end
# frozen_string_literal: true
require "delegate"

# Weak Reference class that allows a referenced object to be
# garbage-collected.
#
# A WeakRef may be used exactly like the object it references.
#
# Usage:
#
#   foo = Object.new            # create a new object instance
#   p foo.to_s                  # original's class
#   foo = WeakRef.new(foo)      # reassign foo with WeakRef instance
#   p foo.to_s                  # should be same class
#   GC.start                    # start the garbage collector
#   p foo.to_s                  # should raise exception (recycled)
#

class WeakRef < Delegator
  VERSION = "0.1.1"

  ##
  # RefError is raised when a referenced object has been recycled by the
  # garbage collector

  class RefError < StandardError
  end

  @@__map = ::ObjectSpace::WeakMap.new

  ##
  # Creates a weak reference to +orig+
  #
  # Raises an ArgumentError if the given +orig+ is immutable, such as Symbol,
  # Integer, or Float.

  def initialize(orig)
    case orig
    when true, false, nil
      @delegate_sd_obj = orig
    else
      @@__map[self] = orig
    end
    super
  end

  def __getobj__ # :nodoc:
    @@__map[self] or defined?(@delegate_sd_obj) ? @delegate_sd_obj :
      Kernel::raise(RefError, "Invalid Reference - probably recycled", Kernel::caller(2))
  end

  def __setobj__(obj) # :nodoc:
  end

  ##
  # Returns true if the referenced object is still alive.

  def weakref_alive?
    @@__map.key?(self) or defined?(@delegate_sd_obj)
  end
end
begin
  require 'sorted_set'
rescue ::LoadError
  raise "The `SortedSet` class has been extracted from the `set` library." \
        "You must use the `sorted_set` gem or other alternatives."
end
# frozen_string_literal: true
module Fiddle
  # A mixin that provides methods for parsing C struct and prototype signatures.
  #
  # == Example
  #   require 'fiddle/import'
  #
  #   include Fiddle::CParser
  #     #=> Object
  #
  #   parse_ctype('int')
  #     #=> Fiddle::TYPE_INT
  #
  #   parse_struct_signature(['int i', 'char c'])
  #     #=> [[Fiddle::TYPE_INT, Fiddle::TYPE_CHAR], ["i", "c"]]
  #
  #   parse_signature('double sum(double, double)')
  #     #=> ["sum", Fiddle::TYPE_DOUBLE, [Fiddle::TYPE_DOUBLE, Fiddle::TYPE_DOUBLE]]
  #
  module CParser
    # Parses a C struct's members
    #
    # Example:
    #   require 'fiddle/import'
    #
    #   include Fiddle::CParser
    #     #=> Object
    #
    #   parse_struct_signature(['int i', 'char c'])
    #     #=> [[Fiddle::TYPE_INT, Fiddle::TYPE_CHAR], ["i", "c"]]
    #
    #   parse_struct_signature(['char buffer[80]'])
    #     #=> [[[Fiddle::TYPE_CHAR, 80]], ["buffer"]]
    #
    def parse_struct_signature(signature, tymap=nil)
      if signature.is_a?(String)
        signature = split_arguments(signature, /[,;]/)
      elsif signature.is_a?(Hash)
        signature = [signature]
      end
      mems = []
      tys  = []
      signature.each{|msig|
        msig = compact(msig) if msig.is_a?(String)
        case msig
        when Hash
          msig.each do |struct_name, struct_signature|
            struct_name = struct_name.to_s if struct_name.is_a?(Symbol)
            struct_name = compact(struct_name)
            struct_count = nil
            if struct_name =~ /^([\w\*\s]+)\[(\d+)\]$/
              struct_count = $2.to_i
              struct_name = $1
            end
            if struct_signature.respond_to?(:entity_class)
              struct_type = struct_signature
            else
              parsed_struct = parse_struct_signature(struct_signature, tymap)
              struct_type = CStructBuilder.create(CStruct, *parsed_struct)
            end
            if struct_count
              ty = [struct_type, struct_count]
            else
              ty = struct_type
            end
            mems.push([struct_name, struct_type.members])
            tys.push(ty)
          end
        when /^[\w\*\s]+[\*\s](\w+)$/
          mems.push($1)
          tys.push(parse_ctype(msig, tymap))
        when /^[\w\*\s]+\(\*(\w+)\)\(.*?\)$/
          mems.push($1)
          tys.push(parse_ctype(msig, tymap))
        when /^([\w\*\s]+[\*\s])(\w+)\[(\d+)\]$/
          mems.push($2)
          tys.push([parse_ctype($1.strip, tymap), $3.to_i])
        when /^([\w\*\s]+)\[(\d+)\](\w+)$/
          mems.push($3)
          tys.push([parse_ctype($1.strip, tymap), $2.to_i])
        else
          raise(RuntimeError,"can't parse the struct member: #{msig}")
        end
      }
      return tys, mems
    end

    # Parses a C prototype signature
    #
    # If Hash +tymap+ is provided, the return value and the arguments from the
    # +signature+ are expected to be keys, and the value will be the C type to
    # be looked up.
    #
    # Example:
    #   require 'fiddle/import'
    #
    #   include Fiddle::CParser
    #     #=> Object
    #
    #   parse_signature('double sum(double, double)')
    #     #=> ["sum", Fiddle::TYPE_DOUBLE, [Fiddle::TYPE_DOUBLE, Fiddle::TYPE_DOUBLE]]
    #
    #   parse_signature('void update(void (*cb)(int code))')
    #     #=> ["update", Fiddle::TYPE_VOID, [Fiddle::TYPE_VOIDP]]
    #
    #   parse_signature('char (*getbuffer(void))[80]')
    #     #=> ["getbuffer", Fiddle::TYPE_VOIDP, []]
    #
    def parse_signature(signature, tymap=nil)
      tymap ||= {}
      case compact(signature)
      when /^(?:[\w\*\s]+)\(\*(\w+)\((.*?)\)\)(?:\[\w*\]|\(.*?\));?$/
        func, args = $1, $2
        return [func, TYPE_VOIDP, split_arguments(args).collect {|arg| parse_ctype(arg, tymap)}]
      when /^([\w\*\s]+[\*\s])(\w+)\((.*?)\);?$/
        ret, func, args = $1.strip, $2, $3
        return [func, parse_ctype(ret, tymap), split_arguments(args).collect {|arg| parse_ctype(arg, tymap)}]
      else
        raise(RuntimeError,"can't parse the function prototype: #{signature}")
      end
    end

    # Given a String of C type +ty+, returns the corresponding Fiddle constant.
    #
    # +ty+ can also accept an Array of C type Strings, and will be returned in
    # a corresponding Array.
    #
    # If Hash +tymap+ is provided, +ty+ is expected to be the key, and the
    # value will be the C type to be looked up.
    #
    # Example:
    #   require 'fiddle/import'
    #
    #   include Fiddle::CParser
    #     #=> Object
    #
    #   parse_ctype('int')
    #     #=> Fiddle::TYPE_INT
    #
    #   parse_ctype('double diff')
    #     #=> Fiddle::TYPE_DOUBLE
    #
    #   parse_ctype('unsigned char byte')
    #     #=> -Fiddle::TYPE_CHAR
    #
    #   parse_ctype('const char* const argv[]')
    #     #=> -Fiddle::TYPE_VOIDP
    #
    def parse_ctype(ty, tymap=nil)
      tymap ||= {}
      if ty.is_a?(Array)
        return [parse_ctype(ty[0], tymap), ty[1]]
      end
      ty = ty.gsub(/\Aconst\s+/, "")
      case ty
      when 'void'
        return TYPE_VOID
      when /\A(?:(?:signed\s+)?long\s+long(?:\s+int\s+)?|int64_t)(?:\s+\w+)?\z/
        unless Fiddle.const_defined?(:TYPE_LONG_LONG)
          raise(RuntimeError, "unsupported type: #{ty}")
        end
        return TYPE_LONG_LONG
      when /\A(?:unsigned\s+long\s+long(?:\s+int\s+)?|uint64_t)(?:\s+\w+)?\z/
        unless Fiddle.const_defined?(:TYPE_LONG_LONG)
          raise(RuntimeError, "unsupported type: #{ty}")
        end
        return -TYPE_LONG_LONG
      when /\A(?:signed\s+)?long(?:\s+int\s+)?(?:\s+\w+)?\z/
        return TYPE_LONG
      when /\Aunsigned\s+long(?:\s+int\s+)?(?:\s+\w+)?\z/
        return -TYPE_LONG
      when /\A(?:signed\s+)?int(?:\s+\w+)?\z/
        return TYPE_INT
      when /\A(?:unsigned\s+int|uint)(?:\s+\w+)?\z/
        return -TYPE_INT
      when /\A(?:signed\s+)?short(?:\s+int\s+)?(?:\s+\w+)?\z/
        return TYPE_SHORT
      when /\Aunsigned\s+short(?:\s+int\s+)?(?:\s+\w+)?\z/
        return -TYPE_SHORT
      when /\A(?:signed\s+)?char(?:\s+\w+)?\z/
        return TYPE_CHAR
      when /\Aunsigned\s+char(?:\s+\w+)?\z/
        return  -TYPE_CHAR
      when /\Aint8_t(?:\s+\w+)?\z/
        unless Fiddle.const_defined?(:TYPE_INT8_T)
          raise(RuntimeError, "unsupported type: #{ty}")
        end
        return TYPE_INT8_T
      when /\Auint8_t(?:\s+\w+)?\z/
        unless Fiddle.const_defined?(:TYPE_INT8_T)
          raise(RuntimeError, "unsupported type: #{ty}")
        end
        return -TYPE_INT8_T
      when /\Aint16_t(?:\s+\w+)?\z/
        unless Fiddle.const_defined?(:TYPE_INT16_T)
          raise(RuntimeError, "unsupported type: #{ty}")
        end
        return TYPE_INT16_T
      when /\Auint16_t(?:\s+\w+)?\z/
        unless Fiddle.const_defined?(:TYPE_INT16_T)
          raise(RuntimeError, "unsupported type: #{ty}")
        end
        return -TYPE_INT16_T
      when /\Aint32_t(?:\s+\w+)?\z/
        unless Fiddle.const_defined?(:TYPE_INT32_T)
          raise(RuntimeError, "unsupported type: #{ty}")
        end
        return TYPE_INT32_T
      when /\Auint32_t(?:\s+\w+)?\z/
        unless Fiddle.const_defined?(:TYPE_INT32_T)
          raise(RuntimeError, "unsupported type: #{ty}")
        end
        return -TYPE_INT32_T
      when /\Aint64_t(?:\s+\w+)?\z/
        unless Fiddle.const_defined?(:TYPE_INT64_T)
          raise(RuntimeError, "unsupported type: #{ty}")
        end
        return TYPE_INT64_T
      when /\Auint64_t(?:\s+\w+)?\z/
        unless Fiddle.const_defined?(:TYPE_INT64_T)
          raise(RuntimeError, "unsupported type: #{ty}")
        end
        return -TYPE_INT64_T
      when /\Afloat(?:\s+\w+)?\z/
        return TYPE_FLOAT
      when /\Adouble(?:\s+\w+)?\z/
        return TYPE_DOUBLE
      when /\Asize_t(?:\s+\w+)?\z/
        return TYPE_SIZE_T
      when /\Assize_t(?:\s+\w+)?\z/
        return TYPE_SSIZE_T
      when /\Aptrdiff_t(?:\s+\w+)?\z/
        return TYPE_PTRDIFF_T
      when /\Aintptr_t(?:\s+\w+)?\z/
        return TYPE_INTPTR_T
      when /\Auintptr_t(?:\s+\w+)?\z/
        return TYPE_UINTPTR_T
      when /\*/, /\[[\s\d]*\]/
        return TYPE_VOIDP
      when "..."
        return TYPE_VARIADIC
      else
        ty = ty.split(' ', 2)[0]
        if( tymap[ty] )
          return parse_ctype(tymap[ty], tymap)
        else
          raise(DLError, "unknown type: #{ty}")
        end
      end
    end

    private

    def split_arguments(arguments, sep=',')
      return [] if arguments.strip == 'void'
      arguments.scan(/([\w\*\s]+\(\*\w*\)\(.*?\)|[\w\*\s\[\]]+|\.\.\.)(?:#{sep}\s*|\z)/).collect {|m| m[0]}
    end

    def compact(signature)
      signature.gsub(/\s+/, ' ').gsub(/\s*([\(\)\[\]\*,;])\s*/, '\1').strip
    end

  end
end
# frozen_string_literal: true
require 'fiddle'

module Fiddle
  module PackInfo # :nodoc: all
    ALIGN_MAP = {
      TYPE_VOIDP => ALIGN_VOIDP,
      TYPE_CHAR  => ALIGN_CHAR,
      TYPE_SHORT => ALIGN_SHORT,
      TYPE_INT   => ALIGN_INT,
      TYPE_LONG  => ALIGN_LONG,
      TYPE_FLOAT => ALIGN_FLOAT,
      TYPE_DOUBLE => ALIGN_DOUBLE,
      -TYPE_CHAR  => ALIGN_CHAR,
      -TYPE_SHORT => ALIGN_SHORT,
      -TYPE_INT   => ALIGN_INT,
      -TYPE_LONG  => ALIGN_LONG,
    }

    PACK_MAP = {
      TYPE_VOIDP => "l!",
      TYPE_CHAR  => "c",
      TYPE_SHORT => "s!",
      TYPE_INT   => "i!",
      TYPE_LONG  => "l!",
      TYPE_FLOAT => "f",
      TYPE_DOUBLE => "d",
      -TYPE_CHAR  => "c",
      -TYPE_SHORT => "s!",
      -TYPE_INT   => "i!",
      -TYPE_LONG  => "l!",
    }

    SIZE_MAP = {
      TYPE_VOIDP => SIZEOF_VOIDP,
      TYPE_CHAR  => SIZEOF_CHAR,
      TYPE_SHORT => SIZEOF_SHORT,
      TYPE_INT   => SIZEOF_INT,
      TYPE_LONG  => SIZEOF_LONG,
      TYPE_FLOAT => SIZEOF_FLOAT,
      TYPE_DOUBLE => SIZEOF_DOUBLE,
      -TYPE_CHAR  => SIZEOF_CHAR,
      -TYPE_SHORT => SIZEOF_SHORT,
      -TYPE_INT   => SIZEOF_INT,
      -TYPE_LONG  => SIZEOF_LONG,
    }
    if defined?(TYPE_LONG_LONG)
      ALIGN_MAP[TYPE_LONG_LONG] = ALIGN_MAP[-TYPE_LONG_LONG] = ALIGN_LONG_LONG
      PACK_MAP[TYPE_LONG_LONG] = PACK_MAP[-TYPE_LONG_LONG] = "q"
      SIZE_MAP[TYPE_LONG_LONG] = SIZE_MAP[-TYPE_LONG_LONG] = SIZEOF_LONG_LONG
      PACK_MAP[TYPE_VOIDP] = "q" if SIZEOF_LONG_LONG == SIZEOF_VOIDP
    end

    def align(addr, align)
      d = addr % align
      if( d == 0 )
        addr
      else
        addr + (align - d)
      end
    end
    module_function :align
  end

  class Packer # :nodoc: all
    include PackInfo

    def self.[](*types)
      new(types)
    end

    def initialize(types)
      parse_types(types)
    end

    def size()
      @size
    end

    def pack(ary)
      case SIZEOF_VOIDP
      when SIZEOF_LONG
        ary.pack(@template)
      else
        if defined?(TYPE_LONG_LONG) and
          SIZEOF_VOIDP == SIZEOF_LONG_LONG
          ary.pack(@template)
        else
          raise(RuntimeError, "sizeof(void*)?")
        end
      end
    end

    def unpack(ary)
      case SIZEOF_VOIDP
      when SIZEOF_LONG
        ary.join().unpack(@template)
      else
        if defined?(TYPE_LONG_LONG) and
          SIZEOF_VOIDP == SIZEOF_LONG_LONG
          ary.join().unpack(@template)
        else
          raise(RuntimeError, "sizeof(void*)?")
        end
      end
    end

    private

    def parse_types(types)
      @template = "".dup
      addr     = 0
      types.each{|t|
        orig_addr = addr
        if( t.is_a?(Array) )
          addr = align(orig_addr, ALIGN_MAP[TYPE_VOIDP])
        else
          addr = align(orig_addr, ALIGN_MAP[t])
        end
        d = addr - orig_addr
        if( d > 0 )
          @template << "x#{d}"
        end
        if( t.is_a?(Array) )
          @template << (PACK_MAP[t[0]] * t[1])
          addr += (SIZE_MAP[t[0]] * t[1])
        else
          @template << PACK_MAP[t]
          addr += SIZE_MAP[t]
        end
      }
      addr = align(addr, ALIGN_MAP[TYPE_VOIDP])
      @size = addr
    end
  end
end
# frozen_string_literal: true
require 'fiddle'

module Fiddle
  module ValueUtil #:nodoc: all
    def unsigned_value(val, ty)
      case ty.abs
      when TYPE_CHAR
        [val].pack("c").unpack("C")[0]
      when TYPE_SHORT
        [val].pack("s!").unpack("S!")[0]
      when TYPE_INT
        [val].pack("i!").unpack("I!")[0]
      when TYPE_LONG
        [val].pack("l!").unpack("L!")[0]
      else
        if defined?(TYPE_LONG_LONG) and
          ty.abs == TYPE_LONG_LONG
          [val].pack("q").unpack("Q")[0]
        else
          val
        end
      end
    end

    def signed_value(val, ty)
      case ty.abs
      when TYPE_CHAR
        [val].pack("C").unpack("c")[0]
      when TYPE_SHORT
        [val].pack("S!").unpack("s!")[0]
      when TYPE_INT
        [val].pack("I!").unpack("i!")[0]
      when TYPE_LONG
        [val].pack("L!").unpack("l!")[0]
      else
        if defined?(TYPE_LONG_LONG) and
          ty.abs == TYPE_LONG_LONG
          [val].pack("Q").unpack("q")[0]
        else
          val
        end
      end
    end

    def wrap_args(args, tys, funcs, &block)
      result = []
      tys ||= []
      args.each_with_index{|arg, idx|
        result.push(wrap_arg(arg, tys[idx], funcs, &block))
      }
      result
    end

    def wrap_arg(arg, ty, funcs = [], &block)
      funcs ||= []
      case arg
      when nil
        return 0
      when Pointer
        return arg.to_i
      when IO
        case ty
        when TYPE_VOIDP
          return Pointer[arg].to_i
        else
          return arg.to_i
        end
      when Function
        if( block )
          arg.bind_at_call(&block)
          funcs.push(arg)
        elsif !arg.bound?
          raise(RuntimeError, "block must be given.")
        end
        return arg.to_i
      when String
        if( ty.is_a?(Array) )
          return arg.unpack('C*')
        else
          case SIZEOF_VOIDP
          when SIZEOF_LONG
            return [arg].pack("p").unpack("l!")[0]
          else
            if defined?(SIZEOF_LONG_LONG) and
              SIZEOF_VOIDP == SIZEOF_LONG_LONG
              return [arg].pack("p").unpack("q")[0]
            else
              raise(RuntimeError, "sizeof(void*)?")
            end
          end
        end
      when Float, Integer
        return arg
      when Array
        if( ty.is_a?(Array) ) # used only by struct
          case ty[0]
          when TYPE_VOIDP
            return arg.collect{|v| Integer(v)}
          when TYPE_CHAR
            if( arg.is_a?(String) )
              return val.unpack('C*')
            end
          end
          return arg
        else
          return arg
        end
      else
        if( arg.respond_to?(:to_ptr) )
          return arg.to_ptr.to_i
        else
          begin
            return Integer(arg)
          rescue
            raise(ArgumentError, "unknown argument type: #{arg.class}")
          end
        end
      end
    end
  end
end
# frozen_string_literal: true
module Fiddle
  class Closure

    # the C type of the return of the FFI closure
    attr_reader :ctype

    # arguments of the FFI closure
    attr_reader :args

    # Extends Fiddle::Closure to allow for building the closure in a block
    class BlockCaller < Fiddle::Closure

      # == Description
      #
      # Construct a new BlockCaller object.
      #
      # * +ctype+ is the C type to be returned
      # * +args+ are passed the callback
      # * +abi+ is the abi of the closure
      #
      # If there is an error in preparing the +ffi_cif+ or +ffi_prep_closure+,
      # then a RuntimeError will be raised.
      #
      # == Example
      #
      #   include Fiddle
      #
      #   cb = Closure::BlockCaller.new(TYPE_INT, [TYPE_INT]) do |one|
      #     one
      #   end
      #
      #   func = Function.new(cb, [TYPE_INT], TYPE_INT)
      #
      def initialize ctype, args, abi = Fiddle::Function::DEFAULT, &block
        super(ctype, args, abi)
        @block = block
      end

      # Calls the constructed BlockCaller, with +args+
      #
      # For an example see Fiddle::Closure::BlockCaller.new
      #
      def call *args
        @block.call(*args)
      end
    end
  end
end
# frozen_string_literal: true
module Fiddle
  # Adds Windows type aliases to the including class for use with
  # Fiddle::Importer.
  #
  # The aliases added are:
  # * ATOM
  # * BOOL
  # * BYTE
  # * DWORD
  # * DWORD32
  # * DWORD64
  # * HANDLE
  # * HDC
  # * HINSTANCE
  # * HWND
  # * LPCSTR
  # * LPSTR
  # * PBYTE
  # * PDWORD
  # * PHANDLE
  # * PVOID
  # * PWORD
  # * UCHAR
  # * UINT
  # * ULONG
  # * WORD
  module Win32Types
    def included(m) # :nodoc:
      # https://docs.microsoft.com/en-us/windows/win32/winprog/windows-data-types
      m.module_eval{
        typealias "ATOM", "WORD"
        typealias "BOOL", "int"
        typealias "BYTE", "unsigned char"
        typealias "DWORD", "unsigned long"
        typealias "DWORD32", "uint32_t"
        typealias "DWORD64", "uint64_t"
        typealias "HANDLE", "PVOID"
        typealias "HDC", "HANDLE"
        typealias "HINSTANCE", "HANDLE"
        typealias "HWND", "HANDLE"
        typealias "LPCSTR", "const char *"
        typealias "LPSTR", "char *"
        typealias "PBYTE", "BYTE *"
        typealias "PDWORD", "DWORD *"
        typealias "PHANDLE", "HANDLE *"
        typealias "PVOID", "void *"
        typealias "PWORD", "WORD *"
        typealias "UCHAR", "unsigned char"
        typealias "UINT", "unsigned int"
        typealias "ULONG", "unsigned long"
        typealias "WORD", "unsigned short"
      }
    end
    module_function :included
  end

  # Adds basic type aliases to the including class for use with Fiddle::Importer.
  #
  # The aliases added are +uint+ and +u_int+ (<tt>unsigned int</tt>) and
  # +ulong+ and +u_long+ (<tt>unsigned long</tt>)
  module BasicTypes
    def included(m) # :nodoc:
      m.module_eval{
        typealias "uint", "unsigned int"
        typealias "u_int", "unsigned int"
        typealias "ulong", "unsigned long"
        typealias "u_long", "unsigned long"
      }
    end
    module_function :included
  end
end
# frozen_string_literal: true
require 'fiddle'
require 'fiddle/struct'
require 'fiddle/cparser'

module Fiddle

  # Used internally by Fiddle::Importer
  class CompositeHandler
    # Create a new handler with the open +handlers+
    #
    # Used internally by Fiddle::Importer.dlload
    def initialize(handlers)
      @handlers = handlers
    end

    # Array of the currently loaded libraries.
    def handlers()
      @handlers
    end

    # Returns the address as an Integer from any handlers with the function
    # named +symbol+.
    #
    # Raises a DLError if the handle is closed.
    def sym(symbol)
      @handlers.each{|handle|
        if( handle )
          begin
            addr = handle.sym(symbol)
            return addr
          rescue DLError
          end
        end
      }
      return nil
    end

    # See Fiddle::CompositeHandler.sym
    def [](symbol)
      sym(symbol)
    end
  end

  # A DSL that provides the means to dynamically load libraries and build
  # modules around them including calling extern functions within the C
  # library that has been loaded.
  #
  # == Example
  #
  #   require 'fiddle'
  #   require 'fiddle/import'
  #
  #   module LibSum
  #   	extend Fiddle::Importer
  #   	dlload './libsum.so'
  #   	extern 'double sum(double*, int)'
  #   	extern 'double split(double)'
  #   end
  #
  module Importer
    include Fiddle
    include CParser
    extend Importer

    attr_reader :type_alias
    private :type_alias

    # Creates an array of handlers for the given +libs+, can be an instance of
    # Fiddle::Handle, Fiddle::Importer, or will create a new instance of
    # Fiddle::Handle using Fiddle.dlopen
    #
    # Raises a DLError if the library cannot be loaded.
    #
    # See Fiddle.dlopen
    def dlload(*libs)
      handles = libs.collect{|lib|
        case lib
        when nil
          nil
        when Handle
          lib
        when Importer
          lib.handlers
        else
          Fiddle.dlopen(lib)
        end
      }.flatten()
      @handler = CompositeHandler.new(handles)
      @func_map = {}
      @type_alias = {}
    end

    # Sets the type alias for +alias_type+ as +orig_type+
    def typealias(alias_type, orig_type)
      @type_alias[alias_type] = orig_type
    end

    # Returns the sizeof +ty+, using Fiddle::Importer.parse_ctype to determine
    # the C type and the appropriate Fiddle constant.
    def sizeof(ty)
      case ty
      when String
        ty = parse_ctype(ty, type_alias).abs()
        case ty
        when TYPE_CHAR
          return SIZEOF_CHAR
        when TYPE_SHORT
          return SIZEOF_SHORT
        when TYPE_INT
          return SIZEOF_INT
        when TYPE_LONG
          return SIZEOF_LONG
        when TYPE_FLOAT
          return SIZEOF_FLOAT
        when TYPE_DOUBLE
          return SIZEOF_DOUBLE
        when TYPE_VOIDP
          return SIZEOF_VOIDP
        when TYPE_CONST_STRING
          return SIZEOF_CONST_STRING
        else
          if defined?(TYPE_LONG_LONG) and
            ty == TYPE_LONG_LONG
            return SIZEOF_LONG_LONG
          else
            raise(DLError, "unknown type: #{ty}")
          end
        end
      when Class
        if( ty.instance_methods().include?(:to_ptr) )
          return ty.size()
        end
      end
      return Pointer[ty].size()
    end

    def parse_bind_options(opts)
      h = {}
      while( opt = opts.shift() )
        case opt
        when :stdcall, :cdecl
          h[:call_type] = opt
        when :carried, :temp, :temporal, :bind
          h[:callback_type] = opt
          h[:carrier] = opts.shift()
        else
          h[opt] = true
        end
      end
      h
    end
    private :parse_bind_options

    # :stopdoc:
    CALL_TYPE_TO_ABI = Hash.new { |h, k|
      raise RuntimeError, "unsupported call type: #{k}"
    }.merge({ :stdcall => Function.const_defined?(:STDCALL) ? Function::STDCALL :
                          Function::DEFAULT,
              :cdecl   => Function::DEFAULT,
              nil      => Function::DEFAULT
            }).freeze
    private_constant :CALL_TYPE_TO_ABI
    # :startdoc:

    # Creates a global method from the given C +signature+.
    def extern(signature, *opts)
      symname, ctype, argtype = parse_signature(signature, type_alias)
      opt = parse_bind_options(opts)
      f = import_function(symname, ctype, argtype, opt[:call_type])
      name = symname.gsub(/@.+/,'')
      @func_map[name] = f
      # define_method(name){|*args,&block| f.call(*args,&block)}
      begin
        /^(.+?):(\d+)/ =~ caller.first
        file, line = $1, $2.to_i
      rescue
        file, line = __FILE__, __LINE__+3
      end
      module_eval(<<-EOS, file, line)
        def #{name}(*args, &block)
          @func_map['#{name}'].call(*args,&block)
        end
      EOS
      module_function(name)
      f
    end

    # Creates a global method from the given C +signature+ using the given
    # +opts+ as bind parameters with the given block.
    def bind(signature, *opts, &blk)
      name, ctype, argtype = parse_signature(signature, type_alias)
      h = parse_bind_options(opts)
      case h[:callback_type]
      when :bind, nil
        f = bind_function(name, ctype, argtype, h[:call_type], &blk)
      else
        raise(RuntimeError, "unknown callback type: #{h[:callback_type]}")
      end
      @func_map[name] = f
      #define_method(name){|*args,&block| f.call(*args,&block)}
      begin
        /^(.+?):(\d+)/ =~ caller.first
        file, line = $1, $2.to_i
      rescue
        file, line = __FILE__, __LINE__+3
      end
      module_eval(<<-EOS, file, line)
        def #{name}(*args,&block)
          @func_map['#{name}'].call(*args,&block)
        end
      EOS
      module_function(name)
      f
    end

    # Creates a class to wrap the C struct described by +signature+.
    #
    #   MyStruct = struct ['int i', 'char c']
    def struct(signature)
      tys, mems = parse_struct_signature(signature, type_alias)
      Fiddle::CStructBuilder.create(CStruct, tys, mems)
    end

    # Creates a class to wrap the C union described by +signature+.
    #
    #   MyUnion = union ['int i', 'char c']
    def union(signature)
      tys, mems = parse_struct_signature(signature, type_alias)
      Fiddle::CStructBuilder.create(CUnion, tys, mems)
    end

    # Returns the function mapped to +name+, that was created by either
    # Fiddle::Importer.extern or Fiddle::Importer.bind
    def [](name)
      @func_map[name]
    end

    # Creates a class to wrap the C struct with the value +ty+
    #
    # See also Fiddle::Importer.struct
    def create_value(ty, val=nil)
      s = struct([ty + " value"])
      ptr = s.malloc()
      if( val )
        ptr.value = val
      end
      return ptr
    end
    alias value create_value

    # Returns a new instance of the C struct with the value +ty+ at the +addr+
    # address.
    def import_value(ty, addr)
      s = struct([ty + " value"])
      ptr = s.new(addr)
      return ptr
    end


    # The Fiddle::CompositeHandler instance
    #
    # Will raise an error if no handlers are open.
    def handler
      (@handler ||= nil) or raise "call dlload before importing symbols and functions"
    end

    # Returns a new Fiddle::Pointer instance at the memory address of the given
    # +name+ symbol.
    #
    # Raises a DLError if the +name+ doesn't exist.
    #
    # See Fiddle::CompositeHandler.sym and Fiddle::Handle.sym
    def import_symbol(name)
      addr = handler.sym(name)
      if( !addr )
        raise(DLError, "cannot find the symbol: #{name}")
      end
      Pointer.new(addr)
    end

    # Returns a new Fiddle::Function instance at the memory address of the given
    # +name+ function.
    #
    # Raises a DLError if the +name+ doesn't exist.
    #
    # * +argtype+ is an Array of arguments, passed to the +name+ function.
    # * +ctype+ is the return type of the function
    # * +call_type+ is the ABI of the function
    #
    # See also Fiddle:Function.new
    #
    # See Fiddle::CompositeHandler.sym and Fiddle::Handler.sym
    def import_function(name, ctype, argtype, call_type = nil)
      addr = handler.sym(name)
      if( !addr )
        raise(DLError, "cannot find the function: #{name}()")
      end
      Function.new(addr, argtype, ctype, CALL_TYPE_TO_ABI[call_type],
                   name: name)
    end

    # Returns a new closure wrapper for the +name+ function.
    #
    # * +ctype+ is the return type of the function
    # * +argtype+ is an Array of arguments, passed to the callback function
    # * +call_type+ is the abi of the closure
    # * +block+ is passed to the callback
    #
    # See Fiddle::Closure
    def bind_function(name, ctype, argtype, call_type = nil, &block)
      abi = CALL_TYPE_TO_ABI[call_type]
      closure = Class.new(Fiddle::Closure) {
        define_method(:call, block)
      }.new(ctype, argtype, abi)

      Function.new(closure, argtype, ctype, abi, name: name)
    end
  end
end
# frozen_string_literal: true
module Fiddle
  class Function
    # The ABI of the Function.
    attr_reader :abi

    # The address of this function
    attr_reader :ptr

    # The name of this function
    attr_reader :name

    # Whether GVL is needed to call this function
    def need_gvl?
      @need_gvl
    end

    # The integer memory location of this function
    def to_i
      ptr.to_i
    end
  end
end
module Fiddle
  VERSION = "1.0.8"
end
# frozen_string_literal: true
require 'fiddle'
require 'fiddle/value'
require 'fiddle/pack'

module Fiddle
  # A base class for objects representing a C structure
  class CStruct
    include Enumerable

    # accessor to Fiddle::CStructEntity
    def CStruct.entity_class
      CStructEntity
    end

    def each
      return enum_for(__function__) unless block_given?

      self.class.members.each do |name,|
        yield(self[name])
      end
    end

    def each_pair
      return enum_for(__function__) unless block_given?

      self.class.members.each do |name,|
        yield(name, self[name])
      end
    end

    def to_h
      hash = {}
      each_pair do |name, value|
        hash[name] = unstruct(value)
      end
      hash
    end

    def replace(another)
      if another.nil?
        self.class.members.each do |name,|
          self[name] = nil
        end
      elsif another.respond_to?(:each_pair)
        another.each_pair do |name, value|
          self[name] = value
        end
      else
        another.each do |name, value|
          self[name] = value
        end
      end
      self
    end

    private
    def unstruct(value)
      case value
      when CStruct
        value.to_h
      when Array
        value.collect do |v|
          unstruct(v)
        end
      else
        value
      end
    end
  end

  # A base class for objects representing a C union
  class CUnion
    # accessor to Fiddle::CUnionEntity
    def CUnion.entity_class
      CUnionEntity
    end
  end

  # Wrapper for arrays within a struct
  class StructArray < Array
    include ValueUtil

    def initialize(ptr, type, initial_values)
      @ptr = ptr
      @type = type
      @is_struct = @type.respond_to?(:entity_class)
      if @is_struct
        super(initial_values)
      else
        @size = Fiddle::PackInfo::SIZE_MAP[type]
        @pack_format = Fiddle::PackInfo::PACK_MAP[type]
        super(initial_values.collect { |v| unsigned_value(v, type) })
      end
    end

    def to_ptr
      @ptr
    end

    def []=(index, value)
      if index < 0 || index >= size
        raise IndexError, 'index %d outside of array bounds 0...%d' % [index, size]
      end

      if @is_struct
        self[index].replace(value)
      else
        to_ptr[index * @size, @size] = [value].pack(@pack_format)
        super(index, value)
      end
    end
  end

  # Used to construct C classes (CUnion, CStruct, etc)
  #
  # Fiddle::Importer#struct and Fiddle::Importer#union wrap this functionality in an
  # easy-to-use manner.
  module CStructBuilder
    # Construct a new class given a C:
    # * class +klass+ (CUnion, CStruct, or other that provide an
    #   #entity_class)
    # * +types+ (Fiddle::TYPE_INT, Fiddle::TYPE_SIZE_T, etc., see the C types
    #   constants)
    # * corresponding +members+
    #
    # Fiddle::Importer#struct and Fiddle::Importer#union wrap this functionality in an
    # easy-to-use manner.
    #
    # Examples:
    #
    #   require 'fiddle/struct'
    #   require 'fiddle/cparser'
    #
    #   include Fiddle::CParser
    #
    #   types, members = parse_struct_signature(['int i','char c'])
    #
    #   MyStruct = Fiddle::CStructBuilder.create(Fiddle::CUnion, types, members)
    #
    #   MyStruct.malloc(Fiddle::RUBY_FREE) do |obj|
    #     ...
    #   end
    #
    #   obj = MyStruct.malloc(Fiddle::RUBY_FREE)
    #   begin
    #     ...
    #   ensure
    #     obj.call_free
    #   end
    #
    #   obj = MyStruct.malloc
    #   begin
    #     ...
    #   ensure
    #     Fiddle.free obj.to_ptr
    #   end
    #
    def create(klass, types, members)
      new_class = Class.new(klass){
        define_method(:initialize){|addr, func = nil|
          if addr.is_a?(self.class.entity_class)
            @entity = addr
          else
            @entity = self.class.entity_class.new(addr, types, func)
          end
          @entity.assign_names(members)
        }
        define_method(:[]) { |*args| @entity.send(:[], *args) }
        define_method(:[]=) { |*args| @entity.send(:[]=, *args) }
        define_method(:to_ptr){ @entity }
        define_method(:to_i){ @entity.to_i }
        define_singleton_method(:types) { types }
        define_singleton_method(:members) { members }
        members.each{|name|
          name = name[0] if name.is_a?(Array) # name is a nested struct
          next if method_defined?(name)
          define_method(name){ @entity[name] }
          define_method(name + "="){|val| @entity[name] = val }
        }
        entity_class = klass.entity_class
        alignment = entity_class.alignment(types)
        size = entity_class.size(types)
        define_singleton_method(:alignment) { alignment }
        define_singleton_method(:size) { size }
        define_singleton_method(:malloc) do |func=nil, &block|
          if block
            entity_class.malloc(types, func, size) do |entity|
              block.call(new(entity))
            end
          else
            new(entity_class.malloc(types, func, size))
          end
        end
      }
      return new_class
    end
    module_function :create
  end

  # A pointer to a C structure
  class CStructEntity < Fiddle::Pointer
    include PackInfo
    include ValueUtil

    def CStructEntity.alignment(types)
      max = 1
      types.each do |type, count = 1|
        if type.respond_to?(:entity_class)
          n = type.alignment
        else
          n = ALIGN_MAP[type]
        end
        max = n if n > max
      end
      max
    end

    # Allocates a C struct with the +types+ provided.
    #
    # See Fiddle::Pointer.malloc for memory management issues.
    def CStructEntity.malloc(types, func = nil, size = size(types), &block)
      if block_given?
        super(size, func) do |struct|
          struct.set_ctypes types
          yield struct
        end
      else
        struct = super(size, func)
        struct.set_ctypes types
        struct
      end
    end

    # Returns the offset for the packed sizes for the given +types+.
    #
    #   Fiddle::CStructEntity.size(
    #     [ Fiddle::TYPE_DOUBLE,
    #       Fiddle::TYPE_INT,
    #       Fiddle::TYPE_CHAR,
    #       Fiddle::TYPE_VOIDP ]) #=> 24
    def CStructEntity.size(types)
      offset = 0

      max_align = types.map { |type, count = 1|
        last_offset = offset

        if type.respond_to?(:entity_class)
          align = type.alignment
          type_size = type.size
        else
          align = PackInfo::ALIGN_MAP[type]
          type_size = PackInfo::SIZE_MAP[type]
        end
        offset = PackInfo.align(last_offset, align) +
                 (type_size * count)

        align
      }.max

      PackInfo.align(offset, max_align)
    end

    # Wraps the C pointer +addr+ as a C struct with the given +types+.
    #
    # When the instance is garbage collected, the C function +func+ is called.
    #
    # See also Fiddle::Pointer.new
    def initialize(addr, types, func = nil)
      if func && addr.is_a?(Pointer) && addr.free
        raise ArgumentError, 'free function specified on both underlying struct Pointer and when creating a CStructEntity - who do you want to free this?'
      end
      set_ctypes(types)
      super(addr, @size, func)
    end

    # Set the names of the +members+ in this C struct
    def assign_names(members)
      @members = []
      @nested_structs = {}
      members.each_with_index do |member, index|
        if member.is_a?(Array) # nested struct
          member_name = member[0]
          struct_type, struct_count = @ctypes[index]
          if struct_count.nil?
            struct = struct_type.new(to_i + @offset[index])
          else
            structs = struct_count.times.map do |i|
              struct_type.new(to_i + @offset[index] + i * struct_type.size)
            end
            struct = StructArray.new(to_i + @offset[index],
                                     struct_type,
                                     structs)
          end
          @nested_structs[member_name] = struct
        else
          member_name = member
        end
        @members << member_name
      end
    end

    # Calculates the offsets and sizes for the given +types+ in the struct.
    def set_ctypes(types)
      @ctypes = types
      @offset = []
      offset = 0

      max_align = types.map { |type, count = 1|
        orig_offset = offset
        if type.respond_to?(:entity_class)
          align = type.alignment
          type_size = type.size
        else
          align = ALIGN_MAP[type]
          type_size = SIZE_MAP[type]
        end
        offset = PackInfo.align(orig_offset, align)

        @offset << offset

        offset += (type_size * count)

        align
      }.max

      @size = PackInfo.align(offset, max_align)
    end

    # Fetch struct member +name+ if only one argument is specified. If two
    # arguments are specified, the first is an offset and the second is a
    # length and this method returns the string of +length+ bytes beginning at
    # +offset+.
    #
    # Examples:
    #
    #     my_struct = struct(['int id']).malloc
    #     my_struct.id = 1
    #     my_struct['id'] # => 1
    #     my_struct[0, 4] # => "\x01\x00\x00\x00".b
    #
    def [](*args)
      return super(*args) if args.size > 1
      name = args[0]
      idx = @members.index(name)
      if( idx.nil? )
        raise(ArgumentError, "no such member: #{name}")
      end
      ty = @ctypes[idx]
      if( ty.is_a?(Array) )
        if ty.first.respond_to?(:entity_class)
          return @nested_structs[name]
        else
          r = super(@offset[idx], SIZE_MAP[ty[0]] * ty[1])
        end
      elsif ty.respond_to?(:entity_class)
        return @nested_structs[name]
      else
        r = super(@offset[idx], SIZE_MAP[ty.abs])
      end
      packer = Packer.new([ty])
      val = packer.unpack([r])
      case ty
      when Array
        case ty[0]
        when TYPE_VOIDP
          val = val.collect{|v| Pointer.new(v)}
        end
      when TYPE_VOIDP
        val = Pointer.new(val[0])
      else
        val = val[0]
      end
      if( ty.is_a?(Integer) && (ty < 0) )
        return unsigned_value(val, ty)
      elsif( ty.is_a?(Array) && (ty[0] < 0) )
        return StructArray.new(self + @offset[idx], ty[0], val)
      else
        return val
      end
    end

    # Set struct member +name+, to value +val+. If more arguments are
    # specified, writes the string of bytes to the memory at the given
    # +offset+ and +length+.
    #
    # Examples:
    #
    #     my_struct = struct(['int id']).malloc
    #     my_struct['id'] = 1
    #     my_struct[0, 4] = "\x01\x00\x00\x00".b
    #     my_struct.id # => 1
    #
    def []=(*args)
      return super(*args) if args.size > 2
      name, val = *args
      name = name.to_s if name.is_a?(Symbol)
      nested_struct = @nested_structs[name]
      if nested_struct
        if nested_struct.is_a?(StructArray)
          if val.nil?
            nested_struct.each do |s|
              s.replace(nil)
            end
          else
            val.each_with_index do |v, i|
              nested_struct[i] = v
            end
          end
        else
          nested_struct.replace(val)
        end
        return val
      end
      idx = @members.index(name)
      if( idx.nil? )
        raise(ArgumentError, "no such member: #{name}")
      end
      ty  = @ctypes[idx]
      packer = Packer.new([ty])
      val = wrap_arg(val, ty, [])
      buff = packer.pack([val].flatten())
      super(@offset[idx], buff.size, buff)
      if( ty.is_a?(Integer) && (ty < 0) )
        return unsigned_value(val, ty)
      elsif( ty.is_a?(Array) && (ty[0] < 0) )
        return val.collect{|v| unsigned_value(v,ty[0])}
      else
        return val
      end
    end

    undef_method :size=
    def to_s() # :nodoc:
      super(@size)
    end
  end

  # A pointer to a C union
  class CUnionEntity < CStructEntity
    include PackInfo

    # Returns the size needed for the union with the given +types+.
    #
    #   Fiddle::CUnionEntity.size(
    #     [ Fiddle::TYPE_DOUBLE,
    #       Fiddle::TYPE_INT,
    #       Fiddle::TYPE_CHAR,
    #       Fiddle::TYPE_VOIDP ]) #=> 8
    def CUnionEntity.size(types)
      types.map { |type, count = 1|
        if type.respond_to?(:entity_class)
          type.size * count
        else
          PackInfo::SIZE_MAP[type] * count
        end
      }.max
    end

    # Calculate the necessary offset and for each union member with the given
    # +types+
    def set_ctypes(types)
      @ctypes = types
      @offset = Array.new(types.length, 0)
      @size   = self.class.size types
    end
  end
end
# frozen_string_literal: false
# = monitor.rb
#
# Copyright (C) 2001  Shugo Maeda <shugo@ruby-lang.org>
#
# This library is distributed under the terms of the Ruby license.
# You can freely distribute/modify this library.
#

#
# In concurrent programming, a monitor is an object or module intended to be
# used safely by more than one thread.  The defining characteristic of a
# monitor is that its methods are executed with mutual exclusion.  That is, at
# each point in time, at most one thread may be executing any of its methods.
# This mutual exclusion greatly simplifies reasoning about the implementation
# of monitors compared to reasoning about parallel code that updates a data
# structure.
#
# You can read more about the general principles on the Wikipedia page for
# Monitors[https://en.wikipedia.org/wiki/Monitor_%28synchronization%29]
#
# == Examples
#
# === Simple object.extend
#
#   require 'monitor.rb'
#
#   buf = []
#   buf.extend(MonitorMixin)
#   empty_cond = buf.new_cond
#
#   # consumer
#   Thread.start do
#     loop do
#       buf.synchronize do
#         empty_cond.wait_while { buf.empty? }
#         print buf.shift
#       end
#     end
#   end
#
#   # producer
#   while line = ARGF.gets
#     buf.synchronize do
#       buf.push(line)
#       empty_cond.signal
#     end
#   end
#
# The consumer thread waits for the producer thread to push a line to buf
# while <tt>buf.empty?</tt>.  The producer thread (main thread) reads a
# line from ARGF and pushes it into buf then calls <tt>empty_cond.signal</tt>
# to notify the consumer thread of new data.
#
# === Simple Class include
#
#   require 'monitor'
#
#   class SynchronizedArray < Array
#
#     include MonitorMixin
#
#     def initialize(*args)
#       super(*args)
#     end
#
#     alias :old_shift :shift
#     alias :old_unshift :unshift
#
#     def shift(n=1)
#       self.synchronize do
#         self.old_shift(n)
#       end
#     end
#
#     def unshift(item)
#       self.synchronize do
#         self.old_unshift(item)
#       end
#     end
#
#     # other methods ...
#   end
#
# +SynchronizedArray+ implements an Array with synchronized access to items.
# This Class is implemented as subclass of Array which includes the
# MonitorMixin module.
#

require 'monitor.so'

module MonitorMixin
  #
  # FIXME: This isn't documented in Nutshell.
  #
  # Since MonitorMixin.new_cond returns a ConditionVariable, and the example
  # above calls while_wait and signal, this class should be documented.
  #
  class ConditionVariable
    #
    # Releases the lock held in the associated monitor and waits; reacquires the lock on wakeup.
    #
    # If +timeout+ is given, this method returns after +timeout+ seconds passed,
    # even if no other thread doesn't signal.
    #
    def wait(timeout = nil)
      @monitor.mon_check_owner
      @monitor.wait_for_cond(@cond, timeout)
    end

    #
    # Calls wait repeatedly while the given block yields a truthy value.
    #
    def wait_while
      while yield
        wait
      end
    end

    #
    # Calls wait repeatedly until the given block yields a truthy value.
    #
    def wait_until
      until yield
        wait
      end
    end

    #
    # Wakes up the first thread in line waiting for this lock.
    #
    def signal
      @monitor.mon_check_owner
      @cond.signal
    end

    #
    # Wakes up all threads waiting for this lock.
    #
    def broadcast
      @monitor.mon_check_owner
      @cond.broadcast
    end

    private

    def initialize(monitor)
      @monitor = monitor
      @cond = Thread::ConditionVariable.new
    end
  end

  def self.extend_object(obj)
    super(obj)
    obj.__send__(:mon_initialize)
  end

  #
  # Attempts to enter exclusive section.  Returns +false+ if lock fails.
  #
  def mon_try_enter
    @mon_data.try_enter
  end
  # For backward compatibility
  alias try_mon_enter mon_try_enter

  #
  # Enters exclusive section.
  #
  def mon_enter
    @mon_data.enter
  end

  #
  # Leaves exclusive section.
  #
  def mon_exit
    mon_check_owner
    @mon_data.exit
  end

  #
  # Returns true if this monitor is locked by any thread
  #
  def mon_locked?
    @mon_data.mon_locked?
  end

  #
  # Returns true if this monitor is locked by current thread.
  #
  def mon_owned?
    @mon_data.mon_owned?
  end

  #
  # Enters exclusive section and executes the block.  Leaves the exclusive
  # section automatically when the block exits.  See example under
  # +MonitorMixin+.
  #
  def mon_synchronize(&b)
    @mon_data.synchronize(&b)
  end
  alias synchronize mon_synchronize

  #
  # Creates a new MonitorMixin::ConditionVariable associated with the
  # Monitor object.
  #
  def new_cond
    unless defined?(@mon_data)
      mon_initialize
      @mon_initialized_by_new_cond = true
    end
    return ConditionVariable.new(@mon_data)
  end

  private

  # Use <tt>extend MonitorMixin</tt> or <tt>include MonitorMixin</tt> instead
  # of this constructor.  Have look at the examples above to understand how to
  # use this module.
  def initialize(...)
    super
    mon_initialize
  end

  # Initializes the MonitorMixin after being included in a class or when an
  # object has been extended with the MonitorMixin
  def mon_initialize
    if defined?(@mon_data)
      if defined?(@mon_initialized_by_new_cond)
        return # already initialized.
      elsif @mon_data_owner_object_id == self.object_id
        raise ThreadError, "already initialized"
      end
    end
    @mon_data = ::Monitor.new
    @mon_data_owner_object_id = self.object_id
  end

  def mon_check_owner
    @mon_data.mon_check_owner
  end
end

# Use the Monitor class when you want to have a lock object for blocks with
# mutual exclusion.
#
#   require 'monitor'
#
#   lock = Monitor.new
#   lock.synchronize do
#     # exclusive access
#   end
#
class Monitor
  def new_cond
    ::MonitorMixin::ConditionVariable.new(self)
  end

  # for compatibility
  alias try_mon_enter try_enter
  alias mon_try_enter try_enter
  alias mon_enter enter
  alias mon_exit exit
  alias mon_synchronize synchronize
end

# Documentation comments:
#  - All documentation comes from Nutshell.
#  - MonitorMixin.new_cond appears in the example, but is not documented in
#    Nutshell.
#  - All the internals (internal modules Accessible and Initializable, class
#    ConditionVariable) appear in RDoc.  It might be good to hide them, by
#    making them private, or marking them :nodoc:, etc.
#  - RDoc doesn't recognise aliases, so we have mon_synchronize documented, but
#    not synchronize.
#  - mon_owner is in Nutshell, but appears as an accessor in a separate module
#    here, so is hard/impossible to RDoc.  Some other useful accessors
#    (mon_count and some queue stuff) are also in this module, and don't appear
#    directly in the RDoc output.
#  - in short, it may be worth changing the code layout in this file to make the
#    documentation easier
# frozen_string_literal: false
#--
# $Release Version: 0.3$
# $Revision: 1.12 $

##
# Outputs a source level execution trace of a Ruby program.
#
# It does this by registering an event handler with Kernel#set_trace_func for
# processing incoming events.  It also provides methods for filtering unwanted
# trace output (see Tracer.add_filter, Tracer.on, and Tracer.off).
#
# == Example
#
# Consider the following Ruby script
#
#   class A
#     def square(a)
#       return a*a
#     end
#   end
#
#   a = A.new
#   a.square(5)
#
# Running the above script using <code>ruby -r tracer example.rb</code> will
# output the following trace to STDOUT (Note you can also explicitly
# <code>require 'tracer'</code>)
#
#   #0:<internal:lib/rubygems/custom_require>:38:Kernel:<: -
#   #0:example.rb:3::-: class A
#   #0:example.rb:3::C: class A
#   #0:example.rb:4::-:   def square(a)
#   #0:example.rb:7::E: end
#   #0:example.rb:9::-: a = A.new
#   #0:example.rb:10::-: a.square(5)
#   #0:example.rb:4:A:>:   def square(a)
#   #0:example.rb:5:A:-:     return a*a
#   #0:example.rb:6:A:<:   end
#    |  |         | |  |
#    |  |         | |   ---------------------+ event
#    |  |         |  ------------------------+ class
#    |  |          --------------------------+ line
#    |   ------------------------------------+ filename
#     ---------------------------------------+ thread
#
# Symbol table used for displaying incoming events:
#
# +}+:: call a C-language routine
# +{+:: return from a C-language routine
# +>+:: call a Ruby method
# +C+:: start a class or module definition
# +E+:: finish a class or module definition
# +-+:: execute code on a new line
# +^+:: raise an exception
# +<+:: return from a Ruby method
#
# == Copyright
#
# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
class Tracer
  VERSION = "0.1.1"

  class << self
    # display additional debug information (defaults to false)
    attr_accessor :verbose
    alias verbose? verbose

    # output stream used to output trace (defaults to STDOUT)
    attr_accessor :stdout

    # mutex lock used by tracer for displaying trace output
    attr_reader :stdout_mutex

    # display process id in trace output (defaults to false)
    attr_accessor :display_process_id
    alias display_process_id? display_process_id

    # display thread id in trace output (defaults to true)
    attr_accessor :display_thread_id
    alias display_thread_id? display_thread_id

    # display C-routine calls in trace output (defaults to false)
    attr_accessor :display_c_call
    alias display_c_call? display_c_call
  end

  Tracer::stdout = STDOUT
  Tracer::verbose = false
  Tracer::display_process_id = false
  Tracer::display_thread_id = true
  Tracer::display_c_call = false

  @stdout_mutex = Thread::Mutex.new

  # Symbol table used for displaying trace information
  EVENT_SYMBOL = {
    "line" => "-",
    "call" => ">",
    "return" => "<",
    "class" => "C",
    "end" => "E",
    "raise" => "^",
    "c-call" => "}",
    "c-return" => "{",
    "unknown" => "?"
  }

  def initialize # :nodoc:
    @threads = Hash.new
    if defined? Thread.main
      @threads[Thread.main.object_id] = 0
    else
      @threads[Thread.current.object_id] = 0
    end

    @get_line_procs = {}

    @filters = []
  end

  def stdout # :nodoc:
    Tracer.stdout
  end

  def on # :nodoc:
    if block_given?
      on
      begin
        yield
      ensure
        off
      end
    else
      set_trace_func method(:trace_func).to_proc
      stdout.print "Trace on\n" if Tracer.verbose?
    end
  end

  def off # :nodoc:
    set_trace_func nil
    stdout.print "Trace off\n" if Tracer.verbose?
  end

  def add_filter(p = nil, &b) # :nodoc:
    p ||= b
    @filters.push p
  end

  def set_get_line_procs(file, p = nil, &b) # :nodoc:
    p ||= b
    @get_line_procs[file] = p
  end

  def get_line(file, line) # :nodoc:
    if p = @get_line_procs[file]
      return p.call(line)
    end

    unless list = SCRIPT_LINES__[file]
      list = File.readlines(file) rescue []
      SCRIPT_LINES__[file] = list
    end

    if l = list[line - 1]
      l
    else
      "-\n"
    end
  end

  def get_thread_no # :nodoc:
    if no = @threads[Thread.current.object_id]
      no
    else
      @threads[Thread.current.object_id] = @threads.size
    end
  end

  def trace_func(event, file, line, id, binding, klass, *) # :nodoc:
    return if file == __FILE__

    for p in @filters
      return unless p.call event, file, line, id, binding, klass
    end

    return unless Tracer::display_c_call? or
      event != "c-call" && event != "c-return"

    Tracer::stdout_mutex.synchronize do
      if EVENT_SYMBOL[event]
        stdout.printf("<%d>", $$) if Tracer::display_process_id?
        stdout.printf("#%d:", get_thread_no) if Tracer::display_thread_id?
        if line == 0
          source = "?\n"
        else
          source = get_line(file, line)
        end
        stdout.printf("%s:%d:%s:%s: %s",
               file,
               line,
               klass || '',
               EVENT_SYMBOL[event],
               source)
      end
    end

  end

  # Reference to singleton instance of Tracer
  Single = new

  ##
  # Start tracing
  #
  # === Example
  #
  #   Tracer.on
  #   # code to trace here
  #   Tracer.off
  #
  # You can also pass a block:
  #
  #   Tracer.on {
  #     # trace everything in this block
  #   }

  def Tracer.on
    if block_given?
      Single.on{yield}
    else
      Single.on
    end
  end

  ##
  # Disable tracing

  def Tracer.off
    Single.off
  end

  ##
  # Register an event handler <code>p</code> which is called every time a line
  # in +file_name+ is executed.
  #
  # Example:
  #
  #   Tracer.set_get_line_procs("example.rb", lambda { |line|
  #     puts "line number executed is #{line}"
  #   })

  def Tracer.set_get_line_procs(file_name, p = nil, &b)
    p ||= b
    Single.set_get_line_procs(file_name, p)
  end

  ##
  # Used to filter unwanted trace output
  #
  # Example which only outputs lines of code executed within the Kernel class:
  #
  #   Tracer.add_filter do |event, file, line, id, binding, klass, *rest|
  #     "Kernel" == klass.to_s
  #   end

  def Tracer.add_filter(p = nil, &b)
    p ||= b
    Single.add_filter(p)
  end
end

# :stopdoc:
SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__

if $0 == __FILE__
  # direct call

  $0 = ARGV[0]
  ARGV.shift
  Tracer.on
  require $0
else
  # call Tracer.on only if required by -r command-line option
  count = caller.count {|bt| %r%/rubygems/core_ext/kernel_require\.rb:% !~ bt}
  if (defined?(Gem) and count == 0) or
     (!defined?(Gem) and count <= 1)
    Tracer.on
  end
end
# :startdoc:
# frozen_string_literal: true
#
# = pathname.rb
#
# Object-Oriented Pathname Class
#
# Author:: Tanaka Akira <akr@m17n.org>
# Documentation:: Author and Gavin Sinclair
#
# For documentation, see class Pathname.
#

require 'pathname.so'

class Pathname

  # :stopdoc:

  # to_path is implemented so Pathname objects are usable with File.open, etc.
  TO_PATH = :to_path

  SAME_PATHS = if File::FNM_SYSCASE.nonzero?
    # Avoid #zero? here because #casecmp can return nil.
    proc {|a, b| a.casecmp(b) == 0}
  else
    proc {|a, b| a == b}
  end


  if File::ALT_SEPARATOR
    SEPARATOR_LIST = "#{Regexp.quote File::ALT_SEPARATOR}#{Regexp.quote File::SEPARATOR}"
    SEPARATOR_PAT = /[#{SEPARATOR_LIST}]/
  else
    SEPARATOR_LIST = "#{Regexp.quote File::SEPARATOR}"
    SEPARATOR_PAT = /#{Regexp.quote File::SEPARATOR}/
  end

  if File.dirname('A:') == 'A:.' # DOSish drive letter
    ABSOLUTE_PATH = /\A(?:[A-Za-z]:|#{SEPARATOR_PAT})/o
  else
    ABSOLUTE_PATH = /\A#{SEPARATOR_PAT}/o
  end
  private_constant :ABSOLUTE_PATH

  # :startdoc:

  # chop_basename(path) -> [pre-basename, basename] or nil
  def chop_basename(path) # :nodoc:
    base = File.basename(path)
    if /\A#{SEPARATOR_PAT}?\z/o.match?(base)
      return nil
    else
      return path[0, path.rindex(base)], base
    end
  end
  private :chop_basename

  # split_names(path) -> prefix, [name, ...]
  def split_names(path) # :nodoc:
    names = []
    while r = chop_basename(path)
      path, basename = r
      names.unshift basename
    end
    return path, names
  end
  private :split_names

  def prepend_prefix(prefix, relpath) # :nodoc:
    if relpath.empty?
      File.dirname(prefix)
    elsif /#{SEPARATOR_PAT}/o.match?(prefix)
      prefix = File.dirname(prefix)
      prefix = File.join(prefix, "") if File.basename(prefix + 'a') != 'a'
      prefix + relpath
    else
      prefix + relpath
    end
  end
  private :prepend_prefix

  # Returns clean pathname of +self+ with consecutive slashes and useless dots
  # removed.  The filesystem is not accessed.
  #
  # If +consider_symlink+ is +true+, then a more conservative algorithm is used
  # to avoid breaking symbolic linkages.  This may retain more +..+
  # entries than absolutely necessary, but without accessing the filesystem,
  # this can't be avoided.
  #
  # See Pathname#realpath.
  #
  def cleanpath(consider_symlink=false)
    if consider_symlink
      cleanpath_conservative
    else
      cleanpath_aggressive
    end
  end

  #
  # Clean the path simply by resolving and removing excess +.+ and +..+ entries.
  # Nothing more, nothing less.
  #
  def cleanpath_aggressive # :nodoc:
    path = @path
    names = []
    pre = path
    while r = chop_basename(pre)
      pre, base = r
      case base
      when '.'
      when '..'
        names.unshift base
      else
        if names[0] == '..'
          names.shift
        else
          names.unshift base
        end
      end
    end
    pre.tr!(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR
    if /#{SEPARATOR_PAT}/o.match?(File.basename(pre))
      names.shift while names[0] == '..'
    end
    self.class.new(prepend_prefix(pre, File.join(*names)))
  end
  private :cleanpath_aggressive

  # has_trailing_separator?(path) -> bool
  def has_trailing_separator?(path) # :nodoc:
    if r = chop_basename(path)
      pre, basename = r
      pre.length + basename.length < path.length
    else
      false
    end
  end
  private :has_trailing_separator?

  # add_trailing_separator(path) -> path
  def add_trailing_separator(path) # :nodoc:
    if File.basename(path + 'a') == 'a'
      path
    else
      File.join(path, "") # xxx: Is File.join is appropriate to add separator?
    end
  end
  private :add_trailing_separator

  def del_trailing_separator(path) # :nodoc:
    if r = chop_basename(path)
      pre, basename = r
      pre + basename
    elsif /#{SEPARATOR_PAT}+\z/o =~ path
      $` + File.dirname(path)[/#{SEPARATOR_PAT}*\z/o]
    else
      path
    end
  end
  private :del_trailing_separator

  def cleanpath_conservative # :nodoc:
    path = @path
    names = []
    pre = path
    while r = chop_basename(pre)
      pre, base = r
      names.unshift base if base != '.'
    end
    pre.tr!(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR
    if /#{SEPARATOR_PAT}/o.match?(File.basename(pre))
      names.shift while names[0] == '..'
    end
    if names.empty?
      self.class.new(File.dirname(pre))
    else
      if names.last != '..' && File.basename(path) == '.'
        names << '.'
      end
      result = prepend_prefix(pre, File.join(*names))
      if /\A(?:\.|\.\.)\z/ !~ names.last && has_trailing_separator?(path)
        self.class.new(add_trailing_separator(result))
      else
        self.class.new(result)
      end
    end
  end
  private :cleanpath_conservative

  # Returns the parent directory.
  #
  # This is same as <code>self + '..'</code>.
  def parent
    self + '..'
  end

  # Returns +true+ if +self+ points to a mountpoint.
  def mountpoint?
    begin
      stat1 = self.lstat
      stat2 = self.parent.lstat
      stat1.dev != stat2.dev || stat1.ino == stat2.ino
    rescue Errno::ENOENT
      false
    end
  end

  #
  # Predicate method for root directories.  Returns +true+ if the
  # pathname consists of consecutive slashes.
  #
  # It doesn't access the filesystem.  So it may return +false+ for some
  # pathnames which points to roots such as <tt>/usr/..</tt>.
  #
  def root?
    chop_basename(@path) == nil && /#{SEPARATOR_PAT}/o.match?(@path)
  end

  # Predicate method for testing whether a path is absolute.
  #
  # It returns +true+ if the pathname begins with a slash.
  #
  #   p = Pathname.new('/im/sure')
  #   p.absolute?
  #       #=> true
  #
  #   p = Pathname.new('not/so/sure')
  #   p.absolute?
  #       #=> false
  def absolute?
    ABSOLUTE_PATH.match? @path
  end

  # The opposite of Pathname#absolute?
  #
  # It returns +false+ if the pathname begins with a slash.
  #
  #   p = Pathname.new('/im/sure')
  #   p.relative?
  #       #=> false
  #
  #   p = Pathname.new('not/so/sure')
  #   p.relative?
  #       #=> true
  def relative?
    !absolute?
  end

  #
  # Iterates over each component of the path.
  #
  #   Pathname.new("/usr/bin/ruby").each_filename {|filename| ... }
  #     # yields "usr", "bin", and "ruby".
  #
  # Returns an Enumerator if no block was given.
  #
  #   enum = Pathname.new("/usr/bin/ruby").each_filename
  #     # ... do stuff ...
  #   enum.each { |e| ... }
  #     # yields "usr", "bin", and "ruby".
  #
  def each_filename # :yield: filename
    return to_enum(__method__) unless block_given?
    _, names = split_names(@path)
    names.each {|filename| yield filename }
    nil
  end

  # Iterates over and yields a new Pathname object
  # for each element in the given path in descending order.
  #
  #  Pathname.new('/path/to/some/file.rb').descend {|v| p v}
  #     #<Pathname:/>
  #     #<Pathname:/path>
  #     #<Pathname:/path/to>
  #     #<Pathname:/path/to/some>
  #     #<Pathname:/path/to/some/file.rb>
  #
  #  Pathname.new('path/to/some/file.rb').descend {|v| p v}
  #     #<Pathname:path>
  #     #<Pathname:path/to>
  #     #<Pathname:path/to/some>
  #     #<Pathname:path/to/some/file.rb>
  #
  # Returns an Enumerator if no block was given.
  #
  #   enum = Pathname.new("/usr/bin/ruby").descend
  #     # ... do stuff ...
  #   enum.each { |e| ... }
  #     # yields Pathnames /, /usr, /usr/bin, and /usr/bin/ruby.
  #
  # It doesn't access the filesystem.
  #
  def descend
    return to_enum(__method__) unless block_given?
    vs = []
    ascend {|v| vs << v }
    vs.reverse_each {|v| yield v }
    nil
  end

  # Iterates over and yields a new Pathname object
  # for each element in the given path in ascending order.
  #
  #  Pathname.new('/path/to/some/file.rb').ascend {|v| p v}
  #     #<Pathname:/path/to/some/file.rb>
  #     #<Pathname:/path/to/some>
  #     #<Pathname:/path/to>
  #     #<Pathname:/path>
  #     #<Pathname:/>
  #
  #  Pathname.new('path/to/some/file.rb').ascend {|v| p v}
  #     #<Pathname:path/to/some/file.rb>
  #     #<Pathname:path/to/some>
  #     #<Pathname:path/to>
  #     #<Pathname:path>
  #
  # Returns an Enumerator if no block was given.
  #
  #   enum = Pathname.new("/usr/bin/ruby").ascend
  #     # ... do stuff ...
  #   enum.each { |e| ... }
  #     # yields Pathnames /usr/bin/ruby, /usr/bin, /usr, and /.
  #
  # It doesn't access the filesystem.
  #
  def ascend
    return to_enum(__method__) unless block_given?
    path = @path
    yield self
    while r = chop_basename(path)
      path, = r
      break if path.empty?
      yield self.class.new(del_trailing_separator(path))
    end
  end

  #
  # Appends a pathname fragment to +self+ to produce a new Pathname object.
  #
  #   p1 = Pathname.new("/usr")      # Pathname:/usr
  #   p2 = p1 + "bin/ruby"           # Pathname:/usr/bin/ruby
  #   p3 = p1 + "/etc/passwd"        # Pathname:/etc/passwd
  #
  #   # / is aliased to +.
  #   p4 = p1 / "bin/ruby"           # Pathname:/usr/bin/ruby
  #   p5 = p1 / "/etc/passwd"        # Pathname:/etc/passwd
  #
  # This method doesn't access the file system; it is pure string manipulation.
  #
  def +(other)
    other = Pathname.new(other) unless Pathname === other
    Pathname.new(plus(@path, other.to_s))
  end
  alias / +

  def plus(path1, path2) # -> path # :nodoc:
    prefix2 = path2
    index_list2 = []
    basename_list2 = []
    while r2 = chop_basename(prefix2)
      prefix2, basename2 = r2
      index_list2.unshift prefix2.length
      basename_list2.unshift basename2
    end
    return path2 if prefix2 != ''
    prefix1 = path1
    while true
      while !basename_list2.empty? && basename_list2.first == '.'
        index_list2.shift
        basename_list2.shift
      end
      break unless r1 = chop_basename(prefix1)
      prefix1, basename1 = r1
      next if basename1 == '.'
      if basename1 == '..' || basename_list2.empty? || basename_list2.first != '..'
        prefix1 = prefix1 + basename1
        break
      end
      index_list2.shift
      basename_list2.shift
    end
    r1 = chop_basename(prefix1)
    if !r1 && (r1 = /#{SEPARATOR_PAT}/o.match?(File.basename(prefix1)))
      while !basename_list2.empty? && basename_list2.first == '..'
        index_list2.shift
        basename_list2.shift
      end
    end
    if !basename_list2.empty?
      suffix2 = path2[index_list2.first..-1]
      r1 ? File.join(prefix1, suffix2) : prefix1 + suffix2
    else
      r1 ? prefix1 : File.dirname(prefix1)
    end
  end
  private :plus

  #
  # Joins the given pathnames onto +self+ to create a new Pathname object.
  #
  #   path0 = Pathname.new("/usr")                # Pathname:/usr
  #   path0 = path0.join("bin/ruby")              # Pathname:/usr/bin/ruby
  #       # is the same as
  #   path1 = Pathname.new("/usr") + "bin/ruby"   # Pathname:/usr/bin/ruby
  #   path0 == path1
  #       #=> true
  #
  def join(*args)
    return self if args.empty?
    result = args.pop
    result = Pathname.new(result) unless Pathname === result
    return result if result.absolute?
    args.reverse_each {|arg|
      arg = Pathname.new(arg) unless Pathname === arg
      result = arg + result
      return result if result.absolute?
    }
    self + result
  end

  #
  # Returns the children of the directory (files and subdirectories, not
  # recursive) as an array of Pathname objects.
  #
  # By default, the returned pathnames will have enough information to access
  # the files. If you set +with_directory+ to +false+, then the returned
  # pathnames will contain the filename only.
  #
  # For example:
  #   pn = Pathname("/usr/lib/ruby/1.8")
  #   pn.children
  #       # -> [ Pathname:/usr/lib/ruby/1.8/English.rb,
  #              Pathname:/usr/lib/ruby/1.8/Env.rb,
  #              Pathname:/usr/lib/ruby/1.8/abbrev.rb, ... ]
  #   pn.children(false)
  #       # -> [ Pathname:English.rb, Pathname:Env.rb, Pathname:abbrev.rb, ... ]
  #
  # Note that the results never contain the entries +.+ and +..+ in
  # the directory because they are not children.
  #
  def children(with_directory=true)
    with_directory = false if @path == '.'
    result = []
    Dir.foreach(@path) {|e|
      next if e == '.' || e == '..'
      if with_directory
        result << self.class.new(File.join(@path, e))
      else
        result << self.class.new(e)
      end
    }
    result
  end

  # Iterates over the children of the directory
  # (files and subdirectories, not recursive).
  #
  # It yields Pathname object for each child.
  #
  # By default, the yielded pathnames will have enough information to access
  # the files.
  #
  # If you set +with_directory+ to +false+, then the returned pathnames will
  # contain the filename only.
  #
  #   Pathname("/usr/local").each_child {|f| p f }
  #   #=> #<Pathname:/usr/local/share>
  #   #   #<Pathname:/usr/local/bin>
  #   #   #<Pathname:/usr/local/games>
  #   #   #<Pathname:/usr/local/lib>
  #   #   #<Pathname:/usr/local/include>
  #   #   #<Pathname:/usr/local/sbin>
  #   #   #<Pathname:/usr/local/src>
  #   #   #<Pathname:/usr/local/man>
  #
  #   Pathname("/usr/local").each_child(false) {|f| p f }
  #   #=> #<Pathname:share>
  #   #   #<Pathname:bin>
  #   #   #<Pathname:games>
  #   #   #<Pathname:lib>
  #   #   #<Pathname:include>
  #   #   #<Pathname:sbin>
  #   #   #<Pathname:src>
  #   #   #<Pathname:man>
  #
  # Note that the results never contain the entries +.+ and +..+ in
  # the directory because they are not children.
  #
  # See Pathname#children
  #
  def each_child(with_directory=true, &b)
    children(with_directory).each(&b)
  end

  #
  # Returns a relative path from the given +base_directory+ to the receiver.
  #
  # If +self+ is absolute, then +base_directory+ must be absolute too.
  #
  # If +self+ is relative, then +base_directory+ must be relative too.
  #
  # This method doesn't access the filesystem.  It assumes no symlinks.
  #
  # ArgumentError is raised when it cannot find a relative path.
  #
  # Note that this method does not handle situations where the case sensitivity
  # of the filesystem in use differs from the operating system default.
  #
  def relative_path_from(base_directory)
    base_directory = Pathname.new(base_directory) unless base_directory.is_a? Pathname
    dest_directory = self.cleanpath.to_s
    base_directory = base_directory.cleanpath.to_s
    dest_prefix = dest_directory
    dest_names = []
    while r = chop_basename(dest_prefix)
      dest_prefix, basename = r
      dest_names.unshift basename if basename != '.'
    end
    base_prefix = base_directory
    base_names = []
    while r = chop_basename(base_prefix)
      base_prefix, basename = r
      base_names.unshift basename if basename != '.'
    end
    unless SAME_PATHS[dest_prefix, base_prefix]
      raise ArgumentError, "different prefix: #{dest_prefix.inspect} and #{base_directory.inspect}"
    end
    while !dest_names.empty? &&
          !base_names.empty? &&
          SAME_PATHS[dest_names.first, base_names.first]
      dest_names.shift
      base_names.shift
    end
    if base_names.include? '..'
      raise ArgumentError, "base_directory has ..: #{base_directory.inspect}"
    end
    base_names.fill('..')
    relpath_names = base_names + dest_names
    if relpath_names.empty?
      Pathname.new('.')
    else
      Pathname.new(File.join(*relpath_names))
    end
  end
end


class Pathname    # * Find *
  #
  # Iterates over the directory tree in a depth first manner, yielding a
  # Pathname for each file under "this" directory.
  #
  # Returns an Enumerator if no block is given.
  #
  # Since it is implemented by the standard library module Find, Find.prune can
  # be used to control the traversal.
  #
  # If +self+ is +.+, yielded pathnames begin with a filename in the
  # current directory, not +./+.
  #
  # See Find.find
  #
  def find(ignore_error: true) # :yield: pathname
    return to_enum(__method__, ignore_error: ignore_error) unless block_given?
    require 'find'
    if @path == '.'
      Find.find(@path, ignore_error: ignore_error) {|f| yield self.class.new(f.sub(%r{\A\./}, '')) }
    else
      Find.find(@path, ignore_error: ignore_error) {|f| yield self.class.new(f) }
    end
  end
end


class Pathname    # * FileUtils *
  # Creates a full path, including any intermediate directories that don't yet
  # exist.
  #
  # See FileUtils.mkpath and FileUtils.mkdir_p
  def mkpath
    require 'fileutils'
    FileUtils.mkpath(@path)
    nil
  end

  # Recursively deletes a directory, including all directories beneath it.
  #
  # See FileUtils.rm_r
  def rmtree
    # The name "rmtree" is borrowed from File::Path of Perl.
    # File::Path provides "mkpath" and "rmtree".
    require 'fileutils'
    FileUtils.rm_r(@path)
    nil
  end
end

# frozen_string_literal: true
$expect_verbose = false

# Expect library adds the IO instance method #expect, which does similar act to
# tcl's expect extension.
#
# In order to use this method, you must require expect:
#
#   require 'expect'
#
# Please see #expect for usage.
class IO
  # call-seq:
  #   IO#expect(pattern,timeout=9999999)                  ->  Array
  #   IO#expect(pattern,timeout=9999999) { |result| ... } ->  nil
  #
  # Reads from the IO until the given +pattern+ matches or the +timeout+ is over.
  #
  # It returns an array with the read buffer, followed by the matches.
  # If a block is given, the result is yielded to the block and returns nil.
  #
  # When called without a block, it waits until the input that matches the
  # given +pattern+ is obtained from the IO or the time specified as the
  # timeout passes. An array is returned when the pattern is obtained from the
  # IO. The first element of the array is the entire string obtained from the
  # IO until the pattern matches, followed by elements indicating which the
  # pattern which matched to the anchor in the regular expression.
  #
  # The optional timeout parameter defines, in seconds, the total time to wait
  # for the pattern.  If the timeout expires or eof is found, nil is returned
  # or yielded.  However, the buffer in a timeout session is kept for the next
  # expect call.  The default timeout is 9999999 seconds.
  def expect(pat,timeout=9999999)
    buf = ''.dup
    case pat
    when String
      e_pat = Regexp.new(Regexp.quote(pat))
    when Regexp
      e_pat = pat
    else
      raise TypeError, "unsupported pattern class: #{pat.class}"
    end
    @unusedBuf ||= ''
    while true
      if not @unusedBuf.empty?
        c = @unusedBuf.slice!(0)
      elsif !IO.select([self],nil,nil,timeout) or eof? then
        result = nil
        @unusedBuf = buf
        break
      else
        c = getc
      end
      buf << c
      if $expect_verbose
        STDOUT.print c
        STDOUT.flush
      end
      if mat=e_pat.match(buf) then
        result = [buf,*mat.captures]
        break
      end
    end
    if block_given? then
      yield result
    else
      return result
    end
    nil
  end
end
# frozen_string_literal: true

class Logger
  # Logging severity.
  module Severity
    # Low-level information, mostly for developers.
    DEBUG = 0
    # Generic (useful) information about system operation.
    INFO = 1
    # A warning.
    WARN = 2
    # A handleable error condition.
    ERROR = 3
    # An unhandleable error that results in a program crash.
    FATAL = 4
    # An unknown message that should always be logged.
    UNKNOWN = 5
  end
end
# frozen_string_literal: true

class Logger
  # Default formatter for log messages.
  class Formatter
    Format = "%s, [%s#%d] %5s -- %s: %s\n"

    attr_accessor :datetime_format

    def initialize
      @datetime_format = nil
    end

    def call(severity, time, progname, msg)
      Format % [severity[0..0], format_datetime(time), Process.pid, severity, progname,
        msg2str(msg)]
    end

  private

    def format_datetime(time)
      time.strftime(@datetime_format || "%Y-%m-%dT%H:%M:%S.%6N ")
    end

    def msg2str(msg)
      case msg
      when ::String
        msg
      when ::Exception
        "#{ msg.message } (#{ msg.class })\n#{ msg.backtrace.join("\n") if msg.backtrace }"
      else
        msg.inspect
      end
    end
  end
end
# frozen_string_literal: true

require_relative 'period'

class Logger
  # Device used for logging messages.
  class LogDevice
    include Period

    attr_reader :dev
    attr_reader :filename
    include MonitorMixin

    def initialize(log = nil, shift_age: nil, shift_size: nil, shift_period_suffix: nil, binmode: false)
      @dev = @filename = @shift_age = @shift_size = @shift_period_suffix = nil
      @binmode = binmode
      mon_initialize
      set_dev(log)
      if @filename
        @shift_age = shift_age || 7
        @shift_size = shift_size || 1048576
        @shift_period_suffix = shift_period_suffix || '%Y%m%d'

        unless @shift_age.is_a?(Integer)
          base_time = @dev.respond_to?(:stat) ? @dev.stat.mtime : Time.now
          @next_rotate_time = next_rotate_time(base_time, @shift_age)
        end
      end
    end

    def write(message)
      begin
        synchronize do
          if @shift_age and @dev.respond_to?(:stat)
            begin
              check_shift_log
            rescue
              warn("log shifting failed. #{$!}")
            end
          end
          begin
            @dev.write(message)
          rescue
            warn("log writing failed. #{$!}")
          end
        end
      rescue Exception => ignored
        warn("log writing failed. #{ignored}")
      end
    end

    def close
      begin
        synchronize do
          @dev.close rescue nil
        end
      rescue Exception
        @dev.close rescue nil
      end
    end

    def reopen(log = nil)
      # reopen the same filename if no argument, do nothing for IO
      log ||= @filename if @filename
      if log
        synchronize do
          if @filename and @dev
            @dev.close rescue nil # close only file opened by Logger
            @filename = nil
          end
          set_dev(log)
        end
      end
      self
    end

  private

    def set_dev(log)
      if log.respond_to?(:write) and log.respond_to?(:close)
        @dev = log
        if log.respond_to?(:path)
          @filename = log.path
        end
      else
        @dev = open_logfile(log)
        @dev.sync = true
        @dev.binmode if @binmode
        @filename = log
      end
    end

    def open_logfile(filename)
      begin
        File.open(filename, (File::WRONLY | File::APPEND))
      rescue Errno::ENOENT
        create_logfile(filename)
      end
    end

    def create_logfile(filename)
      begin
        logdev = File.open(filename, (File::WRONLY | File::APPEND | File::CREAT | File::EXCL))
        logdev.flock(File::LOCK_EX)
        logdev.sync = true
        logdev.binmode if @binmode
        add_log_header(logdev)
        logdev.flock(File::LOCK_UN)
      rescue Errno::EEXIST
        # file is created by another process
        logdev = open_logfile(filename)
        logdev.sync = true
      end
      logdev
    end

    def add_log_header(file)
      file.write(
        "# Logfile created on %s by %s\n" % [Time.now.to_s, Logger::ProgName]
      ) if file.size == 0
    end

    def check_shift_log
      if @shift_age.is_a?(Integer)
        # Note: always returns false if '0'.
        if @filename && (@shift_age > 0) && (@dev.stat.size > @shift_size)
          lock_shift_log { shift_log_age }
        end
      else
        now = Time.now
        if now >= @next_rotate_time
          @next_rotate_time = next_rotate_time(now, @shift_age)
          lock_shift_log { shift_log_period(previous_period_end(now, @shift_age)) }
        end
      end
    end

    if /mswin|mingw|cygwin/ =~ RUBY_PLATFORM
      def lock_shift_log
        yield
      end
    else
      def lock_shift_log
        retry_limit = 8
        retry_sleep = 0.1
        begin
          File.open(@filename, File::WRONLY | File::APPEND) do |lock|
            lock.flock(File::LOCK_EX) # inter-process locking. will be unlocked at closing file
            if File.identical?(@filename, lock) and File.identical?(lock, @dev)
              yield # log shifting
            else
              # log shifted by another process (i-node before locking and i-node after locking are different)
              @dev.close rescue nil
              @dev = open_logfile(@filename)
              @dev.sync = true
            end
          end
        rescue Errno::ENOENT
          # @filename file would not exist right after #rename and before #create_logfile
          if retry_limit <= 0
            warn("log rotation inter-process lock failed. #{$!}")
          else
            sleep retry_sleep
            retry_limit -= 1
            retry_sleep *= 2
            retry
          end
        end
      rescue
        warn("log rotation inter-process lock failed. #{$!}")
      end
    end

    def shift_log_age
      (@shift_age-3).downto(0) do |i|
        if FileTest.exist?("#{@filename}.#{i}")
          File.rename("#{@filename}.#{i}", "#{@filename}.#{i+1}")
        end
      end
      @dev.close rescue nil
      File.rename("#{@filename}", "#{@filename}.0")
      @dev = create_logfile(@filename)
      return true
    end

    def shift_log_period(period_end)
      suffix = period_end.strftime(@shift_period_suffix)
      age_file = "#{@filename}.#{suffix}"
      if FileTest.exist?(age_file)
        # try to avoid filename crash caused by Timestamp change.
        idx = 0
        # .99 can be overridden; avoid too much file search with 'loop do'
        while idx < 100
          idx += 1
          age_file = "#{@filename}.#{suffix}.#{idx}"
          break unless FileTest.exist?(age_file)
        end
      end
      @dev.close rescue nil
      File.rename("#{@filename}", age_file)
      @dev = create_logfile(@filename)
      return true
    end
  end
end
# frozen_string_literal: true

class Logger
  module Period
    module_function

    SiD = 24 * 60 * 60

    def next_rotate_time(now, shift_age)
      case shift_age
      when 'daily'
        t = Time.mktime(now.year, now.month, now.mday) + SiD
      when 'weekly'
        t = Time.mktime(now.year, now.month, now.mday) + SiD * (7 - now.wday)
      when 'monthly'
        t = Time.mktime(now.year, now.month, 1) + SiD * 32
        return Time.mktime(t.year, t.month, 1)
      when 'now', 'everytime'
        return now
      else
        raise ArgumentError, "invalid :shift_age #{shift_age.inspect}, should be daily, weekly, monthly, or everytime"
      end
      if t.hour.nonzero? or t.min.nonzero? or t.sec.nonzero?
        hour = t.hour
        t = Time.mktime(t.year, t.month, t.mday)
        t += SiD if hour > 12
      end
      t
    end

    def previous_period_end(now, shift_age)
      case shift_age
      when 'daily'
        t = Time.mktime(now.year, now.month, now.mday) - SiD / 2
      when 'weekly'
        t = Time.mktime(now.year, now.month, now.mday) - (SiD * now.wday + SiD / 2)
      when 'monthly'
        t = Time.mktime(now.year, now.month, 1) - SiD / 2
      when 'now', 'everytime'
        return now
      else
        raise ArgumentError, "invalid :shift_age #{shift_age.inspect}, should be daily, weekly, monthly, or everytime"
      end
      Time.mktime(t.year, t.month, t.mday, 23, 59, 59)
    end
  end
end
# frozen_string_literal: true

# not used after 1.2.7. just for compat.
class Logger
  class Error < RuntimeError # :nodoc:
  end
  class ShiftingError < Error # :nodoc:
  end
end
# frozen_string_literal: true

class Logger
  VERSION = "1.4.3"
end
# frozen_string_literal: true
# = delegate -- Support for the Delegation Pattern
#
# Documentation by James Edward Gray II and Gavin Sinclair

##
# This library provides three different ways to delegate method calls to an
# object.  The easiest to use is SimpleDelegator.  Pass an object to the
# constructor and all methods supported by the object will be delegated.  This
# object can be changed later.
#
# Going a step further, the top level DelegateClass method allows you to easily
# setup delegation through class inheritance.  This is considerably more
# flexible and thus probably the most common use for this library.
#
# Finally, if you need full control over the delegation scheme, you can inherit
# from the abstract class Delegator and customize as needed.  (If you find
# yourself needing this control, have a look at Forwardable which is also in
# the standard library.  It may suit your needs better.)
#
# SimpleDelegator's implementation serves as a nice example of the use of
# Delegator:
#
#   require 'delegate'
#
#   class SimpleDelegator < Delegator
#     def __getobj__
#       @delegate_sd_obj # return object we are delegating to, required
#     end
#
#     def __setobj__(obj)
#       @delegate_sd_obj = obj # change delegation object,
#                              # a feature we're providing
#     end
#   end
#
# == Notes
#
# Be advised, RDoc will not detect delegated methods.
#
class Delegator < BasicObject
  VERSION = "0.2.0"

  kernel = ::Kernel.dup
  kernel.class_eval do
    alias __raise__ raise
    [:to_s, :inspect, :=~, :!~, :===, :<=>, :hash].each do |m|
      undef_method m
    end
    private_instance_methods.each do |m|
      if /\Ablock_given\?\z|\Aiterator\?\z|\A__.*__\z/ =~ m
        next
      end
      undef_method m
    end
  end
  include kernel

  # :stopdoc:
  def self.const_missing(n)
    ::Object.const_get(n)
  end
  # :startdoc:

  ##
  # :method: raise
  # Use #__raise__ if your Delegator does not have a object to delegate the
  # #raise method call.
  #

  #
  # Pass in the _obj_ to delegate method calls to.  All methods supported by
  # _obj_ will be delegated to.
  #
  def initialize(obj)
    __setobj__(obj)
  end

  #
  # Handles the magic of delegation through \_\_getobj\_\_.
  #
  ruby2_keywords def method_missing(m, *args, &block)
    r = true
    target = self.__getobj__ {r = false}

    if r && target_respond_to?(target, m, false)
      target.__send__(m, *args, &block)
    elsif ::Kernel.method_defined?(m) || ::Kernel.private_method_defined?(m)
      ::Kernel.instance_method(m).bind_call(self, *args, &block)
    else
      super(m, *args, &block)
    end
  end

  #
  # Checks for a method provided by this the delegate object by forwarding the
  # call through \_\_getobj\_\_.
  #
  def respond_to_missing?(m, include_private)
    r = true
    target = self.__getobj__ {r = false}
    r &&= target_respond_to?(target, m, include_private)
    if r && include_private && !target_respond_to?(target, m, false)
      warn "delegator does not forward private method \##{m}", uplevel: 3
      return false
    end
    r
  end

  KERNEL_RESPOND_TO = ::Kernel.instance_method(:respond_to?)
  private_constant :KERNEL_RESPOND_TO

  # Handle BasicObject instances
  private def target_respond_to?(target, m, include_private)
    case target
    when Object
      target.respond_to?(m, include_private)
    else
      if KERNEL_RESPOND_TO.bind_call(target, :respond_to?)
        target.respond_to?(m, include_private)
      else
        KERNEL_RESPOND_TO.bind_call(target, m, include_private)
      end
    end
  end

  #
  # Returns the methods available to this delegate object as the union
  # of this object's and \_\_getobj\_\_ methods.
  #
  def methods(all=true)
    __getobj__.methods(all) | super
  end

  #
  # Returns the methods available to this delegate object as the union
  # of this object's and \_\_getobj\_\_ public methods.
  #
  def public_methods(all=true)
    __getobj__.public_methods(all) | super
  end

  #
  # Returns the methods available to this delegate object as the union
  # of this object's and \_\_getobj\_\_ protected methods.
  #
  def protected_methods(all=true)
    __getobj__.protected_methods(all) | super
  end

  # Note: no need to specialize private_methods, since they are not forwarded

  #
  # Returns true if two objects are considered of equal value.
  #
  def ==(obj)
    return true if obj.equal?(self)
    self.__getobj__ == obj
  end

  #
  # Returns true if two objects are not considered of equal value.
  #
  def !=(obj)
    return false if obj.equal?(self)
    __getobj__ != obj
  end

  #
  # Returns true if two objects are considered of equal value.
  #
  def eql?(obj)
    return true if obj.equal?(self)
    obj.eql?(__getobj__)
  end

  #
  # Delegates ! to the \_\_getobj\_\_
  #
  def !
    !__getobj__
  end

  #
  # This method must be overridden by subclasses and should return the object
  # method calls are being delegated to.
  #
  def __getobj__
    __raise__ ::NotImplementedError, "need to define `__getobj__'"
  end

  #
  # This method must be overridden by subclasses and change the object delegate
  # to _obj_.
  #
  def __setobj__(obj)
    __raise__ ::NotImplementedError, "need to define `__setobj__'"
  end

  #
  # Serialization support for the object returned by \_\_getobj\_\_.
  #
  def marshal_dump
    ivars = instance_variables.reject {|var| /\A@delegate_/ =~ var}
    [
      :__v2__,
      ivars, ivars.map {|var| instance_variable_get(var)},
      __getobj__
    ]
  end

  #
  # Reinitializes delegation from a serialized object.
  #
  def marshal_load(data)
    version, vars, values, obj = data
    if version == :__v2__
      vars.each_with_index {|var, i| instance_variable_set(var, values[i])}
      __setobj__(obj)
    else
      __setobj__(data)
    end
  end

  def initialize_clone(obj, freeze: nil) # :nodoc:
    self.__setobj__(obj.__getobj__.clone(freeze: freeze))
  end
  def initialize_dup(obj) # :nodoc:
    self.__setobj__(obj.__getobj__.dup)
  end
  private :initialize_clone, :initialize_dup

  ##
  # :method: freeze
  # Freeze both the object returned by \_\_getobj\_\_ and self.
  #
  def freeze
    __getobj__.freeze
    super()
  end

  @delegator_api = self.public_instance_methods
  def self.public_api # :nodoc:
    @delegator_api
  end
end

##
# A concrete implementation of Delegator, this class provides the means to
# delegate all supported method calls to the object passed into the constructor
# and even to change the object being delegated to at a later time with
# #__setobj__.
#
#   class User
#     def born_on
#       Date.new(1989, 9, 10)
#     end
#   end
#
#   require 'delegate'
#
#   class UserDecorator < SimpleDelegator
#     def birth_year
#       born_on.year
#     end
#   end
#
#   decorated_user = UserDecorator.new(User.new)
#   decorated_user.birth_year  #=> 1989
#   decorated_user.__getobj__  #=> #<User: ...>
#
# A SimpleDelegator instance can take advantage of the fact that SimpleDelegator
# is a subclass of +Delegator+ to call <tt>super</tt> to have methods called on
# the object being delegated to.
#
#   class SuperArray < SimpleDelegator
#     def [](*args)
#       super + 1
#     end
#   end
#
#   SuperArray.new([1])[0]  #=> 2
#
# Here's a simple example that takes advantage of the fact that
# SimpleDelegator's delegation object can be changed at any time.
#
#   class Stats
#     def initialize
#       @source = SimpleDelegator.new([])
#     end
#
#     def stats(records)
#       @source.__setobj__(records)
#
#       "Elements:  #{@source.size}\n" +
#       " Non-Nil:  #{@source.compact.size}\n" +
#       "  Unique:  #{@source.uniq.size}\n"
#     end
#   end
#
#   s = Stats.new
#   puts s.stats(%w{James Edward Gray II})
#   puts
#   puts s.stats([1, 2, 3, nil, 4, 5, 1, 2])
#
# Prints:
#
#   Elements:  4
#    Non-Nil:  4
#     Unique:  4
#
#   Elements:  8
#    Non-Nil:  7
#     Unique:  6
#
class SimpleDelegator < Delegator
  # Returns the current object method calls are being delegated to.
  def __getobj__
    unless defined?(@delegate_sd_obj)
      return yield if block_given?
      __raise__ ::ArgumentError, "not delegated"
    end
    @delegate_sd_obj
  end

  #
  # Changes the delegate object to _obj_.
  #
  # It's important to note that this does *not* cause SimpleDelegator's methods
  # to change.  Because of this, you probably only want to change delegation
  # to objects of the same type as the original delegate.
  #
  # Here's an example of changing the delegation object.
  #
  #   names = SimpleDelegator.new(%w{James Edward Gray II})
  #   puts names[1]    # => Edward
  #   names.__setobj__(%w{Gavin Sinclair})
  #   puts names[1]    # => Sinclair
  #
  def __setobj__(obj)
    __raise__ ::ArgumentError, "cannot delegate to self" if self.equal?(obj)
    @delegate_sd_obj = obj
  end
end

def Delegator.delegating_block(mid) # :nodoc:
  lambda do |*args, &block|
    target = self.__getobj__
    target.__send__(mid, *args, &block)
  end.ruby2_keywords
end

#
# The primary interface to this library.  Use to setup delegation when defining
# your class.
#
#   class MyClass < DelegateClass(ClassToDelegateTo) # Step 1
#     def initialize
#       super(obj_of_ClassToDelegateTo)              # Step 2
#     end
#   end
#
# or:
#
#   MyClass = DelegateClass(ClassToDelegateTo) do    # Step 1
#     def initialize
#       super(obj_of_ClassToDelegateTo)              # Step 2
#     end
#   end
#
# Here's a sample of use from Tempfile which is really a File object with a
# few special rules about storage location and when the File should be
# deleted.  That makes for an almost textbook perfect example of how to use
# delegation.
#
#   class Tempfile < DelegateClass(File)
#     # constant and class member data initialization...
#
#     def initialize(basename, tmpdir=Dir::tmpdir)
#       # build up file path/name in var tmpname...
#
#       @tmpfile = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL, 0600)
#
#       # ...
#
#       super(@tmpfile)
#
#       # below this point, all methods of File are supported...
#     end
#
#     # ...
#   end
#
def DelegateClass(superclass, &block)
  klass = Class.new(Delegator)
  ignores = [*::Delegator.public_api, :to_s, :inspect, :=~, :!~, :===]
  protected_instance_methods = superclass.protected_instance_methods
  protected_instance_methods -= ignores
  public_instance_methods = superclass.public_instance_methods
  public_instance_methods -= ignores
  klass.module_eval do
    def __getobj__ # :nodoc:
      unless defined?(@delegate_dc_obj)
        return yield if block_given?
        __raise__ ::ArgumentError, "not delegated"
      end
      @delegate_dc_obj
    end
    def __setobj__(obj)  # :nodoc:
      __raise__ ::ArgumentError, "cannot delegate to self" if self.equal?(obj)
      @delegate_dc_obj = obj
    end
    protected_instance_methods.each do |method|
      define_method(method, Delegator.delegating_block(method))
      protected method
    end
    public_instance_methods.each do |method|
      define_method(method, Delegator.delegating_block(method))
    end
  end
  klass.define_singleton_method :public_instance_methods do |all=true|
    super(all) | superclass.public_instance_methods
  end
  klass.define_singleton_method :protected_instance_methods do |all=true|
    super(all) | superclass.protected_instance_methods
  end
  klass.define_singleton_method :instance_methods do |all=true|
    super(all) | superclass.instance_methods
  end
  klass.define_singleton_method :public_instance_method do |name|
    super(name)
  rescue NameError
    raise unless self.public_instance_methods.include?(name)
    superclass.public_instance_method(name)
  end
  klass.define_singleton_method :instance_method do |name|
    super(name)
  rescue NameError
    raise unless self.instance_methods.include?(name)
    superclass.instance_method(name)
  end
  klass.module_eval(&block) if block
  return klass
end
# frozen_string_literal: false
require 'digest.so'

module Digest
  # A mutex for Digest().
  REQUIRE_MUTEX = Thread::Mutex.new

  def self.const_missing(name) # :nodoc:
    case name
    when :SHA256, :SHA384, :SHA512
      lib = 'digest/sha2.so'
    else
      lib = File.join('digest', name.to_s.downcase)
    end

    begin
      require lib
    rescue LoadError
      raise LoadError, "library not found for class Digest::#{name} -- #{lib}", caller(1)
    end
    unless Digest.const_defined?(name)
      raise NameError, "uninitialized constant Digest::#{name}", caller(1)
    end
    Digest.const_get(name)
  end

  class ::Digest::Class
    # Creates a digest object and reads a given file, _name_.
    # Optional arguments are passed to the constructor of the digest
    # class.
    #
    #   p Digest::SHA256.file("X11R6.8.2-src.tar.bz2").hexdigest
    #   # => "f02e3c85572dc9ad7cb77c2a638e3be24cc1b5bea9fdbb0b0299c9668475c534"
    def self.file(name, *args)
      new(*args).file(name)
    end

    # Returns the base64 encoded hash value of a given _string_.  The
    # return value is properly padded with '=' and contains no line
    # feeds.
    def self.base64digest(str, *args)
      [digest(str, *args)].pack('m0')
    end
  end

  module Instance
    # Updates the digest with the contents of a given file _name_ and
    # returns self.
    def file(name)
      File.open(name, "rb") {|f|
        buf = ""
        while f.read(16384, buf)
          update buf
        end
      }
      self
    end

    # If none is given, returns the resulting hash value of the digest
    # in a base64 encoded form, keeping the digest's state.
    #
    # If a +string+ is given, returns the hash value for the given
    # +string+ in a base64 encoded form, resetting the digest to the
    # initial state before and after the process.
    #
    # In either case, the return value is properly padded with '=' and
    # contains no line feeds.
    def base64digest(str = nil)
      [str ? digest(str) : digest].pack('m0')
    end

    # Returns the resulting hash value and resets the digest to the
    # initial state.
    def base64digest!
      [digest!].pack('m0')
    end
  end
end

# call-seq:
#   Digest(name) -> digest_subclass
#
# Returns a Digest subclass by +name+ in a thread-safe manner even
# when on-demand loading is involved.
#
#   require 'digest'
#
#   Digest("MD5")
#   # => Digest::MD5
#
#   Digest(:SHA256)
#   # => Digest::SHA256
#
#   Digest(:Foo)
#   # => LoadError: library not found for class Digest::Foo -- digest/foo
def Digest(name)
  const = name.to_sym
  Digest::REQUIRE_MUTEX.synchronize {
    # Ignore autoload's because it is void when we have #const_missing
    Digest.const_missing(const)
  }
rescue LoadError
  # Constants do not necessarily rely on digest/*.
  if Digest.const_defined?(const)
    Digest.const_get(const)
  else
    raise
  end
end
# frozen_string_literal: false

begin
  require 'psych'
rescue LoadError
  warn "It seems your ruby installation is missing psych (for YAML output).\n" \
    "To eliminate this warning, please install libyaml and reinstall your ruby.\n",
    uplevel: 1
  raise
end

YAML = Psych # :nodoc:

# YAML Ain't Markup Language
#
# This module provides a Ruby interface for data serialization in YAML format.
#
# The YAML module is an alias of Psych, the YAML engine for Ruby.
#
# == Usage
#
# Working with YAML can be very simple, for example:
#
#     require 'yaml'
#     # Parse a YAML string
#     YAML.load("--- foo") #=> "foo"
#
#     # Emit some YAML
#     YAML.dump("foo")     # => "--- foo\n...\n"
#     { :a => 'b'}.to_yaml  # => "---\n:a: b\n"
#
# As the implementation is provided by the Psych library, detailed documentation
# can be found in that library's docs (also part of standard library).
#
# == Security
#
# Do not use YAML to load untrusted data. Doing so is unsafe and could allow
# malicious input to execute arbitrary code inside your application. Please see
# doc/security.rdoc for more information.
#
# == History
#
# Syck was the original YAML implementation in Ruby's standard library
# developed by why the lucky stiff.
#
# You can still use Syck, if you prefer, for parsing and emitting YAML, but you
# must install the 'syck' gem now in order to use it.
#
# In older Ruby versions, ie. <= 1.9, Syck is still provided, however it was
# completely removed with the release of Ruby 2.0.0.
#
# == More info
#
# For more advanced details on the implementation see Psych, and also check out
# http://yaml.org for spec details and other helpful information.
#
# Psych is maintained by Aaron Patterson on github: https://github.com/ruby/psych
#
# Syck can also be found on github: https://github.com/ruby/syck
module YAML
end
# frozen_string_literal: true
# = PStore -- Transactional File Storage for Ruby Objects
#
# pstore.rb -
#   originally by matz
#   documentation by Kev Jackson and James Edward Gray II
#   improved by Hongli Lai
#
# See PStore for documentation.

require "digest"

#
# PStore implements a file based persistence mechanism based on a Hash.  User
# code can store hierarchies of Ruby objects (values) into the data store file
# by name (keys).  An object hierarchy may be just a single object.  User code
# may later read values back from the data store or even update data, as needed.
#
# The transactional behavior ensures that any changes succeed or fail together.
# This can be used to ensure that the data store is not left in a transitory
# state, where some values were updated but others were not.
#
# Behind the scenes, Ruby objects are stored to the data store file with
# Marshal.  That carries the usual limitations.  Proc objects cannot be
# marshalled, for example.
#
# == Usage example:
#
#  require "pstore"
#
#  # a mock wiki object...
#  class WikiPage
#    def initialize( page_name, author, contents )
#      @page_name = page_name
#      @revisions = Array.new
#
#      add_revision(author, contents)
#    end
#
#    attr_reader :page_name
#
#    def add_revision( author, contents )
#      @revisions << { :created  => Time.now,
#                      :author   => author,
#                      :contents => contents }
#    end
#
#    def wiki_page_references
#      [@page_name] + @revisions.last[:contents].scan(/\b(?:[A-Z]+[a-z]+){2,}/)
#    end
#
#    # ...
#  end
#
#  # create a new page...
#  home_page = WikiPage.new( "HomePage", "James Edward Gray II",
#                            "A page about the JoysOfDocumentation..." )
#
#  # then we want to update page data and the index together, or not at all...
#  wiki = PStore.new("wiki_pages.pstore")
#  wiki.transaction do  # begin transaction; do all of this or none of it
#    # store page...
#    wiki[home_page.page_name] = home_page
#    # ensure that an index has been created...
#    wiki[:wiki_index] ||= Array.new
#    # update wiki index...
#    wiki[:wiki_index].push(*home_page.wiki_page_references)
#  end                   # commit changes to wiki data store file
#
#  ### Some time later... ###
#
#  # read wiki data...
#  wiki.transaction(true) do  # begin read-only transaction, no changes allowed
#    wiki.roots.each do |data_root_name|
#      p data_root_name
#      p wiki[data_root_name]
#    end
#  end
#
# == Transaction modes
#
# By default, file integrity is only ensured as long as the operating system
# (and the underlying hardware) doesn't raise any unexpected I/O errors. If an
# I/O error occurs while PStore is writing to its file, then the file will
# become corrupted.
#
# You can prevent this by setting <em>pstore.ultra_safe = true</em>.
# However, this results in a minor performance loss, and only works on platforms
# that support atomic file renames. Please consult the documentation for
# +ultra_safe+ for details.
#
# Needless to say, if you're storing valuable data with PStore, then you should
# backup the PStore files from time to time.
class PStore
  VERSION = "0.1.1"

  RDWR_ACCESS = {mode: IO::RDWR | IO::CREAT | IO::BINARY, encoding: Encoding::ASCII_8BIT}.freeze
  RD_ACCESS = {mode: IO::RDONLY | IO::BINARY, encoding: Encoding::ASCII_8BIT}.freeze
  WR_ACCESS = {mode: IO::WRONLY | IO::CREAT | IO::TRUNC | IO::BINARY, encoding: Encoding::ASCII_8BIT}.freeze

  # The error type thrown by all PStore methods.
  class Error < StandardError
  end

  # Whether PStore should do its best to prevent file corruptions, even when under
  # unlikely-to-occur error conditions such as out-of-space conditions and other
  # unusual OS filesystem errors. Setting this flag comes at the price in the form
  # of a performance loss.
  #
  # This flag only has effect on platforms on which file renames are atomic (e.g.
  # all POSIX platforms: Linux, MacOS X, FreeBSD, etc). The default value is false.
  attr_accessor :ultra_safe

  #
  # To construct a PStore object, pass in the _file_ path where you would like
  # the data to be stored.
  #
  # PStore objects are always reentrant. But if _thread_safe_ is set to true,
  # then it will become thread-safe at the cost of a minor performance hit.
  #
  def initialize(file, thread_safe = false)
    dir = File::dirname(file)
    unless File::directory? dir
      raise PStore::Error, format("directory %s does not exist", dir)
    end
    if File::exist? file and not File::readable? file
      raise PStore::Error, format("file %s not readable", file)
    end
    @filename = file
    @abort = false
    @ultra_safe = false
    @thread_safe = thread_safe
    @lock = Thread::Mutex.new
  end

  # Raises PStore::Error if the calling code is not in a PStore#transaction.
  def in_transaction
    raise PStore::Error, "not in transaction" unless @lock.locked?
  end
  #
  # Raises PStore::Error if the calling code is not in a PStore#transaction or
  # if the code is in a read-only PStore#transaction.
  #
  def in_transaction_wr
    in_transaction
    raise PStore::Error, "in read-only transaction" if @rdonly
  end
  private :in_transaction, :in_transaction_wr

  #
  # Retrieves a value from the PStore file data, by _name_.  The hierarchy of
  # Ruby objects stored under that root _name_ will be returned.
  #
  # *WARNING*:  This method is only valid in a PStore#transaction.  It will
  # raise PStore::Error if called at any other time.
  #
  def [](name)
    in_transaction
    @table[name]
  end
  #
  # This method is just like PStore#[], save that you may also provide a
  # _default_ value for the object.  In the event the specified _name_ is not
  # found in the data store, your _default_ will be returned instead.  If you do
  # not specify a default, PStore::Error will be raised if the object is not
  # found.
  #
  # *WARNING*:  This method is only valid in a PStore#transaction.  It will
  # raise PStore::Error if called at any other time.
  #
  def fetch(name, default=PStore::Error)
    in_transaction
    unless @table.key? name
      if default == PStore::Error
        raise PStore::Error, format("undefined root name `%s'", name)
      else
        return default
      end
    end
    @table[name]
  end
  #
  # Stores an individual Ruby object or a hierarchy of Ruby objects in the data
  # store file under the root _name_.  Assigning to a _name_ already in the data
  # store clobbers the old data.
  #
  # == Example:
  #
  #  require "pstore"
  #
  #  store = PStore.new("data_file.pstore")
  #  store.transaction do  # begin transaction
  #    # load some data into the store...
  #    store[:single_object] = "My data..."
  #    store[:obj_hierarchy] = { "Kev Jackson" => ["rational.rb", "pstore.rb"],
  #                              "James Gray"  => ["erb.rb", "pstore.rb"] }
  #  end                   # commit changes to data store file
  #
  # *WARNING*:  This method is only valid in a PStore#transaction and it cannot
  # be read-only.  It will raise PStore::Error if called at any other time.
  #
  def []=(name, value)
    in_transaction_wr
    @table[name] = value
  end
  #
  # Removes an object hierarchy from the data store, by _name_.
  #
  # *WARNING*:  This method is only valid in a PStore#transaction and it cannot
  # be read-only.  It will raise PStore::Error if called at any other time.
  #
  def delete(name)
    in_transaction_wr
    @table.delete name
  end

  #
  # Returns the names of all object hierarchies currently in the store.
  #
  # *WARNING*:  This method is only valid in a PStore#transaction.  It will
  # raise PStore::Error if called at any other time.
  #
  def roots
    in_transaction
    @table.keys
  end
  #
  # Returns true if the supplied _name_ is currently in the data store.
  #
  # *WARNING*:  This method is only valid in a PStore#transaction.  It will
  # raise PStore::Error if called at any other time.
  #
  def root?(name)
    in_transaction
    @table.key? name
  end
  # Returns the path to the data store file.
  def path
    @filename
  end

  #
  # Ends the current PStore#transaction, committing any changes to the data
  # store immediately.
  #
  # == Example:
  #
  #  require "pstore"
  #
  #  store = PStore.new("data_file.pstore")
  #  store.transaction do  # begin transaction
  #    # load some data into the store...
  #    store[:one] = 1
  #    store[:two] = 2
  #
  #    store.commit        # end transaction here, committing changes
  #
  #    store[:three] = 3   # this change is never reached
  #  end
  #
  # *WARNING*:  This method is only valid in a PStore#transaction.  It will
  # raise PStore::Error if called at any other time.
  #
  def commit
    in_transaction
    @abort = false
    throw :pstore_abort_transaction
  end
  #
  # Ends the current PStore#transaction, discarding any changes to the data
  # store.
  #
  # == Example:
  #
  #  require "pstore"
  #
  #  store = PStore.new("data_file.pstore")
  #  store.transaction do  # begin transaction
  #    store[:one] = 1     # this change is not applied, see below...
  #    store[:two] = 2     # this change is not applied, see below...
  #
  #    store.abort         # end transaction here, discard all changes
  #
  #    store[:three] = 3   # this change is never reached
  #  end
  #
  # *WARNING*:  This method is only valid in a PStore#transaction.  It will
  # raise PStore::Error if called at any other time.
  #
  def abort
    in_transaction
    @abort = true
    throw :pstore_abort_transaction
  end

  #
  # Opens a new transaction for the data store.  Code executed inside a block
  # passed to this method may read and write data to and from the data store
  # file.
  #
  # At the end of the block, changes are committed to the data store
  # automatically.  You may exit the transaction early with a call to either
  # PStore#commit or PStore#abort.  See those methods for details about how
  # changes are handled.  Raising an uncaught Exception in the block is
  # equivalent to calling PStore#abort.
  #
  # If _read_only_ is set to +true+, you will only be allowed to read from the
  # data store during the transaction and any attempts to change the data will
  # raise a PStore::Error.
  #
  # Note that PStore does not support nested transactions.
  #
  def transaction(read_only = false)  # :yields:  pstore
    value = nil
    if !@thread_safe
      raise PStore::Error, "nested transaction" unless @lock.try_lock
    else
      begin
        @lock.lock
      rescue ThreadError
        raise PStore::Error, "nested transaction"
      end
    end
    begin
      @rdonly = read_only
      @abort = false
      file = open_and_lock_file(@filename, read_only)
      if file
        begin
          @table, checksum, original_data_size = load_data(file, read_only)

          catch(:pstore_abort_transaction) do
            value = yield(self)
          end

          if !@abort && !read_only
            save_data(checksum, original_data_size, file)
          end
        ensure
          file.close
        end
      else
        # This can only occur if read_only == true.
        @table = {}
        catch(:pstore_abort_transaction) do
          value = yield(self)
        end
      end
    ensure
      @lock.unlock
    end
    value
  end

  private
  # Constant for relieving Ruby's garbage collector.
  CHECKSUM_ALGO = %w[SHA512 SHA384 SHA256 SHA1 RMD160 MD5].each do |algo|
    begin
      break Digest(algo)
    rescue LoadError
    end
  end
  EMPTY_STRING = ""
  EMPTY_MARSHAL_DATA = Marshal.dump({})
  EMPTY_MARSHAL_CHECKSUM = CHECKSUM_ALGO.digest(EMPTY_MARSHAL_DATA)

  #
  # Open the specified filename (either in read-only mode or in
  # read-write mode) and lock it for reading or writing.
  #
  # The opened File object will be returned. If _read_only_ is true,
  # and the file does not exist, then nil will be returned.
  #
  # All exceptions are propagated.
  #
  def open_and_lock_file(filename, read_only)
    if read_only
      begin
        file = File.new(filename, **RD_ACCESS)
        begin
          file.flock(File::LOCK_SH)
          return file
        rescue
          file.close
          raise
        end
      rescue Errno::ENOENT
        return nil
      end
    else
      file = File.new(filename, **RDWR_ACCESS)
      file.flock(File::LOCK_EX)
      return file
    end
  end

  # Load the given PStore file.
  # If +read_only+ is true, the unmarshalled Hash will be returned.
  # If +read_only+ is false, a 3-tuple will be returned: the unmarshalled
  # Hash, a checksum of the data, and the size of the data.
  def load_data(file, read_only)
    if read_only
      begin
        table = load(file)
        raise Error, "PStore file seems to be corrupted." unless table.is_a?(Hash)
      rescue EOFError
        # This seems to be a newly-created file.
        table = {}
      end
      table
    else
      data = file.read
      if data.empty?
        # This seems to be a newly-created file.
        table = {}
        checksum = empty_marshal_checksum
        size = empty_marshal_data.bytesize
      else
        table = load(data)
        checksum = CHECKSUM_ALGO.digest(data)
        size = data.bytesize
        raise Error, "PStore file seems to be corrupted." unless table.is_a?(Hash)
      end
      data.replace(EMPTY_STRING)
      [table, checksum, size]
    end
  end

  def on_windows?
    is_windows = RUBY_PLATFORM =~ /mswin|mingw|bccwin|wince/
    self.class.__send__(:define_method, :on_windows?) do
      is_windows
    end
    is_windows
  end

  def save_data(original_checksum, original_file_size, file)
    new_data = dump(@table)

    if new_data.bytesize != original_file_size || CHECKSUM_ALGO.digest(new_data) != original_checksum
      if @ultra_safe && !on_windows?
        # Windows doesn't support atomic file renames.
        save_data_with_atomic_file_rename_strategy(new_data, file)
      else
        save_data_with_fast_strategy(new_data, file)
      end
    end

    new_data.replace(EMPTY_STRING)
  end

  def save_data_with_atomic_file_rename_strategy(data, file)
    temp_filename = "#{@filename}.tmp.#{Process.pid}.#{rand 1000000}"
    temp_file = File.new(temp_filename, **WR_ACCESS)
    begin
      temp_file.flock(File::LOCK_EX)
      temp_file.write(data)
      temp_file.flush
      File.rename(temp_filename, @filename)
    rescue
      File.unlink(temp_file) rescue nil
      raise
    ensure
      temp_file.close
    end
  end

  def save_data_with_fast_strategy(data, file)
    file.rewind
    file.write(data)
    file.truncate(data.bytesize)
  end


  # This method is just a wrapped around Marshal.dump
  # to allow subclass overriding used in YAML::Store.
  def dump(table)  # :nodoc:
    Marshal::dump(table)
  end

  # This method is just a wrapped around Marshal.load.
  # to allow subclass overriding used in YAML::Store.
  def load(content)  # :nodoc:
    Marshal::load(content)
  end

  def empty_marshal_data
    EMPTY_MARSHAL_DATA
  end
  def empty_marshal_checksum
    EMPTY_MARSHAL_CHECKSUM
  end
end
# -*- coding: us-ascii -*-
# frozen-string-literal: false
# module to create Makefile for extension modules
# invoke like: ruby -r mkmf extconf.rb

require 'rbconfig'
require 'fileutils'
require 'shellwords'

class String
  # :stopdoc:

  # Wraps a string in escaped quotes if it contains whitespace.
  def quote
    /\s/ =~ self ? "\"#{self}\"" : "#{self}"
  end

  # Escape whitespaces for Makefile.
  def unspace
    gsub(/\s/, '\\\\\\&')
  end

  # Generates a string used as cpp macro name.
  def tr_cpp
    strip.upcase.tr_s("^A-Z0-9_*", "_").tr_s("*", "P")
  end

  def funcall_style
    /\)\z/ =~ self ? dup : "#{self}()"
  end

  def sans_arguments
    self[/\A[^()]+/]
  end

  # :startdoc:
end

class Array
  # :stopdoc:

  # Wraps all strings in escaped quotes if they contain whitespace.
  def quote
    map {|s| s.quote}
  end

  # :startdoc:
end

##
# mkmf.rb is used by Ruby C extensions to generate a Makefile which will
# correctly compile and link the C extension to Ruby and a third-party
# library.
module MakeMakefile
  #### defer until this module become global-state free.
  # def self.extended(obj)
  #   obj.init_mkmf
  #   super
  # end
  #
  # def initialize(*args, rbconfig: RbConfig, **rest)
  #   init_mkmf(rbconfig::MAKEFILE_CONFIG, rbconfig::CONFIG)
  #   super(*args, **rest)
  # end

  ##
  # The makefile configuration using the defaults from when Ruby was built.

  CONFIG = RbConfig::MAKEFILE_CONFIG
  ORIG_LIBPATH = ENV['LIB']

  ##
  # Extensions for files compiled with a C compiler

  C_EXT = %w[c m]

  ##
  # Extensions for files complied with a C++ compiler

  CXX_EXT = %w[cc mm cxx cpp]
  unless File.exist?(File.join(*File.split(__FILE__).tap {|d, b| b.swapcase}))
    CXX_EXT.concat(%w[C])
  end

  ##
  # Extensions for source files

  SRC_EXT = C_EXT + CXX_EXT

  ##
  # Extensions for header files

  HDR_EXT = %w[h hpp]
  $static = nil
  $config_h = '$(arch_hdrdir)/ruby/config.h'
  $default_static = $static

  unless defined? $configure_args
    $configure_args = {}
    args = CONFIG["configure_args"]
    if ENV["CONFIGURE_ARGS"]
      args << " " << ENV["CONFIGURE_ARGS"]
    end
    for arg in Shellwords::shellwords(args)
      arg, val = arg.split('=', 2)
      next unless arg
      arg.tr!('_', '-')
      if arg.sub!(/^(?!--)/, '--')
        val or next
        arg.downcase!
      end
      next if /^--(?:top|topsrc|src|cur)dir$/ =~ arg
      $configure_args[arg] = val || true
    end
    for arg in ARGV
      arg, val = arg.split('=', 2)
      next unless arg
      arg.tr!('_', '-')
      if arg.sub!(/^(?!--)/, '--')
        val or next
        arg.downcase!
      end
      $configure_args[arg] = val || true
    end
  end

  $libdir = CONFIG["libdir"]
  $rubylibdir = CONFIG["rubylibdir"]
  $archdir = CONFIG["archdir"]
  $sitedir = CONFIG["sitedir"]
  $sitelibdir = CONFIG["sitelibdir"]
  $sitearchdir = CONFIG["sitearchdir"]
  $vendordir = CONFIG["vendordir"]
  $vendorlibdir = CONFIG["vendorlibdir"]
  $vendorarchdir = CONFIG["vendorarchdir"]

  $mswin = /mswin/ =~ RUBY_PLATFORM
  $mingw = /mingw/ =~ RUBY_PLATFORM
  $cygwin = /cygwin/ =~ RUBY_PLATFORM
  $netbsd = /netbsd/ =~ RUBY_PLATFORM
  $haiku = /haiku/ =~ RUBY_PLATFORM
  $solaris = /solaris/ =~ RUBY_PLATFORM
  $universal = /universal/ =~ RUBY_PLATFORM
  $dest_prefix_pattern = (File::PATH_SEPARATOR == ';' ? /\A([[:alpha:]]:)?/ : /\A/)

  # :stopdoc:

  def config_string(key, config = CONFIG)
    s = config[key] and !s.empty? and block_given? ? yield(s) : s
  end
  module_function :config_string

  def dir_re(dir)
    Regexp.new('\$(?:\('+dir+'\)|\{'+dir+'\})(?:\$(?:\(target_prefix\)|\{target_prefix\}))?')
  end
  module_function :dir_re

  def relative_from(path, base)
    dir = File.join(path, "")
    if File.expand_path(dir) == File.expand_path(dir, base)
      path
    else
      File.join(base, path)
    end
  end

  INSTALL_DIRS = [
    [dir_re('commondir'), "$(RUBYCOMMONDIR)"],
    [dir_re('sitedir'), "$(RUBYCOMMONDIR)"],
    [dir_re('vendordir'), "$(RUBYCOMMONDIR)"],
    [dir_re('rubylibdir'), "$(RUBYLIBDIR)"],
    [dir_re('archdir'), "$(RUBYARCHDIR)"],
    [dir_re('sitelibdir'), "$(RUBYLIBDIR)"],
    [dir_re('vendorlibdir'), "$(RUBYLIBDIR)"],
    [dir_re('sitearchdir'), "$(RUBYARCHDIR)"],
    [dir_re('vendorarchdir'), "$(RUBYARCHDIR)"],
    [dir_re('rubyhdrdir'), "$(RUBYHDRDIR)"],
    [dir_re('sitehdrdir'), "$(SITEHDRDIR)"],
    [dir_re('vendorhdrdir'), "$(VENDORHDRDIR)"],
    [dir_re('bindir'), "$(BINDIR)"],
  ]

  def install_dirs(target_prefix = nil)
    if $extout and $extmk
      dirs = [
        ['BINDIR',        '$(extout)/bin'],
        ['RUBYCOMMONDIR', '$(extout)/common'],
        ['RUBYLIBDIR',    '$(RUBYCOMMONDIR)$(target_prefix)'],
        ['RUBYARCHDIR',   '$(extout)/$(arch)$(target_prefix)'],
        ['HDRDIR',        '$(extout)/include/ruby$(target_prefix)'],
        ['ARCHHDRDIR',    '$(extout)/include/$(arch)/ruby$(target_prefix)'],
        ['extout',        "#$extout"],
        ['extout_prefix', "#$extout_prefix"],
      ]
    elsif $extmk
      dirs = [
        ['BINDIR',        '$(bindir)'],
        ['RUBYCOMMONDIR', '$(rubylibdir)'],
        ['RUBYLIBDIR',    '$(rubylibdir)$(target_prefix)'],
        ['RUBYARCHDIR',   '$(archdir)$(target_prefix)'],
        ['HDRDIR',        '$(rubyhdrdir)/ruby$(target_prefix)'],
        ['ARCHHDRDIR',    '$(rubyhdrdir)/$(arch)/ruby$(target_prefix)'],
      ]
    elsif $configure_args.has_key?('--vendor')
      dirs = [
        ['BINDIR',        '$(bindir)'],
        ['RUBYCOMMONDIR', '$(vendordir)$(target_prefix)'],
        ['RUBYLIBDIR',    '$(vendorlibdir)$(target_prefix)'],
        ['RUBYARCHDIR',   '$(vendorarchdir)$(target_prefix)'],
        ['HDRDIR',        '$(vendorhdrdir)$(target_prefix)'],
        ['ARCHHDRDIR',    '$(vendorarchhdrdir)$(target_prefix)'],
      ]
    else
      dirs = [
        ['BINDIR',        '$(bindir)'],
        ['RUBYCOMMONDIR', '$(sitedir)$(target_prefix)'],
        ['RUBYLIBDIR',    '$(sitelibdir)$(target_prefix)'],
        ['RUBYARCHDIR',   '$(sitearchdir)$(target_prefix)'],
        ['HDRDIR',        '$(sitehdrdir)$(target_prefix)'],
        ['ARCHHDRDIR',    '$(sitearchhdrdir)$(target_prefix)'],
      ]
    end
    dirs << ['target_prefix', (target_prefix ? "/#{target_prefix}" : "")]
    dirs
  end

  def map_dir(dir, map = nil)
    map ||= INSTALL_DIRS
    map.inject(dir) {|d, (orig, new)| d.gsub(orig, new)}
  end

  topdir = File.dirname(File.dirname(__FILE__))
  path = File.expand_path($0)
  until (dir = File.dirname(path)) == path
    if File.identical?(dir, topdir)
      $extmk = true if %r"\A(?:ext|enc|tool|test)\z" =~ File.basename(path)
      break
    end
    path = dir
  end
  $extmk ||= false
  if not $extmk and File.exist?(($hdrdir = RbConfig::CONFIG["rubyhdrdir"]) + "/ruby/ruby.h")
    $topdir = $hdrdir
    $top_srcdir = $hdrdir
    $arch_hdrdir = RbConfig::CONFIG["rubyarchhdrdir"]
  elsif File.exist?(($hdrdir = ($top_srcdir ||= topdir) + "/include")  + "/ruby.h")
    $topdir ||= RbConfig::CONFIG["topdir"]
    $arch_hdrdir = "$(extout)/include/$(arch)"
  else
    abort <<MESSAGE
mkmf.rb can't find header files for ruby at #{$hdrdir}/ruby.h

You might have to install separate package for the ruby development
environment, ruby-dev or ruby-devel for example.
MESSAGE
  end

  CONFTEST = "conftest".freeze
  CONFTEST_C = "#{CONFTEST}.c"

  OUTFLAG = CONFIG['OUTFLAG']
  COUTFLAG = CONFIG['COUTFLAG']
  CSRCFLAG = CONFIG['CSRCFLAG']
  CPPOUTFILE = config_string('CPPOUTFILE') {|str| str.sub(/\bconftest\b/, CONFTEST)}

  def rm_f(*files)
    opt = (Hash === files.last ? [files.pop] : [])
    FileUtils.rm_f(Dir[*files.flatten], *opt)
  end
  module_function :rm_f

  def rm_rf(*files)
    opt = (Hash === files.last ? [files.pop] : [])
    FileUtils.rm_rf(Dir[*files.flatten], *opt)
  end
  module_function :rm_rf

  # Returns time stamp of the +target+ file if it exists and is newer than or
  # equal to all of +times+.
  def modified?(target, times)
    (t = File.mtime(target)) rescue return nil
    Array === times or times = [times]
    t if times.all? {|n| n <= t}
  end

  def split_libs(*strs)
    strs.map {|s| s.split(/\s+(?=-|\z)/)}.flatten
  end

  def merge_libs(*libs)
    libs.inject([]) do |x, y|
      y = y.inject([]) {|ary, e| ary.last == e ? ary : ary << e}
      y.each_with_index do |v, yi|
        if xi = x.rindex(v)
          x[(xi+1)..-1] = merge_libs(y[(yi+1)..-1], x[(xi+1)..-1])
          x[xi, 0] = y[0...yi]
          break
        end
      end and x.concat(y)
      x
    end
  end

  # This is a custom logging module. It generates an mkmf.log file when you
  # run your extconf.rb script. This can be useful for debugging unexpected
  # failures.
  #
  # This module and its associated methods are meant for internal use only.
  #
  module Logging
    @log = nil
    @logfile = 'mkmf.log'
    @orgerr = $stderr.dup
    @orgout = $stdout.dup
    @postpone = 0
    @quiet = $extmk

    def self::log_open
      @log ||= File::open(@logfile, 'wb')
      @log.sync = true
    end

    def self::log_opened?
      @log and not @log.closed?
    end

    def self::open
      log_open
      $stderr.reopen(@log)
      $stdout.reopen(@log)
      yield
    ensure
      $stderr.reopen(@orgerr)
      $stdout.reopen(@orgout)
    end

    def self::message(*s)
      log_open
      @log.printf(*s)
    end

    def self::logfile file
      @logfile = file
      log_close
    end

    def self::log_close
      if @log and not @log.closed?
        @log.flush
        @log.close
        @log = nil
      end
    end

    def self::postpone
      tmplog = "mkmftmp#{@postpone += 1}.log"
      open do
        log, *save = @log, @logfile, @orgout, @orgerr
        @log, @logfile, @orgout, @orgerr = nil, tmplog, log, log
        begin
          log.print(open {yield @log})
        ensure
          @log.close if @log and not @log.closed?
          File::open(tmplog) {|t| FileUtils.copy_stream(t, log)} if File.exist?(tmplog)
          @log, @logfile, @orgout, @orgerr = log, *save
          @postpone -= 1
          MakeMakefile.rm_f tmplog
        end
      end
    end

    class << self
      attr_accessor :quiet
    end
  end

  def libpath_env
    # used only if native compiling
    if libpathenv = config_string("LIBPATHENV")
      pathenv = ENV[libpathenv]
      libpath = RbConfig.expand($DEFLIBPATH.join(File::PATH_SEPARATOR))
      {libpathenv => [libpath, pathenv].compact.join(File::PATH_SEPARATOR)}
    else
      {}
    end
  end

  def xsystem command, opts = nil
    varpat = /\$\((\w+)\)|\$\{(\w+)\}/
    if varpat =~ command
      vars = Hash.new {|h, k| h[k] = ENV[k]}
      command = command.dup
      nil while command.gsub!(varpat) {vars[$1||$2]}
    end
    Logging::open do
      puts command.quote
      if opts and opts[:werror]
        result = nil
        Logging.postpone do |log|
          output = IO.popen(libpath_env, command, &:read)
          result = ($?.success? and File.zero?(log.path))
          output
        end
        result
      else
        system(libpath_env, command)
      end
    end
  end

  def xpopen command, *mode, &block
    Logging::open do
      case mode[0]
      when nil, /^r/
        puts "#{command} |"
      else
        puts "| #{command}"
      end
      IO.popen(libpath_env, command, *mode, &block)
    end
  end

  def log_src(src, heading="checked program was")
    src = src.split(/^/)
    fmt = "%#{src.size.to_s.size}d: %s"
    Logging::message <<"EOM"
#{heading}:
/* begin */
EOM
    src.each_with_index {|line, no| Logging::message fmt, no+1, line}
    Logging::message <<"EOM"
/* end */

EOM
  end

  def conftest_source
    CONFTEST_C
  end

  def create_tmpsrc(src)
    src = "#{COMMON_HEADERS}\n#{src}"
    src = yield(src) if block_given?
    src.gsub!(/[ \t]+$/, '')
    src.gsub!(/\A\n+|^\n+$/, '')
    src.sub!(/[^\n]\z/, "\\&\n")
    count = 0
    begin
      open(conftest_source, "wb") do |cfile|
        cfile.print src
      end
    rescue Errno::EACCES
      if (count += 1) < 5
        sleep 0.2
        retry
      end
    end
    src
  end

  def have_devel?
    unless defined? $have_devel
      $have_devel = true
      $have_devel = try_link(MAIN_DOES_NOTHING)
    end
    $have_devel
  end

  def try_do(src, command, *opts, &b)
    unless have_devel?
      raise <<MSG
The compiler failed to generate an executable file.
You have to install development tools first.
MSG
    end
    begin
      src = create_tmpsrc(src, &b)
      xsystem(command, *opts)
    ensure
      log_src(src)
    end
  end

  def link_config(ldflags, opt="", libpath=$DEFLIBPATH|$LIBPATH)
    librubyarg = $extmk ? $LIBRUBYARG_STATIC : "$(LIBRUBYARG)"
    conf = RbConfig::CONFIG.merge('hdrdir' => $hdrdir.quote,
                                  'src' => "#{conftest_source}",
                                  'arch_hdrdir' => $arch_hdrdir.quote,
                                  'top_srcdir' => $top_srcdir.quote,
                                  'INCFLAGS' => "#$INCFLAGS",
                                  'CPPFLAGS' => "#$CPPFLAGS",
                                  'CFLAGS' => "#$CFLAGS",
                                  'ARCH_FLAG' => "#$ARCH_FLAG",
                                  'LDFLAGS' => "#$LDFLAGS #{ldflags}",
                                  'LOCAL_LIBS' => "#$LOCAL_LIBS #$libs",
                                  'LIBS' => "#{librubyarg} #{opt} #$LIBS")
    conf['LIBPATH'] = libpathflag(libpath.map {|s| RbConfig::expand(s.dup, conf)})
    conf
  end

  def link_command(ldflags, *opts)
    conf = link_config(ldflags, *opts)
    RbConfig::expand(TRY_LINK.dup, conf)
  end

  def cc_config(opt="")
    conf = RbConfig::CONFIG.merge('hdrdir' => $hdrdir.quote, 'srcdir' => $srcdir.quote,
                                  'arch_hdrdir' => $arch_hdrdir.quote,
                                  'top_srcdir' => $top_srcdir.quote)
    conf
  end

  def cc_command(opt="")
    conf = cc_config(opt)
    RbConfig::expand("$(CC) #$INCFLAGS #$CPPFLAGS #$CFLAGS #$ARCH_FLAG #{opt} -c #{CONFTEST_C}",
                     conf)
  end

  def cpp_command(outfile, opt="")
    conf = cc_config(opt)
    if $universal and (arch_flag = conf['ARCH_FLAG']) and !arch_flag.empty?
      conf['ARCH_FLAG'] = arch_flag.gsub(/(?:\G|\s)-arch\s+\S+/, '')
    end
    RbConfig::expand("$(CPP) #$INCFLAGS #$CPPFLAGS #$CFLAGS #{opt} #{CONFTEST_C} #{outfile}",
                     conf)
  end

  def libpathflag(libpath=$DEFLIBPATH|$LIBPATH)
    libpath.map{|x|
      case x
      when "$(topdir)", /\A\./
        LIBPATHFLAG
      else
        LIBPATHFLAG+RPATHFLAG
      end % x.quote
    }.join
  end

  def with_werror(opt, opts = nil)
    if opts
      if opts[:werror] and config_string("WERRORFLAG") {|flag| opt = opt ? "#{opt} #{flag}" : flag}
        (opts = opts.dup).delete(:werror)
      end
      yield(opt, opts)
    else
      yield(opt)
    end
  end

  def try_link0(src, opt="", *opts, &b) # :nodoc:
    exe = CONFTEST+$EXEEXT
    cmd = link_command("", opt)
    if $universal
      require 'tmpdir'
      Dir.mktmpdir("mkmf_", oldtmpdir = ENV["TMPDIR"]) do |tmpdir|
        begin
          ENV["TMPDIR"] = tmpdir
          try_do(src, cmd, *opts, &b)
        ensure
          ENV["TMPDIR"] = oldtmpdir
        end
      end
    else
      try_do(src, cmd, *opts, &b)
    end and File.executable?(exe) or return nil
    exe
  ensure
    MakeMakefile.rm_rf(*Dir["#{CONFTEST}*"]-[exe])
  end

  # Returns whether or not the +src+ can be compiled as a C source and linked
  # with its depending libraries successfully.  +opt+ is passed to the linker
  # as options. Note that +$CFLAGS+ and +$LDFLAGS+ are also passed to the
  # linker.
  #
  # If a block given, it is called with the source before compilation. You can
  # modify the source in the block.
  #
  # [+src+] a String which contains a C source
  # [+opt+] a String which contains linker options
  def try_link(src, opt="", *opts, &b)
    exe = try_link0(src, opt, *opts, &b) or return false
    MakeMakefile.rm_f exe
    true
  end

  # Returns whether or not the +src+ can be compiled as a C source.  +opt+ is
  # passed to the C compiler as options. Note that +$CFLAGS+ is also passed to
  # the compiler.
  #
  # If a block given, it is called with the source before compilation. You can
  # modify the source in the block.
  #
  # [+src+] a String which contains a C source
  # [+opt+] a String which contains compiler options
  def try_compile(src, opt="", *opts, &b)
    with_werror(opt, *opts) {|_opt, *| try_do(src, cc_command(_opt), *opts, &b)} and
      File.file?("#{CONFTEST}.#{$OBJEXT}")
  ensure
    MakeMakefile.rm_f "#{CONFTEST}*"
  end

  # Returns whether or not the +src+ can be preprocessed with the C
  # preprocessor.  +opt+ is passed to the preprocessor as options. Note that
  # +$CFLAGS+ is also passed to the preprocessor.
  #
  # If a block given, it is called with the source before preprocessing. You
  # can modify the source in the block.
  #
  # [+src+] a String which contains a C source
  # [+opt+] a String which contains preprocessor options
  def try_cpp(src, opt="", *opts, &b)
    try_do(src, cpp_command(CPPOUTFILE, opt), *opts, &b) and
      File.file?("#{CONFTEST}.i")
  ensure
    MakeMakefile.rm_f "#{CONFTEST}*"
  end

  alias_method :try_header, (config_string('try_header') || :try_cpp)

  def cpp_include(header)
    if header
      header = [header] unless header.kind_of? Array
      header.map {|h| String === h ? "#include <#{h}>\n" : h}.join
    else
      ""
    end
  end

  def with_cppflags(flags)
    cppflags = $CPPFLAGS
    $CPPFLAGS = flags.dup
    ret = yield
  ensure
    $CPPFLAGS = cppflags unless ret
  end

  def try_cppflags(flags, opts = {})
    try_header(MAIN_DOES_NOTHING, flags, {:werror => true}.update(opts))
  end

  def append_cppflags(flags, *opts)
    Array(flags).each do |flag|
      if checking_for("whether #{flag} is accepted as CPPFLAGS") {
           try_cppflags(flag, *opts)
         }
        $CPPFLAGS << " " << flag
      end
    end
  end

  def with_cflags(flags)
    cflags = $CFLAGS
    $CFLAGS = flags.dup
    ret = yield
  ensure
    $CFLAGS = cflags unless ret
  end

  def try_cflags(flags, opts = {})
    try_compile(MAIN_DOES_NOTHING, flags, {:werror => true}.update(opts))
  end

  def append_cflags(flags, *opts)
    Array(flags).each do |flag|
      if checking_for("whether #{flag} is accepted as CFLAGS") {
           try_cflags(flag, *opts)
         }
        $CFLAGS << " " << flag
      end
    end
  end

  def with_ldflags(flags)
    ldflags = $LDFLAGS
    $LDFLAGS = flags.dup
    ret = yield
  ensure
    $LDFLAGS = ldflags unless ret
  end

  def try_ldflags(flags, opts = {})
    opts = {:werror => true}.update(opts) if $mswin
    try_link(MAIN_DOES_NOTHING, flags, opts)
  end

  def append_ldflags(flags, *opts)
    Array(flags).each do |flag|
      if checking_for("whether #{flag} is accepted as LDFLAGS") {
           try_ldflags(flag, *opts)
         }
        $LDFLAGS << " " << flag
      end
    end
  end

  def try_static_assert(expr, headers = nil, opt = "", &b)
    headers = cpp_include(headers)
    try_compile(<<SRC, opt, &b)
#{headers}
/*top*/
int conftest_const[(#{expr}) ? 1 : -1];
SRC
  end

  def try_constant(const, headers = nil, opt = "", &b)
    includes = cpp_include(headers)
    neg = try_static_assert("#{const} < 0", headers, opt)
    if CROSS_COMPILING
      if neg
        const = "-(#{const})"
      elsif try_static_assert("#{const} > 0", headers, opt)
        # positive constant
      elsif try_static_assert("#{const} == 0", headers, opt)
        return 0
      else
        # not a constant
        return nil
      end
      upper = 1
      until try_static_assert("#{const} <= #{upper}", headers, opt)
        lower = upper
        upper <<= 1
      end
      return nil unless lower
      while upper > lower + 1
        mid = (upper + lower) / 2
        if try_static_assert("#{const} > #{mid}", headers, opt)
          lower = mid
        else
          upper = mid
        end
      end
      upper = -upper if neg
      return upper
    else
      src = %{#{includes}
#include <stdio.h>
/*top*/
typedef#{neg ? '' : ' unsigned'}
#ifdef PRI_LL_PREFIX
#define PRI_CONFTEST_PREFIX PRI_LL_PREFIX
LONG_LONG
#else
#define PRI_CONFTEST_PREFIX "l"
long
#endif
conftest_type;
conftest_type conftest_const = (conftest_type)(#{const});
int main() {printf("%"PRI_CONFTEST_PREFIX"#{neg ? 'd' : 'u'}\\n", conftest_const); return 0;}
}
      begin
        if try_link0(src, opt, &b)
          xpopen("./#{CONFTEST}") do |f|
            return Integer(f.gets)
          end
        end
      ensure
        MakeMakefile.rm_f "#{CONFTEST}#{$EXEEXT}"
      end
    end
    nil
  end

  # You should use +have_func+ rather than +try_func+.
  #
  # [+func+] a String which contains a symbol name
  # [+libs+] a String which contains library names.
  # [+headers+] a String or an Array of strings which contains names of header
  #             files.
  def try_func(func, libs, headers = nil, opt = "", &b)
    headers = cpp_include(headers)
    case func
    when /^&/
      decltype = proc {|x|"const volatile void *#{x}"}
    when /\)$/
      call = func
    when nil
      call = ""
    else
      call = "#{func}()"
      decltype = proc {|x| "void ((*#{x})())"}
    end
    if opt and !opt.empty?
      [[:to_str], [:join, " "], [:to_s]].each do |meth, *args|
        if opt.respond_to?(meth)
          break opt = opt.__send__(meth, *args)
        end
      end
      opt = "#{opt} #{libs}"
    else
      opt = libs
    end
    decltype && try_link(<<"SRC", opt, &b) or
#{headers}
/*top*/
extern int t(void);
#{MAIN_DOES_NOTHING 't'}
int t(void) { #{decltype["volatile p"]}; p = (#{decltype[]})#{func}; return !p; }
SRC
    call && try_link(<<"SRC", opt, &b)
#{headers}
/*top*/
extern int t(void);
#{MAIN_DOES_NOTHING 't'}
#{"extern void #{call};" if decltype}
int t(void) { #{call}; return 0; }
SRC
  end

  # You should use +have_var+ rather than +try_var+.
  def try_var(var, headers = nil, opt = "", &b)
    headers = cpp_include(headers)
    try_compile(<<"SRC", opt, &b)
#{headers}
/*top*/
extern int t(void);
#{MAIN_DOES_NOTHING 't'}
int t(void) { const volatile void *volatile p; p = &(&#{var})[0]; return !p; }
SRC
  end

  # Returns whether or not the +src+ can be preprocessed with the C
  # preprocessor and matches with +pat+.
  #
  # If a block given, it is called with the source before compilation. You can
  # modify the source in the block.
  #
  # [+pat+] a Regexp or a String
  # [+src+] a String which contains a C source
  # [+opt+] a String which contains preprocessor options
  #
  # NOTE: When pat is a Regexp the matching will be checked in process,
  # otherwise egrep(1) will be invoked to check it.
  def egrep_cpp(pat, src, opt = "", &b)
    src = create_tmpsrc(src, &b)
    xpopen(cpp_command('', opt)) do |f|
      if Regexp === pat
        puts("    ruby -ne 'print if #{pat.inspect}'")
        f.grep(pat) {|l|
          puts "#{f.lineno}: #{l}"
          return true
        }
        false
      else
        puts("    egrep '#{pat}'")
        begin
          stdin = $stdin.dup
          $stdin.reopen(f)
          system("egrep", pat)
        ensure
          $stdin.reopen(stdin)
        end
      end
    end
  ensure
    MakeMakefile.rm_f "#{CONFTEST}*"
    log_src(src)
  end

  # This is used internally by the have_macro? method.
  def macro_defined?(macro, src, opt = "", &b)
    src = src.sub(/[^\n]\z/, "\\&\n")
    try_compile(src + <<"SRC", opt, &b)
/*top*/
#ifndef #{macro}
# error
|:/ === #{macro} undefined === /:|
#endif
SRC
  end

  # Returns whether or not:
  # * the +src+ can be compiled as a C source,
  # * the result object can be linked with its depending libraries
  #   successfully,
  # * the linked file can be invoked as an executable
  # * and the executable exits successfully
  #
  # +opt+ is passed to the linker as options. Note that +$CFLAGS+ and
  # +$LDFLAGS+ are also passed to the linker.
  #
  # If a block given, it is called with the source before compilation. You can
  # modify the source in the block.
  #
  # [+src+] a String which contains a C source
  # [+opt+] a String which contains linker options
  #
  # Returns true when the executable exits successfully, false when it fails,
  # or nil when preprocessing, compilation or link fails.
  def try_run(src, opt = "", &b)
    raise "cannot run test program while cross compiling" if CROSS_COMPILING
    if try_link0(src, opt, &b)
      xsystem("./#{CONFTEST}")
    else
      nil
    end
  ensure
    MakeMakefile.rm_f "#{CONFTEST}*"
  end

  def install_files(mfile, ifiles, map = nil, srcprefix = nil)
    ifiles or return
    ifiles.empty? and return
    srcprefix ||= "$(srcdir)/#{srcprefix}".chomp('/')
    RbConfig::expand(srcdir = srcprefix.dup)
    dirs = []
    path = Hash.new {|h, i| h[i] = dirs.push([i])[-1]}
    ifiles.each do |files, dir, prefix|
      dir = map_dir(dir, map)
      prefix &&= %r|\A#{Regexp.quote(prefix)}/?|
      if /\A\.\// =~ files
        # install files which are in current working directory.
        files = files[2..-1]
        len = nil
      else
        # install files which are under the $(srcdir).
        files = File.join(srcdir, files)
        len = srcdir.size
      end
      f = nil
      Dir.glob(files) do |fx|
        f = fx
        f[0..len] = "" if len
        case File.basename(f)
        when *$NONINSTALLFILES
          next
        end
        d = File.dirname(f)
        d.sub!(prefix, "") if prefix
        d = (d.empty? || d == ".") ? dir : File.join(dir, d)
        f = File.join(srcprefix, f) if len
        path[d] << f
      end
      unless len or f
        d = File.dirname(files)
        d.sub!(prefix, "") if prefix
        d = (d.empty? || d == ".") ? dir : File.join(dir, d)
        path[d] << files
      end
    end
    dirs
  end

  def install_rb(mfile, dest, srcdir = nil)
    install_files(mfile, [["lib/**/*.rb", dest, "lib"]], nil, srcdir)
  end

  def append_library(libs, lib) # :no-doc:
    format(LIBARG, lib) + " " + libs
  end

  def message(*s)
    unless Logging.quiet and not $VERBOSE
      printf(*s)
      $stdout.flush
    end
  end

  # This emits a string to stdout that allows users to see the results of the
  # various have* and find* methods as they are tested.
  #
  # Internal use only.
  #
  def checking_for(m, fmt = nil)
    f = caller[0][/in `([^<].*)'$/, 1] and f << ": " #` for vim #'
    m = "checking #{/\Acheck/ =~ f ? '' : 'for '}#{m}... "
    message "%s", m
    a = r = nil
    Logging::postpone do
      r = yield
      a = (fmt ? "#{fmt % r}" : r ? "yes" : "no")
      "#{f}#{m}-------------------- #{a}\n\n"
    end
    message "%s\n", a
    Logging::message "--------------------\n\n"
    r
  end

  def checking_message(target, place = nil, opt = nil)
    [["in", place], ["with", opt]].inject("#{target}") do |msg, (pre, noun)|
      if noun
        [[:to_str], [:join, ","], [:to_s]].each do |meth, *args|
          if noun.respond_to?(meth)
            break noun = noun.__send__(meth, *args)
          end
        end
        unless noun.empty?
          msg << " #{pre} " unless msg.empty?
          msg << noun
        end
      end
      msg
    end
  end

  # :startdoc:

  # Returns whether or not +macro+ is defined either in the common header
  # files or within any +headers+ you provide.
  #
  # Any options you pass to +opt+ are passed along to the compiler.
  #
  def have_macro(macro, headers = nil, opt = "", &b)
    checking_for checking_message(macro, headers, opt) do
      macro_defined?(macro, cpp_include(headers), opt, &b)
    end
  end

  # Returns whether or not the given entry point +func+ can be found within
  # +lib+.  If +func+ is +nil+, the <code>main()</code> entry point is used by
  # default.  If found, it adds the library to list of libraries to be used
  # when linking your extension.
  #
  # If +headers+ are provided, it will include those header files as the
  # header files it looks in when searching for +func+.
  #
  # The real name of the library to be linked can be altered by
  # <code>--with-FOOlib</code> configuration option.
  #
  def have_library(lib, func = nil, headers = nil, opt = "", &b)
    dir_config(lib)
    lib = with_config(lib+'lib', lib)
    checking_for checking_message(func && func.funcall_style, LIBARG%lib, opt) do
      if COMMON_LIBS.include?(lib)
        true
      else
        libs = append_library($libs, lib)
        if try_func(func, libs, headers, opt, &b)
          $libs = libs
          true
        else
          false
        end
      end
    end
  end

  # Returns whether or not the entry point +func+ can be found within the
  # library +lib+ in one of the +paths+ specified, where +paths+ is an array
  # of strings.  If +func+ is +nil+ , then the <code>main()</code> function is
  # used as the entry point.
  #
  # If +lib+ is found, then the path it was found on is added to the list of
  # library paths searched and linked against.
  #
  def find_library(lib, func, *paths, &b)
    dir_config(lib)
    lib = with_config(lib+'lib', lib)
    paths = paths.collect {|path| path.split(File::PATH_SEPARATOR)}.flatten
    checking_for checking_message(func && func.funcall_style, LIBARG%lib) do
      libpath = $LIBPATH
      libs = append_library($libs, lib)
      begin
        until r = try_func(func, libs, &b) or paths.empty?
          $LIBPATH = libpath | [paths.shift]
        end
        if r
          $libs = libs
          libpath = nil
        end
      ensure
        $LIBPATH = libpath if libpath
      end
      r
    end
  end

  # Returns whether or not the function +func+ can be found in the common
  # header files, or within any +headers+ that you provide.  If found, a macro
  # is passed as a preprocessor constant to the compiler using the function
  # name, in uppercase, prepended with +HAVE_+.
  #
  # To check functions in an additional library, you need to check that
  # library first using <code>have_library()</code>.  The +func+ shall be
  # either mere function name or function name with arguments.
  #
  # For example, if <code>have_func('foo')</code> returned +true+, then the
  # +HAVE_FOO+ preprocessor macro would be passed to the compiler.
  #
  def have_func(func, headers = nil, opt = "", &b)
    checking_for checking_message(func.funcall_style, headers, opt) do
      if try_func(func, $libs, headers, opt, &b)
        $defs << "-DHAVE_#{func.sans_arguments.tr_cpp}"
        true
      else
        false
      end
    end
  end

  # Returns whether or not the variable +var+ can be found in the common
  # header files, or within any +headers+ that you provide.  If found, a macro
  # is passed as a preprocessor constant to the compiler using the variable
  # name, in uppercase, prepended with +HAVE_+.
  #
  # To check variables in an additional library, you need to check that
  # library first using <code>have_library()</code>.
  #
  # For example, if <code>have_var('foo')</code> returned true, then the
  # +HAVE_FOO+ preprocessor macro would be passed to the compiler.
  #
  def have_var(var, headers = nil, opt = "", &b)
    checking_for checking_message(var, headers, opt) do
      if try_var(var, headers, opt, &b)
        $defs.push(format("-DHAVE_%s", var.tr_cpp))
        true
      else
        false
      end
    end
  end

  # Returns whether or not the given +header+ file can be found on your system.
  # If found, a macro is passed as a preprocessor constant to the compiler
  # using the header file name, in uppercase, prepended with +HAVE_+.
  #
  # For example, if <code>have_header('foo.h')</code> returned true, then the
  # +HAVE_FOO_H+ preprocessor macro would be passed to the compiler.
  #
  def have_header(header, preheaders = nil, opt = "", &b)
    dir_config(header[/.*?(?=\/)|.*?(?=\.)/])
    checking_for header do
      if try_header(cpp_include(preheaders)+cpp_include(header), opt, &b)
        $defs.push(format("-DHAVE_%s", header.tr_cpp))
        true
      else
        false
      end
    end
  end

  # Returns whether or not the given +framework+ can be found on your system.
  # If found, a macro is passed as a preprocessor constant to the compiler
  # using the framework name, in uppercase, prepended with +HAVE_FRAMEWORK_+.
  #
  # For example, if <code>have_framework('Ruby')</code> returned true, then
  # the +HAVE_FRAMEWORK_RUBY+ preprocessor macro would be passed to the
  # compiler.
  #
  # If +fw+ is a pair of the framework name and its header file name
  # that header file is checked, instead of the normally used header
  # file which is named same as the framework.
  def have_framework(fw, &b)
    if Array === fw
      fw, header = *fw
    else
      header = "#{fw}.h"
    end
    checking_for fw do
      src = cpp_include("#{fw}/#{header}") << "\n" "int main(void){return 0;}"
      opt = " -framework #{fw}"
      if try_link(src, opt, &b) or (objc = try_link(src, "-ObjC#{opt}", &b))
        $defs.push(format("-DHAVE_FRAMEWORK_%s", fw.tr_cpp))
        # TODO: non-worse way than this hack, to get rid of separating
        # option and its argument.
        $LDFLAGS << " -ObjC" if objc and /(\A|\s)-ObjC(\s|\z)/ !~ $LDFLAGS
        $LIBS << opt
        true
      else
        false
      end
    end
  end

  # Instructs mkmf to search for the given +header+ in any of the +paths+
  # provided, and returns whether or not it was found in those paths.
  #
  # If the header is found then the path it was found on is added to the list
  # of included directories that are sent to the compiler (via the
  # <code>-I</code> switch).
  #
  def find_header(header, *paths)
    message = checking_message(header, paths)
    header = cpp_include(header)
    checking_for message do
      if try_header(header)
        true
      else
        found = false
        paths.each do |dir|
          opt = "-I#{dir}".quote
          if try_header(header, opt)
            $INCFLAGS << " " << opt
            found = true
            break
          end
        end
        found
      end
    end
  end

  # Returns whether or not the struct of type +type+ contains +member+.  If
  # it does not, or the struct type can't be found, then false is returned.
  # You may optionally specify additional +headers+ in which to look for the
  # struct (in addition to the common header files).
  #
  # If found, a macro is passed as a preprocessor constant to the compiler
  # using the type name and the member name, in uppercase, prepended with
  # +HAVE_+.
  #
  # For example, if <code>have_struct_member('struct foo', 'bar')</code>
  # returned true, then the +HAVE_STRUCT_FOO_BAR+ preprocessor macro would be
  # passed to the compiler.
  #
  # +HAVE_ST_BAR+ is also defined for backward compatibility.
  #
  def have_struct_member(type, member, headers = nil, opt = "", &b)
    checking_for checking_message("#{type}.#{member}", headers) do
      if try_compile(<<"SRC", opt, &b)
#{cpp_include(headers)}
/*top*/
int s = (char *)&((#{type}*)0)->#{member} - (char *)0;
#{MAIN_DOES_NOTHING}
SRC
        $defs.push(format("-DHAVE_%s_%s", type.tr_cpp, member.tr_cpp))
        $defs.push(format("-DHAVE_ST_%s", member.tr_cpp)) # backward compatibility
        true
      else
        false
      end
    end
  end

  # Returns whether or not the static type +type+ is defined.
  #
  # See also +have_type+
  #
  def try_type(type, headers = nil, opt = "", &b)
    if try_compile(<<"SRC", opt, &b)
#{cpp_include(headers)}
/*top*/
typedef #{type} conftest_type;
int conftestval[sizeof(conftest_type)?1:-1];
SRC
      $defs.push(format("-DHAVE_TYPE_%s", type.tr_cpp))
      true
    else
      false
    end
  end

  # Returns whether or not the static type +type+ is defined.  You may
  # optionally pass additional +headers+ to check against in addition to the
  # common header files.
  #
  # You may also pass additional flags to +opt+ which are then passed along to
  # the compiler.
  #
  # If found, a macro is passed as a preprocessor constant to the compiler
  # using the type name, in uppercase, prepended with +HAVE_TYPE_+.
  #
  # For example, if <code>have_type('foo')</code> returned true, then the
  # +HAVE_TYPE_FOO+ preprocessor macro would be passed to the compiler.
  #
  def have_type(type, headers = nil, opt = "", &b)
    checking_for checking_message(type, headers, opt) do
      try_type(type, headers, opt, &b)
    end
  end

  # Returns where the static type +type+ is defined.
  #
  # You may also pass additional flags to +opt+ which are then passed along to
  # the compiler.
  #
  # See also +have_type+.
  #
  def find_type(type, opt, *headers, &b)
    opt ||= ""
    fmt = "not found"
    def fmt.%(x)
      x ? x.respond_to?(:join) ? x.join(",") : x : self
    end
    checking_for checking_message(type, nil, opt), fmt do
      headers.find do |h|
        try_type(type, h, opt, &b)
      end
    end
  end

  # Returns whether or not the constant +const+ is defined.
  #
  # See also +have_const+
  #
  def try_const(const, headers = nil, opt = "", &b)
    const, type = *const
    if try_compile(<<"SRC", opt, &b)
#{cpp_include(headers)}
/*top*/
typedef #{type || 'int'} conftest_type;
conftest_type conftestval = #{type ? '' : '(int)'}#{const};
SRC
      $defs.push(format("-DHAVE_CONST_%s", const.tr_cpp))
      true
    else
      false
    end
  end

  # Returns whether or not the constant +const+ is defined.  You may
  # optionally pass the +type+ of +const+ as <code>[const, type]</code>,
  # such as:
  #
  #   have_const(%w[PTHREAD_MUTEX_INITIALIZER pthread_mutex_t], "pthread.h")
  #
  # You may also pass additional +headers+ to check against in addition to the
  # common header files, and additional flags to +opt+ which are then passed
  # along to the compiler.
  #
  # If found, a macro is passed as a preprocessor constant to the compiler
  # using the type name, in uppercase, prepended with +HAVE_CONST_+.
  #
  # For example, if <code>have_const('foo')</code> returned true, then the
  # +HAVE_CONST_FOO+ preprocessor macro would be passed to the compiler.
  #
  def have_const(const, headers = nil, opt = "", &b)
    checking_for checking_message([*const].compact.join(' '), headers, opt) do
      try_const(const, headers, opt, &b)
    end
  end

  # :stopdoc:
  STRING_OR_FAILED_FORMAT = "%s"
  def STRING_OR_FAILED_FORMAT.%(x) # :nodoc:
    x ? super : "failed"
  end

  def typedef_expr(type, headers)
    typename, member = type.split('.', 2)
    prelude = cpp_include(headers).split(/$/)
    prelude << "typedef #{typename} rbcv_typedef_;\n"
    return "rbcv_typedef_", member, prelude
  end

  def try_signedness(type, member, headers = nil, opts = nil)
    raise ArgumentError, "don't know how to tell signedness of members" if member
    if try_static_assert("(#{type})-1 < 0", headers, opts)
      return -1
    elsif try_static_assert("(#{type})-1 > 0", headers, opts)
      return +1
    end
  end

  # :startdoc:

  # Returns the size of the given +type+.  You may optionally specify
  # additional +headers+ to search in for the +type+.
  #
  # If found, a macro is passed as a preprocessor constant to the compiler
  # using the type name, in uppercase, prepended with +SIZEOF_+, followed by
  # the type name, followed by <code>=X</code> where "X" is the actual size.
  #
  # For example, if <code>check_sizeof('mystruct')</code> returned 12, then
  # the <code>SIZEOF_MYSTRUCT=12</code> preprocessor macro would be passed to
  # the compiler.
  #
  def check_sizeof(type, headers = nil, opts = "", &b)
    typedef, member, prelude = typedef_expr(type, headers)
    prelude << "#{typedef} *rbcv_ptr_;\n"
    prelude = [prelude]
    expr = "sizeof((*rbcv_ptr_)#{"." << member if member})"
    fmt = STRING_OR_FAILED_FORMAT
    checking_for checking_message("size of #{type}", headers), fmt do
      if size = try_constant(expr, prelude, opts, &b)
        $defs.push(format("-DSIZEOF_%s=%s", type.tr_cpp, size))
        size
      end
    end
  end

  # Returns the signedness of the given +type+.  You may optionally specify
  # additional +headers+ to search in for the +type+.
  #
  # If the +type+ is found and is a numeric type, a macro is passed as a
  # preprocessor constant to the compiler using the +type+ name, in uppercase,
  # prepended with +SIGNEDNESS_OF_+, followed by the +type+ name, followed by
  # <code>=X</code> where "X" is positive integer if the +type+ is unsigned
  # and a negative integer if the +type+ is signed.
  #
  # For example, if +size_t+ is defined as unsigned, then
  # <code>check_signedness('size_t')</code> would return +1 and the
  # <code>SIGNEDNESS_OF_SIZE_T=+1</code> preprocessor macro would be passed to
  # the compiler.  The <code>SIGNEDNESS_OF_INT=-1</code> macro would be set
  # for <code>check_signedness('int')</code>
  #
  def check_signedness(type, headers = nil, opts = nil, &b)
    typedef, member, prelude = typedef_expr(type, headers)
    signed = nil
    checking_for("signedness of #{type}", STRING_OR_FAILED_FORMAT) do
      signed = try_signedness(typedef, member, [prelude], opts, &b) or next nil
      $defs.push("-DSIGNEDNESS_OF_%s=%+d" % [type.tr_cpp, signed])
      signed < 0 ? "signed" : "unsigned"
    end
    signed
  end

  # Returns the convertible integer type of the given +type+.  You may
  # optionally specify additional +headers+ to search in for the +type+.
  # _convertible_ means actually the same type, or typedef'd from the same
  # type.
  #
  # If the +type+ is an integer type and the _convertible_ type is found,
  # the following macros are passed as preprocessor constants to the compiler
  # using the +type+ name, in uppercase.
  #
  # * +TYPEOF_+, followed by the +type+ name, followed by <code>=X</code>
  #   where "X" is the found _convertible_ type name.
  # * +TYP2NUM+ and +NUM2TYP+,
  #   where +TYP+ is the +type+ name in uppercase with replacing an +_t+
  #   suffix with "T", followed by <code>=X</code> where "X" is the macro name
  #   to convert +type+ to an Integer object, and vice versa.
  #
  # For example, if +foobar_t+ is defined as unsigned long, then
  # <code>convertible_int("foobar_t")</code> would return "unsigned long", and
  # define these macros:
  #
  #   #define TYPEOF_FOOBAR_T unsigned long
  #   #define FOOBART2NUM ULONG2NUM
  #   #define NUM2FOOBART NUM2ULONG
  #
  def convertible_int(type, headers = nil, opts = nil, &b)
    type, macname = *type
    checking_for("convertible type of #{type}", STRING_OR_FAILED_FORMAT) do
      if UNIVERSAL_INTS.include?(type)
        type
      else
        typedef, member, prelude = typedef_expr(type, headers, &b)
        if member
          prelude << "static rbcv_typedef_ rbcv_var;"
          compat = UNIVERSAL_INTS.find {|t|
            try_static_assert("sizeof(rbcv_var.#{member}) == sizeof(#{t})", [prelude], opts, &b)
          }
        else
          next unless signed = try_signedness(typedef, member, [prelude])
          u = "unsigned " if signed > 0
          prelude << "extern rbcv_typedef_ foo();"
          compat = UNIVERSAL_INTS.find {|t|
            try_compile([prelude, "extern #{u}#{t} foo();"].join("\n"), opts, :werror=>true, &b)
          }
        end
        if compat
          macname ||= type.sub(/_(?=t\z)/, '').tr_cpp
          conv = (compat == "long long" ? "LL" : compat.upcase)
          compat = "#{u}#{compat}"
          typename = type.tr_cpp
          $defs.push(format("-DSIZEOF_%s=SIZEOF_%s", typename, compat.tr_cpp))
          $defs.push(format("-DTYPEOF_%s=%s", typename, compat.quote))
          $defs.push(format("-DPRI_%s_PREFIX=PRI_%s_PREFIX", macname, conv))
          conv = (u ? "U" : "") + conv
          $defs.push(format("-D%s2NUM=%s2NUM", macname, conv))
          $defs.push(format("-DNUM2%s=NUM2%s", macname, conv))
          compat
        end
      end
    end
  end
  # :stopdoc:

  # Used internally by the what_type? method to determine if +type+ is a scalar
  # pointer.
  def scalar_ptr_type?(type, member = nil, headers = nil, &b)
    try_compile(<<"SRC", &b)   # pointer
#{cpp_include(headers)}
/*top*/
volatile #{type} conftestval;
extern int t(void);
#{MAIN_DOES_NOTHING 't'}
int t(void) {return (int)(1-*(conftestval#{member ? ".#{member}" : ""}));}
SRC
  end

  # Used internally by the what_type? method to determine if +type+ is a scalar
  # pointer.
  def scalar_type?(type, member = nil, headers = nil, &b)
    try_compile(<<"SRC", &b)   # pointer
#{cpp_include(headers)}
/*top*/
volatile #{type} conftestval;
extern int t(void);
#{MAIN_DOES_NOTHING 't'}
int t(void) {return (int)(1-(conftestval#{member ? ".#{member}" : ""}));}
SRC
  end

  # Used internally by the what_type? method to check if the _typeof_ GCC
  # extension is available.
  def have_typeof?
    return $typeof if defined?($typeof)
    $typeof = %w[__typeof__ typeof].find do |t|
      try_compile(<<SRC)
int rbcv_foo;
#{t}(rbcv_foo) rbcv_bar;
SRC
    end
  end

  def what_type?(type, member = nil, headers = nil, &b)
    m = "#{type}"
    var = val = "*rbcv_var_"
    func = "rbcv_func_(void)"
    if member
      m << "." << member
    else
      type, member = type.split('.', 2)
    end
    if member
      val = "(#{var}).#{member}"
    end
    prelude = [cpp_include(headers).split(/^/)]
    prelude << ["typedef #{type} rbcv_typedef_;\n",
                "extern rbcv_typedef_ *#{func};\n",
                "rbcv_typedef_ #{var};\n",
               ]
    type = "rbcv_typedef_"
    fmt = member && !(typeof = have_typeof?) ? "seems %s" : "%s"
    if typeof
      var = "*rbcv_member_"
      func = "rbcv_mem_func_(void)"
      member = nil
      type = "rbcv_mem_typedef_"
      prelude[-1] << "typedef #{typeof}(#{val}) #{type};\n"
      prelude[-1] << "extern #{type} *#{func};\n"
      prelude[-1] << "#{type} #{var};\n"
      val = var
    end
    def fmt.%(x)
      x ? super : "unknown"
    end
    checking_for checking_message(m, headers), fmt do
      if scalar_ptr_type?(type, member, prelude, &b)
        if try_static_assert("sizeof(*#{var}) == 1", prelude)
          return "string"
        end
        ptr = "*"
      elsif scalar_type?(type, member, prelude, &b)
        unless member and !typeof or try_static_assert("(#{type})-1 < 0", prelude)
          unsigned = "unsigned"
        end
        ptr = ""
      else
        next
      end
      type = UNIVERSAL_INTS.find do |t|
        pre = prelude
        unless member
          pre += [["#{unsigned} #{t} #{ptr}#{var};\n",
                   "extern #{unsigned} #{t} #{ptr}*#{func};\n"]]
        end
        try_static_assert("sizeof(#{ptr}#{val}) == sizeof(#{unsigned} #{t})", pre)
      end
      type or next
      [unsigned, type, ptr].join(" ").strip
    end
  end

  # This method is used internally by the find_executable method.
  #
  # Internal use only.
  #
  def find_executable0(bin, path = nil)
    executable_file = proc do |name|
      begin
        stat = File.stat(name)
      rescue SystemCallError
      else
        next name if stat.file? and stat.executable?
      end
    end

    exts = config_string('EXECUTABLE_EXTS') {|s| s.split} || config_string('EXEEXT') {|s| [s]}
    if File.expand_path(bin) == bin
      return bin if executable_file.call(bin)
      if exts
        exts.each {|ext| executable_file.call(file = bin + ext) and return file}
      end
      return nil
    end
    if path ||= ENV['PATH']
      path = path.split(File::PATH_SEPARATOR)
    else
      path = %w[/usr/local/bin /usr/ucb /usr/bin /bin]
    end
    file = nil
    path.each do |dir|
      dir.sub!(/\A"(.*)"\z/m, '\1') if $mswin or $mingw
      return file if executable_file.call(file = File.join(dir, bin))
      if exts
        exts.each {|ext| executable_file.call(ext = file + ext) and return ext}
      end
    end
    nil
  end

  # :startdoc:

  # Searches for the executable +bin+ on +path+.  The default path is your
  # +PATH+ environment variable. If that isn't defined, it will resort to
  # searching /usr/local/bin, /usr/ucb, /usr/bin and /bin.
  #
  # If found, it will return the full path, including the executable name, of
  # where it was found.
  #
  # Note that this method does not actually affect the generated Makefile.
  #
  def find_executable(bin, path = nil)
    checking_for checking_message(bin, path) do
      find_executable0(bin, path)
    end
  end

  # :stopdoc:

  def arg_config(config, default=nil, &block)
    $arg_config << [config, default]
    defaults = []
    if default
      defaults << default
    elsif !block
      defaults << nil
    end
    $configure_args.fetch(config.tr('_', '-'), *defaults, &block)
  end

  # :startdoc:

  # Tests for the presence of a <tt>--with-</tt>_config_ or
  # <tt>--without-</tt>_config_ option.  Returns +true+ if the with option is
  # given, +false+ if the without option is given, and the default value
  # otherwise.
  #
  # This can be useful for adding custom definitions, such as debug
  # information.
  #
  # Example:
  #
  #    if with_config("debug")
  #       $defs.push("-DOSSL_DEBUG") unless $defs.include? "-DOSSL_DEBUG"
  #    end
  #
  def with_config(config, default=nil)
    config = config.sub(/^--with[-_]/, '')
    val = arg_config("--with-"+config) do
      if arg_config("--without-"+config)
        false
      elsif block_given?
        yield(config, default)
      else
        break default
      end
    end
    case val
    when "yes"
      true
    when "no"
      false
    else
      val
    end
  end

  # Tests for the presence of an <tt>--enable-</tt>_config_ or
  # <tt>--disable-</tt>_config_ option. Returns +true+ if the enable option is
  # given, +false+ if the disable option is given, and the default value
  # otherwise.
  #
  # This can be useful for adding custom definitions, such as debug
  # information.
  #
  # Example:
  #
  #    if enable_config("debug")
  #       $defs.push("-DOSSL_DEBUG") unless $defs.include? "-DOSSL_DEBUG"
  #    end
  #
  def enable_config(config, default=nil)
    if arg_config("--enable-"+config)
      true
    elsif arg_config("--disable-"+config)
      false
    elsif block_given?
      yield(config, default)
    else
      return default
    end
  end

  # Generates a header file consisting of the various macro definitions
  # generated by other methods such as have_func and have_header. These are
  # then wrapped in a custom <code>#ifndef</code> based on the +header+ file
  # name, which defaults to "extconf.h".
  #
  # For example:
  #
  #   # extconf.rb
  #   require 'mkmf'
  #   have_func('realpath')
  #   have_header('sys/utime.h')
  #   create_header
  #   create_makefile('foo')
  #
  # The above script would generate the following extconf.h file:
  #
  #   #ifndef EXTCONF_H
  #   #define EXTCONF_H
  #   #define HAVE_REALPATH 1
  #   #define HAVE_SYS_UTIME_H 1
  #   #endif
  #
  # Given that the create_header method generates a file based on definitions
  # set earlier in your extconf.rb file, you will probably want to make this
  # one of the last methods you call in your script.
  #
  def create_header(header = "extconf.h")
    message "creating %s\n", header
    sym = header.tr_cpp
    hdr = ["#ifndef #{sym}\n#define #{sym}\n"]
    for line in $defs
      case line
      when /^-D([^=]+)(?:=(.*))?/
        hdr << "#define #$1 #{$2 ? Shellwords.shellwords($2)[0].gsub(/(?=\t+)/, "\\\n") : 1}\n"
      when /^-U(.*)/
        hdr << "#undef #$1\n"
      end
    end
    hdr << "#endif\n"
    hdr = hdr.join("")
    log_src(hdr, "#{header} is")
    unless (IO.read(header) == hdr rescue false)
      open(header, "wb") do |hfile|
        hfile.write(hdr)
      end
    end
    $extconf_h = header
  end

  # call-seq:
  #   dir_config(target)
  #   dir_config(target, prefix)
  #   dir_config(target, idefault, ldefault)
  #
  # Sets a +target+ name that the user can then use to configure
  # various "with" options with on the command line by using that
  # name.  For example, if the target is set to "foo", then the user
  # could use the <code>--with-foo-dir=prefix</code>,
  # <code>--with-foo-include=dir</code> and
  # <code>--with-foo-lib=dir</code> command line options to tell where
  # to search for header/library files.
  #
  # You may pass along additional parameters to specify default
  # values.  If one is given it is taken as default +prefix+, and if
  # two are given they are taken as "include" and "lib" defaults in
  # that order.
  #
  # In any case, the return value will be an array of determined
  # "include" and "lib" directories, either of which can be nil if no
  # corresponding command line option is given when no default value
  # is specified.
  #
  # Note that dir_config only adds to the list of places to search for
  # libraries and include files.  It does not link the libraries into your
  # application.
  #
  def dir_config(target, idefault=nil, ldefault=nil)
    if conf = $config_dirs[target]
      return conf
    end

    if dir = with_config(target + "-dir", (idefault unless ldefault))
      defaults = Array === dir ? dir : dir.split(File::PATH_SEPARATOR)
      idefault = ldefault = nil
    end

    idir = with_config(target + "-include", idefault)
    $arg_config.last[1] ||= "${#{target}-dir}/include"
    ldir = with_config(target + "-lib", ldefault)
    $arg_config.last[1] ||= "${#{target}-dir}/#{_libdir_basename}"

    idirs = idir ? Array === idir ? idir.dup : idir.split(File::PATH_SEPARATOR) : []
    if defaults
      idirs.concat(defaults.collect {|d| d + "/include"})
      idir = ([idir] + idirs).compact.join(File::PATH_SEPARATOR)
    end
    unless idirs.empty?
      idirs.collect! {|d| "-I" + d}
      idirs -= Shellwords.shellwords($CPPFLAGS)
      unless idirs.empty?
        $CPPFLAGS = (idirs.quote << $CPPFLAGS).join(" ")
      end
    end

    ldirs = ldir ? Array === ldir ? ldir.dup : ldir.split(File::PATH_SEPARATOR) : []
    if defaults
      ldirs.concat(defaults.collect {|d| "#{d}/#{_libdir_basename}"})
      ldir = ([ldir] + ldirs).compact.join(File::PATH_SEPARATOR)
    end
    $LIBPATH = ldirs | $LIBPATH

    $config_dirs[target] = [idir, ldir]
  end

  # Returns compile/link information about an installed library in a
  # tuple of <code>[cflags, ldflags, libs]</code>, by using the
  # command found first in the following commands:
  #
  # 1. If <code>--with-{pkg}-config={command}</code> is given via
  #    command line option: <code>{command} {option}</code>
  #
  # 2. <code>{pkg}-config {option}</code>
  #
  # 3. <code>pkg-config {option} {pkg}</code>
  #
  # Where {option} is, for instance, <code>--cflags</code>.
  #
  # The values obtained are appended to +$INCFLAGS+, +$CFLAGS+, +$LDFLAGS+ and
  # +$libs+.
  #
  # If an <code>option</code> argument is given, the config command is
  # invoked with the option and a stripped output string is returned
  # without modifying any of the global values mentioned above.
  def pkg_config(pkg, option=nil)
    if pkgconfig = with_config("#{pkg}-config") and find_executable0(pkgconfig)
      # iff package specific config command is given
    elsif ($PKGCONFIG ||=
           (pkgconfig = with_config("pkg-config", ("pkg-config" unless CROSS_COMPILING))) &&
           find_executable0(pkgconfig) && pkgconfig) and
        xsystem("#{$PKGCONFIG} --exists #{pkg}")
      # default to pkg-config command
      pkgconfig = $PKGCONFIG
      get = proc {|opt|
        opt = xpopen("#{$PKGCONFIG} --#{opt} #{pkg}", err:[:child, :out], &:read)
        Logging.open {puts opt.each_line.map{|s|"=> #{s.inspect}"}}
        opt.strip if $?.success?
      }
    elsif find_executable0(pkgconfig = "#{pkg}-config")
      # default to package specific config command, as a last resort.
    else
      pkgconfig = nil
    end
    if pkgconfig
      get ||= proc {|opt|
        opt = xpopen("#{pkgconfig} --#{opt}", err:[:child, :out], &:read)
        Logging.open {puts opt.each_line.map{|s|"=> #{s.inspect}"}}
        opt.strip if $?.success?
      }
    end
    orig_ldflags = $LDFLAGS
    if get and option
      get[option]
    elsif get and try_ldflags(ldflags = get['libs'])
      if incflags = get['cflags-only-I']
        $INCFLAGS << " " << incflags
        cflags = get['cflags-only-other']
      else
        cflags = get['cflags']
      end
      libs = get['libs-only-l']
      if cflags
        $CFLAGS += " " << cflags
        $CXXFLAGS += " " << cflags
      end
      if libs
        ldflags = (Shellwords.shellwords(ldflags) - Shellwords.shellwords(libs)).quote.join(" ")
      else
        libs, ldflags = Shellwords.shellwords(ldflags).partition {|s| s =~ /-l([^ ]+)/ }.map {|l|l.quote.join(" ")}
      end
      $libs += " " << libs

      $LDFLAGS = [orig_ldflags, ldflags].join(' ')
      Logging::message "package configuration for %s\n", pkg
      Logging::message "incflags: %s\ncflags: %s\nldflags: %s\nlibs: %s\n\n",
                       incflags, cflags, ldflags, libs
      [[incflags, cflags].join(' '), ldflags, libs]
    else
      Logging::message "package configuration for %s is not found\n", pkg
      nil
    end
  end

  # :stopdoc:

  def with_destdir(dir)
    dir = dir.sub($dest_prefix_pattern, '')
    /\A\$[\(\{]/ =~ dir ? dir : "$(DESTDIR)"+dir
  end

  # Converts forward slashes to backslashes. Aimed at MS Windows.
  #
  # Internal use only.
  #
  def winsep(s)
    s.tr('/', '\\')
  end

  # Converts native path to format acceptable in Makefile
  #
  # Internal use only.
  #
  if !CROSS_COMPILING
    case CONFIG['build_os']
    when 'mingw32'
      def mkintpath(path)
        # mingw uses make from msys and it needs special care
        # converts from C:\some\path to /C/some/path
        path = path.dup
        path.tr!('\\', '/')
        path.sub!(/\A([A-Za-z]):(?=\/)/, '/\1')
        path
      end
    when 'cygwin'
      if CONFIG['target_os'] != 'cygwin'
        def mkintpath(path)
          IO.popen(["cygpath", "-u", path], &:read).chomp
        end
      end
    end
  end
  unless method_defined?(:mkintpath)
    def mkintpath(path)
      path
    end
  end

  def configuration(srcdir)
    mk = []
    vpath = $VPATH.dup
    CONFIG["hdrdir"] ||= $hdrdir
    mk << %{
SHELL = /bin/sh

# V=0 quiet, V=1 verbose.  other values don't work.
V = 1
Q1 = $(V:1=)
Q = $(Q1:0=@)
ECHO1 = $(V:1=@ #{CONFIG['NULLCMD']})
ECHO = $(ECHO1:0=@ echo)
NULLCMD = #{CONFIG['NULLCMD']}

#### Start of system configuration section. ####
#{"top_srcdir = " + $top_srcdir.sub(%r"\A#{Regexp.quote($topdir)}/", "$(topdir)/") if $extmk}
srcdir = #{srcdir.gsub(/\$\((srcdir)\)|\$\{(srcdir)\}/) {mkintpath(CONFIG[$1||$2]).unspace}}
topdir = #{mkintpath(topdir = $extmk ? CONFIG["topdir"] : $topdir).unspace}
hdrdir = #{(hdrdir = CONFIG["hdrdir"]) == topdir ? "$(topdir)" : mkintpath(hdrdir).unspace}
arch_hdrdir = #{mkintpath($arch_hdrdir).unspace}
PATH_SEPARATOR = #{CONFIG['PATH_SEPARATOR']}
VPATH = #{vpath.join(CONFIG['PATH_SEPARATOR'])}
}
    if $extmk
      mk << "RUBYLIB =\n""RUBYOPT = -\n"
    end
    prefix = mkintpath(CONFIG["prefix"])
    if destdir = prefix[$dest_prefix_pattern, 1]
      mk << "\nDESTDIR = #{destdir}\n"
      prefix = prefix[destdir.size..-1]
    end
    mk << "prefix = #{with_destdir(prefix).unspace}\n"
    CONFIG.each do |key, var|
      mk << "#{key} = #{with_destdir(mkintpath(var)).unspace}\n" if /.prefix$/ =~ key
    end
    CONFIG.each do |key, var|
      next if /^abs_/ =~ key
      next if /^(?:src|top(?:_src)?|build|hdr)dir$/ =~ key
      next unless /dir$/ =~ key
      mk << "#{key} = #{with_destdir(var)}\n"
    end
    if !$extmk and !$configure_args.has_key?('--ruby') and
        sep = config_string('BUILD_FILE_SEPARATOR')
      sep = ":/=#{sep}"
    else
      sep = ""
    end
    possible_command = (proc {|s| s if /top_srcdir|tooldir/ !~ s} unless $extmk)
    extconf_h = $extconf_h ? "-DRUBY_EXTCONF_H=\\\"$(RUBY_EXTCONF_H)\\\" " : $defs.join(" ") << " "
    headers = %w[
      $(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
    ]
    headers += $headers
    if RULE_SUBST
      headers.each {|h| h.sub!(/.*/, &RULE_SUBST.method(:%))}
    end
    headers << $config_h
    headers << '$(RUBY_EXTCONF_H)' if $extconf_h
    mk << %{

CC_WRAPPER = #{CONFIG['CC_WRAPPER']}
CC = #{CONFIG['CC']}
CXX = #{CONFIG['CXX']}
LIBRUBY = #{CONFIG['LIBRUBY']}
LIBRUBY_A = #{CONFIG['LIBRUBY_A']}
LIBRUBYARG_SHARED = #$LIBRUBYARG_SHARED
LIBRUBYARG_STATIC = #$LIBRUBYARG_STATIC
empty =
OUTFLAG = #{OUTFLAG}$(empty)
COUTFLAG = #{COUTFLAG}$(empty)
CSRCFLAG = #{CSRCFLAG}$(empty)

RUBY_EXTCONF_H = #{$extconf_h}
cflags   = #{CONFIG['cflags']}
cxxflags = #{CONFIG['cxxflags']}
optflags = #{CONFIG['optflags']}
debugflags = #{CONFIG['debugflags']}
warnflags = #{$warnflags}
cppflags = #{CONFIG['cppflags']}
CCDLFLAGS = #{$static ? '' : CONFIG['CCDLFLAGS']}
CFLAGS   = $(CCDLFLAGS) #$CFLAGS $(ARCH_FLAG)
INCFLAGS = -I. #$INCFLAGS
DEFS     = #{CONFIG['DEFS']}
CPPFLAGS = #{extconf_h}#{$CPPFLAGS}
CXXFLAGS = $(CCDLFLAGS) #$CXXFLAGS $(ARCH_FLAG)
ldflags  = #{$LDFLAGS}
dldflags = #{$DLDFLAGS} #{CONFIG['EXTDLDFLAGS']}
ARCH_FLAG = #{$ARCH_FLAG}
DLDFLAGS = $(ldflags) $(dldflags) $(ARCH_FLAG)
LDSHARED = #{CONFIG['LDSHARED']}
LDSHAREDXX = #{config_string('LDSHAREDXX') || '$(LDSHARED)'}
AR = #{CONFIG['AR']}
EXEEXT = #{CONFIG['EXEEXT']}

}
    CONFIG.each do |key, val|
      mk << "#{key} = #{val}\n" if /^RUBY.*NAME/ =~ key
    end
    mk << %{
arch = #{CONFIG['arch']}
sitearch = #{CONFIG['sitearch']}
ruby_version = #{RbConfig::CONFIG['ruby_version']}
ruby = #{$ruby.sub(%r[\A#{Regexp.quote(RbConfig::CONFIG['bindir'])}(?=/|\z)]) {'$(bindir)'}}
RUBY = $(ruby#{sep})
BUILTRUBY = #{if defined?($builtruby) && $builtruby
    $builtruby
  else
    File.join('$(bindir)', CONFIG["RUBY_INSTALL_NAME"] + CONFIG['EXEEXT'])
  end}
ruby_headers = #{headers.join(' ')}

RM = #{config_string('RM', &possible_command) || '$(RUBY) -run -e rm -- -f'}
RM_RF = #{'$(RUBY) -run -e rm -- -rf'}
RMDIRS = #{config_string('RMDIRS', &possible_command) || '$(RUBY) -run -e rmdir -- -p'}
MAKEDIRS = #{config_string('MAKEDIRS', &possible_command) || '@$(RUBY) -run -e mkdir -- -p'}
INSTALL = #{config_string('INSTALL', &possible_command) || '@$(RUBY) -run -e install -- -vp'}
INSTALL_PROG = #{config_string('INSTALL_PROG') || '$(INSTALL) -m 0755'}
INSTALL_DATA = #{config_string('INSTALL_DATA') || '$(INSTALL) -m 0644'}
COPY = #{config_string('CP', &possible_command) || '@$(RUBY) -run -e cp -- -v'}
TOUCH = exit >

#### End of system configuration section. ####

preload = #{defined?($preload) && $preload ? $preload.join(' ') : ''}
}
    mk
  end

  def timestamp_file(name, target_prefix = nil)
    pat = {}
    name = '$(RUBYARCHDIR)' if name == '$(TARGET_SO_DIR)'
    install_dirs.each do |n, d|
      pat[n] = $` if /\$\(target_prefix\)\z/ =~ d
    end
    name = name.gsub(/\$\((#{pat.keys.join("|")})\)/) {pat[$1]+target_prefix}
    name.sub!(/(\$\((?:site)?arch\))\/*/, '')
    arch = $1 || ''
    name.chomp!('/')
    name = name.gsub(/(\$[({]|[})])|(\/+)|[^-.\w]+/) {$1 ? "" : $2 ? ".-." : "_"}
    File.join("$(TIMESTAMP_DIR)", arch, "#{name.sub(/\A(?=.)/, '.')}.time")
  end
  # :startdoc:

  # creates a stub Makefile.
  #
  def dummy_makefile(srcdir)
    configuration(srcdir) << <<RULES << CLEANINGS
CLEANFILES = #{$cleanfiles.join(' ')}
DISTCLEANFILES = #{$distcleanfiles.join(' ')}

all install static install-so install-rb: Makefile
	@$(NULLCMD)
.PHONY: all install static install-so install-rb
.PHONY: clean clean-so clean-static clean-rb

RULES
  end

  def each_compile_rules # :nodoc:
    vpath_splat = /\$\(\*VPATH\*\)/
    COMPILE_RULES.each do |rule|
      if vpath_splat =~ rule
        $VPATH.each do |path|
          yield rule.sub(vpath_splat) {path}
        end
      else
        yield rule
      end
    end
  end

  # Processes the data contents of the "depend" file.  Each line of this file
  # is expected to be a file name.
  #
  # Returns the output of findings, in Makefile format.
  #
  def depend_rules(depend)
    suffixes = []
    depout = []
    cont = implicit = nil
    impconv = proc do
      each_compile_rules {|rule| depout << (rule % implicit[0]) << implicit[1]}
      implicit = nil
    end
    ruleconv = proc do |line|
      if implicit
        if /\A\t/ =~ line
          implicit[1] << line
          next
        else
          impconv[]
        end
      end
      if m = /\A\.(\w+)\.(\w+)(?:\s*:)/.match(line)
        suffixes << m[1] << m[2]
        implicit = [[m[1], m[2]], [m.post_match]]
        next
      elsif RULE_SUBST and /\A(?!\s*\w+\s*=)[$\w][^#]*:/ =~ line
        line.sub!(/\s*\#.*$/, '')
        comment = $&
        line.gsub!(%r"(\s)(?!\.)([^$(){}+=:\s\\,]+)(?=\s|\z)") {$1 + RULE_SUBST % $2}
        line = line.chomp + comment + "\n" if comment
      end
      depout << line
    end
    depend.each_line do |line|
      line.gsub!(/\.o\b/, ".#{$OBJEXT}")
      line.gsub!(/\{\$\(VPATH\)\}/, "") unless $nmake
      line.gsub!(/\$\((?:hdr|top)dir\)\/config.h/, $config_h)
      if $nmake && /\A\s*\$\(RM|COPY\)/ =~ line
        line.gsub!(%r"[-\w\./]{2,}"){$&.tr("/", "\\")}
        line.gsub!(/(\$\((?!RM|COPY)[^:)]+)(?=\))/, '\1:/=\\')
      end
      if /(?:^|[^\\])(?:\\\\)*\\$/ =~ line
        (cont ||= []) << line
        next
      elsif cont
        line = (cont << line).join
        cont = nil
      end
      ruleconv.call(line)
    end
    if cont
      ruleconv.call(cont.join)
    elsif implicit
      impconv.call
    end
    unless suffixes.empty?
      depout.unshift(".SUFFIXES: ." + suffixes.uniq.join(" .") + "\n\n")
    end
    if $extconf_h
      depout.unshift("$(OBJS): $(RUBY_EXTCONF_H)\n\n")
      depout.unshift("$(OBJS): $(hdrdir)/ruby/win32.h\n\n") if $mswin or $mingw
    end
    depout.flatten!
    depout
  end

  # Generates the Makefile for your extension, passing along any options and
  # preprocessor constants that you may have generated through other methods.
  #
  # The +target+ name should correspond the name of the global function name
  # defined within your C extension, minus the +Init_+.  For example, if your
  # C extension is defined as +Init_foo+, then your target would simply be
  # "foo".
  #
  # If any "/" characters are present in the target name, only the last name
  # is interpreted as the target name, and the rest are considered toplevel
  # directory names, and the generated Makefile will be altered accordingly to
  # follow that directory structure.
  #
  # For example, if you pass "test/foo" as a target name, your extension will
  # be installed under the "test" directory.  This means that in order to
  # load the file within a Ruby program later, that directory structure will
  # have to be followed, e.g. <code>require 'test/foo'</code>.
  #
  # The +srcprefix+ should be used when your source files are not in the same
  # directory as your build script. This will not only eliminate the need for
  # you to manually copy the source files into the same directory as your
  # build script, but it also sets the proper +target_prefix+ in the generated
  # Makefile.
  #
  # Setting the +target_prefix+ will, in turn, install the generated binary in
  # a directory under your <code>RbConfig::CONFIG['sitearchdir']</code> that
  # mimics your local filesystem when you run <code>make install</code>.
  #
  # For example, given the following file tree:
  #
  #   ext/
  #     extconf.rb
  #     test/
  #       foo.c
  #
  # And given the following code:
  #
  #   create_makefile('test/foo', 'test')
  #
  # That will set the +target_prefix+ in the generated Makefile to "test".
  # That, in turn, will create the following file tree when installed via the
  # <code>make install</code> command:
  #
  #   /path/to/ruby/sitearchdir/test/foo.so
  #
  # It is recommended that you use this approach to generate your makefiles,
  # instead of copying files around manually, because some third party
  # libraries may depend on the +target_prefix+ being set properly.
  #
  # The +srcprefix+ argument can be used to override the default source
  # directory, i.e. the current directory.  It is included as part of the
  # +VPATH+ and added to the list of +INCFLAGS+.
  #
  def create_makefile(target, srcprefix = nil)
    $target = target
    libpath = $DEFLIBPATH|$LIBPATH
    message "creating Makefile\n"
    MakeMakefile.rm_f "#{CONFTEST}*"
    if CONFIG["DLEXT"] == $OBJEXT
      for lib in libs = $libs.split(' ')
        lib.sub!(/-l(.*)/, %%"lib\\1.#{$LIBEXT}"%)
      end
      $defs.push(format("-DEXTLIB='%s'", libs.join(",")))
    end

    if target.include?('/')
      target_prefix, target = File.split(target)
      target_prefix[0,0] = '/'
    else
      target_prefix = ""
    end

    srcprefix ||= "$(srcdir)/#{srcprefix}".chomp('/')
    RbConfig.expand(srcdir = srcprefix.dup)

    ext = ".#{$OBJEXT}"
    orig_srcs = Dir[File.join(srcdir, "*.{#{SRC_EXT.join(%q{,})}}")].sort
    if not $objs
      srcs = $srcs || orig_srcs
      $objs = []
      objs = srcs.inject(Hash.new {[]}) {|h, f|
        h.key?(o = File.basename(f, ".*") << ext) or $objs << o
        h[o] <<= f
        h
      }
      unless objs.delete_if {|b, f| f.size == 1}.empty?
        dups = objs.sort.map {|b, f|
          "#{b[/.*\./]}{#{f.collect {|n| n[/([^.]+)\z/]}.join(',')}}"
        }
        abort "source files duplication - #{dups.join(", ")}"
      end
    else
      $objs.collect! {|o| File.basename(o, ".*") << ext} unless $OBJEXT == "o"
      srcs = $srcs || $objs.collect {|o| o.chomp(ext) << ".c"}
    end
    $srcs = srcs

    hdrs = Dir[File.join(srcdir, "*.{#{HDR_EXT.join(%q{,})}}")]

    target = nil if $objs.empty?

    if target and EXPORT_PREFIX
      if File.exist?(File.join(srcdir, target + '.def'))
        deffile = "$(srcdir)/$(TARGET).def"
        unless EXPORT_PREFIX.empty?
          makedef = %{$(RUBY) -pe "$$_.sub!(/^(?=\\w)/,'#{EXPORT_PREFIX}') unless 1../^EXPORTS$/i" #{deffile}}
        end
      else
        makedef = %{(echo EXPORTS && echo $(TARGET_ENTRY))}
      end
      if makedef
        $cleanfiles << '$(DEFFILE)'
        origdef = deffile
        deffile = "$(TARGET)-$(arch).def"
      end
    end
    origdef ||= ''

    if $extout and $INSTALLFILES
      $cleanfiles.concat($INSTALLFILES.collect {|files, dir|File.join(dir, files.delete_prefix('./'))})
      $distcleandirs.concat($INSTALLFILES.collect {|files, dir| dir})
    end

    if $extmk and $static
      $defs << "-DRUBY_EXPORT=1"
    end

    if $extmk and not $extconf_h
      create_header
    end

    libpath = libpathflag(libpath)

    dllib = target ? "$(TARGET).#{CONFIG['DLEXT']}" : ""
    staticlib = target ? "$(TARGET).#$LIBEXT" : ""
    conf = configuration(srcprefix)
    conf << "\
libpath = #{($DEFLIBPATH|$LIBPATH).join(" ")}
LIBPATH = #{libpath}
DEFFILE = #{deffile}

CLEANFILES = #{$cleanfiles.join(' ')}
DISTCLEANFILES = #{$distcleanfiles.join(' ')}
DISTCLEANDIRS = #{$distcleandirs.join(' ')}

extout = #{$extout && $extout.quote}
extout_prefix = #{$extout_prefix}
target_prefix = #{target_prefix}
LOCAL_LIBS = #{$LOCAL_LIBS}
LIBS = #{$LIBRUBYARG} #{$libs} #{$LIBS}
ORIG_SRCS = #{orig_srcs.collect(&File.method(:basename)).join(' ')}
SRCS = $(ORIG_SRCS) #{(srcs - orig_srcs).collect(&File.method(:basename)).join(' ')}
OBJS = #{$objs.join(" ")}
HDRS = #{hdrs.map{|h| '$(srcdir)/' + File.basename(h)}.join(' ')}
LOCAL_HDRS = #{$headers.join(' ')}
TARGET = #{target}
TARGET_NAME = #{target && target[/\A\w+/]}
TARGET_ENTRY = #{EXPORT_PREFIX || ''}Init_$(TARGET_NAME)
DLLIB = #{dllib}
EXTSTATIC = #{$static || ""}
STATIC_LIB = #{staticlib unless $static.nil?}
#{!$extout && defined?($installed_list) ? "INSTALLED_LIST = #{$installed_list}\n" : ""}
TIMESTAMP_DIR = #{$extout && $extmk ? '$(extout)/.timestamp' : '.'}
" #"
    # TODO: fixme
    install_dirs.each {|d| conf << ("%-14s= %s\n" % d) if /^[[:upper:]]/ =~ d[0]}
    sodir = $extout ? '$(TARGET_SO_DIR)' : '$(RUBYARCHDIR)'
    n = '$(TARGET_SO_DIR)$(TARGET)'
    conf << "\
TARGET_SO_DIR =#{$extout ? " $(RUBYARCHDIR)/" : ''}
TARGET_SO     = $(TARGET_SO_DIR)$(DLLIB)
CLEANLIBS     = #{'$(TARGET_SO) ' if target}#{config_string('cleanlibs') {|t| t.gsub(/\$\*/) {n}}}
CLEANOBJS     = *.#{$OBJEXT} #{config_string('cleanobjs') {|t| t.gsub(/\$\*/, "$(TARGET)#{deffile ? '-$(arch)': ''}")} if target} *.bak
" #"

    conf = yield(conf) if block_given?
    mfile = open("Makefile", "wb")
    mfile.puts(conf)
    mfile.print "
all:    #{$extout ? "install" : target ? "$(DLLIB)" : "Makefile"}
static: #{$extmk && !$static ? "all" : "$(STATIC_LIB)#{$extout ? " install-rb" : ""}"}
.PHONY: all install static install-so install-rb
.PHONY: clean clean-so clean-static clean-rb
" #"
    mfile.print CLEANINGS
    fsep = config_string('BUILD_FILE_SEPARATOR') {|s| s unless s == "/"}
    if fsep
      sep = ":/=#{fsep}"
      fseprepl = proc {|s|
        s = s.gsub("/", fsep)
        s = s.gsub(/(\$\(\w+)(\))/) {$1+sep+$2}
        s.gsub(/(\$\{\w+)(\})/) {$1+sep+$2}
      }
      rsep = ":#{fsep}=/"
    else
      fseprepl = proc {|s| s}
      sep = ""
      rsep = ""
    end
    dirs = []
    mfile.print "install: install-so install-rb\n\n"
    dir = sodir.dup
    mfile.print("install-so: ")
    if target
      f = "$(DLLIB)"
      dest = "$(TARGET_SO)"
      stamp = timestamp_file(dir, target_prefix)
      if $extout
        mfile.puts dest
        mfile.print "clean-so::\n"
        mfile.print "\t-$(Q)$(RM) #{fseprepl[dest]} #{fseprepl[stamp]}\n"
        mfile.print "\t-$(Q)$(RMDIRS) #{fseprepl[dir]}#{$ignore_error}\n"
      else
        mfile.print "#{f} #{stamp}\n"
        mfile.print "\t$(INSTALL_PROG) #{fseprepl[f]} #{dir}\n"
        if defined?($installed_list)
          mfile.print "\t@echo #{dir}/#{File.basename(f)}>>$(INSTALLED_LIST)\n"
        end
      end
      mfile.print "clean-static::\n"
      mfile.print "\t-$(Q)$(RM) $(STATIC_LIB)\n"
    else
      mfile.puts "Makefile"
    end
    mfile.print("install-rb: pre-install-rb do-install-rb install-rb-default\n")
    mfile.print("install-rb-default: pre-install-rb-default do-install-rb-default\n")
    mfile.print("pre-install-rb: Makefile\n")
    mfile.print("pre-install-rb-default: Makefile\n")
    mfile.print("do-install-rb:\n")
    mfile.print("do-install-rb-default:\n")
    for sfx, i in [["-default", [["lib/**/*.rb", "$(RUBYLIBDIR)", "lib"]]], ["", $INSTALLFILES]]
      files = install_files(mfile, i, nil, srcprefix) or next
      for dir, *files in files
        unless dirs.include?(dir)
          dirs << dir
          mfile.print "pre-install-rb#{sfx}: #{timestamp_file(dir, target_prefix)}\n"
        end
        for f in files
          dest = "#{dir}/#{File.basename(f)}"
          mfile.print("do-install-rb#{sfx}: #{dest}\n")
          mfile.print("#{dest}: #{f} #{timestamp_file(dir, target_prefix)}\n")
          mfile.print("\t$(Q) $(#{$extout ? 'COPY' : 'INSTALL_DATA'}) #{f} $(@D)\n")
          if defined?($installed_list) and !$extout
            mfile.print("\t@echo #{dest}>>$(INSTALLED_LIST)\n")
          end
          if $extout
            mfile.print("clean-rb#{sfx}::\n")
            mfile.print("\t-$(Q)$(RM) #{fseprepl[dest]}\n")
          end
        end
      end
      mfile.print "pre-install-rb#{sfx}:\n"
      if files.empty?
        mfile.print("\t@$(NULLCMD)\n")
      else
        q = "$(MAKE) -q do-install-rb#{sfx}"
        if $nmake
          mfile.print "!if \"$(Q)\" == \"@\"\n\t@#{q} || \\\n!endif\n\t"
        else
          mfile.print "\t$(Q1:0=@#{q} || )"
        end
        mfile.print "$(ECHO1:0=echo) installing#{sfx.sub(/^-/, " ")} #{target} libraries\n"
      end
      if $extout
        dirs.uniq!
        unless dirs.empty?
          mfile.print("clean-rb#{sfx}::\n")
          for dir in dirs.sort_by {|d| -d.count('/')}
            stamp = timestamp_file(dir, target_prefix)
            mfile.print("\t-$(Q)$(RM) #{fseprepl[stamp]}\n")
            mfile.print("\t-$(Q)$(RMDIRS) #{fseprepl[dir]}#{$ignore_error}\n")
          end
        end
      end
    end
    dirs.unshift(sodir) if target and !dirs.include?(sodir)
    dirs.each do |d|
      t = timestamp_file(d, target_prefix)
      mfile.print "#{t}:\n\t$(Q) $(MAKEDIRS) $(@D) #{d}\n\t$(Q) $(TOUCH) $@\n"
    end

    mfile.print <<-SITEINSTALL

site-install: site-install-so site-install-rb
site-install-so: install-so
site-install-rb: install-rb

    SITEINSTALL

    return unless target

    mfile.print ".SUFFIXES: .#{(SRC_EXT + [$OBJEXT, $ASMEXT]).compact.join(' .')}\n"
    mfile.print "\n"

    compile_command = "\n\t$(ECHO) compiling $(<#{rsep})\n\t$(Q) %s\n\n"
    command = compile_command % COMPILE_CXX
    asm_command = compile_command.sub(/compiling/, 'translating') % ASSEMBLE_CXX
    CXX_EXT.each do |e|
      each_compile_rules do |rule|
        mfile.printf(rule, e, $OBJEXT)
        mfile.print(command)
        mfile.printf(rule, e, $ASMEXT)
        mfile.print(asm_command)
      end
    end
    command = compile_command % COMPILE_C
    asm_command = compile_command.sub(/compiling/, 'translating') % ASSEMBLE_C
    C_EXT.each do |e|
      each_compile_rules do |rule|
        mfile.printf(rule, e, $OBJEXT)
        mfile.print(command)
        mfile.printf(rule, e, $ASMEXT)
        mfile.print(asm_command)
      end
    end

    mfile.print "$(TARGET_SO): "
    mfile.print "$(DEFFILE) " if makedef
    mfile.print "$(OBJS) Makefile"
    mfile.print " #{timestamp_file(sodir, target_prefix)}" if $extout
    mfile.print "\n"
    mfile.print "\t$(ECHO) linking shared-object #{target_prefix.sub(/\A\/(.*)/, '\1/')}$(DLLIB)\n"
    mfile.print "\t-$(Q)$(RM) $(@#{sep})\n"
    link_so = LINK_SO.gsub(/^/, "\t$(Q) ")
    if srcs.any?(&%r"\.(?:#{CXX_EXT.join('|')})\z".method(:===))
      link_so = link_so.sub(/\bLDSHARED\b/, '\&XX')
    end
    mfile.print link_so, "\n\n"
    unless $static.nil?
      mfile.print "$(STATIC_LIB): $(OBJS)\n\t-$(Q)$(RM) $(@#{sep})\n\t"
      mfile.print "$(ECHO) linking static-library $(@#{rsep})\n\t$(Q) "
      mfile.print "$(AR) #{config_string('ARFLAGS') || 'cru '}$@ $(OBJS)"
      config_string('RANLIB') do |ranlib|
        mfile.print "\n\t-$(Q)#{ranlib} $(@) 2> /dev/null || true"
      end
    end
    mfile.print "\n\n"
    if makedef
      mfile.print "$(DEFFILE): #{origdef}\n"
      mfile.print "\t$(ECHO) generating $(@#{rsep})\n"
      mfile.print "\t$(Q) #{makedef} > $@\n\n"
    end

    depend = File.join(srcdir, "depend")
    if File.exist?(depend)
      mfile.print("###\n", *depend_rules(File.read(depend)))
    else
      mfile.print "$(OBJS): $(HDRS) $(ruby_headers)\n"
    end

    $makefile_created = true
  ensure
    mfile.close if mfile
  end

  # :stopdoc:

  def init_mkmf(config = CONFIG, rbconfig = RbConfig::CONFIG)
    $makefile_created = false
    $arg_config = []
    $enable_shared = config['ENABLE_SHARED'] == 'yes'
    $defs = []
    $extconf_h = nil
    $config_dirs = {}

    if $warnflags = CONFIG['warnflags'] and CONFIG['GCC'] == 'yes'
      # turn warnings into errors only for bundled extensions.
      config['warnflags'] = $warnflags.gsub(/(\A|\s)-Werror[-=]/, '\1-W')
      if /icc\z/ =~ config['CC']
        config['warnflags'].gsub!(/(\A|\s)-W(?:division-by-zero|deprecated-declarations)/, '\1')
      end
      RbConfig.expand(rbconfig['warnflags'] = config['warnflags'].dup)
      config.each do |key, val|
        RbConfig.expand(rbconfig[key] = val.dup) if /warnflags/ =~ val
      end
      $warnflags = config['warnflags'] unless $extmk
    end
    if (w = rbconfig['CC_WRAPPER']) and !w.empty? and !File.executable?(w)
      rbconfig['CC_WRAPPER'] = config['CC_WRAPPER'] = ''
    end
    $CFLAGS = with_config("cflags", arg_config("CFLAGS", config["CFLAGS"])).dup
    $CXXFLAGS = (with_config("cxxflags", arg_config("CXXFLAGS", config["CXXFLAGS"]))||'').dup
    $ARCH_FLAG = with_config("arch_flag", arg_config("ARCH_FLAG", config["ARCH_FLAG"])).dup
    $CPPFLAGS = with_config("cppflags", arg_config("CPPFLAGS", config["CPPFLAGS"])).dup
    $LDFLAGS = with_config("ldflags", arg_config("LDFLAGS", config["LDFLAGS"])).dup
    $INCFLAGS = "-I$(arch_hdrdir)"
    $INCFLAGS << " -I$(hdrdir)/ruby/backward" unless $extmk
    $INCFLAGS << " -I$(hdrdir) -I$(srcdir)"
    $DLDFLAGS = with_config("dldflags", arg_config("DLDFLAGS", config["DLDFLAGS"])).dup
    config_string("ADDITIONAL_DLDFLAGS") {|flags| $DLDFLAGS << " " << flags} unless $extmk
    $LIBEXT = config['LIBEXT'].dup
    $OBJEXT = config["OBJEXT"].dup
    $EXEEXT = config["EXEEXT"].dup
    $ASMEXT = config_string('ASMEXT', &:dup) || 'S'
    $LIBS = "#{config['LIBS']} #{config['DLDLIBS']}"
    $LIBRUBYARG = ""
    $LIBRUBYARG_STATIC = config['LIBRUBYARG_STATIC']
    $LIBRUBYARG_SHARED = config['LIBRUBYARG_SHARED']
    $DEFLIBPATH = [$extmk ? "$(topdir)" : "$(#{config["libdirname"] || "libdir"})"]
    $DEFLIBPATH.unshift(".")
    $LIBPATH = []
    $INSTALLFILES = []
    $NONINSTALLFILES = [/~\z/, /\A#.*#\z/, /\A\.#/, /\.bak\z/i, /\.orig\z/, /\.rej\z/, /\.l[ao]\z/, /\.o\z/]
    $VPATH = %w[$(srcdir) $(arch_hdrdir)/ruby $(hdrdir)/ruby]

    $objs = nil
    $srcs = nil
    $headers = []
    $libs = ""
    if $enable_shared or RbConfig.expand(config["LIBRUBY"].dup) != RbConfig.expand(config["LIBRUBY_A"].dup)
      $LIBRUBYARG = config['LIBRUBYARG']
    end

    $LOCAL_LIBS = ""

    $cleanfiles = config_string('CLEANFILES') {|s| Shellwords.shellwords(s)} || []
    $cleanfiles << "mkmf.log"
    $distcleanfiles = config_string('DISTCLEANFILES') {|s| Shellwords.shellwords(s)} || []
    $distcleandirs = config_string('DISTCLEANDIRS') {|s| Shellwords.shellwords(s)} || []

    $extout ||= nil
    $extout_prefix ||= nil

    $arg_config.clear
    $config_dirs.clear
    dir_config("opt")
  end

  FailedMessage = <<MESSAGE
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
MESSAGE

  # Returns whether or not the Makefile was successfully generated. If not,
  # the script will abort with an error message.
  #
  # Internal use only.
  #
  def mkmf_failed(path)
    unless $makefile_created or File.exist?("Makefile")
      opts = $arg_config.collect {|t, n| "\t#{t}#{n ? "=#{n}" : ""}\n"}
      abort "*** #{path} failed ***\n" + FailedMessage + opts.join
    end
  end

  private

  def _libdir_basename
    @libdir_basename ||= config_string("libdir") {|name| name[/\A\$\(exec_prefix\)\/(.*)/, 1]} || "lib"
  end

  def MAIN_DOES_NOTHING(*refs)
    src = MAIN_DOES_NOTHING
    unless refs.empty?
      src = src.sub(/\{/) do
        $& +
          "\n  if (argc > 1000000) {\n" +
          refs.map {|n|"    int (* volatile #{n}p)(void)=(int (*)(void))&#{n};\n"}.join("") +
          refs.map {|n|"    printf(\"%d\", (*#{n}p)());\n"}.join("") +
          "  }\n"
      end
    end
    src
  end

  extend self
  init_mkmf

  $make = with_config("make-prog", ENV["MAKE"] || "make")
  make, = Shellwords.shellwords($make)
  $nmake = nil
  case
  when $mswin
    $nmake = ?m if /nmake/i =~ make
  end
  $ignore_error = $nmake ? '' : ' 2> /dev/null || true'

  RbConfig::CONFIG["srcdir"] = CONFIG["srcdir"] =
    $srcdir = arg_config("--srcdir", File.dirname($0))
  $configure_args["--topsrcdir"] ||= $srcdir
  if $curdir = arg_config("--curdir")
    RbConfig.expand(curdir = $curdir.dup)
  else
    curdir = $curdir = "."
  end
  unless File.expand_path(RbConfig::CONFIG["topdir"]) == File.expand_path(curdir)
    CONFIG["topdir"] = $curdir
    RbConfig::CONFIG["topdir"] = curdir
  end
  $configure_args["--topdir"] ||= $curdir
  $ruby = arg_config("--ruby", File.join(RbConfig::CONFIG["bindir"], CONFIG["ruby_install_name"]))

  RbConfig.expand(CONFIG["RUBY_SO_NAME"])

  # :startdoc:

  split = Shellwords.method(:shellwords).to_proc

  EXPORT_PREFIX = config_string('EXPORT_PREFIX') {|s| s.strip}

  hdr = ['#include "ruby.h"' "\n"]
  config_string('COMMON_MACROS') do |s|
    Shellwords.shellwords(s).each do |w|
      w, v = w.split(/=/, 2)
      hdr << "#ifndef #{w}"
      hdr << "#define #{[w, v].compact.join(" ")}"
      hdr << "#endif /* #{w} */"
    end
  end
  config_string('COMMON_HEADERS') do |s|
    Shellwords.shellwords(s).each {|w| hdr << "#include <#{w}>"}
  end

  ##
  # Common headers for Ruby C extensions

  COMMON_HEADERS = hdr.join("\n")

  ##
  # Common libraries for Ruby C extensions

  COMMON_LIBS = config_string('COMMON_LIBS', &split) || []

  ##
  # make compile rules

  COMPILE_RULES = config_string('COMPILE_RULES', &split) || %w[.%s.%s:]
  RULE_SUBST = config_string('RULE_SUBST')

  ##
  # Command which will compile C files in the generated Makefile

  COMPILE_C = config_string('COMPILE_C') || '$(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$<'

  ##
  # Command which will compile C++ files in the generated Makefile

  COMPILE_CXX = config_string('COMPILE_CXX') || '$(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$<'

  ##
  # Command which will translate C files to assembler sources in the generated Makefile

  ASSEMBLE_C = config_string('ASSEMBLE_C') || COMPILE_C.sub(/(?<=\s)-c(?=\s)/, '-S')

  ##
  # Command which will translate C++ files to assembler sources in the generated Makefile

  ASSEMBLE_CXX = config_string('ASSEMBLE_CXX') || COMPILE_CXX.sub(/(?<=\s)-c(?=\s)/, '-S')

  ##
  # Command which will compile a program in order to test linking a library

  TRY_LINK = config_string('TRY_LINK') ||
    "$(CC) #{OUTFLAG}#{CONFTEST}#{$EXEEXT} $(INCFLAGS) $(CPPFLAGS) " \
    "$(CFLAGS) $(src) $(LIBPATH) $(LDFLAGS) $(ARCH_FLAG) $(LOCAL_LIBS) $(LIBS)"

  ##
  # Command which will link a shared library

  LINK_SO = (config_string('LINK_SO') || "").sub(/^$/) do
    if CONFIG["DLEXT"] == $OBJEXT
      "ld $(DLDFLAGS) -r -o $@ $(OBJS)\n"
    else
      "$(LDSHARED) #{OUTFLAG}$@ $(OBJS) " \
      "$(LIBPATH) $(DLDFLAGS) $(LOCAL_LIBS) $(LIBS)"
    end
  end

  ##
  # Argument which will add a library path to the linker

  LIBPATHFLAG = config_string('LIBPATHFLAG') || ' -L%s'
  RPATHFLAG = config_string('RPATHFLAG') || ''

  ##
  # Argument which will add a library to the linker

  LIBARG = config_string('LIBARG') || '-l%s'

  ##
  # A C main function which does no work

  MAIN_DOES_NOTHING = config_string('MAIN_DOES_NOTHING') || "int main(int argc, char **argv)\n{\n  return !!argv[argc];\n}"
  UNIVERSAL_INTS = config_string('UNIVERSAL_INTS') {|s| Shellwords.shellwords(s)} ||
    %w[int short long long\ long]

  sep = config_string('BUILD_FILE_SEPARATOR') {|s| ":/=#{s}" if s != "/"} || ""

  ##
  # Makefile rules that will clean the extension build directory

  CLEANINGS = "
clean-static::
clean-rb-default::
clean-rb::
clean-so::
clean: clean-so clean-static clean-rb-default clean-rb
\t\t-$(Q)$(RM) $(CLEANLIBS#{sep}) $(CLEANOBJS#{sep}) $(CLEANFILES#{sep}) .*.time

distclean-rb-default::
distclean-rb::
distclean-so::
distclean-static::
distclean: clean distclean-so distclean-static distclean-rb-default distclean-rb
\t\t-$(Q)$(RM) Makefile $(RUBY_EXTCONF_H) #{CONFTEST}.* mkmf.log
\t\t-$(Q)$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES#{sep})
\t\t-$(Q)$(RMDIRS) $(DISTCLEANDIRS#{sep})#{$ignore_error}

realclean: distclean
"

  @lang = Hash.new(self)

  def self.[](name)
    @lang.fetch(name)
  end

  def self.[]=(name, mod)
    @lang[name] = mod
  end

  self["C++"] = Module.new do
    include MakeMakefile
    extend self

    CONFTEST_CXX = "#{CONFTEST}.#{config_string('CXX_EXT') || CXX_EXT[0]}"

    TRY_LINK_CXX = config_string('TRY_LINK_CXX') ||
                   ((cmd = TRY_LINK.gsub(/\$\(C(?:C|(FLAGS))\)/, '$(CXX\1)')) != TRY_LINK && cmd) ||
                   "$(CXX) #{OUTFLAG}#{CONFTEST}#{$EXEEXT} $(INCFLAGS) $(CPPFLAGS) " \
                   "$(CXXFLAGS) $(src) $(LIBPATH) $(LDFLAGS) $(ARCH_FLAG) $(LOCAL_LIBS) $(LIBS)"

    def have_devel?
      unless defined? @have_devel
        @have_devel = true
        @have_devel = try_link(MAIN_DOES_NOTHING)
      end
      @have_devel
    end

    def conftest_source
      CONFTEST_CXX
    end

    def cc_command(opt="")
      conf = cc_config(opt)
      RbConfig::expand("$(CXX) #$INCFLAGS #$CPPFLAGS #$CXXFLAGS #$ARCH_FLAG #{opt} -c #{CONFTEST_CXX}",
                       conf)
    end

    def link_command(ldflags, *opts)
      conf = link_config(ldflags, *opts)
      RbConfig::expand(TRY_LINK_CXX.dup, conf)
    end
  end
end

# MakeMakefile::Global = #
m = Module.new {
  include(MakeMakefile)
  private(*MakeMakefile.public_instance_methods(false))
}
include m

if not $extmk and /\A(extconf|makefile).rb\z/ =~ File.basename($0)
  END {mkmf_failed($0)}
end
#--
#
#
#
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
# see the file "COPYING".
#
#++

module Racc

  class SourceText
    def initialize(text, filename, lineno)
      @text = text
      @filename = filename
      @lineno = lineno
    end

    attr_reader :text
    attr_reader :filename
    attr_reader :lineno

    def to_s
      "#<SourceText #{location()}>"
    end

    def location
      "#{@filename}:#{@lineno}"
    end
  end

end
#--
#
#
#
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
# see the file "COPYING".
#
#++

require 'racc/compat'
require 'racc/iset'
require 'racc/sourcetext'
require 'racc/logfilegenerator'
require 'racc/exception'
require 'forwardable'

module Racc

  class Grammar

    def initialize(debug_flags = DebugFlags.new)
      @symboltable = SymbolTable.new
      @debug_symbol = debug_flags.token
      @rules   = []  # :: [Rule]
      @start   = nil
      @n_expected_srconflicts = nil
      @prec_table = []
      @prec_table_closed = false
      @closed = false
      @states = nil
    end

    attr_reader :start
    attr_reader :symboltable
    attr_accessor :n_expected_srconflicts

    def [](x)
      @rules[x]
    end

    def each_rule(&block)
      @rules.each(&block)
    end

    alias each each_rule

    def each_index(&block)
      @rules.each_index(&block)
    end

    def each_with_index(&block)
      @rules.each_with_index(&block)
    end

    def size
      @rules.size
    end

    def to_s
      "<Racc::Grammar>"
    end

    extend Forwardable

    def_delegator "@symboltable", :each, :each_symbol
    def_delegator "@symboltable", :each_terminal
    def_delegator "@symboltable", :each_nonterminal

    def intern(value, dummy = false)
      @symboltable.intern(value, dummy)
    end

    def symbols
      @symboltable.symbols
    end

    def nonterminal_base
      @symboltable.nt_base
    end

    def useless_nonterminal_exist?
      n_useless_nonterminals() != 0
    end

    def n_useless_nonterminals
      @n_useless_nonterminals ||= each_useless_nonterminal.count
    end

    def each_useless_nonterminal
      return to_enum __method__ unless block_given?

      @symboltable.each_nonterminal do |sym|
        yield sym if sym.useless?
      end
    end

    def useless_rule_exist?
      n_useless_rules() != 0
    end

    def n_useless_rules
      @n_useless_rules ||= each_useless_rule.count
    end

    def each_useless_rule
      return to_enum __method__ unless block_given?

      each do |r|
        yield r if r.useless?
      end
    end

    def nfa
      (@states ||= States.new(self)).nfa
    end

    def dfa
      (@states ||= States.new(self)).dfa
    end

    alias states dfa

    def state_transition_table
      states().state_transition_table
    end

    def parser_class
      states = states()   # cache
      if $DEBUG
        srcfilename = caller(1).first.slice(/\A(.*?):/, 1)
        begin
          write_log srcfilename + ".output"
        rescue SystemCallError
        end
        report = lambda {|s| $stderr.puts "racc: #{srcfilename}: #{s}" }
        if states.should_report_srconflict?
          report["#{states.n_srconflicts} shift/reduce conflicts"]
        end
        if states.rrconflict_exist?
          report["#{states.n_rrconflicts} reduce/reduce conflicts"]
        end
        g = states.grammar
        if g.useless_nonterminal_exist?
          report["#{g.n_useless_nonterminals} useless nonterminals"]
        end
        if g.useless_rule_exist?
          report["#{g.n_useless_rules} useless rules"]
        end
      end
      states.state_transition_table.parser_class
    end

    def write_log(path)
      File.open(path, 'w') {|f|
        LogFileGenerator.new(states()).output f
      }
    end

    #
    # Grammar Definition Interface
    #

    def add(rule)
      raise ArgumentError, "rule added after the Grammar closed" if @closed
      @rules.push rule
    end

    def added?(sym)
      @rules.detect {|r| r.target == sym }
    end

    def start_symbol=(s)
      raise CompileError, "start symbol set twice'" if @start
      @start = s
    end

    def declare_precedence(assoc, syms)
      raise CompileError, "precedence table defined twice" if @prec_table_closed
      @prec_table.push [assoc, syms]
    end

    def end_precedence_declaration(reverse)
      @prec_table_closed = true
      return if @prec_table.empty?
      table = reverse ? @prec_table.reverse : @prec_table
      table.each_with_index do |(assoc, syms), idx|
        syms.each do |sym|
          sym.assoc = assoc
          sym.precedence = idx
        end
      end
    end

    #
    # Dynamic Generation Interface
    #

    def Grammar.define(&block)
      env = DefinitionEnv.new
      env.instance_eval(&block)
      env.grammar
    end

    class DefinitionEnv
      def initialize
        @grammar = Grammar.new
        @seqs = Hash.new(0)
        @delayed = []
      end

      def grammar
        flush_delayed
        @grammar.each do |rule|
          if rule.specified_prec
            rule.specified_prec = @grammar.intern(rule.specified_prec)
          end
        end
        @grammar.init
        @grammar
      end

      def precedence_table(&block)
        env = PrecedenceDefinitionEnv.new(@grammar)
        env.instance_eval(&block)
        @grammar.end_precedence_declaration env.reverse
      end

      def method_missing(mid, *args, &block)
        unless mid.to_s[-1,1] == '='
          super   # raises NoMethodError
        end
        target = @grammar.intern(mid.to_s.chop.intern)
        unless args.size == 1
          raise ArgumentError, "too many arguments for #{mid} (#{args.size} for 1)"
        end
        _add target, args.first
      end

      def _add(target, x)
        case x
        when Sym
          @delayed.each do |rule|
            rule.replace x, target if rule.target == x
          end
          @grammar.symboltable.delete x
        else
          x.each_rule do |r|
            r.target = target
            @grammar.add r
          end
        end
        flush_delayed
      end

      def _delayed_add(rule)
        @delayed.push rule
      end

      def _added?(sym)
        @grammar.added?(sym) or @delayed.detect {|r| r.target == sym }
      end

      def flush_delayed
        return if @delayed.empty?
        @delayed.each do |rule|
          @grammar.add rule
        end
        @delayed.clear
      end

      def seq(*list, &block)
        Rule.new(nil, list.map {|x| _intern(x) }, UserAction.proc(block))
      end

      def null(&block)
        seq(&block)
      end

      def action(&block)
        id = "@#{@seqs["action"] += 1}".intern
        _delayed_add Rule.new(@grammar.intern(id), [], UserAction.proc(block))
        id
      end

      alias _ action

      def option(sym, default = nil, &block)
        _defmetasyntax("option", _intern(sym), block) {|target|
          seq() { default } | seq(sym)
        }
      end

      def many(sym, &block)
        _defmetasyntax("many", _intern(sym), block) {|target|
            seq() { [] }\
          | seq(target, sym) {|list, x| list.push x; list }
        }
      end

      def many1(sym, &block)
        _defmetasyntax("many1", _intern(sym), block) {|target|
            seq(sym) {|x| [x] }\
          | seq(target, sym) {|list, x| list.push x; list }
        }
      end

      def separated_by(sep, sym, &block)
        option(separated_by1(sep, sym), [], &block)
      end

      def separated_by1(sep, sym, &block)
        _defmetasyntax("separated_by1", _intern(sym), block) {|target|
            seq(sym) {|x| [x] }\
          | seq(target, sep, sym) {|list, _, x| list.push x; list }
        }
      end

      def _intern(x)
        case x
        when Symbol, String
          @grammar.intern(x)
        when Racc::Sym
          x
        else
          raise TypeError, "wrong type #{x.class} (expected Symbol/String/Racc::Sym)"
        end
      end

      private

      def _defmetasyntax(type, id, action, &block)
        if action
          idbase = "#{type}@#{id}-#{@seqs[type] += 1}"
          target = _wrap(idbase, "#{idbase}-core", action)
          _regist("#{idbase}-core", &block)
        else
          target = _regist("#{type}@#{id}", &block)
        end
        @grammar.intern(target)
      end

      def _regist(target_name)
        target = target_name.intern
        unless _added?(@grammar.intern(target))
          yield(target).each_rule do |rule|
            rule.target = @grammar.intern(target)
            _delayed_add rule
          end
        end
        target
      end

      def _wrap(target_name, sym, block)
        target = target_name.intern
        _delayed_add Rule.new(@grammar.intern(target),
                              [@grammar.intern(sym.intern)],
                              UserAction.proc(block))
        target
      end
    end

    class PrecedenceDefinitionEnv
      def initialize(g)
        @grammar = g
        @prechigh_seen = false
        @preclow_seen = false
        @reverse = false
      end

      attr_reader :reverse

      def higher
        if @prechigh_seen
          raise CompileError, "prechigh used twice"
        end
        @prechigh_seen = true
      end

      def lower
        if @preclow_seen
          raise CompileError, "preclow used twice"
        end
        if @prechigh_seen
          @reverse = true
        end
        @preclow_seen = true
      end

      def left(*syms)
        @grammar.declare_precedence :Left, syms.map {|s| @grammar.intern(s) }
      end

      def right(*syms)
        @grammar.declare_precedence :Right, syms.map {|s| @grammar.intern(s) }
      end

      def nonassoc(*syms)
        @grammar.declare_precedence :Nonassoc, syms.map {|s| @grammar.intern(s)}
      end
    end

    #
    # Computation
    #

    def init
      return if @closed
      @closed = true
      @start ||= @rules.map {|r| r.target }.detect {|sym| not sym.dummy? }
      raise CompileError, 'no rule in input' if @rules.empty?
      add_start_rule
      @rules.freeze
      fix_ident
      compute_hash
      compute_heads
      determine_terminals
      compute_nullable_0
      @symboltable.fix
      compute_locate
      @symboltable.each_nonterminal {|t| compute_expand t }
      compute_nullable
      compute_useless
    end

    private

    def add_start_rule
      r = Rule.new(@symboltable.dummy,
                   [@start, @symboltable.anchor, @symboltable.anchor],
                   UserAction.empty)
      r.ident = 0
      r.hash = 0
      r.precedence = nil
      @rules.unshift r
    end

    # Rule#ident
    # LocationPointer#ident
    def fix_ident
      @rules.each_with_index do |rule, idx|
        rule.ident = idx
      end
    end

    # Rule#hash
    def compute_hash
      hash = 4   # size of dummy rule
      @rules.each do |rule|
        rule.hash = hash
        hash += (rule.size + 1)
      end
    end

    # Sym#heads
    def compute_heads
      @rules.each do |rule|
        rule.target.heads.push rule.ptrs[0]
      end
    end

    # Sym#terminal?
    def determine_terminals
      @symboltable.each do |s|
        s.term = s.heads.empty?
      end
    end

    # Sym#self_null?
    def compute_nullable_0
      @symboltable.each do |s|
        if s.terminal?
          s.snull = false
        else
          s.snull = s.heads.any? {|loc| loc.reduce? }
        end
      end
    end

    # Sym#locate
    def compute_locate
      @rules.each do |rule|
        t = nil
        rule.ptrs.each do |ptr|
          unless ptr.reduce?
            tok = ptr.dereference
            tok.locate.push ptr
            t = tok if tok.terminal?
          end
        end
        rule.precedence = t
      end
    end

    # Sym#expand
    def compute_expand(t)
      puts "expand> #{t.to_s}" if @debug_symbol
      t.expand = _compute_expand(t, ISet.new, [])
      puts "expand< #{t.to_s}: #{t.expand.to_s}" if @debug_symbol
    end

    def _compute_expand(t, set, lock)
      if tmp = t.expand
        set.update tmp
        return set
      end
      tok = nil
      set.update_a t.heads
      t.heads.each do |ptr|
        tok = ptr.dereference
        if tok and tok.nonterminal?
          unless lock[tok.ident]
            lock[tok.ident] = true
            _compute_expand tok, set, lock
          end
        end
      end
      set
    end

    # Sym#nullable?, Rule#nullable?
    def compute_nullable
      @rules.each       {|r| r.null = false }
      @symboltable.each {|t| t.null = false }
      r = @rules.dup
      s = @symboltable.nonterminals
      begin
        rs = r.size
        ss = s.size
        check_rules_nullable r
        check_symbols_nullable s
      end until rs == r.size and ss == s.size
    end

    def check_rules_nullable(rules)
      rules.delete_if do |rule|
        rule.null = true
        rule.symbols.each do |t|
          unless t.nullable?
            rule.null = false
            break
          end
        end
        rule.nullable?
      end
    end

    def check_symbols_nullable(symbols)
      symbols.delete_if do |sym|
        sym.heads.each do |ptr|
          if ptr.rule.nullable?
            sym.null = true
            break
          end
        end
        sym.nullable?
      end
    end

    # Sym#useless?, Rule#useless?
    # FIXME: what means "useless"?
    def compute_useless
      @symboltable.each_terminal {|sym| sym.useless = false }
      @symboltable.each_nonterminal {|sym| sym.useless = true }
      @rules.each {|rule| rule.useless = true }
      r = @rules.dup
      s = @symboltable.nonterminals
      begin
        rs = r.size
        ss = s.size
        check_rules_useless r
        check_symbols_useless s
      end until r.size == rs and s.size == ss
    end

    def check_rules_useless(rules)
      rules.delete_if do |rule|
        rule.useless = false
        rule.symbols.each do |sym|
          if sym.useless?
            rule.useless = true
            break
          end
        end
        not rule.useless?
      end
    end

    def check_symbols_useless(s)
      s.delete_if do |t|
        t.heads.each do |ptr|
          unless ptr.rule.useless?
            t.useless = false
            break
          end
        end
        not t.useless?
      end
    end

  end   # class Grammar


  class Rule

    def initialize(target, syms, act)
      @target = target
      @symbols = syms
      @action = act
      @alternatives = []

      @ident = nil
      @hash = nil
      @ptrs = nil
      @precedence = nil
      @specified_prec = nil
      @null = nil
      @useless = nil
    end

    attr_accessor :target
    attr_reader :symbols
    attr_reader :action

    def |(x)
      @alternatives.push x.rule
      self
    end

    def rule
      self
    end

    def each_rule(&block)
      yield self
      @alternatives.each(&block)
    end

    attr_accessor :ident

    attr_reader :hash
    attr_reader :ptrs

    def hash=(n)
      @hash = n
      ptrs = []
      @symbols.each_with_index do |sym, idx|
        ptrs.push LocationPointer.new(self, idx, sym)
      end
      ptrs.push LocationPointer.new(self, @symbols.size, nil)
      @ptrs = ptrs
    end

    def precedence
      @specified_prec || @precedence
    end

    def precedence=(sym)
      @precedence ||= sym
    end

    def prec(sym, &block)
      @specified_prec = sym
      if block
        unless @action.empty?
          raise CompileError, 'both of rule action block and prec block given'
        end
        @action = UserAction.proc(block)
      end
      self
    end

    attr_accessor :specified_prec

    def nullable?() @null end
    def null=(n)    @null = n end

    def useless?()  @useless end
    def useless=(u) @useless = u end

    def inspect
      "#<Racc::Rule id=#{@ident} (#{@target})>"
    end

    def ==(other)
      other.kind_of?(Rule) and @ident == other.ident
    end

    def [](idx)
      @symbols[idx]
    end

    def size
      @symbols.size
    end

    def empty?
      @symbols.empty?
    end

    def to_s
      "#<rule#{@ident}>"
    end

    def accept?
      if tok = @symbols[-1]
        tok.anchor?
      else
        false
      end
    end

    def each(&block)
      @symbols.each(&block)
    end

    def replace(src, dest)
      @target = dest
      @symbols = @symbols.map {|s| s == src ? dest : s }
    end

  end   # class Rule


  class UserAction

    def UserAction.source_text(src)
      new(src, nil)
    end

    def UserAction.proc(pr = nil, &block)
      if pr and block
        raise ArgumentError, "both of argument and block given"
      end
      new(nil, pr || block)
    end

    def UserAction.empty
      new(nil, nil)
    end

    private_class_method :new

    def initialize(src, proc)
      @source = src
      @proc = proc
    end

    attr_reader :source
    attr_reader :proc

    def source?
      not @proc
    end

    def proc?
      not @source
    end

    def empty?
      not @proc and not @source
    end

    def name
      "{action type=#{@source || @proc || 'nil'}}"
    end

    alias inspect name

  end


  class OrMark
    def initialize(lineno)
      @lineno = lineno
    end

    def name
      '|'
    end

    alias inspect name

    attr_reader :lineno
  end


  class Prec
    def initialize(symbol, lineno)
      @symbol = symbol
      @lineno = lineno
    end

    def name
      "=#{@symbol}"
    end

    alias inspect name

    attr_reader :symbol
    attr_reader :lineno
  end


  #
  # A set of rule and position in it's RHS.
  # Note that the number of pointers is more than rule's RHS array,
  # because pointer points right edge of the final symbol when reducing.
  #
  class LocationPointer

    def initialize(rule, i, sym)
      @rule   = rule
      @index  = i
      @symbol = sym
      @ident  = @rule.hash + i
      @reduce = sym.nil?
    end

    attr_reader :rule
    attr_reader :index
    attr_reader :symbol

    alias dereference symbol

    attr_reader :ident
    alias hash ident
    attr_reader :reduce
    alias reduce? reduce

    def to_s
      sprintf('(%d,%d %s)',
              @rule.ident, @index, (reduce?() ? '#' : @symbol.to_s))
    end

    alias inspect to_s

    def eql?(ot)
      @hash == ot.hash
    end

    alias == eql?

    def head?
      @index == 0
    end

    def next
      @rule.ptrs[@index + 1] or ptr_bug!
    end

    alias increment next

    def before(len)
      @rule.ptrs[@index - len] or ptr_bug!
    end

    private

    def ptr_bug!
      raise "racc: fatal: pointer not exist: self: #{to_s}"
    end

  end   # class LocationPointer


  class SymbolTable

    include Enumerable

    def initialize
      @symbols = []   # :: [Racc::Sym]
      @cache   = {}   # :: {(String|Symbol) => Racc::Sym}
      @dummy  = intern(:$start, true)
      @anchor = intern(false, true)     # Symbol ID = 0
      @error  = intern(:error, false)   # Symbol ID = 1
    end

    attr_reader :dummy
    attr_reader :anchor
    attr_reader :error

    def [](id)
      @symbols[id]
    end

    def intern(val, dummy = false)
      @cache[val] ||=
          begin
            sym = Sym.new(val, dummy)
            @symbols.push sym
            sym
          end
    end

    attr_reader :symbols
    alias to_a symbols

    def delete(sym)
      @symbols.delete sym
      @cache.delete sym.value
    end

    attr_reader :nt_base

    def nt_max
      @symbols.size
    end

    def each(&block)
      @symbols.each(&block)
    end

    def terminals(&block)
      @symbols[0, @nt_base]
    end

    def each_terminal(&block)
      @terms.each(&block)
    end

    def nonterminals
      @symbols[@nt_base, @symbols.size - @nt_base]
    end

    def each_nonterminal(&block)
      @nterms.each(&block)
    end

    def fix
      terms, nterms = @symbols.partition {|s| s.terminal? }
      @symbols = terms + nterms
      @terms = terms
      @nterms = nterms
      @nt_base = terms.size
      fix_ident
      check_terminals
    end

    private

    def fix_ident
      @symbols.each_with_index do |t, i|
        t.ident = i
      end
    end

    def check_terminals
      return unless @symbols.any? {|s| s.should_terminal? }
      @anchor.should_terminal
      @error.should_terminal
      each_terminal do |t|
        t.should_terminal if t.string_symbol?
      end
      each do |s|
        s.should_terminal if s.assoc
      end
      terminals().reject {|t| t.should_terminal? }.each do |t|
        raise CompileError, "terminal #{t} not declared as terminal"
      end
      nonterminals().select {|n| n.should_terminal? }.each do |n|
        raise CompileError, "symbol #{n} declared as terminal but is not terminal"
      end
    end

  end   # class SymbolTable


  # Stands terminal and nonterminal symbols.
  class Sym

    def initialize(value, dummyp)
      @ident = nil
      @value = value
      @dummyp = dummyp

      @term  = nil
      @nterm = nil
      @should_terminal = false
      @precedence = nil
      case value
      when Symbol
        @to_s = value.to_s
        @serialized = value.inspect
        @string = false
      when String
        @to_s = value.inspect
        @serialized = value.dump
        @string = true
      when false
        @to_s = '$end'
        @serialized = 'false'
        @string = false
      when ErrorSymbolValue
        @to_s = 'error'
        @serialized = 'Object.new'
        @string = false
      else
        raise ArgumentError, "unknown symbol value: #{value.class}"
      end

      @heads    = []
      @locate   = []
      @snull    = nil
      @null     = nil
      @expand   = nil
      @useless  = nil
    end

    class << self
      def once_writer(nm)
        nm = nm.id2name
        module_eval(<<-EOS)
          def #{nm}=(v)
            raise 'racc: fatal: @#{nm} != nil' unless @#{nm}.nil?
            @#{nm} = v
          end
        EOS
      end
    end

    once_writer :ident
    attr_reader :ident

    alias hash ident

    attr_reader :value

    def dummy?
      @dummyp
    end

    def terminal?
      @term
    end

    def nonterminal?
      @nterm
    end

    def term=(t)
      raise 'racc: fatal: term= called twice' unless @term.nil?
      @term = t
      @nterm = !t
    end

    def should_terminal
      @should_terminal = true
    end

    def should_terminal?
      @should_terminal
    end

    def string_symbol?
      @string
    end

    def serialize
      @serialized
    end

    attr_writer :serialized

    attr_accessor :precedence
    attr_accessor :assoc

    def to_s
      @to_s.dup
    end

    alias inspect to_s

    def |(x)
      rule() | x.rule
    end

    def rule
      Rule.new(nil, [self], UserAction.empty)
    end

    #
    # cache
    #

    attr_reader :heads
    attr_reader :locate

    def self_null?
      @snull
    end

    once_writer :snull

    def nullable?
      @null
    end

    def null=(n)
      @null = n
    end

    attr_reader :expand
    once_writer :expand

    def useless?
      @useless
    end

    def useless=(f)
      @useless = f
    end

  end   # class Sym

end   # module Racc
#--
#
#
#
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
# see the file "COPYING".
#
#++

require 'racc/compat'
require 'racc/sourcetext'
require 'racc/parser-text'
require 'rbconfig'

module Racc

  class ParserFileGenerator

    class Params
      def self.bool_attr(name)
        module_eval(<<-End)
          def #{name}?
            @#{name}
          end

          def #{name}=(b)
            @#{name} = b
          end
        End
      end

      attr_accessor :filename
      attr_accessor :classname
      attr_accessor :superclass
      bool_attr :omit_action_call
      bool_attr :result_var
      attr_accessor :header
      attr_accessor :inner
      attr_accessor :footer

      bool_attr :debug_parser
      bool_attr :convert_line
      bool_attr :convert_line_all
      bool_attr :embed_runtime
      bool_attr :make_executable
      attr_accessor :interpreter

      def initialize
        # Parameters derived from parser
        self.filename = nil
        self.classname = nil
        self.superclass = 'Racc::Parser'
        self.omit_action_call = true
        self.result_var = true
        self.header = []
        self.inner  = []
        self.footer = []

        # Parameters derived from command line options
        self.debug_parser = false
        self.convert_line = true
        self.convert_line_all = false
        self.embed_runtime = false
        self.make_executable = false
        self.interpreter = nil
      end
    end

    def initialize(states, params)
      @states = states
      @grammar = states.grammar
      @params = params
    end

    def generate_parser
      string_io = StringIO.new

      init_line_conversion_system
      @f = string_io
      parser_file

      string_io.rewind
      string_io.read
    end

    def generate_parser_file(destpath)
      init_line_conversion_system
      File.open(destpath, 'w') {|f|
        @f = f
        parser_file
      }
      File.chmod 0755, destpath if @params.make_executable?
    end

    private

    def parser_file
      shebang @params.interpreter if @params.make_executable?
      notice
      line
      if @params.embed_runtime?
        embed_library runtime_source()
      else
        require 'racc/parser.rb'
      end
      header
      parser_class(@params.classname, @params.superclass) {
        inner
        state_transition_table
      }
      footer
    end

    c = ::RbConfig::CONFIG
    RUBY_PATH = "#{c['bindir']}/#{c['ruby_install_name']}#{c['EXEEXT']}"

    def shebang(path)
      line '#!' + (path == 'ruby' ? RUBY_PATH : path)
    end

    def notice
      line %q[#]
      line %q[# DO NOT MODIFY!!!!]
      line %Q[# This file is automatically generated by Racc #{Racc::Version}]
      line %Q[# from Racc grammar file "#{@params.filename}".]
      line %q[#]
    end

    def runtime_source
      SourceText.new(::Racc::PARSER_TEXT, 'racc/parser.rb', 1)
    end

    def embed_library(src)
      line %[###### #{src.filename} begin]
      line %[unless $".index '#{src.filename}']
      line %[$".push '#{src.filename}']
      put src, @params.convert_line?
      line %[end]
      line %[###### #{src.filename} end]
    end

    def require(feature)
      line "require '#{feature}'"
    end

    def parser_class(classname, superclass)
      mods = classname.split('::')
      classid = mods.pop
      mods.each do |mod|
        indent; line "module #{mod}"
        cref_push mod
      end
      indent; line "class #{classid} < #{superclass}"
      cref_push classid
      yield
      cref_pop
      indent; line "end   \# class #{classid}"
      mods.reverse_each do |mod|
        cref_pop
        indent; line "end   \# module #{mod}"
      end
    end

    def header
      @params.header.each do |src|
        line
        put src, @params.convert_line_all?
      end
    end

    def inner
      @params.inner.each do |src|
        line
        put src, @params.convert_line?
      end
    end

    def footer
      @params.footer.each do |src|
        line
        put src, @params.convert_line_all?
      end
    end

    # Low Level Routines

    def put(src, convert_line = false)
      if convert_line
        replace_location(src) {
          @f.puts src.text
        }
      else
        @f.puts src.text
      end
    end

    def line(str = '')
      @f.puts str
    end

    def init_line_conversion_system
      @cref = []
      @used_separator = {}
    end

    def cref_push(name)
      @cref.push name
    end

    def cref_pop
      @cref.pop
    end

    def indent
      @f.print '  ' * @cref.size
    end

    def toplevel?
      @cref.empty?
    end

    def replace_location(src)
      sep = make_separator(src)
      @f.print 'self.class.' if toplevel?
      @f.puts "module_eval(<<'#{sep}', '#{src.filename}', #{src.lineno})"
      yield
      @f.puts sep
    end

    def make_separator(src)
      sep = unique_separator(src.filename)
      sep *= 2 while src.text.index(sep)
      sep
    end

    def unique_separator(id)
      sep = String.new "...end #{id}/module_eval..."
      while @used_separator.key?(sep)
        sep.concat sprintf('%02x', rand(255))
      end
      @used_separator[sep] = true
      sep
    end

    #
    # State Transition Table Serialization
    #

    public

    def put_state_transition_table(f)
      @f = f
      state_transition_table
    end

    private

    def state_transition_table
      table = @states.state_transition_table
      table.use_result_var = @params.result_var?
      table.debug_parser = @params.debug_parser?

      line "##### State transition tables begin ###"
      line
      integer_list 'racc_action_table', table.action_table
      line
      integer_list 'racc_action_check', table.action_check
      line
      integer_list 'racc_action_pointer', table.action_pointer
      line
      integer_list 'racc_action_default', table.action_default
      line
      integer_list 'racc_goto_table', table.goto_table
      line
      integer_list 'racc_goto_check', table.goto_check
      line
      integer_list 'racc_goto_pointer', table.goto_pointer
      line
      integer_list 'racc_goto_default', table.goto_default
      line
      i_i_sym_list 'racc_reduce_table', table.reduce_table
      line
      line "racc_reduce_n = #{table.reduce_n}"
      line
      line "racc_shift_n = #{table.shift_n}"
      line
      sym_int_hash 'racc_token_table', table.token_table
      line
      line "racc_nt_base = #{table.nt_base}"
      line
      line "racc_use_result_var = #{table.use_result_var}"
      line
      @f.print(unindent_auto(<<-End))
        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 ]
      End
      line
      string_list 'Racc_token_to_s_table', table.token_to_s_table
      line
      line "Racc_debug_parser = #{table.debug_parser}"
      line
      line '##### State transition tables end #####'
      actions
    end

    def integer_list(name, table)
      if table.size > 2000
        serialize_integer_list_compressed name, table
      else
        serialize_integer_list_std name, table
      end
    end

    def serialize_integer_list_compressed(name, table)
      # TODO: this can be made a LOT more clean with a simple split/map
      sep  = "\n"
      nsep = ",\n"
      buf  = String.new
      com  = ''
      ncom = ','
      co   = com
      @f.print 'clist = ['
      table.each do |i|
        buf << co << i.to_s; co = ncom
        if buf.size > 66
          @f.print sep; sep = nsep
          @f.print "'", buf, "'"
          buf = String.new
          co = com
        end
      end
      unless buf.empty?
        @f.print sep
        @f.print "'", buf, "'"
      end
      line ' ]'

      @f.print(<<-End)
        #{name} = arr = ::Array.new(#{table.size}, nil)
        idx = 0
        clist.each do |str|
          str.split(',', -1).each do |i|
            arr[idx] = i.to_i unless i.empty?
            idx += 1
          end
        end
      End
    end

    def serialize_integer_list_std(name, table)
      sep = ''
      line "#{name} = ["
      table.each_slice(10) do |ns|
        @f.print sep; sep = ",\n"
        @f.print ns.map {|n| sprintf('%6s', n ? n.to_s : 'nil') }.join(',')
      end
      line ' ]'
    end

    def i_i_sym_list(name, table)
      sep = ''
      line "#{name} = ["
      table.each_slice(3) do |len, target, mid|
        @f.print sep; sep = ",\n"
        @f.printf '  %d, %d, %s', len, target, mid.inspect
      end
      line " ]"
    end

    def sym_int_hash(name, h)
      sep = "\n"
      @f.print "#{name} = {"
      h.to_a.sort_by {|sym, i| i }.each do |sym, i|
        @f.print sep; sep = ",\n"
        @f.printf "  %s => %d", sym.serialize, i
      end
      line " }"
    end

    def string_list(name, list)
      sep = "  "
      line "#{name} = ["
      list.each do |s|
        @f.print sep; sep = ",\n  "
        @f.print s.dump
      end
      line ' ]'
    end

    def actions
      @grammar.each do |rule|
        unless rule.action.source?
          raise "racc: fatal: cannot generate parser file when any action is a Proc"
        end
      end

      if @params.result_var?
        decl = ', result'
        retval = "\n    result"
        default_body = ''
      else
        decl = ''
        retval = ''
        default_body = 'val[0]'
      end
      @grammar.each do |rule|
        line
        if rule.action.empty? and @params.omit_action_call?
          line "# reduce #{rule.ident} omitted"
        else
          src0 = rule.action.source || SourceText.new(default_body, __FILE__, 0)
          if @params.convert_line?
            src = remove_blank_lines(src0)
            delim = make_delimiter(src.text)
            @f.printf unindent_auto(<<-End),
              module_eval(<<'%s', '%s', %d)
                def _reduce_%d(val, _values%s)
                  %s%s
                end
              %s
            End
                      delim, src.filename, src.lineno - 1,
                        rule.ident, decl,
                        src.text, retval,
                      delim
          else
            src = remove_blank_lines(src0)
            @f.printf unindent_auto(<<-End),
              def _reduce_%d(val, _values%s)
              %s%s
              end
            End
                      rule.ident, decl,
                      src.text, retval
          end
        end
      end
      line
      @f.printf unindent_auto(<<-'End'), decl
        def _reduce_none(val, _values%s)
          val[0]
        end
      End
      line
    end

    def remove_blank_lines(src)
      body = src.text.dup
      line = src.lineno
      while body.slice!(/\A[ \t\f]*(?:\n|\r\n|\r)/)
        line += 1
      end
      SourceText.new(body, src.filename, line)
    end

    def make_delimiter(body)
      delim = '.,.,'
      while body.index(delim)
        delim *= 2
      end
      delim
    end

    def unindent_auto(str)
      lines = str.lines.to_a
      n = minimum_indent(lines)
      lines.map {|line| detab(line).sub(indent_re(n), '').rstrip + "\n" }.join('')
    end

    def minimum_indent(lines)
      lines.map {|line| n_indent(line) }.min
    end

    def n_indent(line)
      line.slice(/\A\s+/).size
    end

    RE_CACHE = {}

    def indent_re(n)
      RE_CACHE[n] ||= /\A {#{n}}/
    end

    def detab(str, ts = 8)
      add = 0
      len = nil
      str.gsub(/\t/) {
        len = ts - ($`.size + add) % ts
        add += len - 1
        ' ' * len
      }
    end

  end

end
#--
#
#
#
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
# see the file "COPYING".
#
#++

require 'racc'
require 'racc/compat'
require 'racc/grammar'
require 'racc/parserfilegenerator'
require 'racc/sourcetext'
require 'stringio'

module Racc

  grammar = Grammar.define {
    g = self

    g.class = seq(:CLASS, :cname, many(:param), :RULE, :rules, option(:END))

    g.cname       = seq(:rubyconst) {|name|
                      @result.params.classname = name
                    }\
                  | seq(:rubyconst, "<", :rubyconst) {|c, _, s|
                      @result.params.classname = c
                      @result.params.superclass = s
                    }

    g.rubyconst   = separated_by1(:colon2, :SYMBOL) {|syms|
                      syms.map {|s| s.to_s }.join('::')
                    }

    g.colon2 = seq(':', ':')

    g.param       = seq(:CONV, many1(:convdef), :END) {|*|
                      #@grammar.end_convert_block   # FIXME
                    }\
                  | seq(:PRECHIGH, many1(:precdef), :PRECLOW) {|*|
                      @grammar.end_precedence_declaration true
                    }\
                  | seq(:PRECLOW, many1(:precdef), :PRECHIGH) {|*|
                      @grammar.end_precedence_declaration false
                    }\
                  | seq(:START, :symbol) {|_, sym|
                      @grammar.start_symbol = sym
                    }\
                  | seq(:TOKEN, :symbols) {|_, syms|
                      syms.each do |s|
                        s.should_terminal
                      end
                    }\
                  | seq(:OPTION, :options) {|_, syms|
                      syms.each do |opt|
                        case opt
                        when 'result_var'
                          @result.params.result_var = true
                        when 'no_result_var'
                          @result.params.result_var = false
                        when 'omit_action_call'
                          @result.params.omit_action_call = true
                        when 'no_omit_action_call'
                          @result.params.omit_action_call = false
                        else
                          raise CompileError, "unknown option: #{opt}"
                        end
                      end
                    }\
                  | seq(:EXPECT, :DIGIT) {|_, num|
                      if @grammar.n_expected_srconflicts
                        raise CompileError, "`expect' seen twice"
                      end
                      @grammar.n_expected_srconflicts = num
                    }

    g.convdef     = seq(:symbol, :STRING) {|sym, code|
                      sym.serialized = code
                    }

    g.precdef     = seq(:LEFT, :symbols) {|_, syms|
                      @grammar.declare_precedence :Left, syms
                    }\
                  | seq(:RIGHT, :symbols) {|_, syms|
                      @grammar.declare_precedence :Right, syms
                    }\
                  | seq(:NONASSOC, :symbols) {|_, syms|
                      @grammar.declare_precedence :Nonassoc, syms
                    }

    g.symbols     = seq(:symbol) {|sym|
                      [sym]
                    }\
                  | seq(:symbols, :symbol) {|list, sym|
                      list.push sym
                      list
                    }\
                  | seq(:symbols, "|")

    g.symbol      = seq(:SYMBOL) {|sym| @grammar.intern(sym) }\
                  | seq(:STRING) {|str| @grammar.intern(str) }

    g.options     = many(:SYMBOL) {|syms| syms.map {|s| s.to_s } }

    g.rules       = option(:rules_core) {|list|
                      add_rule_block list  unless list.empty?
                      nil
                    }

    g.rules_core  = seq(:symbol) {|sym|
                      [sym]
                    }\
                  | seq(:rules_core, :rule_item) {|list, i|
                      list.push i
                      list
                    }\
                  | seq(:rules_core, ';') {|list, *|
                      add_rule_block list  unless list.empty?
                      list.clear
                      list
                    }\
                  | seq(:rules_core, ':') {|list, *|
                      next_target = list.pop
                      add_rule_block list  unless list.empty?
                      [next_target]
                    }

    g.rule_item   = seq(:symbol)\
                  | seq("|") {|*|
                      OrMark.new(@scanner.lineno)
                    }\
                  | seq("=", :symbol) {|_, sym|
                      Prec.new(sym, @scanner.lineno)
                    }\
                  | seq(:ACTION) {|src|
                      UserAction.source_text(src)
                    }
  }

  GrammarFileParser = grammar.parser_class

  if grammar.states.srconflict_exist?
    raise 'Racc boot script fatal: S/R conflict in build'
  end
  if grammar.states.rrconflict_exist?
    raise 'Racc boot script fatal: R/R conflict in build'
  end

  class GrammarFileParser   # reopen

    class Result
      def initialize(grammar)
        @grammar = grammar
        @params = ParserFileGenerator::Params.new
      end

      attr_reader :grammar
      attr_reader :params
    end

    def GrammarFileParser.parse_file(filename)
      parse(File.read(filename), filename, 1)
    end

    def GrammarFileParser.parse(src, filename = '-', lineno = 1)
      new().parse(src, filename, lineno)
    end

    def initialize(debug_flags = DebugFlags.new)
      @yydebug = debug_flags.parse
    end

    def parse(src, filename = '-', lineno = 1)
      @filename = filename
      @lineno = lineno
      @scanner = GrammarFileScanner.new(src, @filename)
      @scanner.debug = @yydebug
      @grammar = Grammar.new
      @result = Result.new(@grammar)
      @embedded_action_seq = 0
      yyparse @scanner, :yylex
      parse_user_code
      @result.grammar.init
      @result
    end

    private

    def next_token
      @scanner.scan
    end

    def on_error(tok, val, _values)
      if val.respond_to?(:id2name)
        v = val.id2name
      elsif val.kind_of?(String)
        v = val
      else
        v = val.inspect
      end
      raise CompileError, "#{location()}: unexpected token '#{v}'"
    end

    def location
      "#{@filename}:#{@lineno - 1 + @scanner.lineno}"
    end

    def add_rule_block(list)
      sprec = nil
      target = list.shift
      case target
      when OrMark, UserAction, Prec
        raise CompileError, "#{target.lineno}: unexpected symbol #{target.name}"
      end
      curr = []
      list.each do |i|
        case i
        when OrMark
          add_rule target, curr, sprec
          curr = []
          sprec = nil
        when Prec
          raise CompileError, "'=<prec>' used twice in one rule" if sprec
          sprec = i.symbol
        else
          curr.push i
        end
      end
      add_rule target, curr, sprec
    end

    def add_rule(target, list, sprec)
      if list.last.kind_of?(UserAction)
        act = list.pop
      else
        act = UserAction.empty
      end
      list.map! {|s| s.kind_of?(UserAction) ? embedded_action(s) : s }
      rule = Rule.new(target, list, act)
      rule.specified_prec = sprec
      @grammar.add rule
    end

    def embedded_action(act)
      sym = @grammar.intern("@#{@embedded_action_seq += 1}".intern, true)
      @grammar.add Rule.new(sym, [], act)
      sym
    end

    #
    # User Code Block
    #

    def parse_user_code
      line = @scanner.lineno
      _, *blocks = *@scanner.epilogue.split(/^----/)
      blocks.each do |block|
        header, *body = block.lines.to_a
        label0, pathes = *header.sub(/\A-+/, '').split('=', 2)
        label = canonical_label(label0)
        (pathes ? pathes.strip.split(' ') : []).each do |path|
          add_user_code label, SourceText.new(File.read(path), path, 1)
        end
        add_user_code label, SourceText.new(body.join(''), @filename, line + 1)
        line += (1 + body.size)
      end
    end

    USER_CODE_LABELS = {
      'header'  => :header,
      'prepare' => :header,   # obsolete
      'inner'   => :inner,
      'footer'  => :footer,
      'driver'  => :footer    # obsolete
    }

    def canonical_label(src)
      label = src.to_s.strip.downcase.slice(/\w+/)
      unless USER_CODE_LABELS.key?(label)
        raise CompileError, "unknown user code type: #{label.inspect}"
      end
      label
    end

    def add_user_code(label, src)
      @result.params.public_send(USER_CODE_LABELS[label]).push src
    end

  end


  class GrammarFileScanner

    def initialize(str, filename = '-')
      @lines  = str.b.split(/\n|\r\n|\r/)
      @filename = filename
      @lineno = -1
      @line_head   = true
      @in_rule_blk = false
      @in_conv_blk = false
      @in_block = nil
      @epilogue = ''
      @debug = false
      next_line
    end

    attr_reader :epilogue

    def lineno
      @lineno + 1
    end

    attr_accessor :debug

    def yylex(&block)
      unless @debug
        yylex0(&block)
      else
        yylex0 do |sym, tok|
          $stderr.printf "%7d %-10s %s\n", lineno(), sym.inspect, tok.inspect
          yield [sym, tok]
        end
      end
    end

    private

    def yylex0
      begin
        until @line.empty?
          @line.sub!(/\A\s+/, '')
          if /\A\#/ =~ @line
            break
          elsif /\A\/\*/ =~ @line
            skip_comment
          elsif s = reads(/\A[a-zA-Z_]\w*/)
            yield [atom_symbol(s), s.intern]
          elsif s = reads(/\A\d+/)
            yield [:DIGIT, s.to_i]
          elsif ch = reads(/\A./)
            case ch
            when '"', "'"
              yield [:STRING, eval(scan_quoted(ch))]
            when '{'
              lineno = lineno()
              yield [:ACTION, SourceText.new(scan_action(), @filename, lineno)]
            else
              if ch == '|'
                @line_head = false
              end
              yield [ch, ch]
            end
          else
          end
        end
      end while next_line()
      yield nil
    end

    def next_line
      @lineno += 1
      @line = @lines[@lineno]
      if not @line or /\A----/ =~ @line
        @epilogue = @lines.join("\n")
        @lines.clear
        @line = nil
        if @in_block
          @lineno -= 1
          scan_error! sprintf('unterminated %s', @in_block)
        end
        false
      else
        @line.sub!(/(?:\n|\r\n|\r)\z/, '')
        @line_head = true
        true
      end
    end

    ReservedWord = {
      'right'    => :RIGHT,
      'left'     => :LEFT,
      'nonassoc' => :NONASSOC,
      'preclow'  => :PRECLOW,
      'prechigh' => :PRECHIGH,
      'token'    => :TOKEN,
      'convert'  => :CONV,
      'options'  => :OPTION,
      'start'    => :START,
      'expect'   => :EXPECT,
      'class'    => :CLASS,
      'rule'     => :RULE,
      'end'      => :END
    }

    def atom_symbol(token)
      if token == 'end'
        symbol = :END
        @in_conv_blk = false
        @in_rule_blk = false
      else
        if @line_head and not @in_conv_blk and not @in_rule_blk
          symbol = ReservedWord[token] || :SYMBOL
        else
          symbol = :SYMBOL
        end
        case symbol
        when :RULE then @in_rule_blk = true
        when :CONV then @in_conv_blk = true
        end
      end
      @line_head = false
      symbol
    end

    def skip_comment
      @in_block = 'comment'
      until m = /\*\//.match(@line)
        next_line
      end
      @line = m.post_match
      @in_block = nil
    end

    $raccs_print_type = false

    def scan_action
      buf = String.new
      nest = 1
      pre = nil
      @in_block = 'action'
      begin
        pre = nil
        if s = reads(/\A\s+/)
          # does not set 'pre'
          buf << s
        end
        until @line.empty?
          if s = reads(/\A[^'"`{}%#\/\$]+/)
            buf << (pre = s)
            next
          end
          case ch = read(1)
          when '{'
            nest += 1
            buf << (pre = ch)
          when '}'
            nest -= 1
            if nest == 0
              @in_block = nil
              buf.sub!(/[ \t\f]+\z/, '')
              return buf
            end
            buf << (pre = ch)
          when '#'   # comment
            buf << ch << @line
            break
          when "'", '"', '`'
            buf << (pre = scan_quoted(ch))
          when '%'
            if literal_head? pre, @line
              # % string, regexp, array
              buf << ch
              case ch = read(1)
              when /[qQx]/n
                buf << ch << (pre = scan_quoted(read(1), '%string'))
              when /wW/n
                buf << ch << (pre = scan_quoted(read(1), '%array'))
              when /s/n
                buf << ch << (pre = scan_quoted(read(1), '%symbol'))
              when /r/n
                buf << ch << (pre = scan_quoted(read(1), '%regexp'))
              when /[a-zA-Z0-9= ]/n   # does not include "_"
                scan_error! "unknown type of % literal '%#{ch}'"
              else
                buf << (pre = scan_quoted(ch, '%string'))
              end
            else
              # operator
              buf << '||op->' if $raccs_print_type
              buf << (pre = ch)
            end
          when '/'
            if literal_head? pre, @line
              # regexp
              buf << (pre = scan_quoted(ch, 'regexp'))
            else
              # operator
              buf << '||op->' if $raccs_print_type
              buf << (pre = ch)
            end
          when '$'   # gvar
            buf << ch << (pre = read(1))
          else
            raise 'racc: fatal: must not happen'
          end
        end
        buf << "\n"
      end while next_line()
      raise 'racc: fatal: scan finished before parser finished'
    end

    def literal_head?(pre, post)
      (!pre || /[a-zA-Z_0-9]/n !~ pre[-1,1]) &&
          !post.empty? && /\A[\s\=]/n !~ post
    end

    def read(len)
      s = @line[0, len]
      @line = @line[len .. -1]
      s
    end

    def reads(re)
      m = re.match(@line) or return nil
      @line = m.post_match
      m[0]
    end

    def scan_quoted(left, tag = 'string')
      buf = left.dup
      buf = "||#{tag}->" + buf if $raccs_print_type
      re = get_quoted_re(left)
      sv, @in_block = @in_block, tag
      begin
        if s = reads(re)
          buf << s
          break
        else
          buf << @line
        end
      end while next_line()
      @in_block = sv
      buf << "<-#{tag}||" if $raccs_print_type
      buf
    end

    LEFT_TO_RIGHT = {
      '(' => ')',
      '{' => '}',
      '[' => ']',
      '<' => '>'
    }

    CACHE = {}

    def get_quoted_re(left)
      term = Regexp.quote(LEFT_TO_RIGHT[left] || left)
      CACHE[left] ||= /\A[^#{term}\\]*(?:\\.[^\\#{term}]*)*#{term}/
    end

    def scan_error!(msg)
      raise CompileError, "#{lineno()}: #{msg}"
    end

  end

end   # module Racc
# frozen_string_literal: false
#--
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
#
# As a special exception, when this code is copied by Racc
# into a Racc output file, you may use that output file
# without restriction.
#++

require 'racc/info'

unless defined?(NotImplementedError)
  NotImplementedError = NotImplementError # :nodoc:
end

module Racc
  class ParseError < StandardError; end
end
unless defined?(::ParseError)
  ParseError = Racc::ParseError
end

# Racc is a LALR(1) parser generator.
# It is written in Ruby itself, and generates Ruby programs.
#
# == Command-line Reference
#
#     racc [-o<var>filename</var>] [--output-file=<var>filename</var>]
#          [-e<var>rubypath</var>] [--executable=<var>rubypath</var>]
#          [-v] [--verbose]
#          [-O<var>filename</var>] [--log-file=<var>filename</var>]
#          [-g] [--debug]
#          [-E] [--embedded]
#          [-l] [--no-line-convert]
#          [-c] [--line-convert-all]
#          [-a] [--no-omit-actions]
#          [-C] [--check-only]
#          [-S] [--output-status]
#          [--version] [--copyright] [--help] <var>grammarfile</var>
#
# [+grammarfile+]
#   Racc grammar file. Any extension is permitted.
# [-o+outfile+, --output-file=+outfile+]
#   A filename for output. default is <+filename+>.tab.rb
# [-O+filename+, --log-file=+filename+]
#   Place logging output in file +filename+.
#   Default log file name is <+filename+>.output.
# [-e+rubypath+, --executable=+rubypath+]
#   output executable file(mode 755). where +path+ is the Ruby interpreter.
# [-v, --verbose]
#   verbose mode. create +filename+.output file, like yacc's y.output file.
# [-g, --debug]
#   add debug code to parser class. To display debuggin information,
#   use this '-g' option and set @yydebug true in parser class.
# [-E, --embedded]
#   Output parser which doesn't need runtime files (racc/parser.rb).
# [-C, --check-only]
#   Check syntax of racc grammar file and quit.
# [-S, --output-status]
#   Print messages time to time while compiling.
# [-l, --no-line-convert]
#   turns off line number converting.
# [-c, --line-convert-all]
#   Convert line number of actions, inner, header and footer.
# [-a, --no-omit-actions]
#   Call all actions, even if an action is empty.
# [--version]
#   print Racc version and quit.
# [--copyright]
#   Print copyright and quit.
# [--help]
#   Print usage and quit.
#
# == Generating Parser Using Racc
#
# To compile Racc grammar file, simply type:
#
#   $ racc parse.y
#
# This creates Ruby script file "parse.tab.y". The -o option can change the output filename.
#
# == Writing A Racc Grammar File
#
# If you want your own parser, you have to write a grammar file.
# A grammar file contains the name of your parser class, grammar for the parser,
# user code, and anything else.
# When writing a grammar file, yacc's knowledge is helpful.
# If you have not used yacc before, Racc is not too difficult.
#
# Here's an example Racc grammar file.
#
#   class Calcparser
#   rule
#     target: exp { print val[0] }
#
#     exp: exp '+' exp
#        | exp '*' exp
#        | '(' exp ')'
#        | NUMBER
#   end
#
# Racc grammar files resemble yacc files.
# But (of course), this is Ruby code.
# yacc's $$ is the 'result', $0, $1... is
# an array called 'val', and $-1, $-2... is an array called '_values'.
#
# See the {Grammar File Reference}[rdoc-ref:lib/racc/rdoc/grammar.en.rdoc] for
# more information on grammar files.
#
# == Parser
#
# Then you must prepare the parse entry method. There are two types of
# parse methods in Racc, Racc::Parser#do_parse and Racc::Parser#yyparse
#
# Racc::Parser#do_parse is simple.
#
# It's yyparse() of yacc, and Racc::Parser#next_token is yylex().
# This method must returns an array like [TOKENSYMBOL, ITS_VALUE].
# EOF is [false, false].
# (TOKENSYMBOL is a Ruby symbol (taken from String#intern) by default.
# If you want to change this, see the grammar reference.
#
# Racc::Parser#yyparse is little complicated, but useful.
# It does not use Racc::Parser#next_token, instead it gets tokens from any iterator.
#
# For example, <code>yyparse(obj, :scan)</code> causes
# calling +obj#scan+, and you can return tokens by yielding them from +obj#scan+.
#
# == Debugging
#
# When debugging, "-v" or/and the "-g" option is helpful.
#
# "-v" creates verbose log file (.output).
# "-g" creates a "Verbose Parser".
# Verbose Parser prints the internal status when parsing.
# But it's _not_ automatic.
# You must use -g option and set +@yydebug+ to +true+ in order to get output.
# -g option only creates the verbose parser.
#
# === Racc reported syntax error.
#
# Isn't there too many "end"?
# grammar of racc file is changed in v0.10.
#
# Racc does not use '%' mark, while yacc uses huge number of '%' marks..
#
# === Racc reported "XXXX conflicts".
#
# Try "racc -v xxxx.y".
# It causes producing racc's internal log file, xxxx.output.
#
# === Generated parsers does not work correctly
#
# Try "racc -g xxxx.y".
# This command let racc generate "debugging parser".
# Then set @yydebug=true in your parser.
# It produces a working log of your parser.
#
# == Re-distributing Racc runtime
#
# A parser, which is created by Racc, requires the Racc runtime module;
# racc/parser.rb.
#
# Ruby 1.8.x comes with Racc runtime module,
# you need NOT distribute Racc runtime files.
#
# If you want to include the Racc runtime module with your parser.
# This can be done by using '-E' option:
#
#   $ racc -E -omyparser.rb myparser.y
#
# This command creates myparser.rb which `includes' Racc runtime.
# Only you must do is to distribute your parser file (myparser.rb).
#
# Note: parser.rb is ruby license, but your parser is not.
# Your own parser is completely yours.
module Racc

  unless defined?(Racc_No_Extensions)
    Racc_No_Extensions = false # :nodoc:
  end

  class Parser

    Racc_Runtime_Version = ::Racc::VERSION
    Racc_Runtime_Core_Version_R = ::Racc::VERSION

    begin
      if Object.const_defined?(:RUBY_ENGINE) and RUBY_ENGINE == 'jruby'
        require 'jruby'
        require 'racc/cparse-jruby.jar'
        com.headius.racc.Cparse.new.load(JRuby.runtime, false)
      else
        require 'racc/cparse'
      end

      unless new.respond_to?(:_racc_do_parse_c, true)
        raise LoadError, 'old cparse.so'
      end
      if Racc_No_Extensions
        raise LoadError, 'selecting ruby version of racc runtime core'
      end

      Racc_Main_Parsing_Routine    = :_racc_do_parse_c # :nodoc:
      Racc_YY_Parse_Method         = :_racc_yyparse_c # :nodoc:
      Racc_Runtime_Core_Version    = Racc_Runtime_Core_Version_C # :nodoc:
      Racc_Runtime_Type            = 'c' # :nodoc:
    rescue LoadError
      Racc_Main_Parsing_Routine    = :_racc_do_parse_rb
      Racc_YY_Parse_Method         = :_racc_yyparse_rb
      Racc_Runtime_Core_Version    = Racc_Runtime_Core_Version_R
      Racc_Runtime_Type            = 'ruby'
    end

    def Parser.racc_runtime_type # :nodoc:
      Racc_Runtime_Type
    end

    def _racc_setup
      @yydebug = false unless self.class::Racc_debug_parser
      @yydebug = false unless defined?(@yydebug)
      if @yydebug
        @racc_debug_out = $stderr unless defined?(@racc_debug_out)
        @racc_debug_out ||= $stderr
      end
      arg = self.class::Racc_arg
      arg[13] = true if arg.size < 14
      arg
    end

    def _racc_init_sysvars
      @racc_state  = [0]
      @racc_tstack = []
      @racc_vstack = []

      @racc_t = nil
      @racc_val = nil

      @racc_read_next = true

      @racc_user_yyerror = false
      @racc_error_status = 0
    end

    # The entry point of the parser. This method is used with #next_token.
    # If Racc wants to get token (and its value), calls next_token.
    #
    # Example:
    #     def parse
    #       @q = [[1,1],
    #             [2,2],
    #             [3,3],
    #             [false, '$']]
    #       do_parse
    #     end
    #
    #     def next_token
    #       @q.shift
    #     end
    class_eval %{
    def do_parse
      #{Racc_Main_Parsing_Routine}(_racc_setup(), false)
    end
    }

    # The method to fetch next token.
    # If you use #do_parse method, you must implement #next_token.
    #
    # The format of return value is [TOKEN_SYMBOL, VALUE].
    # +token-symbol+ is represented by Ruby's symbol by default, e.g. :IDENT
    # for 'IDENT'.  ";" (String) for ';'.
    #
    # The final symbol (End of file) must be false.
    def next_token
      raise NotImplementedError, "#{self.class}\#next_token is not defined"
    end

    def _racc_do_parse_rb(arg, in_debug)
      action_table, action_check, action_default, action_pointer,
      _,            _,            _,              _,
      _,            _,            token_table,    * = arg

      _racc_init_sysvars
      tok = act = i = nil

      catch(:racc_end_parse) {
        while true
          if i = action_pointer[@racc_state[-1]]
            if @racc_read_next
              if @racc_t != 0   # not EOF
                tok, @racc_val = next_token()
                unless tok      # EOF
                  @racc_t = 0
                else
                  @racc_t = (token_table[tok] or 1)   # error token
                end
                racc_read_token(@racc_t, tok, @racc_val) if @yydebug
                @racc_read_next = false
              end
            end
            i += @racc_t
            unless i >= 0 and
                   act = action_table[i] and
                   action_check[i] == @racc_state[-1]
              act = action_default[@racc_state[-1]]
            end
          else
            act = action_default[@racc_state[-1]]
          end
          while act = _racc_evalact(act, arg)
            ;
          end
        end
      }
    end

    # Another entry point for the parser.
    # If you use this method, you must implement RECEIVER#METHOD_ID method.
    #
    # RECEIVER#METHOD_ID is a method to get next token.
    # It must 'yield' the token, which format is [TOKEN-SYMBOL, VALUE].
    class_eval %{
    def yyparse(recv, mid)
      #{Racc_YY_Parse_Method}(recv, mid, _racc_setup(), false)
    end
    }

    def _racc_yyparse_rb(recv, mid, arg, c_debug)
      action_table, action_check, action_default, action_pointer,
      _,            _,            _,              _,
      _,            _,            token_table,    * = arg

      _racc_init_sysvars

      catch(:racc_end_parse) {
        until i = action_pointer[@racc_state[-1]]
          while act = _racc_evalact(action_default[@racc_state[-1]], arg)
            ;
          end
        end
        recv.__send__(mid) do |tok, val|
          unless tok
            @racc_t = 0
          else
            @racc_t = (token_table[tok] or 1)   # error token
          end
          @racc_val = val
          @racc_read_next = false

          i += @racc_t
          unless i >= 0 and
                 act = action_table[i] and
                 action_check[i] == @racc_state[-1]
            act = action_default[@racc_state[-1]]
          end
          while act = _racc_evalact(act, arg)
            ;
          end

          while !(i = action_pointer[@racc_state[-1]]) ||
                ! @racc_read_next ||
                @racc_t == 0  # $
            unless i and i += @racc_t and
                   i >= 0 and
                   act = action_table[i] and
                   action_check[i] == @racc_state[-1]
              act = action_default[@racc_state[-1]]
            end
            while act = _racc_evalact(act, arg)
              ;
            end
          end
        end
      }
    end

    ###
    ### common
    ###

    def _racc_evalact(act, arg)
      action_table, action_check, _, action_pointer,
      _,            _,            _, _,
      _,            _,            _, shift_n,
      reduce_n,     * = arg
      nerr = 0   # tmp

      if act > 0 and act < shift_n
        #
        # shift
        #
        if @racc_error_status > 0
          @racc_error_status -= 1 unless @racc_t <= 1 # error token or EOF
        end
        @racc_vstack.push @racc_val
        @racc_state.push act
        @racc_read_next = true
        if @yydebug
          @racc_tstack.push @racc_t
          racc_shift @racc_t, @racc_tstack, @racc_vstack
        end

      elsif act < 0 and act > -reduce_n
        #
        # reduce
        #
        code = catch(:racc_jump) {
          @racc_state.push _racc_do_reduce(arg, act)
          false
        }
        if code
          case code
          when 1 # yyerror
            @racc_user_yyerror = true   # user_yyerror
            return -reduce_n
          when 2 # yyaccept
            return shift_n
          else
            raise '[Racc Bug] unknown jump code'
          end
        end

      elsif act == shift_n
        #
        # accept
        #
        racc_accept if @yydebug
        throw :racc_end_parse, @racc_vstack[0]

      elsif act == -reduce_n
        #
        # error
        #
        case @racc_error_status
        when 0
          unless arg[21]    # user_yyerror
            nerr += 1
            on_error @racc_t, @racc_val, @racc_vstack
          end
        when 3
          if @racc_t == 0   # is $
            # We're at EOF, and another error occurred immediately after
            # attempting auto-recovery
            throw :racc_end_parse, nil
          end
          @racc_read_next = true
        end
        @racc_user_yyerror = false
        @racc_error_status = 3
        while true
          if i = action_pointer[@racc_state[-1]]
            i += 1   # error token
            if  i >= 0 and
                (act = action_table[i]) and
                action_check[i] == @racc_state[-1]
              break
            end
          end
          throw :racc_end_parse, nil if @racc_state.size <= 1
          @racc_state.pop
          @racc_vstack.pop
          if @yydebug
            @racc_tstack.pop
            racc_e_pop @racc_state, @racc_tstack, @racc_vstack
          end
        end
        return act

      else
        raise "[Racc Bug] unknown action #{act.inspect}"
      end

      racc_next_state(@racc_state[-1], @racc_state) if @yydebug

      nil
    end

    def _racc_do_reduce(arg, act)
      _,          _,            _,            _,
      goto_table, goto_check,   goto_default, goto_pointer,
      nt_base,    reduce_table, _,            _,
      _,          use_result,   * = arg

      state = @racc_state
      vstack = @racc_vstack
      tstack = @racc_tstack

      i = act * -3
      len       = reduce_table[i]
      reduce_to = reduce_table[i+1]
      method_id = reduce_table[i+2]
      void_array = []

      tmp_t = tstack[-len, len] if @yydebug
      tmp_v = vstack[-len, len]
      tstack[-len, len] = void_array if @yydebug
      vstack[-len, len] = void_array
      state[-len, len]  = void_array

      # tstack must be updated AFTER method call
      if use_result
        vstack.push __send__(method_id, tmp_v, vstack, tmp_v[0])
      else
        vstack.push __send__(method_id, tmp_v, vstack)
      end
      tstack.push reduce_to

      racc_reduce(tmp_t, reduce_to, tstack, vstack) if @yydebug

      k1 = reduce_to - nt_base
      if i = goto_pointer[k1]
        i += state[-1]
        if i >= 0 and (curstate = goto_table[i]) and goto_check[i] == k1
          return curstate
        end
      end
      goto_default[k1]
    end

    # This method is called when a parse error is found.
    #
    # ERROR_TOKEN_ID is an internal ID of token which caused error.
    # You can get string representation of this ID by calling
    # #token_to_str.
    #
    # ERROR_VALUE is a value of error token.
    #
    # value_stack is a stack of symbol values.
    # DO NOT MODIFY this object.
    #
    # This method raises ParseError by default.
    #
    # If this method returns, parsers enter "error recovering mode".
    def on_error(t, val, vstack)
      raise ParseError, sprintf("\nparse error on value %s (%s)",
                                val.inspect, token_to_str(t) || '?')
    end

    # Enter error recovering mode.
    # This method does not call #on_error.
    def yyerror
      throw :racc_jump, 1
    end

    # Exit parser.
    # Return value is Symbol_Value_Stack[0].
    def yyaccept
      throw :racc_jump, 2
    end

    # Leave error recovering mode.
    def yyerrok
      @racc_error_status = 0
    end

    # For debugging output
    def racc_read_token(t, tok, val)
      @racc_debug_out.print 'read    '
      @racc_debug_out.print tok.inspect, '(', racc_token2str(t), ') '
      @racc_debug_out.puts val.inspect
      @racc_debug_out.puts
    end

    def racc_shift(tok, tstack, vstack)
      @racc_debug_out.puts "shift   #{racc_token2str tok}"
      racc_print_stacks tstack, vstack
      @racc_debug_out.puts
    end

    def racc_reduce(toks, sim, tstack, vstack)
      out = @racc_debug_out
      out.print 'reduce '
      if toks.empty?
        out.print ' <none>'
      else
        toks.each {|t| out.print ' ', racc_token2str(t) }
      end
      out.puts " --> #{racc_token2str(sim)}"
      racc_print_stacks tstack, vstack
      @racc_debug_out.puts
    end

    def racc_accept
      @racc_debug_out.puts 'accept'
      @racc_debug_out.puts
    end

    def racc_e_pop(state, tstack, vstack)
      @racc_debug_out.puts 'error recovering mode: pop token'
      racc_print_states state
      racc_print_stacks tstack, vstack
      @racc_debug_out.puts
    end

    def racc_next_state(curstate, state)
      @racc_debug_out.puts  "goto    #{curstate}"
      racc_print_states state
      @racc_debug_out.puts
    end

    def racc_print_stacks(t, v)
      out = @racc_debug_out
      out.print '        ['
      t.each_index do |i|
        out.print ' (', racc_token2str(t[i]), ' ', v[i].inspect, ')'
      end
      out.puts ' ]'
    end

    def racc_print_states(s)
      out = @racc_debug_out
      out.print '        ['
      s.each {|st| out.print ' ', st }
      out.puts ' ]'
    end

    def racc_token2str(tok)
      self.class::Racc_token_to_s_table[tok] or
          raise "[Racc Bug] can't convert token #{tok} to string"
    end

    # Convert internal ID of token symbol to the string.
    def token_to_str(t)
      self.class::Racc_token_to_s_table[t]
    end

  end

end
#--
#
#
#
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
# see the file "COPYING".
#
#++

module Racc
  VERSION   = '1.5.2'
  Version = VERSION
  Copyright = 'Copyright (c) 1999-2006 Minero Aoki'
end
#--
#
#
#
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
# see the file "COPYING".
#
#++

unless Object.method_defined?(:__send)
  class Object
    alias __send __send__
  end
end

unless Object.method_defined?(:__send!)
  class Object
    alias __send! __send__
  end
end

unless Array.method_defined?(:map!)
  class Array
    if Array.method_defined?(:collect!)
      alias map! collect!
    else
      alias map! filter
    end
  end
end
#--
#
#
#
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
# see the file "COPYING".
#
#++

require 'racc/parser'

unless Object.method_defined?(:funcall)
  class Object
    alias funcall __send__
  end
end

module Racc

  StateTransitionTable = Struct.new(:action_table,
                                    :action_check,
                                    :action_default,
                                    :action_pointer,
                                    :goto_table,
                                    :goto_check,
                                    :goto_default,
                                    :goto_pointer,
                                    :token_table,
                                    :reduce_table,
                                    :reduce_n,
                                    :shift_n,
                                    :nt_base,
                                    :token_to_s_table,
                                    :use_result_var,
                                    :debug_parser)
  class StateTransitionTable   # reopen
    def StateTransitionTable.generate(states)
      StateTransitionTableGenerator.new(states).generate
    end

    def initialize(states)
      super()
      @states = states
      @grammar = states.grammar
      self.use_result_var = true
      self.debug_parser = true
    end

    attr_reader :states
    attr_reader :grammar

    def parser_class
      ParserClassGenerator.new(@states).generate
    end

    def token_value_table
      h = {}
      token_table().each do |sym, i|
        h[sym.value] = i
      end
      h
    end
  end


  class StateTransitionTableGenerator

    def initialize(states)
      @states = states
      @grammar = states.grammar
    end

    def generate
      t = StateTransitionTable.new(@states)
      gen_action_tables t, @states
      gen_goto_tables t, @grammar
      t.token_table = token_table(@grammar)
      t.reduce_table = reduce_table(@grammar)
      t.reduce_n = @states.reduce_n
      t.shift_n = @states.shift_n
      t.nt_base = @grammar.nonterminal_base
      t.token_to_s_table = @grammar.symbols.map {|sym| sym.to_s }
      t
    end

    def reduce_table(grammar)
      t = [0, 0, :racc_error]
      grammar.each_with_index do |rule, idx|
        next if idx == 0
        t.push rule.size
        t.push rule.target.ident
        t.push(if rule.action.empty?   # and @params.omit_action_call?
               then :_reduce_none
               else "_reduce_#{idx}".intern
               end)
      end
      t
    end

    def token_table(grammar)
      h = {}
      grammar.symboltable.terminals.each do |t|
        h[t] = t.ident
      end
      h
    end

    def gen_action_tables(t, states)
      t.action_table = yytable  = []
      t.action_check = yycheck  = []
      t.action_default = yydefact = []
      t.action_pointer = yypact   = []
      e1 = []
      e2 = []
      states.each do |state|
        yydefact.push act2actid(state.defact)
        if state.action.empty?
          yypact.push nil
          next
        end
        vector = []
        state.action.each do |tok, act|
          vector[tok.ident] = act2actid(act)
        end
        addent e1, vector, state.ident, yypact
      end
      set_table e1, e2, yytable, yycheck, yypact
    end

    def gen_goto_tables(t, grammar)
      t.goto_table   = yytable2  = []
      t.goto_check   = yycheck2  = []
      t.goto_pointer = yypgoto   = []
      t.goto_default = yydefgoto = []
      e1 = []
      e2 = []
      grammar.each_nonterminal do |tok|
        tmp = []

        # decide default
        freq = Array.new(@states.size, 0)
        @states.each do |state|
          st = state.goto_table[tok]
          if st
            st = st.ident
            freq[st] += 1
          end
          tmp[state.ident] = st
        end
        max = freq.max
        if max > 1
          default = freq.index(max)
          tmp.map! {|i| default == i ? nil : i }
        else
          default = nil
        end
        yydefgoto.push default

        # delete default value
        tmp.pop until tmp.last or tmp.empty?
        if tmp.compact.empty?
          # only default
          yypgoto.push nil
          next
        end

        addent e1, tmp, (tok.ident - grammar.nonterminal_base), yypgoto
      end
      set_table e1, e2, yytable2, yycheck2, yypgoto
    end

    def addent(all, arr, chkval, ptr)
      max = arr.size
      min = nil
      arr.each_with_index do |item, idx|
        if item
          min ||= idx
        end
      end
      ptr.push(-7777)    # mark
      arr = arr[min...max]
      all.push [arr, chkval, mkmapexp(arr), min, ptr.size - 1]
    end

    n = 2 ** 16
    begin
      Regexp.compile("a{#{n}}")
      RE_DUP_MAX = n
    rescue RegexpError
      n /= 2
      retry
    end

    def mkmapexp(arr)
      i = ii = 0
      as = arr.size
      map = String.new
      maxdup = RE_DUP_MAX
      curr = nil
      while i < as
        ii = i + 1
        if arr[i]
          ii += 1 while ii < as and arr[ii]
          curr = '-'
        else
          ii += 1 while ii < as and not arr[ii]
          curr = '.'
        end

        offset = ii - i
        if offset == 1
          map << curr
        else
          while offset > maxdup
            map << "#{curr}{#{maxdup}}"
            offset -= maxdup
          end
          map << "#{curr}{#{offset}}" if offset > 1
        end
        i = ii
      end
      Regexp.compile(map, 'n')
    end

    def set_table(entries, dummy, tbl, chk, ptr)
      upper = 0
      map = '-' * 10240

      # sort long to short
      entries.sort_by!.with_index {|a,i| [-a[0].size, i] }

      entries.each do |arr, chkval, expr, min, ptri|
        if upper + arr.size > map.size
          map << '-' * (arr.size + 1024)
        end
        idx = map.index(expr)
        ptr[ptri] = idx - min
        arr.each_with_index do |item, i|
          if item
            i += idx
            tbl[i] = item
            chk[i] = chkval
            map[i] = ?o
          end
        end
        upper = idx + arr.size
      end
    end

    def act2actid(act)
      case act
      when Shift  then act.goto_id
      when Reduce then -act.ruleid
      when Accept then @states.shift_n
      when Error  then @states.reduce_n * -1
      else
        raise "racc: fatal: wrong act type #{act.class} in action table"
      end
    end

  end


  class ParserClassGenerator

    def initialize(states)
      @states = states
      @grammar = states.grammar
    end

    def generate
      table = @states.state_transition_table
      c = Class.new(::Racc::Parser)
      c.const_set :Racc_arg, [table.action_table,
                              table.action_check,
                              table.action_default,
                              table.action_pointer,
                              table.goto_table,
                              table.goto_check,
                              table.goto_default,
                              table.goto_pointer,
                              table.nt_base,
                              table.reduce_table,
                              table.token_value_table,
                              table.shift_n,
                              table.reduce_n,
                              false]
      c.const_set :Racc_token_to_s_table, table.token_to_s_table
      c.const_set :Racc_debug_parser, true
      define_actions c
      c
    end

    private

    def define_actions(c)
      c.module_eval "def _reduce_none(vals, vstack) vals[0] end"
      @grammar.each do |rule|
        if rule.action.empty?
          c.funcall(:alias_method, "_reduce_#{rule.ident}", :_reduce_none)
        else
          c.funcall(:define_method, "_racc_action_#{rule.ident}", &rule.action.proc)
          c.module_eval(<<-End, __FILE__, __LINE__ + 1)
            def _reduce_#{rule.ident}(vals, vstack)
              _racc_action_#{rule.ident}(*vals)
            end
          End
        end
      end
    end

  end

end   # module Racc
def generate_parser_text_rb(target)
  return if File.exist?(srcfile(target))
  $stderr.puts "generating #{target}..."
  File.open(target, 'w') {|f|
    f.puts "module Racc"
    f.puts "  PARSER_TEXT = <<'__end_of_file__'"
    f.puts File.read(srcfile('parser.rb'))
    f.puts "__end_of_file__"
    f.puts "end"
  }
end

generate_parser_text_rb 'parser-text.rb'
#--
#
#
#
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
# see the file "COPYING".
#
#++

module Racc

  # An "indexed" set.  All items must respond to :ident.
  class ISet

    def initialize(a = [])
      @set = a
    end

    attr_reader :set

    def add(i)
      @set[i.ident] = i
    end

    def [](key)
      @set[key.ident]
    end

    def []=(key, val)
      @set[key.ident] = val
    end

    alias include? []
    alias key? []

    def update(other)
      s = @set
      o = other.set
      o.each_index do |idx|
        if t = o[idx]
          s[idx] = t
        end
      end
    end

    def update_a(a)
      s = @set
      a.each {|i| s[i.ident] = i }
    end

    def delete(key)
      i = @set[key.ident]
      @set[key.ident] = nil
      i
    end

    def each(&block)
      @set.compact.each(&block)
    end

    def to_a
      @set.compact
    end

    def to_s
      "[#{@set.compact.join(' ')}]"
    end

    alias inspect to_s

    def size
      @set.nitems
    end

    def empty?
      @set.nitems == 0
    end

    def clear
      @set.clear
    end

    def dup
      ISet.new(@set.dup)
    end

  end   # class ISet

end   # module Racc
require 'racc'
require 'racc/parser'
require 'racc/grammarfileparser'
require 'racc/parserfilegenerator'
require 'racc/logfilegenerator'
module Racc
  PARSER_TEXT = <<'__end_of_file__'
# frozen_string_literal: false
#--
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
#
# As a special exception, when this code is copied by Racc
# into a Racc output file, you may use that output file
# without restriction.
#++

require 'racc/info'

unless defined?(NotImplementedError)
  NotImplementedError = NotImplementError # :nodoc:
end

module Racc
  class ParseError < StandardError; end
end
unless defined?(::ParseError)
  ParseError = Racc::ParseError
end

# Racc is a LALR(1) parser generator.
# It is written in Ruby itself, and generates Ruby programs.
#
# == Command-line Reference
#
#     racc [-o<var>filename</var>] [--output-file=<var>filename</var>]
#          [-e<var>rubypath</var>] [--executable=<var>rubypath</var>]
#          [-v] [--verbose]
#          [-O<var>filename</var>] [--log-file=<var>filename</var>]
#          [-g] [--debug]
#          [-E] [--embedded]
#          [-l] [--no-line-convert]
#          [-c] [--line-convert-all]
#          [-a] [--no-omit-actions]
#          [-C] [--check-only]
#          [-S] [--output-status]
#          [--version] [--copyright] [--help] <var>grammarfile</var>
#
# [+grammarfile+]
#   Racc grammar file. Any extension is permitted.
# [-o+outfile+, --output-file=+outfile+]
#   A filename for output. default is <+filename+>.tab.rb
# [-O+filename+, --log-file=+filename+]
#   Place logging output in file +filename+.
#   Default log file name is <+filename+>.output.
# [-e+rubypath+, --executable=+rubypath+]
#   output executable file(mode 755). where +path+ is the Ruby interpreter.
# [-v, --verbose]
#   verbose mode. create +filename+.output file, like yacc's y.output file.
# [-g, --debug]
#   add debug code to parser class. To display debuggin information,
#   use this '-g' option and set @yydebug true in parser class.
# [-E, --embedded]
#   Output parser which doesn't need runtime files (racc/parser.rb).
# [-C, --check-only]
#   Check syntax of racc grammar file and quit.
# [-S, --output-status]
#   Print messages time to time while compiling.
# [-l, --no-line-convert]
#   turns off line number converting.
# [-c, --line-convert-all]
#   Convert line number of actions, inner, header and footer.
# [-a, --no-omit-actions]
#   Call all actions, even if an action is empty.
# [--version]
#   print Racc version and quit.
# [--copyright]
#   Print copyright and quit.
# [--help]
#   Print usage and quit.
#
# == Generating Parser Using Racc
#
# To compile Racc grammar file, simply type:
#
#   $ racc parse.y
#
# This creates Ruby script file "parse.tab.y". The -o option can change the output filename.
#
# == Writing A Racc Grammar File
#
# If you want your own parser, you have to write a grammar file.
# A grammar file contains the name of your parser class, grammar for the parser,
# user code, and anything else.
# When writing a grammar file, yacc's knowledge is helpful.
# If you have not used yacc before, Racc is not too difficult.
#
# Here's an example Racc grammar file.
#
#   class Calcparser
#   rule
#     target: exp { print val[0] }
#
#     exp: exp '+' exp
#        | exp '*' exp
#        | '(' exp ')'
#        | NUMBER
#   end
#
# Racc grammar files resemble yacc files.
# But (of course), this is Ruby code.
# yacc's $$ is the 'result', $0, $1... is
# an array called 'val', and $-1, $-2... is an array called '_values'.
#
# See the {Grammar File Reference}[rdoc-ref:lib/racc/rdoc/grammar.en.rdoc] for
# more information on grammar files.
#
# == Parser
#
# Then you must prepare the parse entry method. There are two types of
# parse methods in Racc, Racc::Parser#do_parse and Racc::Parser#yyparse
#
# Racc::Parser#do_parse is simple.
#
# It's yyparse() of yacc, and Racc::Parser#next_token is yylex().
# This method must returns an array like [TOKENSYMBOL, ITS_VALUE].
# EOF is [false, false].
# (TOKENSYMBOL is a Ruby symbol (taken from String#intern) by default.
# If you want to change this, see the grammar reference.
#
# Racc::Parser#yyparse is little complicated, but useful.
# It does not use Racc::Parser#next_token, instead it gets tokens from any iterator.
#
# For example, <code>yyparse(obj, :scan)</code> causes
# calling +obj#scan+, and you can return tokens by yielding them from +obj#scan+.
#
# == Debugging
#
# When debugging, "-v" or/and the "-g" option is helpful.
#
# "-v" creates verbose log file (.output).
# "-g" creates a "Verbose Parser".
# Verbose Parser prints the internal status when parsing.
# But it's _not_ automatic.
# You must use -g option and set +@yydebug+ to +true+ in order to get output.
# -g option only creates the verbose parser.
#
# === Racc reported syntax error.
#
# Isn't there too many "end"?
# grammar of racc file is changed in v0.10.
#
# Racc does not use '%' mark, while yacc uses huge number of '%' marks..
#
# === Racc reported "XXXX conflicts".
#
# Try "racc -v xxxx.y".
# It causes producing racc's internal log file, xxxx.output.
#
# === Generated parsers does not work correctly
#
# Try "racc -g xxxx.y".
# This command let racc generate "debugging parser".
# Then set @yydebug=true in your parser.
# It produces a working log of your parser.
#
# == Re-distributing Racc runtime
#
# A parser, which is created by Racc, requires the Racc runtime module;
# racc/parser.rb.
#
# Ruby 1.8.x comes with Racc runtime module,
# you need NOT distribute Racc runtime files.
#
# If you want to include the Racc runtime module with your parser.
# This can be done by using '-E' option:
#
#   $ racc -E -omyparser.rb myparser.y
#
# This command creates myparser.rb which `includes' Racc runtime.
# Only you must do is to distribute your parser file (myparser.rb).
#
# Note: parser.rb is ruby license, but your parser is not.
# Your own parser is completely yours.
module Racc

  unless defined?(Racc_No_Extensions)
    Racc_No_Extensions = false # :nodoc:
  end

  class Parser

    Racc_Runtime_Version = ::Racc::VERSION
    Racc_Runtime_Core_Version_R = ::Racc::VERSION

    begin
      if Object.const_defined?(:RUBY_ENGINE) and RUBY_ENGINE == 'jruby'
        require 'jruby'
        require 'racc/cparse-jruby.jar'
        com.headius.racc.Cparse.new.load(JRuby.runtime, false)
      else
        require 'racc/cparse'
      end

      unless new.respond_to?(:_racc_do_parse_c, true)
        raise LoadError, 'old cparse.so'
      end
      if Racc_No_Extensions
        raise LoadError, 'selecting ruby version of racc runtime core'
      end

      Racc_Main_Parsing_Routine    = :_racc_do_parse_c # :nodoc:
      Racc_YY_Parse_Method         = :_racc_yyparse_c # :nodoc:
      Racc_Runtime_Core_Version    = Racc_Runtime_Core_Version_C # :nodoc:
      Racc_Runtime_Type            = 'c' # :nodoc:
    rescue LoadError
      Racc_Main_Parsing_Routine    = :_racc_do_parse_rb
      Racc_YY_Parse_Method         = :_racc_yyparse_rb
      Racc_Runtime_Core_Version    = Racc_Runtime_Core_Version_R
      Racc_Runtime_Type            = 'ruby'
    end

    def Parser.racc_runtime_type # :nodoc:
      Racc_Runtime_Type
    end

    def _racc_setup
      @yydebug = false unless self.class::Racc_debug_parser
      @yydebug = false unless defined?(@yydebug)
      if @yydebug
        @racc_debug_out = $stderr unless defined?(@racc_debug_out)
        @racc_debug_out ||= $stderr
      end
      arg = self.class::Racc_arg
      arg[13] = true if arg.size < 14
      arg
    end

    def _racc_init_sysvars
      @racc_state  = [0]
      @racc_tstack = []
      @racc_vstack = []

      @racc_t = nil
      @racc_val = nil

      @racc_read_next = true

      @racc_user_yyerror = false
      @racc_error_status = 0
    end

    # The entry point of the parser. This method is used with #next_token.
    # If Racc wants to get token (and its value), calls next_token.
    #
    # Example:
    #     def parse
    #       @q = [[1,1],
    #             [2,2],
    #             [3,3],
    #             [false, '$']]
    #       do_parse
    #     end
    #
    #     def next_token
    #       @q.shift
    #     end
    class_eval %{
    def do_parse
      #{Racc_Main_Parsing_Routine}(_racc_setup(), false)
    end
    }

    # The method to fetch next token.
    # If you use #do_parse method, you must implement #next_token.
    #
    # The format of return value is [TOKEN_SYMBOL, VALUE].
    # +token-symbol+ is represented by Ruby's symbol by default, e.g. :IDENT
    # for 'IDENT'.  ";" (String) for ';'.
    #
    # The final symbol (End of file) must be false.
    def next_token
      raise NotImplementedError, "#{self.class}\#next_token is not defined"
    end

    def _racc_do_parse_rb(arg, in_debug)
      action_table, action_check, action_default, action_pointer,
      _,            _,            _,              _,
      _,            _,            token_table,    * = arg

      _racc_init_sysvars
      tok = act = i = nil

      catch(:racc_end_parse) {
        while true
          if i = action_pointer[@racc_state[-1]]
            if @racc_read_next
              if @racc_t != 0   # not EOF
                tok, @racc_val = next_token()
                unless tok      # EOF
                  @racc_t = 0
                else
                  @racc_t = (token_table[tok] or 1)   # error token
                end
                racc_read_token(@racc_t, tok, @racc_val) if @yydebug
                @racc_read_next = false
              end
            end
            i += @racc_t
            unless i >= 0 and
                   act = action_table[i] and
                   action_check[i] == @racc_state[-1]
              act = action_default[@racc_state[-1]]
            end
          else
            act = action_default[@racc_state[-1]]
          end
          while act = _racc_evalact(act, arg)
            ;
          end
        end
      }
    end

    # Another entry point for the parser.
    # If you use this method, you must implement RECEIVER#METHOD_ID method.
    #
    # RECEIVER#METHOD_ID is a method to get next token.
    # It must 'yield' the token, which format is [TOKEN-SYMBOL, VALUE].
    class_eval %{
    def yyparse(recv, mid)
      #{Racc_YY_Parse_Method}(recv, mid, _racc_setup(), false)
    end
    }

    def _racc_yyparse_rb(recv, mid, arg, c_debug)
      action_table, action_check, action_default, action_pointer,
      _,            _,            _,              _,
      _,            _,            token_table,    * = arg

      _racc_init_sysvars

      catch(:racc_end_parse) {
        until i = action_pointer[@racc_state[-1]]
          while act = _racc_evalact(action_default[@racc_state[-1]], arg)
            ;
          end
        end
        recv.__send__(mid) do |tok, val|
          unless tok
            @racc_t = 0
          else
            @racc_t = (token_table[tok] or 1)   # error token
          end
          @racc_val = val
          @racc_read_next = false

          i += @racc_t
          unless i >= 0 and
                 act = action_table[i] and
                 action_check[i] == @racc_state[-1]
            act = action_default[@racc_state[-1]]
          end
          while act = _racc_evalact(act, arg)
            ;
          end

          while !(i = action_pointer[@racc_state[-1]]) ||
                ! @racc_read_next ||
                @racc_t == 0  # $
            unless i and i += @racc_t and
                   i >= 0 and
                   act = action_table[i] and
                   action_check[i] == @racc_state[-1]
              act = action_default[@racc_state[-1]]
            end
            while act = _racc_evalact(act, arg)
              ;
            end
          end
        end
      }
    end

    ###
    ### common
    ###

    def _racc_evalact(act, arg)
      action_table, action_check, _, action_pointer,
      _,            _,            _, _,
      _,            _,            _, shift_n,
      reduce_n,     * = arg
      nerr = 0   # tmp

      if act > 0 and act < shift_n
        #
        # shift
        #
        if @racc_error_status > 0
          @racc_error_status -= 1 unless @racc_t <= 1 # error token or EOF
        end
        @racc_vstack.push @racc_val
        @racc_state.push act
        @racc_read_next = true
        if @yydebug
          @racc_tstack.push @racc_t
          racc_shift @racc_t, @racc_tstack, @racc_vstack
        end

      elsif act < 0 and act > -reduce_n
        #
        # reduce
        #
        code = catch(:racc_jump) {
          @racc_state.push _racc_do_reduce(arg, act)
          false
        }
        if code
          case code
          when 1 # yyerror
            @racc_user_yyerror = true   # user_yyerror
            return -reduce_n
          when 2 # yyaccept
            return shift_n
          else
            raise '[Racc Bug] unknown jump code'
          end
        end

      elsif act == shift_n
        #
        # accept
        #
        racc_accept if @yydebug
        throw :racc_end_parse, @racc_vstack[0]

      elsif act == -reduce_n
        #
        # error
        #
        case @racc_error_status
        when 0
          unless arg[21]    # user_yyerror
            nerr += 1
            on_error @racc_t, @racc_val, @racc_vstack
          end
        when 3
          if @racc_t == 0   # is $
            # We're at EOF, and another error occurred immediately after
            # attempting auto-recovery
            throw :racc_end_parse, nil
          end
          @racc_read_next = true
        end
        @racc_user_yyerror = false
        @racc_error_status = 3
        while true
          if i = action_pointer[@racc_state[-1]]
            i += 1   # error token
            if  i >= 0 and
                (act = action_table[i]) and
                action_check[i] == @racc_state[-1]
              break
            end
          end
          throw :racc_end_parse, nil if @racc_state.size <= 1
          @racc_state.pop
          @racc_vstack.pop
          if @yydebug
            @racc_tstack.pop
            racc_e_pop @racc_state, @racc_tstack, @racc_vstack
          end
        end
        return act

      else
        raise "[Racc Bug] unknown action #{act.inspect}"
      end

      racc_next_state(@racc_state[-1], @racc_state) if @yydebug

      nil
    end

    def _racc_do_reduce(arg, act)
      _,          _,            _,            _,
      goto_table, goto_check,   goto_default, goto_pointer,
      nt_base,    reduce_table, _,            _,
      _,          use_result,   * = arg

      state = @racc_state
      vstack = @racc_vstack
      tstack = @racc_tstack

      i = act * -3
      len       = reduce_table[i]
      reduce_to = reduce_table[i+1]
      method_id = reduce_table[i+2]
      void_array = []

      tmp_t = tstack[-len, len] if @yydebug
      tmp_v = vstack[-len, len]
      tstack[-len, len] = void_array if @yydebug
      vstack[-len, len] = void_array
      state[-len, len]  = void_array

      # tstack must be updated AFTER method call
      if use_result
        vstack.push __send__(method_id, tmp_v, vstack, tmp_v[0])
      else
        vstack.push __send__(method_id, tmp_v, vstack)
      end
      tstack.push reduce_to

      racc_reduce(tmp_t, reduce_to, tstack, vstack) if @yydebug

      k1 = reduce_to - nt_base
      if i = goto_pointer[k1]
        i += state[-1]
        if i >= 0 and (curstate = goto_table[i]) and goto_check[i] == k1
          return curstate
        end
      end
      goto_default[k1]
    end

    # This method is called when a parse error is found.
    #
    # ERROR_TOKEN_ID is an internal ID of token which caused error.
    # You can get string representation of this ID by calling
    # #token_to_str.
    #
    # ERROR_VALUE is a value of error token.
    #
    # value_stack is a stack of symbol values.
    # DO NOT MODIFY this object.
    #
    # This method raises ParseError by default.
    #
    # If this method returns, parsers enter "error recovering mode".
    def on_error(t, val, vstack)
      raise ParseError, sprintf("\nparse error on value %s (%s)",
                                val.inspect, token_to_str(t) || '?')
    end

    # Enter error recovering mode.
    # This method does not call #on_error.
    def yyerror
      throw :racc_jump, 1
    end

    # Exit parser.
    # Return value is Symbol_Value_Stack[0].
    def yyaccept
      throw :racc_jump, 2
    end

    # Leave error recovering mode.
    def yyerrok
      @racc_error_status = 0
    end

    # For debugging output
    def racc_read_token(t, tok, val)
      @racc_debug_out.print 'read    '
      @racc_debug_out.print tok.inspect, '(', racc_token2str(t), ') '
      @racc_debug_out.puts val.inspect
      @racc_debug_out.puts
    end

    def racc_shift(tok, tstack, vstack)
      @racc_debug_out.puts "shift   #{racc_token2str tok}"
      racc_print_stacks tstack, vstack
      @racc_debug_out.puts
    end

    def racc_reduce(toks, sim, tstack, vstack)
      out = @racc_debug_out
      out.print 'reduce '
      if toks.empty?
        out.print ' <none>'
      else
        toks.each {|t| out.print ' ', racc_token2str(t) }
      end
      out.puts " --> #{racc_token2str(sim)}"
      racc_print_stacks tstack, vstack
      @racc_debug_out.puts
    end

    def racc_accept
      @racc_debug_out.puts 'accept'
      @racc_debug_out.puts
    end

    def racc_e_pop(state, tstack, vstack)
      @racc_debug_out.puts 'error recovering mode: pop token'
      racc_print_states state
      racc_print_stacks tstack, vstack
      @racc_debug_out.puts
    end

    def racc_next_state(curstate, state)
      @racc_debug_out.puts  "goto    #{curstate}"
      racc_print_states state
      @racc_debug_out.puts
    end

    def racc_print_stacks(t, v)
      out = @racc_debug_out
      out.print '        ['
      t.each_index do |i|
        out.print ' (', racc_token2str(t[i]), ' ', v[i].inspect, ')'
      end
      out.puts ' ]'
    end

    def racc_print_states(s)
      out = @racc_debug_out
      out.print '        ['
      s.each {|st| out.print ' ', st }
      out.puts ' ]'
    end

    def racc_token2str(tok)
      self.class::Racc_token_to_s_table[tok] or
          raise "[Racc Bug] can't convert token #{tok} to string"
    end

    # Convert internal ID of token symbol to the string.
    def token_to_str(t)
      self.class::Racc_token_to_s_table[t]
    end

  end

end

__end_of_file__
end
#--
#
#
#
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
# see the file "COPYING".
#
#++

module Racc

  class DebugFlags
    def DebugFlags.parse_option_string(s)
      parse = rule = token = state = la = prec = conf = false
      s.split(//).each do |ch|
        case ch
        when 'p' then parse = true
        when 'r' then rule = true
        when 't' then token = true
        when 's' then state = true
        when 'l' then la = true
        when 'c' then prec = true
        when 'o' then conf = true
        else
          raise "unknown debug flag char: #{ch.inspect}"
        end
      end
      new(parse, rule, token, state, la, prec, conf)
    end

    def initialize(parse = false, rule = false, token = false, state = false,
                   la = false, prec = false, conf = false)
      @parse = parse
      @rule = rule
      @token = token
      @state = state
      @la = la
      @prec = prec
      @any = (parse || rule || token || state || la || prec)
      @status_logging = conf
    end

    attr_reader :parse
    attr_reader :rule
    attr_reader :token
    attr_reader :state
    attr_reader :la
    attr_reader :prec

    def any?
      @any
    end

    attr_reader :status_logging
  end

end
#--
#
#
#
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
# see the file "COPYING".
#
#++

module Racc
  class Error < StandardError; end
  class CompileError < Error; end
end
#--
#
#
#
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
# see the file "COPYING".
#
#++

require 'racc/iset'
require 'racc/statetransitiontable'
require 'racc/exception'
require 'forwardable'

module Racc

  # A table of LALR states.
  class States

    include Enumerable

    def initialize(grammar, debug_flags = DebugFlags.new)
      @grammar = grammar
      @symboltable = grammar.symboltable
      @d_state = debug_flags.state
      @d_la    = debug_flags.la
      @d_prec  = debug_flags.prec
      @states = []
      @statecache = {}
      @actions = ActionTable.new(@grammar, self)
      @nfa_computed = false
      @dfa_computed = false
    end

    attr_reader :grammar
    attr_reader :actions

    def size
      @states.size
    end

    def inspect
      '#<state table>'
    end

    alias to_s inspect

    def [](i)
      @states[i]
    end

    def each_state(&block)
      @states.each(&block)
    end

    alias each each_state

    def each_index(&block)
      @states.each_index(&block)
    end

    extend Forwardable

    def_delegator "@actions", :shift_n
    def_delegator "@actions", :reduce_n
    def_delegator "@actions", :nt_base

    def should_report_srconflict?
      srconflict_exist? and
          (n_srconflicts() != @grammar.n_expected_srconflicts)
    end

    def srconflict_exist?
      n_srconflicts() != 0
    end

    def n_srconflicts
      @n_srconflicts ||= inject(0) {|sum, st| sum + st.n_srconflicts }
    end

    def rrconflict_exist?
      n_rrconflicts() != 0
    end

    def n_rrconflicts
      @n_rrconflicts ||= inject(0) {|sum, st| sum + st.n_rrconflicts }
    end

    def state_transition_table
      @state_transition_table ||= StateTransitionTable.generate(self.dfa)
    end

    #
    # NFA (Non-deterministic Finite Automaton) Computation
    #

    public

    def nfa
      return self if @nfa_computed
      compute_nfa
      @nfa_computed = true
      self
    end

    private

    def compute_nfa
      @grammar.init
      # add state 0
      core_to_state  [ @grammar[0].ptrs[0] ]
      # generate LALR states
      cur = 0
      @gotos = []
      while cur < @states.size
        generate_states @states[cur]   # state is added here
        cur += 1
      end
      @actions.init
    end

    def generate_states(state)
      puts "dstate: #{state}" if @d_state

      table = {}
      state.closure.each do |ptr|
        if sym = ptr.dereference
          addsym table, sym, ptr.next
        end
      end
      table.each do |sym, core|
        puts "dstate: sym=#{sym} ncore=#{core}" if @d_state

        dest = core_to_state(core.to_a)
        state.goto_table[sym] = dest
        id = sym.nonterminal?() ? @gotos.size : nil
        g = Goto.new(id, sym, state, dest)
        @gotos.push g if sym.nonterminal?
        state.gotos[sym] = g
        puts "dstate: #{state.ident} --#{sym}--> #{dest.ident}" if @d_state

        # check infinite recursion
        if state.ident == dest.ident and state.closure.size == 1
          raise CompileError,
              sprintf("Infinite recursion: state %d, with rule %d",
                      state.ident, state.ptrs[0].rule.ident)
        end
      end
    end

    def addsym(table, sym, ptr)
      unless s = table[sym]
        table[sym] = s = ISet.new
      end
      s.add ptr
    end

    def core_to_state(core)
      #
      # convert CORE to a State object.
      # If matching state does not exist, create it and add to the table.
      #

      k = fingerprint(core)
      unless dest = @statecache[k]
        # not registered yet
        dest = State.new(@states.size, core)
        @states.push dest

        @statecache[k] = dest

        puts "core_to_state: create state   ID #{dest.ident}" if @d_state
      else
        if @d_state
          puts "core_to_state: dest is cached ID #{dest.ident}"
          puts "core_to_state: dest core #{dest.core.join(' ')}"
        end
      end

      dest
    end

    def fingerprint(arr)
      arr.map {|i| i.ident }.pack('L*')
    end

    #
    # DFA (Deterministic Finite Automaton) Generation
    #

    public

    def dfa
      return self if @dfa_computed
      nfa
      compute_dfa
      @dfa_computed = true
      self
    end

    private

    def compute_dfa
      la = lookahead()
      @states.each do |state|
        state.la = la
        resolve state
      end
      set_accept
      @states.each do |state|
        pack state
      end
      check_useless
    end

    def lookahead
      #
      # lookahead algorithm ver.3 -- from bison 1.26
      #

      gotos = @gotos
      if @d_la
        puts "\n--- goto ---"
        gotos.each_with_index {|g, i| print i, ' '; p g }
      end

      ### initialize_LA()
      ### set_goto_map()
      la_rules = []
      @states.each do |state|
        state.check_la la_rules
      end

      ### initialize_F()
      f     = create_tmap(gotos.size)
      reads = []
      edge  = []
      gotos.each do |goto|
        goto.to_state.goto_table.each do |t, st|
          if t.terminal?
            f[goto.ident] |= (1 << t.ident)
          elsif t.nullable?
            edge.push goto.to_state.gotos[t].ident
          end
        end
        if edge.empty?
          reads.push nil
        else
          reads.push edge
          edge = []
        end
      end
      digraph f, reads
      if @d_la
        puts "\n--- F1 (reads) ---"
        print_tab gotos, reads, f
      end

      ### build_relations()
      ### compute_FOLLOWS
      path = nil
      edge = []
      lookback = Array.new(la_rules.size, nil)
      includes = []
      gotos.each do |goto|
        goto.symbol.heads.each do |ptr|
          path = record_path(goto.from_state, ptr.rule)
          lastgoto = path.last
          st = lastgoto ? lastgoto.to_state : goto.from_state
          if st.conflict?
            addrel lookback, st.rruleid(ptr.rule), goto
          end
          path.reverse_each do |g|
            break if     g.symbol.terminal?
            edge.push    g.ident
            break unless g.symbol.nullable?
          end
        end
        if edge.empty?
          includes.push nil
        else
          includes.push edge
          edge = []
        end
      end
      includes = transpose(includes)
      digraph f, includes
      if @d_la
        puts "\n--- F2 (includes) ---"
        print_tab gotos, includes, f
      end

      ### compute_lookaheads
      la = create_tmap(la_rules.size)
      lookback.each_with_index do |arr, i|
        if arr
          arr.each do |g|
            la[i] |= f[g.ident]
          end
        end
      end
      if @d_la
        puts "\n--- LA (lookback) ---"
        print_tab la_rules, lookback, la
      end

      la
    end

    def create_tmap(size)
      Array.new(size, 0)   # use Integer as bitmap
    end

    def addrel(tbl, i, item)
      if a = tbl[i]
        a.push item
      else
        tbl[i] = [item]
      end
    end

    def record_path(begst, rule)
      st = begst
      path = []
      rule.symbols.each do |t|
        goto = st.gotos[t]
        path.push goto
        st = goto.to_state
      end
      path
    end

    def transpose(rel)
      new = Array.new(rel.size, nil)
      rel.each_with_index do |arr, idx|
        if arr
          arr.each do |i|
            addrel new, i, idx
          end
        end
      end
      new
    end

    def digraph(map, relation)
      n = relation.size
      index    = Array.new(n, nil)
      vertices = []
      @infinity = n + 2

      index.each_index do |i|
        if not index[i] and relation[i]
          traverse i, index, vertices, map, relation
        end
      end
    end

    def traverse(i, index, vertices, map, relation)
      vertices.push i
      index[i] = height = vertices.size

      if rp = relation[i]
        rp.each do |proci|
          unless index[proci]
            traverse proci, index, vertices, map, relation
          end
          if index[i] > index[proci]
            # circulative recursion !!!
            index[i] = index[proci]
          end
          map[i] |= map[proci]
        end
      end

      if index[i] == height
        while true
          proci = vertices.pop
          index[proci] = @infinity
          break if i == proci

          map[proci] |= map[i]
        end
      end
    end

    # for debug
    def print_atab(idx, tab)
      tab.each_with_index do |i,ii|
        printf '%-20s', idx[ii].inspect
        p i
      end
    end

    def print_tab(idx, rel, tab)
      tab.each_with_index do |bin,i|
        print i, ' ', idx[i].inspect, ' << '; p rel[i]
        print '  '
        each_t(@symboltable, bin) {|t| print ' ', t }
        puts
      end
    end

    # for debug
    def print_tab_i(idx, rel, tab, i)
      bin = tab[i]
      print i, ' ', idx[i].inspect, ' << '; p rel[i]
      print '  '
      each_t(@symboltable, bin) {|t| print ' ', t }
    end

    # for debug
    def printb(i)
      each_t(@symboltable, i) do |t|
        print t, ' '
      end
      puts
    end

    def each_t(tbl, set)
      0.upto( set.size ) do |i|
        (0..7).each do |ii|
          if set[idx = i * 8 + ii] == 1
            yield tbl[idx]
          end
        end
      end
    end

    #
    # resolve
    #

    def resolve(state)
      if state.conflict?
        resolve_rr state, state.ritems
        resolve_sr state, state.stokens
      else
        if state.rrules.empty?
          # shift
          state.stokens.each do |t|
            state.action[t] = @actions.shift(state.goto_table[t])
          end
        else
          # reduce
          state.defact = @actions.reduce(state.rrules[0])
        end
      end
    end

    def resolve_rr(state, r)
      r.each do |item|
        item.each_la(@symboltable) do |t|
          act = state.action[t]
          if act
            unless act.kind_of?(Reduce)
              raise "racc: fatal: #{act.class} in action table"
            end
            # Cannot resolve R/R conflict (on t).
            # Reduce with upper rule as default.
            state.rr_conflict act.rule, item.rule, t
          else
            # No conflict.
            state.action[t] = @actions.reduce(item.rule)
          end
        end
      end
    end

    def resolve_sr(state, s)
      s.each do |stok|
        goto = state.goto_table[stok]
        act = state.action[stok]

        unless act
          # no conflict
          state.action[stok] = @actions.shift(goto)
        else
          unless act.kind_of?(Reduce)
            puts 'DEBUG -------------------------------'
            p stok
            p act
            state.action.each do |k,v|
              print k.inspect, ' ', v.inspect, "\n"
            end
            raise "racc: fatal: #{act.class} in action table"
          end

          # conflict on stok

          rtok = act.rule.precedence
          case do_resolve_sr(stok, rtok)
          when :Reduce
            # action is already set

          when :Shift
            # overwrite
            act.decref
            state.action[stok] = @actions.shift(goto)

          when :Error
            act.decref
            state.action[stok] = @actions.error

          when :CantResolve
            # shift as default
            act.decref
            state.action[stok] = @actions.shift(goto)
            state.sr_conflict stok, act.rule
          end
        end
      end
    end

    ASSOC = {
      :Left     => :Reduce,
      :Right    => :Shift,
      :Nonassoc => :Error
    }

    def do_resolve_sr(stok, rtok)
      puts "resolve_sr: s/r conflict: rtok=#{rtok}, stok=#{stok}" if @d_prec

      unless rtok and rtok.precedence
        puts "resolve_sr: no prec for #{rtok}(R)" if @d_prec
        return :CantResolve
      end
      rprec = rtok.precedence

      unless stok and stok.precedence
        puts "resolve_sr: no prec for #{stok}(S)" if @d_prec
        return :CantResolve
      end
      sprec = stok.precedence

      ret = if rprec == sprec
              ASSOC[rtok.assoc] or
                  raise "racc: fatal: #{rtok}.assoc is not Left/Right/Nonassoc"
            else
              (rprec > sprec) ? (:Reduce) : (:Shift)
            end

      puts "resolve_sr: resolved as #{ret.id2name}" if @d_prec
      ret
    end

    #
    # complete
    #

    def set_accept
      anch = @symboltable.anchor
      init_state = @states[0].goto_table[@grammar.start]
      targ_state = init_state.action[anch].goto_state
      acc_state  = targ_state.action[anch].goto_state

      acc_state.action.clear
      acc_state.goto_table.clear
      acc_state.defact = @actions.accept
    end

    def pack(state)
      ### find most frequently used reduce rule
      act = state.action
      arr = Array.new(@grammar.size, 0)
      act.each do |t, a|
        arr[a.ruleid] += 1  if a.kind_of?(Reduce)
      end
      i = arr.max
      s = (i > 0) ? arr.index(i) : nil

      ### set & delete default action
      if s
        r = @actions.reduce(s)
        if not state.defact or state.defact == r
          act.delete_if {|t, a| a == r }
          state.defact = r
        end
      else
        state.defact ||= @actions.error
      end
    end

    def check_useless
      used = []
      @actions.each_reduce do |act|
        if not act or act.refn == 0
          act.rule.useless = true
        else
          t = act.rule.target
          used[t.ident] = t
        end
      end
      @symboltable.nt_base.upto(@symboltable.nt_max - 1) do |n|
        unless used[n]
          @symboltable[n].useless = true
        end
      end
    end

  end   # class StateTable


  # A LALR state.
  class State

    def initialize(ident, core)
      @ident = ident
      @core = core
      @goto_table = {}
      @gotos = {}
      @stokens = nil
      @ritems = nil
      @action = {}
      @defact = nil
      @rrconf = nil
      @srconf = nil

      @closure = make_closure(@core)
    end

    attr_reader :ident
    alias stateid ident
    alias hash ident

    attr_reader :core
    attr_reader :closure

    attr_reader :goto_table
    attr_reader :gotos

    attr_reader :stokens
    attr_reader :ritems
    attr_reader :rrules

    attr_reader :action
    attr_accessor :defact   # default action

    attr_reader :rrconf
    attr_reader :srconf

    def inspect
      "<state #{@ident}>"
    end

    alias to_s inspect

    def ==(oth)
      @ident == oth.ident
    end

    alias eql? ==

    def make_closure(core)
      set = ISet.new
      core.each do |ptr|
        set.add ptr
        if t = ptr.dereference and t.nonterminal?
          set.update_a t.expand
        end
      end
      set.to_a
    end

    def check_la(la_rules)
      @conflict = false
      s = []
      r = []
      @closure.each do |ptr|
        if t = ptr.dereference
          if t.terminal?
            s[t.ident] = t
            if t.ident == 1    # $error
              @conflict = true
            end
          end
        else
          r.push ptr.rule
        end
      end
      unless r.empty?
        if not s.empty? or r.size > 1
          @conflict = true
        end
      end
      s.compact!
      @stokens  = s
      @rrules = r

      if @conflict
        @la_rules_i = la_rules.size
        @la_rules = r.map {|i| i.ident }
        la_rules.concat r
      else
        @la_rules_i = @la_rules = nil
      end
    end

    def conflict?
      @conflict
    end

    def rruleid(rule)
      if i = @la_rules.index(rule.ident)
        @la_rules_i + i
      else
        puts '/// rruleid'
        p self
        p rule
        p @rrules
        p @la_rules_i
        raise 'racc: fatal: cannot get reduce rule id'
      end
    end

    def la=(la)
      return unless @conflict
      i = @la_rules_i
      @ritems = r = []
      @rrules.each do |rule|
        r.push Item.new(rule, la[i])
        i += 1
      end
    end

    def rr_conflict(high, low, ctok)
      c = RRconflict.new(@ident, high, low, ctok)

      @rrconf ||= {}
      if a = @rrconf[ctok]
        a.push c
      else
        @rrconf[ctok] = [c]
      end
    end

    def sr_conflict(shift, reduce)
      c = SRconflict.new(@ident, shift, reduce)

      @srconf ||= {}
      if a = @srconf[shift]
        a.push c
      else
        @srconf[shift] = [c]
      end
    end

    def n_srconflicts
      @srconf ? @srconf.size : 0
    end

    def n_rrconflicts
      @rrconf ? @rrconf.size : 0
    end

  end   # class State


  #
  # Represents a transition on the grammar.
  # "Real goto" means a transition by nonterminal,
  # but this class treats also terminal's.
  # If one is a terminal transition, .ident returns nil.
  #
  class Goto
    def initialize(ident, sym, from, to)
      @ident      = ident
      @symbol     = sym
      @from_state = from
      @to_state   = to
    end

    attr_reader :ident
    attr_reader :symbol
    attr_reader :from_state
    attr_reader :to_state

    def inspect
      "(#{@from_state.ident}-#{@symbol}->#{@to_state.ident})"
    end
  end


  # LALR item.  A set of rule and its lookahead tokens.
  class Item
    def initialize(rule, la)
      @rule = rule
      @la  = la
    end

    attr_reader :rule
    attr_reader :la

    def each_la(tbl)
      la = @la
      0.upto(la.size - 1) do |i|
        (0..7).each do |ii|
          if la[idx = i * 8 + ii] == 1
            yield tbl[idx]
          end
        end
      end
    end
  end


  # The table of LALR actions. Actions are either of
  # Shift, Reduce, Accept and Error.
  class ActionTable

    def initialize(rt, st)
      @grammar = rt
      @statetable = st

      @reduce = []
      @shift = []
      @accept = nil
      @error = nil
    end

    def init
      @grammar.each do |rule|
        @reduce.push Reduce.new(rule)
      end
      @statetable.each do |state|
        @shift.push Shift.new(state)
      end
      @accept = Accept.new
      @error = Error.new
    end

    def reduce_n
      @reduce.size
    end

    def reduce(i)
      case i
      when Rule    then i = i.ident
      when Integer then ;
      else
        raise "racc: fatal: wrong class #{i.class} for reduce"
      end

      r = @reduce[i] or raise "racc: fatal: reduce action #{i.inspect} not exist"
      r.incref
      r
    end

    def each_reduce(&block)
      @reduce.each(&block)
    end

    def shift_n
      @shift.size
    end

    def shift(i)
      case i
      when State   then i = i.ident
      when Integer then ;
      else
        raise "racc: fatal: wrong class #{i.class} for shift"
      end

      @shift[i] or raise "racc: fatal: shift action #{i} does not exist"
    end

    def each_shift(&block)
      @shift.each(&block)
    end

    attr_reader :accept
    attr_reader :error

  end


  class Shift
    def initialize(goto)
      @goto_state = goto
    end

    attr_reader :goto_state

    def goto_id
      @goto_state.ident
    end

    def inspect
      "<shift #{@goto_state.ident}>"
    end
  end


  class Reduce
    def initialize(rule)
      @rule = rule
      @refn = 0
    end

    attr_reader :rule
    attr_reader :refn

    def ruleid
      @rule.ident
    end

    def inspect
      "<reduce #{@rule.ident}>"
    end

    def incref
      @refn += 1
    end

    def decref
      @refn -= 1
      raise 'racc: fatal: act.refn < 0' if @refn < 0
    end
  end

  class Accept
    def inspect
      "<accept>"
    end
  end

  class Error
    def inspect
      "<error>"
    end
  end

  class SRconflict
    def initialize(sid, shift, reduce)
      @stateid = sid
      @shift   = shift
      @reduce  = reduce
    end

    attr_reader :stateid
    attr_reader :shift
    attr_reader :reduce

    def to_s
      sprintf('state %d: S/R conflict rule %d reduce and shift %s',
              @stateid, @reduce.ruleid, @shift.to_s)
    end
  end

  class RRconflict
    def initialize(sid, high, low, tok)
      @stateid   = sid
      @high_prec = high
      @low_prec  = low
      @token     = tok
    end

    attr_reader :stateid
    attr_reader :high_prec
    attr_reader :low_prec
    attr_reader :token

    def to_s
      sprintf('state %d: R/R conflict with rule %d and %d on %s',
              @stateid, @high_prec.ident, @low_prec.ident, @token.to_s)
    end
  end

end
#--
#
#
#
# Copyright (c) 1999-2006 Minero Aoki
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
# see the file "COPYING".
#
#++

module Racc

  class LogFileGenerator

    def initialize(states, debug_flags = DebugFlags.new)
      @states = states
      @grammar = states.grammar
      @debug_flags = debug_flags
    end

    def output(out)
      output_conflict out; out.puts
      output_useless  out; out.puts
      output_rule     out; out.puts
      output_token    out; out.puts
      output_state    out
    end

    #
    # Warnings
    #

    def output_conflict(out)
      @states.each do |state|
        if state.srconf
          out.printf "state %d contains %d shift/reduce conflicts\n",
                     state.stateid, state.srconf.size
        end
        if state.rrconf
          out.printf "state %d contains %d reduce/reduce conflicts\n",
                     state.stateid, state.rrconf.size
        end
      end
    end

    def output_useless(out)
      @grammar.each do |rl|
        if rl.useless?
          out.printf "rule %d (%s) never reduced\n",
                     rl.ident, rl.target.to_s
        end
      end
      @grammar.each_nonterminal do |t|
        if t.useless?
          out.printf "useless nonterminal %s\n", t.to_s
        end
      end
    end

    #
    # States
    #

    def output_state(out)
      out << "--------- State ---------\n"

      showall = @debug_flags.la || @debug_flags.state
      @states.each do |state|
        out << "\nstate #{state.ident}\n\n"

        (showall ? state.closure : state.core).each do |ptr|
          pointer_out(out, ptr) if ptr.rule.ident != 0 or showall
        end
        out << "\n"

        action_out out, state
      end
    end

    def pointer_out(out, ptr)
      buf = sprintf("%4d) %s :", ptr.rule.ident, ptr.rule.target.to_s)
      ptr.rule.symbols.each_with_index do |tok, idx|
        buf << ' _' if idx == ptr.index
        buf << ' ' << tok.to_s
      end
      buf << ' _' if ptr.reduce?
      out.puts buf
    end

    def action_out(f, state)
      sr = state.srconf && state.srconf.dup
      rr = state.rrconf && state.rrconf.dup
      acts = state.action
      keys = acts.keys
      keys.sort! {|a,b| a.ident <=> b.ident }

      [ Shift, Reduce, Error, Accept ].each do |klass|
        keys.delete_if do |tok|
          act = acts[tok]
          if act.kind_of?(klass)
            outact f, tok, act
            if sr and c = sr.delete(tok)
              outsrconf f, c
            end
            if rr and c = rr.delete(tok)
              outrrconf f, c
            end

            true
          else
            false
          end
        end
      end
      sr.each {|tok, c| outsrconf f, c } if sr
      rr.each {|tok, c| outrrconf f, c } if rr

      act = state.defact
      if not act.kind_of?(Error) or @debug_flags.any?
        outact f, '$default', act
      end

      f.puts
      state.goto_table.each do |t, st|
        if t.nonterminal?
          f.printf "  %-12s  go to state %d\n", t.to_s, st.ident
        end
      end
    end

    def outact(f, t, act)
      case act
      when Shift
        f.printf "  %-12s  shift, and go to state %d\n",
                 t.to_s, act.goto_id
      when Reduce
        f.printf "  %-12s  reduce using rule %d (%s)\n",
                 t.to_s, act.ruleid, act.rule.target.to_s
      when Accept
        f.printf "  %-12s  accept\n", t.to_s
      when Error
        f.printf "  %-12s  error\n", t.to_s
      else
        raise "racc: fatal: wrong act for outact: act=#{act}(#{act.class})"
      end
    end

    def outsrconf(f, confs)
      confs.each do |c|
        r = c.reduce
        f.printf "  %-12s  [reduce using rule %d (%s)]\n",
                 c.shift.to_s, r.ident, r.target.to_s
      end
    end

    def outrrconf(f, confs)
      confs.each do |c|
        r = c.low_prec
        f.printf "  %-12s  [reduce using rule %d (%s)]\n",
                 c.token.to_s, r.ident, r.target.to_s
      end
    end

    #
    # Rules
    #

    def output_rule(out)
      out.print "-------- Grammar --------\n\n"
      @grammar.each do |rl|
        if @debug_flags.any? or rl.ident != 0
          out.printf "rule %d %s: %s\n",
                     rl.ident, rl.target.to_s, rl.symbols.join(' ')
        end
      end
    end

    #
    # Tokens
    #

    def output_token(out)
      out.print "------- Symbols -------\n\n"

      out.print "**Nonterminals, with rules where they appear\n\n"
      @grammar.each_nonterminal do |t|
        tmp = <<SRC
  %s (%d)
    on right: %s
    on left : %s
SRC
        out.printf tmp, t.to_s, t.ident,
                   symbol_locations(t.locate).join(' '),
                   symbol_locations(t.heads).join(' ')
      end

      out.print "\n**Terminals, with rules where they appear\n\n"
      @grammar.each_terminal do |t|
        out.printf "  %s (%d) %s\n",
                   t.to_s, t.ident, symbol_locations(t.locate).join(' ')
      end
    end

    def symbol_locations(locs)
      locs.map {|loc| loc.rule.ident }.reject {|n| n == 0 }.uniq
    end

  end

end   # module Racc
# frozen_string_literal: true
require 'uri'
require 'stringio'
require 'time'

module URI
  # Allows the opening of various resources including URIs.
  #
  # If the first argument responds to the 'open' method, 'open' is called on
  # it with the rest of the arguments.
  #
  # If the first argument is a string that begins with <code>(protocol)://<code>, it is parsed by
  # URI.parse.  If the parsed object responds to the 'open' method,
  # 'open' is called on it with the rest of the arguments.
  #
  # Otherwise, Kernel#open is called.
  #
  # OpenURI::OpenRead#open provides URI::HTTP#open, URI::HTTPS#open and
  # URI::FTP#open, Kernel#open.
  #
  # We can accept URIs and strings that begin with http://, https:// and
  # ftp://. In these cases, the opened file object is extended by OpenURI::Meta.
  def self.open(name, *rest, &block)
    if name.respond_to?(:open)
      name.open(*rest, &block)
    elsif name.respond_to?(:to_str) &&
          %r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} =~ name &&
          (uri = URI.parse(name)).respond_to?(:open)
      uri.open(*rest, &block)
    else
      super
    end
  end
end

# OpenURI is an easy-to-use wrapper for Net::HTTP, Net::HTTPS and Net::FTP.
#
# == Example
#
# It is possible to open an http, https or ftp URL as though it were a file:
#
#   URI.open("http://www.ruby-lang.org/") {|f|
#     f.each_line {|line| p line}
#   }
#
# The opened file has several getter methods for its meta-information, as
# follows, since it is extended by OpenURI::Meta.
#
#   URI.open("http://www.ruby-lang.org/en") {|f|
#     f.each_line {|line| p line}
#     p f.base_uri         # <URI::HTTP:0x40e6ef2 URL:http://www.ruby-lang.org/en/>
#     p f.content_type     # "text/html"
#     p f.charset          # "iso-8859-1"
#     p f.content_encoding # []
#     p f.last_modified    # Thu Dec 05 02:45:02 UTC 2002
#   }
#
# Additional header fields can be specified by an optional hash argument.
#
#   URI.open("http://www.ruby-lang.org/en/",
#     "User-Agent" => "Ruby/#{RUBY_VERSION}",
#     "From" => "foo@bar.invalid",
#     "Referer" => "http://www.ruby-lang.org/") {|f|
#     # ...
#   }
#
# The environment variables such as http_proxy, https_proxy and ftp_proxy
# are in effect by default. Here we disable proxy:
#
#   URI.open("http://www.ruby-lang.org/en/", :proxy => nil) {|f|
#     # ...
#   }
#
# See OpenURI::OpenRead.open and URI.open for more on available options.
#
# URI objects can be opened in a similar way.
#
#   uri = URI.parse("http://www.ruby-lang.org/en/")
#   uri.open {|f|
#     # ...
#   }
#
# URI objects can be read directly. The returned string is also extended by
# OpenURI::Meta.
#
#   str = uri.read
#   p str.base_uri
#
# Author:: Tanaka Akira <akr@m17n.org>

module OpenURI
  Options = {
    :proxy => true,
    :proxy_http_basic_authentication => true,
    :progress_proc => true,
    :content_length_proc => true,
    :http_basic_authentication => true,
    :read_timeout => true,
    :open_timeout => true,
    :ssl_ca_cert => nil,
    :ssl_verify_mode => nil,
    :ftp_active_mode => false,
    :redirect => true,
    :encoding => nil,
  }

  def OpenURI.check_options(options) # :nodoc:
    options.each {|k, v|
      next unless Symbol === k
      unless Options.include? k
        raise ArgumentError, "unrecognized option: #{k}"
      end
    }
  end

  def OpenURI.scan_open_optional_arguments(*rest) # :nodoc:
    if !rest.empty? && (String === rest.first || Integer === rest.first)
      mode = rest.shift
      if !rest.empty? && Integer === rest.first
        perm = rest.shift
      end
    end
    return mode, perm, rest
  end

  def OpenURI.open_uri(name, *rest) # :nodoc:
    uri = URI::Generic === name ? name : URI.parse(name)
    mode, _, rest = OpenURI.scan_open_optional_arguments(*rest)
    options = rest.shift if !rest.empty? && Hash === rest.first
    raise ArgumentError.new("extra arguments") if !rest.empty?
    options ||= {}
    OpenURI.check_options(options)

    if /\Arb?(?:\Z|:([^:]+))/ =~ mode
      encoding, = $1,Encoding.find($1) if $1
      mode = nil
    end
    if options.has_key? :encoding
      if !encoding.nil?
        raise ArgumentError, "encoding specified twice"
      end
      encoding = Encoding.find(options[:encoding])
    end

    unless mode == nil ||
           mode == 'r' || mode == 'rb' ||
           mode == File::RDONLY
      raise ArgumentError.new("invalid access mode #{mode} (#{uri.class} resource is read only.)")
    end

    io = open_loop(uri, options)
    io.set_encoding(encoding) if encoding
    if block_given?
      begin
        yield io
      ensure
        if io.respond_to? :close!
          io.close! # Tempfile
        else
          io.close if !io.closed?
        end
      end
    else
      io
    end
  end

  def OpenURI.open_loop(uri, options) # :nodoc:
    proxy_opts = []
    proxy_opts << :proxy_http_basic_authentication if options.include? :proxy_http_basic_authentication
    proxy_opts << :proxy if options.include? :proxy
    proxy_opts.compact!
    if 1 < proxy_opts.length
      raise ArgumentError, "multiple proxy options specified"
    end
    case proxy_opts.first
    when :proxy_http_basic_authentication
      opt_proxy, proxy_user, proxy_pass = options.fetch(:proxy_http_basic_authentication)
      proxy_user = proxy_user.to_str
      proxy_pass = proxy_pass.to_str
      if opt_proxy == true
        raise ArgumentError.new("Invalid authenticated proxy option: #{options[:proxy_http_basic_authentication].inspect}")
      end
    when :proxy
      opt_proxy = options.fetch(:proxy)
      proxy_user = nil
      proxy_pass = nil
    when nil
      opt_proxy = true
      proxy_user = nil
      proxy_pass = nil
    end
    case opt_proxy
    when true
      find_proxy = lambda {|u| pxy = u.find_proxy; pxy ? [pxy, nil, nil] : nil}
    when nil, false
      find_proxy = lambda {|u| nil}
    when String
      opt_proxy = URI.parse(opt_proxy)
      find_proxy = lambda {|u| [opt_proxy, proxy_user, proxy_pass]}
    when URI::Generic
      find_proxy = lambda {|u| [opt_proxy, proxy_user, proxy_pass]}
    else
      raise ArgumentError.new("Invalid proxy option: #{opt_proxy}")
    end

    uri_set = {}
    buf = nil
    while true
      redirect = catch(:open_uri_redirect) {
        buf = Buffer.new
        uri.buffer_open(buf, find_proxy.call(uri), options)
        nil
      }
      if redirect
        if redirect.relative?
          # Although it violates RFC2616, Location: field may have relative
          # URI.  It is converted to absolute URI using uri as a base URI.
          redirect = uri + redirect
        end
        if !options.fetch(:redirect, true)
          raise HTTPRedirect.new(buf.io.status.join(' '), buf.io, redirect)
        end
        unless OpenURI.redirectable?(uri, redirect)
          raise "redirection forbidden: #{uri} -> #{redirect}"
        end
        if options.include? :http_basic_authentication
          # send authentication only for the URI directly specified.
          options = options.dup
          options.delete :http_basic_authentication
        end
        uri = redirect
        raise "HTTP redirection loop: #{uri}" if uri_set.include? uri.to_s
        uri_set[uri.to_s] = true
      else
        break
      end
    end
    io = buf.io
    io.base_uri = uri
    io
  end

  def OpenURI.redirectable?(uri1, uri2) # :nodoc:
    # This test is intended to forbid a redirection from http://... to
    # file:///etc/passwd, file:///dev/zero, etc.  CVE-2011-1521
    # https to http redirect is also forbidden intentionally.
    # It avoids sending secure cookie or referer by non-secure HTTP protocol.
    # (RFC 2109 4.3.1, RFC 2965 3.3, RFC 2616 15.1.3)
    # However this is ad hoc.  It should be extensible/configurable.
    uri1.scheme.downcase == uri2.scheme.downcase ||
    (/\A(?:http|ftp)\z/i =~ uri1.scheme && /\A(?:https?|ftp)\z/i =~ uri2.scheme)
  end

  def OpenURI.open_http(buf, target, proxy, options) # :nodoc:
    if proxy
      proxy_uri, proxy_user, proxy_pass = proxy
      raise "Non-HTTP proxy URI: #{proxy_uri}" if proxy_uri.class != URI::HTTP
    end

    if target.userinfo
      raise ArgumentError, "userinfo not supported.  [RFC3986]"
    end

    header = {}
    options.each {|k, v| header[k] = v if String === k }

    require 'net/http'
    klass = Net::HTTP
    if URI::HTTP === target
      # HTTP or HTTPS
      if proxy
        unless proxy_user && proxy_pass
          proxy_user, proxy_pass = proxy_uri.userinfo.split(':') if proxy_uri.userinfo
        end
        if proxy_user && proxy_pass
          klass = Net::HTTP::Proxy(proxy_uri.hostname, proxy_uri.port, proxy_user, proxy_pass)
        else
          klass = Net::HTTP::Proxy(proxy_uri.hostname, proxy_uri.port)
        end
      end
      target_host = target.hostname
      target_port = target.port
      request_uri = target.request_uri
    else
      # FTP over HTTP proxy
      target_host = proxy_uri.hostname
      target_port = proxy_uri.port
      request_uri = target.to_s
      if proxy_user && proxy_pass
        header["Proxy-Authorization"] =
                        'Basic ' + ["#{proxy_user}:#{proxy_pass}"].pack('m0')
      end
    end

    http = proxy ? klass.new(target_host, target_port) : klass.new(target_host, target_port, nil)
    if target.class == URI::HTTPS
      require 'net/https'
      http.use_ssl = true
      http.verify_mode = options[:ssl_verify_mode] || OpenSSL::SSL::VERIFY_PEER
      store = OpenSSL::X509::Store.new
      if options[:ssl_ca_cert]
        Array(options[:ssl_ca_cert]).each do |cert|
          if File.directory? cert
            store.add_path cert
          else
            store.add_file cert
          end
        end
      else
        store.set_default_paths
      end
      http.cert_store = store
    end
    if options.include? :read_timeout
      http.read_timeout = options[:read_timeout]
    end
    if options.include? :open_timeout
      http.open_timeout = options[:open_timeout]
    end

    resp = nil
    http.start {
      req = Net::HTTP::Get.new(request_uri, header)
      if options.include? :http_basic_authentication
        user, pass = options[:http_basic_authentication]
        req.basic_auth user, pass
      end
      http.request(req) {|response|
        resp = response
        if options[:content_length_proc] && Net::HTTPSuccess === resp
          if resp.key?('Content-Length')
            options[:content_length_proc].call(resp['Content-Length'].to_i)
          else
            options[:content_length_proc].call(nil)
          end
        end
        resp.read_body {|str|
          buf << str
          if options[:progress_proc] && Net::HTTPSuccess === resp
            options[:progress_proc].call(buf.size)
          end
          str.clear
        }
      }
    }
    io = buf.io
    io.rewind
    io.status = [resp.code, resp.message]
    resp.each_name {|name| buf.io.meta_add_field2 name, resp.get_fields(name) }
    case resp
    when Net::HTTPSuccess
    when Net::HTTPMovedPermanently, # 301
         Net::HTTPFound, # 302
         Net::HTTPSeeOther, # 303
         Net::HTTPTemporaryRedirect # 307
      begin
        loc_uri = URI.parse(resp['location'])
      rescue URI::InvalidURIError
        raise OpenURI::HTTPError.new(io.status.join(' ') + ' (Invalid Location URI)', io)
      end
      throw :open_uri_redirect, loc_uri
    else
      raise OpenURI::HTTPError.new(io.status.join(' '), io)
    end
  end

  class HTTPError < StandardError
    def initialize(message, io)
      super(message)
      @io = io
    end
    attr_reader :io
  end

  # Raised on redirection,
  # only occurs when +redirect+ option for HTTP is +false+.
  class HTTPRedirect < HTTPError
    def initialize(message, io, uri)
      super(message, io)
      @uri = uri
    end
    attr_reader :uri
  end

  class Buffer # :nodoc: all
    def initialize
      @io = StringIO.new
      @size = 0
    end
    attr_reader :size

    StringMax = 10240
    def <<(str)
      @io << str
      @size += str.length
      if StringIO === @io && StringMax < @size
        require 'tempfile'
        io = Tempfile.new('open-uri')
        io.binmode
        Meta.init io, @io if Meta === @io
        io << @io.string
        @io = io
      end
    end

    def io
      Meta.init @io unless Meta === @io
      @io
    end
  end

  # Mixin for holding meta-information.
  module Meta
    def Meta.init(obj, src=nil) # :nodoc:
      obj.extend Meta
      obj.instance_eval {
        @base_uri = nil
        @meta = {} # name to string.  legacy.
        @metas = {} # name to array of strings.
      }
      if src
        obj.status = src.status
        obj.base_uri = src.base_uri
        src.metas.each {|name, values|
          obj.meta_add_field2(name, values)
        }
      end
    end

    # returns an Array that consists of status code and message.
    attr_accessor :status

    # returns a URI that is the base of relative URIs in the data.
    # It may differ from the URI supplied by a user due to redirection.
    attr_accessor :base_uri

    # returns a Hash that represents header fields.
    # The Hash keys are downcased for canonicalization.
    # The Hash values are a field body.
    # If there are multiple field with same field name,
    # the field values are concatenated with a comma.
    attr_reader :meta

    # returns a Hash that represents header fields.
    # The Hash keys are downcased for canonicalization.
    # The Hash value are an array of field values.
    attr_reader :metas

    def meta_setup_encoding # :nodoc:
      charset = self.charset
      enc = nil
      if charset
        begin
          enc = Encoding.find(charset)
        rescue ArgumentError
        end
      end
      enc = Encoding::ASCII_8BIT unless enc
      if self.respond_to? :force_encoding
        self.force_encoding(enc)
      elsif self.respond_to? :string
        self.string.force_encoding(enc)
      else # Tempfile
        self.set_encoding enc
      end
    end

    def meta_add_field2(name, values) # :nodoc:
      name = name.downcase
      @metas[name] = values
      @meta[name] = values.join(', ')
      meta_setup_encoding if name == 'content-type'
    end

    def meta_add_field(name, value) # :nodoc:
      meta_add_field2(name, [value])
    end

    # returns a Time that represents the Last-Modified field.
    def last_modified
      if vs = @metas['last-modified']
        v = vs.join(', ')
        Time.httpdate(v)
      else
        nil
      end
    end

    # :stopdoc:
    RE_LWS = /[\r\n\t ]+/n
    RE_TOKEN = %r{[^\x00- ()<>@,;:\\"/\[\]?={}\x7f]+}n
    RE_QUOTED_STRING = %r{"(?:[\r\n\t !#-\[\]-~\x80-\xff]|\\[\x00-\x7f])*"}n
    RE_PARAMETERS = %r{(?:;#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?=#{RE_LWS}?(?:#{RE_TOKEN}|#{RE_QUOTED_STRING})#{RE_LWS}?)*}n
    # :startdoc:

    def content_type_parse # :nodoc:
      vs = @metas['content-type']
      # The last (?:;#{RE_LWS}?)? matches extra ";" which violates RFC2045.
      if vs && %r{\A#{RE_LWS}?(#{RE_TOKEN})#{RE_LWS}?/(#{RE_TOKEN})#{RE_LWS}?(#{RE_PARAMETERS})(?:;#{RE_LWS}?)?\z}no =~ vs.join(', ')
        type = $1.downcase
        subtype = $2.downcase
        parameters = []
        $3.scan(/;#{RE_LWS}?(#{RE_TOKEN})#{RE_LWS}?=#{RE_LWS}?(?:(#{RE_TOKEN})|(#{RE_QUOTED_STRING}))/no) {|att, val, qval|
          if qval
            val = qval[1...-1].gsub(/[\r\n\t !#-\[\]-~\x80-\xff]+|(\\[\x00-\x7f])/n) { $1 ? $1[1,1] : $& }
          end
          parameters << [att.downcase, val]
        }
        ["#{type}/#{subtype}", *parameters]
      else
        nil
      end
    end

    # returns "type/subtype" which is MIME Content-Type.
    # It is downcased for canonicalization.
    # Content-Type parameters are stripped.
    def content_type
      type, *_ = content_type_parse
      type || 'application/octet-stream'
    end

    # returns a charset parameter in Content-Type field.
    # It is downcased for canonicalization.
    #
    # If charset parameter is not given but a block is given,
    # the block is called and its result is returned.
    # It can be used to guess charset.
    #
    # If charset parameter and block is not given,
    # nil is returned except text type.
    # In that case, "utf-8" is returned as defined by RFC6838 4.2.1
    def charset
      type, *parameters = content_type_parse
      if pair = parameters.assoc('charset')
        pair.last.downcase
      elsif block_given?
        yield
      elsif type && %r{\Atext/} =~ type
        "utf-8" # RFC6838 4.2.1
      else
        nil
      end
    end

    # Returns a list of encodings in Content-Encoding field as an array of
    # strings.
    #
    # The encodings are downcased for canonicalization.
    def content_encoding
      vs = @metas['content-encoding']
      if vs && %r{\A#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?(?:,#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?)*}o =~ (v = vs.join(', '))
        v.scan(RE_TOKEN).map {|content_coding| content_coding.downcase}
      else
        []
      end
    end
  end

  # Mixin for HTTP and FTP URIs.
  module OpenRead
    # OpenURI::OpenRead#open provides `open' for URI::HTTP and URI::FTP.
    #
    # OpenURI::OpenRead#open takes optional 3 arguments as:
    #
    #   OpenURI::OpenRead#open([mode [, perm]] [, options]) [{|io| ... }]
    #
    # OpenURI::OpenRead#open returns an IO-like object if block is not given.
    # Otherwise it yields the IO object and return the value of the block.
    # The IO object is extended with OpenURI::Meta.
    #
    # +mode+ and +perm+ are the same as Kernel#open.
    #
    # However, +mode+ must be read mode because OpenURI::OpenRead#open doesn't
    # support write mode (yet).
    # Also +perm+ is ignored because it is meaningful only for file creation.
    #
    # +options+ must be a hash.
    #
    # Each option with a string key specifies an extra header field for HTTP.
    # I.e., it is ignored for FTP without HTTP proxy.
    #
    # The hash may include other options, where keys are symbols:
    #
    # [:proxy]
    #  Synopsis:
    #    :proxy => "http://proxy.foo.com:8000/"
    #    :proxy => URI.parse("http://proxy.foo.com:8000/")
    #    :proxy => true
    #    :proxy => false
    #    :proxy => nil
    #
    #  If :proxy option is specified, the value should be String, URI,
    #  boolean or nil.
    #
    #  When String or URI is given, it is treated as proxy URI.
    #
    #  When true is given or the option itself is not specified,
    #  environment variable `scheme_proxy' is examined.
    #  `scheme' is replaced by `http', `https' or `ftp'.
    #
    #  When false or nil is given, the environment variables are ignored and
    #  connection will be made to a server directly.
    #
    # [:proxy_http_basic_authentication]
    #  Synopsis:
    #    :proxy_http_basic_authentication =>
    #      ["http://proxy.foo.com:8000/", "proxy-user", "proxy-password"]
    #    :proxy_http_basic_authentication =>
    #      [URI.parse("http://proxy.foo.com:8000/"),
    #       "proxy-user", "proxy-password"]
    #
    #  If :proxy option is specified, the value should be an Array with 3
    #  elements.  It should contain a proxy URI, a proxy user name and a proxy
    #  password.  The proxy URI should be a String, an URI or nil.  The proxy
    #  user name and password should be a String.
    #
    #  If nil is given for the proxy URI, this option is just ignored.
    #
    #  If :proxy and :proxy_http_basic_authentication is specified,
    #  ArgumentError is raised.
    #
    # [:http_basic_authentication]
    #  Synopsis:
    #    :http_basic_authentication=>[user, password]
    #
    #  If :http_basic_authentication is specified,
    #  the value should be an array which contains 2 strings:
    #  username and password.
    #  It is used for HTTP Basic authentication defined by RFC 2617.
    #
    # [:content_length_proc]
    #  Synopsis:
    #    :content_length_proc => lambda {|content_length| ... }
    #
    #  If :content_length_proc option is specified, the option value procedure
    #  is called before actual transfer is started.
    #  It takes one argument, which is expected content length in bytes.
    #
    #  If two or more transfers are performed by HTTP redirection, the
    #  procedure is called only once for the last transfer.
    #
    #  When expected content length is unknown, the procedure is called with
    #  nil.  This happens when the HTTP response has no Content-Length header.
    #
    # [:progress_proc]
    #  Synopsis:
    #    :progress_proc => lambda {|size| ...}
    #
    #  If :progress_proc option is specified, the proc is called with one
    #  argument each time when `open' gets content fragment from network.
    #  The argument +size+ is the accumulated transferred size in bytes.
    #
    #  If two or more transfer is done by HTTP redirection, the procedure
    #  is called only one for a last transfer.
    #
    #  :progress_proc and :content_length_proc are intended to be used for
    #  progress bar.
    #  For example, it can be implemented as follows using Ruby/ProgressBar.
    #
    #    pbar = nil
    #    open("http://...",
    #      :content_length_proc => lambda {|t|
    #        if t && 0 < t
    #          pbar = ProgressBar.new("...", t)
    #          pbar.file_transfer_mode
    #        end
    #      },
    #      :progress_proc => lambda {|s|
    #        pbar.set s if pbar
    #      }) {|f| ... }
    #
    # [:read_timeout]
    #  Synopsis:
    #    :read_timeout=>nil     (no timeout)
    #    :read_timeout=>10      (10 second)
    #
    #  :read_timeout option specifies a timeout of read for http connections.
    #
    # [:open_timeout]
    #  Synopsis:
    #    :open_timeout=>nil     (no timeout)
    #    :open_timeout=>10      (10 second)
    #
    #  :open_timeout option specifies a timeout of open for http connections.
    #
    # [:ssl_ca_cert]
    #  Synopsis:
    #    :ssl_ca_cert=>filename or an Array of filenames
    #
    #  :ssl_ca_cert is used to specify CA certificate for SSL.
    #  If it is given, default certificates are not used.
    #
    # [:ssl_verify_mode]
    #  Synopsis:
    #    :ssl_verify_mode=>mode
    #
    #  :ssl_verify_mode is used to specify openssl verify mode.
    #
    # [:ftp_active_mode]
    #  Synopsis:
    #    :ftp_active_mode=>bool
    #
    #  <tt>:ftp_active_mode => true</tt> is used to make ftp active mode.
    #  Ruby 1.9 uses passive mode by default.
    #  Note that the active mode is default in Ruby 1.8 or prior.
    #
    # [:redirect]
    #  Synopsis:
    #    :redirect=>bool
    #
    #  +:redirect+ is true by default.  <tt>:redirect => false</tt> is used to
    #  disable all HTTP redirects.
    #
    #  OpenURI::HTTPRedirect exception raised on redirection.
    #  Using +true+ also means that redirections between http and ftp are
    #  permitted.
    #
    def open(*rest, &block)
      OpenURI.open_uri(self, *rest, &block)
    end

    # OpenURI::OpenRead#read([ options ]) reads a content referenced by self and
    # returns the content as string.
    # The string is extended with OpenURI::Meta.
    # The argument +options+ is same as OpenURI::OpenRead#open.
    def read(options={})
      self.open(options) {|f|
        str = f.read
        Meta.init str, f
        str
      }
    end
  end
end

module URI
  class HTTP
    def buffer_open(buf, proxy, options) # :nodoc:
      OpenURI.open_http(buf, self, proxy, options)
    end

    include OpenURI::OpenRead
  end

  class FTP
    def buffer_open(buf, proxy, options) # :nodoc:
      if proxy
        OpenURI.open_http(buf, self, proxy, options)
        return
      end
      require 'net/ftp'

      path = self.path
      path = path.sub(%r{\A/}, '%2F') # re-encode the beginning slash because uri library decodes it.
      directories = path.split(%r{/}, -1)
      directories.each {|d|
        d.gsub!(/%([0-9A-Fa-f][0-9A-Fa-f])/) { [$1].pack("H2") }
      }
      unless filename = directories.pop
        raise ArgumentError, "no filename: #{self.inspect}"
      end
      directories.each {|d|
        if /[\r\n]/ =~ d
          raise ArgumentError, "invalid directory: #{d.inspect}"
        end
      }
      if /[\r\n]/ =~ filename
        raise ArgumentError, "invalid filename: #{filename.inspect}"
      end
      typecode = self.typecode
      if typecode && /\A[aid]\z/ !~ typecode
        raise ArgumentError, "invalid typecode: #{typecode.inspect}"
      end

      # The access sequence is defined by RFC 1738
      ftp = Net::FTP.new
      ftp.connect(self.hostname, self.port)
      ftp.passive = !options[:ftp_active_mode]
      # todo: extract user/passwd from .netrc.
      user = 'anonymous'
      passwd = nil
      user, passwd = self.userinfo.split(/:/) if self.userinfo
      ftp.login(user, passwd)
      directories.each {|cwd|
        ftp.voidcmd("CWD #{cwd}")
      }
      if typecode
        # xxx: typecode D is not handled.
        ftp.voidcmd("TYPE #{typecode.upcase}")
      end
      if options[:content_length_proc]
        options[:content_length_proc].call(ftp.size(filename))
      end
      ftp.retrbinary("RETR #{filename}", 4096) { |str|
        buf << str
        options[:progress_proc].call(buf.size) if options[:progress_proc]
      }
      ftp.close
      buf.io.rewind
    end

    include OpenURI::OpenRead
  end
end
# frozen-string-literal: true
##
# == Manipulates strings like the UNIX Bourne shell
#
# This module manipulates strings according to the word parsing rules
# of the UNIX Bourne shell.
#
# The shellwords() function was originally a port of shellwords.pl,
# but modified to conform to the Shell & Utilities volume of the IEEE
# Std 1003.1-2008, 2016 Edition [1].
#
# === Usage
#
# You can use Shellwords to parse a string into a Bourne shell friendly Array.
#
#   require 'shellwords'
#
#   argv = Shellwords.split('three blind "mice"')
#   argv #=> ["three", "blind", "mice"]
#
# Once you've required Shellwords, you can use the #split alias
# String#shellsplit.
#
#   argv = "see how they run".shellsplit
#   argv #=> ["see", "how", "they", "run"]
#
# They treat quotes as special characters, so an unmatched quote will
# cause an ArgumentError.
#
#   argv = "they all ran after the farmer's wife".shellsplit
#        #=> ArgumentError: Unmatched quote: ...
#
# Shellwords also provides methods that do the opposite.
# Shellwords.escape, or its alias, String#shellescape, escapes
# shell metacharacters in a string for use in a command line.
#
#   filename = "special's.txt"
#
#   system("cat -- #{filename.shellescape}")
#   # runs "cat -- special\\'s.txt"
#
# Note the '--'.  Without it, cat(1) will treat the following argument
# as a command line option if it starts with '-'.  It is guaranteed
# that Shellwords.escape converts a string to a form that a Bourne
# shell will parse back to the original string, but it is the
# programmer's responsibility to make sure that passing an arbitrary
# argument to a command does no harm.
#
# Shellwords also comes with a core extension for Array, Array#shelljoin.
#
#   dir = "Funny GIFs"
#   argv = %W[ls -lta -- #{dir}]
#   system(argv.shelljoin + " | less")
#   # runs "ls -lta -- Funny\\ GIFs | less"
#
# You can use this method to build a complete command line out of an
# array of arguments.
#
# === Authors
# * Wakou Aoyama
# * Akinori MUSHA <knu@iDaemons.org>
#
# === Contact
# * Akinori MUSHA <knu@iDaemons.org> (current maintainer)
#
# === Resources
#
# 1: {IEEE Std 1003.1-2008, 2016 Edition, the Shell & Utilities volume}[http://pubs.opengroup.org/onlinepubs/9699919799/utilities/contents.html]

module Shellwords
  # Splits a string into an array of tokens in the same way the UNIX
  # Bourne shell does.
  #
  #   argv = Shellwords.split('here are "two words"')
  #   argv #=> ["here", "are", "two words"]
  #
  # Note, however, that this is not a command line parser.  Shell
  # metacharacters except for the single and double quotes and
  # backslash are not treated as such.
  #
  #   argv = Shellwords.split('ruby my_prog.rb | less')
  #   argv #=> ["ruby", "my_prog.rb", "|", "less"]
  #
  # String#shellsplit is a shortcut for this function.
  #
  #   argv = 'here are "two words"'.shellsplit
  #   argv #=> ["here", "are", "two words"]
  def shellsplit(line)
    words = []
    field = String.new
    line.scan(/\G\s*(?>([^\s\\\'\"]+)|'([^\']*)'|"((?:[^\"\\]|\\.)*)"|(\\.?)|(\S))(\s|\z)?/m) do
      |word, sq, dq, esc, garbage, sep|
      raise ArgumentError, "Unmatched quote: #{line.inspect}" if garbage
      # 2.2.3 Double-Quotes:
      #
      #   The <backslash> shall retain its special meaning as an
      #   escape character only when followed by one of the following
      #   characters when considered special:
      #
      #   $ ` " \ <newline>
      field << (word || sq || (dq && dq.gsub(/\\([$`"\\\n])/, '\\1')) || esc.gsub(/\\(.)/, '\\1'))
      if sep
        words << field
        field = String.new
      end
    end
    words
  end

  alias shellwords shellsplit

  module_function :shellsplit, :shellwords

  class << self
    alias split shellsplit
  end

  # Escapes a string so that it can be safely used in a Bourne shell
  # command line.  +str+ can be a non-string object that responds to
  # +to_s+.
  #
  # Note that a resulted string should be used unquoted and is not
  # intended for use in double quotes nor in single quotes.
  #
  #   argv = Shellwords.escape("It's better to give than to receive")
  #   argv #=> "It\\'s\\ better\\ to\\ give\\ than\\ to\\ receive"
  #
  # String#shellescape is a shorthand for this function.
  #
  #   argv = "It's better to give than to receive".shellescape
  #   argv #=> "It\\'s\\ better\\ to\\ give\\ than\\ to\\ receive"
  #
  #   # Search files in lib for method definitions
  #   pattern = "^[ \t]*def "
  #   open("| grep -Ern -e #{pattern.shellescape} lib") { |grep|
  #     grep.each_line { |line|
  #       file, lineno, matched_line = line.split(':', 3)
  #       # ...
  #     }
  #   }
  #
  # It is the caller's responsibility to encode the string in the right
  # encoding for the shell environment where this string is used.
  #
  # Multibyte characters are treated as multibyte characters, not as bytes.
  #
  # Returns an empty quoted String if +str+ has a length of zero.
  def shellescape(str)
    str = str.to_s

    # An empty argument will be skipped, so return empty quotes.
    return "''".dup if str.empty?

    str = str.dup

    # Treat multibyte characters as is.  It is the caller's responsibility
    # to encode the string in the right encoding for the shell
    # environment.
    str.gsub!(/[^A-Za-z0-9_\-.,:+\/@\n]/, "\\\\\\&")

    # A LF cannot be escaped with a backslash because a backslash + LF
    # combo is regarded as a line continuation and simply ignored.
    str.gsub!(/\n/, "'\n'")

    return str
  end

  module_function :shellescape

  class << self
    alias escape shellescape
  end

  # Builds a command line string from an argument list, +array+.
  #
  # All elements are joined into a single string with fields separated by a
  # space, where each element is escaped for the Bourne shell and stringified
  # using +to_s+.
  #
  #   ary = ["There's", "a", "time", "and", "place", "for", "everything"]
  #   argv = Shellwords.join(ary)
  #   argv #=> "There\\'s a time and place for everything"
  #
  # Array#shelljoin is a shortcut for this function.
  #
  #   ary = ["Don't", "rock", "the", "boat"]
  #   argv = ary.shelljoin
  #   argv #=> "Don\\'t rock the boat"
  #
  # You can also mix non-string objects in the elements as allowed in Array#join.
  #
  #   output = `#{['ps', '-p', $$].shelljoin}`
  #
  def shelljoin(array)
    array.map { |arg| shellescape(arg) }.join(' ')
  end

  module_function :shelljoin

  class << self
    alias join shelljoin
  end
end

class String
  # call-seq:
  #   str.shellsplit => array
  #
  # Splits +str+ into an array of tokens in the same way the UNIX
  # Bourne shell does.
  #
  # See Shellwords.shellsplit for details.
  def shellsplit
    Shellwords.split(self)
  end

  # call-seq:
  #   str.shellescape => string
  #
  # Escapes +str+ so that it can be safely used in a Bourne shell
  # command line.
  #
  # See Shellwords.shellescape for details.
  def shellescape
    Shellwords.escape(self)
  end
end

class Array
  # call-seq:
  #   array.shelljoin => string
  #
  # Builds a command line string from an argument list +array+ joining
  # all elements escaped for the Bourne shell and separated by a space.
  #
  # See Shellwords.shelljoin for details.
  def shelljoin
    Shellwords.join(self)
  end
end
#frozen_string_literal: false
require 'json/common'

##
# = JavaScript \Object Notation (\JSON)
#
# \JSON is a lightweight data-interchange format.
#
# A \JSON value is one of the following:
# - Double-quoted text:  <tt>"foo"</tt>.
# - Number:  +1+, +1.0+, +2.0e2+.
# - Boolean:  +true+, +false+.
# - Null: +null+.
# - \Array: an ordered list of values, enclosed by square brackets:
#     ["foo", 1, 1.0, 2.0e2, true, false, null]
#
# - \Object: a collection of name/value pairs, enclosed by curly braces;
#   each name is double-quoted text;
#   the values may be any \JSON values:
#     {"a": "foo", "b": 1, "c": 1.0, "d": 2.0e2, "e": true, "f": false, "g": null}
#
# A \JSON array or object may contain nested arrays, objects, and scalars
# to any depth:
#   {"foo": {"bar": 1, "baz": 2}, "bat": [0, 1, 2]}
#   [{"foo": 0, "bar": 1}, ["baz", 2]]
#
# == Using \Module \JSON
#
# To make module \JSON available in your code, begin with:
#   require 'json'
#
# All examples here assume that this has been done.
#
# === Parsing \JSON
#
# You can parse a \String containing \JSON data using
# either of two methods:
# - <tt>JSON.parse(source, opts)</tt>
# - <tt>JSON.parse!(source, opts)</tt>
#
# where
# - +source+ is a Ruby object.
# - +opts+ is a \Hash object containing options
#   that control both input allowed and output formatting.
#
# The difference between the two methods
# is that JSON.parse! omits some checks
# and may not be safe for some +source+ data;
# use it only for data from trusted sources.
# Use the safer method JSON.parse for less trusted sources.
#
# ==== Parsing \JSON Arrays
#
# When +source+ is a \JSON array, JSON.parse by default returns a Ruby \Array:
#   json = '["foo", 1, 1.0, 2.0e2, true, false, null]'
#   ruby = JSON.parse(json)
#   ruby # => ["foo", 1, 1.0, 200.0, true, false, nil]
#   ruby.class # => Array
#
# The \JSON array may contain nested arrays, objects, and scalars
# to any depth:
#   json = '[{"foo": 0, "bar": 1}, ["baz", 2]]'
#   JSON.parse(json) # => [{"foo"=>0, "bar"=>1}, ["baz", 2]]
#
# ==== Parsing \JSON \Objects
#
# When the source is a \JSON object, JSON.parse by default returns a Ruby \Hash:
#   json = '{"a": "foo", "b": 1, "c": 1.0, "d": 2.0e2, "e": true, "f": false, "g": null}'
#   ruby = JSON.parse(json)
#   ruby # => {"a"=>"foo", "b"=>1, "c"=>1.0, "d"=>200.0, "e"=>true, "f"=>false, "g"=>nil}
#   ruby.class # => Hash
#
# The \JSON object may contain nested arrays, objects, and scalars
# to any depth:
#   json = '{"foo": {"bar": 1, "baz": 2}, "bat": [0, 1, 2]}'
#   JSON.parse(json) # => {"foo"=>{"bar"=>1, "baz"=>2}, "bat"=>[0, 1, 2]}
#
# ==== Parsing \JSON Scalars
#
# When the source is a \JSON scalar (not an array or object),
# JSON.parse returns a Ruby scalar.
#
# \String:
#   ruby = JSON.parse('"foo"')
#   ruby # => 'foo'
#   ruby.class # => String
# \Integer:
#   ruby = JSON.parse('1')
#   ruby # => 1
#   ruby.class # => Integer
# \Float:
#   ruby = JSON.parse('1.0')
#   ruby # => 1.0
#   ruby.class # => Float
#   ruby = JSON.parse('2.0e2')
#   ruby # => 200
#   ruby.class # => Float
# Boolean:
#   ruby = JSON.parse('true')
#   ruby # => true
#   ruby.class # => TrueClass
#   ruby = JSON.parse('false')
#   ruby # => false
#   ruby.class # => FalseClass
# Null:
#   ruby = JSON.parse('null')
#   ruby # => nil
#   ruby.class # => NilClass
#
# ==== Parsing Options
#
# ====== Input Options
#
# Option +max_nesting+ (\Integer) specifies the maximum nesting depth allowed;
# defaults to +100+; specify +false+ to disable depth checking.
#
# With the default, +false+:
#   source = '[0, [1, [2, [3]]]]'
#   ruby = JSON.parse(source)
#   ruby # => [0, [1, [2, [3]]]]
# Too deep:
#   # Raises JSON::NestingError (nesting of 2 is too deep):
#   JSON.parse(source, {max_nesting: 1})
# Bad value:
#   # Raises TypeError (wrong argument type Symbol (expected Fixnum)):
#   JSON.parse(source, {max_nesting: :foo})
#
# ---
#
# Option +allow_nan+ (boolean) specifies whether to allow
# NaN, Infinity, and MinusInfinity in +source+;
# defaults to +false+.
#
# With the default, +false+:
#   # Raises JSON::ParserError (225: unexpected token at '[NaN]'):
#   JSON.parse('[NaN]')
#   # Raises JSON::ParserError (232: unexpected token at '[Infinity]'):
#   JSON.parse('[Infinity]')
#   # Raises JSON::ParserError (248: unexpected token at '[-Infinity]'):
#   JSON.parse('[-Infinity]')
# Allow:
#   source = '[NaN, Infinity, -Infinity]'
#   ruby = JSON.parse(source, {allow_nan: true})
#   ruby # => [NaN, Infinity, -Infinity]
#
# ====== Output Options
#
# Option +symbolize_names+ (boolean) specifies whether returned \Hash keys
# should be Symbols;
# defaults to +false+ (use Strings).
#
# With the default, +false+:
#   source = '{"a": "foo", "b": 1.0, "c": true, "d": false, "e": null}'
#   ruby = JSON.parse(source)
#   ruby # => {"a"=>"foo", "b"=>1.0, "c"=>true, "d"=>false, "e"=>nil}
# Use Symbols:
#   ruby = JSON.parse(source, {symbolize_names: true})
#   ruby # => {:a=>"foo", :b=>1.0, :c=>true, :d=>false, :e=>nil}
#
# ---
#
# Option +object_class+ (\Class) specifies the Ruby class to be used
# for each \JSON object;
# defaults to \Hash.
#
# With the default, \Hash:
#   source = '{"a": "foo", "b": 1.0, "c": true, "d": false, "e": null}'
#   ruby = JSON.parse(source)
#   ruby.class # => Hash
# Use class \OpenStruct:
#   ruby = JSON.parse(source, {object_class: OpenStruct})
#   ruby # => #<OpenStruct a="foo", b=1.0, c=true, d=false, e=nil>
#
# ---
#
# Option +array_class+ (\Class) specifies the Ruby class to be used
# for each \JSON array;
# defaults to \Array.
#
# With the default, \Array:
#   source = '["foo", 1.0, true, false, null]'
#   ruby = JSON.parse(source)
#   ruby.class # => Array
# Use class \Set:
#   ruby = JSON.parse(source, {array_class: Set})
#   ruby # => #<Set: {"foo", 1.0, true, false, nil}>
#
# ---
#
# Option +create_additions+ (boolean) specifies whether to use \JSON additions in parsing.
# See {\JSON Additions}[#module-JSON-label-JSON+Additions].
#
# === Generating \JSON
#
# To generate a Ruby \String containing \JSON data,
# use method <tt>JSON.generate(source, opts)</tt>, where
# - +source+ is a Ruby object.
# - +opts+ is a \Hash object containing options
#   that control both input allowed and output formatting.
#
# ==== Generating \JSON from Arrays
#
# When the source is a Ruby \Array, JSON.generate returns
# a \String containing a \JSON array:
#   ruby = [0, 's', :foo]
#   json = JSON.generate(ruby)
#   json # => '[0,"s","foo"]'
#
# The Ruby \Array array may contain nested arrays, hashes, and scalars
# to any depth:
#   ruby = [0, [1, 2], {foo: 3, bar: 4}]
#   json = JSON.generate(ruby)
#   json # => '[0,[1,2],{"foo":3,"bar":4}]'
#
# ==== Generating \JSON from Hashes
#
# When the source is a Ruby \Hash, JSON.generate returns
# a \String containing a \JSON object:
#   ruby = {foo: 0, bar: 's', baz: :bat}
#   json = JSON.generate(ruby)
#   json # => '{"foo":0,"bar":"s","baz":"bat"}'
#
# The Ruby \Hash array may contain nested arrays, hashes, and scalars
# to any depth:
#   ruby = {foo: [0, 1], bar: {baz: 2, bat: 3}, bam: :bad}
#   json = JSON.generate(ruby)
#   json # => '{"foo":[0,1],"bar":{"baz":2,"bat":3},"bam":"bad"}'
#
# ==== Generating \JSON from Other Objects
#
# When the source is neither an \Array nor a \Hash,
# the generated \JSON data depends on the class of the source.
#
# When the source is a Ruby \Integer or \Float, JSON.generate returns
# a \String containing a \JSON number:
#   JSON.generate(42) # => '42'
#   JSON.generate(0.42) # => '0.42'
#
# When the source is a Ruby \String, JSON.generate returns
# a \String containing a \JSON string (with double-quotes):
#   JSON.generate('A string') # => '"A string"'
#
# When the source is +true+, +false+ or +nil+, JSON.generate returns
# a \String containing the corresponding \JSON token:
#   JSON.generate(true) # => 'true'
#   JSON.generate(false) # => 'false'
#   JSON.generate(nil) # => 'null'
#
# When the source is none of the above, JSON.generate returns
# a \String containing a \JSON string representation of the source:
#   JSON.generate(:foo) # => '"foo"'
#   JSON.generate(Complex(0, 0)) # => '"0+0i"'
#   JSON.generate(Dir.new('.')) # => '"#<Dir>"'
#
# ==== Generating Options
#
# ====== Input Options
#
# Option +allow_nan+ (boolean) specifies whether
# +NaN+, +Infinity+, and <tt>-Infinity</tt> may be generated;
# defaults to +false+.
#
# With the default, +false+:
#   # Raises JSON::GeneratorError (920: NaN not allowed in JSON):
#   JSON.generate(JSON::NaN)
#   # Raises JSON::GeneratorError (917: Infinity not allowed in JSON):
#   JSON.generate(JSON::Infinity)
#   # Raises JSON::GeneratorError (917: -Infinity not allowed in JSON):
#   JSON.generate(JSON::MinusInfinity)
#
# Allow:
#   ruby = [Float::NaN, Float::Infinity, Float::MinusInfinity]
#   JSON.generate(ruby, allow_nan: true) # => '[NaN,Infinity,-Infinity]'
#
# ---
#
# Option +max_nesting+ (\Integer) specifies the maximum nesting depth
# in +obj+; defaults to +100+.
#
# With the default, +100+:
#   obj = [[[[[[0]]]]]]
#   JSON.generate(obj) # => '[[[[[[0]]]]]]'
#
# Too deep:
#   # Raises JSON::NestingError (nesting of 2 is too deep):
#   JSON.generate(obj, max_nesting: 2)
#
# ====== Output Options
#
# The default formatting options generate the most compact
# \JSON data, all on one line and with no whitespace.
#
# You can use these formatting options to generate
# \JSON data in a more open format, using whitespace.
# See also JSON.pretty_generate.
#
# - Option +array_nl+ (\String) specifies a string (usually a newline)
#   to be inserted after each \JSON array; defaults to the empty \String, <tt>''</tt>.
# - Option +object_nl+ (\String) specifies a string (usually a newline)
#   to be inserted after each \JSON object; defaults to the empty \String, <tt>''</tt>.
# - Option +indent+ (\String) specifies the string (usually spaces) to be
#   used for indentation; defaults to the empty \String, <tt>''</tt>;
#   defaults to the empty \String, <tt>''</tt>;
#   has no effect unless options +array_nl+ or +object_nl+ specify newlines.
# - Option +space+ (\String) specifies a string (usually a space) to be
#   inserted after the colon in each \JSON object's pair;
#   defaults to the empty \String, <tt>''</tt>.
# - Option +space_before+ (\String) specifies a string (usually a space) to be
#   inserted before the colon in each \JSON object's pair;
#   defaults to the empty \String, <tt>''</tt>.
#
# In this example, +obj+ is used first to generate the shortest
# \JSON data (no whitespace), then again with all formatting options
# specified:
#
#   obj = {foo: [:bar, :baz], bat: {bam: 0, bad: 1}}
#   json = JSON.generate(obj)
#   puts 'Compact:', json
#   opts = {
#     array_nl: "\n",
#     object_nl: "\n",
#     indent: '  ',
#     space_before: ' ',
#     space: ' '
#   }
#   puts 'Open:', JSON.generate(obj, opts)
#
# Output:
#   Compact:
#   {"foo":["bar","baz"],"bat":{"bam":0,"bad":1}}
#   Open:
#   {
#     "foo" : [
#       "bar",
#       "baz"
#   ],
#     "bat" : {
#       "bam" : 0,
#       "bad" : 1
#     }
#   }
#
# == \JSON Additions
#
# When you "round trip" a non-\String object from Ruby to \JSON and back,
# you have a new \String, instead of the object you began with:
#   ruby0 = Range.new(0, 2)
#   json = JSON.generate(ruby0)
#   json # => '0..2"'
#   ruby1 = JSON.parse(json)
#   ruby1 # => '0..2'
#   ruby1.class # => String
#
# You can use \JSON _additions_ to preserve the original object.
# The addition is an extension of a ruby class, so that:
# - \JSON.generate stores more information in the \JSON string.
# - \JSON.parse, called with option +create_additions+,
#   uses that information to create a proper Ruby object.
#
# This example shows a \Range being generated into \JSON
# and parsed back into Ruby, both without and with
# the addition for \Range:
#   ruby = Range.new(0, 2)
#   # This passage does not use the addition for Range.
#   json0 = JSON.generate(ruby)
#   ruby0 = JSON.parse(json0)
#   # This passage uses the addition for Range.
#   require 'json/add/range'
#   json1 = JSON.generate(ruby)
#   ruby1 = JSON.parse(json1, create_additions: true)
#   # Make a nice display.
#   display = <<EOT
#   Generated JSON:
#     Without addition:  #{json0} (#{json0.class})
#     With addition:     #{json1} (#{json1.class})
#   Parsed JSON:
#     Without addition:  #{ruby0.inspect} (#{ruby0.class})
#     With addition:     #{ruby1.inspect} (#{ruby1.class})
#   EOT
#   puts display
#
# This output shows the different results:
#   Generated JSON:
#     Without addition:  "0..2" (String)
#     With addition:     {"json_class":"Range","a":[0,2,false]} (String)
#   Parsed JSON:
#     Without addition:  "0..2" (String)
#     With addition:     0..2 (Range)
#
# The \JSON module includes additions for certain classes.
# You can also craft custom additions.
# See {Custom \JSON Additions}[#module-JSON-label-Custom+JSON+Additions].
#
# === Built-in Additions
#
# The \JSON module includes additions for certain classes.
# To use an addition, +require+ its source:
# - BigDecimal: <tt>require 'json/add/bigdecimal'</tt>
# - Complex: <tt>require 'json/add/complex'</tt>
# - Date: <tt>require 'json/add/date'</tt>
# - DateTime: <tt>require 'json/add/date_time'</tt>
# - Exception: <tt>require 'json/add/exception'</tt>
# - OpenStruct: <tt>require 'json/add/ostruct'</tt>
# - Range: <tt>require 'json/add/range'</tt>
# - Rational: <tt>require 'json/add/rational'</tt>
# - Regexp: <tt>require 'json/add/regexp'</tt>
# - Set: <tt>require 'json/add/set'</tt>
# - Struct: <tt>require 'json/add/struct'</tt>
# - Symbol: <tt>require 'json/add/symbol'</tt>
# - Time: <tt>require 'json/add/time'</tt>
#
# To reduce punctuation clutter, the examples below
# show the generated \JSON via +puts+, rather than the usual +inspect+,
#
# \BigDecimal:
#   require 'json/add/bigdecimal'
#   ruby0 = BigDecimal(0) # 0.0
#   json = JSON.generate(ruby0) # {"json_class":"BigDecimal","b":"27:0.0"}
#   ruby1 = JSON.parse(json, create_additions: true) # 0.0
#   ruby1.class # => BigDecimal
#
# \Complex:
#   require 'json/add/complex'
#   ruby0 = Complex(1+0i) # 1+0i
#   json = JSON.generate(ruby0) # {"json_class":"Complex","r":1,"i":0}
#   ruby1 = JSON.parse(json, create_additions: true) # 1+0i
#   ruby1.class # Complex
#
# \Date:
#   require 'json/add/date'
#   ruby0 = Date.today # 2020-05-02
#   json = JSON.generate(ruby0) # {"json_class":"Date","y":2020,"m":5,"d":2,"sg":2299161.0}
#   ruby1 = JSON.parse(json, create_additions: true) # 2020-05-02
#   ruby1.class # Date
#
# \DateTime:
#   require 'json/add/date_time'
#   ruby0 = DateTime.now # 2020-05-02T10:38:13-05:00
#   json = JSON.generate(ruby0) # {"json_class":"DateTime","y":2020,"m":5,"d":2,"H":10,"M":38,"S":13,"of":"-5/24","sg":2299161.0}
#   ruby1 = JSON.parse(json, create_additions: true) # 2020-05-02T10:38:13-05:00
#   ruby1.class # DateTime
#
# \Exception (and its subclasses including \RuntimeError):
#   require 'json/add/exception'
#   ruby0 = Exception.new('A message') # A message
#   json = JSON.generate(ruby0) # {"json_class":"Exception","m":"A message","b":null}
#   ruby1 = JSON.parse(json, create_additions: true) # A message
#   ruby1.class # Exception
#   ruby0 = RuntimeError.new('Another message') # Another message
#   json = JSON.generate(ruby0) # {"json_class":"RuntimeError","m":"Another message","b":null}
#   ruby1 = JSON.parse(json, create_additions: true) # Another message
#   ruby1.class # RuntimeError
#
# \OpenStruct:
#   require 'json/add/ostruct'
#   ruby0 = OpenStruct.new(name: 'Matz', language: 'Ruby') # #<OpenStruct name="Matz", language="Ruby">
#   json = JSON.generate(ruby0) # {"json_class":"OpenStruct","t":{"name":"Matz","language":"Ruby"}}
#   ruby1 = JSON.parse(json, create_additions: true) # #<OpenStruct name="Matz", language="Ruby">
#   ruby1.class # OpenStruct
#
# \Range:
#   require 'json/add/range'
#   ruby0 = Range.new(0, 2) # 0..2
#   json = JSON.generate(ruby0) # {"json_class":"Range","a":[0,2,false]}
#   ruby1 = JSON.parse(json, create_additions: true) # 0..2
#   ruby1.class # Range
#
# \Rational:
#   require 'json/add/rational'
#   ruby0 = Rational(1, 3) # 1/3
#   json = JSON.generate(ruby0) # {"json_class":"Rational","n":1,"d":3}
#   ruby1 = JSON.parse(json, create_additions: true) # 1/3
#   ruby1.class # Rational
#
# \Regexp:
#   require 'json/add/regexp'
#   ruby0 = Regexp.new('foo') # (?-mix:foo)
#   json = JSON.generate(ruby0) # {"json_class":"Regexp","o":0,"s":"foo"}
#   ruby1 = JSON.parse(json, create_additions: true) # (?-mix:foo)
#   ruby1.class # Regexp
#
# \Set:
#   require 'json/add/set'
#   ruby0 = Set.new([0, 1, 2]) # #<Set: {0, 1, 2}>
#   json = JSON.generate(ruby0) # {"json_class":"Set","a":[0,1,2]}
#   ruby1 = JSON.parse(json, create_additions: true) # #<Set: {0, 1, 2}>
#   ruby1.class # Set
#
# \Struct:
#   require 'json/add/struct'
#   Customer = Struct.new(:name, :address) # Customer
#   ruby0 = Customer.new("Dave", "123 Main") # #<struct Customer name="Dave", address="123 Main">
#   json = JSON.generate(ruby0) # {"json_class":"Customer","v":["Dave","123 Main"]}
#   ruby1 = JSON.parse(json, create_additions: true) # #<struct Customer name="Dave", address="123 Main">
#   ruby1.class # Customer
  #
# \Symbol:
#   require 'json/add/symbol'
#   ruby0 = :foo # foo
#   json = JSON.generate(ruby0) # {"json_class":"Symbol","s":"foo"}
#   ruby1 = JSON.parse(json, create_additions: true) # foo
#   ruby1.class # Symbol
#
# \Time:
#   require 'json/add/time'
#   ruby0 = Time.now # 2020-05-02 11:28:26 -0500
#   json = JSON.generate(ruby0) # {"json_class":"Time","s":1588436906,"n":840560000}
#   ruby1 = JSON.parse(json, create_additions: true) # 2020-05-02 11:28:26 -0500
#   ruby1.class # Time
#
#
# === Custom \JSON Additions
#
# In addition to the \JSON additions provided,
# you can craft \JSON additions of your own,
# either for Ruby built-in classes or for user-defined classes.
#
# Here's a user-defined class +Foo+:
#   class Foo
#     attr_accessor :bar, :baz
#     def initialize(bar, baz)
#       self.bar = bar
#       self.baz = baz
#     end
#   end
#
# Here's the \JSON addition for it:
#   # Extend class Foo with JSON addition.
#   class Foo
#     # Serialize Foo object with its class name and arguments
#     def to_json(*args)
#       {
#         JSON.create_id  => self.class.name,
#         'a'             => [ bar, baz ]
#       }.to_json(*args)
#     end
#     # Deserialize JSON string by constructing new Foo object with arguments.
#     def self.json_create(object)
#       new(*object['a'])
#     end
#   end
#
# Demonstration:
#   require 'json'
#   # This Foo object has no custom addition.
#   foo0 = Foo.new(0, 1)
#   json0 = JSON.generate(foo0)
#   obj0 = JSON.parse(json0)
#   # Lood the custom addition.
#   require_relative 'foo_addition'
#   # This foo has the custom addition.
#   foo1 = Foo.new(0, 1)
#   json1 = JSON.generate(foo1)
#   obj1 = JSON.parse(json1, create_additions: true)
#   #   Make a nice display.
#   display = <<EOT
#   Generated JSON:
#     Without custom addition:  #{json0} (#{json0.class})
#     With custom addition:     #{json1} (#{json1.class})
#   Parsed JSON:
#     Without custom addition:  #{obj0.inspect} (#{obj0.class})
#     With custom addition:     #{obj1.inspect} (#{obj1.class})
#   EOT
#   puts display
#
# Output:
#
#   Generated JSON:
#     Without custom addition:  "#<Foo:0x0000000006534e80>" (String)
#     With custom addition:     {"json_class":"Foo","a":[0,1]} (String)
#   Parsed JSON:
#     Without custom addition:  "#<Foo:0x0000000006534e80>" (String)
#     With custom addition:     #<Foo:0x0000000006473bb8 @bar=0, @baz=1> (Foo)
#
module JSON
  require 'json/version'

  begin
    require 'json/ext'
  rescue LoadError
    require 'json/pure'
  end
end
# -*- coding: us-ascii -*-
# frozen_string_literal: true
# = ERB -- Ruby Templating
#
# Author:: Masatoshi SEKI
# Documentation:: James Edward Gray II, Gavin Sinclair, and Simon Chiang
#
# See ERB for primary documentation and ERB::Util for a couple of utility
# routines.
#
# Copyright (c) 1999-2000,2002,2003 Masatoshi SEKI
#
# You can redistribute it and/or modify it under the same terms as Ruby.

require "cgi/util"

#
# = ERB -- Ruby Templating
#
# == Introduction
#
# ERB provides an easy to use but powerful templating system for Ruby.  Using
# ERB, actual Ruby code can be added to any plain text document for the
# purposes of generating document information details and/or flow control.
#
# A very simple example is this:
#
#   require 'erb'
#
#   x = 42
#   template = ERB.new <<-EOF
#     The value of x is: <%= x %>
#   EOF
#   puts template.result(binding)
#
# <em>Prints:</em> The value of x is: 42
#
# More complex examples are given below.
#
#
# == Recognized Tags
#
# ERB recognizes certain tags in the provided template and converts them based
# on the rules below:
#
#   <% Ruby code -- inline with output %>
#   <%= Ruby expression -- replace with result %>
#   <%# comment -- ignored -- useful in testing %>
#   % a line of Ruby code -- treated as <% line %> (optional -- see ERB.new)
#   %% replaced with % if first thing on a line and % processing is used
#   <%% or %%> -- replace with <% or %> respectively
#
# All other text is passed through ERB filtering unchanged.
#
#
# == Options
#
# There are several settings you can change when you use ERB:
# * the nature of the tags that are recognized;
# * the binding used to resolve local variables in the template.
#
# See the ERB.new and ERB#result methods for more detail.
#
# == Character encodings
#
# ERB (or Ruby code generated by ERB) returns a string in the same
# character encoding as the input string.  When the input string has
# a magic comment, however, it returns a string in the encoding specified
# by the magic comment.
#
#   # -*- coding: utf-8 -*-
#   require 'erb'
#
#   template = ERB.new <<EOF
#   <%#-*- coding: Big5 -*-%>
#     \_\_ENCODING\_\_ is <%= \_\_ENCODING\_\_ %>.
#   EOF
#   puts template.result
#
# <em>Prints:</em> \_\_ENCODING\_\_ is Big5.
#
#
# == Examples
#
# === Plain Text
#
# ERB is useful for any generic templating situation.  Note that in this example, we use the
# convenient "% at start of line" tag, and we quote the template literally with
# <tt>%q{...}</tt> to avoid trouble with the backslash.
#
#   require "erb"
#
#   # Create template.
#   template = %q{
#     From:  James Edward Gray II <james@grayproductions.net>
#     To:  <%= to %>
#     Subject:  Addressing Needs
#
#     <%= to[/\w+/] %>:
#
#     Just wanted to send a quick note assuring that your needs are being
#     addressed.
#
#     I want you to know that my team will keep working on the issues,
#     especially:
#
#     <%# ignore numerous minor requests -- focus on priorities %>
#     % priorities.each do |priority|
#       * <%= priority %>
#     % end
#
#     Thanks for your patience.
#
#     James Edward Gray II
#   }.gsub(/^  /, '')
#
#   message = ERB.new(template, trim_mode: "%<>")
#
#   # Set up template data.
#   to = "Community Spokesman <spokesman@ruby_community.org>"
#   priorities = [ "Run Ruby Quiz",
#                  "Document Modules",
#                  "Answer Questions on Ruby Talk" ]
#
#   # Produce result.
#   email = message.result
#   puts email
#
# <i>Generates:</i>
#
#   From:  James Edward Gray II <james@grayproductions.net>
#   To:  Community Spokesman <spokesman@ruby_community.org>
#   Subject:  Addressing Needs
#
#   Community:
#
#   Just wanted to send a quick note assuring that your needs are being addressed.
#
#   I want you to know that my team will keep working on the issues, especially:
#
#       * Run Ruby Quiz
#       * Document Modules
#       * Answer Questions on Ruby Talk
#
#   Thanks for your patience.
#
#   James Edward Gray II
#
# === Ruby in HTML
#
# ERB is often used in <tt>.rhtml</tt> files (HTML with embedded Ruby).  Notice the need in
# this example to provide a special binding when the template is run, so that the instance
# variables in the Product object can be resolved.
#
#   require "erb"
#
#   # Build template data class.
#   class Product
#     def initialize( code, name, desc, cost )
#       @code = code
#       @name = name
#       @desc = desc
#       @cost = cost
#
#       @features = [ ]
#     end
#
#     def add_feature( feature )
#       @features << feature
#     end
#
#     # Support templating of member data.
#     def get_binding
#       binding
#     end
#
#     # ...
#   end
#
#   # Create template.
#   template = %{
#     <html>
#       <head><title>Ruby Toys -- <%= @name %></title></head>
#       <body>
#
#         <h1><%= @name %> (<%= @code %>)</h1>
#         <p><%= @desc %></p>
#
#         <ul>
#           <% @features.each do |f| %>
#             <li><b><%= f %></b></li>
#           <% end %>
#         </ul>
#
#         <p>
#           <% if @cost < 10 %>
#             <b>Only <%= @cost %>!!!</b>
#           <% else %>
#              Call for a price, today!
#           <% end %>
#         </p>
#
#       </body>
#     </html>
#   }.gsub(/^  /, '')
#
#   rhtml = ERB.new(template)
#
#   # Set up template data.
#   toy = Product.new( "TZ-1002",
#                      "Rubysapien",
#                      "Geek's Best Friend!  Responds to Ruby commands...",
#                      999.95 )
#   toy.add_feature("Listens for verbal commands in the Ruby language!")
#   toy.add_feature("Ignores Perl, Java, and all C variants.")
#   toy.add_feature("Karate-Chop Action!!!")
#   toy.add_feature("Matz signature on left leg.")
#   toy.add_feature("Gem studded eyes... Rubies, of course!")
#
#   # Produce result.
#   rhtml.run(toy.get_binding)
#
# <i>Generates (some blank lines removed):</i>
#
#    <html>
#      <head><title>Ruby Toys -- Rubysapien</title></head>
#      <body>
#
#        <h1>Rubysapien (TZ-1002)</h1>
#        <p>Geek's Best Friend!  Responds to Ruby commands...</p>
#
#        <ul>
#            <li><b>Listens for verbal commands in the Ruby language!</b></li>
#            <li><b>Ignores Perl, Java, and all C variants.</b></li>
#            <li><b>Karate-Chop Action!!!</b></li>
#            <li><b>Matz signature on left leg.</b></li>
#            <li><b>Gem studded eyes... Rubies, of course!</b></li>
#        </ul>
#
#        <p>
#             Call for a price, today!
#        </p>
#
#      </body>
#    </html>
#
#
# == Notes
#
# There are a variety of templating solutions available in various Ruby projects.
# For example, RDoc, distributed with Ruby, uses its own template engine, which
# can be reused elsewhere.
#
# Other popular engines could be found in the corresponding
# {Category}[https://www.ruby-toolbox.com/categories/template_engines] of
# The Ruby Toolbox.
#
class ERB
  Revision = '$Date::                           $' # :nodoc: #'

  # Returns revision information for the erb.rb module.
  def self.version
    "erb.rb [2.2.0 #{ERB::Revision.split[1]}]"
  end
end

#--
# ERB::Compiler
class ERB
  # = ERB::Compiler
  #
  # Compiles ERB templates into Ruby code; the compiled code produces the
  # template result when evaluated. ERB::Compiler provides hooks to define how
  # generated output is handled.
  #
  # Internally ERB does something like this to generate the code returned by
  # ERB#src:
  #
  #   compiler = ERB::Compiler.new('<>')
  #   compiler.pre_cmd    = ["_erbout=+''"]
  #   compiler.put_cmd    = "_erbout.<<"
  #   compiler.insert_cmd = "_erbout.<<"
  #   compiler.post_cmd   = ["_erbout"]
  #
  #   code, enc = compiler.compile("Got <%= obj %>!\n")
  #   puts code
  #
  # <i>Generates</i>:
  #
  #   #coding:UTF-8
  #   _erbout=+''; _erbout.<< "Got ".freeze; _erbout.<<(( obj ).to_s); _erbout.<< "!\n".freeze; _erbout
  #
  # By default the output is sent to the print method.  For example:
  #
  #   compiler = ERB::Compiler.new('<>')
  #   code, enc = compiler.compile("Got <%= obj %>!\n")
  #   puts code
  #
  # <i>Generates</i>:
  #
  #   #coding:UTF-8
  #   print "Got ".freeze; print(( obj ).to_s); print "!\n".freeze
  #
  # == Evaluation
  #
  # The compiled code can be used in any context where the names in the code
  # correctly resolve. Using the last example, each of these print 'Got It!'
  #
  # Evaluate using a variable:
  #
  #   obj = 'It'
  #   eval code
  #
  # Evaluate using an input:
  #
  #   mod = Module.new
  #   mod.module_eval %{
  #     def get(obj)
  #       #{code}
  #     end
  #   }
  #   extend mod
  #   get('It')
  #
  # Evaluate using an accessor:
  #
  #   klass = Class.new Object
  #   klass.class_eval %{
  #     attr_accessor :obj
  #     def initialize(obj)
  #       @obj = obj
  #     end
  #     def get_it
  #       #{code}
  #     end
  #   }
  #   klass.new('It').get_it
  #
  # Good! See also ERB#def_method, ERB#def_module, and ERB#def_class.
  class Compiler # :nodoc:
    class PercentLine # :nodoc:
      def initialize(str)
        @value = str
      end
      attr_reader :value
      alias :to_s :value
    end

    class Scanner # :nodoc:
      @scanner_map = {}
      class << self
        def register_scanner(klass, trim_mode, percent)
          @scanner_map[[trim_mode, percent]] = klass
        end
        alias :regist_scanner :register_scanner
      end

      def self.default_scanner=(klass)
        @default_scanner = klass
      end

      def self.make_scanner(src, trim_mode, percent)
        klass = @scanner_map.fetch([trim_mode, percent], @default_scanner)
        klass.new(src, trim_mode, percent)
      end

      DEFAULT_STAGS = %w(<%% <%= <%# <%).freeze
      DEFAULT_ETAGS = %w(%%> %>).freeze
      def initialize(src, trim_mode, percent)
        @src = src
        @stag = nil
        @stags = DEFAULT_STAGS
        @etags = DEFAULT_ETAGS
      end
      attr_accessor :stag
      attr_reader :stags, :etags

      def scan; end
    end

    class TrimScanner < Scanner # :nodoc:
      def initialize(src, trim_mode, percent)
        super
        @trim_mode = trim_mode
        @percent = percent
        if @trim_mode == '>'
          @scan_reg  = /(.*?)(%>\r?\n|#{(stags + etags).join('|')}|\n|\z)/m
          @scan_line = self.method(:trim_line1)
        elsif @trim_mode == '<>'
          @scan_reg  = /(.*?)(%>\r?\n|#{(stags + etags).join('|')}|\n|\z)/m
          @scan_line = self.method(:trim_line2)
        elsif @trim_mode == '-'
          @scan_reg  = /(.*?)(^[ \t]*<%\-|<%\-|-%>\r?\n|-%>|#{(stags + etags).join('|')}|\z)/m
          @scan_line = self.method(:explicit_trim_line)
        else
          @scan_reg  = /(.*?)(#{(stags + etags).join('|')}|\n|\z)/m
          @scan_line = self.method(:scan_line)
        end
      end

      def scan(&block)
        @stag = nil
        if @percent
          @src.each_line do |line|
            percent_line(line, &block)
          end
        else
          @scan_line.call(@src, &block)
        end
        nil
      end

      def percent_line(line, &block)
        if @stag || line[0] != ?%
          return @scan_line.call(line, &block)
        end

        line[0] = ''
        if line[0] == ?%
          @scan_line.call(line, &block)
        else
          yield(PercentLine.new(line.chomp))
        end
      end

      def scan_line(line)
        line.scan(@scan_reg) do |tokens|
          tokens.each do |token|
            next if token.empty?
            yield(token)
          end
        end
      end

      def trim_line1(line)
        line.scan(@scan_reg) do |tokens|
          tokens.each do |token|
            next if token.empty?
            if token == "%>\n" || token == "%>\r\n"
              yield('%>')
              yield(:cr)
            else
              yield(token)
            end
          end
        end
      end

      def trim_line2(line)
        head = nil
        line.scan(@scan_reg) do |tokens|
          tokens.each do |token|
            next if token.empty?
            head = token unless head
            if token == "%>\n" || token == "%>\r\n"
              yield('%>')
              if is_erb_stag?(head)
                yield(:cr)
              else
                yield("\n")
              end
              head = nil
            else
              yield(token)
              head = nil if token == "\n"
            end
          end
        end
      end

      def explicit_trim_line(line)
        line.scan(@scan_reg) do |tokens|
          tokens.each do |token|
            next if token.empty?
            if @stag.nil? && /[ \t]*<%-/ =~ token
              yield('<%')
            elsif @stag && (token == "-%>\n" || token == "-%>\r\n")
              yield('%>')
              yield(:cr)
            elsif @stag && token == '-%>'
              yield('%>')
            else
              yield(token)
            end
          end
        end
      end

      ERB_STAG = %w(<%= <%# <%)
      def is_erb_stag?(s)
        ERB_STAG.member?(s)
      end
    end

    Scanner.default_scanner = TrimScanner

    begin
      require 'strscan'
    rescue LoadError
    else
      class SimpleScanner < Scanner # :nodoc:
        def scan
          stag_reg = (stags == DEFAULT_STAGS) ? /(.*?)(<%[%=#]?|\z)/m : /(.*?)(#{stags.join('|')}|\z)/m
          etag_reg = (etags == DEFAULT_ETAGS) ? /(.*?)(%%?>|\z)/m : /(.*?)(#{etags.join('|')}|\z)/m
          scanner = StringScanner.new(@src)
          while ! scanner.eos?
            scanner.scan(@stag ? etag_reg : stag_reg)
            yield(scanner[1])
            yield(scanner[2])
          end
        end
      end
      Scanner.register_scanner(SimpleScanner, nil, false)

      class ExplicitScanner < Scanner # :nodoc:
        def scan
          stag_reg = /(.*?)(^[ \t]*<%-|<%-|#{stags.join('|')}|\z)/m
          etag_reg = /(.*?)(-%>|#{etags.join('|')}|\z)/m
          scanner = StringScanner.new(@src)
          while ! scanner.eos?
            scanner.scan(@stag ? etag_reg : stag_reg)
            yield(scanner[1])

            elem = scanner[2]
            if /[ \t]*<%-/ =~ elem
              yield('<%')
            elsif elem == '-%>'
              yield('%>')
              yield(:cr) if scanner.scan(/(\r?\n|\z)/)
            else
              yield(elem)
            end
          end
        end
      end
      Scanner.register_scanner(ExplicitScanner, '-', false)
    end

    class Buffer # :nodoc:
      def initialize(compiler, enc=nil, frozen=nil)
        @compiler = compiler
        @line = []
        @script = +''
        @script << "#coding:#{enc}\n" if enc
        @script << "#frozen-string-literal:#{frozen}\n" unless frozen.nil?
        @compiler.pre_cmd.each do |x|
          push(x)
        end
      end
      attr_reader :script

      def push(cmd)
        @line << cmd
      end

      def cr
        @script << (@line.join('; '))
        @line = []
        @script << "\n"
      end

      def close
        return unless @line
        @compiler.post_cmd.each do |x|
          push(x)
        end
        @script << (@line.join('; '))
        @line = nil
      end
    end

    def add_put_cmd(out, content)
      out.push("#{@put_cmd} #{content.dump}.freeze#{"\n" * content.count("\n")}")
    end

    def add_insert_cmd(out, content)
      out.push("#{@insert_cmd}((#{content}).to_s)")
    end

    # Compiles an ERB template into Ruby code.  Returns an array of the code
    # and encoding like ["code", Encoding].
    def compile(s)
      enc = s.encoding
      raise ArgumentError, "#{enc} is not ASCII compatible" if enc.dummy?
      s = s.b # see String#b
      magic_comment = detect_magic_comment(s, enc)
      out = Buffer.new(self, *magic_comment)

      self.content = +''
      scanner = make_scanner(s)
      scanner.scan do |token|
        next if token.nil?
        next if token == ''
        if scanner.stag.nil?
          compile_stag(token, out, scanner)
        else
          compile_etag(token, out, scanner)
        end
      end
      add_put_cmd(out, content) if content.size > 0
      out.close
      return out.script, *magic_comment
    end

    def compile_stag(stag, out, scanner)
      case stag
      when PercentLine
        add_put_cmd(out, content) if content.size > 0
        self.content = +''
        out.push(stag.to_s)
        out.cr
      when :cr
        out.cr
      when '<%', '<%=', '<%#'
        scanner.stag = stag
        add_put_cmd(out, content) if content.size > 0
        self.content = +''
      when "\n"
        content << "\n"
        add_put_cmd(out, content)
        self.content = +''
      when '<%%'
        content << '<%'
      else
        content << stag
      end
    end

    def compile_etag(etag, out, scanner)
      case etag
      when '%>'
        compile_content(scanner.stag, out)
        scanner.stag = nil
        self.content = +''
      when '%%>'
        content << '%>'
      else
        content << etag
      end
    end

    def compile_content(stag, out)
      case stag
      when '<%'
        if content[-1] == ?\n
          content.chop!
          out.push(content)
          out.cr
        else
          out.push(content)
        end
      when '<%='
        add_insert_cmd(out, content)
      when '<%#'
        # commented out
      end
    end

    def prepare_trim_mode(mode) # :nodoc:
      case mode
      when 1
        return [false, '>']
      when 2
        return [false, '<>']
      when 0, nil
        return [false, nil]
      when String
        unless mode.match?(/\A(%|-|>|<>){1,2}\z/)
          warn_invalid_trim_mode(mode, uplevel: 5)
        end

        perc = mode.include?('%')
        if mode.include?('-')
          return [perc, '-']
        elsif mode.include?('<>')
          return [perc, '<>']
        elsif mode.include?('>')
          return [perc, '>']
        else
          [perc, nil]
        end
      else
        warn_invalid_trim_mode(mode, uplevel: 5)
        return [false, nil]
      end
    end

    def make_scanner(src) # :nodoc:
      Scanner.make_scanner(src, @trim_mode, @percent)
    end

    # Construct a new compiler using the trim_mode. See ERB::new for available
    # trim modes.
    def initialize(trim_mode)
      @percent, @trim_mode = prepare_trim_mode(trim_mode)
      @put_cmd = 'print'
      @insert_cmd = @put_cmd
      @pre_cmd = []
      @post_cmd = []
    end
    attr_reader :percent, :trim_mode

    # The command to handle text that ends with a newline
    attr_accessor :put_cmd

    # The command to handle text that is inserted prior to a newline
    attr_accessor :insert_cmd

    # An array of commands prepended to compiled code
    attr_accessor :pre_cmd

    # An array of commands appended to compiled code
    attr_accessor :post_cmd

    private

    # A buffered text in #compile
    attr_accessor :content

    def detect_magic_comment(s, enc = nil)
      re = @percent ? /\G(?:<%#(.*)%>|%#(.*)\n)/ : /\G<%#(.*)%>/
      frozen = nil
      s.scan(re) do
        comment = $+
        comment = $1 if comment[/-\*-\s*(.*?)\s*-*-$/]
        case comment
        when %r"coding\s*[=:]\s*([[:alnum:]\-_]+)"
          enc = Encoding.find($1.sub(/-(?:mac|dos|unix)/i, ''))
        when %r"frozen[-_]string[-_]literal\s*:\s*([[:alnum:]]+)"
          frozen = $1
        end
      end
      return enc, frozen
    end

    def warn_invalid_trim_mode(mode, uplevel:)
      warn "Invalid ERB trim mode: #{mode.inspect} (trim_mode: nil, 0, 1, 2, or String composed of '%' and/or '-', '>', '<>')", uplevel: uplevel + 1
    end
  end
end

#--
# ERB
class ERB
  #
  # Constructs a new ERB object with the template specified in _str_.
  #
  # An ERB object works by building a chunk of Ruby code that will output
  # the completed template when run.
  #
  # If _trim_mode_ is passed a String containing one or more of the following
  # modifiers, ERB will adjust its code generation as listed:
  #
  #     %  enables Ruby code processing for lines beginning with %
  #     <> omit newline for lines starting with <% and ending in %>
  #     >  omit newline for lines ending in %>
  #     -  omit blank lines ending in -%>
  #
  # _eoutvar_ can be used to set the name of the variable ERB will build up
  # its output in.  This is useful when you need to run multiple ERB
  # templates through the same binding and/or when you want to control where
  # output ends up.  Pass the name of the variable to be used inside a String.
  #
  # === Example
  #
  #  require "erb"
  #
  #  # build data class
  #  class Listings
  #    PRODUCT = { :name => "Chicken Fried Steak",
  #                :desc => "A well messages pattie, breaded and fried.",
  #                :cost => 9.95 }
  #
  #    attr_reader :product, :price
  #
  #    def initialize( product = "", price = "" )
  #      @product = product
  #      @price = price
  #    end
  #
  #    def build
  #      b = binding
  #      # create and run templates, filling member data variables
  #      ERB.new(<<-'END_PRODUCT'.gsub(/^\s+/, ""), trim_mode: "", eoutvar: "@product").result b
  #        <%= PRODUCT[:name] %>
  #        <%= PRODUCT[:desc] %>
  #      END_PRODUCT
  #      ERB.new(<<-'END_PRICE'.gsub(/^\s+/, ""), trim_mode: "", eoutvar: "@price").result b
  #        <%= PRODUCT[:name] %> -- <%= PRODUCT[:cost] %>
  #        <%= PRODUCT[:desc] %>
  #      END_PRICE
  #    end
  #  end
  #
  #  # setup template data
  #  listings = Listings.new
  #  listings.build
  #
  #  puts listings.product + "\n" + listings.price
  #
  # _Generates_
  #
  #  Chicken Fried Steak
  #  A well messages pattie, breaded and fried.
  #
  #  Chicken Fried Steak -- 9.95
  #  A well messages pattie, breaded and fried.
  #
  def initialize(str, safe_level=NOT_GIVEN, legacy_trim_mode=NOT_GIVEN, legacy_eoutvar=NOT_GIVEN, trim_mode: nil, eoutvar: '_erbout')
    # Complex initializer for $SAFE deprecation at [Feature #14256]. Use keyword arguments to pass trim_mode or eoutvar.
    if safe_level != NOT_GIVEN
      warn 'Passing safe_level with the 2nd argument of ERB.new is deprecated. Do not use it, and specify other arguments as keyword arguments.', uplevel: 1 if $VERBOSE || !ZERO_SAFE_LEVELS.include?(safe_level)
    end
    if legacy_trim_mode != NOT_GIVEN
      warn 'Passing trim_mode with the 3rd argument of ERB.new is deprecated. Use keyword argument like ERB.new(str, trim_mode: ...) instead.', uplevel: 1 if $VERBOSE
      trim_mode = legacy_trim_mode
    end
    if legacy_eoutvar != NOT_GIVEN
      warn 'Passing eoutvar with the 4th argument of ERB.new is deprecated. Use keyword argument like ERB.new(str, eoutvar: ...) instead.', uplevel: 1 if $VERBOSE
      eoutvar = legacy_eoutvar
    end

    compiler = make_compiler(trim_mode)
    set_eoutvar(compiler, eoutvar)
    @src, @encoding, @frozen_string = *compiler.compile(str)
    @filename = nil
    @lineno = 0
    @_init = self.class.singleton_class
  end
  NOT_GIVEN = Object.new
  private_constant :NOT_GIVEN
  ZERO_SAFE_LEVELS = [0, nil]
  private_constant :ZERO_SAFE_LEVELS

  ##
  # Creates a new compiler for ERB.  See ERB::Compiler.new for details

  def make_compiler(trim_mode)
    ERB::Compiler.new(trim_mode)
  end

  # The Ruby code generated by ERB
  attr_reader :src

  # The encoding to eval
  attr_reader :encoding

  # The optional _filename_ argument passed to Kernel#eval when the ERB code
  # is run
  attr_accessor :filename

  # The optional _lineno_ argument passed to Kernel#eval when the ERB code
  # is run
  attr_accessor :lineno

  #
  # Sets optional filename and line number that will be used in ERB code
  # evaluation and error reporting. See also #filename= and #lineno=
  #
  #   erb = ERB.new('<%= some_x %>')
  #   erb.render
  #   # undefined local variable or method `some_x'
  #   #   from (erb):1
  #
  #   erb.location = ['file.erb', 3]
  #   # All subsequent error reporting would use new location
  #   erb.render
  #   # undefined local variable or method `some_x'
  #   #   from file.erb:4
  #
  def location=((filename, lineno))
    @filename = filename
    @lineno = lineno if lineno
  end

  #
  # Can be used to set _eoutvar_ as described in ERB::new.  It's probably
  # easier to just use the constructor though, since calling this method
  # requires the setup of an ERB _compiler_ object.
  #
  def set_eoutvar(compiler, eoutvar = '_erbout')
    compiler.put_cmd = "#{eoutvar}.<<"
    compiler.insert_cmd = "#{eoutvar}.<<"
    compiler.pre_cmd = ["#{eoutvar} = +''"]
    compiler.post_cmd = [eoutvar]
  end

  # Generate results and print them. (see ERB#result)
  def run(b=new_toplevel)
    print self.result(b)
  end

  #
  # Executes the generated ERB code to produce a completed template, returning
  # the results of that code.  (See ERB::new for details on how this process
  # can be affected by _safe_level_.)
  #
  # _b_ accepts a Binding object which is used to set the context of
  # code evaluation.
  #
  def result(b=new_toplevel)
    unless @_init.equal?(self.class.singleton_class)
      raise ArgumentError, "not initialized"
    end
    eval(@src, b, (@filename || '(erb)'), @lineno)
  end

  # Render a template on a new toplevel binding with local variables specified
  # by a Hash object.
  def result_with_hash(hash)
    b = new_toplevel(hash.keys)
    hash.each_pair do |key, value|
      b.local_variable_set(key, value)
    end
    result(b)
  end

  ##
  # Returns a new binding each time *near* TOPLEVEL_BINDING for runs that do
  # not specify a binding.

  def new_toplevel(vars = nil)
    b = TOPLEVEL_BINDING
    if vars
      vars = vars.select {|v| b.local_variable_defined?(v)}
      unless vars.empty?
        return b.eval("tap {|;#{vars.join(',')}| break binding}")
      end
    end
    b.dup
  end
  private :new_toplevel

  # Define _methodname_ as instance method of _mod_ from compiled Ruby source.
  #
  # example:
  #   filename = 'example.rhtml'   # 'arg1' and 'arg2' are used in example.rhtml
  #   erb = ERB.new(File.read(filename))
  #   erb.def_method(MyClass, 'render(arg1, arg2)', filename)
  #   print MyClass.new.render('foo', 123)
  def def_method(mod, methodname, fname='(ERB)')
    src = self.src.sub(/^(?!#|$)/) {"def #{methodname}\n"} << "\nend\n"
    mod.module_eval do
      eval(src, binding, fname, -1)
    end
  end

  # Create unnamed module, define _methodname_ as instance method of it, and return it.
  #
  # example:
  #   filename = 'example.rhtml'   # 'arg1' and 'arg2' are used in example.rhtml
  #   erb = ERB.new(File.read(filename))
  #   erb.filename = filename
  #   MyModule = erb.def_module('render(arg1, arg2)')
  #   class MyClass
  #     include MyModule
  #   end
  def def_module(methodname='erb')
    mod = Module.new
    def_method(mod, methodname, @filename || '(ERB)')
    mod
  end

  # Define unnamed class which has _methodname_ as instance method, and return it.
  #
  # example:
  #   class MyClass_
  #     def initialize(arg1, arg2)
  #       @arg1 = arg1;  @arg2 = arg2
  #     end
  #   end
  #   filename = 'example.rhtml'  # @arg1 and @arg2 are used in example.rhtml
  #   erb = ERB.new(File.read(filename))
  #   erb.filename = filename
  #   MyClass = erb.def_class(MyClass_, 'render()')
  #   print MyClass.new('foo', 123).render()
  def def_class(superklass=Object, methodname='result')
    cls = Class.new(superklass)
    def_method(cls, methodname, @filename || '(ERB)')
    cls
  end
end

#--
# ERB::Util
class ERB
  # A utility module for conversion routines, often handy in HTML generation.
  module Util
    public
    #
    # A utility method for escaping HTML tag characters in _s_.
    #
    #   require "erb"
    #   include ERB::Util
    #
    #   puts html_escape("is a > 0 & a < 10?")
    #
    # _Generates_
    #
    #   is a &gt; 0 &amp; a &lt; 10?
    #
    def html_escape(s)
      CGI.escapeHTML(s.to_s)
    end
    alias h html_escape
    module_function :h
    module_function :html_escape

    #
    # A utility method for encoding the String _s_ as a URL.
    #
    #   require "erb"
    #   include ERB::Util
    #
    #   puts url_encode("Programming Ruby:  The Pragmatic Programmer's Guide")
    #
    # _Generates_
    #
    #   Programming%20Ruby%3A%20%20The%20Pragmatic%20Programmer%27s%20Guide
    #
    def url_encode(s)
      s.to_s.b.gsub(/[^a-zA-Z0-9_\-.~]/n) { |m|
        sprintf("%%%02X", m.unpack1("C"))
      }
    end
    alias u url_encode
    module_function :u
    module_function :url_encode
  end
end

#--
# ERB::DefMethod
class ERB
  # Utility module to define eRuby script as instance method.
  #
  # === Example
  #
  # example.rhtml:
  #   <% for item in @items %>
  #   <b><%= item %></b>
  #   <% end %>
  #
  # example.rb:
  #   require 'erb'
  #   class MyClass
  #     extend ERB::DefMethod
  #     def_erb_method('render()', 'example.rhtml')
  #     def initialize(items)
  #       @items = items
  #     end
  #   end
  #   print MyClass.new([10,20,30]).render()
  #
  # result:
  #
  #   <b>10</b>
  #
  #   <b>20</b>
  #
  #   <b>30</b>
  #
  module DefMethod
    public
    # define _methodname_ as instance method of current module, using ERB
    # object or eRuby file
    def def_erb_method(methodname, erb_or_fname)
      if erb_or_fname.kind_of? String
        fname = erb_or_fname
        erb = ERB.new(File.read(fname))
        erb.def_method(self, methodname, fname)
      else
        erb = erb_or_fname
        erb.def_method(self, methodname, erb.filename || '(ERB)')
      end
    end
    module_function :def_erb_method
  end
end
# :stopdoc:
module Forwardable
  def self._valid_method?(method)
    iseq = RubyVM::InstructionSequence.compile("().#{method}", nil, nil, 0, false)
  rescue SyntaxError
    false
  else
    iseq.to_a.dig(-1, 1, 1, :mid) == method.to_sym
  end

  def self._compile_method(src, file, line)
    RubyVM::InstructionSequence.compile(src, file, file, line,
               trace_instruction: false)
      .eval
  end
end
# frozen_string_literal: true
#  Include the English library file in a Ruby script, and you can
#  reference the global variables such as <tt>$_</tt> using less
#  cryptic names, listed below.
#
#  Without 'English':
#
#      $\ = ' -- '
#      "waterbuffalo" =~ /buff/
#      print $', $$, "\n"
#
#  With English:
#
#      require "English"
#
#      $OUTPUT_FIELD_SEPARATOR = ' -- '
#      "waterbuffalo" =~ /buff/
#      print $POSTMATCH, $PID, "\n"
#
#  Below is a full list of descriptive aliases and their associated global
#  variable:
#
#  $ERROR_INFO::              $!
#  $ERROR_POSITION::          $@
#  $FS::                      $;
#  $FIELD_SEPARATOR::         $;
#  $OFS::                     $,
#  $OUTPUT_FIELD_SEPARATOR::  $,
#  $RS::                      $/
#  $INPUT_RECORD_SEPARATOR::  $/
#  $ORS::                     $\
#  $OUTPUT_RECORD_SEPARATOR:: $\
#  $INPUT_LINE_NUMBER::       $.
#  $NR::                      $.
#  $LAST_READ_LINE::          $_
#  $DEFAULT_OUTPUT::          $>
#  $DEFAULT_INPUT::           $<
#  $PID::                     $$
#  $PROCESS_ID::              $$
#  $CHILD_STATUS::            $?
#  $LAST_MATCH_INFO::         $~
#  $IGNORECASE::              $=
#  $ARGV::                    $*
#  $MATCH::                   $&
#  $PREMATCH::                $`
#  $POSTMATCH::               $'
#  $LAST_PAREN_MATCH::        $+
#
module English end if false

# The exception object passed to +raise+.
alias $ERROR_INFO              $!

# The stack backtrace generated by the last
# exception. See Kernel#caller for details. Thread local.
alias $ERROR_POSITION          $@

# The default separator pattern used by String#split.  May be set from
# the command line using the <tt>-F</tt> flag.
alias $FS                      $;

# The default separator pattern used by String#split.  May be set from
# the command line using the <tt>-F</tt> flag.
alias $FIELD_SEPARATOR         $;

# The separator string output between the parameters to methods such
# as Kernel#print and Array#join. Defaults to +nil+, which adds no
# text.
alias $OFS                     $,

# The separator string output between the parameters to methods such
# as Kernel#print and Array#join. Defaults to +nil+, which adds no
# text.
alias $OUTPUT_FIELD_SEPARATOR  $,

# The input record separator (newline by default). This is the value
# that routines such as Kernel#gets use to determine record
# boundaries. If set to +nil+, +gets+ will read the entire file.
alias $RS                      $/

# The input record separator (newline by default). This is the value
# that routines such as Kernel#gets use to determine record
# boundaries. If set to +nil+, +gets+ will read the entire file.
alias $INPUT_RECORD_SEPARATOR  $/

# The string appended to the output of every call to methods such as
# Kernel#print and IO#write. The default value is +nil+.
alias $ORS                     $\

# The string appended to the output of every call to methods such as
# Kernel#print and IO#write. The default value is +nil+.
alias $OUTPUT_RECORD_SEPARATOR $\

# The number of the last line read from the current input file.
alias $INPUT_LINE_NUMBER       $.

# The number of the last line read from the current input file.
alias $NR                      $.

# The last line read by Kernel#gets or
# Kernel#readline. Many string-related functions in the
# Kernel module operate on <tt>$_</tt> by default. The variable is
# local to the current scope. Thread local.
alias $LAST_READ_LINE          $_

# The destination of output for Kernel#print
# and Kernel#printf. The default value is
# <tt>$stdout</tt>.
alias $DEFAULT_OUTPUT          $>

# An object that provides access to the concatenation
# of the contents of all the files
# given as command-line arguments, or <tt>$stdin</tt>
# (in the case where there are no
# arguments). <tt>$<</tt> supports methods similar to a
# File object:
# +inmode+, +close+,
# <tt>closed?</tt>, +each+,
# <tt>each_byte</tt>, <tt>each_line</tt>,
# +eof+, <tt>eof?</tt>, +file+,
# +filename+, +fileno+,
# +getc+, +gets+, +lineno+,
# <tt>lineno=</tt>, +path+,
# +pos+, <tt>pos=</tt>,
# +read+, +readchar+,
# +readline+, +readlines+,
# +rewind+, +seek+, +skip+,
# +tell+, <tt>to_a</tt>, <tt>to_i</tt>,
# <tt>to_io</tt>, <tt>to_s</tt>, along with the
# methods in Enumerable. The method +file+
# returns a File object for the file currently
# being read. This may change as <tt>$<</tt> reads
# through the files on the command line. Read only.
alias $DEFAULT_INPUT           $<

# The process number of the program being executed. Read only.
alias $PID                     $$

# The process number of the program being executed. Read only.
alias $PROCESS_ID              $$

# The exit status of the last child process to terminate. Read
# only. Thread local.
alias $CHILD_STATUS            $?

# A +MatchData+ object that encapsulates the results of a successful
# pattern match. The variables <tt>$&</tt>, <tt>$`</tt>, <tt>$'</tt>,
# and <tt>$1</tt> to <tt>$9</tt> are all derived from
# <tt>$~</tt>. Assigning to <tt>$~</tt> changes the values of these
# derived variables.  This variable is local to the current
# scope.
alias $LAST_MATCH_INFO         $~

# This variable is no longer effective. Deprecated.
alias $IGNORECASE              $=

# An array of strings containing the command-line
# options from the invocation of the program. Options
# used by the Ruby interpreter will have been
# removed. Read only. Also known simply as +ARGV+.
alias $ARGV                    $*

# The string matched by the last successful pattern
# match. This variable is local to the current
# scope. Read only.
alias $MATCH                   $&

# The string preceding the match in the last
# successful pattern match. This variable is local to
# the current scope. Read only.
alias $PREMATCH                $`

# The string following the match in the last
# successful pattern match. This variable is local to
# the current scope. Read only.
alias $POSTMATCH               $'

# The contents of the highest-numbered group matched in the last
# successful pattern match. Thus, in <tt>"cat" =~ /(c|a)(t|z)/</tt>,
# <tt>$+</tt> will be set to "t".  This variable is local to the
# current scope. Read only.
alias $LAST_PAREN_MATCH        $+
# frozen_string_literal: true
# date.rb: Written by Tadayoshi Funaba 1998-2011

require 'date_core'

class Date
  VERSION = '3.1.3' # :nodoc:

  def infinite?
    false
  end

  class Infinity < Numeric # :nodoc:

    def initialize(d=1) @d = d <=> 0 end

    def d() @d end

    protected :d

    def zero?() false end
    def finite?() false end
    def infinite?() d.nonzero? end
    def nan?() d.zero? end

    def abs() self.class.new end

    def -@() self.class.new(-d) end
    def +@() self.class.new(+d) end

    def <=>(other)
      case other
      when Infinity; return d <=> other.d
      when Numeric; return d
      else
        begin
          l, r = other.coerce(self)
          return l <=> r
        rescue NoMethodError
        end
      end
      nil
    end

    def coerce(other)
      case other
      when Numeric; return -d, d
      else
        super
      end
    end

    def to_f
      return 0 if @d == 0
      if @d > 0
        Float::INFINITY
      else
        -Float::INFINITY
      end
    end

  end

end
# frozen_string_literal: true
#
# This class implements a pretty printing algorithm. It finds line breaks and
# nice indentations for grouped structure.
#
# By default, the class assumes that primitive elements are strings and each
# byte in the strings have single column in width. But it can be used for
# other situations by giving suitable arguments for some methods:
# * newline object and space generation block for PrettyPrint.new
# * optional width argument for PrettyPrint#text
# * PrettyPrint#breakable
#
# There are several candidate uses:
# * text formatting using proportional fonts
# * multibyte characters which has columns different to number of bytes
# * non-string formatting
#
# == Bugs
# * Box based formatting?
# * Other (better) model/algorithm?
#
# Report any bugs at http://bugs.ruby-lang.org
#
# == References
# Christian Lindig, Strictly Pretty, March 2000,
# http://www.st.cs.uni-sb.de/~lindig/papers/#pretty
#
# Philip Wadler, A prettier printer, March 1998,
# http://homepages.inf.ed.ac.uk/wadler/topics/language-design.html#prettier
#
# == Author
# Tanaka Akira <akr@fsij.org>
#
class PrettyPrint

  # This is a convenience method which is same as follows:
  #
  #   begin
  #     q = PrettyPrint.new(output, maxwidth, newline, &genspace)
  #     ...
  #     q.flush
  #     output
  #   end
  #
  def PrettyPrint.format(output=''.dup, maxwidth=79, newline="\n", genspace=lambda {|n| ' ' * n})
    q = PrettyPrint.new(output, maxwidth, newline, &genspace)
    yield q
    q.flush
    output
  end

  # This is similar to PrettyPrint::format but the result has no breaks.
  #
  # +maxwidth+, +newline+ and +genspace+ are ignored.
  #
  # The invocation of +breakable+ in the block doesn't break a line and is
  # treated as just an invocation of +text+.
  #
  def PrettyPrint.singleline_format(output=''.dup, maxwidth=nil, newline=nil, genspace=nil)
    q = SingleLine.new(output)
    yield q
    output
  end

  # Creates a buffer for pretty printing.
  #
  # +output+ is an output target. If it is not specified, '' is assumed. It
  # should have a << method which accepts the first argument +obj+ of
  # PrettyPrint#text, the first argument +sep+ of PrettyPrint#breakable, the
  # first argument +newline+ of PrettyPrint.new, and the result of a given
  # block for PrettyPrint.new.
  #
  # +maxwidth+ specifies maximum line length. If it is not specified, 79 is
  # assumed. However actual outputs may overflow +maxwidth+ if long
  # non-breakable texts are provided.
  #
  # +newline+ is used for line breaks. "\n" is used if it is not specified.
  #
  # The block is used to generate spaces. {|width| ' ' * width} is used if it
  # is not given.
  #
  def initialize(output=''.dup, maxwidth=79, newline="\n", &genspace)
    @output = output
    @maxwidth = maxwidth
    @newline = newline
    @genspace = genspace || lambda {|n| ' ' * n}

    @output_width = 0
    @buffer_width = 0
    @buffer = []

    root_group = Group.new(0)
    @group_stack = [root_group]
    @group_queue = GroupQueue.new(root_group)
    @indent = 0
  end

  # The output object.
  #
  # This defaults to '', and should accept the << method
  attr_reader :output

  # The maximum width of a line, before it is separated in to a newline
  #
  # This defaults to 79, and should be an Integer
  attr_reader :maxwidth

  # The value that is appended to +output+ to add a new line.
  #
  # This defaults to "\n", and should be String
  attr_reader :newline

  # A lambda or Proc, that takes one argument, of an Integer, and returns
  # the corresponding number of spaces.
  #
  # By default this is:
  #   lambda {|n| ' ' * n}
  attr_reader :genspace

  # The number of spaces to be indented
  attr_reader :indent

  # The PrettyPrint::GroupQueue of groups in stack to be pretty printed
  attr_reader :group_queue

  # Returns the group most recently added to the stack.
  #
  # Contrived example:
  #   out = ""
  #   => ""
  #   q = PrettyPrint.new(out)
  #   => #<PrettyPrint:0x82f85c0 @output="", @maxwidth=79, @newline="\n", @genspace=#<Proc:0x82f8368@/home/vbatts/.rvm/rubies/ruby-head/lib/ruby/2.0.0/prettyprint.rb:82 (lambda)>, @output_width=0, @buffer_width=0, @buffer=[], @group_stack=[#<PrettyPrint::Group:0x82f8138 @depth=0, @breakables=[], @break=false>], @group_queue=#<PrettyPrint::GroupQueue:0x82fb7c0 @queue=[[#<PrettyPrint::Group:0x82f8138 @depth=0, @breakables=[], @break=false>]]>, @indent=0>
  #   q.group {
  #     q.text q.current_group.inspect
  #     q.text q.newline
  #     q.group(q.current_group.depth + 1) {
  #       q.text q.current_group.inspect
  #       q.text q.newline
  #       q.group(q.current_group.depth + 1) {
  #         q.text q.current_group.inspect
  #         q.text q.newline
  #         q.group(q.current_group.depth + 1) {
  #           q.text q.current_group.inspect
  #           q.text q.newline
  #         }
  #       }
  #     }
  #   }
  #   => 284
  #    puts out
  #   #<PrettyPrint::Group:0x8354758 @depth=1, @breakables=[], @break=false>
  #   #<PrettyPrint::Group:0x8354550 @depth=2, @breakables=[], @break=false>
  #   #<PrettyPrint::Group:0x83541cc @depth=3, @breakables=[], @break=false>
  #   #<PrettyPrint::Group:0x8347e54 @depth=4, @breakables=[], @break=false>
  def current_group
    @group_stack.last
  end

  # Breaks the buffer into lines that are shorter than #maxwidth
  def break_outmost_groups
    while @maxwidth < @output_width + @buffer_width
      return unless group = @group_queue.deq
      until group.breakables.empty?
        data = @buffer.shift
        @output_width = data.output(@output, @output_width)
        @buffer_width -= data.width
      end
      while !@buffer.empty? && Text === @buffer.first
        text = @buffer.shift
        @output_width = text.output(@output, @output_width)
        @buffer_width -= text.width
      end
    end
  end

  # This adds +obj+ as a text of +width+ columns in width.
  #
  # If +width+ is not specified, obj.length is used.
  #
  def text(obj, width=obj.length)
    if @buffer.empty?
      @output << obj
      @output_width += width
    else
      text = @buffer.last
      unless Text === text
        text = Text.new
        @buffer << text
      end
      text.add(obj, width)
      @buffer_width += width
      break_outmost_groups
    end
  end

  # This is similar to #breakable except
  # the decision to break or not is determined individually.
  #
  # Two #fill_breakable under a group may cause 4 results:
  # (break,break), (break,non-break), (non-break,break), (non-break,non-break).
  # This is different to #breakable because two #breakable under a group
  # may cause 2 results:
  # (break,break), (non-break,non-break).
  #
  # The text +sep+ is inserted if a line is not broken at this point.
  #
  # If +sep+ is not specified, " " is used.
  #
  # If +width+ is not specified, +sep.length+ is used. You will have to
  # specify this when +sep+ is a multibyte character, for example.
  #
  def fill_breakable(sep=' ', width=sep.length)
    group { breakable sep, width }
  end

  # This says "you can break a line here if necessary", and a +width+\-column
  # text +sep+ is inserted if a line is not broken at the point.
  #
  # If +sep+ is not specified, " " is used.
  #
  # If +width+ is not specified, +sep.length+ is used. You will have to
  # specify this when +sep+ is a multibyte character, for example.
  #
  def breakable(sep=' ', width=sep.length)
    group = @group_stack.last
    if group.break?
      flush
      @output << @newline
      @output << @genspace.call(@indent)
      @output_width = @indent
      @buffer_width = 0
    else
      @buffer << Breakable.new(sep, width, self)
      @buffer_width += width
      break_outmost_groups
    end
  end

  # Groups line break hints added in the block. The line break hints are all
  # to be used or not.
  #
  # If +indent+ is specified, the method call is regarded as nested by
  # nest(indent) { ... }.
  #
  # If +open_obj+ is specified, <tt>text open_obj, open_width</tt> is called
  # before grouping. If +close_obj+ is specified, <tt>text close_obj,
  # close_width</tt> is called after grouping.
  #
  def group(indent=0, open_obj='', close_obj='', open_width=open_obj.length, close_width=close_obj.length)
    text open_obj, open_width
    group_sub {
      nest(indent) {
        yield
      }
    }
    text close_obj, close_width
  end

  # Takes a block and queues a new group that is indented 1 level further.
  def group_sub
    group = Group.new(@group_stack.last.depth + 1)
    @group_stack.push group
    @group_queue.enq group
    begin
      yield
    ensure
      @group_stack.pop
      if group.breakables.empty?
        @group_queue.delete group
      end
    end
  end

  # Increases left margin after newline with +indent+ for line breaks added in
  # the block.
  #
  def nest(indent)
    @indent += indent
    begin
      yield
    ensure
      @indent -= indent
    end
  end

  # outputs buffered data.
  #
  def flush
    @buffer.each {|data|
      @output_width = data.output(@output, @output_width)
    }
    @buffer.clear
    @buffer_width = 0
  end

  # The Text class is the means by which to collect strings from objects.
  #
  # This class is intended for internal use of the PrettyPrint buffers.
  class Text # :nodoc:

    # Creates a new text object.
    #
    # This constructor takes no arguments.
    #
    # The workflow is to append a PrettyPrint::Text object to the buffer, and
    # being able to call the buffer.last() to reference it.
    #
    # As there are objects, use PrettyPrint::Text#add to include the objects
    # and the width to utilized by the String version of this object.
    def initialize
      @objs = []
      @width = 0
    end

    # The total width of the objects included in this Text object.
    attr_reader :width

    # Render the String text of the objects that have been added to this Text object.
    #
    # Output the text to +out+, and increment the width to +output_width+
    def output(out, output_width)
      @objs.each {|obj| out << obj}
      output_width + @width
    end

    # Include +obj+ in the objects to be pretty printed, and increment
    # this Text object's total width by +width+
    def add(obj, width)
      @objs << obj
      @width += width
    end
  end

  # The Breakable class is used for breaking up object information
  #
  # This class is intended for internal use of the PrettyPrint buffers.
  class Breakable # :nodoc:

    # Create a new Breakable object.
    #
    # Arguments:
    # * +sep+ String of the separator
    # * +width+ Integer width of the +sep+
    # * +q+ parent PrettyPrint object, to base from
    def initialize(sep, width, q)
      @obj = sep
      @width = width
      @pp = q
      @indent = q.indent
      @group = q.current_group
      @group.breakables.push self
    end

    # Holds the separator String
    #
    # The +sep+ argument from ::new
    attr_reader :obj

    # The width of +obj+ / +sep+
    attr_reader :width

    # The number of spaces to indent.
    #
    # This is inferred from +q+ within PrettyPrint, passed in ::new
    attr_reader :indent

    # Render the String text of the objects that have been added to this
    # Breakable object.
    #
    # Output the text to +out+, and increment the width to +output_width+
    def output(out, output_width)
      @group.breakables.shift
      if @group.break?
        out << @pp.newline
        out << @pp.genspace.call(@indent)
        @indent
      else
        @pp.group_queue.delete @group if @group.breakables.empty?
        out << @obj
        output_width + @width
      end
    end
  end

  # The Group class is used for making indentation easier.
  #
  # While this class does neither the breaking into newlines nor indentation,
  # it is used in a stack (as well as a queue) within PrettyPrint, to group
  # objects.
  #
  # For information on using groups, see PrettyPrint#group
  #
  # This class is intended for internal use of the PrettyPrint buffers.
  class Group # :nodoc:
    # Create a Group object
    #
    # Arguments:
    # * +depth+ - this group's relation to previous groups
    def initialize(depth)
      @depth = depth
      @breakables = []
      @break = false
    end

    # This group's relation to previous groups
    attr_reader :depth

    # Array to hold the Breakable objects for this Group
    attr_reader :breakables

    # Makes a break for this Group, and returns true
    def break
      @break = true
    end

    # Boolean of whether this Group has made a break
    def break?
      @break
    end

    # Boolean of whether this Group has been queried for being first
    #
    # This is used as a predicate, and ought to be called first.
    def first?
      if defined? @first
        false
      else
        @first = false
        true
      end
    end
  end

  # The GroupQueue class is used for managing the queue of Group to be pretty
  # printed.
  #
  # This queue groups the Group objects, based on their depth.
  #
  # This class is intended for internal use of the PrettyPrint buffers.
  class GroupQueue # :nodoc:
    # Create a GroupQueue object
    #
    # Arguments:
    # * +groups+ - one or more PrettyPrint::Group objects
    def initialize(*groups)
      @queue = []
      groups.each {|g| enq g}
    end

    # Enqueue +group+
    #
    # This does not strictly append the group to the end of the queue,
    # but instead adds it in line, base on the +group.depth+
    def enq(group)
      depth = group.depth
      @queue << [] until depth < @queue.length
      @queue[depth] << group
    end

    # Returns the outer group of the queue
    def deq
      @queue.each {|gs|
        (gs.length-1).downto(0) {|i|
          unless gs[i].breakables.empty?
            group = gs.slice!(i, 1).first
            group.break
            return group
          end
        }
        gs.each {|group| group.break}
        gs.clear
      }
      return nil
    end

    # Remote +group+ from this queue
    def delete(group)
      @queue[group.depth].delete(group)
    end
  end

  # PrettyPrint::SingleLine is used by PrettyPrint.singleline_format
  #
  # It is passed to be similar to a PrettyPrint object itself, by responding to:
  # * #text
  # * #breakable
  # * #nest
  # * #group
  # * #flush
  # * #first?
  #
  # but instead, the output has no line breaks
  #
  class SingleLine
    # Create a PrettyPrint::SingleLine object
    #
    # Arguments:
    # * +output+ - String (or similar) to store rendered text. Needs to respond to '<<'
    # * +maxwidth+ - Argument position expected to be here for compatibility.
    #                This argument is a noop.
    # * +newline+ - Argument position expected to be here for compatibility.
    #               This argument is a noop.
    def initialize(output, maxwidth=nil, newline=nil)
      @output = output
      @first = [true]
    end

    # Add +obj+ to the text to be output.
    #
    # +width+ argument is here for compatibility. It is a noop argument.
    def text(obj, width=nil)
      @output << obj
    end

    # Appends +sep+ to the text to be output. By default +sep+ is ' '
    #
    # +width+ argument is here for compatibility. It is a noop argument.
    def breakable(sep=' ', width=nil)
      @output << sep
    end

    # Takes +indent+ arg, but does nothing with it.
    #
    # Yields to a block.
    def nest(indent) # :nodoc:
      yield
    end

    # Opens a block for grouping objects to be pretty printed.
    #
    # Arguments:
    # * +indent+ - noop argument. Present for compatibility.
    # * +open_obj+ - text appended before the &blok. Default is ''
    # * +close_obj+ - text appended after the &blok. Default is ''
    # * +open_width+ - noop argument. Present for compatibility.
    # * +close_width+ - noop argument. Present for compatibility.
    def group(indent=nil, open_obj='', close_obj='', open_width=nil, close_width=nil)
      @first.push true
      @output << open_obj
      yield
      @output << close_obj
      @first.pop
    end

    # Method present for compatibility, but is a noop
    def flush # :nodoc:
    end

    # This is used as a predicate, and ought to be called first.
    def first?
      result = @first[-1]
      @first[-1] = false
      result
    end
  end
end
# frozen_string_literal: true
#
# ipaddr.rb - A class to manipulate an IP address
#
# Copyright (c) 2002 Hajimu UMEMOTO <ume@mahoroba.org>.
# Copyright (c) 2007, 2009, 2012 Akinori MUSHA <knu@iDaemons.org>.
# All rights reserved.
#
# You can redistribute and/or modify it under the same terms as Ruby.
#
# $Id$
#
# Contact:
#   - Akinori MUSHA <knu@iDaemons.org> (current maintainer)
#
# TODO:
#   - scope_id support
#
require 'socket'

# IPAddr provides a set of methods to manipulate an IP address.  Both IPv4 and
# IPv6 are supported.
#
# == Example
#
#   require 'ipaddr'
#
#   ipaddr1 = IPAddr.new "3ffe:505:2::1"
#
#   p ipaddr1                   #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0001/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff>
#
#   p ipaddr1.to_s              #=> "3ffe:505:2::1"
#
#   ipaddr2 = ipaddr1.mask(48)  #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0000/ffff:ffff:ffff:0000:0000:0000:0000:0000>
#
#   p ipaddr2.to_s              #=> "3ffe:505:2::"
#
#   ipaddr3 = IPAddr.new "192.168.2.0/24"
#
#   p ipaddr3                   #=> #<IPAddr: IPv4:192.168.2.0/255.255.255.0>

class IPAddr

  # 32 bit mask for IPv4
  IN4MASK = 0xffffffff
  # 128 bit mask for IPv6
  IN6MASK = 0xffffffffffffffffffffffffffffffff
  # Format string for IPv6
  IN6FORMAT = (["%.4x"] * 8).join(':')

  # Regexp _internally_ used for parsing IPv4 address.
  RE_IPV4ADDRLIKE = %r{
    \A
    (\d+) \. (\d+) \. (\d+) \. (\d+)
    \z
  }x

  # Regexp _internally_ used for parsing IPv6 address.
  RE_IPV6ADDRLIKE_FULL = %r{
    \A
    (?:
      (?: [\da-f]{1,4} : ){7} [\da-f]{1,4}
    |
      ( (?: [\da-f]{1,4} : ){6} )
      (\d+) \. (\d+) \. (\d+) \. (\d+)
    )
    \z
  }xi

  # Regexp _internally_ used for parsing IPv6 address.
  RE_IPV6ADDRLIKE_COMPRESSED = %r{
    \A
    ( (?: (?: [\da-f]{1,4} : )* [\da-f]{1,4} )? )
    ::
    ( (?:
      ( (?: [\da-f]{1,4} : )* )
      (?:
        [\da-f]{1,4}
      |
        (\d+) \. (\d+) \. (\d+) \. (\d+)
      )
    )? )
    \z
  }xi

  # Generic IPAddr related error. Exceptions raised in this class should
  # inherit from Error.
  class Error < ArgumentError; end

  # Raised when the provided IP address is an invalid address.
  class InvalidAddressError < Error; end

  # Raised when the address family is invalid such as an address with an
  # unsupported family, an address with an inconsistent family, or an address
  # who's family cannot be determined.
  class AddressFamilyError < Error; end

  # Raised when the address is an invalid length.
  class InvalidPrefixError < InvalidAddressError; end

  # Returns the address family of this IP address.
  attr_reader :family

  # Creates a new ipaddr containing the given network byte ordered
  # string form of an IP address.
  def self.new_ntoh(addr)
    return new(ntop(addr))
  end

  # Convert a network byte ordered string form of an IP address into
  # human readable form.
  def self.ntop(addr)
    case addr.size
    when 4
      s = addr.unpack('C4').join('.')
    when 16
      s = IN6FORMAT % addr.unpack('n8')
    else
      raise AddressFamilyError, "unsupported address family"
    end
    return s
  end

  # Returns a new ipaddr built by bitwise AND.
  def &(other)
    return self.clone.set(@addr & coerce_other(other).to_i)
  end

  # Returns a new ipaddr built by bitwise OR.
  def |(other)
    return self.clone.set(@addr | coerce_other(other).to_i)
  end

  # Returns a new ipaddr built by bitwise right-shift.
  def >>(num)
    return self.clone.set(@addr >> num)
  end

  # Returns a new ipaddr built by bitwise left shift.
  def <<(num)
    return self.clone.set(addr_mask(@addr << num))
  end

  # Returns a new ipaddr built by bitwise negation.
  def ~
    return self.clone.set(addr_mask(~@addr))
  end

  # Returns true if two ipaddrs are equal.
  def ==(other)
    other = coerce_other(other)
  rescue
    false
  else
    @family == other.family && @addr == other.to_i
  end

  # Returns a new ipaddr built by masking IP address with the given
  # prefixlen/netmask. (e.g. 8, 64, "255.255.255.0", etc.)
  def mask(prefixlen)
    return self.clone.mask!(prefixlen)
  end

  # Returns true if the given ipaddr is in the range.
  #
  # e.g.:
  #   require 'ipaddr'
  #   net1 = IPAddr.new("192.168.2.0/24")
  #   net2 = IPAddr.new("192.168.2.100")
  #   net3 = IPAddr.new("192.168.3.0")
  #   p net1.include?(net2)     #=> true
  #   p net1.include?(net3)     #=> false
  def include?(other)
    other = coerce_other(other)
    if ipv4_mapped?
      if (@mask_addr >> 32) != 0xffffffffffffffffffffffff
        return false
      end
      mask_addr = (@mask_addr & IN4MASK)
      addr = (@addr & IN4MASK)
      family = Socket::AF_INET
    else
      mask_addr = @mask_addr
      addr = @addr
      family = @family
    end
    if other.ipv4_mapped?
      other_addr = (other.to_i & IN4MASK)
      other_family = Socket::AF_INET
    else
      other_addr = other.to_i
      other_family = other.family
    end

    if family != other_family
      return false
    end
    return ((addr & mask_addr) == (other_addr & mask_addr))
  end
  alias === include?

  # Returns the integer representation of the ipaddr.
  def to_i
    return @addr
  end

  # Returns a string containing the IP address representation.
  def to_s
    str = to_string
    return str if ipv4?

    str.gsub!(/\b0{1,3}([\da-f]+)\b/i, '\1')
    loop do
      break if str.sub!(/\A0:0:0:0:0:0:0:0\z/, '::')
      break if str.sub!(/\b0:0:0:0:0:0:0\b/, ':')
      break if str.sub!(/\b0:0:0:0:0:0\b/, ':')
      break if str.sub!(/\b0:0:0:0:0\b/, ':')
      break if str.sub!(/\b0:0:0:0\b/, ':')
      break if str.sub!(/\b0:0:0\b/, ':')
      break if str.sub!(/\b0:0\b/, ':')
      break
    end
    str.sub!(/:{3,}/, '::')

    if /\A::(ffff:)?([\da-f]{1,4}):([\da-f]{1,4})\z/i =~ str
      str = sprintf('::%s%d.%d.%d.%d', $1, $2.hex / 256, $2.hex % 256, $3.hex / 256, $3.hex % 256)
    end

    str
  end

  # Returns a string containing the IP address representation in
  # canonical form.
  def to_string
    return _to_string(@addr)
  end

  # Returns a network byte ordered string form of the IP address.
  def hton
    case @family
    when Socket::AF_INET
      return [@addr].pack('N')
    when Socket::AF_INET6
      return (0..7).map { |i|
        (@addr >> (112 - 16 * i)) & 0xffff
      }.pack('n8')
    else
      raise AddressFamilyError, "unsupported address family"
    end
  end

  # Returns true if the ipaddr is an IPv4 address.
  def ipv4?
    return @family == Socket::AF_INET
  end

  # Returns true if the ipaddr is an IPv6 address.
  def ipv6?
    return @family == Socket::AF_INET6
  end

  # Returns true if the ipaddr is a loopback address.
  def loopback?
    case @family
    when Socket::AF_INET
      @addr & 0xff000000 == 0x7f000000
    when Socket::AF_INET6
      @addr == 1
    else
      raise AddressFamilyError, "unsupported address family"
    end
  end

  # Returns true if the ipaddr is a private address.  IPv4 addresses
  # in 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16 as defined in RFC
  # 1918 and IPv6 Unique Local Addresses in fc00::/7 as defined in RFC
  # 4193 are considered private.
  def private?
    case @family
    when Socket::AF_INET
      @addr & 0xff000000 == 0x0a000000 ||    # 10.0.0.0/8
        @addr & 0xfff00000 == 0xac100000 ||  # 172.16.0.0/12
        @addr & 0xffff0000 == 0xc0a80000     # 192.168.0.0/16
    when Socket::AF_INET6
      @addr & 0xfe00_0000_0000_0000_0000_0000_0000_0000 == 0xfc00_0000_0000_0000_0000_0000_0000_0000
    else
      raise AddressFamilyError, "unsupported address family"
    end
  end

  # Returns true if the ipaddr is a link-local address.  IPv4
  # addresses in 169.254.0.0/16 reserved by RFC 3927 and Link-Local
  # IPv6 Unicast Addresses in fe80::/10 reserved by RFC 4291 are
  # considered link-local.
  def link_local?
    case @family
    when Socket::AF_INET
      @addr & 0xffff0000 == 0xa9fe0000 # 169.254.0.0/16
    when Socket::AF_INET6
      @addr & 0xffc0_0000_0000_0000_0000_0000_0000_0000 == 0xfe80_0000_0000_0000_0000_0000_0000_0000
    else
      raise AddressFamilyError, "unsupported address family"
    end
  end

  # Returns true if the ipaddr is an IPv4-mapped IPv6 address.
  def ipv4_mapped?
    return ipv6? && (@addr >> 32) == 0xffff
  end

  # Returns true if the ipaddr is an IPv4-compatible IPv6 address.
  def ipv4_compat?
    warn "IPAddr\##{__callee__} is obsolete", uplevel: 1 if $VERBOSE
    _ipv4_compat?
  end

  def _ipv4_compat?
    if !ipv6? || (@addr >> 32) != 0
      return false
    end
    a = (@addr & IN4MASK)
    return a != 0 && a != 1
  end

  private :_ipv4_compat?

  # Returns a new ipaddr built by converting the native IPv4 address
  # into an IPv4-mapped IPv6 address.
  def ipv4_mapped
    if !ipv4?
      raise InvalidAddressError, "not an IPv4 address"
    end
    return self.clone.set(@addr | 0xffff00000000, Socket::AF_INET6)
  end

  # Returns a new ipaddr built by converting the native IPv4 address
  # into an IPv4-compatible IPv6 address.
  def ipv4_compat
    warn "IPAddr\##{__callee__} is obsolete", uplevel: 1 if $VERBOSE
    if !ipv4?
      raise InvalidAddressError, "not an IPv4 address"
    end
    return self.clone.set(@addr, Socket::AF_INET6)
  end

  # Returns a new ipaddr built by converting the IPv6 address into a
  # native IPv4 address.  If the IP address is not an IPv4-mapped or
  # IPv4-compatible IPv6 address, returns self.
  def native
    if !ipv4_mapped? && !_ipv4_compat?
      return self
    end
    return self.clone.set(@addr & IN4MASK, Socket::AF_INET)
  end

  # Returns a string for DNS reverse lookup.  It returns a string in
  # RFC3172 form for an IPv6 address.
  def reverse
    case @family
    when Socket::AF_INET
      return _reverse + ".in-addr.arpa"
    when Socket::AF_INET6
      return ip6_arpa
    else
      raise AddressFamilyError, "unsupported address family"
    end
  end

  # Returns a string for DNS reverse lookup compatible with RFC3172.
  def ip6_arpa
    if !ipv6?
      raise InvalidAddressError, "not an IPv6 address"
    end
    return _reverse + ".ip6.arpa"
  end

  # Returns a string for DNS reverse lookup compatible with RFC1886.
  def ip6_int
    if !ipv6?
      raise InvalidAddressError, "not an IPv6 address"
    end
    return _reverse + ".ip6.int"
  end

  # Returns the successor to the ipaddr.
  def succ
    return self.clone.set(@addr + 1, @family)
  end

  # Compares the ipaddr with another.
  def <=>(other)
    other = coerce_other(other)
  rescue
    nil
  else
    @addr <=> other.to_i if other.family == @family
  end
  include Comparable

  # Checks equality used by Hash.
  def eql?(other)
    return self.class == other.class && self.hash == other.hash && self == other
  end

  # Returns a hash value used by Hash, Set, and Array classes
  def hash
    return ([@addr, @mask_addr].hash << 1) | (ipv4? ? 0 : 1)
  end

  # Creates a Range object for the network address.
  def to_range
    begin_addr = (@addr & @mask_addr)

    case @family
    when Socket::AF_INET
      end_addr = (@addr | (IN4MASK ^ @mask_addr))
    when Socket::AF_INET6
      end_addr = (@addr | (IN6MASK ^ @mask_addr))
    else
      raise AddressFamilyError, "unsupported address family"
    end

    return clone.set(begin_addr, @family)..clone.set(end_addr, @family)
  end

  # Returns the prefix length in bits for the ipaddr.
  def prefix
    case @family
    when Socket::AF_INET
      n = IN4MASK ^ @mask_addr
      i = 32
    when Socket::AF_INET6
      n = IN6MASK ^ @mask_addr
      i = 128
    else
      raise AddressFamilyError, "unsupported address family"
    end
    while n.positive?
      n >>= 1
      i -= 1
    end
    i
  end

  # Sets the prefix length in bits
  def prefix=(prefix)
    case prefix
    when Integer
      mask!(prefix)
    else
      raise InvalidPrefixError, "prefix must be an integer"
    end
  end

  # Returns a string containing a human-readable representation of the
  # ipaddr. ("#<IPAddr: family:address/mask>")
  def inspect
    case @family
    when Socket::AF_INET
      af = "IPv4"
    when Socket::AF_INET6
      af = "IPv6"
    else
      raise AddressFamilyError, "unsupported address family"
    end
    return sprintf("#<%s: %s:%s/%s>", self.class.name,
                   af, _to_string(@addr), _to_string(@mask_addr))
  end

  protected

  # Set +@addr+, the internal stored ip address, to given +addr+. The
  # parameter +addr+ is validated using the first +family+ member,
  # which is +Socket::AF_INET+ or +Socket::AF_INET6+.
  def set(addr, *family)
    case family[0] ? family[0] : @family
    when Socket::AF_INET
      if addr < 0 || addr > IN4MASK
        raise InvalidAddressError, "invalid address"
      end
    when Socket::AF_INET6
      if addr < 0 || addr > IN6MASK
        raise InvalidAddressError, "invalid address"
      end
    else
      raise AddressFamilyError, "unsupported address family"
    end
    @addr = addr
    if family[0]
      @family = family[0]
    end
    return self
  end

  # Set current netmask to given mask.
  def mask!(mask)
    case mask
    when String
      if mask =~ /\A\d+\z/
        prefixlen = mask.to_i
      else
        m = IPAddr.new(mask)
        if m.family != @family
          raise InvalidPrefixError, "address family is not same"
        end
        @mask_addr = m.to_i
        n = @mask_addr ^ m.instance_variable_get(:@mask_addr)
        unless ((n + 1) & n).zero?
          raise InvalidPrefixError, "invalid mask #{mask}"
        end
        @addr &= @mask_addr
        return self
      end
    else
      prefixlen = mask
    end
    case @family
    when Socket::AF_INET
      if prefixlen < 0 || prefixlen > 32
        raise InvalidPrefixError, "invalid length"
      end
      masklen = 32 - prefixlen
      @mask_addr = ((IN4MASK >> masklen) << masklen)
    when Socket::AF_INET6
      if prefixlen < 0 || prefixlen > 128
        raise InvalidPrefixError, "invalid length"
      end
      masklen = 128 - prefixlen
      @mask_addr = ((IN6MASK >> masklen) << masklen)
    else
      raise AddressFamilyError, "unsupported address family"
    end
    @addr = ((@addr >> masklen) << masklen)
    return self
  end

  private

  # Creates a new ipaddr object either from a human readable IP
  # address representation in string, or from a packed in_addr value
  # followed by an address family.
  #
  # In the former case, the following are the valid formats that will
  # be recognized: "address", "address/prefixlen" and "address/mask",
  # where IPv6 address may be enclosed in square brackets (`[' and
  # `]').  If a prefixlen or a mask is specified, it returns a masked
  # IP address.  Although the address family is determined
  # automatically from a specified string, you can specify one
  # explicitly by the optional second argument.
  #
  # Otherwise an IP address is generated from a packed in_addr value
  # and an address family.
  #
  # The IPAddr class defines many methods and operators, and some of
  # those, such as &, |, include? and ==, accept a string, or a packed
  # in_addr value instead of an IPAddr object.
  def initialize(addr = '::', family = Socket::AF_UNSPEC)
    if !addr.kind_of?(String)
      case family
      when Socket::AF_INET, Socket::AF_INET6
        set(addr.to_i, family)
        @mask_addr = (family == Socket::AF_INET) ? IN4MASK : IN6MASK
        return
      when Socket::AF_UNSPEC
        raise AddressFamilyError, "address family must be specified"
      else
        raise AddressFamilyError, "unsupported address family: #{family}"
      end
    end
    prefix, prefixlen = addr.split('/')
    if prefix =~ /\A\[(.*)\]\z/i
      prefix = $1
      family = Socket::AF_INET6
    end
    # It seems AI_NUMERICHOST doesn't do the job.
    #Socket.getaddrinfo(left, nil, Socket::AF_INET6, Socket::SOCK_STREAM, nil,
    #                  Socket::AI_NUMERICHOST)
    @addr = @family = nil
    if family == Socket::AF_UNSPEC || family == Socket::AF_INET
      @addr = in_addr(prefix)
      if @addr
        @family = Socket::AF_INET
      end
    end
    if !@addr && (family == Socket::AF_UNSPEC || family == Socket::AF_INET6)
      @addr = in6_addr(prefix)
      @family = Socket::AF_INET6
    end
    if family != Socket::AF_UNSPEC && @family != family
      raise AddressFamilyError, "address family mismatch"
    end
    if prefixlen
      mask!(prefixlen)
    else
      @mask_addr = (@family == Socket::AF_INET) ? IN4MASK : IN6MASK
    end
  rescue InvalidAddressError => e
    raise e.class, "#{e.message}: #{addr}"
  end

  def coerce_other(other)
    case other
    when IPAddr
      other
    when String
      self.class.new(other)
    else
      self.class.new(other, @family)
    end
  end

  def in_addr(addr)
    case addr
    when Array
      octets = addr
    else
      m = RE_IPV4ADDRLIKE.match(addr) or return nil
      octets = m.captures
    end
    octets.inject(0) { |i, s|
      (n = s.to_i) < 256 or raise InvalidAddressError, "invalid address"
      s.match(/\A0./) and raise InvalidAddressError, "zero-filled number in IPv4 address is ambiguous"
      i << 8 | n
    }
  end

  def in6_addr(left)
    case left
    when RE_IPV6ADDRLIKE_FULL
      if $2
        addr = in_addr($~[2,4])
        left = $1 + ':'
      else
        addr = 0
      end
      right = ''
    when RE_IPV6ADDRLIKE_COMPRESSED
      if $4
        left.count(':') <= 6 or raise InvalidAddressError, "invalid address"
        addr = in_addr($~[4,4])
        left = $1
        right = $3 + '0:0'
      else
        left.count(':') <= ($1.empty? || $2.empty? ? 8 : 7) or
          raise InvalidAddressError, "invalid address"
        left = $1
        right = $2
        addr = 0
      end
    else
      raise InvalidAddressError, "invalid address"
    end
    l = left.split(':')
    r = right.split(':')
    rest = 8 - l.size - r.size
    if rest < 0
      return nil
    end
    (l + Array.new(rest, '0') + r).inject(0) { |i, s|
      i << 16 | s.hex
    } | addr
  end

  def addr_mask(addr)
    case @family
    when Socket::AF_INET
      return addr & IN4MASK
    when Socket::AF_INET6
      return addr & IN6MASK
    else
      raise AddressFamilyError, "unsupported address family"
    end
  end

  def _reverse
    case @family
    when Socket::AF_INET
      return (0..3).map { |i|
        (@addr >> (8 * i)) & 0xff
      }.join('.')
    when Socket::AF_INET6
      return ("%.32x" % @addr).reverse!.gsub!(/.(?!$)/, '\&.')
    else
      raise AddressFamilyError, "unsupported address family"
    end
  end

  def _to_string(addr)
    case @family
    when Socket::AF_INET
      return (0..3).map { |i|
        (addr >> (24 - 8 * i)) & 0xff
      }.join('.')
    when Socket::AF_INET6
      return (("%.32x" % addr).gsub!(/.{4}(?!$)/, '\&:'))
    else
      raise AddressFamilyError, "unsupported address family"
    end
  end

end

unless Socket.const_defined? :AF_INET6
  class Socket < BasicSocket
    # IPv6 protocol family
    AF_INET6 = Object.new
  end

  class << IPSocket
    private

    def valid_v6?(addr)
      case addr
      when IPAddr::RE_IPV6ADDRLIKE_FULL
        if $2
          $~[2,4].all? {|i| i.to_i < 256 }
        else
          true
        end
      when IPAddr::RE_IPV6ADDRLIKE_COMPRESSED
        if $4
          addr.count(':') <= 6 && $~[4,4].all? {|i| i.to_i < 256}
        else
          addr.count(':') <= 7
        end
      else
        false
      end
    end

    alias getaddress_orig getaddress

    public

    # Returns a +String+ based representation of a valid DNS hostname,
    # IPv4 or IPv6 address.
    #
    #   IPSocket.getaddress 'localhost'         #=> "::1"
    #   IPSocket.getaddress 'broadcasthost'     #=> "255.255.255.255"
    #   IPSocket.getaddress 'www.ruby-lang.org' #=> "221.186.184.68"
    #   IPSocket.getaddress 'www.ccc.de'        #=> "2a00:1328:e102:ccc0::122"
    def getaddress(s)
      if valid_v6?(s)
        s
      else
        getaddress_orig(s)
      end
    end
  end
end
# frozen_string_literal: false
# Timeout long-running blocks
#
# == Synopsis
#
#   require 'timeout'
#   status = Timeout::timeout(5) {
#     # Something that should be interrupted if it takes more than 5 seconds...
#   }
#
# == Description
#
# Timeout provides a way to auto-terminate a potentially long-running
# operation if it hasn't finished in a fixed amount of time.
#
# Previous versions didn't use a module for namespacing, however
# #timeout is provided for backwards compatibility.  You
# should prefer Timeout.timeout instead.
#
# == Copyright
#
# Copyright:: (C) 2000  Network Applied Communication Laboratory, Inc.
# Copyright:: (C) 2000  Information-technology Promotion Agency, Japan

module Timeout
  VERSION = "0.1.1"

  # Raised by Timeout.timeout when the block times out.
  class Error < RuntimeError
    attr_reader :thread

    def self.catch(*args)
      exc = new(*args)
      exc.instance_variable_set(:@thread, Thread.current)
      ::Kernel.catch(exc) {yield exc}
    end

    def exception(*)
      # TODO: use Fiber.current to see if self can be thrown
      if self.thread == Thread.current
        bt = caller
        begin
          throw(self, bt)
        rescue UncaughtThrowError
        end
      end
      self
    end
  end

  # :stopdoc:
  THIS_FILE = /\A#{Regexp.quote(__FILE__)}:/o
  CALLER_OFFSET = ((c = caller[0]) && THIS_FILE =~ c) ? 1 : 0
  private_constant :THIS_FILE, :CALLER_OFFSET
  # :startdoc:

  # Perform an operation in a block, raising an error if it takes longer than
  # +sec+ seconds to complete.
  #
  # +sec+:: Number of seconds to wait for the block to terminate. Any number
  #         may be used, including Floats to specify fractional seconds. A
  #         value of 0 or +nil+ will execute the block without any timeout.
  # +klass+:: Exception Class to raise if the block fails to terminate
  #           in +sec+ seconds.  Omitting will use the default, Timeout::Error
  # +message+:: Error message to raise with Exception Class.
  #             Omitting will use the default, "execution expired"
  #
  # Returns the result of the block *if* the block completed before
  # +sec+ seconds, otherwise throws an exception, based on the value of +klass+.
  #
  # The exception thrown to terminate the given block cannot be rescued inside
  # the block unless +klass+ is given explicitly. However, the block can use
  # ensure to prevent the handling of the exception.  For that reason, this
  # method cannot be relied on to enforce timeouts for untrusted blocks.
  #
  # Note that this is both a method of module Timeout, so you can <tt>include
  # Timeout</tt> into your classes so they have a #timeout method, as well as
  # a module method, so you can call it directly as Timeout.timeout().
  def timeout(sec, klass = nil, message = nil)   #:yield: +sec+
    return yield(sec) if sec == nil or sec.zero?
    message ||= "execution expired".freeze
    from = "from #{caller_locations(1, 1)[0]}" if $DEBUG
    e = Error
    bl = proc do |exception|
      begin
        x = Thread.current
        y = Thread.start {
          Thread.current.name = from
          begin
            sleep sec
          rescue => e
            x.raise e
          else
            x.raise exception, message
          end
        }
        return yield(sec)
      ensure
        if y
          y.kill
          y.join # make sure y is dead.
        end
      end
    end
    if klass
      begin
        bl.call(klass)
      rescue klass => e
        bt = e.backtrace
      end
    else
      bt = Error.catch(message, &bl)
    end
    level = -caller(CALLER_OFFSET).size-2
    while THIS_FILE =~ bt[level]
      bt.delete_at(level)
    end
    raise(e, message, bt)
  end

  module_function :timeout
end

def timeout(*args, &block)
  warn "Object##{__method__} is deprecated, use Timeout.timeout instead.", uplevel: 1
  Timeout.timeout(*args, &block)
end

# Another name for Timeout::Error, defined for backwards compatibility with
# earlier versions of timeout.rb.
TimeoutError = Timeout::Error
class Object
  deprecate_constant :TimeoutError
end
# frozen_string_literal: true

require 'socket.so'
require 'io/wait'

class Addrinfo
  # creates an Addrinfo object from the arguments.
  #
  # The arguments are interpreted as similar to self.
  #
  #   Addrinfo.tcp("0.0.0.0", 4649).family_addrinfo("www.ruby-lang.org", 80)
  #   #=> #<Addrinfo: 221.186.184.68:80 TCP (www.ruby-lang.org:80)>
  #
  #   Addrinfo.unix("/tmp/sock").family_addrinfo("/tmp/sock2")
  #   #=> #<Addrinfo: /tmp/sock2 SOCK_STREAM>
  #
  def family_addrinfo(*args)
    if args.empty?
      raise ArgumentError, "no address specified"
    elsif Addrinfo === args.first
      raise ArgumentError, "too many arguments" if args.length != 1
      addrinfo = args.first
      if (self.pfamily != addrinfo.pfamily) ||
         (self.socktype != addrinfo.socktype)
        raise ArgumentError, "Addrinfo type mismatch"
      end
      addrinfo
    elsif self.ip?
      raise ArgumentError, "IP address needs host and port but #{args.length} arguments given" if args.length != 2
      host, port = args
      Addrinfo.getaddrinfo(host, port, self.pfamily, self.socktype, self.protocol)[0]
    elsif self.unix?
      raise ArgumentError, "UNIX socket needs single path argument but #{args.length} arguments given" if args.length != 1
      path, = args
      Addrinfo.unix(path)
    else
      raise ArgumentError, "unexpected family"
    end
  end

  # creates a new Socket connected to the address of +local_addrinfo+.
  #
  # If _local_addrinfo_ is nil, the address of the socket is not bound.
  #
  # The _timeout_ specify the seconds for timeout.
  # Errno::ETIMEDOUT is raised when timeout occur.
  #
  # If a block is given the created socket is yielded for each address.
  #
  def connect_internal(local_addrinfo, timeout=nil) # :yields: socket
    sock = Socket.new(self.pfamily, self.socktype, self.protocol)
    begin
      sock.ipv6only! if self.ipv6?
      sock.bind local_addrinfo if local_addrinfo
      if timeout
        case sock.connect_nonblock(self, exception: false)
        when 0 # success or EISCONN, other errors raise
          break
        when :wait_writable
          sock.wait_writable(timeout) or
            raise Errno::ETIMEDOUT, 'user specified timeout'
        end while true
      else
        sock.connect(self)
      end
    rescue Exception
      sock.close
      raise
    end
    if block_given?
      begin
        yield sock
      ensure
        sock.close
      end
    else
      sock
    end
  end
  protected :connect_internal

  # :call-seq:
  #   addrinfo.connect_from([local_addr_args], [opts]) {|socket| ... }
  #   addrinfo.connect_from([local_addr_args], [opts])
  #
  # creates a socket connected to the address of self.
  #
  # If one or more arguments given as _local_addr_args_,
  # it is used as the local address of the socket.
  # _local_addr_args_ is given for family_addrinfo to obtain actual address.
  #
  # If _local_addr_args_ is not given, the local address of the socket is not bound.
  #
  # The optional last argument _opts_ is options represented by a hash.
  # _opts_ may have following options:
  #
  # [:timeout] specify the timeout in seconds.
  #
  # If a block is given, it is called with the socket and the value of the block is returned.
  # The socket is returned otherwise.
  #
  #   Addrinfo.tcp("www.ruby-lang.org", 80).connect_from("0.0.0.0", 4649) {|s|
  #     s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
  #     puts s.read
  #   }
  #
  #   # Addrinfo object can be taken for the argument.
  #   Addrinfo.tcp("www.ruby-lang.org", 80).connect_from(Addrinfo.tcp("0.0.0.0", 4649)) {|s|
  #     s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
  #     puts s.read
  #   }
  #
  def connect_from(*args, timeout: nil, &block)
    connect_internal(family_addrinfo(*args), timeout, &block)
  end

  # :call-seq:
  #   addrinfo.connect([opts]) {|socket| ... }
  #   addrinfo.connect([opts])
  #
  # creates a socket connected to the address of self.
  #
  # The optional argument _opts_ is options represented by a hash.
  # _opts_ may have following options:
  #
  # [:timeout] specify the timeout in seconds.
  #
  # If a block is given, it is called with the socket and the value of the block is returned.
  # The socket is returned otherwise.
  #
  #   Addrinfo.tcp("www.ruby-lang.org", 80).connect {|s|
  #     s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
  #     puts s.read
  #   }
  #
  def connect(timeout: nil, &block)
    connect_internal(nil, timeout, &block)
  end

  # :call-seq:
  #   addrinfo.connect_to([remote_addr_args], [opts]) {|socket| ... }
  #   addrinfo.connect_to([remote_addr_args], [opts])
  #
  # creates a socket connected to _remote_addr_args_ and bound to self.
  #
  # The optional last argument _opts_ is options represented by a hash.
  # _opts_ may have following options:
  #
  # [:timeout] specify the timeout in seconds.
  #
  # If a block is given, it is called with the socket and the value of the block is returned.
  # The socket is returned otherwise.
  #
  #   Addrinfo.tcp("0.0.0.0", 4649).connect_to("www.ruby-lang.org", 80) {|s|
  #     s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
  #     puts s.read
  #   }
  #
  def connect_to(*args, timeout: nil, &block)
    remote_addrinfo = family_addrinfo(*args)
    remote_addrinfo.connect_internal(self, timeout, &block)
  end

  # creates a socket bound to self.
  #
  # If a block is given, it is called with the socket and the value of the block is returned.
  # The socket is returned otherwise.
  #
  #   Addrinfo.udp("0.0.0.0", 9981).bind {|s|
  #     s.local_address.connect {|s| s.send "hello", 0 }
  #     p s.recv(10) #=> "hello"
  #   }
  #
  def bind
    sock = Socket.new(self.pfamily, self.socktype, self.protocol)
    begin
      sock.ipv6only! if self.ipv6?
      sock.setsockopt(:SOCKET, :REUSEADDR, 1)
      sock.bind(self)
    rescue Exception
      sock.close
      raise
    end
    if block_given?
      begin
        yield sock
      ensure
        sock.close
      end
    else
      sock
    end
  end

  # creates a listening socket bound to self.
  def listen(backlog=Socket::SOMAXCONN)
    sock = Socket.new(self.pfamily, self.socktype, self.protocol)
    begin
      sock.ipv6only! if self.ipv6?
      sock.setsockopt(:SOCKET, :REUSEADDR, 1)
      sock.bind(self)
      sock.listen(backlog)
    rescue Exception
      sock.close
      raise
    end
    if block_given?
      begin
        yield sock
      ensure
        sock.close
      end
    else
      sock
    end
  end

  # iterates over the list of Addrinfo objects obtained by Addrinfo.getaddrinfo.
  #
  #   Addrinfo.foreach(nil, 80) {|x| p x }
  #   #=> #<Addrinfo: 127.0.0.1:80 TCP (:80)>
  #   #   #<Addrinfo: 127.0.0.1:80 UDP (:80)>
  #   #   #<Addrinfo: [::1]:80 TCP (:80)>
  #   #   #<Addrinfo: [::1]:80 UDP (:80)>
  #
  def self.foreach(nodename, service, family=nil, socktype=nil, protocol=nil, flags=nil, timeout: nil, &block)
    Addrinfo.getaddrinfo(nodename, service, family, socktype, protocol, flags, timeout: timeout).each(&block)
  end
end

class BasicSocket < IO
  # Returns an address of the socket suitable for connect in the local machine.
  #
  # This method returns _self_.local_address, except following condition.
  #
  # - IPv4 unspecified address (0.0.0.0) is replaced by IPv4 loopback address (127.0.0.1).
  # - IPv6 unspecified address (::) is replaced by IPv6 loopback address (::1).
  #
  # If the local address is not suitable for connect, SocketError is raised.
  # IPv4 and IPv6 address which port is 0 is not suitable for connect.
  # Unix domain socket which has no path is not suitable for connect.
  #
  #   Addrinfo.tcp("0.0.0.0", 0).listen {|serv|
  #     p serv.connect_address #=> #<Addrinfo: 127.0.0.1:53660 TCP>
  #     serv.connect_address.connect {|c|
  #       s, _ = serv.accept
  #       p [c, s] #=> [#<Socket:fd 4>, #<Socket:fd 6>]
  #     }
  #   }
  #
  def connect_address
    addr = local_address
    afamily = addr.afamily
    if afamily == Socket::AF_INET
      raise SocketError, "unbound IPv4 socket" if addr.ip_port == 0
      if addr.ip_address == "0.0.0.0"
        addr = Addrinfo.new(["AF_INET", addr.ip_port, nil, "127.0.0.1"], addr.pfamily, addr.socktype, addr.protocol)
      end
    elsif defined?(Socket::AF_INET6) && afamily == Socket::AF_INET6
      raise SocketError, "unbound IPv6 socket" if addr.ip_port == 0
      if addr.ip_address == "::"
        addr = Addrinfo.new(["AF_INET6", addr.ip_port, nil, "::1"], addr.pfamily, addr.socktype, addr.protocol)
      elsif addr.ip_address == "0.0.0.0" # MacOS X 10.4 returns "a.b.c.d" for IPv4-mapped IPv6 address.
        addr = Addrinfo.new(["AF_INET6", addr.ip_port, nil, "::1"], addr.pfamily, addr.socktype, addr.protocol)
      elsif addr.ip_address == "::ffff:0.0.0.0" # MacOS X 10.6 returns "::ffff:a.b.c.d" for IPv4-mapped IPv6 address.
        addr = Addrinfo.new(["AF_INET6", addr.ip_port, nil, "::1"], addr.pfamily, addr.socktype, addr.protocol)
      end
    elsif defined?(Socket::AF_UNIX) && afamily == Socket::AF_UNIX
      raise SocketError, "unbound Unix socket" if addr.unix_path == ""
    end
    addr
  end

  # call-seq:
  #    basicsocket.sendmsg(mesg, flags=0, dest_sockaddr=nil, *controls) => numbytes_sent
  #
  # sendmsg sends a message using sendmsg(2) system call in blocking manner.
  #
  # _mesg_ is a string to send.
  #
  # _flags_ is bitwise OR of MSG_* constants such as Socket::MSG_OOB.
  #
  # _dest_sockaddr_ is a destination socket address for connection-less socket.
  # It should be a sockaddr such as a result of Socket.sockaddr_in.
  # An Addrinfo object can be used too.
  #
  # _controls_ is a list of ancillary data.
  # The element of _controls_ should be Socket::AncillaryData or
  # 3-elements array.
  # The 3-element array should contains cmsg_level, cmsg_type and data.
  #
  # The return value, _numbytes_sent_ is an integer which is the number of bytes sent.
  #
  # sendmsg can be used to implement send_io as follows:
  #
  #   # use Socket::AncillaryData.
  #   ancdata = Socket::AncillaryData.int(:UNIX, :SOCKET, :RIGHTS, io.fileno)
  #   sock.sendmsg("a", 0, nil, ancdata)
  #
  #   # use 3-element array.
  #   ancdata = [:SOCKET, :RIGHTS, [io.fileno].pack("i!")]
  #   sock.sendmsg("\0", 0, nil, ancdata)
  def sendmsg(mesg, flags = 0, dest_sockaddr = nil, *controls)
    __sendmsg(mesg, flags, dest_sockaddr, controls)
  end

  # call-seq:
  #    basicsocket.sendmsg_nonblock(mesg, flags=0, dest_sockaddr=nil, *controls, opts={}) => numbytes_sent
  #
  # sendmsg_nonblock sends a message using sendmsg(2) system call in non-blocking manner.
  #
  # It is similar to BasicSocket#sendmsg
  # but the non-blocking flag is set before the system call
  # and it doesn't retry the system call.
  #
  # By specifying a keyword argument _exception_ to +false+, you can indicate
  # that sendmsg_nonblock should not raise an IO::WaitWritable exception, but
  # return the symbol +:wait_writable+ instead.
  def sendmsg_nonblock(mesg, flags = 0, dest_sockaddr = nil, *controls,
                       exception: true)
    __sendmsg_nonblock(mesg, flags, dest_sockaddr, controls, exception)
  end

  # call-seq:
  # 	basicsocket.recv_nonblock(maxlen [, flags [, buf [, options ]]]) => mesg
  #
  # Receives up to _maxlen_ bytes from +socket+ using recvfrom(2) after
  # O_NONBLOCK is set for the underlying file descriptor.
  # _flags_ is zero or more of the +MSG_+ options.
  # The result, _mesg_, is the data received.
  #
  # When recvfrom(2) returns 0, Socket#recv_nonblock returns
  # an empty string as data.
  # The meaning depends on the socket: EOF on TCP, empty packet on UDP, etc.
  #
  # === Parameters
  # * +maxlen+ - the number of bytes to receive from the socket
  # * +flags+ - zero or more of the +MSG_+ options
  # * +buf+ - destination String buffer
  # * +options+ - keyword hash, supporting `exception: false`
  #
  # === Example
  # 	serv = TCPServer.new("127.0.0.1", 0)
  # 	af, port, host, addr = serv.addr
  # 	c = TCPSocket.new(addr, port)
  # 	s = serv.accept
  # 	c.send "aaa", 0
  # 	begin # emulate blocking recv.
  # 	  p s.recv_nonblock(10) #=> "aaa"
  # 	rescue IO::WaitReadable
  # 	  IO.select([s])
  # 	  retry
  # 	end
  #
  # Refer to Socket#recvfrom for the exceptions that may be thrown if the call
  # to _recv_nonblock_ fails.
  #
  # BasicSocket#recv_nonblock may raise any error corresponding to recvfrom(2) failure,
  # including Errno::EWOULDBLOCK.
  #
  # If the exception is Errno::EWOULDBLOCK or Errno::EAGAIN,
  # it is extended by IO::WaitReadable.
  # So IO::WaitReadable can be used to rescue the exceptions for retrying recv_nonblock.
  #
  # By specifying a keyword argument _exception_ to +false+, you can indicate
  # that recv_nonblock should not raise an IO::WaitReadable exception, but
  # return the symbol +:wait_readable+ instead.
  #
  # === See
  # * Socket#recvfrom
  def recv_nonblock(len, flag = 0, str = nil, exception: true)
    __recv_nonblock(len, flag, str, exception)
  end

  # call-seq:
  #    basicsocket.recvmsg(maxmesglen=nil, flags=0, maxcontrollen=nil, opts={}) => [mesg, sender_addrinfo, rflags, *controls]
  #
  # recvmsg receives a message using recvmsg(2) system call in blocking manner.
  #
  # _maxmesglen_ is the maximum length of mesg to receive.
  #
  # _flags_ is bitwise OR of MSG_* constants such as Socket::MSG_PEEK.
  #
  # _maxcontrollen_ is the maximum length of controls (ancillary data) to receive.
  #
  # _opts_ is option hash.
  # Currently :scm_rights=>bool is the only option.
  #
  # :scm_rights option specifies that application expects SCM_RIGHTS control message.
  # If the value is nil or false, application don't expects SCM_RIGHTS control message.
  # In this case, recvmsg closes the passed file descriptors immediately.
  # This is the default behavior.
  #
  # If :scm_rights value is neither nil nor false, application expects SCM_RIGHTS control message.
  # In this case, recvmsg creates IO objects for each file descriptors for
  # Socket::AncillaryData#unix_rights method.
  #
  # The return value is 4-elements array.
  #
  # _mesg_ is a string of the received message.
  #
  # _sender_addrinfo_ is a sender socket address for connection-less socket.
  # It is an Addrinfo object.
  # For connection-oriented socket such as TCP, sender_addrinfo is platform dependent.
  #
  # _rflags_ is a flags on the received message which is bitwise OR of MSG_* constants such as Socket::MSG_TRUNC.
  # It will be nil if the system uses 4.3BSD style old recvmsg system call.
  #
  # _controls_ is ancillary data which is an array of Socket::AncillaryData objects such as:
  #
  #   #<Socket::AncillaryData: AF_UNIX SOCKET RIGHTS 7>
  #
  # _maxmesglen_ and _maxcontrollen_ can be nil.
  # In that case, the buffer will be grown until the message is not truncated.
  # Internally, MSG_PEEK is used.
  # Buffer full and MSG_CTRUNC are checked for truncation.
  #
  # recvmsg can be used to implement recv_io as follows:
  #
  #   mesg, sender_sockaddr, rflags, *controls = sock.recvmsg(:scm_rights=>true)
  #   controls.each {|ancdata|
  #     if ancdata.cmsg_is?(:SOCKET, :RIGHTS)
  #       return ancdata.unix_rights[0]
  #     end
  #   }
  def recvmsg(dlen = nil, flags = 0, clen = nil, scm_rights: false)
    __recvmsg(dlen, flags, clen, scm_rights)
  end

  # call-seq:
  #    basicsocket.recvmsg_nonblock(maxdatalen=nil, flags=0, maxcontrollen=nil, opts={}) => [data, sender_addrinfo, rflags, *controls]
  #
  # recvmsg receives a message using recvmsg(2) system call in non-blocking manner.
  #
  # It is similar to BasicSocket#recvmsg
  # but non-blocking flag is set before the system call
  # and it doesn't retry the system call.
  #
  # By specifying a keyword argument _exception_ to +false+, you can indicate
  # that recvmsg_nonblock should not raise an IO::WaitReadable exception, but
  # return the symbol +:wait_readable+ instead.
  def recvmsg_nonblock(dlen = nil, flags = 0, clen = nil,
                       scm_rights: false, exception: true)
    __recvmsg_nonblock(dlen, flags, clen, scm_rights, exception)
  end

  # Linux-specific optimizations to avoid fcntl for IO#read_nonblock
  # and IO#write_nonblock using MSG_DONTWAIT
  # Do other platforms support MSG_DONTWAIT reliably?
  if RUBY_PLATFORM =~ /linux/ && Socket.const_defined?(:MSG_DONTWAIT)
    def read_nonblock(len, str = nil, exception: true) # :nodoc:
      __read_nonblock(len, str, exception)
    end

    def write_nonblock(buf, exception: true) # :nodoc:
      __write_nonblock(buf, exception)
    end
  end
end

class Socket < BasicSocket
  # enable the socket option IPV6_V6ONLY if IPV6_V6ONLY is available.
  def ipv6only!
    if defined? Socket::IPV6_V6ONLY
      self.setsockopt(:IPV6, :V6ONLY, 1)
    end
  end

  # call-seq:
  #   socket.recvfrom_nonblock(maxlen[, flags[, outbuf[, opts]]]) => [mesg, sender_addrinfo]
  #
  # Receives up to _maxlen_ bytes from +socket+ using recvfrom(2) after
  # O_NONBLOCK is set for the underlying file descriptor.
  # _flags_ is zero or more of the +MSG_+ options.
  # The first element of the results, _mesg_, is the data received.
  # The second element, _sender_addrinfo_, contains protocol-specific address
  # information of the sender.
  #
  # When recvfrom(2) returns 0, Socket#recvfrom_nonblock returns
  # an empty string as data.
  # The meaning depends on the socket: EOF on TCP, empty packet on UDP, etc.
  #
  # === Parameters
  # * +maxlen+ - the maximum number of bytes to receive from the socket
  # * +flags+ - zero or more of the +MSG_+ options
  # * +outbuf+ - destination String buffer
  # * +opts+ - keyword hash, supporting `exception: false`
  #
  # === Example
  #   # In one file, start this first
  #   require 'socket'
  #   include Socket::Constants
  #   socket = Socket.new(AF_INET, SOCK_STREAM, 0)
  #   sockaddr = Socket.sockaddr_in(2200, 'localhost')
  #   socket.bind(sockaddr)
  #   socket.listen(5)
  #   client, client_addrinfo = socket.accept
  #   begin # emulate blocking recvfrom
  #     pair = client.recvfrom_nonblock(20)
  #   rescue IO::WaitReadable
  #     IO.select([client])
  #     retry
  #   end
  #   data = pair[0].chomp
  #   puts "I only received 20 bytes '#{data}'"
  #   sleep 1
  #   socket.close
  #
  #   # In another file, start this second
  #   require 'socket'
  #   include Socket::Constants
  #   socket = Socket.new(AF_INET, SOCK_STREAM, 0)
  #   sockaddr = Socket.sockaddr_in(2200, 'localhost')
  #   socket.connect(sockaddr)
  #   socket.puts "Watch this get cut short!"
  #   socket.close
  #
  # Refer to Socket#recvfrom for the exceptions that may be thrown if the call
  # to _recvfrom_nonblock_ fails.
  #
  # Socket#recvfrom_nonblock may raise any error corresponding to recvfrom(2) failure,
  # including Errno::EWOULDBLOCK.
  #
  # If the exception is Errno::EWOULDBLOCK or Errno::EAGAIN,
  # it is extended by IO::WaitReadable.
  # So IO::WaitReadable can be used to rescue the exceptions for retrying
  # recvfrom_nonblock.
  #
  # By specifying a keyword argument _exception_ to +false+, you can indicate
  # that recvfrom_nonblock should not raise an IO::WaitReadable exception, but
  # return the symbol +:wait_readable+ instead.
  #
  # === See
  # * Socket#recvfrom
  def recvfrom_nonblock(len, flag = 0, str = nil, exception: true)
    __recvfrom_nonblock(len, flag, str, exception)
  end

  # call-seq:
  #   socket.accept_nonblock([options]) => [client_socket, client_addrinfo]
  #
  # Accepts an incoming connection using accept(2) after
  # O_NONBLOCK is set for the underlying file descriptor.
  # It returns an array containing the accepted socket
  # for the incoming connection, _client_socket_,
  # and an Addrinfo, _client_addrinfo_.
  #
  # === Example
  #   # In one script, start this first
  #   require 'socket'
  #   include Socket::Constants
  #   socket = Socket.new(AF_INET, SOCK_STREAM, 0)
  #   sockaddr = Socket.sockaddr_in(2200, 'localhost')
  #   socket.bind(sockaddr)
  #   socket.listen(5)
  #   begin # emulate blocking accept
  #     client_socket, client_addrinfo = socket.accept_nonblock
  #   rescue IO::WaitReadable, Errno::EINTR
  #     IO.select([socket])
  #     retry
  #   end
  #   puts "The client said, '#{client_socket.readline.chomp}'"
  #   client_socket.puts "Hello from script one!"
  #   socket.close
  #
  #   # In another script, start this second
  #   require 'socket'
  #   include Socket::Constants
  #   socket = Socket.new(AF_INET, SOCK_STREAM, 0)
  #   sockaddr = Socket.sockaddr_in(2200, 'localhost')
  #   socket.connect(sockaddr)
  #   socket.puts "Hello from script 2."
  #   puts "The server said, '#{socket.readline.chomp}'"
  #   socket.close
  #
  # Refer to Socket#accept for the exceptions that may be thrown if the call
  # to _accept_nonblock_ fails.
  #
  # Socket#accept_nonblock may raise any error corresponding to accept(2) failure,
  # including Errno::EWOULDBLOCK.
  #
  # If the exception is Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::ECONNABORTED or Errno::EPROTO,
  # it is extended by IO::WaitReadable.
  # So IO::WaitReadable can be used to rescue the exceptions for retrying accept_nonblock.
  #
  # By specifying a keyword argument _exception_ to +false+, you can indicate
  # that accept_nonblock should not raise an IO::WaitReadable exception, but
  # return the symbol +:wait_readable+ instead.
  #
  # === See
  # * Socket#accept
  def accept_nonblock(exception: true)
    __accept_nonblock(exception)
  end

  # :call-seq:
  #   Socket.tcp(host, port, local_host=nil, local_port=nil, [opts]) {|socket| ... }
  #   Socket.tcp(host, port, local_host=nil, local_port=nil, [opts])
  #
  # creates a new socket object connected to host:port using TCP/IP.
  #
  # If local_host:local_port is given,
  # the socket is bound to it.
  #
  # The optional last argument _opts_ is options represented by a hash.
  # _opts_ may have following options:
  #
  # [:connect_timeout] specify the timeout in seconds.
  # [:resolv_timeout] specify the name resolution timeout in seconds.
  #
  # If a block is given, the block is called with the socket.
  # The value of the block is returned.
  # The socket is closed when this method returns.
  #
  # If no block is given, the socket is returned.
  #
  #   Socket.tcp("www.ruby-lang.org", 80) {|sock|
  #     sock.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
  #     sock.close_write
  #     puts sock.read
  #   }
  #
  def self.tcp(host, port, local_host = nil, local_port = nil, connect_timeout: nil, resolv_timeout: nil) # :yield: socket
    last_error = nil
    ret = nil

    local_addr_list = nil
    if local_host != nil || local_port != nil
      local_addr_list = Addrinfo.getaddrinfo(local_host, local_port, nil, :STREAM, nil)
    end

    Addrinfo.foreach(host, port, nil, :STREAM, timeout: resolv_timeout) {|ai|
      if local_addr_list
        local_addr = local_addr_list.find {|local_ai| local_ai.afamily == ai.afamily }
        next unless local_addr
      else
        local_addr = nil
      end
      begin
        sock = local_addr ?
          ai.connect_from(local_addr, timeout: connect_timeout) :
          ai.connect(timeout: connect_timeout)
      rescue SystemCallError
        last_error = $!
        next
      end
      ret = sock
      break
    }
    unless ret
      if last_error
        raise last_error
      else
        raise SocketError, "no appropriate local address"
      end
    end
    if block_given?
      begin
        yield ret
      ensure
        ret.close
      end
    else
      ret
    end
  end

  # :stopdoc:
  def self.ip_sockets_port0(ai_list, reuseaddr)
    sockets = []
    begin
      sockets.clear
      port = nil
      ai_list.each {|ai|
        begin
          s = Socket.new(ai.pfamily, ai.socktype, ai.protocol)
        rescue SystemCallError
          next
        end
        sockets << s
        s.ipv6only! if ai.ipv6?
        if reuseaddr
          s.setsockopt(:SOCKET, :REUSEADDR, 1)
        end
        unless port
          s.bind(ai)
          port = s.local_address.ip_port
        else
          s.bind(ai.family_addrinfo(ai.ip_address, port))
        end
      }
    rescue Errno::EADDRINUSE
      sockets.each(&:close)
      retry
    rescue Exception
      sockets.each(&:close)
      raise
    end
    sockets
  end
  class << self
    private :ip_sockets_port0
  end

  def self.tcp_server_sockets_port0(host)
    ai_list = Addrinfo.getaddrinfo(host, 0, nil, :STREAM, nil, Socket::AI_PASSIVE)
    sockets = ip_sockets_port0(ai_list, true)
    begin
      sockets.each {|s|
        s.listen(Socket::SOMAXCONN)
      }
    rescue Exception
      sockets.each(&:close)
      raise
    end
    sockets
  end
  class << self
    private :tcp_server_sockets_port0
  end
  # :startdoc:

  # creates TCP/IP server sockets for _host_ and _port_.
  # _host_ is optional.
  #
  # If no block given,
  # it returns an array of listening sockets.
  #
  # If a block is given, the block is called with the sockets.
  # The value of the block is returned.
  # The socket is closed when this method returns.
  #
  # If _port_ is 0, actual port number is chosen dynamically.
  # However all sockets in the result has same port number.
  #
  #   # tcp_server_sockets returns two sockets.
  #   sockets = Socket.tcp_server_sockets(1296)
  #   p sockets #=> [#<Socket:fd 3>, #<Socket:fd 4>]
  #
  #   # The sockets contains IPv6 and IPv4 sockets.
  #   sockets.each {|s| p s.local_address }
  #   #=> #<Addrinfo: [::]:1296 TCP>
  #   #   #<Addrinfo: 0.0.0.0:1296 TCP>
  #
  #   # IPv6 and IPv4 socket has same port number, 53114, even if it is chosen dynamically.
  #   sockets = Socket.tcp_server_sockets(0)
  #   sockets.each {|s| p s.local_address }
  #   #=> #<Addrinfo: [::]:53114 TCP>
  #   #   #<Addrinfo: 0.0.0.0:53114 TCP>
  #
  #   # The block is called with the sockets.
  #   Socket.tcp_server_sockets(0) {|sockets|
  #     p sockets #=> [#<Socket:fd 3>, #<Socket:fd 4>]
  #   }
  #
  def self.tcp_server_sockets(host=nil, port)
    if port == 0
      sockets = tcp_server_sockets_port0(host)
    else
      last_error = nil
      sockets = []
      begin
        Addrinfo.foreach(host, port, nil, :STREAM, nil, Socket::AI_PASSIVE) {|ai|
          begin
            s = ai.listen
          rescue SystemCallError
            last_error = $!
            next
          end
          sockets << s
        }
        if sockets.empty?
          raise last_error
        end
      rescue Exception
        sockets.each(&:close)
        raise
      end
    end
    if block_given?
      begin
        yield sockets
      ensure
        sockets.each(&:close)
      end
    else
      sockets
    end
  end

  # yield socket and client address for each a connection accepted via given sockets.
  #
  # The arguments are a list of sockets.
  # The individual argument should be a socket or an array of sockets.
  #
  # This method yields the block sequentially.
  # It means that the next connection is not accepted until the block returns.
  # So concurrent mechanism, thread for example, should be used to service multiple clients at a time.
  #
  def self.accept_loop(*sockets) # :yield: socket, client_addrinfo
    sockets.flatten!(1)
    if sockets.empty?
      raise ArgumentError, "no sockets"
    end
    loop {
      readable, _, _ = IO.select(sockets)
      readable.each {|r|
        sock, addr = r.accept_nonblock(exception: false)
        next if sock == :wait_readable
        yield sock, addr
      }
    }
  end

  # creates a TCP/IP server on _port_ and calls the block for each connection accepted.
  # The block is called with a socket and a client_address as an Addrinfo object.
  #
  # If _host_ is specified, it is used with _port_ to determine the server addresses.
  #
  # The socket is *not* closed when the block returns.
  # So application should close it explicitly.
  #
  # This method calls the block sequentially.
  # It means that the next connection is not accepted until the block returns.
  # So concurrent mechanism, thread for example, should be used to service multiple clients at a time.
  #
  # Note that Addrinfo.getaddrinfo is used to determine the server socket addresses.
  # When Addrinfo.getaddrinfo returns two or more addresses,
  # IPv4 and IPv6 address for example,
  # all of them are used.
  # Socket.tcp_server_loop succeeds if one socket can be used at least.
  #
  #   # Sequential echo server.
  #   # It services only one client at a time.
  #   Socket.tcp_server_loop(16807) {|sock, client_addrinfo|
  #     begin
  #       IO.copy_stream(sock, sock)
  #     ensure
  #       sock.close
  #     end
  #   }
  #
  #   # Threaded echo server
  #   # It services multiple clients at a time.
  #   # Note that it may accept connections too much.
  #   Socket.tcp_server_loop(16807) {|sock, client_addrinfo|
  #     Thread.new {
  #       begin
  #         IO.copy_stream(sock, sock)
  #       ensure
  #         sock.close
  #       end
  #     }
  #   }
  #
  def self.tcp_server_loop(host=nil, port, &b) # :yield: socket, client_addrinfo
    tcp_server_sockets(host, port) {|sockets|
      accept_loop(sockets, &b)
    }
  end

  # :call-seq:
  #   Socket.udp_server_sockets([host, ] port)
  #
  # Creates UDP/IP sockets for a UDP server.
  #
  # If no block given, it returns an array of sockets.
  #
  # If a block is given, the block is called with the sockets.
  # The value of the block is returned.
  # The sockets are closed when this method returns.
  #
  # If _port_ is zero, some port is chosen.
  # But the chosen port is used for the all sockets.
  #
  #   # UDP/IP echo server
  #   Socket.udp_server_sockets(0) {|sockets|
  #     p sockets.first.local_address.ip_port     #=> 32963
  #     Socket.udp_server_loop_on(sockets) {|msg, msg_src|
  #       msg_src.reply msg
  #     }
  #   }
  #
  def self.udp_server_sockets(host=nil, port)
    last_error = nil
    sockets = []

    ipv6_recvpktinfo = nil
    if defined? Socket::AncillaryData
      if defined? Socket::IPV6_RECVPKTINFO # RFC 3542
        ipv6_recvpktinfo = Socket::IPV6_RECVPKTINFO
      elsif defined? Socket::IPV6_PKTINFO # RFC 2292
        ipv6_recvpktinfo = Socket::IPV6_PKTINFO
      end
    end

    local_addrs = Socket.ip_address_list

    ip_list = []
    Addrinfo.foreach(host, port, nil, :DGRAM, nil, Socket::AI_PASSIVE) {|ai|
      if ai.ipv4? && ai.ip_address == "0.0.0.0"
        local_addrs.each {|a|
          next unless a.ipv4?
          ip_list << Addrinfo.new(a.to_sockaddr, :INET, :DGRAM, 0);
        }
      elsif ai.ipv6? && ai.ip_address == "::" && !ipv6_recvpktinfo
        local_addrs.each {|a|
          next unless a.ipv6?
          ip_list << Addrinfo.new(a.to_sockaddr, :INET6, :DGRAM, 0);
        }
      else
        ip_list << ai
      end
    }
    ip_list.uniq!(&:to_sockaddr)

    if port == 0
      sockets = ip_sockets_port0(ip_list, false)
    else
      ip_list.each {|ip|
        ai = Addrinfo.udp(ip.ip_address, port)
        begin
          s = ai.bind
        rescue SystemCallError
          last_error = $!
          next
        end
        sockets << s
      }
      if sockets.empty?
        raise last_error
      end
    end

    sockets.each {|s|
      ai = s.local_address
      if ipv6_recvpktinfo && ai.ipv6? && ai.ip_address == "::"
        s.setsockopt(:IPV6, ipv6_recvpktinfo, 1)
      end
    }

    if block_given?
      begin
        yield sockets
      ensure
        sockets.each(&:close) if sockets
      end
    else
      sockets
    end
  end

  # :call-seq:
  #   Socket.udp_server_recv(sockets) {|msg, msg_src| ... }
  #
  # Receive UDP/IP packets from the given _sockets_.
  # For each packet received, the block is called.
  #
  # The block receives _msg_ and _msg_src_.
  # _msg_ is a string which is the payload of the received packet.
  # _msg_src_ is a Socket::UDPSource object which is used for reply.
  #
  # Socket.udp_server_loop can be implemented using this method as follows.
  #
  #   udp_server_sockets(host, port) {|sockets|
  #     loop {
  #       readable, _, _ = IO.select(sockets)
  #       udp_server_recv(readable) {|msg, msg_src| ... }
  #     }
  #   }
  #
  def self.udp_server_recv(sockets)
    sockets.each {|r|
      msg, sender_addrinfo, _, *controls = r.recvmsg_nonblock(exception: false)
      next if msg == :wait_readable
      ai = r.local_address
      if ai.ipv6? and pktinfo = controls.find {|c| c.cmsg_is?(:IPV6, :PKTINFO) }
        ai = Addrinfo.udp(pktinfo.ipv6_pktinfo_addr.ip_address, ai.ip_port)
        yield msg, UDPSource.new(sender_addrinfo, ai) {|reply_msg|
          r.sendmsg reply_msg, 0, sender_addrinfo, pktinfo
        }
      else
        yield msg, UDPSource.new(sender_addrinfo, ai) {|reply_msg|
          r.send reply_msg, 0, sender_addrinfo
        }
      end
    }
  end

  # :call-seq:
  #   Socket.udp_server_loop_on(sockets) {|msg, msg_src| ... }
  #
  # Run UDP/IP server loop on the given sockets.
  #
  # The return value of Socket.udp_server_sockets is appropriate for the argument.
  #
  # It calls the block for each message received.
  #
  def self.udp_server_loop_on(sockets, &b) # :yield: msg, msg_src
    loop {
      readable, _, _ = IO.select(sockets)
      udp_server_recv(readable, &b)
    }
  end

  # :call-seq:
  #   Socket.udp_server_loop(port) {|msg, msg_src| ... }
  #   Socket.udp_server_loop(host, port) {|msg, msg_src| ... }
  #
  # creates a UDP/IP server on _port_ and calls the block for each message arrived.
  # The block is called with the message and its source information.
  #
  # This method allocates sockets internally using _port_.
  # If _host_ is specified, it is used conjunction with _port_ to determine the server addresses.
  #
  # The _msg_ is a string.
  #
  # The _msg_src_ is a Socket::UDPSource object.
  # It is used for reply.
  #
  #   # UDP/IP echo server.
  #   Socket.udp_server_loop(9261) {|msg, msg_src|
  #     msg_src.reply msg
  #   }
  #
  def self.udp_server_loop(host=nil, port, &b) # :yield: message, message_source
    udp_server_sockets(host, port) {|sockets|
      udp_server_loop_on(sockets, &b)
    }
  end

  # UDP/IP address information used by Socket.udp_server_loop.
  class UDPSource
    # +remote_address+ is an Addrinfo object.
    #
    # +local_address+ is an Addrinfo object.
    #
    # +reply_proc+ is a Proc used to send reply back to the source.
    def initialize(remote_address, local_address, &reply_proc)
      @remote_address = remote_address
      @local_address = local_address
      @reply_proc = reply_proc
    end

    # Address of the source
    attr_reader :remote_address

    # Local address
    attr_reader :local_address

    def inspect # :nodoc:
      "\#<#{self.class}: #{@remote_address.inspect_sockaddr} to #{@local_address.inspect_sockaddr}>".dup
    end

    # Sends the String +msg+ to the source
    def reply(msg)
      @reply_proc.call msg
    end
  end

  # creates a new socket connected to path using UNIX socket socket.
  #
  # If a block is given, the block is called with the socket.
  # The value of the block is returned.
  # The socket is closed when this method returns.
  #
  # If no block is given, the socket is returned.
  #
  #   # talk to /tmp/sock socket.
  #   Socket.unix("/tmp/sock") {|sock|
  #     t = Thread.new { IO.copy_stream(sock, STDOUT) }
  #     IO.copy_stream(STDIN, sock)
  #     t.join
  #   }
  #
  def self.unix(path) # :yield: socket
    addr = Addrinfo.unix(path)
    sock = addr.connect
    if block_given?
      begin
        yield sock
      ensure
        sock.close
      end
    else
      sock
    end
  end

  # creates a UNIX server socket on _path_
  #
  # If no block given, it returns a listening socket.
  #
  # If a block is given, it is called with the socket and the block value is returned.
  # When the block exits, the socket is closed and the socket file is removed.
  #
  #   socket = Socket.unix_server_socket("/tmp/s")
  #   p socket                  #=> #<Socket:fd 3>
  #   p socket.local_address    #=> #<Addrinfo: /tmp/s SOCK_STREAM>
  #
  #   Socket.unix_server_socket("/tmp/sock") {|s|
  #     p s                     #=> #<Socket:fd 3>
  #     p s.local_address       #=> # #<Addrinfo: /tmp/sock SOCK_STREAM>
  #   }
  #
  def self.unix_server_socket(path)
    unless unix_socket_abstract_name?(path)
      begin
        st = File.lstat(path)
      rescue Errno::ENOENT
      end
      if st&.socket? && st.owned?
        File.unlink path
      end
    end
    s = Addrinfo.unix(path).listen
    if block_given?
      begin
        yield s
      ensure
        s.close
        unless unix_socket_abstract_name?(path)
          File.unlink path
        end
      end
    else
      s
    end
  end

  class << self
    private

    def unix_socket_abstract_name?(path)
      /linux/ =~ RUBY_PLATFORM && /\A(\0|\z)/ =~ path
    end
  end

  # creates a UNIX socket server on _path_.
  # It calls the block for each socket accepted.
  #
  # If _host_ is specified, it is used with _port_ to determine the server ports.
  #
  # The socket is *not* closed when the block returns.
  # So application should close it.
  #
  # This method deletes the socket file pointed by _path_ at first if
  # the file is a socket file and it is owned by the user of the application.
  # This is safe only if the directory of _path_ is not changed by a malicious user.
  # So don't use /tmp/malicious-users-directory/socket.
  # Note that /tmp/socket and /tmp/your-private-directory/socket is safe assuming that /tmp has sticky bit.
  #
  #   # Sequential echo server.
  #   # It services only one client at a time.
  #   Socket.unix_server_loop("/tmp/sock") {|sock, client_addrinfo|
  #     begin
  #       IO.copy_stream(sock, sock)
  #     ensure
  #       sock.close
  #     end
  #   }
  #
  def self.unix_server_loop(path, &b) # :yield: socket, client_addrinfo
    unix_server_socket(path) {|serv|
      accept_loop(serv, &b)
    }
  end

  # call-seq:
  #   socket.connect_nonblock(remote_sockaddr, [options]) => 0
  #
  # Requests a connection to be made on the given +remote_sockaddr+ after
  # O_NONBLOCK is set for the underlying file descriptor.
  # Returns 0 if successful, otherwise an exception is raised.
  #
  # === Parameter
  #  # +remote_sockaddr+ - the +struct+ sockaddr contained in a string or Addrinfo object
  #
  # === Example:
  #   # Pull down Google's web page
  #   require 'socket'
  #   include Socket::Constants
  #   socket = Socket.new(AF_INET, SOCK_STREAM, 0)
  #   sockaddr = Socket.sockaddr_in(80, 'www.google.com')
  #   begin # emulate blocking connect
  #     socket.connect_nonblock(sockaddr)
  #   rescue IO::WaitWritable
  #     IO.select(nil, [socket]) # wait 3-way handshake completion
  #     begin
  #       socket.connect_nonblock(sockaddr) # check connection failure
  #     rescue Errno::EISCONN
  #     end
  #   end
  #   socket.write("GET / HTTP/1.0\r\n\r\n")
  #   results = socket.read
  #
  # Refer to Socket#connect for the exceptions that may be thrown if the call
  # to _connect_nonblock_ fails.
  #
  # Socket#connect_nonblock may raise any error corresponding to connect(2) failure,
  # including Errno::EINPROGRESS.
  #
  # If the exception is Errno::EINPROGRESS,
  # it is extended by IO::WaitWritable.
  # So IO::WaitWritable can be used to rescue the exceptions for retrying connect_nonblock.
  #
  # By specifying a keyword argument _exception_ to +false+, you can indicate
  # that connect_nonblock should not raise an IO::WaitWritable exception, but
  # return the symbol +:wait_writable+ instead.
  #
  # === See
  #  # Socket#connect
  def connect_nonblock(addr, exception: true)
    __connect_nonblock(addr, exception)
  end
end

class UDPSocket < IPSocket

  # call-seq:
  #   udpsocket.recvfrom_nonblock(maxlen [, flags[, outbuf [, options]]]) => [mesg, sender_inet_addr]
  #
  # Receives up to _maxlen_ bytes from +udpsocket+ using recvfrom(2) after
  # O_NONBLOCK is set for the underlying file descriptor.
  # _flags_ is zero or more of the +MSG_+ options.
  # The first element of the results, _mesg_, is the data received.
  # The second element, _sender_inet_addr_, is an array to represent the sender address.
  #
  # When recvfrom(2) returns 0,
  # Socket#recvfrom_nonblock returns an empty string as data.
  # It means an empty packet.
  #
  # === Parameters
  # * +maxlen+ - the number of bytes to receive from the socket
  # * +flags+ - zero or more of the +MSG_+ options
  # * +outbuf+ - destination String buffer
  # * +options+ - keyword hash, supporting `exception: false`
  #
  # === Example
  # 	require 'socket'
  # 	s1 = UDPSocket.new
  # 	s1.bind("127.0.0.1", 0)
  # 	s2 = UDPSocket.new
  # 	s2.bind("127.0.0.1", 0)
  # 	s2.connect(*s1.addr.values_at(3,1))
  # 	s1.connect(*s2.addr.values_at(3,1))
  # 	s1.send "aaa", 0
  # 	begin # emulate blocking recvfrom
  # 	  p s2.recvfrom_nonblock(10)  #=> ["aaa", ["AF_INET", 33302, "localhost.localdomain", "127.0.0.1"]]
  # 	rescue IO::WaitReadable
  # 	  IO.select([s2])
  # 	  retry
  # 	end
  #
  # Refer to Socket#recvfrom for the exceptions that may be thrown if the call
  # to _recvfrom_nonblock_ fails.
  #
  # UDPSocket#recvfrom_nonblock may raise any error corresponding to recvfrom(2) failure,
  # including Errno::EWOULDBLOCK.
  #
  # If the exception is Errno::EWOULDBLOCK or Errno::EAGAIN,
  # it is extended by IO::WaitReadable.
  # So IO::WaitReadable can be used to rescue the exceptions for retrying recvfrom_nonblock.
  #
  # By specifying a keyword argument _exception_ to +false+, you can indicate
  # that recvfrom_nonblock should not raise an IO::WaitReadable exception, but
  # return the symbol +:wait_readable+ instead.
  #
  # === See
  # * Socket#recvfrom
  def recvfrom_nonblock(len, flag = 0, outbuf = nil, exception: true)
    __recvfrom_nonblock(len, flag, outbuf, exception)
  end
end

class TCPServer < TCPSocket

  # call-seq:
  #   tcpserver.accept_nonblock([options]) => tcpsocket
  #
  # Accepts an incoming connection using accept(2) after
  # O_NONBLOCK is set for the underlying file descriptor.
  # It returns an accepted TCPSocket for the incoming connection.
  #
  # === Example
  # 	require 'socket'
  # 	serv = TCPServer.new(2202)
  # 	begin # emulate blocking accept
  # 	  sock = serv.accept_nonblock
  # 	rescue IO::WaitReadable, Errno::EINTR
  # 	  IO.select([serv])
  # 	  retry
  # 	end
  # 	# sock is an accepted socket.
  #
  # Refer to Socket#accept for the exceptions that may be thrown if the call
  # to TCPServer#accept_nonblock fails.
  #
  # TCPServer#accept_nonblock may raise any error corresponding to accept(2) failure,
  # including Errno::EWOULDBLOCK.
  #
  # If the exception is Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::ECONNABORTED, Errno::EPROTO,
  # it is extended by IO::WaitReadable.
  # So IO::WaitReadable can be used to rescue the exceptions for retrying accept_nonblock.
  #
  # By specifying a keyword argument _exception_ to +false+, you can indicate
  # that accept_nonblock should not raise an IO::WaitReadable exception, but
  # return the symbol +:wait_readable+ instead.
  #
  # === See
  # * TCPServer#accept
  # * Socket#accept
  def accept_nonblock(exception: true)
    __accept_nonblock(exception)
  end
end

class UNIXServer < UNIXSocket
  # call-seq:
  #   unixserver.accept_nonblock([options]) => unixsocket
  #
  # Accepts an incoming connection using accept(2) after
  # O_NONBLOCK is set for the underlying file descriptor.
  # It returns an accepted UNIXSocket for the incoming connection.
  #
  # === Example
  # 	require 'socket'
  # 	serv = UNIXServer.new("/tmp/sock")
  # 	begin # emulate blocking accept
  # 	  sock = serv.accept_nonblock
  # 	rescue IO::WaitReadable, Errno::EINTR
  # 	  IO.select([serv])
  # 	  retry
  # 	end
  # 	# sock is an accepted socket.
  #
  # Refer to Socket#accept for the exceptions that may be thrown if the call
  # to UNIXServer#accept_nonblock fails.
  #
  # UNIXServer#accept_nonblock may raise any error corresponding to accept(2) failure,
  # including Errno::EWOULDBLOCK.
  #
  # If the exception is Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::ECONNABORTED or Errno::EPROTO,
  # it is extended by IO::WaitReadable.
  # So IO::WaitReadable can be used to rescue the exceptions for retrying accept_nonblock.
  #
  # By specifying a keyword argument _exception_ to +false+, you can indicate
  # that accept_nonblock should not raise an IO::WaitReadable exception, but
  # return the symbol +:wait_readable+ instead.
  #
  # === See
  # * UNIXServer#accept
  # * Socket#accept
  def accept_nonblock(exception: true)
    __accept_nonblock(exception)
  end
end if defined?(UNIXSocket)
# frozen_string_literal: true
#
# = base64.rb: methods for base64-encoding and -decoding strings
#

# The Base64 module provides for the encoding (#encode64, #strict_encode64,
# #urlsafe_encode64) and decoding (#decode64, #strict_decode64,
# #urlsafe_decode64) of binary data using a Base64 representation.
#
# == Example
#
# A simple encoding and decoding.
#
#     require "base64"
#
#     enc   = Base64.encode64('Send reinforcements')
#                         # -> "U2VuZCByZWluZm9yY2VtZW50cw==\n"
#     plain = Base64.decode64(enc)
#                         # -> "Send reinforcements"
#
# The purpose of using base64 to encode data is that it translates any
# binary data into purely printable characters.

module Base64
  module_function

  # Returns the Base64-encoded version of +bin+.
  # This method complies with RFC 2045.
  # Line feeds are added to every 60 encoded characters.
  #
  #    require 'base64'
  #    Base64.encode64("Now is the time for all good coders\nto learn Ruby")
  #
  # <i>Generates:</i>
  #
  #    Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g
  #    UnVieQ==
  def encode64(bin)
    [bin].pack("m")
  end

  # Returns the Base64-decoded version of +str+.
  # This method complies with RFC 2045.
  # Characters outside the base alphabet are ignored.
  #
  #   require 'base64'
  #   str = 'VGhpcyBpcyBsaW5lIG9uZQpUaGlzIG' +
  #         'lzIGxpbmUgdHdvClRoaXMgaXMgbGlu' +
  #         'ZSB0aHJlZQpBbmQgc28gb24uLi4K'
  #   puts Base64.decode64(str)
  #
  # <i>Generates:</i>
  #
  #    This is line one
  #    This is line two
  #    This is line three
  #    And so on...
  def decode64(str)
    str.unpack1("m")
  end

  # Returns the Base64-encoded version of +bin+.
  # This method complies with RFC 4648.
  # No line feeds are added.
  def strict_encode64(bin)
    [bin].pack("m0")
  end

  # Returns the Base64-decoded version of +str+.
  # This method complies with RFC 4648.
  # ArgumentError is raised if +str+ is incorrectly padded or contains
  # non-alphabet characters.  Note that CR or LF are also rejected.
  def strict_decode64(str)
    str.unpack1("m0")
  end

  # Returns the Base64-encoded version of +bin+.
  # This method complies with ``Base 64 Encoding with URL and Filename Safe
  # Alphabet'' in RFC 4648.
  # The alphabet uses '-' instead of '+' and '_' instead of '/'.
  # Note that the result can still contain '='.
  # You can remove the padding by setting +padding+ as false.
  def urlsafe_encode64(bin, padding: true)
    str = strict_encode64(bin)
    str.tr!("+/", "-_")
    str.delete!("=") unless padding
    str
  end

  # Returns the Base64-decoded version of +str+.
  # This method complies with ``Base 64 Encoding with URL and Filename Safe
  # Alphabet'' in RFC 4648.
  # The alphabet uses '-' instead of '+' and '_' instead of '/'.
  #
  # The padding character is optional.
  # This method accepts both correctly-padded and unpadded input.
  # Note that it still rejects incorrectly-padded input.
  def urlsafe_decode64(str)
    # NOTE: RFC 4648 does say nothing about unpadded input, but says that
    # "the excess pad characters MAY also be ignored", so it is inferred that
    # unpadded input is also acceptable.
    str = str.tr("-_", "+/")
    if !str.end_with?("=") && str.length % 4 != 0
      str = str.ljust((str.length + 3) & ~3, "=")
    end
    strict_decode64(str)
  end
end
# frozen_string_literal: true

#
# = open3.rb: Popen, but with stderr, too
#
# Author:: Yukihiro Matsumoto
# Documentation:: Konrad Meyer
#
# Open3 gives you access to stdin, stdout, and stderr when running other
# programs.
#

#
# Open3 grants you access to stdin, stdout, stderr and a thread to wait for the
# child process when running another program.
# You can specify various attributes, redirections, current directory, etc., of
# the program in the same way as for Process.spawn.
#
# - Open3.popen3 : pipes for stdin, stdout, stderr
# - Open3.popen2 : pipes for stdin, stdout
# - Open3.popen2e : pipes for stdin, merged stdout and stderr
# - Open3.capture3 : give a string for stdin; get strings for stdout, stderr
# - Open3.capture2 : give a string for stdin; get a string for stdout
# - Open3.capture2e : give a string for stdin; get a string for merged stdout and stderr
# - Open3.pipeline_rw : pipes for first stdin and last stdout of a pipeline
# - Open3.pipeline_r : pipe for last stdout of a pipeline
# - Open3.pipeline_w : pipe for first stdin of a pipeline
# - Open3.pipeline_start : run a pipeline without waiting
# - Open3.pipeline : run a pipeline and wait for its completion
#

module Open3
  VERSION = "0.1.1"

  # Open stdin, stdout, and stderr streams and start external executable.
  # In addition, a thread to wait for the started process is created.
  # The thread has a pid method and a thread variable :pid which is the pid of
  # the started process.
  #
  # Block form:
  #
  #   Open3.popen3([env,] cmd... [, opts]) {|stdin, stdout, stderr, wait_thr|
  #     pid = wait_thr.pid # pid of the started process.
  #     ...
  #     exit_status = wait_thr.value # Process::Status object returned.
  #   }
  #
  # Non-block form:
  #
  #   stdin, stdout, stderr, wait_thr = Open3.popen3([env,] cmd... [, opts])
  #   pid = wait_thr[:pid]  # pid of the started process
  #   ...
  #   stdin.close  # stdin, stdout and stderr should be closed explicitly in this form.
  #   stdout.close
  #   stderr.close
  #   exit_status = wait_thr.value  # Process::Status object returned.
  #
  # The parameters env, cmd, and opts are passed to Process.spawn.
  # A commandline string and a list of argument strings can be accepted as follows:
  #
  #   Open3.popen3("echo abc") {|i, o, e, t| ... }
  #   Open3.popen3("echo", "abc") {|i, o, e, t| ... }
  #   Open3.popen3(["echo", "argv0"], "abc") {|i, o, e, t| ... }
  #
  # If the last parameter, opts, is a Hash, it is recognized as an option for Process.spawn.
  #
  #   Open3.popen3("pwd", :chdir=>"/") {|i,o,e,t|
  #     p o.read.chomp #=> "/"
  #   }
  #
  # wait_thr.value waits for the termination of the process.
  # The block form also waits for the process when it returns.
  #
  # Closing stdin, stdout and stderr does not wait for the process to complete.
  #
  # You should be careful to avoid deadlocks.
  # Since pipes are fixed length buffers,
  # Open3.popen3("prog") {|i, o, e, t| o.read } deadlocks if
  # the program generates too much output on stderr.
  # You should read stdout and stderr simultaneously (using threads or IO.select).
  # However, if you don't need stderr output, you can use Open3.popen2.
  # If merged stdout and stderr output is not a problem, you can use Open3.popen2e.
  # If you really need stdout and stderr output as separate strings, you can consider Open3.capture3.
  #
  def popen3(*cmd, &block)
    if Hash === cmd.last
      opts = cmd.pop.dup
    else
      opts = {}
    end

    in_r, in_w = IO.pipe
    opts[:in] = in_r
    in_w.sync = true

    out_r, out_w = IO.pipe
    opts[:out] = out_w

    err_r, err_w = IO.pipe
    opts[:err] = err_w

    popen_run(cmd, opts, [in_r, out_w, err_w], [in_w, out_r, err_r], &block)
  end
  module_function :popen3

  # Open3.popen2 is similar to Open3.popen3 except that it doesn't create a pipe for
  # the standard error stream.
  #
  # Block form:
  #
  #   Open3.popen2([env,] cmd... [, opts]) {|stdin, stdout, wait_thr|
  #     pid = wait_thr.pid # pid of the started process.
  #     ...
  #     exit_status = wait_thr.value # Process::Status object returned.
  #   }
  #
  # Non-block form:
  #
  #   stdin, stdout, wait_thr = Open3.popen2([env,] cmd... [, opts])
  #   ...
  #   stdin.close  # stdin and stdout should be closed explicitly in this form.
  #   stdout.close
  #
  # See Process.spawn for the optional hash arguments _env_ and _opts_.
  #
  # Example:
  #
  #   Open3.popen2("wc -c") {|i,o,t|
  #     i.print "answer to life the universe and everything"
  #     i.close
  #     p o.gets #=> "42\n"
  #   }
  #
  #   Open3.popen2("bc -q") {|i,o,t|
  #     i.puts "obase=13"
  #     i.puts "6 * 9"
  #     p o.gets #=> "42\n"
  #   }
  #
  #   Open3.popen2("dc") {|i,o,t|
  #     i.print "42P"
  #     i.close
  #     p o.read #=> "*"
  #   }
  #
  def popen2(*cmd, &block)
    if Hash === cmd.last
      opts = cmd.pop.dup
    else
      opts = {}
    end

    in_r, in_w = IO.pipe
    opts[:in] = in_r
    in_w.sync = true

    out_r, out_w = IO.pipe
    opts[:out] = out_w

    popen_run(cmd, opts, [in_r, out_w], [in_w, out_r], &block)
  end
  module_function :popen2

  # Open3.popen2e is similar to Open3.popen3 except that it merges
  # the standard output stream and the standard error stream.
  #
  # Block form:
  #
  #   Open3.popen2e([env,] cmd... [, opts]) {|stdin, stdout_and_stderr, wait_thr|
  #     pid = wait_thr.pid # pid of the started process.
  #     ...
  #     exit_status = wait_thr.value # Process::Status object returned.
  #   }
  #
  # Non-block form:
  #
  #   stdin, stdout_and_stderr, wait_thr = Open3.popen2e([env,] cmd... [, opts])
  #   ...
  #   stdin.close  # stdin and stdout_and_stderr should be closed explicitly in this form.
  #   stdout_and_stderr.close
  #
  # See Process.spawn for the optional hash arguments _env_ and _opts_.
  #
  # Example:
  #   # check gcc warnings
  #   source = "foo.c"
  #   Open3.popen2e("gcc", "-Wall", source) {|i,oe,t|
  #     oe.each {|line|
  #       if /warning/ =~ line
  #         ...
  #       end
  #     }
  #   }
  #
  def popen2e(*cmd, &block)
    if Hash === cmd.last
      opts = cmd.pop.dup
    else
      opts = {}
    end

    in_r, in_w = IO.pipe
    opts[:in] = in_r
    in_w.sync = true

    out_r, out_w = IO.pipe
    opts[[:out, :err]] = out_w

    popen_run(cmd, opts, [in_r, out_w], [in_w, out_r], &block)
  ensure
    if block
      in_r.close
      in_w.close
      out_r.close
      out_w.close
    end
  end
  module_function :popen2e

  def popen_run(cmd, opts, child_io, parent_io) # :nodoc:
    pid = spawn(*cmd, opts)
    wait_thr = Process.detach(pid)
    child_io.each(&:close)
    result = [*parent_io, wait_thr]
    if defined? yield
      begin
        return yield(*result)
      ensure
        parent_io.each(&:close)
        wait_thr.join
      end
    end
    result
  end
  module_function :popen_run
  class << self
    private :popen_run
  end

  # Open3.capture3 captures the standard output and the standard error of a command.
  #
  #   stdout_str, stderr_str, status = Open3.capture3([env,] cmd... [, opts])
  #
  # The arguments env, cmd and opts are passed to Open3.popen3 except
  # <code>opts[:stdin_data]</code> and <code>opts[:binmode]</code>.  See Process.spawn.
  #
  # If <code>opts[:stdin_data]</code> is specified, it is sent to the command's standard input.
  #
  # If <code>opts[:binmode]</code> is true, internal pipes are set to binary mode.
  #
  # Examples:
  #
  #   # dot is a command of graphviz.
  #   graph = <<'End'
  #     digraph g {
  #       a -> b
  #     }
  #   End
  #   drawn_graph, dot_log = Open3.capture3("dot -v", :stdin_data=>graph)
  #
  #   o, e, s = Open3.capture3("echo abc; sort >&2", :stdin_data=>"foo\nbar\nbaz\n")
  #   p o #=> "abc\n"
  #   p e #=> "bar\nbaz\nfoo\n"
  #   p s #=> #<Process::Status: pid 32682 exit 0>
  #
  #   # generate a thumbnail image using the convert command of ImageMagick.
  #   # However, if the image is really stored in a file,
  #   # system("convert", "-thumbnail", "80", "png:#{filename}", "png:-") is better
  #   # because of reduced memory consumption.
  #   # But if the image is stored in a DB or generated by the gnuplot Open3.capture2 example,
  #   # Open3.capture3 should be considered.
  #   #
  #   image = File.read("/usr/share/openclipart/png/animals/mammals/sheep-md-v0.1.png", :binmode=>true)
  #   thumbnail, err, s = Open3.capture3("convert -thumbnail 80 png:- png:-", :stdin_data=>image, :binmode=>true)
  #   if s.success?
  #     STDOUT.binmode; print thumbnail
  #   end
  #
  def capture3(*cmd)
    if Hash === cmd.last
      opts = cmd.pop.dup
    else
      opts = {}
    end

    stdin_data = opts.delete(:stdin_data) || ''
    binmode = opts.delete(:binmode)

    popen3(*cmd, opts) {|i, o, e, t|
      if binmode
        i.binmode
        o.binmode
        e.binmode
      end
      out_reader = Thread.new { o.read }
      err_reader = Thread.new { e.read }
      begin
        if stdin_data.respond_to? :readpartial
          IO.copy_stream(stdin_data, i)
        else
          i.write stdin_data
        end
      rescue Errno::EPIPE
      end
      i.close
      [out_reader.value, err_reader.value, t.value]
    }
  end
  module_function :capture3

  # Open3.capture2 captures the standard output of a command.
  #
  #   stdout_str, status = Open3.capture2([env,] cmd... [, opts])
  #
  # The arguments env, cmd and opts are passed to Open3.popen3 except
  # <code>opts[:stdin_data]</code> and <code>opts[:binmode]</code>.  See Process.spawn.
  #
  # If <code>opts[:stdin_data]</code> is specified, it is sent to the command's standard input.
  #
  # If <code>opts[:binmode]</code> is true, internal pipes are set to binary mode.
  #
  # Example:
  #
  #   # factor is a command for integer factorization.
  #   o, s = Open3.capture2("factor", :stdin_data=>"42")
  #   p o #=> "42: 2 3 7\n"
  #
  #   # generate x**2 graph in png using gnuplot.
  #   gnuplot_commands = <<"End"
  #     set terminal png
  #     plot x**2, "-" with lines
  #     1 14
  #     2 1
  #     3 8
  #     4 5
  #     e
  #   End
  #   image, s = Open3.capture2("gnuplot", :stdin_data=>gnuplot_commands, :binmode=>true)
  #
  def capture2(*cmd)
    if Hash === cmd.last
      opts = cmd.pop.dup
    else
      opts = {}
    end

    stdin_data = opts.delete(:stdin_data)
    binmode = opts.delete(:binmode)

    popen2(*cmd, opts) {|i, o, t|
      if binmode
        i.binmode
        o.binmode
      end
      out_reader = Thread.new { o.read }
      if stdin_data
        begin
          if stdin_data.respond_to? :readpartial
            IO.copy_stream(stdin_data, i)
          else
            i.write stdin_data
          end
        rescue Errno::EPIPE
        end
      end
      i.close
      [out_reader.value, t.value]
    }
  end
  module_function :capture2

  # Open3.capture2e captures the standard output and the standard error of a command.
  #
  #   stdout_and_stderr_str, status = Open3.capture2e([env,] cmd... [, opts])
  #
  # The arguments env, cmd and opts are passed to Open3.popen3 except
  # <code>opts[:stdin_data]</code> and <code>opts[:binmode]</code>.  See Process.spawn.
  #
  # If <code>opts[:stdin_data]</code> is specified, it is sent to the command's standard input.
  #
  # If <code>opts[:binmode]</code> is true, internal pipes are set to binary mode.
  #
  # Example:
  #
  #   # capture make log
  #   make_log, s = Open3.capture2e("make")
  #
  def capture2e(*cmd)
    if Hash === cmd.last
      opts = cmd.pop.dup
    else
      opts = {}
    end

    stdin_data = opts.delete(:stdin_data)
    binmode = opts.delete(:binmode)

    popen2e(*cmd, opts) {|i, oe, t|
      if binmode
        i.binmode
        oe.binmode
      end
      outerr_reader = Thread.new { oe.read }
      if stdin_data
        begin
          if stdin_data.respond_to? :readpartial
            IO.copy_stream(stdin_data, i)
          else
            i.write stdin_data
          end
        rescue Errno::EPIPE
        end
      end
      i.close
      [outerr_reader.value, t.value]
    }
  end
  module_function :capture2e

  # Open3.pipeline_rw starts a list of commands as a pipeline with pipes
  # which connect to stdin of the first command and stdout of the last command.
  #
  #   Open3.pipeline_rw(cmd1, cmd2, ... [, opts]) {|first_stdin, last_stdout, wait_threads|
  #     ...
  #   }
  #
  #   first_stdin, last_stdout, wait_threads = Open3.pipeline_rw(cmd1, cmd2, ... [, opts])
  #   ...
  #   first_stdin.close
  #   last_stdout.close
  #
  # Each cmd is a string or an array.
  # If it is an array, the elements are passed to Process.spawn.
  #
  #   cmd:
  #     commandline                              command line string which is passed to a shell
  #     [env, commandline, opts]                 command line string which is passed to a shell
  #     [env, cmdname, arg1, ..., opts]          command name and one or more arguments (no shell)
  #     [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
  #
  #   Note that env and opts are optional, as for Process.spawn.
  #
  # The options to pass to Process.spawn are constructed by merging
  # +opts+, the last hash element of the array, and
  # specifications for the pipes between each of the commands.
  #
  # Example:
  #
  #   Open3.pipeline_rw("tr -dc A-Za-z", "wc -c") {|i, o, ts|
  #     i.puts "All persons more than a mile high to leave the court."
  #     i.close
  #     p o.gets #=> "42\n"
  #   }
  #
  #   Open3.pipeline_rw("sort", "cat -n") {|stdin, stdout, wait_thrs|
  #     stdin.puts "foo"
  #     stdin.puts "bar"
  #     stdin.puts "baz"
  #     stdin.close     # send EOF to sort.
  #     p stdout.read   #=> "     1\tbar\n     2\tbaz\n     3\tfoo\n"
  #   }
  def pipeline_rw(*cmds, &block)
    if Hash === cmds.last
      opts = cmds.pop.dup
    else
      opts = {}
    end

    in_r, in_w = IO.pipe
    opts[:in] = in_r
    in_w.sync = true

    out_r, out_w = IO.pipe
    opts[:out] = out_w

    pipeline_run(cmds, opts, [in_r, out_w], [in_w, out_r], &block)
  end
  module_function :pipeline_rw

  # Open3.pipeline_r starts a list of commands as a pipeline with a pipe
  # which connects to stdout of the last command.
  #
  #   Open3.pipeline_r(cmd1, cmd2, ... [, opts]) {|last_stdout, wait_threads|
  #     ...
  #   }
  #
  #   last_stdout, wait_threads = Open3.pipeline_r(cmd1, cmd2, ... [, opts])
  #   ...
  #   last_stdout.close
  #
  # Each cmd is a string or an array.
  # If it is an array, the elements are passed to Process.spawn.
  #
  #   cmd:
  #     commandline                              command line string which is passed to a shell
  #     [env, commandline, opts]                 command line string which is passed to a shell
  #     [env, cmdname, arg1, ..., opts]          command name and one or more arguments (no shell)
  #     [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
  #
  #   Note that env and opts are optional, as for Process.spawn.
  #
  # Example:
  #
  #   Open3.pipeline_r("zcat /var/log/apache2/access.log.*.gz",
  #                    [{"LANG"=>"C"}, "grep", "GET /favicon.ico"],
  #                    "logresolve") {|o, ts|
  #     o.each_line {|line|
  #       ...
  #     }
  #   }
  #
  #   Open3.pipeline_r("yes", "head -10") {|o, ts|
  #     p o.read      #=> "y\ny\ny\ny\ny\ny\ny\ny\ny\ny\n"
  #     p ts[0].value #=> #<Process::Status: pid 24910 SIGPIPE (signal 13)>
  #     p ts[1].value #=> #<Process::Status: pid 24913 exit 0>
  #   }
  #
  def pipeline_r(*cmds, &block)
    if Hash === cmds.last
      opts = cmds.pop.dup
    else
      opts = {}
    end

    out_r, out_w = IO.pipe
    opts[:out] = out_w

    pipeline_run(cmds, opts, [out_w], [out_r], &block)
  end
  module_function :pipeline_r

  # Open3.pipeline_w starts a list of commands as a pipeline with a pipe
  # which connects to stdin of the first command.
  #
  #   Open3.pipeline_w(cmd1, cmd2, ... [, opts]) {|first_stdin, wait_threads|
  #     ...
  #   }
  #
  #   first_stdin, wait_threads = Open3.pipeline_w(cmd1, cmd2, ... [, opts])
  #   ...
  #   first_stdin.close
  #
  # Each cmd is a string or an array.
  # If it is an array, the elements are passed to Process.spawn.
  #
  #   cmd:
  #     commandline                              command line string which is passed to a shell
  #     [env, commandline, opts]                 command line string which is passed to a shell
  #     [env, cmdname, arg1, ..., opts]          command name and one or more arguments (no shell)
  #     [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
  #
  #   Note that env and opts are optional, as for Process.spawn.
  #
  # Example:
  #
  #   Open3.pipeline_w("bzip2 -c", :out=>"/tmp/hello.bz2") {|i, ts|
  #     i.puts "hello"
  #   }
  #
  def pipeline_w(*cmds, &block)
    if Hash === cmds.last
      opts = cmds.pop.dup
    else
      opts = {}
    end

    in_r, in_w = IO.pipe
    opts[:in] = in_r
    in_w.sync = true

    pipeline_run(cmds, opts, [in_r], [in_w], &block)
  end
  module_function :pipeline_w

  # Open3.pipeline_start starts a list of commands as a pipeline.
  # No pipes are created for stdin of the first command and
  # stdout of the last command.
  #
  #   Open3.pipeline_start(cmd1, cmd2, ... [, opts]) {|wait_threads|
  #     ...
  #   }
  #
  #   wait_threads = Open3.pipeline_start(cmd1, cmd2, ... [, opts])
  #   ...
  #
  # Each cmd is a string or an array.
  # If it is an array, the elements are passed to Process.spawn.
  #
  #   cmd:
  #     commandline                              command line string which is passed to a shell
  #     [env, commandline, opts]                 command line string which is passed to a shell
  #     [env, cmdname, arg1, ..., opts]          command name and one or more arguments (no shell)
  #     [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
  #
  #   Note that env and opts are optional, as for Process.spawn.
  #
  # Example:
  #
  #   # Run xeyes in 10 seconds.
  #   Open3.pipeline_start("xeyes") {|ts|
  #     sleep 10
  #     t = ts[0]
  #     Process.kill("TERM", t.pid)
  #     p t.value #=> #<Process::Status: pid 911 SIGTERM (signal 15)>
  #   }
  #
  #   # Convert pdf to ps and send it to a printer.
  #   # Collect error message of pdftops and lpr.
  #   pdf_file = "paper.pdf"
  #   printer = "printer-name"
  #   err_r, err_w = IO.pipe
  #   Open3.pipeline_start(["pdftops", pdf_file, "-"],
  #                        ["lpr", "-P#{printer}"],
  #                        :err=>err_w) {|ts|
  #     err_w.close
  #     p err_r.read # error messages of pdftops and lpr.
  #   }
  #
  def pipeline_start(*cmds, &block)
    if Hash === cmds.last
      opts = cmds.pop.dup
    else
      opts = {}
    end

    if block
      pipeline_run(cmds, opts, [], [], &block)
    else
      ts, = pipeline_run(cmds, opts, [], [])
      ts
    end
  end
  module_function :pipeline_start

  # Open3.pipeline starts a list of commands as a pipeline.
  # It waits for the completion of the commands.
  # No pipes are created for stdin of the first command and
  # stdout of the last command.
  #
  #   status_list = Open3.pipeline(cmd1, cmd2, ... [, opts])
  #
  # Each cmd is a string or an array.
  # If it is an array, the elements are passed to Process.spawn.
  #
  #   cmd:
  #     commandline                              command line string which is passed to a shell
  #     [env, commandline, opts]                 command line string which is passed to a shell
  #     [env, cmdname, arg1, ..., opts]          command name and one or more arguments (no shell)
  #     [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
  #
  #   Note that env and opts are optional, as Process.spawn.
  #
  # Example:
  #
  #   fname = "/usr/share/man/man1/ruby.1.gz"
  #   p Open3.pipeline(["zcat", fname], "nroff -man", "less")
  #   #=> [#<Process::Status: pid 11817 exit 0>,
  #   #    #<Process::Status: pid 11820 exit 0>,
  #   #    #<Process::Status: pid 11828 exit 0>]
  #
  #   fname = "/usr/share/man/man1/ls.1.gz"
  #   Open3.pipeline(["zcat", fname], "nroff -man", "colcrt")
  #
  #   # convert PDF to PS and send to a printer by lpr
  #   pdf_file = "paper.pdf"
  #   printer = "printer-name"
  #   Open3.pipeline(["pdftops", pdf_file, "-"],
  #                  ["lpr", "-P#{printer}"])
  #
  #   # count lines
  #   Open3.pipeline("sort", "uniq -c", :in=>"names.txt", :out=>"count")
  #
  #   # cyclic pipeline
  #   r,w = IO.pipe
  #   w.print "ibase=14\n10\n"
  #   Open3.pipeline("bc", "tee /dev/tty", :in=>r, :out=>w)
  #   #=> 14
  #   #   18
  #   #   22
  #   #   30
  #   #   42
  #   #   58
  #   #   78
  #   #   106
  #   #   202
  #
  def pipeline(*cmds)
    if Hash === cmds.last
      opts = cmds.pop.dup
    else
      opts = {}
    end

    pipeline_run(cmds, opts, [], []) {|ts|
      ts.map(&:value)
    }
  end
  module_function :pipeline

  def pipeline_run(cmds, pipeline_opts, child_io, parent_io) # :nodoc:
    if cmds.empty?
      raise ArgumentError, "no commands"
    end

    opts_base = pipeline_opts.dup
    opts_base.delete :in
    opts_base.delete :out

    wait_thrs = []
    r = nil
    cmds.each_with_index {|cmd, i|
      cmd_opts = opts_base.dup
      if String === cmd
        cmd = [cmd]
      else
        cmd_opts.update cmd.pop if Hash === cmd.last
      end
      if i == 0
        if !cmd_opts.include?(:in)
          if pipeline_opts.include?(:in)
            cmd_opts[:in] = pipeline_opts[:in]
          end
        end
      else
        cmd_opts[:in] = r
      end
      if i != cmds.length - 1
        r2, w2 = IO.pipe
        cmd_opts[:out] = w2
      else
        if !cmd_opts.include?(:out)
          if pipeline_opts.include?(:out)
            cmd_opts[:out] = pipeline_opts[:out]
          end
        end
      end
      pid = spawn(*cmd, cmd_opts)
      wait_thrs << Process.detach(pid)
      r&.close
      w2&.close
      r = r2
    }
    result = parent_io + [wait_thrs]
    child_io.each(&:close)
    if defined? yield
      begin
        return yield(*result)
      ensure
        parent_io.each(&:close)
        wait_thrs.each(&:join)
      end
    end
    result
  end
  module_function :pipeline_run
  class << self
    private :pipeline_run
  end

end
# frozen_string_literal: false
#
# Note: Rinda::Ring API is unstable.
#
require 'drb/drb'
require_relative 'rinda'
require 'ipaddr'

module Rinda

  ##
  # The default port Ring discovery will use.

  Ring_PORT = 7647

  ##
  # A RingServer allows a Rinda::TupleSpace to be located via UDP broadcasts.
  # Default service location uses the following steps:
  #
  # 1. A RingServer begins listening on the network broadcast UDP address.
  # 2. A RingFinger sends a UDP packet containing the DRb URI where it will
  #    listen for a reply.
  # 3. The RingServer receives the UDP packet and connects back to the
  #    provided DRb URI with the DRb service.
  #
  # A RingServer requires a TupleSpace:
  #
  #   ts = Rinda::TupleSpace.new
  #   rs = Rinda::RingServer.new
  #
  # RingServer can also listen on multicast addresses for announcements.  This
  # allows multiple RingServers to run on the same host.  To use network
  # broadcast and multicast:
  #
  #   ts = Rinda::TupleSpace.new
  #   rs = Rinda::RingServer.new ts, %w[Socket::INADDR_ANY, 239.0.0.1 ff02::1]

  class RingServer

    include DRbUndumped

    ##
    # Special renewer for the RingServer to allow shutdown

    class Renewer # :nodoc:
      include DRbUndumped

      ##
      # Set to false to shutdown future requests using this Renewer

      attr_writer :renew

      def initialize # :nodoc:
        @renew = true
      end

      def renew # :nodoc:
        @renew ? 1 : true
      end
    end

    ##
    # Advertises +ts+ on the given +addresses+ at +port+.
    #
    # If +addresses+ is omitted only the UDP broadcast address is used.
    #
    # +addresses+ can contain multiple addresses.  If a multicast address is
    # given in +addresses+ then the RingServer will listen for multicast
    # queries.
    #
    # If you use IPv4 multicast you may need to set an address of the inbound
    # interface which joins a multicast group.
    #
    #   ts = Rinda::TupleSpace.new
    #   rs = Rinda::RingServer.new(ts, [['239.0.0.1', '9.5.1.1']])
    #
    # You can set addresses as an Array Object.  The first element of the
    # Array is a multicast address and the second is an inbound interface
    # address.  If the second is omitted then '0.0.0.0' is used.
    #
    # If you use IPv6 multicast you may need to set both the local interface
    # address and the inbound interface index:
    #
    #   rs = Rinda::RingServer.new(ts, [['ff02::1', '::1', 1]])
    #
    # The first element is a multicast address and the second is an inbound
    # interface address.  The third is an inbound interface index.
    #
    # At this time there is no easy way to get an interface index by name.
    #
    # If the second is omitted then '::1' is used.
    # If the third is omitted then 0 (default interface) is used.

    def initialize(ts, addresses=[Socket::INADDR_ANY], port=Ring_PORT)
      @port = port

      if Integer === addresses then
        addresses, @port = [Socket::INADDR_ANY], addresses
      end

      @renewer = Renewer.new

      @ts = ts
      @sockets = []
      addresses.each do |address|
        if Array === address
          make_socket(*address)
        else
          make_socket(address)
        end
      end

      @w_services = write_services
      @r_service  = reply_service
    end

    ##
    # Creates a socket at +address+
    #
    # If +address+ is multicast address then +interface_address+ and
    # +multicast_interface+ can be set as optional.
    #
    # A created socket is bound to +interface_address+.  If you use IPv4
    # multicast then the interface of +interface_address+ is used as the
    # inbound interface.  If +interface_address+ is omitted or nil then
    # '0.0.0.0' or '::1' is used.
    #
    # If you use IPv6 multicast then +multicast_interface+ is used as the
    # inbound interface.  +multicast_interface+ is a network interface index.
    # If +multicast_interface+ is omitted then 0 (default interface) is used.

    def make_socket(address, interface_address=nil, multicast_interface=0)
      addrinfo = Addrinfo.udp(address, @port)

      socket = Socket.new(addrinfo.pfamily, addrinfo.socktype,
                          addrinfo.protocol)

      if addrinfo.ipv4_multicast? or addrinfo.ipv6_multicast? then
        if Socket.const_defined?(:SO_REUSEPORT) then
          socket.setsockopt(:SOCKET, :SO_REUSEPORT, true)
        else
          socket.setsockopt(:SOCKET, :SO_REUSEADDR, true)
        end

        if addrinfo.ipv4_multicast? then
          interface_address = '0.0.0.0' if interface_address.nil?
          socket.bind(Addrinfo.udp(interface_address, @port))

          mreq = IPAddr.new(addrinfo.ip_address).hton +
            IPAddr.new(interface_address).hton

          socket.setsockopt(:IPPROTO_IP, :IP_ADD_MEMBERSHIP, mreq)
        else
          interface_address = '::1' if interface_address.nil?
          socket.bind(Addrinfo.udp(interface_address, @port))

          mreq = IPAddr.new(addrinfo.ip_address).hton +
            [multicast_interface].pack('I')

          socket.setsockopt(:IPPROTO_IPV6, :IPV6_JOIN_GROUP, mreq)
        end
      else
        socket.bind(addrinfo)
      end

      socket
    rescue
      socket = socket.close if socket
      raise
    ensure
      @sockets << socket if socket
    end

    ##
    # Creates threads that pick up UDP packets and passes them to do_write for
    # decoding.

    def write_services
      @sockets.map do |s|
        Thread.new(s) do |socket|
          loop do
            msg = socket.recv(1024)
            do_write(msg)
          end
        end
      end
    end

    ##
    # Extracts the response URI from +msg+ and adds it to TupleSpace where it
    # will be picked up by +reply_service+ for notification.

    def do_write(msg)
      Thread.new do
        begin
          tuple, sec = Marshal.load(msg)
          @ts.write(tuple, sec)
        rescue
        end
      end
    end

    ##
    # Creates a thread that notifies waiting clients from the TupleSpace.

    def reply_service
      Thread.new do
        loop do
          do_reply
        end
      end
    end

    ##
    # Pulls lookup tuples out of the TupleSpace and sends their DRb object the
    # address of the local TupleSpace.

    def do_reply
      tuple = @ts.take([:lookup_ring, nil], @renewer)
      Thread.new { tuple[1].call(@ts) rescue nil}
    rescue
    end

    ##
    # Shuts down the RingServer

    def shutdown
      @renewer.renew = false

      @w_services.each do |thread|
        thread.kill
        thread.join
      end

      @sockets.each do |socket|
        socket.close
      end

      @r_service.kill
      @r_service.join
    end

  end

  ##
  # RingFinger is used by RingServer clients to discover the RingServer's
  # TupleSpace.  Typically, all a client needs to do is call
  # RingFinger.primary to retrieve the remote TupleSpace, which it can then
  # begin using.
  #
  # To find the first available remote TupleSpace:
  #
  #   Rinda::RingFinger.primary
  #
  # To create a RingFinger that broadcasts to a custom list:
  #
  #   rf = Rinda::RingFinger.new  ['localhost', '192.0.2.1']
  #   rf.primary
  #
  # Rinda::RingFinger also understands multicast addresses and sets them up
  # properly.  This allows you to run multiple RingServers on the same host:
  #
  #   rf = Rinda::RingFinger.new ['239.0.0.1']
  #   rf.primary
  #
  # You can set the hop count (or TTL) for multicast searches using
  # #multicast_hops.
  #
  # If you use IPv6 multicast you may need to set both an address and the
  # outbound interface index:
  #
  #   rf = Rinda::RingFinger.new ['ff02::1']
  #   rf.multicast_interface = 1
  #   rf.primary
  #
  # At this time there is no easy way to get an interface index by name.

  class RingFinger

    @@broadcast_list = ['<broadcast>', 'localhost']

    @@finger = nil

    ##
    # Creates a singleton RingFinger and looks for a RingServer.  Returns the
    # created RingFinger.

    def self.finger
      unless @@finger
        @@finger = self.new
        @@finger.lookup_ring_any
      end
      @@finger
    end

    ##
    # Returns the first advertised TupleSpace.

    def self.primary
      finger.primary
    end

    ##
    # Contains all discovered TupleSpaces except for the primary.

    def self.to_a
      finger.to_a
    end

    ##
    # The list of addresses where RingFinger will send query packets.

    attr_accessor :broadcast_list

    ##
    # Maximum number of hops for sent multicast packets (if using a multicast
    # address in the broadcast list).  The default is 1 (same as UDP
    # broadcast).

    attr_accessor :multicast_hops

    ##
    # The interface index to send IPv6 multicast packets from.

    attr_accessor :multicast_interface

    ##
    # The port that RingFinger will send query packets to.

    attr_accessor :port

    ##
    # Contain the first advertised TupleSpace after lookup_ring_any is called.

    attr_accessor :primary

    ##
    # Creates a new RingFinger that will look for RingServers at +port+ on
    # the addresses in +broadcast_list+.
    #
    # If +broadcast_list+ contains a multicast address then multicast queries
    # will be made using the given multicast_hops and multicast_interface.

    def initialize(broadcast_list=@@broadcast_list, port=Ring_PORT)
      @broadcast_list = broadcast_list || ['localhost']
      @port = port
      @primary = nil
      @rings = []

      @multicast_hops = 1
      @multicast_interface = 0
    end

    ##
    # Contains all discovered TupleSpaces except for the primary.

    def to_a
      @rings
    end

    ##
    # Iterates over all discovered TupleSpaces starting with the primary.

    def each
      lookup_ring_any unless @primary
      return unless @primary
      yield(@primary)
      @rings.each { |x| yield(x) }
    end

    ##
    # Looks up RingServers waiting +timeout+ seconds.  RingServers will be
    # given +block+ as a callback, which will be called with the remote
    # TupleSpace.

    def lookup_ring(timeout=5, &block)
      return lookup_ring_any(timeout) unless block_given?

      msg = Marshal.dump([[:lookup_ring, DRbObject.new(block)], timeout])
      @broadcast_list.each do |it|
        send_message(it, msg)
      end
      sleep(timeout)
    end

    ##
    # Returns the first found remote TupleSpace.  Any further recovered
    # TupleSpaces can be found by calling +to_a+.

    def lookup_ring_any(timeout=5)
      queue = Thread::Queue.new

      Thread.new do
        self.lookup_ring(timeout) do |ts|
          queue.push(ts)
        end
        queue.push(nil)
      end

      @primary = queue.pop
      raise('RingNotFound') if @primary.nil?

      Thread.new do
        while it = queue.pop
          @rings.push(it)
        end
      end

      @primary
    end

    ##
    # Creates a socket for +address+ with the appropriate multicast options
    # for multicast addresses.

    def make_socket(address) # :nodoc:
      addrinfo = Addrinfo.udp(address, @port)

      soc = Socket.new(addrinfo.pfamily, addrinfo.socktype, addrinfo.protocol)
      begin
        if addrinfo.ipv4_multicast? then
          soc.setsockopt(Socket::Option.ipv4_multicast_loop(1))
          soc.setsockopt(Socket::Option.ipv4_multicast_ttl(@multicast_hops))
        elsif addrinfo.ipv6_multicast? then
          soc.setsockopt(:IPPROTO_IPV6, :IPV6_MULTICAST_LOOP, true)
          soc.setsockopt(:IPPROTO_IPV6, :IPV6_MULTICAST_HOPS,
                         [@multicast_hops].pack('I'))
          soc.setsockopt(:IPPROTO_IPV6, :IPV6_MULTICAST_IF,
                         [@multicast_interface].pack('I'))
        else
          soc.setsockopt(:SOL_SOCKET, :SO_BROADCAST, true)
        end

        soc.connect(addrinfo)
      rescue Exception
        soc.close
        raise
      end

      soc
    end

    def send_message(address, message) # :nodoc:
      soc = make_socket(address)

      soc.send(message, 0)
    rescue
      nil
    ensure
      soc.close if soc
    end

  end

  ##
  # RingProvider uses a RingServer advertised TupleSpace as a name service.
  # TupleSpace clients can register themselves with the remote TupleSpace and
  # look up other provided services via the remote TupleSpace.
  #
  # Services are registered with a tuple of the format [:name, klass,
  # DRbObject, description].

  class RingProvider

    ##
    # Creates a RingProvider that will provide a +klass+ service running on
    # +front+, with a +description+.  +renewer+ is optional.

    def initialize(klass, front, desc, renewer = nil)
      @tuple = [:name, klass, front, desc]
      @renewer = renewer || Rinda::SimpleRenewer.new
    end

    ##
    # Advertises this service on the primary remote TupleSpace.

    def provide
      ts = Rinda::RingFinger.primary
      ts.write(@tuple, @renewer)
    end

  end

end
# frozen_string_literal: false
require 'monitor'
require 'drb/drb'
require_relative 'rinda'
require 'forwardable'

module Rinda

  ##
  # A TupleEntry is a Tuple (i.e. a possible entry in some Tuplespace)
  # together with expiry and cancellation data.

  class TupleEntry

    include DRbUndumped

    attr_accessor :expires

    ##
    # Creates a TupleEntry based on +ary+ with an optional renewer or expiry
    # time +sec+.
    #
    # A renewer must implement the +renew+ method which returns a Numeric,
    # nil, or true to indicate when the tuple has expired.

    def initialize(ary, sec=nil)
      @cancel = false
      @expires = nil
      @tuple = make_tuple(ary)
      @renewer = nil
      renew(sec)
    end

    ##
    # Marks this TupleEntry as canceled.

    def cancel
      @cancel = true
    end

    ##
    # A TupleEntry is dead when it is canceled or expired.

    def alive?
      !canceled? && !expired?
    end

    ##
    # Return the object which makes up the tuple itself: the Array
    # or Hash.

    def value; @tuple.value; end

    ##
    # Returns the canceled status.

    def canceled?; @cancel; end

    ##
    # Has this tuple expired? (true/false).
    #
    # A tuple has expired when its expiry timer based on the +sec+ argument to
    # #initialize runs out.

    def expired?
      return true unless @expires
      return false if @expires > Time.now
      return true if @renewer.nil?
      renew(@renewer)
      return true unless @expires
      return @expires < Time.now
    end

    ##
    # Reset the expiry time according to +sec_or_renewer+.
    #
    # +nil+::    it is set to expire in the far future.
    # +true+::   it has expired.
    # Numeric::  it will expire in that many seconds.
    #
    # Otherwise the argument refers to some kind of renewer object
    # which will reset its expiry time.

    def renew(sec_or_renewer)
      sec, @renewer = get_renewer(sec_or_renewer)
      @expires = make_expires(sec)
    end

    ##
    # Returns an expiry Time based on +sec+ which can be one of:
    # Numeric:: +sec+ seconds into the future
    # +true+::  the expiry time is the start of 1970 (i.e. expired)
    # +nil+::   it is  Tue Jan 19 03:14:07 GMT Standard Time 2038 (i.e. when
    #           UNIX clocks will die)

    def make_expires(sec=nil)
      case sec
      when Numeric
        Time.now + sec
      when true
        Time.at(1)
      when nil
        Time.at(2**31-1)
      end
    end

    ##
    # Retrieves +key+ from the tuple.

    def [](key)
      @tuple[key]
    end

    ##
    # Fetches +key+ from the tuple.

    def fetch(key)
      @tuple.fetch(key)
    end

    ##
    # The size of the tuple.

    def size
      @tuple.size
    end

    ##
    # Creates a Rinda::Tuple for +ary+.

    def make_tuple(ary)
      Rinda::Tuple.new(ary)
    end

    private

    ##
    # Returns a valid argument to make_expires and the renewer or nil.
    #
    # Given +true+, +nil+, or Numeric, returns that value and +nil+ (no actual
    # renewer).  Otherwise it returns an expiry value from calling +it.renew+
    # and the renewer.

    def get_renewer(it)
      case it
      when Numeric, true, nil
        return it, nil
      else
        begin
          return it.renew, it
        rescue Exception
          return it, nil
        end
      end
    end

  end

  ##
  # A TemplateEntry is a Template together with expiry and cancellation data.

  class TemplateEntry < TupleEntry
    ##
    # Matches this TemplateEntry against +tuple+.  See Template#match for
    # details on how a Template matches a Tuple.

    def match(tuple)
      @tuple.match(tuple)
    end

    alias === match

    def make_tuple(ary) # :nodoc:
      Rinda::Template.new(ary)
    end

  end

  ##
  # <i>Documentation?</i>

  class WaitTemplateEntry < TemplateEntry

    attr_reader :found

    def initialize(place, ary, expires=nil)
      super(ary, expires)
      @place = place
      @cond = place.new_cond
      @found = nil
    end

    def cancel
      super
      signal
    end

    def wait
      @cond.wait
    end

    def read(tuple)
      @found = tuple
      signal
    end

    def signal
      @place.synchronize do
        @cond.signal
      end
    end

  end

  ##
  # A NotifyTemplateEntry is returned by TupleSpace#notify and is notified of
  # TupleSpace changes.  You may receive either your subscribed event or the
  # 'close' event when iterating over notifications.
  #
  # See TupleSpace#notify_event for valid notification types.
  #
  # == Example
  #
  #   ts = Rinda::TupleSpace.new
  #   observer = ts.notify 'write', [nil]
  #
  #   Thread.start do
  #     observer.each { |t| p t }
  #   end
  #
  #   3.times { |i| ts.write [i] }
  #
  # Outputs:
  #
  #   ['write', [0]]
  #   ['write', [1]]
  #   ['write', [2]]

  class NotifyTemplateEntry < TemplateEntry

    ##
    # Creates a new NotifyTemplateEntry that watches +place+ for +event+s that
    # match +tuple+.

    def initialize(place, event, tuple, expires=nil)
      ary = [event, Rinda::Template.new(tuple)]
      super(ary, expires)
      @queue = Thread::Queue.new
      @done = false
    end

    ##
    # Called by TupleSpace to notify this NotifyTemplateEntry of a new event.

    def notify(ev)
      @queue.push(ev)
    end

    ##
    # Retrieves a notification.  Raises RequestExpiredError when this
    # NotifyTemplateEntry expires.

    def pop
      raise RequestExpiredError if @done
      it = @queue.pop
      @done = true if it[0] == 'close'
      return it
    end

    ##
    # Yields event/tuple pairs until this NotifyTemplateEntry expires.

    def each # :yields: event, tuple
      while !@done
        it = pop
        yield(it)
      end
    rescue
    ensure
      cancel
    end

  end

  ##
  # TupleBag is an unordered collection of tuples. It is the basis
  # of Tuplespace.

  class TupleBag
    class TupleBin
      extend Forwardable
      def_delegators '@bin', :find_all, :delete_if, :each, :empty?

      def initialize
        @bin = []
      end

      def add(tuple)
        @bin.push(tuple)
      end

      def delete(tuple)
        idx = @bin.rindex(tuple)
        @bin.delete_at(idx) if idx
      end

      def find
        @bin.reverse_each do |x|
          return x if yield(x)
        end
        nil
      end
    end

    def initialize # :nodoc:
      @hash = {}
      @enum = enum_for(:each_entry)
    end

    ##
    # +true+ if the TupleBag to see if it has any expired entries.

    def has_expires?
      @enum.find do |tuple|
        tuple.expires
      end
    end

    ##
    # Add +tuple+ to the TupleBag.

    def push(tuple)
      key = bin_key(tuple)
      @hash[key] ||= TupleBin.new
      @hash[key].add(tuple)
    end

    ##
    # Removes +tuple+ from the TupleBag.

    def delete(tuple)
      key = bin_key(tuple)
      bin = @hash[key]
      return nil unless bin
      bin.delete(tuple)
      @hash.delete(key) if bin.empty?
      tuple
    end

    ##
    # Finds all live tuples that match +template+.
    def find_all(template)
      bin_for_find(template).find_all do |tuple|
        tuple.alive? && template.match(tuple)
      end
    end

    ##
    # Finds a live tuple that matches +template+.

    def find(template)
      bin_for_find(template).find do |tuple|
        tuple.alive? && template.match(tuple)
      end
    end

    ##
    # Finds all tuples in the TupleBag which when treated as templates, match
    # +tuple+ and are alive.

    def find_all_template(tuple)
      @enum.find_all do |template|
        template.alive? && template.match(tuple)
      end
    end

    ##
    # Delete tuples which dead tuples from the TupleBag, returning the deleted
    # tuples.

    def delete_unless_alive
      deleted = []
      @hash.each do |key, bin|
        bin.delete_if do |tuple|
          if tuple.alive?
            false
          else
            deleted.push(tuple)
            true
          end
        end
      end
      deleted
    end

    private
    def each_entry(&blk)
      @hash.each do |k, v|
        v.each(&blk)
      end
    end

    def bin_key(tuple)
      head = tuple[0]
      if head.class == Symbol
        return head
      else
        false
      end
    end

    def bin_for_find(template)
      key = bin_key(template)
      key ? @hash.fetch(key, []) : @enum
    end
  end

  ##
  # The Tuplespace manages access to the tuples it contains,
  # ensuring mutual exclusion requirements are met.
  #
  # The +sec+ option for the write, take, move, read and notify methods may
  # either be a number of seconds or a Renewer object.

  class TupleSpace

    include DRbUndumped
    include MonitorMixin

    ##
    # Creates a new TupleSpace.  +period+ is used to control how often to look
    # for dead tuples after modifications to the TupleSpace.
    #
    # If no dead tuples are found +period+ seconds after the last
    # modification, the TupleSpace will stop looking for dead tuples.

    def initialize(period=60)
      super()
      @bag = TupleBag.new
      @read_waiter = TupleBag.new
      @take_waiter = TupleBag.new
      @notify_waiter = TupleBag.new
      @period = period
      @keeper = nil
    end

    ##
    # Adds +tuple+

    def write(tuple, sec=nil)
      entry = create_entry(tuple, sec)
      synchronize do
        if entry.expired?
          @read_waiter.find_all_template(entry).each do |template|
            template.read(tuple)
          end
          notify_event('write', entry.value)
          notify_event('delete', entry.value)
        else
          @bag.push(entry)
          start_keeper if entry.expires
          @read_waiter.find_all_template(entry).each do |template|
            template.read(tuple)
          end
          @take_waiter.find_all_template(entry).each do |template|
            template.signal
          end
          notify_event('write', entry.value)
        end
      end
      entry
    end

    ##
    # Removes +tuple+

    def take(tuple, sec=nil, &block)
      move(nil, tuple, sec, &block)
    end

    ##
    # Moves +tuple+ to +port+.

    def move(port, tuple, sec=nil)
      template = WaitTemplateEntry.new(self, tuple, sec)
      yield(template) if block_given?
      synchronize do
        entry = @bag.find(template)
        if entry
          port.push(entry.value) if port
          @bag.delete(entry)
          notify_event('take', entry.value)
          return port ? nil : entry.value
        end
        raise RequestExpiredError if template.expired?

        begin
          @take_waiter.push(template)
          start_keeper if template.expires
          while true
            raise RequestCanceledError if template.canceled?
            raise RequestExpiredError if template.expired?
            entry = @bag.find(template)
            if entry
              port.push(entry.value) if port
              @bag.delete(entry)
              notify_event('take', entry.value)
              return port ? nil : entry.value
            end
            template.wait
          end
        ensure
          @take_waiter.delete(template)
        end
      end
    end

    ##
    # Reads +tuple+, but does not remove it.

    def read(tuple, sec=nil)
      template = WaitTemplateEntry.new(self, tuple, sec)
      yield(template) if block_given?
      synchronize do
        entry = @bag.find(template)
        return entry.value if entry
        raise RequestExpiredError if template.expired?

        begin
          @read_waiter.push(template)
          start_keeper if template.expires
          template.wait
          raise RequestCanceledError if template.canceled?
          raise RequestExpiredError if template.expired?
          return template.found
        ensure
          @read_waiter.delete(template)
        end
      end
    end

    ##
    # Returns all tuples matching +tuple+.  Does not remove the found tuples.

    def read_all(tuple)
      template = WaitTemplateEntry.new(self, tuple, nil)
      synchronize do
        entry = @bag.find_all(template)
        entry.collect do |e|
          e.value
        end
      end
    end

    ##
    # Registers for notifications of +event+.  Returns a NotifyTemplateEntry.
    # See NotifyTemplateEntry for examples of how to listen for notifications.
    #
    # +event+ can be:
    # 'write'::  A tuple was added
    # 'take'::   A tuple was taken or moved
    # 'delete':: A tuple was lost after being overwritten or expiring
    #
    # The TupleSpace will also notify you of the 'close' event when the
    # NotifyTemplateEntry has expired.

    def notify(event, tuple, sec=nil)
      template = NotifyTemplateEntry.new(self, event, tuple, sec)
      synchronize do
        @notify_waiter.push(template)
      end
      template
    end

    private

    def create_entry(tuple, sec)
      TupleEntry.new(tuple, sec)
    end

    ##
    # Removes dead tuples.

    def keep_clean
      synchronize do
        @read_waiter.delete_unless_alive.each do |e|
          e.signal
        end
        @take_waiter.delete_unless_alive.each do |e|
          e.signal
        end
        @notify_waiter.delete_unless_alive.each do |e|
          e.notify(['close'])
        end
        @bag.delete_unless_alive.each do |e|
          notify_event('delete', e.value)
        end
      end
    end

    ##
    # Notifies all registered listeners for +event+ of a status change of
    # +tuple+.

    def notify_event(event, tuple)
      ev = [event, tuple]
      @notify_waiter.find_all_template(ev).each do |template|
        template.notify(ev)
      end
    end

    ##
    # Creates a thread that scans the tuplespace for expired tuples.

    def start_keeper
      return if @keeper && @keeper.alive?
      @keeper = Thread.new do
        while true
          sleep(@period)
          synchronize do
            break unless need_keeper?
            keep_clean
          end
        end
      end
    end

    ##
    # Checks the tuplespace to see if it needs cleaning.

    def need_keeper?
      return true if @bag.has_expires?
      return true if @read_waiter.has_expires?
      return true if @take_waiter.has_expires?
      return true if @notify_waiter.has_expires?
    end

  end

end

# frozen_string_literal: false
require 'drb/drb'

##
# A module to implement the Linda distributed computing paradigm in Ruby.
#
# Rinda is part of DRb (dRuby).
#
# == Example(s)
#
# See the sample/drb/ directory in the Ruby distribution, from 1.8.2 onwards.
#
#--
# TODO
# == Introduction to Linda/rinda?
#
# == Why is this library separate from DRb?

module Rinda

  ##
  # Rinda error base class

  class RindaError < RuntimeError; end

  ##
  # Raised when a hash-based tuple has an invalid key.

  class InvalidHashTupleKey < RindaError; end

  ##
  # Raised when trying to use a canceled tuple.

  class RequestCanceledError < ThreadError; end

  ##
  # Raised when trying to use an expired tuple.

  class RequestExpiredError < ThreadError; end

  ##
  # A tuple is the elementary object in Rinda programming.
  # Tuples may be matched against templates if the tuple and
  # the template are the same size.

  class Tuple

    ##
    # Creates a new Tuple from +ary_or_hash+ which must be an Array or Hash.

    def initialize(ary_or_hash)
      if hash?(ary_or_hash)
        init_with_hash(ary_or_hash)
      else
        init_with_ary(ary_or_hash)
      end
    end

    ##
    # The number of elements in the tuple.

    def size
      @tuple.size
    end

    ##
    # Accessor method for elements of the tuple.

    def [](k)
      @tuple[k]
    end

    ##
    # Fetches item +k+ from the tuple.

    def fetch(k)
      @tuple.fetch(k)
    end

    ##
    # Iterate through the tuple, yielding the index or key, and the
    # value, thus ensuring arrays are iterated similarly to hashes.

    def each # FIXME
      if Hash === @tuple
        @tuple.each { |k, v| yield(k, v) }
      else
        @tuple.each_with_index { |v, k| yield(k, v) }
      end
    end

    ##
    # Return the tuple itself
    def value
      @tuple
    end

    private

    def hash?(ary_or_hash)
      ary_or_hash.respond_to?(:keys)
    end

    ##
    # Munges +ary+ into a valid Tuple.

    def init_with_ary(ary)
      @tuple = Array.new(ary.size)
      @tuple.size.times do |i|
        @tuple[i] = ary[i]
      end
    end

    ##
    # Ensures +hash+ is a valid Tuple.

    def init_with_hash(hash)
      @tuple = Hash.new
      hash.each do |k, v|
        raise InvalidHashTupleKey unless String === k
        @tuple[k] = v
      end
    end

  end

  ##
  # Templates are used to match tuples in Rinda.

  class Template < Tuple

    ##
    # Matches this template against +tuple+.  The +tuple+ must be the same
    # size as the template.  An element with a +nil+ value in a template acts
    # as a wildcard, matching any value in the corresponding position in the
    # tuple.  Elements of the template match the +tuple+ if the are #== or
    # #===.
    #
    #   Template.new([:foo, 5]).match   Tuple.new([:foo, 5]) # => true
    #   Template.new([:foo, nil]).match Tuple.new([:foo, 5]) # => true
    #   Template.new([String]).match    Tuple.new(['hello']) # => true
    #
    #   Template.new([:foo]).match      Tuple.new([:foo, 5]) # => false
    #   Template.new([:foo, 6]).match   Tuple.new([:foo, 5]) # => false
    #   Template.new([:foo, nil]).match Tuple.new([:foo])    # => false
    #   Template.new([:foo, 6]).match   Tuple.new([:foo])    # => false

    def match(tuple)
      return false unless tuple.respond_to?(:size)
      return false unless tuple.respond_to?(:fetch)
      return false unless self.size == tuple.size
      each do |k, v|
        begin
          it = tuple.fetch(k)
        rescue
          return false
        end
        next if v.nil?
        next if v == it
        next if v === it
        return false
      end
      return true
    end

    ##
    # Alias for #match.

    def ===(tuple)
      match(tuple)
    end

  end

  ##
  # <i>Documentation?</i>

  class DRbObjectTemplate

    ##
    # Creates a new DRbObjectTemplate that will match against +uri+ and +ref+.

    def initialize(uri=nil, ref=nil)
      @drb_uri = uri
      @drb_ref = ref
    end

    ##
    # This DRbObjectTemplate matches +ro+ if the remote object's drburi and
    # drbref are the same.  +nil+ is used as a wildcard.

    def ===(ro)
      return true if super(ro)
      unless @drb_uri.nil?
        return false unless (@drb_uri === ro.__drburi rescue false)
      end
      unless @drb_ref.nil?
        return false unless (@drb_ref === ro.__drbref rescue false)
      end
      true
    end

  end

  ##
  # TupleSpaceProxy allows a remote Tuplespace to appear as local.

  class TupleSpaceProxy
    ##
    # A Port ensures that a moved tuple arrives properly at its destination
    # and does not get lost.
    #
    # See https://bugs.ruby-lang.org/issues/8125

    class Port # :nodoc:
      attr_reader :value

      def self.deliver
        port = new

        begin
          yield(port)
        ensure
          port.close
        end

        port.value
      end

      def initialize
        @open = true
        @value = nil
      end

      ##
      # Don't let the DRb thread push to it when remote sends tuple

      def close
        @open = false
      end

      ##
      # Stores +value+ and ensure it does not get marshaled multiple times.

      def push value
        raise 'port closed' unless @open

        @value = value

        nil # avoid Marshal
      end
    end

    ##
    # Creates a new TupleSpaceProxy to wrap +ts+.

    def initialize(ts)
      @ts = ts
    end

    ##
    # Adds +tuple+ to the proxied TupleSpace.  See TupleSpace#write.

    def write(tuple, sec=nil)
      @ts.write(tuple, sec)
    end

    ##
    # Takes +tuple+ from the proxied TupleSpace.  See TupleSpace#take.

    def take(tuple, sec=nil, &block)
      Port.deliver do |port|
        @ts.move(DRbObject.new(port), tuple, sec, &block)
      end
    end

    ##
    # Reads +tuple+ from the proxied TupleSpace.  See TupleSpace#read.

    def read(tuple, sec=nil, &block)
      @ts.read(tuple, sec, &block)
    end

    ##
    # Reads all tuples matching +tuple+ from the proxied TupleSpace.  See
    # TupleSpace#read_all.

    def read_all(tuple)
      @ts.read_all(tuple)
    end

    ##
    # Registers for notifications of event +ev+ on the proxied TupleSpace.
    # See TupleSpace#notify

    def notify(ev, tuple, sec=nil)
      @ts.notify(ev, tuple, sec)
    end

  end

  ##
  # An SimpleRenewer allows a TupleSpace to check if a TupleEntry is still
  # alive.

  class SimpleRenewer

    include DRbUndumped

    ##
    # Creates a new SimpleRenewer that keeps an object alive for another +sec+
    # seconds.

    def initialize(sec=180)
      @sec = sec
    end

    ##
    # Called by the TupleSpace to check if the object is still alive.

    def renew
      @sec
    end
  end

end

# frozen_string_literal: true
#
# $Id$
#
# Copyright (c) 2003-2005 Minero Aoki
#
# This program is free software.
# You can distribute and/or modify this program under the Ruby License.
# For details of Ruby License, see ruby/COPYING.
#

require 'ripper.so'

class Ripper

  # Parses the given Ruby program read from +src+.
  # +src+ must be a String or an IO or a object with a #gets method.
  def Ripper.parse(src, filename = '(ripper)', lineno = 1)
    new(src, filename, lineno).parse
  end

  # This array contains name of parser events.
  PARSER_EVENTS = PARSER_EVENT_TABLE.keys

  # This array contains name of scanner events.
  SCANNER_EVENTS = SCANNER_EVENT_TABLE.keys

  # This array contains name of all ripper events.
  EVENTS = PARSER_EVENTS + SCANNER_EVENTS

  private

  # :stopdoc:
  def _dispatch_0() nil end
  def _dispatch_1(a) a end
  def _dispatch_2(a, b) a end
  def _dispatch_3(a, b, c) a end
  def _dispatch_4(a, b, c, d) a end
  def _dispatch_5(a, b, c, d, e) a end
  def _dispatch_6(a, b, c, d, e, f) a end
  def _dispatch_7(a, b, c, d, e, f, g) a end
  # :startdoc:

  #
  # Parser Events
  #

  PARSER_EVENT_TABLE.each do |id, arity|
    alias_method "on_#{id}", "_dispatch_#{arity}"
  end

  # This method is called when weak warning is produced by the parser.
  # +fmt+ and +args+ is printf style.
  def warn(fmt, *args)
  end

  # This method is called when strong warning is produced by the parser.
  # +fmt+ and +args+ is printf style.
  def warning(fmt, *args)
  end

  # This method is called when the parser found syntax error.
  def compile_error(msg)
  end

  #
  # Scanner Events
  #

  SCANNER_EVENTS.each do |id|
    alias_method "on_#{id}", :_dispatch_1
  end

end
# frozen_string_literal: true
#
# $Id$
#
# Copyright (c) 2004,2005 Minero Aoki
#
# This program is free software.
# You can distribute and/or modify this program under the Ruby License.
# For details of Ruby License, see ruby/COPYING.
#

require 'ripper/core'

class Ripper

  # Tokenizes the Ruby program and returns an array of strings.
  # The +filename+ and +lineno+ arguments are mostly ignored, since the
  # return value is just the tokenized input.
  # By default, this method does not handle syntax errors in +src+,
  # use the +raise_errors+ keyword to raise a SyntaxError for an error in +src+.
  #
  #   p Ripper.tokenize("def m(a) nil end")
  #      # => ["def", " ", "m", "(", "a", ")", " ", "nil", " ", "end"]
  #
  def Ripper.tokenize(src, filename = '-', lineno = 1, **kw)
    Lexer.new(src, filename, lineno).tokenize(**kw)
  end

  # Tokenizes the Ruby program and returns an array of an array,
  # which is formatted like
  # <code>[[lineno, column], type, token, state]</code>.
  # The +filename+ argument is mostly ignored.
  # By default, this method does not handle syntax errors in +src+,
  # use the +raise_errors+ keyword to raise a SyntaxError for an error in +src+.
  #
  #   require 'ripper'
  #   require 'pp'
  #
  #   pp Ripper.lex("def m(a) nil end")
  #   #=> [[[1,  0], :on_kw,     "def", FNAME    ],
  #        [[1,  3], :on_sp,     " ",   FNAME    ],
  #        [[1,  4], :on_ident,  "m",   ENDFN    ],
  #        [[1,  5], :on_lparen, "(",   BEG|LABEL],
  #        [[1,  6], :on_ident,  "a",   ARG      ],
  #        [[1,  7], :on_rparen, ")",   ENDFN    ],
  #        [[1,  8], :on_sp,     " ",   BEG      ],
  #        [[1,  9], :on_kw,     "nil", END      ],
  #        [[1, 12], :on_sp,     " ",   END      ],
  #        [[1, 13], :on_kw,     "end", END      ]]
  #
  def Ripper.lex(src, filename = '-', lineno = 1, **kw)
    Lexer.new(src, filename, lineno).lex(**kw)
  end

  class Lexer < ::Ripper   #:nodoc: internal use only
    State = Struct.new(:to_int, :to_s) do
      alias to_i to_int
      def initialize(i) super(i, Ripper.lex_state_name(i)).freeze end
      # def inspect; "#<#{self.class}: #{self}>" end
      alias inspect to_s
      def pretty_print(q) q.text(to_s) end
      def ==(i) super or to_int == i end
      def &(i) self.class.new(to_int & i) end
      def |(i) self.class.new(to_int | i) end
      def allbits?(i) to_int.allbits?(i) end
      def anybits?(i) to_int.anybits?(i) end
      def nobits?(i) to_int.nobits?(i) end
    end

    Elem = Struct.new(:pos, :event, :tok, :state, :message) do
      def initialize(pos, event, tok, state, message = nil)
        super(pos, event, tok, State.new(state), message)
      end

      def inspect
        "#<#{self.class}: #{event}@#{pos[0]}:#{pos[1]}:#{state}: #{tok.inspect}#{": " if message}#{message}>"
      end

      def pretty_print(q)
        q.group(2, "#<#{self.class}:", ">") {
          q.breakable
          q.text("#{event}@#{pos[0]}:#{pos[1]}")
          q.breakable
          q.text(state)
          q.breakable
          q.text("token: ")
          tok.pretty_print(q)
          if message
            q.breakable
            q.text("message: ")
            q.text(message)
          end
        }
      end

      def to_a
        a = super
        a.pop unless a.last
        a
      end
    end

    attr_reader :errors

    def tokenize(**kw)
      parse(**kw).sort_by(&:pos).map(&:tok)
    end

    def lex(**kw)
      parse(**kw).sort_by(&:pos).map(&:to_a)
    end

    # parse the code and returns elements including errors.
    def scan(**kw)
      result = (parse(**kw) + errors + @stack.flatten).uniq.sort_by {|e| [*e.pos, (e.message ? -1 : 0)]}
      result.each_with_index do |e, i|
        if e.event == :on_parse_error and e.tok.empty? and (pre = result[i-1]) and
          pre.pos[0] == e.pos[0] and (pre.pos[1] + pre.tok.size) == e.pos[1]
          e.tok = pre.tok
          e.pos[1] = pre.pos[1]
          result[i-1] = e
          result[i] = pre
        end
      end
      result
    end

    def parse(raise_errors: false)
      @errors = []
      @buf = []
      @stack = []
      super()
      @buf = @stack.pop unless @stack.empty?
      if raise_errors and !@errors.empty?
        raise SyntaxError, @errors.map(&:message).join(' ;')
      end
      @buf.flatten!
      unless (result = @buf).empty?
        result.concat(@buf) until (@buf = []; super(); @buf.flatten!; @buf.empty?)
      end
      result
    end

    private

    unless SCANNER_EVENT_TABLE.key?(:ignored_sp)
      SCANNER_EVENT_TABLE[:ignored_sp] = 1
      SCANNER_EVENTS << :ignored_sp
      EVENTS << :ignored_sp
    end

    def on_heredoc_dedent(v, w)
      ignored_sp = []
      heredoc = @buf.last
      heredoc.each_with_index do |e, i|
        if Elem === e and e.event == :on_tstring_content and e.pos[1].zero?
          tok = e.tok.dup if w > 0 and /\A\s/ =~ e.tok
          if (n = dedent_string(e.tok, w)) > 0
            if e.tok.empty?
              e.tok = tok[0, n]
              e.event = :on_ignored_sp
              next
            end
            ignored_sp << [i, Elem.new(e.pos.dup, :on_ignored_sp, tok[0, n], e.state)]
            e.pos[1] += n
          end
        end
      end
      ignored_sp.reverse_each do |i, e|
        heredoc[i, 0] = [e]
      end
      v
    end

    def on_heredoc_beg(tok)
      @stack.push @buf
      buf = []
      @buf.push buf
      @buf = buf
      @buf.push Elem.new([lineno(), column()], __callee__, tok, state())
    end

    def on_heredoc_end(tok)
      @buf.push Elem.new([lineno(), column()], __callee__, tok, state())
      @buf = @stack.pop
    end

    def _push_token(tok)
      e = Elem.new([lineno(), column()], __callee__, tok, state())
      @buf.push(e)
      e
    end

    def on_error1(mesg)
      @errors.push Elem.new([lineno(), column()], __callee__, token(), state(), mesg)
    end

    def on_error2(mesg, elem)
      @errors.push Elem.new(elem.pos, __callee__, elem.tok, elem.state, mesg)
    end
    PARSER_EVENTS.grep(/_error\z/) do |e|
      arity = PARSER_EVENT_TABLE.fetch(e)
      alias_method "on_#{e}", "on_error#{arity}"
    end
    alias compile_error on_error1

    (SCANNER_EVENTS.map {|event|:"on_#{event}"} - private_instance_methods(false)).each do |event|
      alias_method event, :_push_token
    end
  end

  # [EXPERIMENTAL]
  # Parses +src+ and return a string which was matched to +pattern+.
  # +pattern+ should be described as Regexp.
  #
  #   require 'ripper'
  #
  #   p Ripper.slice('def m(a) nil end', 'ident')                   #=> "m"
  #   p Ripper.slice('def m(a) nil end', '[ident lparen rparen]+')  #=> "m(a)"
  #   p Ripper.slice("<<EOS\nstring\nEOS",
  #                  'heredoc_beg nl $(tstring_content*) heredoc_end', 1)
  #       #=> "string\n"
  #
  def Ripper.slice(src, pattern, n = 0)
    if m = token_match(src, pattern)
    then m.string(n)
    else nil
    end
  end

  def Ripper.token_match(src, pattern)   #:nodoc:
    TokenPattern.compile(pattern).match(src)
  end

  class TokenPattern   #:nodoc:

    class Error < ::StandardError # :nodoc:
    end
    class CompileError < Error # :nodoc:
    end
    class MatchError < Error # :nodoc:
    end

    class << self
      alias compile new
    end

    def initialize(pattern)
      @source = pattern
      @re = compile(pattern)
    end

    def match(str)
      match_list(::Ripper.lex(str))
    end

    def match_list(tokens)
      if m = @re.match(map_tokens(tokens))
      then MatchData.new(tokens, m)
      else nil
      end
    end

    private

    def compile(pattern)
      if m = /[^\w\s$()\[\]{}?*+\.]/.match(pattern)
        raise CompileError, "invalid char in pattern: #{m[0].inspect}"
      end
      buf = +''
      pattern.scan(/(?:\w+|\$\(|[()\[\]\{\}?*+\.]+)/) do |tok|
        case tok
        when /\w/
          buf.concat map_token(tok)
        when '$('
          buf.concat '('
        when '('
          buf.concat '(?:'
        when /[?*\[\])\.]/
          buf.concat tok
        else
          raise 'must not happen'
        end
      end
      Regexp.compile(buf)
    rescue RegexpError => err
      raise CompileError, err.message
    end

    def map_tokens(tokens)
      tokens.map {|pos,type,str| map_token(type.to_s.delete_prefix('on_')) }.join
    end

    MAP = {}
    seed = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
    SCANNER_EVENT_TABLE.each do |ev, |
      raise CompileError, "[RIPPER FATAL] too many system token" if seed.empty?
      MAP[ev.to_s.delete_prefix('on_')] = seed.shift
    end

    def map_token(tok)
      MAP[tok]  or raise CompileError, "unknown token: #{tok}"
    end

    class MatchData # :nodoc:
      def initialize(tokens, match)
        @tokens = tokens
        @match = match
      end

      def string(n = 0)
        return nil unless @match
        match(n).join
      end

      private

      def match(n = 0)
        return [] unless @match
        @tokens[@match.begin(n)...@match.end(n)].map {|pos,type,str| str }
      end
    end

  end

end
# frozen_string_literal: true
#
# $Id$
#
# Copyright (c) 2004,2005 Minero Aoki
#
# This program is free software.
# You can distribute and/or modify this program under the Ruby License.
# For details of Ruby License, see ruby/COPYING.
#

require 'ripper/lexer'

class Ripper

  # This class handles only scanner events,
  # which are dispatched in the 'right' order (same with input).
  class Filter

    # Creates a new Ripper::Filter instance, passes parameters +src+,
    # +filename+, and +lineno+ to Ripper::Lexer.new
    #
    # The lexer is for internal use only.
    def initialize(src, filename = '-', lineno = 1)
      @__lexer = Lexer.new(src, filename, lineno)
      @__line = nil
      @__col = nil
      @__state = nil
    end

    # The file name of the input.
    def filename
      @__lexer.filename
    end

    # The line number of the current token.
    # This value starts from 1.
    # This method is valid only in event handlers.
    def lineno
      @__line
    end

    # The column number of the current token.
    # This value starts from 0.
    # This method is valid only in event handlers.
    def column
      @__col
    end

    # The scanner's state of the current token.
    # This value is the bitwise OR of zero or more of the +Ripper::EXPR_*+ constants.
    def state
      @__state
    end

    # Starts the parser.
    # +init+ is a data accumulator and is passed to the next event handler (as
    # of Enumerable#inject).
    def parse(init = nil)
      data = init
      @__lexer.lex.each do |pos, event, tok, state|
        @__line, @__col = *pos
        @__state = state
        data = if respond_to?(event, true)
               then __send__(event, tok, data)
               else on_default(event, tok, data)
               end
      end
      data
    end

    private

    # This method is called when some event handler is undefined.
    # +event+ is :on_XXX, +token+ is the scanned token, and +data+ is a data
    # accumulator.
    #
    # The return value of this method is passed to the next event handler (as
    # of Enumerable#inject).
    def on_default(event, token, data)
      data
    end

  end

end
# frozen_string_literal: true
#
# $Id$
#
# Copyright (c) 2004,2005 Minero Aoki
#
# This program is free software.
# You can distribute and/or modify this program under the Ruby License.
# For details of Ruby License, see ruby/COPYING.
#

require 'ripper/core'

class Ripper

  # [EXPERIMENTAL]
  # Parses +src+ and create S-exp tree.
  # Returns more readable tree rather than Ripper.sexp_raw.
  # This method is mainly for developer use.
  # The +filename+ argument is mostly ignored.
  # By default, this method does not handle syntax errors in +src+,
  # returning +nil+ in such cases. Use the +raise_errors+ keyword
  # to raise a SyntaxError for an error in +src+.
  #
  #   require 'ripper'
  #   require 'pp'
  #
  #   pp Ripper.sexp("def m(a) nil end")
  #     #=> [:program,
  #          [[:def,
  #           [:@ident, "m", [1, 4]],
  #           [:paren, [:params, [[:@ident, "a", [1, 6]]], nil, nil, nil, nil, nil, nil]],
  #           [:bodystmt, [[:var_ref, [:@kw, "nil", [1, 9]]]], nil, nil, nil]]]]
  #
  def Ripper.sexp(src, filename = '-', lineno = 1, raise_errors: false)
    builder = SexpBuilderPP.new(src, filename, lineno)
    sexp = builder.parse
    if builder.error?
      if raise_errors
        raise SyntaxError, builder.error
      end
    else
      sexp
    end
  end

  # [EXPERIMENTAL]
  # Parses +src+ and create S-exp tree.
  # This method is mainly for developer use.
  # The +filename+ argument is mostly ignored.
  # By default, this method does not handle syntax errors in +src+,
  # returning +nil+ in such cases. Use the +raise_errors+ keyword
  # to raise a SyntaxError for an error in +src+.
  #
  #   require 'ripper'
  #   require 'pp'
  #
  #   pp Ripper.sexp_raw("def m(a) nil end")
  #     #=> [:program,
  #          [:stmts_add,
  #           [:stmts_new],
  #           [:def,
  #            [:@ident, "m", [1, 4]],
  #            [:paren, [:params, [[:@ident, "a", [1, 6]]], nil, nil, nil]],
  #            [:bodystmt,
  #             [:stmts_add, [:stmts_new], [:var_ref, [:@kw, "nil", [1, 9]]]],
  #             nil,
  #             nil,
  #             nil]]]]
  #
  def Ripper.sexp_raw(src, filename = '-', lineno = 1, raise_errors: false)
    builder = SexpBuilder.new(src, filename, lineno)
    sexp = builder.parse
    if builder.error?
      if raise_errors
        raise SyntaxError, builder.error
      end
    else
      sexp
    end
  end

  class SexpBuilder < ::Ripper   #:nodoc:
    attr_reader :error

    private

    def dedent_element(e, width)
      if (n = dedent_string(e[1], width)) > 0
        e[2][1] += n
      end
      e
    end

    def on_heredoc_dedent(val, width)
      sub = proc do |cont|
        cont.map! do |e|
          if Array === e
            case e[0]
            when :@tstring_content
              e = dedent_element(e, width)
            when /_add\z/
              e[1] = sub[e[1]]
            end
          elsif String === e
            dedent_string(e, width)
          end
          e
        end
      end
      sub[val]
      val
    end

    events = private_instance_methods(false).grep(/\Aon_/) {$'.to_sym}
    (PARSER_EVENTS - events).each do |event|
      module_eval(<<-End, __FILE__, __LINE__ + 1)
        def on_#{event}(*args)
          args.unshift :#{event}
          args
        end
      End
    end

    SCANNER_EVENTS.each do |event|
      module_eval(<<-End, __FILE__, __LINE__ + 1)
        def on_#{event}(tok)
          [:@#{event}, tok, [lineno(), column()]]
        end
      End
    end

    def on_error(mesg)
      @error = mesg
    end
    remove_method :on_parse_error
    alias on_parse_error on_error
    alias compile_error on_error
  end

  class SexpBuilderPP < SexpBuilder #:nodoc:
    private

    def on_heredoc_dedent(val, width)
      val.map! do |e|
        next e if Symbol === e and /_content\z/ =~ e
        if Array === e and e[0] == :@tstring_content
          e = dedent_element(e, width)
        elsif String === e
          dedent_string(e, width)
        end
        e
      end
      val
    end

    def _dispatch_event_new
      []
    end

    def _dispatch_event_push(list, item)
      list.push item
      list
    end

    def on_mlhs_paren(list)
      [:mlhs, *list]
    end

    def on_mlhs_add_star(list, star)
      list.push([:rest_param, star])
    end

    def on_mlhs_add_post(list, post)
      list.concat(post)
    end

    PARSER_EVENT_TABLE.each do |event, arity|
      if /_new\z/ =~ event and arity == 0
        alias_method "on_#{event}", :_dispatch_event_new
      elsif /_add\z/ =~ event
        alias_method "on_#{event}", :_dispatch_event_push
      end
    end
  end

end
# frozen_string_literal: true
# logger.rb - simple logging utility
# Copyright (C) 2000-2003, 2005, 2008, 2011  NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
#
# Documentation:: NAKAMURA, Hiroshi and Gavin Sinclair
# License::
#   You can redistribute it and/or modify it under the same terms of Ruby's
#   license; either the dual license version in 2003, or any later version.
# Revision:: $Id$
#
# A simple system for logging messages.  See Logger for more documentation.

require 'monitor'

require_relative 'logger/version'
require_relative 'logger/formatter'
require_relative 'logger/log_device'
require_relative 'logger/severity'
require_relative 'logger/errors'

# == Description
#
# The Logger class provides a simple but sophisticated logging utility that
# you can use to output messages.
#
# The messages have associated levels, such as +INFO+ or +ERROR+ that indicate
# their importance.  You can then give the Logger a level, and only messages
# at that level or higher will be printed.
#
# The levels are:
#
# +UNKNOWN+:: An unknown message that should always be logged.
# +FATAL+:: An unhandleable error that results in a program crash.
# +ERROR+:: A handleable error condition.
# +WARN+::  A warning.
# +INFO+::  Generic (useful) information about system operation.
# +DEBUG+:: Low-level information for developers.
#
# For instance, in a production system, you may have your Logger set to
# +INFO+ or even +WARN+.
# When you are developing the system, however, you probably
# want to know about the program's internal state, and would set the Logger to
# +DEBUG+.
#
# *Note*: Logger does not escape or sanitize any messages passed to it.
# Developers should be aware of when potentially malicious data (user-input)
# is passed to Logger, and manually escape the untrusted data:
#
#   logger.info("User-input: #{input.dump}")
#   logger.info("User-input: %p" % input)
#
# You can use #formatter= for escaping all data.
#
#   original_formatter = Logger::Formatter.new
#   logger.formatter = proc { |severity, datetime, progname, msg|
#     original_formatter.call(severity, datetime, progname, msg.dump)
#   }
#   logger.info(input)
#
# === Example
#
# This creates a Logger that outputs to the standard output stream, with a
# level of +WARN+:
#
#   require 'logger'
#
#   logger = Logger.new(STDOUT)
#   logger.level = Logger::WARN
#
#   logger.debug("Created logger")
#   logger.info("Program started")
#   logger.warn("Nothing to do!")
#
#   path = "a_non_existent_file"
#
#   begin
#     File.foreach(path) do |line|
#       unless line =~ /^(\w+) = (.*)$/
#         logger.error("Line in wrong format: #{line.chomp}")
#       end
#     end
#   rescue => err
#     logger.fatal("Caught exception; exiting")
#     logger.fatal(err)
#   end
#
# Because the Logger's level is set to +WARN+, only the warning, error, and
# fatal messages are recorded.  The debug and info messages are silently
# discarded.
#
# === Features
#
# There are several interesting features that Logger provides, like
# auto-rolling of log files, setting the format of log messages, and
# specifying a program name in conjunction with the message.  The next section
# shows you how to achieve these things.
#
#
# == HOWTOs
#
# === How to create a logger
#
# The options below give you various choices, in more or less increasing
# complexity.
#
# 1. Create a logger which logs messages to STDERR/STDOUT.
#
#      logger = Logger.new(STDERR)
#      logger = Logger.new(STDOUT)
#
# 2. Create a logger for the file which has the specified name.
#
#      logger = Logger.new('logfile.log')
#
# 3. Create a logger for the specified file.
#
#      file = File.open('foo.log', File::WRONLY | File::APPEND)
#      # To create new logfile, add File::CREAT like:
#      # file = File.open('foo.log', File::WRONLY | File::APPEND | File::CREAT)
#      logger = Logger.new(file)
#
# 4. Create a logger which ages the logfile once it reaches a certain size.
#    Leave 10 "old" log files where each file is about 1,024,000 bytes.
#
#      logger = Logger.new('foo.log', 10, 1024000)
#
# 5. Create a logger which ages the logfile daily/weekly/monthly.
#
#      logger = Logger.new('foo.log', 'daily')
#      logger = Logger.new('foo.log', 'weekly')
#      logger = Logger.new('foo.log', 'monthly')
#
# === How to log a message
#
# Notice the different methods (+fatal+, +error+, +info+) being used to log
# messages of various levels?  Other methods in this family are +warn+ and
# +debug+.  +add+ is used below to log a message of an arbitrary (perhaps
# dynamic) level.
#
# 1. Message in a block.
#
#      logger.fatal { "Argument 'foo' not given." }
#
# 2. Message as a string.
#
#      logger.error "Argument #{@foo} mismatch."
#
# 3. With progname.
#
#      logger.info('initialize') { "Initializing..." }
#
# 4. With severity.
#
#      logger.add(Logger::FATAL) { 'Fatal error!' }
#
# The block form allows you to create potentially complex log messages,
# but to delay their evaluation until and unless the message is
# logged.  For example, if we have the following:
#
#     logger.debug { "This is a " + potentially + " expensive operation" }
#
# If the logger's level is +INFO+ or higher, no debug messages will be logged,
# and the entire block will not even be evaluated.  Compare to this:
#
#     logger.debug("This is a " + potentially + " expensive operation")
#
# Here, the string concatenation is done every time, even if the log
# level is not set to show the debug message.
#
# === How to close a logger
#
#      logger.close
#
# === Setting severity threshold
#
# 1. Original interface.
#
#      logger.sev_threshold = Logger::WARN
#
# 2. Log4r (somewhat) compatible interface.
#
#      logger.level = Logger::INFO
#
#      # DEBUG < INFO < WARN < ERROR < FATAL < UNKNOWN
#
# 3. Symbol or String (case insensitive)
#
#      logger.level = :info
#      logger.level = 'INFO'
#
#      # :debug < :info < :warn < :error < :fatal < :unknown
#
# 4. Constructor
#
#      Logger.new(logdev, level: Logger::INFO)
#      Logger.new(logdev, level: :info)
#      Logger.new(logdev, level: 'INFO')
#
# == Format
#
# Log messages are rendered in the output stream in a certain format by
# default.  The default format and a sample are shown below:
#
# Log format:
#   SeverityID, [DateTime #pid] SeverityLabel -- ProgName: message
#
# Log sample:
#   I, [1999-03-03T02:34:24.895701 #19074]  INFO -- Main: info.
#
# You may change the date and time format via #datetime_format=.
#
#   logger.datetime_format = '%Y-%m-%d %H:%M:%S'
#         # e.g. "2004-01-03 00:54:26"
#
# or via the constructor.
#
#   Logger.new(logdev, datetime_format: '%Y-%m-%d %H:%M:%S')
#
# Or, you may change the overall format via the #formatter= method.
#
#   logger.formatter = proc do |severity, datetime, progname, msg|
#     "#{datetime}: #{msg}\n"
#   end
#   # e.g. "2005-09-22 08:51:08 +0900: hello world"
#
# or via the constructor.
#
#   Logger.new(logdev, formatter: proc {|severity, datetime, progname, msg|
#     "#{datetime}: #{msg}\n"
#   })
#
class Logger
  _, name, rev = %w$Id$
  if name
    name = name.chomp(",v")
  else
    name = File.basename(__FILE__)
  end
  rev ||= "v#{VERSION}"
  ProgName = "#{name}/#{rev}"

  include Severity

  # Logging severity threshold (e.g. <tt>Logger::INFO</tt>).
  attr_reader :level

  # Set logging severity threshold.
  #
  # +severity+:: The Severity of the log message.
  def level=(severity)
    if severity.is_a?(Integer)
      @level = severity
    else
      case severity.to_s.downcase
      when 'debug'
        @level = DEBUG
      when 'info'
        @level = INFO
      when 'warn'
        @level = WARN
      when 'error'
        @level = ERROR
      when 'fatal'
        @level = FATAL
      when 'unknown'
        @level = UNKNOWN
      else
        raise ArgumentError, "invalid log level: #{severity}"
      end
    end
  end

  # Program name to include in log messages.
  attr_accessor :progname

  # Set date-time format.
  #
  # +datetime_format+:: A string suitable for passing to +strftime+.
  def datetime_format=(datetime_format)
    @default_formatter.datetime_format = datetime_format
  end

  # Returns the date format being used.  See #datetime_format=
  def datetime_format
    @default_formatter.datetime_format
  end

  # Logging formatter, as a +Proc+ that will take four arguments and
  # return the formatted message. The arguments are:
  #
  # +severity+:: The Severity of the log message.
  # +time+:: A Time instance representing when the message was logged.
  # +progname+:: The #progname configured, or passed to the logger method.
  # +msg+:: The _Object_ the user passed to the log message; not necessarily a
  #         String.
  #
  # The block should return an Object that can be written to the logging
  # device via +write+.  The default formatter is used when no formatter is
  # set.
  attr_accessor :formatter

  alias sev_threshold level
  alias sev_threshold= level=

  # Returns +true+ iff the current severity level allows for the printing of
  # +DEBUG+ messages.
  def debug?; level <= DEBUG; end

  # Sets the severity to DEBUG.
  def debug!; self.level = DEBUG; end

  # Returns +true+ iff the current severity level allows for the printing of
  # +INFO+ messages.
  def info?; level <= INFO; end

  # Sets the severity to INFO.
  def info!; self.level = INFO; end

  # Returns +true+ iff the current severity level allows for the printing of
  # +WARN+ messages.
  def warn?; level <= WARN; end

  # Sets the severity to WARN.
  def warn!; self.level = WARN; end

  # Returns +true+ iff the current severity level allows for the printing of
  # +ERROR+ messages.
  def error?; level <= ERROR; end

  # Sets the severity to ERROR.
  def error!; self.level = ERROR; end

  # Returns +true+ iff the current severity level allows for the printing of
  # +FATAL+ messages.
  def fatal?; level <= FATAL; end

  # Sets the severity to FATAL.
  def fatal!; self.level = FATAL; end

  #
  # :call-seq:
  #   Logger.new(logdev, shift_age = 0, shift_size = 1048576)
  #   Logger.new(logdev, shift_age = 'weekly')
  #   Logger.new(logdev, level: :info)
  #   Logger.new(logdev, progname: 'progname')
  #   Logger.new(logdev, formatter: formatter)
  #   Logger.new(logdev, datetime_format: '%Y-%m-%d %H:%M:%S')
  #
  # === Args
  #
  # +logdev+::
  #   The log device.  This is a filename (String), IO object (typically
  #   +STDOUT+, +STDERR+, or an open file), +nil+ (it writes nothing) or
  #   +File::NULL+ (same as +nil+).
  # +shift_age+::
  #   Number of old log files to keep, *or* frequency of rotation (+daily+,
  #   +weekly+ or +monthly+). Default value is 0, which disables log file
  #   rotation.
  # +shift_size+::
  #   Maximum logfile size in bytes (only applies when +shift_age+ is a positive
  #   Integer). Defaults to +1048576+ (1MB).
  # +level+::
  #   Logging severity threshold. Default values is Logger::DEBUG.
  # +progname+::
  #   Program name to include in log messages. Default value is nil.
  # +formatter+::
  #   Logging formatter. Default values is an instance of Logger::Formatter.
  # +datetime_format+::
  #   Date and time format. Default value is '%Y-%m-%d %H:%M:%S'.
  # +binmode+::
  #   Use binary mode on the log device. Default value is false.
  # +shift_period_suffix+::
  #   The log file suffix format for +daily+, +weekly+ or +monthly+ rotation.
  #   Default is '%Y%m%d'.
  #
  # === Description
  #
  # Create an instance.
  #
  def initialize(logdev, shift_age = 0, shift_size = 1048576, level: DEBUG,
                 progname: nil, formatter: nil, datetime_format: nil,
                 binmode: false, shift_period_suffix: '%Y%m%d')
    self.level = level
    self.progname = progname
    @default_formatter = Formatter.new
    self.datetime_format = datetime_format
    self.formatter = formatter
    @logdev = nil
    if logdev && logdev != File::NULL
      @logdev = LogDevice.new(logdev, shift_age: shift_age,
        shift_size: shift_size,
        shift_period_suffix: shift_period_suffix,
        binmode: binmode)
    end
  end

  #
  # :call-seq:
  #   Logger#reopen
  #   Logger#reopen(logdev)
  #
  # === Args
  #
  # +logdev+::
  #   The log device.  This is a filename (String) or IO object (typically
  #   +STDOUT+, +STDERR+, or an open file).  reopen the same filename if
  #   it is +nil+, do nothing for IO.  Default is +nil+.
  #
  # === Description
  #
  # Reopen a log device.
  #
  def reopen(logdev = nil)
    @logdev&.reopen(logdev)
    self
  end

  #
  # :call-seq:
  #   Logger#add(severity, message = nil, progname = nil) { ... }
  #
  # === Args
  #
  # +severity+::
  #   Severity.  Constants are defined in Logger namespace: +DEBUG+, +INFO+,
  #   +WARN+, +ERROR+, +FATAL+, or +UNKNOWN+.
  # +message+::
  #   The log message.  A String or Exception.
  # +progname+::
  #   Program name string.  Can be omitted.  Treated as a message if no
  #   +message+ and +block+ are given.
  # +block+::
  #   Can be omitted.  Called to get a message string if +message+ is nil.
  #
  # === Return
  #
  # When the given severity is not high enough (for this particular logger),
  # log no message, and return +true+.
  #
  # === Description
  #
  # Log a message if the given severity is high enough.  This is the generic
  # logging method.  Users will be more inclined to use #debug, #info, #warn,
  # #error, and #fatal.
  #
  # <b>Message format</b>: +message+ can be any object, but it has to be
  # converted to a String in order to log it.  Generally, +inspect+ is used
  # if the given object is not a String.
  # A special case is an +Exception+ object, which will be printed in detail,
  # including message, class, and backtrace.  See #msg2str for the
  # implementation if required.
  #
  # === Bugs
  #
  # * Logfile is not locked.
  # * Append open does not need to lock file.
  # * If the OS supports multi I/O, records possibly may be mixed.
  #
  def add(severity, message = nil, progname = nil)
    severity ||= UNKNOWN
    if @logdev.nil? or severity < level
      return true
    end
    if progname.nil?
      progname = @progname
    end
    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))
    true
  end
  alias log add

  #
  # Dump given message to the log device without any formatting.  If no log
  # device exists, return +nil+.
  #
  def <<(msg)
    @logdev&.write(msg)
  end

  #
  # Log a +DEBUG+ message.
  #
  # See #info for more information.
  #
  def debug(progname = nil, &block)
    add(DEBUG, nil, progname, &block)
  end

  #
  # :call-seq:
  #   info(message)
  #   info(progname, &block)
  #
  # Log an +INFO+ message.
  #
  # +message+:: The message to log; does not need to be a String.
  # +progname+:: In the block form, this is the #progname to use in the
  #              log message.  The default can be set with #progname=.
  # +block+:: Evaluates to the message to log.  This is not evaluated unless
  #           the logger's level is sufficient to log the message.  This
  #           allows you to create potentially expensive logging messages that
  #           are only called when the logger is configured to show them.
  #
  # === Examples
  #
  #   logger.info("MainApp") { "Received connection from #{ip}" }
  #   # ...
  #   logger.info "Waiting for input from user"
  #   # ...
  #   logger.info { "User typed #{input}" }
  #
  # You'll probably stick to the second form above, unless you want to provide a
  # program name (which you can do with #progname= as well).
  #
  # === Return
  #
  # See #add.
  #
  def info(progname = nil, &block)
    add(INFO, nil, progname, &block)
  end

  #
  # Log a +WARN+ message.
  #
  # See #info for more information.
  #
  def warn(progname = nil, &block)
    add(WARN, nil, progname, &block)
  end

  #
  # Log an +ERROR+ message.
  #
  # See #info for more information.
  #
  def error(progname = nil, &block)
    add(ERROR, nil, progname, &block)
  end

  #
  # Log a +FATAL+ message.
  #
  # See #info for more information.
  #
  def fatal(progname = nil, &block)
    add(FATAL, nil, progname, &block)
  end

  #
  # Log an +UNKNOWN+ message.  This will be printed no matter what the logger's
  # level is.
  #
  # See #info for more information.
  #
  def unknown(progname = nil, &block)
    add(UNKNOWN, nil, progname, &block)
  end

  #
  # Close the logging device.
  #
  def close
    @logdev&.close
  end

private

  # Severity label for logging (max 5 chars).
  SEV_LABEL = %w(DEBUG INFO WARN ERROR FATAL ANY).freeze

  def format_severity(severity)
    SEV_LABEL[severity] || 'ANY'
  end

  def format_message(severity, datetime, progname, msg)
    (@formatter || @default_formatter).call(severity, datetime, progname, msg)
  end
end
# frozen_string_literal: true
#
# Implementation of the _Observer_ object-oriented design pattern.  The
# following documentation is copied, with modifications, from "Programming
# Ruby", by Hunt and Thomas; http://www.ruby-doc.org/docs/ProgrammingRuby/html/lib_patterns.html.
#
# See Observable for more info.

# The Observer pattern (also known as publish/subscribe) provides a simple
# mechanism for one object to inform a set of interested third-party objects
# when its state changes.
#
# == Mechanism
#
# The notifying class mixes in the +Observable+
# module, which provides the methods for managing the associated observer
# objects.
#
# The observable object must:
# * assert that it has +#changed+
# * call +#notify_observers+
#
# An observer subscribes to updates using Observable#add_observer, which also
# specifies the method called via #notify_observers. The default method for
# #notify_observers is #update.
#
# === Example
#
# The following example demonstrates this nicely.  A +Ticker+, when run,
# continually receives the stock +Price+ for its <tt>@symbol</tt>.  A +Warner+
# is a general observer of the price, and two warners are demonstrated, a
# +WarnLow+ and a +WarnHigh+, which print a warning if the price is below or
# above their set limits, respectively.
#
# The +update+ callback allows the warners to run without being explicitly
# called.  The system is set up with the +Ticker+ and several observers, and the
# observers do their duty without the top-level code having to interfere.
#
# Note that the contract between publisher and subscriber (observable and
# observer) is not declared or enforced.  The +Ticker+ publishes a time and a
# price, and the warners receive that.  But if you don't ensure that your
# contracts are correct, nothing else can warn you.
#
#   require "observer"
#
#   class Ticker          ### Periodically fetch a stock price.
#     include Observable
#
#     def initialize(symbol)
#       @symbol = symbol
#     end
#
#     def run
#       last_price = nil
#       loop do
#         price = Price.fetch(@symbol)
#         print "Current price: #{price}\n"
#         if price != last_price
#           changed                 # notify observers
#           last_price = price
#           notify_observers(Time.now, price)
#         end
#         sleep 1
#       end
#     end
#   end
#
#   class Price           ### A mock class to fetch a stock price (60 - 140).
#     def self.fetch(symbol)
#       60 + rand(80)
#     end
#   end
#
#   class Warner          ### An abstract observer of Ticker objects.
#     def initialize(ticker, limit)
#       @limit = limit
#       ticker.add_observer(self)
#     end
#   end
#
#   class WarnLow < Warner
#     def update(time, price)       # callback for observer
#       if price < @limit
#         print "--- #{time.to_s}: Price below #@limit: #{price}\n"
#       end
#     end
#   end
#
#   class WarnHigh < Warner
#     def update(time, price)       # callback for observer
#       if price > @limit
#         print "+++ #{time.to_s}: Price above #@limit: #{price}\n"
#       end
#     end
#   end
#
#   ticker = Ticker.new("MSFT")
#   WarnLow.new(ticker, 80)
#   WarnHigh.new(ticker, 120)
#   ticker.run
#
# Produces:
#
#   Current price: 83
#   Current price: 75
#   --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 75
#   Current price: 90
#   Current price: 134
#   +++ Sun Jun 09 00:10:25 CDT 2002: Price above 120: 134
#   Current price: 134
#   Current price: 112
#   Current price: 79
#   --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 79
#
# === Usage with procs
#
# The +#notify_observers+ method can also be used with +proc+s by using
# the +:call+ as +func+ parameter.
#
# The following example illustrates the use of a lambda:
#
#   require 'observer'
#
#   class Ticker
#     include Observable
#
#     def run
#       # logic to retrieve the price (here 77.0)
#       changed
#       notify_observers(77.0)
#     end
#   end
#
#   ticker = Ticker.new
#   warner = ->(price) { puts "New price received: #{price}" }
#   ticker.add_observer(warner, :call)
#   ticker.run
module Observable
  VERSION = "0.1.1"

  #
  # Add +observer+ as an observer on this object. So that it will receive
  # notifications.
  #
  # +observer+:: the object that will be notified of changes.
  # +func+:: Symbol naming the method that will be called when this Observable
  #          has changes.
  #
  #          This method must return true for +observer.respond_to?+ and will
  #          receive <tt>*arg</tt> when #notify_observers is called, where
  #          <tt>*arg</tt> is the value passed to #notify_observers by this
  #          Observable
  def add_observer(observer, func=:update)
    @observer_peers = {} unless defined? @observer_peers
    unless observer.respond_to? func
      raise NoMethodError, "observer does not respond to `#{func}'"
    end
    @observer_peers[observer] = func
  end

  #
  # Remove +observer+ as an observer on this object so that it will no longer
  # receive notifications.
  #
  # +observer+:: An observer of this Observable
  def delete_observer(observer)
    @observer_peers.delete observer if defined? @observer_peers
  end

  #
  # Remove all observers associated with this object.
  #
  def delete_observers
    @observer_peers.clear if defined? @observer_peers
  end

  #
  # Return the number of observers associated with this object.
  #
  def count_observers
    if defined? @observer_peers
      @observer_peers.size
    else
      0
    end
  end

  #
  # Set the changed state of this object.  Notifications will be sent only if
  # the changed +state+ is +true+.
  #
  # +state+:: Boolean indicating the changed state of this Observable.
  #
  def changed(state=true)
    @observer_state = state
  end

  #
  # Returns true if this object's state has been changed since the last
  # #notify_observers call.
  #
  def changed?
    if defined? @observer_state and @observer_state
      true
    else
      false
    end
  end

  #
  # Notify observers of a change in state *if* this object's changed state is
  # +true+.
  #
  # This will invoke the method named in #add_observer, passing <tt>*arg</tt>.
  # The changed state is then set to +false+.
  #
  # <tt>*arg</tt>:: Any arguments to pass to the observers.
  def notify_observers(*arg)
    if defined? @observer_state and @observer_state
      if defined? @observer_peers
        @observer_peers.each do |k, v|
          k.__send__(v, *arg)
        end
      end
      @observer_state = false
    end
  end

end
require 'io/console'
require 'timeout'
require 'forwardable'
require 'reline/version'
require 'reline/config'
require 'reline/key_actor'
require 'reline/key_stroke'
require 'reline/line_editor'
require 'reline/history'
require 'rbconfig'

module Reline
  FILENAME_COMPLETION_PROC = nil
  USERNAME_COMPLETION_PROC = nil

  Key = Struct.new('Key', :char, :combined_char, :with_meta)
  CursorPos = Struct.new(:x, :y)

  class Core
    ATTR_READER_NAMES = %i(
      completion_append_character
      basic_word_break_characters
      completer_word_break_characters
      basic_quote_characters
      completer_quote_characters
      filename_quote_characters
      special_prefixes
      completion_proc
      output_modifier_proc
      prompt_proc
      auto_indent_proc
      pre_input_hook
      dig_perfect_match_proc
    ).each(&method(:attr_reader))

    attr_accessor :config
    attr_accessor :key_stroke
    attr_accessor :line_editor
    attr_accessor :last_incremental_search
    attr_reader :output

    def initialize
      self.output = STDOUT
      yield self
      @completion_quote_character = nil
      @bracketed_paste_finished = false
    end

    def encoding
      Reline::IOGate.encoding
    end

    def completion_append_character=(val)
      if val.nil?
        @completion_append_character = nil
      elsif val.size == 1
        @completion_append_character = val.encode(Reline::IOGate.encoding)
      elsif val.size > 1
        @completion_append_character = val[0].encode(Reline::IOGate.encoding)
      else
        @completion_append_character = nil
      end
    end

    def basic_word_break_characters=(v)
      @basic_word_break_characters = v.encode(Reline::IOGate.encoding)
    end

    def completer_word_break_characters=(v)
      @completer_word_break_characters = v.encode(Reline::IOGate.encoding)
    end

    def basic_quote_characters=(v)
      @basic_quote_characters = v.encode(Reline::IOGate.encoding)
    end

    def completer_quote_characters=(v)
      @completer_quote_characters = v.encode(Reline::IOGate.encoding)
    end

    def filename_quote_characters=(v)
      @filename_quote_characters = v.encode(Reline::IOGate.encoding)
    end

    def special_prefixes=(v)
      @special_prefixes = v.encode(Reline::IOGate.encoding)
    end

    def completion_case_fold=(v)
      @config.completion_ignore_case = v
    end

    def completion_case_fold
      @config.completion_ignore_case
    end

    def completion_quote_character
      @completion_quote_character
    end

    def completion_proc=(p)
      raise ArgumentError unless p.respond_to?(:call) or p.nil?
      @completion_proc = p
    end

    def output_modifier_proc=(p)
      raise ArgumentError unless p.respond_to?(:call) or p.nil?
      @output_modifier_proc = p
    end

    def prompt_proc=(p)
      raise ArgumentError unless p.respond_to?(:call) or p.nil?
      @prompt_proc = p
    end

    def auto_indent_proc=(p)
      raise ArgumentError unless p.respond_to?(:call) or p.nil?
      @auto_indent_proc = p
    end

    def pre_input_hook=(p)
      @pre_input_hook = p
    end

    def dig_perfect_match_proc=(p)
      raise ArgumentError unless p.respond_to?(:call) or p.nil?
      @dig_perfect_match_proc = p
    end

    def input=(val)
      raise TypeError unless val.respond_to?(:getc) or val.nil?
      if val.respond_to?(:getc)
        if defined?(Reline::ANSI) and Reline::IOGate == Reline::ANSI
          Reline::ANSI.input = val
        elsif Reline::IOGate == Reline::GeneralIO
          Reline::GeneralIO.input = val
        end
      end
    end

    def output=(val)
      raise TypeError unless val.respond_to?(:write) or val.nil?
      @output = val
      if defined?(Reline::ANSI) and Reline::IOGate == Reline::ANSI
        Reline::ANSI.output = val
      end
    end

    def vi_editing_mode
      config.editing_mode = :vi_insert
      nil
    end

    def emacs_editing_mode
      config.editing_mode = :emacs
      nil
    end

    def vi_editing_mode?
      config.editing_mode_is?(:vi_insert, :vi_command)
    end

    def emacs_editing_mode?
      config.editing_mode_is?(:emacs)
    end

    def get_screen_size
      Reline::IOGate.get_screen_size
    end

    def readmultiline(prompt = '', add_hist = false, &confirm_multiline_termination)
      unless confirm_multiline_termination
        raise ArgumentError.new('#readmultiline needs block to confirm multiline termination')
      end
      inner_readline(prompt, add_hist, true, &confirm_multiline_termination)

      whole_buffer = line_editor.whole_buffer.dup
      whole_buffer.taint if RUBY_VERSION < '2.7'
      if add_hist and whole_buffer and whole_buffer.chomp("\n").size > 0
        Reline::HISTORY << whole_buffer
      end

      line_editor.reset_line if line_editor.whole_buffer.nil?
      whole_buffer
    end

    def readline(prompt = '', add_hist = false)
      inner_readline(prompt, add_hist, false)

      line = line_editor.line.dup
      line.taint if RUBY_VERSION < '2.7'
      if add_hist and line and line.chomp("\n").size > 0
        Reline::HISTORY << line.chomp("\n")
      end

      line_editor.reset_line if line_editor.line.nil?
      line
    end

    private def inner_readline(prompt, add_hist, multiline, &confirm_multiline_termination)
      if ENV['RELINE_STDERR_TTY']
        if Reline::IOGate.win?
          $stderr = File.open(ENV['RELINE_STDERR_TTY'], 'a')
        else
          $stderr.reopen(ENV['RELINE_STDERR_TTY'], 'w')
        end
        $stderr.sync = true
        $stderr.puts "Reline is used by #{Process.pid}"
      end
      otio = Reline::IOGate.prep

      may_req_ambiguous_char_width
      line_editor.reset(prompt, encoding: Reline::IOGate.encoding)
      if multiline
        line_editor.multiline_on
        if block_given?
          line_editor.confirm_multiline_termination_proc = confirm_multiline_termination
        end
      else
        line_editor.multiline_off
      end
      line_editor.output = output
      line_editor.completion_proc = completion_proc
      line_editor.completion_append_character = completion_append_character
      line_editor.output_modifier_proc = output_modifier_proc
      line_editor.prompt_proc = prompt_proc
      line_editor.auto_indent_proc = auto_indent_proc
      line_editor.dig_perfect_match_proc = dig_perfect_match_proc
      line_editor.pre_input_hook = pre_input_hook

      unless config.test_mode
        config.read
        config.reset_default_key_bindings
        Reline::IOGate::RAW_KEYSTROKE_CONFIG.each_pair do |key, func|
          config.add_default_key_binding(key, func)
        end
      end

      line_editor.rerender

      begin
        prev_pasting_state = false
        loop do
          prev_pasting_state = Reline::IOGate.in_pasting?
          read_io(config.keyseq_timeout) { |inputs|
            line_editor.set_pasting_state(Reline::IOGate.in_pasting?)
            inputs.each { |c|
              line_editor.input_key(c)
              line_editor.rerender
            }
            if @bracketed_paste_finished
              line_editor.rerender_all
              @bracketed_paste_finished = false
            end
          }
          if prev_pasting_state == true and not Reline::IOGate.in_pasting? and not line_editor.finished?
            line_editor.set_pasting_state(false)
            prev_pasting_state = false
            line_editor.rerender_all
          end
          break if line_editor.finished?
        end
        Reline::IOGate.move_cursor_column(0)
      rescue Errno::EIO
        # Maybe the I/O has been closed.
      rescue StandardError => e
        line_editor.finalize
        Reline::IOGate.deprep(otio)
        raise e
      end

      line_editor.finalize
      Reline::IOGate.deprep(otio)
    end

    # Keystrokes of GNU Readline will timeout it with the specification of
    # "keyseq-timeout" when waiting for the 2nd character after the 1st one.
    # If the 2nd character comes after 1st ESC without timeout it has a
    # meta-property of meta-key to discriminate modified key with meta-key
    # from multibyte characters that come with 8th bit on.
    #
    # GNU Readline will wait for the 2nd character with "keyseq-timeout"
    # milli-seconds but wait forever after 3rd characters.
    private def read_io(keyseq_timeout, &block)
      buffer = []
      loop do
        c = Reline::IOGate.getc
        if c == -1
          result = :unmatched
          @bracketed_paste_finished = true
        else
          buffer << c
          result = key_stroke.match_status(buffer)
        end
        case result
        when :matched
          expanded = key_stroke.expand(buffer).map{ |expanded_c|
            Reline::Key.new(expanded_c, expanded_c, false)
          }
          block.(expanded)
          break
        when :matching
          if buffer.size == 1
            begin
              succ_c = nil
              Timeout.timeout(keyseq_timeout / 1000.0) {
                succ_c = Reline::IOGate.getc
              }
            rescue Timeout::Error # cancel matching only when first byte
              block.([Reline::Key.new(c, c, false)])
              break
            else
              if key_stroke.match_status(buffer.dup.push(succ_c)) == :unmatched
                if c == "\e".ord
                  block.([Reline::Key.new(succ_c, succ_c | 0b10000000, true)])
                else
                  block.([Reline::Key.new(c, c, false), Reline::Key.new(succ_c, succ_c, false)])
                end
                break
              else
                Reline::IOGate.ungetc(succ_c)
              end
            end
          end
        when :unmatched
          if buffer.size == 1 and c == "\e".ord
            read_escaped_key(keyseq_timeout, c, block)
          else
            expanded = buffer.map{ |expanded_c|
              Reline::Key.new(expanded_c, expanded_c, false)
            }
            block.(expanded)
          end
          break
        end
      end
    end

    private def read_escaped_key(keyseq_timeout, c, block)
      begin
        escaped_c = nil
        Timeout.timeout(keyseq_timeout / 1000.0) {
          escaped_c = Reline::IOGate.getc
        }
      rescue Timeout::Error # independent ESC
        block.([Reline::Key.new(c, c, false)])
      else
        if escaped_c.nil?
          block.([Reline::Key.new(c, c, false)])
        elsif escaped_c >= 128 # maybe, first byte of multi byte
          block.([Reline::Key.new(c, c, false), Reline::Key.new(escaped_c, escaped_c, false)])
        elsif escaped_c == "\e".ord # escape twice
          block.([Reline::Key.new(c, c, false), Reline::Key.new(c, c, false)])
        else
          block.([Reline::Key.new(escaped_c, escaped_c | 0b10000000, true)])
        end
      end
    end

    def ambiguous_width
      may_req_ambiguous_char_width unless defined? @ambiguous_width
      @ambiguous_width
    end

    private def may_req_ambiguous_char_width
      @ambiguous_width = 2 if Reline::IOGate == Reline::GeneralIO or STDOUT.is_a?(File)
      return if @ambiguous_width
      Reline::IOGate.move_cursor_column(0)
      begin
        output.write "\u{25bd}"
      rescue Encoding::UndefinedConversionError
        # LANG=C
        @ambiguous_width = 1
      else
        @ambiguous_width = Reline::IOGate.cursor_pos.x
      end
      Reline::IOGate.move_cursor_column(0)
      Reline::IOGate.erase_after_cursor
    end
  end

  extend Forwardable
  extend SingleForwardable

  #--------------------------------------------------------
  # Documented API
  #--------------------------------------------------------

  (Core::ATTR_READER_NAMES).each { |name|
    def_single_delegators :core, "#{name}", "#{name}="
  }
  def_single_delegators :core, :input=, :output=
  def_single_delegators :core, :vi_editing_mode, :emacs_editing_mode
  def_single_delegators :core, :readline
  def_single_delegators :core, :completion_case_fold, :completion_case_fold=
  def_single_delegators :core, :completion_quote_character
  def_instance_delegators self, :readline
  private :readline


  #--------------------------------------------------------
  # Undocumented API
  #--------------------------------------------------------

  # Testable in original
  def_single_delegators :core, :get_screen_size
  def_single_delegators :line_editor, :eof?
  def_instance_delegators self, :eof?
  def_single_delegators :line_editor, :delete_text
  def_single_delegator :line_editor, :line, :line_buffer
  def_single_delegator :line_editor, :byte_pointer, :point
  def_single_delegator :line_editor, :byte_pointer=, :point=

  def self.insert_text(*args, &block)
    line_editor.insert_text(*args, &block)
    self
  end

  # Untestable in original
  def_single_delegator :line_editor, :rerender, :redisplay
  def_single_delegators :core, :vi_editing_mode?, :emacs_editing_mode?
  def_single_delegators :core, :ambiguous_width
  def_single_delegators :core, :last_incremental_search
  def_single_delegators :core, :last_incremental_search=

  def_single_delegators :core, :readmultiline
  def_instance_delegators self, :readmultiline
  private :readmultiline

  def self.encoding_system_needs
    self.core.encoding
  end

  def self.core
    @core ||= Core.new { |core|
      core.config = Reline::Config.new
      core.key_stroke = Reline::KeyStroke.new(core.config)
      core.line_editor = Reline::LineEditor.new(core.config, Reline::IOGate.encoding)

      core.basic_word_break_characters = " \t\n`><=;|&{("
      core.completer_word_break_characters = " \t\n`><=;|&{("
      core.basic_quote_characters = '"\''
      core.completer_quote_characters = '"\''
      core.filename_quote_characters = ""
      core.special_prefixes = ""
    }
  end

  def self.ungetc(c)
    Reline::IOGate.ungetc(c)
  end

  def self.line_editor
    core.line_editor
  end
end

if RbConfig::CONFIG['host_os'] =~ /mswin|msys|mingw|cygwin|bccwin|wince|emc/
  require 'reline/windows'
  if Reline::Windows.msys_tty?
    require 'reline/ansi'
    Reline::IOGate = Reline::ANSI
  else
    Reline::IOGate = Reline::Windows
  end
else
  require 'reline/ansi'
  Reline::IOGate = Reline::ANSI
end
Reline::HISTORY = Reline::History.new(Reline.core.config)
require 'reline/general_io'
# frozen_string_literal: false
#
#   forwardable.rb -
#       $Release Version: 1.1$
#       $Revision$
#       by Keiju ISHITSUKA(keiju@ishitsuka.com)
#       original definition by delegator.rb
#       Revised by Daniel J. Berger with suggestions from Florian Gross.
#
#       Documentation by James Edward Gray II and Gavin Sinclair



# The Forwardable module provides delegation of specified
# methods to a designated object, using the methods #def_delegator
# and #def_delegators.
#
# For example, say you have a class RecordCollection which
# contains an array <tt>@records</tt>.  You could provide the lookup method
# #record_number(), which simply calls #[] on the <tt>@records</tt>
# array, like this:
#
#   require 'forwardable'
#
#   class RecordCollection
#     attr_accessor :records
#     extend Forwardable
#     def_delegator :@records, :[], :record_number
#   end
#
# We can use the lookup method like so:
#
#   r = RecordCollection.new
#   r.records = [4,5,6]
#   r.record_number(0)  # => 4
#
# Further, if you wish to provide the methods #size, #<<, and #map,
# all of which delegate to @records, this is how you can do it:
#
#   class RecordCollection # re-open RecordCollection class
#     def_delegators :@records, :size, :<<, :map
#   end
#
#   r = RecordCollection.new
#   r.records = [1,2,3]
#   r.record_number(0)   # => 1
#   r.size               # => 3
#   r << 4               # => [1, 2, 3, 4]
#   r.map { |x| x * 2 }  # => [2, 4, 6, 8]
#
# You can even extend regular objects with Forwardable.
#
#   my_hash = Hash.new
#   my_hash.extend Forwardable              # prepare object for delegation
#   my_hash.def_delegator "STDOUT", "puts"  # add delegation for STDOUT.puts()
#   my_hash.puts "Howdy!"
#
# == Another example
#
# You could use Forwardable as an alternative to inheritance, when you don't want
# to inherit all methods from the superclass. For instance, here is how you might
# add a range of +Array+ instance methods to a new class +Queue+:
#
#   class Queue
#     extend Forwardable
#
#     def initialize
#       @q = [ ]    # prepare delegate object
#     end
#
#     # setup preferred interface, enq() and deq()...
#     def_delegator :@q, :push, :enq
#     def_delegator :@q, :shift, :deq
#
#     # support some general Array methods that fit Queues well
#     def_delegators :@q, :clear, :first, :push, :shift, :size
#   end
#
#   q = Queue.new
#   q.enq 1, 2, 3, 4, 5
#   q.push 6
#
#   q.shift    # => 1
#   while q.size > 0
#     puts q.deq
#   end
#
#   q.enq "Ruby", "Perl", "Python"
#   puts q.first
#   q.clear
#   puts q.first
#
# This should output:
#
#   2
#   3
#   4
#   5
#   6
#   Ruby
#   nil
#
# == Notes
#
# Be advised, RDoc will not detect delegated methods.
#
# +forwardable.rb+ provides single-method delegation via the def_delegator and
# def_delegators methods. For full-class delegation via DelegateClass, see
# +delegate.rb+.
#
module Forwardable
  require 'forwardable/impl'

  # Version of +forwardable.rb+
  VERSION = "1.3.2"
  FORWARDABLE_VERSION = VERSION

  @debug = nil
  class << self
    # ignored
    attr_accessor :debug
  end

  # Takes a hash as its argument.  The key is a symbol or an array of
  # symbols.  These symbols correspond to method names, instance variable
  # names, or constant names (see def_delegator).  The value is
  # the accessor to which the methods will be delegated.
  #
  # :call-seq:
  #    delegate method => accessor
  #    delegate [method, method, ...] => accessor
  #
  def instance_delegate(hash)
    hash.each do |methods, accessor|
      unless defined?(methods.each)
        def_instance_delegator(accessor, methods)
      else
        methods.each {|method| def_instance_delegator(accessor, method)}
      end
    end
  end

  #
  # Shortcut for defining multiple delegator methods, but with no
  # provision for using a different name.  The following two code
  # samples have the same effect:
  #
  #   def_delegators :@records, :size, :<<, :map
  #
  #   def_delegator :@records, :size
  #   def_delegator :@records, :<<
  #   def_delegator :@records, :map
  #
  def def_instance_delegators(accessor, *methods)
    methods.each do |method|
      next if /\A__(?:send|id)__\z/ =~ method
      def_instance_delegator(accessor, method)
    end
  end

  # Define +method+ as delegator instance method with an optional
  # alias name +ali+. Method calls to +ali+ will be delegated to
  # +accessor.method+.  +accessor+ should be a method name, instance
  # variable name, or constant name.  Use the full path to the
  # constant if providing the constant name.
  # Returns the name of the method defined.
  #
  #   class MyQueue
  #     CONST = 1
  #     extend Forwardable
  #     attr_reader :queue
  #     def initialize
  #       @queue = []
  #     end
  #
  #     def_delegator :@queue, :push, :mypush
  #     def_delegator 'MyQueue::CONST', :to_i
  #   end
  #
  #   q = MyQueue.new
  #   q.mypush 42
  #   q.queue    #=> [42]
  #   q.push 23  #=> NoMethodError
  #   q.to_i     #=> 1
  #
  def def_instance_delegator(accessor, method, ali = method)
    gen = Forwardable._delegator_method(self, accessor, method, ali)

    # If it's not a class or module, it's an instance
    mod = Module === self ? self : singleton_class
    ret = mod.module_eval(&gen)
    mod.__send__(:ruby2_keywords, ali) if RUBY_VERSION >= '2.7'
    ret
  end

  alias delegate instance_delegate
  alias def_delegators def_instance_delegators
  alias def_delegator def_instance_delegator

  # :nodoc:
  def self._delegator_method(obj, accessor, method, ali)
    accessor = accessor.to_s unless Symbol === accessor

    if Module === obj ?
         obj.method_defined?(accessor) || obj.private_method_defined?(accessor) :
         obj.respond_to?(accessor, true)
      accessor = "#{accessor}()"
    end

    method_call = ".__send__(:#{method}, *args, &block)"
    if _valid_method?(method)
      loc, = caller_locations(2,1)
      pre = "_ ="
      mesg = "#{Module === obj ? obj : obj.class}\##{ali} at #{loc.path}:#{loc.lineno} forwarding to private method "
      method_call = "#{<<-"begin;"}\n#{<<-"end;".chomp}"
        begin;
          unless defined? _.#{method}
            ::Kernel.warn #{mesg.dump}"\#{_.class}"'##{method}', uplevel: 1
            _#{method_call}
          else
            _.#{method}(*args, &block)
          end
        end;
    end

    _compile_method("#{<<-"begin;"}\n#{<<-"end;"}", __FILE__, __LINE__+1)
    begin;
      proc do
        def #{ali}(*args, &block)
          #{pre}
          begin
            #{accessor}
          end#{method_call}
        end
      end
    end;
  end
end

# SingleForwardable can be used to setup delegation at the object level as well.
#
#    printer = String.new
#    printer.extend SingleForwardable        # prepare object for delegation
#    printer.def_delegator "STDOUT", "puts"  # add delegation for STDOUT.puts()
#    printer.puts "Howdy!"
#
# Also, SingleForwardable can be used to set up delegation for a Class or Module.
#
#   class Implementation
#     def self.service
#       puts "serviced!"
#     end
#   end
#
#   module Facade
#     extend SingleForwardable
#     def_delegator :Implementation, :service
#   end
#
#   Facade.service #=> serviced!
#
# If you want to use both Forwardable and SingleForwardable, you can
# use methods def_instance_delegator and def_single_delegator, etc.
module SingleForwardable
  # Takes a hash as its argument.  The key is a symbol or an array of
  # symbols.  These symbols correspond to method names.  The value is
  # the accessor to which the methods will be delegated.
  #
  # :call-seq:
  #    delegate method => accessor
  #    delegate [method, method, ...] => accessor
  #
  def single_delegate(hash)
    hash.each do |methods, accessor|
      unless defined?(methods.each)
        def_single_delegator(accessor, methods)
      else
        methods.each {|method| def_single_delegator(accessor, method)}
      end
    end
  end

  #
  # Shortcut for defining multiple delegator methods, but with no
  # provision for using a different name.  The following two code
  # samples have the same effect:
  #
  #   def_delegators :@records, :size, :<<, :map
  #
  #   def_delegator :@records, :size
  #   def_delegator :@records, :<<
  #   def_delegator :@records, :map
  #
  def def_single_delegators(accessor, *methods)
    methods.each do |method|
      next if /\A__(?:send|id)__\z/ =~ method
      def_single_delegator(accessor, method)
    end
  end

  # :call-seq:
  #   def_single_delegator(accessor, method, new_name=method)
  #
  # Defines a method _method_ which delegates to _accessor_ (i.e. it calls
  # the method of the same name in _accessor_).  If _new_name_ is
  # provided, it is used as the name for the delegate method.
  # Returns the name of the method defined.
  def def_single_delegator(accessor, method, ali = method)
    gen = Forwardable._delegator_method(self, accessor, method, ali)

    ret = instance_eval(&gen)
    singleton_class.__send__(:ruby2_keywords, ali) if RUBY_VERSION >= '2.7'
    ret
  end

  alias delegate single_delegate
  alias def_delegators def_single_delegators
  alias def_delegator def_single_delegator
end
require 'racc/compat'
require 'racc/debugflags'
require 'racc/grammar'
require 'racc/state'
require 'racc/exception'
require 'racc/info'
# frozen_string_literal: false
# = uri/ftp.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# License:: You can redistribute it and/or modify it under the same term as Ruby.
#
# See URI for general documentation
#

require_relative 'generic'

module URI

  #
  # FTP URI syntax is defined by RFC1738 section 3.2.
  #
  # This class will be redesigned because of difference of implementations;
  # the structure of its path. draft-hoffman-ftp-uri-04 is a draft but it
  # is a good summary about the de facto spec.
  # http://tools.ietf.org/html/draft-hoffman-ftp-uri-04
  #
  class FTP < Generic
    # A Default port of 21 for URI::FTP.
    DEFAULT_PORT = 21

    #
    # An Array of the available components for URI::FTP.
    #
    COMPONENT = [
      :scheme,
      :userinfo, :host, :port,
      :path, :typecode
    ].freeze

    #
    # Typecode is "a", "i", or "d".
    #
    # * "a" indicates a text file (the FTP command was ASCII)
    # * "i" indicates a binary file (FTP command IMAGE)
    # * "d" indicates the contents of a directory should be displayed
    #
    TYPECODE = ['a', 'i', 'd'].freeze

    # Typecode prefix ";type=".
    TYPECODE_PREFIX = ';type='.freeze

    def self.new2(user, password, host, port, path,
                  typecode = nil, arg_check = true) # :nodoc:
      # Do not use this method!  Not tested.  [Bug #7301]
      # This methods remains just for compatibility,
      # Keep it undocumented until the active maintainer is assigned.
      typecode = nil if typecode.size == 0
      if typecode && !TYPECODE.include?(typecode)
        raise ArgumentError,
          "bad typecode is specified: #{typecode}"
      end

      # do escape

      self.new('ftp',
               [user, password],
               host, port, nil,
               typecode ? path + TYPECODE_PREFIX + typecode : path,
               nil, nil, nil, arg_check)
    end

    #
    # == Description
    #
    # Creates a new URI::FTP object from components, with syntax checking.
    #
    # The components accepted are +userinfo+, +host+, +port+, +path+, and
    # +typecode+.
    #
    # The components should be provided either as an Array, or as a Hash
    # with keys formed by preceding the component names with a colon.
    #
    # If an Array is used, the components must be passed in the
    # order <code>[userinfo, host, port, path, typecode]</code>.
    #
    # If the path supplied is absolute, it will be escaped in order to
    # make it absolute in the URI.
    #
    # Examples:
    #
    #     require 'uri'
    #
    #     uri1 = URI::FTP.build(['user:password', 'ftp.example.com', nil,
    #       '/path/file.zip', 'i'])
    #     uri1.to_s  # => "ftp://user:password@ftp.example.com/%2Fpath/file.zip;type=i"
    #
    #     uri2 = URI::FTP.build({:host => 'ftp.example.com',
    #       :path => 'ruby/src'})
    #     uri2.to_s  # => "ftp://ftp.example.com/ruby/src"
    #
    def self.build(args)

      # Fix the incoming path to be generic URL syntax
      # FTP path  ->  URL path
      # foo/bar       /foo/bar
      # /foo/bar      /%2Ffoo/bar
      #
      if args.kind_of?(Array)
        args[3] = '/' + args[3].sub(/^\//, '%2F')
      else
        args[:path] = '/' + args[:path].sub(/^\//, '%2F')
      end

      tmp = Util::make_components_hash(self, args)

      if tmp[:typecode]
        if tmp[:typecode].size == 1
          tmp[:typecode] = TYPECODE_PREFIX + tmp[:typecode]
        end
        tmp[:path] << tmp[:typecode]
      end

      return super(tmp)
    end

    #
    # == Description
    #
    # Creates a new URI::FTP object from generic URL components with no
    # syntax checking.
    #
    # Unlike build(), this method does not escape the path component as
    # required by RFC1738; instead it is treated as per RFC2396.
    #
    # Arguments are +scheme+, +userinfo+, +host+, +port+, +registry+, +path+,
    # +opaque+, +query+, and +fragment+, in that order.
    #
    def initialize(scheme,
                   userinfo, host, port, registry,
                   path, opaque,
                   query,
                   fragment,
                   parser = nil,
                   arg_check = false)
      raise InvalidURIError unless path
      path = path.sub(/^\//,'')
      path.sub!(/^%2F/,'/')
      super(scheme, userinfo, host, port, registry, path, opaque,
            query, fragment, parser, arg_check)
      @typecode = nil
      if tmp = @path.index(TYPECODE_PREFIX)
        typecode = @path[tmp + TYPECODE_PREFIX.size..-1]
        @path = @path[0..tmp - 1]

        if arg_check
          self.typecode = typecode
        else
          self.set_typecode(typecode)
        end
      end
    end

    # typecode accessor.
    #
    # See URI::FTP::COMPONENT.
    attr_reader :typecode

    # Validates typecode +v+,
    # returns +true+ or +false+.
    #
    def check_typecode(v)
      if TYPECODE.include?(v)
        return true
      else
        raise InvalidComponentError,
          "bad typecode(expected #{TYPECODE.join(', ')}): #{v}"
      end
    end
    private :check_typecode

    # Private setter for the typecode +v+.
    #
    # See also URI::FTP.typecode=.
    #
    def set_typecode(v)
      @typecode = v
    end
    protected :set_typecode

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the typecode +v+
    # (with validation).
    #
    # See also URI::FTP.check_typecode.
    #
    # == Usage
    #
    #   require 'uri'
    #
    #   uri = URI.parse("ftp://john@ftp.example.com/my_file.img")
    #   #=> #<URI::FTP ftp://john@ftp.example.com/my_file.img>
    #   uri.typecode = "i"
    #   uri
    #   #=> #<URI::FTP ftp://john@ftp.example.com/my_file.img;type=i>
    #
    def typecode=(typecode)
      check_typecode(typecode)
      set_typecode(typecode)
      typecode
    end

    def merge(oth) # :nodoc:
      tmp = super(oth)
      if self != tmp
        tmp.set_typecode(oth.typecode)
      end

      return tmp
    end

    # Returns the path from an FTP URI.
    #
    # RFC 1738 specifically states that the path for an FTP URI does not
    # include the / which separates the URI path from the URI host. Example:
    #
    # <code>ftp://ftp.example.com/pub/ruby</code>
    #
    # The above URI indicates that the client should connect to
    # ftp.example.com then cd to pub/ruby from the initial login directory.
    #
    # If you want to cd to an absolute directory, you must include an
    # escaped / (%2F) in the path. Example:
    #
    # <code>ftp://ftp.example.com/%2Fpub/ruby</code>
    #
    # This method will then return "/pub/ruby".
    #
    def path
      return @path.sub(/^\//,'').sub(/^%2F/,'/')
    end

    # Private setter for the path of the URI::FTP.
    def set_path(v)
      super("/" + v.sub(/^\//, "%2F"))
    end
    protected :set_path

    # Returns a String representation of the URI::FTP.
    def to_s
      save_path = nil
      if @typecode
        save_path = @path
        @path = @path + TYPECODE_PREFIX + @typecode
      end
      str = super
      if @typecode
        @path = save_path
      end

      return str
    end
  end
  @@schemes['FTP'] = FTP
end
# frozen_string_literal: false
# = uri/wss.rb
#
# Author:: Matt Muller <mamuller@amazon.com>
# License:: You can redistribute it and/or modify it under the same term as Ruby.
#
# See URI for general documentation
#

require_relative 'ws'

module URI

  # The default port for WSS URIs is 443, and the scheme is 'wss:' rather
  # than 'ws:'. Other than that, WSS URIs are identical to WS URIs;
  # see URI::WS.
  class WSS < WS
    # A Default port of 443 for URI::WSS
    DEFAULT_PORT = 443
  end
  @@schemes['WSS'] = WSS
end
# frozen_string_literal: false
# = uri/https.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# License:: You can redistribute it and/or modify it under the same term as Ruby.
#
# See URI for general documentation
#

require_relative 'http'

module URI

  # The default port for HTTPS URIs is 443, and the scheme is 'https:' rather
  # than 'http:'. Other than that, HTTPS URIs are identical to HTTP URIs;
  # see URI::HTTP.
  class HTTPS < HTTP
    # A Default port of 443 for URI::HTTPS
    DEFAULT_PORT = 443
  end
  @@schemes['HTTPS'] = HTTPS
end
# frozen_string_literal: true

require_relative 'generic'

module URI

  #
  # The "file" URI is defined by RFC8089.
  #
  class File < Generic
    # A Default port of nil for URI::File.
    DEFAULT_PORT = nil

    #
    # An Array of the available components for URI::File.
    #
    COMPONENT = [
      :scheme,
      :host,
      :path
    ].freeze

    #
    # == Description
    #
    # Creates a new URI::File object from components, with syntax checking.
    #
    # The components accepted are +host+ and +path+.
    #
    # The components should be provided either as an Array, or as a Hash
    # with keys formed by preceding the component names with a colon.
    #
    # If an Array is used, the components must be passed in the
    # order <code>[host, path]</code>.
    #
    # Examples:
    #
    #     require 'uri'
    #
    #     uri1 = URI::File.build(['host.example.com', '/path/file.zip'])
    #     uri1.to_s  # => "file://host.example.com/path/file.zip"
    #
    #     uri2 = URI::File.build({:host => 'host.example.com',
    #       :path => '/ruby/src'})
    #     uri2.to_s  # => "file://host.example.com/ruby/src"
    #
    def self.build(args)
      tmp = Util::make_components_hash(self, args)
      super(tmp)
    end

    # Protected setter for the host component +v+.
    #
    # See also URI::Generic.host=.
    #
    def set_host(v)
      v = "" if v.nil? || v == "localhost"
      @host = v
    end

    # do nothing
    def set_port(v)
    end

    # raise InvalidURIError
    def check_userinfo(user)
      raise URI::InvalidURIError, "can not set userinfo for file URI"
    end

    # raise InvalidURIError
    def check_user(user)
      raise URI::InvalidURIError, "can not set user for file URI"
    end

    # raise InvalidURIError
    def check_password(user)
      raise URI::InvalidURIError, "can not set password for file URI"
    end

    # do nothing
    def set_userinfo(v)
    end

    # do nothing
    def set_user(v)
    end

    # do nothing
    def set_password(v)
    end
  end

  @@schemes['FILE'] = File
end
# frozen_string_literal: true
#--
# = uri/common.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# License::
#   You can redistribute it and/or modify it under the same term as Ruby.
#
# See URI for general documentation
#

require_relative "rfc2396_parser"
require_relative "rfc3986_parser"

module URI
  REGEXP = RFC2396_REGEXP
  Parser = RFC2396_Parser
  RFC3986_PARSER = RFC3986_Parser.new

  # URI::Parser.new
  DEFAULT_PARSER = Parser.new
  DEFAULT_PARSER.pattern.each_pair do |sym, str|
    unless REGEXP::PATTERN.const_defined?(sym)
      REGEXP::PATTERN.const_set(sym, str)
    end
  end
  DEFAULT_PARSER.regexp.each_pair do |sym, str|
    const_set(sym, str)
  end

  module Util # :nodoc:
    def make_components_hash(klass, array_hash)
      tmp = {}
      if array_hash.kind_of?(Array) &&
          array_hash.size == klass.component.size - 1
        klass.component[1..-1].each_index do |i|
          begin
            tmp[klass.component[i + 1]] = array_hash[i].clone
          rescue TypeError
            tmp[klass.component[i + 1]] = array_hash[i]
          end
        end

      elsif array_hash.kind_of?(Hash)
        array_hash.each do |key, value|
          begin
            tmp[key] = value.clone
          rescue TypeError
            tmp[key] = value
          end
        end
      else
        raise ArgumentError,
          "expected Array of or Hash of components of #{klass} (#{klass.component[1..-1].join(', ')})"
      end
      tmp[:scheme] = klass.to_s.sub(/\A.*::/, '').downcase

      return tmp
    end
    module_function :make_components_hash
  end

  include REGEXP

  @@schemes = {}
  # Returns a Hash of the defined schemes.
  def self.scheme_list
    @@schemes
  end

  #
  # Construct a URI instance, using the scheme to detect the appropriate class
  # from +URI.scheme_list+.
  #
  def self.for(scheme, *arguments, default: Generic)
    if scheme
      uri_class = @@schemes[scheme.upcase] || default
    else
      uri_class = default
    end

    return uri_class.new(scheme, *arguments)
  end

  #
  # Base class for all URI exceptions.
  #
  class Error < StandardError; end
  #
  # Not a URI.
  #
  class InvalidURIError < Error; end
  #
  # Not a URI component.
  #
  class InvalidComponentError < Error; end
  #
  # URI is valid, bad usage is not.
  #
  class BadURIError < Error; end

  #
  # == Synopsis
  #
  #   URI::split(uri)
  #
  # == Args
  #
  # +uri+::
  #   String with URI.
  #
  # == Description
  #
  # Splits the string on following parts and returns array with result:
  #
  # * Scheme
  # * Userinfo
  # * Host
  # * Port
  # * Registry
  # * Path
  # * Opaque
  # * Query
  # * Fragment
  #
  # == Usage
  #
  #   require 'uri'
  #
  #   URI.split("http://www.ruby-lang.org/")
  #   # => ["http", nil, "www.ruby-lang.org", nil, nil, "/", nil, nil, nil]
  #
  def self.split(uri)
    RFC3986_PARSER.split(uri)
  end

  #
  # == Synopsis
  #
  #   URI::parse(uri_str)
  #
  # == Args
  #
  # +uri_str+::
  #   String with URI.
  #
  # == Description
  #
  # Creates one of the URI's subclasses instance from the string.
  #
  # == Raises
  #
  # URI::InvalidURIError::
  #   Raised if URI given is not a correct one.
  #
  # == Usage
  #
  #   require 'uri'
  #
  #   uri = URI.parse("http://www.ruby-lang.org/")
  #   # => #<URI::HTTP http://www.ruby-lang.org/>
  #   uri.scheme
  #   # => "http"
  #   uri.host
  #   # => "www.ruby-lang.org"
  #
  # It's recommended to first ::escape the provided +uri_str+ if there are any
  # invalid URI characters.
  #
  def self.parse(uri)
    RFC3986_PARSER.parse(uri)
  end

  #
  # == Synopsis
  #
  #   URI::join(str[, str, ...])
  #
  # == Args
  #
  # +str+::
  #   String(s) to work with, will be converted to RFC3986 URIs before merging.
  #
  # == Description
  #
  # Joins URIs.
  #
  # == Usage
  #
  #   require 'uri'
  #
  #   URI.join("http://example.com/","main.rbx")
  #   # => #<URI::HTTP http://example.com/main.rbx>
  #
  #   URI.join('http://example.com', 'foo')
  #   # => #<URI::HTTP http://example.com/foo>
  #
  #   URI.join('http://example.com', '/foo', '/bar')
  #   # => #<URI::HTTP http://example.com/bar>
  #
  #   URI.join('http://example.com', '/foo', 'bar')
  #   # => #<URI::HTTP http://example.com/bar>
  #
  #   URI.join('http://example.com', '/foo/', 'bar')
  #   # => #<URI::HTTP http://example.com/foo/bar>
  #
  def self.join(*str)
    RFC3986_PARSER.join(*str)
  end

  #
  # == Synopsis
  #
  #   URI::extract(str[, schemes][,&blk])
  #
  # == Args
  #
  # +str+::
  #   String to extract URIs from.
  # +schemes+::
  #   Limit URI matching to specific schemes.
  #
  # == Description
  #
  # Extracts URIs from a string. If block given, iterates through all matched URIs.
  # Returns nil if block given or array with matches.
  #
  # == Usage
  #
  #   require "uri"
  #
  #   URI.extract("text here http://foo.example.org/bla and here mailto:test@example.com and here also.")
  #   # => ["http://foo.example.com/bla", "mailto:test@example.com"]
  #
  def self.extract(str, schemes = nil, &block)
    warn "URI.extract is obsolete", uplevel: 1 if $VERBOSE
    DEFAULT_PARSER.extract(str, schemes, &block)
  end

  #
  # == Synopsis
  #
  #   URI::regexp([match_schemes])
  #
  # == Args
  #
  # +match_schemes+::
  #   Array of schemes. If given, resulting regexp matches to URIs
  #   whose scheme is one of the match_schemes.
  #
  # == Description
  #
  # Returns a Regexp object which matches to URI-like strings.
  # The Regexp object returned by this method includes arbitrary
  # number of capture group (parentheses).  Never rely on its number.
  #
  # == Usage
  #
  #   require 'uri'
  #
  #   # extract first URI from html_string
  #   html_string.slice(URI.regexp)
  #
  #   # remove ftp URIs
  #   html_string.sub(URI.regexp(['ftp']), '')
  #
  #   # You should not rely on the number of parentheses
  #   html_string.scan(URI.regexp) do |*matches|
  #     p $&
  #   end
  #
  def self.regexp(schemes = nil)
    warn "URI.regexp is obsolete", uplevel: 1 if $VERBOSE
    DEFAULT_PARSER.make_regexp(schemes)
  end

  TBLENCWWWCOMP_ = {} # :nodoc:
  256.times do |i|
    TBLENCWWWCOMP_[-i.chr] = -('%%%02X' % i)
  end
  TBLENCWWWCOMP_[' '] = '+'
  TBLENCWWWCOMP_.freeze
  TBLDECWWWCOMP_ = {} # :nodoc:
  256.times do |i|
    h, l = i>>4, i&15
    TBLDECWWWCOMP_[-('%%%X%X' % [h, l])] = -i.chr
    TBLDECWWWCOMP_[-('%%%x%X' % [h, l])] = -i.chr
    TBLDECWWWCOMP_[-('%%%X%x' % [h, l])] = -i.chr
    TBLDECWWWCOMP_[-('%%%x%x' % [h, l])] = -i.chr
  end
  TBLDECWWWCOMP_['+'] = ' '
  TBLDECWWWCOMP_.freeze

  # Encodes given +str+ to URL-encoded form data.
  #
  # This method doesn't convert *, -, ., 0-9, A-Z, _, a-z, but does convert SP
  # (ASCII space) to + and converts others to %XX.
  #
  # If +enc+ is given, convert +str+ to the encoding before percent encoding.
  #
  # This is an implementation of
  # https://www.w3.org/TR/2013/CR-html5-20130806/forms.html#url-encoded-form-data.
  #
  # See URI.decode_www_form_component, URI.encode_www_form.
  def self.encode_www_form_component(str, enc=nil)
    str = str.to_s.dup
    if str.encoding != Encoding::ASCII_8BIT
      if enc && enc != Encoding::ASCII_8BIT
        str.encode!(Encoding::UTF_8, invalid: :replace, undef: :replace)
        str.encode!(enc, fallback: ->(x){"&##{x.ord};"})
      end
      str.force_encoding(Encoding::ASCII_8BIT)
    end
    str.gsub!(/[^*\-.0-9A-Z_a-z]/, TBLENCWWWCOMP_)
    str.force_encoding(Encoding::US_ASCII)
  end

  # Decodes given +str+ of URL-encoded form data.
  #
  # This decodes + to SP.
  #
  # See URI.encode_www_form_component, URI.decode_www_form.
  def self.decode_www_form_component(str, enc=Encoding::UTF_8)
    raise ArgumentError, "invalid %-encoding (#{str})" if /%(?!\h\h)/ =~ str
    str.b.gsub(/\+|%\h\h/, TBLDECWWWCOMP_).force_encoding(enc)
  end

  # Generates URL-encoded form data from given +enum+.
  #
  # This generates application/x-www-form-urlencoded data defined in HTML5
  # from given an Enumerable object.
  #
  # This internally uses URI.encode_www_form_component(str).
  #
  # This method doesn't convert the encoding of given items, so convert them
  # before calling this method if you want to send data as other than original
  # encoding or mixed encoding data. (Strings which are encoded in an HTML5
  # ASCII incompatible encoding are converted to UTF-8.)
  #
  # This method doesn't handle files.  When you send a file, use
  # multipart/form-data.
  #
  # This refers https://url.spec.whatwg.org/#concept-urlencoded-serializer
  #
  #    URI.encode_www_form([["q", "ruby"], ["lang", "en"]])
  #    #=> "q=ruby&lang=en"
  #    URI.encode_www_form("q" => "ruby", "lang" => "en")
  #    #=> "q=ruby&lang=en"
  #    URI.encode_www_form("q" => ["ruby", "perl"], "lang" => "en")
  #    #=> "q=ruby&q=perl&lang=en"
  #    URI.encode_www_form([["q", "ruby"], ["q", "perl"], ["lang", "en"]])
  #    #=> "q=ruby&q=perl&lang=en"
  #
  # See URI.encode_www_form_component, URI.decode_www_form.
  def self.encode_www_form(enum, enc=nil)
    enum.map do |k,v|
      if v.nil?
        encode_www_form_component(k, enc)
      elsif v.respond_to?(:to_ary)
        v.to_ary.map do |w|
          str = encode_www_form_component(k, enc)
          unless w.nil?
            str << '='
            str << encode_www_form_component(w, enc)
          end
        end.join('&')
      else
        str = encode_www_form_component(k, enc)
        str << '='
        str << encode_www_form_component(v, enc)
      end
    end.join('&')
  end

  # Decodes URL-encoded form data from given +str+.
  #
  # This decodes application/x-www-form-urlencoded data
  # and returns an array of key-value arrays.
  #
  # This refers http://url.spec.whatwg.org/#concept-urlencoded-parser,
  # so this supports only &-separator, and doesn't support ;-separator.
  #
  #    ary = URI.decode_www_form("a=1&a=2&b=3")
  #    ary                   #=> [['a', '1'], ['a', '2'], ['b', '3']]
  #    ary.assoc('a').last   #=> '1'
  #    ary.assoc('b').last   #=> '3'
  #    ary.rassoc('a').last  #=> '2'
  #    Hash[ary]             #=> {"a"=>"2", "b"=>"3"}
  #
  # See URI.decode_www_form_component, URI.encode_www_form.
  def self.decode_www_form(str, enc=Encoding::UTF_8, separator: '&', use__charset_: false, isindex: false)
    raise ArgumentError, "the input of #{self.name}.#{__method__} must be ASCII only string" unless str.ascii_only?
    ary = []
    return ary if str.empty?
    enc = Encoding.find(enc)
    str.b.each_line(separator) do |string|
      string.chomp!(separator)
      key, sep, val = string.partition('=')
      if isindex
        if sep.empty?
          val = key
          key = +''
        end
        isindex = false
      end

      if use__charset_ and key == '_charset_' and e = get_encoding(val)
        enc = e
        use__charset_ = false
      end

      key.gsub!(/\+|%\h\h/, TBLDECWWWCOMP_)
      if val
        val.gsub!(/\+|%\h\h/, TBLDECWWWCOMP_)
      else
        val = +''
      end

      ary << [key, val]
    end
    ary.each do |k, v|
      k.force_encoding(enc)
      k.scrub!
      v.force_encoding(enc)
      v.scrub!
    end
    ary
  end

  private
=begin command for WEB_ENCODINGS_
  curl https://encoding.spec.whatwg.org/encodings.json|
  ruby -rjson -e 'H={}
  h={
    "shift_jis"=>"Windows-31J",
    "euc-jp"=>"cp51932",
    "iso-2022-jp"=>"cp50221",
    "x-mac-cyrillic"=>"macCyrillic",
  }
  JSON($<.read).map{|x|x["encodings"]}.flatten.each{|x|
    Encoding.find(n=h.fetch(n=x["name"].downcase,n))rescue next
    x["labels"].each{|y|H[y]=n}
  }
  puts "{"
  H.each{|k,v|puts %[  #{k.dump}=>#{v.dump},]}
  puts "}"
'
=end
  WEB_ENCODINGS_ = {
    "unicode-1-1-utf-8"=>"utf-8",
    "utf-8"=>"utf-8",
    "utf8"=>"utf-8",
    "866"=>"ibm866",
    "cp866"=>"ibm866",
    "csibm866"=>"ibm866",
    "ibm866"=>"ibm866",
    "csisolatin2"=>"iso-8859-2",
    "iso-8859-2"=>"iso-8859-2",
    "iso-ir-101"=>"iso-8859-2",
    "iso8859-2"=>"iso-8859-2",
    "iso88592"=>"iso-8859-2",
    "iso_8859-2"=>"iso-8859-2",
    "iso_8859-2:1987"=>"iso-8859-2",
    "l2"=>"iso-8859-2",
    "latin2"=>"iso-8859-2",
    "csisolatin3"=>"iso-8859-3",
    "iso-8859-3"=>"iso-8859-3",
    "iso-ir-109"=>"iso-8859-3",
    "iso8859-3"=>"iso-8859-3",
    "iso88593"=>"iso-8859-3",
    "iso_8859-3"=>"iso-8859-3",
    "iso_8859-3:1988"=>"iso-8859-3",
    "l3"=>"iso-8859-3",
    "latin3"=>"iso-8859-3",
    "csisolatin4"=>"iso-8859-4",
    "iso-8859-4"=>"iso-8859-4",
    "iso-ir-110"=>"iso-8859-4",
    "iso8859-4"=>"iso-8859-4",
    "iso88594"=>"iso-8859-4",
    "iso_8859-4"=>"iso-8859-4",
    "iso_8859-4:1988"=>"iso-8859-4",
    "l4"=>"iso-8859-4",
    "latin4"=>"iso-8859-4",
    "csisolatincyrillic"=>"iso-8859-5",
    "cyrillic"=>"iso-8859-5",
    "iso-8859-5"=>"iso-8859-5",
    "iso-ir-144"=>"iso-8859-5",
    "iso8859-5"=>"iso-8859-5",
    "iso88595"=>"iso-8859-5",
    "iso_8859-5"=>"iso-8859-5",
    "iso_8859-5:1988"=>"iso-8859-5",
    "arabic"=>"iso-8859-6",
    "asmo-708"=>"iso-8859-6",
    "csiso88596e"=>"iso-8859-6",
    "csiso88596i"=>"iso-8859-6",
    "csisolatinarabic"=>"iso-8859-6",
    "ecma-114"=>"iso-8859-6",
    "iso-8859-6"=>"iso-8859-6",
    "iso-8859-6-e"=>"iso-8859-6",
    "iso-8859-6-i"=>"iso-8859-6",
    "iso-ir-127"=>"iso-8859-6",
    "iso8859-6"=>"iso-8859-6",
    "iso88596"=>"iso-8859-6",
    "iso_8859-6"=>"iso-8859-6",
    "iso_8859-6:1987"=>"iso-8859-6",
    "csisolatingreek"=>"iso-8859-7",
    "ecma-118"=>"iso-8859-7",
    "elot_928"=>"iso-8859-7",
    "greek"=>"iso-8859-7",
    "greek8"=>"iso-8859-7",
    "iso-8859-7"=>"iso-8859-7",
    "iso-ir-126"=>"iso-8859-7",
    "iso8859-7"=>"iso-8859-7",
    "iso88597"=>"iso-8859-7",
    "iso_8859-7"=>"iso-8859-7",
    "iso_8859-7:1987"=>"iso-8859-7",
    "sun_eu_greek"=>"iso-8859-7",
    "csiso88598e"=>"iso-8859-8",
    "csisolatinhebrew"=>"iso-8859-8",
    "hebrew"=>"iso-8859-8",
    "iso-8859-8"=>"iso-8859-8",
    "iso-8859-8-e"=>"iso-8859-8",
    "iso-ir-138"=>"iso-8859-8",
    "iso8859-8"=>"iso-8859-8",
    "iso88598"=>"iso-8859-8",
    "iso_8859-8"=>"iso-8859-8",
    "iso_8859-8:1988"=>"iso-8859-8",
    "visual"=>"iso-8859-8",
    "csisolatin6"=>"iso-8859-10",
    "iso-8859-10"=>"iso-8859-10",
    "iso-ir-157"=>"iso-8859-10",
    "iso8859-10"=>"iso-8859-10",
    "iso885910"=>"iso-8859-10",
    "l6"=>"iso-8859-10",
    "latin6"=>"iso-8859-10",
    "iso-8859-13"=>"iso-8859-13",
    "iso8859-13"=>"iso-8859-13",
    "iso885913"=>"iso-8859-13",
    "iso-8859-14"=>"iso-8859-14",
    "iso8859-14"=>"iso-8859-14",
    "iso885914"=>"iso-8859-14",
    "csisolatin9"=>"iso-8859-15",
    "iso-8859-15"=>"iso-8859-15",
    "iso8859-15"=>"iso-8859-15",
    "iso885915"=>"iso-8859-15",
    "iso_8859-15"=>"iso-8859-15",
    "l9"=>"iso-8859-15",
    "iso-8859-16"=>"iso-8859-16",
    "cskoi8r"=>"koi8-r",
    "koi"=>"koi8-r",
    "koi8"=>"koi8-r",
    "koi8-r"=>"koi8-r",
    "koi8_r"=>"koi8-r",
    "koi8-ru"=>"koi8-u",
    "koi8-u"=>"koi8-u",
    "dos-874"=>"windows-874",
    "iso-8859-11"=>"windows-874",
    "iso8859-11"=>"windows-874",
    "iso885911"=>"windows-874",
    "tis-620"=>"windows-874",
    "windows-874"=>"windows-874",
    "cp1250"=>"windows-1250",
    "windows-1250"=>"windows-1250",
    "x-cp1250"=>"windows-1250",
    "cp1251"=>"windows-1251",
    "windows-1251"=>"windows-1251",
    "x-cp1251"=>"windows-1251",
    "ansi_x3.4-1968"=>"windows-1252",
    "ascii"=>"windows-1252",
    "cp1252"=>"windows-1252",
    "cp819"=>"windows-1252",
    "csisolatin1"=>"windows-1252",
    "ibm819"=>"windows-1252",
    "iso-8859-1"=>"windows-1252",
    "iso-ir-100"=>"windows-1252",
    "iso8859-1"=>"windows-1252",
    "iso88591"=>"windows-1252",
    "iso_8859-1"=>"windows-1252",
    "iso_8859-1:1987"=>"windows-1252",
    "l1"=>"windows-1252",
    "latin1"=>"windows-1252",
    "us-ascii"=>"windows-1252",
    "windows-1252"=>"windows-1252",
    "x-cp1252"=>"windows-1252",
    "cp1253"=>"windows-1253",
    "windows-1253"=>"windows-1253",
    "x-cp1253"=>"windows-1253",
    "cp1254"=>"windows-1254",
    "csisolatin5"=>"windows-1254",
    "iso-8859-9"=>"windows-1254",
    "iso-ir-148"=>"windows-1254",
    "iso8859-9"=>"windows-1254",
    "iso88599"=>"windows-1254",
    "iso_8859-9"=>"windows-1254",
    "iso_8859-9:1989"=>"windows-1254",
    "l5"=>"windows-1254",
    "latin5"=>"windows-1254",
    "windows-1254"=>"windows-1254",
    "x-cp1254"=>"windows-1254",
    "cp1255"=>"windows-1255",
    "windows-1255"=>"windows-1255",
    "x-cp1255"=>"windows-1255",
    "cp1256"=>"windows-1256",
    "windows-1256"=>"windows-1256",
    "x-cp1256"=>"windows-1256",
    "cp1257"=>"windows-1257",
    "windows-1257"=>"windows-1257",
    "x-cp1257"=>"windows-1257",
    "cp1258"=>"windows-1258",
    "windows-1258"=>"windows-1258",
    "x-cp1258"=>"windows-1258",
    "x-mac-cyrillic"=>"macCyrillic",
    "x-mac-ukrainian"=>"macCyrillic",
    "chinese"=>"gbk",
    "csgb2312"=>"gbk",
    "csiso58gb231280"=>"gbk",
    "gb2312"=>"gbk",
    "gb_2312"=>"gbk",
    "gb_2312-80"=>"gbk",
    "gbk"=>"gbk",
    "iso-ir-58"=>"gbk",
    "x-gbk"=>"gbk",
    "gb18030"=>"gb18030",
    "big5"=>"big5",
    "big5-hkscs"=>"big5",
    "cn-big5"=>"big5",
    "csbig5"=>"big5",
    "x-x-big5"=>"big5",
    "cseucpkdfmtjapanese"=>"cp51932",
    "euc-jp"=>"cp51932",
    "x-euc-jp"=>"cp51932",
    "csiso2022jp"=>"cp50221",
    "iso-2022-jp"=>"cp50221",
    "csshiftjis"=>"Windows-31J",
    "ms932"=>"Windows-31J",
    "ms_kanji"=>"Windows-31J",
    "shift-jis"=>"Windows-31J",
    "shift_jis"=>"Windows-31J",
    "sjis"=>"Windows-31J",
    "windows-31j"=>"Windows-31J",
    "x-sjis"=>"Windows-31J",
    "cseuckr"=>"euc-kr",
    "csksc56011987"=>"euc-kr",
    "euc-kr"=>"euc-kr",
    "iso-ir-149"=>"euc-kr",
    "korean"=>"euc-kr",
    "ks_c_5601-1987"=>"euc-kr",
    "ks_c_5601-1989"=>"euc-kr",
    "ksc5601"=>"euc-kr",
    "ksc_5601"=>"euc-kr",
    "windows-949"=>"euc-kr",
    "utf-16be"=>"utf-16be",
    "utf-16"=>"utf-16le",
    "utf-16le"=>"utf-16le",
  } # :nodoc:

  # :nodoc:
  # return encoding or nil
  # http://encoding.spec.whatwg.org/#concept-encoding-get
  def self.get_encoding(label)
    Encoding.find(WEB_ENCODINGS_[label.to_str.strip.downcase]) rescue nil
  end
end # module URI

module Kernel

  #
  # Returns +uri+ converted to an URI object.
  #
  def URI(uri)
    if uri.is_a?(URI::Generic)
      uri
    elsif uri = String.try_convert(uri)
      URI.parse(uri)
    else
      raise ArgumentError,
        "bad argument (expected URI object or URI string)"
    end
  end
  module_function :URI
end
# frozen_string_literal: false
module URI
  class RFC3986_Parser # :nodoc:
    # URI defined in RFC3986
    # this regexp is modified not to host is not empty string
    RFC3986_URI = /\A(?<URI>(?<scheme>[A-Za-z][+\-.0-9A-Za-z]*+):(?<hier-part>\/\/(?<authority>(?:(?<userinfo>(?:%\h\h|[!$&-.0-;=A-Z_a-z~])*+)@)?(?<host>(?<IP-literal>\[(?:(?<IPv6address>(?:\h{1,4}:){6}(?<ls32>\h{1,4}:\h{1,4}|(?<IPv4address>(?<dec-octet>[1-9]\d|1\d{2}|2[0-4]\d|25[0-5]|\d)\.\g<dec-octet>\.\g<dec-octet>\.\g<dec-octet>))|::(?:\h{1,4}:){5}\g<ls32>|\h{1,4}?::(?:\h{1,4}:){4}\g<ls32>|(?:(?:\h{1,4}:)?\h{1,4})?::(?:\h{1,4}:){3}\g<ls32>|(?:(?:\h{1,4}:){,2}\h{1,4})?::(?:\h{1,4}:){2}\g<ls32>|(?:(?:\h{1,4}:){,3}\h{1,4})?::\h{1,4}:\g<ls32>|(?:(?:\h{1,4}:){,4}\h{1,4})?::\g<ls32>|(?:(?:\h{1,4}:){,5}\h{1,4})?::\h{1,4}|(?:(?:\h{1,4}:){,6}\h{1,4})?::)|(?<IPvFuture>v\h++\.[!$&-.0-;=A-Z_a-z~]++))\])|\g<IPv4address>|(?<reg-name>(?:%\h\h|[!$&-.0-9;=A-Z_a-z~])++))?(?::(?<port>\d*+))?)(?<path-abempty>(?:\/(?<segment>(?:%\h\h|[!$&-.0-;=@-Z_a-z~])*+))*+)|(?<path-absolute>\/(?:(?<segment-nz>(?:%\h\h|[!$&-.0-;=@-Z_a-z~])++)(?:\/\g<segment>)*+)?)|(?<path-rootless>\g<segment-nz>(?:\/\g<segment>)*+)|(?<path-empty>))(?:\?(?<query>[^#]*+))?(?:\#(?<fragment>(?:%\h\h|[!$&-.0-;=@-Z_a-z~\/?])*+))?)\z/
    RFC3986_relative_ref = /\A(?<relative-ref>(?<relative-part>\/\/(?<authority>(?:(?<userinfo>(?:%\h\h|[!$&-.0-;=A-Z_a-z~])*+)@)?(?<host>(?<IP-literal>\[(?:(?<IPv6address>(?:\h{1,4}:){6}(?<ls32>\h{1,4}:\h{1,4}|(?<IPv4address>(?<dec-octet>[1-9]\d|1\d{2}|2[0-4]\d|25[0-5]|\d)\.\g<dec-octet>\.\g<dec-octet>\.\g<dec-octet>))|::(?:\h{1,4}:){5}\g<ls32>|\h{1,4}?::(?:\h{1,4}:){4}\g<ls32>|(?:(?:\h{1,4}:){,1}\h{1,4})?::(?:\h{1,4}:){3}\g<ls32>|(?:(?:\h{1,4}:){,2}\h{1,4})?::(?:\h{1,4}:){2}\g<ls32>|(?:(?:\h{1,4}:){,3}\h{1,4})?::\h{1,4}:\g<ls32>|(?:(?:\h{1,4}:){,4}\h{1,4})?::\g<ls32>|(?:(?:\h{1,4}:){,5}\h{1,4})?::\h{1,4}|(?:(?:\h{1,4}:){,6}\h{1,4})?::)|(?<IPvFuture>v\h++\.[!$&-.0-;=A-Z_a-z~]++))\])|\g<IPv4address>|(?<reg-name>(?:%\h\h|[!$&-.0-9;=A-Z_a-z~])++))?(?::(?<port>\d*+))?)(?<path-abempty>(?:\/(?<segment>(?:%\h\h|[!$&-.0-;=@-Z_a-z~])*+))*+)|(?<path-absolute>\/(?:(?<segment-nz>(?:%\h\h|[!$&-.0-;=@-Z_a-z~])++)(?:\/\g<segment>)*+)?)|(?<path-noscheme>(?<segment-nz-nc>(?:%\h\h|[!$&-.0-9;=@-Z_a-z~])++)(?:\/\g<segment>)*+)|(?<path-empty>))(?:\?(?<query>[^#]*+))?(?:\#(?<fragment>(?:%\h\h|[!$&-.0-;=@-Z_a-z~\/?])*+))?)\z/
    attr_reader :regexp

    def initialize
      @regexp = default_regexp.each_value(&:freeze).freeze
    end

    def split(uri) #:nodoc:
      begin
        uri = uri.to_str
      rescue NoMethodError
        raise InvalidURIError, "bad URI(is not URI?): #{uri.inspect}"
      end
      uri.ascii_only? or
        raise InvalidURIError, "URI must be ascii only #{uri.dump}"
      if m = RFC3986_URI.match(uri)
        query = m["query".freeze]
        scheme = m["scheme".freeze]
        opaque = m["path-rootless".freeze]
        if opaque
          opaque << "?#{query}" if query
          [ scheme,
            nil, # userinfo
            nil, # host
            nil, # port
            nil, # registry
            nil, # path
            opaque,
            nil, # query
            m["fragment".freeze]
          ]
        else # normal
          [ scheme,
            m["userinfo".freeze],
            m["host".freeze],
            m["port".freeze],
            nil, # registry
            (m["path-abempty".freeze] ||
             m["path-absolute".freeze] ||
             m["path-empty".freeze]),
            nil, # opaque
            query,
            m["fragment".freeze]
          ]
        end
      elsif m = RFC3986_relative_ref.match(uri)
        [ nil, # scheme
          m["userinfo".freeze],
          m["host".freeze],
          m["port".freeze],
          nil, # registry,
          (m["path-abempty".freeze] ||
           m["path-absolute".freeze] ||
           m["path-noscheme".freeze] ||
           m["path-empty".freeze]),
          nil, # opaque
          m["query".freeze],
          m["fragment".freeze]
        ]
      else
        raise InvalidURIError, "bad URI(is not URI?): #{uri.inspect}"
      end
    end

    def parse(uri) # :nodoc:
      URI.for(*self.split(uri), self)
    end


    def join(*uris) # :nodoc:
      uris[0] = convert_to_uri(uris[0])
      uris.inject :merge
    end

    @@to_s = Kernel.instance_method(:to_s)
    def inspect
      @@to_s.bind_call(self)
    end

    private

    def default_regexp # :nodoc:
      {
        SCHEME: /\A[A-Za-z][A-Za-z0-9+\-.]*\z/,
        USERINFO: /\A(?:%\h\h|[!$&-.0-;=A-Z_a-z~])*\z/,
        HOST: /\A(?:(?<IP-literal>\[(?:(?<IPv6address>(?:\h{1,4}:){6}(?<ls32>\h{1,4}:\h{1,4}|(?<IPv4address>(?<dec-octet>[1-9]\d|1\d{2}|2[0-4]\d|25[0-5]|\d)\.\g<dec-octet>\.\g<dec-octet>\.\g<dec-octet>))|::(?:\h{1,4}:){5}\g<ls32>|\h{,4}::(?:\h{1,4}:){4}\g<ls32>|(?:(?:\h{1,4}:)?\h{1,4})?::(?:\h{1,4}:){3}\g<ls32>|(?:(?:\h{1,4}:){,2}\h{1,4})?::(?:\h{1,4}:){2}\g<ls32>|(?:(?:\h{1,4}:){,3}\h{1,4})?::\h{1,4}:\g<ls32>|(?:(?:\h{1,4}:){,4}\h{1,4})?::\g<ls32>|(?:(?:\h{1,4}:){,5}\h{1,4})?::\h{1,4}|(?:(?:\h{1,4}:){,6}\h{1,4})?::)|(?<IPvFuture>v\h+\.[!$&-.0-;=A-Z_a-z~]+))\])|\g<IPv4address>|(?<reg-name>(?:%\h\h|[!$&-.0-9;=A-Z_a-z~])*))\z/,
        ABS_PATH: /\A\/(?:%\h\h|[!$&-.0-;=@-Z_a-z~])*(?:\/(?:%\h\h|[!$&-.0-;=@-Z_a-z~])*)*\z/,
        REL_PATH: /\A(?:%\h\h|[!$&-.0-;=@-Z_a-z~])+(?:\/(?:%\h\h|[!$&-.0-;=@-Z_a-z~])*)*\z/,
        QUERY: /\A(?:%\h\h|[!$&-.0-;=@-Z_a-z~\/?])*\z/,
        FRAGMENT: /\A(?:%\h\h|[!$&-.0-;=@-Z_a-z~\/?])*\z/,
        OPAQUE: /\A(?:[^\/].*)?\z/,
        PORT: /\A[\x09\x0a\x0c\x0d ]*+\d*[\x09\x0a\x0c\x0d ]*\z/,
      }
    end

    def convert_to_uri(uri)
      if uri.is_a?(URI::Generic)
        uri
      elsif uri = String.try_convert(uri)
        parse(uri)
      else
        raise ArgumentError,
          "bad argument (expected URI object or URI string)"
      end
    end

  end # class Parser
end # module URI
# frozen_string_literal: false
# = uri/http.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# License:: You can redistribute it and/or modify it under the same term as Ruby.
#
# See URI for general documentation
#

require_relative 'generic'

module URI

  #
  # The syntax of HTTP URIs is defined in RFC1738 section 3.3.
  #
  # Note that the Ruby URI library allows HTTP URLs containing usernames and
  # passwords. This is not legal as per the RFC, but used to be
  # supported in Internet Explorer 5 and 6, before the MS04-004 security
  # update. See <URL:http://support.microsoft.com/kb/834489>.
  #
  class HTTP < Generic
    # A Default port of 80 for URI::HTTP.
    DEFAULT_PORT = 80

    # An Array of the available components for URI::HTTP.
    COMPONENT = %i[
      scheme
      userinfo host port
      path
      query
      fragment
    ].freeze

    #
    # == Description
    #
    # Creates a new URI::HTTP object from components, with syntax checking.
    #
    # The components accepted are userinfo, host, port, path, query, and
    # fragment.
    #
    # The components should be provided either as an Array, or as a Hash
    # with keys formed by preceding the component names with a colon.
    #
    # If an Array is used, the components must be passed in the
    # order <code>[userinfo, host, port, path, query, fragment]</code>.
    #
    # Example:
    #
    #     uri = URI::HTTP.build(host: 'www.example.com', path: '/foo/bar')
    #
    #     uri = URI::HTTP.build([nil, "www.example.com", nil, "/path",
    #       "query", 'fragment'])
    #
    # Currently, if passed userinfo components this method generates
    # invalid HTTP URIs as per RFC 1738.
    #
    def self.build(args)
      tmp = Util.make_components_hash(self, args)
      super(tmp)
    end

    #
    # == Description
    #
    # Returns the full path for an HTTP request, as required by Net::HTTP::Get.
    #
    # If the URI contains a query, the full path is URI#path + '?' + URI#query.
    # Otherwise, the path is simply URI#path.
    #
    # Example:
    #
    #     uri = URI::HTTP.build(path: '/foo/bar', query: 'test=true')
    #     uri.request_uri #  => "/foo/bar?test=true"
    #
    def request_uri
      return unless @path

      url = @query ? "#@path?#@query" : @path.dup
      url.start_with?(?/.freeze) ? url : ?/ + url
    end
  end

  @@schemes['HTTP'] = HTTP

end
# frozen_string_literal: false
# = uri/ws.rb
#
# Author:: Matt Muller <mamuller@amazon.com>
# License:: You can redistribute it and/or modify it under the same term as Ruby.
#
# See URI for general documentation
#

require_relative 'generic'

module URI

  #
  # The syntax of WS URIs is defined in RFC6455 section 3.
  #
  # Note that the Ruby URI library allows WS URLs containing usernames and
  # passwords. This is not legal as per the RFC, but used to be
  # supported in Internet Explorer 5 and 6, before the MS04-004 security
  # update. See <URL:http://support.microsoft.com/kb/834489>.
  #
  class WS < Generic
    # A Default port of 80 for URI::WS.
    DEFAULT_PORT = 80

    # An Array of the available components for URI::WS.
    COMPONENT = %i[
      scheme
      userinfo host port
      path
      query
    ].freeze

    #
    # == Description
    #
    # Creates a new URI::WS object from components, with syntax checking.
    #
    # The components accepted are userinfo, host, port, path, and query.
    #
    # The components should be provided either as an Array, or as a Hash
    # with keys formed by preceding the component names with a colon.
    #
    # If an Array is used, the components must be passed in the
    # order <code>[userinfo, host, port, path, query]</code>.
    #
    # Example:
    #
    #     uri = URI::WS.build(host: 'www.example.com', path: '/foo/bar')
    #
    #     uri = URI::WS.build([nil, "www.example.com", nil, "/path", "query"])
    #
    # Currently, if passed userinfo components this method generates
    # invalid WS URIs as per RFC 1738.
    #
    def self.build(args)
      tmp = Util.make_components_hash(self, args)
      super(tmp)
    end

    #
    # == Description
    #
    # Returns the full path for a WS URI, as required by Net::HTTP::Get.
    #
    # If the URI contains a query, the full path is URI#path + '?' + URI#query.
    # Otherwise, the path is simply URI#path.
    #
    # Example:
    #
    #     uri = URI::WS.build(path: '/foo/bar', query: 'test=true')
    #     uri.request_uri #  => "/foo/bar?test=true"
    #
    def request_uri
      return unless @path

      url = @query ? "#@path?#@query" : @path.dup
      url.start_with?(?/.freeze) ? url : ?/ + url
    end
  end

  @@schemes['WS'] = WS

end
# frozen_string_literal: false
# = uri/ldap.rb
#
# License:: You can redistribute it and/or modify it under the same term as Ruby.
#
# See URI for general documentation
#

require_relative 'ldap'

module URI

  # The default port for LDAPS URIs is 636, and the scheme is 'ldaps:' rather
  # than 'ldap:'. Other than that, LDAPS URIs are identical to LDAP URIs;
  # see URI::LDAP.
  class LDAPS < LDAP
    # A Default port of 636 for URI::LDAPS
    DEFAULT_PORT = 636
  end
  @@schemes['LDAPS'] = LDAPS
end
# frozen_string_literal: false
# = uri/mailto.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# License:: You can redistribute it and/or modify it under the same term as Ruby.
#
# See URI for general documentation
#

require_relative 'generic'

module URI

  #
  # RFC6068, the mailto URL scheme.
  #
  class MailTo < Generic
    include REGEXP

    # A Default port of nil for URI::MailTo.
    DEFAULT_PORT = nil

    # An Array of the available components for URI::MailTo.
    COMPONENT = [ :scheme, :to, :headers ].freeze

    # :stopdoc:
    #  "hname" and "hvalue" are encodings of an RFC 822 header name and
    #  value, respectively. As with "to", all URL reserved characters must
    #  be encoded.
    #
    #  "#mailbox" is as specified in RFC 822 [RFC822]. This means that it
    #  consists of zero or more comma-separated mail addresses, possibly
    #  including "phrase" and "comment" components. Note that all URL
    #  reserved characters in "to" must be encoded: in particular,
    #  parentheses, commas, and the percent sign ("%"), which commonly occur
    #  in the "mailbox" syntax.
    #
    #  Within mailto URLs, the characters "?", "=", "&" are reserved.

    # ; RFC 6068
    # hfields      = "?" hfield *( "&" hfield )
    # hfield       = hfname "=" hfvalue
    # hfname       = *qchar
    # hfvalue      = *qchar
    # qchar        = unreserved / pct-encoded / some-delims
    # some-delims  = "!" / "$" / "'" / "(" / ")" / "*"
    #              / "+" / "," / ";" / ":" / "@"
    #
    # ; RFC3986
    # unreserved   = ALPHA / DIGIT / "-" / "." / "_" / "~"
    # pct-encoded  = "%" HEXDIG HEXDIG
    HEADER_REGEXP  = /\A(?<hfield>(?:%\h\h|[!$'-.0-;@-Z_a-z~])*=(?:%\h\h|[!$'-.0-;@-Z_a-z~])*)(?:&\g<hfield>)*\z/
    # practical regexp for email address
    # https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
    EMAIL_REGEXP = /\A[a-zA-Z0-9.!\#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\z/
    # :startdoc:

    #
    # == Description
    #
    # Creates a new URI::MailTo object from components, with syntax checking.
    #
    # Components can be provided as an Array or Hash. If an Array is used,
    # the components must be supplied as <code>[to, headers]</code>.
    #
    # If a Hash is used, the keys are the component names preceded by colons.
    #
    # The headers can be supplied as a pre-encoded string, such as
    # <code>"subject=subscribe&cc=address"</code>, or as an Array of Arrays
    # like <code>[['subject', 'subscribe'], ['cc', 'address']]</code>.
    #
    # Examples:
    #
    #    require 'uri'
    #
    #    m1 = URI::MailTo.build(['joe@example.com', 'subject=Ruby'])
    #    m1.to_s  # => "mailto:joe@example.com?subject=Ruby"
    #
    #    m2 = URI::MailTo.build(['john@example.com', [['Subject', 'Ruby'], ['Cc', 'jack@example.com']]])
    #    m2.to_s  # => "mailto:john@example.com?Subject=Ruby&Cc=jack@example.com"
    #
    #    m3 = URI::MailTo.build({:to => 'listman@example.com', :headers => [['subject', 'subscribe']]})
    #    m3.to_s  # => "mailto:listman@example.com?subject=subscribe"
    #
    def self.build(args)
      tmp = Util.make_components_hash(self, args)

      case tmp[:to]
      when Array
        tmp[:opaque] = tmp[:to].join(',')
      when String
        tmp[:opaque] = tmp[:to].dup
      else
        tmp[:opaque] = ''
      end

      if tmp[:headers]
        query =
          case tmp[:headers]
          when Array
            tmp[:headers].collect { |x|
              if x.kind_of?(Array)
                x[0] + '=' + x[1..-1].join
              else
                x.to_s
              end
            }.join('&')
          when Hash
            tmp[:headers].collect { |h,v|
              h + '=' + v
            }.join('&')
          else
            tmp[:headers].to_s
          end
        unless query.empty?
          tmp[:opaque] << '?' << query
        end
      end

      super(tmp)
    end

    #
    # == Description
    #
    # Creates a new URI::MailTo object from generic URL components with
    # no syntax checking.
    #
    # This method is usually called from URI::parse, which checks
    # the validity of each component.
    #
    def initialize(*arg)
      super(*arg)

      @to = nil
      @headers = []

      # The RFC3986 parser does not normally populate opaque
      @opaque = "?#{@query}" if @query && !@opaque

      unless @opaque
        raise InvalidComponentError,
          "missing opaque part for mailto URL"
      end
      to, header = @opaque.split('?', 2)
      # allow semicolon as a addr-spec separator
      # http://support.microsoft.com/kb/820868
      unless /\A(?:[^@,;]+@[^@,;]+(?:\z|[,;]))*\z/ =~ to
        raise InvalidComponentError,
          "unrecognised opaque part for mailtoURL: #{@opaque}"
      end

      if arg[10] # arg_check
        self.to = to
        self.headers = header
      else
        set_to(to)
        set_headers(header)
      end
    end

    # The primary e-mail address of the URL, as a String.
    attr_reader :to

    # E-mail headers set by the URL, as an Array of Arrays.
    attr_reader :headers

    # Checks the to +v+ component.
    def check_to(v)
      return true unless v
      return true if v.size == 0

      v.split(/[,;]/).each do |addr|
        # check url safety as path-rootless
        if /\A(?:%\h\h|[!$&-.0-;=@-Z_a-z~])*\z/ !~ addr
          raise InvalidComponentError,
            "an address in 'to' is invalid as URI #{addr.dump}"
        end

        # check addr-spec
        # don't s/\+/ /g
        addr.gsub!(/%\h\h/, URI::TBLDECWWWCOMP_)
        if EMAIL_REGEXP !~ addr
          raise InvalidComponentError,
            "an address in 'to' is invalid as uri-escaped addr-spec #{addr.dump}"
        end
      end

      true
    end
    private :check_to

    # Private setter for to +v+.
    def set_to(v)
      @to = v
    end
    protected :set_to

    # Setter for to +v+.
    def to=(v)
      check_to(v)
      set_to(v)
      v
    end

    # Checks the headers +v+ component against either
    # * HEADER_REGEXP
    def check_headers(v)
      return true unless v
      return true if v.size == 0
      if HEADER_REGEXP !~ v
        raise InvalidComponentError,
          "bad component(expected opaque component): #{v}"
      end

      true
    end
    private :check_headers

    # Private setter for headers +v+.
    def set_headers(v)
      @headers = []
      if v
        v.split('&').each do |x|
          @headers << x.split(/=/, 2)
        end
      end
    end
    protected :set_headers

    # Setter for headers +v+.
    def headers=(v)
      check_headers(v)
      set_headers(v)
      v
    end

    # Constructs String from URI.
    def to_s
      @scheme + ':' +
        if @to
          @to
        else
          ''
        end +
        if @headers.size > 0
          '?' + @headers.collect{|x| x.join('=')}.join('&')
        else
          ''
        end +
        if @fragment
          '#' + @fragment
        else
          ''
        end
    end

    # Returns the RFC822 e-mail text equivalent of the URL, as a String.
    #
    # Example:
    #
    #   require 'uri'
    #
    #   uri = URI.parse("mailto:ruby-list@ruby-lang.org?Subject=subscribe&cc=myaddr")
    #   uri.to_mailtext
    #   # => "To: ruby-list@ruby-lang.org\nSubject: subscribe\nCc: myaddr\n\n\n"
    #
    def to_mailtext
      to = URI.decode_www_form_component(@to)
      head = ''
      body = ''
      @headers.each do |x|
        case x[0]
        when 'body'
          body = URI.decode_www_form_component(x[1])
        when 'to'
          to << ', ' + URI.decode_www_form_component(x[1])
        else
          head << URI.decode_www_form_component(x[0]).capitalize + ': ' +
            URI.decode_www_form_component(x[1])  + "\n"
        end
      end

      "To: #{to}
#{head}
#{body}
"
    end
    alias to_rfc822text to_mailtext
  end

  @@schemes['MAILTO'] = MailTo
end
# frozen_string_literal: false
# = uri/ldap.rb
#
# Author::
#  Takaaki Tateishi <ttate@jaist.ac.jp>
#  Akira Yamada <akira@ruby-lang.org>
# License::
#   URI::LDAP is copyrighted free software by Takaaki Tateishi and Akira Yamada.
#   You can redistribute it and/or modify it under the same term as Ruby.
#
# See URI for general documentation
#

require_relative 'generic'

module URI

  #
  # LDAP URI SCHEMA (described in RFC2255).
  #--
  # ldap://<host>/<dn>[?<attrs>[?<scope>[?<filter>[?<extensions>]]]]
  #++
  class LDAP < Generic

    # A Default port of 389 for URI::LDAP.
    DEFAULT_PORT = 389

    # An Array of the available components for URI::LDAP.
    COMPONENT = [
      :scheme,
      :host, :port,
      :dn,
      :attributes,
      :scope,
      :filter,
      :extensions,
    ].freeze

    # Scopes available for the starting point.
    #
    # * SCOPE_BASE - the Base DN
    # * SCOPE_ONE  - one level under the Base DN, not including the base DN and
    #   not including any entries under this
    # * SCOPE_SUB  - subtrees, all entries at all levels
    #
    SCOPE = [
      SCOPE_ONE = 'one',
      SCOPE_SUB = 'sub',
      SCOPE_BASE = 'base',
    ].freeze

    #
    # == Description
    #
    # Creates a new URI::LDAP object from components, with syntax checking.
    #
    # The components accepted are host, port, dn, attributes,
    # scope, filter, and extensions.
    #
    # The components should be provided either as an Array, or as a Hash
    # with keys formed by preceding the component names with a colon.
    #
    # If an Array is used, the components must be passed in the
    # order <code>[host, port, dn, attributes, scope, filter, extensions]</code>.
    #
    # Example:
    #
    #     uri = URI::LDAP.build({:host => 'ldap.example.com',
    #       :dn => '/dc=example'})
    #
    #     uri = URI::LDAP.build(["ldap.example.com", nil,
    #       "/dc=example;dc=com", "query", nil, nil, nil])
    #
    def self.build(args)
      tmp = Util::make_components_hash(self, args)

      if tmp[:dn]
        tmp[:path] = tmp[:dn]
      end

      query = []
      [:extensions, :filter, :scope, :attributes].collect do |x|
        next if !tmp[x] && query.size == 0
        query.unshift(tmp[x])
      end

      tmp[:query] = query.join('?')

      return super(tmp)
    end

    #
    # == Description
    #
    # Creates a new URI::LDAP object from generic URI components as per
    # RFC 2396. No LDAP-specific syntax checking is performed.
    #
    # Arguments are +scheme+, +userinfo+, +host+, +port+, +registry+, +path+,
    # +opaque+, +query+, and +fragment+, in that order.
    #
    # Example:
    #
    #     uri = URI::LDAP.new("ldap", nil, "ldap.example.com", nil, nil,
    #       "/dc=example;dc=com", nil, "query", nil)
    #
    # See also URI::Generic.new.
    #
    def initialize(*arg)
      super(*arg)

      if @fragment
        raise InvalidURIError, 'bad LDAP URL'
      end

      parse_dn
      parse_query
    end

    # Private method to cleanup +dn+ from using the +path+ component attribute.
    def parse_dn
      raise InvalidURIError, 'bad LDAP URL' unless @path
      @dn = @path[1..-1]
    end
    private :parse_dn

    # Private method to cleanup +attributes+, +scope+, +filter+, and +extensions+
    # from using the +query+ component attribute.
    def parse_query
      @attributes = nil
      @scope      = nil
      @filter     = nil
      @extensions = nil

      if @query
        attrs, scope, filter, extensions = @query.split('?')

        @attributes = attrs if attrs && attrs.size > 0
        @scope      = scope if scope && scope.size > 0
        @filter     = filter if filter && filter.size > 0
        @extensions = extensions if extensions && extensions.size > 0
      end
    end
    private :parse_query

    # Private method to assemble +query+ from +attributes+, +scope+, +filter+, and +extensions+.
    def build_path_query
      @path = '/' + @dn

      query = []
      [@extensions, @filter, @scope, @attributes].each do |x|
        next if !x && query.size == 0
        query.unshift(x)
      end
      @query = query.join('?')
    end
    private :build_path_query

    # Returns dn.
    def dn
      @dn
    end

    # Private setter for dn +val+.
    def set_dn(val)
      @dn = val
      build_path_query
      @dn
    end
    protected :set_dn

    # Setter for dn +val+.
    def dn=(val)
      set_dn(val)
      val
    end

    # Returns attributes.
    def attributes
      @attributes
    end

    # Private setter for attributes +val+.
    def set_attributes(val)
      @attributes = val
      build_path_query
      @attributes
    end
    protected :set_attributes

    # Setter for attributes +val+.
    def attributes=(val)
      set_attributes(val)
      val
    end

    # Returns scope.
    def scope
      @scope
    end

    # Private setter for scope +val+.
    def set_scope(val)
      @scope = val
      build_path_query
      @scope
    end
    protected :set_scope

    # Setter for scope +val+.
    def scope=(val)
      set_scope(val)
      val
    end

    # Returns filter.
    def filter
      @filter
    end

    # Private setter for filter +val+.
    def set_filter(val)
      @filter = val
      build_path_query
      @filter
    end
    protected :set_filter

    # Setter for filter +val+.
    def filter=(val)
      set_filter(val)
      val
    end

    # Returns extensions.
    def extensions
      @extensions
    end

    # Private setter for extensions +val+.
    def set_extensions(val)
      @extensions = val
      build_path_query
      @extensions
    end
    protected :set_extensions

    # Setter for extensions +val+.
    def extensions=(val)
      set_extensions(val)
      val
    end

    # Checks if URI has a path.
    # For URI::LDAP this will return +false+.
    def hierarchical?
      false
    end
  end

  @@schemes['LDAP'] = LDAP
end
# frozen_string_literal: false
#--
# = uri/common.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# License::
#   You can redistribute it and/or modify it under the same term as Ruby.
#
# See URI for general documentation
#

module URI
  #
  # Includes URI::REGEXP::PATTERN
  #
  module RFC2396_REGEXP
    #
    # Patterns used to parse URI's
    #
    module PATTERN
      # :stopdoc:

      # RFC 2396 (URI Generic Syntax)
      # RFC 2732 (IPv6 Literal Addresses in URL's)
      # RFC 2373 (IPv6 Addressing Architecture)

      # alpha         = lowalpha | upalpha
      ALPHA = "a-zA-Z"
      # alphanum      = alpha | digit
      ALNUM = "#{ALPHA}\\d"

      # hex           = digit | "A" | "B" | "C" | "D" | "E" | "F" |
      #                         "a" | "b" | "c" | "d" | "e" | "f"
      HEX     = "a-fA-F\\d"
      # escaped       = "%" hex hex
      ESCAPED = "%[#{HEX}]{2}"
      # mark          = "-" | "_" | "." | "!" | "~" | "*" | "'" |
      #                 "(" | ")"
      # unreserved    = alphanum | mark
      UNRESERVED = "\\-_.!~*'()#{ALNUM}"
      # reserved      = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
      #                 "$" | ","
      # reserved      = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
      #                 "$" | "," | "[" | "]" (RFC 2732)
      RESERVED = ";/?:@&=+$,\\[\\]"

      # domainlabel   = alphanum | alphanum *( alphanum | "-" ) alphanum
      DOMLABEL = "(?:[#{ALNUM}](?:[-#{ALNUM}]*[#{ALNUM}])?)"
      # toplabel      = alpha | alpha *( alphanum | "-" ) alphanum
      TOPLABEL = "(?:[#{ALPHA}](?:[-#{ALNUM}]*[#{ALNUM}])?)"
      # hostname      = *( domainlabel "." ) toplabel [ "." ]
      HOSTNAME = "(?:#{DOMLABEL}\\.)*#{TOPLABEL}\\.?"

      # :startdoc:
    end # PATTERN

    # :startdoc:
  end # REGEXP

  # Class that parses String's into URI's.
  #
  # It contains a Hash set of patterns and Regexp's that match and validate.
  #
  class RFC2396_Parser
    include RFC2396_REGEXP

    #
    # == Synopsis
    #
    #   URI::Parser.new([opts])
    #
    # == Args
    #
    # The constructor accepts a hash as options for parser.
    # Keys of options are pattern names of URI components
    # and values of options are pattern strings.
    # The constructor generates set of regexps for parsing URIs.
    #
    # You can use the following keys:
    #
    #   * :ESCAPED (URI::PATTERN::ESCAPED in default)
    #   * :UNRESERVED (URI::PATTERN::UNRESERVED in default)
    #   * :DOMLABEL (URI::PATTERN::DOMLABEL in default)
    #   * :TOPLABEL (URI::PATTERN::TOPLABEL in default)
    #   * :HOSTNAME (URI::PATTERN::HOSTNAME in default)
    #
    # == Examples
    #
    #   p = URI::Parser.new(:ESCAPED => "(?:%[a-fA-F0-9]{2}|%u[a-fA-F0-9]{4})")
    #   u = p.parse("http://example.jp/%uABCD") #=> #<URI::HTTP http://example.jp/%uABCD>
    #   URI.parse(u.to_s) #=> raises URI::InvalidURIError
    #
    #   s = "http://example.com/ABCD"
    #   u1 = p.parse(s) #=> #<URI::HTTP http://example.com/ABCD>
    #   u2 = URI.parse(s) #=> #<URI::HTTP http://example.com/ABCD>
    #   u1 == u2 #=> true
    #   u1.eql?(u2) #=> false
    #
    def initialize(opts = {})
      @pattern = initialize_pattern(opts)
      @pattern.each_value(&:freeze)
      @pattern.freeze

      @regexp = initialize_regexp(@pattern)
      @regexp.each_value(&:freeze)
      @regexp.freeze
    end

    # The Hash of patterns.
    #
    # See also URI::Parser.initialize_pattern.
    attr_reader :pattern

    # The Hash of Regexp.
    #
    # See also URI::Parser.initialize_regexp.
    attr_reader :regexp

    # Returns a split URI against regexp[:ABS_URI].
    def split(uri)
      case uri
      when ''
        # null uri

      when @regexp[:ABS_URI]
        scheme, opaque, userinfo, host, port,
          registry, path, query, fragment = $~[1..-1]

        # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]

        # absoluteURI   = scheme ":" ( hier_part | opaque_part )
        # hier_part     = ( net_path | abs_path ) [ "?" query ]
        # opaque_part   = uric_no_slash *uric

        # abs_path      = "/"  path_segments
        # net_path      = "//" authority [ abs_path ]

        # authority     = server | reg_name
        # server        = [ [ userinfo "@" ] hostport ]

        if !scheme
          raise InvalidURIError,
            "bad URI(absolute but no scheme): #{uri}"
        end
        if !opaque && (!path && (!host && !registry))
          raise InvalidURIError,
            "bad URI(absolute but no path): #{uri}"
        end

      when @regexp[:REL_URI]
        scheme = nil
        opaque = nil

        userinfo, host, port, registry,
          rel_segment, abs_path, query, fragment = $~[1..-1]
        if rel_segment && abs_path
          path = rel_segment + abs_path
        elsif rel_segment
          path = rel_segment
        elsif abs_path
          path = abs_path
        end

        # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]

        # relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]

        # net_path      = "//" authority [ abs_path ]
        # abs_path      = "/"  path_segments
        # rel_path      = rel_segment [ abs_path ]

        # authority     = server | reg_name
        # server        = [ [ userinfo "@" ] hostport ]

      else
        raise InvalidURIError, "bad URI(is not URI?): #{uri}"
      end

      path = '' if !path && !opaque # (see RFC2396 Section 5.2)
      ret = [
        scheme,
        userinfo, host, port,         # X
        registry,                     # X
        path,                         # Y
        opaque,                       # Y
        query,
        fragment
      ]
      return ret
    end

    #
    # == Args
    #
    # +uri+::
    #    String
    #
    # == Description
    #
    # Parses +uri+ and constructs either matching URI scheme object
    # (File, FTP, HTTP, HTTPS, LDAP, LDAPS, or MailTo) or URI::Generic.
    #
    # == Usage
    #
    #   p = URI::Parser.new
    #   p.parse("ldap://ldap.example.com/dc=example?user=john")
    #   #=> #<URI::LDAP ldap://ldap.example.com/dc=example?user=john>
    #
    def parse(uri)
      URI.for(*self.split(uri), self)
    end

    #
    # == Args
    #
    # +uris+::
    #    an Array of Strings
    #
    # == Description
    #
    # Attempts to parse and merge a set of URIs.
    #
    def join(*uris)
      uris[0] = convert_to_uri(uris[0])
      uris.inject :merge
    end

    #
    # :call-seq:
    #   extract( str )
    #   extract( str, schemes )
    #   extract( str, schemes ) {|item| block }
    #
    # == Args
    #
    # +str+::
    #    String to search
    # +schemes+::
    #    Patterns to apply to +str+
    #
    # == Description
    #
    # Attempts to parse and merge a set of URIs.
    # If no +block+ given, then returns the result,
    # else it calls +block+ for each element in result.
    #
    # See also URI::Parser.make_regexp.
    #
    def extract(str, schemes = nil)
      if block_given?
        str.scan(make_regexp(schemes)) { yield $& }
        nil
      else
        result = []
        str.scan(make_regexp(schemes)) { result.push $& }
        result
      end
    end

    # Returns Regexp that is default self.regexp[:ABS_URI_REF],
    # unless +schemes+ is provided. Then it is a Regexp.union with self.pattern[:X_ABS_URI].
    def make_regexp(schemes = nil)
      unless schemes
        @regexp[:ABS_URI_REF]
      else
        /(?=#{Regexp.union(*schemes)}:)#{@pattern[:X_ABS_URI]}/x
      end
    end

    #
    # :call-seq:
    #   escape( str )
    #   escape( str, unsafe )
    #
    # == Args
    #
    # +str+::
    #    String to make safe
    # +unsafe+::
    #    Regexp to apply. Defaults to self.regexp[:UNSAFE]
    #
    # == Description
    #
    # Constructs a safe String from +str+, removing unsafe characters,
    # replacing them with codes.
    #
    def escape(str, unsafe = @regexp[:UNSAFE])
      unless unsafe.kind_of?(Regexp)
        # perhaps unsafe is String object
        unsafe = Regexp.new("[#{Regexp.quote(unsafe)}]", false)
      end
      str.gsub(unsafe) do
        us = $&
        tmp = ''
        us.each_byte do |uc|
          tmp << sprintf('%%%02X', uc)
        end
        tmp
      end.force_encoding(Encoding::US_ASCII)
    end

    #
    # :call-seq:
    #   unescape( str )
    #   unescape( str, escaped )
    #
    # == Args
    #
    # +str+::
    #    String to remove escapes from
    # +escaped+::
    #    Regexp to apply. Defaults to self.regexp[:ESCAPED]
    #
    # == Description
    #
    # Removes escapes from +str+.
    #
    def unescape(str, escaped = @regexp[:ESCAPED])
      enc = str.encoding
      enc = Encoding::UTF_8 if enc == Encoding::US_ASCII
      str.gsub(escaped) { [$&[1, 2]].pack('H2').force_encoding(enc) }
    end

    @@to_s = Kernel.instance_method(:to_s)
    def inspect
      @@to_s.bind_call(self)
    end

    private

    # Constructs the default Hash of patterns.
    def initialize_pattern(opts = {})
      ret = {}
      ret[:ESCAPED] = escaped = (opts.delete(:ESCAPED) || PATTERN::ESCAPED)
      ret[:UNRESERVED] = unreserved = opts.delete(:UNRESERVED) || PATTERN::UNRESERVED
      ret[:RESERVED] = reserved = opts.delete(:RESERVED) || PATTERN::RESERVED
      ret[:DOMLABEL] = opts.delete(:DOMLABEL) || PATTERN::DOMLABEL
      ret[:TOPLABEL] = opts.delete(:TOPLABEL) || PATTERN::TOPLABEL
      ret[:HOSTNAME] = hostname = opts.delete(:HOSTNAME)

      # RFC 2396 (URI Generic Syntax)
      # RFC 2732 (IPv6 Literal Addresses in URL's)
      # RFC 2373 (IPv6 Addressing Architecture)

      # uric          = reserved | unreserved | escaped
      ret[:URIC] = uric = "(?:[#{unreserved}#{reserved}]|#{escaped})"
      # uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
      #                 "&" | "=" | "+" | "$" | ","
      ret[:URIC_NO_SLASH] = uric_no_slash = "(?:[#{unreserved};?:@&=+$,]|#{escaped})"
      # query         = *uric
      ret[:QUERY] = query = "#{uric}*"
      # fragment      = *uric
      ret[:FRAGMENT] = fragment = "#{uric}*"

      # hostname      = *( domainlabel "." ) toplabel [ "." ]
      # reg-name      = *( unreserved / pct-encoded / sub-delims ) # RFC3986
      unless hostname
        ret[:HOSTNAME] = hostname = "(?:[a-zA-Z0-9\\-.]|%\\h\\h)+"
      end

      # RFC 2373, APPENDIX B:
      # IPv6address = hexpart [ ":" IPv4address ]
      # IPv4address   = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
      # hexpart = hexseq | hexseq "::" [ hexseq ] | "::" [ hexseq ]
      # hexseq  = hex4 *( ":" hex4)
      # hex4    = 1*4HEXDIG
      #
      # XXX: This definition has a flaw. "::" + IPv4address must be
      # allowed too.  Here is a replacement.
      #
      # IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
      ret[:IPV4ADDR] = ipv4addr = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"
      # hex4     = 1*4HEXDIG
      hex4 = "[#{PATTERN::HEX}]{1,4}"
      # lastpart = hex4 | IPv4address
      lastpart = "(?:#{hex4}|#{ipv4addr})"
      # hexseq1  = *( hex4 ":" ) hex4
      hexseq1 = "(?:#{hex4}:)*#{hex4}"
      # hexseq2  = *( hex4 ":" ) lastpart
      hexseq2 = "(?:#{hex4}:)*#{lastpart}"
      # IPv6address = hexseq2 | [ hexseq1 ] "::" [ hexseq2 ]
      ret[:IPV6ADDR] = ipv6addr = "(?:#{hexseq2}|(?:#{hexseq1})?::(?:#{hexseq2})?)"

      # IPv6prefix  = ( hexseq1 | [ hexseq1 ] "::" [ hexseq1 ] ) "/" 1*2DIGIT
      # unused

      # ipv6reference = "[" IPv6address "]" (RFC 2732)
      ret[:IPV6REF] = ipv6ref = "\\[#{ipv6addr}\\]"

      # host          = hostname | IPv4address
      # host          = hostname | IPv4address | IPv6reference (RFC 2732)
      ret[:HOST] = host = "(?:#{hostname}|#{ipv4addr}|#{ipv6ref})"
      # port          = *digit
      ret[:PORT] = port = '\d*'
      # hostport      = host [ ":" port ]
      ret[:HOSTPORT] = hostport = "#{host}(?::#{port})?"

      # userinfo      = *( unreserved | escaped |
      #                    ";" | ":" | "&" | "=" | "+" | "$" | "," )
      ret[:USERINFO] = userinfo = "(?:[#{unreserved};:&=+$,]|#{escaped})*"

      # pchar         = unreserved | escaped |
      #                 ":" | "@" | "&" | "=" | "+" | "$" | ","
      pchar = "(?:[#{unreserved}:@&=+$,]|#{escaped})"
      # param         = *pchar
      param = "#{pchar}*"
      # segment       = *pchar *( ";" param )
      segment = "#{pchar}*(?:;#{param})*"
      # path_segments = segment *( "/" segment )
      ret[:PATH_SEGMENTS] = path_segments = "#{segment}(?:/#{segment})*"

      # server        = [ [ userinfo "@" ] hostport ]
      server = "(?:#{userinfo}@)?#{hostport}"
      # reg_name      = 1*( unreserved | escaped | "$" | "," |
      #                     ";" | ":" | "@" | "&" | "=" | "+" )
      ret[:REG_NAME] = reg_name = "(?:[#{unreserved}$,;:@&=+]|#{escaped})+"
      # authority     = server | reg_name
      authority = "(?:#{server}|#{reg_name})"

      # rel_segment   = 1*( unreserved | escaped |
      #                     ";" | "@" | "&" | "=" | "+" | "$" | "," )
      ret[:REL_SEGMENT] = rel_segment = "(?:[#{unreserved};@&=+$,]|#{escaped})+"

      # scheme        = alpha *( alpha | digit | "+" | "-" | "." )
      ret[:SCHEME] = scheme = "[#{PATTERN::ALPHA}][\\-+.#{PATTERN::ALPHA}\\d]*"

      # abs_path      = "/"  path_segments
      ret[:ABS_PATH] = abs_path = "/#{path_segments}"
      # rel_path      = rel_segment [ abs_path ]
      ret[:REL_PATH] = rel_path = "#{rel_segment}(?:#{abs_path})?"
      # net_path      = "//" authority [ abs_path ]
      ret[:NET_PATH] = net_path = "//#{authority}(?:#{abs_path})?"

      # hier_part     = ( net_path | abs_path ) [ "?" query ]
      ret[:HIER_PART] = hier_part = "(?:#{net_path}|#{abs_path})(?:\\?(?:#{query}))?"
      # opaque_part   = uric_no_slash *uric
      ret[:OPAQUE_PART] = opaque_part = "#{uric_no_slash}#{uric}*"

      # absoluteURI   = scheme ":" ( hier_part | opaque_part )
      ret[:ABS_URI] = abs_uri = "#{scheme}:(?:#{hier_part}|#{opaque_part})"
      # relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]
      ret[:REL_URI] = rel_uri = "(?:#{net_path}|#{abs_path}|#{rel_path})(?:\\?#{query})?"

      # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
      ret[:URI_REF] = "(?:#{abs_uri}|#{rel_uri})?(?:##{fragment})?"

      ret[:X_ABS_URI] = "
        (#{scheme}):                           (?# 1: scheme)
        (?:
           (#{opaque_part})                    (?# 2: opaque)
        |
           (?:(?:
             //(?:
                 (?:(?:(#{userinfo})@)?        (?# 3: userinfo)
                   (?:(#{host})(?::(\\d*))?))? (?# 4: host, 5: port)
               |
                 (#{reg_name})                 (?# 6: registry)
               )
             |
             (?!//))                           (?# XXX: '//' is the mark for hostport)
             (#{abs_path})?                    (?# 7: path)
           )(?:\\?(#{query}))?                 (?# 8: query)
        )
        (?:\\#(#{fragment}))?                  (?# 9: fragment)
      "

      ret[:X_REL_URI] = "
        (?:
          (?:
            //
            (?:
              (?:(#{userinfo})@)?       (?# 1: userinfo)
                (#{host})?(?::(\\d*))?  (?# 2: host, 3: port)
            |
              (#{reg_name})             (?# 4: registry)
            )
          )
        |
          (#{rel_segment})              (?# 5: rel_segment)
        )?
        (#{abs_path})?                  (?# 6: abs_path)
        (?:\\?(#{query}))?              (?# 7: query)
        (?:\\#(#{fragment}))?           (?# 8: fragment)
      "

      ret
    end

    # Constructs the default Hash of Regexp's.
    def initialize_regexp(pattern)
      ret = {}

      # for URI::split
      ret[:ABS_URI] = Regexp.new('\A\s*+' + pattern[:X_ABS_URI] + '\s*\z', Regexp::EXTENDED)
      ret[:REL_URI] = Regexp.new('\A\s*+' + pattern[:X_REL_URI] + '\s*\z', Regexp::EXTENDED)

      # for URI::extract
      ret[:URI_REF]     = Regexp.new(pattern[:URI_REF])
      ret[:ABS_URI_REF] = Regexp.new(pattern[:X_ABS_URI], Regexp::EXTENDED)
      ret[:REL_URI_REF] = Regexp.new(pattern[:X_REL_URI], Regexp::EXTENDED)

      # for URI::escape/unescape
      ret[:ESCAPED] = Regexp.new(pattern[:ESCAPED])
      ret[:UNSAFE]  = Regexp.new("[^#{pattern[:UNRESERVED]}#{pattern[:RESERVED]}]")

      # for Generic#initialize
      ret[:SCHEME]   = Regexp.new("\\A#{pattern[:SCHEME]}\\z")
      ret[:USERINFO] = Regexp.new("\\A#{pattern[:USERINFO]}\\z")
      ret[:HOST]     = Regexp.new("\\A#{pattern[:HOST]}\\z")
      ret[:PORT]     = Regexp.new("\\A#{pattern[:PORT]}\\z")
      ret[:OPAQUE]   = Regexp.new("\\A#{pattern[:OPAQUE_PART]}\\z")
      ret[:REGISTRY] = Regexp.new("\\A#{pattern[:REG_NAME]}\\z")
      ret[:ABS_PATH] = Regexp.new("\\A#{pattern[:ABS_PATH]}\\z")
      ret[:REL_PATH] = Regexp.new("\\A#{pattern[:REL_PATH]}\\z")
      ret[:QUERY]    = Regexp.new("\\A#{pattern[:QUERY]}\\z")
      ret[:FRAGMENT] = Regexp.new("\\A#{pattern[:FRAGMENT]}\\z")

      ret
    end

    def convert_to_uri(uri)
      if uri.is_a?(URI::Generic)
        uri
      elsif uri = String.try_convert(uri)
        parse(uri)
      else
        raise ArgumentError,
          "bad argument (expected URI object or URI string)"
      end
    end

  end # class Parser
end # module URI
module URI
  # :stopdoc:
  VERSION_CODE = '001003'.freeze
  VERSION = VERSION_CODE.scan(/../).collect{|n| n.to_i}.join('.').freeze
  # :startdoc:
end
# frozen_string_literal: true

# = uri/generic.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# License:: You can redistribute it and/or modify it under the same term as Ruby.
#
# See URI for general documentation
#

require_relative 'common'
autoload :IPSocket, 'socket'
autoload :IPAddr, 'ipaddr'

module URI

  #
  # Base class for all URI classes.
  # Implements generic URI syntax as per RFC 2396.
  #
  class Generic
    include URI

    #
    # A Default port of nil for URI::Generic.
    #
    DEFAULT_PORT = nil

    #
    # Returns default port.
    #
    def self.default_port
      self::DEFAULT_PORT
    end

    #
    # Returns default port.
    #
    def default_port
      self.class.default_port
    end

    #
    # An Array of the available components for URI::Generic.
    #
    COMPONENT = [
      :scheme,
      :userinfo, :host, :port, :registry,
      :path, :opaque,
      :query,
      :fragment
    ].freeze

    #
    # Components of the URI in the order.
    #
    def self.component
      self::COMPONENT
    end

    USE_REGISTRY = false # :nodoc:

    def self.use_registry # :nodoc:
      self::USE_REGISTRY
    end

    #
    # == Synopsis
    #
    # See ::new.
    #
    # == Description
    #
    # At first, tries to create a new URI::Generic instance using
    # URI::Generic::build. But, if exception URI::InvalidComponentError is raised,
    # then it does URI::Escape.escape all URI components and tries again.
    #
    def self.build2(args)
      begin
        return self.build(args)
      rescue InvalidComponentError
        if args.kind_of?(Array)
          return self.build(args.collect{|x|
            if x.is_a?(String)
              DEFAULT_PARSER.escape(x)
            else
              x
            end
          })
        elsif args.kind_of?(Hash)
          tmp = {}
          args.each do |key, value|
            tmp[key] = if value
                DEFAULT_PARSER.escape(value)
              else
                value
              end
          end
          return self.build(tmp)
        end
      end
    end

    #
    # == Synopsis
    #
    # See ::new.
    #
    # == Description
    #
    # Creates a new URI::Generic instance from components of URI::Generic
    # with check.  Components are: scheme, userinfo, host, port, registry, path,
    # opaque, query, and fragment. You can provide arguments either by an Array or a Hash.
    # See ::new for hash keys to use or for order of array items.
    #
    def self.build(args)
      if args.kind_of?(Array) &&
          args.size == ::URI::Generic::COMPONENT.size
        tmp = args.dup
      elsif args.kind_of?(Hash)
        tmp = ::URI::Generic::COMPONENT.collect do |c|
          if args.include?(c)
            args[c]
          else
            nil
          end
        end
      else
        component = self.class.component rescue ::URI::Generic::COMPONENT
        raise ArgumentError,
        "expected Array of or Hash of components of #{self.class} (#{component.join(', ')})"
      end

      tmp << nil
      tmp << true
      return self.new(*tmp)
    end

    #
    # == Args
    #
    # +scheme+::
    #   Protocol scheme, i.e. 'http','ftp','mailto' and so on.
    # +userinfo+::
    #   User name and password, i.e. 'sdmitry:bla'.
    # +host+::
    #   Server host name.
    # +port+::
    #   Server port.
    # +registry+::
    #   Registry of naming authorities.
    # +path+::
    #   Path on server.
    # +opaque+::
    #   Opaque part.
    # +query+::
    #   Query data.
    # +fragment+::
    #   Part of the URI after '#' character.
    # +parser+::
    #   Parser for internal use [URI::DEFAULT_PARSER by default].
    # +arg_check+::
    #   Check arguments [false by default].
    #
    # == Description
    #
    # Creates a new URI::Generic instance from ``generic'' components without check.
    #
    def initialize(scheme,
                   userinfo, host, port, registry,
                   path, opaque,
                   query,
                   fragment,
                   parser = DEFAULT_PARSER,
                   arg_check = false)
      @scheme = nil
      @user = nil
      @password = nil
      @host = nil
      @port = nil
      @path = nil
      @query = nil
      @opaque = nil
      @fragment = nil
      @parser = parser == DEFAULT_PARSER ? nil : parser

      if arg_check
        self.scheme = scheme
        self.userinfo = userinfo
        self.hostname = host
        self.port = port
        self.path = path
        self.query = query
        self.opaque = opaque
        self.fragment = fragment
      else
        self.set_scheme(scheme)
        self.set_userinfo(userinfo)
        self.set_host(host)
        self.set_port(port)
        self.set_path(path)
        self.query = query
        self.set_opaque(opaque)
        self.fragment=(fragment)
      end
      if registry
        raise InvalidURIError,
          "the scheme #{@scheme} does not accept registry part: #{registry} (or bad hostname?)"
      end

      @scheme&.freeze
      self.set_path('') if !@path && !@opaque # (see RFC2396 Section 5.2)
      self.set_port(self.default_port) if self.default_port && !@port
    end

    #
    # Returns the scheme component of the URI.
    #
    #   URI("http://foo/bar/baz").scheme #=> "http"
    #
    attr_reader :scheme

    # Returns the host component of the URI.
    #
    #   URI("http://foo/bar/baz").host #=> "foo"
    #
    # It returns nil if no host component exists.
    #
    #   URI("mailto:foo@example.org").host #=> nil
    #
    # The component does not contain the port number.
    #
    #   URI("http://foo:8080/bar/baz").host #=> "foo"
    #
    # Since IPv6 addresses are wrapped with brackets in URIs,
    # this method returns IPv6 addresses wrapped with brackets.
    # This form is not appropriate to pass to socket methods such as TCPSocket.open.
    # If unwrapped host names are required, use the #hostname method.
    #
    #   URI("http://[::1]/bar/baz").host     #=> "[::1]"
    #   URI("http://[::1]/bar/baz").hostname #=> "::1"
    #
    attr_reader :host

    # Returns the port component of the URI.
    #
    #   URI("http://foo/bar/baz").port      #=> 80
    #   URI("http://foo:8080/bar/baz").port #=> 8080
    #
    attr_reader :port

    def registry # :nodoc:
      nil
    end

    # Returns the path component of the URI.
    #
    #   URI("http://foo/bar/baz").path #=> "/bar/baz"
    #
    attr_reader :path

    # Returns the query component of the URI.
    #
    #   URI("http://foo/bar/baz?search=FooBar").query #=> "search=FooBar"
    #
    attr_reader :query

    # Returns the opaque part of the URI.
    #
    #   URI("mailto:foo@example.org").opaque #=> "foo@example.org"
    #   URI("http://foo/bar/baz").opaque     #=> nil
    #
    # The portion of the path that does not make use of the slash '/'.
    # The path typically refers to an absolute path or an opaque part.
    # (See RFC2396 Section 3 and 5.2.)
    #
    attr_reader :opaque

    # Returns the fragment component of the URI.
    #
    #   URI("http://foo/bar/baz?search=FooBar#ponies").fragment #=> "ponies"
    #
    attr_reader :fragment

    # Returns the parser to be used.
    #
    # Unless a URI::Parser is defined, DEFAULT_PARSER is used.
    #
    def parser
      if !defined?(@parser) || !@parser
        DEFAULT_PARSER
      else
        @parser || DEFAULT_PARSER
      end
    end

    # Replaces self by other URI object.
    #
    def replace!(oth)
      if self.class != oth.class
        raise ArgumentError, "expected #{self.class} object"
      end

      component.each do |c|
        self.__send__("#{c}=", oth.__send__(c))
      end
    end
    private :replace!

    #
    # Components of the URI in the order.
    #
    def component
      self.class.component
    end

    #
    # Checks the scheme +v+ component against the URI::Parser Regexp for :SCHEME.
    #
    def check_scheme(v)
      if v && parser.regexp[:SCHEME] !~ v
        raise InvalidComponentError,
          "bad component(expected scheme component): #{v}"
      end

      return true
    end
    private :check_scheme

    # Protected setter for the scheme component +v+.
    #
    # See also URI::Generic.scheme=.
    #
    def set_scheme(v)
      @scheme = v&.downcase
    end
    protected :set_scheme

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the scheme component +v+
    # (with validation).
    #
    # See also URI::Generic.check_scheme.
    #
    # == Usage
    #
    #   require 'uri'
    #
    #   uri = URI.parse("http://my.example.com")
    #   uri.scheme = "https"
    #   uri.to_s  #=> "https://my.example.com"
    #
    def scheme=(v)
      check_scheme(v)
      set_scheme(v)
      v
    end

    #
    # Checks the +user+ and +password+.
    #
    # If +password+ is not provided, then +user+ is
    # split, using URI::Generic.split_userinfo, to
    # pull +user+ and +password.
    #
    # See also URI::Generic.check_user, URI::Generic.check_password.
    #
    def check_userinfo(user, password = nil)
      if !password
        user, password = split_userinfo(user)
      end
      check_user(user)
      check_password(password, user)

      return true
    end
    private :check_userinfo

    #
    # Checks the user +v+ component for RFC2396 compliance
    # and against the URI::Parser Regexp for :USERINFO.
    #
    # Can not have a registry or opaque component defined,
    # with a user component defined.
    #
    def check_user(v)
      if @opaque
        raise InvalidURIError,
          "can not set user with opaque"
      end

      return v unless v

      if parser.regexp[:USERINFO] !~ v
        raise InvalidComponentError,
          "bad component(expected userinfo component or user component): #{v}"
      end

      return true
    end
    private :check_user

    #
    # Checks the password +v+ component for RFC2396 compliance
    # and against the URI::Parser Regexp for :USERINFO.
    #
    # Can not have a registry or opaque component defined,
    # with a user component defined.
    #
    def check_password(v, user = @user)
      if @opaque
        raise InvalidURIError,
          "can not set password with opaque"
      end
      return v unless v

      if !user
        raise InvalidURIError,
          "password component depends user component"
      end

      if parser.regexp[:USERINFO] !~ v
        raise InvalidComponentError,
          "bad password component"
      end

      return true
    end
    private :check_password

    #
    # Sets userinfo, argument is string like 'name:pass'.
    #
    def userinfo=(userinfo)
      if userinfo.nil?
        return nil
      end
      check_userinfo(*userinfo)
      set_userinfo(*userinfo)
      # returns userinfo
    end

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the +user+ component
    # (with validation).
    #
    # See also URI::Generic.check_user.
    #
    # == Usage
    #
    #   require 'uri'
    #
    #   uri = URI.parse("http://john:S3nsit1ve@my.example.com")
    #   uri.user = "sam"
    #   uri.to_s  #=> "http://sam:V3ry_S3nsit1ve@my.example.com"
    #
    def user=(user)
      check_user(user)
      set_user(user)
      # returns user
    end

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the +password+ component
    # (with validation).
    #
    # See also URI::Generic.check_password.
    #
    # == Usage
    #
    #   require 'uri'
    #
    #   uri = URI.parse("http://john:S3nsit1ve@my.example.com")
    #   uri.password = "V3ry_S3nsit1ve"
    #   uri.to_s  #=> "http://john:V3ry_S3nsit1ve@my.example.com"
    #
    def password=(password)
      check_password(password)
      set_password(password)
      # returns password
    end

    # Protected setter for the +user+ component, and +password+ if available
    # (with validation).
    #
    # See also URI::Generic.userinfo=.
    #
    def set_userinfo(user, password = nil)
      unless password
        user, password = split_userinfo(user)
      end
      @user     = user
      @password = password if password

      [@user, @password]
    end
    protected :set_userinfo

    # Protected setter for the user component +v+.
    #
    # See also URI::Generic.user=.
    #
    def set_user(v)
      set_userinfo(v, @password)
      v
    end
    protected :set_user

    # Protected setter for the password component +v+.
    #
    # See also URI::Generic.password=.
    #
    def set_password(v)
      @password = v
      # returns v
    end
    protected :set_password

    # Returns the userinfo +ui+ as <code>[user, password]</code>
    # if properly formatted as 'user:password'.
    def split_userinfo(ui)
      return nil, nil unless ui
      user, password = ui.split(':', 2)

      return user, password
    end
    private :split_userinfo

    # Escapes 'user:password' +v+ based on RFC 1738 section 3.1.
    def escape_userpass(v)
      parser.escape(v, /[@:\/]/o) # RFC 1738 section 3.1 #/
    end
    private :escape_userpass

    # Returns the userinfo, either as 'user' or 'user:password'.
    def userinfo
      if @user.nil?
        nil
      elsif @password.nil?
        @user
      else
        @user + ':' + @password
      end
    end

    # Returns the user component.
    def user
      @user
    end

    # Returns the password component.
    def password
      @password
    end

    #
    # Checks the host +v+ component for RFC2396 compliance
    # and against the URI::Parser Regexp for :HOST.
    #
    # Can not have a registry or opaque component defined,
    # with a host component defined.
    #
    def check_host(v)
      return v unless v

      if @opaque
        raise InvalidURIError,
          "can not set host with registry or opaque"
      elsif parser.regexp[:HOST] !~ v
        raise InvalidComponentError,
          "bad component(expected host component): #{v}"
      end

      return true
    end
    private :check_host

    # Protected setter for the host component +v+.
    #
    # See also URI::Generic.host=.
    #
    def set_host(v)
      @host = v
    end
    protected :set_host

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the host component +v+
    # (with validation).
    #
    # See also URI::Generic.check_host.
    #
    # == Usage
    #
    #   require 'uri'
    #
    #   uri = URI.parse("http://my.example.com")
    #   uri.host = "foo.com"
    #   uri.to_s  #=> "http://foo.com"
    #
    def host=(v)
      check_host(v)
      set_host(v)
      v
    end

    # Extract the host part of the URI and unwrap brackets for IPv6 addresses.
    #
    # This method is the same as URI::Generic#host except
    # brackets for IPv6 (and future IP) addresses are removed.
    #
    #   uri = URI("http://[::1]/bar")
    #   uri.hostname      #=> "::1"
    #   uri.host          #=> "[::1]"
    #
    def hostname
      v = self.host
      /\A\[(.*)\]\z/ =~ v ? $1 : v
    end

    # Sets the host part of the URI as the argument with brackets for IPv6 addresses.
    #
    # This method is the same as URI::Generic#host= except
    # the argument can be a bare IPv6 address.
    #
    #   uri = URI("http://foo/bar")
    #   uri.hostname = "::1"
    #   uri.to_s  #=> "http://[::1]/bar"
    #
    # If the argument seems to be an IPv6 address,
    # it is wrapped with brackets.
    #
    def hostname=(v)
      v = "[#{v}]" if /\A\[.*\]\z/ !~ v && /:/ =~ v
      self.host = v
    end

    #
    # Checks the port +v+ component for RFC2396 compliance
    # and against the URI::Parser Regexp for :PORT.
    #
    # Can not have a registry or opaque component defined,
    # with a port component defined.
    #
    def check_port(v)
      return v unless v

      if @opaque
        raise InvalidURIError,
          "can not set port with registry or opaque"
      elsif !v.kind_of?(Integer) && parser.regexp[:PORT] !~ v
        raise InvalidComponentError,
          "bad component(expected port component): #{v.inspect}"
      end

      return true
    end
    private :check_port

    # Protected setter for the port component +v+.
    #
    # See also URI::Generic.port=.
    #
    def set_port(v)
      v = v.empty? ? nil : v.to_i unless !v || v.kind_of?(Integer)
      @port = v
    end
    protected :set_port

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the port component +v+
    # (with validation).
    #
    # See also URI::Generic.check_port.
    #
    # == Usage
    #
    #   require 'uri'
    #
    #   uri = URI.parse("http://my.example.com")
    #   uri.port = 8080
    #   uri.to_s  #=> "http://my.example.com:8080"
    #
    def port=(v)
      check_port(v)
      set_port(v)
      port
    end

    def check_registry(v) # :nodoc:
      raise InvalidURIError, "can not set registry"
    end
    private :check_registry

    def set_registry(v) #:nodoc:
      raise InvalidURIError, "can not set registry"
    end
    protected :set_registry

    def registry=(v)
      raise InvalidURIError, "can not set registry"
    end

    #
    # Checks the path +v+ component for RFC2396 compliance
    # and against the URI::Parser Regexp
    # for :ABS_PATH and :REL_PATH.
    #
    # Can not have a opaque component defined,
    # with a path component defined.
    #
    def check_path(v)
      # raise if both hier and opaque are not nil, because:
      # absoluteURI   = scheme ":" ( hier_part | opaque_part )
      # hier_part     = ( net_path | abs_path ) [ "?" query ]
      if v && @opaque
        raise InvalidURIError,
          "path conflicts with opaque"
      end

      # If scheme is ftp, path may be relative.
      # See RFC 1738 section 3.2.2, and RFC 2396.
      if @scheme && @scheme != "ftp"
        if v && v != '' && parser.regexp[:ABS_PATH] !~ v
          raise InvalidComponentError,
            "bad component(expected absolute path component): #{v}"
        end
      else
        if v && v != '' && parser.regexp[:ABS_PATH] !~ v &&
           parser.regexp[:REL_PATH] !~ v
          raise InvalidComponentError,
            "bad component(expected relative path component): #{v}"
        end
      end

      return true
    end
    private :check_path

    # Protected setter for the path component +v+.
    #
    # See also URI::Generic.path=.
    #
    def set_path(v)
      @path = v
    end
    protected :set_path

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the path component +v+
    # (with validation).
    #
    # See also URI::Generic.check_path.
    #
    # == Usage
    #
    #   require 'uri'
    #
    #   uri = URI.parse("http://my.example.com/pub/files")
    #   uri.path = "/faq/"
    #   uri.to_s  #=> "http://my.example.com/faq/"
    #
    def path=(v)
      check_path(v)
      set_path(v)
      v
    end

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the query component +v+.
    #
    # == Usage
    #
    #   require 'uri'
    #
    #   uri = URI.parse("http://my.example.com/?id=25")
    #   uri.query = "id=1"
    #   uri.to_s  #=> "http://my.example.com/?id=1"
    #
    def query=(v)
      return @query = nil unless v
      raise InvalidURIError, "query conflicts with opaque" if @opaque

      x = v.to_str
      v = x.dup if x.equal? v
      v.encode!(Encoding::UTF_8) rescue nil
      v.delete!("\t\r\n")
      v.force_encoding(Encoding::ASCII_8BIT)
      raise InvalidURIError, "invalid percent escape: #{$1}" if /(%\H\H)/n.match(v)
      v.gsub!(/(?!%\h\h|[!$-&(-;=?-_a-~])./n.freeze){'%%%02X' % $&.ord}
      v.force_encoding(Encoding::US_ASCII)
      @query = v
    end

    #
    # Checks the opaque +v+ component for RFC2396 compliance and
    # against the URI::Parser Regexp for :OPAQUE.
    #
    # Can not have a host, port, user, or path component defined,
    # with an opaque component defined.
    #
    def check_opaque(v)
      return v unless v

      # raise if both hier and opaque are not nil, because:
      # absoluteURI   = scheme ":" ( hier_part | opaque_part )
      # hier_part     = ( net_path | abs_path ) [ "?" query ]
      if @host || @port || @user || @path  # userinfo = @user + ':' + @password
        raise InvalidURIError,
          "can not set opaque with host, port, userinfo or path"
      elsif v && parser.regexp[:OPAQUE] !~ v
        raise InvalidComponentError,
          "bad component(expected opaque component): #{v}"
      end

      return true
    end
    private :check_opaque

    # Protected setter for the opaque component +v+.
    #
    # See also URI::Generic.opaque=.
    #
    def set_opaque(v)
      @opaque = v
    end
    protected :set_opaque

    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the opaque component +v+
    # (with validation).
    #
    # See also URI::Generic.check_opaque.
    #
    def opaque=(v)
      check_opaque(v)
      set_opaque(v)
      v
    end

    #
    # Checks the fragment +v+ component against the URI::Parser Regexp for :FRAGMENT.
    #
    #
    # == Args
    #
    # +v+::
    #    String
    #
    # == Description
    #
    # Public setter for the fragment component +v+
    # (with validation).
    #
    # == Usage
    #
    #   require 'uri'
    #
    #   uri = URI.parse("http://my.example.com/?id=25#time=1305212049")
    #   uri.fragment = "time=1305212086"
    #   uri.to_s  #=> "http://my.example.com/?id=25#time=1305212086"
    #
    def fragment=(v)
      return @fragment = nil unless v

      x = v.to_str
      v = x.dup if x.equal? v
      v.encode!(Encoding::UTF_8) rescue nil
      v.delete!("\t\r\n")
      v.force_encoding(Encoding::ASCII_8BIT)
      v.gsub!(/(?!%\h\h|[!-~])./n){'%%%02X' % $&.ord}
      v.force_encoding(Encoding::US_ASCII)
      @fragment = v
    end

    #
    # Returns true if URI is hierarchical.
    #
    # == Description
    #
    # URI has components listed in order of decreasing significance from left to right,
    # see RFC3986 https://tools.ietf.org/html/rfc3986 1.2.3.
    #
    # == Usage
    #
    #   require 'uri'
    #
    #   uri = URI.parse("http://my.example.com/")
    #   uri.hierarchical?
    #   #=> true
    #   uri = URI.parse("mailto:joe@example.com")
    #   uri.hierarchical?
    #   #=> false
    #
    def hierarchical?
      if @path
        true
      else
        false
      end
    end

    #
    # Returns true if URI has a scheme (e.g. http:// or https://) specified.
    #
    def absolute?
      if @scheme
        true
      else
        false
      end
    end
    alias absolute absolute?

    #
    # Returns true if URI does not have a scheme (e.g. http:// or https://) specified.
    #
    def relative?
      !absolute?
    end

    #
    # Returns an Array of the path split on '/'.
    #
    def split_path(path)
      path.split("/", -1)
    end
    private :split_path

    #
    # Merges a base path +base+, with relative path +rel+,
    # returns a modified base path.
    #
    def merge_path(base, rel)

      # RFC2396, Section 5.2, 5)
      # RFC2396, Section 5.2, 6)
      base_path = split_path(base)
      rel_path  = split_path(rel)

      # RFC2396, Section 5.2, 6), a)
      base_path << '' if base_path.last == '..'
      while i = base_path.index('..')
        base_path.slice!(i - 1, 2)
      end

      if (first = rel_path.first) and first.empty?
        base_path.clear
        rel_path.shift
      end

      # RFC2396, Section 5.2, 6), c)
      # RFC2396, Section 5.2, 6), d)
      rel_path.push('') if rel_path.last == '.' || rel_path.last == '..'
      rel_path.delete('.')

      # RFC2396, Section 5.2, 6), e)
      tmp = []
      rel_path.each do |x|
        if x == '..' &&
            !(tmp.empty? || tmp.last == '..')
          tmp.pop
        else
          tmp << x
        end
      end

      add_trailer_slash = !tmp.empty?
      if base_path.empty?
        base_path = [''] # keep '/' for root directory
      elsif add_trailer_slash
        base_path.pop
      end
      while x = tmp.shift
        if x == '..'
          # RFC2396, Section 4
          # a .. or . in an absolute path has no special meaning
          base_path.pop if base_path.size > 1
        else
          # if x == '..'
          #   valid absolute (but abnormal) path "/../..."
          # else
          #   valid absolute path
          # end
          base_path << x
          tmp.each {|t| base_path << t}
          add_trailer_slash = false
          break
        end
      end
      base_path.push('') if add_trailer_slash

      return base_path.join('/')
    end
    private :merge_path

    #
    # == Args
    #
    # +oth+::
    #    URI or String
    #
    # == Description
    #
    # Destructive form of #merge.
    #
    # == Usage
    #
    #   require 'uri'
    #
    #   uri = URI.parse("http://my.example.com")
    #   uri.merge!("/main.rbx?page=1")
    #   uri.to_s  # => "http://my.example.com/main.rbx?page=1"
    #
    def merge!(oth)
      t = merge(oth)
      if self == t
        nil
      else
        replace!(t)
        self
      end
    end

    #
    # == Args
    #
    # +oth+::
    #    URI or String
    #
    # == Description
    #
    # Merges two URIs.
    #
    # == Usage
    #
    #   require 'uri'
    #
    #   uri = URI.parse("http://my.example.com")
    #   uri.merge("/main.rbx?page=1")
    #   # => "http://my.example.com/main.rbx?page=1"
    #
    def merge(oth)
      rel = parser.__send__(:convert_to_uri, oth)

      if rel.absolute?
        #raise BadURIError, "both URI are absolute" if absolute?
        # hmm... should return oth for usability?
        return rel
      end

      unless self.absolute?
        raise BadURIError, "both URI are relative"
      end

      base = self.dup

      authority = rel.userinfo || rel.host || rel.port

      # RFC2396, Section 5.2, 2)
      if (rel.path.nil? || rel.path.empty?) && !authority && !rel.query
        base.fragment=(rel.fragment) if rel.fragment
        return base
      end

      base.query = nil
      base.fragment=(nil)

      # RFC2396, Section 5.2, 4)
      if !authority
        base.set_path(merge_path(base.path, rel.path)) if base.path && rel.path
      else
        # RFC2396, Section 5.2, 4)
        base.set_path(rel.path) if rel.path
      end

      # RFC2396, Section 5.2, 7)
      base.set_userinfo(rel.userinfo) if rel.userinfo
      base.set_host(rel.host)         if rel.host
      base.set_port(rel.port)         if rel.port
      base.query = rel.query       if rel.query
      base.fragment=(rel.fragment) if rel.fragment

      return base
    end # merge
    alias + merge

    # :stopdoc:
    def route_from_path(src, dst)
      case dst
      when src
        # RFC2396, Section 4.2
        return ''
      when %r{(?:\A|/)\.\.?(?:/|\z)}
        # dst has abnormal absolute path,
        # like "/./", "/../", "/x/../", ...
        return dst.dup
      end

      src_path = src.scan(%r{[^/]*/})
      dst_path = dst.scan(%r{[^/]*/?})

      # discard same parts
      while !dst_path.empty? && dst_path.first == src_path.first
        src_path.shift
        dst_path.shift
      end

      tmp = dst_path.join

      # calculate
      if src_path.empty?
        if tmp.empty?
          return './'
        elsif dst_path.first.include?(':') # (see RFC2396 Section 5)
          return './' + tmp
        else
          return tmp
        end
      end

      return '../' * src_path.size + tmp
    end
    private :route_from_path
    # :startdoc:

    # :stopdoc:
    def route_from0(oth)
      oth = parser.__send__(:convert_to_uri, oth)
      if self.relative?
        raise BadURIError,
          "relative URI: #{self}"
      end
      if oth.relative?
        raise BadURIError,
          "relative URI: #{oth}"
      end

      if self.scheme != oth.scheme
        return self, self.dup
      end
      rel = URI::Generic.new(nil, # it is relative URI
                             self.userinfo, self.host, self.port,
                             nil, self.path, self.opaque,
                             self.query, self.fragment, parser)

      if rel.userinfo != oth.userinfo ||
          rel.host.to_s.downcase != oth.host.to_s.downcase ||
          rel.port != oth.port

        if self.userinfo.nil? && self.host.nil?
          return self, self.dup
        end

        rel.set_port(nil) if rel.port == oth.default_port
        return rel, rel
      end
      rel.set_userinfo(nil)
      rel.set_host(nil)
      rel.set_port(nil)

      if rel.path && rel.path == oth.path
        rel.set_path('')
        rel.query = nil if rel.query == oth.query
        return rel, rel
      elsif rel.opaque && rel.opaque == oth.opaque
        rel.set_opaque('')
        rel.query = nil if rel.query == oth.query
        return rel, rel
      end

      # you can modify `rel', but can not `oth'.
      return oth, rel
    end
    private :route_from0
    # :startdoc:

    #
    # == Args
    #
    # +oth+::
    #    URI or String
    #
    # == Description
    #
    # Calculates relative path from oth to self.
    #
    # == Usage
    #
    #   require 'uri'
    #
    #   uri = URI.parse('http://my.example.com/main.rbx?page=1')
    #   uri.route_from('http://my.example.com')
    #   #=> #<URI::Generic /main.rbx?page=1>
    #
    def route_from(oth)
      # you can modify `rel', but can not `oth'.
      begin
        oth, rel = route_from0(oth)
      rescue
        raise $!.class, $!.message
      end
      if oth == rel
        return rel
      end

      rel.set_path(route_from_path(oth.path, self.path))
      if rel.path == './' && self.query
        # "./?foo" -> "?foo"
        rel.set_path('')
      end

      return rel
    end

    alias - route_from

    #
    # == Args
    #
    # +oth+::
    #    URI or String
    #
    # == Description
    #
    # Calculates relative path to oth from self.
    #
    # == Usage
    #
    #   require 'uri'
    #
    #   uri = URI.parse('http://my.example.com')
    #   uri.route_to('http://my.example.com/main.rbx?page=1')
    #   #=> #<URI::Generic /main.rbx?page=1>
    #
    def route_to(oth)
      parser.__send__(:convert_to_uri, oth).route_from(self)
    end

    #
    # Returns normalized URI.
    #
    #   require 'uri'
    #
    #   URI("HTTP://my.EXAMPLE.com").normalize
    #   #=> #<URI::HTTP http://my.example.com/>
    #
    # Normalization here means:
    #
    # * scheme and host are converted to lowercase,
    # * an empty path component is set to "/".
    #
    def normalize
      uri = dup
      uri.normalize!
      uri
    end

    #
    # Destructive version of #normalize.
    #
    def normalize!
      if path&.empty?
        set_path('/')
      end
      if scheme && scheme != scheme.downcase
        set_scheme(self.scheme.downcase)
      end
      if host && host != host.downcase
        set_host(self.host.downcase)
      end
    end

    #
    # Constructs String from URI.
    #
    def to_s
      str = ''.dup
      if @scheme
        str << @scheme
        str << ':'
      end

      if @opaque
        str << @opaque
      else
        if @host || %w[file postgres].include?(@scheme)
          str << '//'
        end
        if self.userinfo
          str << self.userinfo
          str << '@'
        end
        if @host
          str << @host
        end
        if @port && @port != self.default_port
          str << ':'
          str << @port.to_s
        end
        str << @path
        if @query
          str << '?'
          str << @query
        end
      end
      if @fragment
        str << '#'
        str << @fragment
      end
      str
    end

    #
    # Compares two URIs.
    #
    def ==(oth)
      if self.class == oth.class
        self.normalize.component_ary == oth.normalize.component_ary
      else
        false
      end
    end

    def hash
      self.component_ary.hash
    end

    def eql?(oth)
      self.class == oth.class &&
      parser == oth.parser &&
      self.component_ary.eql?(oth.component_ary)
    end

=begin

--- URI::Generic#===(oth)

=end
#    def ===(oth)
#      raise NotImplementedError
#    end

=begin
=end


    # Returns an Array of the components defined from the COMPONENT Array.
    def component_ary
      component.collect do |x|
        self.__send__(x)
      end
    end
    protected :component_ary

    # == Args
    #
    # +components+::
    #    Multiple Symbol arguments defined in URI::HTTP.
    #
    # == Description
    #
    # Selects specified components from URI.
    #
    # == Usage
    #
    #   require 'uri'
    #
    #   uri = URI.parse('http://myuser:mypass@my.example.com/test.rbx')
    #   uri.select(:userinfo, :host, :path)
    #   # => ["myuser:mypass", "my.example.com", "/test.rbx"]
    #
    def select(*components)
      components.collect do |c|
        if component.include?(c)
          self.__send__(c)
        else
          raise ArgumentError,
            "expected of components of #{self.class} (#{self.class.component.join(', ')})"
        end
      end
    end

    def inspect
      "#<#{self.class} #{self}>"
    end

    #
    # == Args
    #
    # +v+::
    #    URI or String
    #
    # == Description
    #
    # Attempts to parse other URI +oth+,
    # returns [parsed_oth, self].
    #
    # == Usage
    #
    #   require 'uri'
    #
    #   uri = URI.parse("http://my.example.com")
    #   uri.coerce("http://foo.com")
    #   #=> [#<URI::HTTP http://foo.com>, #<URI::HTTP http://my.example.com>]
    #
    def coerce(oth)
      case oth
      when String
        oth = parser.parse(oth)
      else
        super
      end

      return oth, self
    end

    # Returns a proxy URI.
    # The proxy URI is obtained from environment variables such as http_proxy,
    # ftp_proxy, no_proxy, etc.
    # If there is no proper proxy, nil is returned.
    #
    # If the optional parameter +env+ is specified, it is used instead of ENV.
    #
    # Note that capitalized variables (HTTP_PROXY, FTP_PROXY, NO_PROXY, etc.)
    # are examined, too.
    #
    # But http_proxy and HTTP_PROXY is treated specially under CGI environment.
    # It's because HTTP_PROXY may be set by Proxy: header.
    # So HTTP_PROXY is not used.
    # http_proxy is not used too if the variable is case insensitive.
    # CGI_HTTP_PROXY can be used instead.
    def find_proxy(env=ENV)
      raise BadURIError, "relative URI: #{self}" if self.relative?
      name = self.scheme.downcase + '_proxy'
      proxy_uri = nil
      if name == 'http_proxy' && env.include?('REQUEST_METHOD') # CGI?
        # HTTP_PROXY conflicts with *_proxy for proxy settings and
        # HTTP_* for header information in CGI.
        # So it should be careful to use it.
        pairs = env.reject {|k, v| /\Ahttp_proxy\z/i !~ k }
        case pairs.length
        when 0 # no proxy setting anyway.
          proxy_uri = nil
        when 1
          k, _ = pairs.shift
          if k == 'http_proxy' && env[k.upcase] == nil
            # http_proxy is safe to use because ENV is case sensitive.
            proxy_uri = env[name]
          else
            proxy_uri = nil
          end
        else # http_proxy is safe to use because ENV is case sensitive.
          proxy_uri = env.to_hash[name]
        end
        if !proxy_uri
          # Use CGI_HTTP_PROXY.  cf. libwww-perl.
          proxy_uri = env["CGI_#{name.upcase}"]
        end
      elsif name == 'http_proxy'
        unless proxy_uri = env[name]
          if proxy_uri = env[name.upcase]
            warn 'The environment variable HTTP_PROXY is discouraged.  Use http_proxy.', uplevel: 1
          end
        end
      else
        proxy_uri = env[name] || env[name.upcase]
      end

      if proxy_uri.nil? || proxy_uri.empty?
        return nil
      end

      if self.hostname
        begin
          addr = IPSocket.getaddress(self.hostname)
          return nil if /\A127\.|\A::1\z/ =~ addr
        rescue SocketError
        end
      end

      name = 'no_proxy'
      if no_proxy = env[name] || env[name.upcase]
        return nil unless URI::Generic.use_proxy?(self.hostname, addr, self.port, no_proxy)
      end
      URI.parse(proxy_uri)
    end

    def self.use_proxy?(hostname, addr, port, no_proxy) # :nodoc:
      hostname = hostname.downcase
      dothostname = ".#{hostname}"
      no_proxy.scan(/([^:,\s]+)(?::(\d+))?/) {|p_host, p_port|
        if !p_port || port == p_port.to_i
          if p_host.start_with?('.')
            return false if hostname.end_with?(p_host.downcase)
          else
            return false if dothostname.end_with?(".#{p_host.downcase}")
          end
          if addr
            begin
              return false if IPAddr.new(p_host).include?(addr)
            rescue IPAddr::InvalidAddressError
              next
            end
          end
        end
      }
      true
    end
  end
end
# frozen_string_literal: true

require 'socket'
require 'resolv'

class << IPSocket
  # :stopdoc:
  alias original_resolv_getaddress getaddress
  # :startdoc:
  def getaddress(host)
    begin
      return Resolv.getaddress(host).to_s
    rescue Resolv::ResolvError
      raise SocketError, "Hostname not known: #{host}"
    end
  end
end

class TCPSocket < IPSocket
  # :stopdoc:
  alias original_resolv_initialize initialize
  # :startdoc:
  def initialize(host, serv, *rest)
    rest[0] = IPSocket.getaddress(rest[0]) if rest[0]
    original_resolv_initialize(IPSocket.getaddress(host), serv, *rest)
  end
end

class UDPSocket < IPSocket
  # :stopdoc:
  alias original_resolv_bind bind
  # :startdoc:
  def bind(host, port)
    host = IPSocket.getaddress(host) if host != ""
    original_resolv_bind(host, port)
  end

  # :stopdoc:
  alias original_resolv_connect connect
  # :startdoc:
  def connect(host, port)
    original_resolv_connect(IPSocket.getaddress(host), port)
  end

  # :stopdoc:
  alias original_resolv_send send
  # :startdoc:
  def send(mesg, flags, *rest)
    if rest.length == 2
      host, port = rest
      begin
        addrs = Resolv.getaddresses(host)
      rescue Resolv::ResolvError
        raise SocketError, "Hostname not known: #{host}"
      end
      addrs[0...-1].each {|addr|
        begin
          return original_resolv_send(mesg, flags, addr, port)
        rescue SystemCallError
        end
      }
      original_resolv_send(mesg, flags, addrs[-1], port)
    else
      original_resolv_send(mesg, flags, *rest)
    end
  end
end

class SOCKSSocket < TCPSocket
  # :stopdoc:
  alias original_resolv_initialize initialize
  # :startdoc:
  def initialize(host, serv)
    original_resolv_initialize(IPSocket.getaddress(host), port)
  end
end if defined? SOCKSSocket
# encoding: utf-8
# frozen_string_literal: false
#
# = matrix.rb
#
# An implementation of Matrix and Vector classes.
#
# See classes Matrix and Vector for documentation.
#
# Current Maintainer:: Marc-André Lafortune
# Original Author:: Keiju ISHITSUKA
# Original Documentation:: Gavin Sinclair (sourced from <i>Ruby in a Nutshell</i> (Matsumoto, O'Reilly))
##

require_relative "matrix/version"

module ExceptionForMatrix # :nodoc:
  class ErrDimensionMismatch < StandardError
    def initialize(val = nil)
      if val
        super(val)
      else
        super("Dimension mismatch")
      end
    end
  end

  class ErrNotRegular < StandardError
    def initialize(val = nil)
      if val
        super(val)
      else
        super("Not Regular Matrix")
      end
    end
  end

  class ErrOperationNotDefined < StandardError
    def initialize(vals)
      if vals.is_a?(Array)
        super("Operation(#{vals[0]}) can't be defined: #{vals[1]} op #{vals[2]}")
      else
        super(vals)
      end
    end
  end

  class ErrOperationNotImplemented < StandardError
    def initialize(vals)
      super("Sorry, Operation(#{vals[0]}) not implemented: #{vals[1]} op #{vals[2]}")
    end
  end
end

#
# The +Matrix+ class represents a mathematical matrix. It provides methods for creating
# matrices, operating on them arithmetically and algebraically,
# and determining their mathematical properties such as trace, rank, inverse, determinant,
# or eigensystem.
#
class Matrix
  include Enumerable
  include ExceptionForMatrix
  autoload :EigenvalueDecomposition, "matrix/eigenvalue_decomposition"
  autoload :LUPDecomposition, "matrix/lup_decomposition"

  # instance creations
  private_class_method :new
  attr_reader :rows
  protected :rows

  #
  # Creates a matrix where each argument is a row.
  #   Matrix[ [25, 93], [-1, 66] ]
  #   #   =>  25 93
  #   #       -1 66
  #
  def Matrix.[](*rows)
    rows(rows, false)
  end

  #
  # Creates a matrix where +rows+ is an array of arrays, each of which is a row
  # of the matrix.  If the optional argument +copy+ is false, use the given
  # arrays as the internal structure of the matrix without copying.
  #   Matrix.rows([[25, 93], [-1, 66]])
  #   #   =>  25 93
  #   #       -1 66
  #
  def Matrix.rows(rows, copy = true)
    rows = convert_to_array(rows, copy)
    rows.map! do |row|
      convert_to_array(row, copy)
    end
    size = (rows[0] || []).size
    rows.each do |row|
      raise ErrDimensionMismatch, "row size differs (#{row.size} should be #{size})" unless row.size == size
    end
    new rows, size
  end

  #
  # Creates a matrix using +columns+ as an array of column vectors.
  #   Matrix.columns([[25, 93], [-1, 66]])
  #   #   =>  25 -1
  #   #       93 66
  #
  def Matrix.columns(columns)
    rows(columns, false).transpose
  end

  #
  # Creates a matrix of size +row_count+ x +column_count+.
  # It fills the values by calling the given block,
  # passing the current row and column.
  # Returns an enumerator if no block is given.
  #
  #   m = Matrix.build(2, 4) {|row, col| col - row }
  #   #  => Matrix[[0, 1, 2, 3], [-1, 0, 1, 2]]
  #   m = Matrix.build(3) { rand }
  #   #  => a 3x3 matrix with random elements
  #
  def Matrix.build(row_count, column_count = row_count)
    row_count = CoercionHelper.coerce_to_int(row_count)
    column_count = CoercionHelper.coerce_to_int(column_count)
    raise ArgumentError if row_count < 0 || column_count < 0
    return to_enum :build, row_count, column_count unless block_given?
    rows = Array.new(row_count) do |i|
      Array.new(column_count) do |j|
        yield i, j
      end
    end
    new rows, column_count
  end

  #
  # Creates a matrix where the diagonal elements are composed of +values+.
  #   Matrix.diagonal(9, 5, -3)
  #   #  =>  9  0  0
  #   #      0  5  0
  #   #      0  0 -3
  #
  def Matrix.diagonal(*values)
    size = values.size
    return Matrix.empty if size == 0
    rows = Array.new(size) {|j|
      row = Array.new(size, 0)
      row[j] = values[j]
      row
    }
    new rows
  end

  #
  # Creates an +n+ by +n+ diagonal matrix where each diagonal element is
  # +value+.
  #   Matrix.scalar(2, 5)
  #   #  => 5 0
  #   #     0 5
  #
  def Matrix.scalar(n, value)
    diagonal(*Array.new(n, value))
  end

  #
  # Creates an +n+ by +n+ identity matrix.
  #   Matrix.identity(2)
  #   #  => 1 0
  #   #     0 1
  #
  def Matrix.identity(n)
    scalar(n, 1)
  end
  class << Matrix
    alias_method :unit, :identity
    alias_method :I, :identity
  end

  #
  # Creates a zero matrix.
  #   Matrix.zero(2)
  #   #  => 0 0
  #   #     0 0
  #
  def Matrix.zero(row_count, column_count = row_count)
    rows = Array.new(row_count){Array.new(column_count, 0)}
    new rows, column_count
  end

  #
  # Creates a single-row matrix where the values of that row are as given in
  # +row+.
  #   Matrix.row_vector([4,5,6])
  #   #  => 4 5 6
  #
  def Matrix.row_vector(row)
    row = convert_to_array(row)
    new [row]
  end

  #
  # Creates a single-column matrix where the values of that column are as given
  # in +column+.
  #   Matrix.column_vector([4,5,6])
  #   #  => 4
  #   #     5
  #   #     6
  #
  def Matrix.column_vector(column)
    column = convert_to_array(column)
    new [column].transpose, 1
  end

  #
  # Creates a empty matrix of +row_count+ x +column_count+.
  # At least one of +row_count+ or +column_count+ must be 0.
  #
  #   m = Matrix.empty(2, 0)
  #   m == Matrix[ [], [] ]
  #   #  => true
  #   n = Matrix.empty(0, 3)
  #   n == Matrix.columns([ [], [], [] ])
  #   #  => true
  #   m * n
  #   #  => Matrix[[0, 0, 0], [0, 0, 0]]
  #
  def Matrix.empty(row_count = 0, column_count = 0)
    raise ArgumentError, "One size must be 0" if column_count != 0 && row_count != 0
    raise ArgumentError, "Negative size" if column_count < 0 || row_count < 0

    new([[]]*row_count, column_count)
  end

  #
  # Create a matrix by stacking matrices vertically
  #
  #   x = Matrix[[1, 2], [3, 4]]
  #   y = Matrix[[5, 6], [7, 8]]
  #   Matrix.vstack(x, y) # => Matrix[[1, 2], [3, 4], [5, 6], [7, 8]]
  #
  def Matrix.vstack(x, *matrices)
    x = CoercionHelper.coerce_to_matrix(x)
    result = x.send(:rows).map(&:dup)
    matrices.each do |m|
      m = CoercionHelper.coerce_to_matrix(m)
      if m.column_count != x.column_count
        raise ErrDimensionMismatch, "The given matrices must have #{x.column_count} columns, but one has #{m.column_count}"
      end
      result.concat(m.send(:rows))
    end
    new result, x.column_count
  end


  #
  # Create a matrix by stacking matrices horizontally
  #
  #   x = Matrix[[1, 2], [3, 4]]
  #   y = Matrix[[5, 6], [7, 8]]
  #   Matrix.hstack(x, y) # => Matrix[[1, 2, 5, 6], [3, 4, 7, 8]]
  #
  def Matrix.hstack(x, *matrices)
    x = CoercionHelper.coerce_to_matrix(x)
    result = x.send(:rows).map(&:dup)
    total_column_count = x.column_count
    matrices.each do |m|
      m = CoercionHelper.coerce_to_matrix(m)
      if m.row_count != x.row_count
        raise ErrDimensionMismatch, "The given matrices must have #{x.row_count} rows, but one has #{m.row_count}"
      end
      result.each_with_index do |row, i|
        row.concat m.send(:rows)[i]
      end
      total_column_count += m.column_count
    end
    new result, total_column_count
  end

  # :call-seq:
  #   Matrix.combine(*matrices) { |*elements| ... }
  #
  # Create a matrix by combining matrices entrywise, using the given block
  #
  #   x = Matrix[[6, 6], [4, 4]]
  #   y = Matrix[[1, 2], [3, 4]]
  #   Matrix.combine(x, y) {|a, b| a - b} # => Matrix[[5, 4], [1, 0]]
  #
  def Matrix.combine(*matrices)
    return to_enum(__method__, *matrices) unless block_given?

    return Matrix.empty if matrices.empty?
    matrices.map!(&CoercionHelper.method(:coerce_to_matrix))
    x = matrices.first
    matrices.each do |m|
      raise ErrDimensionMismatch unless x.row_count == m.row_count && x.column_count == m.column_count
    end

    rows = Array.new(x.row_count) do |i|
      Array.new(x.column_count) do |j|
        yield matrices.map{|m| m[i,j]}
      end
    end
    new rows, x.column_count
  end

  # :call-seq:
  #   combine(*other_matrices) { |*elements| ... }
  #
  # Creates new matrix by combining with <i>other_matrices</i> entrywise,
  # using the given block.
  #
  #   x = Matrix[[6, 6], [4, 4]]
  #   y = Matrix[[1, 2], [3, 4]]
  #   x.combine(y) {|a, b| a - b} # => Matrix[[5, 4], [1, 0]]
  def combine(*matrices, &block)
    Matrix.combine(self, *matrices, &block)
  end

  #
  # Matrix.new is private; use ::rows, ::columns, ::[], etc... to create.
  #
  def initialize(rows, column_count = rows[0].size)
    # No checking is done at this point. rows must be an Array of Arrays.
    # column_count must be the size of the first row, if there is one,
    # otherwise it *must* be specified and can be any integer >= 0
    @rows = rows
    @column_count = column_count
  end

  private def new_matrix(rows, column_count = rows[0].size) # :nodoc:
    self.class.send(:new, rows, column_count) # bypass privacy of Matrix.new
  end

  #
  # Returns element (+i+,+j+) of the matrix.  That is: row +i+, column +j+.
  #
  def [](i, j)
    @rows.fetch(i){return nil}[j]
  end
  alias element []
  alias component []

  #
  # :call-seq:
  #   matrix[range, range] = matrix/element
  #   matrix[range, integer] = vector/column_matrix/element
  #   matrix[integer, range] = vector/row_matrix/element
  #   matrix[integer, integer] = element
  #
  # Set element or elements of matrix.
  def []=(i, j, v)
    raise FrozenError, "can't modify frozen Matrix" if frozen?
    rows = check_range(i, :row) or row = check_int(i, :row)
    columns = check_range(j, :column) or column = check_int(j, :column)
    if rows && columns
      set_row_and_col_range(rows, columns, v)
    elsif rows
      set_row_range(rows, column, v)
    elsif columns
      set_col_range(row, columns, v)
    else
      set_value(row, column, v)
    end
  end
  alias set_element []=
  alias set_component []=
  private :set_element, :set_component

  # Returns range or nil
  private def check_range(val, direction)
    return unless val.is_a?(Range)
    count = direction == :row ? row_count : column_count
    CoercionHelper.check_range(val, count, direction)
  end

  private def check_int(val, direction)
    count = direction == :row ? row_count : column_count
    CoercionHelper.check_int(val, count, direction)
  end

  private def set_value(row, col, value)
    raise ErrDimensionMismatch, "Expected a a value, got a #{value.class}" if value.respond_to?(:to_matrix)

    @rows[row][col] = value
  end

  private def set_row_and_col_range(row_range, col_range, value)
    if value.is_a?(Matrix)
      if row_range.size != value.row_count || col_range.size != value.column_count
        raise ErrDimensionMismatch, [
          'Expected a Matrix of dimensions',
          "#{row_range.size}x#{col_range.size}",
          'got',
          "#{value.row_count}x#{value.column_count}",
        ].join(' ')
      end
      source = value.instance_variable_get :@rows
      row_range.each_with_index do |row, i|
        @rows[row][col_range] = source[i]
      end
    elsif value.is_a?(Vector)
      raise ErrDimensionMismatch, 'Expected a Matrix or a value, got a Vector'
    else
      value_to_set = Array.new(col_range.size, value)
      row_range.each do |i|
        @rows[i][col_range] = value_to_set
      end
    end
  end

  private def set_row_range(row_range, col, value)
    if value.is_a?(Vector)
      raise ErrDimensionMismatch unless row_range.size == value.size
      set_column_vector(row_range, col, value)
    elsif value.is_a?(Matrix)
      raise ErrDimensionMismatch unless value.column_count == 1
      value = value.column(0)
      raise ErrDimensionMismatch unless row_range.size == value.size
      set_column_vector(row_range, col, value)
    else
      @rows[row_range].each{|e| e[col] = value }
    end
  end

  private def set_column_vector(row_range, col, value)
    value.each_with_index do |e, index|
      r = row_range.begin + index
      @rows[r][col] = e
    end
  end

  private def set_col_range(row, col_range, value)
    value = if value.is_a?(Vector)
      value.to_a
    elsif value.is_a?(Matrix)
      raise ErrDimensionMismatch unless value.row_count == 1
      value.row(0).to_a
    else
      Array.new(col_range.size, value)
    end
    raise ErrDimensionMismatch unless col_range.size == value.size
    @rows[row][col_range] = value
  end

  #
  # Returns the number of rows.
  #
  def row_count
    @rows.size
  end

  alias_method :row_size, :row_count
  #
  # Returns the number of columns.
  #
  attr_reader :column_count
  alias_method :column_size, :column_count

  #
  # Returns row vector number +i+ of the matrix as a Vector (starting at 0 like
  # an array).  When a block is given, the elements of that vector are iterated.
  #
  def row(i, &block) # :yield: e
    if block_given?
      @rows.fetch(i){return self}.each(&block)
      self
    else
      Vector.elements(@rows.fetch(i){return nil})
    end
  end

  #
  # Returns column vector number +j+ of the matrix as a Vector (starting at 0
  # like an array).  When a block is given, the elements of that vector are
  # iterated.
  #
  def column(j) # :yield: e
    if block_given?
      return self if j >= column_count || j < -column_count
      row_count.times do |i|
        yield @rows[i][j]
      end
      self
    else
      return nil if j >= column_count || j < -column_count
      col = Array.new(row_count) {|i|
        @rows[i][j]
      }
      Vector.elements(col, false)
    end
  end

  #
  # Returns a matrix that is the result of iteration of the given block over all
  # elements of the matrix.
  # Elements can be restricted by passing an argument:
  # * :all (default): yields all elements
  # * :diagonal: yields only elements on the diagonal
  # * :off_diagonal: yields all elements except on the diagonal
  # * :lower: yields only elements on or below the diagonal
  # * :strict_lower: yields only elements below the diagonal
  # * :strict_upper: yields only elements above the diagonal
  # * :upper: yields only elements on or above the diagonal
  #   Matrix[ [1,2], [3,4] ].collect { |e| e**2 }
  #   #  => 1  4
  #   #     9 16
  #
  def collect(which = :all, &block) # :yield: e
    return to_enum(:collect, which) unless block_given?
    dup.collect!(which, &block)
  end
  alias_method :map, :collect

  #
  # Invokes the given block for each element of matrix, replacing the element with the value
  # returned by the block.
  # Elements can be restricted by passing an argument:
  # * :all (default): yields all elements
  # * :diagonal: yields only elements on the diagonal
  # * :off_diagonal: yields all elements except on the diagonal
  # * :lower: yields only elements on or below the diagonal
  # * :strict_lower: yields only elements below the diagonal
  # * :strict_upper: yields only elements above the diagonal
  # * :upper: yields only elements on or above the diagonal
  #
  def collect!(which = :all)
    return to_enum(:collect!, which) unless block_given?
    raise FrozenError, "can't modify frozen Matrix" if frozen?
    each_with_index(which){ |e, row_index, col_index| @rows[row_index][col_index] = yield e }
  end

  alias map! collect!

  def freeze
    @rows.each(&:freeze).freeze

    super
  end

  #
  # Yields all elements of the matrix, starting with those of the first row,
  # or returns an Enumerator if no block given.
  # Elements can be restricted by passing an argument:
  # * :all (default): yields all elements
  # * :diagonal: yields only elements on the diagonal
  # * :off_diagonal: yields all elements except on the diagonal
  # * :lower: yields only elements on or below the diagonal
  # * :strict_lower: yields only elements below the diagonal
  # * :strict_upper: yields only elements above the diagonal
  # * :upper: yields only elements on or above the diagonal
  #
  #     Matrix[ [1,2], [3,4] ].each { |e| puts e }
  #       # => prints the numbers 1 to 4
  #     Matrix[ [1,2], [3,4] ].each(:strict_lower).to_a # => [3]
  #
  def each(which = :all, &block) # :yield: e
    return to_enum :each, which unless block_given?
    last = column_count - 1
    case which
    when :all
      @rows.each do |row|
        row.each(&block)
      end
    when :diagonal
      @rows.each_with_index do |row, row_index|
        yield row.fetch(row_index){return self}
      end
    when :off_diagonal
      @rows.each_with_index do |row, row_index|
        column_count.times do |col_index|
          yield row[col_index] unless row_index == col_index
        end
      end
    when :lower
      @rows.each_with_index do |row, row_index|
        0.upto([row_index, last].min) do |col_index|
          yield row[col_index]
        end
      end
    when :strict_lower
      @rows.each_with_index do |row, row_index|
        [row_index, column_count].min.times do |col_index|
          yield row[col_index]
        end
      end
    when :strict_upper
      @rows.each_with_index do |row, row_index|
        (row_index+1).upto(last) do |col_index|
          yield row[col_index]
        end
      end
    when :upper
      @rows.each_with_index do |row, row_index|
        row_index.upto(last) do |col_index|
          yield row[col_index]
        end
      end
    else
      raise ArgumentError, "expected #{which.inspect} to be one of :all, :diagonal, :off_diagonal, :lower, :strict_lower, :strict_upper or :upper"
    end
    self
  end

  #
  # Same as #each, but the row index and column index in addition to the element
  #
  #   Matrix[ [1,2], [3,4] ].each_with_index do |e, row, col|
  #     puts "#{e} at #{row}, #{col}"
  #   end
  #     # => Prints:
  #     #    1 at 0, 0
  #     #    2 at 0, 1
  #     #    3 at 1, 0
  #     #    4 at 1, 1
  #
  def each_with_index(which = :all) # :yield: e, row, column
    return to_enum :each_with_index, which unless block_given?
    last = column_count - 1
    case which
    when :all
      @rows.each_with_index do |row, row_index|
        row.each_with_index do |e, col_index|
          yield e, row_index, col_index
        end
      end
    when :diagonal
      @rows.each_with_index do |row, row_index|
        yield row.fetch(row_index){return self}, row_index, row_index
      end
    when :off_diagonal
      @rows.each_with_index do |row, row_index|
        column_count.times do |col_index|
          yield row[col_index], row_index, col_index unless row_index == col_index
        end
      end
    when :lower
      @rows.each_with_index do |row, row_index|
        0.upto([row_index, last].min) do |col_index|
          yield row[col_index], row_index, col_index
        end
      end
    when :strict_lower
      @rows.each_with_index do |row, row_index|
        [row_index, column_count].min.times do |col_index|
          yield row[col_index], row_index, col_index
        end
      end
    when :strict_upper
      @rows.each_with_index do |row, row_index|
        (row_index+1).upto(last) do |col_index|
          yield row[col_index], row_index, col_index
        end
      end
    when :upper
      @rows.each_with_index do |row, row_index|
        row_index.upto(last) do |col_index|
          yield row[col_index], row_index, col_index
        end
      end
    else
      raise ArgumentError, "expected #{which.inspect} to be one of :all, :diagonal, :off_diagonal, :lower, :strict_lower, :strict_upper or :upper"
    end
    self
  end

  SELECTORS = {all: true, diagonal: true, off_diagonal: true, lower: true, strict_lower: true, strict_upper: true, upper: true}.freeze
  #
  # :call-seq:
  #   index(value, selector = :all) -> [row, column]
  #   index(selector = :all){ block } -> [row, column]
  #   index(selector = :all) -> an_enumerator
  #
  # The index method is specialized to return the index as [row, column]
  # It also accepts an optional +selector+ argument, see #each for details.
  #
  #   Matrix[ [1,2], [3,4] ].index(&:even?) # => [0, 1]
  #   Matrix[ [1,1], [1,1] ].index(1, :strict_lower) # => [1, 0]
  #
  def index(*args)
    raise ArgumentError, "wrong number of arguments(#{args.size} for 0-2)" if args.size > 2
    which = (args.size == 2 || SELECTORS.include?(args.last)) ? args.pop : :all
    return to_enum :find_index, which, *args unless block_given? || args.size == 1
    if args.size == 1
      value = args.first
      each_with_index(which) do |e, row_index, col_index|
        return row_index, col_index if e == value
      end
    else
      each_with_index(which) do |e, row_index, col_index|
        return row_index, col_index if yield e
      end
    end
    nil
  end
  alias_method :find_index, :index

  #
  # Returns a section of the matrix.  The parameters are either:
  # *  start_row, nrows, start_col, ncols; OR
  # *  row_range, col_range
  #
  #   Matrix.diagonal(9, 5, -3).minor(0..1, 0..2)
  #   #  => 9 0 0
  #   #     0 5 0
  #
  # Like Array#[], negative indices count backward from the end of the
  # row or column (-1 is the last element). Returns nil if the starting
  # row or column is greater than row_count or column_count respectively.
  #
  def minor(*param)
    case param.size
    when 2
      row_range, col_range = param
      from_row = row_range.first
      from_row += row_count if from_row < 0
      to_row = row_range.end
      to_row += row_count if to_row < 0
      to_row += 1 unless row_range.exclude_end?
      size_row = to_row - from_row

      from_col = col_range.first
      from_col += column_count if from_col < 0
      to_col = col_range.end
      to_col += column_count if to_col < 0
      to_col += 1 unless col_range.exclude_end?
      size_col = to_col - from_col
    when 4
      from_row, size_row, from_col, size_col = param
      return nil if size_row < 0 || size_col < 0
      from_row += row_count if from_row < 0
      from_col += column_count if from_col < 0
    else
      raise ArgumentError, param.inspect
    end

    return nil if from_row > row_count || from_col > column_count || from_row < 0 || from_col < 0
    rows = @rows[from_row, size_row].collect{|row|
      row[from_col, size_col]
    }
    new_matrix rows, [column_count - from_col, size_col].min
  end

  #
  # Returns the submatrix obtained by deleting the specified row and column.
  #
  #   Matrix.diagonal(9, 5, -3, 4).first_minor(1, 2)
  #   #  => 9 0 0
  #   #     0 0 0
  #   #     0 0 4
  #
  def first_minor(row, column)
    raise RuntimeError, "first_minor of empty matrix is not defined" if empty?

    unless 0 <= row && row < row_count
      raise ArgumentError, "invalid row (#{row.inspect} for 0..#{row_count - 1})"
    end

    unless 0 <= column && column < column_count
      raise ArgumentError, "invalid column (#{column.inspect} for 0..#{column_count - 1})"
    end

    arrays = to_a
    arrays.delete_at(row)
    arrays.each do |array|
      array.delete_at(column)
    end

    new_matrix arrays, column_count - 1
  end

  #
  # Returns the (row, column) cofactor which is obtained by multiplying
  # the first minor by (-1)**(row + column).
  #
  #   Matrix.diagonal(9, 5, -3, 4).cofactor(1, 1)
  #   #  => -108
  #
  def cofactor(row, column)
    raise RuntimeError, "cofactor of empty matrix is not defined" if empty?
    raise ErrDimensionMismatch unless square?

    det_of_minor = first_minor(row, column).determinant
    det_of_minor * (-1) ** (row + column)
  end

  #
  # Returns the adjugate of the matrix.
  #
  #   Matrix[ [7,6],[3,9] ].adjugate
  #   #  => 9 -6
  #   #     -3 7
  #
  def adjugate
    raise ErrDimensionMismatch unless square?
    Matrix.build(row_count, column_count) do |row, column|
      cofactor(column, row)
    end
  end

  #
  # Returns the Laplace expansion along given row or column.
  #
  #    Matrix[[7,6], [3,9]].laplace_expansion(column: 1)
  #    # => 45
  #
  #    Matrix[[Vector[1, 0], Vector[0, 1]], [2, 3]].laplace_expansion(row: 0)
  #    # => Vector[3, -2]
  #
  #
  def laplace_expansion(row: nil, column: nil)
    num = row || column

    if !num || (row && column)
      raise ArgumentError, "exactly one the row or column arguments must be specified"
    end

    raise ErrDimensionMismatch unless square?
    raise RuntimeError, "laplace_expansion of empty matrix is not defined" if empty?

    unless 0 <= num && num < row_count
      raise ArgumentError, "invalid num (#{num.inspect} for 0..#{row_count - 1})"
    end

    send(row ? :row : :column, num).map.with_index { |e, k|
      e * cofactor(*(row ? [num, k] : [k,num]))
    }.inject(:+)
  end
  alias_method :cofactor_expansion, :laplace_expansion


  #--
  # TESTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  #++

  #
  # Returns +true+ if this is a diagonal matrix.
  # Raises an error if matrix is not square.
  #
  def diagonal?
    raise ErrDimensionMismatch unless square?
    each(:off_diagonal).all?(&:zero?)
  end

  #
  # Returns +true+ if this is an empty matrix, i.e. if the number of rows
  # or the number of columns is 0.
  #
  def empty?
    column_count == 0 || row_count == 0
  end

  #
  # Returns +true+ if this is an hermitian matrix.
  # Raises an error if matrix is not square.
  #
  def hermitian?
    raise ErrDimensionMismatch unless square?
    each_with_index(:upper).all? do |e, row, col|
      e == rows[col][row].conj
    end
  end

  #
  # Returns +true+ if this is a lower triangular matrix.
  #
  def lower_triangular?
    each(:strict_upper).all?(&:zero?)
  end

  #
  # Returns +true+ if this is a normal matrix.
  # Raises an error if matrix is not square.
  #
  def normal?
    raise ErrDimensionMismatch unless square?
    rows.each_with_index do |row_i, i|
      rows.each_with_index do |row_j, j|
        s = 0
        rows.each_with_index do |row_k, k|
          s += row_i[k] * row_j[k].conj - row_k[i].conj * row_k[j]
        end
        return false unless s == 0
      end
    end
    true
  end

  #
  # Returns +true+ if this is an orthogonal matrix
  # Raises an error if matrix is not square.
  #
  def orthogonal?
    raise ErrDimensionMismatch unless square?

    rows.each_with_index do |row_i, i|
      rows.each_with_index do |row_j, j|
        s = 0
        row_count.times do |k|
          s += row_i[k] * row_j[k]
        end
        return false unless s == (i == j ? 1 : 0)
      end
    end
    true
  end

  #
  # Returns +true+ if this is a permutation matrix
  # Raises an error if matrix is not square.
  #
  def permutation?
    raise ErrDimensionMismatch unless square?
    cols = Array.new(column_count)
    rows.each_with_index do |row, i|
      found = false
      row.each_with_index do |e, j|
        if e == 1
          return false if found || cols[j]
          found = cols[j] = true
        elsif e != 0
          return false
        end
      end
      return false unless found
    end
    true
  end

  #
  # Returns +true+ if all entries of the matrix are real.
  #
  def real?
    all?(&:real?)
  end

  #
  # Returns +true+ if this is a regular (i.e. non-singular) matrix.
  #
  def regular?
    not singular?
  end

  #
  # Returns +true+ if this is a singular matrix.
  #
  def singular?
    determinant == 0
  end

  #
  # Returns +true+ if this is a square matrix.
  #
  def square?
    column_count == row_count
  end

  #
  # Returns +true+ if this is a symmetric matrix.
  # Raises an error if matrix is not square.
  #
  def symmetric?
    raise ErrDimensionMismatch unless square?
    each_with_index(:strict_upper) do |e, row, col|
      return false if e != rows[col][row]
    end
    true
  end

  #
  # Returns +true+ if this is an antisymmetric matrix.
  # Raises an error if matrix is not square.
  #
  def antisymmetric?
    raise ErrDimensionMismatch unless square?
    each_with_index(:upper) do |e, row, col|
      return false unless e == -rows[col][row]
    end
    true
  end
  alias_method :skew_symmetric?, :antisymmetric?

  #
  # Returns +true+ if this is a unitary matrix
  # Raises an error if matrix is not square.
  #
  def unitary?
    raise ErrDimensionMismatch unless square?
    rows.each_with_index do |row_i, i|
      rows.each_with_index do |row_j, j|
        s = 0
        row_count.times do |k|
          s += row_i[k].conj * row_j[k]
        end
        return false unless s == (i == j ? 1 : 0)
      end
    end
    true
  end

  #
  # Returns +true+ if this is an upper triangular matrix.
  #
  def upper_triangular?
    each(:strict_lower).all?(&:zero?)
  end

  #
  # Returns +true+ if this is a matrix with only zero elements
  #
  def zero?
    all?(&:zero?)
  end

  #--
  # OBJECT METHODS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  #++

  #
  # Returns +true+ if and only if the two matrices contain equal elements.
  #
  def ==(other)
    return false unless Matrix === other &&
                        column_count == other.column_count # necessary for empty matrices
    rows == other.rows
  end

  def eql?(other)
    return false unless Matrix === other &&
                        column_count == other.column_count # necessary for empty matrices
    rows.eql? other.rows
  end

  #
  # Called for dup & clone.
  #
  private def initialize_copy(m)
    super
    @rows = @rows.map(&:dup) unless frozen?
  end

  #
  # Returns a hash-code for the matrix.
  #
  def hash
    @rows.hash
  end

  #--
  # ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  #++

  #
  # Matrix multiplication.
  #   Matrix[[2,4], [6,8]] * Matrix.identity(2)
  #   #  => 2 4
  #   #     6 8
  #
  def *(m) # m is matrix or vector or number
    case(m)
    when Numeric
      new_rows = @rows.collect {|row|
        row.collect {|e| e * m }
      }
      return new_matrix new_rows, column_count
    when Vector
      m = self.class.column_vector(m)
      r = self * m
      return r.column(0)
    when Matrix
      raise ErrDimensionMismatch if column_count != m.row_count
      m_rows = m.rows
      new_rows = rows.map do |row_i|
        Array.new(m.column_count) do |j|
          vij = 0
          column_count.times do |k|
            vij += row_i[k] * m_rows[k][j]
          end
          vij
        end
      end
      return new_matrix new_rows, m.column_count
    else
      return apply_through_coercion(m, __method__)
    end
  end

  #
  # Matrix addition.
  #   Matrix.scalar(2,5) + Matrix[[1,0], [-4,7]]
  #   #  =>  6  0
  #   #     -4 12
  #
  def +(m)
    case m
    when Numeric
      raise ErrOperationNotDefined, ["+", self.class, m.class]
    when Vector
      m = self.class.column_vector(m)
    when Matrix
    else
      return apply_through_coercion(m, __method__)
    end

    raise ErrDimensionMismatch unless row_count == m.row_count && column_count == m.column_count

    rows = Array.new(row_count) {|i|
      Array.new(column_count) {|j|
        self[i, j] + m[i, j]
      }
    }
    new_matrix rows, column_count
  end

  #
  # Matrix subtraction.
  #   Matrix[[1,5], [4,2]] - Matrix[[9,3], [-4,1]]
  #   #  => -8  2
  #   #      8  1
  #
  def -(m)
    case m
    when Numeric
      raise ErrOperationNotDefined, ["-", self.class, m.class]
    when Vector
      m = self.class.column_vector(m)
    when Matrix
    else
      return apply_through_coercion(m, __method__)
    end

    raise ErrDimensionMismatch unless row_count == m.row_count && column_count == m.column_count

    rows = Array.new(row_count) {|i|
      Array.new(column_count) {|j|
        self[i, j] - m[i, j]
      }
    }
    new_matrix rows, column_count
  end

  #
  # Matrix division (multiplication by the inverse).
  #   Matrix[[7,6], [3,9]] / Matrix[[2,9], [3,1]]
  #   #  => -7  1
  #   #     -3 -6
  #
  def /(other)
    case other
    when Numeric
      rows = @rows.collect {|row|
        row.collect {|e| e / other }
      }
      return new_matrix rows, column_count
    when Matrix
      return self * other.inverse
    else
      return apply_through_coercion(other, __method__)
    end
  end

  #
  # Hadamard product
  #    Matrix[[1,2], [3,4]].hadamard_product(Matrix[[1,2], [3,2]])
  #    #  => 1  4
  #    #     9  8
  #
  def hadamard_product(m)
    combine(m){|a, b| a * b}
  end
  alias_method :entrywise_product, :hadamard_product

  #
  # Returns the inverse of the matrix.
  #   Matrix[[-1, -1], [0, -1]].inverse
  #   #  => -1  1
  #   #      0 -1
  #
  def inverse
    raise ErrDimensionMismatch unless square?
    self.class.I(row_count).send(:inverse_from, self)
  end
  alias_method :inv, :inverse

  private def inverse_from(src) # :nodoc:
    last = row_count - 1
    a = src.to_a

    0.upto(last) do |k|
      i = k
      akk = a[k][k].abs
      (k+1).upto(last) do |j|
        v = a[j][k].abs
        if v > akk
          i = j
          akk = v
        end
      end
      raise ErrNotRegular if akk == 0
      if i != k
        a[i], a[k] = a[k], a[i]
        @rows[i], @rows[k] = @rows[k], @rows[i]
      end
      akk = a[k][k]

      0.upto(last) do |ii|
        next if ii == k
        q = a[ii][k].quo(akk)
        a[ii][k] = 0

        (k + 1).upto(last) do |j|
          a[ii][j] -= a[k][j] * q
        end
        0.upto(last) do |j|
          @rows[ii][j] -= @rows[k][j] * q
        end
      end

      (k+1).upto(last) do |j|
        a[k][j] = a[k][j].quo(akk)
      end
      0.upto(last) do |j|
        @rows[k][j] = @rows[k][j].quo(akk)
      end
    end
    self
  end

  #
  # Matrix exponentiation.
  # Equivalent to multiplying the matrix by itself N times.
  # Non integer exponents will be handled by diagonalizing the matrix.
  #
  #   Matrix[[7,6], [3,9]] ** 2
  #   #  => 67 96
  #   #     48 99
  #
  def **(exp)
    case exp
    when Integer
      case
      when exp == 0
        _make_sure_it_is_invertible = inverse
        self.class.identity(column_count)
      when exp < 0
        inverse.power_int(-exp)
      else
        power_int(exp)
      end
    when Numeric
      v, d, v_inv = eigensystem
      v * self.class.diagonal(*d.each(:diagonal).map{|e| e ** exp}) * v_inv
    else
      raise ErrOperationNotDefined, ["**", self.class, exp.class]
    end
  end

  protected def power_int(exp)
    # assumes `exp` is an Integer > 0
    #
    # Previous algorithm:
    #   build M**2, M**4 = (M**2)**2, M**8, ... and multiplying those you need
    #   e.g. M**0b1011 = M**11 = M * M**2 * M**8
    #                              ^  ^
    #   (highlighted the 2 out of 5 multiplications involving `M * x`)
    #
    # Current algorithm has same number of multiplications but with lower exponents:
    #    M**11 = M * (M * M**4)**2
    #              ^    ^  ^
    #   (highlighted the 3 out of 5 multiplications involving `M * x`)
    #
    # This should be faster for all (non nil-potent) matrices.
    case
    when exp == 1
      self
    when exp.odd?
      self * power_int(exp - 1)
    else
      sqrt = power_int(exp / 2)
      sqrt * sqrt
    end
  end

  def +@
    self
  end

  # Unary matrix negation.
  #
  #   -Matrix[[1,5], [4,2]]
  #   # => -1 -5
  #   #    -4 -2
  def -@
    collect {|e| -e }
  end

  #
  # Returns the absolute value elementwise
  #
  def abs
    collect(&:abs)
  end

  #--
  # MATRIX FUNCTIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  #++

  #
  # Returns the determinant of the matrix.
  #
  # Beware that using Float values can yield erroneous results
  # because of their lack of precision.
  # Consider using exact types like Rational or BigDecimal instead.
  #
  #   Matrix[[7,6], [3,9]].determinant
  #   #  => 45
  #
  def determinant
    raise ErrDimensionMismatch unless square?
    m = @rows
    case row_count
      # Up to 4x4, give result using Laplacian expansion by minors.
      # This will typically be faster, as well as giving good results
      # in case of Floats
    when 0
      +1
    when 1
      + m[0][0]
    when 2
      + m[0][0] * m[1][1] - m[0][1] * m[1][0]
    when 3
      m0, m1, m2 = m
      + m0[0] * m1[1] * m2[2] - m0[0] * m1[2] * m2[1] \
      - m0[1] * m1[0] * m2[2] + m0[1] * m1[2] * m2[0] \
      + m0[2] * m1[0] * m2[1] - m0[2] * m1[1] * m2[0]
    when 4
      m0, m1, m2, m3 = m
      + m0[0] * m1[1] * m2[2] * m3[3] - m0[0] * m1[1] * m2[3] * m3[2] \
      - m0[0] * m1[2] * m2[1] * m3[3] + m0[0] * m1[2] * m2[3] * m3[1] \
      + m0[0] * m1[3] * m2[1] * m3[2] - m0[0] * m1[3] * m2[2] * m3[1] \
      - m0[1] * m1[0] * m2[2] * m3[3] + m0[1] * m1[0] * m2[3] * m3[2] \
      + m0[1] * m1[2] * m2[0] * m3[3] - m0[1] * m1[2] * m2[3] * m3[0] \
      - m0[1] * m1[3] * m2[0] * m3[2] + m0[1] * m1[3] * m2[2] * m3[0] \
      + m0[2] * m1[0] * m2[1] * m3[3] - m0[2] * m1[0] * m2[3] * m3[1] \
      - m0[2] * m1[1] * m2[0] * m3[3] + m0[2] * m1[1] * m2[3] * m3[0] \
      + m0[2] * m1[3] * m2[0] * m3[1] - m0[2] * m1[3] * m2[1] * m3[0] \
      - m0[3] * m1[0] * m2[1] * m3[2] + m0[3] * m1[0] * m2[2] * m3[1] \
      + m0[3] * m1[1] * m2[0] * m3[2] - m0[3] * m1[1] * m2[2] * m3[0] \
      - m0[3] * m1[2] * m2[0] * m3[1] + m0[3] * m1[2] * m2[1] * m3[0]
    else
      # For bigger matrices, use an efficient and general algorithm.
      # Currently, we use the Gauss-Bareiss algorithm
      determinant_bareiss
    end
  end
  alias_method :det, :determinant

  #
  # Private. Use Matrix#determinant
  #
  # Returns the determinant of the matrix, using
  # Bareiss' multistep integer-preserving gaussian elimination.
  # It has the same computational cost order O(n^3) as standard Gaussian elimination.
  # Intermediate results are fraction free and of lower complexity.
  # A matrix of Integers will have thus intermediate results that are also Integers,
  # with smaller bignums (if any), while a matrix of Float will usually have
  # intermediate results with better precision.
  #
  private def determinant_bareiss
    size = row_count
    last = size - 1
    a = to_a
    no_pivot = Proc.new{ return 0 }
    sign = +1
    pivot = 1
    size.times do |k|
      previous_pivot = pivot
      if (pivot = a[k][k]) == 0
        switch = (k+1 ... size).find(no_pivot) {|row|
          a[row][k] != 0
        }
        a[switch], a[k] = a[k], a[switch]
        pivot = a[k][k]
        sign = -sign
      end
      (k+1).upto(last) do |i|
        ai = a[i]
        (k+1).upto(last) do |j|
          ai[j] =  (pivot * ai[j] - ai[k] * a[k][j]) / previous_pivot
        end
      end
    end
    sign * pivot
  end

  #
  # deprecated; use Matrix#determinant
  #
  def determinant_e
    warn "Matrix#determinant_e is deprecated; use #determinant", uplevel: 1
    determinant
  end
  alias_method :det_e, :determinant_e

  #
  # Returns a new matrix resulting by stacking horizontally
  # the receiver with the given matrices
  #
  #   x = Matrix[[1, 2], [3, 4]]
  #   y = Matrix[[5, 6], [7, 8]]
  #   x.hstack(y) # => Matrix[[1, 2, 5, 6], [3, 4, 7, 8]]
  #
  def hstack(*matrices)
    self.class.hstack(self, *matrices)
  end

  #
  # Returns the rank of the matrix.
  # Beware that using Float values can yield erroneous results
  # because of their lack of precision.
  # Consider using exact types like Rational or BigDecimal instead.
  #
  #   Matrix[[7,6], [3,9]].rank
  #   #  => 2
  #
  def rank
    # We currently use Bareiss' multistep integer-preserving gaussian elimination
    # (see comments on determinant)
    a = to_a
    last_column = column_count - 1
    last_row = row_count - 1
    pivot_row = 0
    previous_pivot = 1
    0.upto(last_column) do |k|
      switch_row = (pivot_row .. last_row).find {|row|
        a[row][k] != 0
      }
      if switch_row
        a[switch_row], a[pivot_row] = a[pivot_row], a[switch_row] unless pivot_row == switch_row
        pivot = a[pivot_row][k]
        (pivot_row+1).upto(last_row) do |i|
           ai = a[i]
           (k+1).upto(last_column) do |j|
             ai[j] =  (pivot * ai[j] - ai[k] * a[pivot_row][j]) / previous_pivot
           end
         end
        pivot_row += 1
        previous_pivot = pivot
      end
    end
    pivot_row
  end

  #
  # deprecated; use Matrix#rank
  #
  def rank_e
    warn "Matrix#rank_e is deprecated; use #rank", uplevel: 1
    rank
  end

  # Returns a matrix with entries rounded to the given precision
  # (see Float#round)
  #
  def round(ndigits=0)
    map{|e| e.round(ndigits)}
  end

  #
  # Returns the trace (sum of diagonal elements) of the matrix.
  #   Matrix[[7,6], [3,9]].trace
  #   #  => 16
  #
  def trace
    raise ErrDimensionMismatch unless square?
    (0...column_count).inject(0) do |tr, i|
      tr + @rows[i][i]
    end
  end
  alias_method :tr, :trace

  #
  # Returns the transpose of the matrix.
  #   Matrix[[1,2], [3,4], [5,6]]
  #   #  => 1 2
  #   #     3 4
  #   #     5 6
  #   Matrix[[1,2], [3,4], [5,6]].transpose
  #   #  => 1 3 5
  #   #     2 4 6
  #
  def transpose
    return self.class.empty(column_count, 0) if row_count.zero?
    new_matrix @rows.transpose, row_count
  end
  alias_method :t, :transpose

  #
  # Returns a new matrix resulting by stacking vertically
  # the receiver with the given matrices
  #
  #   x = Matrix[[1, 2], [3, 4]]
  #   y = Matrix[[5, 6], [7, 8]]
  #   x.vstack(y) # => Matrix[[1, 2], [3, 4], [5, 6], [7, 8]]
  #
  def vstack(*matrices)
    self.class.vstack(self, *matrices)
  end

  #--
  # DECOMPOSITIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  #++

  #
  # Returns the Eigensystem of the matrix; see +EigenvalueDecomposition+.
  #   m = Matrix[[1, 2], [3, 4]]
  #   v, d, v_inv = m.eigensystem
  #   d.diagonal? # => true
  #   v.inv == v_inv # => true
  #   (v * d * v_inv).round(5) == m # => true
  #
  def eigensystem
    EigenvalueDecomposition.new(self)
  end
  alias_method :eigen, :eigensystem

  #
  # Returns the LUP decomposition of the matrix; see +LUPDecomposition+.
  #   a = Matrix[[1, 2], [3, 4]]
  #   l, u, p = a.lup
  #   l.lower_triangular? # => true
  #   u.upper_triangular? # => true
  #   p.permutation?      # => true
  #   l * u == p * a      # => true
  #   a.lup.solve([2, 5]) # => Vector[(1/1), (1/2)]
  #
  def lup
    LUPDecomposition.new(self)
  end
  alias_method :lup_decomposition, :lup

  #--
  # COMPLEX ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  #++

  #
  # Returns the conjugate of the matrix.
  #   Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
  #   #  => 1+2i   i  0
  #   #        1   2  3
  #   Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].conjugate
  #   #  => 1-2i  -i  0
  #   #        1   2  3
  #
  def conjugate
    collect(&:conjugate)
  end
  alias_method :conj, :conjugate

  #
  # Returns the adjoint of the matrix.
  #
  #   Matrix[ [i,1],[2,-i] ].adjoint
  #   #  => -i 2
  #   #      1 i
  #
  def adjoint
    conjugate.transpose
  end

  #
  # Returns the imaginary part of the matrix.
  #   Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
  #   #  => 1+2i  i  0
  #   #        1  2  3
  #   Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].imaginary
  #   #  =>   2i  i  0
  #   #        0  0  0
  #
  def imaginary
    collect(&:imaginary)
  end
  alias_method :imag, :imaginary

  #
  # Returns the real part of the matrix.
  #   Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
  #   #  => 1+2i  i  0
  #   #        1  2  3
  #   Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].real
  #   #  =>    1  0  0
  #   #        1  2  3
  #
  def real
    collect(&:real)
  end

  #
  # Returns an array containing matrices corresponding to the real and imaginary
  # parts of the matrix
  #
  #   m.rect == [m.real, m.imag]  # ==> true for all matrices m
  #
  def rect
    [real, imag]
  end
  alias_method :rectangular, :rect

  #--
  # CONVERTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  #++

  #
  # The coerce method provides support for Ruby type coercion.
  # This coercion mechanism is used by Ruby to handle mixed-type
  # numeric operations: it is intended to find a compatible common
  # type between the two operands of the operator.
  # See also Numeric#coerce.
  #
  def coerce(other)
    case other
    when Numeric
      return Scalar.new(other), self
    else
      raise TypeError, "#{self.class} can't be coerced into #{other.class}"
    end
  end

  #
  # Returns an array of the row vectors of the matrix.  See Vector.
  #
  def row_vectors
    Array.new(row_count) {|i|
      row(i)
    }
  end

  #
  # Returns an array of the column vectors of the matrix.  See Vector.
  #
  def column_vectors
    Array.new(column_count) {|i|
      column(i)
    }
  end

  #
  # Explicit conversion to a Matrix. Returns self
  #
  def to_matrix
    self
  end

  #
  # Returns an array of arrays that describe the rows of the matrix.
  #
  def to_a
    @rows.collect(&:dup)
  end

  # Deprecated.
  #
  # Use <code>map(&:to_f)</code>
  def elements_to_f
    warn "Matrix#elements_to_f is deprecated, use map(&:to_f)", uplevel: 1
    map(&:to_f)
  end

  # Deprecated.
  #
  # Use <code>map(&:to_i)</code>
  def elements_to_i
    warn "Matrix#elements_to_i is deprecated, use map(&:to_i)", uplevel: 1
    map(&:to_i)
  end

  # Deprecated.
  #
  # Use <code>map(&:to_r)</code>
  def elements_to_r
    warn "Matrix#elements_to_r is deprecated, use map(&:to_r)", uplevel: 1
    map(&:to_r)
  end

  #--
  # PRINTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  #++

  #
  # Overrides Object#to_s
  #
  def to_s
    if empty?
      "#{self.class}.empty(#{row_count}, #{column_count})"
    else
      "#{self.class}[" + @rows.collect{|row|
        "[" + row.collect{|e| e.to_s}.join(", ") + "]"
      }.join(", ")+"]"
    end
  end

  #
  # Overrides Object#inspect
  #
  def inspect
    if empty?
      "#{self.class}.empty(#{row_count}, #{column_count})"
    else
      "#{self.class}#{@rows.inspect}"
    end
  end

  # Private helper modules

  module ConversionHelper # :nodoc:
    #
    # Converts the obj to an Array. If copy is set to true
    # a copy of obj will be made if necessary.
    #
    private def convert_to_array(obj, copy = false) # :nodoc:
      case obj
      when Array
        copy ? obj.dup : obj
      when Vector
        obj.to_a
      else
        begin
          converted = obj.to_ary
        rescue Exception => e
          raise TypeError, "can't convert #{obj.class} into an Array (#{e.message})"
        end
        raise TypeError, "#{obj.class}#to_ary should return an Array" unless converted.is_a? Array
        converted
      end
    end
  end

  extend ConversionHelper

  module CoercionHelper # :nodoc:
    #
    # Applies the operator +oper+ with argument +obj+
    # through coercion of +obj+
    #
    private def apply_through_coercion(obj, oper)
      coercion = obj.coerce(self)
      raise TypeError unless coercion.is_a?(Array) && coercion.length == 2
      coercion[0].public_send(oper, coercion[1])
    rescue
      raise TypeError, "#{obj.inspect} can't be coerced into #{self.class}"
    end

    #
    # Helper method to coerce a value into a specific class.
    # Raises a TypeError if the coercion fails or the returned value
    # is not of the right class.
    # (from Rubinius)
    #
    def self.coerce_to(obj, cls, meth) # :nodoc:
      return obj if obj.kind_of?(cls)
      raise TypeError, "Expected a #{cls} but got a #{obj.class}" unless obj.respond_to? meth
      begin
        ret = obj.__send__(meth)
      rescue Exception => e
        raise TypeError, "Coercion error: #{obj.inspect}.#{meth} => #{cls} failed:\n" \
                         "(#{e.message})"
      end
      raise TypeError, "Coercion error: obj.#{meth} did NOT return a #{cls} (was #{ret.class})" unless ret.kind_of? cls
      ret
    end

    def self.coerce_to_int(obj)
      coerce_to(obj, Integer, :to_int)
    end

    def self.coerce_to_matrix(obj)
      coerce_to(obj, Matrix, :to_matrix)
    end

    # Returns `nil` for non Ranges
    # Checks range validity, return canonical range with 0 <= begin <= end < count
    def self.check_range(val, count, kind)
      canonical = (val.begin + (val.begin < 0 ? count : 0))..
                  (val.end ? val.end + (val.end < 0 ? count : 0) - (val.exclude_end? ? 1 : 0)
                           : count - 1)
      unless 0 <= canonical.begin && canonical.begin <= canonical.end && canonical.end < count
        raise IndexError, "given range #{val} is outside of #{kind} dimensions: 0...#{count}"
      end
      canonical
    end

    def self.check_int(val, count, kind)
      val = CoercionHelper.coerce_to_int(val)
      if val >= count || val < -count
        raise IndexError, "given #{kind} #{val} is outside of #{-count}...#{count}"
      end
      val
    end
  end

  include CoercionHelper

  # Private CLASS

  class Scalar < Numeric # :nodoc:
    include ExceptionForMatrix
    include CoercionHelper

    def initialize(value)
      @value = value
    end

    # ARITHMETIC
    def +(other)
      case other
      when Numeric
        Scalar.new(@value + other)
      when Vector, Matrix
        raise ErrOperationNotDefined, ["+", @value.class, other.class]
      else
        apply_through_coercion(other, __method__)
      end
    end

    def -(other)
      case other
      when Numeric
        Scalar.new(@value - other)
      when Vector, Matrix
        raise ErrOperationNotDefined, ["-", @value.class, other.class]
      else
        apply_through_coercion(other, __method__)
      end
    end

    def *(other)
      case other
      when Numeric
        Scalar.new(@value * other)
      when Vector, Matrix
        other.collect{|e| @value * e}
      else
        apply_through_coercion(other, __method__)
      end
    end

    def /(other)
      case other
      when Numeric
        Scalar.new(@value / other)
      when Vector
        raise ErrOperationNotDefined, ["/", @value.class, other.class]
      when Matrix
        self * other.inverse
      else
        apply_through_coercion(other, __method__)
      end
    end

    def **(other)
      case other
      when Numeric
        Scalar.new(@value ** other)
      when Vector
        raise ErrOperationNotDefined, ["**", @value.class, other.class]
      when Matrix
        #other.powered_by(self)
        raise ErrOperationNotImplemented, ["**", @value.class, other.class]
      else
        apply_through_coercion(other, __method__)
      end
    end
  end

end


#
# The +Vector+ class represents a mathematical vector, which is useful in its own right, and
# also constitutes a row or column of a Matrix.
#
# == Method Catalogue
#
# To create a Vector:
# * Vector.[](*array)
# * Vector.elements(array, copy = true)
# * Vector.basis(size: n, index: k)
# * Vector.zero(n)
#
# To access elements:
# * #[](i)
#
# To set elements:
# * #[]=(i, v)
#
# To enumerate the elements:
# * #each2(v)
# * #collect2(v)
#
# Properties of vectors:
# * #angle_with(v)
# * Vector.independent?(*vs)
# * #independent?(*vs)
# * #zero?
#
# Vector arithmetic:
# * #*(x) "is matrix or number"
# * #+(v)
# * #-(v)
# * #/(v)
# * #+@
# * #-@
#
# Vector functions:
# * #inner_product(v), #dot(v)
# * #cross_product(v), #cross(v)
# * #collect
# * #collect!
# * #magnitude
# * #map
# * #map!
# * #map2(v)
# * #norm
# * #normalize
# * #r
# * #round
# * #size
#
# Conversion to other data types:
# * #covector
# * #to_a
# * #coerce(other)
#
# String representations:
# * #to_s
# * #inspect
#
class Vector
  include ExceptionForMatrix
  include Enumerable
  include Matrix::CoercionHelper
  extend Matrix::ConversionHelper
  #INSTANCE CREATION

  private_class_method :new
  attr_reader :elements
  protected :elements

  #
  # Creates a Vector from a list of elements.
  #   Vector[7, 4, ...]
  #
  def Vector.[](*array)
    new convert_to_array(array, false)
  end

  #
  # Creates a vector from an Array.  The optional second argument specifies
  # whether the array itself or a copy is used internally.
  #
  def Vector.elements(array, copy = true)
    new convert_to_array(array, copy)
  end

  #
  # Returns a standard basis +n+-vector, where k is the index.
  #
  #    Vector.basis(size:, index:) # => Vector[0, 1, 0]
  #
  def Vector.basis(size:, index:)
    raise ArgumentError, "invalid size (#{size} for 1..)" if size < 1
    raise ArgumentError, "invalid index (#{index} for 0...#{size})" unless 0 <= index && index < size
    array = Array.new(size, 0)
    array[index] = 1
    new convert_to_array(array, false)
  end

  #
  # Return a zero vector.
  #
  #    Vector.zero(3) # => Vector[0, 0, 0]
  #
  def Vector.zero(size)
    raise ArgumentError, "invalid size (#{size} for 0..)" if size < 0
    array = Array.new(size, 0)
    new convert_to_array(array, false)
  end

  #
  # Vector.new is private; use Vector[] or Vector.elements to create.
  #
  def initialize(array)
    # No checking is done at this point.
    @elements = array
  end

  # ACCESSING

  #
  # :call-seq:
  #   vector[range]
  #   vector[integer]
  #
  # Returns element or elements of the vector.
  #
  def [](i)
    @elements[i]
  end
  alias element []
  alias component []

  #
  # :call-seq:
  #   vector[range] = new_vector
  #   vector[range] = row_matrix
  #   vector[range] = new_element
  #   vector[integer] = new_element
  #
  # Set element or elements of vector.
  #
  def []=(i, v)
    raise FrozenError, "can't modify frozen Vector" if frozen?
    if i.is_a?(Range)
      range = Matrix::CoercionHelper.check_range(i, size, :vector)
      set_range(range, v)
    else
      index = Matrix::CoercionHelper.check_int(i, size, :index)
      set_value(index, v)
    end
  end
  alias set_element []=
  alias set_component []=
  private :set_element, :set_component

  private def set_value(index, value)
    @elements[index] = value
  end

  private def set_range(range, value)
    if value.is_a?(Vector)
      raise ArgumentError, "vector to be set has wrong size" unless range.size == value.size
      @elements[range] = value.elements
    elsif value.is_a?(Matrix)
      raise ErrDimensionMismatch unless value.row_count == 1
      @elements[range] = value.row(0).elements
    else
      @elements[range] = Array.new(range.size, value)
    end
  end

  # Returns a vector with entries rounded to the given precision
  # (see Float#round)
  #
  def round(ndigits=0)
    map{|e| e.round(ndigits)}
  end

  #
  # Returns the number of elements in the vector.
  #
  def size
    @elements.size
  end

  #--
  # ENUMERATIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  #++

  #
  # Iterate over the elements of this vector
  #
  def each(&block)
    return to_enum(:each) unless block_given?
    @elements.each(&block)
    self
  end

  #
  # Iterate over the elements of this vector and +v+ in conjunction.
  #
  def each2(v) # :yield: e1, e2
    raise TypeError, "Integer is not like Vector" if v.kind_of?(Integer)
    raise ErrDimensionMismatch if size != v.size
    return to_enum(:each2, v) unless block_given?
    size.times do |i|
      yield @elements[i], v[i]
    end
    self
  end

  #
  # Collects (as in Enumerable#collect) over the elements of this vector and +v+
  # in conjunction.
  #
  def collect2(v) # :yield: e1, e2
    raise TypeError, "Integer is not like Vector" if v.kind_of?(Integer)
    raise ErrDimensionMismatch if size != v.size
    return to_enum(:collect2, v) unless block_given?
    Array.new(size) do |i|
      yield @elements[i], v[i]
    end
  end

  #--
  # PROPERTIES -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  #++

  #
  # Returns +true+ iff all of vectors are linearly independent.
  #
  #   Vector.independent?(Vector[1,0], Vector[0,1])
  #   #  => true
  #
  #   Vector.independent?(Vector[1,2], Vector[2,4])
  #   #  => false
  #
  def Vector.independent?(*vs)
    vs.each do |v|
      raise TypeError, "expected Vector, got #{v.class}" unless v.is_a?(Vector)
      raise ErrDimensionMismatch unless v.size == vs.first.size
    end
    return false if vs.count > vs.first.size
    Matrix[*vs].rank.eql?(vs.count)
  end

  #
  # Returns +true+ iff all of vectors are linearly independent.
  #
  #   Vector[1,0].independent?(Vector[0,1])
  #   # => true
  #
  #   Vector[1,2].independent?(Vector[2,4])
  #   # => false
  #
  def independent?(*vs)
    self.class.independent?(self, *vs)
  end

  #
  # Returns +true+ iff all elements are zero.
  #
  def zero?
    all?(&:zero?)
  end

  #
  # Makes the matrix frozen and Ractor-shareable
  #
  def freeze
    @elements.freeze
    super
  end

  #
  # Called for dup & clone.
  #
  private def initialize_copy(v)
    super
    @elements = @elements.dup unless frozen?
  end


  #--
  # COMPARING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  #++

  #
  # Returns +true+ iff the two vectors have the same elements in the same order.
  #
  def ==(other)
    return false unless Vector === other
    @elements == other.elements
  end

  def eql?(other)
    return false unless Vector === other
    @elements.eql? other.elements
  end

  #
  # Returns a hash-code for the vector.
  #
  def hash
    @elements.hash
  end

  #--
  # ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  #++

  #
  # Multiplies the vector by +x+, where +x+ is a number or a matrix.
  #
  def *(x)
    case x
    when Numeric
      els = @elements.collect{|e| e * x}
      self.class.elements(els, false)
    when Matrix
      Matrix.column_vector(self) * x
    when Vector
      raise ErrOperationNotDefined, ["*", self.class, x.class]
    else
      apply_through_coercion(x, __method__)
    end
  end

  #
  # Vector addition.
  #
  def +(v)
    case v
    when Vector
      raise ErrDimensionMismatch if size != v.size
      els = collect2(v) {|v1, v2|
        v1 + v2
      }
      self.class.elements(els, false)
    when Matrix
      Matrix.column_vector(self) + v
    else
      apply_through_coercion(v, __method__)
    end
  end

  #
  # Vector subtraction.
  #
  def -(v)
    case v
    when Vector
      raise ErrDimensionMismatch if size != v.size
      els = collect2(v) {|v1, v2|
        v1 - v2
      }
      self.class.elements(els, false)
    when Matrix
      Matrix.column_vector(self) - v
    else
      apply_through_coercion(v, __method__)
    end
  end

  #
  # Vector division.
  #
  def /(x)
    case x
    when Numeric
      els = @elements.collect{|e| e / x}
      self.class.elements(els, false)
    when Matrix, Vector
      raise ErrOperationNotDefined, ["/", self.class, x.class]
    else
      apply_through_coercion(x, __method__)
    end
  end

  def +@
    self
  end

  def -@
    collect {|e| -e }
  end

  #--
  # VECTOR FUNCTIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  #++

  #
  # Returns the inner product of this vector with the other.
  #   Vector[4,7].inner_product Vector[10,1] # => 47
  #
  def inner_product(v)
    raise ErrDimensionMismatch if size != v.size

    p = 0
    each2(v) {|v1, v2|
      p += v1 * v2.conj
    }
    p
  end
  alias_method :dot, :inner_product

  #
  # Returns the cross product of this vector with the others.
  #   Vector[1, 0, 0].cross_product Vector[0, 1, 0]  # => Vector[0, 0, 1]
  #
  # It is generalized to other dimensions to return a vector perpendicular
  # to the arguments.
  #   Vector[1, 2].cross_product # => Vector[-2, 1]
  #   Vector[1, 0, 0, 0].cross_product(
  #      Vector[0, 1, 0, 0],
  #      Vector[0, 0, 1, 0]
  #   )  #=> Vector[0, 0, 0, 1]
  #
  def cross_product(*vs)
    raise ErrOperationNotDefined, "cross product is not defined on vectors of dimension #{size}" unless size >= 2
    raise ArgumentError, "wrong number of arguments (#{vs.size} for #{size - 2})" unless vs.size == size - 2
    vs.each do |v|
      raise TypeError, "expected Vector, got #{v.class}" unless v.is_a? Vector
      raise ErrDimensionMismatch unless v.size == size
    end
    case size
    when 2
      Vector[-@elements[1], @elements[0]]
    when 3
      v = vs[0]
      Vector[ v[2]*@elements[1] - v[1]*@elements[2],
        v[0]*@elements[2] - v[2]*@elements[0],
        v[1]*@elements[0] - v[0]*@elements[1] ]
    else
      rows = self, *vs, Array.new(size) {|i| Vector.basis(size: size, index: i) }
      Matrix.rows(rows).laplace_expansion(row: size - 1)
    end
  end
  alias_method :cross, :cross_product

  #
  # Like Array#collect.
  #
  def collect(&block) # :yield: e
    return to_enum(:collect) unless block_given?
    els = @elements.collect(&block)
    self.class.elements(els, false)
  end
  alias_method :map, :collect

  #
  # Like Array#collect!
  #
  def collect!(&block)
    return to_enum(:collect!) unless block_given?
    raise FrozenError, "can't modify frozen Vector" if frozen?
    @elements.collect!(&block)
    self
  end
  alias map! collect!

  #
  # Returns the modulus (Pythagorean distance) of the vector.
  #   Vector[5,8,2].r # => 9.643650761
  #
  def magnitude
    Math.sqrt(@elements.inject(0) {|v, e| v + e.abs2})
  end
  alias_method :r, :magnitude
  alias_method :norm, :magnitude

  #
  # Like Vector#collect2, but returns a Vector instead of an Array.
  #
  def map2(v, &block) # :yield: e1, e2
    return to_enum(:map2, v) unless block_given?
    els = collect2(v, &block)
    self.class.elements(els, false)
  end

  class ZeroVectorError < StandardError
  end
  #
  # Returns a new vector with the same direction but with norm 1.
  #   v = Vector[5,8,2].normalize
  #   # => Vector[0.5184758473652127, 0.8295613557843402, 0.20739033894608505]
  #   v.norm # => 1.0
  #
  def normalize
    n = magnitude
    raise ZeroVectorError, "Zero vectors can not be normalized" if n == 0
    self / n
  end

  #
  # Returns an angle with another vector. Result is within the [0..Math::PI].
  #   Vector[1,0].angle_with(Vector[0,1])
  #   # => Math::PI / 2
  #
  def angle_with(v)
    raise TypeError, "Expected a Vector, got a #{v.class}" unless v.is_a?(Vector)
    raise ErrDimensionMismatch if size != v.size
    prod = magnitude * v.magnitude
    raise ZeroVectorError, "Can't get angle of zero vector" if prod == 0
    dot = inner_product(v)
    if dot.abs >= prod
      dot.positive? ? 0 : Math::PI
    else
      Math.acos(dot / prod)
    end
  end

  #--
  # CONVERTING
  #++

  #
  # Creates a single-row matrix from this vector.
  #
  def covector
    Matrix.row_vector(self)
  end

  #
  # Returns the elements of the vector in an array.
  #
  def to_a
    @elements.dup
  end

  #
  # Return a single-column matrix from this vector
  #
  def to_matrix
    Matrix.column_vector(self)
  end

  def elements_to_f
    warn "Vector#elements_to_f is deprecated", uplevel: 1
    map(&:to_f)
  end

  def elements_to_i
    warn "Vector#elements_to_i is deprecated", uplevel: 1
    map(&:to_i)
  end

  def elements_to_r
    warn "Vector#elements_to_r is deprecated", uplevel: 1
    map(&:to_r)
  end

  #
  # The coerce method provides support for Ruby type coercion.
  # This coercion mechanism is used by Ruby to handle mixed-type
  # numeric operations: it is intended to find a compatible common
  # type between the two operands of the operator.
  # See also Numeric#coerce.
  #
  def coerce(other)
    case other
    when Numeric
      return Matrix::Scalar.new(other), self
    else
      raise TypeError, "#{self.class} can't be coerced into #{other.class}"
    end
  end

  #--
  # PRINTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  #++

  #
  # Overrides Object#to_s
  #
  def to_s
    "Vector[" + @elements.join(", ") + "]"
  end

  #
  # Overrides Object#inspect
  #
  def inspect
    "Vector" + @elements.inspect
  end
end
# coding: utf-8
# frozen_string_literal: false

# Copyright Ayumu Nojima (野島 歩) and Martin J. Dürst (duerst@it.aoyama.ac.jp)

# This file, the companion file tables.rb (autogenerated), and the module,
# constants, and method defined herein are part of the implementation of the
# built-in String class, not part of the standard library. They should
# therefore never be gemified. They implement the methods
# String#unicode_normalize, String#unicode_normalize!, and String#unicode_normalized?.
#
# They are placed here because they are written in Ruby. They are loaded on
# demand when any of the three methods mentioned above is executed for the
# first time. This reduces the memory footprint and startup time for scripts
# and applications that do not use those methods.
#
# The name and even the existence of the module UnicodeNormalize and all of its
# content are purely an implementation detail, and should not be exposed in
# any test or spec or otherwise.

require_relative 'tables'


module UnicodeNormalize  # :nodoc:
  ## Constant for max hash capacity to avoid DoS attack
  MAX_HASH_LENGTH = 18000 # enough for all test cases, otherwise tests get slow

  ## Regular Expressions and Hash Constants
  REGEXP_D = Regexp.compile(REGEXP_D_STRING, Regexp::EXTENDED)
  REGEXP_C = Regexp.compile(REGEXP_C_STRING, Regexp::EXTENDED)
  REGEXP_K = Regexp.compile(REGEXP_K_STRING, Regexp::EXTENDED)
  NF_HASH_D = Hash.new do |hash, key|
                         hash.shift if hash.length>MAX_HASH_LENGTH # prevent DoS attack
                         hash[key] = nfd_one(key)
                       end
  NF_HASH_C = Hash.new do |hash, key|
                         hash.shift if hash.length>MAX_HASH_LENGTH # prevent DoS attack
                         hash[key] = nfc_one(key)
                       end

  ## Constants For Hangul
  # for details such as the meaning of the identifiers below, please see
  # http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf, pp. 144/145
  SBASE = 0xAC00
  LBASE = 0x1100
  VBASE = 0x1161
  TBASE = 0x11A7
  LCOUNT = 19
  VCOUNT = 21
  TCOUNT = 28
  NCOUNT = VCOUNT * TCOUNT
  SCOUNT = LCOUNT * NCOUNT

  # Unicode-based encodings (except UTF-8)
  UNICODE_ENCODINGS = [Encoding::UTF_16BE, Encoding::UTF_16LE, Encoding::UTF_32BE, Encoding::UTF_32LE,
                       Encoding::GB18030, Encoding::UCS_2BE, Encoding::UCS_4BE]

  ## Hangul Algorithm
  def self.hangul_decomp_one(target)
    syllable_index = target.ord - SBASE
    return target if syllable_index < 0 || syllable_index >= SCOUNT
    l = LBASE + syllable_index / NCOUNT
    v = VBASE + (syllable_index % NCOUNT) / TCOUNT
    t = TBASE + syllable_index % TCOUNT
    (t==TBASE ? [l, v] : [l, v, t]).pack('U*') + target[1..-1]
  end

  def self.hangul_comp_one(string)
    length = string.length
    if length>1 and 0 <= (lead =string[0].ord-LBASE) and lead  < LCOUNT and
                    0 <= (vowel=string[1].ord-VBASE) and vowel < VCOUNT
      lead_vowel = SBASE + (lead * VCOUNT + vowel) * TCOUNT
      if length>2 and 0 < (trail=string[2].ord-TBASE) and trail < TCOUNT
        (lead_vowel + trail).chr(Encoding::UTF_8) + string[3..-1]
      else
        lead_vowel.chr(Encoding::UTF_8) + string[2..-1]
      end
    else
      string
    end
  end

  ## Canonical Ordering
  def self.canonical_ordering_one(string)
    sorting = string.each_char.collect { |c| [c, CLASS_TABLE[c]] }
    (sorting.length-2).downto(0) do |i| # almost, but not exactly bubble sort
      (0..i).each do |j|
        later_class = sorting[j+1].last
        if 0<later_class and later_class<sorting[j].last
          sorting[j], sorting[j+1] = sorting[j+1], sorting[j]
        end
      end
    end
    return sorting.collect(&:first).join('')
  end

  ## Normalization Forms for Patterns (not whole Strings)
  def self.nfd_one(string)
    string = string.chars.map! {|c| DECOMPOSITION_TABLE[c] || c}.join('')
    canonical_ordering_one(hangul_decomp_one(string))
  end

  def self.nfc_one(string)
    nfd_string = nfd_one string
    start = nfd_string[0]
    last_class = CLASS_TABLE[start]-1
    accents = ''
    nfd_string[1..-1].each_char do |accent|
      accent_class = CLASS_TABLE[accent]
      if last_class<accent_class and composite = COMPOSITION_TABLE[start+accent]
        start = composite
      else
        accents << accent
        last_class = accent_class
      end
    end
    hangul_comp_one(start+accents)
  end

  def self.normalize(string, form = :nfc)
    encoding = string.encoding
    case encoding
    when Encoding::UTF_8
      case form
      when :nfc then
        string.gsub REGEXP_C, NF_HASH_C
      when :nfd then
        string.gsub REGEXP_D, NF_HASH_D
      when :nfkc then
        string.gsub(REGEXP_K, KOMPATIBLE_TABLE).gsub(REGEXP_C, NF_HASH_C)
      when :nfkd then
        string.gsub(REGEXP_K, KOMPATIBLE_TABLE).gsub(REGEXP_D, NF_HASH_D)
      else
        raise ArgumentError, "Invalid normalization form #{form}."
      end
    when Encoding::US_ASCII
      string
    when *UNICODE_ENCODINGS
      normalize(string.encode(Encoding::UTF_8), form).encode(encoding)
    else
      raise Encoding::CompatibilityError, "Unicode Normalization not appropriate for #{encoding}"
    end
  end

  def self.normalized?(string, form = :nfc)
    encoding = string.encoding
    case encoding
    when Encoding::UTF_8
      case form
      when :nfc then
        string.scan REGEXP_C do |match|
          return false  if NF_HASH_C[match] != match
        end
        true
      when :nfd then
        string.scan REGEXP_D do |match|
          return false  if NF_HASH_D[match] != match
        end
        true
      when :nfkc then
        normalized?(string, :nfc) and string !~ REGEXP_K
      when :nfkd then
        normalized?(string, :nfd) and string !~ REGEXP_K
      else
        raise ArgumentError, "Invalid normalization form #{form}."
      end
    when Encoding::US_ASCII
      true
    when *UNICODE_ENCODINGS
      normalized? string.encode(Encoding::UTF_8), form
    else
      raise Encoding::CompatibilityError, "Unicode Normalization not appropriate for #{encoding}"
    end
  end
end # module
# coding: us-ascii
# frozen_string_literal: true

# automatically generated by template/unicode_norm_gen.tmpl

module UnicodeNormalize  # :nodoc:
  accents = "" \
    "[\u0300-\u034E" \
    "\u0350-\u036F" \
    "\u0483-\u0487" \
    "\u0591-\u05BD" \
    "\u05BF" \
    "\u05C1\u05C2" \
    "\u05C4\u05C5" \
    "\u05C7" \
    "\u0610-\u061A" \
    "\u064B-\u065F" \
    "\u0670" \
    "\u06D6-\u06DC" \
    "\u06DF-\u06E4" \
    "\u06E7\u06E8" \
    "\u06EA-\u06ED" \
    "\u0711" \
    "\u0730-\u074A" \
    "\u07EB-\u07F3" \
    "\u07FD" \
    "\u0816-\u0819" \
    "\u081B-\u0823" \
    "\u0825-\u0827" \
    "\u0829-\u082D" \
    "\u0859-\u085B" \
    "\u08D3-\u08E1" \
    "\u08E3-\u08FF" \
    "\u093C" \
    "\u094D" \
    "\u0951-\u0954" \
    "\u09BC" \
    "\u09BE" \
    "\u09CD" \
    "\u09D7" \
    "\u09FE" \
    "\u0A3C" \
    "\u0A4D" \
    "\u0ABC" \
    "\u0ACD" \
    "\u0B3C" \
    "\u0B3E" \
    "\u0B4D" \
    "\u0B56\u0B57" \
    "\u0BBE" \
    "\u0BCD" \
    "\u0BD7" \
    "\u0C4D" \
    "\u0C55\u0C56" \
    "\u0CBC" \
    "\u0CC2" \
    "\u0CCD" \
    "\u0CD5\u0CD6" \
    "\u0D3B\u0D3C" \
    "\u0D3E" \
    "\u0D4D" \
    "\u0D57" \
    "\u0DCA" \
    "\u0DCF" \
    "\u0DDF" \
    "\u0E38-\u0E3A" \
    "\u0E48-\u0E4B" \
    "\u0EB8-\u0EBA" \
    "\u0EC8-\u0ECB" \
    "\u0F18\u0F19" \
    "\u0F35" \
    "\u0F37" \
    "\u0F39" \
    "\u0F71\u0F72" \
    "\u0F74" \
    "\u0F7A-\u0F7D" \
    "\u0F80" \
    "\u0F82-\u0F84" \
    "\u0F86\u0F87" \
    "\u0FC6" \
    "\u102E" \
    "\u1037" \
    "\u1039\u103A" \
    "\u108D" \
    "\u135D-\u135F" \
    "\u1714" \
    "\u1734" \
    "\u17D2" \
    "\u17DD" \
    "\u18A9" \
    "\u1939-\u193B" \
    "\u1A17\u1A18" \
    "\u1A60" \
    "\u1A75-\u1A7C" \
    "\u1A7F" \
    "\u1AB0-\u1ABD" \
    "\u1B34\u1B35" \
    "\u1B44" \
    "\u1B6B-\u1B73" \
    "\u1BAA\u1BAB" \
    "\u1BE6" \
    "\u1BF2\u1BF3" \
    "\u1C37" \
    "\u1CD0-\u1CD2" \
    "\u1CD4-\u1CE0" \
    "\u1CE2-\u1CE8" \
    "\u1CED" \
    "\u1CF4" \
    "\u1CF8\u1CF9" \
    "\u1DC0-\u1DF9" \
    "\u1DFB-\u1DFF" \
    "\u20D0-\u20DC" \
    "\u20E1" \
    "\u20E5-\u20F0" \
    "\u2CEF-\u2CF1" \
    "\u2D7F" \
    "\u2DE0-\u2DFF" \
    "\u302A-\u302F" \
    "\u3099\u309A" \
    "\uA66F" \
    "\uA674-\uA67D" \
    "\uA69E\uA69F" \
    "\uA6F0\uA6F1" \
    "\uA806" \
    "\uA8C4" \
    "\uA8E0-\uA8F1" \
    "\uA92B-\uA92D" \
    "\uA953" \
    "\uA9B3" \
    "\uA9C0" \
    "\uAAB0" \
    "\uAAB2-\uAAB4" \
    "\uAAB7\uAAB8" \
    "\uAABE\uAABF" \
    "\uAAC1" \
    "\uAAF6" \
    "\uABED" \
    "\uFB1E" \
    "\uFE20-\uFE2F" \
    "\u{101FD}" \
    "\u{102E0}" \
    "\u{10376}-\u{1037A}" \
    "\u{10A0D}" \
    "\u{10A0F}" \
    "\u{10A38}-\u{10A3A}" \
    "\u{10A3F}" \
    "\u{10AE5}\u{10AE6}" \
    "\u{10D24}-\u{10D27}" \
    "\u{10F46}-\u{10F50}" \
    "\u{11046}" \
    "\u{1107F}" \
    "\u{110B9}\u{110BA}" \
    "\u{11100}-\u{11102}" \
    "\u{11127}" \
    "\u{11133}\u{11134}" \
    "\u{11173}" \
    "\u{111C0}" \
    "\u{111CA}" \
    "\u{11235}\u{11236}" \
    "\u{112E9}\u{112EA}" \
    "\u{1133B}\u{1133C}" \
    "\u{1133E}" \
    "\u{1134D}" \
    "\u{11357}" \
    "\u{11366}-\u{1136C}" \
    "\u{11370}-\u{11374}" \
    "\u{11442}" \
    "\u{11446}" \
    "\u{1145E}" \
    "\u{114B0}" \
    "\u{114BA}" \
    "\u{114BD}" \
    "\u{114C2}\u{114C3}" \
    "\u{115AF}" \
    "\u{115BF}\u{115C0}" \
    "\u{1163F}" \
    "\u{116B6}\u{116B7}" \
    "\u{1172B}" \
    "\u{11839}\u{1183A}" \
    "\u{119E0}" \
    "\u{11A34}" \
    "\u{11A47}" \
    "\u{11A99}" \
    "\u{11C3F}" \
    "\u{11D42}" \
    "\u{11D44}\u{11D45}" \
    "\u{11D97}" \
    "\u{16AF0}-\u{16AF4}" \
    "\u{16B30}-\u{16B36}" \
    "\u{1BC9E}" \
    "\u{1D165}-\u{1D169}" \
    "\u{1D16D}-\u{1D172}" \
    "\u{1D17B}-\u{1D182}" \
    "\u{1D185}-\u{1D18B}" \
    "\u{1D1AA}-\u{1D1AD}" \
    "\u{1D242}-\u{1D244}" \
    "\u{1E000}-\u{1E006}" \
    "\u{1E008}-\u{1E018}" \
    "\u{1E01B}-\u{1E021}" \
    "\u{1E023}\u{1E024}" \
    "\u{1E026}-\u{1E02A}" \
    "\u{1E130}-\u{1E136}" \
    "\u{1E2EC}-\u{1E2EF}" \
    "\u{1E8D0}-\u{1E8D6}" \
    "\u{1E944}-\u{1E94A}" \
    "]"
  ACCENTS = accents
  REGEXP_D_STRING = "#{''  # composition starters and composition exclusions
    }" \
    "[\u00C0-\u00C5" \
    "\u00C7-\u00CF" \
    "\u00D1-\u00D6" \
    "\u00D9-\u00DD" \
    "\u00E0-\u00E5" \
    "\u00E7-\u00EF" \
    "\u00F1-\u00F6" \
    "\u00F9-\u00FD" \
    "\u00FF-\u010F" \
    "\u0112-\u0125" \
    "\u0128-\u0130" \
    "\u0134-\u0137" \
    "\u0139-\u013E" \
    "\u0143-\u0148" \
    "\u014C-\u0151" \
    "\u0154-\u0165" \
    "\u0168-\u017E" \
    "\u01A0\u01A1" \
    "\u01AF\u01B0" \
    "\u01CD-\u01DC" \
    "\u01DE-\u01E3" \
    "\u01E6-\u01F0" \
    "\u01F4\u01F5" \
    "\u01F8-\u021B" \
    "\u021E\u021F" \
    "\u0226-\u0233" \
    "\u0340\u0341" \
    "\u0343\u0344" \
    "\u0374" \
    "\u037E" \
    "\u0385-\u038A" \
    "\u038C" \
    "\u038E-\u0390" \
    "\u03AA-\u03B0" \
    "\u03CA-\u03CE" \
    "\u03D3\u03D4" \
    "\u0400\u0401" \
    "\u0403" \
    "\u0407" \
    "\u040C-\u040E" \
    "\u0419" \
    "\u0439" \
    "\u0450\u0451" \
    "\u0453" \
    "\u0457" \
    "\u045C-\u045E" \
    "\u0476\u0477" \
    "\u04C1\u04C2" \
    "\u04D0-\u04D3" \
    "\u04D6\u04D7" \
    "\u04DA-\u04DF" \
    "\u04E2-\u04E7" \
    "\u04EA-\u04F5" \
    "\u04F8\u04F9" \
    "\u0622-\u0626" \
    "\u06C0" \
    "\u06C2" \
    "\u06D3" \
    "\u0929" \
    "\u0931" \
    "\u0934" \
    "\u0958-\u095F" \
    "\u09CB\u09CC" \
    "\u09DC\u09DD" \
    "\u09DF" \
    "\u0A33" \
    "\u0A36" \
    "\u0A59-\u0A5B" \
    "\u0A5E" \
    "\u0B48" \
    "\u0B4B\u0B4C" \
    "\u0B5C\u0B5D" \
    "\u0B94" \
    "\u0BCA-\u0BCC" \
    "\u0C48" \
    "\u0CC0" \
    "\u0CC7\u0CC8" \
    "\u0CCA\u0CCB" \
    "\u0D4A-\u0D4C" \
    "\u0DDA" \
    "\u0DDC-\u0DDE" \
    "\u0F43" \
    "\u0F4D" \
    "\u0F52" \
    "\u0F57" \
    "\u0F5C" \
    "\u0F69" \
    "\u0F73" \
    "\u0F75\u0F76" \
    "\u0F78" \
    "\u0F81" \
    "\u0F93" \
    "\u0F9D" \
    "\u0FA2" \
    "\u0FA7" \
    "\u0FAC" \
    "\u0FB9" \
    "\u1026" \
    "\u1B06" \
    "\u1B08" \
    "\u1B0A" \
    "\u1B0C" \
    "\u1B0E" \
    "\u1B12" \
    "\u1B3B" \
    "\u1B3D" \
    "\u1B40\u1B41" \
    "\u1B43" \
    "\u1E00-\u1E99" \
    "\u1E9B" \
    "\u1EA0-\u1EF9" \
    "\u1F00-\u1F15" \
    "\u1F18-\u1F1D" \
    "\u1F20-\u1F45" \
    "\u1F48-\u1F4D" \
    "\u1F50-\u1F57" \
    "\u1F59" \
    "\u1F5B" \
    "\u1F5D" \
    "\u1F5F-\u1F7D" \
    "\u1F80-\u1FB4" \
    "\u1FB6-\u1FBC" \
    "\u1FBE" \
    "\u1FC1-\u1FC4" \
    "\u1FC6-\u1FD3" \
    "\u1FD6-\u1FDB" \
    "\u1FDD-\u1FEF" \
    "\u1FF2-\u1FF4" \
    "\u1FF6-\u1FFD" \
    "\u2000\u2001" \
    "\u2126" \
    "\u212A\u212B" \
    "\u219A\u219B" \
    "\u21AE" \
    "\u21CD-\u21CF" \
    "\u2204" \
    "\u2209" \
    "\u220C" \
    "\u2224" \
    "\u2226" \
    "\u2241" \
    "\u2244" \
    "\u2247" \
    "\u2249" \
    "\u2260" \
    "\u2262" \
    "\u226D-\u2271" \
    "\u2274\u2275" \
    "\u2278\u2279" \
    "\u2280\u2281" \
    "\u2284\u2285" \
    "\u2288\u2289" \
    "\u22AC-\u22AF" \
    "\u22E0-\u22E3" \
    "\u22EA-\u22ED" \
    "\u2329\u232A" \
    "\u2ADC" \
    "\u304C" \
    "\u304E" \
    "\u3050" \
    "\u3052" \
    "\u3054" \
    "\u3056" \
    "\u3058" \
    "\u305A" \
    "\u305C" \
    "\u305E" \
    "\u3060" \
    "\u3062" \
    "\u3065" \
    "\u3067" \
    "\u3069" \
    "\u3070\u3071" \
    "\u3073\u3074" \
    "\u3076\u3077" \
    "\u3079\u307A" \
    "\u307C\u307D" \
    "\u3094" \
    "\u309E" \
    "\u30AC" \
    "\u30AE" \
    "\u30B0" \
    "\u30B2" \
    "\u30B4" \
    "\u30B6" \
    "\u30B8" \
    "\u30BA" \
    "\u30BC" \
    "\u30BE" \
    "\u30C0" \
    "\u30C2" \
    "\u30C5" \
    "\u30C7" \
    "\u30C9" \
    "\u30D0\u30D1" \
    "\u30D3\u30D4" \
    "\u30D6\u30D7" \
    "\u30D9\u30DA" \
    "\u30DC\u30DD" \
    "\u30F4" \
    "\u30F7-\u30FA" \
    "\u30FE" \
    "\uF900-\uFA0D" \
    "\uFA10" \
    "\uFA12" \
    "\uFA15-\uFA1E" \
    "\uFA20" \
    "\uFA22" \
    "\uFA25\uFA26" \
    "\uFA2A-\uFA6D" \
    "\uFA70-\uFAD9" \
    "\uFB1D" \
    "\uFB1F" \
    "\uFB2A-\uFB36" \
    "\uFB38-\uFB3C" \
    "\uFB3E" \
    "\uFB40\uFB41" \
    "\uFB43\uFB44" \
    "\uFB46-\uFB4E" \
    "\u{1109A}" \
    "\u{1109C}" \
    "\u{110AB}" \
    "\u{1112E}\u{1112F}" \
    "\u{1134B}\u{1134C}" \
    "\u{114BB}\u{114BC}" \
    "\u{114BE}" \
    "\u{115BA}\u{115BB}" \
    "\u{1D15E}-\u{1D164}" \
    "\u{1D1BB}-\u{1D1C0}" \
    "\u{2F800}-\u{2FA1D}" \
    "]#{accents}*" \
    "|#{''  # characters that can be the result of a composition, except composition starters
    }" \
    "[<->" \
    "A-P" \
    "R-Z" \
    "a-p" \
    "r-z" \
    "\u00A8" \
    "\u00C6" \
    "\u00D8" \
    "\u00E6" \
    "\u00F8" \
    "\u017F" \
    "\u01B7" \
    "\u0292" \
    "\u0391" \
    "\u0395" \
    "\u0397" \
    "\u0399" \
    "\u039F" \
    "\u03A1" \
    "\u03A5" \
    "\u03A9" \
    "\u03B1" \
    "\u03B5" \
    "\u03B7" \
    "\u03B9" \
    "\u03BF" \
    "\u03C1" \
    "\u03C5" \
    "\u03C9" \
    "\u03D2" \
    "\u0406" \
    "\u0410" \
    "\u0413" \
    "\u0415-\u0418" \
    "\u041A" \
    "\u041E" \
    "\u0423" \
    "\u0427" \
    "\u042B" \
    "\u042D" \
    "\u0430" \
    "\u0433" \
    "\u0435-\u0438" \
    "\u043A" \
    "\u043E" \
    "\u0443" \
    "\u0447" \
    "\u044B" \
    "\u044D" \
    "\u0456" \
    "\u0474\u0475" \
    "\u04D8\u04D9" \
    "\u04E8\u04E9" \
    "\u0627" \
    "\u0648" \
    "\u064A" \
    "\u06C1" \
    "\u06D2" \
    "\u06D5" \
    "\u0928" \
    "\u0930" \
    "\u0933" \
    "\u09C7" \
    "\u0B47" \
    "\u0B92" \
    "\u0BC6\u0BC7" \
    "\u0C46" \
    "\u0CBF" \
    "\u0CC6" \
    "\u0D46\u0D47" \
    "\u0DD9" \
    "\u1025" \
    "\u1B05" \
    "\u1B07" \
    "\u1B09" \
    "\u1B0B" \
    "\u1B0D" \
    "\u1B11" \
    "\u1B3A" \
    "\u1B3C" \
    "\u1B3E\u1B3F" \
    "\u1B42" \
    "\u1FBF" \
    "\u1FFE" \
    "\u2190" \
    "\u2192" \
    "\u2194" \
    "\u21D0" \
    "\u21D2" \
    "\u21D4" \
    "\u2203" \
    "\u2208" \
    "\u220B" \
    "\u2223" \
    "\u2225" \
    "\u223C" \
    "\u2243" \
    "\u2245" \
    "\u2248" \
    "\u224D" \
    "\u2261" \
    "\u2264\u2265" \
    "\u2272\u2273" \
    "\u2276\u2277" \
    "\u227A-\u227D" \
    "\u2282\u2283" \
    "\u2286\u2287" \
    "\u2291\u2292" \
    "\u22A2" \
    "\u22A8\u22A9" \
    "\u22AB" \
    "\u22B2-\u22B5" \
    "\u3046" \
    "\u304B" \
    "\u304D" \
    "\u304F" \
    "\u3051" \
    "\u3053" \
    "\u3055" \
    "\u3057" \
    "\u3059" \
    "\u305B" \
    "\u305D" \
    "\u305F" \
    "\u3061" \
    "\u3064" \
    "\u3066" \
    "\u3068" \
    "\u306F" \
    "\u3072" \
    "\u3075" \
    "\u3078" \
    "\u307B" \
    "\u309D" \
    "\u30A6" \
    "\u30AB" \
    "\u30AD" \
    "\u30AF" \
    "\u30B1" \
    "\u30B3" \
    "\u30B5" \
    "\u30B7" \
    "\u30B9" \
    "\u30BB" \
    "\u30BD" \
    "\u30BF" \
    "\u30C1" \
    "\u30C4" \
    "\u30C6" \
    "\u30C8" \
    "\u30CF" \
    "\u30D2" \
    "\u30D5" \
    "\u30D8" \
    "\u30DB" \
    "\u30EF-\u30F2" \
    "\u30FD" \
    "\u{11099}" \
    "\u{1109B}" \
    "\u{110A5}" \
    "\u{11131}\u{11132}" \
    "\u{11347}" \
    "\u{114B9}" \
    "\u{115B8}\u{115B9}" \
    "]?#{accents}+" \
    "|#{''  # precomposed Hangul syllables
    }" \
    "[\u{AC00}-\u{D7A4}]"
  REGEXP_C_STRING = "#{''  # composition exclusions
    }" \
    "[\u0340\u0341" \
    "\u0343\u0344" \
    "\u0374" \
    "\u037E" \
    "\u0387" \
    "\u0958-\u095F" \
    "\u09DC\u09DD" \
    "\u09DF" \
    "\u0A33" \
    "\u0A36" \
    "\u0A59-\u0A5B" \
    "\u0A5E" \
    "\u0B5C\u0B5D" \
    "\u0F43" \
    "\u0F4D" \
    "\u0F52" \
    "\u0F57" \
    "\u0F5C" \
    "\u0F69" \
    "\u0F73" \
    "\u0F75\u0F76" \
    "\u0F78" \
    "\u0F81" \
    "\u0F93" \
    "\u0F9D" \
    "\u0FA2" \
    "\u0FA7" \
    "\u0FAC" \
    "\u0FB9" \
    "\u1F71" \
    "\u1F73" \
    "\u1F75" \
    "\u1F77" \
    "\u1F79" \
    "\u1F7B" \
    "\u1F7D" \
    "\u1FBB" \
    "\u1FBE" \
    "\u1FC9" \
    "\u1FCB" \
    "\u1FD3" \
    "\u1FDB" \
    "\u1FE3" \
    "\u1FEB" \
    "\u1FEE\u1FEF" \
    "\u1FF9" \
    "\u1FFB" \
    "\u1FFD" \
    "\u2000\u2001" \
    "\u2126" \
    "\u212A\u212B" \
    "\u2329\u232A" \
    "\u2ADC" \
    "\uF900-\uFA0D" \
    "\uFA10" \
    "\uFA12" \
    "\uFA15-\uFA1E" \
    "\uFA20" \
    "\uFA22" \
    "\uFA25\uFA26" \
    "\uFA2A-\uFA6D" \
    "\uFA70-\uFAD9" \
    "\uFB1D" \
    "\uFB1F" \
    "\uFB2A-\uFB36" \
    "\uFB38-\uFB3C" \
    "\uFB3E" \
    "\uFB40\uFB41" \
    "\uFB43\uFB44" \
    "\uFB46-\uFB4E" \
    "\u{1D15E}-\u{1D164}" \
    "\u{1D1BB}-\u{1D1C0}" \
    "\u{2F800}-\u{2FA1D}" \
    "]#{accents}*" \
    "|#{''  # composition starters and characters that can be the result of a composition
    }" \
    "[<->" \
    "A-P" \
    "R-Z" \
    "a-p" \
    "r-z" \
    "\u00A8" \
    "\u00C0-\u00CF" \
    "\u00D1-\u00D6" \
    "\u00D8-\u00DD" \
    "\u00E0-\u00EF" \
    "\u00F1-\u00F6" \
    "\u00F8-\u00FD" \
    "\u00FF-\u010F" \
    "\u0112-\u0125" \
    "\u0128-\u0130" \
    "\u0134-\u0137" \
    "\u0139-\u013E" \
    "\u0143-\u0148" \
    "\u014C-\u0151" \
    "\u0154-\u0165" \
    "\u0168-\u017F" \
    "\u01A0\u01A1" \
    "\u01AF\u01B0" \
    "\u01B7" \
    "\u01CD-\u01DC" \
    "\u01DE-\u01E3" \
    "\u01E6-\u01F0" \
    "\u01F4\u01F5" \
    "\u01F8-\u021B" \
    "\u021E\u021F" \
    "\u0226-\u0233" \
    "\u0292" \
    "\u0385\u0386" \
    "\u0388-\u038A" \
    "\u038C" \
    "\u038E-\u0391" \
    "\u0395" \
    "\u0397" \
    "\u0399" \
    "\u039F" \
    "\u03A1" \
    "\u03A5" \
    "\u03A9-\u03B1" \
    "\u03B5" \
    "\u03B7" \
    "\u03B9" \
    "\u03BF" \
    "\u03C1" \
    "\u03C5" \
    "\u03C9-\u03CE" \
    "\u03D2-\u03D4" \
    "\u0400\u0401" \
    "\u0403" \
    "\u0406\u0407" \
    "\u040C-\u040E" \
    "\u0410" \
    "\u0413" \
    "\u0415-\u041A" \
    "\u041E" \
    "\u0423" \
    "\u0427" \
    "\u042B" \
    "\u042D" \
    "\u0430" \
    "\u0433" \
    "\u0435-\u043A" \
    "\u043E" \
    "\u0443" \
    "\u0447" \
    "\u044B" \
    "\u044D" \
    "\u0450\u0451" \
    "\u0453" \
    "\u0456\u0457" \
    "\u045C-\u045E" \
    "\u0474-\u0477" \
    "\u04C1\u04C2" \
    "\u04D0-\u04D3" \
    "\u04D6-\u04DF" \
    "\u04E2-\u04F5" \
    "\u04F8\u04F9" \
    "\u0622-\u0627" \
    "\u0648" \
    "\u064A" \
    "\u06C0-\u06C2" \
    "\u06D2\u06D3" \
    "\u06D5" \
    "\u0928\u0929" \
    "\u0930\u0931" \
    "\u0933\u0934" \
    "\u09C7" \
    "\u09CB\u09CC" \
    "\u0B47\u0B48" \
    "\u0B4B\u0B4C" \
    "\u0B92" \
    "\u0B94" \
    "\u0BC6\u0BC7" \
    "\u0BCA-\u0BCC" \
    "\u0C46" \
    "\u0C48" \
    "\u0CBF\u0CC0" \
    "\u0CC6-\u0CC8" \
    "\u0CCA\u0CCB" \
    "\u0D46\u0D47" \
    "\u0D4A-\u0D4C" \
    "\u0DD9\u0DDA" \
    "\u0DDC-\u0DDE" \
    "\u1025\u1026" \
    "\u1B05-\u1B0E" \
    "\u1B11\u1B12" \
    "\u1B3A-\u1B43" \
    "\u1E00-\u1E99" \
    "\u1E9B" \
    "\u1EA0-\u1EF9" \
    "\u1F00-\u1F15" \
    "\u1F18-\u1F1D" \
    "\u1F20-\u1F45" \
    "\u1F48-\u1F4D" \
    "\u1F50-\u1F57" \
    "\u1F59" \
    "\u1F5B" \
    "\u1F5D" \
    "\u1F5F-\u1F70" \
    "\u1F72" \
    "\u1F74" \
    "\u1F76" \
    "\u1F78" \
    "\u1F7A" \
    "\u1F7C" \
    "\u1F80-\u1FB4" \
    "\u1FB6-\u1FBA" \
    "\u1FBC" \
    "\u1FBF" \
    "\u1FC1-\u1FC4" \
    "\u1FC6-\u1FC8" \
    "\u1FCA" \
    "\u1FCC-\u1FD2" \
    "\u1FD6-\u1FDA" \
    "\u1FDD-\u1FE2" \
    "\u1FE4-\u1FEA" \
    "\u1FEC\u1FED" \
    "\u1FF2-\u1FF4" \
    "\u1FF6-\u1FF8" \
    "\u1FFA" \
    "\u1FFC" \
    "\u1FFE" \
    "\u2190" \
    "\u2192" \
    "\u2194" \
    "\u219A\u219B" \
    "\u21AE" \
    "\u21CD-\u21D0" \
    "\u21D2" \
    "\u21D4" \
    "\u2203\u2204" \
    "\u2208\u2209" \
    "\u220B\u220C" \
    "\u2223-\u2226" \
    "\u223C" \
    "\u2241" \
    "\u2243-\u2245" \
    "\u2247-\u2249" \
    "\u224D" \
    "\u2260-\u2262" \
    "\u2264\u2265" \
    "\u226D-\u227D" \
    "\u2280-\u2289" \
    "\u2291\u2292" \
    "\u22A2" \
    "\u22A8\u22A9" \
    "\u22AB-\u22AF" \
    "\u22B2-\u22B5" \
    "\u22E0-\u22E3" \
    "\u22EA-\u22ED" \
    "\u3046" \
    "\u304B-\u3062" \
    "\u3064-\u3069" \
    "\u306F-\u307D" \
    "\u3094" \
    "\u309D\u309E" \
    "\u30A6" \
    "\u30AB-\u30C2" \
    "\u30C4-\u30C9" \
    "\u30CF-\u30DD" \
    "\u30EF-\u30F2" \
    "\u30F4" \
    "\u30F7-\u30FA" \
    "\u30FD\u30FE" \
    "\u{11099}-\u{1109C}" \
    "\u{110A5}" \
    "\u{110AB}" \
    "\u{1112E}\u{1112F}" \
    "\u{11131}\u{11132}" \
    "\u{11347}" \
    "\u{1134B}\u{1134C}" \
    "\u{114B9}" \
    "\u{114BB}\u{114BC}" \
    "\u{114BE}" \
    "\u{115B8}-\u{115BB}" \
    "]?#{accents}+" \
    "|#{''  # Hangul syllables with separate trailer
    }" \
    "[\uAC00" \
    "\uAC1C" \
    "\uAC38" \
    "\uAC54" \
    "\uAC70" \
    "\uAC8C" \
    "\uACA8" \
    "\uACC4" \
    "\uACE0" \
    "\uACFC" \
    "\uAD18" \
    "\uAD34" \
    "\uAD50" \
    "\uAD6C" \
    "\uAD88" \
    "\uADA4" \
    "\uADC0" \
    "\uADDC" \
    "\uADF8" \
    "\uAE14" \
    "\uAE30" \
    "\uAE4C" \
    "\uAE68" \
    "\uAE84" \
    "\uAEA0" \
    "\uAEBC" \
    "\uAED8" \
    "\uAEF4" \
    "\uAF10" \
    "\uAF2C" \
    "\uAF48" \
    "\uAF64" \
    "\uAF80" \
    "\uAF9C" \
    "\uAFB8" \
    "\uAFD4" \
    "\uAFF0" \
    "\uB00C" \
    "\uB028" \
    "\uB044" \
    "\uB060" \
    "\uB07C" \
    "\uB098" \
    "\uB0B4" \
    "\uB0D0" \
    "\uB0EC" \
    "\uB108" \
    "\uB124" \
    "\uB140" \
    "\uB15C" \
    "\uB178" \
    "\uB194" \
    "\uB1B0" \
    "\uB1CC" \
    "\uB1E8" \
    "\uB204" \
    "\uB220" \
    "\uB23C" \
    "\uB258" \
    "\uB274" \
    "\uB290" \
    "\uB2AC" \
    "\uB2C8" \
    "\uB2E4" \
    "\uB300" \
    "\uB31C" \
    "\uB338" \
    "\uB354" \
    "\uB370" \
    "\uB38C" \
    "\uB3A8" \
    "\uB3C4" \
    "\uB3E0" \
    "\uB3FC" \
    "\uB418" \
    "\uB434" \
    "\uB450" \
    "\uB46C" \
    "\uB488" \
    "\uB4A4" \
    "\uB4C0" \
    "\uB4DC" \
    "\uB4F8" \
    "\uB514" \
    "\uB530" \
    "\uB54C" \
    "\uB568" \
    "\uB584" \
    "\uB5A0" \
    "\uB5BC" \
    "\uB5D8" \
    "\uB5F4" \
    "\uB610" \
    "\uB62C" \
    "\uB648" \
    "\uB664" \
    "\uB680" \
    "\uB69C" \
    "\uB6B8" \
    "\uB6D4" \
    "\uB6F0" \
    "\uB70C" \
    "\uB728" \
    "\uB744" \
    "\uB760" \
    "\uB77C" \
    "\uB798" \
    "\uB7B4" \
    "\uB7D0" \
    "\uB7EC" \
    "\uB808" \
    "\uB824" \
    "\uB840" \
    "\uB85C" \
    "\uB878" \
    "\uB894" \
    "\uB8B0" \
    "\uB8CC" \
    "\uB8E8" \
    "\uB904" \
    "\uB920" \
    "\uB93C" \
    "\uB958" \
    "\uB974" \
    "\uB990" \
    "\uB9AC" \
    "\uB9C8" \
    "\uB9E4" \
    "\uBA00" \
    "\uBA1C" \
    "\uBA38" \
    "\uBA54" \
    "\uBA70" \
    "\uBA8C" \
    "\uBAA8" \
    "\uBAC4" \
    "\uBAE0" \
    "\uBAFC" \
    "\uBB18" \
    "\uBB34" \
    "\uBB50" \
    "\uBB6C" \
    "\uBB88" \
    "\uBBA4" \
    "\uBBC0" \
    "\uBBDC" \
    "\uBBF8" \
    "\uBC14" \
    "\uBC30" \
    "\uBC4C" \
    "\uBC68" \
    "\uBC84" \
    "\uBCA0" \
    "\uBCBC" \
    "\uBCD8" \
    "\uBCF4" \
    "\uBD10" \
    "\uBD2C" \
    "\uBD48" \
    "\uBD64" \
    "\uBD80" \
    "\uBD9C" \
    "\uBDB8" \
    "\uBDD4" \
    "\uBDF0" \
    "\uBE0C" \
    "\uBE28" \
    "\uBE44" \
    "\uBE60" \
    "\uBE7C" \
    "\uBE98" \
    "\uBEB4" \
    "\uBED0" \
    "\uBEEC" \
    "\uBF08" \
    "\uBF24" \
    "\uBF40" \
    "\uBF5C" \
    "\uBF78" \
    "\uBF94" \
    "\uBFB0" \
    "\uBFCC" \
    "\uBFE8" \
    "\uC004" \
    "\uC020" \
    "\uC03C" \
    "\uC058" \
    "\uC074" \
    "\uC090" \
    "\uC0AC" \
    "\uC0C8" \
    "\uC0E4" \
    "\uC100" \
    "\uC11C" \
    "\uC138" \
    "\uC154" \
    "\uC170" \
    "\uC18C" \
    "\uC1A8" \
    "\uC1C4" \
    "\uC1E0" \
    "\uC1FC" \
    "\uC218" \
    "\uC234" \
    "\uC250" \
    "\uC26C" \
    "\uC288" \
    "\uC2A4" \
    "\uC2C0" \
    "\uC2DC" \
    "\uC2F8" \
    "\uC314" \
    "\uC330" \
    "\uC34C" \
    "\uC368" \
    "\uC384" \
    "\uC3A0" \
    "\uC3BC" \
    "\uC3D8" \
    "\uC3F4" \
    "\uC410" \
    "\uC42C" \
    "\uC448" \
    "\uC464" \
    "\uC480" \
    "\uC49C" \
    "\uC4B8" \
    "\uC4D4" \
    "\uC4F0" \
    "\uC50C" \
    "\uC528" \
    "\uC544" \
    "\uC560" \
    "\uC57C" \
    "\uC598" \
    "\uC5B4" \
    "\uC5D0" \
    "\uC5EC" \
    "\uC608" \
    "\uC624" \
    "\uC640" \
    "\uC65C" \
    "\uC678" \
    "\uC694" \
    "\uC6B0" \
    "\uC6CC" \
    "\uC6E8" \
    "\uC704" \
    "\uC720" \
    "\uC73C" \
    "\uC758" \
    "\uC774" \
    "\uC790" \
    "\uC7AC" \
    "\uC7C8" \
    "\uC7E4" \
    "\uC800" \
    "\uC81C" \
    "\uC838" \
    "\uC854" \
    "\uC870" \
    "\uC88C" \
    "\uC8A8" \
    "\uC8C4" \
    "\uC8E0" \
    "\uC8FC" \
    "\uC918" \
    "\uC934" \
    "\uC950" \
    "\uC96C" \
    "\uC988" \
    "\uC9A4" \
    "\uC9C0" \
    "\uC9DC" \
    "\uC9F8" \
    "\uCA14" \
    "\uCA30" \
    "\uCA4C" \
    "\uCA68" \
    "\uCA84" \
    "\uCAA0" \
    "\uCABC" \
    "\uCAD8" \
    "\uCAF4" \
    "\uCB10" \
    "\uCB2C" \
    "\uCB48" \
    "\uCB64" \
    "\uCB80" \
    "\uCB9C" \
    "\uCBB8" \
    "\uCBD4" \
    "\uCBF0" \
    "\uCC0C" \
    "\uCC28" \
    "\uCC44" \
    "\uCC60" \
    "\uCC7C" \
    "\uCC98" \
    "\uCCB4" \
    "\uCCD0" \
    "\uCCEC" \
    "\uCD08" \
    "\uCD24" \
    "\uCD40" \
    "\uCD5C" \
    "\uCD78" \
    "\uCD94" \
    "\uCDB0" \
    "\uCDCC" \
    "\uCDE8" \
    "\uCE04" \
    "\uCE20" \
    "\uCE3C" \
    "\uCE58" \
    "\uCE74" \
    "\uCE90" \
    "\uCEAC" \
    "\uCEC8" \
    "\uCEE4" \
    "\uCF00" \
    "\uCF1C" \
    "\uCF38" \
    "\uCF54" \
    "\uCF70" \
    "\uCF8C" \
    "\uCFA8" \
    "\uCFC4" \
    "\uCFE0" \
    "\uCFFC" \
    "\uD018" \
    "\uD034" \
    "\uD050" \
    "\uD06C" \
    "\uD088" \
    "\uD0A4" \
    "\uD0C0" \
    "\uD0DC" \
    "\uD0F8" \
    "\uD114" \
    "\uD130" \
    "\uD14C" \
    "\uD168" \
    "\uD184" \
    "\uD1A0" \
    "\uD1BC" \
    "\uD1D8" \
    "\uD1F4" \
    "\uD210" \
    "\uD22C" \
    "\uD248" \
    "\uD264" \
    "\uD280" \
    "\uD29C" \
    "\uD2B8" \
    "\uD2D4" \
    "\uD2F0" \
    "\uD30C" \
    "\uD328" \
    "\uD344" \
    "\uD360" \
    "\uD37C" \
    "\uD398" \
    "\uD3B4" \
    "\uD3D0" \
    "\uD3EC" \
    "\uD408" \
    "\uD424" \
    "\uD440" \
    "\uD45C" \
    "\uD478" \
    "\uD494" \
    "\uD4B0" \
    "\uD4CC" \
    "\uD4E8" \
    "\uD504" \
    "\uD520" \
    "\uD53C" \
    "\uD558" \
    "\uD574" \
    "\uD590" \
    "\uD5AC" \
    "\uD5C8" \
    "\uD5E4" \
    "\uD600" \
    "\uD61C" \
    "\uD638" \
    "\uD654" \
    "\uD670" \
    "\uD68C" \
    "\uD6A8" \
    "\uD6C4" \
    "\uD6E0" \
    "\uD6FC" \
    "\uD718" \
    "\uD734" \
    "\uD750" \
    "\uD76C" \
    "\uD788" \
    "][\u11A8-\u11C2]" \
    "|#{''  # decomposed Hangul syllables
    }" \
    "[\u1100-\u1112][\u1161-\u1175][\u11A8-\u11C2]?"
  REGEXP_K_STRING = "" \
    "[\u00A0" \
    "\u00A8" \
    "\u00AA" \
    "\u00AF" \
    "\u00B2-\u00B5" \
    "\u00B8-\u00BA" \
    "\u00BC-\u00BE" \
    "\u0132\u0133" \
    "\u013F\u0140" \
    "\u0149" \
    "\u017F" \
    "\u01C4-\u01CC" \
    "\u01F1-\u01F3" \
    "\u02B0-\u02B8" \
    "\u02D8-\u02DD" \
    "\u02E0-\u02E4" \
    "\u037A" \
    "\u0384\u0385" \
    "\u03D0-\u03D6" \
    "\u03F0-\u03F2" \
    "\u03F4\u03F5" \
    "\u03F9" \
    "\u0587" \
    "\u0675-\u0678" \
    "\u0E33" \
    "\u0EB3" \
    "\u0EDC\u0EDD" \
    "\u0F0C" \
    "\u0F77" \
    "\u0F79" \
    "\u10FC" \
    "\u1D2C-\u1D2E" \
    "\u1D30-\u1D3A" \
    "\u1D3C-\u1D4D" \
    "\u1D4F-\u1D6A" \
    "\u1D78" \
    "\u1D9B-\u1DBF" \
    "\u1E9A\u1E9B" \
    "\u1FBD" \
    "\u1FBF-\u1FC1" \
    "\u1FCD-\u1FCF" \
    "\u1FDD-\u1FDF" \
    "\u1FED\u1FEE" \
    "\u1FFD\u1FFE" \
    "\u2000-\u200A" \
    "\u2011" \
    "\u2017" \
    "\u2024-\u2026" \
    "\u202F" \
    "\u2033\u2034" \
    "\u2036\u2037" \
    "\u203C" \
    "\u203E" \
    "\u2047-\u2049" \
    "\u2057" \
    "\u205F" \
    "\u2070\u2071" \
    "\u2074-\u208E" \
    "\u2090-\u209C" \
    "\u20A8" \
    "\u2100-\u2103" \
    "\u2105-\u2107" \
    "\u2109-\u2113" \
    "\u2115\u2116" \
    "\u2119-\u211D" \
    "\u2120-\u2122" \
    "\u2124" \
    "\u2128" \
    "\u212C\u212D" \
    "\u212F-\u2131" \
    "\u2133-\u2139" \
    "\u213B-\u2140" \
    "\u2145-\u2149" \
    "\u2150-\u217F" \
    "\u2189" \
    "\u222C\u222D" \
    "\u222F\u2230" \
    "\u2460-\u24EA" \
    "\u2A0C" \
    "\u2A74-\u2A76" \
    "\u2C7C\u2C7D" \
    "\u2D6F" \
    "\u2E9F" \
    "\u2EF3" \
    "\u2F00-\u2FD5" \
    "\u3000" \
    "\u3036" \
    "\u3038-\u303A" \
    "\u309B\u309C" \
    "\u309F" \
    "\u30FF" \
    "\u3131-\u318E" \
    "\u3192-\u319F" \
    "\u3200-\u321E" \
    "\u3220-\u3247" \
    "\u3250-\u327E" \
    "\u3280-\u33FF" \
    "\uA69C\uA69D" \
    "\uA770" \
    "\uA7F8\uA7F9" \
    "\uAB5C-\uAB5F" \
    "\uFB00-\uFB06" \
    "\uFB13-\uFB17" \
    "\uFB20-\uFB29" \
    "\uFB4F-\uFBB1" \
    "\uFBD3-\uFD3D" \
    "\uFD50-\uFD8F" \
    "\uFD92-\uFDC7" \
    "\uFDF0-\uFDFC" \
    "\uFE10-\uFE19" \
    "\uFE30-\uFE44" \
    "\uFE47-\uFE52" \
    "\uFE54-\uFE66" \
    "\uFE68-\uFE6B" \
    "\uFE70-\uFE72" \
    "\uFE74" \
    "\uFE76-\uFEFC" \
    "\uFF01-\uFFBE" \
    "\uFFC2-\uFFC7" \
    "\uFFCA-\uFFCF" \
    "\uFFD2-\uFFD7" \
    "\uFFDA-\uFFDC" \
    "\uFFE0-\uFFE6" \
    "\uFFE8-\uFFEE" \
    "\u{1D400}-\u{1D454}" \
    "\u{1D456}-\u{1D49C}" \
    "\u{1D49E}\u{1D49F}" \
    "\u{1D4A2}" \
    "\u{1D4A5}\u{1D4A6}" \
    "\u{1D4A9}-\u{1D4AC}" \
    "\u{1D4AE}-\u{1D4B9}" \
    "\u{1D4BB}" \
    "\u{1D4BD}-\u{1D4C3}" \
    "\u{1D4C5}-\u{1D505}" \
    "\u{1D507}-\u{1D50A}" \
    "\u{1D50D}-\u{1D514}" \
    "\u{1D516}-\u{1D51C}" \
    "\u{1D51E}-\u{1D539}" \
    "\u{1D53B}-\u{1D53E}" \
    "\u{1D540}-\u{1D544}" \
    "\u{1D546}" \
    "\u{1D54A}-\u{1D550}" \
    "\u{1D552}-\u{1D6A5}" \
    "\u{1D6A8}-\u{1D7CB}" \
    "\u{1D7CE}-\u{1D7FF}" \
    "\u{1EE00}-\u{1EE03}" \
    "\u{1EE05}-\u{1EE1F}" \
    "\u{1EE21}\u{1EE22}" \
    "\u{1EE24}" \
    "\u{1EE27}" \
    "\u{1EE29}-\u{1EE32}" \
    "\u{1EE34}-\u{1EE37}" \
    "\u{1EE39}" \
    "\u{1EE3B}" \
    "\u{1EE42}" \
    "\u{1EE47}" \
    "\u{1EE49}" \
    "\u{1EE4B}" \
    "\u{1EE4D}-\u{1EE4F}" \
    "\u{1EE51}\u{1EE52}" \
    "\u{1EE54}" \
    "\u{1EE57}" \
    "\u{1EE59}" \
    "\u{1EE5B}" \
    "\u{1EE5D}" \
    "\u{1EE5F}" \
    "\u{1EE61}\u{1EE62}" \
    "\u{1EE64}" \
    "\u{1EE67}-\u{1EE6A}" \
    "\u{1EE6C}-\u{1EE72}" \
    "\u{1EE74}-\u{1EE77}" \
    "\u{1EE79}-\u{1EE7C}" \
    "\u{1EE7E}" \
    "\u{1EE80}-\u{1EE89}" \
    "\u{1EE8B}-\u{1EE9B}" \
    "\u{1EEA1}-\u{1EEA3}" \
    "\u{1EEA5}-\u{1EEA9}" \
    "\u{1EEAB}-\u{1EEBB}" \
    "\u{1F100}-\u{1F10A}" \
    "\u{1F110}-\u{1F12E}" \
    "\u{1F130}-\u{1F14F}" \
    "\u{1F16A}-\u{1F16C}" \
    "\u{1F190}" \
    "\u{1F200}-\u{1F202}" \
    "\u{1F210}-\u{1F23B}" \
    "\u{1F240}-\u{1F248}" \
    "\u{1F250}\u{1F251}" \
    "]"

  class_table = {
    "\u0300"=>230,
    "\u0301"=>230,
    "\u0302"=>230,
    "\u0303"=>230,
    "\u0304"=>230,
    "\u0305"=>230,
    "\u0306"=>230,
    "\u0307"=>230,
    "\u0308"=>230,
    "\u0309"=>230,
    "\u030A"=>230,
    "\u030B"=>230,
    "\u030C"=>230,
    "\u030D"=>230,
    "\u030E"=>230,
    "\u030F"=>230,
    "\u0310"=>230,
    "\u0311"=>230,
    "\u0312"=>230,
    "\u0313"=>230,
    "\u0314"=>230,
    "\u0315"=>232,
    "\u0316"=>220,
    "\u0317"=>220,
    "\u0318"=>220,
    "\u0319"=>220,
    "\u031A"=>232,
    "\u031B"=>216,
    "\u031C"=>220,
    "\u031D"=>220,
    "\u031E"=>220,
    "\u031F"=>220,
    "\u0320"=>220,
    "\u0321"=>202,
    "\u0322"=>202,
    "\u0323"=>220,
    "\u0324"=>220,
    "\u0325"=>220,
    "\u0326"=>220,
    "\u0327"=>202,
    "\u0328"=>202,
    "\u0329"=>220,
    "\u032A"=>220,
    "\u032B"=>220,
    "\u032C"=>220,
    "\u032D"=>220,
    "\u032E"=>220,
    "\u032F"=>220,
    "\u0330"=>220,
    "\u0331"=>220,
    "\u0332"=>220,
    "\u0333"=>220,
    "\u0334"=>1,
    "\u0335"=>1,
    "\u0336"=>1,
    "\u0337"=>1,
    "\u0338"=>1,
    "\u0339"=>220,
    "\u033A"=>220,
    "\u033B"=>220,
    "\u033C"=>220,
    "\u033D"=>230,
    "\u033E"=>230,
    "\u033F"=>230,
    "\u0340"=>230,
    "\u0341"=>230,
    "\u0342"=>230,
    "\u0343"=>230,
    "\u0344"=>230,
    "\u0345"=>240,
    "\u0346"=>230,
    "\u0347"=>220,
    "\u0348"=>220,
    "\u0349"=>220,
    "\u034A"=>230,
    "\u034B"=>230,
    "\u034C"=>230,
    "\u034D"=>220,
    "\u034E"=>220,
    "\u0350"=>230,
    "\u0351"=>230,
    "\u0352"=>230,
    "\u0353"=>220,
    "\u0354"=>220,
    "\u0355"=>220,
    "\u0356"=>220,
    "\u0357"=>230,
    "\u0358"=>232,
    "\u0359"=>220,
    "\u035A"=>220,
    "\u035B"=>230,
    "\u035C"=>233,
    "\u035D"=>234,
    "\u035E"=>234,
    "\u035F"=>233,
    "\u0360"=>234,
    "\u0361"=>234,
    "\u0362"=>233,
    "\u0363"=>230,
    "\u0364"=>230,
    "\u0365"=>230,
    "\u0366"=>230,
    "\u0367"=>230,
    "\u0368"=>230,
    "\u0369"=>230,
    "\u036A"=>230,
    "\u036B"=>230,
    "\u036C"=>230,
    "\u036D"=>230,
    "\u036E"=>230,
    "\u036F"=>230,
    "\u0483"=>230,
    "\u0484"=>230,
    "\u0485"=>230,
    "\u0486"=>230,
    "\u0487"=>230,
    "\u0591"=>220,
    "\u0592"=>230,
    "\u0593"=>230,
    "\u0594"=>230,
    "\u0595"=>230,
    "\u0596"=>220,
    "\u0597"=>230,
    "\u0598"=>230,
    "\u0599"=>230,
    "\u059A"=>222,
    "\u059B"=>220,
    "\u059C"=>230,
    "\u059D"=>230,
    "\u059E"=>230,
    "\u059F"=>230,
    "\u05A0"=>230,
    "\u05A1"=>230,
    "\u05A2"=>220,
    "\u05A3"=>220,
    "\u05A4"=>220,
    "\u05A5"=>220,
    "\u05A6"=>220,
    "\u05A7"=>220,
    "\u05A8"=>230,
    "\u05A9"=>230,
    "\u05AA"=>220,
    "\u05AB"=>230,
    "\u05AC"=>230,
    "\u05AD"=>222,
    "\u05AE"=>228,
    "\u05AF"=>230,
    "\u05B0"=>10,
    "\u05B1"=>11,
    "\u05B2"=>12,
    "\u05B3"=>13,
    "\u05B4"=>14,
    "\u05B5"=>15,
    "\u05B6"=>16,
    "\u05B7"=>17,
    "\u05B8"=>18,
    "\u05B9"=>19,
    "\u05BA"=>19,
    "\u05BB"=>20,
    "\u05BC"=>21,
    "\u05BD"=>22,
    "\u05BF"=>23,
    "\u05C1"=>24,
    "\u05C2"=>25,
    "\u05C4"=>230,
    "\u05C5"=>220,
    "\u05C7"=>18,
    "\u0610"=>230,
    "\u0611"=>230,
    "\u0612"=>230,
    "\u0613"=>230,
    "\u0614"=>230,
    "\u0615"=>230,
    "\u0616"=>230,
    "\u0617"=>230,
    "\u0618"=>30,
    "\u0619"=>31,
    "\u061A"=>32,
    "\u064B"=>27,
    "\u064C"=>28,
    "\u064D"=>29,
    "\u064E"=>30,
    "\u064F"=>31,
    "\u0650"=>32,
    "\u0651"=>33,
    "\u0652"=>34,
    "\u0653"=>230,
    "\u0654"=>230,
    "\u0655"=>220,
    "\u0656"=>220,
    "\u0657"=>230,
    "\u0658"=>230,
    "\u0659"=>230,
    "\u065A"=>230,
    "\u065B"=>230,
    "\u065C"=>220,
    "\u065D"=>230,
    "\u065E"=>230,
    "\u065F"=>220,
    "\u0670"=>35,
    "\u06D6"=>230,
    "\u06D7"=>230,
    "\u06D8"=>230,
    "\u06D9"=>230,
    "\u06DA"=>230,
    "\u06DB"=>230,
    "\u06DC"=>230,
    "\u06DF"=>230,
    "\u06E0"=>230,
    "\u06E1"=>230,
    "\u06E2"=>230,
    "\u06E3"=>220,
    "\u06E4"=>230,
    "\u06E7"=>230,
    "\u06E8"=>230,
    "\u06EA"=>220,
    "\u06EB"=>230,
    "\u06EC"=>230,
    "\u06ED"=>220,
    "\u0711"=>36,
    "\u0730"=>230,
    "\u0731"=>220,
    "\u0732"=>230,
    "\u0733"=>230,
    "\u0734"=>220,
    "\u0735"=>230,
    "\u0736"=>230,
    "\u0737"=>220,
    "\u0738"=>220,
    "\u0739"=>220,
    "\u073A"=>230,
    "\u073B"=>220,
    "\u073C"=>220,
    "\u073D"=>230,
    "\u073E"=>220,
    "\u073F"=>230,
    "\u0740"=>230,
    "\u0741"=>230,
    "\u0742"=>220,
    "\u0743"=>230,
    "\u0744"=>220,
    "\u0745"=>230,
    "\u0746"=>220,
    "\u0747"=>230,
    "\u0748"=>220,
    "\u0749"=>230,
    "\u074A"=>230,
    "\u07EB"=>230,
    "\u07EC"=>230,
    "\u07ED"=>230,
    "\u07EE"=>230,
    "\u07EF"=>230,
    "\u07F0"=>230,
    "\u07F1"=>230,
    "\u07F2"=>220,
    "\u07F3"=>230,
    "\u07FD"=>220,
    "\u0816"=>230,
    "\u0817"=>230,
    "\u0818"=>230,
    "\u0819"=>230,
    "\u081B"=>230,
    "\u081C"=>230,
    "\u081D"=>230,
    "\u081E"=>230,
    "\u081F"=>230,
    "\u0820"=>230,
    "\u0821"=>230,
    "\u0822"=>230,
    "\u0823"=>230,
    "\u0825"=>230,
    "\u0826"=>230,
    "\u0827"=>230,
    "\u0829"=>230,
    "\u082A"=>230,
    "\u082B"=>230,
    "\u082C"=>230,
    "\u082D"=>230,
    "\u0859"=>220,
    "\u085A"=>220,
    "\u085B"=>220,
    "\u08D3"=>220,
    "\u08D4"=>230,
    "\u08D5"=>230,
    "\u08D6"=>230,
    "\u08D7"=>230,
    "\u08D8"=>230,
    "\u08D9"=>230,
    "\u08DA"=>230,
    "\u08DB"=>230,
    "\u08DC"=>230,
    "\u08DD"=>230,
    "\u08DE"=>230,
    "\u08DF"=>230,
    "\u08E0"=>230,
    "\u08E1"=>230,
    "\u08E3"=>220,
    "\u08E4"=>230,
    "\u08E5"=>230,
    "\u08E6"=>220,
    "\u08E7"=>230,
    "\u08E8"=>230,
    "\u08E9"=>220,
    "\u08EA"=>230,
    "\u08EB"=>230,
    "\u08EC"=>230,
    "\u08ED"=>220,
    "\u08EE"=>220,
    "\u08EF"=>220,
    "\u08F0"=>27,
    "\u08F1"=>28,
    "\u08F2"=>29,
    "\u08F3"=>230,
    "\u08F4"=>230,
    "\u08F5"=>230,
    "\u08F6"=>220,
    "\u08F7"=>230,
    "\u08F8"=>230,
    "\u08F9"=>220,
    "\u08FA"=>220,
    "\u08FB"=>230,
    "\u08FC"=>230,
    "\u08FD"=>230,
    "\u08FE"=>230,
    "\u08FF"=>230,
    "\u093C"=>7,
    "\u094D"=>9,
    "\u0951"=>230,
    "\u0952"=>220,
    "\u0953"=>230,
    "\u0954"=>230,
    "\u09BC"=>7,
    "\u09CD"=>9,
    "\u09FE"=>230,
    "\u0A3C"=>7,
    "\u0A4D"=>9,
    "\u0ABC"=>7,
    "\u0ACD"=>9,
    "\u0B3C"=>7,
    "\u0B4D"=>9,
    "\u0BCD"=>9,
    "\u0C4D"=>9,
    "\u0C55"=>84,
    "\u0C56"=>91,
    "\u0CBC"=>7,
    "\u0CCD"=>9,
    "\u0D3B"=>9,
    "\u0D3C"=>9,
    "\u0D4D"=>9,
    "\u0DCA"=>9,
    "\u0E38"=>103,
    "\u0E39"=>103,
    "\u0E3A"=>9,
    "\u0E48"=>107,
    "\u0E49"=>107,
    "\u0E4A"=>107,
    "\u0E4B"=>107,
    "\u0EB8"=>118,
    "\u0EB9"=>118,
    "\u0EBA"=>9,
    "\u0EC8"=>122,
    "\u0EC9"=>122,
    "\u0ECA"=>122,
    "\u0ECB"=>122,
    "\u0F18"=>220,
    "\u0F19"=>220,
    "\u0F35"=>220,
    "\u0F37"=>220,
    "\u0F39"=>216,
    "\u0F71"=>129,
    "\u0F72"=>130,
    "\u0F74"=>132,
    "\u0F7A"=>130,
    "\u0F7B"=>130,
    "\u0F7C"=>130,
    "\u0F7D"=>130,
    "\u0F80"=>130,
    "\u0F82"=>230,
    "\u0F83"=>230,
    "\u0F84"=>9,
    "\u0F86"=>230,
    "\u0F87"=>230,
    "\u0FC6"=>220,
    "\u1037"=>7,
    "\u1039"=>9,
    "\u103A"=>9,
    "\u108D"=>220,
    "\u135D"=>230,
    "\u135E"=>230,
    "\u135F"=>230,
    "\u1714"=>9,
    "\u1734"=>9,
    "\u17D2"=>9,
    "\u17DD"=>230,
    "\u18A9"=>228,
    "\u1939"=>222,
    "\u193A"=>230,
    "\u193B"=>220,
    "\u1A17"=>230,
    "\u1A18"=>220,
    "\u1A60"=>9,
    "\u1A75"=>230,
    "\u1A76"=>230,
    "\u1A77"=>230,
    "\u1A78"=>230,
    "\u1A79"=>230,
    "\u1A7A"=>230,
    "\u1A7B"=>230,
    "\u1A7C"=>230,
    "\u1A7F"=>220,
    "\u1AB0"=>230,
    "\u1AB1"=>230,
    "\u1AB2"=>230,
    "\u1AB3"=>230,
    "\u1AB4"=>230,
    "\u1AB5"=>220,
    "\u1AB6"=>220,
    "\u1AB7"=>220,
    "\u1AB8"=>220,
    "\u1AB9"=>220,
    "\u1ABA"=>220,
    "\u1ABB"=>230,
    "\u1ABC"=>230,
    "\u1ABD"=>220,
    "\u1B34"=>7,
    "\u1B44"=>9,
    "\u1B6B"=>230,
    "\u1B6C"=>220,
    "\u1B6D"=>230,
    "\u1B6E"=>230,
    "\u1B6F"=>230,
    "\u1B70"=>230,
    "\u1B71"=>230,
    "\u1B72"=>230,
    "\u1B73"=>230,
    "\u1BAA"=>9,
    "\u1BAB"=>9,
    "\u1BE6"=>7,
    "\u1BF2"=>9,
    "\u1BF3"=>9,
    "\u1C37"=>7,
    "\u1CD0"=>230,
    "\u1CD1"=>230,
    "\u1CD2"=>230,
    "\u1CD4"=>1,
    "\u1CD5"=>220,
    "\u1CD6"=>220,
    "\u1CD7"=>220,
    "\u1CD8"=>220,
    "\u1CD9"=>220,
    "\u1CDA"=>230,
    "\u1CDB"=>230,
    "\u1CDC"=>220,
    "\u1CDD"=>220,
    "\u1CDE"=>220,
    "\u1CDF"=>220,
    "\u1CE0"=>230,
    "\u1CE2"=>1,
    "\u1CE3"=>1,
    "\u1CE4"=>1,
    "\u1CE5"=>1,
    "\u1CE6"=>1,
    "\u1CE7"=>1,
    "\u1CE8"=>1,
    "\u1CED"=>220,
    "\u1CF4"=>230,
    "\u1CF8"=>230,
    "\u1CF9"=>230,
    "\u1DC0"=>230,
    "\u1DC1"=>230,
    "\u1DC2"=>220,
    "\u1DC3"=>230,
    "\u1DC4"=>230,
    "\u1DC5"=>230,
    "\u1DC6"=>230,
    "\u1DC7"=>230,
    "\u1DC8"=>230,
    "\u1DC9"=>230,
    "\u1DCA"=>220,
    "\u1DCB"=>230,
    "\u1DCC"=>230,
    "\u1DCD"=>234,
    "\u1DCE"=>214,
    "\u1DCF"=>220,
    "\u1DD0"=>202,
    "\u1DD1"=>230,
    "\u1DD2"=>230,
    "\u1DD3"=>230,
    "\u1DD4"=>230,
    "\u1DD5"=>230,
    "\u1DD6"=>230,
    "\u1DD7"=>230,
    "\u1DD8"=>230,
    "\u1DD9"=>230,
    "\u1DDA"=>230,
    "\u1DDB"=>230,
    "\u1DDC"=>230,
    "\u1DDD"=>230,
    "\u1DDE"=>230,
    "\u1DDF"=>230,
    "\u1DE0"=>230,
    "\u1DE1"=>230,
    "\u1DE2"=>230,
    "\u1DE3"=>230,
    "\u1DE4"=>230,
    "\u1DE5"=>230,
    "\u1DE6"=>230,
    "\u1DE7"=>230,
    "\u1DE8"=>230,
    "\u1DE9"=>230,
    "\u1DEA"=>230,
    "\u1DEB"=>230,
    "\u1DEC"=>230,
    "\u1DED"=>230,
    "\u1DEE"=>230,
    "\u1DEF"=>230,
    "\u1DF0"=>230,
    "\u1DF1"=>230,
    "\u1DF2"=>230,
    "\u1DF3"=>230,
    "\u1DF4"=>230,
    "\u1DF5"=>230,
    "\u1DF6"=>232,
    "\u1DF7"=>228,
    "\u1DF8"=>228,
    "\u1DF9"=>220,
    "\u1DFB"=>230,
    "\u1DFC"=>233,
    "\u1DFD"=>220,
    "\u1DFE"=>230,
    "\u1DFF"=>220,
    "\u20D0"=>230,
    "\u20D1"=>230,
    "\u20D2"=>1,
    "\u20D3"=>1,
    "\u20D4"=>230,
    "\u20D5"=>230,
    "\u20D6"=>230,
    "\u20D7"=>230,
    "\u20D8"=>1,
    "\u20D9"=>1,
    "\u20DA"=>1,
    "\u20DB"=>230,
    "\u20DC"=>230,
    "\u20E1"=>230,
    "\u20E5"=>1,
    "\u20E6"=>1,
    "\u20E7"=>230,
    "\u20E8"=>220,
    "\u20E9"=>230,
    "\u20EA"=>1,
    "\u20EB"=>1,
    "\u20EC"=>220,
    "\u20ED"=>220,
    "\u20EE"=>220,
    "\u20EF"=>220,
    "\u20F0"=>230,
    "\u2CEF"=>230,
    "\u2CF0"=>230,
    "\u2CF1"=>230,
    "\u2D7F"=>9,
    "\u2DE0"=>230,
    "\u2DE1"=>230,
    "\u2DE2"=>230,
    "\u2DE3"=>230,
    "\u2DE4"=>230,
    "\u2DE5"=>230,
    "\u2DE6"=>230,
    "\u2DE7"=>230,
    "\u2DE8"=>230,
    "\u2DE9"=>230,
    "\u2DEA"=>230,
    "\u2DEB"=>230,
    "\u2DEC"=>230,
    "\u2DED"=>230,
    "\u2DEE"=>230,
    "\u2DEF"=>230,
    "\u2DF0"=>230,
    "\u2DF1"=>230,
    "\u2DF2"=>230,
    "\u2DF3"=>230,
    "\u2DF4"=>230,
    "\u2DF5"=>230,
    "\u2DF6"=>230,
    "\u2DF7"=>230,
    "\u2DF8"=>230,
    "\u2DF9"=>230,
    "\u2DFA"=>230,
    "\u2DFB"=>230,
    "\u2DFC"=>230,
    "\u2DFD"=>230,
    "\u2DFE"=>230,
    "\u2DFF"=>230,
    "\u302A"=>218,
    "\u302B"=>228,
    "\u302C"=>232,
    "\u302D"=>222,
    "\u302E"=>224,
    "\u302F"=>224,
    "\u3099"=>8,
    "\u309A"=>8,
    "\uA66F"=>230,
    "\uA674"=>230,
    "\uA675"=>230,
    "\uA676"=>230,
    "\uA677"=>230,
    "\uA678"=>230,
    "\uA679"=>230,
    "\uA67A"=>230,
    "\uA67B"=>230,
    "\uA67C"=>230,
    "\uA67D"=>230,
    "\uA69E"=>230,
    "\uA69F"=>230,
    "\uA6F0"=>230,
    "\uA6F1"=>230,
    "\uA806"=>9,
    "\uA8C4"=>9,
    "\uA8E0"=>230,
    "\uA8E1"=>230,
    "\uA8E2"=>230,
    "\uA8E3"=>230,
    "\uA8E4"=>230,
    "\uA8E5"=>230,
    "\uA8E6"=>230,
    "\uA8E7"=>230,
    "\uA8E8"=>230,
    "\uA8E9"=>230,
    "\uA8EA"=>230,
    "\uA8EB"=>230,
    "\uA8EC"=>230,
    "\uA8ED"=>230,
    "\uA8EE"=>230,
    "\uA8EF"=>230,
    "\uA8F0"=>230,
    "\uA8F1"=>230,
    "\uA92B"=>220,
    "\uA92C"=>220,
    "\uA92D"=>220,
    "\uA953"=>9,
    "\uA9B3"=>7,
    "\uA9C0"=>9,
    "\uAAB0"=>230,
    "\uAAB2"=>230,
    "\uAAB3"=>230,
    "\uAAB4"=>220,
    "\uAAB7"=>230,
    "\uAAB8"=>230,
    "\uAABE"=>230,
    "\uAABF"=>230,
    "\uAAC1"=>230,
    "\uAAF6"=>9,
    "\uABED"=>9,
    "\uFB1E"=>26,
    "\uFE20"=>230,
    "\uFE21"=>230,
    "\uFE22"=>230,
    "\uFE23"=>230,
    "\uFE24"=>230,
    "\uFE25"=>230,
    "\uFE26"=>230,
    "\uFE27"=>220,
    "\uFE28"=>220,
    "\uFE29"=>220,
    "\uFE2A"=>220,
    "\uFE2B"=>220,
    "\uFE2C"=>220,
    "\uFE2D"=>220,
    "\uFE2E"=>230,
    "\uFE2F"=>230,
    "\u{101FD}"=>220,
    "\u{102E0}"=>220,
    "\u{10376}"=>230,
    "\u{10377}"=>230,
    "\u{10378}"=>230,
    "\u{10379}"=>230,
    "\u{1037A}"=>230,
    "\u{10A0D}"=>220,
    "\u{10A0F}"=>230,
    "\u{10A38}"=>230,
    "\u{10A39}"=>1,
    "\u{10A3A}"=>220,
    "\u{10A3F}"=>9,
    "\u{10AE5}"=>230,
    "\u{10AE6}"=>220,
    "\u{10D24}"=>230,
    "\u{10D25}"=>230,
    "\u{10D26}"=>230,
    "\u{10D27}"=>230,
    "\u{10F46}"=>220,
    "\u{10F47}"=>220,
    "\u{10F48}"=>230,
    "\u{10F49}"=>230,
    "\u{10F4A}"=>230,
    "\u{10F4B}"=>220,
    "\u{10F4C}"=>230,
    "\u{10F4D}"=>220,
    "\u{10F4E}"=>220,
    "\u{10F4F}"=>220,
    "\u{10F50}"=>220,
    "\u{11046}"=>9,
    "\u{1107F}"=>9,
    "\u{110B9}"=>9,
    "\u{110BA}"=>7,
    "\u{11100}"=>230,
    "\u{11101}"=>230,
    "\u{11102}"=>230,
    "\u{11133}"=>9,
    "\u{11134}"=>9,
    "\u{11173}"=>7,
    "\u{111C0}"=>9,
    "\u{111CA}"=>7,
    "\u{11235}"=>9,
    "\u{11236}"=>7,
    "\u{112E9}"=>7,
    "\u{112EA}"=>9,
    "\u{1133B}"=>7,
    "\u{1133C}"=>7,
    "\u{1134D}"=>9,
    "\u{11366}"=>230,
    "\u{11367}"=>230,
    "\u{11368}"=>230,
    "\u{11369}"=>230,
    "\u{1136A}"=>230,
    "\u{1136B}"=>230,
    "\u{1136C}"=>230,
    "\u{11370}"=>230,
    "\u{11371}"=>230,
    "\u{11372}"=>230,
    "\u{11373}"=>230,
    "\u{11374}"=>230,
    "\u{11442}"=>9,
    "\u{11446}"=>7,
    "\u{1145E}"=>230,
    "\u{114C2}"=>9,
    "\u{114C3}"=>7,
    "\u{115BF}"=>9,
    "\u{115C0}"=>7,
    "\u{1163F}"=>9,
    "\u{116B6}"=>9,
    "\u{116B7}"=>7,
    "\u{1172B}"=>9,
    "\u{11839}"=>9,
    "\u{1183A}"=>7,
    "\u{119E0}"=>9,
    "\u{11A34}"=>9,
    "\u{11A47}"=>9,
    "\u{11A99}"=>9,
    "\u{11C3F}"=>9,
    "\u{11D42}"=>7,
    "\u{11D44}"=>9,
    "\u{11D45}"=>9,
    "\u{11D97}"=>9,
    "\u{16AF0}"=>1,
    "\u{16AF1}"=>1,
    "\u{16AF2}"=>1,
    "\u{16AF3}"=>1,
    "\u{16AF4}"=>1,
    "\u{16B30}"=>230,
    "\u{16B31}"=>230,
    "\u{16B32}"=>230,
    "\u{16B33}"=>230,
    "\u{16B34}"=>230,
    "\u{16B35}"=>230,
    "\u{16B36}"=>230,
    "\u{1BC9E}"=>1,
    "\u{1D165}"=>216,
    "\u{1D166}"=>216,
    "\u{1D167}"=>1,
    "\u{1D168}"=>1,
    "\u{1D169}"=>1,
    "\u{1D16D}"=>226,
    "\u{1D16E}"=>216,
    "\u{1D16F}"=>216,
    "\u{1D170}"=>216,
    "\u{1D171}"=>216,
    "\u{1D172}"=>216,
    "\u{1D17B}"=>220,
    "\u{1D17C}"=>220,
    "\u{1D17D}"=>220,
    "\u{1D17E}"=>220,
    "\u{1D17F}"=>220,
    "\u{1D180}"=>220,
    "\u{1D181}"=>220,
    "\u{1D182}"=>220,
    "\u{1D185}"=>230,
    "\u{1D186}"=>230,
    "\u{1D187}"=>230,
    "\u{1D188}"=>230,
    "\u{1D189}"=>230,
    "\u{1D18A}"=>220,
    "\u{1D18B}"=>220,
    "\u{1D1AA}"=>230,
    "\u{1D1AB}"=>230,
    "\u{1D1AC}"=>230,
    "\u{1D1AD}"=>230,
    "\u{1D242}"=>230,
    "\u{1D243}"=>230,
    "\u{1D244}"=>230,
    "\u{1E000}"=>230,
    "\u{1E001}"=>230,
    "\u{1E002}"=>230,
    "\u{1E003}"=>230,
    "\u{1E004}"=>230,
    "\u{1E005}"=>230,
    "\u{1E006}"=>230,
    "\u{1E008}"=>230,
    "\u{1E009}"=>230,
    "\u{1E00A}"=>230,
    "\u{1E00B}"=>230,
    "\u{1E00C}"=>230,
    "\u{1E00D}"=>230,
    "\u{1E00E}"=>230,
    "\u{1E00F}"=>230,
    "\u{1E010}"=>230,
    "\u{1E011}"=>230,
    "\u{1E012}"=>230,
    "\u{1E013}"=>230,
    "\u{1E014}"=>230,
    "\u{1E015}"=>230,
    "\u{1E016}"=>230,
    "\u{1E017}"=>230,
    "\u{1E018}"=>230,
    "\u{1E01B}"=>230,
    "\u{1E01C}"=>230,
    "\u{1E01D}"=>230,
    "\u{1E01E}"=>230,
    "\u{1E01F}"=>230,
    "\u{1E020}"=>230,
    "\u{1E021}"=>230,
    "\u{1E023}"=>230,
    "\u{1E024}"=>230,
    "\u{1E026}"=>230,
    "\u{1E027}"=>230,
    "\u{1E028}"=>230,
    "\u{1E029}"=>230,
    "\u{1E02A}"=>230,
    "\u{1E130}"=>230,
    "\u{1E131}"=>230,
    "\u{1E132}"=>230,
    "\u{1E133}"=>230,
    "\u{1E134}"=>230,
    "\u{1E135}"=>230,
    "\u{1E136}"=>230,
    "\u{1E2EC}"=>230,
    "\u{1E2ED}"=>230,
    "\u{1E2EE}"=>230,
    "\u{1E2EF}"=>230,
    "\u{1E8D0}"=>220,
    "\u{1E8D1}"=>220,
    "\u{1E8D2}"=>220,
    "\u{1E8D3}"=>220,
    "\u{1E8D4}"=>220,
    "\u{1E8D5}"=>220,
    "\u{1E8D6}"=>220,
    "\u{1E944}"=>230,
    "\u{1E945}"=>230,
    "\u{1E946}"=>230,
    "\u{1E947}"=>230,
    "\u{1E948}"=>230,
    "\u{1E949}"=>230,
    "\u{1E94A}"=>7,
  }
  class_table.default = 0
  CLASS_TABLE = class_table.freeze

  DECOMPOSITION_TABLE = {
    "\u00C0"=>"A\u0300",
    "\u00C1"=>"A\u0301",
    "\u00C2"=>"A\u0302",
    "\u00C3"=>"A\u0303",
    "\u00C4"=>"A\u0308",
    "\u00C5"=>"A\u030A",
    "\u00C7"=>"C\u0327",
    "\u00C8"=>"E\u0300",
    "\u00C9"=>"E\u0301",
    "\u00CA"=>"E\u0302",
    "\u00CB"=>"E\u0308",
    "\u00CC"=>"I\u0300",
    "\u00CD"=>"I\u0301",
    "\u00CE"=>"I\u0302",
    "\u00CF"=>"I\u0308",
    "\u00D1"=>"N\u0303",
    "\u00D2"=>"O\u0300",
    "\u00D3"=>"O\u0301",
    "\u00D4"=>"O\u0302",
    "\u00D5"=>"O\u0303",
    "\u00D6"=>"O\u0308",
    "\u00D9"=>"U\u0300",
    "\u00DA"=>"U\u0301",
    "\u00DB"=>"U\u0302",
    "\u00DC"=>"U\u0308",
    "\u00DD"=>"Y\u0301",
    "\u00E0"=>"a\u0300",
    "\u00E1"=>"a\u0301",
    "\u00E2"=>"a\u0302",
    "\u00E3"=>"a\u0303",
    "\u00E4"=>"a\u0308",
    "\u00E5"=>"a\u030A",
    "\u00E7"=>"c\u0327",
    "\u00E8"=>"e\u0300",
    "\u00E9"=>"e\u0301",
    "\u00EA"=>"e\u0302",
    "\u00EB"=>"e\u0308",
    "\u00EC"=>"i\u0300",
    "\u00ED"=>"i\u0301",
    "\u00EE"=>"i\u0302",
    "\u00EF"=>"i\u0308",
    "\u00F1"=>"n\u0303",
    "\u00F2"=>"o\u0300",
    "\u00F3"=>"o\u0301",
    "\u00F4"=>"o\u0302",
    "\u00F5"=>"o\u0303",
    "\u00F6"=>"o\u0308",
    "\u00F9"=>"u\u0300",
    "\u00FA"=>"u\u0301",
    "\u00FB"=>"u\u0302",
    "\u00FC"=>"u\u0308",
    "\u00FD"=>"y\u0301",
    "\u00FF"=>"y\u0308",
    "\u0100"=>"A\u0304",
    "\u0101"=>"a\u0304",
    "\u0102"=>"A\u0306",
    "\u0103"=>"a\u0306",
    "\u0104"=>"A\u0328",
    "\u0105"=>"a\u0328",
    "\u0106"=>"C\u0301",
    "\u0107"=>"c\u0301",
    "\u0108"=>"C\u0302",
    "\u0109"=>"c\u0302",
    "\u010A"=>"C\u0307",
    "\u010B"=>"c\u0307",
    "\u010C"=>"C\u030C",
    "\u010D"=>"c\u030C",
    "\u010E"=>"D\u030C",
    "\u010F"=>"d\u030C",
    "\u0112"=>"E\u0304",
    "\u0113"=>"e\u0304",
    "\u0114"=>"E\u0306",
    "\u0115"=>"e\u0306",
    "\u0116"=>"E\u0307",
    "\u0117"=>"e\u0307",
    "\u0118"=>"E\u0328",
    "\u0119"=>"e\u0328",
    "\u011A"=>"E\u030C",
    "\u011B"=>"e\u030C",
    "\u011C"=>"G\u0302",
    "\u011D"=>"g\u0302",
    "\u011E"=>"G\u0306",
    "\u011F"=>"g\u0306",
    "\u0120"=>"G\u0307",
    "\u0121"=>"g\u0307",
    "\u0122"=>"G\u0327",
    "\u0123"=>"g\u0327",
    "\u0124"=>"H\u0302",
    "\u0125"=>"h\u0302",
    "\u0128"=>"I\u0303",
    "\u0129"=>"i\u0303",
    "\u012A"=>"I\u0304",
    "\u012B"=>"i\u0304",
    "\u012C"=>"I\u0306",
    "\u012D"=>"i\u0306",
    "\u012E"=>"I\u0328",
    "\u012F"=>"i\u0328",
    "\u0130"=>"I\u0307",
    "\u0134"=>"J\u0302",
    "\u0135"=>"j\u0302",
    "\u0136"=>"K\u0327",
    "\u0137"=>"k\u0327",
    "\u0139"=>"L\u0301",
    "\u013A"=>"l\u0301",
    "\u013B"=>"L\u0327",
    "\u013C"=>"l\u0327",
    "\u013D"=>"L\u030C",
    "\u013E"=>"l\u030C",
    "\u0143"=>"N\u0301",
    "\u0144"=>"n\u0301",
    "\u0145"=>"N\u0327",
    "\u0146"=>"n\u0327",
    "\u0147"=>"N\u030C",
    "\u0148"=>"n\u030C",
    "\u014C"=>"O\u0304",
    "\u014D"=>"o\u0304",
    "\u014E"=>"O\u0306",
    "\u014F"=>"o\u0306",
    "\u0150"=>"O\u030B",
    "\u0151"=>"o\u030B",
    "\u0154"=>"R\u0301",
    "\u0155"=>"r\u0301",
    "\u0156"=>"R\u0327",
    "\u0157"=>"r\u0327",
    "\u0158"=>"R\u030C",
    "\u0159"=>"r\u030C",
    "\u015A"=>"S\u0301",
    "\u015B"=>"s\u0301",
    "\u015C"=>"S\u0302",
    "\u015D"=>"s\u0302",
    "\u015E"=>"S\u0327",
    "\u015F"=>"s\u0327",
    "\u0160"=>"S\u030C",
    "\u0161"=>"s\u030C",
    "\u0162"=>"T\u0327",
    "\u0163"=>"t\u0327",
    "\u0164"=>"T\u030C",
    "\u0165"=>"t\u030C",
    "\u0168"=>"U\u0303",
    "\u0169"=>"u\u0303",
    "\u016A"=>"U\u0304",
    "\u016B"=>"u\u0304",
    "\u016C"=>"U\u0306",
    "\u016D"=>"u\u0306",
    "\u016E"=>"U\u030A",
    "\u016F"=>"u\u030A",
    "\u0170"=>"U\u030B",
    "\u0171"=>"u\u030B",
    "\u0172"=>"U\u0328",
    "\u0173"=>"u\u0328",
    "\u0174"=>"W\u0302",
    "\u0175"=>"w\u0302",
    "\u0176"=>"Y\u0302",
    "\u0177"=>"y\u0302",
    "\u0178"=>"Y\u0308",
    "\u0179"=>"Z\u0301",
    "\u017A"=>"z\u0301",
    "\u017B"=>"Z\u0307",
    "\u017C"=>"z\u0307",
    "\u017D"=>"Z\u030C",
    "\u017E"=>"z\u030C",
    "\u01A0"=>"O\u031B",
    "\u01A1"=>"o\u031B",
    "\u01AF"=>"U\u031B",
    "\u01B0"=>"u\u031B",
    "\u01CD"=>"A\u030C",
    "\u01CE"=>"a\u030C",
    "\u01CF"=>"I\u030C",
    "\u01D0"=>"i\u030C",
    "\u01D1"=>"O\u030C",
    "\u01D2"=>"o\u030C",
    "\u01D3"=>"U\u030C",
    "\u01D4"=>"u\u030C",
    "\u01D5"=>"U\u0308\u0304",
    "\u01D6"=>"u\u0308\u0304",
    "\u01D7"=>"U\u0308\u0301",
    "\u01D8"=>"u\u0308\u0301",
    "\u01D9"=>"U\u0308\u030C",
    "\u01DA"=>"u\u0308\u030C",
    "\u01DB"=>"U\u0308\u0300",
    "\u01DC"=>"u\u0308\u0300",
    "\u01DE"=>"A\u0308\u0304",
    "\u01DF"=>"a\u0308\u0304",
    "\u01E0"=>"A\u0307\u0304",
    "\u01E1"=>"a\u0307\u0304",
    "\u01E2"=>"\u00C6\u0304",
    "\u01E3"=>"\u00E6\u0304",
    "\u01E6"=>"G\u030C",
    "\u01E7"=>"g\u030C",
    "\u01E8"=>"K\u030C",
    "\u01E9"=>"k\u030C",
    "\u01EA"=>"O\u0328",
    "\u01EB"=>"o\u0328",
    "\u01EC"=>"O\u0328\u0304",
    "\u01ED"=>"o\u0328\u0304",
    "\u01EE"=>"\u01B7\u030C",
    "\u01EF"=>"\u0292\u030C",
    "\u01F0"=>"j\u030C",
    "\u01F4"=>"G\u0301",
    "\u01F5"=>"g\u0301",
    "\u01F8"=>"N\u0300",
    "\u01F9"=>"n\u0300",
    "\u01FA"=>"A\u030A\u0301",
    "\u01FB"=>"a\u030A\u0301",
    "\u01FC"=>"\u00C6\u0301",
    "\u01FD"=>"\u00E6\u0301",
    "\u01FE"=>"\u00D8\u0301",
    "\u01FF"=>"\u00F8\u0301",
    "\u0200"=>"A\u030F",
    "\u0201"=>"a\u030F",
    "\u0202"=>"A\u0311",
    "\u0203"=>"a\u0311",
    "\u0204"=>"E\u030F",
    "\u0205"=>"e\u030F",
    "\u0206"=>"E\u0311",
    "\u0207"=>"e\u0311",
    "\u0208"=>"I\u030F",
    "\u0209"=>"i\u030F",
    "\u020A"=>"I\u0311",
    "\u020B"=>"i\u0311",
    "\u020C"=>"O\u030F",
    "\u020D"=>"o\u030F",
    "\u020E"=>"O\u0311",
    "\u020F"=>"o\u0311",
    "\u0210"=>"R\u030F",
    "\u0211"=>"r\u030F",
    "\u0212"=>"R\u0311",
    "\u0213"=>"r\u0311",
    "\u0214"=>"U\u030F",
    "\u0215"=>"u\u030F",
    "\u0216"=>"U\u0311",
    "\u0217"=>"u\u0311",
    "\u0218"=>"S\u0326",
    "\u0219"=>"s\u0326",
    "\u021A"=>"T\u0326",
    "\u021B"=>"t\u0326",
    "\u021E"=>"H\u030C",
    "\u021F"=>"h\u030C",
    "\u0226"=>"A\u0307",
    "\u0227"=>"a\u0307",
    "\u0228"=>"E\u0327",
    "\u0229"=>"e\u0327",
    "\u022A"=>"O\u0308\u0304",
    "\u022B"=>"o\u0308\u0304",
    "\u022C"=>"O\u0303\u0304",
    "\u022D"=>"o\u0303\u0304",
    "\u022E"=>"O\u0307",
    "\u022F"=>"o\u0307",
    "\u0230"=>"O\u0307\u0304",
    "\u0231"=>"o\u0307\u0304",
    "\u0232"=>"Y\u0304",
    "\u0233"=>"y\u0304",
    "\u0340"=>"\u0300",
    "\u0341"=>"\u0301",
    "\u0343"=>"\u0313",
    "\u0344"=>"\u0308\u0301",
    "\u0374"=>"\u02B9",
    "\u037E"=>";",
    "\u0385"=>"\u00A8\u0301",
    "\u0386"=>"\u0391\u0301",
    "\u0387"=>"\u00B7",
    "\u0388"=>"\u0395\u0301",
    "\u0389"=>"\u0397\u0301",
    "\u038A"=>"\u0399\u0301",
    "\u038C"=>"\u039F\u0301",
    "\u038E"=>"\u03A5\u0301",
    "\u038F"=>"\u03A9\u0301",
    "\u0390"=>"\u03B9\u0308\u0301",
    "\u03AA"=>"\u0399\u0308",
    "\u03AB"=>"\u03A5\u0308",
    "\u03AC"=>"\u03B1\u0301",
    "\u03AD"=>"\u03B5\u0301",
    "\u03AE"=>"\u03B7\u0301",
    "\u03AF"=>"\u03B9\u0301",
    "\u03B0"=>"\u03C5\u0308\u0301",
    "\u03CA"=>"\u03B9\u0308",
    "\u03CB"=>"\u03C5\u0308",
    "\u03CC"=>"\u03BF\u0301",
    "\u03CD"=>"\u03C5\u0301",
    "\u03CE"=>"\u03C9\u0301",
    "\u03D3"=>"\u03D2\u0301",
    "\u03D4"=>"\u03D2\u0308",
    "\u0400"=>"\u0415\u0300",
    "\u0401"=>"\u0415\u0308",
    "\u0403"=>"\u0413\u0301",
    "\u0407"=>"\u0406\u0308",
    "\u040C"=>"\u041A\u0301",
    "\u040D"=>"\u0418\u0300",
    "\u040E"=>"\u0423\u0306",
    "\u0419"=>"\u0418\u0306",
    "\u0439"=>"\u0438\u0306",
    "\u0450"=>"\u0435\u0300",
    "\u0451"=>"\u0435\u0308",
    "\u0453"=>"\u0433\u0301",
    "\u0457"=>"\u0456\u0308",
    "\u045C"=>"\u043A\u0301",
    "\u045D"=>"\u0438\u0300",
    "\u045E"=>"\u0443\u0306",
    "\u0476"=>"\u0474\u030F",
    "\u0477"=>"\u0475\u030F",
    "\u04C1"=>"\u0416\u0306",
    "\u04C2"=>"\u0436\u0306",
    "\u04D0"=>"\u0410\u0306",
    "\u04D1"=>"\u0430\u0306",
    "\u04D2"=>"\u0410\u0308",
    "\u04D3"=>"\u0430\u0308",
    "\u04D6"=>"\u0415\u0306",
    "\u04D7"=>"\u0435\u0306",
    "\u04DA"=>"\u04D8\u0308",
    "\u04DB"=>"\u04D9\u0308",
    "\u04DC"=>"\u0416\u0308",
    "\u04DD"=>"\u0436\u0308",
    "\u04DE"=>"\u0417\u0308",
    "\u04DF"=>"\u0437\u0308",
    "\u04E2"=>"\u0418\u0304",
    "\u04E3"=>"\u0438\u0304",
    "\u04E4"=>"\u0418\u0308",
    "\u04E5"=>"\u0438\u0308",
    "\u04E6"=>"\u041E\u0308",
    "\u04E7"=>"\u043E\u0308",
    "\u04EA"=>"\u04E8\u0308",
    "\u04EB"=>"\u04E9\u0308",
    "\u04EC"=>"\u042D\u0308",
    "\u04ED"=>"\u044D\u0308",
    "\u04EE"=>"\u0423\u0304",
    "\u04EF"=>"\u0443\u0304",
    "\u04F0"=>"\u0423\u0308",
    "\u04F1"=>"\u0443\u0308",
    "\u04F2"=>"\u0423\u030B",
    "\u04F3"=>"\u0443\u030B",
    "\u04F4"=>"\u0427\u0308",
    "\u04F5"=>"\u0447\u0308",
    "\u04F8"=>"\u042B\u0308",
    "\u04F9"=>"\u044B\u0308",
    "\u0622"=>"\u0627\u0653",
    "\u0623"=>"\u0627\u0654",
    "\u0624"=>"\u0648\u0654",
    "\u0625"=>"\u0627\u0655",
    "\u0626"=>"\u064A\u0654",
    "\u06C0"=>"\u06D5\u0654",
    "\u06C2"=>"\u06C1\u0654",
    "\u06D3"=>"\u06D2\u0654",
    "\u0929"=>"\u0928\u093C",
    "\u0931"=>"\u0930\u093C",
    "\u0934"=>"\u0933\u093C",
    "\u0958"=>"\u0915\u093C",
    "\u0959"=>"\u0916\u093C",
    "\u095A"=>"\u0917\u093C",
    "\u095B"=>"\u091C\u093C",
    "\u095C"=>"\u0921\u093C",
    "\u095D"=>"\u0922\u093C",
    "\u095E"=>"\u092B\u093C",
    "\u095F"=>"\u092F\u093C",
    "\u09CB"=>"\u09C7\u09BE",
    "\u09CC"=>"\u09C7\u09D7",
    "\u09DC"=>"\u09A1\u09BC",
    "\u09DD"=>"\u09A2\u09BC",
    "\u09DF"=>"\u09AF\u09BC",
    "\u0A33"=>"\u0A32\u0A3C",
    "\u0A36"=>"\u0A38\u0A3C",
    "\u0A59"=>"\u0A16\u0A3C",
    "\u0A5A"=>"\u0A17\u0A3C",
    "\u0A5B"=>"\u0A1C\u0A3C",
    "\u0A5E"=>"\u0A2B\u0A3C",
    "\u0B48"=>"\u0B47\u0B56",
    "\u0B4B"=>"\u0B47\u0B3E",
    "\u0B4C"=>"\u0B47\u0B57",
    "\u0B5C"=>"\u0B21\u0B3C",
    "\u0B5D"=>"\u0B22\u0B3C",
    "\u0B94"=>"\u0B92\u0BD7",
    "\u0BCA"=>"\u0BC6\u0BBE",
    "\u0BCB"=>"\u0BC7\u0BBE",
    "\u0BCC"=>"\u0BC6\u0BD7",
    "\u0C48"=>"\u0C46\u0C56",
    "\u0CC0"=>"\u0CBF\u0CD5",
    "\u0CC7"=>"\u0CC6\u0CD5",
    "\u0CC8"=>"\u0CC6\u0CD6",
    "\u0CCA"=>"\u0CC6\u0CC2",
    "\u0CCB"=>"\u0CC6\u0CC2\u0CD5",
    "\u0D4A"=>"\u0D46\u0D3E",
    "\u0D4B"=>"\u0D47\u0D3E",
    "\u0D4C"=>"\u0D46\u0D57",
    "\u0DDA"=>"\u0DD9\u0DCA",
    "\u0DDC"=>"\u0DD9\u0DCF",
    "\u0DDD"=>"\u0DD9\u0DCF\u0DCA",
    "\u0DDE"=>"\u0DD9\u0DDF",
    "\u0F43"=>"\u0F42\u0FB7",
    "\u0F4D"=>"\u0F4C\u0FB7",
    "\u0F52"=>"\u0F51\u0FB7",
    "\u0F57"=>"\u0F56\u0FB7",
    "\u0F5C"=>"\u0F5B\u0FB7",
    "\u0F69"=>"\u0F40\u0FB5",
    "\u0F73"=>"\u0F71\u0F72",
    "\u0F75"=>"\u0F71\u0F74",
    "\u0F76"=>"\u0FB2\u0F80",
    "\u0F78"=>"\u0FB3\u0F80",
    "\u0F81"=>"\u0F71\u0F80",
    "\u0F93"=>"\u0F92\u0FB7",
    "\u0F9D"=>"\u0F9C\u0FB7",
    "\u0FA2"=>"\u0FA1\u0FB7",
    "\u0FA7"=>"\u0FA6\u0FB7",
    "\u0FAC"=>"\u0FAB\u0FB7",
    "\u0FB9"=>"\u0F90\u0FB5",
    "\u1026"=>"\u1025\u102E",
    "\u1B06"=>"\u1B05\u1B35",
    "\u1B08"=>"\u1B07\u1B35",
    "\u1B0A"=>"\u1B09\u1B35",
    "\u1B0C"=>"\u1B0B\u1B35",
    "\u1B0E"=>"\u1B0D\u1B35",
    "\u1B12"=>"\u1B11\u1B35",
    "\u1B3B"=>"\u1B3A\u1B35",
    "\u1B3D"=>"\u1B3C\u1B35",
    "\u1B40"=>"\u1B3E\u1B35",
    "\u1B41"=>"\u1B3F\u1B35",
    "\u1B43"=>"\u1B42\u1B35",
    "\u1E00"=>"A\u0325",
    "\u1E01"=>"a\u0325",
    "\u1E02"=>"B\u0307",
    "\u1E03"=>"b\u0307",
    "\u1E04"=>"B\u0323",
    "\u1E05"=>"b\u0323",
    "\u1E06"=>"B\u0331",
    "\u1E07"=>"b\u0331",
    "\u1E08"=>"C\u0327\u0301",
    "\u1E09"=>"c\u0327\u0301",
    "\u1E0A"=>"D\u0307",
    "\u1E0B"=>"d\u0307",
    "\u1E0C"=>"D\u0323",
    "\u1E0D"=>"d\u0323",
    "\u1E0E"=>"D\u0331",
    "\u1E0F"=>"d\u0331",
    "\u1E10"=>"D\u0327",
    "\u1E11"=>"d\u0327",
    "\u1E12"=>"D\u032D",
    "\u1E13"=>"d\u032D",
    "\u1E14"=>"E\u0304\u0300",
    "\u1E15"=>"e\u0304\u0300",
    "\u1E16"=>"E\u0304\u0301",
    "\u1E17"=>"e\u0304\u0301",
    "\u1E18"=>"E\u032D",
    "\u1E19"=>"e\u032D",
    "\u1E1A"=>"E\u0330",
    "\u1E1B"=>"e\u0330",
    "\u1E1C"=>"E\u0327\u0306",
    "\u1E1D"=>"e\u0327\u0306",
    "\u1E1E"=>"F\u0307",
    "\u1E1F"=>"f\u0307",
    "\u1E20"=>"G\u0304",
    "\u1E21"=>"g\u0304",
    "\u1E22"=>"H\u0307",
    "\u1E23"=>"h\u0307",
    "\u1E24"=>"H\u0323",
    "\u1E25"=>"h\u0323",
    "\u1E26"=>"H\u0308",
    "\u1E27"=>"h\u0308",
    "\u1E28"=>"H\u0327",
    "\u1E29"=>"h\u0327",
    "\u1E2A"=>"H\u032E",
    "\u1E2B"=>"h\u032E",
    "\u1E2C"=>"I\u0330",
    "\u1E2D"=>"i\u0330",
    "\u1E2E"=>"I\u0308\u0301",
    "\u1E2F"=>"i\u0308\u0301",
    "\u1E30"=>"K\u0301",
    "\u1E31"=>"k\u0301",
    "\u1E32"=>"K\u0323",
    "\u1E33"=>"k\u0323",
    "\u1E34"=>"K\u0331",
    "\u1E35"=>"k\u0331",
    "\u1E36"=>"L\u0323",
    "\u1E37"=>"l\u0323",
    "\u1E38"=>"L\u0323\u0304",
    "\u1E39"=>"l\u0323\u0304",
    "\u1E3A"=>"L\u0331",
    "\u1E3B"=>"l\u0331",
    "\u1E3C"=>"L\u032D",
    "\u1E3D"=>"l\u032D",
    "\u1E3E"=>"M\u0301",
    "\u1E3F"=>"m\u0301",
    "\u1E40"=>"M\u0307",
    "\u1E41"=>"m\u0307",
    "\u1E42"=>"M\u0323",
    "\u1E43"=>"m\u0323",
    "\u1E44"=>"N\u0307",
    "\u1E45"=>"n\u0307",
    "\u1E46"=>"N\u0323",
    "\u1E47"=>"n\u0323",
    "\u1E48"=>"N\u0331",
    "\u1E49"=>"n\u0331",
    "\u1E4A"=>"N\u032D",
    "\u1E4B"=>"n\u032D",
    "\u1E4C"=>"O\u0303\u0301",
    "\u1E4D"=>"o\u0303\u0301",
    "\u1E4E"=>"O\u0303\u0308",
    "\u1E4F"=>"o\u0303\u0308",
    "\u1E50"=>"O\u0304\u0300",
    "\u1E51"=>"o\u0304\u0300",
    "\u1E52"=>"O\u0304\u0301",
    "\u1E53"=>"o\u0304\u0301",
    "\u1E54"=>"P\u0301",
    "\u1E55"=>"p\u0301",
    "\u1E56"=>"P\u0307",
    "\u1E57"=>"p\u0307",
    "\u1E58"=>"R\u0307",
    "\u1E59"=>"r\u0307",
    "\u1E5A"=>"R\u0323",
    "\u1E5B"=>"r\u0323",
    "\u1E5C"=>"R\u0323\u0304",
    "\u1E5D"=>"r\u0323\u0304",
    "\u1E5E"=>"R\u0331",
    "\u1E5F"=>"r\u0331",
    "\u1E60"=>"S\u0307",
    "\u1E61"=>"s\u0307",
    "\u1E62"=>"S\u0323",
    "\u1E63"=>"s\u0323",
    "\u1E64"=>"S\u0301\u0307",
    "\u1E65"=>"s\u0301\u0307",
    "\u1E66"=>"S\u030C\u0307",
    "\u1E67"=>"s\u030C\u0307",
    "\u1E68"=>"S\u0323\u0307",
    "\u1E69"=>"s\u0323\u0307",
    "\u1E6A"=>"T\u0307",
    "\u1E6B"=>"t\u0307",
    "\u1E6C"=>"T\u0323",
    "\u1E6D"=>"t\u0323",
    "\u1E6E"=>"T\u0331",
    "\u1E6F"=>"t\u0331",
    "\u1E70"=>"T\u032D",
    "\u1E71"=>"t\u032D",
    "\u1E72"=>"U\u0324",
    "\u1E73"=>"u\u0324",
    "\u1E74"=>"U\u0330",
    "\u1E75"=>"u\u0330",
    "\u1E76"=>"U\u032D",
    "\u1E77"=>"u\u032D",
    "\u1E78"=>"U\u0303\u0301",
    "\u1E79"=>"u\u0303\u0301",
    "\u1E7A"=>"U\u0304\u0308",
    "\u1E7B"=>"u\u0304\u0308",
    "\u1E7C"=>"V\u0303",
    "\u1E7D"=>"v\u0303",
    "\u1E7E"=>"V\u0323",
    "\u1E7F"=>"v\u0323",
    "\u1E80"=>"W\u0300",
    "\u1E81"=>"w\u0300",
    "\u1E82"=>"W\u0301",
    "\u1E83"=>"w\u0301",
    "\u1E84"=>"W\u0308",
    "\u1E85"=>"w\u0308",
    "\u1E86"=>"W\u0307",
    "\u1E87"=>"w\u0307",
    "\u1E88"=>"W\u0323",
    "\u1E89"=>"w\u0323",
    "\u1E8A"=>"X\u0307",
    "\u1E8B"=>"x\u0307",
    "\u1E8C"=>"X\u0308",
    "\u1E8D"=>"x\u0308",
    "\u1E8E"=>"Y\u0307",
    "\u1E8F"=>"y\u0307",
    "\u1E90"=>"Z\u0302",
    "\u1E91"=>"z\u0302",
    "\u1E92"=>"Z\u0323",
    "\u1E93"=>"z\u0323",
    "\u1E94"=>"Z\u0331",
    "\u1E95"=>"z\u0331",
    "\u1E96"=>"h\u0331",
    "\u1E97"=>"t\u0308",
    "\u1E98"=>"w\u030A",
    "\u1E99"=>"y\u030A",
    "\u1E9B"=>"\u017F\u0307",
    "\u1EA0"=>"A\u0323",
    "\u1EA1"=>"a\u0323",
    "\u1EA2"=>"A\u0309",
    "\u1EA3"=>"a\u0309",
    "\u1EA4"=>"A\u0302\u0301",
    "\u1EA5"=>"a\u0302\u0301",
    "\u1EA6"=>"A\u0302\u0300",
    "\u1EA7"=>"a\u0302\u0300",
    "\u1EA8"=>"A\u0302\u0309",
    "\u1EA9"=>"a\u0302\u0309",
    "\u1EAA"=>"A\u0302\u0303",
    "\u1EAB"=>"a\u0302\u0303",
    "\u1EAC"=>"A\u0323\u0302",
    "\u1EAD"=>"a\u0323\u0302",
    "\u1EAE"=>"A\u0306\u0301",
    "\u1EAF"=>"a\u0306\u0301",
    "\u1EB0"=>"A\u0306\u0300",
    "\u1EB1"=>"a\u0306\u0300",
    "\u1EB2"=>"A\u0306\u0309",
    "\u1EB3"=>"a\u0306\u0309",
    "\u1EB4"=>"A\u0306\u0303",
    "\u1EB5"=>"a\u0306\u0303",
    "\u1EB6"=>"A\u0323\u0306",
    "\u1EB7"=>"a\u0323\u0306",
    "\u1EB8"=>"E\u0323",
    "\u1EB9"=>"e\u0323",
    "\u1EBA"=>"E\u0309",
    "\u1EBB"=>"e\u0309",
    "\u1EBC"=>"E\u0303",
    "\u1EBD"=>"e\u0303",
    "\u1EBE"=>"E\u0302\u0301",
    "\u1EBF"=>"e\u0302\u0301",
    "\u1EC0"=>"E\u0302\u0300",
    "\u1EC1"=>"e\u0302\u0300",
    "\u1EC2"=>"E\u0302\u0309",
    "\u1EC3"=>"e\u0302\u0309",
    "\u1EC4"=>"E\u0302\u0303",
    "\u1EC5"=>"e\u0302\u0303",
    "\u1EC6"=>"E\u0323\u0302",
    "\u1EC7"=>"e\u0323\u0302",
    "\u1EC8"=>"I\u0309",
    "\u1EC9"=>"i\u0309",
    "\u1ECA"=>"I\u0323",
    "\u1ECB"=>"i\u0323",
    "\u1ECC"=>"O\u0323",
    "\u1ECD"=>"o\u0323",
    "\u1ECE"=>"O\u0309",
    "\u1ECF"=>"o\u0309",
    "\u1ED0"=>"O\u0302\u0301",
    "\u1ED1"=>"o\u0302\u0301",
    "\u1ED2"=>"O\u0302\u0300",
    "\u1ED3"=>"o\u0302\u0300",
    "\u1ED4"=>"O\u0302\u0309",
    "\u1ED5"=>"o\u0302\u0309",
    "\u1ED6"=>"O\u0302\u0303",
    "\u1ED7"=>"o\u0302\u0303",
    "\u1ED8"=>"O\u0323\u0302",
    "\u1ED9"=>"o\u0323\u0302",
    "\u1EDA"=>"O\u031B\u0301",
    "\u1EDB"=>"o\u031B\u0301",
    "\u1EDC"=>"O\u031B\u0300",
    "\u1EDD"=>"o\u031B\u0300",
    "\u1EDE"=>"O\u031B\u0309",
    "\u1EDF"=>"o\u031B\u0309",
    "\u1EE0"=>"O\u031B\u0303",
    "\u1EE1"=>"o\u031B\u0303",
    "\u1EE2"=>"O\u031B\u0323",
    "\u1EE3"=>"o\u031B\u0323",
    "\u1EE4"=>"U\u0323",
    "\u1EE5"=>"u\u0323",
    "\u1EE6"=>"U\u0309",
    "\u1EE7"=>"u\u0309",
    "\u1EE8"=>"U\u031B\u0301",
    "\u1EE9"=>"u\u031B\u0301",
    "\u1EEA"=>"U\u031B\u0300",
    "\u1EEB"=>"u\u031B\u0300",
    "\u1EEC"=>"U\u031B\u0309",
    "\u1EED"=>"u\u031B\u0309",
    "\u1EEE"=>"U\u031B\u0303",
    "\u1EEF"=>"u\u031B\u0303",
    "\u1EF0"=>"U\u031B\u0323",
    "\u1EF1"=>"u\u031B\u0323",
    "\u1EF2"=>"Y\u0300",
    "\u1EF3"=>"y\u0300",
    "\u1EF4"=>"Y\u0323",
    "\u1EF5"=>"y\u0323",
    "\u1EF6"=>"Y\u0309",
    "\u1EF7"=>"y\u0309",
    "\u1EF8"=>"Y\u0303",
    "\u1EF9"=>"y\u0303",
    "\u1F00"=>"\u03B1\u0313",
    "\u1F01"=>"\u03B1\u0314",
    "\u1F02"=>"\u03B1\u0313\u0300",
    "\u1F03"=>"\u03B1\u0314\u0300",
    "\u1F04"=>"\u03B1\u0313\u0301",
    "\u1F05"=>"\u03B1\u0314\u0301",
    "\u1F06"=>"\u03B1\u0313\u0342",
    "\u1F07"=>"\u03B1\u0314\u0342",
    "\u1F08"=>"\u0391\u0313",
    "\u1F09"=>"\u0391\u0314",
    "\u1F0A"=>"\u0391\u0313\u0300",
    "\u1F0B"=>"\u0391\u0314\u0300",
    "\u1F0C"=>"\u0391\u0313\u0301",
    "\u1F0D"=>"\u0391\u0314\u0301",
    "\u1F0E"=>"\u0391\u0313\u0342",
    "\u1F0F"=>"\u0391\u0314\u0342",
    "\u1F10"=>"\u03B5\u0313",
    "\u1F11"=>"\u03B5\u0314",
    "\u1F12"=>"\u03B5\u0313\u0300",
    "\u1F13"=>"\u03B5\u0314\u0300",
    "\u1F14"=>"\u03B5\u0313\u0301",
    "\u1F15"=>"\u03B5\u0314\u0301",
    "\u1F18"=>"\u0395\u0313",
    "\u1F19"=>"\u0395\u0314",
    "\u1F1A"=>"\u0395\u0313\u0300",
    "\u1F1B"=>"\u0395\u0314\u0300",
    "\u1F1C"=>"\u0395\u0313\u0301",
    "\u1F1D"=>"\u0395\u0314\u0301",
    "\u1F20"=>"\u03B7\u0313",
    "\u1F21"=>"\u03B7\u0314",
    "\u1F22"=>"\u03B7\u0313\u0300",
    "\u1F23"=>"\u03B7\u0314\u0300",
    "\u1F24"=>"\u03B7\u0313\u0301",
    "\u1F25"=>"\u03B7\u0314\u0301",
    "\u1F26"=>"\u03B7\u0313\u0342",
    "\u1F27"=>"\u03B7\u0314\u0342",
    "\u1F28"=>"\u0397\u0313",
    "\u1F29"=>"\u0397\u0314",
    "\u1F2A"=>"\u0397\u0313\u0300",
    "\u1F2B"=>"\u0397\u0314\u0300",
    "\u1F2C"=>"\u0397\u0313\u0301",
    "\u1F2D"=>"\u0397\u0314\u0301",
    "\u1F2E"=>"\u0397\u0313\u0342",
    "\u1F2F"=>"\u0397\u0314\u0342",
    "\u1F30"=>"\u03B9\u0313",
    "\u1F31"=>"\u03B9\u0314",
    "\u1F32"=>"\u03B9\u0313\u0300",
    "\u1F33"=>"\u03B9\u0314\u0300",
    "\u1F34"=>"\u03B9\u0313\u0301",
    "\u1F35"=>"\u03B9\u0314\u0301",
    "\u1F36"=>"\u03B9\u0313\u0342",
    "\u1F37"=>"\u03B9\u0314\u0342",
    "\u1F38"=>"\u0399\u0313",
    "\u1F39"=>"\u0399\u0314",
    "\u1F3A"=>"\u0399\u0313\u0300",
    "\u1F3B"=>"\u0399\u0314\u0300",
    "\u1F3C"=>"\u0399\u0313\u0301",
    "\u1F3D"=>"\u0399\u0314\u0301",
    "\u1F3E"=>"\u0399\u0313\u0342",
    "\u1F3F"=>"\u0399\u0314\u0342",
    "\u1F40"=>"\u03BF\u0313",
    "\u1F41"=>"\u03BF\u0314",
    "\u1F42"=>"\u03BF\u0313\u0300",
    "\u1F43"=>"\u03BF\u0314\u0300",
    "\u1F44"=>"\u03BF\u0313\u0301",
    "\u1F45"=>"\u03BF\u0314\u0301",
    "\u1F48"=>"\u039F\u0313",
    "\u1F49"=>"\u039F\u0314",
    "\u1F4A"=>"\u039F\u0313\u0300",
    "\u1F4B"=>"\u039F\u0314\u0300",
    "\u1F4C"=>"\u039F\u0313\u0301",
    "\u1F4D"=>"\u039F\u0314\u0301",
    "\u1F50"=>"\u03C5\u0313",
    "\u1F51"=>"\u03C5\u0314",
    "\u1F52"=>"\u03C5\u0313\u0300",
    "\u1F53"=>"\u03C5\u0314\u0300",
    "\u1F54"=>"\u03C5\u0313\u0301",
    "\u1F55"=>"\u03C5\u0314\u0301",
    "\u1F56"=>"\u03C5\u0313\u0342",
    "\u1F57"=>"\u03C5\u0314\u0342",
    "\u1F59"=>"\u03A5\u0314",
    "\u1F5B"=>"\u03A5\u0314\u0300",
    "\u1F5D"=>"\u03A5\u0314\u0301",
    "\u1F5F"=>"\u03A5\u0314\u0342",
    "\u1F60"=>"\u03C9\u0313",
    "\u1F61"=>"\u03C9\u0314",
    "\u1F62"=>"\u03C9\u0313\u0300",
    "\u1F63"=>"\u03C9\u0314\u0300",
    "\u1F64"=>"\u03C9\u0313\u0301",
    "\u1F65"=>"\u03C9\u0314\u0301",
    "\u1F66"=>"\u03C9\u0313\u0342",
    "\u1F67"=>"\u03C9\u0314\u0342",
    "\u1F68"=>"\u03A9\u0313",
    "\u1F69"=>"\u03A9\u0314",
    "\u1F6A"=>"\u03A9\u0313\u0300",
    "\u1F6B"=>"\u03A9\u0314\u0300",
    "\u1F6C"=>"\u03A9\u0313\u0301",
    "\u1F6D"=>"\u03A9\u0314\u0301",
    "\u1F6E"=>"\u03A9\u0313\u0342",
    "\u1F6F"=>"\u03A9\u0314\u0342",
    "\u1F70"=>"\u03B1\u0300",
    "\u1F71"=>"\u03B1\u0301",
    "\u1F72"=>"\u03B5\u0300",
    "\u1F73"=>"\u03B5\u0301",
    "\u1F74"=>"\u03B7\u0300",
    "\u1F75"=>"\u03B7\u0301",
    "\u1F76"=>"\u03B9\u0300",
    "\u1F77"=>"\u03B9\u0301",
    "\u1F78"=>"\u03BF\u0300",
    "\u1F79"=>"\u03BF\u0301",
    "\u1F7A"=>"\u03C5\u0300",
    "\u1F7B"=>"\u03C5\u0301",
    "\u1F7C"=>"\u03C9\u0300",
    "\u1F7D"=>"\u03C9\u0301",
    "\u1F80"=>"\u03B1\u0313\u0345",
    "\u1F81"=>"\u03B1\u0314\u0345",
    "\u1F82"=>"\u03B1\u0313\u0300\u0345",
    "\u1F83"=>"\u03B1\u0314\u0300\u0345",
    "\u1F84"=>"\u03B1\u0313\u0301\u0345",
    "\u1F85"=>"\u03B1\u0314\u0301\u0345",
    "\u1F86"=>"\u03B1\u0313\u0342\u0345",
    "\u1F87"=>"\u03B1\u0314\u0342\u0345",
    "\u1F88"=>"\u0391\u0313\u0345",
    "\u1F89"=>"\u0391\u0314\u0345",
    "\u1F8A"=>"\u0391\u0313\u0300\u0345",
    "\u1F8B"=>"\u0391\u0314\u0300\u0345",
    "\u1F8C"=>"\u0391\u0313\u0301\u0345",
    "\u1F8D"=>"\u0391\u0314\u0301\u0345",
    "\u1F8E"=>"\u0391\u0313\u0342\u0345",
    "\u1F8F"=>"\u0391\u0314\u0342\u0345",
    "\u1F90"=>"\u03B7\u0313\u0345",
    "\u1F91"=>"\u03B7\u0314\u0345",
    "\u1F92"=>"\u03B7\u0313\u0300\u0345",
    "\u1F93"=>"\u03B7\u0314\u0300\u0345",
    "\u1F94"=>"\u03B7\u0313\u0301\u0345",
    "\u1F95"=>"\u03B7\u0314\u0301\u0345",
    "\u1F96"=>"\u03B7\u0313\u0342\u0345",
    "\u1F97"=>"\u03B7\u0314\u0342\u0345",
    "\u1F98"=>"\u0397\u0313\u0345",
    "\u1F99"=>"\u0397\u0314\u0345",
    "\u1F9A"=>"\u0397\u0313\u0300\u0345",
    "\u1F9B"=>"\u0397\u0314\u0300\u0345",
    "\u1F9C"=>"\u0397\u0313\u0301\u0345",
    "\u1F9D"=>"\u0397\u0314\u0301\u0345",
    "\u1F9E"=>"\u0397\u0313\u0342\u0345",
    "\u1F9F"=>"\u0397\u0314\u0342\u0345",
    "\u1FA0"=>"\u03C9\u0313\u0345",
    "\u1FA1"=>"\u03C9\u0314\u0345",
    "\u1FA2"=>"\u03C9\u0313\u0300\u0345",
    "\u1FA3"=>"\u03C9\u0314\u0300\u0345",
    "\u1FA4"=>"\u03C9\u0313\u0301\u0345",
    "\u1FA5"=>"\u03C9\u0314\u0301\u0345",
    "\u1FA6"=>"\u03C9\u0313\u0342\u0345",
    "\u1FA7"=>"\u03C9\u0314\u0342\u0345",
    "\u1FA8"=>"\u03A9\u0313\u0345",
    "\u1FA9"=>"\u03A9\u0314\u0345",
    "\u1FAA"=>"\u03A9\u0313\u0300\u0345",
    "\u1FAB"=>"\u03A9\u0314\u0300\u0345",
    "\u1FAC"=>"\u03A9\u0313\u0301\u0345",
    "\u1FAD"=>"\u03A9\u0314\u0301\u0345",
    "\u1FAE"=>"\u03A9\u0313\u0342\u0345",
    "\u1FAF"=>"\u03A9\u0314\u0342\u0345",
    "\u1FB0"=>"\u03B1\u0306",
    "\u1FB1"=>"\u03B1\u0304",
    "\u1FB2"=>"\u03B1\u0300\u0345",
    "\u1FB3"=>"\u03B1\u0345",
    "\u1FB4"=>"\u03B1\u0301\u0345",
    "\u1FB6"=>"\u03B1\u0342",
    "\u1FB7"=>"\u03B1\u0342\u0345",
    "\u1FB8"=>"\u0391\u0306",
    "\u1FB9"=>"\u0391\u0304",
    "\u1FBA"=>"\u0391\u0300",
    "\u1FBB"=>"\u0391\u0301",
    "\u1FBC"=>"\u0391\u0345",
    "\u1FBE"=>"\u03B9",
    "\u1FC1"=>"\u00A8\u0342",
    "\u1FC2"=>"\u03B7\u0300\u0345",
    "\u1FC3"=>"\u03B7\u0345",
    "\u1FC4"=>"\u03B7\u0301\u0345",
    "\u1FC6"=>"\u03B7\u0342",
    "\u1FC7"=>"\u03B7\u0342\u0345",
    "\u1FC8"=>"\u0395\u0300",
    "\u1FC9"=>"\u0395\u0301",
    "\u1FCA"=>"\u0397\u0300",
    "\u1FCB"=>"\u0397\u0301",
    "\u1FCC"=>"\u0397\u0345",
    "\u1FCD"=>"\u1FBF\u0300",
    "\u1FCE"=>"\u1FBF\u0301",
    "\u1FCF"=>"\u1FBF\u0342",
    "\u1FD0"=>"\u03B9\u0306",
    "\u1FD1"=>"\u03B9\u0304",
    "\u1FD2"=>"\u03B9\u0308\u0300",
    "\u1FD3"=>"\u03B9\u0308\u0301",
    "\u1FD6"=>"\u03B9\u0342",
    "\u1FD7"=>"\u03B9\u0308\u0342",
    "\u1FD8"=>"\u0399\u0306",
    "\u1FD9"=>"\u0399\u0304",
    "\u1FDA"=>"\u0399\u0300",
    "\u1FDB"=>"\u0399\u0301",
    "\u1FDD"=>"\u1FFE\u0300",
    "\u1FDE"=>"\u1FFE\u0301",
    "\u1FDF"=>"\u1FFE\u0342",
    "\u1FE0"=>"\u03C5\u0306",
    "\u1FE1"=>"\u03C5\u0304",
    "\u1FE2"=>"\u03C5\u0308\u0300",
    "\u1FE3"=>"\u03C5\u0308\u0301",
    "\u1FE4"=>"\u03C1\u0313",
    "\u1FE5"=>"\u03C1\u0314",
    "\u1FE6"=>"\u03C5\u0342",
    "\u1FE7"=>"\u03C5\u0308\u0342",
    "\u1FE8"=>"\u03A5\u0306",
    "\u1FE9"=>"\u03A5\u0304",
    "\u1FEA"=>"\u03A5\u0300",
    "\u1FEB"=>"\u03A5\u0301",
    "\u1FEC"=>"\u03A1\u0314",
    "\u1FED"=>"\u00A8\u0300",
    "\u1FEE"=>"\u00A8\u0301",
    "\u1FEF"=>"`",
    "\u1FF2"=>"\u03C9\u0300\u0345",
    "\u1FF3"=>"\u03C9\u0345",
    "\u1FF4"=>"\u03C9\u0301\u0345",
    "\u1FF6"=>"\u03C9\u0342",
    "\u1FF7"=>"\u03C9\u0342\u0345",
    "\u1FF8"=>"\u039F\u0300",
    "\u1FF9"=>"\u039F\u0301",
    "\u1FFA"=>"\u03A9\u0300",
    "\u1FFB"=>"\u03A9\u0301",
    "\u1FFC"=>"\u03A9\u0345",
    "\u1FFD"=>"\u00B4",
    "\u2000"=>"\u2002",
    "\u2001"=>"\u2003",
    "\u2126"=>"\u03A9",
    "\u212A"=>"K",
    "\u212B"=>"A\u030A",
    "\u219A"=>"\u2190\u0338",
    "\u219B"=>"\u2192\u0338",
    "\u21AE"=>"\u2194\u0338",
    "\u21CD"=>"\u21D0\u0338",
    "\u21CE"=>"\u21D4\u0338",
    "\u21CF"=>"\u21D2\u0338",
    "\u2204"=>"\u2203\u0338",
    "\u2209"=>"\u2208\u0338",
    "\u220C"=>"\u220B\u0338",
    "\u2224"=>"\u2223\u0338",
    "\u2226"=>"\u2225\u0338",
    "\u2241"=>"\u223C\u0338",
    "\u2244"=>"\u2243\u0338",
    "\u2247"=>"\u2245\u0338",
    "\u2249"=>"\u2248\u0338",
    "\u2260"=>"=\u0338",
    "\u2262"=>"\u2261\u0338",
    "\u226D"=>"\u224D\u0338",
    "\u226E"=>"<\u0338",
    "\u226F"=>">\u0338",
    "\u2270"=>"\u2264\u0338",
    "\u2271"=>"\u2265\u0338",
    "\u2274"=>"\u2272\u0338",
    "\u2275"=>"\u2273\u0338",
    "\u2278"=>"\u2276\u0338",
    "\u2279"=>"\u2277\u0338",
    "\u2280"=>"\u227A\u0338",
    "\u2281"=>"\u227B\u0338",
    "\u2284"=>"\u2282\u0338",
    "\u2285"=>"\u2283\u0338",
    "\u2288"=>"\u2286\u0338",
    "\u2289"=>"\u2287\u0338",
    "\u22AC"=>"\u22A2\u0338",
    "\u22AD"=>"\u22A8\u0338",
    "\u22AE"=>"\u22A9\u0338",
    "\u22AF"=>"\u22AB\u0338",
    "\u22E0"=>"\u227C\u0338",
    "\u22E1"=>"\u227D\u0338",
    "\u22E2"=>"\u2291\u0338",
    "\u22E3"=>"\u2292\u0338",
    "\u22EA"=>"\u22B2\u0338",
    "\u22EB"=>"\u22B3\u0338",
    "\u22EC"=>"\u22B4\u0338",
    "\u22ED"=>"\u22B5\u0338",
    "\u2329"=>"\u3008",
    "\u232A"=>"\u3009",
    "\u2ADC"=>"\u2ADD\u0338",
    "\u304C"=>"\u304B\u3099",
    "\u304E"=>"\u304D\u3099",
    "\u3050"=>"\u304F\u3099",
    "\u3052"=>"\u3051\u3099",
    "\u3054"=>"\u3053\u3099",
    "\u3056"=>"\u3055\u3099",
    "\u3058"=>"\u3057\u3099",
    "\u305A"=>"\u3059\u3099",
    "\u305C"=>"\u305B\u3099",
    "\u305E"=>"\u305D\u3099",
    "\u3060"=>"\u305F\u3099",
    "\u3062"=>"\u3061\u3099",
    "\u3065"=>"\u3064\u3099",
    "\u3067"=>"\u3066\u3099",
    "\u3069"=>"\u3068\u3099",
    "\u3070"=>"\u306F\u3099",
    "\u3071"=>"\u306F\u309A",
    "\u3073"=>"\u3072\u3099",
    "\u3074"=>"\u3072\u309A",
    "\u3076"=>"\u3075\u3099",
    "\u3077"=>"\u3075\u309A",
    "\u3079"=>"\u3078\u3099",
    "\u307A"=>"\u3078\u309A",
    "\u307C"=>"\u307B\u3099",
    "\u307D"=>"\u307B\u309A",
    "\u3094"=>"\u3046\u3099",
    "\u309E"=>"\u309D\u3099",
    "\u30AC"=>"\u30AB\u3099",
    "\u30AE"=>"\u30AD\u3099",
    "\u30B0"=>"\u30AF\u3099",
    "\u30B2"=>"\u30B1\u3099",
    "\u30B4"=>"\u30B3\u3099",
    "\u30B6"=>"\u30B5\u3099",
    "\u30B8"=>"\u30B7\u3099",
    "\u30BA"=>"\u30B9\u3099",
    "\u30BC"=>"\u30BB\u3099",
    "\u30BE"=>"\u30BD\u3099",
    "\u30C0"=>"\u30BF\u3099",
    "\u30C2"=>"\u30C1\u3099",
    "\u30C5"=>"\u30C4\u3099",
    "\u30C7"=>"\u30C6\u3099",
    "\u30C9"=>"\u30C8\u3099",
    "\u30D0"=>"\u30CF\u3099",
    "\u30D1"=>"\u30CF\u309A",
    "\u30D3"=>"\u30D2\u3099",
    "\u30D4"=>"\u30D2\u309A",
    "\u30D6"=>"\u30D5\u3099",
    "\u30D7"=>"\u30D5\u309A",
    "\u30D9"=>"\u30D8\u3099",
    "\u30DA"=>"\u30D8\u309A",
    "\u30DC"=>"\u30DB\u3099",
    "\u30DD"=>"\u30DB\u309A",
    "\u30F4"=>"\u30A6\u3099",
    "\u30F7"=>"\u30EF\u3099",
    "\u30F8"=>"\u30F0\u3099",
    "\u30F9"=>"\u30F1\u3099",
    "\u30FA"=>"\u30F2\u3099",
    "\u30FE"=>"\u30FD\u3099",
    "\uF900"=>"\u8C48",
    "\uF901"=>"\u66F4",
    "\uF902"=>"\u8ECA",
    "\uF903"=>"\u8CC8",
    "\uF904"=>"\u6ED1",
    "\uF905"=>"\u4E32",
    "\uF906"=>"\u53E5",
    "\uF907"=>"\u9F9C",
    "\uF908"=>"\u9F9C",
    "\uF909"=>"\u5951",
    "\uF90A"=>"\u91D1",
    "\uF90B"=>"\u5587",
    "\uF90C"=>"\u5948",
    "\uF90D"=>"\u61F6",
    "\uF90E"=>"\u7669",
    "\uF90F"=>"\u7F85",
    "\uF910"=>"\u863F",
    "\uF911"=>"\u87BA",
    "\uF912"=>"\u88F8",
    "\uF913"=>"\u908F",
    "\uF914"=>"\u6A02",
    "\uF915"=>"\u6D1B",
    "\uF916"=>"\u70D9",
    "\uF917"=>"\u73DE",
    "\uF918"=>"\u843D",
    "\uF919"=>"\u916A",
    "\uF91A"=>"\u99F1",
    "\uF91B"=>"\u4E82",
    "\uF91C"=>"\u5375",
    "\uF91D"=>"\u6B04",
    "\uF91E"=>"\u721B",
    "\uF91F"=>"\u862D",
    "\uF920"=>"\u9E1E",
    "\uF921"=>"\u5D50",
    "\uF922"=>"\u6FEB",
    "\uF923"=>"\u85CD",
    "\uF924"=>"\u8964",
    "\uF925"=>"\u62C9",
    "\uF926"=>"\u81D8",
    "\uF927"=>"\u881F",
    "\uF928"=>"\u5ECA",
    "\uF929"=>"\u6717",
    "\uF92A"=>"\u6D6A",
    "\uF92B"=>"\u72FC",
    "\uF92C"=>"\u90CE",
    "\uF92D"=>"\u4F86",
    "\uF92E"=>"\u51B7",
    "\uF92F"=>"\u52DE",
    "\uF930"=>"\u64C4",
    "\uF931"=>"\u6AD3",
    "\uF932"=>"\u7210",
    "\uF933"=>"\u76E7",
    "\uF934"=>"\u8001",
    "\uF935"=>"\u8606",
    "\uF936"=>"\u865C",
    "\uF937"=>"\u8DEF",
    "\uF938"=>"\u9732",
    "\uF939"=>"\u9B6F",
    "\uF93A"=>"\u9DFA",
    "\uF93B"=>"\u788C",
    "\uF93C"=>"\u797F",
    "\uF93D"=>"\u7DA0",
    "\uF93E"=>"\u83C9",
    "\uF93F"=>"\u9304",
    "\uF940"=>"\u9E7F",
    "\uF941"=>"\u8AD6",
    "\uF942"=>"\u58DF",
    "\uF943"=>"\u5F04",
    "\uF944"=>"\u7C60",
    "\uF945"=>"\u807E",
    "\uF946"=>"\u7262",
    "\uF947"=>"\u78CA",
    "\uF948"=>"\u8CC2",
    "\uF949"=>"\u96F7",
    "\uF94A"=>"\u58D8",
    "\uF94B"=>"\u5C62",
    "\uF94C"=>"\u6A13",
    "\uF94D"=>"\u6DDA",
    "\uF94E"=>"\u6F0F",
    "\uF94F"=>"\u7D2F",
    "\uF950"=>"\u7E37",
    "\uF951"=>"\u964B",
    "\uF952"=>"\u52D2",
    "\uF953"=>"\u808B",
    "\uF954"=>"\u51DC",
    "\uF955"=>"\u51CC",
    "\uF956"=>"\u7A1C",
    "\uF957"=>"\u7DBE",
    "\uF958"=>"\u83F1",
    "\uF959"=>"\u9675",
    "\uF95A"=>"\u8B80",
    "\uF95B"=>"\u62CF",
    "\uF95C"=>"\u6A02",
    "\uF95D"=>"\u8AFE",
    "\uF95E"=>"\u4E39",
    "\uF95F"=>"\u5BE7",
    "\uF960"=>"\u6012",
    "\uF961"=>"\u7387",
    "\uF962"=>"\u7570",
    "\uF963"=>"\u5317",
    "\uF964"=>"\u78FB",
    "\uF965"=>"\u4FBF",
    "\uF966"=>"\u5FA9",
    "\uF967"=>"\u4E0D",
    "\uF968"=>"\u6CCC",
    "\uF969"=>"\u6578",
    "\uF96A"=>"\u7D22",
    "\uF96B"=>"\u53C3",
    "\uF96C"=>"\u585E",
    "\uF96D"=>"\u7701",
    "\uF96E"=>"\u8449",
    "\uF96F"=>"\u8AAA",
    "\uF970"=>"\u6BBA",
    "\uF971"=>"\u8FB0",
    "\uF972"=>"\u6C88",
    "\uF973"=>"\u62FE",
    "\uF974"=>"\u82E5",
    "\uF975"=>"\u63A0",
    "\uF976"=>"\u7565",
    "\uF977"=>"\u4EAE",
    "\uF978"=>"\u5169",
    "\uF979"=>"\u51C9",
    "\uF97A"=>"\u6881",
    "\uF97B"=>"\u7CE7",
    "\uF97C"=>"\u826F",
    "\uF97D"=>"\u8AD2",
    "\uF97E"=>"\u91CF",
    "\uF97F"=>"\u52F5",
    "\uF980"=>"\u5442",
    "\uF981"=>"\u5973",
    "\uF982"=>"\u5EEC",
    "\uF983"=>"\u65C5",
    "\uF984"=>"\u6FFE",
    "\uF985"=>"\u792A",
    "\uF986"=>"\u95AD",
    "\uF987"=>"\u9A6A",
    "\uF988"=>"\u9E97",
    "\uF989"=>"\u9ECE",
    "\uF98A"=>"\u529B",
    "\uF98B"=>"\u66C6",
    "\uF98C"=>"\u6B77",
    "\uF98D"=>"\u8F62",
    "\uF98E"=>"\u5E74",
    "\uF98F"=>"\u6190",
    "\uF990"=>"\u6200",
    "\uF991"=>"\u649A",
    "\uF992"=>"\u6F23",
    "\uF993"=>"\u7149",
    "\uF994"=>"\u7489",
    "\uF995"=>"\u79CA",
    "\uF996"=>"\u7DF4",
    "\uF997"=>"\u806F",
    "\uF998"=>"\u8F26",
    "\uF999"=>"\u84EE",
    "\uF99A"=>"\u9023",
    "\uF99B"=>"\u934A",
    "\uF99C"=>"\u5217",
    "\uF99D"=>"\u52A3",
    "\uF99E"=>"\u54BD",
    "\uF99F"=>"\u70C8",
    "\uF9A0"=>"\u88C2",
    "\uF9A1"=>"\u8AAA",
    "\uF9A2"=>"\u5EC9",
    "\uF9A3"=>"\u5FF5",
    "\uF9A4"=>"\u637B",
    "\uF9A5"=>"\u6BAE",
    "\uF9A6"=>"\u7C3E",
    "\uF9A7"=>"\u7375",
    "\uF9A8"=>"\u4EE4",
    "\uF9A9"=>"\u56F9",
    "\uF9AA"=>"\u5BE7",
    "\uF9AB"=>"\u5DBA",
    "\uF9AC"=>"\u601C",
    "\uF9AD"=>"\u73B2",
    "\uF9AE"=>"\u7469",
    "\uF9AF"=>"\u7F9A",
    "\uF9B0"=>"\u8046",
    "\uF9B1"=>"\u9234",
    "\uF9B2"=>"\u96F6",
    "\uF9B3"=>"\u9748",
    "\uF9B4"=>"\u9818",
    "\uF9B5"=>"\u4F8B",
    "\uF9B6"=>"\u79AE",
    "\uF9B7"=>"\u91B4",
    "\uF9B8"=>"\u96B8",
    "\uF9B9"=>"\u60E1",
    "\uF9BA"=>"\u4E86",
    "\uF9BB"=>"\u50DA",
    "\uF9BC"=>"\u5BEE",
    "\uF9BD"=>"\u5C3F",
    "\uF9BE"=>"\u6599",
    "\uF9BF"=>"\u6A02",
    "\uF9C0"=>"\u71CE",
    "\uF9C1"=>"\u7642",
    "\uF9C2"=>"\u84FC",
    "\uF9C3"=>"\u907C",
    "\uF9C4"=>"\u9F8D",
    "\uF9C5"=>"\u6688",
    "\uF9C6"=>"\u962E",
    "\uF9C7"=>"\u5289",
    "\uF9C8"=>"\u677B",
    "\uF9C9"=>"\u67F3",
    "\uF9CA"=>"\u6D41",
    "\uF9CB"=>"\u6E9C",
    "\uF9CC"=>"\u7409",
    "\uF9CD"=>"\u7559",
    "\uF9CE"=>"\u786B",
    "\uF9CF"=>"\u7D10",
    "\uF9D0"=>"\u985E",
    "\uF9D1"=>"\u516D",
    "\uF9D2"=>"\u622E",
    "\uF9D3"=>"\u9678",
    "\uF9D4"=>"\u502B",
    "\uF9D5"=>"\u5D19",
    "\uF9D6"=>"\u6DEA",
    "\uF9D7"=>"\u8F2A",
    "\uF9D8"=>"\u5F8B",
    "\uF9D9"=>"\u6144",
    "\uF9DA"=>"\u6817",
    "\uF9DB"=>"\u7387",
    "\uF9DC"=>"\u9686",
    "\uF9DD"=>"\u5229",
    "\uF9DE"=>"\u540F",
    "\uF9DF"=>"\u5C65",
    "\uF9E0"=>"\u6613",
    "\uF9E1"=>"\u674E",
    "\uF9E2"=>"\u68A8",
    "\uF9E3"=>"\u6CE5",
    "\uF9E4"=>"\u7406",
    "\uF9E5"=>"\u75E2",
    "\uF9E6"=>"\u7F79",
    "\uF9E7"=>"\u88CF",
    "\uF9E8"=>"\u88E1",
    "\uF9E9"=>"\u91CC",
    "\uF9EA"=>"\u96E2",
    "\uF9EB"=>"\u533F",
    "\uF9EC"=>"\u6EBA",
    "\uF9ED"=>"\u541D",
    "\uF9EE"=>"\u71D0",
    "\uF9EF"=>"\u7498",
    "\uF9F0"=>"\u85FA",
    "\uF9F1"=>"\u96A3",
    "\uF9F2"=>"\u9C57",
    "\uF9F3"=>"\u9E9F",
    "\uF9F4"=>"\u6797",
    "\uF9F5"=>"\u6DCB",
    "\uF9F6"=>"\u81E8",
    "\uF9F7"=>"\u7ACB",
    "\uF9F8"=>"\u7B20",
    "\uF9F9"=>"\u7C92",
    "\uF9FA"=>"\u72C0",
    "\uF9FB"=>"\u7099",
    "\uF9FC"=>"\u8B58",
    "\uF9FD"=>"\u4EC0",
    "\uF9FE"=>"\u8336",
    "\uF9FF"=>"\u523A",
    "\uFA00"=>"\u5207",
    "\uFA01"=>"\u5EA6",
    "\uFA02"=>"\u62D3",
    "\uFA03"=>"\u7CD6",
    "\uFA04"=>"\u5B85",
    "\uFA05"=>"\u6D1E",
    "\uFA06"=>"\u66B4",
    "\uFA07"=>"\u8F3B",
    "\uFA08"=>"\u884C",
    "\uFA09"=>"\u964D",
    "\uFA0A"=>"\u898B",
    "\uFA0B"=>"\u5ED3",
    "\uFA0C"=>"\u5140",
    "\uFA0D"=>"\u55C0",
    "\uFA10"=>"\u585A",
    "\uFA12"=>"\u6674",
    "\uFA15"=>"\u51DE",
    "\uFA16"=>"\u732A",
    "\uFA17"=>"\u76CA",
    "\uFA18"=>"\u793C",
    "\uFA19"=>"\u795E",
    "\uFA1A"=>"\u7965",
    "\uFA1B"=>"\u798F",
    "\uFA1C"=>"\u9756",
    "\uFA1D"=>"\u7CBE",
    "\uFA1E"=>"\u7FBD",
    "\uFA20"=>"\u8612",
    "\uFA22"=>"\u8AF8",
    "\uFA25"=>"\u9038",
    "\uFA26"=>"\u90FD",
    "\uFA2A"=>"\u98EF",
    "\uFA2B"=>"\u98FC",
    "\uFA2C"=>"\u9928",
    "\uFA2D"=>"\u9DB4",
    "\uFA2E"=>"\u90DE",
    "\uFA2F"=>"\u96B7",
    "\uFA30"=>"\u4FAE",
    "\uFA31"=>"\u50E7",
    "\uFA32"=>"\u514D",
    "\uFA33"=>"\u52C9",
    "\uFA34"=>"\u52E4",
    "\uFA35"=>"\u5351",
    "\uFA36"=>"\u559D",
    "\uFA37"=>"\u5606",
    "\uFA38"=>"\u5668",
    "\uFA39"=>"\u5840",
    "\uFA3A"=>"\u58A8",
    "\uFA3B"=>"\u5C64",
    "\uFA3C"=>"\u5C6E",
    "\uFA3D"=>"\u6094",
    "\uFA3E"=>"\u6168",
    "\uFA3F"=>"\u618E",
    "\uFA40"=>"\u61F2",
    "\uFA41"=>"\u654F",
    "\uFA42"=>"\u65E2",
    "\uFA43"=>"\u6691",
    "\uFA44"=>"\u6885",
    "\uFA45"=>"\u6D77",
    "\uFA46"=>"\u6E1A",
    "\uFA47"=>"\u6F22",
    "\uFA48"=>"\u716E",
    "\uFA49"=>"\u722B",
    "\uFA4A"=>"\u7422",
    "\uFA4B"=>"\u7891",
    "\uFA4C"=>"\u793E",
    "\uFA4D"=>"\u7949",
    "\uFA4E"=>"\u7948",
    "\uFA4F"=>"\u7950",
    "\uFA50"=>"\u7956",
    "\uFA51"=>"\u795D",
    "\uFA52"=>"\u798D",
    "\uFA53"=>"\u798E",
    "\uFA54"=>"\u7A40",
    "\uFA55"=>"\u7A81",
    "\uFA56"=>"\u7BC0",
    "\uFA57"=>"\u7DF4",
    "\uFA58"=>"\u7E09",
    "\uFA59"=>"\u7E41",
    "\uFA5A"=>"\u7F72",
    "\uFA5B"=>"\u8005",
    "\uFA5C"=>"\u81ED",
    "\uFA5D"=>"\u8279",
    "\uFA5E"=>"\u8279",
    "\uFA5F"=>"\u8457",
    "\uFA60"=>"\u8910",
    "\uFA61"=>"\u8996",
    "\uFA62"=>"\u8B01",
    "\uFA63"=>"\u8B39",
    "\uFA64"=>"\u8CD3",
    "\uFA65"=>"\u8D08",
    "\uFA66"=>"\u8FB6",
    "\uFA67"=>"\u9038",
    "\uFA68"=>"\u96E3",
    "\uFA69"=>"\u97FF",
    "\uFA6A"=>"\u983B",
    "\uFA6B"=>"\u6075",
    "\uFA6C"=>"\u{242EE}",
    "\uFA6D"=>"\u8218",
    "\uFA70"=>"\u4E26",
    "\uFA71"=>"\u51B5",
    "\uFA72"=>"\u5168",
    "\uFA73"=>"\u4F80",
    "\uFA74"=>"\u5145",
    "\uFA75"=>"\u5180",
    "\uFA76"=>"\u52C7",
    "\uFA77"=>"\u52FA",
    "\uFA78"=>"\u559D",
    "\uFA79"=>"\u5555",
    "\uFA7A"=>"\u5599",
    "\uFA7B"=>"\u55E2",
    "\uFA7C"=>"\u585A",
    "\uFA7D"=>"\u58B3",
    "\uFA7E"=>"\u5944",
    "\uFA7F"=>"\u5954",
    "\uFA80"=>"\u5A62",
    "\uFA81"=>"\u5B28",
    "\uFA82"=>"\u5ED2",
    "\uFA83"=>"\u5ED9",
    "\uFA84"=>"\u5F69",
    "\uFA85"=>"\u5FAD",
    "\uFA86"=>"\u60D8",
    "\uFA87"=>"\u614E",
    "\uFA88"=>"\u6108",
    "\uFA89"=>"\u618E",
    "\uFA8A"=>"\u6160",
    "\uFA8B"=>"\u61F2",
    "\uFA8C"=>"\u6234",
    "\uFA8D"=>"\u63C4",
    "\uFA8E"=>"\u641C",
    "\uFA8F"=>"\u6452",
    "\uFA90"=>"\u6556",
    "\uFA91"=>"\u6674",
    "\uFA92"=>"\u6717",
    "\uFA93"=>"\u671B",
    "\uFA94"=>"\u6756",
    "\uFA95"=>"\u6B79",
    "\uFA96"=>"\u6BBA",
    "\uFA97"=>"\u6D41",
    "\uFA98"=>"\u6EDB",
    "\uFA99"=>"\u6ECB",
    "\uFA9A"=>"\u6F22",
    "\uFA9B"=>"\u701E",
    "\uFA9C"=>"\u716E",
    "\uFA9D"=>"\u77A7",
    "\uFA9E"=>"\u7235",
    "\uFA9F"=>"\u72AF",
    "\uFAA0"=>"\u732A",
    "\uFAA1"=>"\u7471",
    "\uFAA2"=>"\u7506",
    "\uFAA3"=>"\u753B",
    "\uFAA4"=>"\u761D",
    "\uFAA5"=>"\u761F",
    "\uFAA6"=>"\u76CA",
    "\uFAA7"=>"\u76DB",
    "\uFAA8"=>"\u76F4",
    "\uFAA9"=>"\u774A",
    "\uFAAA"=>"\u7740",
    "\uFAAB"=>"\u78CC",
    "\uFAAC"=>"\u7AB1",
    "\uFAAD"=>"\u7BC0",
    "\uFAAE"=>"\u7C7B",
    "\uFAAF"=>"\u7D5B",
    "\uFAB0"=>"\u7DF4",
    "\uFAB1"=>"\u7F3E",
    "\uFAB2"=>"\u8005",
    "\uFAB3"=>"\u8352",
    "\uFAB4"=>"\u83EF",
    "\uFAB5"=>"\u8779",
    "\uFAB6"=>"\u8941",
    "\uFAB7"=>"\u8986",
    "\uFAB8"=>"\u8996",
    "\uFAB9"=>"\u8ABF",
    "\uFABA"=>"\u8AF8",
    "\uFABB"=>"\u8ACB",
    "\uFABC"=>"\u8B01",
    "\uFABD"=>"\u8AFE",
    "\uFABE"=>"\u8AED",
    "\uFABF"=>"\u8B39",
    "\uFAC0"=>"\u8B8A",
    "\uFAC1"=>"\u8D08",
    "\uFAC2"=>"\u8F38",
    "\uFAC3"=>"\u9072",
    "\uFAC4"=>"\u9199",
    "\uFAC5"=>"\u9276",
    "\uFAC6"=>"\u967C",
    "\uFAC7"=>"\u96E3",
    "\uFAC8"=>"\u9756",
    "\uFAC9"=>"\u97DB",
    "\uFACA"=>"\u97FF",
    "\uFACB"=>"\u980B",
    "\uFACC"=>"\u983B",
    "\uFACD"=>"\u9B12",
    "\uFACE"=>"\u9F9C",
    "\uFACF"=>"\u{2284A}",
    "\uFAD0"=>"\u{22844}",
    "\uFAD1"=>"\u{233D5}",
    "\uFAD2"=>"\u3B9D",
    "\uFAD3"=>"\u4018",
    "\uFAD4"=>"\u4039",
    "\uFAD5"=>"\u{25249}",
    "\uFAD6"=>"\u{25CD0}",
    "\uFAD7"=>"\u{27ED3}",
    "\uFAD8"=>"\u9F43",
    "\uFAD9"=>"\u9F8E",
    "\uFB1D"=>"\u05D9\u05B4",
    "\uFB1F"=>"\u05F2\u05B7",
    "\uFB2A"=>"\u05E9\u05C1",
    "\uFB2B"=>"\u05E9\u05C2",
    "\uFB2C"=>"\u05E9\u05BC\u05C1",
    "\uFB2D"=>"\u05E9\u05BC\u05C2",
    "\uFB2E"=>"\u05D0\u05B7",
    "\uFB2F"=>"\u05D0\u05B8",
    "\uFB30"=>"\u05D0\u05BC",
    "\uFB31"=>"\u05D1\u05BC",
    "\uFB32"=>"\u05D2\u05BC",
    "\uFB33"=>"\u05D3\u05BC",
    "\uFB34"=>"\u05D4\u05BC",
    "\uFB35"=>"\u05D5\u05BC",
    "\uFB36"=>"\u05D6\u05BC",
    "\uFB38"=>"\u05D8\u05BC",
    "\uFB39"=>"\u05D9\u05BC",
    "\uFB3A"=>"\u05DA\u05BC",
    "\uFB3B"=>"\u05DB\u05BC",
    "\uFB3C"=>"\u05DC\u05BC",
    "\uFB3E"=>"\u05DE\u05BC",
    "\uFB40"=>"\u05E0\u05BC",
    "\uFB41"=>"\u05E1\u05BC",
    "\uFB43"=>"\u05E3\u05BC",
    "\uFB44"=>"\u05E4\u05BC",
    "\uFB46"=>"\u05E6\u05BC",
    "\uFB47"=>"\u05E7\u05BC",
    "\uFB48"=>"\u05E8\u05BC",
    "\uFB49"=>"\u05E9\u05BC",
    "\uFB4A"=>"\u05EA\u05BC",
    "\uFB4B"=>"\u05D5\u05B9",
    "\uFB4C"=>"\u05D1\u05BF",
    "\uFB4D"=>"\u05DB\u05BF",
    "\uFB4E"=>"\u05E4\u05BF",
    "\u{1109A}"=>"\u{11099}\u{110BA}",
    "\u{1109C}"=>"\u{1109B}\u{110BA}",
    "\u{110AB}"=>"\u{110A5}\u{110BA}",
    "\u{1112E}"=>"\u{11131}\u{11127}",
    "\u{1112F}"=>"\u{11132}\u{11127}",
    "\u{1134B}"=>"\u{11347}\u{1133E}",
    "\u{1134C}"=>"\u{11347}\u{11357}",
    "\u{114BB}"=>"\u{114B9}\u{114BA}",
    "\u{114BC}"=>"\u{114B9}\u{114B0}",
    "\u{114BE}"=>"\u{114B9}\u{114BD}",
    "\u{115BA}"=>"\u{115B8}\u{115AF}",
    "\u{115BB}"=>"\u{115B9}\u{115AF}",
    "\u{1D15E}"=>"\u{1D157}\u{1D165}",
    "\u{1D15F}"=>"\u{1D158}\u{1D165}",
    "\u{1D160}"=>"\u{1D158}\u{1D165}\u{1D16E}",
    "\u{1D161}"=>"\u{1D158}\u{1D165}\u{1D16F}",
    "\u{1D162}"=>"\u{1D158}\u{1D165}\u{1D170}",
    "\u{1D163}"=>"\u{1D158}\u{1D165}\u{1D171}",
    "\u{1D164}"=>"\u{1D158}\u{1D165}\u{1D172}",
    "\u{1D1BB}"=>"\u{1D1B9}\u{1D165}",
    "\u{1D1BC}"=>"\u{1D1BA}\u{1D165}",
    "\u{1D1BD}"=>"\u{1D1B9}\u{1D165}\u{1D16E}",
    "\u{1D1BE}"=>"\u{1D1BA}\u{1D165}\u{1D16E}",
    "\u{1D1BF}"=>"\u{1D1B9}\u{1D165}\u{1D16F}",
    "\u{1D1C0}"=>"\u{1D1BA}\u{1D165}\u{1D16F}",
    "\u{2F800}"=>"\u4E3D",
    "\u{2F801}"=>"\u4E38",
    "\u{2F802}"=>"\u4E41",
    "\u{2F803}"=>"\u{20122}",
    "\u{2F804}"=>"\u4F60",
    "\u{2F805}"=>"\u4FAE",
    "\u{2F806}"=>"\u4FBB",
    "\u{2F807}"=>"\u5002",
    "\u{2F808}"=>"\u507A",
    "\u{2F809}"=>"\u5099",
    "\u{2F80A}"=>"\u50E7",
    "\u{2F80B}"=>"\u50CF",
    "\u{2F80C}"=>"\u349E",
    "\u{2F80D}"=>"\u{2063A}",
    "\u{2F80E}"=>"\u514D",
    "\u{2F80F}"=>"\u5154",
    "\u{2F810}"=>"\u5164",
    "\u{2F811}"=>"\u5177",
    "\u{2F812}"=>"\u{2051C}",
    "\u{2F813}"=>"\u34B9",
    "\u{2F814}"=>"\u5167",
    "\u{2F815}"=>"\u518D",
    "\u{2F816}"=>"\u{2054B}",
    "\u{2F817}"=>"\u5197",
    "\u{2F818}"=>"\u51A4",
    "\u{2F819}"=>"\u4ECC",
    "\u{2F81A}"=>"\u51AC",
    "\u{2F81B}"=>"\u51B5",
    "\u{2F81C}"=>"\u{291DF}",
    "\u{2F81D}"=>"\u51F5",
    "\u{2F81E}"=>"\u5203",
    "\u{2F81F}"=>"\u34DF",
    "\u{2F820}"=>"\u523B",
    "\u{2F821}"=>"\u5246",
    "\u{2F822}"=>"\u5272",
    "\u{2F823}"=>"\u5277",
    "\u{2F824}"=>"\u3515",
    "\u{2F825}"=>"\u52C7",
    "\u{2F826}"=>"\u52C9",
    "\u{2F827}"=>"\u52E4",
    "\u{2F828}"=>"\u52FA",
    "\u{2F829}"=>"\u5305",
    "\u{2F82A}"=>"\u5306",
    "\u{2F82B}"=>"\u5317",
    "\u{2F82C}"=>"\u5349",
    "\u{2F82D}"=>"\u5351",
    "\u{2F82E}"=>"\u535A",
    "\u{2F82F}"=>"\u5373",
    "\u{2F830}"=>"\u537D",
    "\u{2F831}"=>"\u537F",
    "\u{2F832}"=>"\u537F",
    "\u{2F833}"=>"\u537F",
    "\u{2F834}"=>"\u{20A2C}",
    "\u{2F835}"=>"\u7070",
    "\u{2F836}"=>"\u53CA",
    "\u{2F837}"=>"\u53DF",
    "\u{2F838}"=>"\u{20B63}",
    "\u{2F839}"=>"\u53EB",
    "\u{2F83A}"=>"\u53F1",
    "\u{2F83B}"=>"\u5406",
    "\u{2F83C}"=>"\u549E",
    "\u{2F83D}"=>"\u5438",
    "\u{2F83E}"=>"\u5448",
    "\u{2F83F}"=>"\u5468",
    "\u{2F840}"=>"\u54A2",
    "\u{2F841}"=>"\u54F6",
    "\u{2F842}"=>"\u5510",
    "\u{2F843}"=>"\u5553",
    "\u{2F844}"=>"\u5563",
    "\u{2F845}"=>"\u5584",
    "\u{2F846}"=>"\u5584",
    "\u{2F847}"=>"\u5599",
    "\u{2F848}"=>"\u55AB",
    "\u{2F849}"=>"\u55B3",
    "\u{2F84A}"=>"\u55C2",
    "\u{2F84B}"=>"\u5716",
    "\u{2F84C}"=>"\u5606",
    "\u{2F84D}"=>"\u5717",
    "\u{2F84E}"=>"\u5651",
    "\u{2F84F}"=>"\u5674",
    "\u{2F850}"=>"\u5207",
    "\u{2F851}"=>"\u58EE",
    "\u{2F852}"=>"\u57CE",
    "\u{2F853}"=>"\u57F4",
    "\u{2F854}"=>"\u580D",
    "\u{2F855}"=>"\u578B",
    "\u{2F856}"=>"\u5832",
    "\u{2F857}"=>"\u5831",
    "\u{2F858}"=>"\u58AC",
    "\u{2F859}"=>"\u{214E4}",
    "\u{2F85A}"=>"\u58F2",
    "\u{2F85B}"=>"\u58F7",
    "\u{2F85C}"=>"\u5906",
    "\u{2F85D}"=>"\u591A",
    "\u{2F85E}"=>"\u5922",
    "\u{2F85F}"=>"\u5962",
    "\u{2F860}"=>"\u{216A8}",
    "\u{2F861}"=>"\u{216EA}",
    "\u{2F862}"=>"\u59EC",
    "\u{2F863}"=>"\u5A1B",
    "\u{2F864}"=>"\u5A27",
    "\u{2F865}"=>"\u59D8",
    "\u{2F866}"=>"\u5A66",
    "\u{2F867}"=>"\u36EE",
    "\u{2F868}"=>"\u36FC",
    "\u{2F869}"=>"\u5B08",
    "\u{2F86A}"=>"\u5B3E",
    "\u{2F86B}"=>"\u5B3E",
    "\u{2F86C}"=>"\u{219C8}",
    "\u{2F86D}"=>"\u5BC3",
    "\u{2F86E}"=>"\u5BD8",
    "\u{2F86F}"=>"\u5BE7",
    "\u{2F870}"=>"\u5BF3",
    "\u{2F871}"=>"\u{21B18}",
    "\u{2F872}"=>"\u5BFF",
    "\u{2F873}"=>"\u5C06",
    "\u{2F874}"=>"\u5F53",
    "\u{2F875}"=>"\u5C22",
    "\u{2F876}"=>"\u3781",
    "\u{2F877}"=>"\u5C60",
    "\u{2F878}"=>"\u5C6E",
    "\u{2F879}"=>"\u5CC0",
    "\u{2F87A}"=>"\u5C8D",
    "\u{2F87B}"=>"\u{21DE4}",
    "\u{2F87C}"=>"\u5D43",
    "\u{2F87D}"=>"\u{21DE6}",
    "\u{2F87E}"=>"\u5D6E",
    "\u{2F87F}"=>"\u5D6B",
    "\u{2F880}"=>"\u5D7C",
    "\u{2F881}"=>"\u5DE1",
    "\u{2F882}"=>"\u5DE2",
    "\u{2F883}"=>"\u382F",
    "\u{2F884}"=>"\u5DFD",
    "\u{2F885}"=>"\u5E28",
    "\u{2F886}"=>"\u5E3D",
    "\u{2F887}"=>"\u5E69",
    "\u{2F888}"=>"\u3862",
    "\u{2F889}"=>"\u{22183}",
    "\u{2F88A}"=>"\u387C",
    "\u{2F88B}"=>"\u5EB0",
    "\u{2F88C}"=>"\u5EB3",
    "\u{2F88D}"=>"\u5EB6",
    "\u{2F88E}"=>"\u5ECA",
    "\u{2F88F}"=>"\u{2A392}",
    "\u{2F890}"=>"\u5EFE",
    "\u{2F891}"=>"\u{22331}",
    "\u{2F892}"=>"\u{22331}",
    "\u{2F893}"=>"\u8201",
    "\u{2F894}"=>"\u5F22",
    "\u{2F895}"=>"\u5F22",
    "\u{2F896}"=>"\u38C7",
    "\u{2F897}"=>"\u{232B8}",
    "\u{2F898}"=>"\u{261DA}",
    "\u{2F899}"=>"\u5F62",
    "\u{2F89A}"=>"\u5F6B",
    "\u{2F89B}"=>"\u38E3",
    "\u{2F89C}"=>"\u5F9A",
    "\u{2F89D}"=>"\u5FCD",
    "\u{2F89E}"=>"\u5FD7",
    "\u{2F89F}"=>"\u5FF9",
    "\u{2F8A0}"=>"\u6081",
    "\u{2F8A1}"=>"\u393A",
    "\u{2F8A2}"=>"\u391C",
    "\u{2F8A3}"=>"\u6094",
    "\u{2F8A4}"=>"\u{226D4}",
    "\u{2F8A5}"=>"\u60C7",
    "\u{2F8A6}"=>"\u6148",
    "\u{2F8A7}"=>"\u614C",
    "\u{2F8A8}"=>"\u614E",
    "\u{2F8A9}"=>"\u614C",
    "\u{2F8AA}"=>"\u617A",
    "\u{2F8AB}"=>"\u618E",
    "\u{2F8AC}"=>"\u61B2",
    "\u{2F8AD}"=>"\u61A4",
    "\u{2F8AE}"=>"\u61AF",
    "\u{2F8AF}"=>"\u61DE",
    "\u{2F8B0}"=>"\u61F2",
    "\u{2F8B1}"=>"\u61F6",
    "\u{2F8B2}"=>"\u6210",
    "\u{2F8B3}"=>"\u621B",
    "\u{2F8B4}"=>"\u625D",
    "\u{2F8B5}"=>"\u62B1",
    "\u{2F8B6}"=>"\u62D4",
    "\u{2F8B7}"=>"\u6350",
    "\u{2F8B8}"=>"\u{22B0C}",
    "\u{2F8B9}"=>"\u633D",
    "\u{2F8BA}"=>"\u62FC",
    "\u{2F8BB}"=>"\u6368",
    "\u{2F8BC}"=>"\u6383",
    "\u{2F8BD}"=>"\u63E4",
    "\u{2F8BE}"=>"\u{22BF1}",
    "\u{2F8BF}"=>"\u6422",
    "\u{2F8C0}"=>"\u63C5",
    "\u{2F8C1}"=>"\u63A9",
    "\u{2F8C2}"=>"\u3A2E",
    "\u{2F8C3}"=>"\u6469",
    "\u{2F8C4}"=>"\u647E",
    "\u{2F8C5}"=>"\u649D",
    "\u{2F8C6}"=>"\u6477",
    "\u{2F8C7}"=>"\u3A6C",
    "\u{2F8C8}"=>"\u654F",
    "\u{2F8C9}"=>"\u656C",
    "\u{2F8CA}"=>"\u{2300A}",
    "\u{2F8CB}"=>"\u65E3",
    "\u{2F8CC}"=>"\u66F8",
    "\u{2F8CD}"=>"\u6649",
    "\u{2F8CE}"=>"\u3B19",
    "\u{2F8CF}"=>"\u6691",
    "\u{2F8D0}"=>"\u3B08",
    "\u{2F8D1}"=>"\u3AE4",
    "\u{2F8D2}"=>"\u5192",
    "\u{2F8D3}"=>"\u5195",
    "\u{2F8D4}"=>"\u6700",
    "\u{2F8D5}"=>"\u669C",
    "\u{2F8D6}"=>"\u80AD",
    "\u{2F8D7}"=>"\u43D9",
    "\u{2F8D8}"=>"\u6717",
    "\u{2F8D9}"=>"\u671B",
    "\u{2F8DA}"=>"\u6721",
    "\u{2F8DB}"=>"\u675E",
    "\u{2F8DC}"=>"\u6753",
    "\u{2F8DD}"=>"\u{233C3}",
    "\u{2F8DE}"=>"\u3B49",
    "\u{2F8DF}"=>"\u67FA",
    "\u{2F8E0}"=>"\u6785",
    "\u{2F8E1}"=>"\u6852",
    "\u{2F8E2}"=>"\u6885",
    "\u{2F8E3}"=>"\u{2346D}",
    "\u{2F8E4}"=>"\u688E",
    "\u{2F8E5}"=>"\u681F",
    "\u{2F8E6}"=>"\u6914",
    "\u{2F8E7}"=>"\u3B9D",
    "\u{2F8E8}"=>"\u6942",
    "\u{2F8E9}"=>"\u69A3",
    "\u{2F8EA}"=>"\u69EA",
    "\u{2F8EB}"=>"\u6AA8",
    "\u{2F8EC}"=>"\u{236A3}",
    "\u{2F8ED}"=>"\u6ADB",
    "\u{2F8EE}"=>"\u3C18",
    "\u{2F8EF}"=>"\u6B21",
    "\u{2F8F0}"=>"\u{238A7}",
    "\u{2F8F1}"=>"\u6B54",
    "\u{2F8F2}"=>"\u3C4E",
    "\u{2F8F3}"=>"\u6B72",
    "\u{2F8F4}"=>"\u6B9F",
    "\u{2F8F5}"=>"\u6BBA",
    "\u{2F8F6}"=>"\u6BBB",
    "\u{2F8F7}"=>"\u{23A8D}",
    "\u{2F8F8}"=>"\u{21D0B}",
    "\u{2F8F9}"=>"\u{23AFA}",
    "\u{2F8FA}"=>"\u6C4E",
    "\u{2F8FB}"=>"\u{23CBC}",
    "\u{2F8FC}"=>"\u6CBF",
    "\u{2F8FD}"=>"\u6CCD",
    "\u{2F8FE}"=>"\u6C67",
    "\u{2F8FF}"=>"\u6D16",
    "\u{2F900}"=>"\u6D3E",
    "\u{2F901}"=>"\u6D77",
    "\u{2F902}"=>"\u6D41",
    "\u{2F903}"=>"\u6D69",
    "\u{2F904}"=>"\u6D78",
    "\u{2F905}"=>"\u6D85",
    "\u{2F906}"=>"\u{23D1E}",
    "\u{2F907}"=>"\u6D34",
    "\u{2F908}"=>"\u6E2F",
    "\u{2F909}"=>"\u6E6E",
    "\u{2F90A}"=>"\u3D33",
    "\u{2F90B}"=>"\u6ECB",
    "\u{2F90C}"=>"\u6EC7",
    "\u{2F90D}"=>"\u{23ED1}",
    "\u{2F90E}"=>"\u6DF9",
    "\u{2F90F}"=>"\u6F6E",
    "\u{2F910}"=>"\u{23F5E}",
    "\u{2F911}"=>"\u{23F8E}",
    "\u{2F912}"=>"\u6FC6",
    "\u{2F913}"=>"\u7039",
    "\u{2F914}"=>"\u701E",
    "\u{2F915}"=>"\u701B",
    "\u{2F916}"=>"\u3D96",
    "\u{2F917}"=>"\u704A",
    "\u{2F918}"=>"\u707D",
    "\u{2F919}"=>"\u7077",
    "\u{2F91A}"=>"\u70AD",
    "\u{2F91B}"=>"\u{20525}",
    "\u{2F91C}"=>"\u7145",
    "\u{2F91D}"=>"\u{24263}",
    "\u{2F91E}"=>"\u719C",
    "\u{2F91F}"=>"\u{243AB}",
    "\u{2F920}"=>"\u7228",
    "\u{2F921}"=>"\u7235",
    "\u{2F922}"=>"\u7250",
    "\u{2F923}"=>"\u{24608}",
    "\u{2F924}"=>"\u7280",
    "\u{2F925}"=>"\u7295",
    "\u{2F926}"=>"\u{24735}",
    "\u{2F927}"=>"\u{24814}",
    "\u{2F928}"=>"\u737A",
    "\u{2F929}"=>"\u738B",
    "\u{2F92A}"=>"\u3EAC",
    "\u{2F92B}"=>"\u73A5",
    "\u{2F92C}"=>"\u3EB8",
    "\u{2F92D}"=>"\u3EB8",
    "\u{2F92E}"=>"\u7447",
    "\u{2F92F}"=>"\u745C",
    "\u{2F930}"=>"\u7471",
    "\u{2F931}"=>"\u7485",
    "\u{2F932}"=>"\u74CA",
    "\u{2F933}"=>"\u3F1B",
    "\u{2F934}"=>"\u7524",
    "\u{2F935}"=>"\u{24C36}",
    "\u{2F936}"=>"\u753E",
    "\u{2F937}"=>"\u{24C92}",
    "\u{2F938}"=>"\u7570",
    "\u{2F939}"=>"\u{2219F}",
    "\u{2F93A}"=>"\u7610",
    "\u{2F93B}"=>"\u{24FA1}",
    "\u{2F93C}"=>"\u{24FB8}",
    "\u{2F93D}"=>"\u{25044}",
    "\u{2F93E}"=>"\u3FFC",
    "\u{2F93F}"=>"\u4008",
    "\u{2F940}"=>"\u76F4",
    "\u{2F941}"=>"\u{250F3}",
    "\u{2F942}"=>"\u{250F2}",
    "\u{2F943}"=>"\u{25119}",
    "\u{2F944}"=>"\u{25133}",
    "\u{2F945}"=>"\u771E",
    "\u{2F946}"=>"\u771F",
    "\u{2F947}"=>"\u771F",
    "\u{2F948}"=>"\u774A",
    "\u{2F949}"=>"\u4039",
    "\u{2F94A}"=>"\u778B",
    "\u{2F94B}"=>"\u4046",
    "\u{2F94C}"=>"\u4096",
    "\u{2F94D}"=>"\u{2541D}",
    "\u{2F94E}"=>"\u784E",
    "\u{2F94F}"=>"\u788C",
    "\u{2F950}"=>"\u78CC",
    "\u{2F951}"=>"\u40E3",
    "\u{2F952}"=>"\u{25626}",
    "\u{2F953}"=>"\u7956",
    "\u{2F954}"=>"\u{2569A}",
    "\u{2F955}"=>"\u{256C5}",
    "\u{2F956}"=>"\u798F",
    "\u{2F957}"=>"\u79EB",
    "\u{2F958}"=>"\u412F",
    "\u{2F959}"=>"\u7A40",
    "\u{2F95A}"=>"\u7A4A",
    "\u{2F95B}"=>"\u7A4F",
    "\u{2F95C}"=>"\u{2597C}",
    "\u{2F95D}"=>"\u{25AA7}",
    "\u{2F95E}"=>"\u{25AA7}",
    "\u{2F95F}"=>"\u7AEE",
    "\u{2F960}"=>"\u4202",
    "\u{2F961}"=>"\u{25BAB}",
    "\u{2F962}"=>"\u7BC6",
    "\u{2F963}"=>"\u7BC9",
    "\u{2F964}"=>"\u4227",
    "\u{2F965}"=>"\u{25C80}",
    "\u{2F966}"=>"\u7CD2",
    "\u{2F967}"=>"\u42A0",
    "\u{2F968}"=>"\u7CE8",
    "\u{2F969}"=>"\u7CE3",
    "\u{2F96A}"=>"\u7D00",
    "\u{2F96B}"=>"\u{25F86}",
    "\u{2F96C}"=>"\u7D63",
    "\u{2F96D}"=>"\u4301",
    "\u{2F96E}"=>"\u7DC7",
    "\u{2F96F}"=>"\u7E02",
    "\u{2F970}"=>"\u7E45",
    "\u{2F971}"=>"\u4334",
    "\u{2F972}"=>"\u{26228}",
    "\u{2F973}"=>"\u{26247}",
    "\u{2F974}"=>"\u4359",
    "\u{2F975}"=>"\u{262D9}",
    "\u{2F976}"=>"\u7F7A",
    "\u{2F977}"=>"\u{2633E}",
    "\u{2F978}"=>"\u7F95",
    "\u{2F979}"=>"\u7FFA",
    "\u{2F97A}"=>"\u8005",
    "\u{2F97B}"=>"\u{264DA}",
    "\u{2F97C}"=>"\u{26523}",
    "\u{2F97D}"=>"\u8060",
    "\u{2F97E}"=>"\u{265A8}",
    "\u{2F97F}"=>"\u8070",
    "\u{2F980}"=>"\u{2335F}",
    "\u{2F981}"=>"\u43D5",
    "\u{2F982}"=>"\u80B2",
    "\u{2F983}"=>"\u8103",
    "\u{2F984}"=>"\u440B",
    "\u{2F985}"=>"\u813E",
    "\u{2F986}"=>"\u5AB5",
    "\u{2F987}"=>"\u{267A7}",
    "\u{2F988}"=>"\u{267B5}",
    "\u{2F989}"=>"\u{23393}",
    "\u{2F98A}"=>"\u{2339C}",
    "\u{2F98B}"=>"\u8201",
    "\u{2F98C}"=>"\u8204",
    "\u{2F98D}"=>"\u8F9E",
    "\u{2F98E}"=>"\u446B",
    "\u{2F98F}"=>"\u8291",
    "\u{2F990}"=>"\u828B",
    "\u{2F991}"=>"\u829D",
    "\u{2F992}"=>"\u52B3",
    "\u{2F993}"=>"\u82B1",
    "\u{2F994}"=>"\u82B3",
    "\u{2F995}"=>"\u82BD",
    "\u{2F996}"=>"\u82E6",
    "\u{2F997}"=>"\u{26B3C}",
    "\u{2F998}"=>"\u82E5",
    "\u{2F999}"=>"\u831D",
    "\u{2F99A}"=>"\u8363",
    "\u{2F99B}"=>"\u83AD",
    "\u{2F99C}"=>"\u8323",
    "\u{2F99D}"=>"\u83BD",
    "\u{2F99E}"=>"\u83E7",
    "\u{2F99F}"=>"\u8457",
    "\u{2F9A0}"=>"\u8353",
    "\u{2F9A1}"=>"\u83CA",
    "\u{2F9A2}"=>"\u83CC",
    "\u{2F9A3}"=>"\u83DC",
    "\u{2F9A4}"=>"\u{26C36}",
    "\u{2F9A5}"=>"\u{26D6B}",
    "\u{2F9A6}"=>"\u{26CD5}",
    "\u{2F9A7}"=>"\u452B",
    "\u{2F9A8}"=>"\u84F1",
    "\u{2F9A9}"=>"\u84F3",
    "\u{2F9AA}"=>"\u8516",
    "\u{2F9AB}"=>"\u{273CA}",
    "\u{2F9AC}"=>"\u8564",
    "\u{2F9AD}"=>"\u{26F2C}",
    "\u{2F9AE}"=>"\u455D",
    "\u{2F9AF}"=>"\u4561",
    "\u{2F9B0}"=>"\u{26FB1}",
    "\u{2F9B1}"=>"\u{270D2}",
    "\u{2F9B2}"=>"\u456B",
    "\u{2F9B3}"=>"\u8650",
    "\u{2F9B4}"=>"\u865C",
    "\u{2F9B5}"=>"\u8667",
    "\u{2F9B6}"=>"\u8669",
    "\u{2F9B7}"=>"\u86A9",
    "\u{2F9B8}"=>"\u8688",
    "\u{2F9B9}"=>"\u870E",
    "\u{2F9BA}"=>"\u86E2",
    "\u{2F9BB}"=>"\u8779",
    "\u{2F9BC}"=>"\u8728",
    "\u{2F9BD}"=>"\u876B",
    "\u{2F9BE}"=>"\u8786",
    "\u{2F9BF}"=>"\u45D7",
    "\u{2F9C0}"=>"\u87E1",
    "\u{2F9C1}"=>"\u8801",
    "\u{2F9C2}"=>"\u45F9",
    "\u{2F9C3}"=>"\u8860",
    "\u{2F9C4}"=>"\u8863",
    "\u{2F9C5}"=>"\u{27667}",
    "\u{2F9C6}"=>"\u88D7",
    "\u{2F9C7}"=>"\u88DE",
    "\u{2F9C8}"=>"\u4635",
    "\u{2F9C9}"=>"\u88FA",
    "\u{2F9CA}"=>"\u34BB",
    "\u{2F9CB}"=>"\u{278AE}",
    "\u{2F9CC}"=>"\u{27966}",
    "\u{2F9CD}"=>"\u46BE",
    "\u{2F9CE}"=>"\u46C7",
    "\u{2F9CF}"=>"\u8AA0",
    "\u{2F9D0}"=>"\u8AED",
    "\u{2F9D1}"=>"\u8B8A",
    "\u{2F9D2}"=>"\u8C55",
    "\u{2F9D3}"=>"\u{27CA8}",
    "\u{2F9D4}"=>"\u8CAB",
    "\u{2F9D5}"=>"\u8CC1",
    "\u{2F9D6}"=>"\u8D1B",
    "\u{2F9D7}"=>"\u8D77",
    "\u{2F9D8}"=>"\u{27F2F}",
    "\u{2F9D9}"=>"\u{20804}",
    "\u{2F9DA}"=>"\u8DCB",
    "\u{2F9DB}"=>"\u8DBC",
    "\u{2F9DC}"=>"\u8DF0",
    "\u{2F9DD}"=>"\u{208DE}",
    "\u{2F9DE}"=>"\u8ED4",
    "\u{2F9DF}"=>"\u8F38",
    "\u{2F9E0}"=>"\u{285D2}",
    "\u{2F9E1}"=>"\u{285ED}",
    "\u{2F9E2}"=>"\u9094",
    "\u{2F9E3}"=>"\u90F1",
    "\u{2F9E4}"=>"\u9111",
    "\u{2F9E5}"=>"\u{2872E}",
    "\u{2F9E6}"=>"\u911B",
    "\u{2F9E7}"=>"\u9238",
    "\u{2F9E8}"=>"\u92D7",
    "\u{2F9E9}"=>"\u92D8",
    "\u{2F9EA}"=>"\u927C",
    "\u{2F9EB}"=>"\u93F9",
    "\u{2F9EC}"=>"\u9415",
    "\u{2F9ED}"=>"\u{28BFA}",
    "\u{2F9EE}"=>"\u958B",
    "\u{2F9EF}"=>"\u4995",
    "\u{2F9F0}"=>"\u95B7",
    "\u{2F9F1}"=>"\u{28D77}",
    "\u{2F9F2}"=>"\u49E6",
    "\u{2F9F3}"=>"\u96C3",
    "\u{2F9F4}"=>"\u5DB2",
    "\u{2F9F5}"=>"\u9723",
    "\u{2F9F6}"=>"\u{29145}",
    "\u{2F9F7}"=>"\u{2921A}",
    "\u{2F9F8}"=>"\u4A6E",
    "\u{2F9F9}"=>"\u4A76",
    "\u{2F9FA}"=>"\u97E0",
    "\u{2F9FB}"=>"\u{2940A}",
    "\u{2F9FC}"=>"\u4AB2",
    "\u{2F9FD}"=>"\u{29496}",
    "\u{2F9FE}"=>"\u980B",
    "\u{2F9FF}"=>"\u980B",
    "\u{2FA00}"=>"\u9829",
    "\u{2FA01}"=>"\u{295B6}",
    "\u{2FA02}"=>"\u98E2",
    "\u{2FA03}"=>"\u4B33",
    "\u{2FA04}"=>"\u9929",
    "\u{2FA05}"=>"\u99A7",
    "\u{2FA06}"=>"\u99C2",
    "\u{2FA07}"=>"\u99FE",
    "\u{2FA08}"=>"\u4BCE",
    "\u{2FA09}"=>"\u{29B30}",
    "\u{2FA0A}"=>"\u9B12",
    "\u{2FA0B}"=>"\u9C40",
    "\u{2FA0C}"=>"\u9CFD",
    "\u{2FA0D}"=>"\u4CCE",
    "\u{2FA0E}"=>"\u4CED",
    "\u{2FA0F}"=>"\u9D67",
    "\u{2FA10}"=>"\u{2A0CE}",
    "\u{2FA11}"=>"\u4CF8",
    "\u{2FA12}"=>"\u{2A105}",
    "\u{2FA13}"=>"\u{2A20E}",
    "\u{2FA14}"=>"\u{2A291}",
    "\u{2FA15}"=>"\u9EBB",
    "\u{2FA16}"=>"\u4D56",
    "\u{2FA17}"=>"\u9EF9",
    "\u{2FA18}"=>"\u9EFE",
    "\u{2FA19}"=>"\u9F05",
    "\u{2FA1A}"=>"\u9F0F",
    "\u{2FA1B}"=>"\u9F16",
    "\u{2FA1C}"=>"\u9F3B",
    "\u{2FA1D}"=>"\u{2A600}",
  }.freeze

  KOMPATIBLE_TABLE = {
    "\u00A0"=>" ",
    "\u00A8"=>" \u0308",
    "\u00AA"=>"a",
    "\u00AF"=>" \u0304",
    "\u00B2"=>"2",
    "\u00B3"=>"3",
    "\u00B4"=>" \u0301",
    "\u00B5"=>"\u03BC",
    "\u00B8"=>" \u0327",
    "\u00B9"=>"1",
    "\u00BA"=>"o",
    "\u00BC"=>"1\u20444",
    "\u00BD"=>"1\u20442",
    "\u00BE"=>"3\u20444",
    "\u0132"=>"IJ",
    "\u0133"=>"ij",
    "\u013F"=>"L\u00B7",
    "\u0140"=>"l\u00B7",
    "\u0149"=>"\u02BCn",
    "\u017F"=>"s",
    "\u01C4"=>"D\u017D",
    "\u01C5"=>"D\u017E",
    "\u01C6"=>"d\u017E",
    "\u01C7"=>"LJ",
    "\u01C8"=>"Lj",
    "\u01C9"=>"lj",
    "\u01CA"=>"NJ",
    "\u01CB"=>"Nj",
    "\u01CC"=>"nj",
    "\u01F1"=>"DZ",
    "\u01F2"=>"Dz",
    "\u01F3"=>"dz",
    "\u02B0"=>"h",
    "\u02B1"=>"\u0266",
    "\u02B2"=>"j",
    "\u02B3"=>"r",
    "\u02B4"=>"\u0279",
    "\u02B5"=>"\u027B",
    "\u02B6"=>"\u0281",
    "\u02B7"=>"w",
    "\u02B8"=>"y",
    "\u02D8"=>" \u0306",
    "\u02D9"=>" \u0307",
    "\u02DA"=>" \u030A",
    "\u02DB"=>" \u0328",
    "\u02DC"=>" \u0303",
    "\u02DD"=>" \u030B",
    "\u02E0"=>"\u0263",
    "\u02E1"=>"l",
    "\u02E2"=>"s",
    "\u02E3"=>"x",
    "\u02E4"=>"\u0295",
    "\u037A"=>" \u0345",
    "\u0384"=>" \u0301",
    "\u03D0"=>"\u03B2",
    "\u03D1"=>"\u03B8",
    "\u03D2"=>"\u03A5",
    "\u03D5"=>"\u03C6",
    "\u03D6"=>"\u03C0",
    "\u03F0"=>"\u03BA",
    "\u03F1"=>"\u03C1",
    "\u03F2"=>"\u03C2",
    "\u03F4"=>"\u0398",
    "\u03F5"=>"\u03B5",
    "\u03F9"=>"\u03A3",
    "\u0587"=>"\u0565\u0582",
    "\u0675"=>"\u0627\u0674",
    "\u0676"=>"\u0648\u0674",
    "\u0677"=>"\u06C7\u0674",
    "\u0678"=>"\u064A\u0674",
    "\u0E33"=>"\u0E4D\u0E32",
    "\u0EB3"=>"\u0ECD\u0EB2",
    "\u0EDC"=>"\u0EAB\u0E99",
    "\u0EDD"=>"\u0EAB\u0EA1",
    "\u0F0C"=>"\u0F0B",
    "\u0F77"=>"\u0FB2\u0F81",
    "\u0F79"=>"\u0FB3\u0F81",
    "\u10FC"=>"\u10DC",
    "\u1D2C"=>"A",
    "\u1D2D"=>"\u00C6",
    "\u1D2E"=>"B",
    "\u1D30"=>"D",
    "\u1D31"=>"E",
    "\u1D32"=>"\u018E",
    "\u1D33"=>"G",
    "\u1D34"=>"H",
    "\u1D35"=>"I",
    "\u1D36"=>"J",
    "\u1D37"=>"K",
    "\u1D38"=>"L",
    "\u1D39"=>"M",
    "\u1D3A"=>"N",
    "\u1D3C"=>"O",
    "\u1D3D"=>"\u0222",
    "\u1D3E"=>"P",
    "\u1D3F"=>"R",
    "\u1D40"=>"T",
    "\u1D41"=>"U",
    "\u1D42"=>"W",
    "\u1D43"=>"a",
    "\u1D44"=>"\u0250",
    "\u1D45"=>"\u0251",
    "\u1D46"=>"\u1D02",
    "\u1D47"=>"b",
    "\u1D48"=>"d",
    "\u1D49"=>"e",
    "\u1D4A"=>"\u0259",
    "\u1D4B"=>"\u025B",
    "\u1D4C"=>"\u025C",
    "\u1D4D"=>"g",
    "\u1D4F"=>"k",
    "\u1D50"=>"m",
    "\u1D51"=>"\u014B",
    "\u1D52"=>"o",
    "\u1D53"=>"\u0254",
    "\u1D54"=>"\u1D16",
    "\u1D55"=>"\u1D17",
    "\u1D56"=>"p",
    "\u1D57"=>"t",
    "\u1D58"=>"u",
    "\u1D59"=>"\u1D1D",
    "\u1D5A"=>"\u026F",
    "\u1D5B"=>"v",
    "\u1D5C"=>"\u1D25",
    "\u1D5D"=>"\u03B2",
    "\u1D5E"=>"\u03B3",
    "\u1D5F"=>"\u03B4",
    "\u1D60"=>"\u03C6",
    "\u1D61"=>"\u03C7",
    "\u1D62"=>"i",
    "\u1D63"=>"r",
    "\u1D64"=>"u",
    "\u1D65"=>"v",
    "\u1D66"=>"\u03B2",
    "\u1D67"=>"\u03B3",
    "\u1D68"=>"\u03C1",
    "\u1D69"=>"\u03C6",
    "\u1D6A"=>"\u03C7",
    "\u1D78"=>"\u043D",
    "\u1D9B"=>"\u0252",
    "\u1D9C"=>"c",
    "\u1D9D"=>"\u0255",
    "\u1D9E"=>"\u00F0",
    "\u1D9F"=>"\u025C",
    "\u1DA0"=>"f",
    "\u1DA1"=>"\u025F",
    "\u1DA2"=>"\u0261",
    "\u1DA3"=>"\u0265",
    "\u1DA4"=>"\u0268",
    "\u1DA5"=>"\u0269",
    "\u1DA6"=>"\u026A",
    "\u1DA7"=>"\u1D7B",
    "\u1DA8"=>"\u029D",
    "\u1DA9"=>"\u026D",
    "\u1DAA"=>"\u1D85",
    "\u1DAB"=>"\u029F",
    "\u1DAC"=>"\u0271",
    "\u1DAD"=>"\u0270",
    "\u1DAE"=>"\u0272",
    "\u1DAF"=>"\u0273",
    "\u1DB0"=>"\u0274",
    "\u1DB1"=>"\u0275",
    "\u1DB2"=>"\u0278",
    "\u1DB3"=>"\u0282",
    "\u1DB4"=>"\u0283",
    "\u1DB5"=>"\u01AB",
    "\u1DB6"=>"\u0289",
    "\u1DB7"=>"\u028A",
    "\u1DB8"=>"\u1D1C",
    "\u1DB9"=>"\u028B",
    "\u1DBA"=>"\u028C",
    "\u1DBB"=>"z",
    "\u1DBC"=>"\u0290",
    "\u1DBD"=>"\u0291",
    "\u1DBE"=>"\u0292",
    "\u1DBF"=>"\u03B8",
    "\u1E9A"=>"a\u02BE",
    "\u1FBD"=>" \u0313",
    "\u1FBF"=>" \u0313",
    "\u1FC0"=>" \u0342",
    "\u1FFE"=>" \u0314",
    "\u2002"=>" ",
    "\u2003"=>" ",
    "\u2004"=>" ",
    "\u2005"=>" ",
    "\u2006"=>" ",
    "\u2007"=>" ",
    "\u2008"=>" ",
    "\u2009"=>" ",
    "\u200A"=>" ",
    "\u2011"=>"\u2010",
    "\u2017"=>" \u0333",
    "\u2024"=>".",
    "\u2025"=>"..",
    "\u2026"=>"...",
    "\u202F"=>" ",
    "\u2033"=>"\u2032\u2032",
    "\u2034"=>"\u2032\u2032\u2032",
    "\u2036"=>"\u2035\u2035",
    "\u2037"=>"\u2035\u2035\u2035",
    "\u203C"=>"!!",
    "\u203E"=>" \u0305",
    "\u2047"=>"??",
    "\u2048"=>"?!",
    "\u2049"=>"!?",
    "\u2057"=>"\u2032\u2032\u2032\u2032",
    "\u205F"=>" ",
    "\u2070"=>"0",
    "\u2071"=>"i",
    "\u2074"=>"4",
    "\u2075"=>"5",
    "\u2076"=>"6",
    "\u2077"=>"7",
    "\u2078"=>"8",
    "\u2079"=>"9",
    "\u207A"=>"+",
    "\u207B"=>"\u2212",
    "\u207C"=>"=",
    "\u207D"=>"(",
    "\u207E"=>")",
    "\u207F"=>"n",
    "\u2080"=>"0",
    "\u2081"=>"1",
    "\u2082"=>"2",
    "\u2083"=>"3",
    "\u2084"=>"4",
    "\u2085"=>"5",
    "\u2086"=>"6",
    "\u2087"=>"7",
    "\u2088"=>"8",
    "\u2089"=>"9",
    "\u208A"=>"+",
    "\u208B"=>"\u2212",
    "\u208C"=>"=",
    "\u208D"=>"(",
    "\u208E"=>")",
    "\u2090"=>"a",
    "\u2091"=>"e",
    "\u2092"=>"o",
    "\u2093"=>"x",
    "\u2094"=>"\u0259",
    "\u2095"=>"h",
    "\u2096"=>"k",
    "\u2097"=>"l",
    "\u2098"=>"m",
    "\u2099"=>"n",
    "\u209A"=>"p",
    "\u209B"=>"s",
    "\u209C"=>"t",
    "\u20A8"=>"Rs",
    "\u2100"=>"a/c",
    "\u2101"=>"a/s",
    "\u2102"=>"C",
    "\u2103"=>"\u00B0C",
    "\u2105"=>"c/o",
    "\u2106"=>"c/u",
    "\u2107"=>"\u0190",
    "\u2109"=>"\u00B0F",
    "\u210A"=>"g",
    "\u210B"=>"H",
    "\u210C"=>"H",
    "\u210D"=>"H",
    "\u210E"=>"h",
    "\u210F"=>"\u0127",
    "\u2110"=>"I",
    "\u2111"=>"I",
    "\u2112"=>"L",
    "\u2113"=>"l",
    "\u2115"=>"N",
    "\u2116"=>"No",
    "\u2119"=>"P",
    "\u211A"=>"Q",
    "\u211B"=>"R",
    "\u211C"=>"R",
    "\u211D"=>"R",
    "\u2120"=>"SM",
    "\u2121"=>"TEL",
    "\u2122"=>"TM",
    "\u2124"=>"Z",
    "\u2128"=>"Z",
    "\u212C"=>"B",
    "\u212D"=>"C",
    "\u212F"=>"e",
    "\u2130"=>"E",
    "\u2131"=>"F",
    "\u2133"=>"M",
    "\u2134"=>"o",
    "\u2135"=>"\u05D0",
    "\u2136"=>"\u05D1",
    "\u2137"=>"\u05D2",
    "\u2138"=>"\u05D3",
    "\u2139"=>"i",
    "\u213B"=>"FAX",
    "\u213C"=>"\u03C0",
    "\u213D"=>"\u03B3",
    "\u213E"=>"\u0393",
    "\u213F"=>"\u03A0",
    "\u2140"=>"\u2211",
    "\u2145"=>"D",
    "\u2146"=>"d",
    "\u2147"=>"e",
    "\u2148"=>"i",
    "\u2149"=>"j",
    "\u2150"=>"1\u20447",
    "\u2151"=>"1\u20449",
    "\u2152"=>"1\u204410",
    "\u2153"=>"1\u20443",
    "\u2154"=>"2\u20443",
    "\u2155"=>"1\u20445",
    "\u2156"=>"2\u20445",
    "\u2157"=>"3\u20445",
    "\u2158"=>"4\u20445",
    "\u2159"=>"1\u20446",
    "\u215A"=>"5\u20446",
    "\u215B"=>"1\u20448",
    "\u215C"=>"3\u20448",
    "\u215D"=>"5\u20448",
    "\u215E"=>"7\u20448",
    "\u215F"=>"1\u2044",
    "\u2160"=>"I",
    "\u2161"=>"II",
    "\u2162"=>"III",
    "\u2163"=>"IV",
    "\u2164"=>"V",
    "\u2165"=>"VI",
    "\u2166"=>"VII",
    "\u2167"=>"VIII",
    "\u2168"=>"IX",
    "\u2169"=>"X",
    "\u216A"=>"XI",
    "\u216B"=>"XII",
    "\u216C"=>"L",
    "\u216D"=>"C",
    "\u216E"=>"D",
    "\u216F"=>"M",
    "\u2170"=>"i",
    "\u2171"=>"ii",
    "\u2172"=>"iii",
    "\u2173"=>"iv",
    "\u2174"=>"v",
    "\u2175"=>"vi",
    "\u2176"=>"vii",
    "\u2177"=>"viii",
    "\u2178"=>"ix",
    "\u2179"=>"x",
    "\u217A"=>"xi",
    "\u217B"=>"xii",
    "\u217C"=>"l",
    "\u217D"=>"c",
    "\u217E"=>"d",
    "\u217F"=>"m",
    "\u2189"=>"0\u20443",
    "\u222C"=>"\u222B\u222B",
    "\u222D"=>"\u222B\u222B\u222B",
    "\u222F"=>"\u222E\u222E",
    "\u2230"=>"\u222E\u222E\u222E",
    "\u2460"=>"1",
    "\u2461"=>"2",
    "\u2462"=>"3",
    "\u2463"=>"4",
    "\u2464"=>"5",
    "\u2465"=>"6",
    "\u2466"=>"7",
    "\u2467"=>"8",
    "\u2468"=>"9",
    "\u2469"=>"10",
    "\u246A"=>"11",
    "\u246B"=>"12",
    "\u246C"=>"13",
    "\u246D"=>"14",
    "\u246E"=>"15",
    "\u246F"=>"16",
    "\u2470"=>"17",
    "\u2471"=>"18",
    "\u2472"=>"19",
    "\u2473"=>"20",
    "\u2474"=>"(1)",
    "\u2475"=>"(2)",
    "\u2476"=>"(3)",
    "\u2477"=>"(4)",
    "\u2478"=>"(5)",
    "\u2479"=>"(6)",
    "\u247A"=>"(7)",
    "\u247B"=>"(8)",
    "\u247C"=>"(9)",
    "\u247D"=>"(10)",
    "\u247E"=>"(11)",
    "\u247F"=>"(12)",
    "\u2480"=>"(13)",
    "\u2481"=>"(14)",
    "\u2482"=>"(15)",
    "\u2483"=>"(16)",
    "\u2484"=>"(17)",
    "\u2485"=>"(18)",
    "\u2486"=>"(19)",
    "\u2487"=>"(20)",
    "\u2488"=>"1.",
    "\u2489"=>"2.",
    "\u248A"=>"3.",
    "\u248B"=>"4.",
    "\u248C"=>"5.",
    "\u248D"=>"6.",
    "\u248E"=>"7.",
    "\u248F"=>"8.",
    "\u2490"=>"9.",
    "\u2491"=>"10.",
    "\u2492"=>"11.",
    "\u2493"=>"12.",
    "\u2494"=>"13.",
    "\u2495"=>"14.",
    "\u2496"=>"15.",
    "\u2497"=>"16.",
    "\u2498"=>"17.",
    "\u2499"=>"18.",
    "\u249A"=>"19.",
    "\u249B"=>"20.",
    "\u249C"=>"(a)",
    "\u249D"=>"(b)",
    "\u249E"=>"(c)",
    "\u249F"=>"(d)",
    "\u24A0"=>"(e)",
    "\u24A1"=>"(f)",
    "\u24A2"=>"(g)",
    "\u24A3"=>"(h)",
    "\u24A4"=>"(i)",
    "\u24A5"=>"(j)",
    "\u24A6"=>"(k)",
    "\u24A7"=>"(l)",
    "\u24A8"=>"(m)",
    "\u24A9"=>"(n)",
    "\u24AA"=>"(o)",
    "\u24AB"=>"(p)",
    "\u24AC"=>"(q)",
    "\u24AD"=>"(r)",
    "\u24AE"=>"(s)",
    "\u24AF"=>"(t)",
    "\u24B0"=>"(u)",
    "\u24B1"=>"(v)",
    "\u24B2"=>"(w)",
    "\u24B3"=>"(x)",
    "\u24B4"=>"(y)",
    "\u24B5"=>"(z)",
    "\u24B6"=>"A",
    "\u24B7"=>"B",
    "\u24B8"=>"C",
    "\u24B9"=>"D",
    "\u24BA"=>"E",
    "\u24BB"=>"F",
    "\u24BC"=>"G",
    "\u24BD"=>"H",
    "\u24BE"=>"I",
    "\u24BF"=>"J",
    "\u24C0"=>"K",
    "\u24C1"=>"L",
    "\u24C2"=>"M",
    "\u24C3"=>"N",
    "\u24C4"=>"O",
    "\u24C5"=>"P",
    "\u24C6"=>"Q",
    "\u24C7"=>"R",
    "\u24C8"=>"S",
    "\u24C9"=>"T",
    "\u24CA"=>"U",
    "\u24CB"=>"V",
    "\u24CC"=>"W",
    "\u24CD"=>"X",
    "\u24CE"=>"Y",
    "\u24CF"=>"Z",
    "\u24D0"=>"a",
    "\u24D1"=>"b",
    "\u24D2"=>"c",
    "\u24D3"=>"d",
    "\u24D4"=>"e",
    "\u24D5"=>"f",
    "\u24D6"=>"g",
    "\u24D7"=>"h",
    "\u24D8"=>"i",
    "\u24D9"=>"j",
    "\u24DA"=>"k",
    "\u24DB"=>"l",
    "\u24DC"=>"m",
    "\u24DD"=>"n",
    "\u24DE"=>"o",
    "\u24DF"=>"p",
    "\u24E0"=>"q",
    "\u24E1"=>"r",
    "\u24E2"=>"s",
    "\u24E3"=>"t",
    "\u24E4"=>"u",
    "\u24E5"=>"v",
    "\u24E6"=>"w",
    "\u24E7"=>"x",
    "\u24E8"=>"y",
    "\u24E9"=>"z",
    "\u24EA"=>"0",
    "\u2A0C"=>"\u222B\u222B\u222B\u222B",
    "\u2A74"=>"::=",
    "\u2A75"=>"==",
    "\u2A76"=>"===",
    "\u2C7C"=>"j",
    "\u2C7D"=>"V",
    "\u2D6F"=>"\u2D61",
    "\u2E9F"=>"\u6BCD",
    "\u2EF3"=>"\u9F9F",
    "\u2F00"=>"\u4E00",
    "\u2F01"=>"\u4E28",
    "\u2F02"=>"\u4E36",
    "\u2F03"=>"\u4E3F",
    "\u2F04"=>"\u4E59",
    "\u2F05"=>"\u4E85",
    "\u2F06"=>"\u4E8C",
    "\u2F07"=>"\u4EA0",
    "\u2F08"=>"\u4EBA",
    "\u2F09"=>"\u513F",
    "\u2F0A"=>"\u5165",
    "\u2F0B"=>"\u516B",
    "\u2F0C"=>"\u5182",
    "\u2F0D"=>"\u5196",
    "\u2F0E"=>"\u51AB",
    "\u2F0F"=>"\u51E0",
    "\u2F10"=>"\u51F5",
    "\u2F11"=>"\u5200",
    "\u2F12"=>"\u529B",
    "\u2F13"=>"\u52F9",
    "\u2F14"=>"\u5315",
    "\u2F15"=>"\u531A",
    "\u2F16"=>"\u5338",
    "\u2F17"=>"\u5341",
    "\u2F18"=>"\u535C",
    "\u2F19"=>"\u5369",
    "\u2F1A"=>"\u5382",
    "\u2F1B"=>"\u53B6",
    "\u2F1C"=>"\u53C8",
    "\u2F1D"=>"\u53E3",
    "\u2F1E"=>"\u56D7",
    "\u2F1F"=>"\u571F",
    "\u2F20"=>"\u58EB",
    "\u2F21"=>"\u5902",
    "\u2F22"=>"\u590A",
    "\u2F23"=>"\u5915",
    "\u2F24"=>"\u5927",
    "\u2F25"=>"\u5973",
    "\u2F26"=>"\u5B50",
    "\u2F27"=>"\u5B80",
    "\u2F28"=>"\u5BF8",
    "\u2F29"=>"\u5C0F",
    "\u2F2A"=>"\u5C22",
    "\u2F2B"=>"\u5C38",
    "\u2F2C"=>"\u5C6E",
    "\u2F2D"=>"\u5C71",
    "\u2F2E"=>"\u5DDB",
    "\u2F2F"=>"\u5DE5",
    "\u2F30"=>"\u5DF1",
    "\u2F31"=>"\u5DFE",
    "\u2F32"=>"\u5E72",
    "\u2F33"=>"\u5E7A",
    "\u2F34"=>"\u5E7F",
    "\u2F35"=>"\u5EF4",
    "\u2F36"=>"\u5EFE",
    "\u2F37"=>"\u5F0B",
    "\u2F38"=>"\u5F13",
    "\u2F39"=>"\u5F50",
    "\u2F3A"=>"\u5F61",
    "\u2F3B"=>"\u5F73",
    "\u2F3C"=>"\u5FC3",
    "\u2F3D"=>"\u6208",
    "\u2F3E"=>"\u6236",
    "\u2F3F"=>"\u624B",
    "\u2F40"=>"\u652F",
    "\u2F41"=>"\u6534",
    "\u2F42"=>"\u6587",
    "\u2F43"=>"\u6597",
    "\u2F44"=>"\u65A4",
    "\u2F45"=>"\u65B9",
    "\u2F46"=>"\u65E0",
    "\u2F47"=>"\u65E5",
    "\u2F48"=>"\u66F0",
    "\u2F49"=>"\u6708",
    "\u2F4A"=>"\u6728",
    "\u2F4B"=>"\u6B20",
    "\u2F4C"=>"\u6B62",
    "\u2F4D"=>"\u6B79",
    "\u2F4E"=>"\u6BB3",
    "\u2F4F"=>"\u6BCB",
    "\u2F50"=>"\u6BD4",
    "\u2F51"=>"\u6BDB",
    "\u2F52"=>"\u6C0F",
    "\u2F53"=>"\u6C14",
    "\u2F54"=>"\u6C34",
    "\u2F55"=>"\u706B",
    "\u2F56"=>"\u722A",
    "\u2F57"=>"\u7236",
    "\u2F58"=>"\u723B",
    "\u2F59"=>"\u723F",
    "\u2F5A"=>"\u7247",
    "\u2F5B"=>"\u7259",
    "\u2F5C"=>"\u725B",
    "\u2F5D"=>"\u72AC",
    "\u2F5E"=>"\u7384",
    "\u2F5F"=>"\u7389",
    "\u2F60"=>"\u74DC",
    "\u2F61"=>"\u74E6",
    "\u2F62"=>"\u7518",
    "\u2F63"=>"\u751F",
    "\u2F64"=>"\u7528",
    "\u2F65"=>"\u7530",
    "\u2F66"=>"\u758B",
    "\u2F67"=>"\u7592",
    "\u2F68"=>"\u7676",
    "\u2F69"=>"\u767D",
    "\u2F6A"=>"\u76AE",
    "\u2F6B"=>"\u76BF",
    "\u2F6C"=>"\u76EE",
    "\u2F6D"=>"\u77DB",
    "\u2F6E"=>"\u77E2",
    "\u2F6F"=>"\u77F3",
    "\u2F70"=>"\u793A",
    "\u2F71"=>"\u79B8",
    "\u2F72"=>"\u79BE",
    "\u2F73"=>"\u7A74",
    "\u2F74"=>"\u7ACB",
    "\u2F75"=>"\u7AF9",
    "\u2F76"=>"\u7C73",
    "\u2F77"=>"\u7CF8",
    "\u2F78"=>"\u7F36",
    "\u2F79"=>"\u7F51",
    "\u2F7A"=>"\u7F8A",
    "\u2F7B"=>"\u7FBD",
    "\u2F7C"=>"\u8001",
    "\u2F7D"=>"\u800C",
    "\u2F7E"=>"\u8012",
    "\u2F7F"=>"\u8033",
    "\u2F80"=>"\u807F",
    "\u2F81"=>"\u8089",
    "\u2F82"=>"\u81E3",
    "\u2F83"=>"\u81EA",
    "\u2F84"=>"\u81F3",
    "\u2F85"=>"\u81FC",
    "\u2F86"=>"\u820C",
    "\u2F87"=>"\u821B",
    "\u2F88"=>"\u821F",
    "\u2F89"=>"\u826E",
    "\u2F8A"=>"\u8272",
    "\u2F8B"=>"\u8278",
    "\u2F8C"=>"\u864D",
    "\u2F8D"=>"\u866B",
    "\u2F8E"=>"\u8840",
    "\u2F8F"=>"\u884C",
    "\u2F90"=>"\u8863",
    "\u2F91"=>"\u897E",
    "\u2F92"=>"\u898B",
    "\u2F93"=>"\u89D2",
    "\u2F94"=>"\u8A00",
    "\u2F95"=>"\u8C37",
    "\u2F96"=>"\u8C46",
    "\u2F97"=>"\u8C55",
    "\u2F98"=>"\u8C78",
    "\u2F99"=>"\u8C9D",
    "\u2F9A"=>"\u8D64",
    "\u2F9B"=>"\u8D70",
    "\u2F9C"=>"\u8DB3",
    "\u2F9D"=>"\u8EAB",
    "\u2F9E"=>"\u8ECA",
    "\u2F9F"=>"\u8F9B",
    "\u2FA0"=>"\u8FB0",
    "\u2FA1"=>"\u8FB5",
    "\u2FA2"=>"\u9091",
    "\u2FA3"=>"\u9149",
    "\u2FA4"=>"\u91C6",
    "\u2FA5"=>"\u91CC",
    "\u2FA6"=>"\u91D1",
    "\u2FA7"=>"\u9577",
    "\u2FA8"=>"\u9580",
    "\u2FA9"=>"\u961C",
    "\u2FAA"=>"\u96B6",
    "\u2FAB"=>"\u96B9",
    "\u2FAC"=>"\u96E8",
    "\u2FAD"=>"\u9751",
    "\u2FAE"=>"\u975E",
    "\u2FAF"=>"\u9762",
    "\u2FB0"=>"\u9769",
    "\u2FB1"=>"\u97CB",
    "\u2FB2"=>"\u97ED",
    "\u2FB3"=>"\u97F3",
    "\u2FB4"=>"\u9801",
    "\u2FB5"=>"\u98A8",
    "\u2FB6"=>"\u98DB",
    "\u2FB7"=>"\u98DF",
    "\u2FB8"=>"\u9996",
    "\u2FB9"=>"\u9999",
    "\u2FBA"=>"\u99AC",
    "\u2FBB"=>"\u9AA8",
    "\u2FBC"=>"\u9AD8",
    "\u2FBD"=>"\u9ADF",
    "\u2FBE"=>"\u9B25",
    "\u2FBF"=>"\u9B2F",
    "\u2FC0"=>"\u9B32",
    "\u2FC1"=>"\u9B3C",
    "\u2FC2"=>"\u9B5A",
    "\u2FC3"=>"\u9CE5",
    "\u2FC4"=>"\u9E75",
    "\u2FC5"=>"\u9E7F",
    "\u2FC6"=>"\u9EA5",
    "\u2FC7"=>"\u9EBB",
    "\u2FC8"=>"\u9EC3",
    "\u2FC9"=>"\u9ECD",
    "\u2FCA"=>"\u9ED1",
    "\u2FCB"=>"\u9EF9",
    "\u2FCC"=>"\u9EFD",
    "\u2FCD"=>"\u9F0E",
    "\u2FCE"=>"\u9F13",
    "\u2FCF"=>"\u9F20",
    "\u2FD0"=>"\u9F3B",
    "\u2FD1"=>"\u9F4A",
    "\u2FD2"=>"\u9F52",
    "\u2FD3"=>"\u9F8D",
    "\u2FD4"=>"\u9F9C",
    "\u2FD5"=>"\u9FA0",
    "\u3000"=>" ",
    "\u3036"=>"\u3012",
    "\u3038"=>"\u5341",
    "\u3039"=>"\u5344",
    "\u303A"=>"\u5345",
    "\u309B"=>" \u3099",
    "\u309C"=>" \u309A",
    "\u309F"=>"\u3088\u308A",
    "\u30FF"=>"\u30B3\u30C8",
    "\u3131"=>"\u1100",
    "\u3132"=>"\u1101",
    "\u3133"=>"\u11AA",
    "\u3134"=>"\u1102",
    "\u3135"=>"\u11AC",
    "\u3136"=>"\u11AD",
    "\u3137"=>"\u1103",
    "\u3138"=>"\u1104",
    "\u3139"=>"\u1105",
    "\u313A"=>"\u11B0",
    "\u313B"=>"\u11B1",
    "\u313C"=>"\u11B2",
    "\u313D"=>"\u11B3",
    "\u313E"=>"\u11B4",
    "\u313F"=>"\u11B5",
    "\u3140"=>"\u111A",
    "\u3141"=>"\u1106",
    "\u3142"=>"\u1107",
    "\u3143"=>"\u1108",
    "\u3144"=>"\u1121",
    "\u3145"=>"\u1109",
    "\u3146"=>"\u110A",
    "\u3147"=>"\u110B",
    "\u3148"=>"\u110C",
    "\u3149"=>"\u110D",
    "\u314A"=>"\u110E",
    "\u314B"=>"\u110F",
    "\u314C"=>"\u1110",
    "\u314D"=>"\u1111",
    "\u314E"=>"\u1112",
    "\u314F"=>"\u1161",
    "\u3150"=>"\u1162",
    "\u3151"=>"\u1163",
    "\u3152"=>"\u1164",
    "\u3153"=>"\u1165",
    "\u3154"=>"\u1166",
    "\u3155"=>"\u1167",
    "\u3156"=>"\u1168",
    "\u3157"=>"\u1169",
    "\u3158"=>"\u116A",
    "\u3159"=>"\u116B",
    "\u315A"=>"\u116C",
    "\u315B"=>"\u116D",
    "\u315C"=>"\u116E",
    "\u315D"=>"\u116F",
    "\u315E"=>"\u1170",
    "\u315F"=>"\u1171",
    "\u3160"=>"\u1172",
    "\u3161"=>"\u1173",
    "\u3162"=>"\u1174",
    "\u3163"=>"\u1175",
    "\u3164"=>"\u1160",
    "\u3165"=>"\u1114",
    "\u3166"=>"\u1115",
    "\u3167"=>"\u11C7",
    "\u3168"=>"\u11C8",
    "\u3169"=>"\u11CC",
    "\u316A"=>"\u11CE",
    "\u316B"=>"\u11D3",
    "\u316C"=>"\u11D7",
    "\u316D"=>"\u11D9",
    "\u316E"=>"\u111C",
    "\u316F"=>"\u11DD",
    "\u3170"=>"\u11DF",
    "\u3171"=>"\u111D",
    "\u3172"=>"\u111E",
    "\u3173"=>"\u1120",
    "\u3174"=>"\u1122",
    "\u3175"=>"\u1123",
    "\u3176"=>"\u1127",
    "\u3177"=>"\u1129",
    "\u3178"=>"\u112B",
    "\u3179"=>"\u112C",
    "\u317A"=>"\u112D",
    "\u317B"=>"\u112E",
    "\u317C"=>"\u112F",
    "\u317D"=>"\u1132",
    "\u317E"=>"\u1136",
    "\u317F"=>"\u1140",
    "\u3180"=>"\u1147",
    "\u3181"=>"\u114C",
    "\u3182"=>"\u11F1",
    "\u3183"=>"\u11F2",
    "\u3184"=>"\u1157",
    "\u3185"=>"\u1158",
    "\u3186"=>"\u1159",
    "\u3187"=>"\u1184",
    "\u3188"=>"\u1185",
    "\u3189"=>"\u1188",
    "\u318A"=>"\u1191",
    "\u318B"=>"\u1192",
    "\u318C"=>"\u1194",
    "\u318D"=>"\u119E",
    "\u318E"=>"\u11A1",
    "\u3192"=>"\u4E00",
    "\u3193"=>"\u4E8C",
    "\u3194"=>"\u4E09",
    "\u3195"=>"\u56DB",
    "\u3196"=>"\u4E0A",
    "\u3197"=>"\u4E2D",
    "\u3198"=>"\u4E0B",
    "\u3199"=>"\u7532",
    "\u319A"=>"\u4E59",
    "\u319B"=>"\u4E19",
    "\u319C"=>"\u4E01",
    "\u319D"=>"\u5929",
    "\u319E"=>"\u5730",
    "\u319F"=>"\u4EBA",
    "\u3200"=>"(\u1100)",
    "\u3201"=>"(\u1102)",
    "\u3202"=>"(\u1103)",
    "\u3203"=>"(\u1105)",
    "\u3204"=>"(\u1106)",
    "\u3205"=>"(\u1107)",
    "\u3206"=>"(\u1109)",
    "\u3207"=>"(\u110B)",
    "\u3208"=>"(\u110C)",
    "\u3209"=>"(\u110E)",
    "\u320A"=>"(\u110F)",
    "\u320B"=>"(\u1110)",
    "\u320C"=>"(\u1111)",
    "\u320D"=>"(\u1112)",
    "\u320E"=>"(\u1100\u1161)",
    "\u320F"=>"(\u1102\u1161)",
    "\u3210"=>"(\u1103\u1161)",
    "\u3211"=>"(\u1105\u1161)",
    "\u3212"=>"(\u1106\u1161)",
    "\u3213"=>"(\u1107\u1161)",
    "\u3214"=>"(\u1109\u1161)",
    "\u3215"=>"(\u110B\u1161)",
    "\u3216"=>"(\u110C\u1161)",
    "\u3217"=>"(\u110E\u1161)",
    "\u3218"=>"(\u110F\u1161)",
    "\u3219"=>"(\u1110\u1161)",
    "\u321A"=>"(\u1111\u1161)",
    "\u321B"=>"(\u1112\u1161)",
    "\u321C"=>"(\u110C\u116E)",
    "\u321D"=>"(\u110B\u1169\u110C\u1165\u11AB)",
    "\u321E"=>"(\u110B\u1169\u1112\u116E)",
    "\u3220"=>"(\u4E00)",
    "\u3221"=>"(\u4E8C)",
    "\u3222"=>"(\u4E09)",
    "\u3223"=>"(\u56DB)",
    "\u3224"=>"(\u4E94)",
    "\u3225"=>"(\u516D)",
    "\u3226"=>"(\u4E03)",
    "\u3227"=>"(\u516B)",
    "\u3228"=>"(\u4E5D)",
    "\u3229"=>"(\u5341)",
    "\u322A"=>"(\u6708)",
    "\u322B"=>"(\u706B)",
    "\u322C"=>"(\u6C34)",
    "\u322D"=>"(\u6728)",
    "\u322E"=>"(\u91D1)",
    "\u322F"=>"(\u571F)",
    "\u3230"=>"(\u65E5)",
    "\u3231"=>"(\u682A)",
    "\u3232"=>"(\u6709)",
    "\u3233"=>"(\u793E)",
    "\u3234"=>"(\u540D)",
    "\u3235"=>"(\u7279)",
    "\u3236"=>"(\u8CA1)",
    "\u3237"=>"(\u795D)",
    "\u3238"=>"(\u52B4)",
    "\u3239"=>"(\u4EE3)",
    "\u323A"=>"(\u547C)",
    "\u323B"=>"(\u5B66)",
    "\u323C"=>"(\u76E3)",
    "\u323D"=>"(\u4F01)",
    "\u323E"=>"(\u8CC7)",
    "\u323F"=>"(\u5354)",
    "\u3240"=>"(\u796D)",
    "\u3241"=>"(\u4F11)",
    "\u3242"=>"(\u81EA)",
    "\u3243"=>"(\u81F3)",
    "\u3244"=>"\u554F",
    "\u3245"=>"\u5E7C",
    "\u3246"=>"\u6587",
    "\u3247"=>"\u7B8F",
    "\u3250"=>"PTE",
    "\u3251"=>"21",
    "\u3252"=>"22",
    "\u3253"=>"23",
    "\u3254"=>"24",
    "\u3255"=>"25",
    "\u3256"=>"26",
    "\u3257"=>"27",
    "\u3258"=>"28",
    "\u3259"=>"29",
    "\u325A"=>"30",
    "\u325B"=>"31",
    "\u325C"=>"32",
    "\u325D"=>"33",
    "\u325E"=>"34",
    "\u325F"=>"35",
    "\u3260"=>"\u1100",
    "\u3261"=>"\u1102",
    "\u3262"=>"\u1103",
    "\u3263"=>"\u1105",
    "\u3264"=>"\u1106",
    "\u3265"=>"\u1107",
    "\u3266"=>"\u1109",
    "\u3267"=>"\u110B",
    "\u3268"=>"\u110C",
    "\u3269"=>"\u110E",
    "\u326A"=>"\u110F",
    "\u326B"=>"\u1110",
    "\u326C"=>"\u1111",
    "\u326D"=>"\u1112",
    "\u326E"=>"\u1100\u1161",
    "\u326F"=>"\u1102\u1161",
    "\u3270"=>"\u1103\u1161",
    "\u3271"=>"\u1105\u1161",
    "\u3272"=>"\u1106\u1161",
    "\u3273"=>"\u1107\u1161",
    "\u3274"=>"\u1109\u1161",
    "\u3275"=>"\u110B\u1161",
    "\u3276"=>"\u110C\u1161",
    "\u3277"=>"\u110E\u1161",
    "\u3278"=>"\u110F\u1161",
    "\u3279"=>"\u1110\u1161",
    "\u327A"=>"\u1111\u1161",
    "\u327B"=>"\u1112\u1161",
    "\u327C"=>"\u110E\u1161\u11B7\u1100\u1169",
    "\u327D"=>"\u110C\u116E\u110B\u1174",
    "\u327E"=>"\u110B\u116E",
    "\u3280"=>"\u4E00",
    "\u3281"=>"\u4E8C",
    "\u3282"=>"\u4E09",
    "\u3283"=>"\u56DB",
    "\u3284"=>"\u4E94",
    "\u3285"=>"\u516D",
    "\u3286"=>"\u4E03",
    "\u3287"=>"\u516B",
    "\u3288"=>"\u4E5D",
    "\u3289"=>"\u5341",
    "\u328A"=>"\u6708",
    "\u328B"=>"\u706B",
    "\u328C"=>"\u6C34",
    "\u328D"=>"\u6728",
    "\u328E"=>"\u91D1",
    "\u328F"=>"\u571F",
    "\u3290"=>"\u65E5",
    "\u3291"=>"\u682A",
    "\u3292"=>"\u6709",
    "\u3293"=>"\u793E",
    "\u3294"=>"\u540D",
    "\u3295"=>"\u7279",
    "\u3296"=>"\u8CA1",
    "\u3297"=>"\u795D",
    "\u3298"=>"\u52B4",
    "\u3299"=>"\u79D8",
    "\u329A"=>"\u7537",
    "\u329B"=>"\u5973",
    "\u329C"=>"\u9069",
    "\u329D"=>"\u512A",
    "\u329E"=>"\u5370",
    "\u329F"=>"\u6CE8",
    "\u32A0"=>"\u9805",
    "\u32A1"=>"\u4F11",
    "\u32A2"=>"\u5199",
    "\u32A3"=>"\u6B63",
    "\u32A4"=>"\u4E0A",
    "\u32A5"=>"\u4E2D",
    "\u32A6"=>"\u4E0B",
    "\u32A7"=>"\u5DE6",
    "\u32A8"=>"\u53F3",
    "\u32A9"=>"\u533B",
    "\u32AA"=>"\u5B97",
    "\u32AB"=>"\u5B66",
    "\u32AC"=>"\u76E3",
    "\u32AD"=>"\u4F01",
    "\u32AE"=>"\u8CC7",
    "\u32AF"=>"\u5354",
    "\u32B0"=>"\u591C",
    "\u32B1"=>"36",
    "\u32B2"=>"37",
    "\u32B3"=>"38",
    "\u32B4"=>"39",
    "\u32B5"=>"40",
    "\u32B6"=>"41",
    "\u32B7"=>"42",
    "\u32B8"=>"43",
    "\u32B9"=>"44",
    "\u32BA"=>"45",
    "\u32BB"=>"46",
    "\u32BC"=>"47",
    "\u32BD"=>"48",
    "\u32BE"=>"49",
    "\u32BF"=>"50",
    "\u32C0"=>"1\u6708",
    "\u32C1"=>"2\u6708",
    "\u32C2"=>"3\u6708",
    "\u32C3"=>"4\u6708",
    "\u32C4"=>"5\u6708",
    "\u32C5"=>"6\u6708",
    "\u32C6"=>"7\u6708",
    "\u32C7"=>"8\u6708",
    "\u32C8"=>"9\u6708",
    "\u32C9"=>"10\u6708",
    "\u32CA"=>"11\u6708",
    "\u32CB"=>"12\u6708",
    "\u32CC"=>"Hg",
    "\u32CD"=>"erg",
    "\u32CE"=>"eV",
    "\u32CF"=>"LTD",
    "\u32D0"=>"\u30A2",
    "\u32D1"=>"\u30A4",
    "\u32D2"=>"\u30A6",
    "\u32D3"=>"\u30A8",
    "\u32D4"=>"\u30AA",
    "\u32D5"=>"\u30AB",
    "\u32D6"=>"\u30AD",
    "\u32D7"=>"\u30AF",
    "\u32D8"=>"\u30B1",
    "\u32D9"=>"\u30B3",
    "\u32DA"=>"\u30B5",
    "\u32DB"=>"\u30B7",
    "\u32DC"=>"\u30B9",
    "\u32DD"=>"\u30BB",
    "\u32DE"=>"\u30BD",
    "\u32DF"=>"\u30BF",
    "\u32E0"=>"\u30C1",
    "\u32E1"=>"\u30C4",
    "\u32E2"=>"\u30C6",
    "\u32E3"=>"\u30C8",
    "\u32E4"=>"\u30CA",
    "\u32E5"=>"\u30CB",
    "\u32E6"=>"\u30CC",
    "\u32E7"=>"\u30CD",
    "\u32E8"=>"\u30CE",
    "\u32E9"=>"\u30CF",
    "\u32EA"=>"\u30D2",
    "\u32EB"=>"\u30D5",
    "\u32EC"=>"\u30D8",
    "\u32ED"=>"\u30DB",
    "\u32EE"=>"\u30DE",
    "\u32EF"=>"\u30DF",
    "\u32F0"=>"\u30E0",
    "\u32F1"=>"\u30E1",
    "\u32F2"=>"\u30E2",
    "\u32F3"=>"\u30E4",
    "\u32F4"=>"\u30E6",
    "\u32F5"=>"\u30E8",
    "\u32F6"=>"\u30E9",
    "\u32F7"=>"\u30EA",
    "\u32F8"=>"\u30EB",
    "\u32F9"=>"\u30EC",
    "\u32FA"=>"\u30ED",
    "\u32FB"=>"\u30EF",
    "\u32FC"=>"\u30F0",
    "\u32FD"=>"\u30F1",
    "\u32FE"=>"\u30F2",
    "\u32FF"=>"\u4EE4\u548C",
    "\u3300"=>"\u30A2\u30D1\u30FC\u30C8",
    "\u3301"=>"\u30A2\u30EB\u30D5\u30A1",
    "\u3302"=>"\u30A2\u30F3\u30DA\u30A2",
    "\u3303"=>"\u30A2\u30FC\u30EB",
    "\u3304"=>"\u30A4\u30CB\u30F3\u30B0",
    "\u3305"=>"\u30A4\u30F3\u30C1",
    "\u3306"=>"\u30A6\u30A9\u30F3",
    "\u3307"=>"\u30A8\u30B9\u30AF\u30FC\u30C9",
    "\u3308"=>"\u30A8\u30FC\u30AB\u30FC",
    "\u3309"=>"\u30AA\u30F3\u30B9",
    "\u330A"=>"\u30AA\u30FC\u30E0",
    "\u330B"=>"\u30AB\u30A4\u30EA",
    "\u330C"=>"\u30AB\u30E9\u30C3\u30C8",
    "\u330D"=>"\u30AB\u30ED\u30EA\u30FC",
    "\u330E"=>"\u30AC\u30ED\u30F3",
    "\u330F"=>"\u30AC\u30F3\u30DE",
    "\u3310"=>"\u30AE\u30AC",
    "\u3311"=>"\u30AE\u30CB\u30FC",
    "\u3312"=>"\u30AD\u30E5\u30EA\u30FC",
    "\u3313"=>"\u30AE\u30EB\u30C0\u30FC",
    "\u3314"=>"\u30AD\u30ED",
    "\u3315"=>"\u30AD\u30ED\u30B0\u30E9\u30E0",
    "\u3316"=>"\u30AD\u30ED\u30E1\u30FC\u30C8\u30EB",
    "\u3317"=>"\u30AD\u30ED\u30EF\u30C3\u30C8",
    "\u3318"=>"\u30B0\u30E9\u30E0",
    "\u3319"=>"\u30B0\u30E9\u30E0\u30C8\u30F3",
    "\u331A"=>"\u30AF\u30EB\u30BC\u30A4\u30ED",
    "\u331B"=>"\u30AF\u30ED\u30FC\u30CD",
    "\u331C"=>"\u30B1\u30FC\u30B9",
    "\u331D"=>"\u30B3\u30EB\u30CA",
    "\u331E"=>"\u30B3\u30FC\u30DD",
    "\u331F"=>"\u30B5\u30A4\u30AF\u30EB",
    "\u3320"=>"\u30B5\u30F3\u30C1\u30FC\u30E0",
    "\u3321"=>"\u30B7\u30EA\u30F3\u30B0",
    "\u3322"=>"\u30BB\u30F3\u30C1",
    "\u3323"=>"\u30BB\u30F3\u30C8",
    "\u3324"=>"\u30C0\u30FC\u30B9",
    "\u3325"=>"\u30C7\u30B7",
    "\u3326"=>"\u30C9\u30EB",
    "\u3327"=>"\u30C8\u30F3",
    "\u3328"=>"\u30CA\u30CE",
    "\u3329"=>"\u30CE\u30C3\u30C8",
    "\u332A"=>"\u30CF\u30A4\u30C4",
    "\u332B"=>"\u30D1\u30FC\u30BB\u30F3\u30C8",
    "\u332C"=>"\u30D1\u30FC\u30C4",
    "\u332D"=>"\u30D0\u30FC\u30EC\u30EB",
    "\u332E"=>"\u30D4\u30A2\u30B9\u30C8\u30EB",
    "\u332F"=>"\u30D4\u30AF\u30EB",
    "\u3330"=>"\u30D4\u30B3",
    "\u3331"=>"\u30D3\u30EB",
    "\u3332"=>"\u30D5\u30A1\u30E9\u30C3\u30C9",
    "\u3333"=>"\u30D5\u30A3\u30FC\u30C8",
    "\u3334"=>"\u30D6\u30C3\u30B7\u30A7\u30EB",
    "\u3335"=>"\u30D5\u30E9\u30F3",
    "\u3336"=>"\u30D8\u30AF\u30BF\u30FC\u30EB",
    "\u3337"=>"\u30DA\u30BD",
    "\u3338"=>"\u30DA\u30CB\u30D2",
    "\u3339"=>"\u30D8\u30EB\u30C4",
    "\u333A"=>"\u30DA\u30F3\u30B9",
    "\u333B"=>"\u30DA\u30FC\u30B8",
    "\u333C"=>"\u30D9\u30FC\u30BF",
    "\u333D"=>"\u30DD\u30A4\u30F3\u30C8",
    "\u333E"=>"\u30DC\u30EB\u30C8",
    "\u333F"=>"\u30DB\u30F3",
    "\u3340"=>"\u30DD\u30F3\u30C9",
    "\u3341"=>"\u30DB\u30FC\u30EB",
    "\u3342"=>"\u30DB\u30FC\u30F3",
    "\u3343"=>"\u30DE\u30A4\u30AF\u30ED",
    "\u3344"=>"\u30DE\u30A4\u30EB",
    "\u3345"=>"\u30DE\u30C3\u30CF",
    "\u3346"=>"\u30DE\u30EB\u30AF",
    "\u3347"=>"\u30DE\u30F3\u30B7\u30E7\u30F3",
    "\u3348"=>"\u30DF\u30AF\u30ED\u30F3",
    "\u3349"=>"\u30DF\u30EA",
    "\u334A"=>"\u30DF\u30EA\u30D0\u30FC\u30EB",
    "\u334B"=>"\u30E1\u30AC",
    "\u334C"=>"\u30E1\u30AC\u30C8\u30F3",
    "\u334D"=>"\u30E1\u30FC\u30C8\u30EB",
    "\u334E"=>"\u30E4\u30FC\u30C9",
    "\u334F"=>"\u30E4\u30FC\u30EB",
    "\u3350"=>"\u30E6\u30A2\u30F3",
    "\u3351"=>"\u30EA\u30C3\u30C8\u30EB",
    "\u3352"=>"\u30EA\u30E9",
    "\u3353"=>"\u30EB\u30D4\u30FC",
    "\u3354"=>"\u30EB\u30FC\u30D6\u30EB",
    "\u3355"=>"\u30EC\u30E0",
    "\u3356"=>"\u30EC\u30F3\u30C8\u30B2\u30F3",
    "\u3357"=>"\u30EF\u30C3\u30C8",
    "\u3358"=>"0\u70B9",
    "\u3359"=>"1\u70B9",
    "\u335A"=>"2\u70B9",
    "\u335B"=>"3\u70B9",
    "\u335C"=>"4\u70B9",
    "\u335D"=>"5\u70B9",
    "\u335E"=>"6\u70B9",
    "\u335F"=>"7\u70B9",
    "\u3360"=>"8\u70B9",
    "\u3361"=>"9\u70B9",
    "\u3362"=>"10\u70B9",
    "\u3363"=>"11\u70B9",
    "\u3364"=>"12\u70B9",
    "\u3365"=>"13\u70B9",
    "\u3366"=>"14\u70B9",
    "\u3367"=>"15\u70B9",
    "\u3368"=>"16\u70B9",
    "\u3369"=>"17\u70B9",
    "\u336A"=>"18\u70B9",
    "\u336B"=>"19\u70B9",
    "\u336C"=>"20\u70B9",
    "\u336D"=>"21\u70B9",
    "\u336E"=>"22\u70B9",
    "\u336F"=>"23\u70B9",
    "\u3370"=>"24\u70B9",
    "\u3371"=>"hPa",
    "\u3372"=>"da",
    "\u3373"=>"AU",
    "\u3374"=>"bar",
    "\u3375"=>"oV",
    "\u3376"=>"pc",
    "\u3377"=>"dm",
    "\u3378"=>"dm2",
    "\u3379"=>"dm3",
    "\u337A"=>"IU",
    "\u337B"=>"\u5E73\u6210",
    "\u337C"=>"\u662D\u548C",
    "\u337D"=>"\u5927\u6B63",
    "\u337E"=>"\u660E\u6CBB",
    "\u337F"=>"\u682A\u5F0F\u4F1A\u793E",
    "\u3380"=>"pA",
    "\u3381"=>"nA",
    "\u3382"=>"\u03BCA",
    "\u3383"=>"mA",
    "\u3384"=>"kA",
    "\u3385"=>"KB",
    "\u3386"=>"MB",
    "\u3387"=>"GB",
    "\u3388"=>"cal",
    "\u3389"=>"kcal",
    "\u338A"=>"pF",
    "\u338B"=>"nF",
    "\u338C"=>"\u03BCF",
    "\u338D"=>"\u03BCg",
    "\u338E"=>"mg",
    "\u338F"=>"kg",
    "\u3390"=>"Hz",
    "\u3391"=>"kHz",
    "\u3392"=>"MHz",
    "\u3393"=>"GHz",
    "\u3394"=>"THz",
    "\u3395"=>"\u03BCl",
    "\u3396"=>"ml",
    "\u3397"=>"dl",
    "\u3398"=>"kl",
    "\u3399"=>"fm",
    "\u339A"=>"nm",
    "\u339B"=>"\u03BCm",
    "\u339C"=>"mm",
    "\u339D"=>"cm",
    "\u339E"=>"km",
    "\u339F"=>"mm2",
    "\u33A0"=>"cm2",
    "\u33A1"=>"m2",
    "\u33A2"=>"km2",
    "\u33A3"=>"mm3",
    "\u33A4"=>"cm3",
    "\u33A5"=>"m3",
    "\u33A6"=>"km3",
    "\u33A7"=>"m\u2215s",
    "\u33A8"=>"m\u2215s2",
    "\u33A9"=>"Pa",
    "\u33AA"=>"kPa",
    "\u33AB"=>"MPa",
    "\u33AC"=>"GPa",
    "\u33AD"=>"rad",
    "\u33AE"=>"rad\u2215s",
    "\u33AF"=>"rad\u2215s2",
    "\u33B0"=>"ps",
    "\u33B1"=>"ns",
    "\u33B2"=>"\u03BCs",
    "\u33B3"=>"ms",
    "\u33B4"=>"pV",
    "\u33B5"=>"nV",
    "\u33B6"=>"\u03BCV",
    "\u33B7"=>"mV",
    "\u33B8"=>"kV",
    "\u33B9"=>"MV",
    "\u33BA"=>"pW",
    "\u33BB"=>"nW",
    "\u33BC"=>"\u03BCW",
    "\u33BD"=>"mW",
    "\u33BE"=>"kW",
    "\u33BF"=>"MW",
    "\u33C0"=>"k\u03A9",
    "\u33C1"=>"M\u03A9",
    "\u33C2"=>"a.m.",
    "\u33C3"=>"Bq",
    "\u33C4"=>"cc",
    "\u33C5"=>"cd",
    "\u33C6"=>"C\u2215kg",
    "\u33C7"=>"Co.",
    "\u33C8"=>"dB",
    "\u33C9"=>"Gy",
    "\u33CA"=>"ha",
    "\u33CB"=>"HP",
    "\u33CC"=>"in",
    "\u33CD"=>"KK",
    "\u33CE"=>"KM",
    "\u33CF"=>"kt",
    "\u33D0"=>"lm",
    "\u33D1"=>"ln",
    "\u33D2"=>"log",
    "\u33D3"=>"lx",
    "\u33D4"=>"mb",
    "\u33D5"=>"mil",
    "\u33D6"=>"mol",
    "\u33D7"=>"PH",
    "\u33D8"=>"p.m.",
    "\u33D9"=>"PPM",
    "\u33DA"=>"PR",
    "\u33DB"=>"sr",
    "\u33DC"=>"Sv",
    "\u33DD"=>"Wb",
    "\u33DE"=>"V\u2215m",
    "\u33DF"=>"A\u2215m",
    "\u33E0"=>"1\u65E5",
    "\u33E1"=>"2\u65E5",
    "\u33E2"=>"3\u65E5",
    "\u33E3"=>"4\u65E5",
    "\u33E4"=>"5\u65E5",
    "\u33E5"=>"6\u65E5",
    "\u33E6"=>"7\u65E5",
    "\u33E7"=>"8\u65E5",
    "\u33E8"=>"9\u65E5",
    "\u33E9"=>"10\u65E5",
    "\u33EA"=>"11\u65E5",
    "\u33EB"=>"12\u65E5",
    "\u33EC"=>"13\u65E5",
    "\u33ED"=>"14\u65E5",
    "\u33EE"=>"15\u65E5",
    "\u33EF"=>"16\u65E5",
    "\u33F0"=>"17\u65E5",
    "\u33F1"=>"18\u65E5",
    "\u33F2"=>"19\u65E5",
    "\u33F3"=>"20\u65E5",
    "\u33F4"=>"21\u65E5",
    "\u33F5"=>"22\u65E5",
    "\u33F6"=>"23\u65E5",
    "\u33F7"=>"24\u65E5",
    "\u33F8"=>"25\u65E5",
    "\u33F9"=>"26\u65E5",
    "\u33FA"=>"27\u65E5",
    "\u33FB"=>"28\u65E5",
    "\u33FC"=>"29\u65E5",
    "\u33FD"=>"30\u65E5",
    "\u33FE"=>"31\u65E5",
    "\u33FF"=>"gal",
    "\uA69C"=>"\u044A",
    "\uA69D"=>"\u044C",
    "\uA770"=>"\uA76F",
    "\uA7F8"=>"\u0126",
    "\uA7F9"=>"\u0153",
    "\uAB5C"=>"\uA727",
    "\uAB5D"=>"\uAB37",
    "\uAB5E"=>"\u026B",
    "\uAB5F"=>"\uAB52",
    "\uFB00"=>"ff",
    "\uFB01"=>"fi",
    "\uFB02"=>"fl",
    "\uFB03"=>"ffi",
    "\uFB04"=>"ffl",
    "\uFB05"=>"st",
    "\uFB06"=>"st",
    "\uFB13"=>"\u0574\u0576",
    "\uFB14"=>"\u0574\u0565",
    "\uFB15"=>"\u0574\u056B",
    "\uFB16"=>"\u057E\u0576",
    "\uFB17"=>"\u0574\u056D",
    "\uFB20"=>"\u05E2",
    "\uFB21"=>"\u05D0",
    "\uFB22"=>"\u05D3",
    "\uFB23"=>"\u05D4",
    "\uFB24"=>"\u05DB",
    "\uFB25"=>"\u05DC",
    "\uFB26"=>"\u05DD",
    "\uFB27"=>"\u05E8",
    "\uFB28"=>"\u05EA",
    "\uFB29"=>"+",
    "\uFB4F"=>"\u05D0\u05DC",
    "\uFB50"=>"\u0671",
    "\uFB51"=>"\u0671",
    "\uFB52"=>"\u067B",
    "\uFB53"=>"\u067B",
    "\uFB54"=>"\u067B",
    "\uFB55"=>"\u067B",
    "\uFB56"=>"\u067E",
    "\uFB57"=>"\u067E",
    "\uFB58"=>"\u067E",
    "\uFB59"=>"\u067E",
    "\uFB5A"=>"\u0680",
    "\uFB5B"=>"\u0680",
    "\uFB5C"=>"\u0680",
    "\uFB5D"=>"\u0680",
    "\uFB5E"=>"\u067A",
    "\uFB5F"=>"\u067A",
    "\uFB60"=>"\u067A",
    "\uFB61"=>"\u067A",
    "\uFB62"=>"\u067F",
    "\uFB63"=>"\u067F",
    "\uFB64"=>"\u067F",
    "\uFB65"=>"\u067F",
    "\uFB66"=>"\u0679",
    "\uFB67"=>"\u0679",
    "\uFB68"=>"\u0679",
    "\uFB69"=>"\u0679",
    "\uFB6A"=>"\u06A4",
    "\uFB6B"=>"\u06A4",
    "\uFB6C"=>"\u06A4",
    "\uFB6D"=>"\u06A4",
    "\uFB6E"=>"\u06A6",
    "\uFB6F"=>"\u06A6",
    "\uFB70"=>"\u06A6",
    "\uFB71"=>"\u06A6",
    "\uFB72"=>"\u0684",
    "\uFB73"=>"\u0684",
    "\uFB74"=>"\u0684",
    "\uFB75"=>"\u0684",
    "\uFB76"=>"\u0683",
    "\uFB77"=>"\u0683",
    "\uFB78"=>"\u0683",
    "\uFB79"=>"\u0683",
    "\uFB7A"=>"\u0686",
    "\uFB7B"=>"\u0686",
    "\uFB7C"=>"\u0686",
    "\uFB7D"=>"\u0686",
    "\uFB7E"=>"\u0687",
    "\uFB7F"=>"\u0687",
    "\uFB80"=>"\u0687",
    "\uFB81"=>"\u0687",
    "\uFB82"=>"\u068D",
    "\uFB83"=>"\u068D",
    "\uFB84"=>"\u068C",
    "\uFB85"=>"\u068C",
    "\uFB86"=>"\u068E",
    "\uFB87"=>"\u068E",
    "\uFB88"=>"\u0688",
    "\uFB89"=>"\u0688",
    "\uFB8A"=>"\u0698",
    "\uFB8B"=>"\u0698",
    "\uFB8C"=>"\u0691",
    "\uFB8D"=>"\u0691",
    "\uFB8E"=>"\u06A9",
    "\uFB8F"=>"\u06A9",
    "\uFB90"=>"\u06A9",
    "\uFB91"=>"\u06A9",
    "\uFB92"=>"\u06AF",
    "\uFB93"=>"\u06AF",
    "\uFB94"=>"\u06AF",
    "\uFB95"=>"\u06AF",
    "\uFB96"=>"\u06B3",
    "\uFB97"=>"\u06B3",
    "\uFB98"=>"\u06B3",
    "\uFB99"=>"\u06B3",
    "\uFB9A"=>"\u06B1",
    "\uFB9B"=>"\u06B1",
    "\uFB9C"=>"\u06B1",
    "\uFB9D"=>"\u06B1",
    "\uFB9E"=>"\u06BA",
    "\uFB9F"=>"\u06BA",
    "\uFBA0"=>"\u06BB",
    "\uFBA1"=>"\u06BB",
    "\uFBA2"=>"\u06BB",
    "\uFBA3"=>"\u06BB",
    "\uFBA4"=>"\u06C0",
    "\uFBA5"=>"\u06C0",
    "\uFBA6"=>"\u06C1",
    "\uFBA7"=>"\u06C1",
    "\uFBA8"=>"\u06C1",
    "\uFBA9"=>"\u06C1",
    "\uFBAA"=>"\u06BE",
    "\uFBAB"=>"\u06BE",
    "\uFBAC"=>"\u06BE",
    "\uFBAD"=>"\u06BE",
    "\uFBAE"=>"\u06D2",
    "\uFBAF"=>"\u06D2",
    "\uFBB0"=>"\u06D3",
    "\uFBB1"=>"\u06D3",
    "\uFBD3"=>"\u06AD",
    "\uFBD4"=>"\u06AD",
    "\uFBD5"=>"\u06AD",
    "\uFBD6"=>"\u06AD",
    "\uFBD7"=>"\u06C7",
    "\uFBD8"=>"\u06C7",
    "\uFBD9"=>"\u06C6",
    "\uFBDA"=>"\u06C6",
    "\uFBDB"=>"\u06C8",
    "\uFBDC"=>"\u06C8",
    "\uFBDD"=>"\u06C7\u0674",
    "\uFBDE"=>"\u06CB",
    "\uFBDF"=>"\u06CB",
    "\uFBE0"=>"\u06C5",
    "\uFBE1"=>"\u06C5",
    "\uFBE2"=>"\u06C9",
    "\uFBE3"=>"\u06C9",
    "\uFBE4"=>"\u06D0",
    "\uFBE5"=>"\u06D0",
    "\uFBE6"=>"\u06D0",
    "\uFBE7"=>"\u06D0",
    "\uFBE8"=>"\u0649",
    "\uFBE9"=>"\u0649",
    "\uFBEA"=>"\u0626\u0627",
    "\uFBEB"=>"\u0626\u0627",
    "\uFBEC"=>"\u0626\u06D5",
    "\uFBED"=>"\u0626\u06D5",
    "\uFBEE"=>"\u0626\u0648",
    "\uFBEF"=>"\u0626\u0648",
    "\uFBF0"=>"\u0626\u06C7",
    "\uFBF1"=>"\u0626\u06C7",
    "\uFBF2"=>"\u0626\u06C6",
    "\uFBF3"=>"\u0626\u06C6",
    "\uFBF4"=>"\u0626\u06C8",
    "\uFBF5"=>"\u0626\u06C8",
    "\uFBF6"=>"\u0626\u06D0",
    "\uFBF7"=>"\u0626\u06D0",
    "\uFBF8"=>"\u0626\u06D0",
    "\uFBF9"=>"\u0626\u0649",
    "\uFBFA"=>"\u0626\u0649",
    "\uFBFB"=>"\u0626\u0649",
    "\uFBFC"=>"\u06CC",
    "\uFBFD"=>"\u06CC",
    "\uFBFE"=>"\u06CC",
    "\uFBFF"=>"\u06CC",
    "\uFC00"=>"\u0626\u062C",
    "\uFC01"=>"\u0626\u062D",
    "\uFC02"=>"\u0626\u0645",
    "\uFC03"=>"\u0626\u0649",
    "\uFC04"=>"\u0626\u064A",
    "\uFC05"=>"\u0628\u062C",
    "\uFC06"=>"\u0628\u062D",
    "\uFC07"=>"\u0628\u062E",
    "\uFC08"=>"\u0628\u0645",
    "\uFC09"=>"\u0628\u0649",
    "\uFC0A"=>"\u0628\u064A",
    "\uFC0B"=>"\u062A\u062C",
    "\uFC0C"=>"\u062A\u062D",
    "\uFC0D"=>"\u062A\u062E",
    "\uFC0E"=>"\u062A\u0645",
    "\uFC0F"=>"\u062A\u0649",
    "\uFC10"=>"\u062A\u064A",
    "\uFC11"=>"\u062B\u062C",
    "\uFC12"=>"\u062B\u0645",
    "\uFC13"=>"\u062B\u0649",
    "\uFC14"=>"\u062B\u064A",
    "\uFC15"=>"\u062C\u062D",
    "\uFC16"=>"\u062C\u0645",
    "\uFC17"=>"\u062D\u062C",
    "\uFC18"=>"\u062D\u0645",
    "\uFC19"=>"\u062E\u062C",
    "\uFC1A"=>"\u062E\u062D",
    "\uFC1B"=>"\u062E\u0645",
    "\uFC1C"=>"\u0633\u062C",
    "\uFC1D"=>"\u0633\u062D",
    "\uFC1E"=>"\u0633\u062E",
    "\uFC1F"=>"\u0633\u0645",
    "\uFC20"=>"\u0635\u062D",
    "\uFC21"=>"\u0635\u0645",
    "\uFC22"=>"\u0636\u062C",
    "\uFC23"=>"\u0636\u062D",
    "\uFC24"=>"\u0636\u062E",
    "\uFC25"=>"\u0636\u0645",
    "\uFC26"=>"\u0637\u062D",
    "\uFC27"=>"\u0637\u0645",
    "\uFC28"=>"\u0638\u0645",
    "\uFC29"=>"\u0639\u062C",
    "\uFC2A"=>"\u0639\u0645",
    "\uFC2B"=>"\u063A\u062C",
    "\uFC2C"=>"\u063A\u0645",
    "\uFC2D"=>"\u0641\u062C",
    "\uFC2E"=>"\u0641\u062D",
    "\uFC2F"=>"\u0641\u062E",
    "\uFC30"=>"\u0641\u0645",
    "\uFC31"=>"\u0641\u0649",
    "\uFC32"=>"\u0641\u064A",
    "\uFC33"=>"\u0642\u062D",
    "\uFC34"=>"\u0642\u0645",
    "\uFC35"=>"\u0642\u0649",
    "\uFC36"=>"\u0642\u064A",
    "\uFC37"=>"\u0643\u0627",
    "\uFC38"=>"\u0643\u062C",
    "\uFC39"=>"\u0643\u062D",
    "\uFC3A"=>"\u0643\u062E",
    "\uFC3B"=>"\u0643\u0644",
    "\uFC3C"=>"\u0643\u0645",
    "\uFC3D"=>"\u0643\u0649",
    "\uFC3E"=>"\u0643\u064A",
    "\uFC3F"=>"\u0644\u062C",
    "\uFC40"=>"\u0644\u062D",
    "\uFC41"=>"\u0644\u062E",
    "\uFC42"=>"\u0644\u0645",
    "\uFC43"=>"\u0644\u0649",
    "\uFC44"=>"\u0644\u064A",
    "\uFC45"=>"\u0645\u062C",
    "\uFC46"=>"\u0645\u062D",
    "\uFC47"=>"\u0645\u062E",
    "\uFC48"=>"\u0645\u0645",
    "\uFC49"=>"\u0645\u0649",
    "\uFC4A"=>"\u0645\u064A",
    "\uFC4B"=>"\u0646\u062C",
    "\uFC4C"=>"\u0646\u062D",
    "\uFC4D"=>"\u0646\u062E",
    "\uFC4E"=>"\u0646\u0645",
    "\uFC4F"=>"\u0646\u0649",
    "\uFC50"=>"\u0646\u064A",
    "\uFC51"=>"\u0647\u062C",
    "\uFC52"=>"\u0647\u0645",
    "\uFC53"=>"\u0647\u0649",
    "\uFC54"=>"\u0647\u064A",
    "\uFC55"=>"\u064A\u062C",
    "\uFC56"=>"\u064A\u062D",
    "\uFC57"=>"\u064A\u062E",
    "\uFC58"=>"\u064A\u0645",
    "\uFC59"=>"\u064A\u0649",
    "\uFC5A"=>"\u064A\u064A",
    "\uFC5B"=>"\u0630\u0670",
    "\uFC5C"=>"\u0631\u0670",
    "\uFC5D"=>"\u0649\u0670",
    "\uFC5E"=>" \u064C\u0651",
    "\uFC5F"=>" \u064D\u0651",
    "\uFC60"=>" \u064E\u0651",
    "\uFC61"=>" \u064F\u0651",
    "\uFC62"=>" \u0650\u0651",
    "\uFC63"=>" \u0651\u0670",
    "\uFC64"=>"\u0626\u0631",
    "\uFC65"=>"\u0626\u0632",
    "\uFC66"=>"\u0626\u0645",
    "\uFC67"=>"\u0626\u0646",
    "\uFC68"=>"\u0626\u0649",
    "\uFC69"=>"\u0626\u064A",
    "\uFC6A"=>"\u0628\u0631",
    "\uFC6B"=>"\u0628\u0632",
    "\uFC6C"=>"\u0628\u0645",
    "\uFC6D"=>"\u0628\u0646",
    "\uFC6E"=>"\u0628\u0649",
    "\uFC6F"=>"\u0628\u064A",
    "\uFC70"=>"\u062A\u0631",
    "\uFC71"=>"\u062A\u0632",
    "\uFC72"=>"\u062A\u0645",
    "\uFC73"=>"\u062A\u0646",
    "\uFC74"=>"\u062A\u0649",
    "\uFC75"=>"\u062A\u064A",
    "\uFC76"=>"\u062B\u0631",
    "\uFC77"=>"\u062B\u0632",
    "\uFC78"=>"\u062B\u0645",
    "\uFC79"=>"\u062B\u0646",
    "\uFC7A"=>"\u062B\u0649",
    "\uFC7B"=>"\u062B\u064A",
    "\uFC7C"=>"\u0641\u0649",
    "\uFC7D"=>"\u0641\u064A",
    "\uFC7E"=>"\u0642\u0649",
    "\uFC7F"=>"\u0642\u064A",
    "\uFC80"=>"\u0643\u0627",
    "\uFC81"=>"\u0643\u0644",
    "\uFC82"=>"\u0643\u0645",
    "\uFC83"=>"\u0643\u0649",
    "\uFC84"=>"\u0643\u064A",
    "\uFC85"=>"\u0644\u0645",
    "\uFC86"=>"\u0644\u0649",
    "\uFC87"=>"\u0644\u064A",
    "\uFC88"=>"\u0645\u0627",
    "\uFC89"=>"\u0645\u0645",
    "\uFC8A"=>"\u0646\u0631",
    "\uFC8B"=>"\u0646\u0632",
    "\uFC8C"=>"\u0646\u0645",
    "\uFC8D"=>"\u0646\u0646",
    "\uFC8E"=>"\u0646\u0649",
    "\uFC8F"=>"\u0646\u064A",
    "\uFC90"=>"\u0649\u0670",
    "\uFC91"=>"\u064A\u0631",
    "\uFC92"=>"\u064A\u0632",
    "\uFC93"=>"\u064A\u0645",
    "\uFC94"=>"\u064A\u0646",
    "\uFC95"=>"\u064A\u0649",
    "\uFC96"=>"\u064A\u064A",
    "\uFC97"=>"\u0626\u062C",
    "\uFC98"=>"\u0626\u062D",
    "\uFC99"=>"\u0626\u062E",
    "\uFC9A"=>"\u0626\u0645",
    "\uFC9B"=>"\u0626\u0647",
    "\uFC9C"=>"\u0628\u062C",
    "\uFC9D"=>"\u0628\u062D",
    "\uFC9E"=>"\u0628\u062E",
    "\uFC9F"=>"\u0628\u0645",
    "\uFCA0"=>"\u0628\u0647",
    "\uFCA1"=>"\u062A\u062C",
    "\uFCA2"=>"\u062A\u062D",
    "\uFCA3"=>"\u062A\u062E",
    "\uFCA4"=>"\u062A\u0645",
    "\uFCA5"=>"\u062A\u0647",
    "\uFCA6"=>"\u062B\u0645",
    "\uFCA7"=>"\u062C\u062D",
    "\uFCA8"=>"\u062C\u0645",
    "\uFCA9"=>"\u062D\u062C",
    "\uFCAA"=>"\u062D\u0645",
    "\uFCAB"=>"\u062E\u062C",
    "\uFCAC"=>"\u062E\u0645",
    "\uFCAD"=>"\u0633\u062C",
    "\uFCAE"=>"\u0633\u062D",
    "\uFCAF"=>"\u0633\u062E",
    "\uFCB0"=>"\u0633\u0645",
    "\uFCB1"=>"\u0635\u062D",
    "\uFCB2"=>"\u0635\u062E",
    "\uFCB3"=>"\u0635\u0645",
    "\uFCB4"=>"\u0636\u062C",
    "\uFCB5"=>"\u0636\u062D",
    "\uFCB6"=>"\u0636\u062E",
    "\uFCB7"=>"\u0636\u0645",
    "\uFCB8"=>"\u0637\u062D",
    "\uFCB9"=>"\u0638\u0645",
    "\uFCBA"=>"\u0639\u062C",
    "\uFCBB"=>"\u0639\u0645",
    "\uFCBC"=>"\u063A\u062C",
    "\uFCBD"=>"\u063A\u0645",
    "\uFCBE"=>"\u0641\u062C",
    "\uFCBF"=>"\u0641\u062D",
    "\uFCC0"=>"\u0641\u062E",
    "\uFCC1"=>"\u0641\u0645",
    "\uFCC2"=>"\u0642\u062D",
    "\uFCC3"=>"\u0642\u0645",
    "\uFCC4"=>"\u0643\u062C",
    "\uFCC5"=>"\u0643\u062D",
    "\uFCC6"=>"\u0643\u062E",
    "\uFCC7"=>"\u0643\u0644",
    "\uFCC8"=>"\u0643\u0645",
    "\uFCC9"=>"\u0644\u062C",
    "\uFCCA"=>"\u0644\u062D",
    "\uFCCB"=>"\u0644\u062E",
    "\uFCCC"=>"\u0644\u0645",
    "\uFCCD"=>"\u0644\u0647",
    "\uFCCE"=>"\u0645\u062C",
    "\uFCCF"=>"\u0645\u062D",
    "\uFCD0"=>"\u0645\u062E",
    "\uFCD1"=>"\u0645\u0645",
    "\uFCD2"=>"\u0646\u062C",
    "\uFCD3"=>"\u0646\u062D",
    "\uFCD4"=>"\u0646\u062E",
    "\uFCD5"=>"\u0646\u0645",
    "\uFCD6"=>"\u0646\u0647",
    "\uFCD7"=>"\u0647\u062C",
    "\uFCD8"=>"\u0647\u0645",
    "\uFCD9"=>"\u0647\u0670",
    "\uFCDA"=>"\u064A\u062C",
    "\uFCDB"=>"\u064A\u062D",
    "\uFCDC"=>"\u064A\u062E",
    "\uFCDD"=>"\u064A\u0645",
    "\uFCDE"=>"\u064A\u0647",
    "\uFCDF"=>"\u0626\u0645",
    "\uFCE0"=>"\u0626\u0647",
    "\uFCE1"=>"\u0628\u0645",
    "\uFCE2"=>"\u0628\u0647",
    "\uFCE3"=>"\u062A\u0645",
    "\uFCE4"=>"\u062A\u0647",
    "\uFCE5"=>"\u062B\u0645",
    "\uFCE6"=>"\u062B\u0647",
    "\uFCE7"=>"\u0633\u0645",
    "\uFCE8"=>"\u0633\u0647",
    "\uFCE9"=>"\u0634\u0645",
    "\uFCEA"=>"\u0634\u0647",
    "\uFCEB"=>"\u0643\u0644",
    "\uFCEC"=>"\u0643\u0645",
    "\uFCED"=>"\u0644\u0645",
    "\uFCEE"=>"\u0646\u0645",
    "\uFCEF"=>"\u0646\u0647",
    "\uFCF0"=>"\u064A\u0645",
    "\uFCF1"=>"\u064A\u0647",
    "\uFCF2"=>"\u0640\u064E\u0651",
    "\uFCF3"=>"\u0640\u064F\u0651",
    "\uFCF4"=>"\u0640\u0650\u0651",
    "\uFCF5"=>"\u0637\u0649",
    "\uFCF6"=>"\u0637\u064A",
    "\uFCF7"=>"\u0639\u0649",
    "\uFCF8"=>"\u0639\u064A",
    "\uFCF9"=>"\u063A\u0649",
    "\uFCFA"=>"\u063A\u064A",
    "\uFCFB"=>"\u0633\u0649",
    "\uFCFC"=>"\u0633\u064A",
    "\uFCFD"=>"\u0634\u0649",
    "\uFCFE"=>"\u0634\u064A",
    "\uFCFF"=>"\u062D\u0649",
    "\uFD00"=>"\u062D\u064A",
    "\uFD01"=>"\u062C\u0649",
    "\uFD02"=>"\u062C\u064A",
    "\uFD03"=>"\u062E\u0649",
    "\uFD04"=>"\u062E\u064A",
    "\uFD05"=>"\u0635\u0649",
    "\uFD06"=>"\u0635\u064A",
    "\uFD07"=>"\u0636\u0649",
    "\uFD08"=>"\u0636\u064A",
    "\uFD09"=>"\u0634\u062C",
    "\uFD0A"=>"\u0634\u062D",
    "\uFD0B"=>"\u0634\u062E",
    "\uFD0C"=>"\u0634\u0645",
    "\uFD0D"=>"\u0634\u0631",
    "\uFD0E"=>"\u0633\u0631",
    "\uFD0F"=>"\u0635\u0631",
    "\uFD10"=>"\u0636\u0631",
    "\uFD11"=>"\u0637\u0649",
    "\uFD12"=>"\u0637\u064A",
    "\uFD13"=>"\u0639\u0649",
    "\uFD14"=>"\u0639\u064A",
    "\uFD15"=>"\u063A\u0649",
    "\uFD16"=>"\u063A\u064A",
    "\uFD17"=>"\u0633\u0649",
    "\uFD18"=>"\u0633\u064A",
    "\uFD19"=>"\u0634\u0649",
    "\uFD1A"=>"\u0634\u064A",
    "\uFD1B"=>"\u062D\u0649",
    "\uFD1C"=>"\u062D\u064A",
    "\uFD1D"=>"\u062C\u0649",
    "\uFD1E"=>"\u062C\u064A",
    "\uFD1F"=>"\u062E\u0649",
    "\uFD20"=>"\u062E\u064A",
    "\uFD21"=>"\u0635\u0649",
    "\uFD22"=>"\u0635\u064A",
    "\uFD23"=>"\u0636\u0649",
    "\uFD24"=>"\u0636\u064A",
    "\uFD25"=>"\u0634\u062C",
    "\uFD26"=>"\u0634\u062D",
    "\uFD27"=>"\u0634\u062E",
    "\uFD28"=>"\u0634\u0645",
    "\uFD29"=>"\u0634\u0631",
    "\uFD2A"=>"\u0633\u0631",
    "\uFD2B"=>"\u0635\u0631",
    "\uFD2C"=>"\u0636\u0631",
    "\uFD2D"=>"\u0634\u062C",
    "\uFD2E"=>"\u0634\u062D",
    "\uFD2F"=>"\u0634\u062E",
    "\uFD30"=>"\u0634\u0645",
    "\uFD31"=>"\u0633\u0647",
    "\uFD32"=>"\u0634\u0647",
    "\uFD33"=>"\u0637\u0645",
    "\uFD34"=>"\u0633\u062C",
    "\uFD35"=>"\u0633\u062D",
    "\uFD36"=>"\u0633\u062E",
    "\uFD37"=>"\u0634\u062C",
    "\uFD38"=>"\u0634\u062D",
    "\uFD39"=>"\u0634\u062E",
    "\uFD3A"=>"\u0637\u0645",
    "\uFD3B"=>"\u0638\u0645",
    "\uFD3C"=>"\u0627\u064B",
    "\uFD3D"=>"\u0627\u064B",
    "\uFD50"=>"\u062A\u062C\u0645",
    "\uFD51"=>"\u062A\u062D\u062C",
    "\uFD52"=>"\u062A\u062D\u062C",
    "\uFD53"=>"\u062A\u062D\u0645",
    "\uFD54"=>"\u062A\u062E\u0645",
    "\uFD55"=>"\u062A\u0645\u062C",
    "\uFD56"=>"\u062A\u0645\u062D",
    "\uFD57"=>"\u062A\u0645\u062E",
    "\uFD58"=>"\u062C\u0645\u062D",
    "\uFD59"=>"\u062C\u0645\u062D",
    "\uFD5A"=>"\u062D\u0645\u064A",
    "\uFD5B"=>"\u062D\u0645\u0649",
    "\uFD5C"=>"\u0633\u062D\u062C",
    "\uFD5D"=>"\u0633\u062C\u062D",
    "\uFD5E"=>"\u0633\u062C\u0649",
    "\uFD5F"=>"\u0633\u0645\u062D",
    "\uFD60"=>"\u0633\u0645\u062D",
    "\uFD61"=>"\u0633\u0645\u062C",
    "\uFD62"=>"\u0633\u0645\u0645",
    "\uFD63"=>"\u0633\u0645\u0645",
    "\uFD64"=>"\u0635\u062D\u062D",
    "\uFD65"=>"\u0635\u062D\u062D",
    "\uFD66"=>"\u0635\u0645\u0645",
    "\uFD67"=>"\u0634\u062D\u0645",
    "\uFD68"=>"\u0634\u062D\u0645",
    "\uFD69"=>"\u0634\u062C\u064A",
    "\uFD6A"=>"\u0634\u0645\u062E",
    "\uFD6B"=>"\u0634\u0645\u062E",
    "\uFD6C"=>"\u0634\u0645\u0645",
    "\uFD6D"=>"\u0634\u0645\u0645",
    "\uFD6E"=>"\u0636\u062D\u0649",
    "\uFD6F"=>"\u0636\u062E\u0645",
    "\uFD70"=>"\u0636\u062E\u0645",
    "\uFD71"=>"\u0637\u0645\u062D",
    "\uFD72"=>"\u0637\u0645\u062D",
    "\uFD73"=>"\u0637\u0645\u0645",
    "\uFD74"=>"\u0637\u0645\u064A",
    "\uFD75"=>"\u0639\u062C\u0645",
    "\uFD76"=>"\u0639\u0645\u0645",
    "\uFD77"=>"\u0639\u0645\u0645",
    "\uFD78"=>"\u0639\u0645\u0649",
    "\uFD79"=>"\u063A\u0645\u0645",
    "\uFD7A"=>"\u063A\u0645\u064A",
    "\uFD7B"=>"\u063A\u0645\u0649",
    "\uFD7C"=>"\u0641\u062E\u0645",
    "\uFD7D"=>"\u0641\u062E\u0645",
    "\uFD7E"=>"\u0642\u0645\u062D",
    "\uFD7F"=>"\u0642\u0645\u0645",
    "\uFD80"=>"\u0644\u062D\u0645",
    "\uFD81"=>"\u0644\u062D\u064A",
    "\uFD82"=>"\u0644\u062D\u0649",
    "\uFD83"=>"\u0644\u062C\u062C",
    "\uFD84"=>"\u0644\u062C\u062C",
    "\uFD85"=>"\u0644\u062E\u0645",
    "\uFD86"=>"\u0644\u062E\u0645",
    "\uFD87"=>"\u0644\u0645\u062D",
    "\uFD88"=>"\u0644\u0645\u062D",
    "\uFD89"=>"\u0645\u062D\u062C",
    "\uFD8A"=>"\u0645\u062D\u0645",
    "\uFD8B"=>"\u0645\u062D\u064A",
    "\uFD8C"=>"\u0645\u062C\u062D",
    "\uFD8D"=>"\u0645\u062C\u0645",
    "\uFD8E"=>"\u0645\u062E\u062C",
    "\uFD8F"=>"\u0645\u062E\u0645",
    "\uFD92"=>"\u0645\u062C\u062E",
    "\uFD93"=>"\u0647\u0645\u062C",
    "\uFD94"=>"\u0647\u0645\u0645",
    "\uFD95"=>"\u0646\u062D\u0645",
    "\uFD96"=>"\u0646\u062D\u0649",
    "\uFD97"=>"\u0646\u062C\u0645",
    "\uFD98"=>"\u0646\u062C\u0645",
    "\uFD99"=>"\u0646\u062C\u0649",
    "\uFD9A"=>"\u0646\u0645\u064A",
    "\uFD9B"=>"\u0646\u0645\u0649",
    "\uFD9C"=>"\u064A\u0645\u0645",
    "\uFD9D"=>"\u064A\u0645\u0645",
    "\uFD9E"=>"\u0628\u062E\u064A",
    "\uFD9F"=>"\u062A\u062C\u064A",
    "\uFDA0"=>"\u062A\u062C\u0649",
    "\uFDA1"=>"\u062A\u062E\u064A",
    "\uFDA2"=>"\u062A\u062E\u0649",
    "\uFDA3"=>"\u062A\u0645\u064A",
    "\uFDA4"=>"\u062A\u0645\u0649",
    "\uFDA5"=>"\u062C\u0645\u064A",
    "\uFDA6"=>"\u062C\u062D\u0649",
    "\uFDA7"=>"\u062C\u0645\u0649",
    "\uFDA8"=>"\u0633\u062E\u0649",
    "\uFDA9"=>"\u0635\u062D\u064A",
    "\uFDAA"=>"\u0634\u062D\u064A",
    "\uFDAB"=>"\u0636\u062D\u064A",
    "\uFDAC"=>"\u0644\u062C\u064A",
    "\uFDAD"=>"\u0644\u0645\u064A",
    "\uFDAE"=>"\u064A\u062D\u064A",
    "\uFDAF"=>"\u064A\u062C\u064A",
    "\uFDB0"=>"\u064A\u0645\u064A",
    "\uFDB1"=>"\u0645\u0645\u064A",
    "\uFDB2"=>"\u0642\u0645\u064A",
    "\uFDB3"=>"\u0646\u062D\u064A",
    "\uFDB4"=>"\u0642\u0645\u062D",
    "\uFDB5"=>"\u0644\u062D\u0645",
    "\uFDB6"=>"\u0639\u0645\u064A",
    "\uFDB7"=>"\u0643\u0645\u064A",
    "\uFDB8"=>"\u0646\u062C\u062D",
    "\uFDB9"=>"\u0645\u062E\u064A",
    "\uFDBA"=>"\u0644\u062C\u0645",
    "\uFDBB"=>"\u0643\u0645\u0645",
    "\uFDBC"=>"\u0644\u062C\u0645",
    "\uFDBD"=>"\u0646\u062C\u062D",
    "\uFDBE"=>"\u062C\u062D\u064A",
    "\uFDBF"=>"\u062D\u062C\u064A",
    "\uFDC0"=>"\u0645\u062C\u064A",
    "\uFDC1"=>"\u0641\u0645\u064A",
    "\uFDC2"=>"\u0628\u062D\u064A",
    "\uFDC3"=>"\u0643\u0645\u0645",
    "\uFDC4"=>"\u0639\u062C\u0645",
    "\uFDC5"=>"\u0635\u0645\u0645",
    "\uFDC6"=>"\u0633\u062E\u064A",
    "\uFDC7"=>"\u0646\u062C\u064A",
    "\uFDF0"=>"\u0635\u0644\u06D2",
    "\uFDF1"=>"\u0642\u0644\u06D2",
    "\uFDF2"=>"\u0627\u0644\u0644\u0647",
    "\uFDF3"=>"\u0627\u0643\u0628\u0631",
    "\uFDF4"=>"\u0645\u062D\u0645\u062F",
    "\uFDF5"=>"\u0635\u0644\u0639\u0645",
    "\uFDF6"=>"\u0631\u0633\u0648\u0644",
    "\uFDF7"=>"\u0639\u0644\u064A\u0647",
    "\uFDF8"=>"\u0648\u0633\u0644\u0645",
    "\uFDF9"=>"\u0635\u0644\u0649",
    "\uFDFA"=>"\u0635\u0644\u0649 \u0627\u0644\u0644\u0647 \u0639\u0644\u064A\u0647 \u0648\u0633\u0644\u0645",
    "\uFDFB"=>"\u062C\u0644 \u062C\u0644\u0627\u0644\u0647",
    "\uFDFC"=>"\u0631\u06CC\u0627\u0644",
    "\uFE10"=>",",
    "\uFE11"=>"\u3001",
    "\uFE12"=>"\u3002",
    "\uFE13"=>":",
    "\uFE14"=>";",
    "\uFE15"=>"!",
    "\uFE16"=>"?",
    "\uFE17"=>"\u3016",
    "\uFE18"=>"\u3017",
    "\uFE19"=>"...",
    "\uFE30"=>"..",
    "\uFE31"=>"\u2014",
    "\uFE32"=>"\u2013",
    "\uFE33"=>"_",
    "\uFE34"=>"_",
    "\uFE35"=>"(",
    "\uFE36"=>")",
    "\uFE37"=>"{",
    "\uFE38"=>"}",
    "\uFE39"=>"\u3014",
    "\uFE3A"=>"\u3015",
    "\uFE3B"=>"\u3010",
    "\uFE3C"=>"\u3011",
    "\uFE3D"=>"\u300A",
    "\uFE3E"=>"\u300B",
    "\uFE3F"=>"\u3008",
    "\uFE40"=>"\u3009",
    "\uFE41"=>"\u300C",
    "\uFE42"=>"\u300D",
    "\uFE43"=>"\u300E",
    "\uFE44"=>"\u300F",
    "\uFE47"=>"[",
    "\uFE48"=>"]",
    "\uFE49"=>" \u0305",
    "\uFE4A"=>" \u0305",
    "\uFE4B"=>" \u0305",
    "\uFE4C"=>" \u0305",
    "\uFE4D"=>"_",
    "\uFE4E"=>"_",
    "\uFE4F"=>"_",
    "\uFE50"=>",",
    "\uFE51"=>"\u3001",
    "\uFE52"=>".",
    "\uFE54"=>";",
    "\uFE55"=>":",
    "\uFE56"=>"?",
    "\uFE57"=>"!",
    "\uFE58"=>"\u2014",
    "\uFE59"=>"(",
    "\uFE5A"=>")",
    "\uFE5B"=>"{",
    "\uFE5C"=>"}",
    "\uFE5D"=>"\u3014",
    "\uFE5E"=>"\u3015",
    "\uFE5F"=>"#",
    "\uFE60"=>"&",
    "\uFE61"=>"*",
    "\uFE62"=>"+",
    "\uFE63"=>"-",
    "\uFE64"=>"<",
    "\uFE65"=>">",
    "\uFE66"=>"=",
    "\uFE68"=>"\\",
    "\uFE69"=>"$",
    "\uFE6A"=>"%",
    "\uFE6B"=>"@",
    "\uFE70"=>" \u064B",
    "\uFE71"=>"\u0640\u064B",
    "\uFE72"=>" \u064C",
    "\uFE74"=>" \u064D",
    "\uFE76"=>" \u064E",
    "\uFE77"=>"\u0640\u064E",
    "\uFE78"=>" \u064F",
    "\uFE79"=>"\u0640\u064F",
    "\uFE7A"=>" \u0650",
    "\uFE7B"=>"\u0640\u0650",
    "\uFE7C"=>" \u0651",
    "\uFE7D"=>"\u0640\u0651",
    "\uFE7E"=>" \u0652",
    "\uFE7F"=>"\u0640\u0652",
    "\uFE80"=>"\u0621",
    "\uFE81"=>"\u0622",
    "\uFE82"=>"\u0622",
    "\uFE83"=>"\u0623",
    "\uFE84"=>"\u0623",
    "\uFE85"=>"\u0624",
    "\uFE86"=>"\u0624",
    "\uFE87"=>"\u0625",
    "\uFE88"=>"\u0625",
    "\uFE89"=>"\u0626",
    "\uFE8A"=>"\u0626",
    "\uFE8B"=>"\u0626",
    "\uFE8C"=>"\u0626",
    "\uFE8D"=>"\u0627",
    "\uFE8E"=>"\u0627",
    "\uFE8F"=>"\u0628",
    "\uFE90"=>"\u0628",
    "\uFE91"=>"\u0628",
    "\uFE92"=>"\u0628",
    "\uFE93"=>"\u0629",
    "\uFE94"=>"\u0629",
    "\uFE95"=>"\u062A",
    "\uFE96"=>"\u062A",
    "\uFE97"=>"\u062A",
    "\uFE98"=>"\u062A",
    "\uFE99"=>"\u062B",
    "\uFE9A"=>"\u062B",
    "\uFE9B"=>"\u062B",
    "\uFE9C"=>"\u062B",
    "\uFE9D"=>"\u062C",
    "\uFE9E"=>"\u062C",
    "\uFE9F"=>"\u062C",
    "\uFEA0"=>"\u062C",
    "\uFEA1"=>"\u062D",
    "\uFEA2"=>"\u062D",
    "\uFEA3"=>"\u062D",
    "\uFEA4"=>"\u062D",
    "\uFEA5"=>"\u062E",
    "\uFEA6"=>"\u062E",
    "\uFEA7"=>"\u062E",
    "\uFEA8"=>"\u062E",
    "\uFEA9"=>"\u062F",
    "\uFEAA"=>"\u062F",
    "\uFEAB"=>"\u0630",
    "\uFEAC"=>"\u0630",
    "\uFEAD"=>"\u0631",
    "\uFEAE"=>"\u0631",
    "\uFEAF"=>"\u0632",
    "\uFEB0"=>"\u0632",
    "\uFEB1"=>"\u0633",
    "\uFEB2"=>"\u0633",
    "\uFEB3"=>"\u0633",
    "\uFEB4"=>"\u0633",
    "\uFEB5"=>"\u0634",
    "\uFEB6"=>"\u0634",
    "\uFEB7"=>"\u0634",
    "\uFEB8"=>"\u0634",
    "\uFEB9"=>"\u0635",
    "\uFEBA"=>"\u0635",
    "\uFEBB"=>"\u0635",
    "\uFEBC"=>"\u0635",
    "\uFEBD"=>"\u0636",
    "\uFEBE"=>"\u0636",
    "\uFEBF"=>"\u0636",
    "\uFEC0"=>"\u0636",
    "\uFEC1"=>"\u0637",
    "\uFEC2"=>"\u0637",
    "\uFEC3"=>"\u0637",
    "\uFEC4"=>"\u0637",
    "\uFEC5"=>"\u0638",
    "\uFEC6"=>"\u0638",
    "\uFEC7"=>"\u0638",
    "\uFEC8"=>"\u0638",
    "\uFEC9"=>"\u0639",
    "\uFECA"=>"\u0639",
    "\uFECB"=>"\u0639",
    "\uFECC"=>"\u0639",
    "\uFECD"=>"\u063A",
    "\uFECE"=>"\u063A",
    "\uFECF"=>"\u063A",
    "\uFED0"=>"\u063A",
    "\uFED1"=>"\u0641",
    "\uFED2"=>"\u0641",
    "\uFED3"=>"\u0641",
    "\uFED4"=>"\u0641",
    "\uFED5"=>"\u0642",
    "\uFED6"=>"\u0642",
    "\uFED7"=>"\u0642",
    "\uFED8"=>"\u0642",
    "\uFED9"=>"\u0643",
    "\uFEDA"=>"\u0643",
    "\uFEDB"=>"\u0643",
    "\uFEDC"=>"\u0643",
    "\uFEDD"=>"\u0644",
    "\uFEDE"=>"\u0644",
    "\uFEDF"=>"\u0644",
    "\uFEE0"=>"\u0644",
    "\uFEE1"=>"\u0645",
    "\uFEE2"=>"\u0645",
    "\uFEE3"=>"\u0645",
    "\uFEE4"=>"\u0645",
    "\uFEE5"=>"\u0646",
    "\uFEE6"=>"\u0646",
    "\uFEE7"=>"\u0646",
    "\uFEE8"=>"\u0646",
    "\uFEE9"=>"\u0647",
    "\uFEEA"=>"\u0647",
    "\uFEEB"=>"\u0647",
    "\uFEEC"=>"\u0647",
    "\uFEED"=>"\u0648",
    "\uFEEE"=>"\u0648",
    "\uFEEF"=>"\u0649",
    "\uFEF0"=>"\u0649",
    "\uFEF1"=>"\u064A",
    "\uFEF2"=>"\u064A",
    "\uFEF3"=>"\u064A",
    "\uFEF4"=>"\u064A",
    "\uFEF5"=>"\u0644\u0622",
    "\uFEF6"=>"\u0644\u0622",
    "\uFEF7"=>"\u0644\u0623",
    "\uFEF8"=>"\u0644\u0623",
    "\uFEF9"=>"\u0644\u0625",
    "\uFEFA"=>"\u0644\u0625",
    "\uFEFB"=>"\u0644\u0627",
    "\uFEFC"=>"\u0644\u0627",
    "\uFF01"=>"!",
    "\uFF02"=>"\"",
    "\uFF03"=>"#",
    "\uFF04"=>"$",
    "\uFF05"=>"%",
    "\uFF06"=>"&",
    "\uFF07"=>"'",
    "\uFF08"=>"(",
    "\uFF09"=>")",
    "\uFF0A"=>"*",
    "\uFF0B"=>"+",
    "\uFF0C"=>",",
    "\uFF0D"=>"-",
    "\uFF0E"=>".",
    "\uFF0F"=>"/",
    "\uFF10"=>"0",
    "\uFF11"=>"1",
    "\uFF12"=>"2",
    "\uFF13"=>"3",
    "\uFF14"=>"4",
    "\uFF15"=>"5",
    "\uFF16"=>"6",
    "\uFF17"=>"7",
    "\uFF18"=>"8",
    "\uFF19"=>"9",
    "\uFF1A"=>":",
    "\uFF1B"=>";",
    "\uFF1C"=>"<",
    "\uFF1D"=>"=",
    "\uFF1E"=>">",
    "\uFF1F"=>"?",
    "\uFF20"=>"@",
    "\uFF21"=>"A",
    "\uFF22"=>"B",
    "\uFF23"=>"C",
    "\uFF24"=>"D",
    "\uFF25"=>"E",
    "\uFF26"=>"F",
    "\uFF27"=>"G",
    "\uFF28"=>"H",
    "\uFF29"=>"I",
    "\uFF2A"=>"J",
    "\uFF2B"=>"K",
    "\uFF2C"=>"L",
    "\uFF2D"=>"M",
    "\uFF2E"=>"N",
    "\uFF2F"=>"O",
    "\uFF30"=>"P",
    "\uFF31"=>"Q",
    "\uFF32"=>"R",
    "\uFF33"=>"S",
    "\uFF34"=>"T",
    "\uFF35"=>"U",
    "\uFF36"=>"V",
    "\uFF37"=>"W",
    "\uFF38"=>"X",
    "\uFF39"=>"Y",
    "\uFF3A"=>"Z",
    "\uFF3B"=>"[",
    "\uFF3C"=>"\\",
    "\uFF3D"=>"]",
    "\uFF3E"=>"^",
    "\uFF3F"=>"_",
    "\uFF40"=>"`",
    "\uFF41"=>"a",
    "\uFF42"=>"b",
    "\uFF43"=>"c",
    "\uFF44"=>"d",
    "\uFF45"=>"e",
    "\uFF46"=>"f",
    "\uFF47"=>"g",
    "\uFF48"=>"h",
    "\uFF49"=>"i",
    "\uFF4A"=>"j",
    "\uFF4B"=>"k",
    "\uFF4C"=>"l",
    "\uFF4D"=>"m",
    "\uFF4E"=>"n",
    "\uFF4F"=>"o",
    "\uFF50"=>"p",
    "\uFF51"=>"q",
    "\uFF52"=>"r",
    "\uFF53"=>"s",
    "\uFF54"=>"t",
    "\uFF55"=>"u",
    "\uFF56"=>"v",
    "\uFF57"=>"w",
    "\uFF58"=>"x",
    "\uFF59"=>"y",
    "\uFF5A"=>"z",
    "\uFF5B"=>"{",
    "\uFF5C"=>"|",
    "\uFF5D"=>"}",
    "\uFF5E"=>"~",
    "\uFF5F"=>"\u2985",
    "\uFF60"=>"\u2986",
    "\uFF61"=>"\u3002",
    "\uFF62"=>"\u300C",
    "\uFF63"=>"\u300D",
    "\uFF64"=>"\u3001",
    "\uFF65"=>"\u30FB",
    "\uFF66"=>"\u30F2",
    "\uFF67"=>"\u30A1",
    "\uFF68"=>"\u30A3",
    "\uFF69"=>"\u30A5",
    "\uFF6A"=>"\u30A7",
    "\uFF6B"=>"\u30A9",
    "\uFF6C"=>"\u30E3",
    "\uFF6D"=>"\u30E5",
    "\uFF6E"=>"\u30E7",
    "\uFF6F"=>"\u30C3",
    "\uFF70"=>"\u30FC",
    "\uFF71"=>"\u30A2",
    "\uFF72"=>"\u30A4",
    "\uFF73"=>"\u30A6",
    "\uFF74"=>"\u30A8",
    "\uFF75"=>"\u30AA",
    "\uFF76"=>"\u30AB",
    "\uFF77"=>"\u30AD",
    "\uFF78"=>"\u30AF",
    "\uFF79"=>"\u30B1",
    "\uFF7A"=>"\u30B3",
    "\uFF7B"=>"\u30B5",
    "\uFF7C"=>"\u30B7",
    "\uFF7D"=>"\u30B9",
    "\uFF7E"=>"\u30BB",
    "\uFF7F"=>"\u30BD",
    "\uFF80"=>"\u30BF",
    "\uFF81"=>"\u30C1",
    "\uFF82"=>"\u30C4",
    "\uFF83"=>"\u30C6",
    "\uFF84"=>"\u30C8",
    "\uFF85"=>"\u30CA",
    "\uFF86"=>"\u30CB",
    "\uFF87"=>"\u30CC",
    "\uFF88"=>"\u30CD",
    "\uFF89"=>"\u30CE",
    "\uFF8A"=>"\u30CF",
    "\uFF8B"=>"\u30D2",
    "\uFF8C"=>"\u30D5",
    "\uFF8D"=>"\u30D8",
    "\uFF8E"=>"\u30DB",
    "\uFF8F"=>"\u30DE",
    "\uFF90"=>"\u30DF",
    "\uFF91"=>"\u30E0",
    "\uFF92"=>"\u30E1",
    "\uFF93"=>"\u30E2",
    "\uFF94"=>"\u30E4",
    "\uFF95"=>"\u30E6",
    "\uFF96"=>"\u30E8",
    "\uFF97"=>"\u30E9",
    "\uFF98"=>"\u30EA",
    "\uFF99"=>"\u30EB",
    "\uFF9A"=>"\u30EC",
    "\uFF9B"=>"\u30ED",
    "\uFF9C"=>"\u30EF",
    "\uFF9D"=>"\u30F3",
    "\uFF9E"=>"\u3099",
    "\uFF9F"=>"\u309A",
    "\uFFA0"=>"\u1160",
    "\uFFA1"=>"\u1100",
    "\uFFA2"=>"\u1101",
    "\uFFA3"=>"\u11AA",
    "\uFFA4"=>"\u1102",
    "\uFFA5"=>"\u11AC",
    "\uFFA6"=>"\u11AD",
    "\uFFA7"=>"\u1103",
    "\uFFA8"=>"\u1104",
    "\uFFA9"=>"\u1105",
    "\uFFAA"=>"\u11B0",
    "\uFFAB"=>"\u11B1",
    "\uFFAC"=>"\u11B2",
    "\uFFAD"=>"\u11B3",
    "\uFFAE"=>"\u11B4",
    "\uFFAF"=>"\u11B5",
    "\uFFB0"=>"\u111A",
    "\uFFB1"=>"\u1106",
    "\uFFB2"=>"\u1107",
    "\uFFB3"=>"\u1108",
    "\uFFB4"=>"\u1121",
    "\uFFB5"=>"\u1109",
    "\uFFB6"=>"\u110A",
    "\uFFB7"=>"\u110B",
    "\uFFB8"=>"\u110C",
    "\uFFB9"=>"\u110D",
    "\uFFBA"=>"\u110E",
    "\uFFBB"=>"\u110F",
    "\uFFBC"=>"\u1110",
    "\uFFBD"=>"\u1111",
    "\uFFBE"=>"\u1112",
    "\uFFC2"=>"\u1161",
    "\uFFC3"=>"\u1162",
    "\uFFC4"=>"\u1163",
    "\uFFC5"=>"\u1164",
    "\uFFC6"=>"\u1165",
    "\uFFC7"=>"\u1166",
    "\uFFCA"=>"\u1167",
    "\uFFCB"=>"\u1168",
    "\uFFCC"=>"\u1169",
    "\uFFCD"=>"\u116A",
    "\uFFCE"=>"\u116B",
    "\uFFCF"=>"\u116C",
    "\uFFD2"=>"\u116D",
    "\uFFD3"=>"\u116E",
    "\uFFD4"=>"\u116F",
    "\uFFD5"=>"\u1170",
    "\uFFD6"=>"\u1171",
    "\uFFD7"=>"\u1172",
    "\uFFDA"=>"\u1173",
    "\uFFDB"=>"\u1174",
    "\uFFDC"=>"\u1175",
    "\uFFE0"=>"\u00A2",
    "\uFFE1"=>"\u00A3",
    "\uFFE2"=>"\u00AC",
    "\uFFE3"=>" \u0304",
    "\uFFE4"=>"\u00A6",
    "\uFFE5"=>"\u00A5",
    "\uFFE6"=>"\u20A9",
    "\uFFE8"=>"\u2502",
    "\uFFE9"=>"\u2190",
    "\uFFEA"=>"\u2191",
    "\uFFEB"=>"\u2192",
    "\uFFEC"=>"\u2193",
    "\uFFED"=>"\u25A0",
    "\uFFEE"=>"\u25CB",
    "\u{1D400}"=>"A",
    "\u{1D401}"=>"B",
    "\u{1D402}"=>"C",
    "\u{1D403}"=>"D",
    "\u{1D404}"=>"E",
    "\u{1D405}"=>"F",
    "\u{1D406}"=>"G",
    "\u{1D407}"=>"H",
    "\u{1D408}"=>"I",
    "\u{1D409}"=>"J",
    "\u{1D40A}"=>"K",
    "\u{1D40B}"=>"L",
    "\u{1D40C}"=>"M",
    "\u{1D40D}"=>"N",
    "\u{1D40E}"=>"O",
    "\u{1D40F}"=>"P",
    "\u{1D410}"=>"Q",
    "\u{1D411}"=>"R",
    "\u{1D412}"=>"S",
    "\u{1D413}"=>"T",
    "\u{1D414}"=>"U",
    "\u{1D415}"=>"V",
    "\u{1D416}"=>"W",
    "\u{1D417}"=>"X",
    "\u{1D418}"=>"Y",
    "\u{1D419}"=>"Z",
    "\u{1D41A}"=>"a",
    "\u{1D41B}"=>"b",
    "\u{1D41C}"=>"c",
    "\u{1D41D}"=>"d",
    "\u{1D41E}"=>"e",
    "\u{1D41F}"=>"f",
    "\u{1D420}"=>"g",
    "\u{1D421}"=>"h",
    "\u{1D422}"=>"i",
    "\u{1D423}"=>"j",
    "\u{1D424}"=>"k",
    "\u{1D425}"=>"l",
    "\u{1D426}"=>"m",
    "\u{1D427}"=>"n",
    "\u{1D428}"=>"o",
    "\u{1D429}"=>"p",
    "\u{1D42A}"=>"q",
    "\u{1D42B}"=>"r",
    "\u{1D42C}"=>"s",
    "\u{1D42D}"=>"t",
    "\u{1D42E}"=>"u",
    "\u{1D42F}"=>"v",
    "\u{1D430}"=>"w",
    "\u{1D431}"=>"x",
    "\u{1D432}"=>"y",
    "\u{1D433}"=>"z",
    "\u{1D434}"=>"A",
    "\u{1D435}"=>"B",
    "\u{1D436}"=>"C",
    "\u{1D437}"=>"D",
    "\u{1D438}"=>"E",
    "\u{1D439}"=>"F",
    "\u{1D43A}"=>"G",
    "\u{1D43B}"=>"H",
    "\u{1D43C}"=>"I",
    "\u{1D43D}"=>"J",
    "\u{1D43E}"=>"K",
    "\u{1D43F}"=>"L",
    "\u{1D440}"=>"M",
    "\u{1D441}"=>"N",
    "\u{1D442}"=>"O",
    "\u{1D443}"=>"P",
    "\u{1D444}"=>"Q",
    "\u{1D445}"=>"R",
    "\u{1D446}"=>"S",
    "\u{1D447}"=>"T",
    "\u{1D448}"=>"U",
    "\u{1D449}"=>"V",
    "\u{1D44A}"=>"W",
    "\u{1D44B}"=>"X",
    "\u{1D44C}"=>"Y",
    "\u{1D44D}"=>"Z",
    "\u{1D44E}"=>"a",
    "\u{1D44F}"=>"b",
    "\u{1D450}"=>"c",
    "\u{1D451}"=>"d",
    "\u{1D452}"=>"e",
    "\u{1D453}"=>"f",
    "\u{1D454}"=>"g",
    "\u{1D456}"=>"i",
    "\u{1D457}"=>"j",
    "\u{1D458}"=>"k",
    "\u{1D459}"=>"l",
    "\u{1D45A}"=>"m",
    "\u{1D45B}"=>"n",
    "\u{1D45C}"=>"o",
    "\u{1D45D}"=>"p",
    "\u{1D45E}"=>"q",
    "\u{1D45F}"=>"r",
    "\u{1D460}"=>"s",
    "\u{1D461}"=>"t",
    "\u{1D462}"=>"u",
    "\u{1D463}"=>"v",
    "\u{1D464}"=>"w",
    "\u{1D465}"=>"x",
    "\u{1D466}"=>"y",
    "\u{1D467}"=>"z",
    "\u{1D468}"=>"A",
    "\u{1D469}"=>"B",
    "\u{1D46A}"=>"C",
    "\u{1D46B}"=>"D",
    "\u{1D46C}"=>"E",
    "\u{1D46D}"=>"F",
    "\u{1D46E}"=>"G",
    "\u{1D46F}"=>"H",
    "\u{1D470}"=>"I",
    "\u{1D471}"=>"J",
    "\u{1D472}"=>"K",
    "\u{1D473}"=>"L",
    "\u{1D474}"=>"M",
    "\u{1D475}"=>"N",
    "\u{1D476}"=>"O",
    "\u{1D477}"=>"P",
    "\u{1D478}"=>"Q",
    "\u{1D479}"=>"R",
    "\u{1D47A}"=>"S",
    "\u{1D47B}"=>"T",
    "\u{1D47C}"=>"U",
    "\u{1D47D}"=>"V",
    "\u{1D47E}"=>"W",
    "\u{1D47F}"=>"X",
    "\u{1D480}"=>"Y",
    "\u{1D481}"=>"Z",
    "\u{1D482}"=>"a",
    "\u{1D483}"=>"b",
    "\u{1D484}"=>"c",
    "\u{1D485}"=>"d",
    "\u{1D486}"=>"e",
    "\u{1D487}"=>"f",
    "\u{1D488}"=>"g",
    "\u{1D489}"=>"h",
    "\u{1D48A}"=>"i",
    "\u{1D48B}"=>"j",
    "\u{1D48C}"=>"k",
    "\u{1D48D}"=>"l",
    "\u{1D48E}"=>"m",
    "\u{1D48F}"=>"n",
    "\u{1D490}"=>"o",
    "\u{1D491}"=>"p",
    "\u{1D492}"=>"q",
    "\u{1D493}"=>"r",
    "\u{1D494}"=>"s",
    "\u{1D495}"=>"t",
    "\u{1D496}"=>"u",
    "\u{1D497}"=>"v",
    "\u{1D498}"=>"w",
    "\u{1D499}"=>"x",
    "\u{1D49A}"=>"y",
    "\u{1D49B}"=>"z",
    "\u{1D49C}"=>"A",
    "\u{1D49E}"=>"C",
    "\u{1D49F}"=>"D",
    "\u{1D4A2}"=>"G",
    "\u{1D4A5}"=>"J",
    "\u{1D4A6}"=>"K",
    "\u{1D4A9}"=>"N",
    "\u{1D4AA}"=>"O",
    "\u{1D4AB}"=>"P",
    "\u{1D4AC}"=>"Q",
    "\u{1D4AE}"=>"S",
    "\u{1D4AF}"=>"T",
    "\u{1D4B0}"=>"U",
    "\u{1D4B1}"=>"V",
    "\u{1D4B2}"=>"W",
    "\u{1D4B3}"=>"X",
    "\u{1D4B4}"=>"Y",
    "\u{1D4B5}"=>"Z",
    "\u{1D4B6}"=>"a",
    "\u{1D4B7}"=>"b",
    "\u{1D4B8}"=>"c",
    "\u{1D4B9}"=>"d",
    "\u{1D4BB}"=>"f",
    "\u{1D4BD}"=>"h",
    "\u{1D4BE}"=>"i",
    "\u{1D4BF}"=>"j",
    "\u{1D4C0}"=>"k",
    "\u{1D4C1}"=>"l",
    "\u{1D4C2}"=>"m",
    "\u{1D4C3}"=>"n",
    "\u{1D4C5}"=>"p",
    "\u{1D4C6}"=>"q",
    "\u{1D4C7}"=>"r",
    "\u{1D4C8}"=>"s",
    "\u{1D4C9}"=>"t",
    "\u{1D4CA}"=>"u",
    "\u{1D4CB}"=>"v",
    "\u{1D4CC}"=>"w",
    "\u{1D4CD}"=>"x",
    "\u{1D4CE}"=>"y",
    "\u{1D4CF}"=>"z",
    "\u{1D4D0}"=>"A",
    "\u{1D4D1}"=>"B",
    "\u{1D4D2}"=>"C",
    "\u{1D4D3}"=>"D",
    "\u{1D4D4}"=>"E",
    "\u{1D4D5}"=>"F",
    "\u{1D4D6}"=>"G",
    "\u{1D4D7}"=>"H",
    "\u{1D4D8}"=>"I",
    "\u{1D4D9}"=>"J",
    "\u{1D4DA}"=>"K",
    "\u{1D4DB}"=>"L",
    "\u{1D4DC}"=>"M",
    "\u{1D4DD}"=>"N",
    "\u{1D4DE}"=>"O",
    "\u{1D4DF}"=>"P",
    "\u{1D4E0}"=>"Q",
    "\u{1D4E1}"=>"R",
    "\u{1D4E2}"=>"S",
    "\u{1D4E3}"=>"T",
    "\u{1D4E4}"=>"U",
    "\u{1D4E5}"=>"V",
    "\u{1D4E6}"=>"W",
    "\u{1D4E7}"=>"X",
    "\u{1D4E8}"=>"Y",
    "\u{1D4E9}"=>"Z",
    "\u{1D4EA}"=>"a",
    "\u{1D4EB}"=>"b",
    "\u{1D4EC}"=>"c",
    "\u{1D4ED}"=>"d",
    "\u{1D4EE}"=>"e",
    "\u{1D4EF}"=>"f",
    "\u{1D4F0}"=>"g",
    "\u{1D4F1}"=>"h",
    "\u{1D4F2}"=>"i",
    "\u{1D4F3}"=>"j",
    "\u{1D4F4}"=>"k",
    "\u{1D4F5}"=>"l",
    "\u{1D4F6}"=>"m",
    "\u{1D4F7}"=>"n",
    "\u{1D4F8}"=>"o",
    "\u{1D4F9}"=>"p",
    "\u{1D4FA}"=>"q",
    "\u{1D4FB}"=>"r",
    "\u{1D4FC}"=>"s",
    "\u{1D4FD}"=>"t",
    "\u{1D4FE}"=>"u",
    "\u{1D4FF}"=>"v",
    "\u{1D500}"=>"w",
    "\u{1D501}"=>"x",
    "\u{1D502}"=>"y",
    "\u{1D503}"=>"z",
    "\u{1D504}"=>"A",
    "\u{1D505}"=>"B",
    "\u{1D507}"=>"D",
    "\u{1D508}"=>"E",
    "\u{1D509}"=>"F",
    "\u{1D50A}"=>"G",
    "\u{1D50D}"=>"J",
    "\u{1D50E}"=>"K",
    "\u{1D50F}"=>"L",
    "\u{1D510}"=>"M",
    "\u{1D511}"=>"N",
    "\u{1D512}"=>"O",
    "\u{1D513}"=>"P",
    "\u{1D514}"=>"Q",
    "\u{1D516}"=>"S",
    "\u{1D517}"=>"T",
    "\u{1D518}"=>"U",
    "\u{1D519}"=>"V",
    "\u{1D51A}"=>"W",
    "\u{1D51B}"=>"X",
    "\u{1D51C}"=>"Y",
    "\u{1D51E}"=>"a",
    "\u{1D51F}"=>"b",
    "\u{1D520}"=>"c",
    "\u{1D521}"=>"d",
    "\u{1D522}"=>"e",
    "\u{1D523}"=>"f",
    "\u{1D524}"=>"g",
    "\u{1D525}"=>"h",
    "\u{1D526}"=>"i",
    "\u{1D527}"=>"j",
    "\u{1D528}"=>"k",
    "\u{1D529}"=>"l",
    "\u{1D52A}"=>"m",
    "\u{1D52B}"=>"n",
    "\u{1D52C}"=>"o",
    "\u{1D52D}"=>"p",
    "\u{1D52E}"=>"q",
    "\u{1D52F}"=>"r",
    "\u{1D530}"=>"s",
    "\u{1D531}"=>"t",
    "\u{1D532}"=>"u",
    "\u{1D533}"=>"v",
    "\u{1D534}"=>"w",
    "\u{1D535}"=>"x",
    "\u{1D536}"=>"y",
    "\u{1D537}"=>"z",
    "\u{1D538}"=>"A",
    "\u{1D539}"=>"B",
    "\u{1D53B}"=>"D",
    "\u{1D53C}"=>"E",
    "\u{1D53D}"=>"F",
    "\u{1D53E}"=>"G",
    "\u{1D540}"=>"I",
    "\u{1D541}"=>"J",
    "\u{1D542}"=>"K",
    "\u{1D543}"=>"L",
    "\u{1D544}"=>"M",
    "\u{1D546}"=>"O",
    "\u{1D54A}"=>"S",
    "\u{1D54B}"=>"T",
    "\u{1D54C}"=>"U",
    "\u{1D54D}"=>"V",
    "\u{1D54E}"=>"W",
    "\u{1D54F}"=>"X",
    "\u{1D550}"=>"Y",
    "\u{1D552}"=>"a",
    "\u{1D553}"=>"b",
    "\u{1D554}"=>"c",
    "\u{1D555}"=>"d",
    "\u{1D556}"=>"e",
    "\u{1D557}"=>"f",
    "\u{1D558}"=>"g",
    "\u{1D559}"=>"h",
    "\u{1D55A}"=>"i",
    "\u{1D55B}"=>"j",
    "\u{1D55C}"=>"k",
    "\u{1D55D}"=>"l",
    "\u{1D55E}"=>"m",
    "\u{1D55F}"=>"n",
    "\u{1D560}"=>"o",
    "\u{1D561}"=>"p",
    "\u{1D562}"=>"q",
    "\u{1D563}"=>"r",
    "\u{1D564}"=>"s",
    "\u{1D565}"=>"t",
    "\u{1D566}"=>"u",
    "\u{1D567}"=>"v",
    "\u{1D568}"=>"w",
    "\u{1D569}"=>"x",
    "\u{1D56A}"=>"y",
    "\u{1D56B}"=>"z",
    "\u{1D56C}"=>"A",
    "\u{1D56D}"=>"B",
    "\u{1D56E}"=>"C",
    "\u{1D56F}"=>"D",
    "\u{1D570}"=>"E",
    "\u{1D571}"=>"F",
    "\u{1D572}"=>"G",
    "\u{1D573}"=>"H",
    "\u{1D574}"=>"I",
    "\u{1D575}"=>"J",
    "\u{1D576}"=>"K",
    "\u{1D577}"=>"L",
    "\u{1D578}"=>"M",
    "\u{1D579}"=>"N",
    "\u{1D57A}"=>"O",
    "\u{1D57B}"=>"P",
    "\u{1D57C}"=>"Q",
    "\u{1D57D}"=>"R",
    "\u{1D57E}"=>"S",
    "\u{1D57F}"=>"T",
    "\u{1D580}"=>"U",
    "\u{1D581}"=>"V",
    "\u{1D582}"=>"W",
    "\u{1D583}"=>"X",
    "\u{1D584}"=>"Y",
    "\u{1D585}"=>"Z",
    "\u{1D586}"=>"a",
    "\u{1D587}"=>"b",
    "\u{1D588}"=>"c",
    "\u{1D589}"=>"d",
    "\u{1D58A}"=>"e",
    "\u{1D58B}"=>"f",
    "\u{1D58C}"=>"g",
    "\u{1D58D}"=>"h",
    "\u{1D58E}"=>"i",
    "\u{1D58F}"=>"j",
    "\u{1D590}"=>"k",
    "\u{1D591}"=>"l",
    "\u{1D592}"=>"m",
    "\u{1D593}"=>"n",
    "\u{1D594}"=>"o",
    "\u{1D595}"=>"p",
    "\u{1D596}"=>"q",
    "\u{1D597}"=>"r",
    "\u{1D598}"=>"s",
    "\u{1D599}"=>"t",
    "\u{1D59A}"=>"u",
    "\u{1D59B}"=>"v",
    "\u{1D59C}"=>"w",
    "\u{1D59D}"=>"x",
    "\u{1D59E}"=>"y",
    "\u{1D59F}"=>"z",
    "\u{1D5A0}"=>"A",
    "\u{1D5A1}"=>"B",
    "\u{1D5A2}"=>"C",
    "\u{1D5A3}"=>"D",
    "\u{1D5A4}"=>"E",
    "\u{1D5A5}"=>"F",
    "\u{1D5A6}"=>"G",
    "\u{1D5A7}"=>"H",
    "\u{1D5A8}"=>"I",
    "\u{1D5A9}"=>"J",
    "\u{1D5AA}"=>"K",
    "\u{1D5AB}"=>"L",
    "\u{1D5AC}"=>"M",
    "\u{1D5AD}"=>"N",
    "\u{1D5AE}"=>"O",
    "\u{1D5AF}"=>"P",
    "\u{1D5B0}"=>"Q",
    "\u{1D5B1}"=>"R",
    "\u{1D5B2}"=>"S",
    "\u{1D5B3}"=>"T",
    "\u{1D5B4}"=>"U",
    "\u{1D5B5}"=>"V",
    "\u{1D5B6}"=>"W",
    "\u{1D5B7}"=>"X",
    "\u{1D5B8}"=>"Y",
    "\u{1D5B9}"=>"Z",
    "\u{1D5BA}"=>"a",
    "\u{1D5BB}"=>"b",
    "\u{1D5BC}"=>"c",
    "\u{1D5BD}"=>"d",
    "\u{1D5BE}"=>"e",
    "\u{1D5BF}"=>"f",
    "\u{1D5C0}"=>"g",
    "\u{1D5C1}"=>"h",
    "\u{1D5C2}"=>"i",
    "\u{1D5C3}"=>"j",
    "\u{1D5C4}"=>"k",
    "\u{1D5C5}"=>"l",
    "\u{1D5C6}"=>"m",
    "\u{1D5C7}"=>"n",
    "\u{1D5C8}"=>"o",
    "\u{1D5C9}"=>"p",
    "\u{1D5CA}"=>"q",
    "\u{1D5CB}"=>"r",
    "\u{1D5CC}"=>"s",
    "\u{1D5CD}"=>"t",
    "\u{1D5CE}"=>"u",
    "\u{1D5CF}"=>"v",
    "\u{1D5D0}"=>"w",
    "\u{1D5D1}"=>"x",
    "\u{1D5D2}"=>"y",
    "\u{1D5D3}"=>"z",
    "\u{1D5D4}"=>"A",
    "\u{1D5D5}"=>"B",
    "\u{1D5D6}"=>"C",
    "\u{1D5D7}"=>"D",
    "\u{1D5D8}"=>"E",
    "\u{1D5D9}"=>"F",
    "\u{1D5DA}"=>"G",
    "\u{1D5DB}"=>"H",
    "\u{1D5DC}"=>"I",
    "\u{1D5DD}"=>"J",
    "\u{1D5DE}"=>"K",
    "\u{1D5DF}"=>"L",
    "\u{1D5E0}"=>"M",
    "\u{1D5E1}"=>"N",
    "\u{1D5E2}"=>"O",
    "\u{1D5E3}"=>"P",
    "\u{1D5E4}"=>"Q",
    "\u{1D5E5}"=>"R",
    "\u{1D5E6}"=>"S",
    "\u{1D5E7}"=>"T",
    "\u{1D5E8}"=>"U",
    "\u{1D5E9}"=>"V",
    "\u{1D5EA}"=>"W",
    "\u{1D5EB}"=>"X",
    "\u{1D5EC}"=>"Y",
    "\u{1D5ED}"=>"Z",
    "\u{1D5EE}"=>"a",
    "\u{1D5EF}"=>"b",
    "\u{1D5F0}"=>"c",
    "\u{1D5F1}"=>"d",
    "\u{1D5F2}"=>"e",
    "\u{1D5F3}"=>"f",
    "\u{1D5F4}"=>"g",
    "\u{1D5F5}"=>"h",
    "\u{1D5F6}"=>"i",
    "\u{1D5F7}"=>"j",
    "\u{1D5F8}"=>"k",
    "\u{1D5F9}"=>"l",
    "\u{1D5FA}"=>"m",
    "\u{1D5FB}"=>"n",
    "\u{1D5FC}"=>"o",
    "\u{1D5FD}"=>"p",
    "\u{1D5FE}"=>"q",
    "\u{1D5FF}"=>"r",
    "\u{1D600}"=>"s",
    "\u{1D601}"=>"t",
    "\u{1D602}"=>"u",
    "\u{1D603}"=>"v",
    "\u{1D604}"=>"w",
    "\u{1D605}"=>"x",
    "\u{1D606}"=>"y",
    "\u{1D607}"=>"z",
    "\u{1D608}"=>"A",
    "\u{1D609}"=>"B",
    "\u{1D60A}"=>"C",
    "\u{1D60B}"=>"D",
    "\u{1D60C}"=>"E",
    "\u{1D60D}"=>"F",
    "\u{1D60E}"=>"G",
    "\u{1D60F}"=>"H",
    "\u{1D610}"=>"I",
    "\u{1D611}"=>"J",
    "\u{1D612}"=>"K",
    "\u{1D613}"=>"L",
    "\u{1D614}"=>"M",
    "\u{1D615}"=>"N",
    "\u{1D616}"=>"O",
    "\u{1D617}"=>"P",
    "\u{1D618}"=>"Q",
    "\u{1D619}"=>"R",
    "\u{1D61A}"=>"S",
    "\u{1D61B}"=>"T",
    "\u{1D61C}"=>"U",
    "\u{1D61D}"=>"V",
    "\u{1D61E}"=>"W",
    "\u{1D61F}"=>"X",
    "\u{1D620}"=>"Y",
    "\u{1D621}"=>"Z",
    "\u{1D622}"=>"a",
    "\u{1D623}"=>"b",
    "\u{1D624}"=>"c",
    "\u{1D625}"=>"d",
    "\u{1D626}"=>"e",
    "\u{1D627}"=>"f",
    "\u{1D628}"=>"g",
    "\u{1D629}"=>"h",
    "\u{1D62A}"=>"i",
    "\u{1D62B}"=>"j",
    "\u{1D62C}"=>"k",
    "\u{1D62D}"=>"l",
    "\u{1D62E}"=>"m",
    "\u{1D62F}"=>"n",
    "\u{1D630}"=>"o",
    "\u{1D631}"=>"p",
    "\u{1D632}"=>"q",
    "\u{1D633}"=>"r",
    "\u{1D634}"=>"s",
    "\u{1D635}"=>"t",
    "\u{1D636}"=>"u",
    "\u{1D637}"=>"v",
    "\u{1D638}"=>"w",
    "\u{1D639}"=>"x",
    "\u{1D63A}"=>"y",
    "\u{1D63B}"=>"z",
    "\u{1D63C}"=>"A",
    "\u{1D63D}"=>"B",
    "\u{1D63E}"=>"C",
    "\u{1D63F}"=>"D",
    "\u{1D640}"=>"E",
    "\u{1D641}"=>"F",
    "\u{1D642}"=>"G",
    "\u{1D643}"=>"H",
    "\u{1D644}"=>"I",
    "\u{1D645}"=>"J",
    "\u{1D646}"=>"K",
    "\u{1D647}"=>"L",
    "\u{1D648}"=>"M",
    "\u{1D649}"=>"N",
    "\u{1D64A}"=>"O",
    "\u{1D64B}"=>"P",
    "\u{1D64C}"=>"Q",
    "\u{1D64D}"=>"R",
    "\u{1D64E}"=>"S",
    "\u{1D64F}"=>"T",
    "\u{1D650}"=>"U",
    "\u{1D651}"=>"V",
    "\u{1D652}"=>"W",
    "\u{1D653}"=>"X",
    "\u{1D654}"=>"Y",
    "\u{1D655}"=>"Z",
    "\u{1D656}"=>"a",
    "\u{1D657}"=>"b",
    "\u{1D658}"=>"c",
    "\u{1D659}"=>"d",
    "\u{1D65A}"=>"e",
    "\u{1D65B}"=>"f",
    "\u{1D65C}"=>"g",
    "\u{1D65D}"=>"h",
    "\u{1D65E}"=>"i",
    "\u{1D65F}"=>"j",
    "\u{1D660}"=>"k",
    "\u{1D661}"=>"l",
    "\u{1D662}"=>"m",
    "\u{1D663}"=>"n",
    "\u{1D664}"=>"o",
    "\u{1D665}"=>"p",
    "\u{1D666}"=>"q",
    "\u{1D667}"=>"r",
    "\u{1D668}"=>"s",
    "\u{1D669}"=>"t",
    "\u{1D66A}"=>"u",
    "\u{1D66B}"=>"v",
    "\u{1D66C}"=>"w",
    "\u{1D66D}"=>"x",
    "\u{1D66E}"=>"y",
    "\u{1D66F}"=>"z",
    "\u{1D670}"=>"A",
    "\u{1D671}"=>"B",
    "\u{1D672}"=>"C",
    "\u{1D673}"=>"D",
    "\u{1D674}"=>"E",
    "\u{1D675}"=>"F",
    "\u{1D676}"=>"G",
    "\u{1D677}"=>"H",
    "\u{1D678}"=>"I",
    "\u{1D679}"=>"J",
    "\u{1D67A}"=>"K",
    "\u{1D67B}"=>"L",
    "\u{1D67C}"=>"M",
    "\u{1D67D}"=>"N",
    "\u{1D67E}"=>"O",
    "\u{1D67F}"=>"P",
    "\u{1D680}"=>"Q",
    "\u{1D681}"=>"R",
    "\u{1D682}"=>"S",
    "\u{1D683}"=>"T",
    "\u{1D684}"=>"U",
    "\u{1D685}"=>"V",
    "\u{1D686}"=>"W",
    "\u{1D687}"=>"X",
    "\u{1D688}"=>"Y",
    "\u{1D689}"=>"Z",
    "\u{1D68A}"=>"a",
    "\u{1D68B}"=>"b",
    "\u{1D68C}"=>"c",
    "\u{1D68D}"=>"d",
    "\u{1D68E}"=>"e",
    "\u{1D68F}"=>"f",
    "\u{1D690}"=>"g",
    "\u{1D691}"=>"h",
    "\u{1D692}"=>"i",
    "\u{1D693}"=>"j",
    "\u{1D694}"=>"k",
    "\u{1D695}"=>"l",
    "\u{1D696}"=>"m",
    "\u{1D697}"=>"n",
    "\u{1D698}"=>"o",
    "\u{1D699}"=>"p",
    "\u{1D69A}"=>"q",
    "\u{1D69B}"=>"r",
    "\u{1D69C}"=>"s",
    "\u{1D69D}"=>"t",
    "\u{1D69E}"=>"u",
    "\u{1D69F}"=>"v",
    "\u{1D6A0}"=>"w",
    "\u{1D6A1}"=>"x",
    "\u{1D6A2}"=>"y",
    "\u{1D6A3}"=>"z",
    "\u{1D6A4}"=>"\u0131",
    "\u{1D6A5}"=>"\u0237",
    "\u{1D6A8}"=>"\u0391",
    "\u{1D6A9}"=>"\u0392",
    "\u{1D6AA}"=>"\u0393",
    "\u{1D6AB}"=>"\u0394",
    "\u{1D6AC}"=>"\u0395",
    "\u{1D6AD}"=>"\u0396",
    "\u{1D6AE}"=>"\u0397",
    "\u{1D6AF}"=>"\u0398",
    "\u{1D6B0}"=>"\u0399",
    "\u{1D6B1}"=>"\u039A",
    "\u{1D6B2}"=>"\u039B",
    "\u{1D6B3}"=>"\u039C",
    "\u{1D6B4}"=>"\u039D",
    "\u{1D6B5}"=>"\u039E",
    "\u{1D6B6}"=>"\u039F",
    "\u{1D6B7}"=>"\u03A0",
    "\u{1D6B8}"=>"\u03A1",
    "\u{1D6B9}"=>"\u0398",
    "\u{1D6BA}"=>"\u03A3",
    "\u{1D6BB}"=>"\u03A4",
    "\u{1D6BC}"=>"\u03A5",
    "\u{1D6BD}"=>"\u03A6",
    "\u{1D6BE}"=>"\u03A7",
    "\u{1D6BF}"=>"\u03A8",
    "\u{1D6C0}"=>"\u03A9",
    "\u{1D6C1}"=>"\u2207",
    "\u{1D6C2}"=>"\u03B1",
    "\u{1D6C3}"=>"\u03B2",
    "\u{1D6C4}"=>"\u03B3",
    "\u{1D6C5}"=>"\u03B4",
    "\u{1D6C6}"=>"\u03B5",
    "\u{1D6C7}"=>"\u03B6",
    "\u{1D6C8}"=>"\u03B7",
    "\u{1D6C9}"=>"\u03B8",
    "\u{1D6CA}"=>"\u03B9",
    "\u{1D6CB}"=>"\u03BA",
    "\u{1D6CC}"=>"\u03BB",
    "\u{1D6CD}"=>"\u03BC",
    "\u{1D6CE}"=>"\u03BD",
    "\u{1D6CF}"=>"\u03BE",
    "\u{1D6D0}"=>"\u03BF",
    "\u{1D6D1}"=>"\u03C0",
    "\u{1D6D2}"=>"\u03C1",
    "\u{1D6D3}"=>"\u03C2",
    "\u{1D6D4}"=>"\u03C3",
    "\u{1D6D5}"=>"\u03C4",
    "\u{1D6D6}"=>"\u03C5",
    "\u{1D6D7}"=>"\u03C6",
    "\u{1D6D8}"=>"\u03C7",
    "\u{1D6D9}"=>"\u03C8",
    "\u{1D6DA}"=>"\u03C9",
    "\u{1D6DB}"=>"\u2202",
    "\u{1D6DC}"=>"\u03B5",
    "\u{1D6DD}"=>"\u03B8",
    "\u{1D6DE}"=>"\u03BA",
    "\u{1D6DF}"=>"\u03C6",
    "\u{1D6E0}"=>"\u03C1",
    "\u{1D6E1}"=>"\u03C0",
    "\u{1D6E2}"=>"\u0391",
    "\u{1D6E3}"=>"\u0392",
    "\u{1D6E4}"=>"\u0393",
    "\u{1D6E5}"=>"\u0394",
    "\u{1D6E6}"=>"\u0395",
    "\u{1D6E7}"=>"\u0396",
    "\u{1D6E8}"=>"\u0397",
    "\u{1D6E9}"=>"\u0398",
    "\u{1D6EA}"=>"\u0399",
    "\u{1D6EB}"=>"\u039A",
    "\u{1D6EC}"=>"\u039B",
    "\u{1D6ED}"=>"\u039C",
    "\u{1D6EE}"=>"\u039D",
    "\u{1D6EF}"=>"\u039E",
    "\u{1D6F0}"=>"\u039F",
    "\u{1D6F1}"=>"\u03A0",
    "\u{1D6F2}"=>"\u03A1",
    "\u{1D6F3}"=>"\u0398",
    "\u{1D6F4}"=>"\u03A3",
    "\u{1D6F5}"=>"\u03A4",
    "\u{1D6F6}"=>"\u03A5",
    "\u{1D6F7}"=>"\u03A6",
    "\u{1D6F8}"=>"\u03A7",
    "\u{1D6F9}"=>"\u03A8",
    "\u{1D6FA}"=>"\u03A9",
    "\u{1D6FB}"=>"\u2207",
    "\u{1D6FC}"=>"\u03B1",
    "\u{1D6FD}"=>"\u03B2",
    "\u{1D6FE}"=>"\u03B3",
    "\u{1D6FF}"=>"\u03B4",
    "\u{1D700}"=>"\u03B5",
    "\u{1D701}"=>"\u03B6",
    "\u{1D702}"=>"\u03B7",
    "\u{1D703}"=>"\u03B8",
    "\u{1D704}"=>"\u03B9",
    "\u{1D705}"=>"\u03BA",
    "\u{1D706}"=>"\u03BB",
    "\u{1D707}"=>"\u03BC",
    "\u{1D708}"=>"\u03BD",
    "\u{1D709}"=>"\u03BE",
    "\u{1D70A}"=>"\u03BF",
    "\u{1D70B}"=>"\u03C0",
    "\u{1D70C}"=>"\u03C1",
    "\u{1D70D}"=>"\u03C2",
    "\u{1D70E}"=>"\u03C3",
    "\u{1D70F}"=>"\u03C4",
    "\u{1D710}"=>"\u03C5",
    "\u{1D711}"=>"\u03C6",
    "\u{1D712}"=>"\u03C7",
    "\u{1D713}"=>"\u03C8",
    "\u{1D714}"=>"\u03C9",
    "\u{1D715}"=>"\u2202",
    "\u{1D716}"=>"\u03B5",
    "\u{1D717}"=>"\u03B8",
    "\u{1D718}"=>"\u03BA",
    "\u{1D719}"=>"\u03C6",
    "\u{1D71A}"=>"\u03C1",
    "\u{1D71B}"=>"\u03C0",
    "\u{1D71C}"=>"\u0391",
    "\u{1D71D}"=>"\u0392",
    "\u{1D71E}"=>"\u0393",
    "\u{1D71F}"=>"\u0394",
    "\u{1D720}"=>"\u0395",
    "\u{1D721}"=>"\u0396",
    "\u{1D722}"=>"\u0397",
    "\u{1D723}"=>"\u0398",
    "\u{1D724}"=>"\u0399",
    "\u{1D725}"=>"\u039A",
    "\u{1D726}"=>"\u039B",
    "\u{1D727}"=>"\u039C",
    "\u{1D728}"=>"\u039D",
    "\u{1D729}"=>"\u039E",
    "\u{1D72A}"=>"\u039F",
    "\u{1D72B}"=>"\u03A0",
    "\u{1D72C}"=>"\u03A1",
    "\u{1D72D}"=>"\u0398",
    "\u{1D72E}"=>"\u03A3",
    "\u{1D72F}"=>"\u03A4",
    "\u{1D730}"=>"\u03A5",
    "\u{1D731}"=>"\u03A6",
    "\u{1D732}"=>"\u03A7",
    "\u{1D733}"=>"\u03A8",
    "\u{1D734}"=>"\u03A9",
    "\u{1D735}"=>"\u2207",
    "\u{1D736}"=>"\u03B1",
    "\u{1D737}"=>"\u03B2",
    "\u{1D738}"=>"\u03B3",
    "\u{1D739}"=>"\u03B4",
    "\u{1D73A}"=>"\u03B5",
    "\u{1D73B}"=>"\u03B6",
    "\u{1D73C}"=>"\u03B7",
    "\u{1D73D}"=>"\u03B8",
    "\u{1D73E}"=>"\u03B9",
    "\u{1D73F}"=>"\u03BA",
    "\u{1D740}"=>"\u03BB",
    "\u{1D741}"=>"\u03BC",
    "\u{1D742}"=>"\u03BD",
    "\u{1D743}"=>"\u03BE",
    "\u{1D744}"=>"\u03BF",
    "\u{1D745}"=>"\u03C0",
    "\u{1D746}"=>"\u03C1",
    "\u{1D747}"=>"\u03C2",
    "\u{1D748}"=>"\u03C3",
    "\u{1D749}"=>"\u03C4",
    "\u{1D74A}"=>"\u03C5",
    "\u{1D74B}"=>"\u03C6",
    "\u{1D74C}"=>"\u03C7",
    "\u{1D74D}"=>"\u03C8",
    "\u{1D74E}"=>"\u03C9",
    "\u{1D74F}"=>"\u2202",
    "\u{1D750}"=>"\u03B5",
    "\u{1D751}"=>"\u03B8",
    "\u{1D752}"=>"\u03BA",
    "\u{1D753}"=>"\u03C6",
    "\u{1D754}"=>"\u03C1",
    "\u{1D755}"=>"\u03C0",
    "\u{1D756}"=>"\u0391",
    "\u{1D757}"=>"\u0392",
    "\u{1D758}"=>"\u0393",
    "\u{1D759}"=>"\u0394",
    "\u{1D75A}"=>"\u0395",
    "\u{1D75B}"=>"\u0396",
    "\u{1D75C}"=>"\u0397",
    "\u{1D75D}"=>"\u0398",
    "\u{1D75E}"=>"\u0399",
    "\u{1D75F}"=>"\u039A",
    "\u{1D760}"=>"\u039B",
    "\u{1D761}"=>"\u039C",
    "\u{1D762}"=>"\u039D",
    "\u{1D763}"=>"\u039E",
    "\u{1D764}"=>"\u039F",
    "\u{1D765}"=>"\u03A0",
    "\u{1D766}"=>"\u03A1",
    "\u{1D767}"=>"\u0398",
    "\u{1D768}"=>"\u03A3",
    "\u{1D769}"=>"\u03A4",
    "\u{1D76A}"=>"\u03A5",
    "\u{1D76B}"=>"\u03A6",
    "\u{1D76C}"=>"\u03A7",
    "\u{1D76D}"=>"\u03A8",
    "\u{1D76E}"=>"\u03A9",
    "\u{1D76F}"=>"\u2207",
    "\u{1D770}"=>"\u03B1",
    "\u{1D771}"=>"\u03B2",
    "\u{1D772}"=>"\u03B3",
    "\u{1D773}"=>"\u03B4",
    "\u{1D774}"=>"\u03B5",
    "\u{1D775}"=>"\u03B6",
    "\u{1D776}"=>"\u03B7",
    "\u{1D777}"=>"\u03B8",
    "\u{1D778}"=>"\u03B9",
    "\u{1D779}"=>"\u03BA",
    "\u{1D77A}"=>"\u03BB",
    "\u{1D77B}"=>"\u03BC",
    "\u{1D77C}"=>"\u03BD",
    "\u{1D77D}"=>"\u03BE",
    "\u{1D77E}"=>"\u03BF",
    "\u{1D77F}"=>"\u03C0",
    "\u{1D780}"=>"\u03C1",
    "\u{1D781}"=>"\u03C2",
    "\u{1D782}"=>"\u03C3",
    "\u{1D783}"=>"\u03C4",
    "\u{1D784}"=>"\u03C5",
    "\u{1D785}"=>"\u03C6",
    "\u{1D786}"=>"\u03C7",
    "\u{1D787}"=>"\u03C8",
    "\u{1D788}"=>"\u03C9",
    "\u{1D789}"=>"\u2202",
    "\u{1D78A}"=>"\u03B5",
    "\u{1D78B}"=>"\u03B8",
    "\u{1D78C}"=>"\u03BA",
    "\u{1D78D}"=>"\u03C6",
    "\u{1D78E}"=>"\u03C1",
    "\u{1D78F}"=>"\u03C0",
    "\u{1D790}"=>"\u0391",
    "\u{1D791}"=>"\u0392",
    "\u{1D792}"=>"\u0393",
    "\u{1D793}"=>"\u0394",
    "\u{1D794}"=>"\u0395",
    "\u{1D795}"=>"\u0396",
    "\u{1D796}"=>"\u0397",
    "\u{1D797}"=>"\u0398",
    "\u{1D798}"=>"\u0399",
    "\u{1D799}"=>"\u039A",
    "\u{1D79A}"=>"\u039B",
    "\u{1D79B}"=>"\u039C",
    "\u{1D79C}"=>"\u039D",
    "\u{1D79D}"=>"\u039E",
    "\u{1D79E}"=>"\u039F",
    "\u{1D79F}"=>"\u03A0",
    "\u{1D7A0}"=>"\u03A1",
    "\u{1D7A1}"=>"\u0398",
    "\u{1D7A2}"=>"\u03A3",
    "\u{1D7A3}"=>"\u03A4",
    "\u{1D7A4}"=>"\u03A5",
    "\u{1D7A5}"=>"\u03A6",
    "\u{1D7A6}"=>"\u03A7",
    "\u{1D7A7}"=>"\u03A8",
    "\u{1D7A8}"=>"\u03A9",
    "\u{1D7A9}"=>"\u2207",
    "\u{1D7AA}"=>"\u03B1",
    "\u{1D7AB}"=>"\u03B2",
    "\u{1D7AC}"=>"\u03B3",
    "\u{1D7AD}"=>"\u03B4",
    "\u{1D7AE}"=>"\u03B5",
    "\u{1D7AF}"=>"\u03B6",
    "\u{1D7B0}"=>"\u03B7",
    "\u{1D7B1}"=>"\u03B8",
    "\u{1D7B2}"=>"\u03B9",
    "\u{1D7B3}"=>"\u03BA",
    "\u{1D7B4}"=>"\u03BB",
    "\u{1D7B5}"=>"\u03BC",
    "\u{1D7B6}"=>"\u03BD",
    "\u{1D7B7}"=>"\u03BE",
    "\u{1D7B8}"=>"\u03BF",
    "\u{1D7B9}"=>"\u03C0",
    "\u{1D7BA}"=>"\u03C1",
    "\u{1D7BB}"=>"\u03C2",
    "\u{1D7BC}"=>"\u03C3",
    "\u{1D7BD}"=>"\u03C4",
    "\u{1D7BE}"=>"\u03C5",
    "\u{1D7BF}"=>"\u03C6",
    "\u{1D7C0}"=>"\u03C7",
    "\u{1D7C1}"=>"\u03C8",
    "\u{1D7C2}"=>"\u03C9",
    "\u{1D7C3}"=>"\u2202",
    "\u{1D7C4}"=>"\u03B5",
    "\u{1D7C5}"=>"\u03B8",
    "\u{1D7C6}"=>"\u03BA",
    "\u{1D7C7}"=>"\u03C6",
    "\u{1D7C8}"=>"\u03C1",
    "\u{1D7C9}"=>"\u03C0",
    "\u{1D7CA}"=>"\u03DC",
    "\u{1D7CB}"=>"\u03DD",
    "\u{1D7CE}"=>"0",
    "\u{1D7CF}"=>"1",
    "\u{1D7D0}"=>"2",
    "\u{1D7D1}"=>"3",
    "\u{1D7D2}"=>"4",
    "\u{1D7D3}"=>"5",
    "\u{1D7D4}"=>"6",
    "\u{1D7D5}"=>"7",
    "\u{1D7D6}"=>"8",
    "\u{1D7D7}"=>"9",
    "\u{1D7D8}"=>"0",
    "\u{1D7D9}"=>"1",
    "\u{1D7DA}"=>"2",
    "\u{1D7DB}"=>"3",
    "\u{1D7DC}"=>"4",
    "\u{1D7DD}"=>"5",
    "\u{1D7DE}"=>"6",
    "\u{1D7DF}"=>"7",
    "\u{1D7E0}"=>"8",
    "\u{1D7E1}"=>"9",
    "\u{1D7E2}"=>"0",
    "\u{1D7E3}"=>"1",
    "\u{1D7E4}"=>"2",
    "\u{1D7E5}"=>"3",
    "\u{1D7E6}"=>"4",
    "\u{1D7E7}"=>"5",
    "\u{1D7E8}"=>"6",
    "\u{1D7E9}"=>"7",
    "\u{1D7EA}"=>"8",
    "\u{1D7EB}"=>"9",
    "\u{1D7EC}"=>"0",
    "\u{1D7ED}"=>"1",
    "\u{1D7EE}"=>"2",
    "\u{1D7EF}"=>"3",
    "\u{1D7F0}"=>"4",
    "\u{1D7F1}"=>"5",
    "\u{1D7F2}"=>"6",
    "\u{1D7F3}"=>"7",
    "\u{1D7F4}"=>"8",
    "\u{1D7F5}"=>"9",
    "\u{1D7F6}"=>"0",
    "\u{1D7F7}"=>"1",
    "\u{1D7F8}"=>"2",
    "\u{1D7F9}"=>"3",
    "\u{1D7FA}"=>"4",
    "\u{1D7FB}"=>"5",
    "\u{1D7FC}"=>"6",
    "\u{1D7FD}"=>"7",
    "\u{1D7FE}"=>"8",
    "\u{1D7FF}"=>"9",
    "\u{1EE00}"=>"\u0627",
    "\u{1EE01}"=>"\u0628",
    "\u{1EE02}"=>"\u062C",
    "\u{1EE03}"=>"\u062F",
    "\u{1EE05}"=>"\u0648",
    "\u{1EE06}"=>"\u0632",
    "\u{1EE07}"=>"\u062D",
    "\u{1EE08}"=>"\u0637",
    "\u{1EE09}"=>"\u064A",
    "\u{1EE0A}"=>"\u0643",
    "\u{1EE0B}"=>"\u0644",
    "\u{1EE0C}"=>"\u0645",
    "\u{1EE0D}"=>"\u0646",
    "\u{1EE0E}"=>"\u0633",
    "\u{1EE0F}"=>"\u0639",
    "\u{1EE10}"=>"\u0641",
    "\u{1EE11}"=>"\u0635",
    "\u{1EE12}"=>"\u0642",
    "\u{1EE13}"=>"\u0631",
    "\u{1EE14}"=>"\u0634",
    "\u{1EE15}"=>"\u062A",
    "\u{1EE16}"=>"\u062B",
    "\u{1EE17}"=>"\u062E",
    "\u{1EE18}"=>"\u0630",
    "\u{1EE19}"=>"\u0636",
    "\u{1EE1A}"=>"\u0638",
    "\u{1EE1B}"=>"\u063A",
    "\u{1EE1C}"=>"\u066E",
    "\u{1EE1D}"=>"\u06BA",
    "\u{1EE1E}"=>"\u06A1",
    "\u{1EE1F}"=>"\u066F",
    "\u{1EE21}"=>"\u0628",
    "\u{1EE22}"=>"\u062C",
    "\u{1EE24}"=>"\u0647",
    "\u{1EE27}"=>"\u062D",
    "\u{1EE29}"=>"\u064A",
    "\u{1EE2A}"=>"\u0643",
    "\u{1EE2B}"=>"\u0644",
    "\u{1EE2C}"=>"\u0645",
    "\u{1EE2D}"=>"\u0646",
    "\u{1EE2E}"=>"\u0633",
    "\u{1EE2F}"=>"\u0639",
    "\u{1EE30}"=>"\u0641",
    "\u{1EE31}"=>"\u0635",
    "\u{1EE32}"=>"\u0642",
    "\u{1EE34}"=>"\u0634",
    "\u{1EE35}"=>"\u062A",
    "\u{1EE36}"=>"\u062B",
    "\u{1EE37}"=>"\u062E",
    "\u{1EE39}"=>"\u0636",
    "\u{1EE3B}"=>"\u063A",
    "\u{1EE42}"=>"\u062C",
    "\u{1EE47}"=>"\u062D",
    "\u{1EE49}"=>"\u064A",
    "\u{1EE4B}"=>"\u0644",
    "\u{1EE4D}"=>"\u0646",
    "\u{1EE4E}"=>"\u0633",
    "\u{1EE4F}"=>"\u0639",
    "\u{1EE51}"=>"\u0635",
    "\u{1EE52}"=>"\u0642",
    "\u{1EE54}"=>"\u0634",
    "\u{1EE57}"=>"\u062E",
    "\u{1EE59}"=>"\u0636",
    "\u{1EE5B}"=>"\u063A",
    "\u{1EE5D}"=>"\u06BA",
    "\u{1EE5F}"=>"\u066F",
    "\u{1EE61}"=>"\u0628",
    "\u{1EE62}"=>"\u062C",
    "\u{1EE64}"=>"\u0647",
    "\u{1EE67}"=>"\u062D",
    "\u{1EE68}"=>"\u0637",
    "\u{1EE69}"=>"\u064A",
    "\u{1EE6A}"=>"\u0643",
    "\u{1EE6C}"=>"\u0645",
    "\u{1EE6D}"=>"\u0646",
    "\u{1EE6E}"=>"\u0633",
    "\u{1EE6F}"=>"\u0639",
    "\u{1EE70}"=>"\u0641",
    "\u{1EE71}"=>"\u0635",
    "\u{1EE72}"=>"\u0642",
    "\u{1EE74}"=>"\u0634",
    "\u{1EE75}"=>"\u062A",
    "\u{1EE76}"=>"\u062B",
    "\u{1EE77}"=>"\u062E",
    "\u{1EE79}"=>"\u0636",
    "\u{1EE7A}"=>"\u0638",
    "\u{1EE7B}"=>"\u063A",
    "\u{1EE7C}"=>"\u066E",
    "\u{1EE7E}"=>"\u06A1",
    "\u{1EE80}"=>"\u0627",
    "\u{1EE81}"=>"\u0628",
    "\u{1EE82}"=>"\u062C",
    "\u{1EE83}"=>"\u062F",
    "\u{1EE84}"=>"\u0647",
    "\u{1EE85}"=>"\u0648",
    "\u{1EE86}"=>"\u0632",
    "\u{1EE87}"=>"\u062D",
    "\u{1EE88}"=>"\u0637",
    "\u{1EE89}"=>"\u064A",
    "\u{1EE8B}"=>"\u0644",
    "\u{1EE8C}"=>"\u0645",
    "\u{1EE8D}"=>"\u0646",
    "\u{1EE8E}"=>"\u0633",
    "\u{1EE8F}"=>"\u0639",
    "\u{1EE90}"=>"\u0641",
    "\u{1EE91}"=>"\u0635",
    "\u{1EE92}"=>"\u0642",
    "\u{1EE93}"=>"\u0631",
    "\u{1EE94}"=>"\u0634",
    "\u{1EE95}"=>"\u062A",
    "\u{1EE96}"=>"\u062B",
    "\u{1EE97}"=>"\u062E",
    "\u{1EE98}"=>"\u0630",
    "\u{1EE99}"=>"\u0636",
    "\u{1EE9A}"=>"\u0638",
    "\u{1EE9B}"=>"\u063A",
    "\u{1EEA1}"=>"\u0628",
    "\u{1EEA2}"=>"\u062C",
    "\u{1EEA3}"=>"\u062F",
    "\u{1EEA5}"=>"\u0648",
    "\u{1EEA6}"=>"\u0632",
    "\u{1EEA7}"=>"\u062D",
    "\u{1EEA8}"=>"\u0637",
    "\u{1EEA9}"=>"\u064A",
    "\u{1EEAB}"=>"\u0644",
    "\u{1EEAC}"=>"\u0645",
    "\u{1EEAD}"=>"\u0646",
    "\u{1EEAE}"=>"\u0633",
    "\u{1EEAF}"=>"\u0639",
    "\u{1EEB0}"=>"\u0641",
    "\u{1EEB1}"=>"\u0635",
    "\u{1EEB2}"=>"\u0642",
    "\u{1EEB3}"=>"\u0631",
    "\u{1EEB4}"=>"\u0634",
    "\u{1EEB5}"=>"\u062A",
    "\u{1EEB6}"=>"\u062B",
    "\u{1EEB7}"=>"\u062E",
    "\u{1EEB8}"=>"\u0630",
    "\u{1EEB9}"=>"\u0636",
    "\u{1EEBA}"=>"\u0638",
    "\u{1EEBB}"=>"\u063A",
    "\u{1F100}"=>"0.",
    "\u{1F101}"=>"0,",
    "\u{1F102}"=>"1,",
    "\u{1F103}"=>"2,",
    "\u{1F104}"=>"3,",
    "\u{1F105}"=>"4,",
    "\u{1F106}"=>"5,",
    "\u{1F107}"=>"6,",
    "\u{1F108}"=>"7,",
    "\u{1F109}"=>"8,",
    "\u{1F10A}"=>"9,",
    "\u{1F110}"=>"(A)",
    "\u{1F111}"=>"(B)",
    "\u{1F112}"=>"(C)",
    "\u{1F113}"=>"(D)",
    "\u{1F114}"=>"(E)",
    "\u{1F115}"=>"(F)",
    "\u{1F116}"=>"(G)",
    "\u{1F117}"=>"(H)",
    "\u{1F118}"=>"(I)",
    "\u{1F119}"=>"(J)",
    "\u{1F11A}"=>"(K)",
    "\u{1F11B}"=>"(L)",
    "\u{1F11C}"=>"(M)",
    "\u{1F11D}"=>"(N)",
    "\u{1F11E}"=>"(O)",
    "\u{1F11F}"=>"(P)",
    "\u{1F120}"=>"(Q)",
    "\u{1F121}"=>"(R)",
    "\u{1F122}"=>"(S)",
    "\u{1F123}"=>"(T)",
    "\u{1F124}"=>"(U)",
    "\u{1F125}"=>"(V)",
    "\u{1F126}"=>"(W)",
    "\u{1F127}"=>"(X)",
    "\u{1F128}"=>"(Y)",
    "\u{1F129}"=>"(Z)",
    "\u{1F12A}"=>"\u3014S\u3015",
    "\u{1F12B}"=>"C",
    "\u{1F12C}"=>"R",
    "\u{1F12D}"=>"CD",
    "\u{1F12E}"=>"WZ",
    "\u{1F130}"=>"A",
    "\u{1F131}"=>"B",
    "\u{1F132}"=>"C",
    "\u{1F133}"=>"D",
    "\u{1F134}"=>"E",
    "\u{1F135}"=>"F",
    "\u{1F136}"=>"G",
    "\u{1F137}"=>"H",
    "\u{1F138}"=>"I",
    "\u{1F139}"=>"J",
    "\u{1F13A}"=>"K",
    "\u{1F13B}"=>"L",
    "\u{1F13C}"=>"M",
    "\u{1F13D}"=>"N",
    "\u{1F13E}"=>"O",
    "\u{1F13F}"=>"P",
    "\u{1F140}"=>"Q",
    "\u{1F141}"=>"R",
    "\u{1F142}"=>"S",
    "\u{1F143}"=>"T",
    "\u{1F144}"=>"U",
    "\u{1F145}"=>"V",
    "\u{1F146}"=>"W",
    "\u{1F147}"=>"X",
    "\u{1F148}"=>"Y",
    "\u{1F149}"=>"Z",
    "\u{1F14A}"=>"HV",
    "\u{1F14B}"=>"MV",
    "\u{1F14C}"=>"SD",
    "\u{1F14D}"=>"SS",
    "\u{1F14E}"=>"PPV",
    "\u{1F14F}"=>"WC",
    "\u{1F16A}"=>"MC",
    "\u{1F16B}"=>"MD",
    "\u{1F16C}"=>"MR",
    "\u{1F190}"=>"DJ",
    "\u{1F200}"=>"\u307B\u304B",
    "\u{1F201}"=>"\u30B3\u30B3",
    "\u{1F202}"=>"\u30B5",
    "\u{1F210}"=>"\u624B",
    "\u{1F211}"=>"\u5B57",
    "\u{1F212}"=>"\u53CC",
    "\u{1F213}"=>"\u30C7",
    "\u{1F214}"=>"\u4E8C",
    "\u{1F215}"=>"\u591A",
    "\u{1F216}"=>"\u89E3",
    "\u{1F217}"=>"\u5929",
    "\u{1F218}"=>"\u4EA4",
    "\u{1F219}"=>"\u6620",
    "\u{1F21A}"=>"\u7121",
    "\u{1F21B}"=>"\u6599",
    "\u{1F21C}"=>"\u524D",
    "\u{1F21D}"=>"\u5F8C",
    "\u{1F21E}"=>"\u518D",
    "\u{1F21F}"=>"\u65B0",
    "\u{1F220}"=>"\u521D",
    "\u{1F221}"=>"\u7D42",
    "\u{1F222}"=>"\u751F",
    "\u{1F223}"=>"\u8CA9",
    "\u{1F224}"=>"\u58F0",
    "\u{1F225}"=>"\u5439",
    "\u{1F226}"=>"\u6F14",
    "\u{1F227}"=>"\u6295",
    "\u{1F228}"=>"\u6355",
    "\u{1F229}"=>"\u4E00",
    "\u{1F22A}"=>"\u4E09",
    "\u{1F22B}"=>"\u904A",
    "\u{1F22C}"=>"\u5DE6",
    "\u{1F22D}"=>"\u4E2D",
    "\u{1F22E}"=>"\u53F3",
    "\u{1F22F}"=>"\u6307",
    "\u{1F230}"=>"\u8D70",
    "\u{1F231}"=>"\u6253",
    "\u{1F232}"=>"\u7981",
    "\u{1F233}"=>"\u7A7A",
    "\u{1F234}"=>"\u5408",
    "\u{1F235}"=>"\u6E80",
    "\u{1F236}"=>"\u6709",
    "\u{1F237}"=>"\u6708",
    "\u{1F238}"=>"\u7533",
    "\u{1F239}"=>"\u5272",
    "\u{1F23A}"=>"\u55B6",
    "\u{1F23B}"=>"\u914D",
    "\u{1F240}"=>"\u3014\u672C\u3015",
    "\u{1F241}"=>"\u3014\u4E09\u3015",
    "\u{1F242}"=>"\u3014\u4E8C\u3015",
    "\u{1F243}"=>"\u3014\u5B89\u3015",
    "\u{1F244}"=>"\u3014\u70B9\u3015",
    "\u{1F245}"=>"\u3014\u6253\u3015",
    "\u{1F246}"=>"\u3014\u76D7\u3015",
    "\u{1F247}"=>"\u3014\u52DD\u3015",
    "\u{1F248}"=>"\u3014\u6557\u3015",
    "\u{1F250}"=>"\u5F97",
    "\u{1F251}"=>"\u53EF",
    "\u0385"=>" \u0308\u0301",
    "\u03D3"=>"\u03A5\u0301",
    "\u03D4"=>"\u03A5\u0308",
    "\u1E9B"=>"s\u0307",
    "\u1FC1"=>" \u0308\u0342",
    "\u1FCD"=>" \u0313\u0300",
    "\u1FCE"=>" \u0313\u0301",
    "\u1FCF"=>" \u0313\u0342",
    "\u1FDD"=>" \u0314\u0300",
    "\u1FDE"=>" \u0314\u0301",
    "\u1FDF"=>" \u0314\u0342",
    "\u1FED"=>" \u0308\u0300",
    "\u1FEE"=>" \u0308\u0301",
    "\u1FFD"=>" \u0301",
    "\u2000"=>" ",
    "\u2001"=>" ",
  }.freeze

  COMPOSITION_TABLE = {
    "A\u0300"=>"\u00C0",
    "A\u0301"=>"\u00C1",
    "A\u0302"=>"\u00C2",
    "A\u0303"=>"\u00C3",
    "A\u0308"=>"\u00C4",
    "A\u030A"=>"\u00C5",
    "C\u0327"=>"\u00C7",
    "E\u0300"=>"\u00C8",
    "E\u0301"=>"\u00C9",
    "E\u0302"=>"\u00CA",
    "E\u0308"=>"\u00CB",
    "I\u0300"=>"\u00CC",
    "I\u0301"=>"\u00CD",
    "I\u0302"=>"\u00CE",
    "I\u0308"=>"\u00CF",
    "N\u0303"=>"\u00D1",
    "O\u0300"=>"\u00D2",
    "O\u0301"=>"\u00D3",
    "O\u0302"=>"\u00D4",
    "O\u0303"=>"\u00D5",
    "O\u0308"=>"\u00D6",
    "U\u0300"=>"\u00D9",
    "U\u0301"=>"\u00DA",
    "U\u0302"=>"\u00DB",
    "U\u0308"=>"\u00DC",
    "Y\u0301"=>"\u00DD",
    "a\u0300"=>"\u00E0",
    "a\u0301"=>"\u00E1",
    "a\u0302"=>"\u00E2",
    "a\u0303"=>"\u00E3",
    "a\u0308"=>"\u00E4",
    "a\u030A"=>"\u00E5",
    "c\u0327"=>"\u00E7",
    "e\u0300"=>"\u00E8",
    "e\u0301"=>"\u00E9",
    "e\u0302"=>"\u00EA",
    "e\u0308"=>"\u00EB",
    "i\u0300"=>"\u00EC",
    "i\u0301"=>"\u00ED",
    "i\u0302"=>"\u00EE",
    "i\u0308"=>"\u00EF",
    "n\u0303"=>"\u00F1",
    "o\u0300"=>"\u00F2",
    "o\u0301"=>"\u00F3",
    "o\u0302"=>"\u00F4",
    "o\u0303"=>"\u00F5",
    "o\u0308"=>"\u00F6",
    "u\u0300"=>"\u00F9",
    "u\u0301"=>"\u00FA",
    "u\u0302"=>"\u00FB",
    "u\u0308"=>"\u00FC",
    "y\u0301"=>"\u00FD",
    "y\u0308"=>"\u00FF",
    "A\u0304"=>"\u0100",
    "a\u0304"=>"\u0101",
    "A\u0306"=>"\u0102",
    "a\u0306"=>"\u0103",
    "A\u0328"=>"\u0104",
    "a\u0328"=>"\u0105",
    "C\u0301"=>"\u0106",
    "c\u0301"=>"\u0107",
    "C\u0302"=>"\u0108",
    "c\u0302"=>"\u0109",
    "C\u0307"=>"\u010A",
    "c\u0307"=>"\u010B",
    "C\u030C"=>"\u010C",
    "c\u030C"=>"\u010D",
    "D\u030C"=>"\u010E",
    "d\u030C"=>"\u010F",
    "E\u0304"=>"\u0112",
    "e\u0304"=>"\u0113",
    "E\u0306"=>"\u0114",
    "e\u0306"=>"\u0115",
    "E\u0307"=>"\u0116",
    "e\u0307"=>"\u0117",
    "E\u0328"=>"\u0118",
    "e\u0328"=>"\u0119",
    "E\u030C"=>"\u011A",
    "e\u030C"=>"\u011B",
    "G\u0302"=>"\u011C",
    "g\u0302"=>"\u011D",
    "G\u0306"=>"\u011E",
    "g\u0306"=>"\u011F",
    "G\u0307"=>"\u0120",
    "g\u0307"=>"\u0121",
    "G\u0327"=>"\u0122",
    "g\u0327"=>"\u0123",
    "H\u0302"=>"\u0124",
    "h\u0302"=>"\u0125",
    "I\u0303"=>"\u0128",
    "i\u0303"=>"\u0129",
    "I\u0304"=>"\u012A",
    "i\u0304"=>"\u012B",
    "I\u0306"=>"\u012C",
    "i\u0306"=>"\u012D",
    "I\u0328"=>"\u012E",
    "i\u0328"=>"\u012F",
    "I\u0307"=>"\u0130",
    "J\u0302"=>"\u0134",
    "j\u0302"=>"\u0135",
    "K\u0327"=>"\u0136",
    "k\u0327"=>"\u0137",
    "L\u0301"=>"\u0139",
    "l\u0301"=>"\u013A",
    "L\u0327"=>"\u013B",
    "l\u0327"=>"\u013C",
    "L\u030C"=>"\u013D",
    "l\u030C"=>"\u013E",
    "N\u0301"=>"\u0143",
    "n\u0301"=>"\u0144",
    "N\u0327"=>"\u0145",
    "n\u0327"=>"\u0146",
    "N\u030C"=>"\u0147",
    "n\u030C"=>"\u0148",
    "O\u0304"=>"\u014C",
    "o\u0304"=>"\u014D",
    "O\u0306"=>"\u014E",
    "o\u0306"=>"\u014F",
    "O\u030B"=>"\u0150",
    "o\u030B"=>"\u0151",
    "R\u0301"=>"\u0154",
    "r\u0301"=>"\u0155",
    "R\u0327"=>"\u0156",
    "r\u0327"=>"\u0157",
    "R\u030C"=>"\u0158",
    "r\u030C"=>"\u0159",
    "S\u0301"=>"\u015A",
    "s\u0301"=>"\u015B",
    "S\u0302"=>"\u015C",
    "s\u0302"=>"\u015D",
    "S\u0327"=>"\u015E",
    "s\u0327"=>"\u015F",
    "S\u030C"=>"\u0160",
    "s\u030C"=>"\u0161",
    "T\u0327"=>"\u0162",
    "t\u0327"=>"\u0163",
    "T\u030C"=>"\u0164",
    "t\u030C"=>"\u0165",
    "U\u0303"=>"\u0168",
    "u\u0303"=>"\u0169",
    "U\u0304"=>"\u016A",
    "u\u0304"=>"\u016B",
    "U\u0306"=>"\u016C",
    "u\u0306"=>"\u016D",
    "U\u030A"=>"\u016E",
    "u\u030A"=>"\u016F",
    "U\u030B"=>"\u0170",
    "u\u030B"=>"\u0171",
    "U\u0328"=>"\u0172",
    "u\u0328"=>"\u0173",
    "W\u0302"=>"\u0174",
    "w\u0302"=>"\u0175",
    "Y\u0302"=>"\u0176",
    "y\u0302"=>"\u0177",
    "Y\u0308"=>"\u0178",
    "Z\u0301"=>"\u0179",
    "z\u0301"=>"\u017A",
    "Z\u0307"=>"\u017B",
    "z\u0307"=>"\u017C",
    "Z\u030C"=>"\u017D",
    "z\u030C"=>"\u017E",
    "O\u031B"=>"\u01A0",
    "o\u031B"=>"\u01A1",
    "U\u031B"=>"\u01AF",
    "u\u031B"=>"\u01B0",
    "A\u030C"=>"\u01CD",
    "a\u030C"=>"\u01CE",
    "I\u030C"=>"\u01CF",
    "i\u030C"=>"\u01D0",
    "O\u030C"=>"\u01D1",
    "o\u030C"=>"\u01D2",
    "U\u030C"=>"\u01D3",
    "u\u030C"=>"\u01D4",
    "\u00DC\u0304"=>"\u01D5",
    "\u00FC\u0304"=>"\u01D6",
    "\u00DC\u0301"=>"\u01D7",
    "\u00FC\u0301"=>"\u01D8",
    "\u00DC\u030C"=>"\u01D9",
    "\u00FC\u030C"=>"\u01DA",
    "\u00DC\u0300"=>"\u01DB",
    "\u00FC\u0300"=>"\u01DC",
    "\u00C4\u0304"=>"\u01DE",
    "\u00E4\u0304"=>"\u01DF",
    "\u0226\u0304"=>"\u01E0",
    "\u0227\u0304"=>"\u01E1",
    "\u00C6\u0304"=>"\u01E2",
    "\u00E6\u0304"=>"\u01E3",
    "G\u030C"=>"\u01E6",
    "g\u030C"=>"\u01E7",
    "K\u030C"=>"\u01E8",
    "k\u030C"=>"\u01E9",
    "O\u0328"=>"\u01EA",
    "o\u0328"=>"\u01EB",
    "\u01EA\u0304"=>"\u01EC",
    "\u01EB\u0304"=>"\u01ED",
    "\u01B7\u030C"=>"\u01EE",
    "\u0292\u030C"=>"\u01EF",
    "j\u030C"=>"\u01F0",
    "G\u0301"=>"\u01F4",
    "g\u0301"=>"\u01F5",
    "N\u0300"=>"\u01F8",
    "n\u0300"=>"\u01F9",
    "\u00C5\u0301"=>"\u01FA",
    "\u00E5\u0301"=>"\u01FB",
    "\u00C6\u0301"=>"\u01FC",
    "\u00E6\u0301"=>"\u01FD",
    "\u00D8\u0301"=>"\u01FE",
    "\u00F8\u0301"=>"\u01FF",
    "A\u030F"=>"\u0200",
    "a\u030F"=>"\u0201",
    "A\u0311"=>"\u0202",
    "a\u0311"=>"\u0203",
    "E\u030F"=>"\u0204",
    "e\u030F"=>"\u0205",
    "E\u0311"=>"\u0206",
    "e\u0311"=>"\u0207",
    "I\u030F"=>"\u0208",
    "i\u030F"=>"\u0209",
    "I\u0311"=>"\u020A",
    "i\u0311"=>"\u020B",
    "O\u030F"=>"\u020C",
    "o\u030F"=>"\u020D",
    "O\u0311"=>"\u020E",
    "o\u0311"=>"\u020F",
    "R\u030F"=>"\u0210",
    "r\u030F"=>"\u0211",
    "R\u0311"=>"\u0212",
    "r\u0311"=>"\u0213",
    "U\u030F"=>"\u0214",
    "u\u030F"=>"\u0215",
    "U\u0311"=>"\u0216",
    "u\u0311"=>"\u0217",
    "S\u0326"=>"\u0218",
    "s\u0326"=>"\u0219",
    "T\u0326"=>"\u021A",
    "t\u0326"=>"\u021B",
    "H\u030C"=>"\u021E",
    "h\u030C"=>"\u021F",
    "A\u0307"=>"\u0226",
    "a\u0307"=>"\u0227",
    "E\u0327"=>"\u0228",
    "e\u0327"=>"\u0229",
    "\u00D6\u0304"=>"\u022A",
    "\u00F6\u0304"=>"\u022B",
    "\u00D5\u0304"=>"\u022C",
    "\u00F5\u0304"=>"\u022D",
    "O\u0307"=>"\u022E",
    "o\u0307"=>"\u022F",
    "\u022E\u0304"=>"\u0230",
    "\u022F\u0304"=>"\u0231",
    "Y\u0304"=>"\u0232",
    "y\u0304"=>"\u0233",
    "\u00A8\u0301"=>"\u0385",
    "\u0391\u0301"=>"\u0386",
    "\u0395\u0301"=>"\u0388",
    "\u0397\u0301"=>"\u0389",
    "\u0399\u0301"=>"\u038A",
    "\u039F\u0301"=>"\u038C",
    "\u03A5\u0301"=>"\u038E",
    "\u03A9\u0301"=>"\u038F",
    "\u03CA\u0301"=>"\u0390",
    "\u0399\u0308"=>"\u03AA",
    "\u03A5\u0308"=>"\u03AB",
    "\u03B1\u0301"=>"\u03AC",
    "\u03B5\u0301"=>"\u03AD",
    "\u03B7\u0301"=>"\u03AE",
    "\u03B9\u0301"=>"\u03AF",
    "\u03CB\u0301"=>"\u03B0",
    "\u03B9\u0308"=>"\u03CA",
    "\u03C5\u0308"=>"\u03CB",
    "\u03BF\u0301"=>"\u03CC",
    "\u03C5\u0301"=>"\u03CD",
    "\u03C9\u0301"=>"\u03CE",
    "\u03D2\u0301"=>"\u03D3",
    "\u03D2\u0308"=>"\u03D4",
    "\u0415\u0300"=>"\u0400",
    "\u0415\u0308"=>"\u0401",
    "\u0413\u0301"=>"\u0403",
    "\u0406\u0308"=>"\u0407",
    "\u041A\u0301"=>"\u040C",
    "\u0418\u0300"=>"\u040D",
    "\u0423\u0306"=>"\u040E",
    "\u0418\u0306"=>"\u0419",
    "\u0438\u0306"=>"\u0439",
    "\u0435\u0300"=>"\u0450",
    "\u0435\u0308"=>"\u0451",
    "\u0433\u0301"=>"\u0453",
    "\u0456\u0308"=>"\u0457",
    "\u043A\u0301"=>"\u045C",
    "\u0438\u0300"=>"\u045D",
    "\u0443\u0306"=>"\u045E",
    "\u0474\u030F"=>"\u0476",
    "\u0475\u030F"=>"\u0477",
    "\u0416\u0306"=>"\u04C1",
    "\u0436\u0306"=>"\u04C2",
    "\u0410\u0306"=>"\u04D0",
    "\u0430\u0306"=>"\u04D1",
    "\u0410\u0308"=>"\u04D2",
    "\u0430\u0308"=>"\u04D3",
    "\u0415\u0306"=>"\u04D6",
    "\u0435\u0306"=>"\u04D7",
    "\u04D8\u0308"=>"\u04DA",
    "\u04D9\u0308"=>"\u04DB",
    "\u0416\u0308"=>"\u04DC",
    "\u0436\u0308"=>"\u04DD",
    "\u0417\u0308"=>"\u04DE",
    "\u0437\u0308"=>"\u04DF",
    "\u0418\u0304"=>"\u04E2",
    "\u0438\u0304"=>"\u04E3",
    "\u0418\u0308"=>"\u04E4",
    "\u0438\u0308"=>"\u04E5",
    "\u041E\u0308"=>"\u04E6",
    "\u043E\u0308"=>"\u04E7",
    "\u04E8\u0308"=>"\u04EA",
    "\u04E9\u0308"=>"\u04EB",
    "\u042D\u0308"=>"\u04EC",
    "\u044D\u0308"=>"\u04ED",
    "\u0423\u0304"=>"\u04EE",
    "\u0443\u0304"=>"\u04EF",
    "\u0423\u0308"=>"\u04F0",
    "\u0443\u0308"=>"\u04F1",
    "\u0423\u030B"=>"\u04F2",
    "\u0443\u030B"=>"\u04F3",
    "\u0427\u0308"=>"\u04F4",
    "\u0447\u0308"=>"\u04F5",
    "\u042B\u0308"=>"\u04F8",
    "\u044B\u0308"=>"\u04F9",
    "\u0627\u0653"=>"\u0622",
    "\u0627\u0654"=>"\u0623",
    "\u0648\u0654"=>"\u0624",
    "\u0627\u0655"=>"\u0625",
    "\u064A\u0654"=>"\u0626",
    "\u06D5\u0654"=>"\u06C0",
    "\u06C1\u0654"=>"\u06C2",
    "\u06D2\u0654"=>"\u06D3",
    "\u0928\u093C"=>"\u0929",
    "\u0930\u093C"=>"\u0931",
    "\u0933\u093C"=>"\u0934",
    "\u09C7\u09BE"=>"\u09CB",
    "\u09C7\u09D7"=>"\u09CC",
    "\u0B47\u0B56"=>"\u0B48",
    "\u0B47\u0B3E"=>"\u0B4B",
    "\u0B47\u0B57"=>"\u0B4C",
    "\u0B92\u0BD7"=>"\u0B94",
    "\u0BC6\u0BBE"=>"\u0BCA",
    "\u0BC7\u0BBE"=>"\u0BCB",
    "\u0BC6\u0BD7"=>"\u0BCC",
    "\u0C46\u0C56"=>"\u0C48",
    "\u0CBF\u0CD5"=>"\u0CC0",
    "\u0CC6\u0CD5"=>"\u0CC7",
    "\u0CC6\u0CD6"=>"\u0CC8",
    "\u0CC6\u0CC2"=>"\u0CCA",
    "\u0CCA\u0CD5"=>"\u0CCB",
    "\u0D46\u0D3E"=>"\u0D4A",
    "\u0D47\u0D3E"=>"\u0D4B",
    "\u0D46\u0D57"=>"\u0D4C",
    "\u0DD9\u0DCA"=>"\u0DDA",
    "\u0DD9\u0DCF"=>"\u0DDC",
    "\u0DDC\u0DCA"=>"\u0DDD",
    "\u0DD9\u0DDF"=>"\u0DDE",
    "\u1025\u102E"=>"\u1026",
    "\u1B05\u1B35"=>"\u1B06",
    "\u1B07\u1B35"=>"\u1B08",
    "\u1B09\u1B35"=>"\u1B0A",
    "\u1B0B\u1B35"=>"\u1B0C",
    "\u1B0D\u1B35"=>"\u1B0E",
    "\u1B11\u1B35"=>"\u1B12",
    "\u1B3A\u1B35"=>"\u1B3B",
    "\u1B3C\u1B35"=>"\u1B3D",
    "\u1B3E\u1B35"=>"\u1B40",
    "\u1B3F\u1B35"=>"\u1B41",
    "\u1B42\u1B35"=>"\u1B43",
    "A\u0325"=>"\u1E00",
    "a\u0325"=>"\u1E01",
    "B\u0307"=>"\u1E02",
    "b\u0307"=>"\u1E03",
    "B\u0323"=>"\u1E04",
    "b\u0323"=>"\u1E05",
    "B\u0331"=>"\u1E06",
    "b\u0331"=>"\u1E07",
    "\u00C7\u0301"=>"\u1E08",
    "\u00E7\u0301"=>"\u1E09",
    "D\u0307"=>"\u1E0A",
    "d\u0307"=>"\u1E0B",
    "D\u0323"=>"\u1E0C",
    "d\u0323"=>"\u1E0D",
    "D\u0331"=>"\u1E0E",
    "d\u0331"=>"\u1E0F",
    "D\u0327"=>"\u1E10",
    "d\u0327"=>"\u1E11",
    "D\u032D"=>"\u1E12",
    "d\u032D"=>"\u1E13",
    "\u0112\u0300"=>"\u1E14",
    "\u0113\u0300"=>"\u1E15",
    "\u0112\u0301"=>"\u1E16",
    "\u0113\u0301"=>"\u1E17",
    "E\u032D"=>"\u1E18",
    "e\u032D"=>"\u1E19",
    "E\u0330"=>"\u1E1A",
    "e\u0330"=>"\u1E1B",
    "\u0228\u0306"=>"\u1E1C",
    "\u0229\u0306"=>"\u1E1D",
    "F\u0307"=>"\u1E1E",
    "f\u0307"=>"\u1E1F",
    "G\u0304"=>"\u1E20",
    "g\u0304"=>"\u1E21",
    "H\u0307"=>"\u1E22",
    "h\u0307"=>"\u1E23",
    "H\u0323"=>"\u1E24",
    "h\u0323"=>"\u1E25",
    "H\u0308"=>"\u1E26",
    "h\u0308"=>"\u1E27",
    "H\u0327"=>"\u1E28",
    "h\u0327"=>"\u1E29",
    "H\u032E"=>"\u1E2A",
    "h\u032E"=>"\u1E2B",
    "I\u0330"=>"\u1E2C",
    "i\u0330"=>"\u1E2D",
    "\u00CF\u0301"=>"\u1E2E",
    "\u00EF\u0301"=>"\u1E2F",
    "K\u0301"=>"\u1E30",
    "k\u0301"=>"\u1E31",
    "K\u0323"=>"\u1E32",
    "k\u0323"=>"\u1E33",
    "K\u0331"=>"\u1E34",
    "k\u0331"=>"\u1E35",
    "L\u0323"=>"\u1E36",
    "l\u0323"=>"\u1E37",
    "\u1E36\u0304"=>"\u1E38",
    "\u1E37\u0304"=>"\u1E39",
    "L\u0331"=>"\u1E3A",
    "l\u0331"=>"\u1E3B",
    "L\u032D"=>"\u1E3C",
    "l\u032D"=>"\u1E3D",
    "M\u0301"=>"\u1E3E",
    "m\u0301"=>"\u1E3F",
    "M\u0307"=>"\u1E40",
    "m\u0307"=>"\u1E41",
    "M\u0323"=>"\u1E42",
    "m\u0323"=>"\u1E43",
    "N\u0307"=>"\u1E44",
    "n\u0307"=>"\u1E45",
    "N\u0323"=>"\u1E46",
    "n\u0323"=>"\u1E47",
    "N\u0331"=>"\u1E48",
    "n\u0331"=>"\u1E49",
    "N\u032D"=>"\u1E4A",
    "n\u032D"=>"\u1E4B",
    "\u00D5\u0301"=>"\u1E4C",
    "\u00F5\u0301"=>"\u1E4D",
    "\u00D5\u0308"=>"\u1E4E",
    "\u00F5\u0308"=>"\u1E4F",
    "\u014C\u0300"=>"\u1E50",
    "\u014D\u0300"=>"\u1E51",
    "\u014C\u0301"=>"\u1E52",
    "\u014D\u0301"=>"\u1E53",
    "P\u0301"=>"\u1E54",
    "p\u0301"=>"\u1E55",
    "P\u0307"=>"\u1E56",
    "p\u0307"=>"\u1E57",
    "R\u0307"=>"\u1E58",
    "r\u0307"=>"\u1E59",
    "R\u0323"=>"\u1E5A",
    "r\u0323"=>"\u1E5B",
    "\u1E5A\u0304"=>"\u1E5C",
    "\u1E5B\u0304"=>"\u1E5D",
    "R\u0331"=>"\u1E5E",
    "r\u0331"=>"\u1E5F",
    "S\u0307"=>"\u1E60",
    "s\u0307"=>"\u1E61",
    "S\u0323"=>"\u1E62",
    "s\u0323"=>"\u1E63",
    "\u015A\u0307"=>"\u1E64",
    "\u015B\u0307"=>"\u1E65",
    "\u0160\u0307"=>"\u1E66",
    "\u0161\u0307"=>"\u1E67",
    "\u1E62\u0307"=>"\u1E68",
    "\u1E63\u0307"=>"\u1E69",
    "T\u0307"=>"\u1E6A",
    "t\u0307"=>"\u1E6B",
    "T\u0323"=>"\u1E6C",
    "t\u0323"=>"\u1E6D",
    "T\u0331"=>"\u1E6E",
    "t\u0331"=>"\u1E6F",
    "T\u032D"=>"\u1E70",
    "t\u032D"=>"\u1E71",
    "U\u0324"=>"\u1E72",
    "u\u0324"=>"\u1E73",
    "U\u0330"=>"\u1E74",
    "u\u0330"=>"\u1E75",
    "U\u032D"=>"\u1E76",
    "u\u032D"=>"\u1E77",
    "\u0168\u0301"=>"\u1E78",
    "\u0169\u0301"=>"\u1E79",
    "\u016A\u0308"=>"\u1E7A",
    "\u016B\u0308"=>"\u1E7B",
    "V\u0303"=>"\u1E7C",
    "v\u0303"=>"\u1E7D",
    "V\u0323"=>"\u1E7E",
    "v\u0323"=>"\u1E7F",
    "W\u0300"=>"\u1E80",
    "w\u0300"=>"\u1E81",
    "W\u0301"=>"\u1E82",
    "w\u0301"=>"\u1E83",
    "W\u0308"=>"\u1E84",
    "w\u0308"=>"\u1E85",
    "W\u0307"=>"\u1E86",
    "w\u0307"=>"\u1E87",
    "W\u0323"=>"\u1E88",
    "w\u0323"=>"\u1E89",
    "X\u0307"=>"\u1E8A",
    "x\u0307"=>"\u1E8B",
    "X\u0308"=>"\u1E8C",
    "x\u0308"=>"\u1E8D",
    "Y\u0307"=>"\u1E8E",
    "y\u0307"=>"\u1E8F",
    "Z\u0302"=>"\u1E90",
    "z\u0302"=>"\u1E91",
    "Z\u0323"=>"\u1E92",
    "z\u0323"=>"\u1E93",
    "Z\u0331"=>"\u1E94",
    "z\u0331"=>"\u1E95",
    "h\u0331"=>"\u1E96",
    "t\u0308"=>"\u1E97",
    "w\u030A"=>"\u1E98",
    "y\u030A"=>"\u1E99",
    "\u017F\u0307"=>"\u1E9B",
    "A\u0323"=>"\u1EA0",
    "a\u0323"=>"\u1EA1",
    "A\u0309"=>"\u1EA2",
    "a\u0309"=>"\u1EA3",
    "\u00C2\u0301"=>"\u1EA4",
    "\u00E2\u0301"=>"\u1EA5",
    "\u00C2\u0300"=>"\u1EA6",
    "\u00E2\u0300"=>"\u1EA7",
    "\u00C2\u0309"=>"\u1EA8",
    "\u00E2\u0309"=>"\u1EA9",
    "\u00C2\u0303"=>"\u1EAA",
    "\u00E2\u0303"=>"\u1EAB",
    "\u1EA0\u0302"=>"\u1EAC",
    "\u1EA1\u0302"=>"\u1EAD",
    "\u0102\u0301"=>"\u1EAE",
    "\u0103\u0301"=>"\u1EAF",
    "\u0102\u0300"=>"\u1EB0",
    "\u0103\u0300"=>"\u1EB1",
    "\u0102\u0309"=>"\u1EB2",
    "\u0103\u0309"=>"\u1EB3",
    "\u0102\u0303"=>"\u1EB4",
    "\u0103\u0303"=>"\u1EB5",
    "\u1EA0\u0306"=>"\u1EB6",
    "\u1EA1\u0306"=>"\u1EB7",
    "E\u0323"=>"\u1EB8",
    "e\u0323"=>"\u1EB9",
    "E\u0309"=>"\u1EBA",
    "e\u0309"=>"\u1EBB",
    "E\u0303"=>"\u1EBC",
    "e\u0303"=>"\u1EBD",
    "\u00CA\u0301"=>"\u1EBE",
    "\u00EA\u0301"=>"\u1EBF",
    "\u00CA\u0300"=>"\u1EC0",
    "\u00EA\u0300"=>"\u1EC1",
    "\u00CA\u0309"=>"\u1EC2",
    "\u00EA\u0309"=>"\u1EC3",
    "\u00CA\u0303"=>"\u1EC4",
    "\u00EA\u0303"=>"\u1EC5",
    "\u1EB8\u0302"=>"\u1EC6",
    "\u1EB9\u0302"=>"\u1EC7",
    "I\u0309"=>"\u1EC8",
    "i\u0309"=>"\u1EC9",
    "I\u0323"=>"\u1ECA",
    "i\u0323"=>"\u1ECB",
    "O\u0323"=>"\u1ECC",
    "o\u0323"=>"\u1ECD",
    "O\u0309"=>"\u1ECE",
    "o\u0309"=>"\u1ECF",
    "\u00D4\u0301"=>"\u1ED0",
    "\u00F4\u0301"=>"\u1ED1",
    "\u00D4\u0300"=>"\u1ED2",
    "\u00F4\u0300"=>"\u1ED3",
    "\u00D4\u0309"=>"\u1ED4",
    "\u00F4\u0309"=>"\u1ED5",
    "\u00D4\u0303"=>"\u1ED6",
    "\u00F4\u0303"=>"\u1ED7",
    "\u1ECC\u0302"=>"\u1ED8",
    "\u1ECD\u0302"=>"\u1ED9",
    "\u01A0\u0301"=>"\u1EDA",
    "\u01A1\u0301"=>"\u1EDB",
    "\u01A0\u0300"=>"\u1EDC",
    "\u01A1\u0300"=>"\u1EDD",
    "\u01A0\u0309"=>"\u1EDE",
    "\u01A1\u0309"=>"\u1EDF",
    "\u01A0\u0303"=>"\u1EE0",
    "\u01A1\u0303"=>"\u1EE1",
    "\u01A0\u0323"=>"\u1EE2",
    "\u01A1\u0323"=>"\u1EE3",
    "U\u0323"=>"\u1EE4",
    "u\u0323"=>"\u1EE5",
    "U\u0309"=>"\u1EE6",
    "u\u0309"=>"\u1EE7",
    "\u01AF\u0301"=>"\u1EE8",
    "\u01B0\u0301"=>"\u1EE9",
    "\u01AF\u0300"=>"\u1EEA",
    "\u01B0\u0300"=>"\u1EEB",
    "\u01AF\u0309"=>"\u1EEC",
    "\u01B0\u0309"=>"\u1EED",
    "\u01AF\u0303"=>"\u1EEE",
    "\u01B0\u0303"=>"\u1EEF",
    "\u01AF\u0323"=>"\u1EF0",
    "\u01B0\u0323"=>"\u1EF1",
    "Y\u0300"=>"\u1EF2",
    "y\u0300"=>"\u1EF3",
    "Y\u0323"=>"\u1EF4",
    "y\u0323"=>"\u1EF5",
    "Y\u0309"=>"\u1EF6",
    "y\u0309"=>"\u1EF7",
    "Y\u0303"=>"\u1EF8",
    "y\u0303"=>"\u1EF9",
    "\u03B1\u0313"=>"\u1F00",
    "\u03B1\u0314"=>"\u1F01",
    "\u1F00\u0300"=>"\u1F02",
    "\u1F01\u0300"=>"\u1F03",
    "\u1F00\u0301"=>"\u1F04",
    "\u1F01\u0301"=>"\u1F05",
    "\u1F00\u0342"=>"\u1F06",
    "\u1F01\u0342"=>"\u1F07",
    "\u0391\u0313"=>"\u1F08",
    "\u0391\u0314"=>"\u1F09",
    "\u1F08\u0300"=>"\u1F0A",
    "\u1F09\u0300"=>"\u1F0B",
    "\u1F08\u0301"=>"\u1F0C",
    "\u1F09\u0301"=>"\u1F0D",
    "\u1F08\u0342"=>"\u1F0E",
    "\u1F09\u0342"=>"\u1F0F",
    "\u03B5\u0313"=>"\u1F10",
    "\u03B5\u0314"=>"\u1F11",
    "\u1F10\u0300"=>"\u1F12",
    "\u1F11\u0300"=>"\u1F13",
    "\u1F10\u0301"=>"\u1F14",
    "\u1F11\u0301"=>"\u1F15",
    "\u0395\u0313"=>"\u1F18",
    "\u0395\u0314"=>"\u1F19",
    "\u1F18\u0300"=>"\u1F1A",
    "\u1F19\u0300"=>"\u1F1B",
    "\u1F18\u0301"=>"\u1F1C",
    "\u1F19\u0301"=>"\u1F1D",
    "\u03B7\u0313"=>"\u1F20",
    "\u03B7\u0314"=>"\u1F21",
    "\u1F20\u0300"=>"\u1F22",
    "\u1F21\u0300"=>"\u1F23",
    "\u1F20\u0301"=>"\u1F24",
    "\u1F21\u0301"=>"\u1F25",
    "\u1F20\u0342"=>"\u1F26",
    "\u1F21\u0342"=>"\u1F27",
    "\u0397\u0313"=>"\u1F28",
    "\u0397\u0314"=>"\u1F29",
    "\u1F28\u0300"=>"\u1F2A",
    "\u1F29\u0300"=>"\u1F2B",
    "\u1F28\u0301"=>"\u1F2C",
    "\u1F29\u0301"=>"\u1F2D",
    "\u1F28\u0342"=>"\u1F2E",
    "\u1F29\u0342"=>"\u1F2F",
    "\u03B9\u0313"=>"\u1F30",
    "\u03B9\u0314"=>"\u1F31",
    "\u1F30\u0300"=>"\u1F32",
    "\u1F31\u0300"=>"\u1F33",
    "\u1F30\u0301"=>"\u1F34",
    "\u1F31\u0301"=>"\u1F35",
    "\u1F30\u0342"=>"\u1F36",
    "\u1F31\u0342"=>"\u1F37",
    "\u0399\u0313"=>"\u1F38",
    "\u0399\u0314"=>"\u1F39",
    "\u1F38\u0300"=>"\u1F3A",
    "\u1F39\u0300"=>"\u1F3B",
    "\u1F38\u0301"=>"\u1F3C",
    "\u1F39\u0301"=>"\u1F3D",
    "\u1F38\u0342"=>"\u1F3E",
    "\u1F39\u0342"=>"\u1F3F",
    "\u03BF\u0313"=>"\u1F40",
    "\u03BF\u0314"=>"\u1F41",
    "\u1F40\u0300"=>"\u1F42",
    "\u1F41\u0300"=>"\u1F43",
    "\u1F40\u0301"=>"\u1F44",
    "\u1F41\u0301"=>"\u1F45",
    "\u039F\u0313"=>"\u1F48",
    "\u039F\u0314"=>"\u1F49",
    "\u1F48\u0300"=>"\u1F4A",
    "\u1F49\u0300"=>"\u1F4B",
    "\u1F48\u0301"=>"\u1F4C",
    "\u1F49\u0301"=>"\u1F4D",
    "\u03C5\u0313"=>"\u1F50",
    "\u03C5\u0314"=>"\u1F51",
    "\u1F50\u0300"=>"\u1F52",
    "\u1F51\u0300"=>"\u1F53",
    "\u1F50\u0301"=>"\u1F54",
    "\u1F51\u0301"=>"\u1F55",
    "\u1F50\u0342"=>"\u1F56",
    "\u1F51\u0342"=>"\u1F57",
    "\u03A5\u0314"=>"\u1F59",
    "\u1F59\u0300"=>"\u1F5B",
    "\u1F59\u0301"=>"\u1F5D",
    "\u1F59\u0342"=>"\u1F5F",
    "\u03C9\u0313"=>"\u1F60",
    "\u03C9\u0314"=>"\u1F61",
    "\u1F60\u0300"=>"\u1F62",
    "\u1F61\u0300"=>"\u1F63",
    "\u1F60\u0301"=>"\u1F64",
    "\u1F61\u0301"=>"\u1F65",
    "\u1F60\u0342"=>"\u1F66",
    "\u1F61\u0342"=>"\u1F67",
    "\u03A9\u0313"=>"\u1F68",
    "\u03A9\u0314"=>"\u1F69",
    "\u1F68\u0300"=>"\u1F6A",
    "\u1F69\u0300"=>"\u1F6B",
    "\u1F68\u0301"=>"\u1F6C",
    "\u1F69\u0301"=>"\u1F6D",
    "\u1F68\u0342"=>"\u1F6E",
    "\u1F69\u0342"=>"\u1F6F",
    "\u03B1\u0300"=>"\u1F70",
    "\u03B5\u0300"=>"\u1F72",
    "\u03B7\u0300"=>"\u1F74",
    "\u03B9\u0300"=>"\u1F76",
    "\u03BF\u0300"=>"\u1F78",
    "\u03C5\u0300"=>"\u1F7A",
    "\u03C9\u0300"=>"\u1F7C",
    "\u1F00\u0345"=>"\u1F80",
    "\u1F01\u0345"=>"\u1F81",
    "\u1F02\u0345"=>"\u1F82",
    "\u1F03\u0345"=>"\u1F83",
    "\u1F04\u0345"=>"\u1F84",
    "\u1F05\u0345"=>"\u1F85",
    "\u1F06\u0345"=>"\u1F86",
    "\u1F07\u0345"=>"\u1F87",
    "\u1F08\u0345"=>"\u1F88",
    "\u1F09\u0345"=>"\u1F89",
    "\u1F0A\u0345"=>"\u1F8A",
    "\u1F0B\u0345"=>"\u1F8B",
    "\u1F0C\u0345"=>"\u1F8C",
    "\u1F0D\u0345"=>"\u1F8D",
    "\u1F0E\u0345"=>"\u1F8E",
    "\u1F0F\u0345"=>"\u1F8F",
    "\u1F20\u0345"=>"\u1F90",
    "\u1F21\u0345"=>"\u1F91",
    "\u1F22\u0345"=>"\u1F92",
    "\u1F23\u0345"=>"\u1F93",
    "\u1F24\u0345"=>"\u1F94",
    "\u1F25\u0345"=>"\u1F95",
    "\u1F26\u0345"=>"\u1F96",
    "\u1F27\u0345"=>"\u1F97",
    "\u1F28\u0345"=>"\u1F98",
    "\u1F29\u0345"=>"\u1F99",
    "\u1F2A\u0345"=>"\u1F9A",
    "\u1F2B\u0345"=>"\u1F9B",
    "\u1F2C\u0345"=>"\u1F9C",
    "\u1F2D\u0345"=>"\u1F9D",
    "\u1F2E\u0345"=>"\u1F9E",
    "\u1F2F\u0345"=>"\u1F9F",
    "\u1F60\u0345"=>"\u1FA0",
    "\u1F61\u0345"=>"\u1FA1",
    "\u1F62\u0345"=>"\u1FA2",
    "\u1F63\u0345"=>"\u1FA3",
    "\u1F64\u0345"=>"\u1FA4",
    "\u1F65\u0345"=>"\u1FA5",
    "\u1F66\u0345"=>"\u1FA6",
    "\u1F67\u0345"=>"\u1FA7",
    "\u1F68\u0345"=>"\u1FA8",
    "\u1F69\u0345"=>"\u1FA9",
    "\u1F6A\u0345"=>"\u1FAA",
    "\u1F6B\u0345"=>"\u1FAB",
    "\u1F6C\u0345"=>"\u1FAC",
    "\u1F6D\u0345"=>"\u1FAD",
    "\u1F6E\u0345"=>"\u1FAE",
    "\u1F6F\u0345"=>"\u1FAF",
    "\u03B1\u0306"=>"\u1FB0",
    "\u03B1\u0304"=>"\u1FB1",
    "\u1F70\u0345"=>"\u1FB2",
    "\u03B1\u0345"=>"\u1FB3",
    "\u03AC\u0345"=>"\u1FB4",
    "\u03B1\u0342"=>"\u1FB6",
    "\u1FB6\u0345"=>"\u1FB7",
    "\u0391\u0306"=>"\u1FB8",
    "\u0391\u0304"=>"\u1FB9",
    "\u0391\u0300"=>"\u1FBA",
    "\u0391\u0345"=>"\u1FBC",
    "\u00A8\u0342"=>"\u1FC1",
    "\u1F74\u0345"=>"\u1FC2",
    "\u03B7\u0345"=>"\u1FC3",
    "\u03AE\u0345"=>"\u1FC4",
    "\u03B7\u0342"=>"\u1FC6",
    "\u1FC6\u0345"=>"\u1FC7",
    "\u0395\u0300"=>"\u1FC8",
    "\u0397\u0300"=>"\u1FCA",
    "\u0397\u0345"=>"\u1FCC",
    "\u1FBF\u0300"=>"\u1FCD",
    "\u1FBF\u0301"=>"\u1FCE",
    "\u1FBF\u0342"=>"\u1FCF",
    "\u03B9\u0306"=>"\u1FD0",
    "\u03B9\u0304"=>"\u1FD1",
    "\u03CA\u0300"=>"\u1FD2",
    "\u03B9\u0342"=>"\u1FD6",
    "\u03CA\u0342"=>"\u1FD7",
    "\u0399\u0306"=>"\u1FD8",
    "\u0399\u0304"=>"\u1FD9",
    "\u0399\u0300"=>"\u1FDA",
    "\u1FFE\u0300"=>"\u1FDD",
    "\u1FFE\u0301"=>"\u1FDE",
    "\u1FFE\u0342"=>"\u1FDF",
    "\u03C5\u0306"=>"\u1FE0",
    "\u03C5\u0304"=>"\u1FE1",
    "\u03CB\u0300"=>"\u1FE2",
    "\u03C1\u0313"=>"\u1FE4",
    "\u03C1\u0314"=>"\u1FE5",
    "\u03C5\u0342"=>"\u1FE6",
    "\u03CB\u0342"=>"\u1FE7",
    "\u03A5\u0306"=>"\u1FE8",
    "\u03A5\u0304"=>"\u1FE9",
    "\u03A5\u0300"=>"\u1FEA",
    "\u03A1\u0314"=>"\u1FEC",
    "\u00A8\u0300"=>"\u1FED",
    "\u1F7C\u0345"=>"\u1FF2",
    "\u03C9\u0345"=>"\u1FF3",
    "\u03CE\u0345"=>"\u1FF4",
    "\u03C9\u0342"=>"\u1FF6",
    "\u1FF6\u0345"=>"\u1FF7",
    "\u039F\u0300"=>"\u1FF8",
    "\u03A9\u0300"=>"\u1FFA",
    "\u03A9\u0345"=>"\u1FFC",
    "\u2190\u0338"=>"\u219A",
    "\u2192\u0338"=>"\u219B",
    "\u2194\u0338"=>"\u21AE",
    "\u21D0\u0338"=>"\u21CD",
    "\u21D4\u0338"=>"\u21CE",
    "\u21D2\u0338"=>"\u21CF",
    "\u2203\u0338"=>"\u2204",
    "\u2208\u0338"=>"\u2209",
    "\u220B\u0338"=>"\u220C",
    "\u2223\u0338"=>"\u2224",
    "\u2225\u0338"=>"\u2226",
    "\u223C\u0338"=>"\u2241",
    "\u2243\u0338"=>"\u2244",
    "\u2245\u0338"=>"\u2247",
    "\u2248\u0338"=>"\u2249",
    "=\u0338"=>"\u2260",
    "\u2261\u0338"=>"\u2262",
    "\u224D\u0338"=>"\u226D",
    "<\u0338"=>"\u226E",
    ">\u0338"=>"\u226F",
    "\u2264\u0338"=>"\u2270",
    "\u2265\u0338"=>"\u2271",
    "\u2272\u0338"=>"\u2274",
    "\u2273\u0338"=>"\u2275",
    "\u2276\u0338"=>"\u2278",
    "\u2277\u0338"=>"\u2279",
    "\u227A\u0338"=>"\u2280",
    "\u227B\u0338"=>"\u2281",
    "\u2282\u0338"=>"\u2284",
    "\u2283\u0338"=>"\u2285",
    "\u2286\u0338"=>"\u2288",
    "\u2287\u0338"=>"\u2289",
    "\u22A2\u0338"=>"\u22AC",
    "\u22A8\u0338"=>"\u22AD",
    "\u22A9\u0338"=>"\u22AE",
    "\u22AB\u0338"=>"\u22AF",
    "\u227C\u0338"=>"\u22E0",
    "\u227D\u0338"=>"\u22E1",
    "\u2291\u0338"=>"\u22E2",
    "\u2292\u0338"=>"\u22E3",
    "\u22B2\u0338"=>"\u22EA",
    "\u22B3\u0338"=>"\u22EB",
    "\u22B4\u0338"=>"\u22EC",
    "\u22B5\u0338"=>"\u22ED",
    "\u304B\u3099"=>"\u304C",
    "\u304D\u3099"=>"\u304E",
    "\u304F\u3099"=>"\u3050",
    "\u3051\u3099"=>"\u3052",
    "\u3053\u3099"=>"\u3054",
    "\u3055\u3099"=>"\u3056",
    "\u3057\u3099"=>"\u3058",
    "\u3059\u3099"=>"\u305A",
    "\u305B\u3099"=>"\u305C",
    "\u305D\u3099"=>"\u305E",
    "\u305F\u3099"=>"\u3060",
    "\u3061\u3099"=>"\u3062",
    "\u3064\u3099"=>"\u3065",
    "\u3066\u3099"=>"\u3067",
    "\u3068\u3099"=>"\u3069",
    "\u306F\u3099"=>"\u3070",
    "\u306F\u309A"=>"\u3071",
    "\u3072\u3099"=>"\u3073",
    "\u3072\u309A"=>"\u3074",
    "\u3075\u3099"=>"\u3076",
    "\u3075\u309A"=>"\u3077",
    "\u3078\u3099"=>"\u3079",
    "\u3078\u309A"=>"\u307A",
    "\u307B\u3099"=>"\u307C",
    "\u307B\u309A"=>"\u307D",
    "\u3046\u3099"=>"\u3094",
    "\u309D\u3099"=>"\u309E",
    "\u30AB\u3099"=>"\u30AC",
    "\u30AD\u3099"=>"\u30AE",
    "\u30AF\u3099"=>"\u30B0",
    "\u30B1\u3099"=>"\u30B2",
    "\u30B3\u3099"=>"\u30B4",
    "\u30B5\u3099"=>"\u30B6",
    "\u30B7\u3099"=>"\u30B8",
    "\u30B9\u3099"=>"\u30BA",
    "\u30BB\u3099"=>"\u30BC",
    "\u30BD\u3099"=>"\u30BE",
    "\u30BF\u3099"=>"\u30C0",
    "\u30C1\u3099"=>"\u30C2",
    "\u30C4\u3099"=>"\u30C5",
    "\u30C6\u3099"=>"\u30C7",
    "\u30C8\u3099"=>"\u30C9",
    "\u30CF\u3099"=>"\u30D0",
    "\u30CF\u309A"=>"\u30D1",
    "\u30D2\u3099"=>"\u30D3",
    "\u30D2\u309A"=>"\u30D4",
    "\u30D5\u3099"=>"\u30D6",
    "\u30D5\u309A"=>"\u30D7",
    "\u30D8\u3099"=>"\u30D9",
    "\u30D8\u309A"=>"\u30DA",
    "\u30DB\u3099"=>"\u30DC",
    "\u30DB\u309A"=>"\u30DD",
    "\u30A6\u3099"=>"\u30F4",
    "\u30EF\u3099"=>"\u30F7",
    "\u30F0\u3099"=>"\u30F8",
    "\u30F1\u3099"=>"\u30F9",
    "\u30F2\u3099"=>"\u30FA",
    "\u30FD\u3099"=>"\u30FE",
    "\u{11099}\u{110BA}"=>"\u{1109A}",
    "\u{1109B}\u{110BA}"=>"\u{1109C}",
    "\u{110A5}\u{110BA}"=>"\u{110AB}",
    "\u{11131}\u{11127}"=>"\u{1112E}",
    "\u{11132}\u{11127}"=>"\u{1112F}",
    "\u{11347}\u{1133E}"=>"\u{1134B}",
    "\u{11347}\u{11357}"=>"\u{1134C}",
    "\u{114B9}\u{114BA}"=>"\u{114BB}",
    "\u{114B9}\u{114B0}"=>"\u{114BC}",
    "\u{114B9}\u{114BD}"=>"\u{114BE}",
    "\u{115B8}\u{115AF}"=>"\u{115BA}",
    "\u{115B9}\u{115AF}"=>"\u{115BB}",
  }.freeze
end
# frozen_string_literal: true
require 'psych/versions'
case RUBY_ENGINE
when 'jruby'
  require '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 'psych/nodes'
require 'psych/streaming'
require 'psych/visitors'
require 'psych/handler'
require 'psych/tree_builder'
require 'psych/parser'
require 'psych/omap'
require 'psych/set'
require 'psych/coder'
require 'psych/core_ext'
require 'psych/stream'
require 'psych/json/tree_builder'
require 'psych/json/stream'
require 'psych/handlers/document_stream'
require 'psych/class_loader'

###
# = Overview
#
# Psych is a YAML parser and emitter.
# Psych leverages libyaml [Home page: https://pyyaml.org/wiki/LibYAML]
# or [HG repo: https://bitbucket.org/xi/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)  # => #<StringIO:0x000001009d0890>
#
#   # 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) # => #<Psych::Parser>
#   parser = Psych.parser                       # it's an alias for the above
#
#   parser.parse("---\n - a\n - b")             # => #<Psych::Parser>
#   parser.handler                              # => #<Psych::TreeBuilder>
#   parser.handler.root                         # => #<Psych::Nodes::Stream>
#
# ==== 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")       # => #<Psych::Parser>
#
#   parser.handler.first              # => #<Psych::Nodes::Stream>
#   parser.handler.first.to_ruby      # => ["a"]
#
#   parser.handler.root.first         # => #<Psych::Nodes::Document>
#   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
  # Deprecation guard
  NOT_GIVEN = Object.new.freeze
  private_constant :NOT_GIVEN

  ###
  # 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
  #
  # 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 method.
  #
  def self.unsafe_load yaml, legacy_filename = NOT_GIVEN, filename: nil, fallback: false, symbolize_names: false, freeze: false
    if legacy_filename != NOT_GIVEN
      warn_with_uplevel 'Passing filename with the 2nd argument of Psych.load is deprecated. Use keyword argument like Psych.load(yaml, filename: ...) instead.', uplevel: 1 if $VERBOSE
      filename = legacy_filename
    end

    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
  # * Numeric
  # * 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, legacy_permitted_classes = NOT_GIVEN, legacy_permitted_symbols = NOT_GIVEN, legacy_aliases = NOT_GIVEN, legacy_filename = NOT_GIVEN, permitted_classes: [], permitted_symbols: [], aliases: false, filename: nil, fallback: nil, symbolize_names: false, freeze: false
    if legacy_permitted_classes != NOT_GIVEN
      warn_with_uplevel 'Passing permitted_classes with the 2nd argument of Psych.safe_load is deprecated. Use keyword argument like Psych.safe_load(yaml, permitted_classes: ...) instead.', uplevel: 1 if $VERBOSE
      permitted_classes = legacy_permitted_classes
    end

    if legacy_permitted_symbols != NOT_GIVEN
      warn_with_uplevel 'Passing permitted_symbols with the 3rd argument of Psych.safe_load is deprecated. Use keyword argument like Psych.safe_load(yaml, permitted_symbols: ...) instead.', uplevel: 1 if $VERBOSE
      permitted_symbols = legacy_permitted_symbols
    end

    if legacy_aliases != NOT_GIVEN
      warn_with_uplevel 'Passing aliases with the 4th argument of Psych.safe_load is deprecated. Use keyword argument like Psych.safe_load(yaml, aliases: ...) instead.', uplevel: 1 if $VERBOSE
      aliases = legacy_aliases
    end

    if legacy_filename != NOT_GIVEN
      warn_with_uplevel 'Passing filename with the 5th argument of Psych.safe_load is deprecated. Use keyword argument like Psych.safe_load(yaml, filename: ...) instead.', uplevel: 1 if $VERBOSE
      filename = legacy_filename
    end

    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

  ###
  # 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") # => #<Psych::Nodes::Document:0x00>
  #
  #   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, legacy_filename = NOT_GIVEN, filename: nil, fallback: NOT_GIVEN
    if legacy_filename != NOT_GIVEN
      warn_with_uplevel 'Passing filename with the 2nd argument of Psych.parse is deprecated. Use keyword argument like Psych.parse(yaml, filename: ...) instead.', uplevel: 1 if $VERBOSE
      filename = legacy_filename
    end

    parse_stream(yaml, filename: filename) do |node|
      return node
    end

    if fallback != NOT_GIVEN
      warn_with_uplevel 'Passing the `fallback` keyword argument of Psych.parse is deprecated.', uplevel: 1 if $VERBOSE
      fallback
    else
      false
    end
  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::Nodes::Stream:0x00>
  #
  #   Psych.parse_stream("--- a\n--- b") do |node|
  #     node # => #<Psych::Nodes::Document:0x00>
  #   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, legacy_filename = NOT_GIVEN, filename: nil, &block
    if legacy_filename != NOT_GIVEN
      warn_with_uplevel 'Passing filename with the 2nd argument of Psych.parse_stream is deprecated. Use keyword argument like Psych.parse_stream(yaml, filename: ...) instead.', uplevel: 1 if $VERBOSE
      filename = legacy_filename
    end

    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:
  #
  # [<tt>:indentation</tt>]   Number of space characters used to indent.
  #                           Acceptable value should be in <tt>0..9</tt> range,
  #                           otherwise option is ignored.
  #
  #                           Default: <tt>2</tt>.
  # [<tt>:line_width</tt>]    Max character to wrap line at.
  #
  #                           Default: <tt>0</tt> (meaning "wrap at 81").
  # [<tt>:canonical</tt>]     Write "canonical" YAML form (very verbose, yet
  #                           strictly formal).
  #
  #                           Default: <tt>false</tt>.
  # [<tt>:header</tt>]        Write <tt>%YAML [version]</tt> at the beginning of document.
  #
  #                           Default: <tt>false</tt>.
  #
  # 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)  # => #<StringIO:0x000001009d0890>
  #
  #   # 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

  ###
  # 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, legacy_filename = NOT_GIVEN, filename: nil, fallback: [], **kwargs
    if legacy_filename != NOT_GIVEN
      warn_with_uplevel 'Passing filename with the 2nd argument of Psych.load_stream is deprecated. Use keyword argument like Psych.load_stream(yaml, filename: ...) instead.', uplevel: 1 if $VERBOSE
      filename = legacy_filename
    end

    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
  class << self; alias :load_file :unsafe_load_file; 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

  # :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
# frozen_string_literal: true
#--
# benchmark.rb - a performance benchmarking library
#
# $Id$
#
# Created by Gotoken (gotoken@notwork.org).
#
# Documentation by Gotoken (original RD), Lyle Johnson (RDoc conversion), and
# Gavin Sinclair (editing).
#++
#
# == Overview
#
# The Benchmark module provides methods for benchmarking Ruby code, giving
# detailed reports on the time taken for each task.
#

# The Benchmark module provides methods to measure and report the time
# used to execute Ruby code.
#
# * Measure the time to construct the string given by the expression
#   <code>"a"*1_000_000_000</code>:
#
#       require 'benchmark'
#
#       puts Benchmark.measure { "a"*1_000_000_000 }
#
#   On my machine (OSX 10.8.3 on i5 1.7 GHz) this generates:
#
#       0.350000   0.400000   0.750000 (  0.835234)
#
#   This report shows the user CPU time, system CPU time, the sum of
#   the user and system CPU times, and the elapsed real time. The unit
#   of time is seconds.
#
# * Do some experiments sequentially using the #bm method:
#
#       require 'benchmark'
#
#       n = 5000000
#       Benchmark.bm do |x|
#         x.report { for i in 1..n; a = "1"; end }
#         x.report { n.times do   ; a = "1"; end }
#         x.report { 1.upto(n) do ; a = "1"; end }
#       end
#
#   The result:
#
#              user     system      total        real
#          1.010000   0.000000   1.010000 (  1.014479)
#          1.000000   0.000000   1.000000 (  0.998261)
#          0.980000   0.000000   0.980000 (  0.981335)
#
# * Continuing the previous example, put a label in each report:
#
#       require 'benchmark'
#
#       n = 5000000
#       Benchmark.bm(7) do |x|
#         x.report("for:")   { for i in 1..n; a = "1"; end }
#         x.report("times:") { n.times do   ; a = "1"; end }
#         x.report("upto:")  { 1.upto(n) do ; a = "1"; end }
#       end
#
# The result:
#
#                     user     system      total        real
#       for:      1.010000   0.000000   1.010000 (  1.015688)
#       times:    1.000000   0.000000   1.000000 (  1.003611)
#       upto:     1.030000   0.000000   1.030000 (  1.028098)
#
# * The times for some benchmarks depend on the order in which items
#   are run.  These differences are due to the cost of memory
#   allocation and garbage collection. To avoid these discrepancies,
#   the #bmbm method is provided.  For example, to compare ways to
#   sort an array of floats:
#
#       require 'benchmark'
#
#       array = (1..1000000).map { rand }
#
#       Benchmark.bmbm do |x|
#         x.report("sort!") { array.dup.sort! }
#         x.report("sort")  { array.dup.sort  }
#       end
#
#   The result:
#
#        Rehearsal -----------------------------------------
#        sort!   1.490000   0.010000   1.500000 (  1.490520)
#        sort    1.460000   0.000000   1.460000 (  1.463025)
#        -------------------------------- total: 2.960000sec
#
#                    user     system      total        real
#        sort!   1.460000   0.000000   1.460000 (  1.460465)
#        sort    1.450000   0.010000   1.460000 (  1.448327)
#
# * Report statistics of sequential experiments with unique labels,
#   using the #benchmark method:
#
#       require 'benchmark'
#       include Benchmark         # we need the CAPTION and FORMAT constants
#
#       n = 5000000
#       Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x|
#         tf = x.report("for:")   { for i in 1..n; a = "1"; end }
#         tt = x.report("times:") { n.times do   ; a = "1"; end }
#         tu = x.report("upto:")  { 1.upto(n) do ; a = "1"; end }
#         [tf+tt+tu, (tf+tt+tu)/3]
#       end
#
#   The result:
#
#                     user     system      total        real
#        for:      0.950000   0.000000   0.950000 (  0.952039)
#        times:    0.980000   0.000000   0.980000 (  0.984938)
#        upto:     0.950000   0.000000   0.950000 (  0.946787)
#        >total:   2.880000   0.000000   2.880000 (  2.883764)
#        >avg:     0.960000   0.000000   0.960000 (  0.961255)

module Benchmark

  BENCHMARK_VERSION = "2002-04-25" # :nodoc:

  # Invokes the block with a Benchmark::Report object, which
  # may be used to collect and report on the results of individual
  # benchmark tests. Reserves +label_width+ leading spaces for
  # labels on each line. Prints +caption+ at the top of the
  # report, and uses +format+ to format each line.
  # Returns an array of Benchmark::Tms objects.
  #
  # If the block returns an array of
  # Benchmark::Tms objects, these will be used to format
  # additional lines of output. If +labels+ parameter are
  # given, these are used to label these extra lines.
  #
  # _Note_: Other methods provide a simpler interface to this one, and are
  # suitable for nearly all benchmarking requirements.  See the examples in
  # Benchmark, and the #bm and #bmbm methods.
  #
  # Example:
  #
  #     require 'benchmark'
  #     include Benchmark          # we need the CAPTION and FORMAT constants
  #
  #     n = 5000000
  #     Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x|
  #       tf = x.report("for:")   { for i in 1..n; a = "1"; end }
  #       tt = x.report("times:") { n.times do   ; a = "1"; end }
  #       tu = x.report("upto:")  { 1.upto(n) do ; a = "1"; end }
  #       [tf+tt+tu, (tf+tt+tu)/3]
  #     end
  #
  # Generates:
  #
  #                     user     system      total        real
  #       for:      0.970000   0.000000   0.970000 (  0.970493)
  #       times:    0.990000   0.000000   0.990000 (  0.989542)
  #       upto:     0.970000   0.000000   0.970000 (  0.972854)
  #       >total:   2.930000   0.000000   2.930000 (  2.932889)
  #       >avg:     0.976667   0.000000   0.976667 (  0.977630)
  #

  def benchmark(caption = "", label_width = nil, format = nil, *labels) # :yield: report
    sync = STDOUT.sync
    STDOUT.sync = true
    label_width ||= 0
    label_width += 1
    format ||= FORMAT
    print ' '*label_width + caption unless caption.empty?
    report = Report.new(label_width, format)
    results = yield(report)
    Array === results and results.grep(Tms).each {|t|
      print((labels.shift || t.label || "").ljust(label_width), t.format(format))
    }
    report.list
  ensure
    STDOUT.sync = sync unless sync.nil?
  end


  # A simple interface to the #benchmark method, #bm generates sequential
  # reports with labels. +label_width+ and +labels+ parameters have the same
  # meaning as for #benchmark.
  #
  #     require 'benchmark'
  #
  #     n = 5000000
  #     Benchmark.bm(7) do |x|
  #       x.report("for:")   { for i in 1..n; a = "1"; end }
  #       x.report("times:") { n.times do   ; a = "1"; end }
  #       x.report("upto:")  { 1.upto(n) do ; a = "1"; end }
  #     end
  #
  # Generates:
  #
  #                     user     system      total        real
  #       for:      0.960000   0.000000   0.960000 (  0.957966)
  #       times:    0.960000   0.000000   0.960000 (  0.960423)
  #       upto:     0.950000   0.000000   0.950000 (  0.954864)
  #

  def bm(label_width = 0, *labels, &blk) # :yield: report
    benchmark(CAPTION, label_width, FORMAT, *labels, &blk)
  end


  # Sometimes benchmark results are skewed because code executed
  # earlier encounters different garbage collection overheads than
  # that run later. #bmbm attempts to minimize this effect by running
  # the tests twice, the first time as a rehearsal in order to get the
  # runtime environment stable, the second time for
  # real. GC.start is executed before the start of each of
  # the real timings; the cost of this is not included in the
  # timings. In reality, though, there's only so much that #bmbm can
  # do, and the results are not guaranteed to be isolated from garbage
  # collection and other effects.
  #
  # Because #bmbm takes two passes through the tests, it can
  # calculate the required label width.
  #
  #       require 'benchmark'
  #
  #       array = (1..1000000).map { rand }
  #
  #       Benchmark.bmbm do |x|
  #         x.report("sort!") { array.dup.sort! }
  #         x.report("sort")  { array.dup.sort  }
  #       end
  #
  # Generates:
  #
  #        Rehearsal -----------------------------------------
  #        sort!   1.440000   0.010000   1.450000 (  1.446833)
  #        sort    1.440000   0.000000   1.440000 (  1.448257)
  #        -------------------------------- total: 2.890000sec
  #
  #                    user     system      total        real
  #        sort!   1.460000   0.000000   1.460000 (  1.458065)
  #        sort    1.450000   0.000000   1.450000 (  1.455963)
  #
  # #bmbm yields a Benchmark::Job object and returns an array of
  # Benchmark::Tms objects.
  #
  def bmbm(width = 0) # :yield: job
    job = Job.new(width)
    yield(job)
    width = job.width + 1
    sync = STDOUT.sync
    STDOUT.sync = true

    # rehearsal
    puts 'Rehearsal '.ljust(width+CAPTION.length,'-')
    ets = job.list.inject(Tms.new) { |sum,(label,item)|
      print label.ljust(width)
      res = Benchmark.measure(&item)
      print res.format
      sum + res
    }.format("total: %tsec")
    print " #{ets}\n\n".rjust(width+CAPTION.length+2,'-')

    # take
    print ' '*width + CAPTION
    job.list.map { |label,item|
      GC.start
      print label.ljust(width)
      Benchmark.measure(label, &item).tap { |res| print res }
    }
  ensure
    STDOUT.sync = sync unless sync.nil?
  end

  #
  # Returns the time used to execute the given block as a
  # Benchmark::Tms object. Takes +label+ option.
  #
  #       require 'benchmark'
  #
  #       n = 1000000
  #
  #       time = Benchmark.measure do
  #         n.times { a = "1" }
  #       end
  #       puts time
  #
  # Generates:
  #
  #        0.220000   0.000000   0.220000 (  0.227313)
  #
  def measure(label = "") # :yield:
    t0, r0 = Process.times, Process.clock_gettime(Process::CLOCK_MONOTONIC)
    yield
    t1, r1 = Process.times, Process.clock_gettime(Process::CLOCK_MONOTONIC)
    Benchmark::Tms.new(t1.utime  - t0.utime,
                       t1.stime  - t0.stime,
                       t1.cutime - t0.cutime,
                       t1.cstime - t0.cstime,
                       r1 - r0,
                       label)
  end

  #
  # Returns the elapsed real time used to execute the given block.
  #
  def realtime # :yield:
    r0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    yield
    Process.clock_gettime(Process::CLOCK_MONOTONIC) - r0
  end

  module_function :benchmark, :measure, :realtime, :bm, :bmbm

  #
  # A Job is a sequence of labelled blocks to be processed by the
  # Benchmark.bmbm method.  It is of little direct interest to the user.
  #
  class Job # :nodoc:
    #
    # Returns an initialized Job instance.
    # Usually, one doesn't call this method directly, as new
    # Job objects are created by the #bmbm method.
    # +width+ is a initial value for the label offset used in formatting;
    # the #bmbm method passes its +width+ argument to this constructor.
    #
    def initialize(width)
      @width = width
      @list = []
    end

    #
    # Registers the given label and block pair in the job list.
    #
    def item(label = "", &blk) # :yield:
      raise ArgumentError, "no block" unless block_given?
      label = label.to_s
      w = label.length
      @width = w if @width < w
      @list << [label, blk]
      self
    end

    alias report item

    # An array of 2-element arrays, consisting of label and block pairs.
    attr_reader :list

    # Length of the widest label in the #list.
    attr_reader :width
  end

  #
  # This class is used by the Benchmark.benchmark and Benchmark.bm methods.
  # It is of little direct interest to the user.
  #
  class Report # :nodoc:
    #
    # Returns an initialized Report instance.
    # Usually, one doesn't call this method directly, as new
    # Report objects are created by the #benchmark and #bm methods.
    # +width+ and +format+ are the label offset and
    # format string used by Tms#format.
    #
    def initialize(width = 0, format = nil)
      @width, @format, @list = width, format, []
    end

    #
    # Prints the +label+ and measured time for the block,
    # formatted by +format+. See Tms#format for the
    # formatting rules.
    #
    def item(label = "", *format, &blk) # :yield:
      print label.to_s.ljust(@width)
      @list << res = Benchmark.measure(label, &blk)
      print res.format(@format, *format)
      res
    end

    alias report item

    # An array of Benchmark::Tms objects representing each item.
    attr_reader :list
  end



  #
  # A data object, representing the times associated with a benchmark
  # measurement.
  #
  class Tms

    # Default caption, see also Benchmark::CAPTION
    CAPTION = "      user     system      total        real\n"

    # Default format string, see also Benchmark::FORMAT
    FORMAT = "%10.6u %10.6y %10.6t %10.6r\n"

    # User CPU time
    attr_reader :utime

    # System CPU time
    attr_reader :stime

    # User CPU time of children
    attr_reader :cutime

    # System CPU time of children
    attr_reader :cstime

    # Elapsed real time
    attr_reader :real

    # Total time, that is +utime+ + +stime+ + +cutime+ + +cstime+
    attr_reader :total

    # Label
    attr_reader :label

    #
    # Returns an initialized Tms object which has
    # +utime+ as the user CPU time, +stime+ as the system CPU time,
    # +cutime+ as the children's user CPU time, +cstime+ as the children's
    # system CPU time, +real+ as the elapsed real time and +label+ as the label.
    #
    def initialize(utime = 0.0, stime = 0.0, cutime = 0.0, cstime = 0.0, real = 0.0, label = nil)
      @utime, @stime, @cutime, @cstime, @real, @label = utime, stime, cutime, cstime, real, label.to_s
      @total = @utime + @stime + @cutime + @cstime
    end

    #
    # Returns a new Tms object whose times are the sum of the times for this
    # Tms object, plus the time required to execute the code block (+blk+).
    #
    def add(&blk) # :yield:
      self + Benchmark.measure(&blk)
    end

    #
    # An in-place version of #add.
    # Changes the times of this Tms object by making it the sum of the times
    # for this Tms object, plus the time required to execute
    # the code block (+blk+).
    #
    def add!(&blk)
      t = Benchmark.measure(&blk)
      @utime  = utime + t.utime
      @stime  = stime + t.stime
      @cutime = cutime + t.cutime
      @cstime = cstime + t.cstime
      @real   = real + t.real
      self
    end

    #
    # Returns a new Tms object obtained by memberwise summation
    # of the individual times for this Tms object with those of the +other+
    # Tms object.
    # This method and #/() are useful for taking statistics.
    #
    def +(other); memberwise(:+, other) end

    #
    # Returns a new Tms object obtained by memberwise subtraction
    # of the individual times for the +other+ Tms object from those of this
    # Tms object.
    #
    def -(other); memberwise(:-, other) end

    #
    # Returns a new Tms object obtained by memberwise multiplication
    # of the individual times for this Tms object by +x+.
    #
    def *(x); memberwise(:*, x) end

    #
    # Returns a new Tms object obtained by memberwise division
    # of the individual times for this Tms object by +x+.
    # This method and #+() are useful for taking statistics.
    #
    def /(x); memberwise(:/, x) end

    #
    # Returns the contents of this Tms object as
    # a formatted string, according to a +format+ string
    # like that passed to Kernel.format. In addition, #format
    # accepts the following extensions:
    #
    # <tt>%u</tt>::     Replaced by the user CPU time, as reported by Tms#utime.
    # <tt>%y</tt>::     Replaced by the system CPU time, as reported by #stime (Mnemonic: y of "s*y*stem")
    # <tt>%U</tt>::     Replaced by the children's user CPU time, as reported by Tms#cutime
    # <tt>%Y</tt>::     Replaced by the children's system CPU time, as reported by Tms#cstime
    # <tt>%t</tt>::     Replaced by the total CPU time, as reported by Tms#total
    # <tt>%r</tt>::     Replaced by the elapsed real time, as reported by Tms#real
    # <tt>%n</tt>::     Replaced by the label string, as reported by Tms#label (Mnemonic: n of "*n*ame")
    #
    # If +format+ is not given, FORMAT is used as default value, detailing the
    # user, system and real elapsed time.
    #
    def format(format = nil, *args)
      str = (format || FORMAT).dup
      str.gsub!(/(%[-+.\d]*)n/) { "#{$1}s" % label }
      str.gsub!(/(%[-+.\d]*)u/) { "#{$1}f" % utime }
      str.gsub!(/(%[-+.\d]*)y/) { "#{$1}f" % stime }
      str.gsub!(/(%[-+.\d]*)U/) { "#{$1}f" % cutime }
      str.gsub!(/(%[-+.\d]*)Y/) { "#{$1}f" % cstime }
      str.gsub!(/(%[-+.\d]*)t/) { "#{$1}f" % total }
      str.gsub!(/(%[-+.\d]*)r/) { "(#{$1}f)" % real }
      format ? str % args : str
    end

    #
    # Same as #format.
    #
    def to_s
      format
    end

    #
    # Returns a new 6-element array, consisting of the
    # label, user CPU time, system CPU time, children's
    # user CPU time, children's system CPU time and elapsed
    # real time.
    #
    def to_a
      [@label, @utime, @stime, @cutime, @cstime, @real]
    end

    protected

    #
    # Returns a new Tms object obtained by memberwise operation +op+
    # of the individual times for this Tms object with those of the other
    # Tms object (+x+).
    #
    # +op+ can be a mathematical operation such as <tt>+</tt>, <tt>-</tt>,
    # <tt>*</tt>, <tt>/</tt>
    #
    def memberwise(op, x)
      case x
      when Benchmark::Tms
        Benchmark::Tms.new(utime.__send__(op, x.utime),
                           stime.__send__(op, x.stime),
                           cutime.__send__(op, x.cutime),
                           cstime.__send__(op, x.cstime),
                           real.__send__(op, x.real)
                           )
      else
        Benchmark::Tms.new(utime.__send__(op, x),
                           stime.__send__(op, x),
                           cutime.__send__(op, x),
                           cstime.__send__(op, x),
                           real.__send__(op, x)
                           )
      end
    end
  end

  # The default caption string (heading above the output times).
  CAPTION = Benchmark::Tms::CAPTION

  # The default format string used to display times.  See also Benchmark::Tms#format.
  FORMAT = Benchmark::Tms::FORMAT
end
# frozen_string_literal: true
#
# tempfile - manipulates temporary files
#
# $Id$
#

require 'delegate'
require 'tmpdir'

# A utility class for managing temporary files. When you create a Tempfile
# object, it will create a temporary file with a unique filename. A Tempfile
# objects behaves just like a File object, and you can perform all the usual
# file operations on it: reading data, writing data, changing its permissions,
# etc. So although this class does not explicitly document all instance methods
# supported by File, you can in fact call any File instance method on a
# Tempfile object.
#
# == Synopsis
#
#   require 'tempfile'
#
#   file = Tempfile.new('foo')
#   file.path      # => A unique filename in the OS's temp directory,
#                  #    e.g.: "/tmp/foo.24722.0"
#                  #    This filename contains 'foo' in its basename.
#   file.write("hello world")
#   file.rewind
#   file.read      # => "hello world"
#   file.close
#   file.unlink    # deletes the temp file
#
# == Good practices
#
# === Explicit close
#
# When a Tempfile object is garbage collected, or when the Ruby interpreter
# exits, its associated temporary file is automatically deleted. This means
# that's it's unnecessary to explicitly delete a Tempfile after use, though
# it's good practice to do so: not explicitly deleting unused Tempfiles can
# potentially leave behind large amounts of tempfiles on the filesystem
# until they're garbage collected. The existence of these temp files can make
# it harder to determine a new Tempfile filename.
#
# Therefore, one should always call #unlink or close in an ensure block, like
# this:
#
#   file = Tempfile.new('foo')
#   begin
#      # ...do something with file...
#   ensure
#      file.close
#      file.unlink   # deletes the temp file
#   end
#
# Tempfile.create { ... } exists for this purpose and is more convenient to use.
# Note that Tempfile.create returns a File instance instead of a Tempfile, which
# also avoids the overhead and complications of delegation.
#
#   Tempfile.open('foo') do |file|
#      # ...do something with file...
#   end
#
# === Unlink after creation
#
# On POSIX systems, it's possible to unlink a file right after creating it,
# and before closing it. This removes the filesystem entry without closing
# the file handle, so it ensures that only the processes that already had
# the file handle open can access the file's contents. It's strongly
# recommended that you do this if you do not want any other processes to
# be able to read from or write to the Tempfile, and you do not need to
# know the Tempfile's filename either.
#
# For example, a practical use case for unlink-after-creation would be this:
# you need a large byte buffer that's too large to comfortably fit in RAM,
# e.g. when you're writing a web server and you want to buffer the client's
# file upload data.
#
# Please refer to #unlink for more information and a code example.
#
# == Minor notes
#
# Tempfile's filename picking method is both thread-safe and inter-process-safe:
# it guarantees that no other threads or processes will pick the same filename.
#
# Tempfile itself however may not be entirely thread-safe. If you access the
# same Tempfile object from multiple threads then you should protect it with a
# mutex.
class Tempfile < DelegateClass(File)
  # Creates a temporary file with permissions 0600 (= only readable and
  # writable by the owner) and opens it with mode "w+".
  #
  # It is recommended to use Tempfile.create { ... } instead when possible,
  # because that method avoids the cost of delegation and does not rely on a
  # finalizer to close and unlink the file, which is unreliable.
  #
  # The +basename+ parameter is used to determine the name of the
  # temporary file. You can either pass a String or an Array with
  # 2 String elements. In the former form, the temporary file's base
  # name will begin with the given string. In the latter form,
  # the temporary file's base name will begin with the array's first
  # element, and end with the second element. For example:
  #
  #   file = Tempfile.new('hello')
  #   file.path  # => something like: "/tmp/hello2843-8392-92849382--0"
  #
  #   # Use the Array form to enforce an extension in the filename:
  #   file = Tempfile.new(['hello', '.jpg'])
  #   file.path  # => something like: "/tmp/hello2843-8392-92849382--0.jpg"
  #
  # The temporary file will be placed in the directory as specified
  # by the +tmpdir+ parameter. By default, this is +Dir.tmpdir+.
  #
  #   file = Tempfile.new('hello', '/home/aisaka')
  #   file.path  # => something like: "/home/aisaka/hello2843-8392-92849382--0"
  #
  # You can also pass an options hash. Under the hood, Tempfile creates
  # the temporary file using +File.open+. These options will be passed to
  # +File.open+. This is mostly useful for specifying encoding
  # options, e.g.:
  #
  #   Tempfile.new('hello', '/home/aisaka', encoding: 'ascii-8bit')
  #
  #   # You can also omit the 'tmpdir' parameter:
  #   Tempfile.new('hello', encoding: 'ascii-8bit')
  #
  # Note: +mode+ keyword argument, as accepted by Tempfile, can only be
  # numeric, combination of the modes defined in File::Constants.
  #
  # === Exceptions
  #
  # If Tempfile.new cannot find a unique filename within a limited
  # number of tries, then it will raise an exception.
  def initialize(basename="", tmpdir=nil, mode: 0, **options)
    warn "Tempfile.new doesn't call the given block.", uplevel: 1 if block_given?

    @unlinked = false
    @mode = mode|File::RDWR|File::CREAT|File::EXCL
    ::Dir::Tmpname.create(basename, tmpdir, **options) do |tmpname, n, opts|
      opts[:perm] = 0600
      @tmpfile = File.open(tmpname, @mode, **opts)
      @opts = opts.freeze
    end
    ObjectSpace.define_finalizer(self, Remover.new(@tmpfile))

    super(@tmpfile)
  end

  # Opens or reopens the file with mode "r+".
  def open
    _close
    mode = @mode & ~(File::CREAT|File::EXCL)
    @tmpfile = File.open(@tmpfile.path, mode, **@opts)
    __setobj__(@tmpfile)
  end

  def _close    # :nodoc:
    @tmpfile.close
  end
  protected :_close

  # Closes the file. If +unlink_now+ is true, then the file will be unlinked
  # (deleted) after closing. Of course, you can choose to later call #unlink
  # if you do not unlink it now.
  #
  # If you don't explicitly unlink the temporary file, the removal
  # will be delayed until the object is finalized.
  def close(unlink_now=false)
    _close
    unlink if unlink_now
  end

  # Closes and unlinks (deletes) the file. Has the same effect as called
  # <tt>close(true)</tt>.
  def close!
    close(true)
  end

  # Unlinks (deletes) the file from the filesystem. One should always unlink
  # the file after using it, as is explained in the "Explicit close" good
  # practice section in the Tempfile overview:
  #
  #   file = Tempfile.new('foo')
  #   begin
  #      # ...do something with file...
  #   ensure
  #      file.close
  #      file.unlink   # deletes the temp file
  #   end
  #
  # === Unlink-before-close
  #
  # On POSIX systems it's possible to unlink a file before closing it. This
  # practice is explained in detail in the Tempfile overview (section
  # "Unlink after creation"); please refer there for more information.
  #
  # However, unlink-before-close may not be supported on non-POSIX operating
  # systems. Microsoft Windows is the most notable case: unlinking a non-closed
  # file will result in an error, which this method will silently ignore. If
  # you want to practice unlink-before-close whenever possible, then you should
  # write code like this:
  #
  #   file = Tempfile.new('foo')
  #   file.unlink   # On Windows this silently fails.
  #   begin
  #      # ... do something with file ...
  #   ensure
  #      file.close!   # Closes the file handle. If the file wasn't unlinked
  #                    # because #unlink failed, then this method will attempt
  #                    # to do so again.
  #   end
  def unlink
    return if @unlinked
    begin
      File.unlink(@tmpfile.path)
    rescue Errno::ENOENT
    rescue Errno::EACCES
      # may not be able to unlink on Windows; just ignore
      return
    end
    ObjectSpace.undefine_finalizer(self)
    @unlinked = true
  end
  alias delete unlink

  # Returns the full path name of the temporary file.
  # This will be nil if #unlink has been called.
  def path
    @unlinked ? nil : @tmpfile.path
  end

  # Returns the size of the temporary file.  As a side effect, the IO
  # buffer is flushed before determining the size.
  def size
    if !@tmpfile.closed?
      @tmpfile.size # File#size calls rb_io_flush_raw()
    else
      File.size(@tmpfile.path)
    end
  end
  alias length size

  # :stopdoc:
  def inspect
    if @tmpfile.closed?
      "#<#{self.class}:#{path} (closed)>"
    else
      "#<#{self.class}:#{path}>"
    end
  end

  class Remover # :nodoc:
    def initialize(tmpfile)
      @pid = Process.pid
      @tmpfile = tmpfile
    end

    def call(*args)
      return if @pid != Process.pid

      $stderr.puts "removing #{@tmpfile.path}..." if $DEBUG

      @tmpfile.close
      begin
        File.unlink(@tmpfile.path)
      rescue Errno::ENOENT
      end

      $stderr.puts "done" if $DEBUG
    end
  end

  class << self
    # :startdoc:

    # Creates a new Tempfile.
    #
    # This method is not recommended and exists mostly for backward compatibility.
    # Please use Tempfile.create instead, which avoids the cost of delegation,
    # does not rely on a finalizer, and also unlinks the file when given a block.
    #
    # Tempfile.open is still appropriate if you need the Tempfile to be unlinked
    # by a finalizer and you cannot explicitly know where in the program the
    # Tempfile can be unlinked safely.
    #
    # If no block is given, this is a synonym for Tempfile.new.
    #
    # If a block is given, then a Tempfile object will be constructed,
    # and the block is run with the Tempfile object as argument. The Tempfile
    # object will be automatically closed after the block terminates.
    # However, the file will *not* be unlinked and needs to be manually unlinked
    # with Tempfile#close! or Tempfile#unlink. The finalizer will try to unlink
    # but should not be relied upon as it can keep the file on the disk much
    # longer than intended. For instance, on CRuby, finalizers can be delayed
    # due to conservative stack scanning and references left in unused memory.
    #
    # The call returns the value of the block.
    #
    # In any case, all arguments (<code>*args</code>) will be passed to Tempfile.new.
    #
    #   Tempfile.open('foo', '/home/temp') do |f|
    #      # ... do something with f ...
    #   end
    #
    #   # Equivalent:
    #   f = Tempfile.open('foo', '/home/temp')
    #   begin
    #      # ... do something with f ...
    #   ensure
    #      f.close
    #   end
    def open(*args, **kw)
      tempfile = new(*args, **kw)

      if block_given?
        begin
          yield(tempfile)
        ensure
          tempfile.close
        end
      else
        tempfile
      end
    end
  end
end

# Creates a temporary file as a usual File object (not a Tempfile).
# It does not use finalizer and delegation, which makes it more efficient and reliable.
#
# If no block is given, this is similar to Tempfile.new except
# creating File instead of Tempfile. In that case, the created file is
# not removed automatically. You should use File.unlink to remove it.
#
# If a block is given, then a File object will be constructed,
# and the block is invoked with the object as the argument.
# The File object will be automatically closed and
# the temporary file is removed after the block terminates,
# releasing all resources that the block created.
# The call returns the value of the block.
#
# In any case, all arguments (+basename+, +tmpdir+, +mode+, and
# <code>**options</code>) will be treated the same as for Tempfile.new.
#
#   Tempfile.create('foo', '/home/temp') do |f|
#      # ... do something with f ...
#   end
#
def Tempfile.create(basename="", tmpdir=nil, mode: 0, **options)
  tmpfile = nil
  Dir::Tmpname.create(basename, tmpdir, **options) do |tmpname, n, opts|
    mode |= File::RDWR|File::CREAT|File::EXCL
    opts[:perm] = 0600
    tmpfile = File.open(tmpname, mode, **opts)
  end
  if block_given?
    begin
      yield tmpfile
    ensure
      unless tmpfile.closed?
        if File.identical?(tmpfile, tmpfile.path)
          unlinked = File.unlink tmpfile.path rescue nil
        end
        tmpfile.close
      end
      unless unlinked
        begin
          File.unlink tmpfile.path
        rescue Errno::ENOENT
        end
      end
    end
  else
    tmpfile
  end
end
[ruby3.0]
rake = 13.0.3
rdoc = 6.3.4.1
psych = 3.3.2
json = 2.5.1
io-console = 0.5.7
bundler = 2.2.33
bigdecimal = 3.0.0
rack = 3.0.8
#!/opt/alt/ruby30/bin/ruby
#
# This file was generated by RubyGems.
#
# The application 'erb' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require 'rubygems'

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('erb', 'erb', version)
else
gem "erb", version
load Gem.bin_path("erb", "erb", version)
end
#!/opt/alt/ruby30/bin/ruby
#
# This file was generated by RubyGems.
#
# The application 'bundler' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require 'rubygems'

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('bundler', 'bundle', version)
else
gem "bundler", version
load Gem.bin_path("bundler", "bundle", version)
end
#!/opt/alt/ruby30/bin/ruby
#
# This file was generated by RubyGems.
#
# The application 'bundler' is installed as part of a gem, and
# this file is here to facilitate running it.
#

require 'rubygems'

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('bundler', 'bundler', version)
else
gem "bundler", version
load Gem.bin_path("bundler", "bundler", version)
end
#!/opt/alt/ruby30/bin/ruby
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require 'rubygems'
require 'rubygems/gem_runner'
require 'rubygems/exceptions'

required_version = Gem::Requirement.new ">= 1.8.7"

unless required_version.satisfied_by? Gem.ruby_version then
  abort "Expected Ruby Version #{required_version}, is #{Gem.ruby_version}"
end

args = ARGV.clone

begin
  Gem::GemRunner.new.run args
rescue Gem::SystemExitException => e
  exit e.exit_code
end

#!/opt/alt/ruby30/bin/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'

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
#!/opt/alt/ruby30/bin/ruby
#
# This file was generated by RubyGems.
#
# The application 'rake' 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('rake', 'rake', version)
else
gem "rake", version
load Gem.bin_path("rake", "rake", version)
end
#!/opt/alt/ruby30/bin/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'

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
#!/opt/alt/ruby30/bin/ruby
#
# This file was generated by RubyGems.
#
# The application 'rackup' 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('rackup', 'rackup', version)
else
gem "rackup", version
load Gem.bin_path("rackup", "rackup", version)
end
ELF          >    
      @       @)          @ 8  @         @       @       @       h      h                                                                                                                                                                                                                                                                              D       D              Std                                            Ptd   `      `      `      D       D              Qtd                                                  Rtd                                        /lib64/ld-linux-x86-64.so.2              GNU                      GNU                        GNU G!L?P                Q! e         j	Cֺ|CE:2bKqX                        U                                             c                                            m                                             ;                         "                                                               z                                            i                    E                   2                   k                     o    
      /       Z    X             v          e       9                   J    @              libruby.so.3.0 __gmon_start__ _ITM_deregisterTMCloneTable _ITM_registerTMCloneTable ruby_run_node ruby_init ruby_options ruby_init_stack ruby_sysinit libz.so.1 libpthread.so.0 librt.so.1 libgmp.so.10 libdl.so.2 libcrypt.so.1 libm.so.6 libc.so.6 setlocale __stack_chk_fail __cxa_finalize __libc_start_main _edata __bss_start _end __libc_csu_fini _IO_stdin_used __data_start __libc_csu_init GLIBC_2.4 GLIBC_2.2.5 /opt/alt/ruby30/lib64                                      ii        ui	                                         p                                                                                                                                                                                                                      	                    
                                                   HH  HtH             5B  %C   h    h   h   h   h   h   h   h   q%  D  %  D  %  D  %  D  %  D  %  D  %  D  %  D  H(|$1H4$H5  dH%(   HD$1HH|$H|$FH4$|$IH!HT$dH3%(   uH(W    1I^HHPTLV  H   H=X  H=  H  H9tH  Ht	        H=  H5  H)HHH?HHtH  HtfD      =   u+UH=r   HtH=f  ida  ]     w    f.     AWIAVIAUAATL%  UH-  SL)HHt1    LLDAHH9uH[]A\A]A^A_ff.        HH         ;D      x   p      p`   `   p   8             zR x        /    D    $   4   `    FJw ?:*3$"       \                 t   0y    H0k
A                      D      xe    FEE E(H0H8G@n8A0A(B BBB                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                p                                                                                                                                                              	             H                                                            o    0                          x      
                                                                                          X                                 	                             o          o    h      o           o    :      o                                                                                                                  P	      `	      p	      	      	      	      	      	                                                           GA$3a1 	      
               GA$3p1113  P
                      GA*             GA$annobin gcc 8.5.0 20210514            GA$plugin name: gcc-annobin              GA$running gcc 8.5.0 20210514            GA*             GA*             GA!              GA*FORTIFY               GA+GLIBCXX_ASSERTIONS             GA*GOW *            GA*cf_protection             GA+omit_frame_pointer             GA+stack_clash            GA!stack_realign             GA$3a1        U               GA$3p1113        E                GA*             GA$annobin gcc 8.5.0 20210514            GA$plugin name: gcc-annobin              GA$running gcc 8.5.0 20210514            GA*             GA*             GA!              GA*FORTIFY               GA+GLIBCXX_ASSERTIONS             GA*GOW *            GA*cf_protection             GA+omit_frame_pointer             GA+stack_clash            GA!stack_realign            GA*FORTIFY           5               GA+GLIBCXX_ASSERTIONS   ruby-3.0.7-167.el8.x86_64.debug <K7zXZ  ִF !   t/S] ?Eh=ڊ2N`].>&ԞL);|(WE)ET~2ƘWkz-Ary$ďc! 9㚽]#xa 98xMKR7腻PM=ղt9rI"E]ƴs	
8劾mo߅}u"*gBܽMKfi'L]tA٣12XUzj6/'xf䉰wGafCIƀ<&iMcgv?Xebe뒦7+W7ISt]}H$vUhoRȣQZ}TF$Wck+b\,Ә6ơrpiF)>vkw%Y/b3|ce(51	(n6o$/_1^Юk*9YjyEyoz[Ƽ~V/熴?#܏pI+6<v)/@{ѳ	u%j]\\ظv<z!):jAeF/2@zE25׬wĩ,d<q`afqv3[C2J؟~
R,ȷF
 M8|]&ݱiO8Iӑ}h{&Yؔ]4.A1fw-{vSW'"	x~[B7;-t#Mq0t:5}j%KKm/	xјC)wEMdCc-WJ:X*W*.  ӊ/s   a0ʱg    YZ .shstrtab .interp .note.gnu.property .note.ABI-tag .note.gnu.build-id .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rela.dyn .rela.plt .init .plt.sec .text .fini .rodata .eh_frame_hdr .eh_frame .init_array .fini_array .data.rel.ro .dynamic .got .data .bss .gnu.build.attributes .gnu_debuglink .gnu_debugdata                                                                                                                                                                                      &                                                        4                         $                              G   o       0      0      H                             Q             x      x                                Y                                                      a   o       :      :      ,                            n   o       h      h      0                            }                                                           B       X      X                                              	      	                                                 @	      @	                                                	      	                                                P
      P
                                                H      H                                                 X      X                                                 `      `      D                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
              `            @                                                   D$      $                              /                     h$                                                         '      >                             /*
 * Kluge to support multilib installation of both 32- and 64-bit RPMS:
 * we need to arrange that header files that appear in both RPMs are
 * identical.  Hence, this file is architecture-independent and calls
 * in an arch-dependent file that will appear in just one RPM.
 *
 * To avoid breaking arches not explicitly supported by Red Hat, we
 * use this indirection file *only* on known multilib arches.
 *
 * We pay attention to include _only_ the original multilib-unclean
 * header file.  Including any other system-header file could cause
 * unpredictable include-ordering issues (rhbz#1412274, comment #16).
 *
 * Note: this may well fail if user tries to use gcc's -I- option.
 * But that option is deprecated anyway.
 */
#if defined(__x86_64__)
#include "rb_mjit_min_header-3.0.7-x86_64.h"
#elif defined(__i386__)
#include "rb_mjit_min_header-3.0.7-i386.h"
#elif defined(__ppc64__) || defined(__powerpc64__)
#include "rb_mjit_min_header-3.0.7-ppc64.h"
#elif defined(__ppc__) || defined(__powerpc__)
#include "rb_mjit_min_header-3.0.7-ppc.h"
#elif defined(__s390x__)
#include "rb_mjit_min_header-3.0.7-s390x.h"
#elif defined(__s390__)
#include "rb_mjit_min_header-3.0.7-s390.h"
#elif defined(__sparc__) && defined(__arch64__)
#include "rb_mjit_min_header-3.0.7-sparc64.h"
#elif defined(__sparc__)
#include "rb_mjit_min_header-3.0.7-sparc.h"
#endif
#ifdef __GNUC__
# pragma GCC system_header
#endif
#define ALWAYS_INLINE(x) __attribute__ ((__always_inline__)) x
typedef __builtin_va_list __gnuc_va_list;
typedef __gnuc_va_list va_list;

typedef long unsigned int size_t;
typedef unsigned char __u_char;
typedef unsigned short int __u_short;
typedef unsigned int __u_int;
typedef unsigned long int __u_long;
typedef signed char __int8_t;
typedef unsigned char __uint8_t;
typedef signed short int __int16_t;
typedef unsigned short int __uint16_t;
typedef signed int __int32_t;
typedef unsigned int __uint32_t;
typedef signed long int __int64_t;
typedef unsigned long int __uint64_t;
typedef __int8_t __int_least8_t;
typedef __uint8_t __uint_least8_t;
typedef __int16_t __int_least16_t;
typedef __uint16_t __uint_least16_t;
typedef __int32_t __int_least32_t;
typedef __uint32_t __uint_least32_t;
typedef __int64_t __int_least64_t;
typedef __uint64_t __uint_least64_t;
typedef long int __quad_t;
typedef unsigned long int __u_quad_t;
typedef long int __intmax_t;
typedef unsigned long int __uintmax_t;
typedef unsigned long int __dev_t;
typedef unsigned int __uid_t;
typedef unsigned int __gid_t;
typedef unsigned long int __ino_t;
typedef unsigned long int __ino64_t;
typedef unsigned int __mode_t;
typedef unsigned long int __nlink_t;
typedef long int __off_t;
typedef long int __off64_t;
typedef int __pid_t;
typedef struct { int __val[2]; } __fsid_t;
typedef long int __clock_t;
typedef unsigned long int __rlim_t;
typedef unsigned long int __rlim64_t;
typedef unsigned int __id_t;
typedef long int __time_t;
typedef unsigned int __useconds_t;
typedef long int __suseconds_t;
typedef int __daddr_t;
typedef int __key_t;
typedef int __clockid_t;
typedef void * __timer_t;
typedef long int __blksize_t;
typedef long int __blkcnt_t;
typedef long int __blkcnt64_t;
typedef unsigned long int __fsblkcnt_t;
typedef unsigned long int __fsblkcnt64_t;
typedef unsigned long int __fsfilcnt_t;
typedef unsigned long int __fsfilcnt64_t;
typedef long int __fsword_t;
typedef long int __ssize_t;
typedef long int __syscall_slong_t;
typedef unsigned long int __syscall_ulong_t;
typedef __off64_t __loff_t;
typedef char *__caddr_t;
typedef long int __intptr_t;
typedef unsigned int __socklen_t;
typedef int __sig_atomic_t;
typedef struct
{
  int __count;
  union
  {
    unsigned int __wch;
    char __wchb[4];
  } __value;
} __mbstate_t;
typedef struct _G_fpos_t
{
  __off_t __pos;
  __mbstate_t __state;
} __fpos_t;
typedef struct _G_fpos64_t
{
  __off64_t __pos;
  __mbstate_t __state;
} __fpos64_t;
struct _IO_FILE;
typedef struct _IO_FILE __FILE;
struct _IO_FILE;
typedef struct _IO_FILE FILE;
struct _IO_FILE;
struct _IO_marker;
struct _IO_codecvt;
struct _IO_wide_data;
typedef void _IO_lock_t;
struct _IO_FILE
{
  int _flags;
  char *_IO_read_ptr;
  char *_IO_read_end;
  char *_IO_read_base;
  char *_IO_write_base;
  char *_IO_write_ptr;
  char *_IO_write_end;
  char *_IO_buf_base;
  char *_IO_buf_end;
  char *_IO_save_base;
  char *_IO_backup_base;
  char *_IO_save_end;
  struct _IO_marker *_markers;
  struct _IO_FILE *_chain;
  int _fileno;
  int _flags2;
  __off_t _old_offset;
  unsigned short _cur_column;
  signed char _vtable_offset;
  char _shortbuf[1];
  _IO_lock_t *_lock;
  __off64_t _offset;
  struct _IO_codecvt *_codecvt;
  struct _IO_wide_data *_wide_data;
  struct _IO_FILE *_freeres_list;
  void *_freeres_buf;
  size_t __pad5;
  int _mode;
  char _unused2[15 * sizeof (int) - 4 * sizeof (void *) - sizeof (size_t)];
};
typedef __ssize_t cookie_read_function_t (void *__cookie, char *__buf,
                                          size_t __nbytes);
typedef __ssize_t cookie_write_function_t (void *__cookie, const char *__buf,
                                           size_t __nbytes);
typedef int cookie_seek_function_t (void *__cookie, __off64_t *__pos, int __w);
typedef int cookie_close_function_t (void *__cookie);
typedef struct _IO_cookie_io_functions_t
{
  cookie_read_function_t *read;
  cookie_write_function_t *write;
  cookie_seek_function_t *seek;
  cookie_close_function_t *close;
} cookie_io_functions_t;
typedef __off_t off_t;
typedef __off64_t off64_t;
typedef __ssize_t ssize_t;
typedef __fpos_t fpos_t;
typedef __fpos64_t fpos64_t;
extern FILE *stdin;
extern FILE *stdout;
extern FILE *stderr;
extern int remove (const char *__filename) __attribute__ ((__nothrow__ , __leaf__));
extern int rename (const char *__old, const char *__new) __attribute__ ((__nothrow__ , __leaf__));
extern int renameat (int __oldfd, const char *__old, int __newfd,
       const char *__new) __attribute__ ((__nothrow__ , __leaf__));
extern int renameat2 (int __oldfd, const char *__old, int __newfd,
        const char *__new, unsigned int __flags) __attribute__ ((__nothrow__ , __leaf__));
extern FILE *tmpfile (void) __attribute__ ((__warn_unused_result__));
extern FILE *tmpfile64 (void) __attribute__ ((__warn_unused_result__));
extern char *tmpnam (char *__s) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern char *tmpnam_r (char *__s) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern char *tempnam (const char *__dir, const char *__pfx)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) __attribute__ ((__warn_unused_result__));
extern int fclose (FILE *__stream);
extern int fflush (FILE *__stream);
extern int fflush_unlocked (FILE *__stream);
extern int fcloseall (void);
extern FILE *fopen (const char *__restrict __filename,
      const char *__restrict __modes) __attribute__ ((__warn_unused_result__));
extern FILE *freopen (const char *__restrict __filename,
        const char *__restrict __modes,
        FILE *__restrict __stream) __attribute__ ((__warn_unused_result__));
extern FILE *fopen64 (const char *__restrict __filename,
        const char *__restrict __modes) __attribute__ ((__warn_unused_result__));
extern FILE *freopen64 (const char *__restrict __filename,
   const char *__restrict __modes,
   FILE *__restrict __stream) __attribute__ ((__warn_unused_result__));
extern FILE *fdopen (int __fd, const char *__modes) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern FILE *fopencookie (void *__restrict __magic_cookie,
     const char *__restrict __modes,
     cookie_io_functions_t __io_funcs) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern FILE *fmemopen (void *__s, size_t __len, const char *__modes)
  __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern FILE *open_memstream (char **__bufloc, size_t *__sizeloc) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern void setbuf (FILE *__restrict __stream, char *__restrict __buf) __attribute__ ((__nothrow__ , __leaf__));
extern int setvbuf (FILE *__restrict __stream, char *__restrict __buf,
      int __modes, size_t __n) __attribute__ ((__nothrow__ , __leaf__));
extern void setbuffer (FILE *__restrict __stream, char *__restrict __buf,
         size_t __size) __attribute__ ((__nothrow__ , __leaf__));
extern void setlinebuf (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
extern int fprintf (FILE *__restrict __stream,
      const char *__restrict __format, ...);
extern int printf (const char *__restrict __format, ...);
extern int sprintf (char *__restrict __s,
      const char *__restrict __format, ...) __attribute__ ((__nothrow__));
extern int vfprintf (FILE *__restrict __s, const char *__restrict __format,
       __gnuc_va_list __arg);
extern int vprintf (const char *__restrict __format, __gnuc_va_list __arg);
extern int vsprintf (char *__restrict __s, const char *__restrict __format,
       __gnuc_va_list __arg) __attribute__ ((__nothrow__));
extern int snprintf (char *__restrict __s, size_t __maxlen,
       const char *__restrict __format, ...)
     __attribute__ ((__nothrow__)) __attribute__ ((__format__ (__printf__, 3, 4)));
extern int vsnprintf (char *__restrict __s, size_t __maxlen,
        const char *__restrict __format, __gnuc_va_list __arg)
     __attribute__ ((__nothrow__)) __attribute__ ((__format__ (__printf__, 3, 0)));
extern int vasprintf (char **__restrict __ptr, const char *__restrict __f,
        __gnuc_va_list __arg)
     __attribute__ ((__nothrow__)) __attribute__ ((__format__ (__printf__, 2, 0))) __attribute__ ((__warn_unused_result__));
extern int __asprintf (char **__restrict __ptr,
         const char *__restrict __fmt, ...)
     __attribute__ ((__nothrow__)) __attribute__ ((__format__ (__printf__, 2, 3))) __attribute__ ((__warn_unused_result__));
extern int asprintf (char **__restrict __ptr,
       const char *__restrict __fmt, ...)
     __attribute__ ((__nothrow__)) __attribute__ ((__format__ (__printf__, 2, 3))) __attribute__ ((__warn_unused_result__));
extern int vdprintf (int __fd, const char *__restrict __fmt,
       __gnuc_va_list __arg)
     __attribute__ ((__format__ (__printf__, 2, 0)));
extern int dprintf (int __fd, const char *__restrict __fmt, ...)
     __attribute__ ((__format__ (__printf__, 2, 3)));
extern int fscanf (FILE *__restrict __stream,
     const char *__restrict __format, ...) __attribute__ ((__warn_unused_result__));
extern int scanf (const char *__restrict __format, ...) __attribute__ ((__warn_unused_result__));
extern int sscanf (const char *__restrict __s,
     const char *__restrict __format, ...) __attribute__ ((__nothrow__ , __leaf__));
extern int vfscanf (FILE *__restrict __s, const char *__restrict __format,
      __gnuc_va_list __arg)
     __attribute__ ((__format__ (__scanf__, 2, 0))) __attribute__ ((__warn_unused_result__));
extern int vscanf (const char *__restrict __format, __gnuc_va_list __arg)
     __attribute__ ((__format__ (__scanf__, 1, 0))) __attribute__ ((__warn_unused_result__));
extern int vsscanf (const char *__restrict __s,
      const char *__restrict __format, __gnuc_va_list __arg)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__format__ (__scanf__, 2, 0)));
extern int fgetc (FILE *__stream);
extern int getc (FILE *__stream);
extern int getchar (void);
extern int getc_unlocked (FILE *__stream);
extern int getchar_unlocked (void);
extern int fgetc_unlocked (FILE *__stream);
extern int fputc (int __c, FILE *__stream);
extern int putc (int __c, FILE *__stream);
extern int putchar (int __c);
extern int fputc_unlocked (int __c, FILE *__stream);
extern int putc_unlocked (int __c, FILE *__stream);
extern int putchar_unlocked (int __c);
extern int getw (FILE *__stream);
extern int putw (int __w, FILE *__stream);
extern char *fgets (char *__restrict __s, int __n, FILE *__restrict __stream)
     __attribute__ ((__warn_unused_result__));
extern char *fgets_unlocked (char *__restrict __s, int __n,
        FILE *__restrict __stream) __attribute__ ((__warn_unused_result__));
extern __ssize_t __getdelim (char **__restrict __lineptr,
                             size_t *__restrict __n, int __delimiter,
                             FILE *__restrict __stream) __attribute__ ((__warn_unused_result__));
extern __ssize_t getdelim (char **__restrict __lineptr,
                           size_t *__restrict __n, int __delimiter,
                           FILE *__restrict __stream) __attribute__ ((__warn_unused_result__));
extern __ssize_t getline (char **__restrict __lineptr,
                          size_t *__restrict __n,
                          FILE *__restrict __stream) __attribute__ ((__warn_unused_result__));
extern int fputs (const char *__restrict __s, FILE *__restrict __stream);
extern int puts (const char *__s);
extern int ungetc (int __c, FILE *__stream);
extern size_t fread (void *__restrict __ptr, size_t __size,
       size_t __n, FILE *__restrict __stream) __attribute__ ((__warn_unused_result__));
extern size_t fwrite (const void *__restrict __ptr, size_t __size,
        size_t __n, FILE *__restrict __s);
extern int fputs_unlocked (const char *__restrict __s,
      FILE *__restrict __stream);
extern size_t fread_unlocked (void *__restrict __ptr, size_t __size,
         size_t __n, FILE *__restrict __stream) __attribute__ ((__warn_unused_result__));
extern size_t fwrite_unlocked (const void *__restrict __ptr, size_t __size,
          size_t __n, FILE *__restrict __stream);
extern int fseek (FILE *__stream, long int __off, int __whence);
extern long int ftell (FILE *__stream) __attribute__ ((__warn_unused_result__));
extern void rewind (FILE *__stream);
extern int fseeko (FILE *__stream, __off_t __off, int __whence);
extern __off_t ftello (FILE *__stream) __attribute__ ((__warn_unused_result__));
extern int fgetpos (FILE *__restrict __stream, fpos_t *__restrict __pos);
extern int fsetpos (FILE *__stream, const fpos_t *__pos);
extern int fseeko64 (FILE *__stream, __off64_t __off, int __whence);
extern __off64_t ftello64 (FILE *__stream) __attribute__ ((__warn_unused_result__));
extern int fgetpos64 (FILE *__restrict __stream, fpos64_t *__restrict __pos);
extern int fsetpos64 (FILE *__stream, const fpos64_t *__pos);
extern void clearerr (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
extern int feof (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int ferror (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern void clearerr_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
extern int feof_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int ferror_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern void perror (const char *__s);
extern int sys_nerr;
extern const char *const sys_errlist[];
extern int _sys_nerr;
extern const char *const _sys_errlist[];
extern int fileno (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int fileno_unlocked (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern FILE *popen (const char *__command, const char *__modes) __attribute__ ((__warn_unused_result__));
extern int pclose (FILE *__stream);
extern char *ctermid (char *__s) __attribute__ ((__nothrow__ , __leaf__));
extern char *cuserid (char *__s);
struct obstack;
extern int obstack_printf (struct obstack *__restrict __obstack,
      const char *__restrict __format, ...)
     __attribute__ ((__nothrow__)) __attribute__ ((__format__ (__printf__, 2, 3)));
extern int obstack_vprintf (struct obstack *__restrict __obstack,
       const char *__restrict __format,
       __gnuc_va_list __args)
     __attribute__ ((__nothrow__)) __attribute__ ((__format__ (__printf__, 2, 0)));
extern void flockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
extern int ftrylockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern void funlockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__));
extern int __uflow (FILE *);
extern int __overflow (FILE *, int);
extern __inline __attribute__ ((__gnu_inline__)) int
getchar (void)
{
  return getc (stdin);
}
extern __inline __attribute__ ((__gnu_inline__)) int
fgetc_unlocked (FILE *__fp)
{
  return (__builtin_expect (((__fp)->_IO_read_ptr >= (__fp)->_IO_read_end), 0) ? __uflow (__fp) : *(unsigned char *) (__fp)->_IO_read_ptr++);
}
extern __inline __attribute__ ((__gnu_inline__)) int
getc_unlocked (FILE *__fp)
{
  return (__builtin_expect (((__fp)->_IO_read_ptr >= (__fp)->_IO_read_end), 0) ? __uflow (__fp) : *(unsigned char *) (__fp)->_IO_read_ptr++);
}
extern __inline __attribute__ ((__gnu_inline__)) int
getchar_unlocked (void)
{
  return (__builtin_expect (((stdin)->_IO_read_ptr >= (stdin)->_IO_read_end), 0) ? __uflow (stdin) : *(unsigned char *) (stdin)->_IO_read_ptr++);
}
extern __inline __attribute__ ((__gnu_inline__)) int
putchar (int __c)
{
  return putc (__c, stdout);
}
extern __inline __attribute__ ((__gnu_inline__)) int
fputc_unlocked (int __c, FILE *__stream)
{
  return (__builtin_expect (((__stream)->_IO_write_ptr >= (__stream)->_IO_write_end), 0) ? __overflow (__stream, (unsigned char) (__c)) : (unsigned char) (*(__stream)->_IO_write_ptr++ = (__c)));
}
extern __inline __attribute__ ((__gnu_inline__)) int
putc_unlocked (int __c, FILE *__stream)
{
  return (__builtin_expect (((__stream)->_IO_write_ptr >= (__stream)->_IO_write_end), 0) ? __overflow (__stream, (unsigned char) (__c)) : (unsigned char) (*(__stream)->_IO_write_ptr++ = (__c)));
}
extern __inline __attribute__ ((__gnu_inline__)) int
putchar_unlocked (int __c)
{
  return (__builtin_expect (((stdout)->_IO_write_ptr >= (stdout)->_IO_write_end), 0) ? __overflow (stdout, (unsigned char) (__c)) : (unsigned char) (*(stdout)->_IO_write_ptr++ = (__c)));
}
extern __inline __attribute__ ((__gnu_inline__)) __ssize_t
getline (char **__lineptr, size_t *__n, FILE *__stream)
{
  return __getdelim (__lineptr, __n, '\n', __stream);
}
extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ , __leaf__)) feof_unlocked (FILE *__stream)
{
  return (((__stream)->_flags & 0x0010) != 0);
}
extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ , __leaf__)) ferror_unlocked (FILE *__stream)
{
  return (((__stream)->_flags & 0x0020) != 0);
}
extern int __sprintf_chk (char *__restrict __s, int __flag, size_t __slen,
     const char *__restrict __format, ...) __attribute__ ((__nothrow__ , __leaf__));
extern int __vsprintf_chk (char *__restrict __s, int __flag, size_t __slen,
      const char *__restrict __format,
      __gnuc_va_list __ap) __attribute__ ((__nothrow__ , __leaf__));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
__attribute__ ((__nothrow__ , __leaf__)) sprintf (char *__restrict __s, const char *__restrict __fmt, ...)
{
  return __builtin___sprintf_chk (__s, 2 - 1,
      __builtin_object_size (__s, 2 > 1), __fmt,
      __builtin_va_arg_pack ());
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
__attribute__ ((__nothrow__ , __leaf__)) vsprintf (char *__restrict __s, const char *__restrict __fmt, __gnuc_va_list __ap)
{
  return __builtin___vsprintf_chk (__s, 2 - 1,
       __builtin_object_size (__s, 2 > 1), __fmt, __ap);
}
extern int __snprintf_chk (char *__restrict __s, size_t __n, int __flag,
      size_t __slen, const char *__restrict __format,
      ...) __attribute__ ((__nothrow__ , __leaf__));
extern int __vsnprintf_chk (char *__restrict __s, size_t __n, int __flag,
       size_t __slen, const char *__restrict __format,
       __gnuc_va_list __ap) __attribute__ ((__nothrow__ , __leaf__));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
__attribute__ ((__nothrow__ , __leaf__)) snprintf (char *__restrict __s, size_t __n, const char *__restrict __fmt, ...)
{
  return __builtin___snprintf_chk (__s, __n, 2 - 1,
       __builtin_object_size (__s, 2 > 1), __fmt,
       __builtin_va_arg_pack ());
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
__attribute__ ((__nothrow__ , __leaf__)) vsnprintf (char *__restrict __s, size_t __n, const char *__restrict __fmt, __gnuc_va_list __ap)
{
  return __builtin___vsnprintf_chk (__s, __n, 2 - 1,
        __builtin_object_size (__s, 2 > 1), __fmt, __ap);
}
extern int __fprintf_chk (FILE *__restrict __stream, int __flag,
     const char *__restrict __format, ...);
extern int __printf_chk (int __flag, const char *__restrict __format, ...);
extern int __vfprintf_chk (FILE *__restrict __stream, int __flag,
      const char *__restrict __format, __gnuc_va_list __ap);
extern int __vprintf_chk (int __flag, const char *__restrict __format,
     __gnuc_va_list __ap);
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
fprintf (FILE *__restrict __stream, const char *__restrict __fmt, ...)
{
  return __fprintf_chk (__stream, 2 - 1, __fmt,
   __builtin_va_arg_pack ());
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
printf (const char *__restrict __fmt, ...)
{
  return __printf_chk (2 - 1, __fmt, __builtin_va_arg_pack ());
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
vprintf (const char *__restrict __fmt, __gnuc_va_list __ap)
{
  return __vfprintf_chk (stdout, 2 - 1, __fmt, __ap);
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
vfprintf (FILE *__restrict __stream,
   const char *__restrict __fmt, __gnuc_va_list __ap)
{
  return __vfprintf_chk (__stream, 2 - 1, __fmt, __ap);
}
extern int __dprintf_chk (int __fd, int __flag, const char *__restrict __fmt,
     ...) __attribute__ ((__format__ (__printf__, 3, 4)));
extern int __vdprintf_chk (int __fd, int __flag,
      const char *__restrict __fmt, __gnuc_va_list __arg)
     __attribute__ ((__format__ (__printf__, 3, 0)));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
dprintf (int __fd, const char *__restrict __fmt, ...)
{
  return __dprintf_chk (__fd, 2 - 1, __fmt,
   __builtin_va_arg_pack ());
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
vdprintf (int __fd, const char *__restrict __fmt, __gnuc_va_list __ap)
{
  return __vdprintf_chk (__fd, 2 - 1, __fmt, __ap);
}
extern int __asprintf_chk (char **__restrict __ptr, int __flag,
      const char *__restrict __fmt, ...)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__format__ (__printf__, 3, 4))) __attribute__ ((__warn_unused_result__));
extern int __vasprintf_chk (char **__restrict __ptr, int __flag,
       const char *__restrict __fmt, __gnuc_va_list __arg)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__format__ (__printf__, 3, 0))) __attribute__ ((__warn_unused_result__));
extern int __obstack_printf_chk (struct obstack *__restrict __obstack,
     int __flag, const char *__restrict __format,
     ...)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__format__ (__printf__, 3, 4)));
extern int __obstack_vprintf_chk (struct obstack *__restrict __obstack,
      int __flag,
      const char *__restrict __format,
      __gnuc_va_list __args)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__format__ (__printf__, 3, 0)));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
__attribute__ ((__nothrow__ , __leaf__)) asprintf (char **__restrict __ptr, const char *__restrict __fmt, ...)
{
  return __asprintf_chk (__ptr, 2 - 1, __fmt,
    __builtin_va_arg_pack ());
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
__attribute__ ((__nothrow__ , __leaf__)) __asprintf (char **__restrict __ptr, const char *__restrict __fmt, ...)
{
  return __asprintf_chk (__ptr, 2 - 1, __fmt,
    __builtin_va_arg_pack ());
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
__attribute__ ((__nothrow__ , __leaf__)) obstack_printf (struct obstack *__restrict __obstack, const char *__restrict __fmt, ...)
{
  return __obstack_printf_chk (__obstack, 2 - 1, __fmt,
          __builtin_va_arg_pack ());
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
__attribute__ ((__nothrow__ , __leaf__)) vasprintf (char **__restrict __ptr, const char *__restrict __fmt, __gnuc_va_list __ap)
{
  return __vasprintf_chk (__ptr, 2 - 1, __fmt, __ap);
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
__attribute__ ((__nothrow__ , __leaf__)) obstack_vprintf (struct obstack *__restrict __obstack, const char *__restrict __fmt, __gnuc_va_list __ap)
{
  return __obstack_vprintf_chk (__obstack, 2 - 1, __fmt,
    __ap);
}
extern char *__fgets_chk (char *__restrict __s, size_t __size, int __n,
     FILE *__restrict __stream) __attribute__ ((__warn_unused_result__));
extern char *__fgets_alias (char *__restrict __s, int __n, FILE *__restrict __stream) __asm__ ("" "fgets") __attribute__ ((__warn_unused_result__));
extern char *__fgets_chk_warn (char *__restrict __s, size_t __size, int __n, FILE *__restrict __stream) __asm__ ("" "__fgets_chk")
     __attribute__ ((__warn_unused_result__)) __attribute__((__warning__ ("fgets called with bigger size than length " "of destination buffer")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) __attribute__ ((__warn_unused_result__)) char *
fgets (char *__restrict __s, int __n, FILE *__restrict __stream)
{
  size_t sz = __builtin_object_size (__s, 2 > 1);
  if (((__builtin_constant_p (sz) && (sz) == (long unsigned int) -1) || (((__typeof (__n)) 0 < (__typeof (__n)) -1 || (__builtin_constant_p (__n) && (__n) > 0)) && __builtin_constant_p ((((long unsigned int) (__n)) <= ((sz)) / ((sizeof (char))))) && (((long unsigned int) (__n)) <= ((sz)) / ((sizeof (char)))))))
    return __fgets_alias (__s, __n, __stream);
  if ((((__typeof (__n)) 0 < (__typeof (__n)) -1 || (__builtin_constant_p (__n) && (__n) > 0)) && __builtin_constant_p ((((long unsigned int) (__n)) <= (sz) / (sizeof (char)))) && !(((long unsigned int) (__n)) <= (sz) / (sizeof (char)))))
    return __fgets_chk_warn (__s, sz, __n, __stream);
  return __fgets_chk (__s, sz, __n, __stream);
}
extern size_t __fread_chk (void *__restrict __ptr, size_t __ptrlen,
      size_t __size, size_t __n,
      FILE *__restrict __stream) __attribute__ ((__warn_unused_result__));
extern size_t __fread_alias (void *__restrict __ptr, size_t __size, size_t __n, FILE *__restrict __stream) __asm__ ("" "fread") __attribute__ ((__warn_unused_result__));
extern size_t __fread_chk_warn (void *__restrict __ptr, size_t __ptrlen, size_t __size, size_t __n, FILE *__restrict __stream) __asm__ ("" "__fread_chk")
     __attribute__ ((__warn_unused_result__)) __attribute__((__warning__ ("fread called with bigger size * nmemb than length " "of destination buffer")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) __attribute__ ((__warn_unused_result__)) size_t
fread (void *__restrict __ptr, size_t __size, size_t __n,
       FILE *__restrict __stream)
{
  size_t sz = __builtin_object_size (__ptr, 0);
  if (((__builtin_constant_p (sz) && (sz) == (long unsigned int) -1) || (((__typeof (__n)) 0 < (__typeof (__n)) -1 || (__builtin_constant_p (__n) && (__n) > 0)) && __builtin_constant_p ((((long unsigned int) (__n)) <= ((sz)) / ((__size)))) && (((long unsigned int) (__n)) <= ((sz)) / ((__size))))))
    return __fread_alias (__ptr, __size, __n, __stream);
  if ((((__typeof (__n)) 0 < (__typeof (__n)) -1 || (__builtin_constant_p (__n) && (__n) > 0)) && __builtin_constant_p ((((long unsigned int) (__n)) <= (sz) / (__size))) && !(((long unsigned int) (__n)) <= (sz) / (__size))))
    return __fread_chk_warn (__ptr, sz, __size, __n, __stream);
  return __fread_chk (__ptr, sz, __size, __n, __stream);
}
extern char *__fgets_unlocked_chk (char *__restrict __s, size_t __size,
       int __n, FILE *__restrict __stream) __attribute__ ((__warn_unused_result__));
extern char *__fgets_unlocked_alias (char *__restrict __s, int __n, FILE *__restrict __stream) __asm__ ("" "fgets_unlocked") __attribute__ ((__warn_unused_result__));
extern char *__fgets_unlocked_chk_warn (char *__restrict __s, size_t __size, int __n, FILE *__restrict __stream) __asm__ ("" "__fgets_unlocked_chk")
     __attribute__ ((__warn_unused_result__)) __attribute__((__warning__ ("fgets_unlocked called with bigger size than length " "of destination buffer")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) __attribute__ ((__warn_unused_result__)) char *
fgets_unlocked (char *__restrict __s, int __n, FILE *__restrict __stream)
{
  size_t sz = __builtin_object_size (__s, 2 > 1);
  if (((__builtin_constant_p (sz) && (sz) == (long unsigned int) -1) || (((__typeof (__n)) 0 < (__typeof (__n)) -1 || (__builtin_constant_p (__n) && (__n) > 0)) && __builtin_constant_p ((((long unsigned int) (__n)) <= ((sz)) / ((sizeof (char))))) && (((long unsigned int) (__n)) <= ((sz)) / ((sizeof (char)))))))
    return __fgets_unlocked_alias (__s, __n, __stream);
  if ((((__typeof (__n)) 0 < (__typeof (__n)) -1 || (__builtin_constant_p (__n) && (__n) > 0)) && __builtin_constant_p ((((long unsigned int) (__n)) <= (sz) / (sizeof (char)))) && !(((long unsigned int) (__n)) <= (sz) / (sizeof (char)))))
    return __fgets_unlocked_chk_warn (__s, sz, __n, __stream);
  return __fgets_unlocked_chk (__s, sz, __n, __stream);
}
extern size_t __fread_unlocked_chk (void *__restrict __ptr, size_t __ptrlen,
        size_t __size, size_t __n,
        FILE *__restrict __stream) __attribute__ ((__warn_unused_result__));
extern size_t __fread_unlocked_alias (void *__restrict __ptr, size_t __size, size_t __n, FILE *__restrict __stream) __asm__ ("" "fread_unlocked") __attribute__ ((__warn_unused_result__));
extern size_t __fread_unlocked_chk_warn (void *__restrict __ptr, size_t __ptrlen, size_t __size, size_t __n, FILE *__restrict __stream) __asm__ ("" "__fread_unlocked_chk")
     __attribute__ ((__warn_unused_result__)) __attribute__((__warning__ ("fread_unlocked called with bigger size * nmemb than " "length of destination buffer")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) __attribute__ ((__warn_unused_result__)) size_t
fread_unlocked (void *__restrict __ptr, size_t __size, size_t __n,
  FILE *__restrict __stream)
{
  size_t sz = __builtin_object_size (__ptr, 0);
  if (((__builtin_constant_p (sz) && (sz) == (long unsigned int) -1) || (((__typeof (__n)) 0 < (__typeof (__n)) -1 || (__builtin_constant_p (__n) && (__n) > 0)) && __builtin_constant_p ((((long unsigned int) (__n)) <= ((sz)) / ((__size)))) && (((long unsigned int) (__n)) <= ((sz)) / ((__size))))))
    {
      if (__builtin_constant_p (__size)
   && __builtin_constant_p (__n)
   && (__size | __n) < (((size_t) 1) << (8 * sizeof (size_t) / 2))
   && __size * __n <= 8)
 {
   size_t __cnt = __size * __n;
   char *__cptr = (char *) __ptr;
   if (__cnt == 0)
     return 0;
   for (; __cnt > 0; --__cnt)
     {
       int __c = getc_unlocked (__stream);
       if (__c == (-1))
  break;
       *__cptr++ = __c;
     }
   return (__cptr - (char *) __ptr) / __size;
 }
      return __fread_unlocked_alias (__ptr, __size, __n, __stream);
    }
  if ((((__typeof (__n)) 0 < (__typeof (__n)) -1 || (__builtin_constant_p (__n) && (__n) > 0)) && __builtin_constant_p ((((long unsigned int) (__n)) <= (sz) / (__size))) && !(((long unsigned int) (__n)) <= (sz) / (__size))))
    return __fread_unlocked_chk_warn (__ptr, sz, __size, __n, __stream);
  return __fread_unlocked_chk (__ptr, sz, __size, __n, __stream);
}


typedef __u_char u_char;
typedef __u_short u_short;
typedef __u_int u_int;
typedef __u_long u_long;
typedef __quad_t quad_t;
typedef __u_quad_t u_quad_t;
typedef __fsid_t fsid_t;
typedef __loff_t loff_t;
typedef __ino_t ino_t;
typedef __ino64_t ino64_t;
typedef __dev_t dev_t;
typedef __gid_t gid_t;
typedef __mode_t mode_t;
typedef __nlink_t nlink_t;
typedef __uid_t uid_t;
typedef __pid_t pid_t;
typedef __id_t id_t;
typedef __daddr_t daddr_t;
typedef __caddr_t caddr_t;
typedef __key_t key_t;
typedef __clock_t clock_t;
typedef __clockid_t clockid_t;
typedef __time_t time_t;
typedef __timer_t timer_t;
typedef __useconds_t useconds_t;
typedef __suseconds_t suseconds_t;
typedef unsigned long int ulong;
typedef unsigned short int ushort;
typedef unsigned int uint;
typedef __int8_t int8_t;
typedef __int16_t int16_t;
typedef __int32_t int32_t;
typedef __int64_t int64_t;
typedef __uint8_t u_int8_t;
typedef __uint16_t u_int16_t;
typedef __uint32_t u_int32_t;
typedef __uint64_t u_int64_t;
typedef int register_t __attribute__ ((__mode__ (__word__)));
static __inline __uint16_t
__bswap_16 (__uint16_t __bsx)
{
  return __builtin_bswap16 (__bsx);
}
static __inline __uint32_t
__bswap_32 (__uint32_t __bsx)
{
  return __builtin_bswap32 (__bsx);
}
__extension__ static __inline __uint64_t
__bswap_64 (__uint64_t __bsx)
{
  return __builtin_bswap64 (__bsx);
}
static __inline __uint16_t
__uint16_identity (__uint16_t __x)
{
  return __x;
}
static __inline __uint32_t
__uint32_identity (__uint32_t __x)
{
  return __x;
}
static __inline __uint64_t
__uint64_identity (__uint64_t __x)
{
  return __x;
}
typedef struct
{
  unsigned long int __val[(1024 / (8 * sizeof (unsigned long int)))];
} __sigset_t;
typedef __sigset_t sigset_t;
struct timeval
{
  __time_t tv_sec;
  __suseconds_t tv_usec;
};
struct timespec
{
  __time_t tv_sec;
  __syscall_slong_t tv_nsec;
};
typedef long int __fd_mask;
typedef struct
  {
    __fd_mask fds_bits[1024 / (8 * (int) sizeof (__fd_mask))];
  } fd_set;
typedef __fd_mask fd_mask;

extern int select (int __nfds, fd_set *__restrict __readfds,
     fd_set *__restrict __writefds,
     fd_set *__restrict __exceptfds,
     struct timeval *__restrict __timeout);
extern int pselect (int __nfds, fd_set *__restrict __readfds,
      fd_set *__restrict __writefds,
      fd_set *__restrict __exceptfds,
      const struct timespec *__restrict __timeout,
      const __sigset_t *__restrict __sigmask);
extern long int __fdelt_chk (long int __d);
extern long int __fdelt_warn (long int __d)
  __attribute__((__warning__ ("bit outside of fd_set selected")));

typedef __blksize_t blksize_t;
typedef __blkcnt_t blkcnt_t;
typedef __fsblkcnt_t fsblkcnt_t;
typedef __fsfilcnt_t fsfilcnt_t;
typedef __blkcnt64_t blkcnt64_t;
typedef __fsblkcnt64_t fsblkcnt64_t;
typedef __fsfilcnt64_t fsfilcnt64_t;
struct __pthread_rwlock_arch_t
{
  unsigned int __readers;
  unsigned int __writers;
  unsigned int __wrphase_futex;
  unsigned int __writers_futex;
  unsigned int __pad3;
  unsigned int __pad4;
  int __cur_writer;
  int __shared;
  signed char __rwelision;
  unsigned char __pad1[7];
  unsigned long int __pad2;
  unsigned int __flags;
};
typedef struct __pthread_internal_list
{
  struct __pthread_internal_list *__prev;
  struct __pthread_internal_list *__next;
} __pthread_list_t;
struct __pthread_mutex_s
{
  int __lock ;
  unsigned int __count;
  int __owner;
  unsigned int __nusers;
  int __kind;
 
  short __spins; short __elision;
  __pthread_list_t __list;
 
};
struct __pthread_cond_s
{
  __extension__ union
  {
    __extension__ unsigned long long int __wseq;
    struct
    {
      unsigned int __low;
      unsigned int __high;
    } __wseq32;
  };
  __extension__ union
  {
    __extension__ unsigned long long int __g1_start;
    struct
    {
      unsigned int __low;
      unsigned int __high;
    } __g1_start32;
  };
  unsigned int __g_refs[2] ;
  unsigned int __g_size[2];
  unsigned int __g1_orig_size;
  unsigned int __wrefs;
  unsigned int __g_signals[2];
};
typedef unsigned long int pthread_t;
typedef union
{
  char __size[4];
  int __align;
} pthread_mutexattr_t;
typedef union
{
  char __size[4];
  int __align;
} pthread_condattr_t;
typedef unsigned int pthread_key_t;
typedef int pthread_once_t;
union pthread_attr_t
{
  char __size[56];
  long int __align;
};
typedef union pthread_attr_t pthread_attr_t;
typedef union
{
  struct __pthread_mutex_s __data;
  char __size[40];
  long int __align;
} pthread_mutex_t;
typedef union
{
  struct __pthread_cond_s __data;
  char __size[48];
  __extension__ long long int __align;
} pthread_cond_t;
typedef union
{
  struct __pthread_rwlock_arch_t __data;
  char __size[56];
  long int __align;
} pthread_rwlock_t;
typedef union
{
  char __size[8];
  long int __align;
} pthread_rwlockattr_t;
typedef volatile int pthread_spinlock_t;
typedef union
{
  char __size[32];
  long int __align;
} pthread_barrier_t;
typedef union
{
  char __size[4];
  int __align;
} pthread_barrierattr_t;


struct stat
  {
    __dev_t st_dev;
    __ino_t st_ino;
    __nlink_t st_nlink;
    __mode_t st_mode;
    __uid_t st_uid;
    __gid_t st_gid;
    int __pad0;
    __dev_t st_rdev;
    __off_t st_size;
    __blksize_t st_blksize;
    __blkcnt_t st_blocks;
    struct timespec st_atim;
    struct timespec st_mtim;
    struct timespec st_ctim;
    __syscall_slong_t __glibc_reserved[3];
  };
struct stat64
  {
    __dev_t st_dev;
    __ino64_t st_ino;
    __nlink_t st_nlink;
    __mode_t st_mode;
    __uid_t st_uid;
    __gid_t st_gid;
    int __pad0;
    __dev_t st_rdev;
    __off_t st_size;
    __blksize_t st_blksize;
    __blkcnt64_t st_blocks;
    struct timespec st_atim;
    struct timespec st_mtim;
    struct timespec st_ctim;
    __syscall_slong_t __glibc_reserved[3];
  };
extern int stat (const char *__restrict __file,
   struct stat *__restrict __buf) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int fstat (int __fd, struct stat *__buf) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern int stat64 (const char *__restrict __file,
     struct stat64 *__restrict __buf) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int fstat64 (int __fd, struct stat64 *__buf) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern int fstatat (int __fd, const char *__restrict __file,
      struct stat *__restrict __buf, int __flag)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 3)));
extern int fstatat64 (int __fd, const char *__restrict __file,
        struct stat64 *__restrict __buf, int __flag)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 3)));
extern int lstat (const char *__restrict __file,
    struct stat *__restrict __buf) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int lstat64 (const char *__restrict __file,
      struct stat64 *__restrict __buf)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int chmod (const char *__file, __mode_t __mode)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int lchmod (const char *__file, __mode_t __mode)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int fchmod (int __fd, __mode_t __mode) __attribute__ ((__nothrow__ , __leaf__));
extern int fchmodat (int __fd, const char *__file, __mode_t __mode,
       int __flag)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2))) __attribute__ ((__warn_unused_result__));
extern __mode_t umask (__mode_t __mask) __attribute__ ((__nothrow__ , __leaf__));
extern __mode_t getumask (void) __attribute__ ((__nothrow__ , __leaf__));
extern int mkdir (const char *__path, __mode_t __mode)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int mkdirat (int __fd, const char *__path, __mode_t __mode)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern int mknod (const char *__path, __mode_t __mode, __dev_t __dev)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int mknodat (int __fd, const char *__path, __mode_t __mode,
      __dev_t __dev) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern int mkfifo (const char *__path, __mode_t __mode)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int mkfifoat (int __fd, const char *__path, __mode_t __mode)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern int utimensat (int __fd, const char *__path,
        const struct timespec __times[2],
        int __flags)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern int futimens (int __fd, const struct timespec __times[2]) __attribute__ ((__nothrow__ , __leaf__));
extern int __fxstat (int __ver, int __fildes, struct stat *__stat_buf)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3)));
extern int __xstat (int __ver, const char *__filename,
      struct stat *__stat_buf) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 3)));
extern int __lxstat (int __ver, const char *__filename,
       struct stat *__stat_buf) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 3)));
extern int __fxstatat (int __ver, int __fildes, const char *__filename,
         struct stat *__stat_buf, int __flag)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4)));
extern int __fxstat64 (int __ver, int __fildes, struct stat64 *__stat_buf)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3)));
extern int __xstat64 (int __ver, const char *__filename,
        struct stat64 *__stat_buf) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 3)));
extern int __lxstat64 (int __ver, const char *__filename,
         struct stat64 *__stat_buf) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 3)));
extern int __fxstatat64 (int __ver, int __fildes, const char *__filename,
    struct stat64 *__stat_buf, int __flag)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4)));
extern int __xmknod (int __ver, const char *__path, __mode_t __mode,
       __dev_t *__dev) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 4)));
extern int __xmknodat (int __ver, int __fd, const char *__path,
         __mode_t __mode, __dev_t *__dev)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 5)));
typedef __signed__ char __s8;
typedef unsigned char __u8;
typedef __signed__ short __s16;
typedef unsigned short __u16;
typedef __signed__ int __s32;
typedef unsigned int __u32;
__extension__ typedef __signed__ long long __s64;
__extension__ typedef unsigned long long __u64;
typedef struct {
 unsigned long fds_bits[1024 / (8 * sizeof(long))];
} __kernel_fd_set;
typedef void (*__kernel_sighandler_t)(int);
typedef int __kernel_key_t;
typedef int __kernel_mqd_t;
typedef unsigned short __kernel_old_uid_t;
typedef unsigned short __kernel_old_gid_t;
typedef unsigned long __kernel_old_dev_t;
typedef long __kernel_long_t;
typedef unsigned long __kernel_ulong_t;
typedef __kernel_ulong_t __kernel_ino_t;
typedef unsigned int __kernel_mode_t;
typedef int __kernel_pid_t;
typedef int __kernel_ipc_pid_t;
typedef unsigned int __kernel_uid_t;
typedef unsigned int __kernel_gid_t;
typedef __kernel_long_t __kernel_suseconds_t;
typedef int __kernel_daddr_t;
typedef unsigned int __kernel_uid32_t;
typedef unsigned int __kernel_gid32_t;
typedef __kernel_ulong_t __kernel_size_t;
typedef __kernel_long_t __kernel_ssize_t;
typedef __kernel_long_t __kernel_ptrdiff_t;
typedef struct {
 int val[2];
} __kernel_fsid_t;
typedef __kernel_long_t __kernel_off_t;
typedef long long __kernel_loff_t;
typedef __kernel_long_t __kernel_old_time_t;
typedef __kernel_long_t __kernel_time_t;
typedef long long __kernel_time64_t;
typedef __kernel_long_t __kernel_clock_t;
typedef int __kernel_timer_t;
typedef int __kernel_clockid_t;
typedef char * __kernel_caddr_t;
typedef unsigned short __kernel_uid16_t;
typedef unsigned short __kernel_gid16_t;
typedef __u16 __le16;
typedef __u16 __be16;
typedef __u32 __le32;
typedef __u32 __be32;
typedef __u64 __le64;
typedef __u64 __be64;
typedef __u16 __sum16;
typedef __u32 __wsum;
typedef unsigned __poll_t;
struct statx_timestamp {
 __s64 tv_sec;
 __u32 tv_nsec;
 __s32 __reserved;
};
struct statx {
 __u32 stx_mask;
 __u32 stx_blksize;
 __u64 stx_attributes;
 __u32 stx_nlink;
 __u32 stx_uid;
 __u32 stx_gid;
 __u16 stx_mode;
 __u16 __spare0[1];
 __u64 stx_ino;
 __u64 stx_size;
 __u64 stx_blocks;
 __u64 stx_attributes_mask;
 struct statx_timestamp stx_atime;
 struct statx_timestamp stx_btime;
 struct statx_timestamp stx_ctime;
 struct statx_timestamp stx_mtime;
 __u32 stx_rdev_major;
 __u32 stx_rdev_minor;
 __u32 stx_dev_major;
 __u32 stx_dev_minor;
 __u64 __spare2[14];
};

int statx (int __dirfd, const char *__restrict __path, int __flags,
           unsigned int __mask, struct statx *__restrict __buf)
  __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 5)));

extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ , __leaf__)) stat (const char *__path, struct stat *__statbuf)
{
  return __xstat (1, __path, __statbuf);
}
extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ , __leaf__)) lstat (const char *__path, struct stat *__statbuf)
{
  return __lxstat (1, __path, __statbuf);
}
extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ , __leaf__)) fstat (int __fd, struct stat *__statbuf)
{
  return __fxstat (1, __fd, __statbuf);
}
extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ , __leaf__)) fstatat (int __fd, const char *__filename, struct stat *__statbuf, int __flag)
{
  return __fxstatat (1, __fd, __filename, __statbuf, __flag);
}
extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ , __leaf__)) mknod (const char *__path, __mode_t __mode, __dev_t __dev)
{
  return __xmknod (0, __path, __mode, &__dev);
}
extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ , __leaf__)) mknodat (int __fd, const char *__path, __mode_t __mode, __dev_t __dev)
{
  return __xmknodat (0, __fd, __path, __mode, &__dev);
}
extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ , __leaf__)) stat64 (const char *__path, struct stat64 *__statbuf)
{
  return __xstat64 (1, __path, __statbuf);
}
extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ , __leaf__)) lstat64 (const char *__path, struct stat64 *__statbuf)
{
  return __lxstat64 (1, __path, __statbuf);
}
extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ , __leaf__)) fstat64 (int __fd, struct stat64 *__statbuf)
{
  return __fxstat64 (1, __fd, __statbuf);
}
extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ , __leaf__)) fstatat64 (int __fd, const char *__filename, struct stat64 *__statbuf, int __flag)
{
  return __fxstatat64 (1, __fd, __filename, __statbuf, __flag);
}

typedef int wchar_t;

typedef struct
  {
    int quot;
    int rem;
  } div_t;
typedef struct
  {
    long int quot;
    long int rem;
  } ldiv_t;
__extension__ typedef struct
  {
    long long int quot;
    long long int rem;
  } lldiv_t;
extern size_t __ctype_get_mb_cur_max (void) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern double atof (const char *__nptr)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int atoi (const char *__nptr)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern long int atol (const char *__nptr)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
__extension__ extern long long int atoll (const char *__nptr)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern double strtod (const char *__restrict __nptr,
        char **__restrict __endptr)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern float strtof (const char *__restrict __nptr,
       char **__restrict __endptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern long double strtold (const char *__restrict __nptr,
       char **__restrict __endptr)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern _Float32 strtof32 (const char *__restrict __nptr,
     char **__restrict __endptr)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern _Float64 strtof64 (const char *__restrict __nptr,
     char **__restrict __endptr)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern _Float128 strtof128 (const char *__restrict __nptr,
       char **__restrict __endptr)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern _Float32x strtof32x (const char *__restrict __nptr,
       char **__restrict __endptr)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern _Float64x strtof64x (const char *__restrict __nptr,
       char **__restrict __endptr)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern long int strtol (const char *__restrict __nptr,
   char **__restrict __endptr, int __base)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern unsigned long int strtoul (const char *__restrict __nptr,
      char **__restrict __endptr, int __base)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
__extension__
extern long long int strtoq (const char *__restrict __nptr,
        char **__restrict __endptr, int __base)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
__extension__
extern unsigned long long int strtouq (const char *__restrict __nptr,
           char **__restrict __endptr, int __base)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
__extension__
extern long long int strtoll (const char *__restrict __nptr,
         char **__restrict __endptr, int __base)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
__extension__
extern unsigned long long int strtoull (const char *__restrict __nptr,
     char **__restrict __endptr, int __base)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int strfromd (char *__dest, size_t __size, const char *__format,
       double __f)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3)));
extern int strfromf (char *__dest, size_t __size, const char *__format,
       float __f)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3)));
extern int strfroml (char *__dest, size_t __size, const char *__format,
       long double __f)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3)));
extern int strfromf32 (char *__dest, size_t __size, const char * __format,
         _Float32 __f)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3)));
extern int strfromf64 (char *__dest, size_t __size, const char * __format,
         _Float64 __f)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3)));
extern int strfromf128 (char *__dest, size_t __size, const char * __format,
   _Float128 __f)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3)));
extern int strfromf32x (char *__dest, size_t __size, const char * __format,
   _Float32x __f)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3)));
extern int strfromf64x (char *__dest, size_t __size, const char * __format,
   _Float64x __f)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3)));
struct __locale_struct
{
  struct __locale_data *__locales[13];
  const unsigned short int *__ctype_b;
  const int *__ctype_tolower;
  const int *__ctype_toupper;
  const char *__names[13];
};
typedef struct __locale_struct *__locale_t;
typedef __locale_t locale_t;
extern long int strtol_l (const char *__restrict __nptr,
     char **__restrict __endptr, int __base,
     locale_t __loc) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 4)));
extern unsigned long int strtoul_l (const char *__restrict __nptr,
        char **__restrict __endptr,
        int __base, locale_t __loc)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 4)));
__extension__
extern long long int strtoll_l (const char *__restrict __nptr,
    char **__restrict __endptr, int __base,
    locale_t __loc)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 4)));
__extension__
extern unsigned long long int strtoull_l (const char *__restrict __nptr,
       char **__restrict __endptr,
       int __base, locale_t __loc)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 4)));
extern double strtod_l (const char *__restrict __nptr,
   char **__restrict __endptr, locale_t __loc)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 3)));
extern float strtof_l (const char *__restrict __nptr,
         char **__restrict __endptr, locale_t __loc)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 3)));
extern long double strtold_l (const char *__restrict __nptr,
         char **__restrict __endptr,
         locale_t __loc)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 3)));
extern _Float32 strtof32_l (const char *__restrict __nptr,
       char **__restrict __endptr,
       locale_t __loc)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 3)));
extern _Float64 strtof64_l (const char *__restrict __nptr,
       char **__restrict __endptr,
       locale_t __loc)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 3)));
extern _Float128 strtof128_l (const char *__restrict __nptr,
         char **__restrict __endptr,
         locale_t __loc)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 3)));
extern _Float32x strtof32x_l (const char *__restrict __nptr,
         char **__restrict __endptr,
         locale_t __loc)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 3)));
extern _Float64x strtof64x_l (const char *__restrict __nptr,
         char **__restrict __endptr,
         locale_t __loc)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 3)));
extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ , __leaf__)) atoi (const char *__nptr)
{
  return (int) strtol (__nptr, (char **) ((void *)0), 10);
}
extern __inline __attribute__ ((__gnu_inline__)) long int
__attribute__ ((__nothrow__ , __leaf__)) atol (const char *__nptr)
{
  return strtol (__nptr, (char **) ((void *)0), 10);
}
__extension__ extern __inline __attribute__ ((__gnu_inline__)) long long int
__attribute__ ((__nothrow__ , __leaf__)) atoll (const char *__nptr)
{
  return strtoll (__nptr, (char **) ((void *)0), 10);
}
extern char *l64a (long int __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern long int a64l (const char *__s)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern long int random (void) __attribute__ ((__nothrow__ , __leaf__));
extern void srandom (unsigned int __seed) __attribute__ ((__nothrow__ , __leaf__));
extern char *initstate (unsigned int __seed, char *__statebuf,
   size_t __statelen) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern char *setstate (char *__statebuf) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
struct random_data
  {
    int32_t *fptr;
    int32_t *rptr;
    int32_t *state;
    int rand_type;
    int rand_deg;
    int rand_sep;
    int32_t *end_ptr;
  };
extern int random_r (struct random_data *__restrict __buf,
       int32_t *__restrict __result) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int srandom_r (unsigned int __seed, struct random_data *__buf)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern int initstate_r (unsigned int __seed, char *__restrict __statebuf,
   size_t __statelen,
   struct random_data *__restrict __buf)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 4)));
extern int setstate_r (char *__restrict __statebuf,
         struct random_data *__restrict __buf)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int rand (void) __attribute__ ((__nothrow__ , __leaf__));
extern void srand (unsigned int __seed) __attribute__ ((__nothrow__ , __leaf__));
extern int rand_r (unsigned int *__seed) __attribute__ ((__nothrow__ , __leaf__));
extern double drand48 (void) __attribute__ ((__nothrow__ , __leaf__));
extern double erand48 (unsigned short int __xsubi[3]) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern long int lrand48 (void) __attribute__ ((__nothrow__ , __leaf__));
extern long int nrand48 (unsigned short int __xsubi[3])
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern long int mrand48 (void) __attribute__ ((__nothrow__ , __leaf__));
extern long int jrand48 (unsigned short int __xsubi[3])
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern void srand48 (long int __seedval) __attribute__ ((__nothrow__ , __leaf__));
extern unsigned short int *seed48 (unsigned short int __seed16v[3])
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern void lcong48 (unsigned short int __param[7]) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
struct drand48_data
  {
    unsigned short int __x[3];
    unsigned short int __old_x[3];
    unsigned short int __c;
    unsigned short int __init;
    __extension__ unsigned long long int __a;
  };
extern int drand48_r (struct drand48_data *__restrict __buffer,
        double *__restrict __result) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int erand48_r (unsigned short int __xsubi[3],
        struct drand48_data *__restrict __buffer,
        double *__restrict __result) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int lrand48_r (struct drand48_data *__restrict __buffer,
        long int *__restrict __result)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int nrand48_r (unsigned short int __xsubi[3],
        struct drand48_data *__restrict __buffer,
        long int *__restrict __result)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int mrand48_r (struct drand48_data *__restrict __buffer,
        long int *__restrict __result)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int jrand48_r (unsigned short int __xsubi[3],
        struct drand48_data *__restrict __buffer,
        long int *__restrict __result)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int srand48_r (long int __seedval, struct drand48_data *__buffer)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern int seed48_r (unsigned short int __seed16v[3],
       struct drand48_data *__buffer) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int lcong48_r (unsigned short int __param[7],
        struct drand48_data *__buffer)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *malloc (size_t __size) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) __attribute__ ((__warn_unused_result__));
extern void *calloc (size_t __nmemb, size_t __size)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) __attribute__ ((__warn_unused_result__));
extern void *realloc (void *__ptr, size_t __size)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern void *reallocarray (void *__ptr, size_t __nmemb, size_t __size)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern void free (void *__ptr) __attribute__ ((__nothrow__ , __leaf__));

extern void *alloca (size_t __size) __attribute__ ((__nothrow__ , __leaf__));

extern void *valloc (size_t __size) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) __attribute__ ((__warn_unused_result__));
extern int posix_memalign (void **__memptr, size_t __alignment, size_t __size)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern void *aligned_alloc (size_t __alignment, size_t __size)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) __attribute__ ((__alloc_size__ (2))) __attribute__ ((__warn_unused_result__));
extern void abort (void) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__noreturn__));
extern int atexit (void (*__func) (void)) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int at_quick_exit (void (*__func) (void)) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int on_exit (void (*__func) (int __status, void *__arg), void *__arg)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern void exit (int __status) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__noreturn__));
extern void quick_exit (int __status) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__noreturn__));
extern void _Exit (int __status) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__noreturn__));
extern char *getenv (const char *__name) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern char *secure_getenv (const char *__name)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int putenv (char *__string) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int setenv (const char *__name, const char *__value, int __replace)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern int unsetenv (const char *__name) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int clearenv (void) __attribute__ ((__nothrow__ , __leaf__));
extern char *mktemp (char *__template) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int mkstemp (char *__template) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int mkstemp64 (char *__template) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int mkstemps (char *__template, int __suffixlen) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int mkstemps64 (char *__template, int __suffixlen)
     __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern char *mkdtemp (char *__template) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int mkostemp (char *__template, int __flags) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int mkostemp64 (char *__template, int __flags) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int mkostemps (char *__template, int __suffixlen, int __flags)
     __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int mkostemps64 (char *__template, int __suffixlen, int __flags)
     __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int system (const char *__command) __attribute__ ((__warn_unused_result__));
extern char *canonicalize_file_name (const char *__name)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern char *realpath (const char *__restrict __name,
         char *__restrict __resolved) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
typedef int (*__compar_fn_t) (const void *, const void *);
typedef __compar_fn_t comparison_fn_t;
typedef int (*__compar_d_fn_t) (const void *, const void *, void *);
extern void *bsearch (const void *__key, const void *__base,
        size_t __nmemb, size_t __size, __compar_fn_t __compar)
     __attribute__ ((__nonnull__ (1, 2, 5))) __attribute__ ((__warn_unused_result__));
extern __inline __attribute__ ((__gnu_inline__)) void *
bsearch (const void *__key, const void *__base, size_t __nmemb, size_t __size,
  __compar_fn_t __compar)
{
  size_t __l, __u, __idx;
  const void *__p;
  int __comparison;
  __l = 0;
  __u = __nmemb;
  while (__l < __u)
    {
      __idx = (__l + __u) / 2;
      __p = (void *) (((const char *) __base) + (__idx * __size));
      __comparison = (*__compar) (__key, __p);
      if (__comparison < 0)
 __u = __idx;
      else if (__comparison > 0)
 __l = __idx + 1;
      else
 return (void *) __p;
    }
  return ((void *)0);
}
extern void qsort (void *__base, size_t __nmemb, size_t __size,
     __compar_fn_t __compar) __attribute__ ((__nonnull__ (1, 4)));
extern void qsort_r (void *__base, size_t __nmemb, size_t __size,
       __compar_d_fn_t __compar, void *__arg)
  __attribute__ ((__nonnull__ (1, 4)));
extern int abs (int __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)) __attribute__ ((__warn_unused_result__));
extern long int labs (long int __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)) __attribute__ ((__warn_unused_result__));
__extension__ extern long long int llabs (long long int __x)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)) __attribute__ ((__warn_unused_result__));
extern div_t div (int __numer, int __denom)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)) __attribute__ ((__warn_unused_result__));
extern ldiv_t ldiv (long int __numer, long int __denom)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)) __attribute__ ((__warn_unused_result__));
__extension__ extern lldiv_t lldiv (long long int __numer,
        long long int __denom)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)) __attribute__ ((__warn_unused_result__));
extern char *ecvt (double __value, int __ndigit, int *__restrict __decpt,
     int *__restrict __sign) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4))) __attribute__ ((__warn_unused_result__));
extern char *fcvt (double __value, int __ndigit, int *__restrict __decpt,
     int *__restrict __sign) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4))) __attribute__ ((__warn_unused_result__));
extern char *gcvt (double __value, int __ndigit, char *__buf)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3))) __attribute__ ((__warn_unused_result__));
extern char *qecvt (long double __value, int __ndigit,
      int *__restrict __decpt, int *__restrict __sign)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4))) __attribute__ ((__warn_unused_result__));
extern char *qfcvt (long double __value, int __ndigit,
      int *__restrict __decpt, int *__restrict __sign)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4))) __attribute__ ((__warn_unused_result__));
extern char *qgcvt (long double __value, int __ndigit, char *__buf)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3))) __attribute__ ((__warn_unused_result__));
extern int ecvt_r (double __value, int __ndigit, int *__restrict __decpt,
     int *__restrict __sign, char *__restrict __buf,
     size_t __len) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4, 5)));
extern int fcvt_r (double __value, int __ndigit, int *__restrict __decpt,
     int *__restrict __sign, char *__restrict __buf,
     size_t __len) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4, 5)));
extern int qecvt_r (long double __value, int __ndigit,
      int *__restrict __decpt, int *__restrict __sign,
      char *__restrict __buf, size_t __len)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4, 5)));
extern int qfcvt_r (long double __value, int __ndigit,
      int *__restrict __decpt, int *__restrict __sign,
      char *__restrict __buf, size_t __len)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (3, 4, 5)));
extern int mblen (const char *__s, size_t __n) __attribute__ ((__nothrow__ , __leaf__));
extern int mbtowc (wchar_t *__restrict __pwc,
     const char *__restrict __s, size_t __n) __attribute__ ((__nothrow__ , __leaf__));
extern int wctomb (char *__s, wchar_t __wchar) __attribute__ ((__nothrow__ , __leaf__));
extern size_t mbstowcs (wchar_t *__restrict __pwcs,
   const char *__restrict __s, size_t __n) __attribute__ ((__nothrow__ , __leaf__));
extern size_t wcstombs (char *__restrict __s,
   const wchar_t *__restrict __pwcs, size_t __n)
     __attribute__ ((__nothrow__ , __leaf__));
extern int rpmatch (const char *__response) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int getsubopt (char **__restrict __optionp,
        char *const *__restrict __tokens,
        char **__restrict __valuep)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2, 3))) __attribute__ ((__warn_unused_result__));
extern int posix_openpt (int __oflag) __attribute__ ((__warn_unused_result__));
extern int grantpt (int __fd) __attribute__ ((__nothrow__ , __leaf__));
extern int unlockpt (int __fd) __attribute__ ((__nothrow__ , __leaf__));
extern char *ptsname (int __fd) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int ptsname_r (int __fd, char *__buf, size_t __buflen)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern int getpt (void);
extern int getloadavg (double __loadavg[], int __nelem)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern __inline __attribute__ ((__gnu_inline__)) double
__attribute__ ((__nothrow__ , __leaf__)) atof (const char *__nptr)
{
  return strtod (__nptr, (char **) ((void *)0));
}
extern char *__realpath_chk (const char *__restrict __name,
        char *__restrict __resolved,
        size_t __resolvedlen) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern char *__realpath_alias (const char *__restrict __name, char *__restrict __resolved) __asm__ ("" "realpath") __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern char *__realpath_chk_warn (const char *__restrict __name, char *__restrict __resolved, size_t __resolvedlen) __asm__ ("" "__realpath_chk") __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__))
     __attribute__((__warning__ ("second argument of realpath must be either NULL or at " "least PATH_MAX bytes long buffer")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) __attribute__ ((__warn_unused_result__)) char *
__attribute__ ((__nothrow__ , __leaf__)) realpath (const char *__restrict __name, char *__restrict __resolved)
{
  size_t sz = __builtin_object_size (__resolved, 2 > 1);
  if (sz == (size_t) -1)
    return __realpath_alias (__name, __resolved);
  return __realpath_chk (__name, __resolved, sz);
}
extern int __ptsname_r_chk (int __fd, char *__buf, size_t __buflen,
       size_t __nreal) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern int __ptsname_r_alias (int __fd, char *__buf, size_t __buflen) __asm__ ("" "ptsname_r") __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__nonnull__ (2)));
extern int __ptsname_r_chk_warn (int __fd, char *__buf, size_t __buflen, size_t __nreal) __asm__ ("" "__ptsname_r_chk") __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__nonnull__ (2))) __attribute__((__warning__ ("ptsname_r called with buflen bigger than " "size of buf")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
__attribute__ ((__nothrow__ , __leaf__)) ptsname_r (int __fd, char *__buf, size_t __buflen)
{
  return (((__builtin_constant_p (__builtin_object_size (__buf, 2 > 1)) && (__builtin_object_size (__buf, 2 > 1)) == (long unsigned int) -1) || (((__typeof (__buflen)) 0 < (__typeof (__buflen)) -1 || (__builtin_constant_p (__buflen) && (__buflen) > 0)) && __builtin_constant_p ((((long unsigned int) (__buflen)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char))))) && (((long unsigned int) (__buflen)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char)))))) ? __ptsname_r_alias (__fd, __buf, __buflen) : ((((__typeof (__buflen)) 0 < (__typeof (__buflen)) -1 || (__builtin_constant_p (__buflen) && (__buflen) > 0)) && __builtin_constant_p ((((long unsigned int) (__buflen)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) && !(((long unsigned int) (__buflen)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) ? __ptsname_r_chk_warn (__fd, __buf, __buflen, __builtin_object_size (__buf, 2 > 1)) : __ptsname_r_chk (__fd, __buf, __buflen, __builtin_object_size (__buf, 2 > 1))));
}
extern int __wctomb_chk (char *__s, wchar_t __wchar, size_t __buflen)
  __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int __wctomb_alias (char *__s, wchar_t __wchar) __asm__ ("" "wctomb") __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) __attribute__ ((__warn_unused_result__)) int
__attribute__ ((__nothrow__ , __leaf__)) wctomb (char *__s, wchar_t __wchar)
{
  if (__builtin_object_size (__s, 2 > 1) != (size_t) -1
      && 16 > __builtin_object_size (__s, 2 > 1))
    return __wctomb_chk (__s, __wchar, __builtin_object_size (__s, 2 > 1));
  return __wctomb_alias (__s, __wchar);
}
extern size_t __mbstowcs_chk (wchar_t *__restrict __dst,
         const char *__restrict __src,
         size_t __len, size_t __dstlen) __attribute__ ((__nothrow__ , __leaf__));
extern size_t __mbstowcs_alias (wchar_t *__restrict __dst, const char *__restrict __src, size_t __len) __asm__ ("" "mbstowcs") __attribute__ ((__nothrow__ , __leaf__));
extern size_t __mbstowcs_chk_warn (wchar_t *__restrict __dst, const char *__restrict __src, size_t __len, size_t __dstlen) __asm__ ("" "__mbstowcs_chk") __attribute__ ((__nothrow__ , __leaf__))
     __attribute__((__warning__ ("mbstowcs called with dst buffer smaller than len " "* sizeof (wchar_t)")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) size_t
__attribute__ ((__nothrow__ , __leaf__)) mbstowcs (wchar_t *__restrict __dst, const char *__restrict __src, size_t __len)
{
  return (((__builtin_constant_p (__builtin_object_size (__dst, 2 > 1)) && (__builtin_object_size (__dst, 2 > 1)) == (long unsigned int) -1) || (((__typeof (__len)) 0 < (__typeof (__len)) -1 || (__builtin_constant_p (__len) && (__len) > 0)) && __builtin_constant_p ((((long unsigned int) (__len)) <= ((__builtin_object_size (__dst, 2 > 1))) / ((sizeof (wchar_t))))) && (((long unsigned int) (__len)) <= ((__builtin_object_size (__dst, 2 > 1))) / ((sizeof (wchar_t)))))) ? __mbstowcs_alias (__dst, __src, __len) : ((((__typeof (__len)) 0 < (__typeof (__len)) -1 || (__builtin_constant_p (__len) && (__len) > 0)) && __builtin_constant_p ((((long unsigned int) (__len)) <= (__builtin_object_size (__dst, 2 > 1)) / (sizeof (wchar_t)))) && !(((long unsigned int) (__len)) <= (__builtin_object_size (__dst, 2 > 1)) / (sizeof (wchar_t)))) ? __mbstowcs_chk_warn (__dst, __src, __len, (__builtin_object_size (__dst, 2 > 1)) / (sizeof (wchar_t))) : __mbstowcs_chk (__dst, __src, __len, (__builtin_object_size (__dst, 2 > 1)) / (sizeof (wchar_t)))));
}
extern size_t __wcstombs_chk (char *__restrict __dst,
         const wchar_t *__restrict __src,
         size_t __len, size_t __dstlen) __attribute__ ((__nothrow__ , __leaf__));
extern size_t __wcstombs_alias (char *__restrict __dst, const wchar_t *__restrict __src, size_t __len) __asm__ ("" "wcstombs") __attribute__ ((__nothrow__ , __leaf__));
extern size_t __wcstombs_chk_warn (char *__restrict __dst, const wchar_t *__restrict __src, size_t __len, size_t __dstlen) __asm__ ("" "__wcstombs_chk") __attribute__ ((__nothrow__ , __leaf__))
     __attribute__((__warning__ ("wcstombs called with dst buffer smaller than len")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) size_t
__attribute__ ((__nothrow__ , __leaf__)) wcstombs (char *__restrict __dst, const wchar_t *__restrict __src, size_t __len)
{
  return (((__builtin_constant_p (__builtin_object_size (__dst, 2 > 1)) && (__builtin_object_size (__dst, 2 > 1)) == (long unsigned int) -1) || (((__typeof (__len)) 0 < (__typeof (__len)) -1 || (__builtin_constant_p (__len) && (__len) > 0)) && __builtin_constant_p ((((long unsigned int) (__len)) <= ((__builtin_object_size (__dst, 2 > 1))) / ((sizeof (char))))) && (((long unsigned int) (__len)) <= ((__builtin_object_size (__dst, 2 > 1))) / ((sizeof (char)))))) ? __wcstombs_alias (__dst, __src, __len) : ((((__typeof (__len)) 0 < (__typeof (__len)) -1 || (__builtin_constant_p (__len) && (__len) > 0)) && __builtin_constant_p ((((long unsigned int) (__len)) <= (__builtin_object_size (__dst, 2 > 1)) / (sizeof (char)))) && !(((long unsigned int) (__len)) <= (__builtin_object_size (__dst, 2 > 1)) / (sizeof (char)))) ? __wcstombs_chk_warn (__dst, __src, __len, __builtin_object_size (__dst, 2 > 1)) : __wcstombs_chk (__dst, __src, __len, __builtin_object_size (__dst, 2 > 1))));
}

typedef long int ptrdiff_t;
typedef struct {
  long long __max_align_ll __attribute__((__aligned__(__alignof__(long long))));
  long double __max_align_ld __attribute__((__aligned__(__alignof__(long double))));
} max_align_t;

extern void *memcpy (void *__restrict __dest, const void *__restrict __src,
       size_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *memmove (void *__dest, const void *__src, size_t __n)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *memccpy (void *__restrict __dest, const void *__restrict __src,
        int __c, size_t __n)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *memset (void *__s, int __c, size_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int memcmp (const void *__s1, const void *__s2, size_t __n)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *memchr (const void *__s, int __c, size_t __n)
      __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern void *rawmemchr (const void *__s, int __c)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern void *memrchr (const void *__s, int __c, size_t __n)
      __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strncpy (char *__restrict __dest,
        const char *__restrict __src, size_t __n)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strcat (char *__restrict __dest, const char *__restrict __src)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strncat (char *__restrict __dest, const char *__restrict __src,
        size_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strcmp (const char *__s1, const char *__s2)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strncmp (const char *__s1, const char *__s2, size_t __n)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strcoll (const char *__s1, const char *__s2)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern size_t strxfrm (char *__restrict __dest,
         const char *__restrict __src, size_t __n)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern int strcoll_l (const char *__s1, const char *__s2, locale_t __l)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2, 3)));
extern size_t strxfrm_l (char *__dest, const char *__src, size_t __n,
    locale_t __l) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 4)));
extern char *strdup (const char *__s)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) __attribute__ ((__nonnull__ (1)));
extern char *strndup (const char *__string, size_t __n)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) __attribute__ ((__nonnull__ (1)));
extern char *strchr (const char *__s, int __c)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern char *strrchr (const char *__s, int __c)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern char *strchrnul (const char *__s, int __c)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern size_t strcspn (const char *__s, const char *__reject)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern size_t strspn (const char *__s, const char *__accept)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strpbrk (const char *__s, const char *__accept)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strstr (const char *__haystack, const char *__needle)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strtok (char *__restrict __s, const char *__restrict __delim)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern char *__strtok_r (char *__restrict __s,
    const char *__restrict __delim,
    char **__restrict __save_ptr)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 3)));
extern char *strtok_r (char *__restrict __s, const char *__restrict __delim,
         char **__restrict __save_ptr)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 3)));
extern char *strcasestr (const char *__haystack, const char *__needle)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *memmem (const void *__haystack, size_t __haystacklen,
       const void *__needle, size_t __needlelen)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 3)));
extern void *__mempcpy (void *__restrict __dest,
   const void *__restrict __src, size_t __n)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *mempcpy (void *__restrict __dest,
        const void *__restrict __src, size_t __n)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern size_t strlen (const char *__s)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern size_t strnlen (const char *__string, size_t __maxlen)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern char *strerror (int __errnum) __attribute__ ((__nothrow__ , __leaf__));
extern char *strerror_r (int __errnum, char *__buf, size_t __buflen)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2))) __attribute__ ((__warn_unused_result__));
extern char *strerror_l (int __errnum, locale_t __l) __attribute__ ((__nothrow__ , __leaf__));

extern int bcmp (const void *__s1, const void *__s2, size_t __n)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern void bcopy (const void *__src, void *__dest, size_t __n)
  __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern void bzero (void *__s, size_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern char *index (const char *__s, int __c)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern char *rindex (const char *__s, int __c)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern int ffs (int __i) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int ffsl (long int __l) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
__extension__ extern int ffsll (long long int __ll)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int strcasecmp (const char *__s1, const char *__s2)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strncasecmp (const char *__s1, const char *__s2, size_t __n)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strcasecmp_l (const char *__s1, const char *__s2, locale_t __loc)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2, 3)));
extern int strncasecmp_l (const char *__s1, const char *__s2,
     size_t __n, locale_t __loc)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2, 4)));

extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) void
__attribute__ ((__nothrow__ , __leaf__)) bcopy (const void *__src, void *__dest, size_t __len)
{
  (void) __builtin___memmove_chk (__dest, __src, __len,
      __builtin_object_size (__dest, 0));
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) void
__attribute__ ((__nothrow__ , __leaf__)) bzero (void *__dest, size_t __len)
{
  (void) __builtin___memset_chk (__dest, '\0', __len,
     __builtin_object_size (__dest, 0));
}
extern void explicit_bzero (void *__s, size_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern char *strsep (char **__restrict __stringp,
       const char *__restrict __delim)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strsignal (int __sig) __attribute__ ((__nothrow__ , __leaf__));
extern char *__stpcpy (char *__restrict __dest, const char *__restrict __src)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *stpcpy (char *__restrict __dest, const char *__restrict __src)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *__stpncpy (char *__restrict __dest,
   const char *__restrict __src, size_t __n)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *stpncpy (char *__restrict __dest,
        const char *__restrict __src, size_t __n)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strverscmp (const char *__s1, const char *__s2)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strfry (char *__string) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern void *memfrob (void *__s, size_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern char *basename (const char *__filename) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) void *
__attribute__ ((__nothrow__ , __leaf__)) memcpy (void *__restrict __dest, const void *__restrict __src, size_t __len)
{
  return __builtin___memcpy_chk (__dest, __src, __len,
     __builtin_object_size (__dest, 0));
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) void *
__attribute__ ((__nothrow__ , __leaf__)) memmove (void *__dest, const void *__src, size_t __len)
{
  return __builtin___memmove_chk (__dest, __src, __len,
      __builtin_object_size (__dest, 0));
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) void *
__attribute__ ((__nothrow__ , __leaf__)) mempcpy (void *__restrict __dest, const void *__restrict __src, size_t __len)
{
  return __builtin___mempcpy_chk (__dest, __src, __len,
      __builtin_object_size (__dest, 0));
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) void *
__attribute__ ((__nothrow__ , __leaf__)) memset (void *__dest, int __ch, size_t __len)
{
  return __builtin___memset_chk (__dest, __ch, __len,
     __builtin_object_size (__dest, 0));
}
void __explicit_bzero_chk (void *__dest, size_t __len, size_t __destlen)
  __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) void
__attribute__ ((__nothrow__ , __leaf__)) explicit_bzero (void *__dest, size_t __len)
{
  __explicit_bzero_chk (__dest, __len, __builtin_object_size (__dest, 0));
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) char *
__attribute__ ((__nothrow__ , __leaf__)) strcpy (char *__restrict __dest, const char *__restrict __src)
{
  return __builtin___strcpy_chk (__dest, __src, __builtin_object_size (__dest, 2 > 1));
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) char *
__attribute__ ((__nothrow__ , __leaf__)) stpcpy (char *__restrict __dest, const char *__restrict __src)
{
  return __builtin___stpcpy_chk (__dest, __src, __builtin_object_size (__dest, 2 > 1));
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) char *
__attribute__ ((__nothrow__ , __leaf__)) strncpy (char *__restrict __dest, const char *__restrict __src, size_t __len)
{
  return __builtin___strncpy_chk (__dest, __src, __len,
      __builtin_object_size (__dest, 2 > 1));
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) char *
__attribute__ ((__nothrow__ , __leaf__)) stpncpy (char *__dest, const char *__src, size_t __n)
{
  return __builtin___stpncpy_chk (__dest, __src, __n,
      __builtin_object_size (__dest, 2 > 1));
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) char *
__attribute__ ((__nothrow__ , __leaf__)) strcat (char *__restrict __dest, const char *__restrict __src)
{
  return __builtin___strcat_chk (__dest, __src, __builtin_object_size (__dest, 2 > 1));
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) char *
__attribute__ ((__nothrow__ , __leaf__)) strncat (char *__restrict __dest, const char *__restrict __src, size_t __len)
{
  return __builtin___strncat_chk (__dest, __src, __len,
      __builtin_object_size (__dest, 2 > 1));
}

typedef __uint8_t uint8_t;
typedef __uint16_t uint16_t;
typedef __uint32_t uint32_t;
typedef __uint64_t uint64_t;
typedef __int_least8_t int_least8_t;
typedef __int_least16_t int_least16_t;
typedef __int_least32_t int_least32_t;
typedef __int_least64_t int_least64_t;
typedef __uint_least8_t uint_least8_t;
typedef __uint_least16_t uint_least16_t;
typedef __uint_least32_t uint_least32_t;
typedef __uint_least64_t uint_least64_t;
typedef signed char int_fast8_t;
typedef long int int_fast16_t;
typedef long int int_fast32_t;
typedef long int int_fast64_t;
typedef unsigned char uint_fast8_t;
typedef unsigned long int uint_fast16_t;
typedef unsigned long int uint_fast32_t;
typedef unsigned long int uint_fast64_t;
typedef long int intptr_t;
typedef unsigned long int uintptr_t;
typedef __intmax_t intmax_t;
typedef __uintmax_t uintmax_t;
typedef int __gwchar_t;

typedef struct
  {
    long int quot;
    long int rem;
  } imaxdiv_t;
extern intmax_t imaxabs (intmax_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern imaxdiv_t imaxdiv (intmax_t __numer, intmax_t __denom)
      __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern intmax_t strtoimax (const char *__restrict __nptr,
      char **__restrict __endptr, int __base) __attribute__ ((__nothrow__ , __leaf__));
extern uintmax_t strtoumax (const char *__restrict __nptr,
       char ** __restrict __endptr, int __base) __attribute__ ((__nothrow__ , __leaf__));
extern intmax_t wcstoimax (const __gwchar_t *__restrict __nptr,
      __gwchar_t **__restrict __endptr, int __base)
     __attribute__ ((__nothrow__ , __leaf__));
extern uintmax_t wcstoumax (const __gwchar_t *__restrict __nptr,
       __gwchar_t ** __restrict __endptr, int __base)
     __attribute__ ((__nothrow__ , __leaf__));
extern long int __strtol_internal (const char *__restrict __nptr,
       char **__restrict __endptr,
       int __base, int __group)
  __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern __inline __attribute__ ((__gnu_inline__)) intmax_t
__attribute__ ((__nothrow__ , __leaf__)) strtoimax (const char *__restrict nptr, char **__restrict endptr, int base)
{
  return __strtol_internal (nptr, endptr, base, 0);
}
extern unsigned long int __strtoul_internal (const char *__restrict __nptr,
          char ** __restrict __endptr,
          int __base, int __group)
  __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern __inline __attribute__ ((__gnu_inline__)) uintmax_t
__attribute__ ((__nothrow__ , __leaf__)) strtoumax (const char *__restrict nptr, char **__restrict endptr, int base)
{
  return __strtoul_internal (nptr, endptr, base, 0);
}
extern long int __wcstol_internal (const __gwchar_t * __restrict __nptr,
       __gwchar_t **__restrict __endptr,
       int __base, int __group)
  __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern __inline __attribute__ ((__gnu_inline__)) intmax_t
__attribute__ ((__nothrow__ , __leaf__)) wcstoimax (const __gwchar_t *__restrict nptr, __gwchar_t **__restrict endptr, int base)
{
  return __wcstol_internal (nptr, endptr, base, 0);
}
extern unsigned long int __wcstoul_internal (const __gwchar_t *
          __restrict __nptr,
          __gwchar_t **
          __restrict __endptr,
          int __base, int __group)
  __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern __inline __attribute__ ((__gnu_inline__)) uintmax_t
__attribute__ ((__nothrow__ , __leaf__)) wcstoumax (const __gwchar_t *__restrict nptr, __gwchar_t **__restrict endptr, int base)
{
  return __wcstoul_internal (nptr, endptr, base, 0);
}


typedef __socklen_t socklen_t;
extern int access (const char *__name, int __type) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int euidaccess (const char *__name, int __type)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int eaccess (const char *__name, int __type)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int faccessat (int __fd, const char *__file, int __type, int __flag)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2))) __attribute__ ((__warn_unused_result__));
extern __off_t lseek (int __fd, __off_t __offset, int __whence) __attribute__ ((__nothrow__ , __leaf__));
extern __off64_t lseek64 (int __fd, __off64_t __offset, int __whence)
     __attribute__ ((__nothrow__ , __leaf__));
extern int close (int __fd);
extern ssize_t read (int __fd, void *__buf, size_t __nbytes) __attribute__ ((__warn_unused_result__));
extern ssize_t write (int __fd, const void *__buf, size_t __n) __attribute__ ((__warn_unused_result__));
extern ssize_t pread (int __fd, void *__buf, size_t __nbytes,
        __off_t __offset) __attribute__ ((__warn_unused_result__));
extern ssize_t pwrite (int __fd, const void *__buf, size_t __n,
         __off_t __offset) __attribute__ ((__warn_unused_result__));
extern ssize_t pread64 (int __fd, void *__buf, size_t __nbytes,
   __off64_t __offset) __attribute__ ((__warn_unused_result__));
extern ssize_t pwrite64 (int __fd, const void *__buf, size_t __n,
    __off64_t __offset) __attribute__ ((__warn_unused_result__));
extern int pipe (int __pipedes[2]) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int pipe2 (int __pipedes[2], int __flags) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern unsigned int alarm (unsigned int __seconds) __attribute__ ((__nothrow__ , __leaf__));
extern unsigned int sleep (unsigned int __seconds);
extern __useconds_t ualarm (__useconds_t __value, __useconds_t __interval)
     __attribute__ ((__nothrow__ , __leaf__));
extern int usleep (__useconds_t __useconds);
extern int pause (void);
extern int chown (const char *__file, __uid_t __owner, __gid_t __group)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int fchown (int __fd, __uid_t __owner, __gid_t __group) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int lchown (const char *__file, __uid_t __owner, __gid_t __group)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int fchownat (int __fd, const char *__file, __uid_t __owner,
       __gid_t __group, int __flag)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2))) __attribute__ ((__warn_unused_result__));
extern int chdir (const char *__path) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int fchdir (int __fd) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern char *getcwd (char *__buf, size_t __size) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern char *get_current_dir_name (void) __attribute__ ((__nothrow__ , __leaf__));
extern char *getwd (char *__buf)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__deprecated__)) __attribute__ ((__warn_unused_result__));
extern int dup (int __fd) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int dup2 (int __fd, int __fd2) __attribute__ ((__nothrow__ , __leaf__));
extern int dup3 (int __fd, int __fd2, int __flags) __attribute__ ((__nothrow__ , __leaf__));
extern char **__environ;
extern char **environ;
extern int execve (const char *__path, char *const __argv[],
     char *const __envp[]) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int fexecve (int __fd, char *const __argv[], char *const __envp[])
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern int execv (const char *__path, char *const __argv[])
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int execle (const char *__path, const char *__arg, ...)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int execl (const char *__path, const char *__arg, ...)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int execvp (const char *__file, char *const __argv[])
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int execlp (const char *__file, const char *__arg, ...)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int execvpe (const char *__file, char *const __argv[],
      char *const __envp[])
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern int nice (int __inc) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern void _exit (int __status) __attribute__ ((__noreturn__));
enum
  {
    _PC_LINK_MAX,
    _PC_MAX_CANON,
    _PC_MAX_INPUT,
    _PC_NAME_MAX,
    _PC_PATH_MAX,
    _PC_PIPE_BUF,
    _PC_CHOWN_RESTRICTED,
    _PC_NO_TRUNC,
    _PC_VDISABLE,
    _PC_SYNC_IO,
    _PC_ASYNC_IO,
    _PC_PRIO_IO,
    _PC_SOCK_MAXBUF,
    _PC_FILESIZEBITS,
    _PC_REC_INCR_XFER_SIZE,
    _PC_REC_MAX_XFER_SIZE,
    _PC_REC_MIN_XFER_SIZE,
    _PC_REC_XFER_ALIGN,
    _PC_ALLOC_SIZE_MIN,
    _PC_SYMLINK_MAX,
    _PC_2_SYMLINKS
  };
enum
  {
    _SC_ARG_MAX,
    _SC_CHILD_MAX,
    _SC_CLK_TCK,
    _SC_NGROUPS_MAX,
    _SC_OPEN_MAX,
    _SC_STREAM_MAX,
    _SC_TZNAME_MAX,
    _SC_JOB_CONTROL,
    _SC_SAVED_IDS,
    _SC_REALTIME_SIGNALS,
    _SC_PRIORITY_SCHEDULING,
    _SC_TIMERS,
    _SC_ASYNCHRONOUS_IO,
    _SC_PRIORITIZED_IO,
    _SC_SYNCHRONIZED_IO,
    _SC_FSYNC,
    _SC_MAPPED_FILES,
    _SC_MEMLOCK,
    _SC_MEMLOCK_RANGE,
    _SC_MEMORY_PROTECTION,
    _SC_MESSAGE_PASSING,
    _SC_SEMAPHORES,
    _SC_SHARED_MEMORY_OBJECTS,
    _SC_AIO_LISTIO_MAX,
    _SC_AIO_MAX,
    _SC_AIO_PRIO_DELTA_MAX,
    _SC_DELAYTIMER_MAX,
    _SC_MQ_OPEN_MAX,
    _SC_MQ_PRIO_MAX,
    _SC_VERSION,
    _SC_PAGESIZE,
    _SC_RTSIG_MAX,
    _SC_SEM_NSEMS_MAX,
    _SC_SEM_VALUE_MAX,
    _SC_SIGQUEUE_MAX,
    _SC_TIMER_MAX,
    _SC_BC_BASE_MAX,
    _SC_BC_DIM_MAX,
    _SC_BC_SCALE_MAX,
    _SC_BC_STRING_MAX,
    _SC_COLL_WEIGHTS_MAX,
    _SC_EQUIV_CLASS_MAX,
    _SC_EXPR_NEST_MAX,
    _SC_LINE_MAX,
    _SC_RE_DUP_MAX,
    _SC_CHARCLASS_NAME_MAX,
    _SC_2_VERSION,
    _SC_2_C_BIND,
    _SC_2_C_DEV,
    _SC_2_FORT_DEV,
    _SC_2_FORT_RUN,
    _SC_2_SW_DEV,
    _SC_2_LOCALEDEF,
    _SC_PII,
    _SC_PII_XTI,
    _SC_PII_SOCKET,
    _SC_PII_INTERNET,
    _SC_PII_OSI,
    _SC_POLL,
    _SC_SELECT,
    _SC_UIO_MAXIOV,
    _SC_IOV_MAX = _SC_UIO_MAXIOV,
    _SC_PII_INTERNET_STREAM,
    _SC_PII_INTERNET_DGRAM,
    _SC_PII_OSI_COTS,
    _SC_PII_OSI_CLTS,
    _SC_PII_OSI_M,
    _SC_T_IOV_MAX,
    _SC_THREADS,
    _SC_THREAD_SAFE_FUNCTIONS,
    _SC_GETGR_R_SIZE_MAX,
    _SC_GETPW_R_SIZE_MAX,
    _SC_LOGIN_NAME_MAX,
    _SC_TTY_NAME_MAX,
    _SC_THREAD_DESTRUCTOR_ITERATIONS,
    _SC_THREAD_KEYS_MAX,
    _SC_THREAD_STACK_MIN,
    _SC_THREAD_THREADS_MAX,
    _SC_THREAD_ATTR_STACKADDR,
    _SC_THREAD_ATTR_STACKSIZE,
    _SC_THREAD_PRIORITY_SCHEDULING,
    _SC_THREAD_PRIO_INHERIT,
    _SC_THREAD_PRIO_PROTECT,
    _SC_THREAD_PROCESS_SHARED,
    _SC_NPROCESSORS_CONF,
    _SC_NPROCESSORS_ONLN,
    _SC_PHYS_PAGES,
    _SC_AVPHYS_PAGES,
    _SC_ATEXIT_MAX,
    _SC_PASS_MAX,
    _SC_XOPEN_VERSION,
    _SC_XOPEN_XCU_VERSION,
    _SC_XOPEN_UNIX,
    _SC_XOPEN_CRYPT,
    _SC_XOPEN_ENH_I18N,
    _SC_XOPEN_SHM,
    _SC_2_CHAR_TERM,
    _SC_2_C_VERSION,
    _SC_2_UPE,
    _SC_XOPEN_XPG2,
    _SC_XOPEN_XPG3,
    _SC_XOPEN_XPG4,
    _SC_CHAR_BIT,
    _SC_CHAR_MAX,
    _SC_CHAR_MIN,
    _SC_INT_MAX,
    _SC_INT_MIN,
    _SC_LONG_BIT,
    _SC_WORD_BIT,
    _SC_MB_LEN_MAX,
    _SC_NZERO,
    _SC_SSIZE_MAX,
    _SC_SCHAR_MAX,
    _SC_SCHAR_MIN,
    _SC_SHRT_MAX,
    _SC_SHRT_MIN,
    _SC_UCHAR_MAX,
    _SC_UINT_MAX,
    _SC_ULONG_MAX,
    _SC_USHRT_MAX,
    _SC_NL_ARGMAX,
    _SC_NL_LANGMAX,
    _SC_NL_MSGMAX,
    _SC_NL_NMAX,
    _SC_NL_SETMAX,
    _SC_NL_TEXTMAX,
    _SC_XBS5_ILP32_OFF32,
    _SC_XBS5_ILP32_OFFBIG,
    _SC_XBS5_LP64_OFF64,
    _SC_XBS5_LPBIG_OFFBIG,
    _SC_XOPEN_LEGACY,
    _SC_XOPEN_REALTIME,
    _SC_XOPEN_REALTIME_THREADS,
    _SC_ADVISORY_INFO,
    _SC_BARRIERS,
    _SC_BASE,
    _SC_C_LANG_SUPPORT,
    _SC_C_LANG_SUPPORT_R,
    _SC_CLOCK_SELECTION,
    _SC_CPUTIME,
    _SC_THREAD_CPUTIME,
    _SC_DEVICE_IO,
    _SC_DEVICE_SPECIFIC,
    _SC_DEVICE_SPECIFIC_R,
    _SC_FD_MGMT,
    _SC_FIFO,
    _SC_PIPE,
    _SC_FILE_ATTRIBUTES,
    _SC_FILE_LOCKING,
    _SC_FILE_SYSTEM,
    _SC_MONOTONIC_CLOCK,
    _SC_MULTI_PROCESS,
    _SC_SINGLE_PROCESS,
    _SC_NETWORKING,
    _SC_READER_WRITER_LOCKS,
    _SC_SPIN_LOCKS,
    _SC_REGEXP,
    _SC_REGEX_VERSION,
    _SC_SHELL,
    _SC_SIGNALS,
    _SC_SPAWN,
    _SC_SPORADIC_SERVER,
    _SC_THREAD_SPORADIC_SERVER,
    _SC_SYSTEM_DATABASE,
    _SC_SYSTEM_DATABASE_R,
    _SC_TIMEOUTS,
    _SC_TYPED_MEMORY_OBJECTS,
    _SC_USER_GROUPS,
    _SC_USER_GROUPS_R,
    _SC_2_PBS,
    _SC_2_PBS_ACCOUNTING,
    _SC_2_PBS_LOCATE,
    _SC_2_PBS_MESSAGE,
    _SC_2_PBS_TRACK,
    _SC_SYMLOOP_MAX,
    _SC_STREAMS,
    _SC_2_PBS_CHECKPOINT,
    _SC_V6_ILP32_OFF32,
    _SC_V6_ILP32_OFFBIG,
    _SC_V6_LP64_OFF64,
    _SC_V6_LPBIG_OFFBIG,
    _SC_HOST_NAME_MAX,
    _SC_TRACE,
    _SC_TRACE_EVENT_FILTER,
    _SC_TRACE_INHERIT,
    _SC_TRACE_LOG,
    _SC_LEVEL1_ICACHE_SIZE,
    _SC_LEVEL1_ICACHE_ASSOC,
    _SC_LEVEL1_ICACHE_LINESIZE,
    _SC_LEVEL1_DCACHE_SIZE,
    _SC_LEVEL1_DCACHE_ASSOC,
    _SC_LEVEL1_DCACHE_LINESIZE,
    _SC_LEVEL2_CACHE_SIZE,
    _SC_LEVEL2_CACHE_ASSOC,
    _SC_LEVEL2_CACHE_LINESIZE,
    _SC_LEVEL3_CACHE_SIZE,
    _SC_LEVEL3_CACHE_ASSOC,
    _SC_LEVEL3_CACHE_LINESIZE,
    _SC_LEVEL4_CACHE_SIZE,
    _SC_LEVEL4_CACHE_ASSOC,
    _SC_LEVEL4_CACHE_LINESIZE,
    _SC_IPV6 = _SC_LEVEL1_ICACHE_SIZE + 50,
    _SC_RAW_SOCKETS,
    _SC_V7_ILP32_OFF32,
    _SC_V7_ILP32_OFFBIG,
    _SC_V7_LP64_OFF64,
    _SC_V7_LPBIG_OFFBIG,
    _SC_SS_REPL_MAX,
    _SC_TRACE_EVENT_NAME_MAX,
    _SC_TRACE_NAME_MAX,
    _SC_TRACE_SYS_MAX,
    _SC_TRACE_USER_EVENT_MAX,
    _SC_XOPEN_STREAMS,
    _SC_THREAD_ROBUST_PRIO_INHERIT,
    _SC_THREAD_ROBUST_PRIO_PROTECT
  };
enum
  {
    _CS_PATH,
    _CS_V6_WIDTH_RESTRICTED_ENVS,
    _CS_GNU_LIBC_VERSION,
    _CS_GNU_LIBPTHREAD_VERSION,
    _CS_V5_WIDTH_RESTRICTED_ENVS,
    _CS_V7_WIDTH_RESTRICTED_ENVS,
    _CS_LFS_CFLAGS = 1000,
    _CS_LFS_LDFLAGS,
    _CS_LFS_LIBS,
    _CS_LFS_LINTFLAGS,
    _CS_LFS64_CFLAGS,
    _CS_LFS64_LDFLAGS,
    _CS_LFS64_LIBS,
    _CS_LFS64_LINTFLAGS,
    _CS_XBS5_ILP32_OFF32_CFLAGS = 1100,
    _CS_XBS5_ILP32_OFF32_LDFLAGS,
    _CS_XBS5_ILP32_OFF32_LIBS,
    _CS_XBS5_ILP32_OFF32_LINTFLAGS,
    _CS_XBS5_ILP32_OFFBIG_CFLAGS,
    _CS_XBS5_ILP32_OFFBIG_LDFLAGS,
    _CS_XBS5_ILP32_OFFBIG_LIBS,
    _CS_XBS5_ILP32_OFFBIG_LINTFLAGS,
    _CS_XBS5_LP64_OFF64_CFLAGS,
    _CS_XBS5_LP64_OFF64_LDFLAGS,
    _CS_XBS5_LP64_OFF64_LIBS,
    _CS_XBS5_LP64_OFF64_LINTFLAGS,
    _CS_XBS5_LPBIG_OFFBIG_CFLAGS,
    _CS_XBS5_LPBIG_OFFBIG_LDFLAGS,
    _CS_XBS5_LPBIG_OFFBIG_LIBS,
    _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS,
    _CS_POSIX_V6_ILP32_OFF32_CFLAGS,
    _CS_POSIX_V6_ILP32_OFF32_LDFLAGS,
    _CS_POSIX_V6_ILP32_OFF32_LIBS,
    _CS_POSIX_V6_ILP32_OFF32_LINTFLAGS,
    _CS_POSIX_V6_ILP32_OFFBIG_CFLAGS,
    _CS_POSIX_V6_ILP32_OFFBIG_LDFLAGS,
    _CS_POSIX_V6_ILP32_OFFBIG_LIBS,
    _CS_POSIX_V6_ILP32_OFFBIG_LINTFLAGS,
    _CS_POSIX_V6_LP64_OFF64_CFLAGS,
    _CS_POSIX_V6_LP64_OFF64_LDFLAGS,
    _CS_POSIX_V6_LP64_OFF64_LIBS,
    _CS_POSIX_V6_LP64_OFF64_LINTFLAGS,
    _CS_POSIX_V6_LPBIG_OFFBIG_CFLAGS,
    _CS_POSIX_V6_LPBIG_OFFBIG_LDFLAGS,
    _CS_POSIX_V6_LPBIG_OFFBIG_LIBS,
    _CS_POSIX_V6_LPBIG_OFFBIG_LINTFLAGS,
    _CS_POSIX_V7_ILP32_OFF32_CFLAGS,
    _CS_POSIX_V7_ILP32_OFF32_LDFLAGS,
    _CS_POSIX_V7_ILP32_OFF32_LIBS,
    _CS_POSIX_V7_ILP32_OFF32_LINTFLAGS,
    _CS_POSIX_V7_ILP32_OFFBIG_CFLAGS,
    _CS_POSIX_V7_ILP32_OFFBIG_LDFLAGS,
    _CS_POSIX_V7_ILP32_OFFBIG_LIBS,
    _CS_POSIX_V7_ILP32_OFFBIG_LINTFLAGS,
    _CS_POSIX_V7_LP64_OFF64_CFLAGS,
    _CS_POSIX_V7_LP64_OFF64_LDFLAGS,
    _CS_POSIX_V7_LP64_OFF64_LIBS,
    _CS_POSIX_V7_LP64_OFF64_LINTFLAGS,
    _CS_POSIX_V7_LPBIG_OFFBIG_CFLAGS,
    _CS_POSIX_V7_LPBIG_OFFBIG_LDFLAGS,
    _CS_POSIX_V7_LPBIG_OFFBIG_LIBS,
    _CS_POSIX_V7_LPBIG_OFFBIG_LINTFLAGS,
    _CS_V6_ENV,
    _CS_V7_ENV
  };
extern long int pathconf (const char *__path, int __name)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern long int fpathconf (int __fd, int __name) __attribute__ ((__nothrow__ , __leaf__));
extern long int sysconf (int __name) __attribute__ ((__nothrow__ , __leaf__));
extern size_t confstr (int __name, char *__buf, size_t __len) __attribute__ ((__nothrow__ , __leaf__));
extern __pid_t getpid (void) __attribute__ ((__nothrow__ , __leaf__));
extern __pid_t getppid (void) __attribute__ ((__nothrow__ , __leaf__));
extern __pid_t getpgrp (void) __attribute__ ((__nothrow__ , __leaf__));
extern __pid_t __getpgid (__pid_t __pid) __attribute__ ((__nothrow__ , __leaf__));
extern __pid_t getpgid (__pid_t __pid) __attribute__ ((__nothrow__ , __leaf__));
extern int setpgid (__pid_t __pid, __pid_t __pgid) __attribute__ ((__nothrow__ , __leaf__));
extern int setpgrp (void) __attribute__ ((__nothrow__ , __leaf__));
extern __pid_t setsid (void) __attribute__ ((__nothrow__ , __leaf__));
extern __pid_t getsid (__pid_t __pid) __attribute__ ((__nothrow__ , __leaf__));
extern __uid_t getuid (void) __attribute__ ((__nothrow__ , __leaf__));
extern __uid_t geteuid (void) __attribute__ ((__nothrow__ , __leaf__));
extern __gid_t getgid (void) __attribute__ ((__nothrow__ , __leaf__));
extern __gid_t getegid (void) __attribute__ ((__nothrow__ , __leaf__));
extern int getgroups (int __size, __gid_t __list[]) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int group_member (__gid_t __gid) __attribute__ ((__nothrow__ , __leaf__));
extern int setuid (__uid_t __uid) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int setreuid (__uid_t __ruid, __uid_t __euid) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int seteuid (__uid_t __uid) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int setgid (__gid_t __gid) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int setregid (__gid_t __rgid, __gid_t __egid) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int setegid (__gid_t __gid) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int getresuid (__uid_t *__ruid, __uid_t *__euid, __uid_t *__suid)
     __attribute__ ((__nothrow__ , __leaf__));
extern int getresgid (__gid_t *__rgid, __gid_t *__egid, __gid_t *__sgid)
     __attribute__ ((__nothrow__ , __leaf__));
extern int setresuid (__uid_t __ruid, __uid_t __euid, __uid_t __suid)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int setresgid (__gid_t __rgid, __gid_t __egid, __gid_t __sgid)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern __pid_t fork (void) __attribute__ ((__nothrow__));
extern __pid_t vfork (void) __attribute__ ((__nothrow__ , __leaf__));
extern char *ttyname (int __fd) __attribute__ ((__nothrow__ , __leaf__));
extern int ttyname_r (int __fd, char *__buf, size_t __buflen)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2))) __attribute__ ((__warn_unused_result__));
extern int isatty (int __fd) __attribute__ ((__nothrow__ , __leaf__));
extern int ttyslot (void) __attribute__ ((__nothrow__ , __leaf__));
extern int link (const char *__from, const char *__to)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))) __attribute__ ((__warn_unused_result__));
extern int linkat (int __fromfd, const char *__from, int __tofd,
     const char *__to, int __flags)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 4))) __attribute__ ((__warn_unused_result__));
extern int symlink (const char *__from, const char *__to)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))) __attribute__ ((__warn_unused_result__));
extern ssize_t readlink (const char *__restrict __path,
    char *__restrict __buf, size_t __len)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))) __attribute__ ((__warn_unused_result__));
extern int symlinkat (const char *__from, int __tofd,
        const char *__to) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 3))) __attribute__ ((__warn_unused_result__));
extern ssize_t readlinkat (int __fd, const char *__restrict __path,
      char *__restrict __buf, size_t __len)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 3))) __attribute__ ((__warn_unused_result__));
extern int unlink (const char *__name) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int unlinkat (int __fd, const char *__name, int __flag)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern int rmdir (const char *__path) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern __pid_t tcgetpgrp (int __fd) __attribute__ ((__nothrow__ , __leaf__));
extern int tcsetpgrp (int __fd, __pid_t __pgrp_id) __attribute__ ((__nothrow__ , __leaf__));
extern char *getlogin (void);
extern int getlogin_r (char *__name, size_t __name_len) __attribute__ ((__nonnull__ (1)));
extern int setlogin (const char *__name) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));

extern char *optarg;
extern int optind;
extern int opterr;
extern int optopt;
extern int getopt (int ___argc, char *const *___argv, const char *__shortopts)
       __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 3)));



extern int gethostname (char *__name, size_t __len) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int sethostname (const char *__name, size_t __len)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int sethostid (long int __id) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int getdomainname (char *__name, size_t __len)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int setdomainname (const char *__name, size_t __len)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int vhangup (void) __attribute__ ((__nothrow__ , __leaf__));
extern int revoke (const char *__file) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int profil (unsigned short int *__sample_buffer, size_t __size,
     size_t __offset, unsigned int __scale)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int acct (const char *__name) __attribute__ ((__nothrow__ , __leaf__));
extern char *getusershell (void) __attribute__ ((__nothrow__ , __leaf__));
extern void endusershell (void) __attribute__ ((__nothrow__ , __leaf__));
extern void setusershell (void) __attribute__ ((__nothrow__ , __leaf__));
extern int daemon (int __nochdir, int __noclose) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int chroot (const char *__path) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern char *getpass (const char *__prompt) __attribute__ ((__nonnull__ (1)));
extern int fsync (int __fd);
extern int syncfs (int __fd) __attribute__ ((__nothrow__ , __leaf__));
extern long int gethostid (void);
extern void sync (void) __attribute__ ((__nothrow__ , __leaf__));
extern int getpagesize (void) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int getdtablesize (void) __attribute__ ((__nothrow__ , __leaf__));
extern int truncate (const char *__file, __off_t __length)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int truncate64 (const char *__file, __off64_t __length)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int ftruncate (int __fd, __off_t __length) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int ftruncate64 (int __fd, __off64_t __length) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int brk (void *__addr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern void *sbrk (intptr_t __delta) __attribute__ ((__nothrow__ , __leaf__));
extern long int syscall (long int __sysno, ...) __attribute__ ((__nothrow__ , __leaf__));
extern int lockf (int __fd, int __cmd, __off_t __len) __attribute__ ((__warn_unused_result__));
extern int lockf64 (int __fd, int __cmd, __off64_t __len) __attribute__ ((__warn_unused_result__));
ssize_t copy_file_range (int __infd, __off64_t *__pinoff,
    int __outfd, __off64_t *__poutoff,
    size_t __length, unsigned int __flags);
extern int fdatasync (int __fildes);
extern char *crypt (const char *__key, const char *__salt)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
extern void swab (const void *__restrict __from, void *__restrict __to,
    ssize_t __n) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2)));
int getentropy (void *__buffer, size_t __length) __attribute__ ((__warn_unused_result__));
extern ssize_t __read_chk (int __fd, void *__buf, size_t __nbytes,
      size_t __buflen) __attribute__ ((__warn_unused_result__));
extern ssize_t __read_alias (int __fd, void *__buf, size_t __nbytes) __asm__ ("" "read") __attribute__ ((__warn_unused_result__));
extern ssize_t __read_chk_warn (int __fd, void *__buf, size_t __nbytes, size_t __buflen) __asm__ ("" "__read_chk")
     __attribute__ ((__warn_unused_result__)) __attribute__((__warning__ ("read called with bigger length than size of " "the destination buffer")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) __attribute__ ((__warn_unused_result__)) ssize_t
read (int __fd, void *__buf, size_t __nbytes)
{
  return (((__builtin_constant_p (__builtin_object_size (__buf, 0)) && (__builtin_object_size (__buf, 0)) == (long unsigned int) -1) || (((__typeof (__nbytes)) 0 < (__typeof (__nbytes)) -1 || (__builtin_constant_p (__nbytes) && (__nbytes) > 0)) && __builtin_constant_p ((((long unsigned int) (__nbytes)) <= ((__builtin_object_size (__buf, 0))) / ((sizeof (char))))) && (((long unsigned int) (__nbytes)) <= ((__builtin_object_size (__buf, 0))) / ((sizeof (char)))))) ? __read_alias (__fd, __buf, __nbytes) : ((((__typeof (__nbytes)) 0 < (__typeof (__nbytes)) -1 || (__builtin_constant_p (__nbytes) && (__nbytes) > 0)) && __builtin_constant_p ((((long unsigned int) (__nbytes)) <= (__builtin_object_size (__buf, 0)) / (sizeof (char)))) && !(((long unsigned int) (__nbytes)) <= (__builtin_object_size (__buf, 0)) / (sizeof (char)))) ? __read_chk_warn (__fd, __buf, __nbytes, __builtin_object_size (__buf, 0)) : __read_chk (__fd, __buf, __nbytes, __builtin_object_size (__buf, 0))));
}
extern ssize_t __pread_chk (int __fd, void *__buf, size_t __nbytes,
       __off_t __offset, size_t __bufsize) __attribute__ ((__warn_unused_result__));
extern ssize_t __pread64_chk (int __fd, void *__buf, size_t __nbytes,
         __off64_t __offset, size_t __bufsize) __attribute__ ((__warn_unused_result__));
extern ssize_t __pread_alias (int __fd, void *__buf, size_t __nbytes, __off_t __offset) __asm__ ("" "pread") __attribute__ ((__warn_unused_result__));
extern ssize_t __pread64_alias (int __fd, void *__buf, size_t __nbytes, __off64_t __offset) __asm__ ("" "pread64") __attribute__ ((__warn_unused_result__));
extern ssize_t __pread_chk_warn (int __fd, void *__buf, size_t __nbytes, __off_t __offset, size_t __bufsize) __asm__ ("" "__pread_chk")
     __attribute__ ((__warn_unused_result__)) __attribute__((__warning__ ("pread called with bigger length than size of " "the destination buffer")));
extern ssize_t __pread64_chk_warn (int __fd, void *__buf, size_t __nbytes, __off64_t __offset, size_t __bufsize) __asm__ ("" "__pread64_chk")
     __attribute__ ((__warn_unused_result__)) __attribute__((__warning__ ("pread64 called with bigger length than size of " "the destination buffer")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) __attribute__ ((__warn_unused_result__)) ssize_t
pread (int __fd, void *__buf, size_t __nbytes, __off_t __offset)
{
  return (((__builtin_constant_p (__builtin_object_size (__buf, 0)) && (__builtin_object_size (__buf, 0)) == (long unsigned int) -1) || (((__typeof (__nbytes)) 0 < (__typeof (__nbytes)) -1 || (__builtin_constant_p (__nbytes) && (__nbytes) > 0)) && __builtin_constant_p ((((long unsigned int) (__nbytes)) <= ((__builtin_object_size (__buf, 0))) / ((sizeof (char))))) && (((long unsigned int) (__nbytes)) <= ((__builtin_object_size (__buf, 0))) / ((sizeof (char)))))) ? __pread_alias (__fd, __buf, __nbytes, __offset) : ((((__typeof (__nbytes)) 0 < (__typeof (__nbytes)) -1 || (__builtin_constant_p (__nbytes) && (__nbytes) > 0)) && __builtin_constant_p ((((long unsigned int) (__nbytes)) <= (__builtin_object_size (__buf, 0)) / (sizeof (char)))) && !(((long unsigned int) (__nbytes)) <= (__builtin_object_size (__buf, 0)) / (sizeof (char)))) ? __pread_chk_warn (__fd, __buf, __nbytes, __offset, __builtin_object_size (__buf, 0)) : __pread_chk (__fd, __buf, __nbytes, __offset, __builtin_object_size (__buf, 0))));
}
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) __attribute__ ((__warn_unused_result__)) ssize_t
pread64 (int __fd, void *__buf, size_t __nbytes, __off64_t __offset)
{
  return (((__builtin_constant_p (__builtin_object_size (__buf, 0)) && (__builtin_object_size (__buf, 0)) == (long unsigned int) -1) || (((__typeof (__nbytes)) 0 < (__typeof (__nbytes)) -1 || (__builtin_constant_p (__nbytes) && (__nbytes) > 0)) && __builtin_constant_p ((((long unsigned int) (__nbytes)) <= ((__builtin_object_size (__buf, 0))) / ((sizeof (char))))) && (((long unsigned int) (__nbytes)) <= ((__builtin_object_size (__buf, 0))) / ((sizeof (char)))))) ? __pread64_alias (__fd, __buf, __nbytes, __offset) : ((((__typeof (__nbytes)) 0 < (__typeof (__nbytes)) -1 || (__builtin_constant_p (__nbytes) && (__nbytes) > 0)) && __builtin_constant_p ((((long unsigned int) (__nbytes)) <= (__builtin_object_size (__buf, 0)) / (sizeof (char)))) && !(((long unsigned int) (__nbytes)) <= (__builtin_object_size (__buf, 0)) / (sizeof (char)))) ? __pread64_chk_warn (__fd, __buf, __nbytes, __offset, __builtin_object_size (__buf, 0)) : __pread64_chk (__fd, __buf, __nbytes, __offset, __builtin_object_size (__buf, 0))));
}
extern ssize_t __readlink_chk (const char *__restrict __path,
          char *__restrict __buf, size_t __len,
          size_t __buflen)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1, 2))) __attribute__ ((__warn_unused_result__));
extern ssize_t __readlink_alias (const char *__restrict __path, char *__restrict __buf, size_t __len) __asm__ ("" "readlink") __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__nonnull__ (1, 2))) __attribute__ ((__warn_unused_result__));
extern ssize_t __readlink_chk_warn (const char *__restrict __path, char *__restrict __buf, size_t __len, size_t __buflen) __asm__ ("" "__readlink_chk") __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__nonnull__ (1, 2))) __attribute__ ((__warn_unused_result__)) __attribute__((__warning__ ("readlink called with bigger length " "than size of destination buffer")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) __attribute__ ((__nonnull__ (1, 2))) __attribute__ ((__warn_unused_result__)) ssize_t
__attribute__ ((__nothrow__ , __leaf__)) readlink (const char *__restrict __path, char *__restrict __buf, size_t __len)
{
  return (((__builtin_constant_p (__builtin_object_size (__buf, 2 > 1)) && (__builtin_object_size (__buf, 2 > 1)) == (long unsigned int) -1) || (((__typeof (__len)) 0 < (__typeof (__len)) -1 || (__builtin_constant_p (__len) && (__len) > 0)) && __builtin_constant_p ((((long unsigned int) (__len)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char))))) && (((long unsigned int) (__len)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char)))))) ? __readlink_alias (__path, __buf, __len) : ((((__typeof (__len)) 0 < (__typeof (__len)) -1 || (__builtin_constant_p (__len) && (__len) > 0)) && __builtin_constant_p ((((long unsigned int) (__len)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) && !(((long unsigned int) (__len)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) ? __readlink_chk_warn (__path, __buf, __len, __builtin_object_size (__buf, 2 > 1)) : __readlink_chk (__path, __buf, __len, __builtin_object_size (__buf, 2 > 1))));
}
extern ssize_t __readlinkat_chk (int __fd, const char *__restrict __path,
     char *__restrict __buf, size_t __len,
     size_t __buflen)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2, 3))) __attribute__ ((__warn_unused_result__));
extern ssize_t __readlinkat_alias (int __fd, const char *__restrict __path, char *__restrict __buf, size_t __len) __asm__ ("" "readlinkat") __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__nonnull__ (2, 3))) __attribute__ ((__warn_unused_result__));
extern ssize_t __readlinkat_chk_warn (int __fd, const char *__restrict __path, char *__restrict __buf, size_t __len, size_t __buflen) __asm__ ("" "__readlinkat_chk") __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__nonnull__ (2, 3))) __attribute__ ((__warn_unused_result__)) __attribute__((__warning__ ("readlinkat called with bigger " "length than size of destination " "buffer")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) __attribute__ ((__nonnull__ (2, 3))) __attribute__ ((__warn_unused_result__)) ssize_t
__attribute__ ((__nothrow__ , __leaf__)) readlinkat (int __fd, const char *__restrict __path, char *__restrict __buf, size_t __len)
{
  return (((__builtin_constant_p (__builtin_object_size (__buf, 2 > 1)) && (__builtin_object_size (__buf, 2 > 1)) == (long unsigned int) -1) || (((__typeof (__len)) 0 < (__typeof (__len)) -1 || (__builtin_constant_p (__len) && (__len) > 0)) && __builtin_constant_p ((((long unsigned int) (__len)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char))))) && (((long unsigned int) (__len)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char)))))) ? __readlinkat_alias (__fd, __path, __buf, __len) : ((((__typeof (__len)) 0 < (__typeof (__len)) -1 || (__builtin_constant_p (__len) && (__len) > 0)) && __builtin_constant_p ((((long unsigned int) (__len)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) && !(((long unsigned int) (__len)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) ? __readlinkat_chk_warn (__fd, __path, __buf, __len, __builtin_object_size (__buf, 2 > 1)) : __readlinkat_chk (__fd, __path, __buf, __len, __builtin_object_size (__buf, 2 > 1))));
}
extern char *__getcwd_chk (char *__buf, size_t __size, size_t __buflen)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern char *__getcwd_alias (char *__buf, size_t __size) __asm__ ("" "getcwd") __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern char *__getcwd_chk_warn (char *__buf, size_t __size, size_t __buflen) __asm__ ("" "__getcwd_chk") __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__warn_unused_result__)) __attribute__((__warning__ ("getcwd caller with bigger length than size of " "destination buffer")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) __attribute__ ((__warn_unused_result__)) char *
__attribute__ ((__nothrow__ , __leaf__)) getcwd (char *__buf, size_t __size)
{
  return (((__builtin_constant_p (__builtin_object_size (__buf, 2 > 1)) && (__builtin_object_size (__buf, 2 > 1)) == (long unsigned int) -1) || (((__typeof (__size)) 0 < (__typeof (__size)) -1 || (__builtin_constant_p (__size) && (__size) > 0)) && __builtin_constant_p ((((long unsigned int) (__size)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char))))) && (((long unsigned int) (__size)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char)))))) ? __getcwd_alias (__buf, __size) : ((((__typeof (__size)) 0 < (__typeof (__size)) -1 || (__builtin_constant_p (__size) && (__size) > 0)) && __builtin_constant_p ((((long unsigned int) (__size)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) && !(((long unsigned int) (__size)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) ? __getcwd_chk_warn (__buf, __size, __builtin_object_size (__buf, 2 > 1)) : __getcwd_chk (__buf, __size, __builtin_object_size (__buf, 2 > 1))));
}
extern char *__getwd_chk (char *__buf, size_t buflen)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern char *__getwd_warn (char *__buf) __asm__ ("" "getwd") __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__)) __attribute__((__warning__ ("please use getcwd instead, as getwd " "doesn't specify buffer size")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__deprecated__)) __attribute__ ((__warn_unused_result__)) char *
__attribute__ ((__nothrow__ , __leaf__)) getwd (char *__buf)
{
  if (__builtin_object_size (__buf, 2 > 1) != (size_t) -1)
    return __getwd_chk (__buf, __builtin_object_size (__buf, 2 > 1));
  return __getwd_warn (__buf);
}
extern size_t __confstr_chk (int __name, char *__buf, size_t __len,
        size_t __buflen) __attribute__ ((__nothrow__ , __leaf__));
extern size_t __confstr_alias (int __name, char *__buf, size_t __len) __asm__ ("" "confstr") __attribute__ ((__nothrow__ , __leaf__));
extern size_t __confstr_chk_warn (int __name, char *__buf, size_t __len, size_t __buflen) __asm__ ("" "__confstr_chk") __attribute__ ((__nothrow__ , __leaf__))
     __attribute__((__warning__ ("confstr called with bigger length than size of destination " "buffer")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) size_t
__attribute__ ((__nothrow__ , __leaf__)) confstr (int __name, char *__buf, size_t __len)
{
  return (((__builtin_constant_p (__builtin_object_size (__buf, 2 > 1)) && (__builtin_object_size (__buf, 2 > 1)) == (long unsigned int) -1) || (((__typeof (__len)) 0 < (__typeof (__len)) -1 || (__builtin_constant_p (__len) && (__len) > 0)) && __builtin_constant_p ((((long unsigned int) (__len)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char))))) && (((long unsigned int) (__len)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char)))))) ? __confstr_alias (__name, __buf, __len) : ((((__typeof (__len)) 0 < (__typeof (__len)) -1 || (__builtin_constant_p (__len) && (__len) > 0)) && __builtin_constant_p ((((long unsigned int) (__len)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) && !(((long unsigned int) (__len)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) ? __confstr_chk_warn (__name, __buf, __len, __builtin_object_size (__buf, 2 > 1)) : __confstr_chk (__name, __buf, __len, __builtin_object_size (__buf, 2 > 1))));
}
extern int __getgroups_chk (int __size, __gid_t __list[], size_t __listlen)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int __getgroups_alias (int __size, __gid_t __list[]) __asm__ ("" "getgroups") __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__warn_unused_result__));
extern int __getgroups_chk_warn (int __size, __gid_t __list[], size_t __listlen) __asm__ ("" "__getgroups_chk") __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__warn_unused_result__)) __attribute__((__warning__ ("getgroups called with bigger group count than what " "can fit into destination buffer")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
__attribute__ ((__nothrow__ , __leaf__)) getgroups (int __size, __gid_t __list[])
{
  return (((__builtin_constant_p (__builtin_object_size (__list, 2 > 1)) && (__builtin_object_size (__list, 2 > 1)) == (long unsigned int) -1) || (((__typeof (__size)) 0 < (__typeof (__size)) -1 || (__builtin_constant_p (__size) && (__size) > 0)) && __builtin_constant_p ((((long unsigned int) (__size)) <= ((__builtin_object_size (__list, 2 > 1))) / ((sizeof (__gid_t))))) && (((long unsigned int) (__size)) <= ((__builtin_object_size (__list, 2 > 1))) / ((sizeof (__gid_t)))))) ? __getgroups_alias (__size, __list) : ((((__typeof (__size)) 0 < (__typeof (__size)) -1 || (__builtin_constant_p (__size) && (__size) > 0)) && __builtin_constant_p ((((long unsigned int) (__size)) <= (__builtin_object_size (__list, 2 > 1)) / (sizeof (__gid_t)))) && !(((long unsigned int) (__size)) <= (__builtin_object_size (__list, 2 > 1)) / (sizeof (__gid_t)))) ? __getgroups_chk_warn (__size, __list, __builtin_object_size (__list, 2 > 1)) : __getgroups_chk (__size, __list, __builtin_object_size (__list, 2 > 1))));
}
extern int __ttyname_r_chk (int __fd, char *__buf, size_t __buflen,
       size_t __nreal) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern int __ttyname_r_alias (int __fd, char *__buf, size_t __buflen) __asm__ ("" "ttyname_r") __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__nonnull__ (2)));
extern int __ttyname_r_chk_warn (int __fd, char *__buf, size_t __buflen, size_t __nreal) __asm__ ("" "__ttyname_r_chk") __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__nonnull__ (2))) __attribute__((__warning__ ("ttyname_r called with bigger buflen than " "size of destination buffer")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
__attribute__ ((__nothrow__ , __leaf__)) ttyname_r (int __fd, char *__buf, size_t __buflen)
{
  return (((__builtin_constant_p (__builtin_object_size (__buf, 2 > 1)) && (__builtin_object_size (__buf, 2 > 1)) == (long unsigned int) -1) || (((__typeof (__buflen)) 0 < (__typeof (__buflen)) -1 || (__builtin_constant_p (__buflen) && (__buflen) > 0)) && __builtin_constant_p ((((long unsigned int) (__buflen)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char))))) && (((long unsigned int) (__buflen)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char)))))) ? __ttyname_r_alias (__fd, __buf, __buflen) : ((((__typeof (__buflen)) 0 < (__typeof (__buflen)) -1 || (__builtin_constant_p (__buflen) && (__buflen) > 0)) && __builtin_constant_p ((((long unsigned int) (__buflen)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) && !(((long unsigned int) (__buflen)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) ? __ttyname_r_chk_warn (__fd, __buf, __buflen, __builtin_object_size (__buf, 2 > 1)) : __ttyname_r_chk (__fd, __buf, __buflen, __builtin_object_size (__buf, 2 > 1))));
}
extern int __getlogin_r_chk (char *__buf, size_t __buflen, size_t __nreal)
     __attribute__ ((__nonnull__ (1)));
extern int __getlogin_r_alias (char *__buf, size_t __buflen) __asm__ ("" "getlogin_r") __attribute__ ((__nonnull__ (1)));
extern int __getlogin_r_chk_warn (char *__buf, size_t __buflen, size_t __nreal) __asm__ ("" "__getlogin_r_chk")
     __attribute__ ((__nonnull__ (1))) __attribute__((__warning__ ("getlogin_r called with bigger buflen than " "size of destination buffer")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
getlogin_r (char *__buf, size_t __buflen)
{
  return (((__builtin_constant_p (__builtin_object_size (__buf, 2 > 1)) && (__builtin_object_size (__buf, 2 > 1)) == (long unsigned int) -1) || (((__typeof (__buflen)) 0 < (__typeof (__buflen)) -1 || (__builtin_constant_p (__buflen) && (__buflen) > 0)) && __builtin_constant_p ((((long unsigned int) (__buflen)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char))))) && (((long unsigned int) (__buflen)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char)))))) ? __getlogin_r_alias (__buf, __buflen) : ((((__typeof (__buflen)) 0 < (__typeof (__buflen)) -1 || (__builtin_constant_p (__buflen) && (__buflen) > 0)) && __builtin_constant_p ((((long unsigned int) (__buflen)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) && !(((long unsigned int) (__buflen)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) ? __getlogin_r_chk_warn (__buf, __buflen, __builtin_object_size (__buf, 2 > 1)) : __getlogin_r_chk (__buf, __buflen, __builtin_object_size (__buf, 2 > 1))));
}
extern int __gethostname_chk (char *__buf, size_t __buflen, size_t __nreal)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int __gethostname_alias (char *__buf, size_t __buflen) __asm__ ("" "gethostname") __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int __gethostname_chk_warn (char *__buf, size_t __buflen, size_t __nreal) __asm__ ("" "__gethostname_chk") __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__nonnull__ (1))) __attribute__((__warning__ ("gethostname called with bigger buflen than " "size of destination buffer")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
__attribute__ ((__nothrow__ , __leaf__)) gethostname (char *__buf, size_t __buflen)
{
  return (((__builtin_constant_p (__builtin_object_size (__buf, 2 > 1)) && (__builtin_object_size (__buf, 2 > 1)) == (long unsigned int) -1) || (((__typeof (__buflen)) 0 < (__typeof (__buflen)) -1 || (__builtin_constant_p (__buflen) && (__buflen) > 0)) && __builtin_constant_p ((((long unsigned int) (__buflen)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char))))) && (((long unsigned int) (__buflen)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char)))))) ? __gethostname_alias (__buf, __buflen) : ((((__typeof (__buflen)) 0 < (__typeof (__buflen)) -1 || (__builtin_constant_p (__buflen) && (__buflen) > 0)) && __builtin_constant_p ((((long unsigned int) (__buflen)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) && !(((long unsigned int) (__buflen)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) ? __gethostname_chk_warn (__buf, __buflen, __builtin_object_size (__buf, 2 > 1)) : __gethostname_chk (__buf, __buflen, __builtin_object_size (__buf, 2 > 1))));
}
extern int __getdomainname_chk (char *__buf, size_t __buflen, size_t __nreal)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int __getdomainname_alias (char *__buf, size_t __buflen) __asm__ ("" "getdomainname") __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__));
extern int __getdomainname_chk_warn (char *__buf, size_t __buflen, size_t __nreal) __asm__ ("" "__getdomainname_chk") __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__nonnull__ (1))) __attribute__ ((__warn_unused_result__)) __attribute__((__warning__ ("getdomainname called with bigger " "buflen than size of destination " "buffer")));
extern __inline __attribute__ ((__always_inline__)) __attribute__ ((__gnu_inline__)) __attribute__ ((__artificial__)) int
__attribute__ ((__nothrow__ , __leaf__)) getdomainname (char *__buf, size_t __buflen)
{
  return (((__builtin_constant_p (__builtin_object_size (__buf, 2 > 1)) && (__builtin_object_size (__buf, 2 > 1)) == (long unsigned int) -1) || (((__typeof (__buflen)) 0 < (__typeof (__buflen)) -1 || (__builtin_constant_p (__buflen) && (__buflen) > 0)) && __builtin_constant_p ((((long unsigned int) (__buflen)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char))))) && (((long unsigned int) (__buflen)) <= ((__builtin_object_size (__buf, 2 > 1))) / ((sizeof (char)))))) ? __getdomainname_alias (__buf, __buflen) : ((((__typeof (__buflen)) 0 < (__typeof (__buflen)) -1 || (__builtin_constant_p (__buflen) && (__buflen) > 0)) && __builtin_constant_p ((((long unsigned int) (__buflen)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) && !(((long unsigned int) (__buflen)) <= (__builtin_object_size (__buf, 2 > 1)) / (sizeof (char)))) ? __getdomainname_chk_warn (__buf, __buflen, __builtin_object_size (__buf, 2 > 1)) : __getdomainname_chk (__buf, __buflen, __builtin_object_size (__buf, 2 > 1))));
}



__attribute__((__warn_unused_result__))
__attribute__((__malloc__))
__attribute__((__returns_nonnull__))
__attribute__((__alloc_size__ (1)))
void *ruby_xmalloc(size_t size)

;
__attribute__((__warn_unused_result__))
__attribute__((__malloc__))
__attribute__((__returns_nonnull__))
__attribute__((__alloc_size__ (1,2)))
void *ruby_xmalloc2(size_t nelems, size_t elemsiz)

;
__attribute__((__warn_unused_result__))
__attribute__((__malloc__))
__attribute__((__returns_nonnull__))
__attribute__((__alloc_size__ (1,2)))
void *ruby_xcalloc(size_t nelems, size_t elemsiz)

;
__attribute__((__warn_unused_result__))
__attribute__((__returns_nonnull__))
__attribute__((__alloc_size__ (2)))
void *ruby_xrealloc(void *ptr, size_t newsiz)

;
__attribute__((__warn_unused_result__))
__attribute__((__returns_nonnull__))
__attribute__((__alloc_size__ (2,3)))
void *ruby_xrealloc2(void *ptr, size_t newelems, size_t newsiz)

;
void ruby_xfree(void *ptr)

;


#define RBIMPL_ATTR_COLD_H 
#define RBIMPL_ATTR_COLD() __attribute__((__cold__))


__attribute__((__noreturn__))
__attribute__((__cold__))
void rb_assert_failure(const char *file, int line, const char *name, const char *expr);


#define COLDFUNC RBIMPL_ATTR_COLD()

typedef float float_t;
typedef double double_t;
enum
  {
    FP_INT_UPWARD =
      0,
    FP_INT_DOWNWARD =
      1,
    FP_INT_TOWARDZERO =
      2,
    FP_INT_TONEARESTFROMZERO =
      3,
    FP_INT_TONEAREST =
      4,
  };
extern int __fpclassify (double __value) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int __signbit (double __value) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int __isinf (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __finite (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __isnan (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __iseqsig (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern int __issignaling (double __value) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern double acos (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __acos (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double asin (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __asin (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double atan (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __atan (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double atan2 (double __y, double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __atan2 (double __y, double __x) __attribute__ ((__nothrow__ , __leaf__));
 extern double cos (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __cos (double __x) __attribute__ ((__nothrow__ , __leaf__));
 extern double sin (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __sin (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double tan (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __tan (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double cosh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __cosh (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double sinh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __sinh (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double tanh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __tanh (double __x) __attribute__ ((__nothrow__ , __leaf__));
 extern void sincos (double __x, double *__sinx, double *__cosx) __attribute__ ((__nothrow__ , __leaf__)); extern void __sincos (double __x, double *__sinx, double *__cosx) __attribute__ ((__nothrow__ , __leaf__));
extern double acosh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __acosh (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double asinh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __asinh (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double atanh (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __atanh (double __x) __attribute__ ((__nothrow__ , __leaf__));
 extern double exp (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __exp (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double frexp (double __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__)); extern double __frexp (double __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__));
extern double ldexp (double __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__)); extern double __ldexp (double __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__));
 extern double log (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __log (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double log10 (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __log10 (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double modf (double __x, double *__iptr) __attribute__ ((__nothrow__ , __leaf__)); extern double __modf (double __x, double *__iptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern double exp10 (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __exp10 (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double expm1 (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __expm1 (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double log1p (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __log1p (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double logb (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __logb (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double exp2 (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __exp2 (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double log2 (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __log2 (double __x) __attribute__ ((__nothrow__ , __leaf__));
 extern double pow (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __pow (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double sqrt (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __sqrt (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double hypot (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __hypot (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double cbrt (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __cbrt (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double ceil (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __ceil (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double fabs (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __fabs (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double floor (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __floor (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double fmod (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __fmod (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern int isinf (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int finite (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double drem (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __drem (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double significand (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __significand (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double copysign (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __copysign (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double nan (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__)); extern double __nan (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__));
extern int isnan (double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double j0 (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __j0 (double) __attribute__ ((__nothrow__ , __leaf__));
extern double j1 (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __j1 (double) __attribute__ ((__nothrow__ , __leaf__));
extern double jn (int, double) __attribute__ ((__nothrow__ , __leaf__)); extern double __jn (int, double) __attribute__ ((__nothrow__ , __leaf__));
extern double y0 (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __y0 (double) __attribute__ ((__nothrow__ , __leaf__));
extern double y1 (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __y1 (double) __attribute__ ((__nothrow__ , __leaf__));
extern double yn (int, double) __attribute__ ((__nothrow__ , __leaf__)); extern double __yn (int, double) __attribute__ ((__nothrow__ , __leaf__));
extern double erf (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __erf (double) __attribute__ ((__nothrow__ , __leaf__));
extern double erfc (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __erfc (double) __attribute__ ((__nothrow__ , __leaf__));
extern double lgamma (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __lgamma (double) __attribute__ ((__nothrow__ , __leaf__));
extern double tgamma (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __tgamma (double) __attribute__ ((__nothrow__ , __leaf__));
extern double gamma (double) __attribute__ ((__nothrow__ , __leaf__)); extern double __gamma (double) __attribute__ ((__nothrow__ , __leaf__));
extern double lgamma_r (double, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__)); extern double __lgamma_r (double, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__));
extern double rint (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __rint (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double nextafter (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __nextafter (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double nexttoward (double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __nexttoward (double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double nextdown (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __nextdown (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double nextup (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __nextup (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double remainder (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __remainder (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double scalbn (double __x, int __n) __attribute__ ((__nothrow__ , __leaf__)); extern double __scalbn (double __x, int __n) __attribute__ ((__nothrow__ , __leaf__));
extern int ilogb (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern int __ilogb (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int llogb (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __llogb (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double scalbln (double __x, long int __n) __attribute__ ((__nothrow__ , __leaf__)); extern double __scalbln (double __x, long int __n) __attribute__ ((__nothrow__ , __leaf__));
extern double nearbyint (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern double __nearbyint (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double round (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __round (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double trunc (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __trunc (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double remquo (double __x, double __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__)); extern double __remquo (double __x, double __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__));
extern long int lrint (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lrint (double __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llrint (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llrint (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int lround (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lround (double __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llround (double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llround (double __x) __attribute__ ((__nothrow__ , __leaf__));
extern double fdim (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)); extern double __fdim (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double fmax (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __fmax (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double fmin (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __fmin (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double fma (double __x, double __y, double __z) __attribute__ ((__nothrow__ , __leaf__)); extern double __fma (double __x, double __y, double __z) __attribute__ ((__nothrow__ , __leaf__));
extern double roundeven (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __roundeven (double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern __intmax_t fromfp (double __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __intmax_t __fromfp (double __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __uintmax_t ufromfp (double __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __uintmax_t __ufromfp (double __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __intmax_t fromfpx (double __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __intmax_t __fromfpx (double __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __uintmax_t ufromfpx (double __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __uintmax_t __ufromfpx (double __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern double fmaxmag (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __fmaxmag (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern double fminmag (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern double __fminmag (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int totalorder (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int totalordermag (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int canonicalize (double *__cx, const double *__x) __attribute__ ((__nothrow__ , __leaf__));
extern double getpayload (const double *__x) __attribute__ ((__nothrow__ , __leaf__)); extern double __getpayload (const double *__x) __attribute__ ((__nothrow__ , __leaf__));
extern int setpayload (double *__x, double __payload) __attribute__ ((__nothrow__ , __leaf__));
extern int setpayloadsig (double *__x, double __payload) __attribute__ ((__nothrow__ , __leaf__));
extern double scalb (double __x, double __n) __attribute__ ((__nothrow__ , __leaf__)); extern double __scalb (double __x, double __n) __attribute__ ((__nothrow__ , __leaf__));
extern int __fpclassifyf (float __value) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int __signbitf (float __value) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int __isinff (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __finitef (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __isnanf (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __iseqsigf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern int __issignalingf (float __value) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern float acosf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __acosf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float asinf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __asinf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float atanf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __atanf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float atan2f (float __y, float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __atan2f (float __y, float __x) __attribute__ ((__nothrow__ , __leaf__));
 extern float cosf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __cosf (float __x) __attribute__ ((__nothrow__ , __leaf__));
 extern float sinf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __sinf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float tanf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __tanf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float coshf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __coshf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float sinhf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __sinhf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float tanhf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __tanhf (float __x) __attribute__ ((__nothrow__ , __leaf__));
 extern void sincosf (float __x, float *__sinx, float *__cosx) __attribute__ ((__nothrow__ , __leaf__)); extern void __sincosf (float __x, float *__sinx, float *__cosx) __attribute__ ((__nothrow__ , __leaf__));
extern float acoshf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __acoshf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float asinhf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __asinhf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float atanhf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __atanhf (float __x) __attribute__ ((__nothrow__ , __leaf__));
 extern float expf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __expf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float frexpf (float __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__)); extern float __frexpf (float __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__));
extern float ldexpf (float __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__)); extern float __ldexpf (float __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__));
 extern float logf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __logf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float log10f (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __log10f (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float modff (float __x, float *__iptr) __attribute__ ((__nothrow__ , __leaf__)); extern float __modff (float __x, float *__iptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern float exp10f (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __exp10f (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float expm1f (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __expm1f (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float log1pf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __log1pf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float logbf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __logbf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float exp2f (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __exp2f (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float log2f (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __log2f (float __x) __attribute__ ((__nothrow__ , __leaf__));
 extern float powf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __powf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern float sqrtf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __sqrtf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float hypotf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __hypotf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern float cbrtf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __cbrtf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float ceilf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __ceilf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float fabsf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __fabsf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float floorf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __floorf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float fmodf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __fmodf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern int isinff (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int finitef (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float dremf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __dremf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern float significandf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __significandf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float copysignf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __copysignf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float nanf (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__)); extern float __nanf (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__));
extern int isnanf (float __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float j0f (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __j0f (float) __attribute__ ((__nothrow__ , __leaf__));
extern float j1f (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __j1f (float) __attribute__ ((__nothrow__ , __leaf__));
extern float jnf (int, float) __attribute__ ((__nothrow__ , __leaf__)); extern float __jnf (int, float) __attribute__ ((__nothrow__ , __leaf__));
extern float y0f (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __y0f (float) __attribute__ ((__nothrow__ , __leaf__));
extern float y1f (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __y1f (float) __attribute__ ((__nothrow__ , __leaf__));
extern float ynf (int, float) __attribute__ ((__nothrow__ , __leaf__)); extern float __ynf (int, float) __attribute__ ((__nothrow__ , __leaf__));
extern float erff (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __erff (float) __attribute__ ((__nothrow__ , __leaf__));
extern float erfcf (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __erfcf (float) __attribute__ ((__nothrow__ , __leaf__));
extern float lgammaf (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __lgammaf (float) __attribute__ ((__nothrow__ , __leaf__));
extern float tgammaf (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __tgammaf (float) __attribute__ ((__nothrow__ , __leaf__));
extern float gammaf (float) __attribute__ ((__nothrow__ , __leaf__)); extern float __gammaf (float) __attribute__ ((__nothrow__ , __leaf__));
extern float lgammaf_r (float, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__)); extern float __lgammaf_r (float, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__));
extern float rintf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __rintf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float nextafterf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __nextafterf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern float nexttowardf (float __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __nexttowardf (float __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern float nextdownf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __nextdownf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float nextupf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __nextupf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float remainderf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __remainderf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern float scalbnf (float __x, int __n) __attribute__ ((__nothrow__ , __leaf__)); extern float __scalbnf (float __x, int __n) __attribute__ ((__nothrow__ , __leaf__));
extern int ilogbf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern int __ilogbf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int llogbf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __llogbf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float scalblnf (float __x, long int __n) __attribute__ ((__nothrow__ , __leaf__)); extern float __scalblnf (float __x, long int __n) __attribute__ ((__nothrow__ , __leaf__));
extern float nearbyintf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern float __nearbyintf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float roundf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __roundf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float truncf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __truncf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float remquof (float __x, float __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__)); extern float __remquof (float __x, float __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__));
extern long int lrintf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lrintf (float __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llrintf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llrintf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int lroundf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lroundf (float __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llroundf (float __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llroundf (float __x) __attribute__ ((__nothrow__ , __leaf__));
extern float fdimf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)); extern float __fdimf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__));
extern float fmaxf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __fmaxf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float fminf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __fminf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float fmaf (float __x, float __y, float __z) __attribute__ ((__nothrow__ , __leaf__)); extern float __fmaf (float __x, float __y, float __z) __attribute__ ((__nothrow__ , __leaf__));
extern float roundevenf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __roundevenf (float __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern __intmax_t fromfpf (float __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __intmax_t __fromfpf (float __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __uintmax_t ufromfpf (float __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __uintmax_t __ufromfpf (float __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __intmax_t fromfpxf (float __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __intmax_t __fromfpxf (float __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __uintmax_t ufromfpxf (float __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __uintmax_t __ufromfpxf (float __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern float fmaxmagf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __fmaxmagf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern float fminmagf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern float __fminmagf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int totalorderf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int totalordermagf (float __x, float __y) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int canonicalizef (float *__cx, const float *__x) __attribute__ ((__nothrow__ , __leaf__));
extern float getpayloadf (const float *__x) __attribute__ ((__nothrow__ , __leaf__)); extern float __getpayloadf (const float *__x) __attribute__ ((__nothrow__ , __leaf__));
extern int setpayloadf (float *__x, float __payload) __attribute__ ((__nothrow__ , __leaf__));
extern int setpayloadsigf (float *__x, float __payload) __attribute__ ((__nothrow__ , __leaf__));
extern float scalbf (float __x, float __n) __attribute__ ((__nothrow__ , __leaf__)); extern float __scalbf (float __x, float __n) __attribute__ ((__nothrow__ , __leaf__));
extern int __fpclassifyl (long double __value) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int __signbitl (long double __value) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int __isinfl (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __finitel (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __isnanl (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __iseqsigl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern int __issignalingl (long double __value) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern long double acosl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __acosl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double asinl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __asinl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double atanl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __atanl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double atan2l (long double __y, long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __atan2l (long double __y, long double __x) __attribute__ ((__nothrow__ , __leaf__));
 extern long double cosl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __cosl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
 extern long double sinl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __sinl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double tanl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __tanl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double coshl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __coshl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double sinhl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __sinhl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double tanhl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __tanhl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
 extern void sincosl (long double __x, long double *__sinx, long double *__cosx) __attribute__ ((__nothrow__ , __leaf__)); extern void __sincosl (long double __x, long double *__sinx, long double *__cosx) __attribute__ ((__nothrow__ , __leaf__));
extern long double acoshl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __acoshl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double asinhl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __asinhl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double atanhl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __atanhl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
 extern long double expl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __expl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double frexpl (long double __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__)); extern long double __frexpl (long double __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__));
extern long double ldexpl (long double __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__)); extern long double __ldexpl (long double __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__));
 extern long double logl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __logl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double log10l (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __log10l (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double modfl (long double __x, long double *__iptr) __attribute__ ((__nothrow__ , __leaf__)); extern long double __modfl (long double __x, long double *__iptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern long double exp10l (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __exp10l (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double expm1l (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __expm1l (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double log1pl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __log1pl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double logbl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __logbl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double exp2l (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __exp2l (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double log2l (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __log2l (long double __x) __attribute__ ((__nothrow__ , __leaf__));
 extern long double powl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __powl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern long double sqrtl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __sqrtl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double hypotl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __hypotl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern long double cbrtl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __cbrtl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double ceill (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __ceill (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double fabsl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __fabsl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double floorl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __floorl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double fmodl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __fmodl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern int isinfl (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int finitel (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double dreml (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __dreml (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern long double significandl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __significandl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double copysignl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __copysignl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double nanl (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__)); extern long double __nanl (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__));
extern int isnanl (long double __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double j0l (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __j0l (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double j1l (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __j1l (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double jnl (int, long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __jnl (int, long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double y0l (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __y0l (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double y1l (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __y1l (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double ynl (int, long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __ynl (int, long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double erfl (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __erfl (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double erfcl (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __erfcl (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double lgammal (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __lgammal (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double tgammal (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __tgammal (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double gammal (long double) __attribute__ ((__nothrow__ , __leaf__)); extern long double __gammal (long double) __attribute__ ((__nothrow__ , __leaf__));
extern long double lgammal_r (long double, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__)); extern long double __lgammal_r (long double, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__));
extern long double rintl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __rintl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double nextafterl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __nextafterl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern long double nexttowardl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __nexttowardl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern long double nextdownl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __nextdownl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double nextupl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __nextupl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double remainderl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __remainderl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern long double scalbnl (long double __x, int __n) __attribute__ ((__nothrow__ , __leaf__)); extern long double __scalbnl (long double __x, int __n) __attribute__ ((__nothrow__ , __leaf__));
extern int ilogbl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern int __ilogbl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int llogbl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __llogbl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double scalblnl (long double __x, long int __n) __attribute__ ((__nothrow__ , __leaf__)); extern long double __scalblnl (long double __x, long int __n) __attribute__ ((__nothrow__ , __leaf__));
extern long double nearbyintl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __nearbyintl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double roundl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __roundl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double truncl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __truncl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double remquol (long double __x, long double __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__)); extern long double __remquol (long double __x, long double __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__));
extern long int lrintl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lrintl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llrintl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llrintl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int lroundl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lroundl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llroundl (long double __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llroundl (long double __x) __attribute__ ((__nothrow__ , __leaf__));
extern long double fdiml (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)); extern long double __fdiml (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern long double fmaxl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __fmaxl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double fminl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __fminl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double fmal (long double __x, long double __y, long double __z) __attribute__ ((__nothrow__ , __leaf__)); extern long double __fmal (long double __x, long double __y, long double __z) __attribute__ ((__nothrow__ , __leaf__));
extern long double roundevenl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __roundevenl (long double __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern __intmax_t fromfpl (long double __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __intmax_t __fromfpl (long double __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __uintmax_t ufromfpl (long double __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __uintmax_t __ufromfpl (long double __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __intmax_t fromfpxl (long double __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __intmax_t __fromfpxl (long double __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __uintmax_t ufromfpxl (long double __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __uintmax_t __ufromfpxl (long double __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern long double fmaxmagl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __fmaxmagl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern long double fminmagl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern long double __fminmagl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int totalorderl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int totalordermagl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int canonicalizel (long double *__cx, const long double *__x) __attribute__ ((__nothrow__ , __leaf__));
extern long double getpayloadl (const long double *__x) __attribute__ ((__nothrow__ , __leaf__)); extern long double __getpayloadl (const long double *__x) __attribute__ ((__nothrow__ , __leaf__));
extern int setpayloadl (long double *__x, long double __payload) __attribute__ ((__nothrow__ , __leaf__));
extern int setpayloadsigl (long double *__x, long double __payload) __attribute__ ((__nothrow__ , __leaf__));
extern long double scalbl (long double __x, long double __n) __attribute__ ((__nothrow__ , __leaf__)); extern long double __scalbl (long double __x, long double __n) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 acosf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __acosf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 asinf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __asinf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 atanf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __atanf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 atan2f32 (_Float32 __y, _Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __atan2f32 (_Float32 __y, _Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float32 cosf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __cosf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float32 sinf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __sinf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 tanf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __tanf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 coshf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __coshf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 sinhf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __sinhf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 tanhf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __tanhf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
 extern void sincosf32 (_Float32 __x, _Float32 *__sinx, _Float32 *__cosx) __attribute__ ((__nothrow__ , __leaf__)); extern void __sincosf32 (_Float32 __x, _Float32 *__sinx, _Float32 *__cosx) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 acoshf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __acoshf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 asinhf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __asinhf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 atanhf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __atanhf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float32 expf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __expf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 frexpf32 (_Float32 __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __frexpf32 (_Float32 __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 ldexpf32 (_Float32 __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __ldexpf32 (_Float32 __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float32 logf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __logf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 log10f32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __log10f32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 modff32 (_Float32 __x, _Float32 *__iptr) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __modff32 (_Float32 __x, _Float32 *__iptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern _Float32 exp10f32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __exp10f32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 expm1f32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __expm1f32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 log1pf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __log1pf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 logbf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __logbf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 exp2f32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __exp2f32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 log2f32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __log2f32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float32 powf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __powf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 sqrtf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __sqrtf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 hypotf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __hypotf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 cbrtf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __cbrtf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 ceilf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32 __ceilf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32 fabsf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32 __fabsf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32 floorf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32 __floorf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32 fmodf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __fmodf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 copysignf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32 __copysignf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32 nanf32 (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __nanf32 (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 j0f32 (_Float32) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __j0f32 (_Float32) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 j1f32 (_Float32) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __j1f32 (_Float32) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 jnf32 (int, _Float32) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __jnf32 (int, _Float32) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 y0f32 (_Float32) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __y0f32 (_Float32) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 y1f32 (_Float32) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __y1f32 (_Float32) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 ynf32 (int, _Float32) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __ynf32 (int, _Float32) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 erff32 (_Float32) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __erff32 (_Float32) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 erfcf32 (_Float32) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __erfcf32 (_Float32) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 lgammaf32 (_Float32) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __lgammaf32 (_Float32) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 tgammaf32 (_Float32) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __tgammaf32 (_Float32) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 lgammaf32_r (_Float32, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __lgammaf32_r (_Float32, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 rintf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __rintf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 nextafterf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __nextafterf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 nextdownf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __nextdownf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 nextupf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __nextupf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 remainderf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __remainderf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 scalbnf32 (_Float32 __x, int __n) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __scalbnf32 (_Float32 __x, int __n) __attribute__ ((__nothrow__ , __leaf__));
extern int ilogbf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern int __ilogbf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int llogbf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __llogbf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 scalblnf32 (_Float32 __x, long int __n) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __scalblnf32 (_Float32 __x, long int __n) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 nearbyintf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __nearbyintf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 roundf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32 __roundf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32 truncf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32 __truncf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32 remquof32 (_Float32 __x, _Float32 __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __remquof32 (_Float32 __x, _Float32 __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__));
extern long int lrintf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lrintf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llrintf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llrintf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int lroundf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lroundf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llroundf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llroundf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 fdimf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __fdimf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 fmaxf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32 __fmaxf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32 fminf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32 __fminf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32 fmaf32 (_Float32 __x, _Float32 __y, _Float32 __z) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __fmaf32 (_Float32 __x, _Float32 __y, _Float32 __z) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 roundevenf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32 __roundevenf32 (_Float32 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern __intmax_t fromfpf32 (_Float32 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __intmax_t __fromfpf32 (_Float32 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __uintmax_t ufromfpf32 (_Float32 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __uintmax_t __ufromfpf32 (_Float32 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __intmax_t fromfpxf32 (_Float32 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __intmax_t __fromfpxf32 (_Float32 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __uintmax_t ufromfpxf32 (_Float32 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __uintmax_t __ufromfpxf32 (_Float32 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 fmaxmagf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32 __fmaxmagf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32 fminmagf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32 __fminmagf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int totalorderf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int totalordermagf32 (_Float32 __x, _Float32 __y) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int canonicalizef32 (_Float32 *__cx, const _Float32 *__x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 getpayloadf32 (const _Float32 *__x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32 __getpayloadf32 (const _Float32 *__x) __attribute__ ((__nothrow__ , __leaf__));
extern int setpayloadf32 (_Float32 *__x, _Float32 __payload) __attribute__ ((__nothrow__ , __leaf__));
extern int setpayloadsigf32 (_Float32 *__x, _Float32 __payload) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 acosf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __acosf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 asinf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __asinf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 atanf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __atanf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 atan2f64 (_Float64 __y, _Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __atan2f64 (_Float64 __y, _Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float64 cosf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __cosf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float64 sinf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __sinf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 tanf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __tanf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 coshf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __coshf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 sinhf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __sinhf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 tanhf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __tanhf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
 extern void sincosf64 (_Float64 __x, _Float64 *__sinx, _Float64 *__cosx) __attribute__ ((__nothrow__ , __leaf__)); extern void __sincosf64 (_Float64 __x, _Float64 *__sinx, _Float64 *__cosx) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 acoshf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __acoshf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 asinhf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __asinhf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 atanhf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __atanhf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float64 expf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __expf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 frexpf64 (_Float64 __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __frexpf64 (_Float64 __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 ldexpf64 (_Float64 __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __ldexpf64 (_Float64 __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float64 logf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __logf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 log10f64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __log10f64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 modff64 (_Float64 __x, _Float64 *__iptr) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __modff64 (_Float64 __x, _Float64 *__iptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern _Float64 exp10f64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __exp10f64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 expm1f64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __expm1f64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 log1pf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __log1pf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 logbf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __logbf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 exp2f64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __exp2f64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 log2f64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __log2f64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float64 powf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __powf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 sqrtf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __sqrtf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 hypotf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __hypotf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 cbrtf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __cbrtf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 ceilf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64 __ceilf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64 fabsf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64 __fabsf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64 floorf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64 __floorf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64 fmodf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __fmodf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 copysignf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64 __copysignf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64 nanf64 (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __nanf64 (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 j0f64 (_Float64) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __j0f64 (_Float64) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 j1f64 (_Float64) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __j1f64 (_Float64) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 jnf64 (int, _Float64) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __jnf64 (int, _Float64) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 y0f64 (_Float64) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __y0f64 (_Float64) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 y1f64 (_Float64) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __y1f64 (_Float64) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 ynf64 (int, _Float64) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __ynf64 (int, _Float64) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 erff64 (_Float64) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __erff64 (_Float64) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 erfcf64 (_Float64) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __erfcf64 (_Float64) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 lgammaf64 (_Float64) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __lgammaf64 (_Float64) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 tgammaf64 (_Float64) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __tgammaf64 (_Float64) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 lgammaf64_r (_Float64, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __lgammaf64_r (_Float64, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 rintf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __rintf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 nextafterf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __nextafterf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 nextdownf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __nextdownf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 nextupf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __nextupf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 remainderf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __remainderf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 scalbnf64 (_Float64 __x, int __n) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __scalbnf64 (_Float64 __x, int __n) __attribute__ ((__nothrow__ , __leaf__));
extern int ilogbf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern int __ilogbf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int llogbf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __llogbf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 scalblnf64 (_Float64 __x, long int __n) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __scalblnf64 (_Float64 __x, long int __n) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 nearbyintf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __nearbyintf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 roundf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64 __roundf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64 truncf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64 __truncf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64 remquof64 (_Float64 __x, _Float64 __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __remquof64 (_Float64 __x, _Float64 __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__));
extern long int lrintf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lrintf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llrintf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llrintf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int lroundf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lroundf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llroundf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llroundf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 fdimf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __fdimf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 fmaxf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64 __fmaxf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64 fminf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64 __fminf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64 fmaf64 (_Float64 __x, _Float64 __y, _Float64 __z) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __fmaf64 (_Float64 __x, _Float64 __y, _Float64 __z) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 roundevenf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64 __roundevenf64 (_Float64 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern __intmax_t fromfpf64 (_Float64 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __intmax_t __fromfpf64 (_Float64 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __uintmax_t ufromfpf64 (_Float64 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __uintmax_t __ufromfpf64 (_Float64 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __intmax_t fromfpxf64 (_Float64 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __intmax_t __fromfpxf64 (_Float64 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __uintmax_t ufromfpxf64 (_Float64 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __uintmax_t __ufromfpxf64 (_Float64 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 fmaxmagf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64 __fmaxmagf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64 fminmagf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64 __fminmagf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int totalorderf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int totalordermagf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int canonicalizef64 (_Float64 *__cx, const _Float64 *__x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 getpayloadf64 (const _Float64 *__x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64 __getpayloadf64 (const _Float64 *__x) __attribute__ ((__nothrow__ , __leaf__));
extern int setpayloadf64 (_Float64 *__x, _Float64 __payload) __attribute__ ((__nothrow__ , __leaf__));
extern int setpayloadsigf64 (_Float64 *__x, _Float64 __payload) __attribute__ ((__nothrow__ , __leaf__));
extern int __fpclassifyf128 (_Float128 __value) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int __signbitf128 (_Float128 __value) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int __isinff128 (_Float128 __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __finitef128 (_Float128 __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __isnanf128 (_Float128 __value) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int __iseqsigf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern int __issignalingf128 (_Float128 __value) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern _Float128 acosf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __acosf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 asinf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __asinf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 atanf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __atanf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 atan2f128 (_Float128 __y, _Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __atan2f128 (_Float128 __y, _Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float128 cosf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __cosf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float128 sinf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __sinf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 tanf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __tanf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 coshf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __coshf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 sinhf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __sinhf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 tanhf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __tanhf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
 extern void sincosf128 (_Float128 __x, _Float128 *__sinx, _Float128 *__cosx) __attribute__ ((__nothrow__ , __leaf__)); extern void __sincosf128 (_Float128 __x, _Float128 *__sinx, _Float128 *__cosx) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 acoshf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __acoshf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 asinhf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __asinhf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 atanhf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __atanhf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float128 expf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __expf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 frexpf128 (_Float128 __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __frexpf128 (_Float128 __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 ldexpf128 (_Float128 __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __ldexpf128 (_Float128 __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float128 logf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __logf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 log10f128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __log10f128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 modff128 (_Float128 __x, _Float128 *__iptr) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __modff128 (_Float128 __x, _Float128 *__iptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern _Float128 exp10f128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __exp10f128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 expm1f128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __expm1f128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 log1pf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __log1pf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 logbf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __logbf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 exp2f128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __exp2f128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 log2f128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __log2f128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float128 powf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __powf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 sqrtf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __sqrtf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 hypotf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __hypotf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 cbrtf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __cbrtf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 ceilf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float128 __ceilf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float128 fabsf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float128 __fabsf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float128 floorf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float128 __floorf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float128 fmodf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __fmodf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 copysignf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float128 __copysignf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float128 nanf128 (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __nanf128 (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 j0f128 (_Float128) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __j0f128 (_Float128) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 j1f128 (_Float128) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __j1f128 (_Float128) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 jnf128 (int, _Float128) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __jnf128 (int, _Float128) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 y0f128 (_Float128) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __y0f128 (_Float128) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 y1f128 (_Float128) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __y1f128 (_Float128) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 ynf128 (int, _Float128) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __ynf128 (int, _Float128) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 erff128 (_Float128) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __erff128 (_Float128) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 erfcf128 (_Float128) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __erfcf128 (_Float128) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 lgammaf128 (_Float128) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __lgammaf128 (_Float128) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 tgammaf128 (_Float128) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __tgammaf128 (_Float128) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 lgammaf128_r (_Float128, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __lgammaf128_r (_Float128, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 rintf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __rintf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 nextafterf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __nextafterf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 nextdownf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __nextdownf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 nextupf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __nextupf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 remainderf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __remainderf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 scalbnf128 (_Float128 __x, int __n) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __scalbnf128 (_Float128 __x, int __n) __attribute__ ((__nothrow__ , __leaf__));
extern int ilogbf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern int __ilogbf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int llogbf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __llogbf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 scalblnf128 (_Float128 __x, long int __n) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __scalblnf128 (_Float128 __x, long int __n) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 nearbyintf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __nearbyintf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 roundf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float128 __roundf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float128 truncf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float128 __truncf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float128 remquof128 (_Float128 __x, _Float128 __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __remquof128 (_Float128 __x, _Float128 __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__));
extern long int lrintf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lrintf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llrintf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llrintf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int lroundf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lroundf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llroundf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llroundf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 fdimf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __fdimf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 fmaxf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float128 __fmaxf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float128 fminf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float128 __fminf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float128 fmaf128 (_Float128 __x, _Float128 __y, _Float128 __z) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __fmaf128 (_Float128 __x, _Float128 __y, _Float128 __z) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 roundevenf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float128 __roundevenf128 (_Float128 __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern __intmax_t fromfpf128 (_Float128 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __intmax_t __fromfpf128 (_Float128 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __uintmax_t ufromfpf128 (_Float128 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __uintmax_t __ufromfpf128 (_Float128 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __intmax_t fromfpxf128 (_Float128 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __intmax_t __fromfpxf128 (_Float128 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __uintmax_t ufromfpxf128 (_Float128 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __uintmax_t __ufromfpxf128 (_Float128 __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 fmaxmagf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float128 __fmaxmagf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float128 fminmagf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float128 __fminmagf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int totalorderf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int totalordermagf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int canonicalizef128 (_Float128 *__cx, const _Float128 *__x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float128 getpayloadf128 (const _Float128 *__x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float128 __getpayloadf128 (const _Float128 *__x) __attribute__ ((__nothrow__ , __leaf__));
extern int setpayloadf128 (_Float128 *__x, _Float128 __payload) __attribute__ ((__nothrow__ , __leaf__));
extern int setpayloadsigf128 (_Float128 *__x, _Float128 __payload) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x acosf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __acosf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x asinf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __asinf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x atanf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __atanf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x atan2f32x (_Float32x __y, _Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __atan2f32x (_Float32x __y, _Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float32x cosf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __cosf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float32x sinf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __sinf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x tanf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __tanf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x coshf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __coshf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x sinhf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __sinhf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x tanhf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __tanhf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
 extern void sincosf32x (_Float32x __x, _Float32x *__sinx, _Float32x *__cosx) __attribute__ ((__nothrow__ , __leaf__)); extern void __sincosf32x (_Float32x __x, _Float32x *__sinx, _Float32x *__cosx) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x acoshf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __acoshf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x asinhf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __asinhf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x atanhf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __atanhf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float32x expf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __expf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x frexpf32x (_Float32x __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __frexpf32x (_Float32x __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x ldexpf32x (_Float32x __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __ldexpf32x (_Float32x __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float32x logf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __logf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x log10f32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __log10f32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x modff32x (_Float32x __x, _Float32x *__iptr) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __modff32x (_Float32x __x, _Float32x *__iptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern _Float32x exp10f32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __exp10f32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x expm1f32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __expm1f32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x log1pf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __log1pf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x logbf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __logbf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x exp2f32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __exp2f32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x log2f32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __log2f32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float32x powf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __powf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x sqrtf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __sqrtf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x hypotf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __hypotf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x cbrtf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __cbrtf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x ceilf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32x __ceilf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32x fabsf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32x __fabsf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32x floorf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32x __floorf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32x fmodf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __fmodf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x copysignf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32x __copysignf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32x nanf32x (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __nanf32x (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x j0f32x (_Float32x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __j0f32x (_Float32x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x j1f32x (_Float32x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __j1f32x (_Float32x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x jnf32x (int, _Float32x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __jnf32x (int, _Float32x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x y0f32x (_Float32x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __y0f32x (_Float32x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x y1f32x (_Float32x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __y1f32x (_Float32x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x ynf32x (int, _Float32x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __ynf32x (int, _Float32x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x erff32x (_Float32x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __erff32x (_Float32x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x erfcf32x (_Float32x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __erfcf32x (_Float32x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x lgammaf32x (_Float32x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __lgammaf32x (_Float32x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x tgammaf32x (_Float32x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __tgammaf32x (_Float32x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x lgammaf32x_r (_Float32x, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __lgammaf32x_r (_Float32x, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x rintf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __rintf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x nextafterf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __nextafterf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x nextdownf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __nextdownf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x nextupf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __nextupf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x remainderf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __remainderf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x scalbnf32x (_Float32x __x, int __n) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __scalbnf32x (_Float32x __x, int __n) __attribute__ ((__nothrow__ , __leaf__));
extern int ilogbf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern int __ilogbf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int llogbf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __llogbf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x scalblnf32x (_Float32x __x, long int __n) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __scalblnf32x (_Float32x __x, long int __n) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x nearbyintf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __nearbyintf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x roundf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32x __roundf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32x truncf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32x __truncf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32x remquof32x (_Float32x __x, _Float32x __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __remquof32x (_Float32x __x, _Float32x __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__));
extern long int lrintf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lrintf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llrintf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llrintf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int lroundf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lroundf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llroundf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llroundf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x fdimf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __fdimf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x fmaxf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32x __fmaxf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32x fminf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32x __fminf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32x fmaf32x (_Float32x __x, _Float32x __y, _Float32x __z) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __fmaf32x (_Float32x __x, _Float32x __y, _Float32x __z) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x roundevenf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32x __roundevenf32x (_Float32x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern __intmax_t fromfpf32x (_Float32x __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __intmax_t __fromfpf32x (_Float32x __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __uintmax_t ufromfpf32x (_Float32x __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __uintmax_t __ufromfpf32x (_Float32x __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __intmax_t fromfpxf32x (_Float32x __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __intmax_t __fromfpxf32x (_Float32x __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __uintmax_t ufromfpxf32x (_Float32x __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __uintmax_t __ufromfpxf32x (_Float32x __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x fmaxmagf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32x __fmaxmagf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float32x fminmagf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float32x __fminmagf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int totalorderf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int totalordermagf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int canonicalizef32x (_Float32x *__cx, const _Float32x *__x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x getpayloadf32x (const _Float32x *__x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float32x __getpayloadf32x (const _Float32x *__x) __attribute__ ((__nothrow__ , __leaf__));
extern int setpayloadf32x (_Float32x *__x, _Float32x __payload) __attribute__ ((__nothrow__ , __leaf__));
extern int setpayloadsigf32x (_Float32x *__x, _Float32x __payload) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x acosf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __acosf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x asinf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __asinf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x atanf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __atanf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x atan2f64x (_Float64x __y, _Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __atan2f64x (_Float64x __y, _Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float64x cosf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __cosf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float64x sinf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __sinf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x tanf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __tanf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x coshf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __coshf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x sinhf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __sinhf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x tanhf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __tanhf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
 extern void sincosf64x (_Float64x __x, _Float64x *__sinx, _Float64x *__cosx) __attribute__ ((__nothrow__ , __leaf__)); extern void __sincosf64x (_Float64x __x, _Float64x *__sinx, _Float64x *__cosx) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x acoshf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __acoshf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x asinhf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __asinhf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x atanhf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __atanhf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float64x expf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __expf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x frexpf64x (_Float64x __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __frexpf64x (_Float64x __x, int *__exponent) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x ldexpf64x (_Float64x __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __ldexpf64x (_Float64x __x, int __exponent) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float64x logf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __logf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x log10f64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __log10f64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x modff64x (_Float64x __x, _Float64x *__iptr) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __modff64x (_Float64x __x, _Float64x *__iptr) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (2)));
extern _Float64x exp10f64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __exp10f64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x expm1f64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __expm1f64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x log1pf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __log1pf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x logbf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __logbf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x exp2f64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __exp2f64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x log2f64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __log2f64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
 extern _Float64x powf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __powf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x sqrtf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __sqrtf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x hypotf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __hypotf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x cbrtf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __cbrtf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x ceilf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64x __ceilf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64x fabsf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64x __fabsf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64x floorf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64x __floorf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64x fmodf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __fmodf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x copysignf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64x __copysignf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64x nanf64x (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __nanf64x (const char *__tagb) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x j0f64x (_Float64x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __j0f64x (_Float64x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x j1f64x (_Float64x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __j1f64x (_Float64x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x jnf64x (int, _Float64x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __jnf64x (int, _Float64x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x y0f64x (_Float64x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __y0f64x (_Float64x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x y1f64x (_Float64x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __y1f64x (_Float64x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x ynf64x (int, _Float64x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __ynf64x (int, _Float64x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x erff64x (_Float64x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __erff64x (_Float64x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x erfcf64x (_Float64x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __erfcf64x (_Float64x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x lgammaf64x (_Float64x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __lgammaf64x (_Float64x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x tgammaf64x (_Float64x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __tgammaf64x (_Float64x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x lgammaf64x_r (_Float64x, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __lgammaf64x_r (_Float64x, int *__signgamp) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x rintf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __rintf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x nextafterf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __nextafterf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x nextdownf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __nextdownf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x nextupf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __nextupf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x remainderf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __remainderf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x scalbnf64x (_Float64x __x, int __n) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __scalbnf64x (_Float64x __x, int __n) __attribute__ ((__nothrow__ , __leaf__));
extern int ilogbf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern int __ilogbf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int llogbf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __llogbf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x scalblnf64x (_Float64x __x, long int __n) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __scalblnf64x (_Float64x __x, long int __n) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x nearbyintf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __nearbyintf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x roundf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64x __roundf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64x truncf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64x __truncf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64x remquof64x (_Float64x __x, _Float64x __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __remquof64x (_Float64x __x, _Float64x __y, int *__quo) __attribute__ ((__nothrow__ , __leaf__));
extern long int lrintf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lrintf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llrintf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llrintf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern long int lroundf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern long int __lroundf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
__extension__
extern long long int llroundf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)); extern long long int __llroundf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x fdimf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __fdimf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x fmaxf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64x __fmaxf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64x fminf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64x __fminf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64x fmaf64x (_Float64x __x, _Float64x __y, _Float64x __z) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __fmaf64x (_Float64x __x, _Float64x __y, _Float64x __z) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x roundevenf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64x __roundevenf64x (_Float64x __x) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern __intmax_t fromfpf64x (_Float64x __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __intmax_t __fromfpf64x (_Float64x __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __uintmax_t ufromfpf64x (_Float64x __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __uintmax_t __ufromfpf64x (_Float64x __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __intmax_t fromfpxf64x (_Float64x __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __intmax_t __fromfpxf64x (_Float64x __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern __uintmax_t ufromfpxf64x (_Float64x __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__)); extern __uintmax_t __ufromfpxf64x (_Float64x __x, int __round, unsigned int __width) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x fmaxmagf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64x __fmaxmagf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern _Float64x fminmagf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__)); extern _Float64x __fminmagf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int totalorderf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int totalordermagf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__))
     __attribute__ ((__const__));
extern int canonicalizef64x (_Float64x *__cx, const _Float64x *__x) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x getpayloadf64x (const _Float64x *__x) __attribute__ ((__nothrow__ , __leaf__)); extern _Float64x __getpayloadf64x (const _Float64x *__x) __attribute__ ((__nothrow__ , __leaf__));
extern int setpayloadf64x (_Float64x *__x, _Float64x __payload) __attribute__ ((__nothrow__ , __leaf__));
extern int setpayloadsigf64x (_Float64x *__x, _Float64x __payload) __attribute__ ((__nothrow__ , __leaf__));
extern float fadd (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern float fdiv (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern float fmul (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern float fsub (double __x, double __y) __attribute__ ((__nothrow__ , __leaf__));
extern float faddl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern float fdivl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern float fmull (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern float fsubl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double daddl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double ddivl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double dmull (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern double dsubl (long double __x, long double __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 f32addf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 f32divf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 f32mulf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 f32subf32x (_Float32x __x, _Float32x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 f32addf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 f32divf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 f32mulf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 f32subf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 f32addf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 f32divf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 f32mulf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 f32subf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 f32addf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 f32divf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 f32mulf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32 f32subf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x f32xaddf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x f32xdivf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x f32xmulf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x f32xsubf64 (_Float64 __x, _Float64 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x f32xaddf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x f32xdivf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x f32xmulf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x f32xsubf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x f32xaddf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x f32xdivf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x f32xmulf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float32x f32xsubf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 f64addf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 f64divf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 f64mulf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 f64subf64x (_Float64x __x, _Float64x __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 f64addf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 f64divf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 f64mulf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64 f64subf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x f64xaddf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x f64xdivf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x f64xmulf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern _Float64x f64xsubf128 (_Float128 __x, _Float128 __y) __attribute__ ((__nothrow__ , __leaf__));
extern int signgam;
enum
  {
    FP_NAN =
      0,
    FP_INFINITE =
      1,
    FP_ZERO =
      2,
    FP_SUBNORMAL =
      3,
    FP_NORMAL =
      4
  };
extern int __iscanonicall (long double __x)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));

struct timex
{
  unsigned int modes;
  __syscall_slong_t offset;
  __syscall_slong_t freq;
  __syscall_slong_t maxerror;
  __syscall_slong_t esterror;
  int status;
  __syscall_slong_t constant;
  __syscall_slong_t precision;
  __syscall_slong_t tolerance;
  struct timeval time;
  __syscall_slong_t tick;
  __syscall_slong_t ppsfreq;
  __syscall_slong_t jitter;
  int shift;
  __syscall_slong_t stabil;
  __syscall_slong_t jitcnt;
  __syscall_slong_t calcnt;
  __syscall_slong_t errcnt;
  __syscall_slong_t stbcnt;
  int tai;
  int :32; int :32; int :32; int :32;
  int :32; int :32; int :32; int :32;
  int :32; int :32; int :32;
};

extern int clock_adjtime (__clockid_t __clock_id, struct timex *__utx) __attribute__ ((__nothrow__ , __leaf__));

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;
  long int tm_gmtoff;
  const char *tm_zone;
};
struct itimerspec
  {
    struct timespec it_interval;
    struct timespec it_value;
  };
struct sigevent;

extern clock_t clock (void) __attribute__ ((__nothrow__ , __leaf__));
extern time_t time (time_t *__timer) __attribute__ ((__nothrow__ , __leaf__));
extern double difftime (time_t __time1, time_t __time0)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern time_t mktime (struct tm *__tp) __attribute__ ((__nothrow__ , __leaf__));
extern size_t strftime (char *__restrict __s, size_t __maxsize,
   const char *__restrict __format,
   const struct tm *__restrict __tp) __attribute__ ((__nothrow__ , __leaf__));
extern char *strptime (const char *__restrict __s,
         const char *__restrict __fmt, struct tm *__tp)
     __attribute__ ((__nothrow__ , __leaf__));
extern size_t strftime_l (char *__restrict __s, size_t __maxsize,
     const char *__restrict __format,
     const struct tm *__restrict __tp,
     locale_t __loc) __attribute__ ((__nothrow__ , __leaf__));
extern char *strptime_l (const char *__restrict __s,
    const char *__restrict __fmt, struct tm *__tp,
    locale_t __loc) __attribute__ ((__nothrow__ , __leaf__));
extern struct tm *gmtime (const time_t *__timer) __attribute__ ((__nothrow__ , __leaf__));
extern struct tm *localtime (const time_t *__timer) __attribute__ ((__nothrow__ , __leaf__));
extern struct tm *gmtime_r (const time_t *__restrict __timer,
       struct tm *__restrict __tp) __attribute__ ((__nothrow__ , __leaf__));
extern struct tm *localtime_r (const time_t *__restrict __timer,
          struct tm *__restrict __tp) __attribute__ ((__nothrow__ , __leaf__));
extern char *asctime (const struct tm *__tp) __attribute__ ((__nothrow__ , __leaf__));
extern char *ctime (const time_t *__timer) __attribute__ ((__nothrow__ , __leaf__));
extern char *asctime_r (const struct tm *__restrict __tp,
   char *__restrict __buf) __attribute__ ((__nothrow__ , __leaf__));
extern char *ctime_r (const time_t *__restrict __timer,
        char *__restrict __buf) __attribute__ ((__nothrow__ , __leaf__));
extern char *__tzname[2];
extern int __daylight;
extern long int __timezone;
extern char *tzname[2];
extern void tzset (void) __attribute__ ((__nothrow__ , __leaf__));
extern int daylight;
extern long int timezone;
extern int stime (const time_t *__when) __attribute__ ((__nothrow__ , __leaf__));
extern time_t timegm (struct tm *__tp) __attribute__ ((__nothrow__ , __leaf__));
extern time_t timelocal (struct tm *__tp) __attribute__ ((__nothrow__ , __leaf__));
extern int dysize (int __year) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int nanosleep (const struct timespec *__requested_time,
        struct timespec *__remaining);
extern int clock_getres (clockid_t __clock_id, struct timespec *__res) __attribute__ ((__nothrow__ , __leaf__));
extern int clock_gettime (clockid_t __clock_id, struct timespec *__tp) __attribute__ ((__nothrow__ , __leaf__));
extern int clock_settime (clockid_t __clock_id, const struct timespec *__tp)
     __attribute__ ((__nothrow__ , __leaf__));
extern int clock_nanosleep (clockid_t __clock_id, int __flags,
       const struct timespec *__req,
       struct timespec *__rem);
extern int clock_getcpuclockid (pid_t __pid, clockid_t *__clock_id) __attribute__ ((__nothrow__ , __leaf__));
extern int timer_create (clockid_t __clock_id,
    struct sigevent *__restrict __evp,
    timer_t *__restrict __timerid) __attribute__ ((__nothrow__ , __leaf__));
extern int timer_delete (timer_t __timerid) __attribute__ ((__nothrow__ , __leaf__));
extern int timer_settime (timer_t __timerid, int __flags,
     const struct itimerspec *__restrict __value,
     struct itimerspec *__restrict __ovalue) __attribute__ ((__nothrow__ , __leaf__));
extern int timer_gettime (timer_t __timerid, struct itimerspec *__value)
     __attribute__ ((__nothrow__ , __leaf__));
extern int timer_getoverrun (timer_t __timerid) __attribute__ ((__nothrow__ , __leaf__));
extern int timespec_get (struct timespec *__ts, int __base)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int getdate_err;
extern struct tm *getdate (const char *__string);
extern int getdate_r (const char *__restrict __string,
        struct tm *__restrict __resbufp);


struct timezone
  {
    int tz_minuteswest;
    int tz_dsttime;
  };
typedef struct timezone *__restrict __timezone_ptr_t;
extern int gettimeofday (struct timeval *__restrict __tv,
    __timezone_ptr_t __tz) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int settimeofday (const struct timeval *__tv,
    const struct timezone *__tz)
     __attribute__ ((__nothrow__ , __leaf__));
extern int adjtime (const struct timeval *__delta,
      struct timeval *__olddelta) __attribute__ ((__nothrow__ , __leaf__));
enum __itimer_which
  {
    ITIMER_REAL = 0,
    ITIMER_VIRTUAL = 1,
    ITIMER_PROF = 2
  };
struct itimerval
  {
    struct timeval it_interval;
    struct timeval it_value;
  };
typedef enum __itimer_which __itimer_which_t;
extern int getitimer (__itimer_which_t __which,
        struct itimerval *__value) __attribute__ ((__nothrow__ , __leaf__));
extern int setitimer (__itimer_which_t __which,
        const struct itimerval *__restrict __new,
        struct itimerval *__restrict __old) __attribute__ ((__nothrow__ , __leaf__));
extern int utimes (const char *__file, const struct timeval __tvp[2])
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int lutimes (const char *__file, const struct timeval __tvp[2])
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__nonnull__ (1)));
extern int futimes (int __fd, const struct timeval __tvp[2]) __attribute__ ((__nothrow__ , __leaf__));
extern int futimesat (int __fd, const char *__file,
        const struct timeval __tvp[2]) __attribute__ ((__nothrow__ , __leaf__));



extern size_t strlcpy(char *, const char*, size_t);
extern size_t strlcat(char *, const char*, size_t);
extern void setproctitle(const char *fmt, ...);


typedef unsigned long VALUE;
typedef unsigned long ID;
__extension__ _Static_assert(4 == sizeof(int), "sizeof_int" ": " "SIZEOF_INT == sizeof(int)");
__extension__ _Static_assert(8 == sizeof(long), "sizeof_long" ": " "SIZEOF_LONG == sizeof(long)");
__extension__ _Static_assert(8 == sizeof(long long), "sizeof_long_long" ": " "SIZEOF_LONG_LONG == sizeof(LONG_LONG)");
__extension__ _Static_assert(8 == sizeof(void *), "sizeof_voidp" ": " "SIZEOF_VOIDP == sizeof(void *)");


VALUE rb_class_new(VALUE);
VALUE rb_mod_init_copy(VALUE, VALUE);
VALUE rb_singleton_class_clone(VALUE);
void rb_singleton_class_attached(VALUE,VALUE);
void rb_check_inheritable(VALUE);
VALUE rb_define_class_id(ID, VALUE);
VALUE rb_define_class_id_under(VALUE, ID, VALUE);
VALUE rb_module_new(void);
VALUE rb_define_module_id(ID);
VALUE rb_define_module_id_under(VALUE, ID);
VALUE rb_mod_included_modules(VALUE);
VALUE rb_mod_include_p(VALUE, VALUE);
VALUE rb_mod_ancestors(VALUE);
VALUE rb_class_instance_methods(int, const VALUE*, VALUE);
VALUE rb_class_public_instance_methods(int, const VALUE*, VALUE);
VALUE rb_class_protected_instance_methods(int, const VALUE*, VALUE);
VALUE rb_class_private_instance_methods(int, const VALUE*, VALUE);
VALUE rb_obj_singleton_methods(int, const VALUE*, VALUE);
void rb_define_method_id(VALUE, ID, VALUE (*)(), int);
void rb_undef(VALUE, ID);
void rb_define_protected_method(VALUE, const char*, VALUE (*)(), int);
void rb_define_private_method(VALUE, const char*, VALUE (*)(), int);
void rb_define_singleton_method(VALUE, const char*, VALUE(*)(), int);
VALUE rb_singleton_class(VALUE);




int rb_sourceline(void);
const char *rb_sourcefile(void);
int rb_frame_method_id_and_class(ID *idp, VALUE *klassp);
VALUE rb_check_funcall(VALUE, ID, int, const VALUE*);
VALUE rb_check_funcall_kw(VALUE, ID, int, const VALUE*, int);
void rb_remove_method(VALUE, const char*);
void rb_remove_method_id(VALUE, ID);
VALUE rb_eval_cmd_kw(VALUE, VALUE, int);
VALUE rb_apply(VALUE, ID, VALUE);
VALUE rb_obj_instance_eval(int, const VALUE*, VALUE);
VALUE rb_obj_instance_exec(int, const VALUE*, VALUE);
VALUE rb_mod_module_eval(int, const VALUE*, VALUE);
VALUE rb_mod_module_exec(int, const VALUE*, VALUE);
typedef VALUE (*rb_alloc_func_t)(VALUE);
void rb_define_alloc_func(VALUE, rb_alloc_func_t);
void rb_undef_alloc_func(VALUE);
rb_alloc_func_t rb_get_alloc_func(VALUE);
void rb_clear_constant_cache(void);
void rb_clear_method_cache_by_class(VALUE);
void rb_alias(VALUE, ID, ID);
void rb_attr(VALUE,ID,int,int,int);
int rb_method_boundp(VALUE, ID, int);
int rb_method_basic_definition_p(VALUE, ID);
int rb_obj_respond_to(VALUE, ID, int);
int rb_respond_to(VALUE, ID);
__attribute__((__noreturn__))
VALUE rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker);
void rb_backtrace(void);
VALUE rb_make_backtrace(void);




void rb_define_method(VALUE,const char*,VALUE(*)(),int);
void rb_define_module_function(VALUE,const char*,VALUE(*)(),int);
void rb_define_global_function(const char*,VALUE(*)(),int);
void rb_undef_method(VALUE,const char*);
void rb_define_alias(VALUE,const char*,const char*);
void rb_define_attr(VALUE,const char*,int,int);


__attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_m3(VALUE, const char *, VALUE(*)(), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_m2(VALUE, const char *, VALUE(*)(VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_m1(VALUE, const char *, VALUE(*)(int, union { VALUE *x; const VALUE *y; } __attribute__((__transparent_union__)), VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_00(VALUE, const char *, VALUE(*)(VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_01(VALUE, const char *, VALUE(*)(VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_02(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_03(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_04(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_05(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_06(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_07(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_08(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_09(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_10(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_11(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_12(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_13(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_14(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_singleton_method"))) static void rb_define_singleton_method_15(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int);
__attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_m3(VALUE, const char *, VALUE(*)(), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_m2(VALUE, const char *, VALUE(*)(VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_m1(VALUE, const char *, VALUE(*)(int, union { VALUE *x; const VALUE *y; } __attribute__((__transparent_union__)), VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_00(VALUE, const char *, VALUE(*)(VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_01(VALUE, const char *, VALUE(*)(VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_02(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_03(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_04(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_05(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_06(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_07(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_08(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_09(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_10(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_11(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_12(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_13(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_14(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_protected_method"))) static void rb_define_protected_method_15(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int);
__attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_m3(VALUE, const char *, VALUE(*)(), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_m2(VALUE, const char *, VALUE(*)(VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_m1(VALUE, const char *, VALUE(*)(int, union { VALUE *x; const VALUE *y; } __attribute__((__transparent_union__)), VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_00(VALUE, const char *, VALUE(*)(VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_01(VALUE, const char *, VALUE(*)(VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_02(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_03(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_04(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_05(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_06(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_07(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_08(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_09(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_10(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_11(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_12(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_13(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_14(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_private_method"))) static void rb_define_private_method_15(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int);
__attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_m3(VALUE, const char *, VALUE(*)(), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_m2(VALUE, const char *, VALUE(*)(VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_m1(VALUE, const char *, VALUE(*)(int, union { VALUE *x; const VALUE *y; } __attribute__((__transparent_union__)), VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_00(VALUE, const char *, VALUE(*)(VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_01(VALUE, const char *, VALUE(*)(VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_02(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_03(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_04(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_05(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_06(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_07(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_08(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_09(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_10(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_11(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_12(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_13(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_14(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_module_function"))) static void rb_define_module_function_15(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int);
__attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_m3(const char *, VALUE(*)(), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_m2(const char *, VALUE(*)(VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_m1(const char *, VALUE(*)(int, union { VALUE *x; const VALUE *y; } __attribute__((__transparent_union__)), VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_00(const char *, VALUE(*)(VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_01(const char *, VALUE(*)(VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_02(const char *, VALUE(*)(VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_03(const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_04(const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_05(const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_06(const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_07(const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_08(const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_09(const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_10(const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_11(const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_12(const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_13(const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_14(const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_global_function"))) static void rb_define_global_function_15(const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int);
__attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_m3(VALUE, ID, VALUE(*)(), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_m2(VALUE, ID, VALUE(*)(VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_m1(VALUE, ID, VALUE(*)(int, union { VALUE *x; const VALUE *y; } __attribute__((__transparent_union__)), VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_00(VALUE, ID, VALUE(*)(VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_01(VALUE, ID, VALUE(*)(VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_02(VALUE, ID, VALUE(*)(VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_03(VALUE, ID, VALUE(*)(VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_04(VALUE, ID, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_05(VALUE, ID, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_06(VALUE, ID, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_07(VALUE, ID, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_08(VALUE, ID, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_09(VALUE, ID, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_10(VALUE, ID, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_11(VALUE, ID, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_12(VALUE, ID, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_13(VALUE, ID, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_14(VALUE, ID, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method_id"))) static void rb_define_method_id_15(VALUE, ID, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int);
__attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_m3(VALUE, const char *, VALUE(*)(), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_m2(VALUE, const char *, VALUE(*)(VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_m1(VALUE, const char *, VALUE(*)(int, union { VALUE *x; const VALUE *y; } __attribute__((__transparent_union__)), VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_00(VALUE, const char *, VALUE(*)(VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_01(VALUE, const char *, VALUE(*)(VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_02(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_03(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_04(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_05(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_06(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_07(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_08(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_09(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_10(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_11(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_12(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_13(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_14(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int); __attribute__((__unused__)) __attribute__((__nonnull__ )) __attribute__((__weakref__("rb_define_method"))) static void rb_define_method_15(VALUE, const char *, VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE), int);


VALUE rb_int2big(intptr_t i);
VALUE rb_int2inum(intptr_t i);
VALUE rb_uint2big(uintptr_t i);
VALUE rb_uint2inum(uintptr_t i);


enum

ruby_special_consts {
    RUBY_Qfalse = 0x00,
    RUBY_Qtrue = 0x14,
    RUBY_Qnil = 0x08,
    RUBY_Qundef = 0x34,
    RUBY_IMMEDIATE_MASK = 0x07,
    RUBY_FIXNUM_FLAG = 0x01,
    RUBY_FLONUM_MASK = 0x03,
    RUBY_FLONUM_FLAG = 0x02,
    RUBY_SYMBOL_FLAG = 0x0c,
    RUBY_SPECIAL_SHIFT = 8
};
__attribute__((__const__))

__attribute__((__artificial__))
static inline _Bool
RB_TEST(VALUE obj)
{
    return obj & ~RUBY_Qnil;
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline _Bool
RB_NIL_P(VALUE obj)
{
    return obj == RUBY_Qnil;
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline _Bool
RB_FIXNUM_P(VALUE obj)
{
    return obj & RUBY_FIXNUM_FLAG;
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline _Bool
RB_STATIC_SYM_P(VALUE obj)
{
   
    const VALUE mask = ~((0x7fffffffffffffffL * 2UL + 1UL) << RUBY_SPECIAL_SHIFT);
    return (obj & mask) == RUBY_SYMBOL_FLAG;
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline _Bool
RB_FLONUM_P(VALUE obj)
{
    return (obj & RUBY_FLONUM_MASK) == RUBY_FLONUM_FLAG;
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline _Bool
RB_IMMEDIATE_P(VALUE obj)
{
    return obj & RUBY_IMMEDIATE_MASK;
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline _Bool
RB_SPECIAL_CONST_P(VALUE obj)
{
    return RB_IMMEDIATE_P(obj) || ! RB_TEST(obj);
}
__attribute__((__const__))

static inline VALUE
rb_special_const_p(VALUE obj)
{
    return RB_SPECIAL_CONST_P(obj) * RUBY_Qtrue;
}


__attribute__((__noreturn__))
__attribute__((__cold__))
void rb_out_of_int(long num);
long rb_num2long(VALUE num);
unsigned long rb_num2ulong(VALUE num);


__attribute__((__const__))

__attribute__((__artificial__))
static inline VALUE
RB_INT2FIX(long i)
{
    ((void)0);
    const unsigned long j = i;
    const unsigned long k = 2 * j + RUBY_FIXNUM_FLAG;
    const long l = k;
    const long m = l;
    const VALUE n = m;
    ((void)0);
    return n;
}
static inline int
rb_long2int_inline(long n)
{
    int i = ((int)n);
    if (sizeof(long) <= sizeof(int)) {
        ((__builtin_expect(!!(!!(i == n)), 1)) ? ((void)0) : __builtin_unreachable());
    }
    if (i != n)
        rb_out_of_int(n);
    return i;
}
__attribute__((__const__))

static inline long
rbimpl_fix2long_by_idiv(VALUE x)
{
    ((void)0);
    const long y = x - RUBY_FIXNUM_FLAG;
    const long z = y / 2;
    const long w = ((long)z);
    ((void)0);
    return w;
}
__attribute__((__const__))

static inline long
rbimpl_fix2long_by_shift(VALUE x)
{
    ((void)0);
    const long y = x;
    const long z = y >> 1;
    const long w = ((long)z);
    ((void)0);
    return w;
}
__attribute__((__const__))

static inline _Bool
rbimpl_right_shift_is_arithmetic_p(void)
{
    return (-1 >> 1) == -1;
}
__attribute__((__const__))

static inline long
rb_fix2long(VALUE x)
{
    if (rbimpl_right_shift_is_arithmetic_p()) {
        return rbimpl_fix2long_by_shift(x);
    }
    else {
        return rbimpl_fix2long_by_idiv(x);
    }
}
__attribute__((__const__))

static inline unsigned long
rb_fix2ulong(VALUE x)
{
    ((void)0);
    return rb_fix2long(x);
}
static inline long
rb_num2long_inline(VALUE x)
{
    if (RB_FIXNUM_P(x))
        return rb_fix2long(x);
    else
        return rb_num2long(x);
}
static inline unsigned long
rb_num2ulong_inline(VALUE x)
{
    if (RB_FIXNUM_P(x))
        return rb_fix2ulong(x);
    else
        return rb_num2ulong(x);
}
static inline VALUE
rb_long2num_inline(long v)
{
    if ((((v) < (0x7fffffffffffffffL / 2) + 1) && ((v) >= ((-0x7fffffffffffffffL - 1L) / 2))))
        return RB_INT2FIX(v);
    else
        return rb_int2big(v);
}
static inline VALUE
rb_ulong2num_inline(unsigned long v)
{
    if (((v) < (0x7fffffffffffffffL / 2) + 1))
        return RB_INT2FIX(v);
    else
        return rb_uint2big(v);
}


long rb_num2int(VALUE);
long rb_fix2int(VALUE);
unsigned long rb_num2uint(VALUE);
unsigned long rb_fix2uint(VALUE);


__attribute__((__artificial__))
static inline int
RB_FIX2INT(VALUE x)
{
    long ret;
    if (sizeof(int) < sizeof(long)) {
        ret = rb_fix2int(x);
    }
    else {
        ret = rb_fix2long(x);
    }
    return ((int)ret);
}
static inline int
rb_num2int_inline(VALUE x)
{
    long ret;
    if (sizeof(int) == sizeof(long)) {
        ret = rb_num2long_inline(x);
    }
    else if (RB_FIXNUM_P(x)) {
        ret = rb_fix2int(x);
    }
    else {
        ret = rb_num2int(x);
    }
    return ((int)ret);
}
__attribute__((__artificial__))
static inline unsigned int
RB_NUM2UINT(VALUE x)
{
    unsigned long ret;
    if (sizeof(int) < sizeof(long)) {
        ret = rb_num2uint(x);
    }
    else {
        ret = rb_num2ulong_inline(x);
    }
    return ((unsigned int)ret);
}
__attribute__((__artificial__))
static inline unsigned int
RB_FIX2UINT(VALUE x)
{
    unsigned long ret;
    if (sizeof(int) < sizeof(long)) {
        ret = rb_fix2uint(x);
    }
    else {
        ret = rb_fix2ulong(x);
    }
    return ((unsigned int)ret);
}




static inline VALUE
rb_int2num_inline(int v)
{
    if ((((v) < (0x7fffffffffffffffL / 2) + 1) && ((v) >= ((-0x7fffffffffffffffL - 1L) / 2))))
        return RB_INT2FIX(v);
    else
        return rb_int2big(v);
}
static inline VALUE
rb_uint2num_inline(unsigned int v)
{
    if (((v) < (0x7fffffffffffffffL / 2) + 1))
        return RB_INT2FIX(v);
    else
        return rb_uint2big(v);
}


enum ruby_rvalue_flags { RVALUE_EMBED_LEN_MAX = 3 };
struct
__attribute__((__aligned__(8)))
RBasic {
    VALUE flags;
    const VALUE klass;
};


VALUE rb_obj_hide(VALUE obj);
VALUE rb_obj_reveal(VALUE obj, VALUE klass);


__attribute__((__pure__))
__attribute__((__artificial__))
static inline VALUE
RBASIC_CLASS(VALUE obj)
{
    ((void)0);
    return ((struct RBasic *)(obj))->klass;
}
enum

ruby_value_type {
    RUBY_T_NONE = 0x00,
    RUBY_T_OBJECT = 0x01,
    RUBY_T_CLASS = 0x02,
    RUBY_T_MODULE = 0x03,
    RUBY_T_FLOAT = 0x04,
    RUBY_T_STRING = 0x05,
    RUBY_T_REGEXP = 0x06,
    RUBY_T_ARRAY = 0x07,
    RUBY_T_HASH = 0x08,
    RUBY_T_STRUCT = 0x09,
    RUBY_T_BIGNUM = 0x0a,
    RUBY_T_FILE = 0x0b,
    RUBY_T_DATA = 0x0c,
    RUBY_T_MATCH = 0x0d,
    RUBY_T_COMPLEX = 0x0e,
    RUBY_T_RATIONAL = 0x0f,
    RUBY_T_NIL = 0x11,
    RUBY_T_TRUE = 0x12,
    RUBY_T_FALSE = 0x13,
    RUBY_T_SYMBOL = 0x14,
    RUBY_T_FIXNUM = 0x15,
    RUBY_T_UNDEF = 0x16,
    RUBY_T_IMEMO = 0x1a,
    RUBY_T_NODE = 0x1b,
    RUBY_T_ICLASS = 0x1c,
    RUBY_T_ZOMBIE = 0x1d,
    RUBY_T_MOVED = 0x1e,
    RUBY_T_MASK = 0x1f
};


__attribute__((__cold__))
void rb_check_type(VALUE obj, int t);


__attribute__((__pure__))
__attribute__((__artificial__))
static inline enum ruby_value_type
RB_BUILTIN_TYPE(VALUE obj)
{
    ((void)0);
    VALUE ret = ((struct RBasic *)(obj))->flags & RUBY_T_MASK;
    return ((enum ruby_value_type)ret);
}
__attribute__((__pure__))
static inline _Bool
rb_integer_type_p(VALUE obj)
{
    if (RB_FIXNUM_P(obj)) {
        return 1;
    }
    else if (RB_SPECIAL_CONST_P(obj)) {
        return 0;
    }
    else {
        return RB_BUILTIN_TYPE(obj) == RUBY_T_BIGNUM;
    }
}
__attribute__((__pure__))
static inline enum ruby_value_type
rb_type(VALUE obj)
{
    if (! RB_SPECIAL_CONST_P(obj)) {
        return RB_BUILTIN_TYPE(obj);
    }
    else if (obj == ((VALUE)RUBY_Qfalse)) {
        return RUBY_T_FALSE;
    }
    else if (obj == ((VALUE)RUBY_Qnil)) {
        return RUBY_T_NIL;
    }
    else if (obj == ((VALUE)RUBY_Qtrue)) {
        return RUBY_T_TRUE;
    }
    else if (obj == ((VALUE)RUBY_Qundef)) {
        return RUBY_T_UNDEF;
    }
    else if (RB_FIXNUM_P(obj)) {
        return RUBY_T_FIXNUM;
    }
    else if (RB_STATIC_SYM_P(obj)) {
        return RUBY_T_SYMBOL;
    }
    else {
        ((__builtin_expect(!!(!!(RB_FLONUM_P(obj))), 1)) ? ((void)0) : __builtin_unreachable());
        return RUBY_T_FLOAT;
    }
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline _Bool
RB_FLOAT_TYPE_P(VALUE obj)
{
    if (RB_FLONUM_P(obj)) {
        return 1;
    }
    else if (RB_SPECIAL_CONST_P(obj)) {
        return 0;
    }
    else {
        return RB_BUILTIN_TYPE(obj) == RUBY_T_FLOAT;
    }
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline _Bool
RB_DYNAMIC_SYM_P(VALUE obj)
{
    if (RB_SPECIAL_CONST_P(obj)) {
        return 0;
    }
    else {
        return RB_BUILTIN_TYPE(obj) == RUBY_T_SYMBOL;
    }
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline _Bool
RB_SYMBOL_P(VALUE obj)
{
    return RB_STATIC_SYM_P(obj) || RB_DYNAMIC_SYM_P(obj);
}
__attribute__((__pure__))
__attribute__((__artificial__))
__attribute__((__always_inline__)) inline
static _Bool
rbimpl_RB_TYPE_P_fastpath(VALUE obj, enum ruby_value_type t)
{
    if (t == RUBY_T_TRUE) {
        return obj == ((VALUE)RUBY_Qtrue);
    }
    else if (t == RUBY_T_FALSE) {
        return obj == ((VALUE)RUBY_Qfalse);
    }
    else if (t == RUBY_T_NIL) {
        return obj == ((VALUE)RUBY_Qnil);
    }
    else if (t == RUBY_T_UNDEF) {
        return obj == ((VALUE)RUBY_Qundef);
    }
    else if (t == RUBY_T_FIXNUM) {
        return RB_FIXNUM_P(obj);
    }
    else if (t == RUBY_T_SYMBOL) {
        return RB_SYMBOL_P(obj);
    }
    else if (t == RUBY_T_FLOAT) {
        return RB_FLOAT_TYPE_P(obj);
    }
    else if (RB_SPECIAL_CONST_P(obj)) {
        return 0;
    }
    else if (t == RB_BUILTIN_TYPE(obj)) {
        return 1;
    }
    else {
        return 0;
    }
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline _Bool
RB_TYPE_P(VALUE obj, enum ruby_value_type t)
{
    if (__builtin_constant_p(t)) {
        return rbimpl_RB_TYPE_P_fastpath(obj, t);
    }
    else {
        return t == rb_type(obj);
    }
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline _Bool rbimpl_rtypeddata_p(VALUE obj);
__attribute__((__artificial__))
static inline void
Check_Type(VALUE v, enum ruby_value_type t)
{
    if ((__builtin_expect(!!(! RB_TYPE_P(v, t)), 0))) {
        goto slowpath;
    }
    else if (t != RUBY_T_DATA) {
        goto fastpath;
    }
    else if (rbimpl_rtypeddata_p(v)) {
        goto slowpath;
    }
    else {
        goto fastpath;
    }
  fastpath:
    return;
  slowpath:
    rb_check_type(v, t);
}
enum ruby_fl_ushift { RUBY_FL_USHIFT = 12 };
__extension__
enum

ruby_fl_type {
    RUBY_FL_WB_PROTECTED = (1<<5),
    RUBY_FL_PROMOTED0 = (1<<5),
    RUBY_FL_PROMOTED1 = (1<<6),
    RUBY_FL_PROMOTED = RUBY_FL_PROMOTED0 | RUBY_FL_PROMOTED1,
    RUBY_FL_FINALIZE = (1<<7),
    RUBY_FL_TAINT = (1<<8),
    RUBY_FL_SHAREABLE = (1<<8),
    RUBY_FL_UNTRUSTED = RUBY_FL_TAINT,
    RUBY_FL_SEEN_OBJ_ID = (1<<9),
    RUBY_FL_EXIVAR = (1<<10),
    RUBY_FL_FREEZE = (1<<11),
    RUBY_FL_USER0 = (1<<(RUBY_FL_USHIFT+0)),
    RUBY_FL_USER1 = (1<<(RUBY_FL_USHIFT+1)),
    RUBY_FL_USER2 = (1<<(RUBY_FL_USHIFT+2)),
    RUBY_FL_USER3 = (1<<(RUBY_FL_USHIFT+3)),
    RUBY_FL_USER4 = (1<<(RUBY_FL_USHIFT+4)),
    RUBY_FL_USER5 = (1<<(RUBY_FL_USHIFT+5)),
    RUBY_FL_USER6 = (1<<(RUBY_FL_USHIFT+6)),
    RUBY_FL_USER7 = (1<<(RUBY_FL_USHIFT+7)),
    RUBY_FL_USER8 = (1<<(RUBY_FL_USHIFT+8)),
    RUBY_FL_USER9 = (1<<(RUBY_FL_USHIFT+9)),
    RUBY_FL_USER10 = (1<<(RUBY_FL_USHIFT+10)),
    RUBY_FL_USER11 = (1<<(RUBY_FL_USHIFT+11)),
    RUBY_FL_USER12 = (1<<(RUBY_FL_USHIFT+12)),
    RUBY_FL_USER13 = (1<<(RUBY_FL_USHIFT+13)),
    RUBY_FL_USER14 = (1<<(RUBY_FL_USHIFT+14)),
    RUBY_FL_USER15 = (1<<(RUBY_FL_USHIFT+15)),
    RUBY_FL_USER16 = (1<<(RUBY_FL_USHIFT+16)),
    RUBY_FL_USER17 = (1<<(RUBY_FL_USHIFT+17)),
    RUBY_FL_USER18 = (1<<(RUBY_FL_USHIFT+18)),
    RUBY_FL_USER19 = (1<<(RUBY_FL_USHIFT+19)),
    RUBY_ELTS_SHARED = RUBY_FL_USER2,
    RUBY_FL_SINGLETON = RUBY_FL_USER0,
};
enum { RUBY_FL_DUPPED = RUBY_T_MASK | RUBY_FL_EXIVAR | RUBY_FL_TAINT };


void rb_obj_infect(VALUE victim, VALUE carrier);
void rb_freeze_singleton_class(VALUE klass);


__attribute__((__pure__))
__attribute__((__artificial__))
__attribute__((__always_inline__)) inline
static _Bool
RB_FL_ABLE(VALUE obj)
{
    if (RB_SPECIAL_CONST_P(obj)) {
        return 0;
    }
    else if (RB_TYPE_P(obj, RUBY_T_NODE)) {
        return 0;
    }
    else {
        return 1;
    }
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline VALUE
RB_FL_TEST_RAW(VALUE obj, VALUE flags)
{
    ((void)0);
    return ((struct RBasic *)(obj))->flags & flags;
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline VALUE
RB_FL_TEST(VALUE obj, VALUE flags)
{
    if (RB_FL_ABLE(obj)) {
        return RB_FL_TEST_RAW(obj, flags);
    }
    else {
        return 0UL;
    }
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline _Bool
RB_FL_ANY_RAW(VALUE obj, VALUE flags)
{
    return RB_FL_TEST_RAW(obj, flags);
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline _Bool
RB_FL_ANY(VALUE obj, VALUE flags)
{
    return RB_FL_TEST(obj, flags);
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline _Bool
RB_FL_ALL_RAW(VALUE obj, VALUE flags)
{
    return RB_FL_TEST_RAW(obj, flags) == flags;
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline _Bool
RB_FL_ALL(VALUE obj, VALUE flags)
{
    return RB_FL_TEST(obj, flags) == flags;
}

__attribute__((__artificial__))
static inline void
rbimpl_fl_set_raw_raw(struct RBasic *obj, VALUE flags)
{
    obj->flags |= flags;
}
__attribute__((__artificial__))
static inline void
RB_FL_SET_RAW(VALUE obj, VALUE flags)
{
    ((void)0);
    rbimpl_fl_set_raw_raw(((struct RBasic *)(obj)), flags);
}
__attribute__((__artificial__))
static inline void
RB_FL_SET(VALUE obj, VALUE flags)
{
    if (RB_FL_ABLE(obj)) {
        RB_FL_SET_RAW(obj, flags);
    }
}

__attribute__((__artificial__))
static inline void
rbimpl_fl_unset_raw_raw(struct RBasic *obj, VALUE flags)
{
    obj->flags &= ~flags;
}
__attribute__((__artificial__))
static inline void
RB_FL_UNSET_RAW(VALUE obj, VALUE flags)
{
    ((void)0);
    rbimpl_fl_unset_raw_raw(((struct RBasic *)(obj)), flags);
}
__attribute__((__artificial__))
static inline void
RB_FL_UNSET(VALUE obj, VALUE flags)
{
    if (RB_FL_ABLE(obj)) {
        RB_FL_UNSET_RAW(obj, flags);
    }
}

__attribute__((__artificial__))
static inline void
rbimpl_fl_reverse_raw_raw(struct RBasic *obj, VALUE flags)
{
    obj->flags ^= flags;
}
__attribute__((__artificial__))
static inline void
RB_FL_REVERSE_RAW(VALUE obj, VALUE flags)
{
    ((void)0);
    rbimpl_fl_reverse_raw_raw(((struct RBasic *)(obj)), flags);
}
__attribute__((__artificial__))
static inline void
RB_FL_REVERSE(VALUE obj, VALUE flags)
{
    if (RB_FL_ABLE(obj)) {
        RB_FL_REVERSE_RAW(obj, flags);
    }
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline _Bool
RB_OBJ_TAINTABLE(VALUE obj)
{
    if (! RB_FL_ABLE(obj)) {
        return 0;
    }
    else if (RB_TYPE_P(obj, RUBY_T_BIGNUM)) {
        return 0;
    }
    else if (RB_TYPE_P(obj, RUBY_T_FLOAT)) {
        return 0;
    }
    else {
        return 1;
    }
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline VALUE
RB_OBJ_TAINTED_RAW(VALUE obj)
{
    return RB_FL_TEST_RAW(obj, RUBY_FL_TAINT);
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline _Bool
RB_OBJ_TAINTED(VALUE obj)
{
    return RB_FL_ANY(obj, RUBY_FL_TAINT);
}
__attribute__((__artificial__))
static inline void
RB_OBJ_TAINT_RAW(VALUE obj)
{
    RB_FL_SET_RAW(obj, RUBY_FL_TAINT);
}
__attribute__((__artificial__))
static inline void
RB_OBJ_TAINT(VALUE obj)
{
    if (RB_OBJ_TAINTABLE(obj)) {
        RB_OBJ_TAINT_RAW(obj);
    }
}
__attribute__((__artificial__))
static inline void
RB_OBJ_INFECT_RAW(VALUE dst, VALUE src)
{
    ((void)0);
    ((void)0);
    RB_FL_SET_RAW(dst, RB_OBJ_TAINTED_RAW(src));
}
__attribute__((__artificial__))
static inline void
RB_OBJ_INFECT(VALUE dst, VALUE src)
{
    if (RB_OBJ_TAINTABLE(dst) && RB_FL_ABLE(src)) {
        RB_OBJ_INFECT_RAW(dst, src);
    }
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline VALUE
RB_OBJ_FROZEN_RAW(VALUE obj)
{
    return RB_FL_TEST_RAW(obj, RUBY_FL_FREEZE);
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline _Bool
RB_OBJ_FROZEN(VALUE obj)
{
    if (! RB_FL_ABLE(obj)) {
        return 1;
    }
    else {
        return RB_OBJ_FROZEN_RAW(obj);
    }
}
__attribute__((__artificial__))
static inline void
RB_OBJ_FREEZE_RAW(VALUE obj)
{
    RB_FL_SET_RAW(obj, RUBY_FL_FREEZE);
}
static inline void
rb_obj_freeze_inline(VALUE x)
{
    if (RB_FL_ABLE(x)) {
        RB_OBJ_FREEZE_RAW(x);
        if (RBASIC_CLASS(x) && !(((struct RBasic *)(x))->flags & RUBY_FL_SINGLETON)) {
            rb_freeze_singleton_class(x);
        }
    }
}
enum ruby_rstring_flags {
    RSTRING_NOEMBED = RUBY_FL_USER1,
    RSTRING_EMBED_LEN_MASK = RUBY_FL_USER2 | RUBY_FL_USER3 | RUBY_FL_USER4 |
                              RUBY_FL_USER5 | RUBY_FL_USER6,
    RSTRING_FSTR = RUBY_FL_USER17
};
enum ruby_rstring_consts {
    RSTRING_EMBED_LEN_SHIFT = RUBY_FL_USHIFT + 2,
    RSTRING_EMBED_LEN_MAX = ((int)(sizeof(VALUE[RVALUE_EMBED_LEN_MAX]) / (sizeof(char)))) - 1
};
struct RString {
    struct RBasic basic;
    union {
        struct {
            long len;
            char *ptr;
            union {
                long capa;
                VALUE shared;
            } aux;
        } heap;
        char ary[RSTRING_EMBED_LEN_MAX + 1];
    } as;
};


VALUE rb_str_to_str(VALUE);
VALUE rb_string_value(volatile VALUE*);
char *rb_string_value_ptr(volatile VALUE*);
char *rb_string_value_cstr(volatile VALUE*);
VALUE rb_str_export(VALUE);
VALUE rb_str_export_locale(VALUE);
__attribute__((__error__ ("rb_check_safe_str() and Check_SafeStr() are obsolete; use StringValue() instead")))
void rb_check_safe_str(VALUE);


__attribute__((__pure__))
__attribute__((__artificial__))
static inline long
RSTRING_EMBED_LEN(VALUE str)
{
    ((void)0);
    ((void)0);
    VALUE f = ((struct RBasic *)(str))->flags;
    f &= RSTRING_EMBED_LEN_MASK;
    f >>= RSTRING_EMBED_LEN_SHIFT;
    return ((long)f);
}


__attribute__((__pure__))
__attribute__((__artificial__))
static inline struct RString
rbimpl_rstring_getmem(VALUE str)
{
    ((void)0);
    if (RB_FL_ANY_RAW(str, RSTRING_NOEMBED)) {
        return *((struct RString *)(str));
    }
    else {
        struct RString retval;
        retval.as.heap.len = RSTRING_EMBED_LEN(str);
        retval.as.heap.ptr = ((struct RString *)(str))->as.ary;
        return retval;
    }
}


__attribute__((__pure__))
__attribute__((__artificial__))
static inline long
RSTRING_LEN(VALUE str)
{
    return rbimpl_rstring_getmem(str).as.heap.len;
}
__attribute__((__artificial__))
static inline char *
RSTRING_PTR(VALUE str)
{
    char *ptr = rbimpl_rstring_getmem(str).as.heap.ptr;
    if ((__builtin_expect(!!(! ptr), 0))) {
        fprintf(stderr, "%s\n",
            "RSTRING_PTR is returning NULL!! "
            "SIGSEGV is highly expected to follow immediately. "
            "If you could reproduce, attach your debugger here, "
            "and look at the passed string."
        );
    }
    return ptr;
}
__attribute__((__artificial__))
static inline char *
RSTRING_END(VALUE str)
{
    struct RString buf = rbimpl_rstring_getmem(str);
    if ((__builtin_expect(!!(! buf.as.heap.ptr), 0))) {
        fprintf(stderr, "%s\n",
            "RSTRING_END is returning NULL!! "
            "SIGSEGV is highly expected to follow immediately. "
            "If you could reproduce, attach your debugger here, "
            "and look at the passed string."
        );
    }
    return &buf.as.heap.ptr[buf.as.heap.len];
}
__attribute__((__artificial__))
static inline int
RSTRING_LENINT(VALUE str)
{
    return rb_long2int_inline(RSTRING_LEN(str));
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline VALUE
RB_CHR2FIX(unsigned char c)
{
    return RB_INT2FIX(c);
}
static inline char
rb_num2char_inline(VALUE x)
{
    if (RB_TYPE_P(x, RUBY_T_STRING) && (RSTRING_LEN(x)>=1))
        return RSTRING_PTR(x)[0];
    else
        return ((char)rb_num2int_inline(x));
}


double rb_num2dbl(VALUE);
__attribute__((__pure__))
double rb_float_value(VALUE);
VALUE rb_float_new(double);
VALUE rb_float_new_in_heap(double);




VALUE rb_ll2inum(long long);
VALUE rb_ull2inum(unsigned long long);
long long rb_num2ll(VALUE);
unsigned long long rb_num2ull(VALUE);


static inline long long
rb_num2ll_inline(VALUE x)
{
    if (RB_FIXNUM_P(x))
        return rb_fix2long(x);
    else
        return rb_num2ll(x);
}


short rb_num2short(VALUE);
unsigned short rb_num2ushort(VALUE);
short rb_fix2short(VALUE);
unsigned short rb_fix2ushort(VALUE);


static inline short
rb_num2short_inline(VALUE x)
{
    if (RB_FIXNUM_P(x))
        return rb_fix2short(x);
    else
        return rb_num2short(x);
}


typedef unsigned long st_data_t;
typedef struct st_table st_table;
typedef st_data_t st_index_t;
typedef int st_compare_func(st_data_t, st_data_t);
typedef st_index_t st_hash_func(st_data_t);
typedef char st_check_for_sizeof_st_index_t[8 == (int)sizeof(st_index_t) ? 1 : -1];
struct st_hash_type {
    int (*compare)(st_data_t, st_data_t);
    st_index_t (*hash)(st_data_t);
};
typedef struct st_table_entry st_table_entry;
struct st_table_entry;
struct st_table {
    unsigned char entry_power, bin_power, size_ind;
    unsigned int rebuilds_num;
    const struct st_hash_type *type;
    st_index_t num_entries;
    st_index_t *bins;
    st_index_t entries_start, entries_bound;
    st_table_entry *entries;
};
enum st_retval {ST_CONTINUE, ST_STOP, ST_DELETE, ST_CHECK, ST_REPLACE};
st_table *rb_st_init_table(const struct st_hash_type *);
st_table *rb_st_init_table_with_size(const struct st_hash_type *, st_index_t);
st_table *rb_st_init_numtable(void);
st_table *rb_st_init_numtable_with_size(st_index_t);
st_table *rb_st_init_strtable(void);
st_table *rb_st_init_strtable_with_size(st_index_t);
st_table *rb_st_init_strcasetable(void);
st_table *rb_st_init_strcasetable_with_size(st_index_t);
int rb_st_delete(st_table *, st_data_t *, st_data_t *);
int rb_st_delete_safe(st_table *, st_data_t *, st_data_t *, st_data_t);
int rb_st_shift(st_table *, st_data_t *, st_data_t *);
int rb_st_insert(st_table *, st_data_t, st_data_t);
int rb_st_insert2(st_table *, st_data_t, st_data_t, st_data_t (*)(st_data_t));
int rb_st_lookup(st_table *, st_data_t, st_data_t *);
int rb_st_get_key(st_table *, st_data_t, st_data_t *);
typedef int st_update_callback_func(st_data_t *key, st_data_t *value, st_data_t arg, int existing);
int rb_st_update(st_table *table, st_data_t key, st_update_callback_func *func, st_data_t arg);
typedef int st_foreach_callback_func(st_data_t, st_data_t, st_data_t);
typedef int st_foreach_check_callback_func(st_data_t, st_data_t, st_data_t, int);
int rb_st_foreach_with_replace(st_table *tab, st_foreach_check_callback_func *func, st_update_callback_func *replace, st_data_t arg);
int rb_st_foreach(st_table *, st_foreach_callback_func *, st_data_t);
int rb_st_foreach_check(st_table *, st_foreach_check_callback_func *, st_data_t, st_data_t);
st_index_t rb_st_keys(st_table *table, st_data_t *keys, st_index_t size);
st_index_t rb_st_keys_check(st_table *table, st_data_t *keys, st_index_t size, st_data_t never);
st_index_t rb_st_values(st_table *table, st_data_t *values, st_index_t size);
st_index_t rb_st_values_check(st_table *table, st_data_t *values, st_index_t size, st_data_t never);
void rb_st_add_direct(st_table *, st_data_t, st_data_t);
void rb_st_free_table(st_table *);
void rb_st_cleanup_safe(st_table *, st_data_t);
void rb_st_clear(st_table *);
st_table *rb_st_copy(st_table *);
__attribute__((__const__)) int rb_st_numcmp(st_data_t, st_data_t);
__attribute__((__const__)) st_index_t rb_st_numhash(st_data_t);
__attribute__((__pure__)) int rb_st_locale_insensitive_strcasecmp(const char *s1, const char *s2);
__attribute__((__pure__)) int rb_st_locale_insensitive_strncasecmp(const char *s1, const char *s2, size_t n);
__attribute__((__pure__)) size_t rb_st_memsize(const st_table *);
__attribute__((__pure__)) st_index_t rb_st_hash(const void *ptr, size_t len, st_index_t h);
__attribute__((__const__)) st_index_t rb_st_hash_uint32(st_index_t h, uint32_t i);
__attribute__((__const__)) st_index_t rb_st_hash_uint(st_index_t h, st_index_t i);
__attribute__((__const__)) st_index_t rb_st_hash_end(st_index_t h);
__attribute__((__const__)) st_index_t rb_st_hash_start(st_index_t h);
void rb_hash_bulk_insert_into_st_table(long, const VALUE *, VALUE);


__attribute__((__const__))

__attribute__((__artificial__))
static inline VALUE
RB_ST2FIX(st_data_t i)
{
    long x = i;
    if (x >= 0) {
        x &= (0x7fffffffffffffffL / 2);
    }
    else {
        x |= ((-0x7fffffffffffffffL - 1L) / 2);
    }
    ((void)0);
    unsigned long y = ((unsigned long)x);
    return RB_INT2FIX(y);
}


void rb_gc_writebarrier(VALUE a, VALUE b);
void rb_gc_writebarrier_unprotect(VALUE obj);


__attribute__((__pure__))
__attribute__((__artificial__))
static inline _Bool
RB_OBJ_PROMOTED_RAW(VALUE obj)
{
    ((void)0);
    return RB_FL_ANY_RAW(obj, RUBY_FL_PROMOTED);
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline _Bool
RB_OBJ_PROMOTED(VALUE obj)
{
    if (! RB_FL_ABLE(obj)) {
        return 0;
    }
    else {
        return RB_OBJ_PROMOTED_RAW(obj);
    }
}
static inline VALUE
rb_obj_wb_unprotect(VALUE x, const char *filename __attribute__((__unused__)), int line __attribute__((__unused__)))
{
    rb_gc_writebarrier_unprotect(x);
    return x;
}
static inline VALUE
rb_obj_written(VALUE a, VALUE oldv __attribute__((__unused__)), VALUE b, const char *filename __attribute__((__unused__)), int line __attribute__((__unused__)))
{
    if (!RB_SPECIAL_CONST_P(b)) {
        rb_gc_writebarrier(a, b);
    }
    return a;
}
static inline VALUE
rb_obj_write(VALUE a, VALUE *slot, VALUE b, const char *filename __attribute__((__unused__)), int line __attribute__((__unused__)))
{
    *slot = b;
    rb_obj_written(a, ((VALUE)RUBY_Qundef) , b, filename, line);
    return a;
}
enum ruby_rarray_flags {
    RARRAY_EMBED_FLAG = RUBY_FL_USER1,
    RARRAY_EMBED_LEN_MASK = RUBY_FL_USER4 | RUBY_FL_USER3
    ,
    RARRAY_TRANSIENT_FLAG = RUBY_FL_USER13
};
enum ruby_rarray_consts {
    RARRAY_EMBED_LEN_SHIFT = RUBY_FL_USHIFT + 3,
    RARRAY_EMBED_LEN_MAX = ((int)(sizeof(VALUE[RVALUE_EMBED_LEN_MAX]) / (sizeof(VALUE))))
};
struct RArray {
    struct RBasic basic;
    union {
        struct {
            long len;
            union {
                long capa;
                const
                VALUE shared_root;
            } aux;
            const VALUE *ptr;
        } heap;
        const VALUE ary[RARRAY_EMBED_LEN_MAX];
    } as;
};


VALUE *rb_ary_ptr_use_start(VALUE ary);
void rb_ary_ptr_use_end(VALUE a);
void rb_ary_detransient(VALUE a);


__attribute__((__pure__))
__attribute__((__artificial__))
static inline long
RARRAY_EMBED_LEN(VALUE ary)
{
    ((void)0);
    ((void)0);
    VALUE f = ((struct RBasic *)(ary))->flags;
    f &= RARRAY_EMBED_LEN_MASK;
    f >>= RARRAY_EMBED_LEN_SHIFT;
    return ((long)f);
}
__attribute__((__pure__))
static inline long
rb_array_len(VALUE a)
{
    ((void)0);
    if (RB_FL_ANY_RAW(a, RARRAY_EMBED_FLAG)) {
        return RARRAY_EMBED_LEN(a);
    }
    else {
        return ((struct RArray *)(a))->as.heap.len;
    }
}
__attribute__((__artificial__))
static inline int
RARRAY_LENINT(VALUE ary)
{
    return rb_long2int_inline(rb_array_len(ary));
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline _Bool
RARRAY_TRANSIENT_P(VALUE ary)
{
    ((void)0);
    return RB_FL_ANY_RAW(ary, RARRAY_TRANSIENT_FLAG);
}
__attribute__((__pure__))
static inline const VALUE *
rb_array_const_ptr_transient(VALUE a)
{
    ((void)0);
    if (RB_FL_ANY_RAW(a, RARRAY_EMBED_FLAG)) {
        return (((struct RArray *)(a))->as.ary);
    }
    else {
        return (((struct RArray *)(a))->as.heap.ptr);
    }
}
static inline const VALUE *
rb_array_const_ptr(VALUE a)
{
    ((void)0);
    if (RARRAY_TRANSIENT_P(a)) {
        rb_ary_detransient(a);
    }
    return rb_array_const_ptr_transient(a);
}
static inline VALUE *
rb_array_ptr_use_start(VALUE a,
                       __attribute__((__unused__))
                       int allow_transient)
{
    ((void)0);
    if (!allow_transient) {
        if (RARRAY_TRANSIENT_P(a)) {
            rb_ary_detransient(a);
        }
    }
    return rb_ary_ptr_use_start(a);
}
static inline void
rb_array_ptr_use_end(VALUE a,
                     __attribute__((__unused__))
                     int allow_transient)
{
    ((void)0);
    rb_ary_ptr_use_end(a);
}
static inline VALUE *
RARRAY_PTR(VALUE ary)
{
    ((void)0);
    VALUE tmp = (1 ? rb_obj_wb_unprotect(ary, "./include/ruby/internal/core/rarray.h", 248) : ary);
    return ((VALUE *)rb_array_const_ptr(tmp));
}
static inline void
RARRAY_ASET(VALUE ary, long i, VALUE v)
{
    do { ((void)0); const VALUE rbimpl_ary = (ary); VALUE *ptr = rb_array_ptr_use_start(rbimpl_ary, (1)); (rb_obj_write((VALUE)(ary), (VALUE *)(&ptr[i]), (VALUE)(v), "./include/ruby/internal/core/rarray.h", 256)); rb_array_ptr_use_end(rbimpl_ary, (1)); } while (0);
}


int rb_big_sign(VALUE num);


static inline _Bool
RBIGNUM_POSITIVE_P(VALUE b) {
    ((void)0);
    return rb_big_sign(b);
}
static inline _Bool
RBIGNUM_NEGATIVE_P(VALUE b) {
    ((void)0);
    return ! RBIGNUM_POSITIVE_P(b);
}
enum ruby_rmodule_flags {
    RMODULE_IS_OVERLAID = RUBY_FL_USER2,
    RMODULE_IS_REFINEMENT = RUBY_FL_USER3,
    RMODULE_INCLUDED_INTO_REFINEMENT = RUBY_FL_USER4
};
struct RClass;


VALUE rb_class_get_superclass(VALUE);


typedef void (*RUBY_DATA_FUNC)(void*);
struct RData {
    struct RBasic basic;
    RUBY_DATA_FUNC dmark;
    RUBY_DATA_FUNC dfree;
    void *data;
};


VALUE rb_data_object_wrap(VALUE klass, void *datap, RUBY_DATA_FUNC dmark, RUBY_DATA_FUNC dfree);
VALUE rb_data_object_zalloc(VALUE klass, size_t size, RUBY_DATA_FUNC dmark, RUBY_DATA_FUNC dfree);
extern VALUE rb_cObject;


__attribute__((__warning__ ("untyped Data is unsafe; use TypedData instead"))) __attribute__((__deprecated__ ("by TypedData")))
static inline VALUE
rb_data_object_wrap_warning(VALUE klass, void *ptr, RUBY_DATA_FUNC mark, RUBY_DATA_FUNC free)
{
    return rb_data_object_wrap(klass, ptr, mark, free);
}
static inline void *
rb_data_object_get(VALUE obj)
{
    Check_Type(obj, RUBY_T_DATA);
    return ((struct RData *)(obj))->data;
}
__attribute__((__warning__ ("untyped Data is unsafe; use TypedData instead"))) __attribute__((__deprecated__ ("by TypedData")))
static inline void *
rb_data_object_get_warning(VALUE obj)
{
    return rb_data_object_get(obj);
}
static inline VALUE
rb_data_object_make(VALUE klass, RUBY_DATA_FUNC mark_func, RUBY_DATA_FUNC free_func, void **datap, size_t size)
{
    VALUE result = rb_data_object_zalloc( (klass), (size), ((void (*)(void *))(mark_func)), ((void (*)(void *))(free_func))); (*datap) = ((void *)((struct RData *)(result))->data); ((void)(*datap));
    return result;
}
__attribute__((__deprecated__ ("by: rb_data_object_wrap")))
static inline VALUE
rb_data_object_alloc(VALUE klass, void *data, RUBY_DATA_FUNC dmark, RUBY_DATA_FUNC dfree)
{
    return rb_data_object_wrap(klass, data, dmark, dfree);
}
__attribute__((__deprecated__ ("by: rb_cObject.  Will be removed in 3.1.")))
__attribute__((__pure__))
static inline VALUE
rb_cData(void)
{
    return rb_cObject;
}
struct rb_io_t;
struct RFile {
    struct RBasic basic;
    struct rb_io_t *fptr;
};
struct st_table;


size_t rb_hash_size_num(VALUE hash);
struct st_table *rb_hash_tbl(VALUE, const char *file, int line);
VALUE rb_hash_set_ifnone(VALUE hash, VALUE ifnone);


enum ruby_robject_flags { ROBJECT_EMBED = RUBY_FL_USER1 };
enum ruby_robject_consts { ROBJECT_EMBED_LEN_MAX = ((int)(sizeof(VALUE[RVALUE_EMBED_LEN_MAX]) / (sizeof(VALUE)))) };
struct st_table;
struct RObject {
    struct RBasic basic;
    union {
        struct {
            uint32_t numiv;
            VALUE *ivptr;
            struct st_table *iv_index_tbl;
        } heap;
        VALUE ary[ROBJECT_EMBED_LEN_MAX];
    } as;
};
__attribute__((__pure__))
__attribute__((__artificial__))
static inline uint32_t
ROBJECT_NUMIV(VALUE obj)
{
    ((void)0);
    if (RB_FL_ANY_RAW(obj, ROBJECT_EMBED)) {
        return ROBJECT_EMBED_LEN_MAX;
    }
    else {
        return ((struct RObject *)(obj))->as.heap.numiv;
    }
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline VALUE *
ROBJECT_IVPTR(VALUE obj)
{
    ((void)0);
    struct RObject *const ptr = ((struct RObject *)(obj));
    if (RB_FL_ANY_RAW(obj, ROBJECT_EMBED)) {
        return ptr->as.ary;
    }
    else {
        return ptr->as.heap.ivptr;
    }
}
struct re_patter_buffer;
struct RRegexp {
    struct RBasic basic;
    struct re_pattern_buffer *ptr;
    const VALUE src;
    unsigned long usecnt;
};
__attribute__((__pure__))
__attribute__((__artificial__))
static inline VALUE
RREGEXP_SRC(VALUE rexp)
{
    ((void)0);
    VALUE ret = ((struct RRegexp *)(rexp))->src;
    ((void)0);
    return ret;
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline char *
RREGEXP_SRC_PTR(VALUE rexp)
{
    return RSTRING_PTR(RREGEXP_SRC(rexp));
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline long
RREGEXP_SRC_LEN(VALUE rexp)
{
    return RSTRING_LEN(RREGEXP_SRC(rexp));
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline char *
RREGEXP_SRC_END(VALUE rexp)
{
    return RSTRING_END(RREGEXP_SRC(rexp));
}


VALUE rb_struct_size(VALUE s);
VALUE rb_struct_aref(VALUE, VALUE);
VALUE rb_struct_aset(VALUE, VALUE, VALUE);


__attribute__((__artificial__))
static inline long
RSTRUCT_LEN(VALUE st)
{
    ((void)0);
    return rb_num2long_inline(rb_struct_size(st));
}
__attribute__((__artificial__))
static inline VALUE
RSTRUCT_SET(VALUE st, int k, VALUE v)
{
    ((void)0);
    return rb_struct_aset(st, rb_int2num_inline(k), (v));
}
__attribute__((__artificial__))
static inline VALUE
RSTRUCT_GET(VALUE st, int k)
{
    ((void)0);
    return rb_struct_aref(st, rb_int2num_inline(k));
}


VALUE rb_errinfo(void);
void rb_set_errinfo(VALUE);
typedef enum {
    RB_WARN_CATEGORY_NONE,
    RB_WARN_CATEGORY_DEPRECATED,
    RB_WARN_CATEGORY_EXPERIMENTAL,
    RB_WARN_CATEGORY_ALL_BITS = 0x6
} rb_warning_category_t;
enum rb_io_wait_readwrite {RB_IO_WAIT_READABLE, RB_IO_WAIT_WRITABLE};
__attribute__((__format__(__printf__, (2), (3)))) __attribute__((__noreturn__)) void rb_raise(VALUE, const char*, ...);
__attribute__((__format__(__printf__, (1), (2)))) __attribute__((__noreturn__)) void rb_fatal(const char*, ...);
__attribute__((__cold__)) __attribute__((__format__(__printf__, (1), (2)))) __attribute__((__noreturn__)) void rb_bug(const char*, ...);
__attribute__((__noreturn__)) void rb_bug_errno(const char*, int);
__attribute__((__noreturn__)) void rb_sys_fail(const char*);
__attribute__((__noreturn__)) void rb_sys_fail_str(VALUE);
__attribute__((__noreturn__)) void rb_mod_sys_fail(VALUE, const char*);
__attribute__((__noreturn__)) void rb_mod_sys_fail_str(VALUE, VALUE);
__attribute__((__noreturn__)) void rb_readwrite_sys_fail(enum rb_io_wait_readwrite, const char*);
__attribute__((__noreturn__)) void rb_iter_break(void);
__attribute__((__noreturn__)) void rb_iter_break_value(VALUE);
__attribute__((__noreturn__)) void rb_exit(int);
__attribute__((__noreturn__)) void rb_notimplement(void);
VALUE rb_syserr_new(int, const char *);
VALUE rb_syserr_new_str(int n, VALUE arg);
__attribute__((__noreturn__)) void rb_syserr_fail(int, const char*);
__attribute__((__noreturn__)) void rb_syserr_fail_str(int, VALUE);
__attribute__((__noreturn__)) void rb_mod_syserr_fail(VALUE, int, const char*);
__attribute__((__noreturn__)) void rb_mod_syserr_fail_str(VALUE, int, VALUE);
__attribute__((__noreturn__)) void rb_readwrite_syserr_fail(enum rb_io_wait_readwrite, int, const char*);
__attribute__((__noreturn__)) void rb_unexpected_type(VALUE,int);
VALUE *rb_ruby_verbose_ptr(void);
VALUE *rb_ruby_debug_ptr(void);
__attribute__((__format__(__printf__, (1), (2)))) void rb_warning(const char*, ...);
__attribute__((__format__(__printf__, (2), (3)))) void rb_category_warning(rb_warning_category_t, const char*, ...);
__attribute__((__format__(__printf__, (3), (4)))) void rb_compile_warning(const char *, int, const char*, ...);
__attribute__((__format__(__printf__, (4), (5)))) void rb_category_compile_warn(rb_warning_category_t, const char *, int, const char*, ...);
__attribute__((__format__(__printf__, (1), (2)))) void rb_sys_warning(const char*, ...);
__attribute__((__cold__)) __attribute__((__format__(__printf__, (1), (2)))) void rb_warn(const char*, ...);
__attribute__((__cold__)) __attribute__((__format__(__printf__, (2), (3)))) void rb_category_warn(rb_warning_category_t, const char*, ...);
__attribute__((__format__(__printf__, (3), (4)))) void rb_compile_warn(const char *, int, const char*, ...);


enum rbimpl_typeddata_flags {
    RUBY_TYPED_FREE_IMMEDIATELY = 1,
    RUBY_TYPED_FROZEN_SHAREABLE = RUBY_FL_SHAREABLE,
    RUBY_TYPED_WB_PROTECTED = RUBY_FL_WB_PROTECTED,
    RUBY_TYPED_PROMOTED1 = RUBY_FL_PROMOTED1
};
typedef struct rb_data_type_struct rb_data_type_t;
struct rb_data_type_struct {
    const char *wrap_struct_name;
    struct {
        RUBY_DATA_FUNC dmark;
        RUBY_DATA_FUNC dfree;
        size_t (*dsize)(const void *);
        RUBY_DATA_FUNC dcompact;
        void *reserved[1];
    } function;
    const rb_data_type_t *parent;
    void *data;
    VALUE flags;
};
struct RTypedData {
    struct RBasic basic;
    const rb_data_type_t *type;
    VALUE typed_flag;
    void *data;
};


VALUE rb_data_typed_object_wrap(VALUE klass, void *datap, const rb_data_type_t *);
VALUE rb_data_typed_object_zalloc(VALUE klass, size_t size, const rb_data_type_t *type);
int rb_typeddata_inherited_p(const rb_data_type_t *child, const rb_data_type_t *parent);
int rb_typeddata_is_kind_of(VALUE obj, const rb_data_type_t *data_type);
void *rb_check_typeddata(VALUE obj, const rb_data_type_t *data_type);


__attribute__((__pure__))
__attribute__((__artificial__))
static inline _Bool
rbimpl_rtypeddata_p(VALUE obj)
{
    return ((struct RTypedData *)(obj))->typed_flag == 1;
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline _Bool
RTYPEDDATA_P(VALUE obj)
{
    return rbimpl_rtypeddata_p(obj);
}
__attribute__((__pure__))
__attribute__((__artificial__))
static inline const struct rb_data_type_struct *
RTYPEDDATA_TYPE(VALUE obj)
{
    return ((struct RTypedData *)(obj))->type;
}
static inline VALUE
rb_data_typed_object_make(VALUE klass, const rb_data_type_t *type, void **datap, size_t size)
{
    VALUE result = rb_data_typed_object_zalloc(klass, size, type); (*datap) = ((void *)(((struct RTypedData *)(result))->data)); ((void)(*datap));
    return result;
}
__attribute__((__deprecated__ ("by: rb_data_typed_object_wrap")))
static inline VALUE
rb_data_typed_object_alloc(VALUE klass, void *datap, const rb_data_type_t *type)
{
    return rb_data_typed_object_wrap(klass, datap, type);
}

enum
{
  _ISupper = ((0) < 8 ? ((1 << (0)) << 8) : ((1 << (0)) >> 8)),
  _ISlower = ((1) < 8 ? ((1 << (1)) << 8) : ((1 << (1)) >> 8)),
  _ISalpha = ((2) < 8 ? ((1 << (2)) << 8) : ((1 << (2)) >> 8)),
  _ISdigit = ((3) < 8 ? ((1 << (3)) << 8) : ((1 << (3)) >> 8)),
  _ISxdigit = ((4) < 8 ? ((1 << (4)) << 8) : ((1 << (4)) >> 8)),
  _ISspace = ((5) < 8 ? ((1 << (5)) << 8) : ((1 << (5)) >> 8)),
  _ISprint = ((6) < 8 ? ((1 << (6)) << 8) : ((1 << (6)) >> 8)),
  _ISgraph = ((7) < 8 ? ((1 << (7)) << 8) : ((1 << (7)) >> 8)),
  _ISblank = ((8) < 8 ? ((1 << (8)) << 8) : ((1 << (8)) >> 8)),
  _IScntrl = ((9) < 8 ? ((1 << (9)) << 8) : ((1 << (9)) >> 8)),
  _ISpunct = ((10) < 8 ? ((1 << (10)) << 8) : ((1 << (10)) >> 8)),
  _ISalnum = ((11) < 8 ? ((1 << (11)) << 8) : ((1 << (11)) >> 8))
};
extern const unsigned short int **__ctype_b_loc (void)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern const __int32_t **__ctype_tolower_loc (void)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern const __int32_t **__ctype_toupper_loc (void)
     __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__const__));
extern int isalnum (int) __attribute__ ((__nothrow__ , __leaf__));
extern int isalpha (int) __attribute__ ((__nothrow__ , __leaf__));
extern int iscntrl (int) __attribute__ ((__nothrow__ , __leaf__));
extern int isdigit (int) __attribute__ ((__nothrow__ , __leaf__));
extern int islower (int) __attribute__ ((__nothrow__ , __leaf__));
extern int isgraph (int) __attribute__ ((__nothrow__ , __leaf__));
extern int isprint (int) __attribute__ ((__nothrow__ , __leaf__));
extern int ispunct (int) __attribute__ ((__nothrow__ , __leaf__));
extern int isspace (int) __attribute__ ((__nothrow__ , __leaf__));
extern int isupper (int) __attribute__ ((__nothrow__ , __leaf__));
extern int isxdigit (int) __attribute__ ((__nothrow__ , __leaf__));
extern int tolower (int __c) __attribute__ ((__nothrow__ , __leaf__));
extern int toupper (int __c) __attribute__ ((__nothrow__ , __leaf__));
extern int isblank (int) __attribute__ ((__nothrow__ , __leaf__));
extern int isctype (int __c, int __mask) __attribute__ ((__nothrow__ , __leaf__));
extern int isascii (int __c) __attribute__ ((__nothrow__ , __leaf__));
extern int toascii (int __c) __attribute__ ((__nothrow__ , __leaf__));
extern int _toupper (int) __attribute__ ((__nothrow__ , __leaf__));
extern int _tolower (int) __attribute__ ((__nothrow__ , __leaf__));
extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ , __leaf__)) tolower (int __c)
{
  return __c >= -128 && __c < 256 ? (*__ctype_tolower_loc ())[__c] : __c;
}
extern __inline __attribute__ ((__gnu_inline__)) int
__attribute__ ((__nothrow__ , __leaf__)) toupper (int __c)
{
  return __c >= -128 && __c < 256 ? (*__ctype_toupper_loc ())[__c] : __c;
}
extern int isalnum_l (int, locale_t) __attribute__ ((__nothrow__ , __leaf__));
extern int isalpha_l (int, locale_t) __attribute__ ((__nothrow__ , __leaf__));
extern int iscntrl_l (int, locale_t) __attribute__ ((__nothrow__ , __leaf__));
extern int isdigit_l (int, locale_t) __attribute__ ((__nothrow__ , __leaf__));
extern int islower_l (int, locale_t) __attribute__ ((__nothrow__ , __leaf__));
extern int isgraph_l (int, locale_t) __attribute__ ((__nothrow__ , __leaf__));
extern int isprint_l (int, locale_t) __attribute__ ((__nothrow__ , __leaf__));
extern int ispunct_l (int, locale_t) __attribute__ ((__nothrow__ , __leaf__));
extern int isspace_l (int, locale_t) __attribute__ ((__nothrow__ , __leaf__));
extern int isupper_l (int, locale_t) __attribute__ ((__nothrow__ , __leaf__));
extern int isxdigit_l (int, locale_t) __attribute__ ((__nothrow__ , __leaf__));
extern int isblank_l (int, locale_t) __attribute__ ((__nothrow__ , __leaf__));
extern int __tolower_l (int __c, locale_t __l) __attribute__ ((__nothrow__ , __leaf__));
extern int tolower_l (int __c, locale_t __l) __attribute__ ((__nothrow__ , __leaf__));
extern int __toupper_l (int __c, locale_t __l) __attribute__ ((__nothrow__ , __leaf__));
extern int toupper_l (int __c, locale_t __l) __attribute__ ((__nothrow__ , __leaf__));



int rb_st_locale_insensitive_strcasecmp(const char *s1, const char *s2);
int rb_st_locale_insensitive_strncasecmp(const char *s1, const char *s2, size_t n);
unsigned long ruby_strtoul(const char *str, char **endptr, int base);


__attribute__((__const__))

__attribute__((__artificial__))
static inline int
rb_isascii(int c)
{
    return '\0' <= c && c <= '\x7f';
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline int
rb_isupper(int c)
{
    return 'A' <= c && c <= 'Z';
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline int
rb_islower(int c)
{
    return 'a' <= c && c <= 'z';
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline int
rb_isalpha(int c)
{
    return rb_isupper(c) || rb_islower(c);
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline int
rb_isdigit(int c)
{
    return '0' <= c && c <= '9';
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline int
rb_isalnum(int c)
{
    return rb_isalpha(c) || rb_isdigit(c);
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline int
rb_isxdigit(int c)
{
    return rb_isdigit(c) || ('A' <= c && c <= 'F') || ('a' <= c && c <= 'f');
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline int
rb_isblank(int c)
{
    return c == ' ' || c == '\t';
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline int
rb_isspace(int c)
{
    return c == ' ' || ('\t' <= c && c <= '\r');
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline int
rb_iscntrl(int c)
{
    return ('\0' <= c && c < ' ') || c == '\x7f';
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline int
rb_isprint(int c)
{
    return ' ' <= c && c <= '\x7e';
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline int
rb_ispunct(int c)
{
    return !rb_isalnum(c);
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline int
rb_isgraph(int c)
{
    return '!' <= c && c <= '\x7e';
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline int
rb_tolower(int c)
{
    return rb_isupper(c) ? (c|0x20) : c;
}
__attribute__((__const__))

__attribute__((__artificial__))
static inline int
rb_toupper(int c)
{
    return rb_islower(c) ? (c&0x5f) : c;
}


VALUE rb_eval_string(const char*);
VALUE rb_eval_string_protect(const char*, int*);
VALUE rb_eval_string_wrap(const char*, int*);
VALUE rb_funcall(VALUE, ID, int, ...);
VALUE rb_funcallv(VALUE, ID, int, const VALUE*);
VALUE rb_funcallv_kw(VALUE, ID, int, const VALUE*, int);
VALUE rb_funcallv_public(VALUE, ID, int, const VALUE*);
VALUE rb_funcallv_public_kw(VALUE, ID, int, const VALUE*, int);
VALUE rb_funcall_passing_block(VALUE, ID, int, const VALUE*);
VALUE rb_funcall_passing_block_kw(VALUE, ID, int, const VALUE*, int);
VALUE rb_funcall_with_block(VALUE, ID, int, const VALUE*, VALUE);
VALUE rb_funcall_with_block_kw(VALUE, ID, int, const VALUE*, VALUE, int);
VALUE rb_call_super(int, const VALUE*);
VALUE rb_call_super_kw(int, const VALUE*, int);
VALUE rb_current_receiver(void);
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *);
VALUE rb_extract_keywords(VALUE *orighash);




typedef uint32_t rb_event_flag_t;
typedef void (*rb_event_hook_func_t)(rb_event_flag_t evflag, VALUE data, VALUE self, ID mid, VALUE klass);
void rb_add_event_hook(rb_event_hook_func_t func, rb_event_flag_t events, VALUE data);
int rb_remove_event_hook(rb_event_hook_func_t func);




void rb_gc_register_address(VALUE *valptr);
void rb_global_variable(VALUE *);
void rb_gc_unregister_address(VALUE *valptr);
void rb_gc_register_mark_object(VALUE object);




typedef int ruby_glob_func(const char*,VALUE, void*);
void rb_glob(const char*,void(*)(const char*,VALUE,void*),VALUE);
int ruby_glob(const char*,int,ruby_glob_func*,VALUE);
int ruby_brace_glob(const char*,int,ruby_glob_func*,VALUE);




extern VALUE rb_mKernel;
extern VALUE rb_mComparable;
extern VALUE rb_mEnumerable;
extern VALUE rb_mErrno;
extern VALUE rb_mFileTest;
extern VALUE rb_mGC;
extern VALUE rb_mMath;
extern VALUE rb_mProcess;
extern VALUE rb_mWaitReadable;
extern VALUE rb_mWaitWritable;
extern VALUE rb_cBasicObject;
extern VALUE rb_cObject;
extern VALUE rb_cArray;
extern VALUE rb_cBinding;
extern VALUE rb_cClass;
extern VALUE rb_cDir;
extern VALUE rb_cEncoding;
extern VALUE rb_cEnumerator;
extern VALUE rb_cFalseClass;
extern VALUE rb_cFile;
extern VALUE rb_cComplex;
extern VALUE rb_cFloat;
extern VALUE rb_cHash;
extern VALUE rb_cIO;
extern VALUE rb_cInteger;
extern VALUE rb_cMatch;
extern VALUE rb_cMethod;
extern VALUE rb_cModule;
extern VALUE rb_cNameErrorMesg;
extern VALUE rb_cNilClass;
extern VALUE rb_cNumeric;
extern VALUE rb_cProc;
extern VALUE rb_cRandom;
extern VALUE rb_cRange;
extern VALUE rb_cRational;
extern VALUE rb_cRegexp;
extern VALUE rb_cStat;
extern VALUE rb_cString;
extern VALUE rb_cStruct;
extern VALUE rb_cSymbol;
extern VALUE rb_cThread;
extern VALUE rb_cTime;
extern VALUE rb_cTrueClass;
extern VALUE rb_cUnboundMethod;
extern VALUE rb_eException;
extern VALUE rb_eStandardError;
extern VALUE rb_eSystemExit;
extern VALUE rb_eInterrupt;
extern VALUE rb_eSignal;
extern VALUE rb_eFatal;
extern VALUE rb_eArgError;
extern VALUE rb_eEOFError;
extern VALUE rb_eIndexError;
extern VALUE rb_eStopIteration;
extern VALUE rb_eKeyError;
extern VALUE rb_eRangeError;
extern VALUE rb_eIOError;
extern VALUE rb_eRuntimeError;
extern VALUE rb_eFrozenError;
extern VALUE rb_eSecurityError;
extern VALUE rb_eSystemCallError;
extern VALUE rb_eThreadError;
extern VALUE rb_eTypeError;
extern VALUE rb_eZeroDivError;
extern VALUE rb_eNotImpError;
extern VALUE rb_eNoMemError;
extern VALUE rb_eNoMethodError;
extern VALUE rb_eFloatDomainError;
extern VALUE rb_eLocalJumpError;
extern VALUE rb_eSysStackError;
extern VALUE rb_eRegexpError;
extern VALUE rb_eEncodingError;
extern VALUE rb_eEncCompatError;
extern VALUE rb_eNoMatchingPatternError;
extern VALUE rb_eScriptError;
extern VALUE rb_eNameError;
extern VALUE rb_eSyntaxError;
extern VALUE rb_eLoadError;
extern VALUE rb_eMathDomainError;
extern VALUE rb_stdin, rb_stdout, rb_stderr;
__attribute__((__pure__))
static inline VALUE
rb_class_of(VALUE obj)
{
    if (! RB_SPECIAL_CONST_P(obj)) {
        return RBASIC_CLASS(obj);
    }
    else if (obj == ((VALUE)RUBY_Qfalse)) {
        return rb_cFalseClass;
    }
    else if (obj == ((VALUE)RUBY_Qnil)) {
        return rb_cNilClass;
    }
    else if (obj == ((VALUE)RUBY_Qtrue)) {
        return rb_cTrueClass;
    }
    else if (RB_FIXNUM_P(obj)) {
        return rb_cInteger;
    }
    else if (RB_STATIC_SYM_P(obj)) {
        return rb_cSymbol;
    }
    else if (RB_FLONUM_P(obj)) {
        return rb_cFloat;
    }
    __builtin_unreachable();
}




void ruby_sysinit(int *argc, char ***argv);
void ruby_init(void);
void* ruby_options(int argc, char** argv);
int ruby_executable_node(void *n, int *status);
int ruby_run_node(void *n);
void ruby_show_version(void);
void ruby_show_copyright(void);
void ruby_init_stack(volatile VALUE*);
int ruby_setup(void);
int ruby_cleanup(volatile int);
void ruby_finalize(void);
__attribute__((__noreturn__))
void ruby_stop(int);
int ruby_stack_check(void);
size_t ruby_stack_length(VALUE**);
int ruby_exec_node(void *n);
void ruby_script(const char* name);
void ruby_set_script_name(VALUE name);
void ruby_prog_init(void);
void ruby_set_argv(int, char**);
void *ruby_process_options(int, char**);
void ruby_init_loadpath(void);
void ruby_incpush(const char*);
void ruby_sig_finalize(void);




typedef VALUE rb_block_call_func(VALUE yielded_arg, VALUE callback_arg, int argc, const VALUE *argv, VALUE blockarg);
typedef rb_block_call_func *rb_block_call_func_t;
VALUE rb_each(VALUE);
VALUE rb_yield(VALUE);
VALUE rb_yield_values(int n, ...);
VALUE rb_yield_values2(int n, const VALUE *argv);
VALUE rb_yield_values_kw(int n, const VALUE *argv, int kw_splat);
VALUE rb_yield_splat(VALUE);
VALUE rb_yield_splat_kw(VALUE, int);
VALUE rb_yield_block(VALUE yielded_arg, VALUE callback_arg, int argc, const VALUE *argv, VALUE blockarg);
int rb_keyword_given_p(void);
int rb_block_given_p(void);
void rb_need_block(void);
VALUE rb_iterate(VALUE(*)(VALUE),VALUE,rb_block_call_func_t,VALUE);
VALUE rb_block_call(VALUE,ID,int,const VALUE*,rb_block_call_func_t,VALUE);
VALUE rb_block_call_kw(VALUE,ID,int,const VALUE*,rb_block_call_func_t,VALUE,int);
VALUE rb_rescue(VALUE(*)(VALUE),VALUE,VALUE(*)(VALUE,VALUE),VALUE);
VALUE rb_rescue2(VALUE(*)(VALUE),VALUE,VALUE(*)(VALUE,VALUE),VALUE,...);
VALUE rb_vrescue2(VALUE(*)(VALUE),VALUE,VALUE(*)(VALUE,VALUE),VALUE,va_list);
VALUE rb_ensure(VALUE(*)(VALUE),VALUE,VALUE(*)(VALUE),VALUE);
VALUE rb_catch(const char*,rb_block_call_func_t,VALUE);
VALUE rb_catch_obj(VALUE,rb_block_call_func_t,VALUE);
__attribute__((__noreturn__))
void rb_throw(const char*,VALUE);
__attribute__((__noreturn__))
void rb_throw_obj(VALUE,VALUE);


struct rbimpl_size_mul_overflow_tag {
    _Bool left;
    size_t right;
};


__attribute__((__malloc__))
__attribute__((__returns_nonnull__))
__attribute__((__alloc_size__ (2)))
void *rb_alloc_tmp_buffer(volatile VALUE *store, long len);
__attribute__((__malloc__))
__attribute__((__returns_nonnull__))
__attribute__((__alloc_size__ (2,3)))
void *rb_alloc_tmp_buffer_with_count(volatile VALUE *store, size_t len,size_t count);
void rb_free_tmp_buffer(volatile VALUE *store);
__attribute__((__noreturn__))
void ruby_malloc_size_overflow(size_t, size_t);


static inline int
rb_mul_size_overflow(size_t a, size_t b, size_t max, size_t *c)
{
    __extension__ unsigned __int128 da, db, c2;
    da = a;
    db = b;
    c2 = da * db;
    if (c2 > max) return 1;
    *c = ((size_t)c2);
    return 0;
}

__attribute__((__const__))
static inline struct rbimpl_size_mul_overflow_tag
rbimpl_size_mul_overflow(size_t x, size_t y)
{
    struct rbimpl_size_mul_overflow_tag ret = { 0, 0, };
    ret.left = __builtin_mul_overflow(x, y, &ret.right);
    return ret;
}
static inline size_t
rbimpl_size_mul_or_raise(size_t x, size_t y)
{
    struct rbimpl_size_mul_overflow_tag size =
        rbimpl_size_mul_overflow(x, y);
    if ((__builtin_expect(!!(! size.left), 1))) {
        return size.right;
    }
    else {
        ruby_malloc_size_overflow(x, y);
        __builtin_unreachable();
    }
}
static inline void *
rb_alloc_tmp_buffer2(volatile VALUE *store, long count, size_t elsize)
{
    const size_t total_size = rbimpl_size_mul_or_raise(count, elsize);
    const size_t cnt = (total_size + sizeof(VALUE) - 1) / sizeof(VALUE);
    return rb_alloc_tmp_buffer_with_count(store, total_size, cnt);
}



__attribute__((__nonnull__ (1)))
__attribute__((__returns_nonnull__))
static inline void *
ruby_nonempty_memcpy(void *dest, const void *src, size_t n)
{
    if (n) {
        return memcpy(dest, src, n);
    }
    else {
        return dest;
    }
}




VALUE rb_define_class(const char*,VALUE);
VALUE rb_define_module(const char*);
VALUE rb_define_class_under(VALUE, const char*, VALUE);
VALUE rb_define_module_under(VALUE, const char*);
void rb_include_module(VALUE,VALUE);
void rb_extend_object(VALUE,VALUE);
void rb_prepend_module(VALUE,VALUE);




VALUE rb_newobj(void);
VALUE rb_newobj_of(VALUE, VALUE);
VALUE rb_obj_setup(VALUE obj, VALUE klass, VALUE type);
VALUE rb_obj_class(VALUE);
VALUE rb_singleton_class_clone(VALUE);
void rb_singleton_class_attached(VALUE,VALUE);
void rb_copy_generic_ivar(VALUE,VALUE);


static inline void
rb_clone_setup(VALUE clone, VALUE obj)
{
    ((void)0);
    ((void)0);
    const VALUE flags = RUBY_FL_PROMOTED0 | RUBY_FL_PROMOTED1 | RUBY_FL_FINALIZE;
    rb_obj_setup(clone, rb_singleton_class_clone(obj),
                 RB_FL_TEST_RAW(obj, ~flags));
    rb_singleton_class_attached(RBASIC_CLASS(clone), clone);
    if (RB_FL_TEST(obj, RUBY_FL_EXIVAR)) rb_copy_generic_ivar(clone, obj);
}
static inline void
rb_dup_setup(VALUE dup, VALUE obj)
{
    ((void)0);
    ((void)0);
    rb_obj_setup(dup, rb_obj_class(obj), RB_FL_TEST_RAW(obj, RUBY_FL_DUPPED));
    if (RB_FL_TEST(obj, RUBY_FL_EXIVAR)) rb_copy_generic_ivar(dup, obj);
}


void rb_mem_clear(VALUE*, long);
VALUE rb_assoc_new(VALUE, VALUE);
VALUE rb_check_array_type(VALUE);
VALUE rb_ary_new(void);
VALUE rb_ary_new_capa(long capa);
VALUE rb_ary_new_from_args(long n, ...);
VALUE rb_ary_new_from_values(long n, const VALUE *elts);
VALUE rb_ary_tmp_new(long);
void rb_ary_free(VALUE);
void rb_ary_modify(VALUE);
VALUE rb_ary_freeze(VALUE);
VALUE rb_ary_shared_with_p(VALUE, VALUE);
VALUE rb_ary_aref(int, const VALUE*, VALUE);
VALUE rb_ary_subseq(VALUE, long, long);
void rb_ary_store(VALUE, long, VALUE);
VALUE rb_ary_dup(VALUE);
VALUE rb_ary_resurrect(VALUE ary);
VALUE rb_ary_to_ary(VALUE);
VALUE rb_ary_to_s(VALUE);
VALUE rb_ary_cat(VALUE, const VALUE *, long);
VALUE rb_ary_push(VALUE, VALUE);
VALUE rb_ary_pop(VALUE);
VALUE rb_ary_shift(VALUE);
VALUE rb_ary_unshift(VALUE, VALUE);
VALUE rb_ary_entry(VALUE, long);
VALUE rb_ary_each(VALUE);
VALUE rb_ary_join(VALUE, VALUE);
VALUE rb_ary_reverse(VALUE);
VALUE rb_ary_rotate(VALUE, long);
VALUE rb_ary_sort(VALUE);
VALUE rb_ary_sort_bang(VALUE);
VALUE rb_ary_delete(VALUE, VALUE);
VALUE rb_ary_delete_at(VALUE, long);
VALUE rb_ary_clear(VALUE);
VALUE rb_ary_plus(VALUE, VALUE);
VALUE rb_ary_concat(VALUE, VALUE);
VALUE rb_ary_assoc(VALUE, VALUE);
VALUE rb_ary_rassoc(VALUE, VALUE);
VALUE rb_ary_includes(VALUE, VALUE);
VALUE rb_ary_cmp(VALUE, VALUE);
VALUE rb_ary_replace(VALUE copy, VALUE orig);
VALUE rb_get_values_at(VALUE, long, int, const VALUE*, VALUE(*)(VALUE,long));
VALUE rb_ary_resize(VALUE ary, long len);




VALUE rb_exc_new(VALUE, const char*, long);
VALUE rb_exc_new_cstr(VALUE, const char*);
VALUE rb_exc_new_str(VALUE, VALUE);
__attribute__((__format__(__printf__, (1), (2)))) __attribute__((__noreturn__)) void rb_loaderror(const char*, ...);
__attribute__((__format__(__printf__, (2), (3)))) __attribute__((__noreturn__)) void rb_loaderror_with_path(VALUE path, const char*, ...);
__attribute__((__format__(__printf__, (2), (3)))) __attribute__((__noreturn__)) void rb_name_error(ID, const char*, ...);
__attribute__((__format__(__printf__, (2), (3)))) __attribute__((__noreturn__)) void rb_name_error_str(VALUE, const char*, ...);
__attribute__((__format__(__printf__, (2), (3)))) __attribute__((__noreturn__)) void rb_frozen_error_raise(VALUE, const char*, ...);
__attribute__((__noreturn__)) void rb_invalid_str(const char*, const char*);
__attribute__((__noreturn__)) void rb_error_frozen(const char*);
__attribute__((__noreturn__)) void rb_error_frozen_object(VALUE);
void rb_error_untrusted(VALUE);
void rb_check_frozen(VALUE);
void rb_check_trusted(VALUE);
void rb_check_copyable(VALUE obj, VALUE orig);
__attribute__((__noreturn__)) static void rb_error_arity(int, int, int);


static inline void
rb_check_frozen_inline(VALUE obj)
{
    if ((__builtin_expect(!!(RB_OBJ_FROZEN(obj)), 0))) {
        rb_error_frozen_object(obj);
    }
}
static inline int
rb_check_arity(int argc, int min, int max)
{
    if ((argc < min) || (max != (-1) && argc > max))
        rb_error_arity(argc, min, max);
    return argc;
}


void rb_st_foreach_safe(struct st_table *, int (*)(st_data_t, st_data_t, st_data_t), st_data_t);
VALUE rb_check_hash_type(VALUE);
void rb_hash_foreach(VALUE, int (*)(VALUE, VALUE, VALUE), VALUE);
VALUE rb_hash(VALUE);
VALUE rb_hash_new(void);
VALUE rb_hash_dup(VALUE);
VALUE rb_hash_freeze(VALUE);
VALUE rb_hash_aref(VALUE, VALUE);
VALUE rb_hash_lookup(VALUE, VALUE);