Class: Janeway::Interpreter

Inherits:
Object
  • Object
show all
Includes:
Interpreters
Defined in:
lib/janeway/interpreter.rb

Overview

Tree-walk interpreter to apply the operations from the abstract syntax tree to the input.

This is not intended to be thread-safe, so create this inside a thread as needed. It should be created for a single query and then discarded.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(query, as: :finder, &block) ⇒ Interpreter

Returns a new instance of Interpreter.

Parameters:

  • query (Query)

    abstract syntax tree of the jsonpath query

Raises:

  • (ArgumentError)


27
28
29
30
31
32
33
34
35
36
37
# File 'lib/janeway/interpreter.rb', line 27

def initialize(query, as: :finder, &block)
  raise ArgumentError, "expect Query, got #{query.inspect}" unless query.is_a?(Query)
  unless %i[finder iterator deleter delete_if].include?(as)
    raise ArgumentError, "invalid interpreter type: #{as.inspect}"
  end

  @query = query
  @type = as
  @jsonpath = query.jsonpath
  @root = query_to_interpreter_tree(@query, &block)
end

Instance Attribute Details

#jsonpathObject (readonly)

Returns the value of attribute jsonpath.



13
14
15
# File 'lib/janeway/interpreter.rb', line 13

def jsonpath
  @jsonpath
end

#outputObject (readonly)

Returns the value of attribute output.



13
14
15
# File 'lib/janeway/interpreter.rb', line 13

def output
  @output
end

Class Method Details

.interpret(input, query) ⇒ Object

Interpret a query on the given input, return result

Parameters:

  • input (Hash, Array)
  • query (String)


20
21
22
23
24
# File 'lib/janeway/interpreter.rb', line 20

def self.interpret(input, query)
  tokens = Lexer.lex(query)
  ast = Parser.new(tokens, query).parse
  new(ast).interpret(input)
end

Instance Method Details

#interpret(input) ⇒ Object

Parameters:

  • input (Array, Hash)

    object to be searched

Returns:

  • (Object)


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

def interpret(input)
  unless input.is_a?(Hash) || input.is_a?(Array)
    return [] # can't query on any other types, but need to check because a string is also valid json
  end

  @root.interpret(nil, nil, input, [])
rescue StandardError => e
  # Error during interpretation. Convert it to a Janeway::Error and include the query in the message
  error = err(e.message)
  error.set_backtrace e.backtrace
  raise error
end

#to_json(options = {}) ⇒ String

Return multiline JSON string describing the interpreter tree.

This is not used for parsing / interpretation. It is intended to represent the interpreter tree to help with debugging. This format makes the tree structure much clearer than the #inspect output does.

Returns:

  • (String)


46
47
48
# File 'lib/janeway/interpreter.rb', line 46

def to_json(options = {})
  JSON.pretty_generate(@root.as_json, *options)
end