summaryrefslogtreecommitdiff
path: root/lib/zambyte/meta/gerbil.scm
blob: 9d9cb6432dd4a09f48b9c9769d743fd2621f75b5 (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
(import (std text json)
	(scheme case-lambda)
	(scheme hash-table))
(begin
  (define (json-object . pairs)
    (alist->hash-table pairs eq?))

  (define json-list list)
  (define json-null (if #f #f))

  (define (json-object? obj)
    (or (hash-table? obj)
	(json-record? obj)))

  (define json-list? list?)

  (define (json-null? obj)
    (eq? obj json-null))

  (define (json-object-contains-key? json key)
    (or (and (hash-table? json)
	     (hash-table-contains? json key))
	(and (json-record? json)
	     (json-object-contains-key? ((json-record->typeless json)) key))))

  (define string->json string->json-object)

  (define (json->string json)
    (json-object->string (json->typeless-json json)))

  (define (json-object-ref json key)
    (cond
     ((hash-table? json)
      (if (json-object-contains-key? json key)
	(hash-table-ref json key)
	((json-key-not-found))))
     ((json-record? json)
      (or (and-let* ((pair (assoc key (json-record->accessors json)))
		     (accessor (cdr pair)))
	    (accessor (json-record->internal-record json)))
	  (error "json-object-ref: no accessor for field" (json-record->name json) key)))
     (else ((json-key-not-found)))))

  (define (json-object-set! json key value)
    (cond
     ((and (hash-table? json)
	   (json-object-contains-key? json key))
      (hash-table-set! json key value)
      json)
     ((json-record? json)
      (or (and-let* ((pair (assoc key (json-record->mutators json)))
		     (mutator! (cdr pair)))
	    (mutator! (json-record->internal-record json) value)
	    json)
	  (error "json-object-set!: no mutator for field" (json-record->name json) key)))))

  (define json-list-ref list-ref)
  (define json-list-length length)

  (define (json-object-map proc json)
    (define res (json-object))
    (hash-table-for-each
     (lambda (key value)
       (call-with-values (lambda () (proc key value))
	 (case-lambda
	   ((key value) (hash-table-set! res key value))
	   (_ (error "json-object-map: proc did not return two values")))))
     json)
    res)

  (define json-list-map map)

  (define (json-object->alist obj)
    (cond
     ((hash-table? obj)
      (hash-table->alist obj))
     ((json-record? obj)
      (json-object->alist (json->typeless-json obj)))
     (else (error "json-object->alist: not an object" obj))))

  (define json-list->list values))