|
| 1 | +/* |
| 2 | + * Copyright 2019 The Starlark in Rust Authors. |
| 3 | + * Copyright (c) Facebook, Inc. and its affiliates. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +use std::convert::Infallible; |
| 19 | + |
| 20 | +use crate::typing::Ty; |
| 21 | +use crate::typing::TyStarlarkValue; |
| 22 | +use crate::values::type_repr::StarlarkTypeRepr; |
| 23 | +use crate::values::typing::ty::AbstractType; |
| 24 | +use crate::values::UnpackValue; |
| 25 | +use crate::values::Value; |
| 26 | + |
| 27 | +/// Represent a type of type. (For example, an expression `int` is valid for this type.) |
| 28 | +pub struct TypeType(()); |
| 29 | + |
| 30 | +impl StarlarkTypeRepr for TypeType { |
| 31 | + type Canonical = AbstractType; |
| 32 | + |
| 33 | + fn starlark_type_repr() -> Ty { |
| 34 | + <Self::Canonical as StarlarkTypeRepr>::starlark_type_repr() |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +/// Validate the value is type. |
| 39 | +impl<'v> UnpackValue<'v> for TypeType { |
| 40 | + type Error = Infallible; |
| 41 | + |
| 42 | + fn unpack_value_impl(value: Value<'v>) -> Result<Option<Self>, Self::Error> { |
| 43 | + if TyStarlarkValue::is_type_from_vtable(&value.vtable().starlark_value) { |
| 44 | + Ok(Some(TypeType(()))) |
| 45 | + } else { |
| 46 | + Ok(None) |
| 47 | + } |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +#[cfg(test)] |
| 52 | +mod tests { |
| 53 | + use starlark_derive::starlark_module; |
| 54 | + |
| 55 | + use crate as starlark; |
| 56 | + use crate::assert::Assert; |
| 57 | + use crate::environment::GlobalsBuilder; |
| 58 | + use crate::values::none::NoneType; |
| 59 | + use crate::values::typing::type_type::TypeType; |
| 60 | + |
| 61 | + #[test] |
| 62 | + fn test() { |
| 63 | + #[starlark_module] |
| 64 | + fn module(globals: &mut GlobalsBuilder) { |
| 65 | + fn takes_type(#[starlark(require = pos)] _t: TypeType) -> anyhow::Result<NoneType> { |
| 66 | + Ok(NoneType) |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + let mut a = Assert::new(); |
| 71 | + a.globals_add(module); |
| 72 | + a.pass("takes_type(int)"); |
| 73 | + a.pass("takes_type(list[str] | None)"); |
| 74 | + a.fail( |
| 75 | + "takes_type(1)", |
| 76 | + "Type of parameter `_t` doesn't match, expected `type`,", |
| 77 | + ); |
| 78 | + } |
| 79 | +} |
0 commit comments