Module: SrlRuby

Defined in:
lib/srl_ruby.rb,
lib/srl_ruby/grammar.rb,
lib/srl_ruby/version.rb,
lib/srl_ruby/tokenizer.rb,
lib/srl_ruby/ast_builder.rb

Defined Under Namespace

Classes: ASTBuilder, Tokenizer

Constant Summary collapse

Grammar =

And now build the grammar and make it accessible via a global constant [Rley::Syntax::Grammar]

builder.grammar
VERSION =
'0.4.13'

Class Method Summary collapse

Class Method Details

.load_file(filename) ⇒ Regexp

Compile the SRL expression in given filename into a Regexp object.



12
13
14
15
16
17
18
# File 'lib/srl_ruby.rb', line 12

def self.load_file(filename)
  source = nil
  File.open(filename, 'r') { |f| source = f.read }
  return source if source.nil? || source.empty?

  parse(source)
end

.parse(source) ⇒ Regexp

Compile the given SRL expression into its Regexp equivalent.

Examples:

Matching a (signed) integer literal

some_srl ="  begin with\n    (one of \"+-\") optional,\n    digit once or more,\n  must end\n"
regex = SrlRuby::API.parse(some_srl) # => regex == /^[+\-]?\d+$/


31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/srl_ruby.rb', line 31

def self.parse(source)
  # Create a Rley facade object
  engine = Rley::Engine.new { |cfg| cfg.diagnose = true }

  # Step 1. Load SRL grammar
  engine.use_grammar(SrlRuby::Grammar)

  lexer = SrlRuby::Tokenizer.new(source)
  result = engine.parse(lexer.tokens)

  unless result.success?
    # Stop if the parse failed...
    line1 = "Parsing failed\n"
    line2 = "Reason: #{result.failure_reason.message}"
    raise StandardError, line1 + line2
  end

  # Generate an abstract syntax tree (AST) from the parse result
  engine.configuration.repr_builder = SrlRuby::ASTBuilder
  ast_ptree = engine.convert(result)

  # Now output the regexp literal
  root = ast_ptree.root
  options = root.is_a?(Regex::MatchOption) ? root.combine_opts : nil
  Regexp.new(root.to_str, options)
end