starlark/eval/bc/
native_function.rs

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
18use allocative::Allocative;
19use dupe::Dupe;
20
21use crate::eval::Arguments;
22use crate::eval::Evaluator;
23use crate::values::function::NativeFunc;
24use crate::values::function::NativeFunction;
25use crate::values::FrozenRef;
26use crate::values::FrozenValueTyped;
27use crate::values::Value;
28
29/// Pointer to a native function optimized for bytecode execution.
30#[derive(Copy, Clone, Dupe, Allocative)]
31pub(crate) struct BcNativeFunction {
32    fun: FrozenValueTyped<'static, NativeFunction>,
33    /// Copy function here from `fun` to avoid extra dereference when calling.
34    imp: FrozenRef<'static, dyn NativeFunc>,
35}
36
37impl BcNativeFunction {
38    pub(crate) fn new(fun: FrozenValueTyped<'static, NativeFunction>) -> BcNativeFunction {
39        let imp = fun.as_frozen_ref().map(|f| &*f.function);
40        BcNativeFunction { fun, imp }
41    }
42
43    #[inline]
44    pub(crate) fn fun(&self) -> FrozenValueTyped<'static, NativeFunction> {
45        self.fun
46    }
47
48    #[inline]
49    pub(crate) fn to_value<'v>(&self) -> Value<'v> {
50        self.fun.to_value()
51    }
52
53    #[inline]
54    pub(crate) fn invoke<'v>(
55        &self,
56        args: &Arguments<'v, '_>,
57        eval: &mut Evaluator<'v, '_, '_>,
58    ) -> crate::Result<Value<'v>> {
59        self.imp.invoke(eval, args)
60    }
61}