Class: Fast::ExpressionParser

Inherits:
Object
  • Object
show all
Defined in:
lib/fast.rb

Overview

ExpressionParser empowers the AST search in Ruby. All classes inheriting Fast::Find have a grammar shortcut that is processed here.

Examples:

find a simple int node

Fast.expression("int")
# => #<Fast::Find:0x00007ffae39274e0 @token="int">

parens make the expression an array of Fast::Find and children classes

Fast.expression("(int _)")
# => [#<Fast::Find:0x00007ffae3a860e8 @token="int">, #<Fast::Find:0x00007ffae3a86098 @token="_">]

not int token

Fast.expression("!int")
# => #<Fast::Not:0x00007ffae43f35b8 @token=#<Fast::Find:0x00007ffae43f35e0 @token="int">>

int or float token

Fast.expression("{int float}")
# => #<Fast::Any:0x00007ffae43bbf00 @token=[
#      #<Fast::Find:0x00007ffae43bbfa0 @token="int">,
#      #<Fast::Find:0x00007ffae43bbf50 @token="float">
#     #]>

capture something not nil

Fast.expression("$_")
# => #<Fast::Capture:0x00007ffae433a860 @captures=[], @token=#<Fast::Find:0x00007ffae433a888 @token="_">>

capture a hash with keys that all are not string and not symbols

Fast.expression("(hash (pair ([!sym !str] _))")
# => [#<Fast::Find:0x00007ffae3b45010 @token="hash">,
#      [#<Fast::Find:0x00007ffae3b44f70 @token="pair">,
#       [#<Fast::All:0x00007ffae3b44cf0 @token=[
#         #<Fast::Not:0x00007ffae3b44e30 @token=#<Fast::Find:0x00007ffae3b44e80 @token="sym">>,
#         #<Fast::Not:0x00007ffae3b44d40 @token=#<Fast::Find:0x00007ffae3b44d68 @token="str">>]>,
#         #<Fast::Find:0x00007ffae3b44ca0 @token="_">]]]")")

of match using string expression

Fast.match?(Fast.ast("{1 => 1}"),"(hash (pair ([!sym !str] _))") => true")")

Instance Method Summary collapse

Constructor Details

#initialize(expression) ⇒ ExpressionParser

Returns a new instance of ExpressionParser.

Parameters:

  • expression (String)


388
389
390
# File 'lib/fast.rb', line 388

def initialize(expression)
  @tokens = expression.scan TOKENIZER
end

Instance Method Details

#parseObject

rubocop:disable Metrics/CyclomaticComplexity rubocop:disable Metrics/AbcSize rubocop:disable Metrics/MethodLength



395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'lib/fast.rb', line 395

def parse
  case (token = next_token)
  when '(' then parse_until_peek(')')
  when '{' then Any.new(parse_until_peek('}'))
  when '[' then All.new(parse_until_peek(']'))
  when /^"/ then FindString.new(token[1..-2])
  when /^#\w/ then MethodCall.new(token[1..])
  when /^\.\w[\w\d_]+\?/ then InstanceMethodCall.new(token[1..])
  when '$' then Capture.new(parse)
  when '!' then (@tokens.any? ? Not.new(parse) : Find.new(token))
  when '?' then Maybe.new(parse)
  when '^' then Parent.new(parse)
  when '\\' then FindWithCapture.new(parse)
  when /^%\d/ then FindFromArgument.new(token[1..])
  else Find.new(token)
  end
end