-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmetaL.py
3077 lines (2661 loc) · 85.9 KB
/
metaL.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
## @file
## @brief powered by `metaL`
## @defgroup info metainfo
## @{
MODULE = 'metaL'
TITLE = '[meta]programming [L]anguage'
ABOUT = 'homoiconic metaprogramming system\n* powered by `metaL`'
AUTHOR = 'Dmitry Ponyatov'
EMAIL = '[email protected]'
YEAR = 2020
LICENSE = 'MIT'
GITHUB = 'https://github.com/ponyatov'
LOGO = 'logo.png'
MANIFEST = 'https://github.com/ponyatov/metaL/wiki/metaL-manifest'
## @}
import os, sys, random, re
## @defgroup persist Persistence
## @brief inherit `Unison` *immutable global storage*: https://www.unisonweb.org
import xxhash
## @defgroup object Object
## @brief base object graph node
## @ingroup object
class Object:
## construct object
## @param[in] V given scalar value
def __init__(self, V):
if isinstance(V, Object):
V = V.val
## object name / scalar value (string, number,..)
self.val = V
## slots = attributes = dict = env
self.slot = {}
## nested AST = vector = stack = queue
self.nest = []
## parent nodes registry
self.par = []
## global storage id
## @ingroup persist
self.gid = hash(self)#self.sync().gid
## @name storage/hot-update
## @{
## this method must be called on any object update
## (compute hash, update persistent memory,..)
##
## mostly used in operator methods in form of `return self.sync()`
## @ingroup persist
## @returns self
def sync(self):
# update global hash
self.gid = hash(self)
## sync with storage
#storage.put(self)
return self
## fast object hashing for global storage id
## @ingroup persist
def __hash__(self):
hsh = xxhash.xxh32()
hsh.update(self._type())
hsh.update('%s' % self.val)
for i in self.slot:
hsh.update(i)
hsh.update(self.slot[i].gid.to_bytes(8, 'little'))
for j in self.nest:
hsh.update(j.gid.to_bytes(8, 'little'))
return hsh.intdigest()
## serialize to .json
## @ingroup persist
def json(self):
js = '{"gid":"%x","type":"%s","val":"%s",' % (
self.gid, self._type(), self.val)
slots = []
for k in sorted(self.slot.keys()):
slots.append('"%s":"%.8x"' % (k, self.slot[k].gid))
js += '"slot":{%s},' % ','.join(slots)
nested = []
for i in self.nest:
nested.append('"%.8x"' % i.gid)
js += '"nest":[%s]' % ','.join(nested)
return js + "}"
## @}
## @name dump
## @{
## `print` callback
def __repr__(self): return self.dump()
## dump for tests (no hash/gid in headers)
def test(self): return self.dump(test=True)
## dump in full text tree form
## @param[in] cycle already dumped objects (cycle prevention registry)
## @param[in] depth recursion depth
## @param[in] prefix optional prefix in `<T:V>` header
## @param[in] test test dump option @ref test
def dump(self, cycle=None, depth=0, prefix='', test=False):
# header
tree = self.pad(depth) + self.head(prefix, test)
# cycles
if not depth:
cycle = []
if self in cycle:
return tree + ' _/'
# slot{}s
for i in sorted(self.slot.keys()):
tree += self.slot[i].dump(cycle + [self],
depth + 1, f'{i} = ', test)
# nest[]ed
for j, k in enumerate(self.nest):
tree += k.dump(cycle + [self],
depth + 1, f'{j}: ', test)
# subtree
return tree
## paddig for @ref dump
def pad(self, depth, block=True, tab='\t'):
if block:
ret = '\n'
ret += tab * depth
else:
ret = ''
return ret
## short `<T:V>` header only
## @param[in] prefix optional prefix in `<T:V>` header
## @param[in] test test dump option @ref test
def head(self, prefix='', test=False):
hdr = '%s<%s:%s>' % (prefix, self._type(), self._val())
if not test:
hdr += ' #%.8x @%x' % (self.gid, id(self))
return hdr
## object class name (lowercased as marker of instance)
def _type(self): return self.__class__.__name__.lower()
## `.val` output for dumps (limited length, escaped control chars)
def _val(self): return '%s' % self.val
## @}
## @name plot
## @{
## plot object graph via GraphViz/`dot`
## @returns `digraph{}` string for `dot`
## @param[in] cycle block (plottted nodes accumulator list
## @param[in] depth recursion depth
## @param[in] parent node
## @param[in] label on edge
## @param[in] color of edge
def plot(self, cycle=None, depth=0, parent=None, label='', color='black'):
# recursion root
if not depth:
dig = 'digraph "%s" {\nrankdir=LR;\n' % self.head(test=True)
cycle = []
else:
dig = '\t' * depth
# node
me = 'zid%s' % id(self)
dig += '%s [label="%s"]\n' % (me, self.head(test=True))
# edge
if parent:
dig += '\t' * depth + \
'%s -> %s [label="%s",color="%s"]\n' % (
parent, me, label, color)
# cycles block
if self in cycle:
return dig
else:
cycle += [self]
# slots
for i in sorted(self.slot.keys()):
dig += self.slot[i].plot(cycle, depth + 1,
parent=me, label=i, color='blue')
# recursion root
if not depth:
dig += '}\n'
with open('/tmp/dot.dot', 'w') as f:
f.write(dig)
return dig
else:
return dig
## @}
## @name operator
## @{
## `A.keys()`
def keys(self):
return self.slot.keys()
## `A[key] ~> A.slot[key:str] | A.nest[key:int] `
def __getitem__(self, key):
if isinstance(key, int):
return self.nest[key]
if isinstance(key, str):
return self.slot[key]
# try:
# return self.slot[key]
# except KeyError:
# return Undef(key) // self
raise TypeError(key)
## `A.B`
def dot(self, that, ctx):
assert isinstance(that, Object)
return self[that.val]
## `A[key] = B`
def __setitem__(self, key, that):
if isinstance(that, str):
that = String(that)
if isinstance(that, int):
that = Integer(that)
if isinstance(key, str):
self.slot[key] = that
elif isinstance(key, int):
self.nest[key] = that
else:
raise TypeError(key)
return self.sync()
## `A << B ~> A[B.type] = B`
def __lshift__(self, that):
if isinstance(that, str):
that = String(that)
return self.__setitem__(that._type(), that)
## `A >> B ~> A[B.val] = B`
def __rshift__(self, that):
return self.__setitem__(that.val, that)
## `A // B -> A.push(B)`
## @param[in] that `B`
## @param[in] sync push object with sync
## (hash/storage update, use `False` for massive & IO pushes)
def __floordiv__(self, that):
if isinstance(that, str): # wrap Python string
that = String(that)
that.pre__floordiv__(self)
self.nest.append(that)
that.post__floordiv__(self)
return self
## pre-callback for `__floordiv__`
def pre__floordiv__(self, parent): pass
## post-callback for `__floordiv__`
def post__floordiv__(self, parent):
self.par.append(parent)
## @}
## @name stack ops
## @{
## clean `.nest[]`
def dropall(self):
self.nest = []
return self
## push to `.nest[]`
## @param[in] sync push with sync
## @param[in] that `B` operand to be pushed
def push(self, that):
return self // that
## insert `that` into parent node after the current
def after(self, that):
assert len(self.par) == 1
for parent in self.par:
index = parent.index(self)
parent.insert(index + 1, that)
that.post__floordiv__(parent)
return self
## insert `A[index]=B`
## @param[in] index integer indsex in `.nest[]`
## @param[in] that `B` operand to be inserted
def insert(self, index, that):
self.nest.insert(index, that)
return self
def drop(self, count=1):
for i in range(count):
self.nest.pop()
return self
## find index of subgraph
def index(self, that):
return self.nest.index(that)
## @}
## @name evaluation
## @{
## evaluate in context
## @param[in] ctx context
def eval(self, ctx): raise Error((self))
## apply as function
## @param[in] that operand (function argument/s)
## @param[in] ctx context
def apply(self, that, ctx): raise Error((self))
## @}
## @name code generation
## @{
## comment start (for sigle-line and block comments)
def comment(self):
return self.par[0].comment()
## comment end (for block comments)
def commend(self):
return self.par[0].commend()
## default f"format"ting for all nodes
def __format__(self, spec=None):
ret = f'{self.val}'
if 't' in spec:
ret = ret.title()
if 'u' in spec:
ret = ret.upper()
if 'l' in spec:
ret = ret.lower()
return ret
## to generic text file: use `.json` in place of `Error`
## @ingroup gen
def file(self, depth=0, tab=None):
assert tab
return self.pad(depth, self.par[0].block, tab) + self.json()
## @}
## @ingroup object
## nil value
class Nil(Object):
def __init__(self):
super().__init__('')
## @defgroup error Error
## @ingroup object
## @ingroup error
class Error(Object, BaseException):
pass
# ## @ingroup error
# class Undef(Object):
# pass
## @defgroup prim Primitive
## @ingroup object
## @ingroup prim
class Primitive(Object):
## primitives evaluates to itself
def eval(self, ctx): return self
## @ingroup Nil
class Nil(Primitive):
def __init__(self): Primitive.__init__(self, '')
## @ingroup prim
class Name(Primitive):
## names evaluate via context lookup
def eval(self, ctx): return ctx[self.val]
## assignment
def eq(self, that, ctx):
ctx[self.val] = that
return that
## @ingroup prim
class String(Primitive):
## @param[in] V string value
## @param[in] block source code flag: tabbed blocks or inlined code
def __init__(self, V, block=True, tab=1):
super().__init__(V)
self.block = block
self.tab = tab
self.rem = None
def _val(self):
s = ''
v = '' if self.val == None else self.val
for c in v:
if c == '\n':
s += r'\n'
elif c == '\r':
s += r'\r'
elif c == '\t':
s += r'\t'
else:
s += c
return s
def file(self, depth=0, tab=None):
assert tab
# assert len(self.par) == 1
ret = self.pad(depth, self.par[0].block, tab) + f'{self.val}'
if self.val is None:
ret = ''
ret += f' {self.rem}' if self.rem else ''
for i in self.nest:
ret += i.file(depth + 1, tab)
return ret
def py(self): return self.val
def cc_arg(self): return '"%s"' % self._val()
def post__floordiv__(self, parent):
super().post__floordiv__(parent)
## @ingroup prim
## floating point
class Number(Primitive):
def __init__(self, V):
Primitive.__init__(self, float(V))
def file(self, depth=0, tab=None):
assert tab
return '%s' % self.val
## @name operator
## @{
## `+A`
def plus(self, ctx):
return self.__class__(+self.val)
## `-A`
def minus(self, ctx):
return self.__class__(-self.val)
## `A + B`
def add(self, that, ctx):
assert type(self) == type(that)
return self.__class__(self.val + that.val)
## `A - B`
def sub(self, that, ctx):
assert type(self) == type(that)
return self.__class__(self.val - that.val)
## `A * B`
def mul(self, that, ctx):
assert type(self) == type(that)
return self.__class__(self.val * that.val)
## `A / B`
def div(self, that, ctx):
assert type(self) == type(that)
return self.__class__(self.val / that.val)
## `A ^ B`
def pow(self, that, ctx):
assert type(self) == type(that)
return self.__class__(self.val ** that.val)
## @}
## @ingroup prim
class Integer(Number):
def __init__(self, V):
Primitive.__init__(self, int(V))
## @ingroup prim
## hexadecimal machine number
class Hex(Integer):
def __init__(self, V):
Primitive.__init__(self, int(V[2:], 0x10))
def _val(self):
return hex(self.val)
## @ingroup prim
## bit string
class Bin(Integer):
def __init__(self, V):
Primitive.__init__(self, int(V[2:], 0x02))
def _val(self):
return bin(self.val)
## @defgroup cont Container
## @ingroup object
## @ingroup cont
## generic data container
class Container(Object):
pass
## @ingroup cont
## var size array (Python list)
class Vector(Container):
def __init__(self, V='', nest=None):
super().__init__(V)
if nest:
self.nest = nest
def eval(self, ctx):
res = self.__class__(self.val)
for i in self.nest:
res // i.eval(ctx)
return res
def cc_arg(self):
ret = ','.join([j.cc_arg() for j in self.nest])
return '/* %s */ %s' % (self.head(), ret)
## @ingroup cont
class Tuple(Vector):
def __init__(self, nest=[]):
super().__init__('')
for i in nest:
self // i
def file(self, depth=0, tab=None):
return f'{self}'
def __format__(self, spec):
assert not spec
return ', '.join(f'{i.__format__(spec)}' for i in self.nest)
## @ingroup cont
## FIFO stack
class Stack(Container):
pass
## @ingroup cont
## associative array
class Dict(Container):
pass
## @defgroup active Active
## @ingroup object
## @ingroup active
## executable data elements
class Active(Object):
pass
## @ingroup active
## function
class Fn(Active):
def __init__(self, V, args=[], returns=Nil()):
super().__init__(V)
self['args'] = self.args = Args(args)
self['ret'] = self.ret = returns
self.block = True
def eval(self, ctx): return self
def apply(self, that, ctx):
self['arg'] = that
self['ret'] = Nil()
print('self', self)
print('that', that)
return self['ret']
def at(self, that, ctx): return self.apply(that, ctx)
def file(self, depth=0, tab=None):
pfx = ''
assert tab
res = self.pad(depth, self.par[0].block, tab)
res += 'def %s%s(%s):' % (pfx, self.val, self.args.file(tab=tab))
if not self.nest:
res += ' pass'
for i in self.nest:
res += i.file(depth + 1, tab)
return res
## @ingroup active
## operator
class Op(Active):
def eval(self, ctx):
if self.val == '`':
return self.nest[0]
# greedy computation for all subtrees
greedy = list(map(lambda i: i.eval(ctx), self.nest))
# unary
if len(greedy) == 1:
if self.val == '+':
return greedy[0].plus(ctx)
if self.val == '-':
return greedy[0].minus(ctx)
# binary
if len(greedy) == 2:
if self.val == '+':
return greedy[0].add(greedy[1], ctx)
if self.val == '-':
return greedy[0].sub(greedy[1], ctx)
if self.val == '*':
return greedy[0].mul(greedy[1], ctx)
if self.val == '/':
return greedy[0].div(greedy[1], ctx)
if self.val == '^':
return greedy[0].pow(greedy[1], ctx)
if self.val == '=':
return greedy[0].eq(greedy[1], ctx)
if self.val == '.':
return greedy[0].dot(greedy[1], ctx)
if self.val == ':':
return greedy[0].colon(greedy[1], ctx)
if self.val == '@':
return greedy[0].at(greedy[1], ctx)
# unknown
raise Error((self))
## @ingroup active
## Virtual Machine (environment + stack + message queue)
class VM(Active):
pass
## @ingroup active
## global system VM
vm = VM(MODULE)
vm << vm
## @defgroup meta Meta
## @ingroup object
## @ingroup meta
class Meta(Object):
pass
## @ingroup meta
## source code
class S(Meta, String):
def __init__(self, start=None, end=None, block=True, **kwargs):
if 'doc' in kwargs:
String.__init__(self, kwargs['doc'], block, tab=0)
else:
String.__init__(self, start, block)
self.rem = kwargs['rem'] if 'rem' in kwargs else None
self.end = end
def file(self, depth=0, tab=None):
assert tab
ret = super().file(depth, tab)
ret += self.file_end(depth, tab)
return ret
def file_end(self, depth, tab):
assert tab
blocking = self.block if hasattr(self, 'block') else self.par[0].block
if self.end is None:
return ''
elif self.end == '':
return '\n'
else:
return self.pad(depth, blocking, tab) + self.end
class CR(S):
def __init__(self):
super().__init__('', block=False)
def file(self, depth=0, tab=None):
assert tab
return '\n'
## @ingroup meta
## commented code block
class D(S):
def __init__(self, V='', end=None):
super().__init__(end=end, doc=V)
def file(self, depth=0, tab=None):
assert tab
return super().file(depth - 1, tab)
class H(S):
def __init__(self, V, *vargs, **kwargs):
super().__init__(f'{V}', end=None if 0 in vargs else f'</{V}>')
for i in kwargs:
self[i] = f'{kwargs[i]}'
def file(self, depth=0, tab=None):
assert tab
assert len(self.par) == 1
ret = self.pad(depth, self.par[0].block, tab) + f'<{self.val}'
for i in sorted(self.slot.keys()):
j = 'class' if i == 'clazz' else i
j = re.sub(r'_', r'-', j)
ret += f' {j}="{self.slot[i]}"'
ret += '>'
for j in self.nest:
ret += j.file(depth + 1, tab)
ret += self.file_end(depth, tab)
return ret
## @ingroup meta
class Return(S):
def __init__(self, V):
super().__init__('return %s' % V)
## @ingroup meta
class Arg(Meta, Name):
def __int__(self): return self.val
def file(self, depth=0, tab=' '):
assert tab
return f'{self}'
## @ingroup meta
class Args(Meta, Tuple):
def __init__(self, nest=[]):
Tuple.__init__(self, nest=nest)
self.block = False
## @ingroup meta
class Class(Meta):
def __init__(self, C, sup=None):
if type(C) == type(Class):
super().__init__(C.__name__)
self.C = C
else:
super().__init__(C)
if sup:
self['sup'] = self.sup = Args(sup)
self.block = True
def colon(self, that, ctx):
return self.C(that)
def file(self, depth=0, tab=None):
assert tab
ret = self.pad(depth, self.par[0].block, tab) + f'class {self}'
if 'sup' in self.keys():
ret += f'({self.sup})'
ret += ':'
if self.nest:
for j in self.nest:
ret += j.file(depth + 1, tab)
else:
ret += ' pass'
return ret
## @ingroup meta
class Method(Meta, Fn):
pass
## @ingroup meta
class pyInterface(Meta):
def __init__(self, V, ext=[]):
super().__init__(V)
self.block = True
for i in ext:
self // i
def file(self, depth=0, tab=None):
assert tab
ret = '\n' + \
self.pad(depth, self.par[0].block, tab) + f'## @name {self}'
if 'url' in self.keys():
ret += self.pad(depth, self.par[0].block,
tab=tab) + f"## {self['url']}"
ret += self.pad(depth, self.par[0].block, tab) + '## @{'
ret += '\n'
# z = ''
for i in self.nest:
ret += i.file(depth + 0)
#
ret += '\n'
ret += self.pad(depth, self.par[0].block, tab) + '## @}'
return ret
## @ingroup meta
class Module(Meta):
def file(self, depth=0, tab=None):
assert tab
return self.head(test=True)
vm['module'] = Class(Module)
## @ingroup meta
## text files with any code are devided by sections (can be nested as subsections)
class Section(Meta):
def __init__(self, V, comment=True):
super().__init__(V)
## every section known its parent: file or other outer section
assert not self.par
## sections always blocked in files
self.block = True
if not comment:
self.comment = lambda: False
# ## block mutiple parents for all `Section`s
# def pre__floordiv__(self, parent):
# assert not self.par
# super().pre__floordiv__(parent)
def file(self, depth=0, tab=None):
assert tab
# assert len(self.par) == 1
if not self.nest:
return ''
#
comment = self.comment()
head = self.head(test=True)
commend = self.commend()
#
ret = self.pad(depth, self.par[0].block, tab) if comment else ''
if comment:
ret += f'{comment} \\ {head}{commend}'
for i in self.nest:
ret += i.file(depth, tab)
if comment:
ret += self.pad(depth, self.par[0].block, tab)
ret += f'{comment} / {head}{commend}'
return ret
## @defgroup io IO
## @ingroup object
## @brief base file output
## @ingroup io
class IO(Object):
pass
## @ingroup io
class Dir(IO):
def sync(self):
if not self.par:
try:
os.mkdir(self.val)
except FileExistsError:
pass
return super().sync()
def pre__floordiv__(self, parent):
assert isinstance(parent, Dir)
super().pre__floordiv__(parent)
def post__floordiv__(self, parent):
assert isinstance(parent, Dir)
super().post__floordiv__(parent)
try:
os.mkdir(self.fullpath())
except FileExistsError:
pass
def fullpath(self):
assert len(self.par) <= 1
if self.par:
assert isinstance(self.par[0], Dir)
return self.par[0].fullpath() + '/' + self.val
else:
return self.val
# ## append file
# def __floordiv__(self, that):
# super().__floordiv__(that)
# # if isinstance(that, File):
# # that.fh = open('%s/%s%s' % (self.val, that.val, that.ext), 'w')
# # return IO.__floordiv__(self, that)
# # if isinstance(that, Dir):
# # that.val = '%s/%s' % (self.val, that.val)
# # return IO.__floordiv__(self, that)
# # raise Error((self))
## @ingroup io
class File(IO):
## @param[in] V file name without extension
## @param[in] ext file extension (default none)
## @param[in] comment syntax comment (depends on a file type)
def __init__(self, V, ext='', comment='#', tab='\t'):
## file handler not assigned on File object creation
self.fh = None
##
self.comment = lambda: comment
commends = {'<!--': '-->', '/*': '*/'}
commend = ' ' + commends[comment] if comment in commends else ''
self.commend = lambda: commend
##
super().__init__(V)
self['ext'] = self.ext = ext
self.tab = tab
##
if comment:
powered = f"powered by metaL: {MANIFEST}"
if len(comment) == len('#'):
self // f"{comment} {powered}{commend}"
# self // f"{comment*2} @file{commend}"
elif len(comment) >= len('//'):
self // f"{comment} {powered}{commend}"
# self // f"{comment*2} @file{commend}"
else:
raise Error((self.comment))
## every file has `top` section
self.top = Section('top')
self['top'] = self.top
self // self.top
## every file has `mid`ddle section
self.mid = Section('mid')
self['mid'] = self.mid
self // self.mid
## every file has `bot`tom section
self.bot = Section('bot')
self['bot'] = self.bot
self // self.bot
## all files holds tab-blocked sections/strings
self.block = True
def pre__floordiv__(self, parent):
assert isinstance(parent, Dir)
super().pre__floordiv__(parent)
def post__floordiv__(self, parent):
assert isinstance(parent, Dir)
super().post__floordiv__(parent)
self.fh = open(self.fullpath(), 'w')
def fullpath(self):
assert len(self.par) == 1
assert isinstance(self.par[0], Dir)
return self.par[0].fullpath() + '/' + self.val + self.ext
def __format__(self, spec):
assert not spec
return f'{self.val}{self.ext}'
def file(self, depth=0, tab=None):
assert tab
ret = ''
for j in self.nest:
ret += j.file(depth, tab)
if ret:
assert ret[0] == '\n'
ret = ret[1:] + '\n'
return ret
def sync(self):
if self.fh:
self.fh.seek(0)
self.fh.write(self.file(tab=self.tab))
self.fh.truncate()
self.fh.flush()
return super().sync()
# ## push object/line
# ## @param[in] that `B` operand: string of section will be pushed into file
# ## @param[in] sync `=False` default w/o flush to disk (via `sync()``)
# def __floordiv__(self, that, sync=False):
# return super().__floordiv__(that, sync)
## @defgroup net net
## @brief Networking
## @ingroup io
## @ingroup net
## networking object
class Net(IO):
pass
## @ingroup net
## TCP/IP address
class Ip(Net):
def __format__(self, spec):
assert not spec
return f'{self.val}'
## @ingroup net
## TCP/IP port
class Port(Net):
pass