addressable 2.9.2 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,6 +17,8 @@
17
17
  #++
18
18
 
19
19
 
20
+ require "set"
21
+ require "strscan"
20
22
  require "addressable/version"
21
23
  require "addressable/uri"
22
24
 
@@ -37,18 +39,40 @@ module Addressable
37
39
 
38
40
  var_char =
39
41
  "(?>(?:[#{variable_char_class}]|%[a-fA-F0-9][a-fA-F0-9])+)"
42
+ # Matching accepts a non-ASCII character as it is or pct-encoded.
43
+ non_ascii = "[^\\x00-\\x7F]"
40
44
  RESERVED =
41
- "(?:[#{anything}]|%[a-fA-F0-9][a-fA-F0-9])"
45
+ "(?:[#{anything}]|#{non_ascii}|%[a-fA-F0-9][a-fA-F0-9])"
42
46
  RESERVED_NO_COMMA =
43
- "(?:[#{anything.delete(',')}]|%[a-fA-F0-9][a-fA-F0-9])"
47
+ "(?:[#{anything.delete(',')}]|#{non_ascii}|%[a-fA-F0-9][a-fA-F0-9])"
44
48
  UNRESERVED =
45
49
  "(?:[#{
46
50
  Addressable::URI::CharacterClasses::UNRESERVED
47
- }]|%[a-fA-F0-9][a-fA-F0-9])"
51
+ }]|#{non_ascii}|%[a-fA-F0-9][a-fA-F0-9])"
52
+ # Reserved and fragment expansion encode every character outside the
53
+ # reserved and unreserved sets, except a "%" that starts a pct-encoded
54
+ # triplet (RFC 6570 section 3.2.3).
55
+ RESERVED_ENCODE = /%(?![0-9A-Fa-f]{2})|[^%#{anything}]/
56
+ PCT_ENCODED_OR_CHARACTER = /%[0-9A-Fa-f]{2}|./m
57
+ HEX_DIGITS = "0123456789ABCDEFabcdef".bytes.freeze
58
+ # Whether a regular expression group name can start with ".". Ruby 2.3
59
+ # and earlier only allow a letter or "_" as its first character.
60
+ GROUP_NAME_CAN_START_WITH_DOT = begin
61
+ Regexp.new("(?<.a>)")
62
+ true
63
+ rescue RegexpError
64
+ false
65
+ end
66
+ # A "#" after the one that starts a fragment, as written or as expansion
67
+ # encodes it.
68
+ NUMBER_SIGN_EITHER_FORM = "(?:\\#|%23)"
69
+ # A literal's token: a run of non-ASCII pct-encoded octets, one triplet, or
70
+ # one character.
71
+ LITERAL_TOKEN = /(?:%[89A-Fa-f][0-9A-Fa-f])+|%[0-9A-Fa-f]{2}|./m
48
72
  variable =
49
73
  "(?:#{var_char}(?:\\.?#{var_char})*)"
50
74
  varspec =
51
- "(?:(#{variable})(\\*|:\\d+)?)"
75
+ "(?:(#{variable})(\\*|:[1-9]\\d{0,3})?)"
52
76
  VARNAME =
53
77
  /^#{variable}$/
54
78
  VARSPEC =
@@ -59,6 +83,79 @@ module Addressable
59
83
  "+#./;?&=,!@|"
60
84
  EXPRESSION =
61
85
  /\{([#{operator}])?(#{varspec}(?:,#{varspec})*)\}/
86
+ # RFC 6570 reserves these operators for future extensions.
87
+ RESERVED_OPERATORS = "=,!@|"
88
+ VALID_EXPRESSION =
89
+ /\A\{[+#.\/;?&]?#{varspec}(?:,#{varspec})*\}\z/
90
+ # Literal text, an expression up to the next "}" (or the end, if there's
91
+ # no "}"), or a "}" that doesn't close an expression.
92
+ TEMPLATE_TOKEN = /[^{}]+|\{[^}]*\}?|\}/
93
+ # Expansion encodes non-ASCII literals (RFC 6570 section 3.1). An ASCII
94
+ # character the literals grammar leaves out stays as it is, as most other
95
+ # implementations do.
96
+ LITERAL_ENCODE = /[^\x00-\x7F]/
97
+ # Characters that label expansion encodes, so a value can't contain them
98
+ # as they are: the reserved set (RFC 3986 section 2.2).
99
+ LABEL_DELIMITER = /[:\/?#\[\]@!$&'()*+,;=]/
100
+ private_constant :RESERVED_OPERATORS, :VALID_EXPRESSION, :TEMPLATE_TOKEN,
101
+ :LITERAL_ENCODE, :NUMBER_SIGN_EITHER_FORM, :LITERAL_TOKEN,
102
+ :GROUP_NAME_CAN_START_WITH_DOT, :HEX_DIGITS, :LABEL_DELIMITER
103
+
104
+ NO_MAPPING = Object.new.freeze
105
+ private_constant :NO_MAPPING
106
+
107
+ # Looks up variables in a mapping that isn't enumerable, such as a lambda,
108
+ # once each. As with Hash#fetch, a KeyError means the variable is missing,
109
+ # and nil means it's defined as nil.
110
+ class MappingLookup
111
+ MISSING = Object.new.freeze
112
+
113
+ def initialize(source)
114
+ @source = source
115
+ @values = {}
116
+ end
117
+
118
+ def [](name)
119
+ value = lookup(name)
120
+ value.equal?(MISSING) ? nil : value
121
+ end
122
+
123
+ def key?(name)
124
+ !lookup(name).equal?(MISSING)
125
+ end
126
+
127
+ private
128
+
129
+ def lookup(name)
130
+ @values.fetch(name) do
131
+ @values[name] =
132
+ if @source.respond_to?(:key?) && !@source.key?(name)
133
+ MISSING
134
+ else
135
+ begin
136
+ @source[name]
137
+ rescue KeyError => error
138
+ raise unless missing?(error, name)
139
+ MISSING
140
+ end
141
+ end
142
+ end
143
+ end
144
+
145
+ # KeyError#key is Ruby 2.6+. For an error with no key, MRI raises and
146
+ # TruffleRuby gives nil.
147
+ def missing?(error, name)
148
+ return true unless error.respond_to?(:key)
149
+ begin
150
+ key = error.key
151
+ rescue ArgumentError
152
+ return true
153
+ end
154
+ return true if key.nil?
155
+ (key.is_a?(String) || key.is_a?(Symbol)) && key.to_s == name
156
+ end
157
+ end
158
+ private_constant :MappingLookup
62
159
 
63
160
 
64
161
  LEADERS = {
@@ -77,14 +174,24 @@ module Addressable
77
174
  '/' => '/'
78
175
  }
79
176
 
177
+ # The operators that write each variable's name before its value.
178
+ NAMED_OPERATORS = [';', '?', '&'].freeze
179
+ private_constant :NAMED_OPERATORS
180
+
80
181
  ##
81
182
  # Raised if an invalid template value is supplied.
82
183
  class InvalidTemplateValueError < StandardError
83
184
  end
84
185
 
186
+ ##
187
+ # Raised if a template that doesn't match the RFC 6570 grammar is
188
+ # expanded.
189
+ class InvalidTemplateError < StandardError
190
+ end
191
+
85
192
  ##
86
193
  # Raised if an invalid template operator is used in a pattern.
87
- class InvalidTemplateOperatorError < StandardError
194
+ class InvalidTemplateOperatorError < InvalidTemplateError
88
195
  end
89
196
 
90
197
  ##
@@ -143,10 +250,10 @@ module Addressable
143
250
  # Note that this list will include nils for any variables which
144
251
  # were in the Template, but did not appear in the URI.
145
252
  def values
146
- @values ||= self.variables.inject([]) do |accu, key|
253
+ (@values ||= self.variables.inject([]) do |accu, key|
147
254
  accu << self.mapping[key]
148
255
  accu
149
- end
256
+ end).dup
150
257
  end
151
258
  alias_method :captures, :values
152
259
 
@@ -247,7 +354,7 @@ module Addressable
247
354
  def freeze
248
355
  self.variables
249
356
  self.variable_defaults
250
- self.named_captures
357
+ parse_template_pattern(pattern)
251
358
  super
252
359
  end
253
360
 
@@ -284,6 +391,12 @@ module Addressable
284
391
  # @see #==
285
392
  alias_method :eql?, :==
286
393
 
394
+ ##
395
+ # @return [Integer] A hash consistent with template equality.
396
+ def hash
397
+ self.pattern.hash
398
+ end
399
+
287
400
  ##
288
401
  # Extracts a mapping from the URI using a URI Template pattern.
289
402
  #
@@ -302,8 +415,46 @@ module Addressable
302
415
  # parameter: `[String] name`. The <tt>match</tt> method should return
303
416
  # a <tt>String</tt> containing a regular expression capture group for
304
417
  # matching on that particular variable. The default value is `".*?"`.
305
- # The <tt>match</tt> method has no effect on multivariate operator
306
- # expansions.
418
+ # In a <tt>;</tt>, <tt>?</tt> or <tt>&</tt> expression, the pattern
419
+ # matches the value after the variable's name and <tt>=</tt>, and
420
+ # <tt>restore</tt> is called with the template's variable names.
421
+ #
422
+ # Without a processor, each value is pct-decoded once. Reserved
423
+ # (<tt>{+var}</tt>) and fragment (<tt>{#var}</tt>) expansion keep a
424
+ # value's pct-encoded triplets (RFC 6570 section 3.2.3), so for those
425
+ # operators, expanding an extracted value can give a different URI:
426
+ # <tt>{+path}</tt> extracts <tt>a/b</tt> from <tt>a%2Fb</tt>, which
427
+ # expands to <tt>a/b</tt>, and a value pct-encoded twice comes back
428
+ # encoded once. With any processor, even one that only responds to
429
+ # <tt>match</tt>, values aren't decoded: each is given as it appears in
430
+ # the URI, after <tt>restore</tt> if the processor has it.
431
+ #
432
+ # An exploded <tt>;</tt>, <tt>?</tt> or <tt>&</tt> value whose pairs all
433
+ # have the variable's name as their key is a list; other pairs are an
434
+ # associative array. The key is compared with the name as written, so
435
+ # <tt>{?a*}</tt> reads <tt>?%61=x</tt> as the pair <tt>%61</tt>, decoded
436
+ # to <tt>a</tt>, not as a list.
437
+ #
438
+ # Label expansion (<tt>{.var}</tt>) leaves a <tt>.</tt> in a value as it
439
+ # is, so a value can only contain <tt>.</tt> where it's clear where it
440
+ # ends: a label expression with one variable that isn't exploded, set off
441
+ # on both sides by the start or end of the URI or by characters that
442
+ # label expansion encodes, such as <tt>/</tt>, <tt>?</tt> or <tt>;</tt>.
443
+ # <tt>/f{.ext}</tt> extracts <tt>tar.gz</tt> from <tt>/f.tar.gz</tt>.
444
+ # Elsewhere, each <tt>.</tt> starts a label: <tt>/{name}{.ext}</tt> reads
445
+ # <tt>/archive.tar.gz</tt> as <tt>archive.tar</tt> and <tt>gz</tt>.
446
+ #
447
+ # Matching takes time linear in the URI's length, with two exceptions on
448
+ # MRI before 3.3, JRuby and TruffleRuby, where it can take time
449
+ # polynomial in the URI's length: matching with a processor that gives a
450
+ # variable its own pattern, which keeps every choice open so that the
451
+ # pattern decides the values, and matching some templates that combine an
452
+ # exploded variable, or several variables in one expression, with other
453
+ # expressions, such as <tt>{+c*,d}{&b}.{b}</tt>.
454
+ #
455
+ # @raise [Addressable::Template::InvalidTemplateError]
456
+ # If the template doesn't match the RFC 6570 grammar, e.g. an unclosed
457
+ # expression or a stray <tt>}</tt>.
307
458
  #
308
459
  # @return [Hash, NilClass]
309
460
  # The <tt>Hash</tt> mapping that was extracted from the URI, or
@@ -364,8 +515,46 @@ module Addressable
364
515
  # parameter: `[String] name`. The <tt>match</tt> method should return
365
516
  # a <tt>String</tt> containing a regular expression capture group for
366
517
  # matching on that particular variable. The default value is `".*?"`.
367
- # The <tt>match</tt> method has no effect on multivariate operator
368
- # expansions.
518
+ # In a <tt>;</tt>, <tt>?</tt> or <tt>&</tt> expression, the pattern
519
+ # matches the value after the variable's name and <tt>=</tt>, and
520
+ # <tt>restore</tt> is called with the template's variable names.
521
+ #
522
+ # Without a processor, each value is pct-decoded once. Reserved
523
+ # (<tt>{+var}</tt>) and fragment (<tt>{#var}</tt>) expansion keep a
524
+ # value's pct-encoded triplets (RFC 6570 section 3.2.3), so for those
525
+ # operators, expanding an extracted value can give a different URI:
526
+ # <tt>{+path}</tt> extracts <tt>a/b</tt> from <tt>a%2Fb</tt>, which
527
+ # expands to <tt>a/b</tt>, and a value pct-encoded twice comes back
528
+ # encoded once. With any processor, even one that only responds to
529
+ # <tt>match</tt>, values aren't decoded: each is given as it appears in
530
+ # the URI, after <tt>restore</tt> if the processor has it.
531
+ #
532
+ # An exploded <tt>;</tt>, <tt>?</tt> or <tt>&</tt> value whose pairs all
533
+ # have the variable's name as their key is a list; other pairs are an
534
+ # associative array. The key is compared with the name as written, so
535
+ # <tt>{?a*}</tt> reads <tt>?%61=x</tt> as the pair <tt>%61</tt>, decoded
536
+ # to <tt>a</tt>, not as a list.
537
+ #
538
+ # Label expansion (<tt>{.var}</tt>) leaves a <tt>.</tt> in a value as it
539
+ # is, so a value can only contain <tt>.</tt> where it's clear where it
540
+ # ends: a label expression with one variable that isn't exploded, set off
541
+ # on both sides by the start or end of the URI or by characters that
542
+ # label expansion encodes, such as <tt>/</tt>, <tt>?</tt> or <tt>;</tt>.
543
+ # <tt>/f{.ext}</tt> extracts <tt>tar.gz</tt> from <tt>/f.tar.gz</tt>.
544
+ # Elsewhere, each <tt>.</tt> starts a label: <tt>/{name}{.ext}</tt> reads
545
+ # <tt>/archive.tar.gz</tt> as <tt>archive.tar</tt> and <tt>gz</tt>.
546
+ #
547
+ # Matching takes time linear in the URI's length, with two exceptions on
548
+ # MRI before 3.3, JRuby and TruffleRuby, where it can take time
549
+ # polynomial in the URI's length: matching with a processor that gives a
550
+ # variable its own pattern, which keeps every choice open so that the
551
+ # pattern decides the values, and matching some templates that combine an
552
+ # exploded variable, or several variables in one expression, with other
553
+ # expressions, such as <tt>{+c*,d}{&b}.{b}</tt>.
554
+ #
555
+ # @raise [Addressable::Template::InvalidTemplateError]
556
+ # If the template doesn't match the RFC 6570 grammar, e.g. an unclosed
557
+ # expression or a stray <tt>}</tt>.
369
558
  #
370
559
  # @return [Hash, NilClass]
371
560
  # The <tt>Hash</tt> mapping that was extracted from the URI, or
@@ -413,6 +602,10 @@ module Addressable
413
602
  # match.captures
414
603
  # #=> ["a", ["b", "c"]]
415
604
  def match(uri, processor=nil)
605
+ check_expressions
606
+ # Text that isn't valid UTF-8 isn't a valid URI or IRI, so it doesn't
607
+ # match, as below.
608
+ return nil unless valid_utf8?(uri)
416
609
  unless uri.is_a?(Addressable::URI)
417
610
  begin
418
611
  uri = Addressable::URI.parse(uri)
@@ -426,7 +619,7 @@ module Addressable
426
619
  mapping = {}
427
620
 
428
621
  # First, we need to process the pattern, and extract the values.
429
- expansions, expansion_regexp =
622
+ expansions, expansion_regexp, patterns =
430
623
  parse_template_pattern(pattern, processor)
431
624
 
432
625
  matched = uri.to_str.match(expansion_regexp)
@@ -437,9 +630,28 @@ module Addressable
437
630
  return Addressable::Template::MatchData.new(uri, self, mapping)
438
631
  elsif expansions.size > 0
439
632
  index = 0
440
- expansions.each do |expansion|
633
+ split = !(processor && processor.respond_to?(:match))
634
+ expansions.each_with_index do |expansion, expansion_index|
441
635
  _, operator, varlist = *expansion.match(EXPRESSION)
442
- varlist.split(',').each do |varspec|
636
+ varspecs = varlist.split(',')
637
+ if NAMED_OPERATORS.include?(operator)
638
+ named = named_values(
639
+ operator, varspecs, unparsed_values[index, varspecs.size],
640
+ patterns[expansion_index]
641
+ )
642
+ return nil unless named
643
+ end
644
+ values = if split && varspecs.size > 1
645
+ split_from_left(operator, varspecs, matched, index)
646
+ end
647
+ if !values && [nil, '+', '#', '/', '.'].include?(operator) &&
648
+ varlist.include?('*')
649
+ members = exploded_members(
650
+ operator, varspecs, unparsed_values[index, varspecs.size],
651
+ index, matched, uri.to_str
652
+ )
653
+ end
654
+ varspecs.each_with_index do |varspec, position|
443
655
  _, name, modifier = *varspec.match(VARSPEC)
444
656
  mapping[name] ||= nil
445
657
  case operator
@@ -447,24 +659,16 @@ module Addressable
447
659
  unparsed_value = unparsed_values[index]
448
660
  name = varspec[VARSPEC, 1]
449
661
  value = unparsed_value
450
- value = value.split(JOINERS[operator]) if value && modifier == '*'
451
- when ';', '?', '&'
452
- if modifier == '*'
453
- if unparsed_values[index]
454
- value = unparsed_values[index].split(JOINERS[operator])
455
- value = value.inject({}) do |acc, v|
456
- key, val = v.split('=')
457
- val = "" if val.nil?
458
- acc[key] = val
459
- acc
460
- end
461
- end
462
- else
463
- if (unparsed_values[index])
464
- name, value = unparsed_values[index].split('=')
465
- value = "" if value.nil?
466
- end
662
+ if values
663
+ value = values[position]
664
+ elsif value && modifier == '*'
665
+ value = members[position]
467
666
  end
667
+ when ';', '?', '&'
668
+ # An exploded value is an associative array, even when its
669
+ # pairs repeat the variable's name, as an exploded list's do.
670
+ # A repeated key keeps its last value.
671
+ value = named[position]
468
672
  end
469
673
  if processor != nil && processor.respond_to?(:restore)
470
674
  value = processor.restore(name, value)
@@ -495,10 +699,107 @@ module Addressable
495
699
  end
496
700
  end
497
701
 
702
+ ##
703
+ # The members of each exploded value of a default, +, #, / or .
704
+ # expression in a match. A member can be empty, so a joiner at the end of
705
+ # a value can be an empty member or the one before a later variable, and
706
+ # an empty value can be one empty member or none. Joined with the
707
+ # expression's joiner, the values must give the text the expression
708
+ # matched, so where the first choice doesn't, the others are tried.
709
+ #
710
+ # @param [String, nil] operator The expression's operator.
711
+ # @param [Array<String>] varspecs The expression's variables.
712
+ # @param [Array<String, nil>] values The variables' captures.
713
+ # @param [Integer] index The index of its first capture.
714
+ # @param [MatchData] matched The match.
715
+ # @param [String] text The URI.
716
+ #
717
+ # @return [Hash] The members, for each exploded variable's position.
718
+ def exploded_members(operator, varspecs, values, index, matched, text)
719
+ joiner = JOINERS.fetch(operator, ',')
720
+ exploded = varspecs.map { |varspec| varspec[VARSPEC, 2] == '*' }
721
+ # An empty list is undefined, and has no joiner before it.
722
+ valued = lambda do |at|
723
+ values[at] && !(exploded[at] && values[at].empty?)
724
+ end
725
+ members = {}
726
+ choices = {}
727
+ varspecs.each_index do |position|
728
+ next unless exploded[position] && values[position]
729
+ list = values[position].split(joiner, -1)
730
+ # Right after the leader, an empty value is one empty member.
731
+ if list.empty? && position == 0 && LEADERS.key?(operator)
732
+ list = ['']
733
+ end
734
+ # A later variable that starts right where this value ends has its
735
+ # joiner at the end of this one.
736
+ reached = matched.end(index + position + 1)
737
+ ((position + 1)...varspecs.size).each do |at|
738
+ next unless valued.call(at)
739
+ group = index + at + 1
740
+ list.pop if matched.begin(group) == reached && list.last == ''
741
+ break unless matched.end(group) == matched.begin(group)
742
+ reached = matched.end(group)
743
+ end
744
+ members[position] = list
745
+ # The other choices: up to one fewer empty member at the end for
746
+ # each later variable, or one empty member for an empty value.
747
+ whole = values[position].split(joiner, -1)
748
+ options = [list]
749
+ (0..[varspecs.size - position - 1, whole.size].min).each do |dropped|
750
+ next unless whole[(whole.size - dropped)..-1].all?(&:empty?)
751
+ options << whole[0, whole.size - dropped]
752
+ end
753
+ options << [''] if whole.empty?
754
+ choices[position] = options.uniq
755
+ end
756
+ present = values.each_index.select { |at| values[at] }
757
+ return members if present.empty? || choices.empty?
758
+ expected = text[
759
+ matched.begin(index + present.first + 1)...
760
+ matched.end(index + present.last + 1)
761
+ ]
762
+ joined = lambda do |chosen|
763
+ values.each_index.map do |at|
764
+ next nil unless values[at]
765
+ next values[at] unless exploded[at]
766
+ list = chosen[at]
767
+ list.empty? ? nil : list.join(joiner)
768
+ end.compact.join(joiner)
769
+ end
770
+ return members if joined.call(members) == expected
771
+ positions = choices.keys
772
+ count = positions.inject(1) { |product, at| product * choices[at].size }
773
+ # The choices are few for templates of the usual size; past that,
774
+ # the first one is kept rather than trying them all.
775
+ return members if count > 64
776
+ combos = positions.map { |at| choices[at] }
777
+ first, *rest = combos
778
+ first.product(*rest).each do |combo|
779
+ chosen = Hash[positions.zip(combo)]
780
+ return chosen if joined.call(chosen) == expected
781
+ end
782
+ members
783
+ end
784
+
498
785
  ##
499
786
  # Expands a URI template into another URI template.
500
787
  #
501
- # @param [Hash] mapping The mapping that corresponds to the pattern.
788
+ # @param [Hash, #each_pair, #[]] mapping
789
+ # The values for the template's variables. This can be a Hash, an
790
+ # array of name and value pairs, an object with <tt>each_pair</tt>
791
+ # such as a Struct, or any object that responds to <tt>[]</tt>, such as
792
+ # a lambda. A lambda or other <tt>[]</tt> object is called with each
793
+ # variable's name as a String, at most once per name. Leave the mapping
794
+ # out to look up variables with a block instead.
795
+ #
796
+ # Lookups follow the <tt>Hash#fetch</tt> convention: raise
797
+ # <tt>KeyError</tt> for a variable that's missing, and return <tt>nil</tt>
798
+ # for a variable that's undefined. A missing variable's expression stays
799
+ # in the returned template, and an undefined variable is expanded to
800
+ # nothing, as with a Hash that lacks the key or maps it to <tt>nil</tt>.
801
+ # An object that responds to <tt>key?</tt> reports missing variables with
802
+ # <tt>key?</tt> instead.
502
803
  # @param [#validate, #transform] processor
503
804
  # An optional processor object may be supplied.
504
805
  # @param [Boolean] normalize_values
@@ -516,6 +817,40 @@ module Addressable
516
817
  # encoded automatically. Unicode normalization will be performed both
517
818
  # before and after sending the value to the transform method.
518
819
  #
820
+ # RFC 6570 doesn't define partial expansion, and it can't always give
821
+ # the same result as expanding every variable at once:
822
+ #
823
+ # * In an expression with several variables whose values are joined
824
+ # with "," (<tt>{x,y}</tt>, <tt>{+x,y}</tt> and <tt>{#x,y}</tt>), there's
825
+ # no way to write a "," that appears only if a missing variable is
826
+ # later defined. The partial result assumes that missing variables
827
+ # stay undefined: <tt>{x,y}</tt> with only <tt>x</tt> gives
828
+ # <tt>1{y}</tt>, so expanding <tt>y</tt> later gives <tt>12</tt>, not
829
+ # <tt>1,2</tt>.
830
+ # * In a form-style query (<tt>{?x,y}</tt>), the given variables come
831
+ # first, so that the query still starts with "?" if a missing variable
832
+ # is never given: <tt>{?x,y}</tt> with only <tt>y</tt> gives
833
+ # <tt>?y=2{&x}</tt>. The query has the same pairs, in another order.
834
+ #
835
+ # The result is a template, not a URI, so <tt>#pattern</tt> can differ
836
+ # from <tt>#expand</tt> even when every variable is given: literals stay
837
+ # as written, rather than pct-encoded, and a "#" after the one that
838
+ # starts the fragment isn't encoded until the template is expanded. A
839
+ # missing variable's expression stays in the template, where
840
+ # <tt>#expand</tt> leaves it out.
841
+ #
842
+ # @yield [name] Looks up a variable, when no mapping is given.
843
+ # @yieldparam [String] name The variable's name.
844
+ # @yieldreturn [Object] The variable's value, or <tt>nil</tt> if it's
845
+ # undefined. Raise <tt>KeyError</tt> if the variable is missing.
846
+ #
847
+ # @raise [TypeError] If the mapping isn't one of the types above.
848
+ # @raise [ArgumentError] If both a mapping and a block are given, or
849
+ # neither.
850
+ # @raise [Addressable::Template::InvalidTemplateError]
851
+ # If the template doesn't match the RFC 6570 grammar, e.g. an unclosed
852
+ # expression or a stray <tt>}</tt>.
853
+ #
519
854
  # @return [Addressable::Template] The partially expanded URI template.
520
855
  #
521
856
  # @example
@@ -525,17 +860,25 @@ module Addressable
525
860
  # #=> "http://example.com/1/{two}/"
526
861
  #
527
862
  # Addressable::Template.new(
528
- # "http://example.com/{?one,two}/"
863
+ # "http://example.com/{?one,two}"
529
864
  # ).partial_expand({"one" => "1"}).pattern
530
- # #=> "http://example.com/?one=1{&two}/"
865
+ # #=> "http://example.com/?one=1{&two}"
531
866
  #
532
867
  # Addressable::Template.new(
533
- # "http://example.com/{?one,two,three}/"
868
+ # "http://example.com/{?one,two,three}"
534
869
  # ).partial_expand({"one" => "1", "three" => 3}).pattern
535
870
  # #=> "http://example.com/?one=1{&two}&three=3"
536
- def partial_expand(mapping, processor=nil, normalize_values=true)
871
+ #
872
+ # values = {"one" => "1"}
873
+ # Addressable::Template.new(
874
+ # "http://example.com/{one}/{two}/"
875
+ # ).partial_expand { |name| values.fetch(name) }.pattern
876
+ # #=> "http://example.com/1/{two}/"
877
+ def partial_expand(mapping=NO_MAPPING, processor=nil, normalize_values=true,
878
+ &block)
879
+ check_expressions
537
880
  result = self.pattern.dup
538
- mapping = normalize_keys(mapping)
881
+ mapping = resolve_mapping(mapping, block)
539
882
  result.gsub!( EXPRESSION ) do |capture|
540
883
  transform_partial_capture(mapping, capture, processor, normalize_values)
541
884
  end
@@ -545,7 +888,19 @@ module Addressable
545
888
  ##
546
889
  # Expands a URI template into a full URI.
547
890
  #
548
- # @param [Hash] mapping The mapping that corresponds to the pattern.
891
+ # @param [Hash, #each_pair, #[]] mapping
892
+ # The values for the template's variables. This can be a Hash, an
893
+ # array of name and value pairs, an object with <tt>each_pair</tt>
894
+ # such as a Struct, or any object that responds to <tt>[]</tt>, such as
895
+ # a lambda. A lambda or other <tt>[]</tt> object is called with each
896
+ # variable's name as a String, at most once per name. Leave the mapping
897
+ # out to look up variables with a block instead.
898
+ #
899
+ # Lookups follow the <tt>Hash#fetch</tt> convention: raise
900
+ # <tt>KeyError</tt> for a variable that's missing, and return <tt>nil</tt>
901
+ # for a variable that's undefined. Both expand to nothing. An object that
902
+ # responds to <tt>key?</tt> reports missing variables with <tt>key?</tt>
903
+ # instead.
549
904
  # @param [#validate, #transform] processor
550
905
  # An optional processor object may be supplied.
551
906
  # @param [Boolean] normalize_values
@@ -563,6 +918,18 @@ module Addressable
563
918
  # encoded automatically. Unicode normalization will be performed both
564
919
  # before and after sending the value to the transform method.
565
920
  #
921
+ # @yield [name] Looks up a variable, when no mapping is given.
922
+ # @yieldparam [String] name The variable's name.
923
+ # @yieldreturn [Object] The variable's value, or <tt>nil</tt> if it's
924
+ # undefined. Raise <tt>KeyError</tt> if the variable is missing.
925
+ #
926
+ # @raise [TypeError] If the mapping isn't one of the types above.
927
+ # @raise [ArgumentError] If both a mapping and a block are given, or
928
+ # neither.
929
+ # @raise [Addressable::Template::InvalidTemplateError]
930
+ # If the template doesn't match the RFC 6570 grammar, e.g. an unclosed
931
+ # expression or a stray <tt>}</tt>.
932
+ #
566
933
  # @return [Addressable::URI] The expanded URI template.
567
934
  #
568
935
  # @example
@@ -600,24 +967,36 @@ module Addressable
600
967
  # ExampleProcessor
601
968
  # ).to_str
602
969
  # #=> Addressable::Template::InvalidTemplateValueError
603
- def expand(mapping, processor=nil, normalize_values=true)
604
- result = self.pattern.dup
605
- mapping = normalize_keys(mapping)
970
+ #
971
+ # repository = {"owner" => "sporkmonger", "repo" => "addressable"}
972
+ # Addressable::Template.new(
973
+ # "https://github.com/{owner}/{repo}"
974
+ # ).expand { |name| repository.fetch(name) }.to_str
975
+ # #=> "https://github.com/sporkmonger/addressable"
976
+ def expand(mapping=NO_MAPPING, processor=nil, normalize_values=true,
977
+ &block)
978
+ check_expressions
979
+ mapping = resolve_mapping(mapping, block)
980
+ result = map_literals(self.pattern) do |literal|
981
+ Addressable::URI.encode_component(literal, LITERAL_ENCODE)
982
+ end
606
983
  result.gsub!( EXPRESSION ) do |capture|
607
984
  transform_capture(mapping, capture, processor, normalize_values)
608
985
  end
609
- return Addressable::URI.parse(result)
986
+ return Addressable::URI.parse(encode_later_number_signs(result))
610
987
  end
611
988
 
612
989
  ##
613
990
  # Returns an Array of variables used within the template pattern.
614
991
  # The variables are listed in the Array in the order they appear within
615
992
  # the pattern. Multiple occurrences of a variable within a pattern are
616
- # not represented in this Array.
993
+ # not represented in this Array. An expression that doesn't match the
994
+ # RFC 6570 grammar, such as <tt>{!var}</tt> or <tt>{var:0}</tt>, has no
995
+ # variables to list.
617
996
  #
618
997
  # @return [Array] The variables present in the template's pattern.
619
998
  def variables
620
- @variables ||= ordered_variable_defaults.map { |var, val| var }.uniq
999
+ (@variables ||= ordered_variable_defaults.map { |var, val| var }.uniq).dup
621
1000
  end
622
1001
  alias_method :keys, :variables
623
1002
  alias_method :names, :variables
@@ -628,8 +1007,8 @@ module Addressable
628
1007
  #
629
1008
  # @return [Hash] Mapping of template variables to their defaults
630
1009
  def variable_defaults
631
- @variable_defaults ||=
632
- Hash[*ordered_variable_defaults.reject { |k, v| v.nil? }.flatten]
1010
+ (@variable_defaults ||=
1011
+ Hash[*ordered_variable_defaults.reject { |k, v| v.nil? }.flatten]).dup
633
1012
  end
634
1013
 
635
1014
  ##
@@ -638,8 +1017,20 @@ module Addressable
638
1017
  # URI values, but it cannot fully handle, for example, values that would
639
1018
  # extract to an `Array`.
640
1019
  #
1020
+ # Each variable has a named group. A group name can't start with a digit,
1021
+ # so a variable whose name does has its group named with a leading ".":
1022
+ # `{42}` has the group `.42`. Ruby 2.3 and earlier only allow a letter or
1023
+ # "_" as the first character of a group name, so there a variable whose
1024
+ # name starts with anything else has its group named with "__" before
1025
+ # and after it: `{42}` has `__42__`, and `{%41}` has `__%41__`.
1026
+ #
641
1027
  # @return [Regexp] A regular expression which should match the template.
1028
+ #
1029
+ # @raise [Addressable::Template::InvalidTemplateError]
1030
+ # If the template doesn't match the RFC 6570 grammar, e.g. an unclosed
1031
+ # expression or a stray <tt>}</tt>.
642
1032
  def to_regexp
1033
+ check_expressions
643
1034
  _, source = parse_template_pattern(pattern)
644
1035
  Regexp.new(source)
645
1036
  end
@@ -649,6 +1040,10 @@ module Addressable
649
1040
  #
650
1041
  # @return [String] The source of the `Regexp` given by {#to_regexp}.
651
1042
  #
1043
+ # @raise [Addressable::Template::InvalidTemplateError]
1044
+ # If the template doesn't match the RFC 6570 grammar, e.g. an unclosed
1045
+ # expression or a stray <tt>}</tt>.
1046
+ #
652
1047
  # @api private
653
1048
  def source
654
1049
  self.to_regexp.source
@@ -659,16 +1054,52 @@ module Addressable
659
1054
  #
660
1055
  # @return [Hash] The named captures of the `Regexp` given by {#to_regexp}.
661
1056
  #
1057
+ # @raise [Addressable::Template::InvalidTemplateError]
1058
+ # If the template doesn't match the RFC 6570 grammar, e.g. an unclosed
1059
+ # expression or a stray <tt>}</tt>.
1060
+ #
662
1061
  # @api private
663
1062
  def named_captures
664
- self.to_regexp.named_captures
1063
+ captures = self.to_regexp.named_captures
1064
+ captures.each_with_object({}) do |(group, indexes), names|
1065
+ names[variable_name(group)] = indexes
1066
+ end
665
1067
  end
666
1068
 
667
1069
  private
1070
+ ##
1071
+ # Raises InvalidTemplateError for the first part of the pattern that
1072
+ # isn't a literal or an expression (RFC 6570 section 3).
1073
+ def check_expressions
1074
+ position = 0
1075
+ pattern.scan(TEMPLATE_TOKEN) do |token|
1076
+ if token.start_with?("}")
1077
+ raise InvalidTemplateError, "Unmatched \"}\" at position #{position}"
1078
+ elsif token.start_with?("{")
1079
+ if !token.end_with?("}")
1080
+ raise InvalidTemplateError,
1081
+ "Unclosed template expression #{token.inspect} " \
1082
+ "at position #{position}"
1083
+ elsif token !~ VALID_EXPRESSION
1084
+ if RESERVED_OPERATORS.include?(token[1])
1085
+ raise InvalidTemplateOperatorError,
1086
+ "Invalid template operator #{token[1].inspect} in " \
1087
+ "#{token.inspect} at position #{position}"
1088
+ end
1089
+ raise InvalidTemplateError,
1090
+ "Invalid template expression #{token.inspect} " \
1091
+ "at position #{position}"
1092
+ end
1093
+ end
1094
+ position += token.length
1095
+ end
1096
+ end
1097
+
668
1098
  def ordered_variable_defaults
669
1099
  @ordered_variable_defaults ||= begin
670
1100
  expansions, _ = parse_template_pattern(pattern)
671
- expansions.flat_map do |capture|
1101
+ # An expression with a reserved operator has no variables to list.
1102
+ expansions.grep(VALID_EXPRESSION).flat_map do |capture|
672
1103
  _, _, varlist = *capture.match(EXPRESSION)
673
1104
  varlist.split(',').map do |varspec|
674
1105
  varspec[VARSPEC, 1]
@@ -706,34 +1137,232 @@ module Addressable
706
1137
  def transform_partial_capture(mapping, capture, processor = nil,
707
1138
  normalize_values = true)
708
1139
  _, operator, varlist = *capture.match(EXPRESSION)
709
-
1140
+ operator ||= ""
710
1141
  vars = varlist.split(",")
1142
+ given = lambda { |varspec| mapping.key?(varspec[VARSPEC, 1]) }
1143
+ defined = lambda do |varspec|
1144
+ given.call(varspec) &&
1145
+ !defined_value(mapping[varspec[VARSPEC, 1]]).nil?
1146
+ end
1147
+
1148
+ if vars.all?(&given)
1149
+ return transform_capture(mapping, capture, processor, normalize_values)
1150
+ elsif vars.none?(&given)
1151
+ return capture
1152
+ end
711
1153
 
712
1154
  if operator == "?"
713
1155
  # partial expansion of form style query variables sometimes requires a
714
1156
  # slight reordering of the variables to produce a valid url.
715
- first_to_expand = vars.find { |varspec|
716
- _, name, _ = *varspec.match(VARSPEC)
717
- mapping.key?(name) && !mapping[name].nil?
718
- }
1157
+ first_to_expand = vars.find(&defined)
719
1158
 
720
1159
  vars = [first_to_expand] + vars.reject {|varspec| varspec == first_to_expand} if first_to_expand
721
1160
  end
722
1161
 
723
- vars.
724
- inject("".dup) do |acc, varspec|
725
- _, name, _ = *varspec.match(VARSPEC)
726
- next_val = if mapping.key? name
727
- transform_capture(mapping, "{#{operator}#{varspec}}",
728
- processor, normalize_values)
729
- else
730
- "{#{operator}#{varspec}}"
731
- end
732
- # If we've already expanded at least one '?' operator with non-empty
733
- # value, change to '&'
734
- operator = "&" if (operator == "?") && (next_val != "")
735
- acc << next_val
1162
+ # An undefined variable adds nothing, so it mustn't split the missing
1163
+ # variables around it into separate expressions, which would lose the
1164
+ # separator between them or repeat the operator's prefix.
1165
+ vars = vars.select { |v| !given.call(v) || defined.call(v) }
1166
+
1167
+ # Consecutive variables that are all given, or all missing, stay in one
1168
+ # expression, so that their separator is kept.
1169
+ runs = vars.chunk { |varspec| given.call(varspec) }.to_a
1170
+ if %w(+ #).include?(operator) || operator.empty?
1171
+ transform_partial_comma_runs(
1172
+ mapping, operator, runs, defined, processor, normalize_values
1173
+ )
1174
+ else
1175
+ runs.inject("".dup) do |acc, (is_given, run)|
1176
+ expression = "{#{operator}#{run.join(',')}}"
1177
+ if is_given
1178
+ value = transform_capture(
1179
+ mapping, expression, processor, normalize_values
1180
+ )
1181
+ # After a value, the rest of a query continues with "&".
1182
+ operator = "&" if operator == "?" && !value.empty?
1183
+ acc << value
1184
+ else
1185
+ acc << expression
1186
+ end
1187
+ end
1188
+ end
1189
+ end
1190
+
1191
+ ##
1192
+ # Partially expands the runs of a simple, reserved or fragment expression,
1193
+ # whose values are separated by commas. RFC 6570 has no expression that
1194
+ # adds a comma only if a later variable is defined, so the result is the
1195
+ # same as expanding at once only if each missing variable ends up
1196
+ # undefined. After the first value, a fragment expression's runs use
1197
+ # reserved expansion, which adds no second "#".
1198
+ #
1199
+ # @param [Hash] mapping The mapping to replace captures
1200
+ # @param [String] operator The expression's operator.
1201
+ # @param [Array] runs The given and missing runs of varspecs.
1202
+ # @param [Proc] defined Whether a varspec's variable is given and defined.
1203
+ # @param [#validate, #transform] processor
1204
+ # An optional processor object may be supplied.
1205
+ # @param [Boolean] normalize_values
1206
+ # Optional flag to enable/disable unicode normalization. Default: true
1207
+ #
1208
+ # @return [String] The partially expanded expression
1209
+ def transform_partial_comma_runs(mapping, operator, runs, defined,
1210
+ processor, normalize_values)
1211
+ started = false
1212
+ # Once a given variable is defined, a fragment expression's "#" is
1213
+ # certain, so it comes first, and every run uses reserved expansion.
1214
+ fragment = operator == "#" &&
1215
+ runs.any? { |is_given, run| is_given && run.any?(&defined) }
1216
+ result = fragment ? "#".dup : "".dup
1217
+ runs.inject(result) do |acc, (is_given, run)|
1218
+ run_operator = (started || fragment) && operator == "#" ? "+" : operator
1219
+ expression = "{#{run_operator}#{run.join(',')}}"
1220
+ if is_given
1221
+ # An empty string is defined, so it still takes a separator.
1222
+ if run.any?(&defined)
1223
+ acc << "," if started
1224
+ started = true
1225
+ end
1226
+ acc << transform_capture(
1227
+ mapping, expression, processor, normalize_values
1228
+ )
1229
+ else
1230
+ acc << expression
1231
+ end
1232
+ end
1233
+ end
1234
+
1235
+ ##
1236
+ # Replaces the literal text between the expressions of a pattern.
1237
+ #
1238
+ # @param [String] pattern The URI template pattern.
1239
+ #
1240
+ # @yield [literal] Each run of literal text.
1241
+ #
1242
+ # @return [String] The pattern with each literal replaced.
1243
+ def map_literals(pattern)
1244
+ result = "".dup
1245
+ # StringScanner works in byte offsets; character offsets would make
1246
+ # this quadratic for a pattern with non-ASCII characters.
1247
+ scanner = StringScanner.new(pattern)
1248
+ while (text = scanner.scan_until(EXPRESSION))
1249
+ expression = scanner.matched
1250
+ literal = text.byteslice(0, text.bytesize - expression.bytesize)
1251
+ result << yield(literal, expression) << expression
1252
+ end
1253
+ result << yield(scanner.rest, nil)
1254
+ end
1255
+
1256
+ ##
1257
+ # A URI fragment can't contain "#" (RFC 3986 section 3.5), so expansion
1258
+ # encodes every "#" after the first one, which starts the fragment.
1259
+ #
1260
+ # @param [String] uri The expanded URI.
1261
+ #
1262
+ # @return [String] The URI with any later "#" encoded as "%23".
1263
+ def encode_later_number_signs(uri)
1264
+ start = uri.index('#')
1265
+ return uri unless start
1266
+ uri[0..start] + uri[(start + 1)..-1].gsub('#', '%23')
1267
+ end
1268
+
1269
+ ##
1270
+ # Builds a regular expression for a non-ASCII character, as it is or
1271
+ # pct-encoded in either case.
1272
+ #
1273
+ # @param [String] character The character.
1274
+ #
1275
+ # @return [String] The regular expression source.
1276
+ def either_form(character)
1277
+ encoded = Addressable::URI.encode_component(character, LITERAL_ENCODE)
1278
+ "(?:#{Regexp.escape(character)}|(?i:#{encoded}))"
1279
+ end
1280
+
1281
+ ##
1282
+ # Builds a regular expression for literal text. A non-ASCII character,
1283
+ # written as it is or as pct-encoded UTF-8, matches either way, since
1284
+ # expansion pct-encodes it (RFC 6570 section 3.1). So does a "#" that
1285
+ # expansion may have encoded because a fragment had already started.
1286
+ #
1287
+ # @param [String] literal The literal text.
1288
+ # @param [TrueClass, FalseClass] fragment
1289
+ # Whether a fragment may have started before the literal.
1290
+ #
1291
+ # @return [String] The regular expression source.
1292
+ def literal_regexp(literal, fragment = false)
1293
+ literal.scan(LITERAL_TOKEN).map do |token|
1294
+ if token == '#'
1295
+ source = fragment ? NUMBER_SIGN_EITHER_FORM : '\\#'
1296
+ fragment = true
1297
+ source
1298
+ elsif token =~ LITERAL_ENCODE
1299
+ token.each_char.map { |character| either_form(character) }.join
1300
+ elsif token.length > 3 || token =~ /\A%[89A-Fa-f]/
1301
+ decoded = Addressable::URI.unencode_component(token).dup
1302
+ decoded.force_encoding(Encoding::UTF_8)
1303
+ if decoded.valid_encoding?
1304
+ decoded.each_char.map { |character| either_form(character) }.join
1305
+ else
1306
+ "(?i:#{Regexp.escape(token)})"
1307
+ end
1308
+ else
1309
+ Regexp.escape(token)
1310
+ end
1311
+ end.join
1312
+ end
1313
+
1314
+ ##
1315
+ # Takes the first characters of a value for a prefix modifier. Reserved
1316
+ # and fragment expansion count a pct-encoded triplet as one character,
1317
+ # so that it isn't split (RFC 6570 section 2.4.1).
1318
+ #
1319
+ # @param [String] value The value
1320
+ # @param [Integer] length The maximum number of characters
1321
+ # @param [Boolean] allow_reserved Whether pct-encoded triplets are kept
1322
+ #
1323
+ # @return [String] The prefix
1324
+ def prefix(value, length, allow_reserved)
1325
+ value = value.to_str
1326
+ return value[0...length] unless allow_reserved
1327
+ return value.scan(PCT_ENCODED_OR_CHARACTER).first(length).join if
1328
+ value.valid_encoding?
1329
+ # A regular expression can't scan text that isn't valid UTF-8, but its
1330
+ # characters can be read one at a time, each invalid byte as one.
1331
+ hex = lambda do |character|
1332
+ character && character.bytesize == 1 &&
1333
+ HEX_DIGITS.include?(character.getbyte(0))
736
1334
  end
1335
+ characters = value.each_char.to_a
1336
+ tokens = []
1337
+ until characters.empty? || tokens.size == length
1338
+ if characters[0] == "%" && hex.call(characters[1]) &&
1339
+ hex.call(characters[2])
1340
+ tokens << characters.shift(3).join
1341
+ else
1342
+ tokens << characters.shift
1343
+ end
1344
+ end
1345
+ tokens.join
1346
+ end
1347
+
1348
+ ##
1349
+ # Drops the undefined (nil) members of a list or associative array value.
1350
+ # RFC 6570 treats a list or associative array with no defined members as
1351
+ # undefined, as it does nil.
1352
+ #
1353
+ # @param [Object] value The mapped value
1354
+ #
1355
+ # @return [Object, nil] The value without its undefined members, or nil
1356
+ # if the value is undefined
1357
+ def defined_value(value)
1358
+ value = if value.kind_of?(Hash)
1359
+ value.reject { |_, member| member.nil? }
1360
+ elsif value.respond_to?(:to_ary)
1361
+ value.to_ary.reject { |member| member.nil? }
1362
+ else
1363
+ value
1364
+ end
1365
+ value unless value == {} || value == []
737
1366
  end
738
1367
 
739
1368
  ##
@@ -767,8 +1396,8 @@ module Addressable
767
1396
  _, operator, varlist = *capture.match(EXPRESSION)
768
1397
  return_value = varlist.split(',').inject([]) do |acc, varspec|
769
1398
  _, name, modifier = *varspec.match(VARSPEC)
770
- value = mapping[name]
771
- unless value == nil || value == {}
1399
+ value = defined_value(mapping[name])
1400
+ unless value.nil?
772
1401
  allow_reserved = %w(+ #).include?(operator)
773
1402
  # Common primitives where the .to_s output is well-defined
774
1403
  if Numeric === value || Symbol === value ||
@@ -782,22 +1411,27 @@ module Addressable
782
1411
  raise TypeError,
783
1412
  "Can't convert #{value.class} into String or Array."
784
1413
  end
1414
+ # RFC 6570 section 2.4.1
1415
+ if length && (Hash === value || value.respond_to?(:to_ary))
1416
+ raise InvalidTemplateValueError,
1417
+ "The prefix modifier #{modifier} can't be applied to the " \
1418
+ "list or associative array #{name.inspect}."
1419
+ end
785
1420
 
786
1421
  value = normalize_value(value) if normalize_values
787
1422
 
788
1423
  if processor == nil || !processor.respond_to?(:transform)
789
1424
  # Handle percent escaping
790
1425
  if allow_reserved
791
- encode_map =
792
- Addressable::URI::CharacterClasses::RESERVED +
793
- Addressable::URI::CharacterClasses::UNRESERVED
1426
+ encode_map = RESERVED_ENCODE
794
1427
  else
795
1428
  encode_map = Addressable::URI::CharacterClasses::UNRESERVED
796
1429
  end
797
1430
  if value.kind_of?(Array)
798
1431
  transformed_value = value.map do |val|
799
1432
  if length
800
- Addressable::URI.encode_component(val[0...length], encode_map)
1433
+ Addressable::URI.encode_component(
1434
+ prefix(val, length, allow_reserved), encode_map)
801
1435
  else
802
1436
  Addressable::URI.encode_component(val, encode_map)
803
1437
  end
@@ -827,7 +1461,7 @@ module Addressable
827
1461
  else
828
1462
  if length
829
1463
  transformed_value = Addressable::URI.encode_component(
830
- value[0...length], encode_map)
1464
+ prefix(value, length, allow_reserved), encode_map)
831
1465
  else
832
1466
  transformed_value = Addressable::URI.encode_component(
833
1467
  value, encode_map)
@@ -851,7 +1485,10 @@ module Addressable
851
1485
  end
852
1486
  end
853
1487
  end
854
- acc << [name, transformed_value]
1488
+ # A list or associative array with a member isn't empty, even if
1489
+ # its members join to an empty string (RFC 6570 section 3.2.7).
1490
+ composite = Hash === value || value.respond_to?(:to_ary)
1491
+ acc << [name, transformed_value, composite]
855
1492
  end
856
1493
  acc
857
1494
  end
@@ -885,13 +1522,18 @@ module Addressable
885
1522
  end
886
1523
  }.join(joiner)
887
1524
  when ';'
888
- return_value.map{|k,v|
1525
+ # An empty member or pair value gets no "=" (RFC 6570 appendix A).
1526
+ # Values are pct-encoded, so a pair that ends in "=" is empty.
1527
+ return_value.map{|k,v,composite|
889
1528
  if v.is_a?(Array) && v.first =~ /=/
890
- ';' + v.join(";")
1529
+ ';' + v.map{|pair| pair.end_with?('=') ? pair[0...-1] : pair}.
1530
+ join(";")
891
1531
  elsif v.is_a?(Array)
892
- ';' + v.map{|inner_value| "#{k}=#{inner_value}"}.join(";")
1532
+ ';' + v.map{|inner_value|
1533
+ inner_value == '' ? k : "#{k}=#{inner_value}"
1534
+ }.join(";")
893
1535
  else
894
- v && v != '' ? ";#{k}=#{v}" : ";#{k}"
1536
+ (v && v != '') || composite ? ";#{k}=#{v}" : ";#{k}"
895
1537
  end
896
1538
  }.join
897
1539
  else
@@ -904,7 +1546,8 @@ module Addressable
904
1546
  # operator.
905
1547
  #
906
1548
  # @param [Hash, Array, String] value
907
- # Normalizes unicode keys and values with String#unicode_normalize (NFC)
1549
+ # Normalizes unicode keys and values to NFC, leaving a run of more than
1550
+ # 30 combining marks as it is
908
1551
  #
909
1552
  # @return [Hash, Array, String] The normalized values
910
1553
  def normalize_value(value)
@@ -918,23 +1561,134 @@ module Addressable
918
1561
  }
919
1562
  else
920
1563
  value = value.to_s if !value.kind_of?(String)
921
- if value.encoding != Encoding::UTF_8
922
- value = value.dup.force_encoding(Encoding::UTF_8)
1564
+ value = utf8_value(value)
1565
+ # Text that isn't valid UTF-8 can't be normalized; its bytes are
1566
+ # pct-encoded as they are.
1567
+ if value.valid_encoding?
1568
+ value = UnicodeNormalization.normalize(value, :nfc)
923
1569
  end
924
- value = value.unicode_normalize(:nfc)
925
1570
  end
926
1571
  value
927
1572
  end
928
1573
 
929
1574
  ##
930
- # Generates a hash with string keys
1575
+ # A value as UTF-8. RFC 6570 section 3.2.1 transcodes a value in another
1576
+ # character encoding to UTF-8. A binary or US-ASCII value, or one that
1577
+ # isn't valid in its own encoding, is read as UTF-8 as it is.
1578
+ #
1579
+ # @param [String] value The value.
1580
+ #
1581
+ # @return [String] The value in UTF-8, which may not be valid UTF-8.
1582
+ def utf8_value(value)
1583
+ encoding = value.encoding
1584
+ return value if encoding == Encoding::UTF_8
1585
+ if encoding != Encoding::BINARY && encoding != Encoding::US_ASCII &&
1586
+ value.valid_encoding?
1587
+ begin
1588
+ return value.encode(Encoding::UTF_8)
1589
+ rescue EncodingError
1590
+ # A character with no Unicode equivalent keeps its bytes.
1591
+ end
1592
+ end
1593
+ value.dup.force_encoding(Encoding::UTF_8)
1594
+ end
1595
+
1596
+ ##
1597
+ # Splits the text an expression matched among its variables, when
1598
+ # more than one split would expand to it. RFC 6570 doesn't say which
1599
+ # split to choose, so each variable, from the first, takes as much as it
1600
+ # can: an exploded variable every member left, and any other variable
1601
+ # one member, except that the last variable of a + or # expression,
1602
+ # whose values may contain commas, takes the rest. A variable with
1603
+ # nothing left is undefined. So {/a*,b} reads /x/y as a = ["x", "y"]
1604
+ # and {/a,b*} reads /x/y/z as a = "x" and b = ["y", "z"].
1605
+ #
1606
+ # @return [Array, nil] Each variable's unparsed value, or nil for an
1607
+ # operator whose values aren't split by position, an expression that
1608
+ # repeats a name, or when the variables can't take every member.
1609
+ def split_from_left(operator, varspecs, matched, index)
1610
+ return nil unless [nil, '+', '#', '/', '.'].include?(operator)
1611
+ # A name used twice must have one value; that isn't split here.
1612
+ names = varspecs.map { |varspec| varspec[VARSPEC, 1] }
1613
+ return nil if names.uniq.size < names.size
1614
+ groups = ((index + 1)..(index + varspecs.size)).select do |group|
1615
+ matched[group]
1616
+ end
1617
+ return nil if groups.empty?
1618
+ joiner = JOINERS.fetch(operator, ',')
1619
+ text = matched.string[matched.begin(groups.first)...matched.end(groups.last)]
1620
+ members = text.split(joiner, -1)
1621
+ members = [''] if members.empty?
1622
+ last = varspecs.size - 1
1623
+ values = varspecs.each_with_index.map do |varspec, position|
1624
+ if members.empty?
1625
+ nil
1626
+ elsif varspec[VARSPEC, 2] == '*'
1627
+ members.slice!(0..-1)
1628
+ elsif position == last && (operator == '+' || operator == '#')
1629
+ members.slice!(0..-1).join(joiner)
1630
+ else
1631
+ members.shift
1632
+ end
1633
+ end
1634
+ members.empty? ? values : nil
1635
+ end
1636
+
1637
+ ##
1638
+ # Whether a URI's text is valid UTF-8, read as UTF-8 whatever its
1639
+ # encoding, as Addressable::URI reads it.
1640
+ #
1641
+ # @param [Addressable::URI, #to_str] uri The URI.
1642
+ #
1643
+ # @return [TrueClass, FalseClass]
1644
+ def valid_utf8?(uri)
1645
+ return true unless uri.respond_to?(:to_str)
1646
+ text = uri.to_str
1647
+ text = text.dup.force_encoding(Encoding::UTF_8) unless
1648
+ text.encoding == Encoding::UTF_8
1649
+ text.valid_encoding?
1650
+ end
1651
+
1652
+ ##
1653
+ # Picks the mapping to expand with: the one passed, or the block.
1654
+ #
1655
+ # @param [Object] mapping The mapping argument
1656
+ # @param [Proc, nil] block The block
1657
+ #
1658
+ # @return [Hash, MappingLookup] The normalized mapping
1659
+ def resolve_mapping(mapping, block)
1660
+ if block
1661
+ unless mapping.equal?(NO_MAPPING) || mapping.nil?
1662
+ raise ArgumentError, "Pass a mapping or a block, not both."
1663
+ end
1664
+ return normalize_keys(block)
1665
+ end
1666
+ if mapping.equal?(NO_MAPPING)
1667
+ raise ArgumentError, "A mapping or a block is required."
1668
+ end
1669
+ normalize_keys(mapping)
1670
+ end
1671
+
1672
+ ##
1673
+ # Generates a hash with string keys, or a lookup for a mapping that isn't
1674
+ # enumerable
931
1675
  #
932
- # @param [Hash] mapping A mapping hash to normalize
1676
+ # @param [Hash, #each_pair, #inject, #[]] mapping A mapping to normalize
933
1677
  #
934
- # @return [Hash]
935
- # A hash with stringified keys
1678
+ # @return [Hash, MappingLookup]
1679
+ # A hash with stringified keys, or a lookup
936
1680
  def normalize_keys(mapping)
937
- return mapping.inject({}) do |accu, pair|
1681
+ if mapping.respond_to?(:each_pair)
1682
+ pairs = mapping.to_enum(:each_pair)
1683
+ elsif mapping.respond_to?(:inject)
1684
+ pairs = mapping
1685
+ elsif mapping.respond_to?(:[]) && !mapping.respond_to?(:to_str) &&
1686
+ !(Symbol === mapping) && !(Numeric === mapping)
1687
+ return MappingLookup.new(mapping)
1688
+ else
1689
+ raise TypeError, "Can't convert #{mapping.class} into a mapping."
1690
+ end
1691
+ return pairs.inject({}) do |accu, pair|
938
1692
  name, value = pair
939
1693
  if Symbol === name
940
1694
  name = name.to_s
@@ -949,6 +1703,182 @@ module Addressable
949
1703
  end
950
1704
  end
951
1705
 
1706
+ ##
1707
+ # The pair that a ;, ? or & variable that isn't exploded can match: one
1708
+ # of the names of the expression's variables that aren't exploded, then
1709
+ # "=" and the value. A ; variable's empty value is written as the name
1710
+ # alone. With processor patterns, each name's value is matched with its
1711
+ # own variable's pattern.
1712
+ #
1713
+ # @param [String] operator The expression's operator.
1714
+ # @param [Array<String>] varspecs The expression's varspecs.
1715
+ # @param [Array<String, nil>] results The processor patterns, by varspec.
1716
+ #
1717
+ # @return [String, nil] The regular expression source, or nil if every
1718
+ # variable is exploded.
1719
+ def named_pair_source(operator, varspecs, results)
1720
+ choices = {}
1721
+ varspecs.each_with_index do |varspec, position|
1722
+ next if varspec[VARSPEC, 2] == '*'
1723
+ name = varspec[VARSPEC, 1]
1724
+ choices[name] = results[position] unless choices.key?(name)
1725
+ end
1726
+ return nil if choices.empty?
1727
+ value = "#{UNRESERVED}*?"
1728
+ # A longer name is tried first, so a name isn't taken for the start of
1729
+ # a longer one.
1730
+ choices = choices.sort_by { |name, _| -name.size }
1731
+ if results.compact.empty?
1732
+ names = choices.map { |name, _| named_variable_source(name) }
1733
+ names = "(?:#{names.join('|')})"
1734
+ if operator == ';'
1735
+ "#{names}(?:=#{value})?"
1736
+ else
1737
+ "#{names}=#{value}"
1738
+ end
1739
+ else
1740
+ pairs = choices.map do |name, result|
1741
+ source = named_variable_source(name)
1742
+ pair = "#{source}=(?:#{result || value})"
1743
+ if operator == ';' &&
1744
+ (result.nil? || Regexp.new("\\A(?:#{result})\\z") =~ "")
1745
+ pair += "|#{source}"
1746
+ end
1747
+ pair
1748
+ end
1749
+ "(?:#{pairs.join('|')})"
1750
+ end
1751
+ end
1752
+
1753
+ ##
1754
+ # A variable's name as ;, ? and & expansion writes it, as a regular
1755
+ # expression source. Its pct-encoded triplets match in either case.
1756
+ #
1757
+ # @param [String] name The variable name.
1758
+ #
1759
+ # @return [String] The regular expression source.
1760
+ def named_variable_source(name)
1761
+ name.scan(/%[0-9A-Fa-f]{2}|[^%]+/).map do |part|
1762
+ part.start_with?('%') ? "(?i:#{Regexp.escape(part)})" : Regexp.escape(part)
1763
+ end.join
1764
+ end
1765
+
1766
+ ##
1767
+ # A variable's name with its pct-encoded triplets in upper case, so that
1768
+ # names written with either case compare equal.
1769
+ #
1770
+ # @param [String] name The variable name.
1771
+ #
1772
+ # @return [String] The name.
1773
+ def canonical_name(name)
1774
+ name.gsub(/%[0-9A-Fa-f]{2}/) { |triplet| triplet.upcase }
1775
+ end
1776
+
1777
+ ##
1778
+ # The values of a ;, ? or & expression's variables. A pair with the name
1779
+ # of one of the expression's variables that aren't exploded is that
1780
+ # variable's, wherever it is, and an exploded variable gets the others.
1781
+ # Each name is only given as many times as the expression has it.
1782
+ #
1783
+ # @param [String] operator The expression's operator.
1784
+ # @param [Array<String>] varspecs The expression's varspecs.
1785
+ # @param [Array<String, nil>] captures The text each variable matched.
1786
+ # @param [Array<String, nil>] results The processor patterns, by varspec.
1787
+ #
1788
+ # @return [Array, nil] The value for each varspec, or nil if a name is
1789
+ # given too many times or a value doesn't match its pattern.
1790
+ def named_values(operator, varspecs, captures, results)
1791
+ places = {}
1792
+ varspecs.each_with_index do |varspec, position|
1793
+ next if varspec[VARSPEC, 2] == '*'
1794
+ (places[canonical_name(varspec[VARSPEC, 1])] ||= []) << position
1795
+ end
1796
+ values = Array.new(varspecs.size)
1797
+ taken = Hash.new(0)
1798
+ give = lambda do |name, value|
1799
+ key = canonical_name(name)
1800
+ positions = places[key]
1801
+ return false unless positions && taken[key] < positions.size
1802
+ values[positions[taken[key]]] = value
1803
+ taken[key] += 1
1804
+ true
1805
+ end
1806
+ joiner = Regexp.escape(JOINERS[operator])
1807
+ names = varspecs.reject { |varspec| varspec[VARSPEC, 2] == '*' }.map do |varspec|
1808
+ named_variable_source(varspec[VARSPEC, 1])
1809
+ end.uniq
1810
+ # A pair starts after a joiner that one of the names follows.
1811
+ pair_start = /#{joiner}(?=(?:#{names.join('|')})(?:=|#{joiner}|\z))/
1812
+ varspecs.each_with_index do |varspec, position|
1813
+ capture = captures[position]
1814
+ # The run of pairs is in the first such variable's place, and the
1815
+ # others match nothing.
1816
+ next if capture.nil? || capture.empty? || varspec[VARSPEC, 2] == '*'
1817
+ capture.split(pair_start).each do |pair|
1818
+ name, value = pair.split('=', 2)
1819
+ return nil unless give.call(name, value || "")
1820
+ end
1821
+ end
1822
+ varspecs.each_with_index do |varspec, position|
1823
+ capture = captures[position]
1824
+ next if capture.nil? || varspec[VARSPEC, 2] != '*'
1825
+ pairs = {}
1826
+ claimed = false
1827
+ capture.split(JOINERS[operator]).each do |pair|
1828
+ key, value = pair.split('=', 2)
1829
+ value ||= ""
1830
+ # An empty member has no name, so it stays the exploded variable's.
1831
+ positions = key && places[canonical_name(key)]
1832
+ if positions
1833
+ # A value in an exploded variable's place is checked against
1834
+ # its own variable's pattern, as it is in its own place.
1835
+ pattern = results[positions.first]
1836
+ return nil if pattern && value !~ /\A(?:#{pattern})\z/
1837
+ return nil unless give.call(key, value)
1838
+ claimed = true
1839
+ else
1840
+ pairs[key] = value
1841
+ end
1842
+ end
1843
+ values[position] = claimed && pairs.empty? ? nil : pairs
1844
+ end
1845
+ values
1846
+ end
1847
+
1848
+ ##
1849
+ # The name of the regular expression group for a variable. A group name
1850
+ # can't start with a digit, which a variable name can (RFC 6570 section
1851
+ # 2.3), so such a name gets a leading ".". No variable name starts with
1852
+ # ".", so this can't collide with another variable's group. Ruby 2.3 and
1853
+ # earlier only allow a letter or "_" as the first character, so there a
1854
+ # name that starts with a digit or a pct-encoded triplet is wrapped in
1855
+ # "__" instead.
1856
+ #
1857
+ # @param [String] name The variable name.
1858
+ #
1859
+ # @return [String] The group name.
1860
+ def capture_name(name)
1861
+ if GROUP_NAME_CAN_START_WITH_DOT
1862
+ name =~ /\A[0-9]/ ? ".#{name}" : name
1863
+ else
1864
+ name =~ /\A[A-Za-z_]/ ? name : "__#{name}__"
1865
+ end
1866
+ end
1867
+
1868
+ ##
1869
+ # The variable name for a regular expression group name.
1870
+ #
1871
+ # @param [String] group The group name.
1872
+ #
1873
+ # @return [String] The variable name.
1874
+ def variable_name(group)
1875
+ if GROUP_NAME_CAN_START_WITH_DOT
1876
+ group.start_with?(".") ? group[1..-1] : group
1877
+ else
1878
+ group =~ /\A__([^A-Za-z_].*)__\z/m ? $1 : group
1879
+ end
1880
+ end
1881
+
952
1882
  ##
953
1883
  # Generates the <tt>Regexp</tt> that parses a template pattern. Memoizes the
954
1884
  # value if template processor not set (processors may not be deterministic)
@@ -973,25 +1903,139 @@ module Addressable
973
1903
  #
974
1904
  # @param [String] escaped_pattern The escaped URI template pattern.
975
1905
  #
976
- # @return [Array<Array>] For each expression, the <tt>MatchData</tt> of
977
- # the expression directly after it (or <tt>nil</tt>), and whether the
978
- # text after it could start with a comma.
1906
+ # @return [Array<Array>] For each expression, the expression directly
1907
+ # after it (or <tt>nil</tt>), as an array of the expression, its
1908
+ # operator and its variable list, and whether the text after it could
1909
+ # start with a comma.
979
1910
  def expression_followers(escaped_pattern)
980
- expressions = escaped_pattern.to_enum(:scan, EXPRESSION).map do
981
- Regexp.last_match
982
- end
983
- expressions.each_with_index.map do |current, index|
984
- following = expressions[index + 1]
985
- following = nil unless following && following.begin(0) == current.end(0)
986
- # Expressions can match nothing, so look past any that can't start
987
- # with a comma.
988
- position = current.end(0)
989
- comma = expressions[(index + 1)..-1].any? do |later|
990
- break false unless later.begin(0) == position
991
- position = later.end(0)
992
- may_start_with_comma?(later[1], later[2])
1911
+ # StringScanner works in byte offsets; character offsets would make
1912
+ # this quadratic for a pattern with non-ASCII characters.
1913
+ scanner = StringScanner.new(escaped_pattern)
1914
+ expressions = []
1915
+ while scanner.skip_until(EXPRESSION)
1916
+ finish = scanner.pos
1917
+ expressions << [
1918
+ [scanner[0], scanner[1], scanner[2]],
1919
+ finish - scanner.matched_size,
1920
+ finish
1921
+ ]
1922
+ end
1923
+ # Expressions can match nothing, so the text after an expression could
1924
+ # start with a comma if the expression directly after it could, or if
1925
+ # the text after that one could. Working backwards, each answer comes
1926
+ # from the next one, which keeps this linear for a long run of
1927
+ # expressions.
1928
+ followers = Array.new(expressions.size)
1929
+ comma = false
1930
+ (expressions.size - 1).downto(0) do |index|
1931
+ current_end = expressions[index][2]
1932
+ following, following_start, _ = expressions[index + 1]
1933
+ if following && following_start == current_end
1934
+ comma ||= may_start_with_comma?(following[1], following[2])
1935
+ else
1936
+ following = nil
1937
+ comma = escaped_pattern.byteslice(current_end, 1) == ','
993
1938
  end
994
- [following, comma || escaped_pattern[position] == ',']
1939
+ followers[index] = [following, comma]
1940
+ end
1941
+ followers
1942
+ end
1943
+
1944
+ ##
1945
+ # Whether a label expression's value can contain ".". Label expansion
1946
+ # leaves a "." in a value as it is (RFC 6570 section 3.2.5), so where the
1947
+ # value ends is only known where the expression is delimited by the start
1948
+ # or end of the URI or by characters that can't be part of its expansion
1949
+ # (section 1.4): a lone, unexploded variable, with a reserved character
1950
+ # in the literal text since the previous expression, and a reserved
1951
+ # character next, after any expressions that start with one when they
1952
+ # aren't empty. A "#" counts only if a fragment can't have started
1953
+ # before it, since expansion encodes a later one as "%23".
1954
+ #
1955
+ # @param [Integer] index The expression's index.
1956
+ # @param [Array<String>] expressions The pattern's expressions.
1957
+ # @param [Array<String>] literals
1958
+ # The literal text before each expression, and after the last one.
1959
+ # @param [Array<TrueClass, FalseClass>] either_leader
1960
+ # Whether a fragment may have started before each expression.
1961
+ # @param [Array<TrueClass, FalseClass>] either_literal
1962
+ # Whether a fragment may have started before each literal.
1963
+ #
1964
+ # @return [TrueClass, FalseClass]
1965
+ def label_takes_dots?(index, expressions, literals, either_leader,
1966
+ either_literal)
1967
+ _, operator, varlist = *expressions[index].match(EXPRESSION)
1968
+ return false unless operator == '.' && varlist =~ VARSPEC && $2 != '*'
1969
+ return false unless index == 0 || literals[index] =~ LABEL_DELIMITER
1970
+ position = index + 1
1971
+ while position < expressions.size && literals[position].empty?
1972
+ operator = expressions[position][1]
1973
+ return false unless "/?&;".include?(operator) ||
1974
+ (operator == '#' && !either_leader[position])
1975
+ position += 1
1976
+ end
1977
+ literal = literals[position]
1978
+ return true if literal.empty?
1979
+ literal[0] =~ LABEL_DELIMITER &&
1980
+ !(literal[0] == '#' && either_literal[position]) ? true : false
1981
+ end
1982
+
1983
+ ##
1984
+ # Whether the text after an expression could start with a character.
1985
+ #
1986
+ # @param [Integer] index The expression's index.
1987
+ # @param [String] character The character.
1988
+ # @param [Array<String>] expressions The pattern's expressions.
1989
+ # @param [Array<String>] literals
1990
+ # The literal text before each expression, and after the last one.
1991
+ #
1992
+ # @return [TrueClass, FalseClass]
1993
+ def may_follow_with?(index, character, expressions, literals)
1994
+ position = index + 1
1995
+ loop do
1996
+ literal = literals[position]
1997
+ return literal.start_with?(character) unless literal.empty?
1998
+ return false if position == expressions.size
1999
+ operator = expressions[position][EXPRESSION, 1]
2000
+ leader = LEADERS.fetch(operator, '')
2001
+ if leader.empty?
2002
+ return true if may_contain?(expressions[position], character)
2003
+ elsif leader == character || (operator == '#' && character == '%')
2004
+ return true
2005
+ end
2006
+ # The expression can match nothing.
2007
+ position += 1
2008
+ end
2009
+ end
2010
+
2011
+ ##
2012
+ # Whether what follows an expression always starts with a character that
2013
+ # a + or # member can contain, other than a comma: literal text that
2014
+ # does, after expressions that are empty or start with a leader, or with
2015
+ # characters other than a comma. The URI can't end there.
2016
+ #
2017
+ # @param [Integer] index The expression's index.
2018
+ # @param [Array<String>] expressions The pattern's expressions.
2019
+ # @param [Array<String>] literals
2020
+ # The literal text before each expression, and after the last one.
2021
+ #
2022
+ # @return [TrueClass, FalseClass]
2023
+ def members_follow?(index, expressions, literals)
2024
+ position = index + 1
2025
+ loop do
2026
+ literal = literals[position]
2027
+ unless literal.empty?
2028
+ return literal =~ /\A#{RESERVED}/ && literal[0] != ',' ? true : false
2029
+ end
2030
+ return false if position == expressions.size
2031
+ expression = expressions[position]
2032
+ # A leader is a member's character. Without one, the expression can
2033
+ # start with any character it can contain.
2034
+ if LEADERS.fetch(expression[EXPRESSION, 1], '').empty?
2035
+ return false if may_contain?(expression, ',')
2036
+ end
2037
+ # The expression can also be empty.
2038
+ position += 1
995
2039
  end
996
2040
  end
997
2041
 
@@ -1011,7 +2055,8 @@ module Addressable
1011
2055
  # Whether an expression, followed directly by another one, could only
1012
2056
  # match characters that the other one could also match, in any amount.
1013
2057
  #
1014
- # @param [MatchData] following The expression that follows.
2058
+ # @param [Array] following
2059
+ # The expression that follows, its operator and its variable list.
1015
2060
  # @param [String, nil] operator The operator of the first expression.
1016
2061
  # @param [Array<String>] varspecs The varspecs of the first expression.
1017
2062
  #
@@ -1039,54 +2084,1028 @@ module Addressable
1039
2084
  end
1040
2085
  end
1041
2086
 
2087
+ ##
2088
+ # Whether an expression's expansion can contain a character.
2089
+ #
2090
+ # @param [String] expression The expression.
2091
+ # @param [String] character The character.
2092
+ #
2093
+ # @return [TrueClass, FalseClass]
2094
+ def may_contain?(expression, character)
2095
+ # Any expansion can contain a pct-encoded triplet, and matching accepts
2096
+ # a non-ASCII character as it is.
2097
+ return true if character == '%' || character =~ LITERAL_ENCODE
2098
+ contained_characters(expression).include?(character)
2099
+ end
2100
+
2101
+ ##
2102
+ # The characters of TEXT_CHARACTERS that an expression's expansion can
2103
+ # contain.
2104
+ #
2105
+ # @param [String] expression The expression.
2106
+ #
2107
+ # @return [Array<String>]
2108
+ def contained_characters(expression)
2109
+ _, operator, varlist = *expression.match(EXPRESSION)
2110
+ # A joiner only comes between values.
2111
+ CONTAINED_CHARACTERS.fetch([operator, varlist =~ /[,*]/ ? true : false])
2112
+ end
2113
+
2114
+ ##
2115
+ # The characters of TEXT_CHARACTERS that any of some expressions'
2116
+ # expansions can contain.
2117
+ #
2118
+ # @param [Array<String>] expressions The expressions.
2119
+ #
2120
+ # @return [Array<String>]
2121
+ def characters_in(expressions)
2122
+ # Expressions of the same kind share one set.
2123
+ expressions.map { |expression| contained_characters(expression) }.
2124
+ uniq(&:object_id).inject([], :|)
2125
+ end
2126
+
2127
+ ##
2128
+ # The characters of TEXT_CHARACTERS that match a regexp source for one
2129
+ # character.
2130
+ #
2131
+ # @param [String] group The source.
2132
+ #
2133
+ # @return [Array<String>]
2134
+ def group_characters(group)
2135
+ GROUP_CHARACTERS.fetch(group) do
2136
+ TEXT_CHARACTERS.select { |c| c =~ /\A#{group}\z/ }
2137
+ end
2138
+ end
2139
+
2140
+ ##
2141
+ # Splits a template pattern into its expressions and the literal text
2142
+ # around them, with the regular expression for each literal. Once a
2143
+ # fragment may have started, expansion encodes a later "#" as "%23", so
2144
+ # the literals and fragment expressions after that point match it either
2145
+ # way. Reserved and fragment expansion may start a fragment.
2146
+ #
2147
+ # @param [String] pattern The URI template pattern.
2148
+ #
2149
+ # @return [Array]
2150
+ # The pattern with its literals escaped, its expressions, its
2151
+ # literals (the text before each expression, and after the last one),
2152
+ # their regular expression sources, and whether a fragment may have
2153
+ # started before each expression and before each literal.
2154
+ def template_parts(pattern)
2155
+ fragment = false
2156
+ either_leader = []
2157
+ literals = []
2158
+ either_literal = []
2159
+ expressions = []
2160
+ literal_sources = []
2161
+ escaped_pattern = map_literals(pattern) do |literal, expression|
2162
+ literals << literal
2163
+ either_literal << fragment
2164
+ source = literal_regexp(literal, fragment)
2165
+ literal_sources << source
2166
+ fragment ||= literal.include?('#')
2167
+ if expression
2168
+ expressions << expression
2169
+ either_leader << fragment
2170
+ fragment ||= expression =~ /\A\{[+#]/ ? true : false
2171
+ end
2172
+ source
2173
+ end
2174
+ [escaped_pattern, expressions, literals, literal_sources, either_leader,
2175
+ either_literal]
2176
+ end
2177
+
2178
+ ##
2179
+ # The characters such that text made of one can be put in front of an
2180
+ # expression's value, so that the expression matches it and everything
2181
+ # after it the same way.
2182
+ #
2183
+ # @param [String] expression The expression.
2184
+ # @param [Array<String>] characters The characters to check.
2185
+ #
2186
+ # @return [Array<String>] Those of the characters that can.
2187
+ def absorbed(expression, characters)
2188
+ _, operator, varlist = *expression.match(EXPRESSION)
2189
+ return [] unless operator.nil? || operator == '+'
2190
+ varspecs = varlist.split(',')
2191
+ exploded = varspecs.first[VARSPEC, 2] == '*'
2192
+ # Text in front of a lone exploded value becomes part of its first
2193
+ # member, or, with a comma, members of their own. A + member takes
2194
+ # every character it can, so it couldn't end where it did, unless
2195
+ # only unexploded variables follow it: the text up to its last comma
2196
+ # then becomes members, and the rest becomes part of the next value.
2197
+ return [] if exploded && !(operator.nil? && varspecs.size == 1) &&
2198
+ !(varspecs.size > 1 &&
2199
+ varspecs.drop(1).none? { |varspec| varspec[VARSPEC, 2] == '*' })
2200
+ # The first of several + variables takes every character it can, or
2201
+ # is skipped, so text in front of it would be taken past where the
2202
+ # value ended.
2203
+ return [] if operator == '+' && !exploded && varspecs.size > 1
2204
+ group = group_characters(operator ? RESERVED : UNRESERVED).join
2205
+ characters.select do |character|
2206
+ if character == ',' && (exploded || varspecs.size > 1)
2207
+ # A comma would end the first of several variables.
2208
+ exploded
2209
+ else
2210
+ group.include?(character) || character == '%' ||
2211
+ character =~ LITERAL_ENCODE
2212
+ end
2213
+ end
2214
+ end
2215
+
2216
+ ##
2217
+ # Whether an expression tries the places where it can end in order,
2218
+ # nearest first, as a lone variable of the default, +, #, / or .
2219
+ # operator does. In a block of such expressions, the first choice that
2220
+ # lets literal text match ends the block as early as any choice can.
2221
+ #
2222
+ # @param [String] expression The expression.
2223
+ #
2224
+ # @return [TrueClass, FalseClass]
2225
+ def ends_in_order?(expression)
2226
+ _, operator, varlist = *expression.match(EXPRESSION)
2227
+ [nil, '+', '#', '/', '.'].include?(operator) &&
2228
+ varlist =~ VARSPEC && $2 != '*' ? true : false
2229
+ end
2230
+
2231
+ # Characters that a template's text can contain, other than those that
2232
+ # every expression can.
2233
+ TEXT_CHARACTERS = (("!".."~").to_a - ["%"]).freeze
2234
+ # The thread-local key of the cache for one template build.
2235
+ BUILD_CACHE = :__addressable_template_build
2236
+ # For each operator, including those RFC 6570 reserves, and whether the
2237
+ # expression can join several values, the characters of TEXT_CHARACTERS
2238
+ # that its expansion can contain.
2239
+ CONTAINED_CHARACTERS = [nil, *"+#./;?&=,!@|".chars].
2240
+ product([false, true]).each_with_object({}) do |(op, joins), table|
2241
+ reserved = op == '+' || op == '#'
2242
+ others = [LEADERS.fetch(op, ''),
2243
+ joins ? JOINERS.fetch(op, ',') : '',
2244
+ op && ";?&".include?(op) ? '=' : ''].join
2245
+ table[[op, joins]] = TEXT_CHARACTERS.select do |character|
2246
+ (reserved &&
2247
+ character =~ /[#{Addressable::URI::CharacterClasses::RESERVED}]/) ||
2248
+ character =~ /[#{Addressable::URI::CharacterClasses::UNRESERVED}]/ ||
2249
+ others.include?(character)
2250
+ end.freeze
2251
+ end.freeze
2252
+ # The characters of TEXT_CHARACTERS that an operator's value can contain.
2253
+ GROUP_CHARACTERS = [RESERVED, UNRESERVED].each_with_object({}) do |group, table|
2254
+ table[group] =
2255
+ TEXT_CHARACTERS.select { |c| c =~ /\A#{group}\z/ }.freeze
2256
+ end.freeze
2257
+ private_constant :TEXT_CHARACTERS, :CONTAINED_CHARACTERS, :GROUP_CHARACTERS,
2258
+ :BUILD_CACHE
2259
+
2260
+ ##
2261
+ # Whether a regexp source is valid for the regular expression engine.
2262
+ #
2263
+ # @param [String] source The source.
2264
+ #
2265
+ # @return [TrueClass, FalseClass]
2266
+ def valid_regexp?(source)
2267
+ Regexp.new(source)
2268
+ true
2269
+ rescue RegexpError
2270
+ false
2271
+ end
2272
+
2273
+ ##
2274
+ # A lookahead that checks the end of the URI once: where literal text is
2275
+ # one character that nothing after it can contain, it's the last one in
2276
+ # the URI, so what follows it there must match the rest of the template.
2277
+ # Otherwise, a URI whose end doesn't match would be tried with every
2278
+ # choice before it. The last such literal text is used, so that the
2279
+ # rest is as short as possible.
2280
+ #
2281
+ # @param [Array<String>] expressions The pattern's expressions.
2282
+ # @param [Array<String>] literals
2283
+ # The literal text before each expression, and after the last one.
2284
+ # @param [Array<String>] literal_sources The regexp source of each literal.
2285
+ # @param [Array<String>] expression_sources The regexp source of each
2286
+ # expression.
2287
+ #
2288
+ # @return [String, nil] The lookahead's source, or nil if there's none.
2289
+ def tail_check(expressions, literals, literal_sources, expression_sources)
2290
+ (expressions.size - 2).downto(0) do |index|
2291
+ literal = literals[index + 1]
2292
+ next unless literal.size == 1 && TEXT_CHARACTERS.include?(literal) &&
2293
+ literal_sources[index + 1] == Regexp.escape(literal)
2294
+ outside, final =
2295
+ characters_after(index, expressions, literals, index + 2)
2296
+ next unless (outside - final_characters(final)).include?(literal)
2297
+ rest = ((index + 1)...expressions.size).map do |later|
2298
+ expression_sources[later] + literal_sources[later + 1]
2299
+ end.join
2300
+ # The rest is matched again in the template's own regexp, so its
2301
+ # groups don't capture here. The empty group keeps a group around a
2302
+ # single repetition from warning that it's redundant.
2303
+ rest = rest.gsub(/\(\?<(?![=!])[^>]*>/, '(?:(?:)')
2304
+ source = "(?=(?:#{character_set([literal], true)}*+" \
2305
+ "#{Regexp.escape(literal)})*+#{rest}\\z)"
2306
+ return source if valid_regexp?("\\A#{source}")
2307
+ end
2308
+ nil
2309
+ end
2310
+
2311
+ ##
2312
+ # A lookahead that checks the end of the URI once, where the template
2313
+ # ends with literal text and then an expression that starts with a
2314
+ # leader its values can't contain, and that can contain the literal
2315
+ # text's characters: the literal text must be followed by
2316
+ # a match of the expression that ends the URI, after the first place
2317
+ # where the literal text before it is. Otherwise, a URI whose end doesn't
2318
+ # match would be tried with every choice before it. Since each match of
2319
+ # the expression ends before the next leader, the check takes linear
2320
+ # time.
2321
+ #
2322
+ # @param [Array<String>] expressions The pattern's expressions.
2323
+ # @param [Array<String>] literals
2324
+ # The literal text before each expression, and after the last one.
2325
+ # @param [Array<String>] literal_sources The regexp source of each literal.
2326
+ # @param [Array<String>] expression_sources The regexp source of each
2327
+ # expression.
2328
+ #
2329
+ # @return [String, nil] The lookahead's source, or nil if there's none.
2330
+ def ending_check(expressions, literals, literal_sources,
2331
+ expression_sources)
2332
+ return nil if expressions.size < 2 || !literals.last.empty? ||
2333
+ literals[-2].empty?
2334
+ _, operator, varlist = *expressions.last.match(EXPRESSION)
2335
+ leader = LEADERS[operator]
2336
+ return nil unless leader
2337
+ # A value's character or a joiner that's the leader would let the
2338
+ # expression's matches overlap.
2339
+ values = group_characters(operator == '#' ? RESERVED : UNRESERVED)
2340
+ joiner = varlist =~ /[,*]/ ? JOINERS.fetch(operator, ',') : nil
2341
+ return nil if values.include?(leader) || joiner == leader
2342
+ # Otherwise, the expression's matches can't run past a place where the
2343
+ # literal text is, and nothing is gained.
2344
+ return nil unless (literals[-2].chars & TEXT_CHARACTERS).all? do |c|
2345
+ may_contain?(expressions.last, c)
2346
+ end
2347
+ rest = expression_sources.last.gsub(/\(\?<(?![=!])[^>]*>/, '(?:(?:)')
2348
+ earlier = (expressions.size - 2).downto(0).find do |index|
2349
+ !literals[index].empty?
2350
+ end
2351
+ # The first place where the earlier literal text is.
2352
+ first = earlier ? "(?>[\\s\\S]*?(?=#{literal_sources[earlier]}))" : ""
2353
+ # Its parts are all parts of the template's own regexp, so unlike a
2354
+ # lookbehind, it's always valid.
2355
+ "(?=#{first}[\\s\\S]*?#{literal_sources[-2]}#{rest}\\z)"
2356
+ end
2357
+
2358
+ ##
2359
+ # Lookaheads for a template with a block of expressions that doesn't
2360
+ # commit at the literal text after it. Without them, a URI that doesn't
2361
+ # match would be tried with every way of dividing the text before that
2362
+ # literal text among the block's values, each time matching the rest of
2363
+ # the template again. Both only check what every match has:
2364
+ #
2365
+ # * The literal text after the first expression, in order. Each is
2366
+ # found at its first place after the one before, which is no later
2367
+ # than where any match has it.
2368
+ # * After the literal text that follows the first block that doesn't
2369
+ # commit, the rest of the template, up to the end of the URI, from
2370
+ # some place where that literal text is. Each place is tried once.
2371
+ #
2372
+ # @param [Array<String>] expressions The pattern's expressions.
2373
+ # @param [Array<String>] literals
2374
+ # The literal text before each expression, and after the last one.
2375
+ # @param [Array<String>] literal_sources The regexp source of each literal.
2376
+ # @param [Array<String>] expression_sources The regexp source of each
2377
+ # expression.
2378
+ # @param [Array<Integer>] ends The indexes of the expressions that end
2379
+ # blocks.
2380
+ #
2381
+ # @return [String] The lookaheads' source, empty if there are none.
2382
+ def open_block_checks(expressions, literals, literal_sources,
2383
+ expression_sources, ends)
2384
+ open = (0...(expressions.size - 1)).find do |index|
2385
+ !ends.include?(index) && !literals[index + 1].empty?
2386
+ end
2387
+ return "" unless open
2388
+ # Each literal's place is found, and then matching moves past its first
2389
+ # character, so that the next is found after it.
2390
+ order = (1...literals.size).reject { |index| literals[index].empty? }.
2391
+ map { |index| "(?>[\\s\\S]*?(?=#{literal_sources[index]}))[\\s\\S]" }
2392
+ source = "(?=#{order.join})"
2393
+ # Only an exploded value in the block gives it more ways to divide the
2394
+ # text than the block's other checks bound, so only the order is
2395
+ # checked otherwise, and only where the literal text after the block
2396
+ # can be written two ways, as a "#" can be "%23": the block's values can
2397
+ # then end at either form, and divide the text before it in every way.
2398
+ start = (ends.select { |index| index < open }.max || -1) + 1
2399
+ unless expressions[start..open].any? { |e| e[EXPRESSION, 2].include?('*') }
2400
+ either = literal_sources[open + 1] != Regexp.escape(literals[open + 1])
2401
+ return either && valid_regexp?("\\A#{source}") ? source : ""
2402
+ end
2403
+ # The rest is matched from every place where the literal text is, so
2404
+ # it's checked only where matching itself would reach each of them: a
2405
+ # template that starts with a lone + value, which can take anything.
2406
+ # Where nothing before the literal text can contain its first
2407
+ # character, it's at the first place where that character is, so the
2408
+ # rest is matched only from there.
2409
+ rest = ((open + 1)...expressions.size).map do |later|
2410
+ expression_sources[later] + literal_sources[later + 1]
2411
+ end.join.gsub(/\(\?<(?![=!])[^>]*>/, '(?:(?:)')
2412
+ literal = literals[open + 1]
2413
+ _, operator, varlist = *expressions.first.match(EXPRESSION)
2414
+ varspecs = varlist.split(',')
2415
+ # Otherwise, the rest is matched from each place that matching itself
2416
+ # reaches: where the template starts with the block, with no literal
2417
+ # text in it, and its first expression can match any text of its
2418
+ # characters, with the others empty. Every place the block can reach,
2419
+ # it reaches that way only if that expression can contain everything
2420
+ # the others can.
2421
+ absorbing = start == 0 && literals[1..open].all?(&:empty?) &&
2422
+ (operator.nil? || operator == '+') &&
2423
+ (varspecs.size == 1 || varlist.include?('*')) &&
2424
+ (characters_in(expressions[0..open]) -
2425
+ contained_characters(expressions.first)).empty?
2426
+ if literal_sources[open + 1].start_with?(Regexp.escape(literal[0])) &&
2427
+ TEXT_CHARACTERS.include?(literal[0]) &&
2428
+ literals[0..open].none? { |text| text.include?(literal[0]) } &&
2429
+ expressions[0..open].none? { |e| may_contain?(e, literal[0]) }
2430
+ source += "(?=#{character_set([literal[0]], true)}*+" \
2431
+ "#{literal_sources[open + 1]}#{rest}\\z)"
2432
+ elsif absorbing
2433
+ within = value_class(contained_characters(expressions.first))
2434
+ source += "(?=#{literal_sources.first}#{within}*?" \
2435
+ "#{literal_sources[open + 1]}#{rest}\\z)"
2436
+ end
2437
+ valid_regexp?("\\A#{source}") ? source : ""
2438
+ end
2439
+
2440
+ ##
2441
+ # The expressions after whose literal text a block ends, so that
2442
+ # matching commits to the block's choices. A block ends after literal
2443
+ # text where every expression in it tries its ends in order and the next
2444
+ # value can take anything the block could, so the first choice that lets
2445
+ # the literal text match is the one every later choice would also lead
2446
+ # to.
2447
+ #
2448
+ # @param [Array<String>] expressions The pattern's expressions.
2449
+ # @param [Array<String>] literals
2450
+ # The literal text before each expression, and after the last one.
2451
+ # @param [Array<TrueClass, FalseClass>] empties
2452
+ # Whether each expression only matches nothing.
2453
+ #
2454
+ # @return [Array<Integer>] The expressions' indexes.
2455
+ def block_ends(expressions, literals, empties)
2456
+ ends = Set.new
2457
+ # The characters that the block could match.
2458
+ characters = []
2459
+ # Whether every expression in the block ends in order.
2460
+ ordered = true
2461
+ expressions.each_with_index do |expression, index|
2462
+ ordered &&= empties[index] || ends_in_order?(expression)
2463
+ characters |= contained_characters(expression)
2464
+ literal = literals[index + 1]
2465
+ characters |= literal.chars
2466
+ next if !ordered || literal.empty? || index + 1 == expressions.size
2467
+ following = (index + 1...expressions.size).find do |later|
2468
+ !empties[later]
2469
+ end
2470
+ next unless following && (following == index + 1 ||
2471
+ literals[(index + 2)..following].all?(&:empty?))
2472
+ next unless
2473
+ (characters - absorbed(expressions[following], characters)).empty?
2474
+ ends << index
2475
+ characters = []
2476
+ ordered = true
2477
+ end
2478
+ ends
2479
+ end
2480
+
2481
+ ##
2482
+ # Puts together the regular expression for a template from the sources
2483
+ # for its literal text and its expressions.
2484
+ #
2485
+ # Matching goes left to right in blocks. A block ends after literal text
2486
+ # where whatever the block could match, and that text, could also be put
2487
+ # in front of the next value: the first choice that lets that text match
2488
+ # is then the one that 2.9.x would end up with, since any later choice
2489
+ # only moves text from the block to the next value. Matching commits to
2490
+ # it, so that a URI that doesn't match isn't tried with every way of
2491
+ # dividing it among the variables, which takes polynomial time on
2492
+ # engines that don't memoize (MRI < 3.3, JRuby and TruffleRuby).
2493
+ #
2494
+ # @param [Array<String>] expressions The pattern's expressions.
2495
+ # @param [Array<String>] literals
2496
+ # The literal text before each expression, and after the last one.
2497
+ # @param [Array<String>] literal_sources The regexp source of each literal.
2498
+ # @param [Array<String>] expression_sources The regexp source of each
2499
+ # expression.
2500
+ # @param [Array<TrueClass, FalseClass>] empties
2501
+ # Whether each expression only matches nothing, because the one after
2502
+ # it takes whatever it could.
2503
+ # @param [TrueClass, FalseClass] commit
2504
+ # Whether to commit to choices. With processor patterns, which can
2505
+ # match anything, every choice is kept open.
2506
+ # @param [Array<Integer>] ends
2507
+ # The indexes of the expressions that end blocks, if already found.
2508
+ #
2509
+ # @return [String] The regular expression's source.
2510
+ def assemble_regexp(expressions, literals, literal_sources,
2511
+ expression_sources, empties = [], commit = true,
2512
+ ends = nil)
2513
+ regexp = "\\A".dup
2514
+ if commit
2515
+ # A URI with a character that nothing in the template can match is
2516
+ # rejected before anything is tried. Otherwise, a choice that fails
2517
+ # only there would be tried with every choice before it.
2518
+ allowed = literals.join.chars | characters_in(expressions)
2519
+ allowed = allowed.reject { |character| character =~ LITERAL_ENCODE }
2520
+ regexp << "(?=(?:[#{allowed.map { |c| Regexp.escape(c) }.join}]|" \
2521
+ "%[0-9A-Fa-f]{2}|[^\\x00-\\x7F])*+\\z)"
2522
+ # The same goes for literal text that ends the template, which the
2523
+ # URI must end with. It's checked behind the end, since a literal
2524
+ # before \z in a lookahead keeps some engines from anchoring the
2525
+ # match at the start; literal text that can be written more than one
2526
+ # way can't be checked there, and isn't checked.
2527
+ unless expressions.empty? || literals.last.empty?
2528
+ ending = "(?=[\\s\\S]*+\\z(?<=#{literal_sources.last}))"
2529
+ regexp << ending if valid_regexp?(ending)
2530
+ end
2531
+ tail = tail_check(expressions, literals, literal_sources,
2532
+ expression_sources)
2533
+ regexp << tail if tail
2534
+ last_value = ending_check(expressions, literals, literal_sources,
2535
+ expression_sources)
2536
+ regexp << last_value if last_value
2537
+ ends ||= block_ends(expressions, literals, empties)
2538
+ regexp << open_block_checks(expressions, literals, literal_sources,
2539
+ expression_sources, ends)
2540
+ end
2541
+ regexp << literal_sources.first
2542
+ ends ||= commit ? block_ends(expressions, literals, empties) : []
2543
+ block = "".dup
2544
+ expressions.each_index do |index|
2545
+ block << expression_sources[index] << literal_sources[index + 1]
2546
+ next unless ends.include?(index)
2547
+ regexp << "(?>#{block})"
2548
+ block = "".dup
2549
+ end
2550
+ "#{regexp}#{block}\\z"
2551
+ end
2552
+
2553
+ ##
2554
+ # The regexp source for a character class with a set of ASCII
2555
+ # characters, pct-encoded triplets and non-ASCII characters.
2556
+ #
2557
+ # @param [Array<String>] characters The ASCII characters.
2558
+ #
2559
+ # @return [String]
2560
+ def value_class(characters)
2561
+ others = "[^\\x00-\\x7F]|%[a-fA-F0-9][a-fA-F0-9]"
2562
+ return "(?:#{others})" if characters.empty?
2563
+ "(?:#{character_set(characters)}|#{others})"
2564
+ end
2565
+
2566
+ ##
2567
+ # The regexp source for a set of ASCII characters.
2568
+ #
2569
+ # @param [Array<String>] characters The characters.
2570
+ # @param [TrueClass, FalseClass] negated Whether to match any other one.
2571
+ #
2572
+ # @return [String]
2573
+ def character_set(characters, negated = false)
2574
+ "[#{negated ? '^' : ''}#{characters.map { |c| Regexp.escape(c) }.join}]"
2575
+ end
2576
+
2577
+ ##
2578
+ # The characters that literal text can be matched with: its own, and
2579
+ # those of a non-ASCII character pct-encoded, in either case. (A "#"
2580
+ # that can be "%23" is handled where its value ends.)
2581
+ #
2582
+ # @param [String] literal The literal text.
2583
+ #
2584
+ # @return [Array<String>]
2585
+ def literal_characters(literal)
2586
+ build_memo([:literal, literal]) { uncached_literal_characters(literal) }
2587
+ end
2588
+
2589
+ ##
2590
+ # Works out #literal_characters.
2591
+ #
2592
+ # @param (see #literal_characters)
2593
+ #
2594
+ # @return (see #literal_characters)
2595
+ def uncached_literal_characters(literal)
2596
+ literal.chars.flat_map do |character|
2597
+ if character =~ LITERAL_ENCODE
2598
+ hex = character.unpack('C*').map { |byte| '%02X' % byte }.join
2599
+ [character, '%'] + hex.chars + hex.downcase.chars
2600
+ else
2601
+ [character]
2602
+ end
2603
+ end.uniq
2604
+ end
2605
+
2606
+ ##
2607
+ # The characters that nothing after an expression can contain, and the
2608
+ # final literal text, if it's written only one way, which the URI ends
2609
+ # with. Its characters are counted only where something else after the
2610
+ # expression can contain them, since the URI's last characters are left
2611
+ # for it.
2612
+ #
2613
+ # @param [Integer] index The expression's index.
2614
+ # @param [Array<String>] expressions The pattern's expressions.
2615
+ # @param [Array<String>] literals
2616
+ # The literal text before each expression, and after the last one.
2617
+ # @param [Integer] first The index of the first literal text to count.
2618
+ #
2619
+ # @return [Array] The characters, and the final literal text or nil.
2620
+ def characters_after(index, expressions, literals, first = index + 1)
2621
+ suffixes = character_suffixes(expressions, literals)
2622
+ # Past the last literal text, there's none to count.
2623
+ texts = suffixes[:literals][first]
2624
+ key = [:after, expressions.object_id, literals.object_id,
2625
+ texts && texts.object_id,
2626
+ suffixes[:expressions][index + 1].object_id,
2627
+ first < literals.size]
2628
+ build_memo(key) do
2629
+ uncached_characters_after(index, expressions, literals, first)
2630
+ end
2631
+ end
2632
+
2633
+ ##
2634
+ # Works out #characters_after.
2635
+ #
2636
+ # @param (see #characters_after)
2637
+ #
2638
+ # @return (see #characters_after)
2639
+ def uncached_characters_after(index, expressions, literals, first)
2640
+ later = literals[first..-1] || []
2641
+ final = later.last
2642
+ # A "#" can also be matched as "%23", so longer literal text with one
2643
+ # isn't written only one way. A single character is left as the URI's
2644
+ # last one either way.
2645
+ final = nil unless final && !final.empty? &&
2646
+ final.chars.all? { |c| TEXT_CHARACTERS.include?(c) } &&
2647
+ (final.size == 1 || !final.include?('#'))
2648
+ suffixes = character_suffixes(expressions, literals)
2649
+ characters = suffixes[:literals][first] || []
2650
+ characters |= literal_characters(later.last) if later.last && !final
2651
+ outside = TEXT_CHARACTERS - characters -
2652
+ (suffixes[:expressions][index + 1] || [])
2653
+ final = nil if final && (final.chars & outside).empty?
2654
+ [outside, final]
2655
+ end
2656
+
2657
+ ##
2658
+ # The characters of the final literal text, as #characters_after gives
2659
+ # it.
2660
+ #
2661
+ # @param [String, nil] final The final literal text.
2662
+ #
2663
+ # @return [Array<String>]
2664
+ def final_characters(final)
2665
+ final ? final.chars.uniq : []
2666
+ end
2667
+
2668
+ ##
2669
+ # For each index, the characters that the expressions from there to the
2670
+ # end can contain, and those of the literal text from there up to the
2671
+ # last one. They're worked out once while a template is built, since
2672
+ # each expression needs them.
2673
+ #
2674
+ # @param [Array<String>] expressions The pattern's expressions.
2675
+ # @param [Array<String>] literals
2676
+ # The literal text before each expression, and after the last one.
2677
+ #
2678
+ # @return [Hash] The suffixes, as :expressions and :literals.
2679
+ def character_suffixes(expressions, literals)
2680
+ build_cached(:suffixes, expressions, literals) do
2681
+ # Where a set adds nothing, the one after it is kept, so that
2682
+ # positions with the same characters share one object.
2683
+ widen = lambda do |sets, characters|
2684
+ wider = characters | sets.first
2685
+ sets.unshift(wider.size == sets.first.size ? sets.first : wider)
2686
+ end
2687
+ after = [[]]
2688
+ expressions.reverse_each do |expression|
2689
+ widen.call(after, contained_characters(expression))
2690
+ end
2691
+ texts = [[]]
2692
+ literals[0...-1].reverse_each do |text|
2693
+ widen.call(texts, literal_characters(text))
2694
+ end
2695
+ { expressions: after, literals: texts }
2696
+ end
2697
+ end
2698
+
2699
+ ##
2700
+ # The characters that the template's literal text or any of its
2701
+ # expressions can contain, worked out once while it's built.
2702
+ #
2703
+ # @param [Array<String>] expressions The pattern's expressions.
2704
+ # @param [Array<String>] literals
2705
+ # The literal text before each expression, and after the last one.
2706
+ #
2707
+ # @return [Array<String>]
2708
+ def allowed_characters(expressions, literals)
2709
+ build_cached(:allowed, expressions, literals) do
2710
+ literals.join.chars | characters_in(expressions)
2711
+ end
2712
+ end
2713
+
2714
+ ##
2715
+ # A value worked out once while a template is built, for the build's
2716
+ # own expressions and literals; outside a build, it's worked out each
2717
+ # time.
2718
+ #
2719
+ # @param [Symbol] kind What the value is.
2720
+ # @param [Array<String>] expressions The pattern's expressions.
2721
+ # @param [Array<String>] literals The pattern's literal text.
2722
+ #
2723
+ # @return [Object] The value.
2724
+ def build_cached(kind, expressions, literals)
2725
+ build_memo([kind, expressions.object_id, literals.object_id]) { yield }
2726
+ end
2727
+
2728
+ ##
2729
+ # A value worked out once per key while a template is built; outside a
2730
+ # build, it's worked out each time. Long templates repeat the same
2731
+ # expression in the same surroundings, so the key is what the value
2732
+ # depends on, not the expression's index.
2733
+ #
2734
+ # @param [Array] key What the value depends on.
2735
+ #
2736
+ # @return [Object] The value.
2737
+ def build_memo(key)
2738
+ cache = Thread.current[BUILD_CACHE]
2739
+ return yield unless cache
2740
+ cache.fetch(key) { cache[key] = yield }
2741
+ end
2742
+
2743
+ ##
2744
+ # The regexp source that takes every character of a set up to the last
2745
+ # one, possessively, leaving the URI's last characters for the final
2746
+ # literal text.
2747
+ #
2748
+ # @param [Array<String>] value The characters the value can contain.
2749
+ # @param [Array<String>] eaten The characters to take.
2750
+ # @param [String, nil] final The final literal text.
2751
+ # @param [Array<String>] endings Other regexp sources to take.
2752
+ #
2753
+ # @return [String] The source, empty if there's nothing to take.
2754
+ def take_through(value, eaten, final, endings = [])
2755
+ endings = endings.dup
2756
+ kept = eaten & final_characters(final)
2757
+ set = eaten - kept
2758
+ endings.unshift(character_set(set)) unless set.empty?
2759
+ unless kept.empty?
2760
+ taken = kept.size == 1 ? Regexp.escape(kept.first) : character_set(kept)
2761
+ before_final = final.size == 1 ? "(?!\\z)" : "(?=[\\s\\S]{#{final.size}})"
2762
+ endings << "#{taken}#{before_final}"
2763
+ end
2764
+ return "" if endings.empty?
2765
+ "(?:#{value_class(value - eaten)}*+(?:#{endings.join('|')}))*+"
2766
+ end
2767
+
2768
+ ##
2769
+ # The sets of characters that decide how the last value of an expression
2770
+ # that literal text follows can skip the places where it can't end: the
2771
+ # characters it can contain, the final character, the literal text's
2772
+ # characters and its one character that nothing after it can contain,
2773
+ # the characters that reject the URI once the value has started, and
2774
+ # those it takes up front.
2775
+ #
2776
+ # @param [Integer] index The expression's index.
2777
+ # @param [Array<String>] expressions The pattern's expressions.
2778
+ # @param [Array<String>] literals
2779
+ # The literal text before each expression, and after the last one.
2780
+ # @param [String] group
2781
+ # The regexp source for a character of the value, if not the
2782
+ # operator's.
2783
+ #
2784
+ # @return [Hash, nil] The sets, or nil if the value doesn't skip any.
2785
+ def value_sets(index, expressions, literals, group = nil)
2786
+ _, operator, varlist = *expressions[index].match(EXPRESSION)
2787
+ return nil unless [nil, '+', '#', '/'].include?(operator)
2788
+ return nil if varlist.split(',').last[VARSPEC, 2] == '*'
2789
+ literal = literals[index + 1]
2790
+ return nil if literal.empty?
2791
+ group ||= operator == '+' || operator == '#' ? RESERVED : UNRESERVED
2792
+ after = characters_after(index, expressions, literals, index + 2)
2793
+ key = [:sets, expressions.object_id, literals.object_id, group,
2794
+ after.object_id, literal]
2795
+ build_memo(key) do
2796
+ sets_after(group, literal, after, expressions, literals)
2797
+ end
2798
+ end
2799
+
2800
+ ##
2801
+ # Works out #value_sets once the expression is known to have them.
2802
+ #
2803
+ # @param [String] group The regexp source for a character of the value.
2804
+ # @param [String] literal The literal text after the expression.
2805
+ # @param [Array] after What #characters_after gives for the expression.
2806
+ # @param [Array<String>] expressions The pattern's expressions.
2807
+ # @param [Array<String>] literals
2808
+ # The literal text before each expression, and after the last one.
2809
+ #
2810
+ # @return [Hash, nil] The sets, or nil if the value doesn't skip any.
2811
+ def sets_after(group, literal, after, expressions, literals)
2812
+ value = group_characters(group)
2813
+ outside, final = after
2814
+ # The final character can end the URI, so only taking characters up
2815
+ # front may count it as one that nothing after can contain.
2816
+ strict = outside - final_characters(final)
2817
+ text = literal_characters(literal)
2818
+ # A character of the literal text that nothing after it can contain.
2819
+ last = text.size == 1 && literal.size == 1 && strict.include?(literal) ?
2820
+ literal : nil
2821
+ return nil if !last && !(text & strict).empty?
2822
+ # Characters that nothing in the template can contain are rejected
2823
+ # before matching.
2824
+ allowed = allowed_characters(expressions, literals)
2825
+ {
2826
+ value: value, final: final, text: text, last: last,
2827
+ guard: (strict - value - text) & allowed,
2828
+ # Characters of longer final literal text are rejected only before
2829
+ # the URI's last characters, which are left for it.
2830
+ final_guard: final && final.size > 1 ?
2831
+ ((outside & final_characters(final)) - value - text) & allowed : [],
2832
+ eaten: (outside & value) - text
2833
+ }
2834
+ end
2835
+
2836
+ ##
2837
+ # Whether each expression's last value can start in only a few places,
2838
+ # so that looking ahead to the end of the URI from there costs linear
2839
+ # time in all. The expression starts a block and no earlier variable in
2840
+ # it is exploded, or literal text separates it from a lone variable that
2841
+ # can, and takes up front each character that would make this value
2842
+ # look ahead or take characters: this value then starts once where that
2843
+ # one is empty, and otherwise only after the last such character.
2844
+ #
2845
+ # @param [Array<String>] expressions The pattern's expressions.
2846
+ # @param [Array<String>] literals
2847
+ # The literal text before each expression, and after the last one.
2848
+ # @param [Array<Integer>] ends The expressions that end blocks.
2849
+ #
2850
+ # @return [Array<TrueClass, FalseClass>]
2851
+ def scanned_values(expressions, literals, ends)
2852
+ scans = []
2853
+ sets = Hash.new do |cache, index|
2854
+ cache[index] = value_sets(index, expressions, literals)
2855
+ end
2856
+ expressions.each_with_index do |expression, index|
2857
+ varspecs = expression[EXPRESSION, 2].split(',')
2858
+ if varspecs[0...-1].any? { |varspec| varspec[VARSPEC, 2] == '*' }
2859
+ scans << false
2860
+ elsif index == 0 || ends.include?(index - 1)
2861
+ scans << true
2862
+ else
2863
+ previous = expressions[index - 1][EXPRESSION, 2]
2864
+ before = scans[index - 1] && !literals[index].empty? &&
2865
+ previous =~ VARSPEC && $2 != '*' &&
2866
+ sets[index - 1]
2867
+ after = sets[index]
2868
+ scans << (before && after ?
2869
+ ((after[:guard] | after[:eaten]) - before[:eaten]).empty? : false)
2870
+ end
2871
+ end
2872
+ scans
2873
+ end
2874
+
2875
+ ##
2876
+ # The regexp source for the last value of an expression that literal
2877
+ # text follows, which tries the same values, in the same order, as the
2878
+ # plain one, but skips those that can't let the rest of the URI match:
2879
+ #
2880
+ # * Nothing after the literal text can contain some characters, so the
2881
+ # value takes each of them that it can, up to the last one, and the
2882
+ # URI is rejected if it has one that the value can't take. When the
2883
+ # literal text is one such character, the value takes everything up to
2884
+ # the last place where it's written as it is.
2885
+ # * After those, the next expression can take any characters that the
2886
+ # value could, and the literal text, up to a character that it can't.
2887
+ # Until then, the literal text's first place is the only one tried,
2888
+ # since if the rest doesn't match from there, it doesn't from a later
2889
+ # place either.
2890
+ #
2891
+ # Without this, a URI that doesn't match would be tried with the value
2892
+ # ending at every place where the literal text is, matching the rest
2893
+ # again each time, which takes polynomial time on engines that don't
2894
+ # memoize (MRI < 3.3, JRuby and TruffleRuby).
2895
+ #
2896
+ # @param [Integer] index The expression's index.
2897
+ # @param [Array<String>] expressions The pattern's expressions.
2898
+ # @param [Array<String>] literals
2899
+ # The literal text before each expression, and after the last one.
2900
+ # @param [Array<String>] literal_sources The regexp source of each literal.
2901
+ # @param [Array<TrueClass, FalseClass>] empties
2902
+ # Whether each expression only matches nothing.
2903
+ # @param [String] group
2904
+ # The regexp source for a character of the value, if not the
2905
+ # operator's.
2906
+ # @param [TrueClass, FalseClass] scan
2907
+ # Whether the value can start in only a few places, so that looking
2908
+ # ahead to the end of the URI from there costs linear time in all.
2909
+ #
2910
+ # @return [String, nil] The source, or nil if the plain one is used.
2911
+ def bounded_value(index, expressions, literals, literal_sources, empties,
2912
+ group = nil, scan = true)
2913
+ sets = value_sets(index, expressions, literals, group)
2914
+ return nil unless sets
2915
+ following = (index + 1...expressions.size).find { |later| !empties[later] }
2916
+ # The expression that follows directly, past any that only match
2917
+ # nothing, if only empty literal text comes before it.
2918
+ next_expression = following &&
2919
+ literals[(index + 2)..following].all?(&:empty?) &&
2920
+ expressions[following]
2921
+ key = [:bounded, sets.object_id, scan, next_expression,
2922
+ literal_sources[index + 1]]
2923
+ build_memo(key) do
2924
+ bounded_source(sets, scan, next_expression, literal_sources[index + 1])
2925
+ end
2926
+ end
2927
+
2928
+ ##
2929
+ # Works out #bounded_value from the expression's value sets.
2930
+ #
2931
+ # @param [Hash] sets What #value_sets gives for the expression.
2932
+ # @param [TrueClass, FalseClass] scan See #bounded_value.
2933
+ # @param [String, nil] next_expression
2934
+ # The expression that follows directly, or nil if none does.
2935
+ # @param [String] literal_source The regexp source of the literal text.
2936
+ #
2937
+ # @return [String] The source.
2938
+ def bounded_source(sets, scan, next_expression, literal_source)
2939
+ value, final, text, last, guard, eaten, final_guard =
2940
+ sets.values_at(:value, :final, :text, :last, :guard, :eaten,
2941
+ :final_guard)
2942
+ unless scan
2943
+ # Only the literal text's first place in each stretch is tried.
2944
+ final = last = nil
2945
+ guard = eaten = final_guard = []
2946
+ end
2947
+ source = "".dup
2948
+ if !final_guard.empty?
2949
+ source << "(?=#{character_set(guard | final_guard, true)}*+" \
2950
+ "[\\s\\S]{0,#{final.size}}\\z)"
2951
+ elsif !guard.empty?
2952
+ source << "(?=#{character_set(guard, true)}*+\\z)"
2953
+ end
2954
+ repeated = last && value.include?(last)
2955
+ rest = value - eaten - [last]
2956
+ escaped = Regexp.escape(last) if last
2957
+ endings = repeated ? ["#{escaped}(?=[^#{escaped}]*#{escaped})"] : []
2958
+ source << take_through(value - [last], eaten, final, endings)
2959
+ # Nothing after the literal text can contain its character, so the
2960
+ # literal text is at or after the last place where it's written as it
2961
+ # is.
2962
+ source << "(?:#{value_class(rest)}*+(?=#{escaped}))?+" if last
2963
+ tail = value - eaten - [last]
2964
+ if repeated
2965
+ # The value ends before the last one, or takes it, and the literal
2966
+ # text is pct-encoded after it.
2967
+ source << "(?:#{escaped}#{take_through(value - [last], eaten, final)})??"
2968
+ end
2969
+ if next_expression &&
2970
+ !last && (text - absorbed(next_expression, text)).empty?
2971
+ stops = tail - absorbed(next_expression, tail)
2972
+ within = value_class(tail - stops)
2973
+ first = "(?>#{within}*?(?=#{literal_source}))"
2974
+ source << (stops.empty? ? first :
2975
+ "(?:(?>#{within}*+#{character_set(stops)}))*?#{first}")
2976
+ else
2977
+ source << "#{value_class(tail)}*?"
2978
+ end
2979
+ source
2980
+ end
2981
+
1042
2982
  ##
1043
2983
  # Generates the <tt>Regexp</tt> that parses a template pattern.
1044
2984
  #
2985
+ # Where it's known whether the regular expression engine matches a
2986
+ # regexp in linear time (MRI 3.2 and later, TruffleRuby), the one that keeps
2987
+ # every choice open is used when it does, since the engine then can't
2988
+ # backtrack catastrophically, and its rewrites to commit to choices
2989
+ # could keep the engine from matching in linear time. Both give the same
2990
+ # values.
2991
+ #
1045
2992
  # @param [String] pattern The URI template pattern.
1046
2993
  # @param [#match] processor The template processor to use.
2994
+ # @param [Array<Array>] patterns
2995
+ # The processor's pattern for each variable, if already known.
2996
+ # @param [TrueClass, FalseClass] commit
2997
+ # Whether to commit to choices, if not decided by the patterns.
1047
2998
  #
1048
2999
  # @return [Array, Regexp]
1049
3000
  # An array of expansion variables nad a regular expression which may be
1050
3001
  # used to parse a template pattern
1051
- def parse_new_template_pattern(pattern, processor = nil)
1052
- # Escape the pattern. The two gsubs restore the escaped curly braces
1053
- # back to their original form. Basically, escape everything that isn't
1054
- # within an expansion.
1055
- escaped_pattern = Regexp.escape(
1056
- pattern
1057
- ).gsub(/\\\{(.*?)\\\}/) do |escaped|
1058
- escaped.gsub(/\\(.)/, "\\1")
3002
+ def parse_new_template_pattern(pattern, processor = nil, patterns = nil,
3003
+ commit = nil)
3004
+ # Values that several steps need for each expression are worked
3005
+ # out once per build, in a cache only this thread sees.
3006
+ owner = Thread.current[BUILD_CACHE].nil?
3007
+ Thread.current[BUILD_CACHE] = {} if owner
3008
+ escaped_pattern, raw_expressions, literals, literal_sources,
3009
+ either_leader, either_literal = template_parts(pattern)
3010
+ dotted_labels = raw_expressions.each_index.map do |index|
3011
+ label_takes_dots?(
3012
+ index, raw_expressions, literals, either_leader, either_literal
3013
+ )
1059
3014
  end
1060
3015
 
1061
3016
  expansions = []
3017
+ # How many expressions name each variable.
3018
+ naming = Hash.new(0)
3019
+ raw_expressions.each do |expression|
3020
+ expression[EXPRESSION, 2].split(',').map do |varspec|
3021
+ varspec[VARSPEC, 1]
3022
+ end.uniq.each { |name| naming[name] += 1 }
3023
+ end
1062
3024
  # Processor patterns can match anything, so they get 2.9.0's choices.
1063
3025
  plain_processor = !(processor && processor.respond_to?(:match))
1064
3026
  followers = expression_followers(escaped_pattern)
3027
+ patterns ||= raw_expressions.map do |expansion|
3028
+ expansion[EXPRESSION, 2].split(',').map do |varspec|
3029
+ plain_processor ? nil : processor.match(varspec[VARSPEC, 1])
3030
+ end
3031
+ end
3032
+ # Where a processor gives a variable its own pattern, the choices
3033
+ # before it can't be judged from the operators, so every choice is
3034
+ # kept open, as in 2.9.0.
3035
+ commit = !patterns.flatten.any? if commit.nil?
3036
+ # Where the engine matches the regexp that keeps every choice open in
3037
+ # linear time, it's used, since committing can keep the engine from
3038
+ # doing so.
3039
+ if commit && LINEAR_TIME_CHECKED
3040
+ open = parse_new_template_pattern(pattern, processor, patterns, false)
3041
+ return open if linear_time?(open[1])
3042
+ end
3043
+ # Whether each expression only matches nothing, because the one after
3044
+ # it takes whatever it could.
3045
+ empties = raw_expressions.each_index.map do |index|
3046
+ following = followers[index].first
3047
+ _, operator, varlist = *raw_expressions[index].match(EXPRESSION)
3048
+ plain_processor && following &&
3049
+ absorbed_by?(following, operator, varlist.split(',')) ? true : false
3050
+ end
3051
+ ends = commit ? block_ends(raw_expressions, literals, empties) : []
3052
+ scans = commit ? scanned_values(raw_expressions, literals, ends) : []
1065
3053
 
1066
3054
  # Create a regular expression that captures the values of the
1067
3055
  # variables in the URI.
1068
- regexp_string = escaped_pattern.gsub( EXPRESSION ) do |expansion|
1069
-
3056
+ expression_sources = raw_expressions.map do |expansion|
1070
3057
  index = expansions.size
1071
3058
  expansions << expansion
1072
3059
  _, operator, varlist = *expansion.match(EXPRESSION)
1073
3060
  leader = Regexp.escape(LEADERS.fetch(operator, ''))
3061
+ if operator == '#' && either_leader[index]
3062
+ leader = NUMBER_SIGN_EITHER_FORM
3063
+ end
1074
3064
  joiner = Regexp.escape(JOINERS.fetch(operator, ','))
1075
3065
  varspecs = varlist.split(',')
1076
- results = varspecs.map do |varspec|
1077
- name = varspec[VARSPEC, 1]
1078
- processor && processor.respond_to?(:match) ? processor.match(name) : nil
1079
- end
3066
+ results = patterns[index]
3067
+ # A ;, ? or & variable that isn't exploded is written as its own
3068
+ # name, so a pair in its place can only have the name of one of the
3069
+ # expression's variables that aren't exploded. Matching gives each
3070
+ # pair to its variable afterwards.
3071
+ named = NAMED_OPERATORS.include?(operator) &&
3072
+ named_pair_source(operator, varspecs, results)
1080
3073
  # Without processor patterns, any variable in the expression can take
1081
3074
  # the characters that an earlier variable leaves, which lets the
1082
3075
  # variables after the first one have fewer choices below.
1083
3076
  plain = results.compact.empty?
1084
3077
  explodes = varspecs.map { |varspec| varspec[VARSPEC, 2] == '*' }
1085
3078
  first_explode = explodes.index(true)
3079
+ scan = scans[index]
3080
+ # A name used in another expression too takes the first value it's
3081
+ # given, so a choice skipped below might be the one that gives the
3082
+ # value it gets.
3083
+ shared = varspecs.any? do |varspec|
3084
+ naming[varspec[VARSPEC, 1]] > 1
3085
+ end
3086
+ first_named = explodes.index(false)
1086
3087
  not_after_value =
1087
- "(?<![#{Addressable::URI::CharacterClasses::UNRESERVED}])"
3088
+ "(?<![#{Addressable::URI::CharacterClasses::UNRESERVED}])" \
3089
+ "(?<![^\\x00-\\x7F])"
3090
+ # A lookahead that skips the expression's empty choice where it
3091
+ # can't lead to a match.
3092
+ empty_guard = nil
1088
3093
  combined = varspecs.each_with_index.map do |varspec, position|
1089
3094
  _, name, modifier = *varspec.match(VARSPEC)
3095
+ name = capture_name(name)
3096
+
3097
+ if named && modifier != '*'
3098
+ # The pairs of the variables that aren't exploded are matched
3099
+ # as one run, in any order, by the first of them, so each name
3100
+ # is written once however many variables the expression has.
3101
+ # The others match nothing, and matching gives each pair to its
3102
+ # variable afterwards.
3103
+ if position == first_named
3104
+ next "(?<#{name}>#{named}(?:#{joiner}#{named})*)?"
3105
+ else
3106
+ next "(?<#{name}>)"
3107
+ end
3108
+ end
1090
3109
 
1091
3110
  result = results[position]
1092
3111
  if result
@@ -1100,7 +3119,13 @@ module Addressable
1100
3119
  when '/'
1101
3120
  "#{ UNRESERVED }*?"
1102
3121
  when '.'
1103
- "#{ UNRESERVED.gsub('\.', '') }*?"
3122
+ if dotted_labels[index]
3123
+ # Nothing after the value can continue it, so it takes every
3124
+ # character up to the delimiter.
3125
+ "#{ UNRESERVED }*+"
3126
+ else
3127
+ "#{ UNRESERVED.gsub('\.', '') }*?"
3128
+ end
1104
3129
  when ';'
1105
3130
  # The same strings, tried in the same order, as 2.9.0's
1106
3131
  # "U*=?U*?", but a name without "=" can only match one way.
@@ -1141,20 +3166,40 @@ module Addressable
1141
3166
  if operator == ';'
1142
3167
  "(?<#{name}>)"
1143
3168
  elsif modifier != '*' && varspec == varspecs.last
1144
- "(?<#{name}>#{RESERVED_NO_COMMA}*?)?"
3169
+ bounded = commit && position == varspecs.size - 1 &&
3170
+ bounded_value(index, raw_expressions, literals,
3171
+ literal_sources, empties, RESERVED_NO_COMMA,
3172
+ scan)
3173
+ "(?<#{name}>#{bounded || "#{RESERVED_NO_COMMA}*?"})?"
1145
3174
  else
1146
3175
  # 2.9.0 skipped the variable when it couldn't be empty.
1147
3176
  "(?:(?<#{name}>)(?!#{RESERVED_NO_COMMA}))?"
1148
3177
  end
1149
3178
  elsif plain && modifier == '*' && explodes[(position + 1)..-1].any? &&
1150
- (operator.nil? || operator == '/' || operator == '.')
3179
+ (operator.nil? || operator == '/' || operator == '.') &&
3180
+ !may_follow_with?(index, JOINERS.fetch(operator, ','),
3181
+ raw_expressions, literals)
1151
3182
  # Exploded values were tried shortest first, and a later
1152
3183
  # exploded variable can match whatever this one leaves, so once
1153
3184
  # a split fails, every split where this variable is longer
1154
3185
  # fails too. Of the values tried, only the leading joiners are
1155
- # shorter than every value tried before them.
1156
- "(?<#{name}>(?:#{joiner})*)"
1157
- elsif plain && position > 0 && explodes[position - 1] &&
3186
+ # shorter than every value tried before them. It takes every
3187
+ # leading joiner, so that they aren't divided with the later
3188
+ # variables. That's only when what follows the expression can't
3189
+ # start with a joiner, which would end it earlier. Giving one
3190
+ # back never helps then, so where choices are kept open, the
3191
+ # joiners are taken greedily instead, which an engine that
3192
+ # matches in linear time can do without backtracking.
3193
+ "(?<#{name}>(?:#{joiner})*#{commit ? '+' : ''})"
3194
+ elsif plain && modifier == '*' && position < varspecs.size - 1 &&
3195
+ explodes.count(true) == 1 &&
3196
+ (operator.nil? || operator == '/' || operator == '.')
3197
+ # The later variables can't contain a joiner, so this takes
3198
+ # whole members that a joiner ends, fewest first, and the later
3199
+ # variables divide what's after them. A run of characters
3200
+ # without a joiner isn't divided two ways.
3201
+ "(?<#{name}>(?:#{group}#{joiner})*?)"
3202
+ elsif plain && explodes[0...position].any? && !shared &&
1158
3203
  (operator == '?' || operator == '&')
1159
3204
  # Whatever this variable could match after an exploded one,
1160
3205
  # that one already tried matching itself, unless it couldn't:
@@ -1167,10 +3212,49 @@ module Addressable
1167
3212
  # variable's run of characters with this one never gave a
1168
3213
  # different result, so this one may only start after that run.
1169
3214
  "(?<#{name}>(?:#{not_after_value}#{value || group})?)"
3215
+ elsif commit && modifier == '*' &&
3216
+ position == varspecs.size - 1 &&
3217
+ (operator == '+' || operator == '#') &&
3218
+ members_follow?(index, raw_expressions, literals)
3219
+ # Each member takes every character it can, so the value can
3220
+ # only end before a comma, a character it can't contain or the
3221
+ # end of the URI, and never before what follows it.
3222
+ "(?<#{name}>(?!))?"
1170
3223
  elsif modifier == '*'
1171
- "(?<#{name}>#{value})?"
3224
+ through = ""
3225
+ if commit && plain && scan && varspecs.size == 1 &&
3226
+ literals[index + 1].empty? &&
3227
+ index < raw_expressions.size - 1 &&
3228
+ [nil, '/', '.', '+', '#'].include?(operator)
3229
+ # Another expression follows the value directly, and nothing
3230
+ # after it can contain some characters the value can, so it
3231
+ # takes each of them up to the last one first. Without this,
3232
+ # the later expressions would divide the text before the
3233
+ # last one in every way first.
3234
+ member = if operator == '+' || operator == '#'
3235
+ RESERVED_NO_COMMA
3236
+ else
3237
+ group.sub(/\*[?+]\z/, '')
3238
+ end
3239
+ characters = group_characters(member) |
3240
+ [JOINERS.fetch(operator, ',')]
3241
+ outside, final =
3242
+ characters_after(index, raw_expressions, literals)
3243
+ through = take_through(
3244
+ characters, characters & outside, final
3245
+ )
3246
+ # Without the value, nothing could take them.
3247
+ kept = final_characters(final)
3248
+ taken = characters & outside
3249
+ unless taken.empty?
3250
+ rest = final && !(taken & kept).empty? ?
3251
+ "[\\s\\S]{0,#{final.size}}" : ""
3252
+ empty_guard = "(?=#{character_set(taken, true)}*+#{rest}\\z)"
3253
+ end
3254
+ end
3255
+ "(?<#{name}>#{through}#{value})?"
1172
3256
  elsif varspecs.size > 1 && (operator == '+' || operator == '#') &&
1173
- varspec != varspecs.last
3257
+ position < varspecs.size - 1
1174
3258
  "(?<#{name}>#{RESERVED_NO_COMMA}*+)?"
1175
3259
  elsif plain && position < varspecs.size - 1 &&
1176
3260
  (operator.nil? || operator == '/' || operator == '.')
@@ -1179,6 +3263,10 @@ module Addressable
1179
3263
  # value that could change the result is the whole run up to the
1180
3264
  # next joiner.
1181
3265
  "(?<#{name}>(?:#{group}(?=#{joiner}))??)"
3266
+ elsif commit && position == varspecs.size - 1 &&
3267
+ (bounded = bounded_value(index, raw_expressions, literals,
3268
+ literal_sources, empties, nil, scan))
3269
+ "(?<#{name}>#{bounded})?"
1182
3270
  else
1183
3271
  "(?<#{name}>#{group})?"
1184
3272
  end
@@ -1186,8 +3274,31 @@ module Addressable
1186
3274
  end
1187
3275
  following, comma_follows = followers[index]
1188
3276
  single = varspecs.size == 1 && varspecs.first[VARSPEC, 2] != '*'
1189
- if plain_processor && following &&
1190
- absorbed_by?(following, operator, varspecs)
3277
+ last_group = case operator
3278
+ when '+', '#' then "#{RESERVED}*?"
3279
+ when nil, '/' then "#{UNRESERVED}*?"
3280
+ when '.'
3281
+ "#{UNRESERVED.gsub('\.', '')}*?" unless dotted_labels[index]
3282
+ end
3283
+ if commit && plain && last_group && following &&
3284
+ following[1].nil? && varspecs.last[VARSPEC, 2] != '*'
3285
+ # Values were tried shortest first, and the next expression can
3286
+ # take any run of unreserved characters at its start, and of
3287
+ # commas too if it has an exploded variable, so the last value
3288
+ # only needs to end after a character that the next expression
3289
+ # couldn't take.
3290
+ no_comma = following[2].include?('*') ? "(?<!,)" : ""
3291
+ # Nothing after the value can contain some characters, so it
3292
+ # takes each of them up to the last one first.
3293
+ value_characters = group_characters(last_group.chomp('*?'))
3294
+ outside, final = characters_after(index, raw_expressions, literals)
3295
+ through = scan ? take_through(
3296
+ value_characters, value_characters & outside, final
3297
+ ) : ""
3298
+ combined[-1] = "(?<#{capture_name(varspecs.last[VARSPEC, 1])}>" \
3299
+ "|#{through}#{last_group}#{not_after_value}#{no_comma})?"
3300
+ end
3301
+ if empties[index]
1191
3302
  # Each expression tried its empty alternative first. When the next
1192
3303
  # one follows it directly and can match anything it could, followed
1193
3304
  # by anything the next one could match on its own, every other
@@ -1201,35 +3312,62 @@ module Addressable
1201
3312
  # Values were tried shortest first, and the next expression can
1202
3313
  # match any unreserved characters, so the value only needs to end
1203
3314
  # after a character that the next expression couldn't match.
1204
- combined = "(?<#{varspecs.first[VARSPEC, 1]}>" \
3315
+ combined = "(?<#{capture_name(varspecs.first[VARSPEC, 1])}>" \
1205
3316
  "#{RESERVED}*?#{not_after_value})?"
1206
3317
  elsif plain && varspecs.size > 1 &&
1207
3318
  (operator == '+' || operator == '#') &&
1208
3319
  !comma_follows &&
1209
- varspecs.none? { |varspec| varspec[VARSPEC, 2] == '*' } &&
1210
- !varspecs[0...-1].include?(varspecs.last)
3320
+ varspecs.none? { |varspec| varspec[VARSPEC, 2] == '*' }
1211
3321
  # 2.9.0 tried each value with the joiner after it first, then the
1212
3322
  # value on its own, then skipping the variable, and every other
1213
3323
  # choice gave a value to a later variable that an earlier one had
1214
3324
  # already been tried with. A variable after a skipped one is
1215
- # skipped too. Stopping before a joiner is left out, so this is
1216
- # only used when no joiner can follow the expression. As in 2.9.0,
1217
- # a variable is the last one if its varspec is the same as the
1218
- # last varspec.
3325
+ # skipped too. Stopping before a joiner is left out, so this is only
3326
+ # used when no joiner can follow the expression.
1219
3327
  nested = varspecs[0...-1].reverse.inject("") do |inner, varspec|
1220
- "(?:(?<#{varspec[VARSPEC, 1]}>#{RESERVED_NO_COMMA}*+)" \
3328
+ "(?:(?<#{capture_name(varspec[VARSPEC, 1])}>" \
3329
+ "#{RESERVED_NO_COMMA}*+)" \
1221
3330
  "#{joiner}?+#{inner}|(?=#{RESERVED_NO_COMMA}))"
1222
3331
  end
1223
3332
  combined = nested + combined.last
1224
3333
  else
1225
3334
  combined = combined.join("#{joiner}?")
1226
3335
  end
1227
- "(?:|#{leader}#{combined})"
3336
+ "(?:#{empty_guard}|#{leader}#{combined})"
1228
3337
  end
1229
3338
 
1230
- # Ensure that the regular expression matches the whole URI.
1231
- regexp_string = "\\A#{regexp_string}\\z"
1232
- return expansions, Regexp.new(regexp_string)
3339
+ regexp_string = assemble_regexp(
3340
+ raw_expressions, literals, literal_sources, expression_sources,
3341
+ empties, commit, ends
3342
+ )
3343
+ return expansions, Regexp.new(regexp_string), patterns
3344
+ ensure
3345
+ Thread.current[BUILD_CACHE] = nil if owner
3346
+ end
3347
+
3348
+ # MRI 3.2 memoizes a match, so that it takes linear time, unless the
3349
+ # regexp has a lookaround, an atomic group, a possessive quantifier or a
3350
+ # backreference, but can't say so. Later versions and TruffleRuby can.
3351
+ MEMOIZES_WITHOUT_LOOKAROUNDS =
3352
+ RUBY_ENGINE == 'ruby' && RUBY_VERSION.start_with?('3.2.')
3353
+ UNMEMOIZED = /\(\?(?:[=!>]|<[=!])|[*+?}]\+|\\[1-9k]/
3354
+ LINEAR_TIME_CHECKED =
3355
+ Regexp.respond_to?(:linear_time?) || MEMOIZES_WITHOUT_LOOKAROUNDS
3356
+ private_constant :MEMOIZES_WITHOUT_LOOKAROUNDS, :UNMEMOIZED,
3357
+ :LINEAR_TIME_CHECKED
3358
+
3359
+ ##
3360
+ # Whether the regular expression engine matches a regexp in linear time.
3361
+ #
3362
+ # @param [Regexp] regexp The regexp.
3363
+ #
3364
+ # @return [TrueClass, FalseClass]
3365
+ def linear_time?(regexp)
3366
+ if Regexp.respond_to?(:linear_time?)
3367
+ Regexp.linear_time?(regexp)
3368
+ else
3369
+ regexp.source !~ UNMEMOIZED
3370
+ end
1233
3371
  end
1234
3372
 
1235
3373
  end