-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
lexer.py
1628 lines (1410 loc) · 57.5 KB
/
lexer.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 -*-
"""Plim lexer"""
import functools
import re
from typing import Optional, Tuple, Any, Mapping, Callable, Iterator
import markdown2
from pyrsistent import v
from . import errors
from .util import StringIO, MAXSIZE, joined, space_separated, u
from .extensions import rst_to_html
from .extensions import coffee_to_js
from .extensions import scss_to_css
from .extensions import stylus_to_css
# Preface
# ============================================================================================
WHITESPACE = ' '
NEWLINE = '\n'
OPEN_BRACE = '('
CLOSE_BRACE = ')'
CSS_ID_SHORTCUT_DELIMITER = '#'
CSS_CLASS_SHORTCUT_DELIMITER = '.'
# used to separate tag attributes from its inline content and as a prefix of literal blocks
LITERAL_CONTENT_PREFIX = '|'
# Same as above but with the trailing whitespace
LITERAL_CONTENT_SPACE_PREFIX = ','
DYNAMIC_CONTENT_PREFIX = '='
DYNAMIC_CONTENT_SPACE_PREFIX = "=,"
DYNAMIC_ATTRIBUTES_PREFIX = '**'
# used to separate inline tags
INLINE_TAG_SEPARATOR = ':'
# used to separate attribute-value pairs from one another
ATTRIBUTES_DELIMITER = WHITESPACE
# used to separate attribute name from its value
# This is not the same as DYNAMIC_CONTENT_PREFIX
ATTRIBUTE_VALUE_DELIMITER = '='
# port of ruby's boolean methods:
# Ruby's Slim: selected=option_selected?("Slim")
# Python's Plim: selected=option_selected("Plim")?
BOOLEAN_ATTRIBUTE_MARKER = '?'
LINE_BREAK = '\\'
# Please note that in Plim all tag names are intentionally lower-cased
TAG_RULE = '(?P<html_tag>[a-z][a-z0-9-]*)'
TAG_RE = re.compile(TAG_RULE)
LINE_PARTS_RE = re.compile('(?P<indent>\s*)(?P<line>.*)\s*')
MAKO_FILTERS_TAIL_RE = re.compile('\|\s*(?P<filters>[a-zA-Z][_.a-zA-Z0-9]*(?:,\s*[a-zA-Z][_.a-zA-Z0-9]*)*)\s*$')
NUMERIC_VALUE_RE = re.compile(
# Order matters
# Can parse -NUM, +NUM, NUM, .NUM, NUM% and all its combinations
'(?P<value>(?:[-+]?[0-9]*\.[0-9]+|[-+]?[0-9]+%?))'
)
STATEMENT_CONVERT = {
'unless': 'if not (',
'until': 'while not ('
}
INLINE_PYTHON_TERMINATOR = '---'
CSS_ID_SHORTCUT_TERMINATORS = v(
CSS_CLASS_SHORTCUT_DELIMITER,
WHITESPACE,
OPEN_BRACE,
INLINE_TAG_SEPARATOR
)
CSS_CLASS_SHORTCUT_TERMINATORS = v(
CSS_CLASS_SHORTCUT_DELIMITER,
WHITESPACE,
OPEN_BRACE,
INLINE_TAG_SEPARATOR
)
ATTRIBUTE_TERMINATORS = v(
ATTRIBUTE_VALUE_DELIMITER,
ATTRIBUTES_DELIMITER,
INLINE_TAG_SEPARATOR,
LITERAL_CONTENT_PREFIX,
LITERAL_CONTENT_SPACE_PREFIX
)
ATTRIBUTE_TERMINATORS_WITH_PARENTHESES = v(
ATTRIBUTE_VALUE_DELIMITER,
ATTRIBUTES_DELIMITER,
CLOSE_BRACE
)
ATTRIBUTE_VALUE_TERMINATORS = v(
ATTRIBUTES_DELIMITER,
INLINE_TAG_SEPARATOR,
LITERAL_CONTENT_PREFIX,
LITERAL_CONTENT_SPACE_PREFIX,
DYNAMIC_CONTENT_PREFIX,
BOOLEAN_ATTRIBUTE_MARKER
)
ATTRIBUTE_VALUE_TERMINATORS_WITH_PARENTHESES = v(
ATTRIBUTES_DELIMITER,
INLINE_TAG_SEPARATOR,
LITERAL_CONTENT_PREFIX,
LITERAL_CONTENT_SPACE_PREFIX,
DYNAMIC_CONTENT_PREFIX,
BOOLEAN_ATTRIBUTE_MARKER,
CLOSE_BRACE,
NEWLINE
)
STATEMENT_TERMINATORS = {INLINE_TAG_SEPARATOR, NEWLINE}
PYTHON_EXPR_OPEN_BRACES_RE = re.compile('(?P<start_brace>\(|\{|\[).*')
PYTHON_EXPR_CLOSING_BRACES_RE = re.compile('\)|\}|\].*')
MAKO_EXPR_START_BRACE_RE = re.compile('(?P<start_brace>\$\{).*')
MAKO_EXPR_COUNT_OPEN_BRACES_RE = re.compile('\{')
MAKO_EXPR_COUNT_CLOSING_BRACES_RE = re.compile('\}')
QUOTES_RE = re.compile('(?P<quote_type>\'\'\'|"""|\'|").*') # order matters!
EMBEDDING_QUOTE = '`'
EMBEDDING_QUOTE_ESCAPE = EMBEDDING_QUOTE * 2
EMBEDDING_QUOTE_END = '`_'
EMBEDDING_QUOTES_RE = re.compile('(?P<quote_type>{quote_symbol}).*'.format(quote_symbol=EMBEDDING_QUOTE))
# ============================================================================================
# Okay, let's get started.
# There are three different types of functions below: searchers, parsers, and extractors.
# They are grouped together by API and task similarity.
#
# -- SEARCHERS are helper functions that try to figure out the next step of parsing process
# based on the current chunk of data.
# Each searcher MUST accept one required first positional argument *line*.
# ------------------------------
#
# -- PARSERS are the building blocks of Plim. They follow the strict API rules for both
# input and return values.
#
# Every parser MUST accept five input arguments:
# 1) ``indent_level`` - an indentation level of the current line. When the parser reaches a line
# which indentation is lower or equal to ``indent_level``, it returns control to a top-level function.
# 2) ``current_line`` - a line which is being parsed. This is the line that has been matched by
# ``matched`` object at the previous parsing step.
# 3) ``matched`` - an instance of ``re.MatchObject`` of the regex associated with the current parser.
# 4) ``source`` - an instance of an enumerated object returned by :func:`enumerate_source`.
# 5) ``syntax`` - an instance of one of :class:`plim.syntax.BaseSyntax` children.
#
# Every parser MUST return a 4-tuple of:
# 1) parsed_data - a string of successfully parsed data
# 2) tail_indent - an indentation level of the ``tail line``
# 3) tail_line - a line which indentation level (``tail_indent``) is lower or equal to
# the input ``indent_level``.
# 4) ``source`` - an instance of enumerated object returned by :func:`enumerate_source`
# which represents the remaining (untouched) plim markup.
# ------------------------------
#
# -- EXTRACTORS are "light" versions of parsers. Their input arguments
# and return values are task-specific. However, they still have several common features:
# - Each extractor has its own starting and termination sequences.
# - Each extractor tries to find the starting sequence of characters at the beginning
# of the input line. If that attempt fails, the extractor returns None (in most cases).
# If the attempt is successful, the extractor captures all the input characters up to
# the termination sequence.
# - The return value of the succeeded extractor MUST contain not only the extracted value,
# but also an instance of enumerated object returned by :func:`enumerate_source`.
# ------------------------------
#
# P.S. I intentionally did not use "for" statements in conjunction with iterators.
# I wanted to make all parsers free from implicit side-effects.
# Therefore, you can find a number of "while True" and "try/except StopIteration" constructs below.
# Searchers
# ==================================================================================
def search_quotes(line: str, escape_char: str = '\\', quotes_re = QUOTES_RE) -> Optional[int]:
"""
:param line: may be empty
:param escape_char:
"""
match = quotes_re.match(line)
if not match: return None
find_seq = match.group('quote_type')
find_seq_len = len(find_seq)
pos = find_seq_len
line_len = len(line)
while pos < line_len:
if line[pos] == escape_char:
pos += 2
continue
if line[pos:].startswith(find_seq):
return pos + find_seq_len
pos += 1
return None
def search_parser(lineno, line, syntax) -> Tuple[Any, Any]:
"""Finds a proper parser function for a given line or raises an error
:param lineno:
:param line:
:type syntax: :class:`plim.syntax.BaseSyntax`
"""
for template, parser in syntax.parsers:
matched = template.match(line)
if matched:
return matched, parser
raise errors.ParserNotFound(lineno, line)
# Extractors
# ==================================================================================
def extract_embedding_quotes(content) -> Optional[Tuple[Any, Any, Any]]:
"""
``content`` may be empty
:param content:
:param escape_seq:
"""
match = EMBEDDING_QUOTES_RE.match(content)
if not match:
return None
original_string = [EMBEDDING_QUOTE]
embedded_string = []
tail = content[1:]
while tail:
if tail.startswith(EMBEDDING_QUOTE_ESCAPE):
original_string.append(EMBEDDING_QUOTE_ESCAPE)
embedded_string.append(EMBEDDING_QUOTE)
tail = tail[len(EMBEDDING_QUOTE_ESCAPE):]
continue
if tail.startswith(EMBEDDING_QUOTE):
append_seq = EMBEDDING_QUOTE_END if tail.startswith(EMBEDDING_QUOTE_END) else EMBEDDING_QUOTE
original_string.append(append_seq)
original_string_str = joined(original_string)
content = content[len(original_string_str):]
embedded_string_str = joined(embedded_string)
return embedded_string_str, original_string_str, content
current_char = tail[0]
original_string.append(current_char)
embedded_string.append(current_char)
tail = tail[1:]
original_string_str = joined(original_string)
pos = len(original_string_str)
raise errors.PlimSyntaxError(u('Embedding quote is not closed: "{}"').format(original_string_str), pos)
def _extract_braces_expression(
line: str, source: Iterator[Tuple[Any, str]], starting_braces_re, open_braces_re, closing_braces_re
) -> Optional[Tuple[Any, Any, Any]]:
"""
:param line: may be empty
:param source:
:param starting_braces_re:
:param open_braces_re:
:param closing_braces_re:
"""
match = starting_braces_re.match(line)
if not match:
return None
open_brace = match.group('start_brace')
buf = [open_brace]
tail = line[len(open_brace):]
braces_counter = 1
while True:
if not tail:
_, tail = next(source)
tail = tail.lstrip()
while tail:
current_char = tail[0]
if closing_braces_re.match(current_char):
braces_counter -= 1
buf.append(current_char)
if braces_counter:
tail = tail[1:]
continue
return joined(buf), tail[1:], source
if current_char == NEWLINE:
_, tail = next(source)
tail = tail.lstrip()
continue
if open_braces_re.match(current_char):
braces_counter += 1
buf.append(current_char)
tail = tail[1:]
continue
result = search_quotes(tail)
if result is not None:
buf.append(tail[:result])
tail = tail[result:]
continue
buf.append(current_char)
tail = tail[1:]
extract_braces = lambda line, source: _extract_braces_expression(line, source,
PYTHON_EXPR_OPEN_BRACES_RE,
PYTHON_EXPR_OPEN_BRACES_RE,
PYTHON_EXPR_CLOSING_BRACES_RE
)
extract_mako_expression = lambda line, source: _extract_braces_expression(line, source,
MAKO_EXPR_START_BRACE_RE,
MAKO_EXPR_COUNT_OPEN_BRACES_RE,
MAKO_EXPR_COUNT_CLOSING_BRACES_RE
)
def extract_identifier(line, source, identifier_start='#', terminators=('.', ' ', CLOSE_BRACE, INLINE_TAG_SEPARATOR)):
"""
:param line: Current line. It may be empty.
:type line: str or unicode
:param source:
:type source: str
:param identifier_start:
:param terminators:
:type terminators: tuple or set
"""
if not line or not line.startswith(identifier_start):
return None
pos = len(identifier_start)
buf = [identifier_start]
tail = line[pos:]
while tail:
for terminator in terminators:
if tail.startswith(terminator):
return joined(buf).rstrip(), tail, source
# Let's try to find "mako variable" part of possible css-identifier
result = extract_mako_expression(tail, source)
if result:
expr, tail, source = result
buf.append(expr)
continue
# Check for a string object
result_pos = search_quotes(tail)
if result_pos is not None:
buf.append(tail[:result_pos])
tail = tail[result_pos:]
continue
# Try to search braces of function calls etc
result = extract_braces(tail, source)
if result:
result, tail, source = result
buf.append(result)
continue
current_char = tail[0]
buf.append(current_char)
tail = tail[1:]
return joined(buf).rstrip(), tail, source
def extract_digital_attr_value(line):
result = NUMERIC_VALUE_RE.match(line)
if result:
return result.group('value'), line[result.end():]
return None
def extract_quoted_attr_value(line, search_quotes=search_quotes, remove_escape_seq=True):
"""
:param line:
:param search_quotes:
:param remove_escape_seq: Sometimes escape sequences have to be removed outside of the extractor.
This flag prevents double-escaping of backslash sequences.
:return:
"""
result = search_quotes(line)
if result:
if line.startswith('"""') or line.startswith("'''"):
skip = 3
else:
skip = 1
# remove quotes from value
value = line[skip:result - skip]
# We have to remove backslash escape sequences from the value, but
# at the same time, preserve unicode escape sequences like "\u4e2d\u6587".
if remove_escape_seq:
value = value.encode('raw_unicode_escape')
value = value.decode('unicode_escape')
return value, line[result:]
return None
def extract_dynamic_attr_value(line, source, terminators, syntax):
result = extract_identifier(line, source, '', terminators)
if result is None:
return None
result, tail, source = result
if MAKO_EXPR_START_BRACE_RE.match(line):
# remove VARIABLE_PLACEHOLDER_START_SEQUENCE and VARIABLE_PLACEHOLDER_END_SEQUENCE from variable
value = result[len(syntax.VARIABLE_PLACEHOLDER_START_SEQUENCE):-len(syntax.VARIABLE_PLACEHOLDER_END_SEQUENCE)]
elif line.startswith(OPEN_BRACE):
# remove "(" and ")" from variable
value = result[1:-1]
else:
value = result
return value, tail, source
def extract_dynamic_tag_attributes(line: str, source: str, syntax, inside_parentheses=False) -> Optional[Tuple[Any, Any, Any]]:
"""
Extract one occurrence of ``**dynamic_attributes``
:param line:
:param source:
:param inside_parentheses:
"""
if not line.startswith(DYNAMIC_ATTRIBUTES_PREFIX):
return None
line = line[len(DYNAMIC_ATTRIBUTES_PREFIX):]
terminators = {
WHITESPACE,
NEWLINE,
LITERAL_CONTENT_PREFIX,
LITERAL_CONTENT_SPACE_PREFIX,
# we want to terminate extract_identifier() by DYNAMIC_ATTRIBUTES_PREFIX,
# but it contains two characters, whereas the function checks only one character.
# Therefore, we use a single asterisk terminator here instead of DYNAMIC_ATTRIBUTES_PREFIX.
'*',
INLINE_TAG_SEPARATOR,
LINE_BREAK
}
if inside_parentheses:
terminators.add(CLOSE_BRACE)
result = extract_identifier(line, source, '', terminators)
if result is None:
return None
expr, tail, source = result
attributes = u(
'\n%for __plim_key__, __plim_value__ in {expr}.items():\n'
'{var_start}__plim_key__{var_end}="{var_start}__plim_value__{var_end}"\n'
'%endfor\n'
).format(
expr=expr,
var_start=syntax.VARIABLE_PLACEHOLDER_START_SEQUENCE,
var_end=syntax.VARIABLE_PLACEHOLDER_END_SEQUENCE
)
return attributes, tail, source
def extract_tag_attribute(line: str, source: str, syntax, inside_parentheses=False):
"""
:param line:
:param source:
:param inside_parentheses:
:return:
"""
terminators = inside_parentheses and ATTRIBUTE_TERMINATORS_WITH_PARENTHESES or ATTRIBUTE_TERMINATORS
result = extract_identifier(line, source, '', terminators)
if result and result[0]:
result, tail, source = result
attr_name = result
if tail.startswith(ATTRIBUTE_VALUE_DELIMITER):
# value is presented in a form of
# =${dynamic_value} or =dynamic_value or ="value with spaces"
# ------------------------------------------------------------------
# remove ATTRIBUTE_VALUE_DELIMITER
tail = tail[1:]
# 1. Try to parse quoted literal value
# -------------------------------------
result = extract_quoted_attr_value(tail)
if result:
value, tail = result
# remove possible newline character
value = value.rstrip()
return u('{attr_name}="{value}"').format(attr_name=attr_name, value=value), tail, source
# 2. Try to parse digital value
# -------------------------------------
result = extract_digital_attr_value(tail)
if result:
value, tail = result
return u('{attr_name}="{value}"').format(attr_name=attr_name, value=value), tail, source
# 3. Try to parse dynamic value
# -------------------------------------
terminators = inside_parentheses and ATTRIBUTE_VALUE_TERMINATORS_WITH_PARENTHESES or ATTRIBUTE_VALUE_TERMINATORS
result = extract_dynamic_attr_value(tail, source, terminators, syntax)
if result:
value, tail, source = result
# remove possible newline character
value = value.rstrip()
if tail.startswith(BOOLEAN_ATTRIBUTE_MARKER):
# selected=dynamic_variable?
value = u("""{start_var}({value}) and '{attr_name}="{attr_name}"' or ''|n{end_var}""").format(
value=value,
attr_name=attr_name,
start_var=syntax.VARIABLE_PLACEHOLDER_START_SEQUENCE,
end_var=syntax.VARIABLE_PLACEHOLDER_END_SEQUENCE
)
attribute = value
tail = tail[1:]
else:
attribute = u('{attr_name}="{start_var}{value}{end_var}"').format(
attr_name=attr_name,
value=value,
start_var=syntax.VARIABLE_PLACEHOLDER_START_SEQUENCE,
end_var=syntax.VARIABLE_PLACEHOLDER_END_SEQUENCE
)
return attribute, tail, source
return None
elif inside_parentheses and tail.startswith(ATTRIBUTES_DELIMITER) or tail.startswith(CLOSE_BRACE):
# attribute is presented in a form of boolean attribute
# which should be converted to attr="attr"
return u('{attr_name}="{attr_name}"').format(attr_name=attr_name), tail, source
else:
return None
return None
def extract_line_break(tail, source):
"""
Checks the first character of the tail.
:param tail:
:param source:
:return:
"""
found = False
while True:
if tail.startswith(LINE_BREAK):
found = True
try:
_, tail = next(source)
except StopIteration:
return found, '', source
tail = tail.lstrip()
continue
break
return found, tail, source
def extract_statement_expression(tail, source):
"""
:param tail:
:param source:
:return:
"""
buf = []
# Ensure that tail ends with a newline character
# (required by extract_braces() to properly handle multi-line expressions)
tail = tail.strip() + '\n'
while tail:
# Try to search braces of function calls etc
found, tail, source = extract_line_break(tail, source)
if found:
buf.append(' ')
result = extract_braces(tail, source)
if result:
head, tail, source = result
buf.append(head)
continue
buf.append(tail[0])
tail = tail[1:]
return joined(buf).strip(), source
def extract_tag_line(line, source, syntax):
"""
Returns a 3-tuple of inline tags sequence, closing tags sequence, and a dictionary of
last tag components (name, attributes, content)
:param line:
:type line: str
:param source:
:type source: enumerate
:param parsers: 2-tuple of (parser_regex, parser_callable)
:type parsers: tuple
"""
buf = []
close_buf = []
components = {}
tail = line
while tail:
tag_composer = ['<']
# Get tag name
match = TAG_RE.match(tail)
if match:
html_tag = match.group('html_tag').lower()
tail = tail[match.end():]
else:
html_tag = 'div'
tag_composer.append(html_tag)
components['name'] = html_tag
# 1. Parse css id
# --------------------------------------------
result = extract_identifier(tail, source, CSS_ID_SHORTCUT_DELIMITER, CSS_ID_SHORTCUT_TERMINATORS)
if result is None:
css_id = ''
else:
result, tail, source = result
# remove the preceding '#' character
css_id = result[1:].rstrip()
# 2. Parse css class shortcut
# --------------------------------------------
class_identifiers = []
while True:
result = extract_identifier(tail, source, CSS_CLASS_SHORTCUT_DELIMITER, CSS_CLASS_SHORTCUT_TERMINATORS)
if result:
result, tail, source = result
# remove the preceding '.' character
class_identifiers.append(result[1:].rstrip())
continue
break
# 3. Parse tag attributes
# -----------------------------------
_, tail, source = extract_line_break(tail.lstrip(), source)
inside_parentheses = tail.startswith(OPEN_BRACE)
if inside_parentheses:
tail = tail[1:].lstrip()
attributes = []
while True:
_, tail, source = extract_line_break(tail.lstrip(), source)
# 3.1 try to get and unpack dynamic attributes
result = extract_dynamic_tag_attributes(tail, source, syntax, inside_parentheses)
if result:
dynamic_attrs, tail, source = result
attributes.append(dynamic_attrs)
continue
# 3.2. get attribute-value pairs until the end of the section (indicated by terminators)
result = extract_tag_attribute(tail, source, syntax, inside_parentheses)
if result:
attribute_pair, tail, source = result
if attribute_pair.startswith('id="') and css_id:
raise errors.PlimSyntaxError('Your template has two "id" attribute definitions', line)
if attribute_pair.startswith('class="'):
# len('class="') == 7
class_identifiers.append(attribute_pair[7:-1])
continue
attributes.append(attribute_pair)
continue
else:
if inside_parentheses and not tail:
# We have reached the end of the line.
# Try to parse multiline attributes list.
lineno, tail = next(source)
continue
if css_id:
attributes.append(u('id="{ids}"').format(ids=css_id))
if class_identifiers:
class_identifiers_str = space_separated(class_identifiers)
attributes.append(u('class="{classes}"').format(classes=class_identifiers_str))
break
attributes_str = space_separated(attributes)
components['attributes'] = attributes_str
if attributes_str:
tag_composer.extend([' ', attributes_str])
# 3.2 syntax check
if inside_parentheses:
if tail.startswith(CLOSE_BRACE):
# We have reached the end of attributes definition
tail = tail[1:].lstrip()
else:
raise errors.PlimSyntaxError("Unexpected end of line", tail)
else:
if tail.startswith(' '):
tail = tail.lstrip()
if html_tag in EMPTY_TAGS:
tag_composer.append('/>')
else:
tag_composer.append('>')
close_buf.append(u('</{tag}>').format(tag=html_tag))
buf.append(joined(tag_composer))
if tail.startswith(INLINE_TAG_SEPARATOR):
tail = tail[1:].lstrip()
break
# 3.3 The remainder of the line will be treated as content
# ------------------------------------------------------------------
components['content'] = ''
if tail:
if tail.startswith(DYNAMIC_CONTENT_PREFIX):
tail = tail[1:]
if tail.startswith(DYNAMIC_CONTENT_PREFIX):
# case for the '==' prefix
tail = _inject_n_filter(tail)
if tail.startswith(DYNAMIC_CONTENT_SPACE_PREFIX):
# ensure that a single whitespace is appended
tail, source = extract_statement_expression(tail[2:], source)
buf.append(u("{start_var}{content}{end_var} ").format(
content=tail,
start_var=syntax.VARIABLE_PLACEHOLDER_START_SEQUENCE,
end_var=syntax.VARIABLE_PLACEHOLDER_END_SEQUENCE
))
else:
tail, source = extract_statement_expression(tail[1:], source)
buf.append(u("{start_var}{content}{end_var}").format(
content=tail,
start_var=syntax.VARIABLE_PLACEHOLDER_START_SEQUENCE,
end_var=syntax.VARIABLE_PLACEHOLDER_END_SEQUENCE
))
else:
if tail.startswith(LITERAL_CONTENT_SPACE_PREFIX):
# ensure that a single whitespace is appended
tail, source = extract_statement_expression(tail[1:], source)
buf.append(u("{start_var}{content}{end_var} ").format(
content=tail,
start_var=syntax.VARIABLE_PLACEHOLDER_START_SEQUENCE,
end_var=syntax.VARIABLE_PLACEHOLDER_END_SEQUENCE
))
else:
tail, source = extract_statement_expression(tail, source)
buf.append(u("{start_var}{content}{end_var}").format(
content=tail,
start_var=syntax.VARIABLE_PLACEHOLDER_START_SEQUENCE,
end_var=syntax.VARIABLE_PLACEHOLDER_END_SEQUENCE
))
elif tail.startswith(LITERAL_CONTENT_PREFIX):
tail = _parse_embedded_markup(tail[1:].strip(), syntax)
buf.append(tail)
elif tail.startswith(LITERAL_CONTENT_SPACE_PREFIX):
tail = _parse_embedded_markup(tail[1:].strip(), syntax)
buf.append(u("{content} ").format(content=tail))
else:
tail = _parse_embedded_markup(tail.strip(), syntax)
buf.append(tail)
components['content'] = buf[-1]
tail = ''
return joined(buf), joined(reversed(close_buf)), components, tail, source
# Parsers
# ==================================================================================
def parse_style_script(indent_level, current_line, matched, source, syntax):
"""
:param indent_level:
:param current_line:
:type current_line: str
:param matched:
:param source:
:param syntax: an instance of one of :class:`plim.syntax.BaseSyntax` children.
:type syntax: :class:`plim.syntax.BaseSyntax`
:return:
"""
extracted_html_line, close_buf, _, tail, source = extract_tag_line(current_line, source, syntax)
buf = [extracted_html_line, '\n']
parsed_data, tail_indent, tail_line, source = parse_explicit_literal_no_embedded(
indent_level,
LITERAL_CONTENT_PREFIX,
matched,
source,
syntax
)
buf.extend([parsed_data, close_buf])
return joined(buf), tail_indent, tail_line, source
def parse_doctype(indent_level, current_line, ___, source, syntax):
"""
:param indent_level:
:param current_line:
:param ___:
:param source:
:param syntax: an instance of one of :class:`plim.syntax.BaseSyntax` children.
:type syntax: :class:`plim.syntax.BaseSyntax`
:return:
"""
match = syntax.PARSE_DOCTYPE_RE.match(current_line.strip())
doctype = match.group('type')
return DOCTYPES.get(doctype, DOCTYPES['5']), indent_level, '', source
def parse_handlebars(indent_level, current_line, ___, source, syntax):
"""
:param indent_level:
:param current_line:
:param ___:
:param source:
:param syntax: an instance of one of :class:`plim.syntax.BaseSyntax` children.
:type syntax: :class:`plim.syntax.BaseSyntax`
:return:
"""
processed_tag, tail_indent, tail_line, source = parse_tag_tree(indent_level, current_line, ___, source, syntax)
assert processed_tag.startswith("<handlebars") and processed_tag.endswith("</handlebars>")
# We don't want to use str.replace() here, therefore
# len("<handlebars") == len("handlebars>") == 11
processed_tag = u(
'<script type="text/x-handlebars"{content}script>'
).format(
content=processed_tag[11:-11]
)
return processed_tag, tail_indent, tail_line, source
def parse_tag_tree(indent_level, current_line, ___, source, syntax):
"""
:param indent_level:
:param current_line:
:param ___:
:param source:
:param syntax: an instance of one of :class:`plim.syntax.BaseSyntax` children.
:type syntax: :class:`plim.syntax.BaseSyntax`
:return: 4-tuple
"""
buf = []
close_buf = []
current_line = current_line.strip()
html_tag, close_seq, _, tail, source = extract_tag_line(current_line, source, syntax)
buf.append(html_tag)
close_buf.append(close_seq)
if tail:
parsed, tail_indent, tail_line, source = parse_plim_tail(0, indent_level, tail, source, syntax)
# at this point we have tail_indent <= indent_level
buf.extend(parsed)
buf.append(joined(close_buf))
return joined(buf), tail_indent, tail_line, source
while True:
try:
lineno, current_line = next(source)
except StopIteration:
break
tail_indent, tail_line = scan_line(current_line)
if not tail_line:
continue
if tail_indent <= indent_level:
buf.append(joined(close_buf))
return joined(buf), tail_indent, tail_line, source
# ----------------------------------------------------------
while tail_line:
matched_obj, parse = search_parser(lineno, tail_line, syntax)
parsed_data, tail_indent, tail_line, source = parse(tail_indent, tail_line, matched_obj, source, syntax)
buf.append(parsed_data)
if tail_indent <= indent_level:
buf.append(joined(close_buf))
return joined(buf), tail_indent, tail_line, source
buf.append(joined(close_buf))
return joined(buf), 0, '', source
def parse_markup_languages(indent_level, __, matched, source, syntax):
"""
:param indent_level:
:param __:
:param matched:
:param source:
:param syntax: an instance of one of :class:`plim.syntax.BaseSyntax` children.
:type syntax: :class:`plim.syntax.BaseSyntax`
:return:
"""
markup_parser = MARKUP_LANGUAGES[matched.group('lang')]
parsed_data, tail_indent, tail_line, source = parse_explicit_literal_no_embedded(
indent_level,
LITERAL_CONTENT_PREFIX,
matched,
source,
syntax
)
# This is slow but correct.
# Trying to remove redundant indentation
parsed_data = markup_parser(parsed_data)
return parsed_data.strip(), tail_indent, tail_line, source
def parse_python(indent_level, __, matched, source, syntax):
"""
:param indent_level:
:param __:
:param matched:
:param source:
:param syntax: an instance of one of :class:`plim.syntax.BaseSyntax` children.
:type syntax: :class:`plim.syntax.BaseSyntax`
:return:
"""
# TODO: merge with parse_mako_text()
if matched.group('python').endswith('!'):
buf = ['<%!\n']
else:
buf = ['<%\n']
inline_statement = matched.group('expr')
if inline_statement:
buf.extend([inline_statement.strip(), '\n'])
parsed_data, tail_indent, tail_line, source = parse_explicit_literal_no_embedded(
indent_level,
LITERAL_CONTENT_PREFIX,
matched,
source,
syntax
)
# do not render a python block if it's empty
if not inline_statement and not parsed_data:
return u(''), tail_indent, tail_line, source
buf.extend([u('{literal}\n').format(literal=parsed_data.rstrip()), '%>\n'])
return joined(buf), tail_indent, tail_line, source
def parse_python_new_style(indent_level, __, matched, source, syntax):
"""
:param indent_level:
:param __:
:param matched:
:param source:
:param syntax: an instance of one of :class:`plim.syntax.BaseSyntax` children.
:type syntax: :class:`plim.syntax.BaseSyntax`
:return:
"""
buf = [matched.group('excl') and '-py! ' or '-py ']
inline_statement = matched.group('expr')
if inline_statement:
inline_statement, _tail_line_, source = extract_identifier(inline_statement, source, '', {INLINE_PYTHON_TERMINATOR, NEWLINE})
buf.append(inline_statement)
converted_line = joined(buf).strip()
match = syntax.PARSE_PYTHON_CLASSIC_RE.match(converted_line)
return parse_python(indent_level, __, match, source, syntax)
def parse_mako_text(indent, __, matched, source, syntax):
"""
:param indent:
:param __:
:param matched:
:param syntax: an instance of one of :class:`plim.syntax.BaseSyntax` children.
:type syntax: :class:`plim.syntax.BaseSyntax`
:return:
"""
_, __, components, tail, source = extract_tag_line(matched.group('line').strip(), source, syntax)
buf = ['\n<%text']
if components['attributes']:
buf.extend([' ', components['attributes']])
buf.append('>\n')
if components['content']:
buf.extend([components['content'], '\n'])
parsed_data, tail_indent, tail_line, source = parse_explicit_literal_no_embedded(
indent,
LITERAL_CONTENT_PREFIX,
matched,
source,
syntax
)
if parsed_data:
buf.append(u('{literal}\n').format(literal=parsed_data.rstrip()))
buf.append('</%text>\n')
return joined(buf), tail_indent, tail_line, source
def parse_call(indent_level, current_line, matched, source, syntax):
"""
:param indent_level:
:param current_line:
:param matched: