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 from collections import Iterable
32
33 from lepl.stream.simple import SequenceHelper, StringHelper, ListHelper
34 from lepl.stream.iter import IterableHelper, Cons
35 from lepl.support.lib import basestring, fmt, add_defaults, file
36 from lepl.lexer.stream import TokenHelper
37
38
40 '''
41 Given a value (typically a sequence), generate a stream.
42 '''
43
50
57
64
66 '''
67 Provide a stream for the contents of the iterable. This assumes that
68 each value from the iterable is a "line" which will, in turn, be
69 passed to the stream factory.
70 '''
71 add_defaults(kargs, {'factory': self})
72 cons = Cons(iterable)
73 return ((cons, self(cons.head, **kargs)), IterableHelper(**kargs))
74
76 '''
77 Provide a stream for the contents of the file. There is no
78 corresponding `from_path` because the opening and closing of the
79 path must be done outside the parsing (or the contents will become
80 unavailable), so use instead:
81 with open(path) as f:
82 parser.parse_file(f)
83 which will close the file after parsing.
84 '''
85 try:
86 gkargs = kargs.get('global_kargs', {})
87 add_defaults(gkargs, {'filename': file_.name})
88 add_defaults(kargs, {'global_kargs': gkargs})
89 except AttributeError:
90 pass
91 return self.from_iterable(file_, **kargs)
92
94 '''
95 Create a stream for tokens. The `iterable` is a source of
96 (token_ids, sub_stream) tuples, where `sub_stream` will be
97 matched within the token.
98 '''
99 return (Cons(iterable), TokenHelper(**kargs))
100
102 '''
103 Auto-detect type and wrap appropriately.
104 '''
105 if isinstance(sequence, basestring):
106 return self.from_string(sequence, **kargs)
107 elif isinstance(sequence, list):
108 return self.from_list(sequence, **kargs)
109 elif isinstance(sequence, file):
110 return self.from_file(sequence, **kargs)
111 elif hasattr(sequence, '__getitem__') and hasattr(sequence, '__len__'):
112 return self.from_sequence(sequence, **kargs)
113 elif isinstance(sequence, Iterable):
114 return self.from_iterable(sequence, **kargs)
115 else:
116 raise TypeError(fmt('Cannot generate a stream for type {0}',
117 type(sequence)))
118
119 DEFAULT_STREAM_FACTORY = StreamFactory()
120