[lit] Use more modern syntax for constructing exceptions.
[oota-llvm.git] / utils / lit / lit / ShUtil.py
1 import itertools
2
3 import Util
4 from ShCommands import Command, Pipeline, Seq
5
6 class ShLexer:
7     def __init__(self, data, win32Escapes = False):
8         self.data = data
9         self.pos = 0
10         self.end = len(data)
11         self.win32Escapes = win32Escapes
12
13     def eat(self):
14         c = self.data[self.pos]
15         self.pos += 1
16         return c
17
18     def look(self):
19         return self.data[self.pos]
20
21     def maybe_eat(self, c):
22         """
23         maybe_eat(c) - Consume the character c if it is the next character,
24         returning True if a character was consumed. """
25         if self.data[self.pos] == c:
26             self.pos += 1
27             return True
28         return False
29
30     def lex_arg_fast(self, c):
31         # Get the leading whitespace free section.
32         chunk = self.data[self.pos - 1:].split(None, 1)[0]
33         
34         # If it has special characters, the fast path failed.
35         if ('|' in chunk or '&' in chunk or 
36             '<' in chunk or '>' in chunk or
37             "'" in chunk or '"' in chunk or
38             ';' in chunk or '\\' in chunk):
39             return None
40         
41         self.pos = self.pos - 1 + len(chunk)
42         return chunk
43         
44     def lex_arg_slow(self, c):
45         if c in "'\"":
46             str = self.lex_arg_quoted(c)
47         else:
48             str = c
49         while self.pos != self.end:
50             c = self.look()
51             if c.isspace() or c in "|&;":
52                 break
53             elif c in '><':
54                 # This is an annoying case; we treat '2>' as a single token so
55                 # we don't have to track whitespace tokens.
56
57                 # If the parse string isn't an integer, do the usual thing.
58                 if not str.isdigit():
59                     break
60
61                 # Otherwise, lex the operator and convert to a redirection
62                 # token.
63                 num = int(str)
64                 tok = self.lex_one_token()
65                 assert isinstance(tok, tuple) and len(tok) == 1
66                 return (tok[0], num)                    
67             elif c == '"':
68                 self.eat()
69                 str += self.lex_arg_quoted('"')
70             elif c == "'":
71                 self.eat()
72                 str += self.lex_arg_quoted("'")
73             elif not self.win32Escapes and c == '\\':
74                 # Outside of a string, '\\' escapes everything.
75                 self.eat()
76                 if self.pos == self.end:
77                     Util.warning("escape at end of quoted argument in: %r" % 
78                                  self.data)
79                     return str
80                 str += self.eat()
81             else:
82                 str += self.eat()
83         return str
84
85     def lex_arg_quoted(self, delim):
86         str = ''
87         while self.pos != self.end:
88             c = self.eat()
89             if c == delim:
90                 return str
91             elif c == '\\' and delim == '"':
92                 # Inside a '"' quoted string, '\\' only escapes the quote
93                 # character and backslash, otherwise it is preserved.
94                 if self.pos == self.end:
95                     Util.warning("escape at end of quoted argument in: %r" % 
96                                  self.data)
97                     return str
98                 c = self.eat()
99                 if c == '"': # 
100                     str += '"'
101                 elif c == '\\':
102                     str += '\\'
103                 else:
104                     str += '\\' + c
105             else:
106                 str += c
107         Util.warning("missing quote character in %r" % self.data)
108         return str
109     
110     def lex_arg_checked(self, c):
111         pos = self.pos
112         res = self.lex_arg_fast(c)
113         end = self.pos
114
115         self.pos = pos
116         reference = self.lex_arg_slow(c)
117         if res is not None:
118             if res != reference:
119                 raise ValueError("Fast path failure: %r != %r" % (
120                         res, reference))
121             if self.pos != end:
122                 raise ValueError("Fast path failure: %r != %r" % (
123                         self.pos, end))
124         return reference
125         
126     def lex_arg(self, c):
127         return self.lex_arg_fast(c) or self.lex_arg_slow(c)
128         
129     def lex_one_token(self):
130         """
131         lex_one_token - Lex a single 'sh' token. """
132
133         c = self.eat()
134         if c == ';':
135             return (c,)
136         if c == '|':
137             if self.maybe_eat('|'):
138                 return ('||',)
139             return (c,)
140         if c == '&':
141             if self.maybe_eat('&'):
142                 return ('&&',)
143             if self.maybe_eat('>'): 
144                 return ('&>',)
145             return (c,)
146         if c == '>':
147             if self.maybe_eat('&'):
148                 return ('>&',)
149             if self.maybe_eat('>'):
150                 return ('>>',)
151             return (c,)
152         if c == '<':
153             if self.maybe_eat('&'):
154                 return ('<&',)
155             if self.maybe_eat('>'):
156                 return ('<<',)
157             return (c,)
158
159         return self.lex_arg(c)
160
161     def lex(self):
162         while self.pos != self.end:
163             if self.look().isspace():
164                 self.eat()
165             else:
166                 yield self.lex_one_token()
167
168 ###
169  
170 class ShParser:
171     def __init__(self, data, win32Escapes = False, pipefail = False):
172         self.data = data
173         self.pipefail = pipefail
174         self.tokens = ShLexer(data, win32Escapes = win32Escapes).lex()
175     
176     def lex(self):
177         try:
178             return self.tokens.next()
179         except StopIteration:
180             return None
181     
182     def look(self):
183         next = self.lex()
184         if next is not None:
185             self.tokens = itertools.chain([next], self.tokens)
186         return next
187     
188     def parse_command(self):
189         tok = self.lex()
190         if not tok:
191             raise ValueError("empty command!")
192         if isinstance(tok, tuple):
193             raise ValueError("syntax error near unexpected token %r" % tok[0])
194         
195         args = [tok]
196         redirects = []
197         while 1:
198             tok = self.look()
199
200             # EOF?
201             if tok is None:
202                 break
203
204             # If this is an argument, just add it to the current command.
205             if isinstance(tok, str):
206                 args.append(self.lex())
207                 continue
208
209             # Otherwise see if it is a terminator.
210             assert isinstance(tok, tuple)
211             if tok[0] in ('|',';','&','||','&&'):
212                 break
213             
214             # Otherwise it must be a redirection.
215             op = self.lex()
216             arg = self.lex()
217             if not arg:
218                 raise ValueError("syntax error near token %r" % op[0])
219             redirects.append((op, arg))
220
221         return Command(args, redirects)
222
223     def parse_pipeline(self):
224         negate = False
225
226         commands = [self.parse_command()]
227         while self.look() == ('|',):
228             self.lex()
229             commands.append(self.parse_command())
230         return Pipeline(commands, negate, self.pipefail)
231             
232     def parse(self):
233         lhs = self.parse_pipeline()
234
235         while self.look():
236             operator = self.lex()
237             assert isinstance(operator, tuple) and len(operator) == 1
238
239             if not self.look():
240                 raise ValueError(
241                     "missing argument to operator %r" % operator[0])
242             
243             # FIXME: Operator precedence!!
244             lhs = Seq(lhs, operator[0], self.parse_pipeline())
245
246         return lhs
247
248 ###
249
250 import unittest
251
252 class TestShLexer(unittest.TestCase):
253     def lex(self, str, *args, **kwargs):
254         return list(ShLexer(str, *args, **kwargs).lex())
255
256     def test_basic(self):
257         self.assertEqual(self.lex('a|b>c&d<e;f'),
258                          ['a', ('|',), 'b', ('>',), 'c', ('&',), 'd', 
259                           ('<',), 'e', (';',), 'f'])
260
261     def test_redirection_tokens(self):
262         self.assertEqual(self.lex('a2>c'),
263                          ['a2', ('>',), 'c'])
264         self.assertEqual(self.lex('a 2>c'),
265                          ['a', ('>',2), 'c'])
266         
267     def test_quoting(self):
268         self.assertEqual(self.lex(""" 'a' """),
269                          ['a'])
270         self.assertEqual(self.lex(""" "hello\\"world" """),
271                          ['hello"world'])
272         self.assertEqual(self.lex(""" "hello\\'world" """),
273                          ["hello\\'world"])
274         self.assertEqual(self.lex(""" "hello\\\\world" """),
275                          ["hello\\world"])
276         self.assertEqual(self.lex(""" he"llo wo"rld """),
277                          ["hello world"])
278         self.assertEqual(self.lex(""" a\\ b a\\\\b """),
279                          ["a b", "a\\b"])
280         self.assertEqual(self.lex(""" "" "" """),
281                          ["", ""])
282         self.assertEqual(self.lex(""" a\\ b """, win32Escapes = True),
283                          ['a\\', 'b'])
284
285 class TestShParse(unittest.TestCase):
286     def parse(self, str):
287         return ShParser(str).parse()
288
289     def test_basic(self):
290         self.assertEqual(self.parse('echo hello'),
291                          Pipeline([Command(['echo', 'hello'], [])], False))
292         self.assertEqual(self.parse('echo ""'),
293                          Pipeline([Command(['echo', ''], [])], False))
294         self.assertEqual(self.parse("""echo -DFOO='a'"""),
295                          Pipeline([Command(['echo', '-DFOO=a'], [])], False))
296         self.assertEqual(self.parse('echo -DFOO="a"'),
297                          Pipeline([Command(['echo', '-DFOO=a'], [])], False))
298
299     def test_redirection(self):
300         self.assertEqual(self.parse('echo hello > c'),
301                          Pipeline([Command(['echo', 'hello'], 
302                                            [((('>'),), 'c')])], False))
303         self.assertEqual(self.parse('echo hello > c >> d'),
304                          Pipeline([Command(['echo', 'hello'], [(('>',), 'c'),
305                                                      (('>>',), 'd')])], False))
306         self.assertEqual(self.parse('a 2>&1'),
307                          Pipeline([Command(['a'], [(('>&',2), '1')])], False))
308
309     def test_pipeline(self):
310         self.assertEqual(self.parse('a | b'),
311                          Pipeline([Command(['a'], []),
312                                    Command(['b'], [])],
313                                   False))
314
315         self.assertEqual(self.parse('a | b | c'),
316                          Pipeline([Command(['a'], []),
317                                    Command(['b'], []),
318                                    Command(['c'], [])],
319                                   False))
320
321     def test_list(self):        
322         self.assertEqual(self.parse('a ; b'),
323                          Seq(Pipeline([Command(['a'], [])], False),
324                              ';',
325                              Pipeline([Command(['b'], [])], False)))
326
327         self.assertEqual(self.parse('a & b'),
328                          Seq(Pipeline([Command(['a'], [])], False),
329                              '&',
330                              Pipeline([Command(['b'], [])], False)))
331
332         self.assertEqual(self.parse('a && b'),
333                          Seq(Pipeline([Command(['a'], [])], False),
334                              '&&',
335                              Pipeline([Command(['b'], [])], False)))
336
337         self.assertEqual(self.parse('a || b'),
338                          Seq(Pipeline([Command(['a'], [])], False),
339                              '||',
340                              Pipeline([Command(['b'], [])], False)))
341
342         self.assertEqual(self.parse('a && b || c'),
343                          Seq(Seq(Pipeline([Command(['a'], [])], False),
344                                  '&&',
345                                  Pipeline([Command(['b'], [])], False)),
346                              '||',
347                              Pipeline([Command(['c'], [])], False)))
348
349         self.assertEqual(self.parse('a; b'),
350                          Seq(Pipeline([Command(['a'], [])], False),
351                              ';',
352                              Pipeline([Command(['b'], [])], False)))
353
354 if __name__ == '__main__':
355     unittest.main()