viirya commented on a change in pull request #1849: URL: https://github.com/apache/arrow-datafusion/pull/1849#discussion_r810585200
########## File path: datafusion-jit/src/api.rs ########## @@ -0,0 +1,630 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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 +// +// http://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. + +//! Constructing a function AST at runtime. + +use crate::ast::*; +use crate::jit::JIT; +use datafusion_common::internal_err; +use datafusion_common::{DataFusionError, Result}; +use parking_lot::Mutex; +use std::collections::HashMap; +use std::collections::VecDeque; +use std::fmt::{Debug, Display, Formatter}; +use std::sync::Arc; + +/// External Function signature +struct ExternFuncSignature { + name: String, + /// pointer to the function + code: *const u8, + params: Vec<JITType>, + returns: Option<JITType>, +} + +#[derive(Clone, Debug)] +/// A function consisting of AST nodes that JIT can compile. +pub struct GeneratedFunction { + pub(crate) name: String, + pub(crate) params: Vec<(String, JITType)>, + pub(crate) body: Vec<Stmt>, + pub(crate) ret: Option<(String, JITType)>, +} + +#[derive(Default)] +/// State of Assembler, keep tracking of generated function names +/// and registered external functions. +pub struct AssemblerState { + name_next_id: HashMap<String, u8>, + extern_funcs: HashMap<String, ExternFuncSignature>, +} + +impl AssemblerState { + /// Create a fresh function name with prefix `name`. + pub fn fresh_name(&mut self, name: impl Into<String>) -> String { + let name = name.into(); + if !self.name_next_id.contains_key(&name) { + self.name_next_id.insert(name.clone(), 0); + } + + let id = self.name_next_id.get_mut(&name).unwrap(); + let name = format!("{}_{}", &name, id); + *id += 1; + name + } +} + +/// The very first step for constructing a function at runtime. +pub struct Assembler { + state: Arc<Mutex<AssemblerState>>, +} + +impl Default for Assembler { + fn default() -> Self { + Self { + state: Arc::new(Default::default()), + } + } +} + +impl Assembler { + /// Register an external Rust function to make it accessible by runtime generated functions. + /// Parameters and return types are used to impose type safety while constructing an AST. + pub fn register_extern_fn( + &self, + name: impl Into<String>, + ptr: *const u8, + params: Vec<JITType>, + returns: Option<JITType>, + ) -> Result<()> { + let extern_funcs = &mut self.state.lock().extern_funcs; + let fn_name = name.into(); + let old = extern_funcs.insert( + fn_name.clone(), + ExternFuncSignature { + name: fn_name, + code: ptr, + params, + returns, + }, + ); + + match old { + None => Ok(()), + Some(old) => internal_err!("Extern function {} already exists", old.name), + } + } + + /// Create a new FunctionBuilder with `name` prefix + pub fn new_func_builder(&self, name: impl Into<String>) -> FunctionBuilder { + let name = self.state.lock().fresh_name(name); + FunctionBuilder::new(name, self.state.clone()) + } + + /// Create JIT env which we could compile the AST of constructed function + /// into runnable code. + pub fn create_jit(&self) -> JIT { + let symbols = self + .state + .lock() + .extern_funcs + .values() + .map(|s| (s.name.clone(), s.code)) + .collect::<Vec<_>>(); + JIT::new(symbols) + } +} + +/// Function builder API. Stores the state while +/// we are constructing an AST for a function. +pub struct FunctionBuilder { + name: String, + params: Vec<(String, JITType)>, + ret: Option<(String, JITType)>, + fields: VecDeque<HashMap<String, JITType>>, + assembler_state: Arc<Mutex<AssemblerState>>, +} + +impl FunctionBuilder { + fn new(name: impl Into<String>, assembler_state: Arc<Mutex<AssemblerState>>) -> Self { + let mut fields = VecDeque::new(); + fields.push_back(HashMap::new()); + Self { + name: name.into(), + params: Vec::new(), + ret: None, + fields, + assembler_state, + } + } + + /// Add one more parameter to the function. + pub fn param(mut self, name: impl Into<String>, ty: JITType) -> Self { + let name = name.into(); + assert!(!self.fields.back().unwrap().contains_key(&name)); + self.params.push((name.clone(), ty)); + self.fields.back_mut().unwrap().insert(name, ty); + self + } + + /// Set return type for the function. Functions are of `void` type by default if + /// you do not set the return type. + pub fn ret(mut self, name: impl Into<String>, ty: JITType) -> Self { + let name = name.into(); + assert!(!self.fields.back().unwrap().contains_key(&name)); + self.ret = Some((name.clone(), ty)); + self.fields.back_mut().unwrap().insert(name, ty); + self + } + + /// Enter the function body at start the building. + pub fn enter_block(&mut self) -> CodeBlock { + self.fields.push_back(HashMap::new()); + CodeBlock { + fields: &mut self.fields, + state: &self.assembler_state, + stmts: vec![], + while_state: None, + if_state: None, + fn_state: Some(GeneratedFunction { + name: self.name.clone(), + params: self.params.clone(), + body: vec![], + ret: self.ret.clone(), + }), + } + } +} + +/// Keep `while` condition expr as we are constructing while loop body. +struct WhileState { + condition: Expr, +} + +/// Keep `if-then-else` state, including condition expr, the already built +/// then statements (if we are during building the else block). +struct IfElseState { + condition: Expr, + then_stmts: Vec<Stmt>, + in_then: bool, +} + +impl IfElseState { + /// Move the all current statements in the `then` block and move to `else` block. + fn enter_else(&mut self, then_stmts: Vec<Stmt>) { + self.then_stmts = then_stmts; + self.in_then = false; + } +} + +/// Code block that Review comment: is there missing doc here? Looks like a suddenly broken sentence. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
