regexes 0.0.0 → 0.1.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: dfe1f0e6dac42eaedbbc257f6abc199ec25810aa5b36e85b76838f2af4ba03e2
4
- data.tar.gz: 274c09a5bd347bef58ad4505ab9c6502b416767fe62482c7b18b9ab2aafda311
3
+ metadata.gz: 7f272f5116d87f990a3f5acb0ca3fdcb105fbe981c8f9a3e9718505089279f83
4
+ data.tar.gz: 1817efa5a01462e65a3e7bbcb0c13ecdbeb472ed4293a2c2300dd549c577abc7
5
5
  SHA512:
6
- metadata.gz: 8e37c49f17d8937c2113ac8a07abfaf01253f74129cd3b63c2dfc79c7c106d726574b1573f6c56483ec4a9d9f848090ed237dde6f66be6d09cd369fa66b9f6d3
7
- data.tar.gz: b186be7a17e345777976c463b76a38f66c2bfd8ee548b41aa261d5e29cb6bc0941d33716e8d41c20e734afa5093f8b525972dc64ce91f47f1f34e36931db165b
6
+ metadata.gz: 98a99c67338f7865fbb5e0900d3e38b9abea6d00959a44e8ad9d15740943791da85d5e08180e49d747d66c0e70df8af17addda11c31061371c04277431f0112b
7
+ data.tar.gz: 7a58255860694fa63fffc664fe88c36ad1c827223f608fcbb17f2b2cd4305896720133fe643958a492ee7d3a74ca9ae6c977bc25315bc5033053c82ab3cfe485
data/CHANGELOG.md ADDED
@@ -0,0 +1,61 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 - 2026-11-21
4
+
5
+ ### Added
6
+
7
+ - The library, extracted from an application where it was written: `Regexes::Expression` (a frozen
8
+ `Regexp` with anchors, repetition and case-insensitivity), `Regexes::CharacterClass` (a set of
9
+ characters that can be excluded and extended), `Regexes.sequence` and `Regexes.either`, and the named
10
+ patterns: sets of characters, line breaks, integers, UUIDs, identifiers, UTC offsets, ISO 8601 times,
11
+ HTTP schemes, DNS labels, domain names, email addresses and Markdown code spans.
12
+ - `Regexes.iso8601_date` and `Regexes.iso8601_time` (the time of day), of which `iso8601_date_time` is built.
13
+ - Line anchors: `Expression#line_leading`, `#line_trailing` and `#whole_line`, which know `\r\n`, `\r` and
14
+ `\n` as line breaks, and `#line_leading?` / `#line_trailing?`.
15
+ - `Expression#captured(name)`, a named capture around an expression.
16
+ - Lookarounds: `Expression#followed_by`, `#not_followed_by`, `#preceded_by` and `#not_preceded_by`.
17
+ - `Regexes.literal(text)`, text matched character for character.
18
+ - `Regexes.register(name, pattern)` adds an application's own pattern under a name, as a frozen expression with
19
+ every variation; `Regexes.registered` lists the names added.
20
+ - Sets: `uppercase_letters`, `uppercase_alphanumeric`, `binary_digits`, `octal_digits`, `base32_digits`,
21
+ `base58_digits`, `base64_digits`, `base64url_digits`, `ascii_whitespace`, `dashes`, `apostrophes`,
22
+ `double_quotes`, `unicode_letters`, `unicode_digits`, `combining_marks`, `control_characters` and
23
+ `format_characters`.
24
+ - Breaks: `unicode_line_break` and `paragraph_break`.
25
+ - Numbers: `unsigned_integer`, `positive_integer`, `decimal(places:)`, `unsigned_decimal(places:)`, `json_number`,
26
+ `latitude`, `longitude` and `port_number`.
27
+ - Identifiers: `snake_case`, `screaming_snake_case`, `kebab_case`, `camel_case`, `pascal_case`, `ulid`,
28
+ `semantic_version`, `media_type`, `json_web_token`, `base64` and `base64url`.
29
+ - Times: `iso8601_year_month`, `iso8601_duration` and `rfc3339_timestamp`.
30
+ - Network: `uri_scheme`, `http_url`, `ipv4_address`, `ipv6_address`, `ip_address`, `ipv4_cidr`, `ipv6_cidr` and
31
+ `mac_address`.
32
+ - Mail: `message_id` and `header_field_name`.
33
+ - Codes: `e164_phone_number`, `iban`, `bic`, `language_tag` and `hex_color`.
34
+ - Text: `markdown_code_block` (a fenced block, capturing its `language` and `code`), `markdown_link`,
35
+ `ruby_format_reference`, `mustache_tag`, `shell_variable_reference`, `file_extension` and `emoji`.
36
+ - `Regexes.markdown_code_span` takes a fence of any number of backticks (so ``` ``a ` b`` ``` holds a backtick),
37
+ closing at the first run of the same length, and runs over a line break but never a blank line.
38
+ - `Expression#ecma_source` and `#ecma_flags` translate an expression into ECMAScript, for JavaScript and JSON
39
+ Schema; what ECMAScript can't match the same way raises `Regexes::UntranslatableError`.
40
+
41
+ ### Changed
42
+
43
+ - **Breaking:** `Regexes.iso8601_time` is renamed `iso8601_date_time`; `iso8601_time` is now the time of day
44
+ alone. `Regexes.backtick_code` is renamed `markdown_code_span`.
45
+ - **Breaking:** `Regexes.email_address` matches what an HTML `type=email` input accepts (WHATWG) instead of
46
+ any text around one `@`: quoted local parts, IP-literal domains and characters outside the WHATWG set are
47
+ refused.
48
+ - **Breaking:** ISO 8601 fields are checked against their ranges (month, day, hour, minute, second, offset),
49
+ so `2026-13-01` and `24:00` are refused.
50
+
51
+ - `Regexes.uuid`, and the ISO 8601 patterns that start or end with a digit, never match inside a longer run of
52
+ hex digits or digits.
53
+
54
+ ### Fixed
55
+
56
+ - `Regexes.dns_label` refuses a label of more than 63 characters, and `Regexes.domain_name` a name of more
57
+ than 253 (RFC 1035).
58
+
59
+ ## 0.0.0 - 2026-11-21
60
+
61
+ - Reserved the name on RubyGems.
data/README.md CHANGED
@@ -1,16 +1,146 @@
1
+ > **You are reading the gem package readme.** The repository also contains
2
+ > [`site/`](../site), the docs site. See the [root README](../README.md) for
3
+ > the layout overview.
4
+
1
5
  # regexes
2
6
 
3
- Early days. For now it wraps a regex and answers a few questions about text.
7
+ [![Gem Version](https://img.shields.io/gem/v/regexes)](https://rubygems.org/gems/regexes)
8
+ [![CI](https://github.com/sebscholl-labs/regexes/actions/workflows/ci.yml/badge.svg)](https://github.com/sebscholl-labs/regexes/actions/workflows/ci.yml)
9
+ [![Release](https://img.shields.io/github/v/release/sebscholl-labs/regexes)](https://github.com/sebscholl-labs/regexes/releases)
10
+ [![License](https://img.shields.io/github/license/sebscholl-labs/regexes)](https://github.com/sebscholl-labs/regexes/blob/main/LICENSE.txt)
11
+ [![Ruby](https://img.shields.io/badge/Ruby-%3E%3D%204.0-red)](https://rubygems.org/gems/regexes)
12
+
13
+ **The regex you need, already written.** Patterns named for what they match — UUIDs, IP addresses,
14
+ ISO 8601 times, IBANs — each a frozen `Regexp` that chains anchors, repetition and captures, tested against
15
+ Ruby's own parsers, and runs the same in JavaScript. Every pattern goes anywhere a Regexp does: `gsub`,
16
+ `match?`, `scan`, `case`, `validates format:`.
17
+
18
+ Full documentation: <https://sebscholl-labs.github.io/regexes/>
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ bundle add regexes
24
+ ```
25
+
26
+ or:
27
+
28
+ ```bash
29
+ gem install regexes
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ ```ruby
35
+ require 'regexes'
36
+
37
+ # Search finds whole values: the usual IPv4 regex finds 1.2.3.456 here.
38
+ 'Retry 10.0.0.1, not 1.2.3.456'.scan(Regexes.ipv4_address) # => ["10.0.0.1"]
39
+
40
+ # Validate with .whole: \A and \z, never Ruby's line anchors ^ and $.
41
+ Regexes.lowercase_letters.one_or_more.whole.match?("ok\nevil") # => false
42
+
43
+ # Every form IPv6 writes, and every field range ISO 8601 defines.
44
+ Regexes.ipv6_address.whole.match?('::ffff:192.0.2.1') # => true
45
+ Regexes.iso8601_date_time.whole.match?('2026-13-21T25:61') # => false
46
+
47
+ # Parts come back by name, in the standard's terms.
48
+ Regexes.semantic_version.match('2.1.3-rc.1+sha.5114f85')[:build] # => "sha.5114f85"
49
+ Regexes.http_url.match('http://[::1]:8080/a?b=c#d')[:host] # => "[::1]"
50
+
51
+ # Patterns chain, and compose into your own.
52
+ Regexes.digits.excluded.one_or_more # => /[^0-9]+/
53
+ Regexes.sequence(Regexes.lowercase_letters, Regexes.word_characters.between(0, 23)).whole
54
+ ```
55
+
56
+ ## Named patterns
57
+
58
+ | Section | Patterns |
59
+ |---|---|
60
+ | Sets of characters | `lowercase_letters` `uppercase_letters` `letters` `digits` `lowercase_alphanumeric` `uppercase_alphanumeric` `alphanumeric` `word_characters` `binary_digits` `octal_digits` `hex_digits` `base32_digits` `base58_digits` `base64_digits` `base64url_digits` `whitespace` `ascii_whitespace` `space_or_tab` `newline` `slash` `hyphen` `dashes` `apostrophes` `double_quotes` `unicode_letters` `unicode_digits` `combining_marks` `control_characters` `format_characters` |
61
+ | Characters and breaks | `any_character` `line_break` `unicode_line_break` `paragraph_break` |
62
+ | Numbers | `integer` `unsigned_integer` `positive_integer` `decimal(places:)` `unsigned_decimal(places:)` `json_number` `latitude` `longitude` `port_number` |
63
+ | Identifiers | `identifier` `snake_case` `screaming_snake_case` `kebab_case` `camel_case` `pascal_case` `uuid` `ulid` `semantic_version` `media_type` `json_web_token` `base64` `base64url` |
64
+ | Times | `utc_offset` `iso8601_date` `iso8601_year_month` `iso8601_time` `iso8601_date_time` `iso8601_duration` `rfc3339_timestamp` |
65
+ | Network | `uri_scheme` `http_scheme` `http_url` `dns_label` `domain_name` `ipv4_address` `ipv6_address` `ip_address` `ipv4_cidr` `ipv6_cidr` `mac_address` |
66
+ | Mail | `email_address` `message_id` `header_field_name` `folded_line_break` `unfolded_line_break` |
67
+ | Codes | `e164_phone_number` `iban` `bic` `language_tag` `hex_color` |
68
+ | Text | `markdown_code_span` `markdown_code_block` `markdown_link` `ruby_format_reference` `mustache_tag` `shell_variable_reference` `file_extension` `emoji` |
69
+
70
+ Each checks shape, never meaning (no checksums, no calendar), and one made of a fixed count of digits or
71
+ letters never matches inside a longer run, so searching text finds whole values. Codes that are only a set and
72
+ a count are written as one: a country code is `Regexes.uppercase_letters.exactly(2)`. The
73
+ [reference](https://sebscholl-labs.github.io/regexes/reference/patterns) says what each matches, refuses and
74
+ captures.
75
+
76
+ Names follow [a fixed set of conventions](https://sebscholl-labs.github.io/regexes/design/naming), so the
77
+ one you need can be guessed.
78
+
79
+ ## Variations
80
+
81
+ Every pattern chains these. Each returns a new frozen pattern and leaves the original as it was.
82
+
83
+ - **Anchors:** `leading` (`\A`), `trailing` (`\z`), `whole` (both) anchor to the text, never a line.
84
+ `line_leading`, `line_trailing` and `whole_line` anchor to a line, ended by `\r\n`, `\r` or `\n`.
85
+ - **Repetition:** `one_or_more`, `zero_or_more`, `optional`, `exactly(n)`, `at_least(n)`, `between(min, max)`.
86
+ Repeating a multi-part pattern groups it first, so `ab` repeated is `abab`. Repeat before anchoring.
87
+ - **Case:** `case_insensitive`.
88
+ - **Captures:** `captured(:name)`, read back with `match[:name]`.
89
+ - **Lookarounds:** `followed_by(other)`, `not_followed_by(other)`, `preceded_by(other)`, `not_preceded_by(other)`.
90
+ - **Sets only:** `excluded` (`[^…]`) and `including(characters)`.
91
+
92
+ ## Composition
93
+
94
+ ```ruby
95
+ handle = Regexes.sequence(Regexes.lowercase_letters, Regexes.word_characters.between(0, 23)).whole
96
+ ends = Regexes.either(Regexes.hyphen.one_or_more.leading, Regexes.hyphen.one_or_more.trailing)
97
+
98
+ '--acme-mail-'.gsub(ends, '') # => "acme-mail"
99
+ ```
100
+
101
+ A case-insensitive part stays case-insensitive inside a case-sensitive sequence. `Regexes.literal(text)`
102
+ matches text character for character, the safe way to put a value into a pattern:
4
103
 
5
104
  ```ruby
6
- require "regexes"
105
+ Regexes.literal('.ns.cloudflare.com').trailing # dots that mean dots
106
+ ```
7
107
 
8
- pattern = Regexes::Pattern.new(/\d+/)
108
+ ## In JavaScript and JSON Schema
9
109
 
10
- pattern.match?("abc123") # => true
11
- pattern.matches("a1 b22 c333") # => ["1", "22", "333"]
12
- pattern.count("a1 b22 c333") # => 3
13
- pattern.highlight("a1 b22 c333") # => "a[1] b[22] c[333]"
110
+ Every pattern but `emoji` translates into ECMAScript, for the browser, a mobile app or a JSON Schema
111
+ `pattern`:
112
+
113
+ ```ruby
114
+ Regexes.uuid.whole.ecma_source # => "^(?<![0-9a-fA-F])[0-9a-fA-F]{8}-…$"
115
+ Regexes.uuid.whole.ecma_flags # => "u"
14
116
  ```
15
117
 
16
- You can pass a string instead of a Regexp, e.g. `Regexes::Pattern.new("\\d+")`.
118
+ What the two languages write differently is rewritten (`\A` becomes `^`, the dot `[^\n]`); what ECMAScript
119
+ can't match the same way (`Regexes.emoji`'s grapheme clusters) raises `Regexes::UntranslatableError`. The test
120
+ suite runs every translated pattern in Node against Ruby.
121
+
122
+ ## Your own patterns
123
+
124
+ Register a shape of your application's and it's named, varied and composed like the built-in ones:
125
+
126
+ ```ruby
127
+ Regexes.register(:order_reference, /ORD-[0-9]{6}/)
128
+
129
+ Regexes.order_reference.whole.match?('ORD-004211') # => true
130
+ Regexes.registered # => [:order_reference]
131
+ ```
132
+
133
+ Register the shape unanchored, under a snake_case name nothing else uses; anything else raises
134
+ `ArgumentError`.
135
+
136
+ ## Development
137
+
138
+ ```sh
139
+ bin/setup
140
+ bundle exec rake # tests + RuboCop
141
+ bin/console # IRB with regexes loaded
142
+ ```
143
+
144
+ ## License
145
+
146
+ [MIT](./LICENSE.txt)
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Regexes
4
+ # A set of characters, matching any one of them, with the variations a set allows beyond an expression's:
5
+ # the characters outside it ({#excluded}) and the set with more characters in it ({#including}).
6
+ #
7
+ # Its members are written as they would be between a regular expression's brackets: +a-z0-9+. A set is one
8
+ # unit, so it is repeated as it is: +[a-z]++.
9
+ class CharacterClass < Expression
10
+ # @return [String] the characters in the set, as written between brackets
11
+ attr_reader :members
12
+
13
+ # @param members [String] the characters in the set, as written between brackets
14
+ # @param excluded [Boolean] whether it matches any character but these
15
+ # @param options [Integer] +Regexp+ options, such as +Regexp::IGNORECASE+
16
+ def initialize(members, excluded: false, options: 0)
17
+ @members = members
18
+ @excluded = excluded
19
+ super("[#{'^' if excluded}#{members}]", single: true, options:)
20
+ end
21
+
22
+ # +Regexes.lowercase_letters.excluded+ matches the +1+ and the +A+ of +a1A+. Excluding the excluded set
23
+ # gives back the set.
24
+ #
25
+ # @return [CharacterClass] the set of every character not in this one
26
+ def excluded = CharacterClass.new(members, excluded: !excluded?, options:)
27
+
28
+ # +Regexes.lowercase_alphanumeric.including('_')+ matches +a+, +1+ and +_+. An excluded set excludes the
29
+ # added characters too: +Regexes.slash.excluded.including('?')+ matches neither +/+ nor +?+.
30
+ #
31
+ # @param characters [String] more characters, as written between brackets
32
+ # @return [CharacterClass] the set with them
33
+ def including(characters) = CharacterClass.new("#{members}#{characters}", excluded: excluded?, options:)
34
+
35
+ # @return [CharacterClass] the set, matching letters of either case
36
+ def case_insensitive = CharacterClass.new(members, excluded: excluded?, options: options | IGNORECASE)
37
+
38
+ # @return [Boolean] whether it matches the characters outside its members
39
+ def excluded? = @excluded
40
+ end
41
+ end
@@ -0,0 +1,230 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Regexes
4
+ # Raised when an expression uses what ECMAScript has no faithful equivalent for, so translating it would give a
5
+ # pattern that matches something else.
6
+ class UntranslatableError < StandardError; end
7
+
8
+ # Translates an expression's Ruby source into ECMAScript's, for +new RegExp(source, flags)+ in JavaScript and
9
+ # for a JSON Schema +pattern+ (see {Expression#ecma_source}).
10
+ #
11
+ # It rewrites what the two write differently: the text's anchors (+\A+, +\z+ become +^+, +$+, which without
12
+ # the +m+ flag anchor to the text in ECMAScript, with no allowance for a final line feed); the dot, which in
13
+ # ECMAScript also refuses +\r+ and the line separators; Ruby's POSIX +[:space:]+ and +\R+; and escapes Ruby
14
+ # allows of characters that need none, which ECMAScript's +u+ mode refuses. What has no equivalent raises
15
+ # {UntranslatableError}: +\X+, atomic groups, inline options, a name captured twice, and Ruby's line anchors.
16
+ module Ecma
17
+ extend self
18
+
19
+ # What a Ruby escape outside a character class becomes in ECMAScript, where it differs.
20
+ ESCAPES = {
21
+ 'A' => '^',
22
+ 'z' => '$',
23
+ 'R' => '(?:\r\n|[\n\v\f\r\x85

])',
24
+ 's' => '[ \t\n\v\f\r]'
25
+ }.freeze
26
+ # What a Ruby escape inside a character class becomes in ECMAScript, where it differs.
27
+ CLASS_ESCAPES = { 's' => ' \t\n\v\f\r' }.freeze
28
+ # Escapes both write alike: the shorthands both define as Ruby does, and the escapes of characters that
29
+ # mean something in a pattern.
30
+ KEPT = 'dDwWbBnrtfv0123456789^$\\.*+?()[]{}|/'
31
+ # Escapes ECMAScript has no faithful equivalent for, and why.
32
+ UNTRANSLATABLE = {
33
+ 'X' => 'a grapheme cluster (\X)',
34
+ 'Z' => 'the end of the text or before its final line feed (\Z)',
35
+ 'h' => "Ruby's hex digit (\\h)",
36
+ 'H' => "Ruby's non-hex digit (\\H)",
37
+ 'G' => 'the end of the last match (\G)',
38
+ 'K' => 'a match reset (\K)',
39
+ 'g' => 'a subexpression call (\g)'
40
+ }.freeze
41
+ # Group openings both write alike.
42
+ GROUPS = ['(?:', '(?=', '(?!', '(?<=', '(?<!'].freeze
43
+ # A named capture's opening.
44
+ NAMED_GROUP = /\A\(\?<([A-Za-z_][A-Za-z0-9_]*)>/
45
+ # A quantifier in braces, which ECMAScript writes as Ruby does; any other brace is a literal to escape.
46
+ QUANTIFIER = /\A\{[0-9]+(?:,[0-9]*)?\}/
47
+ # A Unicode escape: four hex digits, or any number in braces.
48
+ UNICODE_ESCAPE = /\A\\u(?:[0-9a-fA-F]{4}|\{[0-9a-fA-F]+\})/
49
+ # A back-reference to a named capture, which ECMAScript writes as Ruby does.
50
+ BACK_REFERENCE = /\A\\k<[A-Za-z_][A-Za-z0-9_]*>/
51
+
52
+ # @param expression [Expression] an expression
53
+ # @return [String] its source as ECMAScript writes it
54
+ # @raise [UntranslatableError] when it uses what ECMAScript has no faithful equivalent for
55
+ def source(expression) = Translation.new(expression.source).result
56
+
57
+ # @param expression [Expression] an expression
58
+ # @return [String] the flags its source needs in ECMAScript: +u+, and +i+ when it ignores case
59
+ # @raise [UntranslatableError] when it is written in extended mode, or matches newlines with +.+
60
+ def flags(expression)
61
+ raise UntranslatableError, "#{expression.inspect} is extended (x), which ECMAScript can't read" if
62
+ expression.options.anybits?(Regexp::EXTENDED)
63
+ raise UntranslatableError, "#{expression.inspect} lets . match newlines (m), which this translation keeps out" if
64
+ expression.options.anybits?(Regexp::MULTILINE)
65
+
66
+ expression.options.anybits?(Regexp::IGNORECASE) ? 'iu' : 'u'
67
+ end
68
+
69
+ # One source being translated, a character at a time.
70
+ class Translation
71
+ # @param ruby [String] a Ruby regular expression's source
72
+ def initialize(ruby)
73
+ @ruby = ruby
74
+ @at = 0
75
+ @in_class = false
76
+ @names = []
77
+ @result = +''
78
+ end
79
+
80
+ # @return [String] the source as ECMAScript writes it, frozen
81
+ # @raise [UntranslatableError] when it uses what ECMAScript has no faithful equivalent for
82
+ def result
83
+ step while @at < @ruby.length
84
+ @result.freeze
85
+ end
86
+
87
+ private
88
+
89
+ # Translates what starts at the current character, and moves past it.
90
+ #
91
+ # @return [void]
92
+ def step
93
+ character = @ruby[@at]
94
+ case character
95
+ when '\\' then escape
96
+ when '[' then open_class
97
+ when ']' then @in_class ? close_class : plain(character)
98
+ when '(' then @in_class ? take(character) : group
99
+ else plain(character)
100
+ end
101
+ end
102
+
103
+ # @param character [String] a character with no special meaning here, or one translated as it is
104
+ # @return [void]
105
+ def plain(character)
106
+ return take(character) if @in_class
107
+
108
+ case character
109
+ when '.' then put('[^\n]', 1)
110
+ when '{' then brace
111
+ when '}', ']' then put("\\#{character}", 1)
112
+ when '^', '$' then untranslatable("Ruby's line anchor (#{character}); use line_leading or line_trailing")
113
+ else take(character)
114
+ end
115
+ end
116
+
117
+ # Copies a quantifier in braces as it is, and escapes a brace that starts none.
118
+ #
119
+ # @return [void]
120
+ def brace = QUANTIFIER.match?(@ruby[@at..]) ? copy(QUANTIFIER) : put('\{', 1)
121
+
122
+ # @return [void]
123
+ def escape
124
+ letter = @ruby[@at + 1]
125
+ untranslatable(UNTRANSLATABLE.fetch(letter)) if UNTRANSLATABLE.key?(letter)
126
+
127
+ case letter
128
+ when 'p', 'P' then property
129
+ when 'u' then copy(UNICODE_ESCAPE)
130
+ when 'k' then back_reference
131
+ when 'x' then put(@ruby[@at, 4], 4)
132
+ else put(escaped(letter), 2)
133
+ end
134
+ end
135
+
136
+ # Copies a back-reference to a named capture, which ECMAScript writes alike.
137
+ #
138
+ # @return [void]
139
+ # @raise [UntranslatableError] when it refers to a capture by number
140
+ def back_reference
141
+ untranslatable('a back-reference by number (\k<1>)') unless BACK_REFERENCE.match?(@ruby[@at..])
142
+
143
+ copy(BACK_REFERENCE)
144
+ end
145
+
146
+ # @param letter [String] the character after a backslash
147
+ # @return [String] that escape as ECMAScript writes it here
148
+ def escaped(letter)
149
+ table = @in_class ? CLASS_ESCAPES : ESCAPES
150
+ return table.fetch(letter) if table.key?(letter)
151
+ return "\\#{letter}" if KEPT.include?(letter) || (@in_class && letter == '-')
152
+
153
+ letter
154
+ end
155
+
156
+ # Copies a Unicode property escape, +\p{…}+, as it is: the names Ruby and ECMAScript share are written
157
+ # alike.
158
+ #
159
+ # @return [void]
160
+ def property
161
+ close = @ruby.index('}', @at)
162
+ put(@ruby[@at..close], close - @at + 1)
163
+ end
164
+
165
+ # @return [void]
166
+ def open_class
167
+ if @in_class
168
+ return put('\p{White_Space}', 9) if @ruby[@at, 9] == '[:space:]'
169
+
170
+ untranslatable('a nested character class or POSIX bracket')
171
+ end
172
+
173
+ @in_class = true
174
+ take('[')
175
+ end
176
+
177
+ # @return [void]
178
+ def close_class
179
+ @in_class = false
180
+ take(']')
181
+ end
182
+
183
+ # @return [void]
184
+ def group
185
+ opening = GROUPS.find { @ruby[@at, it.length] == it }
186
+ return put(opening, opening.length) if opening
187
+ return put('(', 1) unless @ruby[@at + 1] == '?'
188
+
189
+ named_group
190
+ end
191
+
192
+ # Copies a named capture's opening, once for each name.
193
+ #
194
+ # @return [void]
195
+ def named_group
196
+ named = NAMED_GROUP.match(@ruby[@at..])
197
+ untranslatable('an atomic group, inline options or a comment') unless named
198
+ untranslatable("the capture name #{named[1]} used twice") if @names.include?(named[1])
199
+
200
+ @names << named[1]
201
+ copy(NAMED_GROUP)
202
+ end
203
+
204
+ # @param character [String] the current character, copied as it is
205
+ # @return [void]
206
+ def take(character) = put(character, 1)
207
+
208
+ # @param pattern [Regexp] what starts at the current character, anchored at its start
209
+ # @return [void]
210
+ def copy(pattern)
211
+ text = pattern.match(@ruby[@at..])[0]
212
+ put(text, text.length)
213
+ end
214
+
215
+ # @param text [String] what to write
216
+ # @param length [Integer] how many characters of the Ruby source it stands for
217
+ # @return [void]
218
+ def put(text, length)
219
+ @result << text
220
+ @at += length
221
+ end
222
+
223
+ # @param what [String] what can't be translated
224
+ # @raise [UntranslatableError] always
225
+ def untranslatable(what)
226
+ raise UntranslatableError, "/#{@ruby}/ uses #{what}, which ECMAScript can't match the same way"
227
+ end
228
+ end
229
+ end
230
+ end