green_copper_runtime/preprocessors/cpp.rs
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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
//! cpp style preprocessor
//!
//! this can be used to define c-like preprocessing instructions in javascript
//! ```javascript
//! function do_stuff(input) {
//! #ifdef $GRECO_DEBUG
//! if (input.includes('booh')) {
//! throw Error('input should not include booh');
//! }
//! #endif
//! console.log('got input %s', input);
//! }
//! ```
//!
//! it used the gpp crate and docs on how it works are here https://docs.rs/gpp/0.6.0/gpp
//!
//! by default GreenCopperRuntime conditionally sets the $GRECO_DEBUG, $GRECO_TEST and $GRECO_RELEASE
//! you can also add all current env_vars so in script you can use ```let path = "$PATH";```;
//!
//! # Example
//! ```rust
//! use green_copper_runtime::preprocessors::cpp::CppPreProcessor;
//! use quickjs_runtime::builder::QuickJsRuntimeBuilder;
//! use quickjs_runtime::jsutils::Script;
//!
//! let cpp = CppPreProcessor::new().default_extensions().env_vars();
//! let rt = QuickJsRuntimeBuilder::new().script_pre_processor(cpp).build();
//!
//! let path = rt.eval_sync(None, Script::new("test.js", "let p = '$PATH'; p")).ok().expect("script failed");
//! assert!(!path.get_str().is_empty());
//! assert_ne!(path.get_str(), "$PATH");
//!
//! ```
//!
use gpp::{process_str, Context};
use quickjs_runtime::jsutils::JsError;
use quickjs_runtime::jsutils::{Script, ScriptPreProcessor};
use std::cell::RefCell;
use std::env;
pub struct CppPreProcessor {
ctx: RefCell<Context>,
extensions: Vec<&'static str>,
}
impl Default for CppPreProcessor {
fn default() -> Self {
Self::new()
}
}
impl CppPreProcessor {
pub fn new() -> Self {
let mut ret = Self {
ctx: RefCell::new(Context::new()),
extensions: vec![],
};
#[cfg(debug_assertions)]
{
ret = ret.def("GRECO_DEBUG", "true");
}
#[cfg(test)]
{
ret = ret.def("GRECO_TEST", "true");
}
#[cfg(not(any(debug_assertions, test)))]
{
ret = ret.def("GRECO_RELEASE", "true");
}
ret
}
/// add a def
pub fn def(self, key: &str, value: &str) -> Self {
{
let ctx = &mut *self.ctx.borrow_mut();
ctx.macros.insert(format!("${{{key}}}"), value.to_string());
ctx.macros.insert(format!("${key}"), value.to_string());
ctx.macros.insert(format!("__{key}"), value.to_string());
}
self
}
/// add a supported extension e.g. js/mjs/ts/mts/es/mes
pub fn extension(mut self, ext: &'static str) -> Self {
self.extensions.push(ext);
self
}
pub fn env_vars(mut self) -> Self {
log::debug!("adding env vars");
for (key, value) in env::vars() {
log::debug!("adding env var {} = {}", key, value);
self = self.def(key.as_str(), value.as_str());
}
self
}
/// add default extensions : js/mjs/ts/mts/es/mes
pub fn default_extensions(self) -> Self {
self.extension("es")
.extension("mes")
.extension("js")
.extension("mjs")
.extension("ts")
.extension("mts")
}
}
impl ScriptPreProcessor for CppPreProcessor {
fn process(&self, script: &mut Script) -> Result<(), JsError> {
if "CppPreProcessor.not_es".eq(script.get_path()) {
return Ok(());
}
log::debug!("CppPreProcessor > {}", script.get_path());
//println!("CppPreProcessor > {}", script.get_path());
let src = script.get_code();
let res = process_str(src, &mut self.ctx.borrow_mut())
.map_err(|e| JsError::new_string(format!("{e}")))?;
script.set_code(res);
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::preprocessors::cpp::CppPreProcessor;
use crate::tests::init_test_greco_rt;
use futures::executor::block_on;
use quickjs_runtime::jsutils::{Script, ScriptPreProcessor};
use quickjs_runtime::values::JsValueFacade;
#[test]
fn test_ifdef_script_only() {
let cpp = CppPreProcessor::new()
.default_extensions()
.env_vars()
.def("TEST_AUTOMATION", "true");
let mut script = Script::new(
"testifdef.js",
r#"
#ifdef $TEST_AUTOMATION
1
#else
2
#endif
"#,
);
cpp.process(&mut script).unwrap();
assert_eq!("\n1\n", script.get_code());
}
#[test]
fn test_ifdef() {
let rt = init_test_greco_rt();
let fut = rt.eval(
None,
Script::new(
"test.es",
"((function(){\n\
#ifdef HELLO\n\
return 111;\n\
#elifdef $GRECO_DEBUG\n\
return 123;\n\
#else\n\
return 222;\n\
#endif\n\
})());",
),
);
let res = block_on(fut);
let num = match res {
Ok(e) => e,
Err(err) => {
panic!("{}", err);
}
};
if let JsValueFacade::I32 { val } = num {
assert_eq!(val, 123);
} else {
panic!("not an i32")
}
}
#[test]
fn test_vars() {
let rt = init_test_greco_rt();
let fut = rt.eval(
None,
Script::new(
"test.es",
"((function(){\n\
return('p=${PATH}');\n\
})());",
),
);
let res = block_on(fut);
let val = match res {
Ok(e) => e,
Err(err) => {
panic!("{}", err);
}
};
if let JsValueFacade::String { val } = val {
assert_ne!(&*val, "${PATH}");
assert!(!val.is_empty());
} else {
panic!("not a string")
}
}
}