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
/*
 * Copyright 2018 The Starlark in Rust Authors.
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use std::fmt;
use std::fmt::Display;
use std::ops::Deref;

use crate as starlark;
use crate::coerce::coerce;
use crate::typing::Ty;
use crate::values::list::value::display_list;
use crate::values::list::value::FrozenListData;
use crate::values::list::value::ListGen;
use crate::values::type_repr::StarlarkTypeRepr;
use crate::values::types::list::value::ListData;
use crate::values::Coerce;
use crate::values::FrozenValue;
use crate::values::UnpackValue;
use crate::values::Value;
use crate::values::ValueLike;

/// Reference to list content (mutable or frozen).
#[repr(transparent)]
#[derive(Coerce)]
pub struct ListRef<'v> {
    pub(crate) content: [Value<'v>],
}

/// Reference to frozen list content.
#[repr(transparent)]
#[derive(Coerce)]
pub struct FrozenListRef {
    pub(crate) content: [FrozenValue],
}

impl<'v> ListRef<'v> {
    /// `type([])`, which is `"list"`.
    pub const TYPE: &'static str = ListData::TYPE;

    pub(crate) fn new<'a>(slice: &'a [Value<'v>]) -> &'a ListRef<'v> {
        coerce(slice)
    }

    /// List elements.
    pub fn content(&self) -> &[Value<'v>] {
        &self.content
    }

    /// Iterate over the elements in the list.
    pub fn iter<'a>(&'a self) -> impl ExactSizeIterator<Item = Value<'v>> + 'a
    where
        'v: 'a,
    {
        self.content.iter().copied()
    }

    /// Downcast the value to the list or frozen list (both are represented by `ListRef`).
    pub fn from_value(x: Value<'v>) -> Option<&'v ListRef<'v>> {
        if x.unpack_frozen().is_some() {
            x.downcast_ref::<ListGen<FrozenListData>>()
                .map(|x| ListRef::new(coerce(x.0.content())))
        } else {
            let ptr = x.downcast_ref::<ListGen<ListData>>()?;
            Some(ListRef::new(ptr.0.content()))
        }
    }

    /// Downcast the list.
    pub fn from_frozen_value<'f>(x: FrozenValue) -> Option<&'f ListRef<'f>> {
        x.downcast_ref::<ListGen<FrozenListData>>()
            .map(|x| ListRef::new(coerce(x.0.content())))
    }
}

impl FrozenListRef {
    /// `type([])`, which is `"list"`.
    pub const TYPE: &'static str = ListRef::TYPE;

    fn new(slice: &[FrozenValue]) -> &FrozenListRef {
        coerce(slice)
    }

    /// Downcast to the frozen list.
    ///
    /// This function returns `None` if the value is not a list or the list is not frozen.
    pub fn from_value(x: Value) -> Option<&'static FrozenListRef> {
        Self::from_frozen_value(x.unpack_frozen()?)
    }

    /// Downcast to the frozen list.
    ///
    /// This function returns `None` if the value is not a frozen list.
    /// (Value cannot be a mutable list because value is frozen.)
    pub fn from_frozen_value(x: FrozenValue) -> Option<&'static FrozenListRef> {
        x.downcast_ref::<ListGen<FrozenListData>>()
            .map(|x| FrozenListRef::new(x.0.content()))
    }
}

impl<'v> Deref for ListRef<'v> {
    type Target = [Value<'v>];

    fn deref(&self) -> &[Value<'v>] {
        &self.content
    }
}

impl Deref for FrozenListRef {
    type Target = [FrozenValue];

    fn deref(&self) -> &[FrozenValue] {
        &self.content
    }
}

impl<'v> Display for ListRef<'v> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        display_list(&self.content, f)
    }
}

impl Display for FrozenListRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        display_list(coerce(&self.content), f)
    }
}

impl<'v> StarlarkTypeRepr for &'v ListRef<'v> {
    fn starlark_type_repr() -> Ty {
        Vec::<Value<'v>>::starlark_type_repr()
    }
}

impl<'v> StarlarkTypeRepr for &'v FrozenListRef {
    fn starlark_type_repr() -> Ty {
        Vec::<FrozenValue>::starlark_type_repr()
    }
}

impl<'v> UnpackValue<'v> for &'v ListRef<'v> {
    fn expected() -> String {
        "list".to_owned()
    }

    fn unpack_value(value: Value<'v>) -> Option<Self> {
        ListRef::from_value(value)
    }
}

impl<'v> UnpackValue<'v> for &'v FrozenListRef {
    fn expected() -> String {
        "frozen list".to_owned()
    }

    fn unpack_value(value: Value<'v>) -> Option<Self> {
        FrozenListRef::from_value(value)
    }
}