blob: ecd2efd022502bf2ac99d7769d504ac0e24c7293 [file] [log] [blame]
Guido van Rossume7b146f2000-02-04 15:28:42 +00001"""A lexical analyzer class for simple shell-like syntaxes."""
2
Tim Peters70c43782001-01-17 08:48:39 +00003# Module and documentation by Eric S. Raymond, 21 Dec 1998
Guido van Rossumeb4e11a2000-05-01 20:08:46 +00004# Input stacking and error message cleanup added by ESR, March 2000
Tim Peters70c43782001-01-17 08:48:39 +00005# push_source() and pop_source() made explicit by ESR, January 2001.
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +00006# Posix compliance, split(), string arguments, and
7# iterator interface by Gustavo Niemeyer, April 2003.
Guido van Rossum9c30c241998-12-22 05:19:29 +00008
Éric Araujo9bce3112011-07-27 18:29:31 +02009import os
10import re
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
Guido van Rossum68937b42007-05-18 00:51:22 +000014from io import StringIO
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000015
Éric Araujo9bce3112011-07-27 18:29:31 +020016__all__ = ["shlex", "split", "quote"]
Skip Montanaro0de65802001-02-15 22:15:14 +000017
Guido van Rossum9c30c241998-12-22 05:19:29 +000018class shlex:
Tim Peters70c43782001-01-17 08:48:39 +000019 "A lexical analyzer class for simple shell-like syntaxes."
Fred Drake24315232003-04-17 22:01:17 +000020 def __init__(self, instream=None, infile=None, posix=False):
Guido van Rossum3172c5d2007-10-16 18:12:55 +000021 if isinstance(instream, str):
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000022 instream = StringIO(instream)
Raymond Hettingerf13eb552002-06-02 00:40:05 +000023 if instream is not None:
Guido van Rossum9c30c241998-12-22 05:19:29 +000024 self.instream = instream
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000025 self.infile = infile
Guido van Rossum9c30c241998-12-22 05:19:29 +000026 else:
27 self.instream = sys.stdin
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000028 self.infile = None
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000029 self.posix = posix
30 if posix:
31 self.eof = None
32 else:
33 self.eof = ''
Guido van Rossum9c30c241998-12-22 05:19:29 +000034 self.commenters = '#'
Fred Drakedbbf76b2000-07-09 16:44:26 +000035 self.wordchars = ('abcdfeghijklmnopqrstuvwxyz'
36 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_')
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000037 if self.posix:
Antoine Pitroud72402e2010-10-27 18:52:48 +000038 self.wordchars += ('ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
39 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ')
Guido van Rossum9c30c241998-12-22 05:19:29 +000040 self.whitespace = ' \t\r\n'
Fred Drake24315232003-04-17 22:01:17 +000041 self.whitespace_split = False
Guido van Rossum9c30c241998-12-22 05:19:29 +000042 self.quotes = '\'"'
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000043 self.escape = '\\'
44 self.escapedquotes = '"'
Guido van Rossum9c30c241998-12-22 05:19:29 +000045 self.state = ' '
Raymond Hettinger756b3f32004-01-29 06:37:52 +000046 self.pushback = deque()
Guido van Rossum9c30c241998-12-22 05:19:29 +000047 self.lineno = 1
48 self.debug = 0
49 self.token = ''
Raymond Hettinger756b3f32004-01-29 06:37:52 +000050 self.filestack = deque()
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000051 self.source = None
Guido van Rossum9c30c241998-12-22 05:19:29 +000052
53 def push_token(self, tok):
54 "Push a token onto the stack popped by the get_token method"
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000055 if self.debug >= 1:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000056 print("shlex: pushing token " + repr(tok))
Raymond Hettinger756b3f32004-01-29 06:37:52 +000057 self.pushback.appendleft(tok)
Guido van Rossum9c30c241998-12-22 05:19:29 +000058
Eric S. Raymondbddbaf72001-01-16 15:19:13 +000059 def push_source(self, newstream, newfile=None):
60 "Push an input source onto the lexer's input source stack."
Guido van Rossum3172c5d2007-10-16 18:12:55 +000061 if isinstance(newstream, str):
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000062 newstream = StringIO(newstream)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000063 self.filestack.appendleft((self.infile, self.instream, self.lineno))
Eric S. Raymondbddbaf72001-01-16 15:19:13 +000064 self.infile = newfile
65 self.instream = newstream
66 self.lineno = 1
67 if self.debug:
Raymond Hettingerf13eb552002-06-02 00:40:05 +000068 if newfile is not None:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000069 print('shlex: pushing to file %s' % (self.infile,))
Eric S. Raymondbddbaf72001-01-16 15:19:13 +000070 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000071 print('shlex: pushing to stream %s' % (self.instream,))
Eric S. Raymondbddbaf72001-01-16 15:19:13 +000072
73 def pop_source(self):
74 "Pop the input source stack."
75 self.instream.close()
Raymond Hettinger756b3f32004-01-29 06:37:52 +000076 (self.infile, self.instream, self.lineno) = self.filestack.popleft()
Eric S. Raymondbddbaf72001-01-16 15:19:13 +000077 if self.debug:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000078 print('shlex: popping to %s, line %d' \
79 % (self.instream, self.lineno))
Eric S. Raymondbddbaf72001-01-16 15:19:13 +000080 self.state = ' '
81
Guido van Rossum9c30c241998-12-22 05:19:29 +000082 def get_token(self):
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000083 "Get a token from the input stream (or from stack if it's nonempty)"
Guido van Rossum9c30c241998-12-22 05:19:29 +000084 if self.pushback:
Raymond Hettinger756b3f32004-01-29 06:37:52 +000085 tok = self.pushback.popleft()
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000086 if self.debug >= 1:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000087 print("shlex: popping token " + repr(tok))
Guido van Rossum9c30c241998-12-22 05:19:29 +000088 return tok
Fred Drakedbbf76b2000-07-09 16:44:26 +000089 # No pushback. Get a token.
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000090 raw = self.read_token()
91 # Handle inclusions
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +000092 if self.source is not None:
93 while raw == self.source:
94 spec = self.sourcehook(self.read_token())
95 if spec:
96 (newfile, newstream) = spec
97 self.push_source(newstream, newfile)
98 raw = self.get_token()
Guido van Rossumeb4e11a2000-05-01 20:08:46 +000099 # Maybe we got EOF instead?
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000100 while raw == self.eof:
Fred Drake24315232003-04-17 22:01:17 +0000101 if not self.filestack:
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000102 return self.eof
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000103 else:
Eric S. Raymondbddbaf72001-01-16 15:19:13 +0000104 self.pop_source()
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000105 raw = self.get_token()
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000106 # Neither inclusion nor EOF
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000107 if self.debug >= 1:
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000108 if raw != self.eof:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000109 print("shlex: token=" + repr(raw))
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000110 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000111 print("shlex: token=EOF")
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000112 return raw
113
114 def read_token(self):
Fred Drake24315232003-04-17 22:01:17 +0000115 quoted = False
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000116 escapedstate = ' '
Neal Norwitz10cf2182003-04-17 23:09:08 +0000117 while True:
Andrew M. Kuchling49d27c82000-12-23 14:20:24 +0000118 nextchar = self.instream.read(1)
Guido van Rossum9c30c241998-12-22 05:19:29 +0000119 if nextchar == '\n':
Petri Lehtinen0362b542013-02-23 23:03:15 +0100120 self.lineno = self.lineno + 1
Guido van Rossum9c30c241998-12-22 05:19:29 +0000121 if self.debug >= 3:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000122 print("shlex: in state", repr(self.state), \
123 "I see character:", repr(nextchar))
Fred Drakedbbf76b2000-07-09 16:44:26 +0000124 if self.state is None:
Eric S. Raymondbddbaf72001-01-16 15:19:13 +0000125 self.token = '' # past end of file
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000126 break
Guido van Rossum9c30c241998-12-22 05:19:29 +0000127 elif self.state == ' ':
128 if not nextchar:
Eric S. Raymondbddbaf72001-01-16 15:19:13 +0000129 self.state = None # end of file
Guido van Rossum9c30c241998-12-22 05:19:29 +0000130 break
131 elif nextchar in self.whitespace:
132 if self.debug >= 2:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000133 print("shlex: I see whitespace in whitespace state")
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000134 if self.token or (self.posix and quoted):
Fred Drakedbbf76b2000-07-09 16:44:26 +0000135 break # emit current token
Guido van Rossum9c30c241998-12-22 05:19:29 +0000136 else:
137 continue
138 elif nextchar in self.commenters:
139 self.instream.readline()
140 self.lineno = self.lineno + 1
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000141 elif self.posix and nextchar in self.escape:
142 escapedstate = 'a'
143 self.state = nextchar
Guido van Rossum9c30c241998-12-22 05:19:29 +0000144 elif nextchar in self.wordchars:
145 self.token = nextchar
146 self.state = 'a'
147 elif nextchar in self.quotes:
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000148 if not self.posix:
149 self.token = nextchar
Guido van Rossum9c30c241998-12-22 05:19:29 +0000150 self.state = nextchar
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000151 elif self.whitespace_split:
152 self.token = nextchar
153 self.state = 'a'
Guido van Rossum9c30c241998-12-22 05:19:29 +0000154 else:
155 self.token = nextchar
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000156 if self.token or (self.posix and quoted):
Fred Drakedbbf76b2000-07-09 16:44:26 +0000157 break # emit current token
Guido van Rossum9c30c241998-12-22 05:19:29 +0000158 else:
159 continue
160 elif self.state in self.quotes:
Fred Drake24315232003-04-17 22:01:17 +0000161 quoted = True
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000162 if not nextchar: # end of file
Andrew M. Kuchling9d56cd12001-01-09 03:01:15 +0000163 if self.debug >= 2:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000164 print("shlex: I see EOF in quotes state")
Andrew M. Kuchling9d56cd12001-01-09 03:01:15 +0000165 # XXX what error should be raised here?
Collin Winterce36ad82007-08-30 01:19:48 +0000166 raise ValueError("No closing quotation")
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000167 if nextchar == self.state:
168 if not self.posix:
169 self.token = self.token + nextchar
170 self.state = ' '
171 break
172 else:
173 self.state = 'a'
174 elif self.posix and nextchar in self.escape and \
175 self.state in self.escapedquotes:
176 escapedstate = self.state
177 self.state = nextchar
178 else:
179 self.token = self.token + nextchar
180 elif self.state in self.escape:
181 if not nextchar: # end of file
182 if self.debug >= 2:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000183 print("shlex: I see EOF in escape state")
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000184 # XXX what error should be raised here?
Collin Winterce36ad82007-08-30 01:19:48 +0000185 raise ValueError("No escaped character")
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000186 # In posix shells, only the quote itself or the escape
187 # character may be escaped within quotes.
188 if escapedstate in self.quotes and \
189 nextchar != self.state and nextchar != escapedstate:
190 self.token = self.token + self.state
191 self.token = self.token + nextchar
192 self.state = escapedstate
Guido van Rossum9c30c241998-12-22 05:19:29 +0000193 elif self.state == 'a':
194 if not nextchar:
Tim Peters70c43782001-01-17 08:48:39 +0000195 self.state = None # end of file
Guido van Rossum9c30c241998-12-22 05:19:29 +0000196 break
197 elif nextchar in self.whitespace:
198 if self.debug >= 2:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000199 print("shlex: I see whitespace in word state")
Guido van Rossum9c30c241998-12-22 05:19:29 +0000200 self.state = ' '
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000201 if self.token or (self.posix and quoted):
Fred Drakedbbf76b2000-07-09 16:44:26 +0000202 break # emit current token
Guido van Rossum9c30c241998-12-22 05:19:29 +0000203 else:
204 continue
205 elif nextchar in self.commenters:
206 self.instream.readline()
207 self.lineno = self.lineno + 1
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000208 if self.posix:
209 self.state = ' '
210 if self.token or (self.posix and quoted):
211 break # emit current token
212 else:
213 continue
214 elif self.posix and nextchar in self.quotes:
215 self.state = nextchar
216 elif self.posix and nextchar in self.escape:
217 escapedstate = 'a'
218 self.state = nextchar
219 elif nextchar in self.wordchars or nextchar in self.quotes \
220 or self.whitespace_split:
Guido van Rossum9c30c241998-12-22 05:19:29 +0000221 self.token = self.token + nextchar
222 else:
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000223 self.pushback.appendleft(nextchar)
Guido van Rossum9c30c241998-12-22 05:19:29 +0000224 if self.debug >= 2:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000225 print("shlex: I see punctuation in word state")
Guido van Rossumf247d751999-03-22 15:28:08 +0000226 self.state = ' '
Vinay Sajip085e8062016-08-09 15:04:49 +0100227 if self.token or (self.posix and quoted):
Fred Drakedbbf76b2000-07-09 16:44:26 +0000228 break # emit current token
Guido van Rossum9c30c241998-12-22 05:19:29 +0000229 else:
230 continue
Guido van Rossum9c30c241998-12-22 05:19:29 +0000231 result = self.token
232 self.token = ''
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000233 if self.posix and not quoted and result == '':
234 result = None
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000235 if self.debug > 1:
236 if result:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000237 print("shlex: raw token=" + repr(result))
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000238 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000239 print("shlex: raw token=EOF")
Guido van Rossum9c30c241998-12-22 05:19:29 +0000240 return result
241
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000242 def sourcehook(self, newfile):
243 "Hook called on a filename to be sourced."
244 if newfile[0] == '"':
245 newfile = newfile[1:-1]
Fred Drake52dc76c2000-07-03 09:56:23 +0000246 # This implements cpp-like semantics for relative-path inclusion.
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000247 if isinstance(self.infile, str) and not os.path.isabs(newfile):
Fred Drake52dc76c2000-07-03 09:56:23 +0000248 newfile = os.path.join(os.path.dirname(self.infile), newfile)
Guido van Rossumeb4e11a2000-05-01 20:08:46 +0000249 return (newfile, open(newfile, "r"))
250
Guido van Rossum4b83ecb2000-05-01 20:14:12 +0000251 def error_leader(self, infile=None, lineno=None):
252 "Emit a C-compiler-like, Emacs-friendly error-message leader."
Raymond Hettingerf13eb552002-06-02 00:40:05 +0000253 if infile is None:
Guido van Rossum4b83ecb2000-05-01 20:14:12 +0000254 infile = self.infile
Raymond Hettingerf13eb552002-06-02 00:40:05 +0000255 if lineno is None:
Guido van Rossum4b83ecb2000-05-01 20:14:12 +0000256 lineno = self.lineno
257 return "\"%s\", line %d: " % (infile, lineno)
258
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000259 def __iter__(self):
260 return self
261
Georg Brandla18af4e2007-04-21 15:47:16 +0000262 def __next__(self):
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000263 token = self.get_token()
264 if token == self.eof:
265 raise StopIteration
266 return token
267
Guido van Rossume7ba4952007-06-06 23:52:48 +0000268def split(s, comments=False, posix=True):
269 lex = shlex(s, posix=posix)
Gustavo Niemeyer48f3dcc2003-04-20 01:57:03 +0000270 lex.whitespace_split = True
271 if not comments:
272 lex.commenters = ''
Gustavo Niemeyer68d8cef2003-04-17 21:31:33 +0000273 return list(lex)
Guido van Rossum9c30c241998-12-22 05:19:29 +0000274
Éric Araujo9bce3112011-07-27 18:29:31 +0200275
Ezio Melotti67321cc2011-08-16 19:03:41 +0300276_find_unsafe = re.compile(r'[^\w@%+=:,./-]', re.ASCII).search
Éric Araujo9bce3112011-07-27 18:29:31 +0200277
278def quote(s):
279 """Return a shell-escaped version of the string *s*."""
280 if not s:
281 return "''"
282 if _find_unsafe(s) is None:
283 return s
284
285 # use single quotes, and put single quotes into double quotes
286 # the string $'b is then quoted as '$'"'"'b'
287 return "'" + s.replace("'", "'\"'\"'") + "'"
288
289
R David Murray838f2c42014-10-17 20:28:47 -0400290def _print_tokens(lexer):
Guido van Rossum9c30c241998-12-22 05:19:29 +0000291 while 1:
292 tt = lexer.get_token()
R David Murray838f2c42014-10-17 20:28:47 -0400293 if not tt:
Guido van Rossum9c30c241998-12-22 05:19:29 +0000294 break
R David Murray838f2c42014-10-17 20:28:47 -0400295 print("Token: " + repr(tt))
296
297if __name__ == '__main__':
298 if len(sys.argv) == 1:
299 _print_tokens(shlex())
300 else:
301 fn = sys.argv[1]
302 with open(fn) as f:
303 _print_tokens(shlex(f, fn))