Skip to main content

ruff_python_parser/parser/
options.rs

1use ruff_python_ast::{PySourceType, PythonVersion};
2
3use crate::{AsMode, Mode};
4
5/// Options for controlling how a source file is parsed.
6///
7/// You can construct a [`ParseOptions`] directly from a [`Mode`]:
8///
9/// ```
10/// use ruff_python_parser::{Mode, ParseOptions};
11///
12/// let options = ParseOptions::from(Mode::Module);
13/// ```
14///
15/// or from a [`PySourceType`]
16///
17/// ```
18/// use ruff_python_ast::PySourceType;
19/// use ruff_python_parser::ParseOptions;
20///
21/// let options = ParseOptions::from(PySourceType::Python);
22/// ```
23#[derive(Clone, Debug)]
24pub struct ParseOptions {
25    /// Specify the mode in which the code will be parsed.
26    pub(crate) mode: Mode,
27    /// Target version for detecting version-related syntax errors.
28    pub(crate) target_version: PythonVersion,
29}
30
31impl ParseOptions {
32    #[must_use]
33    pub fn with_target_version(mut self, target_version: PythonVersion) -> Self {
34        self.target_version = target_version;
35        self
36    }
37
38    pub fn target_version(&self) -> PythonVersion {
39        self.target_version
40    }
41}
42
43impl From<Mode> for ParseOptions {
44    fn from(mode: Mode) -> Self {
45        Self {
46            mode,
47            target_version: PythonVersion::default(),
48        }
49    }
50}
51
52impl From<PySourceType> for ParseOptions {
53    fn from(source_type: PySourceType) -> Self {
54        Self {
55            mode: source_type.as_mode(),
56            target_version: PythonVersion::default(),
57        }
58    }
59}