class JMESPath::Lexer

@api private

Constants

JSON_NUMBER

@api private

JSON_VALUE

@api private

TOKEN_PATTERNS

@api private

TOKEN_REGEX

@api private

TOKEN_TYPES

@api private

Public Instance Methods

tokenize(expression) click to toggle source

@param [String<JMESPath>] expression @return [Array<Hash>]

# File lib/jmespath/lexer.rb, line 55
def tokenize(expression)
  offset = 0
  tokens = []
  expression.scan(TOKEN_REGEX).each do |match|
    match_index = match.find_index { |token| !token.nil? }
    match_value = match[match_index]
    type = TOKEN_TYPES[match_index]
    token = Token.new(type, match_value, offset)
    if token.type != :skip
      case token.type
      when :number then token_number(token, expression, offset)
      when :literal then token_literal(token, expression, offset)
      when :quoted_identifier
        token_quoted_identifier(token, expression, offset)
      end
      tokens << token
    end
    offset += match_value.size
  end
  tokens << Token.new(:eof, nil, offset)
  unless expression.size == offset
    syntax_error('invalid expression', expression, offset) 
  end
  tokens
end

Private Instance Methods

decode_json(json, expression, offset) click to toggle source
# File lib/jmespath/lexer.rb, line 104
def decode_json(json, expression, offset)
  MultiJson.load(json)
rescue MultiJson::ParseError => e
  syntax_error(e.message, expression, offset)
end
syntax_error(message, expression, offset) click to toggle source
# File lib/jmespath/lexer.rb, line 110
def syntax_error(message, expression, offset)
  msg = message + "in #{expression.inspect} at #{offset}"
  raise Errors::SyntaxError.new(msg)
end
token_literal(token, expression, offset) click to toggle source
# File lib/jmespath/lexer.rb, line 87
def token_literal(token, expression, offset)
  token[:value] = token[:value][1..-2].lstrip.gsub('\`', '`')
  token[:value] =
    case token[:value]
    when 'true', 'false' then token[:value] == 'true'
    when 'null' then nil
    when '' then syntax_error("empty json literal", expression, offset)
    when JSON_VALUE then decode_json(token[:value], expression, offset)
    when JSON_NUMBER then decode_json(token[:value], expression, offset)
    else decode_json('"' + token[:value] + '"', expression, offset)
    end
end
token_number(token, expression, offset) click to toggle source
# File lib/jmespath/lexer.rb, line 83
def token_number(token, expression, offset)
  token[:value] = token[:value].to_i
end
token_quoted_identifier(token, expression, offset) click to toggle source
# File lib/jmespath/lexer.rb, line 100
def token_quoted_identifier(token, expression, offset)
  token[:value] = decode_json(token[:value], expression, offset)
end