starlark/values/
type_repr.rs

1/*
2 * Copyright 2018 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//! Trait and default implementations of a trait that will show starlark type annotations for a
19//! given type.
20
21use std::marker::PhantomData;
22
23use either::Either;
24pub use starlark_derive::StarlarkTypeRepr;
25
26use crate::typing::Ty;
27use crate::values::list::ListType;
28use crate::values::none::NoneType;
29use crate::values::string::str_type::StarlarkStr;
30use crate::values::Heap;
31use crate::values::StarlarkValue;
32use crate::values::Value;
33
34/// Provides a starlark type representation, even if StarlarkValue is not implemented.
35///
36/// # Derive
37///
38/// There is `#[derive(StarlarkTypeRepr)]` for enums, for example:
39///
40/// ```
41/// use starlark::values::type_repr::StarlarkTypeRepr;
42///
43/// #[derive(StarlarkTypeRepr)]
44/// enum IntOrString {
45///     Int(i32),
46///     String(String),
47/// }
48/// ```
49///
50/// It emits type `int | str`.
51///
52/// This derive is useful in combination with derive of [`UnpackValue`](crate::values::UnpackValue).
53pub trait StarlarkTypeRepr {
54    /// Different Rust type representing the same Starlark Type.
55    ///
56    /// For example, `bool` and `StarlarkBool` Rust types represent the same Starlark type `bool`.
57    ///
58    /// Formal requirement: `Self::starlark_type_repr() == Self::Canonical::starlark_type_repr()`.
59    ///
60    /// If unsure, it is safe to put `= Self` here.
61    /// When [`associated_type_defaults`](https://github.com/rust-lang/rust/issues/29661)
62    /// is stabilized, this will be the default.
63    type Canonical: StarlarkTypeRepr;
64
65    /// The representation of a type that a user would use verbatim in starlark type annotations
66    fn starlark_type_repr() -> Ty;
67}
68
69/// A set used just for display purposes.
70///
71/// `SetOf` requires `Unpack` to be implemented, and `Set` does not take type parameters so
72/// we need something for documentation generation.
73pub struct SetType<T: StarlarkTypeRepr> {
74    t: PhantomData<T>,
75}
76
77impl<T: StarlarkTypeRepr> StarlarkTypeRepr for SetType<T> {
78    type Canonical = SetType<T::Canonical>;
79
80    fn starlark_type_repr() -> Ty {
81        Ty::set(T::starlark_type_repr())
82    }
83}
84
85impl<'v, T: StarlarkValue<'v>> StarlarkTypeRepr for T {
86    type Canonical = Self;
87
88    fn starlark_type_repr() -> Ty {
89        Self::get_type_starlark_repr()
90    }
91}
92
93impl StarlarkTypeRepr for String {
94    type Canonical = StarlarkStr;
95
96    fn starlark_type_repr() -> Ty {
97        StarlarkStr::starlark_type_repr()
98    }
99}
100
101impl StarlarkTypeRepr for &str {
102    type Canonical = StarlarkStr;
103
104    fn starlark_type_repr() -> Ty {
105        StarlarkStr::starlark_type_repr()
106    }
107}
108
109impl<T: StarlarkTypeRepr> StarlarkTypeRepr for Option<T> {
110    type Canonical = <Either<NoneType, T> as StarlarkTypeRepr>::Canonical;
111
112    fn starlark_type_repr() -> Ty {
113        Either::<NoneType, T>::starlark_type_repr()
114    }
115}
116
117impl<T: StarlarkTypeRepr> StarlarkTypeRepr for Vec<T> {
118    type Canonical = <ListType<T> as StarlarkTypeRepr>::Canonical;
119
120    fn starlark_type_repr() -> Ty {
121        ListType::<T::Canonical>::starlark_type_repr()
122    }
123}
124
125impl<TLeft: StarlarkTypeRepr, TRight: StarlarkTypeRepr> StarlarkTypeRepr for Either<TLeft, TRight> {
126    type Canonical = Either<TLeft::Canonical, TRight::Canonical>;
127
128    fn starlark_type_repr() -> Ty {
129        Ty::union2(TLeft::starlark_type_repr(), TRight::starlark_type_repr())
130    }
131}
132
133/// Derive macros generate a reference to this method to be able to get the `type_repr` of types
134/// they can't name
135#[doc(hidden)]
136pub fn type_repr_from_attr_impl<'v, T: StarlarkTypeRepr, E>(
137    _f: fn(Value<'v>, &'v Heap) -> Result<T, E>,
138) -> Ty {
139    T::starlark_type_repr()
140}
141
142#[cfg(test)]
143mod tests {
144    use crate::tests::util::TestComplexValue;
145    use crate::util::non_static_type_id::non_static_type_id;
146    use crate::values::type_repr::StarlarkTypeRepr;
147    use crate::values::FrozenValue;
148    use crate::values::Value;
149
150    #[test]
151    fn test_canonical_for_complex_value() {
152        // TODO(nga): `StarlarkTypeRepr::Canonical` should be equal.
153        assert_ne!(
154            non_static_type_id::<<TestComplexValue<Value> as StarlarkTypeRepr>::Canonical>(),
155            non_static_type_id::<<TestComplexValue<FrozenValue> as StarlarkTypeRepr>::Canonical>(),
156        );
157    }
158}