Hog v10.58.0
tobj.tcl
Go to the documentation of this file.
1 
2 # Typed object storage
3 # wraps variables in a dict containing type and value
4 # allows us to export data in a json format
5 # tclint-disable redefined-builtin
6 
7 namespace eval tobj {
8  variable _types_ {String Number Bool Null Dict List}
9 
10  proc isobj {value} {
11  return [expr {
12  ![catch {dict size $value}] &&
13  [dict exists $value __t__] &&
14  [dict exists $value __v__]
15  }]
16  }
17 
18  proc create {type value} {
19  variable _types_
20  if {$type ni $_types_} {
21  error "tobj: unknown type '$type'" "" {INVALID_TOBJ_TYPE}
22  }
23  return [dict create __t__ $type __v__ $value]
24  }
25 
26  proc type {obj} {
27  if {![isobj $obj]} { error "tobj: not a tobj" "" {INVALID_TOBJ} }
28  return [dict get $obj __t__]
29  }
30 
31  proc typeIs {obj type} {
32  if {![isobj $obj]} { error "tobj: not a tobj" "" {INVALID_TOBJ} }
33  return [expr {[dict get $obj __t__] eq $type}]
34  }
35 
36  proc value {obj} {
37  if {![isobj $obj]} { error "tobj: not a tobj" "" {INVALID_TOBJ} }
38  return [dict get $obj __v__]
39  }
40 
41  proc tojson {node {arg {}}} {
42  if {![isobj $node]} { error "tobj: not a tobj" "" {INVALID_TOBJ} }
43  return [_tojson $node [expr {$arg eq "-pretty" ? 0 : -1}]]
44  }
45 
46  proc _tojson {node indent} {
47  set type [dict get $node __t__]
48  set value [dict get $node __v__]
49  set pretty [expr {$indent >= 0}]
50  set pad [expr {$pretty ? [string repeat " " $indent] : ""}]
51  set pad1 [expr {$pretty ? [string repeat " " [expr {$indent+1}]] : ""}]
52  set sep [expr {$pretty ? ",\n" : ", "}]
53  set next [expr {$pretty ? $indent+1 : -1}]
54  switch $type {
55  Dict {
56  if {$pretty && [dict size $value] == 0} { return "{}" }
57  set pairs {}
58  dict for {k child} $value {
59  lappend pairs "${pad1}\"[_escape $k]\": [_tojson $child $next]"
60  }
61  if {$pretty} { return "{\n[join $pairs $sep]\n${pad}}" }
62  return "{[join $pairs {, }]}"
63  }
64  List {
65  if {$pretty && [llength $value] == 0} { return "\[\]" }
66  set items {}
67  foreach item $value { lappend items "${pad1}[_tojson $item $next]" }
68  if {$pretty} { return "\[\n[join $items $sep]\n${pad}\]" }
69  return "\[[join $items {, }]\]"
70  }
71  Number { return $value }
72  Bool { return [expr {$value ? "true" : "false"}] }
73  Null { return "null" }
74  default { return "\"[_escape $value]\"" }
75  }
76  }
77 
78  proc _escape {str} {
79  return [string map {
80  "\\" "\\\\" "\"" "\\\""
81  "\n" "\\n" "\r" "\\r" "\t" "\\t"
82  } $str]
83  }
84 
85  proc String {value} { create String $value }
86  proc Number {value} { create Number $value }
87  proc Bool {value} { create Bool $value }
88  proc Null {} { create Null {} }
89 
90  # Convert any tobj to a plain Tcl string
91  # String/Number → string
92  # Bool → 1 or 0
93  # Null → {} (empty string)
94  # List → Tcl list
95  # Dict → Tcl dict
96  proc native {obj} {
97  if {![isobj $obj]} { error "tobj native: not a tobj" "" {INVALID_TOBJ} }
98  switch [type $obj] {
99  List {
100  set _r {}
101  foreach item [value $obj] { lappend _r [native $item] }
102  return $_r
103  }
104  Dict {
105  set result {}
106  dict for {k v} [value $obj] { dict set result $k [native $v] }
107  return $result
108  }
109  Bool { return [expr {[value $obj] ? 1 : 0}] }
110  Null { return {} }
111  default { return [value $obj] }
112  }
113  }
114 
115  namespace export create type typeIs value isobj tojson native String Number Bool Null
116  namespace ensemble create
117 }
118 
119 # shorthand:
120 proc tstr {v} { tobj create String $v }
121 proc tnum {v} { tobj create Number $v }
122 proc tbool {v} { tobj create Bool $v }
123 proc tnull {} { tobj create Null {} }
124 proc tval {obj} { tobj value $obj }
125 proc tnative {obj} { tobj native $obj }
126 
127 proc tinf {value} {
128  if {$value eq {} || $value eq {null}} { return [tobj Null] }
129  if {$value eq {true} || $value eq {false}} { return [tobj Bool $value] }
130  if {[string is double -strict $value]} { return [tobj Number $value] }
131  return [tobj String $value]
132 }
133 
134 proc tlinf {args} {
135  set result {}
136  ::foreach arg $args {
137  lappend result [tinf $arg]
138  }
139  return $result
140 }
141 
142 namespace eval tlist {
143 
144  proc create {args} {
145  ::set nodes {}
146  ::foreach node $args { ::lappend nodes [expr {[tobj isobj $node] ? $node : [tinf $node]}] }
147  return [tobj create List $nodes]
148  }
149 
150  # create, but every element is forced to String instead of being typed by tinf.
151  # i.e. tinf might make "9" type Number
152  # Use this for raw text that must survive a round-trip
153  proc createstr {args} {
154  ::set nodes {}
155  ::foreach node $args { ::lappend nodes [tobj create String $node] }
156  return [tobj create List $nodes]
157  }
158 
159  proc append {listVar args} {
160  upvar 1 $listVar lst
161  if {![tobj isobj $lst]} { error "tlist append: not a tobj" "" {INVALID_TOBJ} }
162  if {[tobj type $lst] ne "List"} { error "tlist append: not a List node" "" {INVALID_TOBJ_LIST} }
163  if {[llength $args] == 0} { error "tlist append: no nodes given" "" {INVALID_ARGS} }
164  set current [tobj value $lst]
165  ::foreach node $args { ::lappend current [expr {[tobj isobj $node] ? $node : [tinf $node]}] }
166  set lst [tobj create List $current]
167  }
168 
169  proc get {lst index} {
170  if {![tobj isobj $lst]} { error "tlist get: not a tobj" "" {INVALID_TOBJ} }
171  if {[tobj type $lst] ne "List"} { error "tlist get: not a List node" "" {INVALID_TOBJ_LIST} }
172  return [lindex [tobj value $lst] $index]
173  }
174 
175  proc getval {lst index} {
176  if {![tobj isobj $lst]} { error "tlist getval: not a tobj" "" {INVALID_TOBJ} }
177  if {[tobj type $lst] ne "List"} { error "tlist getval: not a List node" "" {INVALID_TOBJ_LIST} }
178  set item [lindex [tobj value $lst] $index]
179  set t [tobj type $item]
180  if {$t eq "Dict" || $t eq "List"} { return $item }
181  return [tobj value $item]
182  }
183 
184  proc length {lst} {
185  if {![tobj isobj $lst]} { error "tlist length: not a tobj" "" {INVALID_TOBJ} }
186  if {[tobj type $lst] ne "List"} { error "tlist length: not a List node" "" {INVALID_TOBJ_LIST} }
187  return [llength [tobj value $lst]]
188  }
189 
190  proc remove {lst index} {
191  if {![tobj isobj $lst]} { error "tlist remove: not a tobj" "" {INVALID_TOBJ} }
192  if {[tobj type $lst] ne "List"} { error "tlist remove: not a List node" "" {INVALID_TOBJ_LIST} }
193  set current [tobj value $lst]
194  set lst [tobj create List [lreplace $current $index $index]]
195  }
196 
197  proc pop {listVar} {
198  upvar 1 $listVar lst
199  if {![tobj isobj $lst]} { error "tlist pop: not a tobj" "" {INVALID_TOBJ} }
200  if {[tobj type $lst] ne "List"} { error "tlist pop: not a List node" "" {INVALID_TOBJ_LIST} }
201  set current [tobj value $lst]
202  set popped [lindex $current end]
203  set lst [tobj create List [lreplace $current end end]]
204  return $popped
205  }
206 
207 
208  proc foreach {itemVar lst body} {
209  if {![tobj isobj $lst]} { error "tlist foreach: not a tobj" "" {INVALID_TOBJ} }
210  if {[tobj type $lst] ne "List"} { error "tlist foreach: not a List node" "" {INVALID_TOBJ_LIST} }
211  ::foreach item [tobj value $lst] {
212  uplevel 1 [list set $itemVar $item]
213  ::set _tlf_code [catch {uplevel 1 $body} _tlf_res _tlf_opts]
214  switch -- $_tlf_code {
215  0 {}
216  3 { break }
217  4 { continue }
218  default {
219  dict set _tlf_opts -level 2
220  return -options $_tlf_opts $_tlf_res
221  }
222  }
223  }
224  }
225 
226  proc foreachval {itemVar lst body} {
227  if {![tobj isobj $lst]} { error "tlist foreachval: not a tobj" "" {INVALID_TOBJ} }
228  if {[tobj type $lst] ne "List"} { error "tlist foreachval: not a List node" "" {INVALID_TOBJ_LIST} }
229  ::foreach item [tobj value $lst] {
230  set _t [tobj type $item]
231  uplevel 1 [list set $itemVar [expr {$_t eq "Dict" || $_t eq "List" ? $item : [tobj value $item]}]]
232  ::set _tlv_code [catch {uplevel 1 $body} _tlv_res _tlv_opts]
233  switch -- $_tlv_code {
234  0 {}
235  3 { break }
236  4 { continue }
237  default {
238  dict set _tlv_opts -level 2
239  return -options $_tlv_opts $_tlv_res
240  }
241  }
242  }
243  }
244 
245  proc elemExists {lst value} {
246  if {![tobj isobj $lst]} { error "tlist elemExists: not a tobj" "" {INVALID_TOBJ} }
247  if {[tobj type $lst] ne "List"} { error "tlist elemExists: not a List node" "" {INVALID_TOBJ_LIST} }
248  ::foreach item [tobj value $lst] {
249  set t [tobj type $item]
250  if {$t ne "Dict" && $t ne "List" && [tobj value $item] eq $value} { return 1 }
251  }
252  return 0
253  }
254 
255  proc index {lst value} {
256  if {![tobj isobj $lst]} { error "tlist index: not a tobj" "" {INVALID_TOBJ} }
257  if {[tobj type $lst] ne "List"} { error "tlist index: not a List node" "" {INVALID_TOBJ_LIST} }
258  set needle [expr {[tobj isobj $value] ? [tobj value $value] : $value}]
259  set i 0
260  ::foreach item [tobj value $lst] {
261  set t [tobj type $item]
262  if {$t ne "Dict" && $t ne "List" && [tobj value $item] eq $needle} { return $i }
263  incr i
264  }
265  return -1
266  }
267 
268  namespace export create createstr append get getval length remove pop foreach foreachval elemExists index
269  namespace ensemble create
270 }
271 
272 namespace eval tdict {
273 
274  # key (tobj) key (tobj)...
275  proc create {args} {
276  if {[llength $args] % 2 != 0} {
277  error "tdict create: args must be key-tobj pairs" "" {INVALID_ARGS}
278  }
279  ::set d [tobj create Dict {}]
280  ::foreach {key obj} $args {
281  _setPath d [list $key] [expr {[tobj isobj $obj] ? $obj : [tinf $obj]}]
282  }
283  return $d
284  }
285 
286  # tdict set dictVar key ?key ...? tobjValue
287  proc set {dictVar args} {
288  if {[llength $args] < 2} {
289  error "tdict set: usage: tdict set dictVar key ?key ...? tobjValue" "" {INVALID_ARGS}
290  }
291  upvar 1 $dictVar d
292  if {![tobj isobj $d]} { error "tdict set: not a tobj" "" {INVALID_TOBJ} }
293  if {[tobj type $d] ne "Dict"} { error "tdict set: not a Dict node" "" {INVALID_TOBJ_DICT} }
294  ::set keyPath [lrange $args 0 end-1]
295  ::set obj [lindex $args end]
296  _setPath d $keyPath [expr {[tobj isobj $obj] ? $obj : [tinf $obj]}]
297  }
298 
299  proc _setPath {dictVar keyPath obj} {
300  upvar 1 $dictVar d
301  ::set key [lindex $keyPath 0]
302  ::set rest [lrange $keyPath 1 end]
303  ::set current [tobj value $d]
304  if {[llength $rest] == 0} {
305  dict set current $key $obj
306  } else {
307  if {[dict exists $current $key]} {
308  ::set nested [dict get $current $key]
309  if {![tobj isobj $nested] || [tobj type $nested] ne "Dict"} {
310  ::set nested [tobj create Dict {}]
311  }
312  } else {
313  ::set nested [tobj create Dict {}]
314  }
315  _setPath nested $rest $obj
316  dict set current $key $nested
317  }
318  ::set d [tobj create Dict $current]
319  }
320 
321  # tdict get dict key ?key ...?
322  proc get {d args} {
323  if {[llength $args] < 1} {
324  error "tdict get: usage: tdict get dict key ?key ...?" "" {INVALID_ARGS}
325  }
326  if {![tobj isobj $d]} { error "tdict get: not a tobj" "" {INVALID_TOBJ} }
327  if {[tobj type $d] ne "Dict"} { error "tdict get: not a Dict node" "" {INVALID_TOBJ_DICT} }
328  return [_getPath $d $args]
329  }
330 
331  proc getval {d args} {
332  ::set obj [get $d {*}$args]
333  ::set t [tobj type $obj]
334  if {$t eq "Dict" || $t eq "List"} { return $obj }
335  return [tobj value $obj]
336  }
337 
338  # tdict getor dict key ?key ...? default
339  # returns default instead of erroring on a missing key.
340  proc getor {d args} {
341  if {[llength $args] < 2} {
342  error "tdict getor: usage: tdict getor dict key ?key ...? default" "" {INVALID_ARGS}
343  }
344  ::set keyPath [lrange $args 0 end-1]
345  if {![exists $d {*}$keyPath]} { return [lindex $args end] }
346  return [getval $d {*}$keyPath]
347  }
348 
349  # tdict getobjor dict key ?key ...? defaultObj
350  # returns defaultObj instead of erroring on a missing key.
351  proc getobjor {d args} {
352  if {[llength $args] < 2} {
353  error "tdict getobjor: usage: tdict getobjor dict key ?key ...? defaultObj" "" {INVALID_ARGS}
354  }
355  ::set keyPath [lrange $args 0 end-1]
356  if {![exists $d {*}$keyPath]} { return [lindex $args end] }
357  return [get $d {*}$keyPath]
358  }
359 
360  proc _getPath {d keyPath} {
361  ::set key [lindex $keyPath 0]
362  ::set rest [lrange $keyPath 1 end]
363  ::set current [tobj value $d]
364  if {![dict exists $current $key]} {
365  error "tdict get: key '$key' not found" "" {INVALID_TOBJ_KEY}
366  }
367  ::set node [dict get $current $key]
368  if {[llength $rest] == 0} { return $node }
369  if {![tobj isobj $node] || [tobj type $node] ne "Dict"} {
370  error "tdict get: '$key' is not a Dict node" "" {INVALID_TOBJ_DICT}
371  }
372  return [_getPath $node $rest]
373  }
374 
375  proc exists {d args} {
376  if {[llength $args] < 1} { return 0 }
377  if {![tobj isobj $d] || [tobj type $d] ne "Dict"} { return 0 }
378  return [expr {![catch {_getPath $d $args}]}]
379  }
380 
381  proc keys {d args} {
382  if {![tobj isobj $d]} { error "tdict keys: not a tobj" "" {INVALID_TOBJ} }
383  if {[tobj type $d] ne "Dict"} { error "tdict keys: not a Dict node" "" {INVALID_TOBJ_DICT} }
384  if {[llength $args] > 0} {
385  return [dict keys [tobj value $d] [lindex $args 0]]
386  }
387  return [dict keys [tobj value $d]]
388  }
389 
390  proc size {d} {
391  if {![tobj isobj $d]} { error "tdict size: not a tobj" "" {INVALID_TOBJ} }
392  if {[tobj type $d] ne "Dict"} { error "tdict size: not a Dict node" "" {INVALID_TOBJ_DICT} }
393  return [dict size [tobj value $d]]
394  }
395 
396  proc for {kvPair d body} {
397  if {![tobj isobj $d]} { error "tdict for: not a tobj" "" {INVALID_TOBJ} }
398  if {[tobj type $d] ne "Dict"} { error "tdict for: not a Dict node" "" {INVALID_TOBJ_DICT} }
399  lassign $kvPair keyVar valVar
400  dict for {_k _v} [tobj value $d] {
401  uplevel 1 [list set $keyVar $_k]
402  uplevel 1 [list set $valVar $_v]
403  ::set _tdf_code [catch {uplevel 1 $body} _tdf_res _tdf_opts]
404  switch -- $_tdf_code {
405  0 {}
406  3 { break }
407  4 { continue }
408  default {
409  # -level must be baked into the caught options dict, not passed as a
410  # separate flag — -options carries its own -level (captured by catch)
411  # that silently wins over a same-command -level override. Level 2
412  # unwinds exactly the proc that contains this tdict-for call, no more.
413  dict set _tdf_opts -level 2
414  return -options $_tdf_opts $_tdf_res
415  }
416  }
417  }
418  }
419 
420  # tdict filter dict key|value pattern
421  # Returns a new tdict containing only entries where the key or scalar value
422  # matches the glob pattern.
423  proc filter {d mode pattern} {
424  if {![tobj isobj $d]} { error "tdict filter: not a tobj" "" {INVALID_TOBJ} }
425  if {[tobj type $d] ne "Dict"} { error "tdict filter: not a Dict node" "" {INVALID_TOBJ_DICT} }
426  ::set result {}
427  dict for {k v} [tobj value $d] {
428  switch -- $mode {
429  key {
430  if {[string match $pattern $k]} { dict set result $k $v }
431  }
432  value {
433  ::set vraw [expr {[tobj isobj $v] && [tobj type $v] ni {Dict List}
434  ? [tobj value $v] : $v}]
435  if {[string match $pattern $vraw]} { dict set result $k $v }
436  }
437  default { error "tdict filter: unknown mode '$mode'" "" {INVALID_ARGS} }
438  }
439  }
440  return [tobj create Dict $result]
441  }
442 
443  # tdict lappend dictVar key ?key ...? tobjNode
444  proc lappend {dictVar args} {
445  if {[llength $args] < 2} {
446  error "tdict lappend: usage: tdict lappend dictVar key ?key ...? tobjNode" "" {INVALID_ARGS}
447  }
448  upvar 1 $dictVar d
449  if {![tobj isobj $d]} { error "tdict lappend: not a tobj" "" {INVALID_TOBJ} }
450  if {[tobj type $d] ne "Dict"} { error "tdict lappend: not a Dict node" "" {INVALID_TOBJ_DICT} }
451 
452  ::set keyPath [lrange $args 0 end-1]
453  ::set obj [lindex $args end]
454  ::set obj [expr {[tobj isobj $obj] ? $obj : [tinf $obj]}]
455  if {[exists $d {*}$keyPath]} {
456  ::set node [_getPath $d $keyPath]
457  if {![tobj isobj $node] || [tobj type $node] ne "List"} {
458  error "tdict lappend: existing value is not a List node" "" {INVALID_TOBJ_LIST}
459  }
460  ::set lst [tobj value $node]
461  } else {
462  ::set lst {}
463  }
464  ::lappend lst $obj
465  _setPath d $keyPath [tobj create List $lst]
466  }
467 
468  # tdict remove dictVar key ?key ...?
469  proc remove {d args} {
470  if {[llength $args] < 1} {
471  error "tdict remove: usage: tdict remove dictr key ?key ...?" "" {INVALID_ARGS}
472  }
473  if {![tobj isobj $d]} { error "tdict remove: not a tobj" "" {INVALID_TOBJ} }
474  if {[tobj type $d] ne "Dict"} { error "tdict remove: not a Dict node" "" {INVALID_TOBJ_DICT} }
475  _removePath d $args
476  }
477 
478  proc _removePath {dictVar keyPath} {
479  upvar 1 $dictVar d
480  ::set key [lindex $keyPath 0]
481  ::set rest [lrange $keyPath 1 end]
482  ::set current [tobj value $d]
483  if {![dict exists $current $key]} {
484  error "tdict remove: key '$key' not found" "" {INVALID_TOBJ_KEY}
485  }
486  if {[llength $rest] == 0} {
487  dict unset current $key
488  } else {
489  ::set nested [dict get $current $key]
490  if {![tobj isobj $nested] || [tobj type $nested] ne "Dict"} {
491  error "tdict remove: '$key' is not a Dict node" "" {INVALID_TOBJ_DICT}
492  }
493  _removePath nested $rest
494  dict set current $key $nested
495  }
496  ::set d [tobj create Dict $current]
497  }
498 
499  namespace export create set lappend get getval getor getobjor exists keys size for filter remove
500  namespace ensemble create
501 }