-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmint.py
1893 lines (1642 loc) · 62.4 KB
/
mint.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 -*-
'''
mint - small, fast and simple template engine.
'''
import os
import re
import ast
import mmap
import time
import fnmatch
import logging
import weakref
import itertools
import htmlentitydefs
from ast import Load, Store, Param
from StringIO import StringIO
from functools import partial
from collections import deque
from xml.etree.ElementTree import TreeBuilder as _TreeBuilder, Element
############# LEXER
class BaseToken(object):
pass
class TokenWrapper(BaseToken):
'''
Objects of this class reprezents tokens
'''
def __init__(self, token, value=None, regex_str=None):
assert value or regex_str, 'Provide token text value or regex'
self.token = intern(token)
if regex_str is not None:
self.regex = re.compile(regex_str, re.U)
else:
self.regex = re.compile(r'%s' % re.escape(value), re.U)
def __str__(self):
return self.token
__repr__ = __str__
class TextToken(BaseToken):
'Special token for text'
def __str__(self):
return 'text'
__repr__ = __str__
class TokenIndent(BaseToken):
def __str__(self):
return 'indent'
__repr__ = __str__
class TokenUnindent(BaseToken):
def __str__(self):
return 'unindent'
__repr__ = __str__
class EOF(BaseToken):
'Special token'
def __str__(self):
return 'eof'
__repr__ = __str__
# constants
TAG_CHAR = '@'
STMT_CHAR = '#'
COMMENT_CHAR = '--'
# Tokens
TOKEN_TAG_START = TokenWrapper('tag_start', value=TAG_CHAR)
TOKEN_TAG_ATTR_SET = TokenWrapper('tag_attr_set', value='%s.' % TAG_CHAR)
TOKEN_TAG_ATTR_APPEND = TokenWrapper('tag_attr_append', value='%s+' % TAG_CHAR)
TOKEN_BASE_TEMPLATE = TokenWrapper('base_template', value='%sbase: ' % STMT_CHAR)
TOKEN_STATEMENT_IF = TokenWrapper('statement_if', value='%sif ' % STMT_CHAR)
TOKEN_STATEMENT_ELIF = TokenWrapper('statement_elif', regex_str=r'(%selif |%selse if )' % (
re.escape(STMT_CHAR), re.escape(STMT_CHAR)))
TOKEN_STATEMENT_ELSE = TokenWrapper('statement_else', value='%selse:' % STMT_CHAR)
TOKEN_STATEMENT_FOR = TokenWrapper('statement_for', value='%sfor ' % STMT_CHAR)
TOKEN_SLOT_DEF = TokenWrapper('slot_def', regex_str=r'(%sdef |%sfunction )' % (re.escape(STMT_CHAR),
re.escape(STMT_CHAR)))
TOKEN_STMT_CHAR = TokenWrapper('hash', value=STMT_CHAR)
TOKEN_COMMENT = TokenWrapper('comment', value=COMMENT_CHAR)
TOKEN_BACKSLASH = TokenWrapper('backslash', value='\\')
TOKEN_DOT = TokenWrapper('dot', value='.')
TOKEN_PLUS = TokenWrapper('plus', value='+')
TOKEN_MINUS = TokenWrapper('minus', value='-')
TOKEN_COLON = TokenWrapper('colon', value=':')
TOKEN_PARENTHESES_OPEN = TokenWrapper('parentheses_open', value='(')
TOKEN_PARENTHESES_CLOSE = TokenWrapper('parentheses_close', value=')')
TOKEN_EXPRESSION_START = TokenWrapper('expression_start', value='{{')
TOKEN_EXPRESSION_END = TokenWrapper('expression_end', value='}}')
TOKEN_WHITESPACE = TokenWrapper('whitespace', regex_str=r'\s+')
TOKEN_NEWLINE = TokenWrapper('newline', regex_str=r'(\r\n|\r|\n)')
TOKEN_EOF = EOF()
TOKEN_TEXT = TextToken()
TOKEN_INDENT = TokenIndent()
TOKEN_UNINDENT = TokenUnindent()
tokens = (
TOKEN_TAG_ATTR_SET,
TOKEN_TAG_ATTR_APPEND,
TOKEN_TAG_START,
TOKEN_BASE_TEMPLATE,
TOKEN_STATEMENT_IF,
TOKEN_STATEMENT_ELIF,
TOKEN_STATEMENT_ELSE,
TOKEN_STATEMENT_FOR,
TOKEN_SLOT_DEF,
TOKEN_STMT_CHAR,
TOKEN_COMMENT,
TOKEN_BACKSLASH,
TOKEN_DOT,
TOKEN_PLUS,
TOKEN_MINUS,
TOKEN_PARENTHESES_OPEN,
TOKEN_PARENTHESES_CLOSE,
TOKEN_EXPRESSION_START,
TOKEN_EXPRESSION_END,
TOKEN_COLON,
TOKEN_WHITESPACE,
TOKEN_NEWLINE,
)
all_tokens = list(tokens) + [TOKEN_EOF, TOKEN_TEXT, TOKEN_INDENT, TOKEN_UNINDENT]
all_except = lambda *t: filter(lambda x: x not in t, all_tokens)
re_comment = re.compile(r'\s*//')
def base_tokenizer(fp):
'Tokenizer. Generates tokens stream from text'
if isinstance(fp, StringIO):
template_file = fp
size = template_file.len
else:
#empty file check
if os.fstat(fp.fileno()).st_size == 0:
yield TOKEN_EOF, 'EOF', 0, 0
return
template_file = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)
size = template_file.size()
lineno = 0
while 1:
lineno += 1
pos = 1
# end of file
if template_file.tell() == size:
yield TOKEN_EOF, 'EOF', lineno, 0
break
# now we tokinize line by line
line = template_file.readline().decode('utf-8')
line = line.replace('\r\n', '')
line = line.replace('\n', '')
# ignoring non XML comments
if re_comment.match(line):
continue
last_text = deque()
while line:
line_len = len(line)
for token in tokens:
m = token.regex.match(line)
if m:
if last_text:
yield TOKEN_TEXT, ''.join(last_text), lineno, pos
pos += len(last_text)
last_text.clear()
offset, value = m.end(), m.group()
line = line[offset:]
yield token, value, lineno, pos
pos += offset
break
# we did not get right in tokens list, so next char is text
if line_len == len(line):
last_text.append(line[0])
line = line[1:]
if last_text:
yield TOKEN_TEXT, ''.join(last_text), lineno, pos
pos += len(last_text)
last_text.clear()
yield TOKEN_NEWLINE, '\n', lineno, pos
# all work is done
template_file.close()
def indent_tokenizer(tokens_stream):
current_indent = 0
indent = 0
for tok in tokens_stream:
token, value, lineno, pos = tok
# backslashed line transfer
if token is TOKEN_BACKSLASH:
next_tok = tokens_stream.next()
next_token, next_value, next_lineno, next_pos = next_tok
if next_token is TOKEN_NEWLINE:
next_tok = tokens_stream.next()
while next_tok[0] in (TOKEN_WHITESPACE, TOKEN_NEWLINE):
next_tok = tokens_stream.next()
# first not newline or whitespace token
yield next_tok
continue
yield tok
tok = next_tok
token, value, lineno, pos = next_tok
# indenting and unindenting
if token is TOKEN_NEWLINE or (token is TOKEN_WHITESPACE and (lineno, pos) == (1, 1)):
if token is TOKEN_NEWLINE:
yield tok
next_tok = tokens_stream.next()
while next_tok[0] is TOKEN_NEWLINE:
next_tok = tokens_stream.next()
else:
next_tok = tok
next_token, next_value, next_lineno, next_pos = next_tok
if next_token is TOKEN_WHITESPACE:
ws_count = len(next_value)
if indent == 0:
indent = ws_count
if ws_count >= indent:
times = ws_count/indent
rest = ws_count % indent
range_ = times - current_indent
if range_ > 0:
# indenting
tmp_curr_indent = current_indent
for i in range(range_):
yield TOKEN_INDENT, ' '*indent, next_lineno, (i+tmp_curr_indent)*indent+1
current_indent += 1
elif range_ < 0:
# unindenting
for i in range(abs(range_)):
yield TOKEN_UNINDENT, ' '*indent, next_lineno, next_pos
current_indent -= 1
if rest:
yield TOKEN_WHITESPACE, ' '*rest, next_lineno, times*indent+1
continue
# next token is the whitespace lighter than indent or any other
# token, so unindenting to zero level
for i in range(current_indent):
yield TOKEN_UNINDENT, ' '*indent, lineno, pos
current_indent = 0
yield next_tok
# we do not yielding newline tokens
continue
yield tok
def tokenizer(fileobj):
return indent_tokenizer(base_tokenizer(fileobj))
############# LEXER END
UNSAFE_CHARS = '&<>"'
CHARS_ENTITIES = dict([(v, '&%s;' % k) for k, v in htmlentitydefs.entitydefs.items()])
UNSAFE_CHARS_ENTITIES = [(k, CHARS_ENTITIES[k]) for k in UNSAFE_CHARS]
UNSAFE_CHARS_ENTITIES_IN_ATTR = [(k, CHARS_ENTITIES[k]) for k in '<>"']
UNSAFE_CHARS_ENTITIES.append(("'",'''))
UNSAFE_CHARS_ENTITIES_IN_ATTR.append(("'",'''))
UNSAFE_CHARS_ENTITIES_REVERSED = [(v,k) for k,v in UNSAFE_CHARS_ENTITIES]
def escape(obj, ctx='tag'):
if hasattr(obj, '__html__'):
safe_markup = obj.__html__()
if ctx == 'tag':
return safe_markup
else:
for k, v in UNSAFE_CHARS_ENTITIES_IN_ATTR:
safe_markup = safe_markup.replace(k, v)
return safe_markup
obj = unicode(obj)
for k, v in UNSAFE_CHARS_ENTITIES:
obj = obj.replace(k, v)
return obj
def unescape(obj):
text = unicode(obj)
for k, v in UNSAFE_CHARS_ENTITIES_REVERSED:
text = text.replace(k, v)
return text
class TemplateError(Exception): pass
class WrongToken(Exception): pass
# variables names (we do not want to override user variables and vise versa)
TREE_BUILDER = '__MINT_TREE_BUILDER__'
TREE_FACTORY = '__MINT_TREE_FACTORY__'
MAIN_FUNCTION = '__MINT_MAIN__'
TAG_START = '__MINT_TAG_START__'
TAG_END = '__MINT_TAG_END__'
DATA = '__MINT_DATA__'
ESCAPE_HELLPER = '__MINT_ESCAPE__'
CURRENT_NODE = '__MINT_CURRENT_NODE__'
##### MINT NODES
class Node(ast.AST):
def __repr__(self):
return '%s' % self.__class__.__name__
class MintTemplate(Node):
def __init__(self, body=None):
self.body = body or []
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.body==other.body
return False
def __repr__(self):
return '%s(body=%r)' % (self.__class__.__name__, self.body)
class BaseTemplate(Node):
def __init__(self, name):
self.name = name
def to_ast(self):
return self
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.name == other.name
return False
class TextNode(Node):
def __init__(self, text, lineno=None, col_offset=None):
self.text = text
self.lineno = lineno
self.col_offset = col_offset
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.text==other.text and self.lineno==other.lineno \
and self.col_offset==other.col_offset
return False
def __repr__(self):
return '%s(%r, lineno=%d, col_offset=%d)' % (self.__class__.__name__, self.text,
self.lineno, self.col_offset)
class ExpressionNode(Node):
def __init__(self, text, lineno=None, col_offset=None):
self.text = text.strip()
self.lineno = lineno
self.col_offset = col_offset
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.text==other.text and self.lineno==other.lineno \
and self.col_offset==other.col_offset
return False
def __repr__(self):
return '%s(%r, lineno=%d, col_offset=%d)' % (self.__class__.__name__, self.text,
self.lineno, self.col_offset)
class TagAttrNode(Node):
def __init__(self, name, value=None, lineno=None, col_offset=None):
self.name = escape(name, ctx='attr')
self.value = value or []
self.lineno = lineno
self.col_offset = col_offset
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.name==other.name and self.value==other.value and self.lineno==other.lineno \
and self.col_offset==other.col_offset
return False
def __repr__(self):
return '%s(%r, value=%r, lineno=%d, col_offset=%d)' % (self.__class__.__name__, self.name,
self.value, self.lineno, self.col_offset)
class SetAttrNode(Node):
def __init__(self, attr_node):
self.attr = attr_node
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.attr==other.attr
return False
class AppendAttrNode(Node):
def __init__(self, attr_node):
self.attr = attr_node
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.attr==other.attr
return False
class TagNode(Node):
def __init__(self, name, attrs=None, body=None, lineno=None, col_offset=None):
self.name = name
self.attrs = attrs or []
self.body = body or []
self.lineno = lineno
self.col_offset = col_offset
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.name==other.name and self.body==other.body and self.attrs==other.attrs\
and self.lineno==other.lineno and self.col_offset==other.col_offset
return False
def __repr__(self):
return '%s(%r, attrs=%r, body=%r, lineno=%d, col_offset=%d)' % (self.__class__.__name__, self.name,
self.attrs, self.body, self.lineno, self.col_offset)
class ForStmtNode(Node):
def __init__(self, text, body=None, lineno=None, col_offset=None):
self.text = text.strip()
self.body = body or []
self.lineno = lineno
self.col_offset = col_offset
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.text==other.text and self.body==other.body and self.lineno==other.lineno \
and self.col_offset==other.col_offset
return False
def __repr__(self):
return '%s(%r, body=%r, lineno=%d, col_offset=%d)' % (self.__class__.__name__, self.text,
self.body, self.lineno, self.col_offset)
class IfStmtNode(Node):
def __init__(self, text, body=None, orelse=None, lineno=None, col_offset=None):
self.text = text
self.body = body or []
self.orelse = orelse or []
self.lineno = lineno
self.col_offset = col_offset
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.text==other.text and self.body==other.body and self.orelse==other.orelse\
and self.lineno==other.lineno and self.col_offset==other.col_offset
return False
def __repr__(self):
return '%s(%r, body=%r, orelse=%r, lineno=%d, col_offset=%d)' % (self.__class__.__name__,
self.text, self.body,
self.orelse, self.lineno, self.col_offset)
class ElseStmtNode(Node):
def __init__(self, body=None, lineno=None, col_offset=None):
self.body = body or []
self.lineno = lineno
self.col_offset = col_offset
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.body==other.body and self.lineno==other.lineno \
and self.col_offset==other.col_offset
return False
def __repr__(self):
return '%s(body=%r, lineno=%d, col_offset=%d)' % (self.__class__.__name__, self.body,
self.lineno, self.col_offset)
class SlotDefNode(Node):
def __init__(self, text, body=None, lineno=None, col_offset=None):
self.text = text.strip()
self.body = body or []
self.lineno = lineno
self.col_offset = col_offset
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.text==other.text and self.body==other.body and self.lineno==other.lineno \
and self.col_offset==other.col_offset
return False
def __repr__(self):
return '%s(%r, body=%r, lineno=%d, col_offset=%d)' % (self.__class__.__name__, self.text,
self.body, self.lineno, self.col_offset)
class SlotCallNode(Node):
def __init__(self, text, lineno=None, col_offset=None):
self.text = text.strip()
self.lineno = lineno
self.col_offset = col_offset
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.text==other.text and self.lineno==other.lineno \
and self.col_offset==other.col_offset
return False
def __repr__(self):
return '%s(%r, lineno=%d, col_offset=%d)' % (self.__class__.__name__, self.text,
self.lineno, self.col_offset)
##### NODES END
##### PARSER
class RecursiveStack(object):
'Stack of stacks'
def __init__(self):
self.stacks = [[]]
@property
def stack(self):
return self.stacks[-1]
@property
def current(self):
return self.stack and self.stack[-1] or None
def push(self, item):
self.stack.append(item)
return True
def pop(self):
return self.stack.pop()
return True
def push_stack(self, new_stack):
self.stacks.append(new_stack)
def pop_stack(self):
return self.stacks.pop()
def __nonzero__(self):
return len(self.stacks)
def __repr__(self):
return repr(self.stacks)
def __iter__(self):
return reversed(self.stack[:])
class Parser(object):
def __init__(self, states):
self.states = dict(states)
def parse(self, tokens_stream, stack):
current_state = 'start'
variantes = self.states[current_state]
for tok in tokens_stream:
token, tok_value, lineno, pos = tok
# accept new token
new_state = None
for item in variantes:
variante, state, callback = item
# tokens sequence
if isinstance(variante, basestring):
variante = globals().get(variante)
if isinstance(variante, (list, tuple)):
if token in variante:
new_state = state
break
elif variante is token:
new_state = state
break
elif isinstance(variante, Parser):
variante.parse(itertools.chain([tok], tokens_stream), stack)
new_state = state
#NOTE: tok still points to first token
if new_state is None:
raise WrongToken('[%s] Unexpected token "%s(%r)" at line %d, pos %d' \
% (current_state, token, tok_value, lineno, pos))
# process of new_state
elif new_state != current_state:
if new_state == 'end':
#print current_state, '%s(%r)' % (token, tok_value), new_state
callback(tok, stack)
#_print_stack(stack)
break
current_state = new_state
variantes = self.states[current_state]
# state callback
#print current_state, '%s(%r)' % (token, tok_value), new_state
callback(tok, stack)
#_print_stack(stack)
def _print_stack(s):
print '[stack]'
for i in s:
print ' '*4, i
print '[end of stack]\n'
# utils functions
def get_tokens(s):
my_tokens = []
while s.current and isinstance(s.current, (list, tuple)):
my_tokens.append(s.pop())
my_tokens.reverse()
return my_tokens
#NOTE: Callbacks are functions that takes token and stack
skip = lambda t, s: None
push = lambda t, s: s.push(t)
pop_stack = lambda t, s: s.pop_stack()
def push_stack(t, s):
if isinstance(s.current, ElseStmtNode):
stmt = s.pop()
s.push_stack(stmt.body)
elif isinstance(s.current, IfStmtNode) and s.current.orelse:
s.push_stack(s.current.orelse[-1].body)
else:
if not hasattr(s.current, 'body'):
raise SyntaxError('Unexpected indent at line %d' % t[2])
s.push_stack(s.current.body)
# text data and inline python expressions
def py_expr(t, s):
my_tokens = get_tokens(s)
lineno, col_offset = my_tokens[0][2], my_tokens[0][3] - 2
s.push(ExpressionNode(u''.join([t[1] for t in my_tokens]),
lineno=lineno, col_offset=col_offset))
def text_value(t, s):
my_tokens = get_tokens(s)
if my_tokens:
lineno, col_offset = my_tokens[0][2], my_tokens[0][3]
s.push(TextNode(u''.join([t[1] for t in my_tokens]),
lineno=lineno, col_offset=col_offset))
def text_value_with_last(t, s):
s.push(t)
text_value(t, s)
# parser of attribute value
attr_data_parser = Parser((
# state name
('start', (
# variantes (token, new_state, callback)
# ((token, token,...), new_state, callback)
# (other_parser, new_state, callback)
# ('other_parser', new_state, callback)
(TOKEN_EXPRESSION_START, 'expr', text_value),
(TOKEN_PARENTHESES_CLOSE, 'end', text_value),
(all_except(TOKEN_NEWLINE), 'start', push),
)),
('expr', (
(TOKEN_EXPRESSION_END, 'start', py_expr),
(all_tokens, 'expr', push),
)),
))
# parser of text data and inline python expressions
data_parser = Parser((
('start', (
(TOKEN_EXPRESSION_START, 'expr', text_value),
(TOKEN_NEWLINE, 'end', text_value_with_last),
(all_except(TOKEN_INDENT), 'start', push),
)),
('expr', (
(TOKEN_EXPRESSION_END, 'start', py_expr),
(all_tokens, 'expr', push),
)),
))
# tag and tag attributes callbacks
def tag_name(t, s):
#if isinstance(s.current, (list, tuple)):
my_tokens = get_tokens(s)
if my_tokens:
lineno, col_offset = my_tokens[0][2], my_tokens[0][3] - 1
s.push(TagNode(u''.join([t[1] for t in my_tokens]),
lineno=lineno, col_offset=col_offset))
def tag_attr_name(t, s):
my_tokens = get_tokens(s)
lineno, col_offset = my_tokens[0][2], my_tokens[0][3]
s.push(TagAttrNode(u''.join([t[1] for t in my_tokens]),
lineno=lineno, col_offset=col_offset))
def tag_attr_value(t, s):
nodes = []
while not isinstance(s.current, TagAttrNode):
nodes.append(s.pop())
attr = s.current
nodes.reverse()
attr.value = nodes
def set_attr(t, s):
nodes = []
while not isinstance(s.current, TagAttrNode):
nodes.append(s.pop())
attr = s.pop()
nodes.reverse()
attr.value = nodes
s.push(SetAttrNode(attr))
def append_attr(t, s):
nodes = []
while not isinstance(s.current, TagAttrNode):
nodes.append(s.pop())
attr = s.pop()
nodes.reverse()
attr.value = nodes
s.push(AppendAttrNode(attr))
def tag_node(t, s):
attrs = []
while isinstance(s.current, TagAttrNode):
attrs.append(s.pop())
tag = s.pop()
# if there were no attrs
if isinstance(tag, (list, tuple)):
my_tokens = get_tokens(s)
my_tokens.append(tag)
lineno, col_offset = my_tokens[0][2], my_tokens[0][3] - 1
tag = TagNode(u''.join([t[1] for t in my_tokens]),
lineno=lineno, col_offset=col_offset)
if attrs:
tag.attrs = attrs
s.push(tag)
def tag_node_with_data(t, s):
tag_node(t, s)
push_stack(t, s)
# tag parser
tag_parser = Parser((
('start', (
(TOKEN_TEXT, 'start', push),
(TOKEN_MINUS, 'start', push),
(TOKEN_COLON, 'start', push),
(TOKEN_DOT, 'attr', tag_name),
(TOKEN_WHITESPACE, 'continue', tag_node_with_data),
(TOKEN_NEWLINE, 'end', tag_node),
)),
('attr', (
(TOKEN_TEXT, 'attr', push),
(TOKEN_MINUS, 'attr', push),
(TOKEN_COLON, 'attr', push),
(TOKEN_PARENTHESES_OPEN, 'attr_value', tag_attr_name),
)),
('attr_value', (
(attr_data_parser, 'start', tag_attr_value),
)),
('continue', (
(TOKEN_TAG_START, 'nested_tag', skip),
(TOKEN_NEWLINE, 'end', pop_stack),
(data_parser, 'end', pop_stack),
)),
('nested_tag', (
('nested_tag_parser', 'end', pop_stack),
)),
))
# this is modified tag parser, supports inline tags with data
nested_tag_parser = Parser(dict(tag_parser.states, start=(
(TOKEN_TEXT, 'start', push),
(TOKEN_MINUS, 'start', push),
(TOKEN_COLON, 'start', push),
(TOKEN_DOT, 'attr', tag_name),
(TOKEN_WHITESPACE, 'continue', tag_node_with_data),
(TOKEN_NEWLINE, 'end', tag_node),
)
).iteritems())
# base parser callbacks
def base_template(t, s):
my_tokens = get_tokens(s)
lineno, col_offset = my_tokens[0][2], my_tokens[0][3]
s.push(BaseTemplate(u''.join([t[1] for t in my_tokens])))
def html_comment(t, s):
my_tokens = get_tokens(s)
lineno, col_offset = my_tokens[0][2], my_tokens[0][3]
s.push(TextNode(Markup(u'<!-- %s -->' % (u''.join([t[1] for t in my_tokens])).strip()),
lineno=lineno, col_offset=col_offset))
def for_stmt(t, s):
my_tokens = get_tokens(s)
lineno, col_offset = my_tokens[0][2], my_tokens[0][3]
s.push(ForStmtNode(u''.join([t[1] for t in my_tokens]),
lineno=lineno, col_offset=col_offset))
def if_stmt(t, s):
my_tokens = get_tokens(s)
lineno, col_offset = my_tokens[0][2], my_tokens[0][3]
s.push(IfStmtNode(u''.join([t[1] for t in my_tokens]),
lineno=lineno, col_offset=col_offset))
def elif_stmt(t, s):
if not isinstance(s.current, IfStmtNode):
pass
#XXX: raise TemplateError
my_tokens = get_tokens(s)
lineno, col_offset = my_tokens[0][2], my_tokens[0][3]
stmt = IfStmtNode(u''.join([t[1] for t in my_tokens]),
lineno=lineno, col_offset=col_offset)
s.current.orelse.append(stmt)
def else_stmt(t, s):
lineno, col_offset = t[2], t[3] - 6
if not isinstance(s.current, IfStmtNode):
pass
#XXX: raise TemplateError
stmt = ElseStmtNode(lineno=lineno, col_offset=col_offset)
# elif
if s.current.orelse:
s.current.orelse[-1].orelse.append(stmt)
# just else
else:
s.current.orelse.append(stmt)
s.push(stmt)
def slot_def(t, s):
my_tokens = get_tokens(s)
lineno, col_offset = my_tokens[0][2], my_tokens[0][3]
s.push(SlotDefNode(u''.join([t[1] for t in my_tokens]),
lineno=lineno, col_offset=col_offset))
def slot_call(t, s):
my_tokens = get_tokens(s)
lineno, col_offset = my_tokens[0][2], my_tokens[0][3]
s.push(SlotCallNode(u''.join([t[1] for t in my_tokens]),
lineno=lineno, col_offset=col_offset))
# base parser (MAIN PARSER)
block_parser = Parser((
# start is always the start of a new line
('start', (
(TOKEN_TEXT, 'text', push),
(TOKEN_EXPRESSION_START, 'expr', skip),
(TOKEN_TAG_ATTR_SET, 'set_attr', skip),
(TOKEN_TAG_ATTR_APPEND, 'append_attr', skip),
(TOKEN_TAG_START, 'tag', skip),
(TOKEN_STATEMENT_FOR, 'for_stmt', push),
(TOKEN_STATEMENT_IF, 'if_stmt', push),
(TOKEN_STATEMENT_ELIF, 'elif_stmt', push),
(TOKEN_STATEMENT_ELSE, 'else_stmt', skip),
(TOKEN_SLOT_DEF, 'slot_def', push),
(TOKEN_BASE_TEMPLATE, 'base', skip),
(TOKEN_STMT_CHAR, 'slot_call', skip),
(TOKEN_COMMENT, 'comment', skip),
(TOKEN_BACKSLASH, 'escaped_text', skip),
(TOKEN_INDENT, 'indent', push_stack),
(TOKEN_UNINDENT, 'start', pop_stack),
(TOKEN_NEWLINE, 'start', skip),
(TOKEN_EOF, 'end', skip),
(all_tokens, 'text', push),
)),
# to prevent multiple indentions in a row
('indent', (
(TOKEN_TEXT, 'text', push),
(TOKEN_EXPRESSION_START, 'expr', skip),
(TOKEN_TAG_ATTR_APPEND, 'append_attr', skip),
(TOKEN_TAG_ATTR_SET, 'set_attr', skip),
(TOKEN_TAG_START, 'tag', skip),
(TOKEN_STATEMENT_FOR, 'for_stmt', push),
(TOKEN_STATEMENT_IF, 'if_stmt', push),
(TOKEN_STATEMENT_ELIF, 'elif_stmt', push),
(TOKEN_STATEMENT_ELSE, 'else_stmt', skip),
(TOKEN_SLOT_DEF, 'slot_def', push),
(TOKEN_STMT_CHAR, 'slot_call', skip),
(TOKEN_COMMENT, 'comment', skip),
(TOKEN_BACKSLASH, 'escaped_text', skip),
(TOKEN_NEWLINE, 'start', skip),
(TOKEN_UNINDENT, 'start', pop_stack),
)),
('base', (
(TOKEN_NEWLINE, 'start', base_template),
(all_tokens, 'base', push),
)),
('text', (
(TOKEN_EXPRESSION_START, 'expr', text_value),
(TOKEN_NEWLINE, 'start', text_value_with_last),
(all_except(TOKEN_INDENT), 'text', push),
)),
('expr', (
(TOKEN_EXPRESSION_END, 'text', py_expr),
(all_tokens, 'expr', push),
)),
('escaped_text', (
(TOKEN_NEWLINE, 'start', text_value_with_last),
(all_except(TOKEN_INDENT), 'escaped_text', push),
)),
('tag', (
(tag_parser, 'start', skip),
)),
('comment', (
(TOKEN_NEWLINE, 'start', html_comment),
(all_tokens, 'comment', push),
)),
('set_attr', (
(TOKEN_TEXT, 'set_attr', push),
(TOKEN_MINUS, 'set_attr', push),
(TOKEN_COLON, 'set_attr', push),
(TOKEN_PARENTHESES_OPEN, 'set_attr_value', tag_attr_name),
)),
('set_attr_value', (
(attr_data_parser, 'start', set_attr),
)),
('append_attr', (
(TOKEN_TEXT, 'append_attr', push),
(TOKEN_MINUS, 'append_attr', push),
(TOKEN_COLON, 'append_attr', push),
(TOKEN_PARENTHESES_OPEN, 'append_attr_value', tag_attr_name),
)),
('append_attr_value', (
(attr_data_parser, 'start', append_attr),
)),
('for_stmt', (
(TOKEN_NEWLINE, 'start', for_stmt),
(all_tokens, 'for_stmt', push),
)),
('if_stmt', (
(TOKEN_NEWLINE, 'start', if_stmt),
(all_tokens, 'if_stmt', push),
)),
('elif_stmt', (
(TOKEN_NEWLINE, 'start', elif_stmt),
(all_tokens, 'elif_stmt', push),
)),
('else_stmt', (
(TOKEN_NEWLINE, 'start', else_stmt),
#(all_tokens, 'else_stmt', push),
)),
('slot_def', (
(TOKEN_NEWLINE, 'start', slot_def),
(all_tokens, 'slot_def', push),
)),
('slot_call', (
(TOKEN_NEWLINE, 'start', slot_call),
(all_tokens, 'slot_call', push),
)),
))
############# PARSER END
class AstWrapper(object):
def __init__(self, lineno, col_offset):
assert lineno is not None and col_offset is not None
self.lineno = lineno
self.col_offset = col_offset
def __getattr__(self, name):
attr = getattr(ast, name)
return partial(attr, lineno=self.lineno, col_offset=self.col_offset, ctx=Load())
class MintToPythonTransformer(ast.NodeTransformer):
def visit_MintTemplate(self, node):
ast_ = AstWrapper(1,1)
module = ast_.Module(body=[
ast_.FunctionDef(name=MAIN_FUNCTION,
body=[],
args=ast_.arguments(args=[], vararg=None, kwargs=None, defaults=[]),
decorator_list=[])])
body = module.body[0].body
for n in node.body:
result = self.visit(n)
if isinstance(result, (list, tuple)):
for i in result:
body.append(i)
else:
body.append(result)
return module
def visit_TextNode(self, node):
ast_ = AstWrapper(node.lineno, node.col_offset)
return ast_.Expr(value=ast_.Call(func=ast_.Name(id=DATA),