lulu 0.0.721

A mini lua runtime
Documentation
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use crate::compiler::Compiler;
use crate::conf::{LuluConf, find_lulu_conf, load_lulu_conf};
use crate::ops::core::{register_consts, register_ops};
use mlua::{Lua, chunk};
use std::path::PathBuf;

pub const STD_FILE: &str = include_str!("./builtins/std.lua");

#[derive(Debug, Clone)]
pub struct LuLib {
  pub bytes: Vec<u8>,
  pub conf: Option<Vec<u8>>,
}

#[derive(Debug, Clone)]
pub enum LuluModSource {
  Code(String),
  Bytecode(Vec<u8>),
}

#[derive(Debug, Clone)]
pub struct LuluMod {
  pub name: String,
  pub source: LuluModSource,
  pub conf: Option<LuluConf>,
}

#[derive(Debug, Clone)]
pub struct Lulu {
  pub mods: Vec<LuluMod>,
  pub lua: Lua,
  pub args: Vec<String>,
  pub current: Option<PathBuf>,
  pub compiler: Compiler,
  std: String,
}

impl Lulu {
  pub fn new(args: Option<Vec<String>>, current: Option<PathBuf>) -> Lulu {
    let mods = Vec::new();
    let lua = unsafe { Lua::unsafe_new() };

    let mut compiler = Compiler::new(None);

    let std = compiler.compile(STD_FILE, None, None);
    // println!("{}", std);

    Lulu {
      mods,
      lua,
      args: args.unwrap_or_default(),
      current,
      compiler,
      std,
    }
  }

  pub fn preload_mods(&mut self) -> mlua::Result<()> {
    let mut processed = std::collections::HashSet::new();
    let mut last_len = 0;

    loop {
      let keys: Vec<String> = self.compiler.importmap.keys().cloned().collect();

      if keys.len() == last_len {
        break;
      }

      last_len = keys.len();

      for name in keys {
        if processed.contains(&name) {
          continue;
        }

        let (path_to_import, path_from_opt, conf) = match self.compiler.importmap.get(&name) {
          Some(v) => v.clone(),
          _ => continue,
        };

        let path_from = path_from_opt.unwrap_or_default();
        if path_from.is_empty() {
          continue;
        }

        let parent = std::path::Path::new(&path_from).parent().unwrap();
        let file_path = parent.join(path_to_import);

        if !file_path.exists() {
          panic!(
            "File {:?} does not exist. Imported from: {}",
            file_path, path_from
          );
        }

        if name.starts_with("bytes://") {
          let bytecode = std::fs::read(&file_path)?;
          self.add_mod_from_bytecode(name.clone(), bytecode, None);
        } else {
          self.add_mod_from_file(name.clone(), file_path, conf.clone())?;
        }

        processed.insert(name);
      }
    }

    register_ops(&self.lua, self)?;

    self
      .lua
      .load(
        r#"
        local embedded = __get_mods__()
        package.preload = package.preload or {}
        require_native = require
        for key, name in pairs(embedded) do
          package.preload[name] = function()
            return exec_mod(name)
          end
        end
        "#,
      )
      .exec()?;

    self.lua.load(self.std.clone()).set_name("std").exec()?;

    register_consts(&self.lua)?;

    Ok(())
  }

  pub fn add_mod(&mut self, lmod: LuluMod) {
    self.mods.push(lmod);
  }

  pub fn add_mod_from_code(&mut self, name: String, code: String, conf: Option<LuluConf>) {
    self.add_mod(LuluMod {
      name,
      source: LuluModSource::Code(self.compiler.clone().compile(code.as_str(), None, None)),
      conf,
    });
  }

  pub fn add_mod_from_bytecode(&mut self, name: String, bytecode: Vec<u8>, conf: Option<LuluConf>) {
    self.add_mod(LuluMod {
      name,
      source: LuluModSource::Bytecode(bytecode),
      conf,
    });
  }

  pub fn add_mod_from_file(
    &mut self,
    name: String,
    path: PathBuf,
    conf: Option<LuluConf>,
  ) -> mlua::Result<()> {
    let raw = std::fs::read(&path)?;

    let source = match std::str::from_utf8(&raw) {
      Ok(code) => LuluModSource::Code(self.compiler.compile(
        code,
        Some(std::fs::canonicalize(path)?.to_string_lossy().to_string()),
        conf.clone(),
      )),
      Err(_) => LuluModSource::Bytecode(raw),
    };

    let modname = if let Some(n) = self.compiler.last_mod.clone() {
      self.compiler.last_mod = None;
      n
    } else {
      name.clone()
    };

    self.add_mod(LuluMod {
      name: modname,
      source,
      conf,
    });
    Ok(())
  }

  pub fn exec_mod(&self, name: &str) -> mlua::Result<mlua::Value> {
    let lmod = self
      .mods
      .iter()
      .find(|m| m.name == name)
      .ok_or_else(|| mlua::Error::RuntimeError(format!("Module {} not found", name)))?;

    let chunk = match &lmod.source {
      LuluModSource::Code(code) => self.lua.load(code),
      LuluModSource::Bytecode(bytes) => self.lua.load(&bytes[..]),
    }
    .set_name(name);

    let env = if let Some(env) = chunk.environment() {
      env.clone()
    } else {
      let env = self.lua.create_table()?;

      let mt = self.lua.create_table()?;
      mt.set("__index", self.lua.globals())?;
      env.set_metatable(Some(mt))?;

      env
    };

    let lmod_table = self.lua.create_table()?;

    if let Some(conf) = lmod.conf.clone() {
      let p = self.lua.create_userdata::<LuluConf>(conf)?;

      lmod_table.set("conf", p)?;
    }
    lmod_table.set("name", name)?;

    env.set("mod", lmod_table)?;

    let req_chunk = self.lua.load(chunk! {
      local name = ({...})[1]
      if mod.conf then
        local modname = mod.conf.manifest.name .. "/" .. name;
        if package.preload[modname] then
          return require_native(modname)
        end
      end
      return require_native(name)
    });

    let req = req_chunk.set_environment(env.clone()).into_function()?;

    env.set("require", req)?;

    if let Some(current) = self.current.clone() {
      env.set("current_path", std::fs::canonicalize(current)?)?;
    } else {
      env.set("current_path", mlua::Value::Nil)?;
    }
    let current = self.current.clone();
    let lookup_dylib = self.lua.create_function(move |_, name: String| {
      let path = std::fs::canonicalize(current.clone().unwrap_or(PathBuf::from(".")))?;

      let name = if name.starts_with("@") {
        let prefix = if std::env::consts::OS == "windows" {
          ""
        } else {
          "lib"
        };
        let ext = match std::env::consts::OS {
          "windows" => ".dll",
          "macos" => ".dylib",
          _ => ".so",
        };

        format!("{}{}{}", prefix, &name[1..], ext)
      } else {
        name
      };
      let lib_folder = path.join(".lib/dylib").join(name.clone());
      let dylib_here = path.join("dylib").join(name.clone());

      if lib_folder.exists() {
        Ok(lib_folder)
      } else if dylib_here.exists() {
        Ok(dylib_here)
      } else {
        Ok(name.into())
      }
    })?;

    env.set("lookup_dylib", lookup_dylib)?;

    let current = self.current.clone();
    env.set(
      "path_resolve",
      self.lua.create_function(move |_, name: String| {
        let path = std::fs::canonicalize(current.clone().unwrap_or(PathBuf::from(".")))?;
        Ok(path.join(name))
      })?,
    )?;

    let using = self
      .lua
      .load(chunk! {
        local args = { ... }
        if type(args[1]) == "function" then
          args[1](getfenv(1))
        elseif type(args[1]) == "table" then
          for k, v in pairs(args[1]) do
            local r = v(getfenv(1))
            if type(r) == "table" and r.__into then
              getfenv(1)[r.__into] = r.__value
            end
          end
        end
      })
      .set_environment(env.clone())
      .into_function()?;

    env.set("using", using)?;

    let chunk = chunk.set_environment(env);

    chunk.eval()
  }

  pub fn entry_mod_path(&mut self, path: PathBuf) -> mlua::Result<String> {
    let mut mainname = "main".to_string();
    let conf = if let Some(root_path) = find_lulu_conf(path.clone()) {
      let c = load_lulu_conf(&self.lua, root_path.clone())?;
      let prefix = if let Some(manifest) = c.clone().manifest {
        if let Ok(n) = manifest.get::<mlua::Value>("name") {
          match n.to_string() {
            Ok(n) => format!("{}/", n),
            Err(_) => "".to_string(),
          }
        } else {
          "".to_string()
        }
      } else {
        "".to_string()
      };

      if let Some(mods) = c.mods.clone() {
        for (name, modpath) in mods {
          let mod_path = root_path.parent().unwrap().join(modpath);
          if mod_path == path {
            mainname = format!("{}{}", prefix, name.clone());
            continue;
          }
          self.add_mod_from_file(
            format!("{}{}", prefix, name.clone()),
            mod_path,
            Some(c.clone()),
          )?;
        }
      }

      if let Some(macros) = c.macros.clone() {
        self.compiler.compile(&macros, None, None);
      }

      if let Some(include) = c.include.clone() {
        for libpath in include {
          let lib_path = root_path
            .parent()
            .unwrap()
            .join(if libpath.starts_with("@") {
              format!(".lib/lulib/{}.lulib", libpath[1..].to_string())
            } else {
              libpath
            });
          let mods = crate::bundle::load_lulib(&lib_path)?;
          crate::bundle::reg_bundle_nods(self, mods)?;
        }
      }
      Some(c)
    } else {
      mainname = path.to_string_lossy().to_string();
      None
    };

    self.add_mod_from_file(mainname.clone(), path.clone(), conf)?;

    self.preload_mods()?;

    Ok(mainname)
  }

  pub fn find_mod(&mut self, name: &str) -> mlua::Result<String> {
    let lmod = self
      .mods
      .iter()
      .find(|m| m.name.ends_with(name))
      .ok_or_else(|| mlua::Error::RuntimeError(format!("No main was found")))?;

    Ok(lmod.name.clone())
  }

  pub async fn exec_final(&mut self, name: &str) -> mlua::Result<mlua::Value> {
    let result = self.exec_mod(name);

    let scheduler: mlua::Function = self
      .lua
      .globals()
      .get::<mlua::Table>("coroutine")?
      .get("resume")?;
    let sched_co: mlua::Value = self
      .lua
      .globals()
      .get::<mlua::Table>("Future")?
      .get("scheduler")?;

    loop {
      let active = scheduler.call::<mlua::Value>(sched_co.clone())?;
      match active {
        mlua::Value::Boolean(true) | mlua::Value::Nil => {
          tokio::task::yield_now().await;
        }
        mlua::Value::Boolean(false) => {
          break;
        }
        _ => break,
      }
    }

    result
  }

  pub async fn exec_entry_mod_path(&mut self, path: PathBuf) -> mlua::Result<()> {
    let mainname = self.entry_mod_path(path)?;
    self.exec_final(mainname.as_str()).await?;

    Ok(())
  }

  pub fn compile(&mut self, path: PathBuf) -> mlua::Result<String> {
    let mainname = self.entry_mod_path(path)?;

    let lmod = self
      .mods
      .iter()
      .find(|m| m.name == mainname)
      .ok_or_else(|| mlua::Error::RuntimeError(format!("Such module was not found")))?;

    match lmod.source.clone() {
      LuluModSource::Code(code) => Ok(code),
      _ => Err(mlua::Error::DeserializeError(
        "Module string was not found".to_string(),
      )),
    }
  }
}