1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
// Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree

use crate::{
    nodes::expression::{DeflatedLeftParen, DeflatedRightParen},
    nodes::op::DeflatedComma,
    tokenizer::whitespace_parser::{Config, WhitespaceError},
    Codegen, CodegenState, EmptyLine, LeftParen, RightParen,
};
use std::ops::Deref;

pub trait WithComma<'r, 'a> {
    fn with_comma(self, comma: DeflatedComma<'r, 'a>) -> Self;
}

pub trait ParenthesizedNode<'a> {
    fn lpar(&self) -> &Vec<LeftParen<'a>>;
    fn rpar(&self) -> &Vec<RightParen<'a>>;

    fn parenthesize<F>(&self, state: &mut CodegenState<'a>, f: F)
    where
        F: FnOnce(&mut CodegenState<'a>),
    {
        for lpar in self.lpar() {
            lpar.codegen(state);
        }
        f(state);
        for rpar in self.rpar() {
            rpar.codegen(state);
        }
    }

    fn with_parens(self, left: LeftParen<'a>, right: RightParen<'a>) -> Self;
}

impl<'a, T: ParenthesizedNode<'a>> ParenthesizedNode<'a> for Box<T> {
    fn lpar(&self) -> &Vec<LeftParen<'a>> {
        self.deref().lpar()
    }
    fn rpar(&self) -> &Vec<RightParen<'a>> {
        self.deref().rpar()
    }
    fn parenthesize<F>(&self, state: &mut CodegenState<'a>, f: F)
    where
        F: FnOnce(&mut CodegenState<'a>),
    {
        self.deref().parenthesize(state, f)
    }
    fn with_parens(self, left: LeftParen<'a>, right: RightParen<'a>) -> Self {
        Self::new((*self).with_parens(left, right))
    }
}

pub trait ParenthesizedDeflatedNode<'r, 'a> {
    fn lpar(&self) -> &Vec<DeflatedLeftParen<'r, 'a>>;
    fn rpar(&self) -> &Vec<DeflatedRightParen<'r, 'a>>;

    fn with_parens(
        self,
        left: DeflatedLeftParen<'r, 'a>,
        right: DeflatedRightParen<'r, 'a>,
    ) -> Self;
}
impl<'r, 'a, T: ParenthesizedDeflatedNode<'r, 'a>> ParenthesizedDeflatedNode<'r, 'a> for Box<T> {
    fn lpar(&self) -> &Vec<DeflatedLeftParen<'r, 'a>> {
        self.deref().lpar()
    }
    fn rpar(&self) -> &Vec<DeflatedRightParen<'r, 'a>> {
        self.deref().rpar()
    }
    fn with_parens(
        self,
        left: DeflatedLeftParen<'r, 'a>,
        right: DeflatedRightParen<'r, 'a>,
    ) -> Self {
        Self::new((*self).with_parens(left, right))
    }
}

pub trait WithLeadingLines<'a> {
    fn leading_lines(&mut self) -> &mut Vec<EmptyLine<'a>>;
}

pub type Result<T> = std::result::Result<T, WhitespaceError>;

pub trait Inflate<'a>
where
    Self: Sized,
{
    type Inflated;
    fn inflate(self, config: &Config<'a>) -> Result<Self::Inflated>;
}

impl<'a, T: Inflate<'a>> Inflate<'a> for Option<T> {
    type Inflated = Option<T::Inflated>;
    fn inflate(self, config: &Config<'a>) -> Result<Self::Inflated> {
        self.map(|x| x.inflate(config)).transpose()
    }
}

impl<'a, T: Inflate<'a> + ?Sized> Inflate<'a> for Box<T> {
    type Inflated = Box<T::Inflated>;
    fn inflate(self, config: &Config<'a>) -> Result<Self::Inflated> {
        match (*self).inflate(config) {
            Ok(a) => Ok(Box::new(a)),
            Err(e) => Err(e),
        }
    }
}

impl<'a, T: Inflate<'a>> Inflate<'a> for Vec<T> {
    type Inflated = Vec<T::Inflated>;
    fn inflate(self, config: &Config<'a>) -> Result<Self::Inflated> {
        self.into_iter().map(|item| item.inflate(config)).collect()
    }
}
#[cfg(feature = "py")]
pub mod py {
    use pyo3::{types::PyAny, types::PyTuple, IntoPy, PyObject, PyResult, Python};

    // TODO: replace with upstream implementation once
    // https://github.com/PyO3/pyo3/issues/1813 is resolved
    pub trait TryIntoPy<T>: Sized {
        fn try_into_py(self, py: Python) -> PyResult<T>;
    }

    // I wish:
    // impl<PyT, T: IntoPy<PyT>> TryIntoPy<PyT> for T {
    //     fn try_into_py(self, py: Python) -> PyResult<PyT> {
    //         Ok(self.into_py(py))
    //     }
    // }

    impl TryIntoPy<PyObject> for bool {
        fn try_into_py(self, py: Python) -> PyResult<PyObject> {
            Ok(self.into_py(py))
        }
    }

    impl<T: TryIntoPy<PyObject>> TryIntoPy<PyObject> for Box<T>
    where
        T: TryIntoPy<PyObject>,
    {
        fn try_into_py(self, py: Python) -> PyResult<PyObject> {
            (*self).try_into_py(py)
        }
    }

    impl<T> TryIntoPy<PyObject> for Option<T>
    where
        T: TryIntoPy<PyObject>,
    {
        fn try_into_py(self, py: Python) -> PyResult<PyObject> {
            Ok(match self {
                None => py.None(),
                Some(x) => x.try_into_py(py)?,
            })
        }
    }

    impl<T> TryIntoPy<PyObject> for Vec<T>
    where
        T: TryIntoPy<PyObject>,
    {
        fn try_into_py(self, py: Python) -> PyResult<PyObject> {
            let converted = self
                .into_iter()
                .map(|x| x.try_into_py(py))
                .collect::<PyResult<Vec<_>>>()?
                .into_iter();
            Ok(PyTuple::new(py, converted).into())
        }
    }

    impl TryIntoPy<PyObject> for PyTuple {
        fn try_into_py(self, py: Python) -> PyResult<PyObject> {
            Ok(self.into_py(py))
        }
    }

    impl<'a> TryIntoPy<PyObject> for &'a str {
        fn try_into_py(self, py: Python) -> PyResult<PyObject> {
            Ok(self.into_py(py))
        }
    }

    impl<T> TryIntoPy<PyObject> for &'_ T
    where
        T: AsRef<PyAny>,
    {
        fn try_into_py(self, py: Python) -> PyResult<PyObject> {
            Ok(self.into_py(py))
        }
    }
}