-
Notifications
You must be signed in to change notification settings - Fork 252
/
union.rs
403 lines (364 loc) · 14.2 KB
/
union.rs
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use std::borrow::Cow;
use std::fmt::Write;
use pyo3::intern;
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList, PyString};
use ahash::AHashMap;
use crate::build_tools::{is_strict, schema_or_config, SchemaDict};
use crate::errors::{ErrorType, ValError, ValLineError, ValResult};
use crate::input::{GenericMapping, Input};
use crate::lookup_key::LookupKey;
use crate::questions::Question;
use crate::recursion_guard::RecursionGuard;
use super::custom_error::CustomError;
use super::{build_validator, BuildContext, BuildValidator, CombinedValidator, Extra, Validator};
#[derive(Debug, Clone)]
pub struct UnionValidator {
choices: Vec<CombinedValidator>,
custom_error: Option<CustomError>,
strict: bool,
name: String,
}
impl BuildValidator for UnionValidator {
const EXPECTED_TYPE: &'static str = "union";
fn build(
schema: &PyDict,
config: Option<&PyDict>,
build_context: &mut BuildContext,
) -> PyResult<CombinedValidator> {
let py = schema.py();
let choices: Vec<CombinedValidator> = schema
.get_as_req::<&PyList>(intern!(py, "choices"))?
.iter()
.map(|choice| build_validator(choice, config, build_context))
.collect::<PyResult<Vec<CombinedValidator>>>()?;
let descr = choices.iter().map(|v| v.get_name()).collect::<Vec<_>>().join(",");
Ok(Self {
choices,
custom_error: CustomError::build(schema)?,
strict: is_strict(schema, config)?,
name: format!("{}[{descr}]", Self::EXPECTED_TYPE),
}
.into())
}
}
impl UnionValidator {
fn or_custom_error<'s, 'data>(
&'s self,
errors: Option<Vec<ValLineError<'data>>>,
input: &'data impl Input<'data>,
) -> ValError<'data> {
if let Some(errors) = errors {
ValError::LineErrors(errors)
} else {
self.custom_error.as_ref().unwrap().as_val_error(input)
}
}
}
impl Validator for UnionValidator {
fn validate<'s, 'data>(
&'s self,
py: Python<'data>,
input: &'data impl Input<'data>,
extra: &Extra,
slots: &'data [CombinedValidator],
recursion_guard: &'s mut RecursionGuard,
) -> ValResult<'data, PyObject> {
if extra.strict.unwrap_or(self.strict) {
let mut errors: Option<Vec<ValLineError>> = match self.custom_error {
None => Some(Vec::with_capacity(self.choices.len())),
_ => None,
};
let strict_extra = extra.as_strict();
for validator in &self.choices {
let line_errors = match validator.validate(py, input, &strict_extra, slots, recursion_guard) {
Err(ValError::LineErrors(line_errors)) => line_errors,
otherwise => return otherwise,
};
if let Some(ref mut errors) = errors {
errors.extend(
line_errors
.into_iter()
.map(|err| err.with_outer_location(validator.get_name().into())),
);
}
}
Err(self.or_custom_error(errors, input))
} else {
// 1st pass: check if the value is an exact instance of one of the Union types,
// e.g. use validate in strict mode
let strict_extra = extra.as_strict();
if let Some(res) = self
.choices
.iter()
.map(|validator| validator.validate(py, input, &strict_extra, slots, recursion_guard))
.find(ValResult::is_ok)
{
return res;
}
let mut errors: Option<Vec<ValLineError>> = match self.custom_error {
None => Some(Vec::with_capacity(self.choices.len())),
_ => None,
};
// 2nd pass: check if the value can be coerced into one of the Union types, e.g. use validate
for validator in &self.choices {
let line_errors = match validator.validate(py, input, extra, slots, recursion_guard) {
Err(ValError::LineErrors(line_errors)) => line_errors,
success => return success,
};
if let Some(ref mut errors) = errors {
errors.extend(
line_errors
.into_iter()
.map(|err| err.with_outer_location(validator.get_name().into())),
);
}
}
Err(self.or_custom_error(errors, input))
}
}
fn get_name(&self) -> &str {
&self.name
}
fn ask(&self, question: &Question) -> bool {
self.choices.iter().all(|v| v.ask(question))
}
fn complete(&mut self, build_context: &BuildContext) -> PyResult<()> {
self.choices.iter_mut().try_for_each(|v| v.complete(build_context))
}
}
#[derive(Debug, Clone)]
enum Discriminator {
/// use `LookupKey` to find the tag, same as we do to find values in typed_dict aliases
LookupKey(LookupKey),
/// call a function to find the tag to use
Function(PyObject),
/// Custom discriminator specifically for the root `Schema` union in self-schema
SelfSchema,
}
impl Discriminator {
fn new(py: Python, raw: &PyAny) -> PyResult<Self> {
if raw.is_callable() {
return Ok(Self::Function(raw.to_object(py)));
} else if let Ok(py_str) = raw.cast_as::<PyString>() {
if py_str.to_str()? == "self-schema-discriminator" {
return Ok(Self::SelfSchema);
}
}
let lookup_key = LookupKey::from_py(py, raw, None)?;
Ok(Self::LookupKey(lookup_key))
}
fn to_string_py(&self, py: Python) -> PyResult<String> {
match self {
Self::Function(f) => Ok(format!("{}()", f.getattr(py, "__name__")?)),
Self::LookupKey(lookup_key) => Ok(lookup_key.to_string()),
Self::SelfSchema => Ok("self-schema".to_string()),
}
}
}
#[derive(Debug, Clone)]
pub struct TaggedUnionValidator {
choices: AHashMap<String, CombinedValidator>,
discriminator: Discriminator,
from_attributes: bool,
strict: bool,
custom_error: Option<CustomError>,
tags_repr: String,
discriminator_repr: String,
name: String,
}
impl BuildValidator for TaggedUnionValidator {
const EXPECTED_TYPE: &'static str = "tagged-union";
fn build(
schema: &PyDict,
config: Option<&PyDict>,
build_context: &mut BuildContext,
) -> PyResult<CombinedValidator> {
let py = schema.py();
let discriminator = Discriminator::new(py, schema.get_as_req(intern!(py, "discriminator"))?)?;
let discriminator_repr = discriminator.to_string_py(py)?;
let mut choices = AHashMap::new();
let mut first = true;
let mut tags_repr = String::with_capacity(50);
let mut descr = String::with_capacity(50);
for item in schema.get_as_req::<&PyDict>(intern!(py, "choices"))?.items().iter() {
let tag: String = item.get_item(0)?.extract()?;
let value = item.get_item(1)?;
let validator = build_validator(value, config, build_context)?;
if first {
first = false;
write!(tags_repr, "'{tag}'").unwrap();
descr.push_str(validator.get_name());
} else {
write!(tags_repr, ", '{tag}'").unwrap();
// no spaces in get_name() output to make loc easy to read
write!(descr, ",{}", validator.get_name()).unwrap();
}
choices.insert(tag, validator);
}
let key = intern!(py, "from_attributes");
let from_attributes = schema_or_config(schema, config, key, key)?.unwrap_or(false);
Ok(Self {
choices,
discriminator,
from_attributes,
strict: is_strict(schema, config)?,
custom_error: CustomError::build(schema)?,
tags_repr,
discriminator_repr,
name: format!("{}[{descr}]", Self::EXPECTED_TYPE),
}
.into())
}
}
impl Validator for TaggedUnionValidator {
fn validate<'s, 'data>(
&'s self,
py: Python<'data>,
input: &'data impl Input<'data>,
extra: &Extra,
slots: &'data [CombinedValidator],
recursion_guard: &'s mut RecursionGuard,
) -> ValResult<'data, PyObject> {
match self.discriminator {
Discriminator::LookupKey(ref lookup_key) => {
macro_rules! find_validator {
($dict:ident, $get_method:ident) => {{
// note all these methods return PyResult<Option<(data, data)>>, the outer Err is just for
// errors when getting attributes which should be "raised"
match lookup_key.$get_method($dict)? {
Some((_, value)) => {
if self.strict {
value.strict_str()
} else {
value.lax_str()
}
}
None => Err(self.tag_not_found(input)),
}
}};
}
let dict = input.validate_typed_dict(self.strict, self.from_attributes)?;
let tag = match dict {
GenericMapping::PyDict(dict) => find_validator!(dict, py_get_item),
GenericMapping::PyGetAttr(obj) => find_validator!(obj, py_get_attr),
GenericMapping::JsonObject(mapping) => find_validator!(mapping, json_get),
}?;
self.find_call_validator(py, tag.as_cow()?, input, extra, slots, recursion_guard)
}
Discriminator::Function(ref func) => {
let tag = func.call1(py, (input.to_object(py),))?;
if tag.is_none(py) {
Err(self.tag_not_found(input))
} else {
let tag: &PyString = tag.cast_as(py)?;
self.find_call_validator(py, tag.to_string_lossy(), input, extra, slots, recursion_guard)
}
}
Discriminator::SelfSchema => self.find_call_validator(
py,
self.self_schema_tag(py, input)?,
input,
extra,
slots,
recursion_guard,
),
}
}
fn get_name(&self) -> &str {
&self.name
}
fn ask(&self, question: &Question) -> bool {
self.choices.values().all(|v| v.ask(question))
}
fn complete(&mut self, build_context: &BuildContext) -> PyResult<()> {
self.choices
.iter_mut()
.try_for_each(|(_, validator)| validator.complete(build_context))
}
}
impl TaggedUnionValidator {
fn self_schema_tag<'s, 'data>(
&'s self,
py: Python<'data>,
input: &'data impl Input<'data>,
) -> ValResult<'data, Cow<'data, str>> {
let dict = input.strict_dict()?;
let either_tag = match dict {
GenericMapping::PyDict(dict) => match dict.get_item(intern!(py, "type")) {
Some(t) => t.strict_str()?,
None => return Err(self.tag_not_found(input)),
},
_ => unreachable!(),
};
let tag_cow = either_tag.as_cow()?;
let tag = tag_cow.as_ref();
// custom logic to distinguish between different function and tuple schemas
if tag == "function" || tag == "tuple" {
let mode = match dict {
GenericMapping::PyDict(dict) => match dict.get_item(intern!(py, "mode")) {
Some(m) => Some(m.strict_str()?),
None => None,
},
_ => unreachable!(),
};
if tag == "function" {
let mode = mode.ok_or_else(|| self.tag_not_found(input))?;
match mode.as_cow()?.as_ref() {
"plain" => Ok(Cow::Borrowed("function-plain")),
"wrap" => Ok(Cow::Borrowed("function-wrap")),
_ => Ok(Cow::Borrowed("function")),
}
} else {
// tag == "tuple"
if let Some(mode) = mode {
if mode.as_cow()?.as_ref() == "positional" {
return Ok(Cow::Borrowed("tuple-positional"));
}
}
Ok(Cow::Borrowed("tuple-variable"))
}
} else {
Ok(Cow::Owned(tag.to_string()))
}
}
fn find_call_validator<'s, 'data>(
&'s self,
py: Python<'data>,
tag: Cow<str>,
input: &'data impl Input<'data>,
extra: &Extra,
slots: &'data [CombinedValidator],
recursion_guard: &'s mut RecursionGuard,
) -> ValResult<'data, PyObject> {
if let Some(validator) = self.choices.get(tag.as_ref()) {
match validator.validate(py, input, extra, slots, recursion_guard) {
Ok(res) => Ok(res),
Err(err) => Err(err.with_outer_location(tag.as_ref().into())),
}
} else {
match self.custom_error {
Some(ref custom_error) => Err(custom_error.as_val_error(input)),
None => Err(ValError::new(
ErrorType::UnionTagInvalid {
discriminator: self.discriminator_repr.clone(),
tag: tag.to_string(),
expected_tags: self.tags_repr.clone(),
},
input,
)),
}
}
}
fn tag_not_found<'s, 'data>(&'s self, input: &'data impl Input<'data>) -> ValError<'data> {
match self.custom_error {
Some(ref custom_error) => custom_error.as_val_error(input),
None => ValError::new(
ErrorType::UnionTagNotFound {
discriminator: self.discriminator_repr.clone(),
},
input,
),
}
}
}