blob: 863e4049ac06c395a115f6ef85df5286dc7aca01 [file] [log] [blame]
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +00001# -*- coding: iso-8859-1 -*-
Guido van Rossume7b146f2000-02-04 15:28:42 +00002"""A lexical analyzer class for simple shell-like syntaxes."""
3
Tim Peters70c43782001-01-17 08:48:39 +00004# Module and documentation by Eric S. Raymond, 21 Dec 1998
Guido van Rossumeb4e11a2000-05-01 20:08:46 +00005# Input stacking and error message cleanup added by ESR, March 2000
Tim Peters70c43782001-01-17 08:48:39 +00006# push_source() and pop_source() made explicit by ESR, January 2001.
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +00007# Posix compliance, split(), string arguments, and
8# iterator interface by Gustavo Niemeyer, April 2003.
Guido van Rossum9c30c241998-12-22 05:19:29 +00009
Fred Drake52dc76c2000-07-03 09:56:23 +000010import os.path
Guido van Rossum73898c71999-05-03 18:14:16 +000011import sys
Guido van Rossum9c30c241998-12-22 05:19:29 +000012
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000013from types import StringTypes
14
15try:
16 from cStringIO import StringIO
17except ImportError:
18 from StringIO import StringIO
19
20__all__ = ["shlex", "split"]
Skip Montanaro0de65802001-02-15 22:15:14 +000021
Guido van Rossum9c30c241998-12-22 05:19:29 +000022class shlex:
Tim Peters70c43782001-01-17 08:48:39 +000023 "A lexical analyzer class for simple shell-like syntaxes."
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000024 def __init__(self, instream=None, infile=None, posix=0):
25 if type(instream) in StringTypes:
26 instream = StringIO(instream)
Raymond Hettingerf13eb552002-06-02 00:40:05 +000027 if instream is not None:
Guido van Rossum9c30c241998-12-22 05:19:29 +000028 self.instream = instream
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000029 self.infile = infile
Guido van Rossum9c30c241998-12-22 05:19:29 +000030 else:
31 self.instream = sys.stdin
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000032 self.infile = None
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000033 self.posix = posix
34 if posix:
35 self.eof = None
36 else:
37 self.eof = ''
Guido van Rossum9c30c241998-12-22 05:19:29 +000038 self.commenters = '#'
Fred Drakedbbf76b2000-07-09 16:44:26 +000039 self.wordchars = ('abcdfeghijklmnopqrstuvwxyz'
40 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_')
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000041 if self.posix:
42 self.wordchars += ('ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
43 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ')
Guido van Rossum9c30c241998-12-22 05:19:29 +000044 self.whitespace = ' \t\r\n'
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000045 self.whitespace_split = 0
Guido van Rossum9c30c241998-12-22 05:19:29 +000046 self.quotes = '\'"'
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000047 self.escape = '\\'
48 self.escapedquotes = '"'
Guido van Rossum9c30c241998-12-22 05:19:29 +000049 self.state = ' '
Andrew M. Kuchling49d27c82000-12-23 14:20:24 +000050 self.pushback = []
Guido van Rossum9c30c241998-12-22 05:19:29 +000051 self.lineno = 1
52 self.debug = 0
53 self.token = ''
Fred Drakedbbf76b2000-07-09 16:44:26 +000054 self.filestack = []
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000055 self.source = None
56 if self.debug:
Fred Drake52dc76c2000-07-03 09:56:23 +000057 print 'shlex: reading from %s, line %d' \
58 % (self.instream, self.lineno)
Guido van Rossum9c30c241998-12-22 05:19:29 +000059
60 def push_token(self, tok):
61 "Push a token onto the stack popped by the get_token method"
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000062 if self.debug >= 1:
63 print "shlex: pushing token " + `tok`
Andrew M. Kuchling49d27c82000-12-23 14:20:24 +000064 self.pushback = [tok] + self.pushback
Guido van Rossum9c30c241998-12-22 05:19:29 +000065
Eric S. Raymondbddbaf72001-01-16 15:19:13 +000066 def push_source(self, newstream, newfile=None):
67 "Push an input source onto the lexer's input source stack."
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000068 if type(newstream) in StringTypes:
69 newstream = StringIO(newstream)
Eric S. Raymondbddbaf72001-01-16 15:19:13 +000070 self.filestack.insert(0, (self.infile, self.instream, self.lineno))
71 self.infile = newfile
72 self.instream = newstream
73 self.lineno = 1
74 if self.debug:
Raymond Hettingerf13eb552002-06-02 00:40:05 +000075 if newfile is not None:
Eric S. Raymondbddbaf72001-01-16 15:19:13 +000076 print 'shlex: pushing to file %s' % (self.infile,)
77 else:
78 print 'shlex: pushing to stream %s' % (self.instream,)
79
80 def pop_source(self):
81 "Pop the input source stack."
82 self.instream.close()
83 (self.infile, self.instream, self.lineno) = self.filestack[0]
84 self.filestack = self.filestack[1:]
85 if self.debug:
86 print 'shlex: popping to %s, line %d' \
87 % (self.instream, self.lineno)
88 self.state = ' '
89
Guido van Rossum9c30c241998-12-22 05:19:29 +000090 def get_token(self):
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000091 "Get a token from the input stream (or from stack if it's nonempty)"
Guido van Rossum9c30c241998-12-22 05:19:29 +000092 if self.pushback:
93 tok = self.pushback[0]
94 self.pushback = self.pushback[1:]
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000095 if self.debug >= 1:
96 print "shlex: popping token " + `tok`
Guido van Rossum9c30c241998-12-22 05:19:29 +000097 return tok
Fred Drakedbbf76b2000-07-09 16:44:26 +000098 # No pushback. Get a token.
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000099 raw = self.read_token()
100 # Handle inclusions
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000101 if self.source is not None:
102 while raw == self.source:
103 spec = self.sourcehook(self.read_token())
104 if spec:
105 (newfile, newstream) = spec
106 self.push_source(newstream, newfile)
107 raw = self.get_token()
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000108 # Maybe we got EOF instead?
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000109 while raw == self.eof:
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000110 if len(self.filestack) == 0:
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000111 return self.eof
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000112 else:
Eric S. Raymondbddbaf72001-01-16 15:19:13 +0000113 self.pop_source()
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000114 raw = self.get_token()
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000115 # Neither inclusion nor EOF
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000116 if self.debug >= 1:
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000117 if raw != self.eof:
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000118 print "shlex: token=" + `raw`
119 else:
120 print "shlex: token=EOF"
121 return raw
122
123 def read_token(self):
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000124 quoted = 0
125 escapedstate = ' '
Guido van Rossum9c30c241998-12-22 05:19:29 +0000126 while 1:
Andrew M. Kuchling49d27c82000-12-23 14:20:24 +0000127 nextchar = self.instream.read(1)
Guido van Rossum9c30c241998-12-22 05:19:29 +0000128 if nextchar == '\n':
129 self.lineno = self.lineno + 1
130 if self.debug >= 3:
Fred Drake52dc76c2000-07-03 09:56:23 +0000131 print "shlex: in state", repr(self.state), \
Tim Peters70c43782001-01-17 08:48:39 +0000132 "I see character:", repr(nextchar)
Fred Drakedbbf76b2000-07-09 16:44:26 +0000133 if self.state is None:
Eric S. Raymondbddbaf72001-01-16 15:19:13 +0000134 self.token = '' # past end of file
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000135 break
Guido van Rossum9c30c241998-12-22 05:19:29 +0000136 elif self.state == ' ':
137 if not nextchar:
Eric S. Raymondbddbaf72001-01-16 15:19:13 +0000138 self.state = None # end of file
Guido van Rossum9c30c241998-12-22 05:19:29 +0000139 break
140 elif nextchar in self.whitespace:
141 if self.debug >= 2:
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000142 print "shlex: I see whitespace in whitespace state"
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000143 if self.token or (self.posix and quoted):
Fred Drakedbbf76b2000-07-09 16:44:26 +0000144 break # emit current token
Guido van Rossum9c30c241998-12-22 05:19:29 +0000145 else:
146 continue
147 elif nextchar in self.commenters:
148 self.instream.readline()
149 self.lineno = self.lineno + 1
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000150 elif self.posix and nextchar in self.escape:
151 escapedstate = 'a'
152 self.state = nextchar
Guido van Rossum9c30c241998-12-22 05:19:29 +0000153 elif nextchar in self.wordchars:
154 self.token = nextchar
155 self.state = 'a'
156 elif nextchar in self.quotes:
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000157 if not self.posix:
158 self.token = nextchar
Guido van Rossum9c30c241998-12-22 05:19:29 +0000159 self.state = nextchar
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000160 elif self.whitespace_split:
161 self.token = nextchar
162 self.state = 'a'
Guido van Rossum9c30c241998-12-22 05:19:29 +0000163 else:
164 self.token = nextchar
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000165 if self.token or (self.posix and quoted):
Fred Drakedbbf76b2000-07-09 16:44:26 +0000166 break # emit current token
Guido van Rossum9c30c241998-12-22 05:19:29 +0000167 else:
168 continue
169 elif self.state in self.quotes:
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000170 quoted = 1
171 if not nextchar: # end of file
Andrew M. Kuchling9d56cd12001-01-09 03:01:15 +0000172 if self.debug >= 2:
173 print "shlex: I see EOF in quotes state"
174 # XXX what error should be raised here?
175 raise ValueError, "No closing quotation"
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000176 if nextchar == self.state:
177 if not self.posix:
178 self.token = self.token + nextchar
179 self.state = ' '
180 break
181 else:
182 self.state = 'a'
183 elif self.posix and nextchar in self.escape and \
184 self.state in self.escapedquotes:
185 escapedstate = self.state
186 self.state = nextchar
187 else:
188 self.token = self.token + nextchar
189 elif self.state in self.escape:
190 if not nextchar: # end of file
191 if self.debug >= 2:
192 print "shlex: I see EOF in escape state"
193 # XXX what error should be raised here?
194 raise ValueError, "No escaped character"
195 # In posix shells, only the quote itself or the escape
196 # character may be escaped within quotes.
197 if escapedstate in self.quotes and \
198 nextchar != self.state and nextchar != escapedstate:
199 self.token = self.token + self.state
200 self.token = self.token + nextchar
201 self.state = escapedstate
Guido van Rossum9c30c241998-12-22 05:19:29 +0000202 elif self.state == 'a':
203 if not nextchar:
Tim Peters70c43782001-01-17 08:48:39 +0000204 self.state = None # end of file
Guido van Rossum9c30c241998-12-22 05:19:29 +0000205 break
206 elif nextchar in self.whitespace:
207 if self.debug >= 2:
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000208 print "shlex: I see whitespace in word state"
Guido van Rossum9c30c241998-12-22 05:19:29 +0000209 self.state = ' '
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000210 if self.token or (self.posix and quoted):
Fred Drakedbbf76b2000-07-09 16:44:26 +0000211 break # emit current token
Guido van Rossum9c30c241998-12-22 05:19:29 +0000212 else:
213 continue
214 elif nextchar in self.commenters:
215 self.instream.readline()
216 self.lineno = self.lineno + 1
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000217 if self.posix:
218 self.state = ' '
219 if self.token or (self.posix and quoted):
220 break # emit current token
221 else:
222 continue
223 elif self.posix and nextchar in self.quotes:
224 self.state = nextchar
225 elif self.posix and nextchar in self.escape:
226 escapedstate = 'a'
227 self.state = nextchar
228 elif nextchar in self.wordchars or nextchar in self.quotes \
229 or self.whitespace_split:
Guido van Rossum9c30c241998-12-22 05:19:29 +0000230 self.token = self.token + nextchar
231 else:
232 self.pushback = [nextchar] + self.pushback
233 if self.debug >= 2:
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000234 print "shlex: I see punctuation in word state"
Guido van Rossumf247d751999-03-22 15:28:08 +0000235 self.state = ' '
Guido van Rossum9c30c241998-12-22 05:19:29 +0000236 if self.token:
Fred Drakedbbf76b2000-07-09 16:44:26 +0000237 break # emit current token
Guido van Rossum9c30c241998-12-22 05:19:29 +0000238 else:
239 continue
Guido van Rossum9c30c241998-12-22 05:19:29 +0000240 result = self.token
241 self.token = ''
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000242 if self.posix and not quoted and result == '':
243 result = None
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000244 if self.debug > 1:
245 if result:
246 print "shlex: raw token=" + `result`
247 else:
248 print "shlex: raw token=EOF"
Guido van Rossum9c30c241998-12-22 05:19:29 +0000249 return result
250
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000251 def sourcehook(self, newfile):
252 "Hook called on a filename to be sourced."
253 if newfile[0] == '"':
254 newfile = newfile[1:-1]
Fred Drake52dc76c2000-07-03 09:56:23 +0000255 # This implements cpp-like semantics for relative-path inclusion.
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000256 if type(self.infile) in StringTypes and not os.path.isabs(newfile):
Fred Drake52dc76c2000-07-03 09:56:23 +0000257 newfile = os.path.join(os.path.dirname(self.infile), newfile)
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000258 return (newfile, open(newfile, "r"))
259
Guido van Rossum4b83ecb2000-05-01 20:14:12 +0000260 def error_leader(self, infile=None, lineno=None):
261 "Emit a C-compiler-like, Emacs-friendly error-message leader."
Raymond Hettingerf13eb552002-06-02 00:40:05 +0000262 if infile is None:
Guido van Rossum4b83ecb2000-05-01 20:14:12 +0000263 infile = self.infile
Raymond Hettingerf13eb552002-06-02 00:40:05 +0000264 if lineno is None:
Guido van Rossum4b83ecb2000-05-01 20:14:12 +0000265 lineno = self.lineno
266 return "\"%s\", line %d: " % (infile, lineno)
267
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000268 def __iter__(self):
269 return self
270
271 def next(self):
272 token = self.get_token()
273 if token == self.eof:
274 raise StopIteration
275 return token
276
277def split(s, posix=1, spaces=1):
278 lex = shlex(s, posix=posix)
279 lex.whitespace_split = spaces
280 return list(lex)
Guido van Rossum9c30c241998-12-22 05:19:29 +0000281
Tim Peters70c43782001-01-17 08:48:39 +0000282if __name__ == '__main__':
Fred Drake52dc76c2000-07-03 09:56:23 +0000283 if len(sys.argv) == 1:
284 lexer = shlex()
285 else:
286 file = sys.argv[1]
287 lexer = shlex(open(file), file)
Guido van Rossum9c30c241998-12-22 05:19:29 +0000288 while 1:
289 tt = lexer.get_token()
Fred Drake52dc76c2000-07-03 09:56:23 +0000290 if tt:
291 print "Token: " + repr(tt)
292 else:
Guido van Rossum9c30c241998-12-22 05:19:29 +0000293 break