summary refs log tree commit diff
path: root/lib/sson.rb
blob: dd4ea67d7edf4182da0337eda2fb2d345619d5cf (plain) (blame)
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# SSON - S-Expression Standard Object Notation
# a faithful embedding of JSON (RFC 8259) into a S-Expression syntax

#
# value = "#n" / "#t" / "#f" /
#         "(" value* ")" / "#(" (string value)* ")" /
#         json-number / string
# string = json-string / literal
# literal = [^0-9#;()" \t\r\n+-][^#;()" \t\r\n]*
# ";" starts a comment until end of line, it is treated as whitespace
#

# To the extent possible under law, Leah Neukirchen <leah@vuxu.org>
# has waived all copyright and related or neighboring rights to this work.
# http://creativecommons.org/publicdomain/zero/1.0/

require 'json'
require 'prettyprint'
require 'strscan'

module SSON
  VERSION = "0.1"

  class SSONError < StandardError; end
  class GeneratorError < SSONError; end
  class ParserError < SSONError; end
end
class << SSON
  SCANIDENT = /[^0-9#;()" \t\r\n+-][^#;()" \t\r\n]*/
  IDENT = /\A#{SCANIDENT}\z/

  def generate(o)
    case o
    when Hash
      r = "#("
      o.each { |k, v| 
        r << " "  if r.size > 2
        r << generate(k.to_s) << " " << generate(v) 
      }
      r << ")"
      r
    when Array
      r = "("
      o.each { |e|
        r << " "  if r.size > 1
        r << generate(e)
      }
      r << ")"
      r
    when true
      "#t"
    when false
      "#f"
    when nil
      "#n"
    when Integer
      o.to_s
    when Float
      if o.nan?
        raise GeneratorError, "NaN not allowed in SSON"
      elsif o.infinite?
        raise GeneratorError, "Infinity not allowed in SSON"
      end
      o.to_s
    when String
      if o =~ IDENT
        o
      else
        JSON.generate(o)
      end
    else
      # like JSON.generate
      generate(o.to_s)
    end
  end

  def pretty_generate(obj)
    return PrettyPrint.format('', 80) { |q|
      inner = lambda { |o|
        case o
        when Array
          q.group(1) {
            q.text "("
            b = false
            o.each { |e|
              q.breakable " "  if b
              b = true
              inner[e]
            }
            q.text ")"
          }
        when Hash
          q.group(2) {
            q.text "#("
            b = false
            o.each { |k, v|
              q.breakable " "  if b
              b = true
              q.group {
                inner[k]
                q.text " "
                inner[v]
              }
            }
            q.text ")"
          }

        when true; q.text "#t"
        when false; q.text "#f"
        when nil; q.text "#n"
        when Integer
          q.text o.to_s
        when Float
          if o.nan?
            raise GeneratorError, "NaN not allowed in SSON"
          elsif o.infinite?
            raise GeneratorError, "Infinity not allowed in SSON"
          end
          q.text o.to_s
        when String
          if o =~ IDENT
            q.text o  # ES5 identifier
          else
            q.text JSON.generate(o)
          end
        end
      }
      inner[obj]
    }
  end

  def parse(str)
    e = SSON.enum_for(:tok, str)
    r = parse_form e
    begin
      e.next
    rescue StopIteration
      r
    else
      raise SSON::ParserError, "trailing garbage"
    end
  end

  private

  def tok(str)
    ss = StringScanner.new(str)
    until ss.eos?
      if ss.scan(/\A[ \t\r\n]+/) || ss.scan(/;[^\n]*$/)
        # ignore
      elsif ss.scan(/\(/);      yield :OPEN
      elsif ss.scan(/\)/);      yield :CLOSE
      elsif ss.scan(/#\(/);     yield :HASH
      elsif ss.scan(/#n/);      yield :NULL
      elsif ss.scan(/#t/);      yield :TRUE
      elsif ss.scan(/#f/);      yield :FALSE
      elsif s = ss.scan(/"(\\"|[^"])*"/)
        yield JSON.parse(s)
      elsif s = ss.scan(SCANIDENT)
        yield s
      elsif s = ss.scan(/[-+]?(?:\d*\.?\d+|\d+\.?\d*)(?:[eE][-+]?\d+)?/)
        yield Float(s)
      else
        raise SSON::ParserError, "invalid SSON: " + ss.peek(20).dump
      end
    end
  end

  def parse_form(e)
    case t = e.next
    when :OPEN
      r = []
      while e.peek != :CLOSE
        r << parse_form(e)
      end
      e.next
      r
    when :HASH
      r = {}
      while e.peek != :CLOSE
        k = e.next
        raise "non string key"  unless k.kind_of?(String)
        v = parse_form(e)
        r[k] = v
      end
      e.next
      r
    when :CLOSE;   raise SSON::ParserError, "invalid SSON, toplevel )"
    when :NULL;    nil
    when :TRUE;    true
    when :FALSE;   false
    when String;   t
    when Float;    t
    end
  rescue StopIteration
    raise ParserError, "early EOF"
  end

end