-
Notifications
You must be signed in to change notification settings - Fork 7
/
json.oc
235 lines (217 loc) · 6.58 KB
/
json.oc
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
//! JSON parsing and serialization
//!
//! This module heavily relies on {{Value}} as the representation of the data.
//! It also re-uses the {{Lexer}} from the compiler.
import std::fs
import std::buffer::Buffer
import std::vector::Vector
import std::value::{ Value, ValueType }
import std::span::{ Span, Location }
import compiler::lexer::Lexer
import compiler::tokens::{ Token, TokenType }
//* JSON Parser
struct Parser {
tokens: &Vector<&Token>
curr: u32
}
def Parser::make(tokens: &Vector<&Token>): Parser {
let parser: Parser
parser.tokens = tokens
parser.curr = 0
return parser
}
def Parser::token(&this): &Token => .tokens.at(.curr)
def Parser::consume(&this, type: TokenType): &Token {
if .token().type != type {
println("Expected %s but got %s", type.str(), .token().type.str())
std::exit(1)
}
let tok = .token()
.curr += 1
return tok
}
def Parser::parse_object(&this): &Value {
let start = .consume(TokenType::OpenCurly)
let json = Value::new(ValueType::Dictionary)
while .token().type != TokenType::CloseCurly {
let key = .consume(TokenType::StringLiteral)
.consume(TokenType::Colon)
let value = .parse_value()
json.u.as_dict.insert(key.text, value)
if .token().type == TokenType::Comma {
.consume(TokenType::Comma)
}
}
let end = .consume(TokenType::CloseCurly)
json.span = start.span.join(end.span)
return json
}
def Parser::parse_array(&this): &Value {
let start = .consume(TokenType::OpenSquare)
let json = Value::new(ValueType::List)
while .token().type != TokenType::CloseSquare {
let value = .parse_value()
json.u.as_list.push(value)
if .token().type == TokenType::Comma {
.consume(TokenType::Comma)
}
}
let end = .consume(TokenType::CloseSquare)
json.span = start.span.join(end.span)
return json
}
def Parser::parse_value(&this): &Value => match .token().type {
Null => {
let tok = .consume(TokenType::Null)
let val = Value::new(ValueType::Null)
val.span = tok.span
yield val
}
True | False => {
let json = Value::new(ValueType::Bool)
let tok = .token()
json.u.as_bool = tok.text.eq("true")
json.span = tok.span
.curr += 1
yield json
}
IntLiteral => {
let json = Value::new(ValueType::Integer)
let tok = .consume(TokenType::IntLiteral)
json.u.as_int = tok.text.to_i32() as i64
json.span = tok.span
yield json
}
FloatLiteral => {
let json = Value::new(ValueType::Float)
let tok = .consume(TokenType::FloatLiteral)
json.u.as_float = std::libc::strtod(tok.text, null)
json.span = tok.span
yield json
}
StringLiteral => {
let json = Value::new(ValueType::String)
let tok = .consume(TokenType::StringLiteral)
json.u.as_str = Buffer::from_str(tok.text)
json.span = tok.span
yield json
}
OpenCurly => .parse_object()
OpenSquare => .parse_array()
Minus => {
let start = .consume(TokenType::Minus)
let next = .parse_value()
match next.type {
Integer => {
next.u.as_int = -next.u.as_int
}
Float => {
next.u.as_float = -next.u.as_float
}
else => {
println("Unexpected token in json::Parser::parse_value: %s", next.type.str())
std::exit(1)
}
}
next.span = start.span.join(next.span)
yield next
}
else => {
println("Unexpected token in json::Parser::parse_value: %s", .token().type.str())
std::exit(1)
}
}
def Parser::parse(&this): &Value => match .token().type {
OpenCurly => .parse_object()
OpenSquare => .parse_array()
else => {
println("Expected { or [ at JSON top level")
std::exit(1)
}
}
////////////////////////////////////////////////////////////////////////////////
//* Parse a JSON string into a Value
def parse(source: str, filename: str = "<anonymous>"): &Value {
let lexer = Lexer::make(source, filename)
let tokens = lexer.lex()
let parser = Parser::make(tokens)
return parser.parse()
}
//* Open and parse a JSON file into a Value
def parse_from_file(filename: str): &Value {
let source = fs::read_file(filename)
return parse(source.str(), filename)
}
//* Serialize a Value into JSON, into a given Buffer
def serialize_into(val: &Value, sb: &Buffer) {
match val.type {
Null => sb += "null"
Bool => sb += if val.u.as_bool "true" else "false"
Integer => sb <<= `{val.u.as_int}`
Float => sb <<= `{val.u.as_float}`
String => {
sb += "\""
let buf = val.u.as_str
for let i = 0; i < buf.size; i += 1 {
let c = buf.data[i] as char
match c {
'\b' => sb += "\\b"
'\f' => sb += "\\f"
'\n' => sb += "\\n"
'\r' => sb += "\\r"
'\t' => sb += "\\t"
'\\' => sb += "\\\\"
'"' => sb += "\\\""
else => {
if c.is_print() {
sb += c
} else {
sb <<= `\\x{buf.data[i]:02x}`
}
}
}
}
sb += "\""
}
List => {
sb += "["
let lst = val.u.as_list
for let i = 0; i < lst.size; i += 1 {
let value = lst.at(i)
if i > 0 {
sb += ","
}
serialize_into(value, sb)
}
sb += "]"
}
Dictionary => {
sb += "{"
let first = true
for iter in val.u.as_dict.iter() {
if not first {
sb += ","
}
first = false
sb += "\""
sb += iter.key
sb += "\":"
let value = iter.value
serialize_into(value, sb)
}
sb += "}"
}
}
}
//* Serialize a Value into JSON, returning a new {{Buffer}}
def serialize(val: &Value): Buffer {
let sb = Buffer::make()
serialize_into(val, &sb)
return sb
}
//* Serialize a Value into JSON, writing to a file
def write_to_file(val: &Value, filename: str) {
let sb = serialize(val)
fs::write_file(filename, sb)
sb.free()
}