grammar.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. import hashlib
  2. import os
  3. from typing import Generic, TypeVar, Union, Dict, Optional, Any, Iterator
  4. from pathlib import Path
  5. from parso._compatibility import is_pypy
  6. from parso.pgen2 import generate_grammar
  7. from parso.utils import split_lines, python_bytes_to_unicode, \
  8. PythonVersionInfo, parse_version_string
  9. from parso.python.diff import DiffParser
  10. from parso.python.tokenize import tokenize_lines, tokenize, PythonToken
  11. from parso.python.token import PythonTokenTypes
  12. from parso.cache import parser_cache, load_module, try_to_save_module
  13. from parso.parser import BaseParser
  14. from parso.python.parser import Parser as PythonParser
  15. from parso.python.errors import ErrorFinderConfig
  16. from parso.python import pep8
  17. from parso.file_io import FileIO, KnownContentFileIO
  18. from parso.normalizer import RefactoringNormalizer, NormalizerConfig
  19. _loaded_grammars: Dict[str, 'Grammar'] = {}
  20. _NodeT = TypeVar("_NodeT")
  21. class Grammar(Generic[_NodeT]):
  22. """
  23. :py:func:`parso.load_grammar` returns instances of this class.
  24. Creating custom none-python grammars by calling this is not supported, yet.
  25. :param text: A BNF representation of your grammar.
  26. """
  27. _start_nonterminal: str
  28. _error_normalizer_config: Optional[ErrorFinderConfig] = None
  29. _token_namespace: Any = None
  30. _default_normalizer_config: NormalizerConfig = pep8.PEP8NormalizerConfig()
  31. def __init__(self, text: str, *, tokenizer, parser=BaseParser, diff_parser=None):
  32. self._pgen_grammar = generate_grammar(
  33. text,
  34. token_namespace=self._get_token_namespace()
  35. )
  36. self._parser = parser
  37. self._tokenizer = tokenizer
  38. self._diff_parser = diff_parser
  39. self._hashed = hashlib.sha256(text.encode("utf-8")).hexdigest()
  40. def parse(self,
  41. code: Union[str, bytes] = None,
  42. *,
  43. error_recovery=True,
  44. path: Union[os.PathLike, str] = None,
  45. start_symbol: str = None,
  46. cache=False,
  47. diff_cache=False,
  48. cache_path: Union[os.PathLike, str] = None,
  49. file_io: FileIO = None) -> _NodeT:
  50. """
  51. If you want to parse a Python file you want to start here, most likely.
  52. If you need finer grained control over the parsed instance, there will be
  53. other ways to access it.
  54. :param str code: A unicode or bytes string. When it's not possible to
  55. decode bytes to a string, returns a
  56. :py:class:`UnicodeDecodeError`.
  57. :param bool error_recovery: If enabled, any code will be returned. If
  58. it is invalid, it will be returned as an error node. If disabled,
  59. you will get a ParseError when encountering syntax errors in your
  60. code.
  61. :param str start_symbol: The grammar rule (nonterminal) that you want
  62. to parse. Only allowed to be used when error_recovery is False.
  63. :param str path: The path to the file you want to open. Only needed for caching.
  64. :param bool cache: Keeps a copy of the parser tree in RAM and on disk
  65. if a path is given. Returns the cached trees if the corresponding
  66. files on disk have not changed. Note that this stores pickle files
  67. on your file system (e.g. for Linux in ``~/.cache/parso/``).
  68. :param bool diff_cache: Diffs the cached python module against the new
  69. code and tries to parse only the parts that have changed. Returns
  70. the same (changed) module that is found in cache. Using this option
  71. requires you to not do anything anymore with the cached modules
  72. under that path, because the contents of it might change. This
  73. option is still somewhat experimental. If you want stability,
  74. please don't use it.
  75. :param bool cache_path: If given saves the parso cache in this
  76. directory. If not given, defaults to the default cache places on
  77. each platform.
  78. :return: A subclass of :py:class:`parso.tree.NodeOrLeaf`. Typically a
  79. :py:class:`parso.python.tree.Module`.
  80. """
  81. if code is None and path is None and file_io is None:
  82. raise TypeError("Please provide either code or a path.")
  83. if isinstance(path, str):
  84. path = Path(path)
  85. if isinstance(cache_path, str):
  86. cache_path = Path(cache_path)
  87. if start_symbol is None:
  88. start_symbol = self._start_nonterminal
  89. if error_recovery and start_symbol != 'file_input':
  90. raise NotImplementedError("This is currently not implemented.")
  91. if file_io is None:
  92. if code is None:
  93. file_io = FileIO(path) # type: ignore[arg-type]
  94. else:
  95. file_io = KnownContentFileIO(path, code)
  96. if cache and file_io.path is not None:
  97. module_node = load_module(self._hashed, file_io, cache_path=cache_path)
  98. if module_node is not None:
  99. return module_node # type: ignore[no-any-return]
  100. if code is None:
  101. code = file_io.read()
  102. code = python_bytes_to_unicode(code)
  103. lines = split_lines(code, keepends=True)
  104. if diff_cache:
  105. if self._diff_parser is None:
  106. raise TypeError("You have to define a diff parser to be able "
  107. "to use this option.")
  108. try:
  109. module_cache_item = parser_cache[self._hashed][file_io.path]
  110. except KeyError:
  111. pass
  112. else:
  113. module_node = module_cache_item.node
  114. old_lines = module_cache_item.lines
  115. if old_lines == lines:
  116. return module_node # type: ignore[no-any-return]
  117. new_node = self._diff_parser(
  118. self._pgen_grammar, self._tokenizer, module_node
  119. ).update(
  120. old_lines=old_lines,
  121. new_lines=lines
  122. )
  123. try_to_save_module(self._hashed, file_io, new_node, lines,
  124. # Never pickle in pypy, it's slow as hell.
  125. pickling=cache and not is_pypy,
  126. cache_path=cache_path)
  127. return new_node # type: ignore[no-any-return]
  128. tokens = self._tokenizer(lines)
  129. p = self._parser(
  130. self._pgen_grammar,
  131. error_recovery=error_recovery,
  132. start_nonterminal=start_symbol
  133. )
  134. root_node = p.parse(tokens=tokens)
  135. if cache or diff_cache:
  136. try_to_save_module(self._hashed, file_io, root_node, lines,
  137. # Never pickle in pypy, it's slow as hell.
  138. pickling=cache and not is_pypy,
  139. cache_path=cache_path)
  140. return root_node # type: ignore[no-any-return]
  141. def _get_token_namespace(self):
  142. ns = self._token_namespace
  143. if ns is None:
  144. raise ValueError("The token namespace should be set.")
  145. return ns
  146. def iter_errors(self, node):
  147. """
  148. Given a :py:class:`parso.tree.NodeOrLeaf` returns a generator of
  149. :py:class:`parso.normalizer.Issue` objects. For Python this is
  150. a list of syntax/indentation errors.
  151. """
  152. if self._error_normalizer_config is None:
  153. raise ValueError("No error normalizer specified for this grammar.")
  154. return self._get_normalizer_issues(node, self._error_normalizer_config)
  155. def refactor(self, base_node, node_to_str_map):
  156. return RefactoringNormalizer(node_to_str_map).walk(base_node)
  157. def _get_normalizer(self, normalizer_config):
  158. if normalizer_config is None:
  159. normalizer_config = self._default_normalizer_config
  160. if normalizer_config is None:
  161. raise ValueError("You need to specify a normalizer, because "
  162. "there's no default normalizer for this tree.")
  163. return normalizer_config.create_normalizer(self)
  164. def _normalize(self, node, normalizer_config=None):
  165. """
  166. TODO this is not public, yet.
  167. The returned code will be normalized, e.g. PEP8 for Python.
  168. """
  169. normalizer = self._get_normalizer(normalizer_config)
  170. return normalizer.walk(node)
  171. def _get_normalizer_issues(self, node, normalizer_config=None):
  172. normalizer = self._get_normalizer(normalizer_config)
  173. normalizer.walk(node)
  174. return normalizer.issues
  175. def __repr__(self):
  176. nonterminals = self._pgen_grammar.nonterminal_to_dfas.keys()
  177. txt = ' '.join(list(nonterminals)[:3]) + ' ...'
  178. return '<%s:%s>' % (self.__class__.__name__, txt)
  179. class PythonGrammar(Grammar):
  180. _error_normalizer_config = ErrorFinderConfig()
  181. _token_namespace = PythonTokenTypes
  182. _start_nonterminal = 'file_input'
  183. def __init__(self, version_info: PythonVersionInfo, bnf_text: str):
  184. super().__init__(
  185. bnf_text,
  186. tokenizer=self._tokenize_lines,
  187. parser=PythonParser,
  188. diff_parser=DiffParser
  189. )
  190. self.version_info = version_info
  191. def _tokenize_lines(self, lines, **kwargs) -> Iterator[PythonToken]:
  192. return tokenize_lines(lines, version_info=self.version_info, **kwargs)
  193. def _tokenize(self, code):
  194. # Used by Jedi.
  195. return tokenize(code, version_info=self.version_info)
  196. def load_grammar(*, version: str = None, path: str = None):
  197. """
  198. Loads a :py:class:`parso.Grammar`. The default version is the current Python
  199. version.
  200. :param str version: A python version string, e.g. ``version='3.8'``.
  201. :param str path: A path to a grammar file
  202. """
  203. # NOTE: this (3, 14) should be updated to the latest version parso supports.
  204. # (if this doesn't happen, users will get older syntaxes and spurious warnings)
  205. passed_version_info = parse_version_string(version)
  206. version_info = min(passed_version_info, PythonVersionInfo(3, 14))
  207. # # NOTE: this is commented out until parso properly supports newer Python grammars.
  208. # if passed_version_info != version_info:
  209. # warnings.warn('parso does not support %s.%s yet.' % (
  210. # passed_version_info.major, passed_version_info.minor
  211. # ))
  212. file = path or os.path.join(
  213. 'python',
  214. 'grammar%s%s.txt' % (version_info.major, version_info.minor)
  215. )
  216. path = os.path.join(os.path.dirname(__file__), file)
  217. try:
  218. return _loaded_grammars[path]
  219. except KeyError:
  220. try:
  221. with open(path) as f:
  222. bnf_text = f.read()
  223. grammar = PythonGrammar(version_info, bnf_text)
  224. return _loaded_grammars.setdefault(path, grammar)
  225. except FileNotFoundError:
  226. message = "Python version %s.%s is currently not supported." % (
  227. version_info.major, version_info.minor
  228. )
  229. raise NotImplementedError(message)