We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Future-proof preconditions.py:_TOKEN_RE
3.7 adds a warning about possible future changes to re: https://bugs.python.org/issue30349
A future version of python will add nested sets, which allows nesting of sets using `[...]`. Escape the inner `[` in the re so it doesn't trigger a nested set.
Closes #140.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pytype/pytd/parse/preconditions.py`
Content:
```
1 # Copyright 2016 Google Inc. All Rights Reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 """Preconditions for automatic argument checking."""
16 
17 import re
18 
19 from pytype import utils
20 
21 
22 class PreconditionError(ValueError):
23   pass
24 
25 
26 class _Precondition(object):
27   """Base class for preconditions."""
28 
29   def check(self, value):
30     """Raise PreconditionError if value does not match condition."""
31     raise NotImplementedError
32 
33   def allowed_types(self):
34     """Returns a set of types or typenames that are allowed."""
35     raise NotImplementedError
36 
37 
38 class _ClassNamePrecondition(_Precondition):
39   """Precondition that expects an instance of a specific class."""
40 
41   def __init__(self, class_name):
42     super(_ClassNamePrecondition, self).__init__()
43     self._class_name = class_name
44 
45   def check(self, value):
46     actual = type(value).__name__
47     if actual != self._class_name:
48       raise PreconditionError(
49           "actual=%s, expected=%s" % (actual, self._class_name))
50 
51   def allowed_types(self):
52     return {self._class_name}
53 
54 
55 class _IsInstancePrecondition(_Precondition):
56   """Precondition that expects an instance of a class or subclass."""
57 
58   def __init__(self, cls):
59     super(_IsInstancePrecondition, self).__init__()
60     self._cls = cls
61 
62   def check(self, value):
63     if not isinstance(value, self._cls):
64       raise PreconditionError(
65           "actual=%s, expected_superclass=%s" % (
66               type(value).__name__, self._cls.__name__))
67 
68   def allowed_types(self):
69     return {self._cls}
70 
71 
72 _REGISTERED_CLASSES = {}
73 
74 
75 def register(cls):
76   """Register a class object for use in {X} syntax."""
77   name = cls.__name__
78   assert name not in _REGISTERED_CLASSES
79   _REGISTERED_CLASSES[name] = _IsInstancePrecondition(cls)
80 
81 
82 class _TuplePrecondition(_Precondition):
83   """Precondition that expects a tuple."""
84 
85   def __init__(self, element_condition):
86     super(_TuplePrecondition, self).__init__()
87     self._element_condition = element_condition
88 
89   def check(self, value):
90     if not isinstance(value, tuple):
91       raise PreconditionError(
92           "actual=%s, expected=tuple" % type(value).__name__)
93     for v in value:
94       self._element_condition.check(v)
95 
96   def allowed_types(self):
97     return self._element_condition.allowed_types()
98 
99 
100 class _OrPrecondition(_Precondition):
101   """Precondition that expects one of various choices to match."""
102 
103   def __init__(self, choices):
104     super(_OrPrecondition, self).__init__()
105     self._choices = choices
106 
107   def check(self, value):
108     errors = []
109     for c in self._choices:
110       try:
111         c.check(value)
112         return
113       except PreconditionError as e:
114         errors.append(e)
115     raise PreconditionError(
116         " or ".join("(%s)" % utils.message(e) for e in errors))
117 
118   def allowed_types(self):
119     allowed = set()
120     for c in self._choices:
121       allowed |= c.allowed_types()
122     return allowed
123 
124 
125 class CallChecker(object):
126   """Class that performs argument checks against a collection of conditions."""
127 
128   def __init__(self, condition_pairs):
129     """Create a checker given a sequence of (name, precondition) pairs."""
130     self._arg_sequence = tuple(condition_pairs)
131     self._arg_map = dict(self._arg_sequence)
132 
133   def check(self, *args, **kwargs):
134     """Raise PreconditionError if the actual call is invalid."""
135     # This check is intended to be in addition to an actual call, so an
136     # incorrect number of args or undefined kwargs should be caught elsewhere.
137     for value, pair in zip(args, self._arg_sequence):
138       name, condition = pair
139       self._check_arg(condition, name, value)
140     for name, value in kwargs.items():
141       condition = self._arg_map.get(name)
142       self._check_arg(condition, name, value)
143 
144   def _check_arg(self, condition, name, value):
145     if condition:
146       try:
147         condition.check(value)
148       except PreconditionError as e:
149         raise PreconditionError("argument=%s: %s." % (name, utils.message(e)))
150 
151   def allowed_types(self):
152     """Determines the types and typenames allowed by calls to the checker.
153 
154     Returns:
155       A set of types and/or typenames (strings).  A typename matches
156       only that one class while a type matches any subclass of the type.
157     """
158     allowed = set()
159     for _, c in self._arg_sequence:
160       allowed |= c.allowed_types()
161     return allowed
162 
163 
164 # RE to match a single token.  Leading whitepace is ignored.
165 _TOKEN_RE = re.compile(
166     r"\s*(?:(?P<literal>[[\]{}])|(?P<word>[a-zA-Z_]\w*))")
167 
168 # Token codes (aside from literal characters)
169 _TOKEN_NAME = 1
170 _TOKEN_TUPLE = 2
171 _TOKEN_OR = 3
172 
173 _RESERVED = {
174     "tuple": _TOKEN_TUPLE,
175     "or": _TOKEN_OR,
176 }
177 
178 
179 class _Parser(object):
180   """A parser for precondition specifications."""
181 
182   def __init__(self, spec):
183     self._spec = spec.strip()  # Must strip trailing whitespace.
184     self._pos = 0
185     self._pending_token = None
186 
187   def parse(self):
188     """Parse the spec and return a precondition."""
189     cond = self._parse_or()
190     self._expect(None)
191     return cond
192 
193   def _peek_token(self):
194     """Return the token code of the next token (do not consume token)."""
195     if self._pending_token is None:
196       self._pending_token = self._pop_token()
197     return self._pending_token[0]
198 
199   def _pop_token(self):
200     """Consume the next token and return (token_code, token_val)."""
201     if self._pending_token is not None:
202       result = self._pending_token
203       self._pending_token = None
204       return result
205 
206     if self._pos >= len(self._spec):
207       return None, None
208     m = _TOKEN_RE.match(self._spec, self._pos)
209     if not m:
210       raise ValueError("Syntax Error")
211     self._pos = m.end()
212     literal = m.group("literal")
213     if literal:
214       return literal, None
215     word = m.group("word")
216     t = _RESERVED.get(word)
217     if t:
218       return t, None
219     else:
220       return _TOKEN_NAME, word
221 
222   def _expect(self, expected_code):
223     """Pop the next token, raise a ValueError if the code does not match."""
224     t, val = self._pop_token()  # pylint: disable=unpacking-non-sequence
225     if t != expected_code:
226       raise ValueError("Syntax Error")
227     return val
228 
229   def _parse_or(self):
230     """Parse one or more conditions separated by "or"."""
231     choices = [self._parse_one()]
232     while self._peek_token() == _TOKEN_OR:
233       self._pop_token()
234       choices.append(self._parse_one())
235     if len(choices) == 1:
236       return choices[0]
237     else:
238       return _OrPrecondition(choices)
239 
240   def _parse_one(self):
241     """Parse a single condition (not including "or")."""
242     t, val = self._pop_token()  # pylint: disable=unpacking-non-sequence
243     if t == _TOKEN_NAME:
244       return _ClassNamePrecondition(val if val != "None" else "NoneType")
245     elif t == "{":
246       name = self._expect(_TOKEN_NAME)
247       self._expect("}")
248       cond = _REGISTERED_CLASSES.get(name)
249       if cond is None:
250         raise ValueError(
251             "Class '%s' is not registered for preconditions." % name)
252       return cond
253     elif t == _TOKEN_TUPLE:
254       self._expect("[")
255       element = self._parse_or()
256       self._expect("]")
257       return _TuplePrecondition(element)
258     raise ValueError("Syntax Error")
259 
260 
261 def parse(spec):
262   """Return a _Precondition for the given string."""
263   return _Parser(spec).parse()
264 
265 
266 def parse_arg(arg_spec):
267   """Return (name, precondition) or (name, None) for given argument spec."""
268   name, _, spec = arg_spec.partition(":")
269   return name, parse(spec) if spec else None
270
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pytype/pytd/parse/preconditions.py b/pytype/pytd/parse/preconditions.py
--- a/pytype/pytd/parse/preconditions.py
+++ b/pytype/pytd/parse/preconditions.py
@@ -163,7 +163,7 @@
 
 # RE to match a single token.  Leading whitepace is ignored.
 _TOKEN_RE = re.compile(
-    r"\s*(?:(?P<literal>[[\]{}])|(?P<word>[a-zA-Z_]\w*))")
+    r"\s*(?:(?P<literal>[\[\]{}])|(?P<word>[a-zA-Z_]\w*))")
 
 # Token codes (aside from literal characters)
 _TOKEN_NAME = 1

{"golden_diff": "diff --git a/pytype/pytd/parse/preconditions.py b/pytype/pytd/parse/preconditions.py\n--- a/pytype/pytd/parse/preconditions.py\n+++ b/pytype/pytd/parse/preconditions.py\n@@ -163,7 +163,7 @@\n \n # RE to match a single token.  Leading whitepace is ignored.\n _TOKEN_RE = re.compile(\n-    r\"\\s*(?:(?P<literal>[[\\]{}])|(?P<word>[a-zA-Z_]\\w*))\")\n+    r\"\\s*(?:(?P<literal>[\\[\\]{}])|(?P<word>[a-zA-Z_]\\w*))\")\n \n # Token codes (aside from literal characters)\n _TOKEN_NAME = 1\n", "issue": "Future-proof preconditions.py:_TOKEN_RE\n3.7 adds a warning about possible future changes to re: https://bugs.python.org/issue30349\r\nA future version of python will add nested sets, which allows nesting of sets using `[...]`. Escape the inner `[` in the re so it doesn't trigger a nested set.\r\nCloses #140.\n", "before_files": [{"content": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Preconditions for automatic argument checking.\"\"\"\n\nimport re\n\nfrom pytype import utils\n\n\nclass PreconditionError(ValueError):\n  pass\n\n\nclass _Precondition(object):\n  \"\"\"Base class for preconditions.\"\"\"\n\n  def check(self, value):\n    \"\"\"Raise PreconditionError if value does not match condition.\"\"\"\n    raise NotImplementedError\n\n  def allowed_types(self):\n    \"\"\"Returns a set of types or typenames that are allowed.\"\"\"\n    raise NotImplementedError\n\n\nclass _ClassNamePrecondition(_Precondition):\n  \"\"\"Precondition that expects an instance of a specific class.\"\"\"\n\n  def __init__(self, class_name):\n    super(_ClassNamePrecondition, self).__init__()\n    self._class_name = class_name\n\n  def check(self, value):\n    actual = type(value).__name__\n    if actual != self._class_name:\n      raise PreconditionError(\n          \"actual=%s, expected=%s\" % (actual, self._class_name))\n\n  def allowed_types(self):\n    return {self._class_name}\n\n\nclass _IsInstancePrecondition(_Precondition):\n  \"\"\"Precondition that expects an instance of a class or subclass.\"\"\"\n\n  def __init__(self, cls):\n    super(_IsInstancePrecondition, self).__init__()\n    self._cls = cls\n\n  def check(self, value):\n    if not isinstance(value, self._cls):\n      raise PreconditionError(\n          \"actual=%s, expected_superclass=%s\" % (\n              type(value).__name__, self._cls.__name__))\n\n  def allowed_types(self):\n    return {self._cls}\n\n\n_REGISTERED_CLASSES = {}\n\n\ndef register(cls):\n  \"\"\"Register a class object for use in {X} syntax.\"\"\"\n  name = cls.__name__\n  assert name not in _REGISTERED_CLASSES\n  _REGISTERED_CLASSES[name] = _IsInstancePrecondition(cls)\n\n\nclass _TuplePrecondition(_Precondition):\n  \"\"\"Precondition that expects a tuple.\"\"\"\n\n  def __init__(self, element_condition):\n    super(_TuplePrecondition, self).__init__()\n    self._element_condition = element_condition\n\n  def check(self, value):\n    if not isinstance(value, tuple):\n      raise PreconditionError(\n          \"actual=%s, expected=tuple\" % type(value).__name__)\n    for v in value:\n      self._element_condition.check(v)\n\n  def allowed_types(self):\n    return self._element_condition.allowed_types()\n\n\nclass _OrPrecondition(_Precondition):\n  \"\"\"Precondition that expects one of various choices to match.\"\"\"\n\n  def __init__(self, choices):\n    super(_OrPrecondition, self).__init__()\n    self._choices = choices\n\n  def check(self, value):\n    errors = []\n    for c in self._choices:\n      try:\n        c.check(value)\n        return\n      except PreconditionError as e:\n        errors.append(e)\n    raise PreconditionError(\n        \" or \".join(\"(%s)\" % utils.message(e) for e in errors))\n\n  def allowed_types(self):\n    allowed = set()\n    for c in self._choices:\n      allowed |= c.allowed_types()\n    return allowed\n\n\nclass CallChecker(object):\n  \"\"\"Class that performs argument checks against a collection of conditions.\"\"\"\n\n  def __init__(self, condition_pairs):\n    \"\"\"Create a checker given a sequence of (name, precondition) pairs.\"\"\"\n    self._arg_sequence = tuple(condition_pairs)\n    self._arg_map = dict(self._arg_sequence)\n\n  def check(self, *args, **kwargs):\n    \"\"\"Raise PreconditionError if the actual call is invalid.\"\"\"\n    # This check is intended to be in addition to an actual call, so an\n    # incorrect number of args or undefined kwargs should be caught elsewhere.\n    for value, pair in zip(args, self._arg_sequence):\n      name, condition = pair\n      self._check_arg(condition, name, value)\n    for name, value in kwargs.items():\n      condition = self._arg_map.get(name)\n      self._check_arg(condition, name, value)\n\n  def _check_arg(self, condition, name, value):\n    if condition:\n      try:\n        condition.check(value)\n      except PreconditionError as e:\n        raise PreconditionError(\"argument=%s: %s.\" % (name, utils.message(e)))\n\n  def allowed_types(self):\n    \"\"\"Determines the types and typenames allowed by calls to the checker.\n\n    Returns:\n      A set of types and/or typenames (strings).  A typename matches\n      only that one class while a type matches any subclass of the type.\n    \"\"\"\n    allowed = set()\n    for _, c in self._arg_sequence:\n      allowed |= c.allowed_types()\n    return allowed\n\n\n# RE to match a single token.  Leading whitepace is ignored.\n_TOKEN_RE = re.compile(\n    r\"\\s*(?:(?P<literal>[[\\]{}])|(?P<word>[a-zA-Z_]\\w*))\")\n\n# Token codes (aside from literal characters)\n_TOKEN_NAME = 1\n_TOKEN_TUPLE = 2\n_TOKEN_OR = 3\n\n_RESERVED = {\n    \"tuple\": _TOKEN_TUPLE,\n    \"or\": _TOKEN_OR,\n}\n\n\nclass _Parser(object):\n  \"\"\"A parser for precondition specifications.\"\"\"\n\n  def __init__(self, spec):\n    self._spec = spec.strip()  # Must strip trailing whitespace.\n    self._pos = 0\n    self._pending_token = None\n\n  def parse(self):\n    \"\"\"Parse the spec and return a precondition.\"\"\"\n    cond = self._parse_or()\n    self._expect(None)\n    return cond\n\n  def _peek_token(self):\n    \"\"\"Return the token code of the next token (do not consume token).\"\"\"\n    if self._pending_token is None:\n      self._pending_token = self._pop_token()\n    return self._pending_token[0]\n\n  def _pop_token(self):\n    \"\"\"Consume the next token and return (token_code, token_val).\"\"\"\n    if self._pending_token is not None:\n      result = self._pending_token\n      self._pending_token = None\n      return result\n\n    if self._pos >= len(self._spec):\n      return None, None\n    m = _TOKEN_RE.match(self._spec, self._pos)\n    if not m:\n      raise ValueError(\"Syntax Error\")\n    self._pos = m.end()\n    literal = m.group(\"literal\")\n    if literal:\n      return literal, None\n    word = m.group(\"word\")\n    t = _RESERVED.get(word)\n    if t:\n      return t, None\n    else:\n      return _TOKEN_NAME, word\n\n  def _expect(self, expected_code):\n    \"\"\"Pop the next token, raise a ValueError if the code does not match.\"\"\"\n    t, val = self._pop_token()  # pylint: disable=unpacking-non-sequence\n    if t != expected_code:\n      raise ValueError(\"Syntax Error\")\n    return val\n\n  def _parse_or(self):\n    \"\"\"Parse one or more conditions separated by \"or\".\"\"\"\n    choices = [self._parse_one()]\n    while self._peek_token() == _TOKEN_OR:\n      self._pop_token()\n      choices.append(self._parse_one())\n    if len(choices) == 1:\n      return choices[0]\n    else:\n      return _OrPrecondition(choices)\n\n  def _parse_one(self):\n    \"\"\"Parse a single condition (not including \"or\").\"\"\"\n    t, val = self._pop_token()  # pylint: disable=unpacking-non-sequence\n    if t == _TOKEN_NAME:\n      return _ClassNamePrecondition(val if val != \"None\" else \"NoneType\")\n    elif t == \"{\":\n      name = self._expect(_TOKEN_NAME)\n      self._expect(\"}\")\n      cond = _REGISTERED_CLASSES.get(name)\n      if cond is None:\n        raise ValueError(\n            \"Class '%s' is not registered for preconditions.\" % name)\n      return cond\n    elif t == _TOKEN_TUPLE:\n      self._expect(\"[\")\n      element = self._parse_or()\n      self._expect(\"]\")\n      return _TuplePrecondition(element)\n    raise ValueError(\"Syntax Error\")\n\n\ndef parse(spec):\n  \"\"\"Return a _Precondition for the given string.\"\"\"\n  return _Parser(spec).parse()\n\n\ndef parse_arg(arg_spec):\n  \"\"\"Return (name, precondition) or (name, None) for given argument spec.\"\"\"\n  name, _, spec = arg_spec.partition(\":\")\n  return name, parse(spec) if spec else None\n", "path": "pytype/pytd/parse/preconditions.py"}], "after_files": [{"content": "# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Preconditions for automatic argument checking.\"\"\"\n\nimport re\n\nfrom pytype import utils\n\n\nclass PreconditionError(ValueError):\n  pass\n\n\nclass _Precondition(object):\n  \"\"\"Base class for preconditions.\"\"\"\n\n  def check(self, value):\n    \"\"\"Raise PreconditionError if value does not match condition.\"\"\"\n    raise NotImplementedError\n\n  def allowed_types(self):\n    \"\"\"Returns a set of types or typenames that are allowed.\"\"\"\n    raise NotImplementedError\n\n\nclass _ClassNamePrecondition(_Precondition):\n  \"\"\"Precondition that expects an instance of a specific class.\"\"\"\n\n  def __init__(self, class_name):\n    super(_ClassNamePrecondition, self).__init__()\n    self._class_name = class_name\n\n  def check(self, value):\n    actual = type(value).__name__\n    if actual != self._class_name:\n      raise PreconditionError(\n          \"actual=%s, expected=%s\" % (actual, self._class_name))\n\n  def allowed_types(self):\n    return {self._class_name}\n\n\nclass _IsInstancePrecondition(_Precondition):\n  \"\"\"Precondition that expects an instance of a class or subclass.\"\"\"\n\n  def __init__(self, cls):\n    super(_IsInstancePrecondition, self).__init__()\n    self._cls = cls\n\n  def check(self, value):\n    if not isinstance(value, self._cls):\n      raise PreconditionError(\n          \"actual=%s, expected_superclass=%s\" % (\n              type(value).__name__, self._cls.__name__))\n\n  def allowed_types(self):\n    return {self._cls}\n\n\n_REGISTERED_CLASSES = {}\n\n\ndef register(cls):\n  \"\"\"Register a class object for use in {X} syntax.\"\"\"\n  name = cls.__name__\n  assert name not in _REGISTERED_CLASSES\n  _REGISTERED_CLASSES[name] = _IsInstancePrecondition(cls)\n\n\nclass _TuplePrecondition(_Precondition):\n  \"\"\"Precondition that expects a tuple.\"\"\"\n\n  def __init__(self, element_condition):\n    super(_TuplePrecondition, self).__init__()\n    self._element_condition = element_condition\n\n  def check(self, value):\n    if not isinstance(value, tuple):\n      raise PreconditionError(\n          \"actual=%s, expected=tuple\" % type(value).__name__)\n    for v in value:\n      self._element_condition.check(v)\n\n  def allowed_types(self):\n    return self._element_condition.allowed_types()\n\n\nclass _OrPrecondition(_Precondition):\n  \"\"\"Precondition that expects one of various choices to match.\"\"\"\n\n  def __init__(self, choices):\n    super(_OrPrecondition, self).__init__()\n    self._choices = choices\n\n  def check(self, value):\n    errors = []\n    for c in self._choices:\n      try:\n        c.check(value)\n        return\n      except PreconditionError as e:\n        errors.append(e)\n    raise PreconditionError(\n        \" or \".join(\"(%s)\" % utils.message(e) for e in errors))\n\n  def allowed_types(self):\n    allowed = set()\n    for c in self._choices:\n      allowed |= c.allowed_types()\n    return allowed\n\n\nclass CallChecker(object):\n  \"\"\"Class that performs argument checks against a collection of conditions.\"\"\"\n\n  def __init__(self, condition_pairs):\n    \"\"\"Create a checker given a sequence of (name, precondition) pairs.\"\"\"\n    self._arg_sequence = tuple(condition_pairs)\n    self._arg_map = dict(self._arg_sequence)\n\n  def check(self, *args, **kwargs):\n    \"\"\"Raise PreconditionError if the actual call is invalid.\"\"\"\n    # This check is intended to be in addition to an actual call, so an\n    # incorrect number of args or undefined kwargs should be caught elsewhere.\n    for value, pair in zip(args, self._arg_sequence):\n      name, condition = pair\n      self._check_arg(condition, name, value)\n    for name, value in kwargs.items():\n      condition = self._arg_map.get(name)\n      self._check_arg(condition, name, value)\n\n  def _check_arg(self, condition, name, value):\n    if condition:\n      try:\n        condition.check(value)\n      except PreconditionError as e:\n        raise PreconditionError(\"argument=%s: %s.\" % (name, utils.message(e)))\n\n  def allowed_types(self):\n    \"\"\"Determines the types and typenames allowed by calls to the checker.\n\n    Returns:\n      A set of types and/or typenames (strings).  A typename matches\n      only that one class while a type matches any subclass of the type.\n    \"\"\"\n    allowed = set()\n    for _, c in self._arg_sequence:\n      allowed |= c.allowed_types()\n    return allowed\n\n\n# RE to match a single token.  Leading whitepace is ignored.\n_TOKEN_RE = re.compile(\n    r\"\\s*(?:(?P<literal>[\\[\\]{}])|(?P<word>[a-zA-Z_]\\w*))\")\n\n# Token codes (aside from literal characters)\n_TOKEN_NAME = 1\n_TOKEN_TUPLE = 2\n_TOKEN_OR = 3\n\n_RESERVED = {\n    \"tuple\": _TOKEN_TUPLE,\n    \"or\": _TOKEN_OR,\n}\n\n\nclass _Parser(object):\n  \"\"\"A parser for precondition specifications.\"\"\"\n\n  def __init__(self, spec):\n    self._spec = spec.strip()  # Must strip trailing whitespace.\n    self._pos = 0\n    self._pending_token = None\n\n  def parse(self):\n    \"\"\"Parse the spec and return a precondition.\"\"\"\n    cond = self._parse_or()\n    self._expect(None)\n    return cond\n\n  def _peek_token(self):\n    \"\"\"Return the token code of the next token (do not consume token).\"\"\"\n    if self._pending_token is None:\n      self._pending_token = self._pop_token()\n    return self._pending_token[0]\n\n  def _pop_token(self):\n    \"\"\"Consume the next token and return (token_code, token_val).\"\"\"\n    if self._pending_token is not None:\n      result = self._pending_token\n      self._pending_token = None\n      return result\n\n    if self._pos >= len(self._spec):\n      return None, None\n    m = _TOKEN_RE.match(self._spec, self._pos)\n    if not m:\n      raise ValueError(\"Syntax Error\")\n    self._pos = m.end()\n    literal = m.group(\"literal\")\n    if literal:\n      return literal, None\n    word = m.group(\"word\")\n    t = _RESERVED.get(word)\n    if t:\n      return t, None\n    else:\n      return _TOKEN_NAME, word\n\n  def _expect(self, expected_code):\n    \"\"\"Pop the next token, raise a ValueError if the code does not match.\"\"\"\n    t, val = self._pop_token()  # pylint: disable=unpacking-non-sequence\n    if t != expected_code:\n      raise ValueError(\"Syntax Error\")\n    return val\n\n  def _parse_or(self):\n    \"\"\"Parse one or more conditions separated by \"or\".\"\"\"\n    choices = [self._parse_one()]\n    while self._peek_token() == _TOKEN_OR:\n      self._pop_token()\n      choices.append(self._parse_one())\n    if len(choices) == 1:\n      return choices[0]\n    else:\n      return _OrPrecondition(choices)\n\n  def _parse_one(self):\n    \"\"\"Parse a single condition (not including \"or\").\"\"\"\n    t, val = self._pop_token()  # pylint: disable=unpacking-non-sequence\n    if t == _TOKEN_NAME:\n      return _ClassNamePrecondition(val if val != \"None\" else \"NoneType\")\n    elif t == \"{\":\n      name = self._expect(_TOKEN_NAME)\n      self._expect(\"}\")\n      cond = _REGISTERED_CLASSES.get(name)\n      if cond is None:\n        raise ValueError(\n            \"Class '%s' is not registered for preconditions.\" % name)\n      return cond\n    elif t == _TOKEN_TUPLE:\n      self._expect(\"[\")\n      element = self._parse_or()\n      self._expect(\"]\")\n      return _TuplePrecondition(element)\n    raise ValueError(\"Syntax Error\")\n\n\ndef parse(spec):\n  \"\"\"Return a _Precondition for the given string.\"\"\"\n  return _Parser(spec).parse()\n\n\ndef parse_arg(arg_spec):\n  \"\"\"Return (name, precondition) or (name, None) for given argument spec.\"\"\"\n  name, _, spec = arg_spec.partition(\":\")\n  return name, parse(spec) if spec else None\n", "path": "pytype/pytd/parse/preconditions.py"}]}