zuzu-rust 0.5.0

Rust implementation of ZuzuScript
Documentation
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
=encoding utf8

=head1 NAME

std/data/ini - INI encoding and decoding for ZuzuScript.

=head1 SYNOPSIS

  from std/data/ini import INI;

  let codec := new INI( pretty: true, canonical: true );
  let text := codec.encode({
    app: {
      name: "zuzu",
      debug: true,
      port: 5000,
    },
  });
  let data := codec.decode(text);

=head1 IMPLEMENTATION SUPPORT

This module is supported by zuzu.pl, zuzu-rust, and zuzu-js on Node and
Electron. It is partially supported by zuzu-js in the browser: in-memory
INI encode/decode coverage passes, but file-backed load/dump coverage is
unsupported because browser filesystem capability is unavailable.

=head1 DESCRIPTION

This module provides a pure-Zuzu implementation of INI parsing and
serialization, with a user-facing API modelled on C<std/data/json>.

=head1 EXPORTS

=head2 Classes

=over

=item C<< INI({ utf8?: Bool, pretty?: Bool, canonical?: Bool }) >>

Constructs an INI codec. Returns: C<INI>.

=item C<< codec.encode(value) >>

Parameters: C<value> is a C<Dict> or compatible mapping. Returns:
C<String>. Encodes C<value> as INI text.

=item C<< codec.encode_binarystring(value) >>

Parameters: C<value> is a C<Dict> or compatible mapping. Returns:
C<BinaryString>. Encodes C<value> as UTF-8 INI bytes.

=item C<< codec.decode(String text) >>

Parameters: C<text> is INI text. Returns: C<Dict>. Decodes INI text
into a dictionary.

=item C<< codec.decode_binarystring(BinaryString bytes) >>

Parameters: C<bytes> is UTF-8 INI bytes. Returns: C<Dict>. Decodes INI
bytes into a dictionary.

=item C<< codec.load(Path path) >>

Parameters: C<path> is a C<std/io> C<Path>. Returns: C<Dict>. Reads INI
text from C<path> and decodes it.

=item C<< codec.dump(Path path, value) >>

Parameters: C<path> is a C<std/io> C<Path> and C<value> is a C<Dict> or
compatible mapping. Returns: C<null>. Encodes C<value> and writes INI
text to C<path>.

=back

=head1 COPYRIGHT AND LICENCE

B<< std/data/ini >> is copyright Toby Inkster.

It is free software; you may redistribute it and/or modify it under
the terms of either the Artistic License 1.0 or the GNU General Public
License version 2.

=cut

from std/string import substr, index;


function _is_space ( String ch ) {
	return ch ≡ " " or ch ≡ "\t" or ch ≡ "\r" or ch ≡ "\n";
}

function _trim ( String text ) {
	let start := 0;
	let stop := length text;
	while ( start < stop and _is_space( substr( text, start, 1 ) ) ) {
		start++;
	}
	while ( stop > start and _is_space( substr( text, stop - 1, 1 ) ) ) {
		stop--;
	}

	return substr( text, start, stop - start );
}

function _strip_comment ( String line ) {
	let in_quote := false;
	let escaped := false;
	let i := 0;
	let n := length line;

	while ( i < n ) {
		let ch := substr( line, i, 1 );

		if (in_quote) {
			if (escaped) {
				escaped := false;
			}
			else if ( ch ≡ "\\" ) {
				escaped := true;
			}
			else if ( ch ≡ "\"" ) {
				in_quote := false;
			}
		}

		else {
			if ( ch ≡ "\"" ) {
				in_quote := true;
			}
			else if ( ch ≡";" or ch ≡ "#" ) {
				return substr( line, 0, i );
			}
		}

		i++;
	}

	return line;
}

function _unescape_string ( String text ) {
	let out := "";
	let i := 0;
	let n := length text;

	while ( i < n ) {
		let ch := substr( text, i, 1 );

		if ( ch ≡ "\\" ) {
			i++;
			die "Unterminated INI string escape" if i >= n;
			let esc := substr( text, i, 1 );
			if ( esc ≡ "n" ) {
				out _= "\n";
			}
			else if ( esc ≡ "r" ) {
				out _= "\r";
			}
			else if ( esc ≡ "t" ) {
				out _= "\t";
			}
			else if ( esc ≡ "\"" ) {
				out _= "\"";
			}
			else if ( esc ≡ "\\" ) {
				out _= "\\";
			}
			else {
				out _= esc;
			}
		}

		else {
			out _= ch;
		}
		i++;
	}

	return out;
}

function _parse_value ( String raw ) {
	let text := _trim(raw);
	if ( text ≡ "" ) {
		return "";
	}
	if ( substr( text, 0, 1 ) ≡ "\"" and substr( text, length text - 1, 1 ) ≡ "\"" ) {
		let inner := substr( text, 1, length text - 2 );
		return _unescape_string(inner);
	}
	if ( text ≡ "true" ) {
		return true;
	}
	if ( text ≡ "false" ) {
		return false;
	}
	if ( text ~ /^-?[0-9]+(\.[0-9]+)?$/ ) {
		return text + 0;
	}

	return text;
}

function _escape_string ( String text ) {
	let out := "";
	let i := 0;
	let n := length text;

	while ( i < n ) {
		let ch := substr( text, i, 1 );
		if ( ch ≡ "\\" ) {
			out _= "\\\\";
		}
		else if ( ch ≡ "\"" ) {
			out _= "\\\"";
		}
		else if ( ch ≡ "\n" ) {
			out _= "\\n";
		}
		else if ( ch ≡ "\r" ) {
			out _= "\\r";
		}
		else if ( ch ≡ "\t" ) {
			out _= "\\t";
		}
		else {
			out _= ch;
		}
		i++;
	}

	return out;
}

function _encode_value (value) {
	if ( value instanceof Boolean ) {
		return value ? "true": "false";
	}
	if ( value instanceof Number ) {
		return "" _ value;
	}
	if ( value instanceof Array ) {
		let out := "[";
		let i := 0;
		while ( i < value.length() ) {
			if ( i > 0 ) {
				out _= ", ";
			}
			out _= _encode_value( value[i] );
			i++;
		}
		out _= "]";
		return out;
	}
	if ( value instanceof String ) {
		return `"${_escape_string(value)}"`;
	}
	die `Unsupported INI type for scalar value: ${typeof value}`;
}

function _join_lines ( Array lines, Boolean pretty ) {
	let out := "";
	let i := 0;

	while ( i < lines.length() ) {
		if ( i > 0 ) {
			out _= "\n";
		}
		out _= lines[i];
		i++;
	}

	if (pretty) {
		out _= "\n";
	}

	return out;
}

function _normalize_for_encoding ( value ) {
	if ( value instanceof Array ) {
		let out := [];
		let i := 0;
		while ( i < value.length() ) {
			out.push( _normalize_for_encoding( value[i] ) );
			i++;
		}
		return out;
	}

	if ( value instanceof Set or value instanceof Bag ) {
		return _normalize_for_encoding( value.sortstr() );
	}

	if ( value instanceof PairList ) {
		let out := {};
		let pairs := value.to_Array();
		let i := 0;
		while ( i < pairs.length() ) {
			let pair := pairs[i]{pair};
			let key := pair[0];
			if ( not out.exists(key) ) {
				out.set( key, _normalize_for_encoding( pair[1] ) );
			}
			i++;
		}
		return out;
	}

	if ( value instanceof Dict ) {
		let out := {};
		let keys := value.sorted_keys();
		let i := 0;
		while ( i < keys.length() ) {
			let key := keys[i];
			out.set( key, _normalize_for_encoding( value.get(key) ) );
			i++;
		}
		return out;
	}

	return value;
}

function _ensure_section ( Dict root, String section ) {
	if ( not root.exists(section) ) {
		root.set( section, {} );
	}
	let maybe := root.get(section);
	die `INI section '${section}' must be a Dict` if not( maybe instanceof Dict );

	return maybe;
}

function _decode_ini ( String source ) {
	let root := {};
	let section := "";
	_ensure_section( root, section );
	let pos := 0;
	let n := length source;
	let done := false;

	while ( pos <= n and not done ) {
		let nl := index( source, "\n", pos );
		let stop;
		if ( nl < 0 ) {
			stop := n;
		}
		else {
			stop := nl;
		}
		let raw := substr( source, pos, stop - pos );
		let line := _trim( _strip_comment(raw) );

		if ( line ≢ "" ) {

			if ( substr( line, 0, 1 ) ≡ "[" and substr( line, length line - 1, 1 ) ≡ "]" ) {
				section := _trim( substr( line, 1, length line - 2 ) );
				die "Empty INI section name" if section ≡ "";
				_ensure_section( root, section );
			}

			else {
				let eq_pos := index( line, "=" );
				die "Expected INI key = value" if eq_pos < 0;
				let key := _trim( substr( line, 0, eq_pos ) );
				die "Empty INI key" if key ≡ "";
				let value := _parse_value( substr( line, eq_pos + 1 ) );
				let sec := _ensure_section( root, section );
				sec.set( key, value );
			}

		}

		if ( nl < 0 ) {
			done := true;
		}
		else {
			pos := nl + 1;
		}
	}

	return root;
}

function _encode_ini ( Dict data, Boolean pretty, Boolean canonical ) {
	let lines := [];
	let top := data.exists("") ? data.get(""): {};
	die "INI top-level default section must be a Dict" if not( top instanceof Dict );
	let top_keys := canonical ? top.sorted_keys(): top.keys();
	let i := 0;

	while ( i < top_keys.length() ) {
		let key := top_keys[i];
		lines.push( key _ " = " _ _encode_value( top.get(key) ) );
		i++;
	}

	let sections := canonical ? data.sorted_keys(): data.keys();
	i := 0;

	while ( i < sections.length() ) {
		let section := sections[i];
		i++;

		if ( section ≢ "" ) {
			let sec := data.get(section);
			die `INI section '${section}' must map to Dict` if not( sec instanceof Dict );
			if ( pretty and lines.length() > 0 ) {
				lines.push("");
			}
			lines.push( "[" _ section _ "]" );
			let keys := canonical ? sec.sorted_keys(): sec.keys();
			let j := 0;

			while ( j < keys.length() ) {
				let key := keys[j];
				lines.push( key _ " = " _ _encode_value( sec.get(key) ) );
				j++;
			}

		}

	}

	return _join_lines( lines, pretty );
}

class INI {
	let Boolean utf8 := true;
	let Boolean pretty := false;
	let Boolean canonical := false;

	method encode (value) {
		let normalized := _normalize_for_encoding(value);
		die "INI encoder expects a Dict at top level" if not( normalized instanceof Dict );
		return _encode_ini( normalized, pretty, canonical );
	}

	method encode_binarystring (value) {
		return to_binary( self.encode(value) );
	}

	method decode ( String text ) {
		let src := text;
		src := "" if src ≡ null;

		return _decode_ini(src);
	}

	method decode_binarystring ( BinaryString raw ) {
		return self.decode( to_string(raw) );
	}

	method load (path) {
		from std/io import Path;
		die "INI.load is denied by runtime policy" if __system__{deny_fs};
		die "INI.load expects a std/io Path object" if not( path instanceof Path );
		return self.decode_binarystring( path.slurp() );
	}

	method dump ( path, value ) {
		from std/io import Path;
		die "INI.dump is denied by runtime policy" if __system__{deny_fs};
		die "INI.dump expects a std/io Path object" if not( path instanceof Path );
		path.spew( self.encode_binarystring(value) );

		return path;
	}

}