blob: 6114d2df014d121eb490ec45c434e896118ca6e4 [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
Raymond Hettinger756b3f32004-01-29 06:37:52 +000012from collections import deque
Guido van Rossum9c30c241998-12-22 05:19:29 +000013
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000014try:
15 from cStringIO import StringIO
16except ImportError:
17 from StringIO import StringIO
18
19__all__ = ["shlex", "split"]
Skip Montanaro0de65802001-02-15 22:15:14 +000020
Guido van Rossum9c30c241998-12-22 05:19:29 +000021class shlex:
Tim Peters70c43782001-01-17 08:48:39 +000022 "A lexical analyzer class for simple shell-like syntaxes."
Fred Drake24315232003-04-17 22:01:17 +000023 def __init__(self, instream=None, infile=None, posix=False):
Neal Norwitz10cf2182003-04-17 23:09:08 +000024 if isinstance(instream, basestring):
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000025 instream = StringIO(instream)
Raymond Hettingerf13eb552002-06-02 00:40:05 +000026 if instream is not None:
Guido van Rossum9c30c241998-12-22 05:19:29 +000027 self.instream = instream
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000028 self.infile = infile
Guido van Rossum9c30c241998-12-22 05:19:29 +000029 else:
30 self.instream = sys.stdin
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000031 self.infile = None
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000032 self.posix = posix
33 if posix:
34 self.eof = None
35 else:
36 self.eof = ''
Guido van Rossum9c30c241998-12-22 05:19:29 +000037 self.commenters = '#'
Fred Drakedbbf76b2000-07-09 16:44:26 +000038 self.wordchars = ('abcdfeghijklmnopqrstuvwxyz'
39 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_')
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000040 if self.posix:
41 self.wordchars += ('ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
42 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ')
Guido van Rossum9c30c241998-12-22 05:19:29 +000043 self.whitespace = ' \t\r\n'
Fred Drake24315232003-04-17 22:01:17 +000044 self.whitespace_split = False
Guido van Rossum9c30c241998-12-22 05:19:29 +000045 self.quotes = '\'"'
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000046 self.escape = '\\'
47 self.escapedquotes = '"'
Guido van Rossum9c30c241998-12-22 05:19:29 +000048 self.state = ' '
Raymond Hettinger756b3f32004-01-29 06:37:52 +000049 self.pushback = deque()
Guido van Rossum9c30c241998-12-22 05:19:29 +000050 self.lineno = 1
Petri Lehtinen43072782013-02-23 22:07:39 +010051 self._lines_found = 0
Guido van Rossum9c30c241998-12-22 05:19:29 +000052 self.debug = 0
53 self.token = ''
Raymond Hettinger756b3f32004-01-29 06:37:52 +000054 self.filestack = deque()
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:
Walter Dörwald70a6b492004-02-12 17:35:32 +000063 print "shlex: pushing token " + repr(tok)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000064 self.pushback.appendleft(tok)
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."
Neal Norwitz10cf2182003-04-17 23:09:08 +000068 if isinstance(newstream, basestring):
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000069 newstream = StringIO(newstream)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000070 self.filestack.appendleft((self.infile, self.instream, self.lineno))
Eric S. Raymondbddbaf72001-01-16 15:19:13 +000071 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()
Raymond Hettinger756b3f32004-01-29 06:37:52 +000083 (self.infile, self.instream, self.lineno) = self.filestack.popleft()
Eric S. Raymondbddbaf72001-01-16 15:19:13 +000084 if self.debug:
85 print 'shlex: popping to %s, line %d' \
86 % (self.instream, self.lineno)
87 self.state = ' '
88
Guido van Rossum9c30c241998-12-22 05:19:29 +000089 def get_token(self):
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000090 "Get a token from the input stream (or from stack if it's nonempty)"
Guido van Rossum9c30c241998-12-22 05:19:29 +000091 if self.pushback:
Raymond Hettinger756b3f32004-01-29 06:37:52 +000092 tok = self.pushback.popleft()
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000093 if self.debug >= 1:
Walter Dörwald70a6b492004-02-12 17:35:32 +000094 print "shlex: popping token " + repr(tok)
Guido van Rossum9c30c241998-12-22 05:19:29 +000095 return tok
Fred Drakedbbf76b2000-07-09 16:44:26 +000096 # No pushback. Get a token.
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000097 raw = self.read_token()
98 # Handle inclusions
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000099 if self.source is not None:
100 while raw == self.source:
101 spec = self.sourcehook(self.read_token())
102 if spec:
103 (newfile, newstream) = spec
104 self.push_source(newstream, newfile)
105 raw = self.get_token()
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000106 # Maybe we got EOF instead?
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000107 while raw == self.eof:
Fred Drake24315232003-04-17 22:01:17 +0000108 if not self.filestack:
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000109 return self.eof
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000110 else:
Eric S. Raymondbddbaf72001-01-16 15:19:13 +0000111 self.pop_source()
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000112 raw = self.get_token()
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000113 # Neither inclusion nor EOF
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000114 if self.debug >= 1:
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000115 if raw != self.eof:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000116 print "shlex: token=" + repr(raw)
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000117 else:
118 print "shlex: token=EOF"
119 return raw
120
121 def read_token(self):
Petri Lehtinen43072782013-02-23 22:07:39 +0100122 if self._lines_found:
123 self.lineno += self._lines_found
124 self._lines_found = 0
125
126 i = 0
Fred Drake24315232003-04-17 22:01:17 +0000127 quoted = False
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000128 escapedstate = ' '
Neal Norwitz10cf2182003-04-17 23:09:08 +0000129 while True:
Petri Lehtinen43072782013-02-23 22:07:39 +0100130 i += 1
Andrew M. Kuchling49d27c82000-12-23 14:20:24 +0000131 nextchar = self.instream.read(1)
Guido van Rossum9c30c241998-12-22 05:19:29 +0000132 if nextchar == '\n':
Petri Lehtinen43072782013-02-23 22:07:39 +0100133 # In case newline is the first character increment lineno
134 if i == 1:
135 self.lineno += 1
136 else:
137 self._lines_found += 1
138
Guido van Rossum9c30c241998-12-22 05:19:29 +0000139 if self.debug >= 3:
Fred Drake52dc76c2000-07-03 09:56:23 +0000140 print "shlex: in state", repr(self.state), \
Tim Peters70c43782001-01-17 08:48:39 +0000141 "I see character:", repr(nextchar)
Fred Drakedbbf76b2000-07-09 16:44:26 +0000142 if self.state is None:
Eric S. Raymondbddbaf72001-01-16 15:19:13 +0000143 self.token = '' # past end of file
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000144 break
Guido van Rossum9c30c241998-12-22 05:19:29 +0000145 elif self.state == ' ':
146 if not nextchar:
Eric S. Raymondbddbaf72001-01-16 15:19:13 +0000147 self.state = None # end of file
Guido van Rossum9c30c241998-12-22 05:19:29 +0000148 break
149 elif nextchar in self.whitespace:
150 if self.debug >= 2:
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000151 print "shlex: I see whitespace in whitespace state"
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000152 if self.token or (self.posix and quoted):
Fred Drakedbbf76b2000-07-09 16:44:26 +0000153 break # emit current token
Guido van Rossum9c30c241998-12-22 05:19:29 +0000154 else:
155 continue
156 elif nextchar in self.commenters:
157 self.instream.readline()
Petri Lehtinen43072782013-02-23 22:07:39 +0100158 # Not considered a token so incrementing lineno directly
Guido van Rossum9c30c241998-12-22 05:19:29 +0000159 self.lineno = self.lineno + 1
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000160 elif self.posix and nextchar in self.escape:
161 escapedstate = 'a'
162 self.state = nextchar
Guido van Rossum9c30c241998-12-22 05:19:29 +0000163 elif nextchar in self.wordchars:
164 self.token = nextchar
165 self.state = 'a'
166 elif nextchar in self.quotes:
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000167 if not self.posix:
168 self.token = nextchar
Guido van Rossum9c30c241998-12-22 05:19:29 +0000169 self.state = nextchar
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000170 elif self.whitespace_split:
171 self.token = nextchar
172 self.state = 'a'
Guido van Rossum9c30c241998-12-22 05:19:29 +0000173 else:
174 self.token = nextchar
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000175 if self.token or (self.posix and quoted):
Fred Drakedbbf76b2000-07-09 16:44:26 +0000176 break # emit current token
Guido van Rossum9c30c241998-12-22 05:19:29 +0000177 else:
178 continue
179 elif self.state in self.quotes:
Fred Drake24315232003-04-17 22:01:17 +0000180 quoted = True
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000181 if not nextchar: # end of file
Andrew M. Kuchling9d56cd12001-01-09 03:01:15 +0000182 if self.debug >= 2:
183 print "shlex: I see EOF in quotes state"
184 # XXX what error should be raised here?
185 raise ValueError, "No closing quotation"
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000186 if nextchar == self.state:
187 if not self.posix:
188 self.token = self.token + nextchar
189 self.state = ' '
190 break
191 else:
192 self.state = 'a'
193 elif self.posix and nextchar in self.escape and \
194 self.state in self.escapedquotes:
195 escapedstate = self.state
196 self.state = nextchar
197 else:
198 self.token = self.token + nextchar
199 elif self.state in self.escape:
200 if not nextchar: # end of file
201 if self.debug >= 2:
202 print "shlex: I see EOF in escape state"
203 # XXX what error should be raised here?
204 raise ValueError, "No escaped character"
205 # In posix shells, only the quote itself or the escape
206 # character may be escaped within quotes.
207 if escapedstate in self.quotes and \
208 nextchar != self.state and nextchar != escapedstate:
209 self.token = self.token + self.state
210 self.token = self.token + nextchar
211 self.state = escapedstate
Guido van Rossum9c30c241998-12-22 05:19:29 +0000212 elif self.state == 'a':
213 if not nextchar:
Tim Peters70c43782001-01-17 08:48:39 +0000214 self.state = None # end of file
Guido van Rossum9c30c241998-12-22 05:19:29 +0000215 break
216 elif nextchar in self.whitespace:
217 if self.debug >= 2:
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000218 print "shlex: I see whitespace in word state"
Guido van Rossum9c30c241998-12-22 05:19:29 +0000219 self.state = ' '
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000220 if self.token or (self.posix and quoted):
Fred Drakedbbf76b2000-07-09 16:44:26 +0000221 break # emit current token
Guido van Rossum9c30c241998-12-22 05:19:29 +0000222 else:
223 continue
224 elif nextchar in self.commenters:
225 self.instream.readline()
Petri Lehtinen43072782013-02-23 22:07:39 +0100226 # Not considered a token so incrementing lineno directly
Guido van Rossum9c30c241998-12-22 05:19:29 +0000227 self.lineno = self.lineno + 1
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000228 if self.posix:
229 self.state = ' '
230 if self.token or (self.posix and quoted):
231 break # emit current token
232 else:
233 continue
234 elif self.posix and nextchar in self.quotes:
235 self.state = nextchar
236 elif self.posix and nextchar in self.escape:
237 escapedstate = 'a'
238 self.state = nextchar
239 elif nextchar in self.wordchars or nextchar in self.quotes \
240 or self.whitespace_split:
Guido van Rossum9c30c241998-12-22 05:19:29 +0000241 self.token = self.token + nextchar
242 else:
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000243 self.pushback.appendleft(nextchar)
Guido van Rossum9c30c241998-12-22 05:19:29 +0000244 if self.debug >= 2:
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000245 print "shlex: I see punctuation in word state"
Guido van Rossumf247d751999-03-22 15:28:08 +0000246 self.state = ' '
Guido van Rossum9c30c241998-12-22 05:19:29 +0000247 if self.token:
Fred Drakedbbf76b2000-07-09 16:44:26 +0000248 break # emit current token
Guido van Rossum9c30c241998-12-22 05:19:29 +0000249 else:
250 continue
Guido van Rossum9c30c241998-12-22 05:19:29 +0000251 result = self.token
252 self.token = ''
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000253 if self.posix and not quoted and result == '':
254 result = None
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000255 if self.debug > 1:
256 if result:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000257 print "shlex: raw token=" + repr(result)
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000258 else:
259 print "shlex: raw token=EOF"
Guido van Rossum9c30c241998-12-22 05:19:29 +0000260 return result
261
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000262 def sourcehook(self, newfile):
263 "Hook called on a filename to be sourced."
264 if newfile[0] == '"':
265 newfile = newfile[1:-1]
Fred Drake52dc76c2000-07-03 09:56:23 +0000266 # This implements cpp-like semantics for relative-path inclusion.
Neal Norwitz10cf2182003-04-17 23:09:08 +0000267 if isinstance(self.infile, basestring) and not os.path.isabs(newfile):
Fred Drake52dc76c2000-07-03 09:56:23 +0000268 newfile = os.path.join(os.path.dirname(self.infile), newfile)
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000269 return (newfile, open(newfile, "r"))
270
Guido van Rossum4b83ecb2000-05-01 20:14:12 +0000271 def error_leader(self, infile=None, lineno=None):
272 "Emit a C-compiler-like, Emacs-friendly error-message leader."
Raymond Hettingerf13eb552002-06-02 00:40:05 +0000273 if infile is None:
Guido van Rossum4b83ecb2000-05-01 20:14:12 +0000274 infile = self.infile
Raymond Hettingerf13eb552002-06-02 00:40:05 +0000275 if lineno is None:
Guido van Rossum4b83ecb2000-05-01 20:14:12 +0000276 lineno = self.lineno
277 return "\"%s\", line %d: " % (infile, lineno)
278
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000279 def __iter__(self):
280 return self
281
282 def next(self):
283 token = self.get_token()
284 if token == self.eof:
285 raise StopIteration
286 return token
287
Georg Brandlc90bc752007-05-24 16:49:29 +0000288def split(s, comments=False, posix=True):
Georg Brandldd96ca32007-05-24 17:33:33 +0000289 lex = shlex(s, posix=posix)
Gustavo Niemeyer48f3dcc2003-04-20 01:57:03 +0000290 lex.whitespace_split = True
291 if not comments:
292 lex.commenters = ''
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000293 return list(lex)
Guido van Rossum9c30c241998-12-22 05:19:29 +0000294
Tim Peters70c43782001-01-17 08:48:39 +0000295if __name__ == '__main__':
Fred Drake52dc76c2000-07-03 09:56:23 +0000296 if len(sys.argv) == 1:
297 lexer = shlex()
298 else:
299 file = sys.argv[1]
300 lexer = shlex(open(file), file)
Guido van Rossum9c30c241998-12-22 05:19:29 +0000301 while 1:
302 tt = lexer.get_token()
Fred Drake52dc76c2000-07-03 09:56:23 +0000303 if tt:
304 print "Token: " + repr(tt)
305 else:
Guido van Rossum9c30c241998-12-22 05:19:29 +0000306 break