Class: Janeway::Parser

Inherits:
Object
  • Object
show all
Includes:
Functions
Defined in:
lib/janeway/parser.rb

Overview

Transform a list of tokens into an Abstract Syntax Tree

Constant Summary collapse

UNARY_OPERATORS =
%w[! -].freeze
BINARY_OPERATORS =
%w[== != > < >= <= ,].freeze
LOGICAL_OPERATORS =
%w[&& ||].freeze
LOWEST_PRECEDENCE =
0
OPERATOR_PRECEDENCE =
{
  ',' => 0,
  '||' => 1,
  '&&' => 2,
  '==' => 3,
  '!=' => 3,
  '>' => 4,
  '<' => 4,
  '>=' => 4,
  '<=' => 4,
  '(' => 8,
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Functions

#parse_function_count, #parse_function_length, #parse_function_match, #parse_function_parameter, #parse_function_search, #parse_function_value, #translate_iregex_to_ruby_regex

Constructor Details

#initialize(tokens, jsonpath) ⇒ Parser

Returns a new instance of Parser.

Parameters:

  • tokens (Array<Token>)
  • jsonpath (String)

    original jsonpath query string



42
43
44
45
46
# File 'lib/janeway/parser.rb', line 42

def initialize(tokens, jsonpath)
  @tokens = tokens
  @next_p = 0
  @jsonpath = jsonpath
end

Instance Attribute Details

#tokensObject (readonly)

Returns the value of attribute tokens.



10
11
12
# File 'lib/janeway/parser.rb', line 10

def tokens
  @tokens
end

Class Method Details

.parse(jsonpath) ⇒ AST::Query

Parameters:

  • jsonpath (String)

    jsonpath query to be lexed and parsed

Returns:

Raises:

  • (ArgumentError)


33
34
35
36
37
38
# File 'lib/janeway/parser.rb', line 33

def self.parse(jsonpath)
  raise ArgumentError, "expect jsonpath string, got #{jsonpath.inspect}" unless jsonpath.is_a?(String)

  tokens = Janeway::Lexer.lex(jsonpath)
  new(tokens, jsonpath).parse
end

Instance Method Details

#parseAST::Query

Parse the token list and create an Abstract Syntax Tree

Returns:



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/janeway/parser.rb', line 50

def parse
  consume
  raise err('JsonPath queries must start with root identifier "$"') unless current.type == :root

  root_node = parse_root
  consume
  unless current.type == :eof
    remaining = tokens[@next_p..].map(&:lexeme).join
    raise err("Unrecognized expressions after query: #{remaining}")
  end

  AST::Query.new(root_node, @jsonpath)
end