Module: Malady::Reader

Defined in:
lib/malady/reader.rb

Class Method Summary collapse

Class Method Details

.parse_string(string) ⇒ Object



4
5
6
# File 'lib/malady/reader.rb', line 4

def parse_string(string)
  read_str(string)
end

.read_atom(token) ⇒ Object



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

def read_atom(token)
  case token
  when /^-?\d+$/
    [:integer, token.to_i]
  when 'true'
    [:boolean, :true]
  when 'false'
    [:boolean, :false]
  when /^\D+$/
    [:symbol, token]
  else
    raise 'Reader error: Unknown token'
  end
end

.read_form(tokens) ⇒ Object



13
14
15
16
17
18
19
# File 'lib/malady/reader.rb', line 13

def read_form(tokens)
  if tokens.first =~ /(\(|\[)/
    read_list(tokens)
  else
    read_atom(tokens.shift)
  end
end

.read_list(tokens) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/malady/reader.rb', line 21

def read_list(tokens)
  raise 'Reader error: read_list called on non-list' if tokens.shift !~ /(\(|\[)/
  list = [:list]

  while tokens.first !~ /(\)|\])/
    raise 'Reader error: Unmatched parens' if tokens.empty?
    list << read_form(tokens)
  end

  tokens.shift # pop our closing paren

  list
end

.read_str(string) ⇒ Object



8
9
10
11
# File 'lib/malady/reader.rb', line 8

def read_str(string)
  tokens = tokenizer(string)
  read_form(tokens)
end

.tokenizer(string) ⇒ Object



50
51
52
53
54
55
56
57
58
59
# File 'lib/malady/reader.rb', line 50

def tokenizer(string)
  pos = 0
  re = /[\s,]*(~@|[\[\]{}()'`~^@]|"(?:\\.|[^\\"])*"|;.*|[^\s\[\]{}('"`,;)]*)/
  result = []
  while (m = re.match(string, pos)) && pos < string.size
    result << m.to_s.strip
    pos = m.end(0)
  end
  result
end