Class: Janeway::Interpreter

Inherits:
Object
  • Object
show all
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) ⇒ Interpreter

Returns a new instance of Interpreter.

Parameters:

  • query (AST::Query)

    abstract syntax tree of the jsonpath query

Raises:

  • (ArgumentError)


25
26
27
28
29
30
31
32
# File 'lib/janeway/interpreter.rb', line 25

def initialize(query)
  raise ArgumentError, "expect AST::Query, got #{query.inspect}" unless query.is_a?(AST::Query)

  @query = query
  @jsonpath = query.jsonpath
  @input = nil
  @pipeline = query_to_interpreter_pipeline(@query)
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)


18
19
20
21
22
# File 'lib/janeway/interpreter.rb', line 18

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)


36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/janeway/interpreter.rb', line 36

def interpret(input)
  @input = 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

  @pipeline.first.interpret(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

#push(node) ⇒ Object

Append an interpreter onto the end of the pipeline

Parameters:



52
53
54
# File 'lib/janeway/interpreter.rb', line 52

def push(node)
  @pipeline.last.next = node
end