Class: Sexpistol::Parser
- Inherits:
-
StringScanner
- Object
- StringScanner
- Sexpistol::Parser
- Defined in:
- lib/sexpistol/parser.rb
Constant Summary collapse
- PARANTHESES =
/[()]/.freeze
- STRING =
/"([^"\\]|\\.)*"/.freeze
- FLOAT =
/[\-+]? [0-9]+ ((e[0-9]+) | (\.[0-9]+(e[0-9]+)?)) [\s()]/x.freeze
- INTEGER =
/[\-+]?[0-9]+[\s()]/.freeze
- SYMBOL =
/[^0-9()\s]+[^()\s]*/.freeze
Instance Method Summary collapse
- #fetch_token ⇒ Object
-
#initialize(string) ⇒ Parser
constructor
A new instance of Parser.
- #parse(level = 0, exp = []) ⇒ Object
Constructor Details
#initialize(string) ⇒ Parser
Returns a new instance of Parser.
13 14 15 16 17 18 |
# File 'lib/sexpistol/parser.rb', line 13 def initialize(string) raise 'String given is not an s-expression' if string.strip[0] != '(' raise 'Invalid s-expression' if string.count('(') != string.count(')') super(string.strip) end |
Instance Method Details
#fetch_token ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/sexpistol/parser.rb', line 37 def fetch_token skip(/\s+/) return matched if scan(PARANTHESES) return matched.undump if scan(STRING) return matched.to_f if scan(FLOAT) return matched.to_i if scan(INTEGER) return matched.to_sym if scan(SYMBOL) raise "Invalid token at position #{pos} near '#{scan(/.{0,20}/)}'." end |
#parse(level = 0, exp = []) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/sexpistol/parser.rb', line 20 def parse(level = 0, exp = []) until eos? case token = fetch_token when ')' then break when '(' then exp << parse(level + 1) when String, Integer, Float, Symbol then exp << token end end if level.zero? exp = exp.first if exp.first.is_a?(Array) && exp.length == 1 exp = Sexpistol::SExpressionArray.new(exp) if exp.all? { |item| item.is_a?(Array) } end exp end |