1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
// The MIT License (MIT)
//
// Copyright (c) 2017 Doublify Technologies
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

use std::cell::RefCell;
use std::iter::Peekable;

/// Kind of token
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Kind {
  /// String
  String,
  /// Integer
  Integer,
  /// Boolean
  Boolean,
  /// Identifier
  Identifier,
  /// Curly brace
  Curly,
  /// Parentheses
  Parentheses,
  /// Colon
  Colon,
}

/// Token
#[derive(Clone, Debug, PartialEq)]
pub struct Token {
  /// Kind
  pub kind: Kind,
  /// Value
  pub binding: String,
}

impl Token {
  /// Creates token from static string slice
  pub fn new(kind: Kind, binding: &'static str) -> Token {
    Token {
      kind,
      binding: String::from(binding),
    }
  }

  /// Changes token kind and returns new token
  pub fn change_kind(&self, kind: Kind) -> Token {
    Token {
      kind,
      binding: self.binding.to_owned(),
    }
  }
}

/// Handles string
fn tokenize_string<'a, It>(it: &mut Peekable<It>,
                           buffer: &RefCell<String>,
                           ch: char)
                           -> Result<String, &'a str>
  where It: Iterator<Item = char>
{
  let mut escaped = false;
  let quote = ch.clone();
  let quote_str = quote;

  while let Some(ch) = it.peek().map(|c| *c) {
    if escaped {
      buffer.borrow_mut().push(ch);
      escaped = false;
    } else if ch == '\\' {
      escaped = true;
    } else if ch == quote {
      it.next();
      let mut result = String::new();
      result.push(quote_str);
      result.push_str(buffer.borrow().as_str());
      result.push(quote_str);

      return Ok(result);
    } else {
      buffer.borrow_mut().push(ch);
    }

    it.next();
  }

  Err("Can't parse string")
}

/// Scans query
pub fn scan(raw_query: &str) -> Vec<Token> {
  let query = raw_query.to_owned() + " ";
  let mut it = query.chars().peekable();
  let tokens = RefCell::new(vec![]);
  let buffer = RefCell::new(String::new());

  let bind_identifier = |binding: String| if !binding.is_empty() {
    tokens
      .borrow_mut()
      .push(
        Token {
          kind: Kind::Identifier,
          binding,
        },
      );

    buffer.borrow_mut().clear()
  };

  let consume_token = |token: Token| {
    bind_identifier(buffer.clone().into_inner());

    tokens.borrow_mut().push(token)
  };

  while let Some(ch) = it.next() {
    match ch {
      '"' | '\'' => {
        let str = tokenize_string(&mut it, &buffer, ch).unwrap();
        bind_identifier(str);
      }
      ' ' => bind_identifier(buffer.clone().into_inner()),
      ':' => consume_token(Token::new(Kind::Colon, ":")),
      '{' => consume_token(Token::new(Kind::Curly, "{")),
      '}' => consume_token(Token::new(Kind::Curly, "}")),
      '(' => consume_token(Token::new(Kind::Parentheses, "(")),
      ')' => consume_token(Token::new(Kind::Parentheses, ")")),
      _ => buffer.borrow_mut().push(ch),
    }

    if ch != '"' || ch != '\'' {
      continue;
    }
  }

  tokens.to_owned().into_inner()
}