File: ecma-re-validator.rb

package info (click to toggle)
ruby-ecma-re-validator 0.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 188 kB
  • sloc: ruby: 297; makefile: 4; sh: 3
file content (49 lines) | stat: -rw-r--r-- 1,238 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# frozen_string_literal: true

require 'regexp_parser'

module EcmaReValidator
  # JS doesn't have Unicode matching
  UNICODE_CHARACTERS = Regexp::Syntax::Token::UnicodeProperty::All

  INVALID_REGEXP = [
    # JS doesn't have \A, \Z, \z
    :bos, :eos_ob_eol, :eos,
    # JS doesn't have lookbehinds
    :lookbehind, :nlookbehind,
    # JS doesn't have atomic grouping
    :atomic,
    # JS doesn't have possesive quantifiers
    :zero_or_one_possessive, :zero_or_more_possessive, :one_or_more_possessive,
    # JS doesn't have named capture groups
    :named_ab, :named_sq,
    # JS doesn't support modifying options
    :options, :options_switch,
    # JS doesn't support conditionals
    :condition_open,
    # JS doesn't support comments
    :comment
  ].freeze

  INVALID_TOKENS = INVALID_REGEXP + UNICODE_CHARACTERS

  def self.valid?(input)
    if input.is_a? String
      begin
        input = Regexp.new(input)
      rescue RegexpError
        return false
      end
    elsif !input.is_a? Regexp
      return false
    end

    Regexp::Scanner.scan(input).none? do |t|
      if t[1] == :word || t[1] == :space || t[1] == :digit
        t[0] != :type
      else
        INVALID_TOKENS.include?(t[1])
      end
    end
  end
end