-
Notifications
You must be signed in to change notification settings - Fork 0
/
sxprlib.py
1509 lines (1285 loc) · 44.4 KB
/
sxprlib.py
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding:utf-8 -*-
"""S-expression library for Python ver1.1
S-expression data structure parser/manipulator intended for
parsing and manipulating lisp program, lisp data, netlists like EDIF and KiCAD, etc.
This library is tested with the following huge EDIF file.
Filename: 0644.edf (12MB)
File URL: http://web.archive.org/web/20040812175715/http://mint.cs.man.ac.uk/Projects/gertrude/edif-files/index.html
"""
sxpr_version = "1.1"
##################################################################################
# This library is released under the MIT license. #
# ------------------------------------------------------- #
# Copyright (c) 2023 Kitanokitsune #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to deal #
# in the Software without restriction, including without limitation the rights #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
# copies of the Software, and to permit persons to whom the Software is #
# furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in all #
# copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #
# SOFTWARE. #
##################################################################################
sxprlib_enableLineComment = True # treat ";" as line comment if True
sxprlib_enableBlockComment = False # treat "#|...|#" as block comment if True
sxprlib_enableEscape = False # treat "\" in a string as an escape char if True
sxprlib_enableQuote = False # treat "'" as lisp-like special form (quote) if True
sxprlib_enableFuncRef = False # treat "#'" as lisp's function reference if True
sxprlib_enableDec = True # enable decimal number (like "1234567890") if True
sxprlib_enableFloat = False # enable floating point (like "12.1", "12e10") if True
sxprlib_enableBin = False # enable binary number (like "#b10") if True
sxprlib_enableOct = False # enable octal number (like "#o76") if True
sxprlib_enableHex = False # enable hexadecimal number (like "#xFE") if True
sxprlib_enableRadix = False # enable radix number (like "#36rABCZ") if True
sxprlib_enableComplex = False # treat "#C(...)" as a complex number if True
sxprlib_enableArray = False # treat "#(...)" or "#nA(...) as an array if True
sxprlib_enableFrac = False # treat "[+-]?[0-9]+/[0-9]+" as fractional number if True
sxprlib_enableChar = False # treat "#\s" as a character if True
sxprlib_ignoreCase = False # ignore case of Symbol if True
from sys import stdout as __stdout
from json import dumps as _dumps
from unicodedata import east_asian_width as _east_asian_width
# define east_asian_width column count
eawcolumncount = {"W": 2, "F": 2, "A": 2, "H": 1, "Na": 1, "N": 1}
from re import compile as __compile
from re import ASCII as __ASCII
_is_integer = __compile(r"[+-]?\d+", __ASCII).fullmatch
_is_bin = __compile(r"[+-]?#[bB][01]+(/[01]+)?", __ASCII).fullmatch
_is_oct = __compile(r"[+-]?#[oO][0-7]+(/[0-7]+)?", __ASCII).fullmatch
_is_hex = __compile(r"[+-]?#[xX][0-9a-fA-F]+(/[0-9a-fA-F]+)?", __ASCII).fullmatch
_is_radix = __compile(
r"[+-]?#[1-9][0-9]?[rR][0-9a-zA-Z]+(/[0-9a-zA-Z]+)?", __ASCII
).fullmatch
_is_number = __compile(
r"[+-]?(\d+(\.\d*)?|\d*\.\d+)([defsDEFS][+-]?\d+)?", __ASCII
).fullmatch
_is_fraction = __compile(r"[+-]?\d+/\d+", __ASCII).fullmatch
_is_arrayprefix = __compile(r"#[0-9]+[aA]", __ASCII).fullmatch
_is_charhex = __compile(r"#\\[uxUX][0-9a-fA-F]+", __ASCII).fullmatch
from weakref import WeakValueDictionary as _WVDic
def _inany(item, lists):
for l in lists:
if item in l:
return True
return False
def __is_oct_digit(c):
if ("0" <= c) and (c <= "7"):
return True
else:
return False
def __is_hex_digit(c):
if ("0" <= c) and (c <= "9"):
return True
elif ("a" <= c) and (c <= "f"):
return True
elif ("A" <= c) and (c <= "F"):
return True
else:
return False
# ---------------------- data type definition
class _ReadOnlyClassVarMeta(type):
def __setattr__(self, name, value):
if not name in self.__dict__:
raise PermissionError(name)
if self.__dict__[name] is not None:
raise PermissionError("{} is read only!".format(name))
super().__setattr__(name, value)
def __delattr__(self, name):
if not name in self.__dict__:
raise AttributeError(name)
else:
raise PermissionError(name)
# data type: Nil
class Nil(metaclass=_ReadOnlyClassVarMeta):
"""Definition of Nil data type"""
__singleinstance = None
car = None
cdr = None
def __new__(self, *args, **kwargs):
if Nil.__singleinstance is None:
Nil.__singleinstance = super().__new__(self)
Nil.car = Nil.__singleinstance
Nil.cdr = Nil.__singleinstance
return Nil.__singleinstance
def __setattr__(self, name, value):
if name in {"car", "cdr"}: # avoid overriding/hiding class variable car and cdr
raise PermissionError(name)
# super().__setattr__(name, value)
self.__dict__[name] = value
def __str__(self):
return "()"
def __repr__(self):
return "NIL"
def __len__(self):
return 0
def __iter__(self):
return _ConsIterator(self)
def __eq__(self, v):
return self is v
def __ne__(self, v):
return self is not v
_NIL = Nil() # Nil() returns a singleton NIL instance
NIL = Nil()
# data type: Cons
class Cons:
"""Definition of Cons data type"""
def __init__(self, car=_NIL, cdr=_NIL):
self.car = car
self.cdr = cdr
def __str__(self):
l = []
s = Cons.__Sxpr2Str(self, l)
l.clear()
del l
return s
def __repr__(self):
l = dict()
s = Cons.__Sxpr2Repr(self, l)
l.clear()
del l
return s
def __len__(self):
n = 1
c = self
occurence = {id(c)}
while type(c.cdr) is Cons and not id(c.cdr) in occurence:
n = n + 1
occurence.add(id(c.cdr))
c = c.cdr
occurence.clear()
del occurence
return n
def __getitem__(self, n):
if type(n) is slice:
raise NotImplementedError("Cons: Slicing Cons object is not implemented.")
if n < 0:
raise IndexError("Cons: index out of range")
m = n
c = self
while m > 0:
if not type(c) in {Cons, Nil}:
raise IndexError("Cons: index out of range")
c = c.cdr
m = m - 1
if type(c) is not Cons:
return c
else:
return c.car
def __setitem__(self, n, x):
if type(n) is slice:
raise NotImplementedError("Cons: Slicing Cons object is not implemented.")
if n < 0:
raise IndexError("Cons: index out of range")
m = n
c = self
p = _NIL
while m > 0:
if type(c) is not Cons:
raise IndexError("Cons: index out of range")
p = c
c = c.cdr
m = m - 1
if type(c) is not Cons:
p.cdr = x
else:
c.car = x
def __iter__(self):
return _ConsIterator(self)
def __delattr__(self, name):
if name in {"car", "cdr"}:
raise PermissionError(name)
else:
super().__delattr__(name)
def __eq__(self, v):
if type(v) is Cons:
return repr(self) == repr(v)
return False
def __ne__(self, v):
if type(v) is Cons:
return repr(self) != repr(v)
return True
@staticmethod
def __Sxpr2Str(ex, occurence):
if type(ex) is Cons:
if sxprlib_enableQuote and ex.car == Symbol("quote") and consp(ex.cdr):
if null(ex.cdr.cdr):
return "'{}".format(Cons.__Sxpr2Str(ex.cdr.car, occurence))
if sxprlib_enableFuncRef and ex.car == Symbol("function") and consp(ex.cdr):
if null(ex.cdr.cdr) and symbolp(ex.cdr.car):
return "#'{}".format(Cons.__Sxpr2Str(ex.cdr.car, occurence))
return "({})".format(Cons.__Cons2SeqStr(ex, occurence))
return str(ex)
@staticmethod
def __Cons2SeqStr(c, occurence):
localoccurence = set()
occurence.append(localoccurence)
s = []
while True:
if type(c) is not Cons:
oc = []
oc.extend(occurence)
s.extend([". ", Cons.__Sxpr2Str(c, oc)])
oc.clear()
break
if _inany(id(c), occurence):
s.append("...")
break
localoccurence.add(id(c))
oc = []
oc.extend(occurence)
s.append(Cons.__Sxpr2Str(c.car, oc))
oc.clear()
c = c.cdr
if type(c) is Nil:
break
s.append(" ")
localoccurence.clear()
return "".join(s)
@staticmethod
def __Sxpr2Repr(s, occurence):
if s is _NIL:
return "NIL"
elif type(s) is not Cons:
return repr(s)
sbeg = []
send = []
while True:
if type(s) is Array:
sbeg.extend(
[
"Array(",
str(s.dim),
", ",
Cons.__Sxpr2Repr(s.value, occurence),
")",
]
)
break
elif type(s) is not Cons:
sbeg.append(repr(s))
break
if id(s) in occurence:
sbeg.extend(["<Cons at #", str(occurence[id(s)]), ">"])
break
occurence[id(s)] = len(occurence)
if type(s.car) is Array:
sbeg.extend(
[
"Cons(Array(",
str(s.car.dim),
", ",
Cons.__Sxpr2Repr(s.car.value, occurence),
"), ",
]
)
send.append(")")
else:
sbeg.extend(["Cons(", Cons.__Sxpr2Repr(s.car, occurence), ", "])
send.append(")")
s = s.cdr
sbeg.extend(send)
# del send
return "".join(sbeg)
# data type: Char
class Char:
"""Definition of Char data type"""
__CharInstance = _WVDic({})
__NameToCharDic = {
"Backspace": "\x08",
"Escape": "\x1b",
"Linefeed": "\n",
"Newline": "\n",
"Page": "\x0c",
"Return": "\r",
"Rubout": "\x1f",
"Space": " ",
"Tab": "\t",
}
__CharToNameDic = {
"\x08": "Backspace",
"\t": "Tab",
"\n": "Linefeed",
"\x0c": "Page",
"\r": "Return",
"\x1b": "Escape",
"\x1f": "Rubout",
" ": "Space",
}
def __new__(self, value="?"):
if type(value) is Char:
return value
elif type(value) is str:
v = value
elif type(value) is String:
v = value.value
else:
v = str(value)
if not Char.IsChar(v):
raise ValueError('Char(): Illegal argument "{}"!'.format(v))
if _is_charhex(v): # "#\\[uxUX][0-9a-fA-F]+"
v = "{:c}".format(int(v[3:], 16))
elif v.startswith("#\\"):
v = v.replace("#\\", "")
v = Char.__NameToCharDic.get(v.capitalize(), v)
obj = Char.__CharInstance.get(v)
if obj is None:
obj = super().__new__(self)
obj.value = v
Char.__CharInstance[v] = obj
return obj
def __str__(self):
v = self.value
c = ord(v)
if c <= 32 or (127 <= c and c <= 255):
v = "#\\{}".format(Char.__CharToNameDic.get(v, "x{:02x}".format(c)))
else:
v = _dumps(v, ensure_ascii=False)
v = "#\\" + v[1:][:-1]
v = v.replace("\\\\", "\\")
if len(v) >= 12:
v = "#\\U{:08x}".format(c)
return v
def __repr__(self):
v = self.value
c = ord(v)
if c <= 32 or (127 <= c and c <= 255):
v = '"{}"'.format(Char.__CharToNameDic.get(v, "\\x{:02x}".format(c)))
else:
v = _dumps(v, ensure_ascii=False)
if len(v) >= 14:
v = '"\\U{:08x}"'.format(c)
return "Char({})".format(v)
def __setattr__(self, name, value):
if name == "value" and name in self.__dict__: # avoid overriding 'value'
raise PermissionError("Char: {} is read only!".format(name))
# super().__setattr__(name, value)
self.__dict__[name] = value
def __delattr__(self, name):
if name == "value":
raise PermissionError(name)
else:
super().__delattr__(name)
def __hash__(self):
return hash(("SxprLib Char", self.value))
def __eq__(self, v):
if type(v) in {Char, String}:
return v.value == self.value
elif type(v) is str:
return v == self.value
return False
def __ne__(self, v):
if type(v) in {Char, String}:
return v.value != self.value
elif type(v) is str:
return v != self.value
return True
@staticmethod
def listall():
return [x for x in Char.__CharInstance]
@staticmethod
def IsChar(s):
if type(s) is not str:
return False
if _is_charhex(s): # "#\\[uxUX][0-9a-fA-F]+"
x = int(s[3:], 16)
if 0 <= x and x <= 0x10FFFF:
return True
else:
return False
if s.startswith("#\\"):
s = s.replace("#\\", "")
if len(s) == 1:
return True
else:
return s.capitalize() in Char.__NameToCharDic
# data type: Symbol
class Symbol:
"""Definition of Symbol data type"""
__SymbolInstance = _WVDic({})
def __new__(self, value="?"):
if type(value) is Symbol:
return value
elif type(value) is str:
v = value
elif type(value) is String:
v = value.value
else:
v = str(value)
if sxprlib_ignoreCase:
v = v.lower()
if not v:
raise ValueError("Symbol(): the argument must be a non-empty string!")
obj = Symbol.__SymbolInstance.get(v)
if obj is None:
obj = super().__new__(self)
obj.value = v
Symbol.__SymbolInstance[v] = obj
return obj
def __str__(self):
if self.value == ".":
return "\\."
else:
s = str(self.value).translate(
str.maketrans(
{
"(": "\\(",
")": "\\)",
" ": "_",
"|": "\\|",
'"': '\\"',
"\a": "\\a",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
"\t": "\\t",
"\v": "\\v",
}
)
)
if (
(sxprlib_enableDec and _is_integer(s))
or (sxprlib_enableBin and _is_bin(s))
or (sxprlib_enableOct and _is_oct(s))
or (sxprlib_enableHex and _is_hex(s))
or (sxprlib_enableRadix and _is_radix(s))
or (sxprlib_enableFrac and _is_fraction(s))
or (sxprlib_enableFloat and _is_number(s) and not _is_integer(s))
):
s = "|{}|".format(s)
return "{}".format(s)
def __repr__(self):
return "Symbol({})".format(repr(self.value))
def __setattr__(self, name, value):
if name == "value" and name in self.__dict__: # avoid overriding 'value'
raise PermissionError("Symbol: {} is read only!".format(name))
# super().__setattr__(name, value)
self.__dict__[name] = value
def __delattr__(self, name):
if name == "value":
raise PermissionError(name)
else:
super().__delattr__(name)
def __hash__(self):
return hash(("SxprLib Symbol", self.value))
def __eq__(self, v):
if type(v) is Symbol:
return self.value == v.value
return False
def __ne__(self, v):
if type(v) is Symbol:
return self.value != v.value
return True
@staticmethod
def listall():
return [x for x in Symbol.__SymbolInstance]
# data type: String
class String:
"""Definition of String data type"""
def __init__(self, value=""):
if type(value) is str:
self.value = value
elif type(value) in {Symbol, String}:
self.value = value.value
else:
self.value = str(value)
def __str__(self):
s = _dumps(self.value, ensure_ascii=False)
if not sxprlib_enableEscape:
s = s.replace("\\\\", "\\")
return s
def __repr__(self):
return "String({})".format(repr(self.value))
def __setattr__(self, name, value):
if name == "value" and name in self.__dict__: # avoid overriding 'value'
raise PermissionError("String: {} is read only!".format(name))
# super().__setattr__(name, value)
self.__dict__[name] = value
def __delattr__(self, name):
if name == "value":
raise PermissionError(name)
else:
super().__delattr__(name)
def __hash__(self):
return hash(("SxprLib String", self.value))
def __eq__(self, v):
if type(v) is String:
return self.value == v.value
else:
return self.value == v
def __ne__(self, v):
if type(v) is String:
return self.value != v.value
else:
return self.value != v
# data type: Int & Float
# use Python built-in int/float type
# data type: Fraction
# use Python standard module fractions.Fraction
from fractions import Fraction
# data type: Complex
from ratcomplex import Complex
Complex.str_format_spec = "#C({0} {1})"
# data type: Array
class Array:
"""Definition of Array data type"""
def __init__(self, dim, value=_NIL):
self.dim = int(dim)
if listp(value):
self.value = value
elif type(value) in {list, tuple}:
self.value = py2sx(value, False)
else:
self.value = py2sx(list(value), False)
def __str__(self):
if self.dim == 1:
return "#{}".format(str(self.value))
else:
return "#{}A{}".format(self.dim, str(self.value))
def __repr__(self):
return "Array({}, {})".format(self.dim, repr(self.value))
def __setattr__(self, name, value):
if name == "dim":
v = int(value)
elif name == "value":
if listp(value):
v = value
elif type(value) in {list, tuple}:
v = py2sx(value, False)
else:
v = py2sx(list(value), False)
else:
v = value
self.__dict__[name] = v
def __delattr__(self, name):
if name in {"dim", "value"}:
raise PermissionError(name)
else:
super().__delattr__(name)
# ------------------------- Cons Iterator
# Cons Iterator: enables S-expression data to be used in 'for v in CONS' form
class _ConsIterator:
"""Cons iterator object"""
def __init__(self, cons):
self.__cons = cons
self.__occurence = set()
def __next__(self):
if type(self.__cons) is Nil or id(self.__cons) in self.__occurence:
self.__occurence.clear()
raise StopIteration()
if type(self.__cons) is Cons:
value = self.__cons.car
self.__occurence.add(id(self.__cons))
self.__cons = self.__cons.cdr
else:
value = self.__cons
self.__cons = _NIL
return value
# ------------------------- Standard Lisp function
def car(c):
"""return car of Cons object"""
return c.car
def cdr(c):
"""return cdr of Cons object"""
return c.cdr
def mkcons(a, d):
"""make Cons object"""
return Cons(a, d)
def mklist(*args):
"""make S-expression List (chained Cons) object"""
r = _NIL
for v in args[::-1]:
r = Cons(v, r)
return r
def consp(s):
"""check if argument is Cons type"""
return type(s) is Cons
def null(s):
"""check if argument is Nil type"""
return s is _NIL
def listp(s):
"""check if argument is Nil or Cons type"""
return (s is _NIL) or (type(s) is Cons)
def symbolp(s):
"""check if argument is Symbol type"""
return type(s) is Symbol
def stringp(s):
"""check if argument is String or str type"""
return type(s) in {String, str}
def characterp(s):
"""check if argument is Char type"""
return type(s) is Char
def integerp(s):
"""check if argument is int type"""
return type(s) is int
def floatp(s):
"""check if argument is float type"""
return type(s) is float
def rationalp(s):
"""check if argument is int or Fraction type"""
return type(s) in {int, Fraction}
def complexp(s):
"""check if argument is built-in complex or Complex type"""
return type(s) in {complex, Complex}
def realp(s):
"""check if argument is int or float or Fraction type"""
return type(s) in {int, float, Fraction}
def numberp(s):
"""check if argument is int or float or Fraction or complex or Complex type"""
return type(s) in {int, float, Fraction, complex, Complex}
def atom(s):
"""check if argument is NOT Cons type"""
return not (consp(s))
def arrayp(s):
"""check if argument is Array type"""
return type(s) is Array
def vectorp(s):
"""check if argument is Array type and dimension is 1"""
if type(s) is Array:
return s.dim == 1
return False
def mkreverse(l):
"""make reversed S-expression List"""
if not listp(l):
raise TypeError(
"mkreverse(): Not a valid S-expression List! {}".format(repr(l))
)
n = len(l)
r = _NIL
for v in l:
if n < 1:
break
r = Cons(v, r)
n = n - 1
return r
def mkappend(l1, l2):
"""make appended S-expression List"""
if null(l1):
return l2
elif consp(l1):
n = len(l1) - 1
ret = Cons(l1.car)
c = ret
l = l1.cdr
while n > 0:
c.cdr = Cons(l.car)
c = c.cdr
l = l.cdr
n = n - 1
c.cdr = l2
return ret
else:
raise TypeError("mkappend(): Not a List!")
def nconc(l1, l2): # destructive append
"""concatenate two S-expression Lists destructively"""
if null(l1):
return l2
elif consp(l1):
n = len(l1) - 1
ret = l1
while n > 0:
l1 = l1.cdr
n = n - 1
l1.cdr = l2
return ret
else:
raise TypeError("nconc(): Not a List!")
def member(s, l):
"""search S-expression List for item"""
if not consp(l):
return _NIL
n = len(l)
while not (s == l.car):
l = l.cdr
n = n - 1
if n < 1:
return _NIL
return l
# ------------------------- miscellaneous tools
# sx2py: convert S-expression object to Python object
def sx2py(s, native=True):
"""convert S-expression object to Python object"""
occurence = set()
listdic = dict()
s = __sx2py(s, native, occurence, listdic)
listdic.clear()
occurence.clear()
return s
def __sx2py(s, native, occurence, listdic):
if s is _NIL:
return []
elif native and (type(s) in {String, Symbol, Char}):
return s.value
elif type(s) is Cons:
# if (
# sxprlib_enableQuote
# and s.car == Symbol("quote")
# and consp(s.cdr)
# and null(s.cdr.cdr)
# ):
# return __sx2py(s.cdr.car, native, occurence, listdic)
# if (
# sxprlib_enableFuncRef
# and s.car == Symbol("function")
# and consp(s.cdr)
# and null(s.cdr.cdr)
# and symbolp(s.cdr.car)
# ):
# return __sx2py(s.cdr.car, native, occurence, listdic)
if id(s) in listdic:
return listdic[id(s)]
else:
l = []
listdic[id(s)] = l
while type(s) is Cons:
if id(s) in occurence:
raise ValueError("sx2py(): unresolvable recursion found.")
occurence.add(id(s))
l.append(__sx2py(s.car, native, occurence, listdic))
s = s.cdr
if s is not _NIL:
l.append(__sx2py(s, native, occurence, listdic))
return l
elif type(s) is Fraction:
if s.denominator == 1:
return s.numerator
else:
return s
elif type(s) is Complex:
return complex(s)
elif type(s) is Array:
return __sx2py(s.value, native, occurence, listdic)
else:
return s
# py2sx: convert Python list/tuple to S-expression object
def py2sx(l, strassym=True):
"""convert Python list/tuple to S-expression object"""
occurence = dict()
s = __py2sx(l, strassym, occurence)
occurence.clear()
return s
def __py2sx(l, strassym, occurence):
if type(l) in {list, tuple}:
if id(l) in occurence:
return occurence[id(l)]
else:
if l:
ret = Cons(__py2sx(l[0], strassym, occurence))
occurence[id(l)] = ret
s = ret
for i in l[1:]:
s.cdr = Cons(__py2sx(i, strassym, occurence))
s = s.cdr
s.cdr = _NIL
else:
ret = _NIL
return ret
elif type(l) is str:
if strassym:
return Symbol(l)
else:
return String(l)
elif type(l) is complex:
return Complex(l.real, l.imag)
elif type(l) in {
int,
float,
Fraction,
Nil,
Cons,
Char,
Symbol,
String,
Complex,
Array,
}:
return l
else:
return String(str(l))
# sxpprint: simple pretty-print for S-expression data structure
def sxpprint(s, file=__stdout):
"""simple pretty-print for S-expression"""
out = file
occurence = []
__sxpprint_sub(s, 0, occurence, out)
out.write("\n")
occurence.clear()
del occurence
def __sxpprint_sub(s, n, occurence, out):
localoccurence = set()
occurence.append(localoccurence)
quote = ""
while sxprlib_enableQuote and consp(s):
if s.car == Symbol("quote") and consp(s.cdr):
if null(s.cdr.cdr):
quote = quote + "'"
s = s.cdr.car
continue
break
if sxprlib_enableFuncRef and consp(s):
if s.car == Symbol("function") and consp(s.cdr):
if null(s.cdr.cdr) and symbolp(s.cdr.car):
quote = quote + "#'"
s = s.cdr.car