|
| 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::mem; |
| 19 | +use std::slice; |
| 20 | +use std::str; |
| 21 | + |
| 22 | +use starlark::environment::Globals; |
| 23 | +use starlark::environment::Module; |
| 24 | +use starlark::eval::Evaluator; |
| 25 | +use starlark::syntax::AstModule; |
| 26 | +use starlark::syntax::Dialect; |
| 27 | +use starlark::values::Value; |
| 28 | + |
| 29 | +#[no_mangle] |
| 30 | +pub extern "C" fn allocation(n: usize) -> *mut u8 { |
| 31 | + mem::ManuallyDrop::new(Vec::with_capacity(n)).as_mut_ptr() |
| 32 | +} |
| 33 | + |
| 34 | +#[no_mangle] |
| 35 | +pub unsafe extern "C" fn evaluate(s: *const u8) -> *mut u8 { |
| 36 | + let length = u32::from_le_bytes(*(s as *const [u8; 4])) as usize; |
| 37 | + let input = slice::from_raw_parts(s.offset(4), length); |
| 38 | + let output = evaluate_buffers(input); |
| 39 | + mem::ManuallyDrop::new(output).as_mut_ptr() |
| 40 | +} |
| 41 | + |
| 42 | +fn evaluate_buffers(input: &[u8]) -> Vec<u8> { |
| 43 | + let contents = str::from_utf8(input).unwrap(); |
| 44 | + let result = evaluate_starlark(contents); |
| 45 | + let success = result.is_ok(); |
| 46 | + let message = result.unwrap_or_else(|e| e.into_anyhow().to_string()); |
| 47 | + let len = message.len(); |
| 48 | + let mut buffer = Vec::with_capacity(len + 8); |
| 49 | + buffer.push(if success { 1 } else { 0 }); |
| 50 | + buffer.extend(vec![0; 3]); |
| 51 | + buffer.extend_from_slice(&(len as u32).to_le_bytes()); |
| 52 | + buffer.extend_from_slice(message.as_bytes()); |
| 53 | + buffer |
| 54 | +} |
| 55 | + |
| 56 | +fn evaluate_starlark(content: &str) -> Result<String, starlark::Error> { |
| 57 | + let ast: AstModule = |
| 58 | + AstModule::parse("hello_world.star", content.to_owned(), &Dialect::Standard)?; |
| 59 | + let globals = Globals::standard(); |
| 60 | + let module: Module = Module::new(); |
| 61 | + let mut eval: Evaluator = Evaluator::new(&module); |
| 62 | + let res: Value = eval.eval_module(ast, &globals)?; |
| 63 | + Ok(res.to_string()) |
| 64 | +} |
0 commit comments