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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
use crate::bundle::{bundle_lulu_or_exec, load_lulib, run_bundle, set_exec_path};
use crate::cli::{CacheCommand, Cli, Commands};
use crate::conf::load_lulu_conf;
use crate::core::Lulu;
use crate::ops::{TOK_ASYNC_HANDLES, core::register_consts};
use crate::package_manager::PackageManager;
use clap::Parser;
use mlua::Result;
use mlua::prelude::LuaError;
use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, Mutex};

mod builders;
mod bundle;
mod cli;
pub mod compiler;
pub mod conf;
pub mod core;
mod lml;
mod lulibs;
mod ops;
mod package_manager;
mod project;
mod resolver;
mod util;

macro_rules! into_exec_command {
  ($lua:expr, $env:expr, (), $cmd:expr $(, $arg:expr)*) => {{
    let env_ref = $env.clone();
    $lua.create_function(move |_, ()| {
      let mut cmd = std::process::Command::new(std::env::current_exe()?);
      cmd.arg($cmd);
      $(
        cmd.arg($arg);
      )*
      let map = env_ref.lock().unwrap();
      for (k, v) in map.iter() {
        cmd.env(k, v);
      }
      cmd.status()?;
      Ok(())
    })?
  }};

  ($lua:expr, $env:expr, ($($arg_name:ident : $arg_type:ty),+), $cmd:expr $(, $arg:expr)*) => {{
    let env_ref = $env.clone();
    #[allow(unused_parens)]
    $lua.create_function(move |_, ($($arg_name),+): ($($arg_type),+)| {
      let mut cmd = std::process::Command::new(std::env::current_exe()?);
      cmd.arg($cmd);
      $(
        cmd.arg($arg);
      )*
      let map = env_ref.lock().unwrap();
      for (k, v) in map.iter() {
        cmd.env(k, v);
      }
      cmd.status()?;
      Ok(())
    })?
  }};
}

#[tokio::main(flavor = "multi_thread", worker_threads = 4)]
async fn main() -> Result<()> {
  crate::ops::std::init_std_modules();
  if let Some(mods) = bundle::load_embedded_scripts() {
    handle_error!(
      run_bundle(
        mods,
        &mut Lulu::new(
          Some(std::env::args().skip(1).collect()),
          Some(std::env::current_exe()?.parent().unwrap().to_path_buf())
        )
      )
      .await
    );
  } else {
    let cli = Cli::parse();

    match &cli.command {
      Commands::Run { file, args, build } => {
        handle_error!(if *build {
          let lua = mlua::Lua::new();
          let conf = load_lulu_conf(&lua, file.join("lulu.conf.lua"))?;
          let name = conf.manifest.unwrap().get::<String>("name")?;
          std::process::Command::new(std::env::current_exe()?)
            .arg("build")
            .arg(file.clone())
            .status()?;
          let runpath = if file.join(format!(".lib/{name}.lulib")).exists() {
            file.join(format!(".lib/{name}.lulib"))
          } else {
            file.join(".lib").join(name)
          };

          if runpath.ends_with(".lulib") {
            let mods = load_lulib(&runpath)?;
            run_bundle(mods, &mut Lulu::new(Some(args.clone()), Some(runpath))).await?;
          } else {
            std::process::Command::new(runpath).args(args).status()?;
          }
          Ok(())
        } else if file.extension().and_then(|s| s.to_str()) == Some("lulib") {
          let mods = load_lulib(file)?;
          run_bundle(
            mods,
            &mut Lulu::new(
              Some(args.clone()),
              Some(file.parent().unwrap().to_path_buf()),
            ),
          )
          .await
        } else if file.is_dir() {
          let mut lulu = Lulu::new(Some(args.clone()), Some(file.to_path_buf()));
          let filepath = if file.join("init.lua").exists() {
            file.join("init.lua")
          } else {
            file.join("main.lua")
          };
          lulu.exec_entry_mod_path(filepath.clone()).await
        } else {
          let mut lulu = Lulu::new(
            Some(args.clone()),
            Some(file.parent().unwrap().to_path_buf()),
          );
          lulu.exec_entry_mod_path(file.clone()).await
        });
      }
      Commands::Compile { file } => {
        let path = std::fs::canonicalize(file)?;
        let mut lulu = Lulu::new(None, Some(path.clone().parent().unwrap().to_path_buf()));
        println!("{}", lulu.compile(path.clone())?);
      }
      Commands::Test { file, test, args } => {
        let mut lulu = Lulu::new(
          Some(args.clone()),
          Some(file.parent().unwrap().to_path_buf()),
        );
        lulu.compiler.env = "test".to_string();
        lulu.compiler.current_test = test.clone();
        handle_error!(lulu.exec_entry_mod_path(file.clone()).await);
      }
      Commands::Bundle { file, output } => {
        let mut lulu = Lulu::new(None, None);
        bundle_lulu_or_exec(&mut lulu, file.clone(), output.clone())?;
      }
      Commands::Resolve { item } => {
        let pkg_manager = PackageManager::new().map_err(|e| mlua::Error::external(e))?;

        async {
          if item.starts_with("http") || item.starts_with("github:") {
            let path = std::path::PathBuf::from(".");

            match pkg_manager.install_package(item.as_str(), &path).await {
              Ok(_) => {}
              Err(e) => eprintln!("Failed to resolve dependency \"{}\": {}", item, e),
            };
          } else {
            let path = std::path::PathBuf::from(item);
            let conf_path = path.join("lulu.conf.lua");

            if let Ok(conf_string) = std::fs::read_to_string(conf_path.clone()) {
              let lua = mlua::Lua::new();
              let parent_path = path.clone();

              if let Ok(Some(dependencies)) =
                conf::load_lulu_conf_dependiencies(&lua, conf_string.clone())
              {
                let packages_to_install = dependencies;
                match pkg_manager
                  .install_packages(&packages_to_install, &parent_path)
                  .await
                {
                  Ok(_) => {}
                  Err(e) => eprintln!("Failed to resolve dependencies: {}", e),
                }
              } else {
                eprintln!("No dependencies found in {}", conf_path.display());
              }
            } else {
              eprintln!("Could not read configuration file: {}", conf_path.display());
            }
          }
        }
        .await;
      }
      Commands::Build { path } => {
        let conf_path = path.join("lulu.conf.lua");
        crate::builders::register_default_builders();

        if !conf_path.exists() {
          eprintln!("Path has no lulu.conf.lua");
          return Ok(());
        }

        let conf_string = std::fs::read_to_string(conf_path.clone())?;
        let lua = mlua::Lua::new();

        register_consts(&lua)?;
        crate::util::create_lib_folders(&path)?;

        if let Some(build_fn_lua) = conf::load_lulu_conf_builder(&lua, conf_string.clone())? {
          let main = conf::load_lulu_conf_code(&lua, conf::CodeType::Code(conf_string))?;
          let name = main
            .manifest
            .unwrap_or(lua.create_table()?)
            .get::<String>("name")?;

          let env = Arc::new(Mutex::new(HashMap::<String, String>::new()));
          let lulu_arc = Arc::new(Mutex::new(Lulu::new(None, None)));

          let env_ref = env.clone();
          lua.globals().set(
            "set_env",
            lua.create_function(move |_, (name, value): (String, String)| {
              let mut map = env_ref.lock().unwrap();
              map.insert(name, value);
              Ok(())
            })?,
          )?;

          let bundle_path = path.clone();
          let bundle = into_exec_command!(lua, env, (file: String, output: String), "bundle", bundle_path.clone().join(file), bundle_path.join(output));

          // let bname = name.clone();
          // let bundle_main_path = path.clone();
          // let bundle_main_path = path.clone();
          // lua.globals().set("bundle", lua.create_function(move |_, file: String| {
          //     bundle_lulu_or_exec(&mut lulu, bundle_main_path.join(file).to_path_buf(), Path::new(&format!(".lib/{}.lulib", name.clone())).to_path_buf())
          //   })?)?;
          // let bundle_main_entry = into_exec_command!(lua, env, (file: String), "bundle", bundle_main_path.clone().join(file), bundle_main_path.join(format!(".lib/{}.lulib", bname.clone())));

          // let name = name.clone();
          // let bundle_main_path = path.clone();
          // let bundle_main_entry_exec = into_exec_command!(lua, env, (file: String), "bundle", bundle_main_path.clone().join(file), bundle_main_path.join(format!(".lib/{}", name.clone())));

          let ipath = path.clone();
          let larc = lulu_arc.clone();
          lua.globals().set(
            "include_bytes",
            lua.create_function(move |_, (name, file): (String, String)| {
              let file_path = ipath.join(file);
              let bytes = std::fs::read(file_path)?;
              let mut lulu = larc.lock().unwrap();
              lulu.add_mod_from_bytecode(format!("bytes://{}", name), bytes, None);
              Ok(())
            })?,
          )?;

          let ipath = path.clone();
          let larc = lulu_arc.clone();
          lua.globals().set(
            "execute_file",
            lua.create_function(move |_, file: String| {
              let file_path = ipath.join(file.clone());
              let code = std::fs::read(file_path)?;
              let lulu = larc.lock().unwrap();
              lulu.lua.load(code).set_name(file).exec()?;
              Ok(())
            })?,
          )?;

          lua.globals().set(
            "download_file_async",
            lua.create_async_function(async move |_, url: String| {
              PackageManager::new()
                .map_err(|e| {
                  eprintln!("Failed to initialize package manager: {}", e);
                  mlua::Error::external(e)
                })?
                .clone()
                .download_file(&url)
                .await
                .map_err(|e| {
                  eprintln!("Failed to download file: {}", e);
                  mlua::Error::external(e)
                })
            })?,
          )?;

          lua.globals().set(
            "download_file",
            lua
              .load(mlua::chunk! {
                local f = coroutine.create(function(...)
                  download_file_async(...)
                  return false
                end)
                local done = true
                while done do
                  done = coroutine.resume(f, ...)
                end
              })
              .into_function()?,
          )?;

          let bw_path = path.clone();
          lua.globals().set(
            "build_with",
            lua.create_function(
              move |_, (builder, path, args): (String, String, Option<Vec<String>>)| {
                let path = bw_path.join(path);
                crate::builders::build_path(builder, path, args.unwrap_or(Vec::new()))?;
                Ok(())
              },
            )?,
          )?;

          let exec_path = path.clone();
          lua.globals().set(
            "exec_command",
            lua.create_function(
              move |_, (command, args, path): (String, Vec<String>, Option<String>)| {
                let exec_path = if let Some(path) = path {
                  exec_path.join(path)
                } else {
                  exec_path.clone()
                };
                let mut cmd = std::process::Command::new(command);
                cmd.current_dir(exec_path).args(args);
                let status = cmd.status().map_err(mlua::Error::external)?;
                if status.success() {
                  Ok(())
                } else {
                  Err(mlua::Error::external(status.to_string()))
                }
              },
            )?,
          )?;

          lua.globals().set(
            "new_builder",
            lua.create_function(move |_, (name, function): (String, mlua::Function)| {
              #[derive(Clone)]
              struct CustomBuilder {
                func: Arc<mlua::Function>,
              }

              impl crate::builders::BuilderTrait for CustomBuilder {
                fn build(&self, path: &std::path::PathBuf, args: &[String]) -> mlua::Result<()> {
                  self.func.call::<()>((path.clone(), args.to_vec()))
                }
              }

              {
                use crate::builders::BUILDERS;
                let mut map = BUILDERS.write().unwrap();
                map.insert(
                  name.clone(),
                  Arc::new(CustomBuilder {
                    func: Arc::new(function),
                  }),
                );
              }

              Ok(())
            })?,
          )?;

          let collect_path = path.clone();
          lua.globals().set(
            "collect_lib",
            lua.create_function(move |_, file: String| {
              let path = collect_path.join(file);
              let libpath = collect_path.join(format!(
                ".lib/dylib/{}",
                path.file_name().unwrap().to_string_lossy()
              ));

              std::fs::copy(path, libpath).map_err(mlua::Error::external)?;

              Ok(())
            })?,
          )?;

          let copy_path = path.clone();
          lua.globals().set(
            "copy_all",
            lua.create_function(move |_, (file, dest): (String, String)| {
              let path = copy_path.join(file);
              let dest = copy_path.join(dest);

              crate::util::copy_recursively(path, dest).map_err(mlua::Error::external)?;

              Ok(())
            })?,
          )?;

          let collect_path = path.clone();
          lua.globals().set(
            "collect_libs",
            lua.create_function(move |_, files: HashMap<String, Vec<String>>| {
              let current_os = std::env::consts::OS;

              let libs = if let Some(url) = files.get(current_os) {
                Ok(url)
              } else if let Some(url) =
                files.get(&format!("{}-{}", current_os, std::env::consts::ARCH))
              {
                Ok(url)
              } else {
                Err(mlua::Error::external(format!(
                  "No lib found for OS: {}",
                  current_os
                )))
              }?;

              for file in libs.iter() {
                let path = collect_path.join(file);
                let libpath = collect_path.join(format!(
                  ".lib/dylib/{}",
                  path.file_name().unwrap().to_string_lossy()
                ));

                std::fs::copy(path, libpath).map_err(mlua::Error::external)?;
              }

              Ok(())
            })?,
          )?;

          lua.globals().set(
            "set_stub",
            lua.create_function(move |_, path: String| {
              set_exec_path(path);
              Ok(())
            })?,
          )?;

          let stubs_fn =
            lua.create_async_function(async move |_, stubs: HashMap<String, String>| {
              let current_os = std::env::consts::OS;

              let url = if let Some(url) = stubs.get(current_os) {
                Ok(url)
              } else if let Some(url) =
                stubs.get(&format!("{}-{}", current_os, std::env::consts::ARCH))
              {
                Ok(url)
              } else {
                Err(mlua::Error::external(format!(
                  "No stub found for OS: {}",
                  current_os
                )))
              }?;

              let path = if url.starts_with("http") {
                let cache_path = PackageManager::new()
                  .map_err(|e| {
                    eprintln!("Failed to initialize package manager: {}", e);
                    mlua::Error::external(e)
                  })?
                  .download_file(url)
                  .await
                  .map_err(|e| {
                    eprintln!("Failed to download file: {}", e);
                    mlua::Error::external(e)
                  })?;

                let file_name = url
                  .split('/')
                  .last()
                  .ok_or_else(|| mlua::Error::external("Invalid URL: missing file name"))?;

                let file_path = cache_path.join(file_name);

                #[cfg(unix)]
                {
                  use std::os::unix::fs::PermissionsExt;
                  let mut perms = std::fs::metadata(file_path.clone())?.permissions();
                  perms.set_mode(perms.mode() | 0o111);
                  std::fs::set_permissions(file_path.clone(), perms)?;
                }

                file_path
              } else {
                Path::new(url).to_path_buf()
              };

              set_exec_path(path);
              Ok(())
            })?;

          lua.globals().set("stubs_async", stubs_fn)?;

          lua.globals().set(
            "stubs",
            lua
              .load(mlua::chunk! {
                local f = coroutine.create(function(...)
                  stubs_async(...)
                  return false
                end)
                local done = true
                while done do
                  done = coroutine.resume(f, ...)
                end
              })
              .into_function()?,
          )?;

          let larc = lulu_arc.clone();
          lua.globals().set(
            "set_cfg_env",
            lua.create_function(move |_, (key, value): (String, String)| {
              let mut lulu = larc.lock().unwrap();
              lulu.compiler.defs.insert(key, value);
              Ok(())
            })?,
          )?;

          let bname = name.clone();
          let bundle_main_path = path.clone();
          let larc = lulu_arc.clone();
          lua.globals().set(
            "bundle_main",
            lua.create_function(move |_, (file, lulib): (String, Option<bool>)| {
              let is_lulib = if let Some(lulib) = lulib {
                lulib
              } else {
                false
              };
              let mut lulu = larc.lock().unwrap();
              bundle_lulu_or_exec(
                &mut lulu,
                bundle_main_path.join(file).to_path_buf(),
                Path::new(&format!(
                  ".lib/{}{}",
                  bname.clone(),
                  if is_lulib { ".lulib" } else { "" }
                ))
                .to_path_buf(),
              )
            })?,
          )?;

          let build_path = path.clone();
          let build =
            into_exec_command!(lua, env, (file: String), "build", build_path.clone().join(file));

          let resolve_path = path.clone();
          let resolve_dependencies =
            into_exec_command!(lua, env, (), "resolve", resolve_path.clone());

          let exists_path = path.clone();
          let exists_func =
            lua.create_function(move |_, name: String| Ok(exists_path.join(name).exists()))?;

          lua
            .globals()
            .set("resolve_dependencies", resolve_dependencies)?;

          lua.globals().set("bundle", bundle)?;
          // lua.globals().set("bundle_main", bundle_main_entry)?;
          // lua
          //   .globals()
          //   .set("bundle_main_exec", bundle_main_entry_exec)?;
          lua.globals().set("build", build)?;
          lua.globals().set("exists", exists_func)?;

          handle_error!(build_fn_lua.call::<()>(()));
        }
      }
      Commands::Update { packages, project } => {
        let pkg_manager = PackageManager::new().map_err(|e| {
          eprintln!("Failed to initialize package manager: {}", e);
          mlua::Error::external(e)
        })?;

        async {
          for package in packages {
            if let Err(e) = pkg_manager.clear_package_cache(package) {
              eprintln!("Warning: Failed to clear cache for {}: {}", package, e);
            }
          }

          match pkg_manager.install_packages(packages, project).await {
            Ok(_) => {}
            Err(e) => {
              eprintln!("Package update failed: {}", e);
            }
          }
        }
        .await;
      }
      Commands::New {
        name,
        git,
        lib,
        ignore,
      } => {
        project::new(name.clone(), *git, *ignore, *lib);
      }
      Commands::Cache { cache_command } => {
        let pkg_manager = PackageManager::new().map_err(|e| {
          eprintln!("Failed to initialize package manager: {}", e);
          mlua::Error::external(e)
        })?;

        match cache_command {
          CacheCommand::Clear => match pkg_manager.clear_cache() {
            Ok(()) => println!("Package cache cleared successfully"),
            Err(e) => eprintln!("Failed to clear cache: {}", e),
          },
          CacheCommand::List => match pkg_manager.list_cached_packages() {
            Ok(packages) => {
              if packages.is_empty() {
                println!("No cached packages found");
              } else {
                println!("Cached packages:");
                for package in packages {
                  println!("  - {}", package);
                }
              }
            }
            Err(e) => eprintln!("Failed to list cached packages: {}", e),
          },
          CacheCommand::Remove { package_url } => {
            match pkg_manager.clear_package_cache(package_url) {
              Ok(()) => println!("Package cache cleared for: {}", package_url),
              Err(e) => eprintln!("Failed to clear package cache: {}", e),
            }
          }
        }
      }
    }
  }

  let handles = std::mem::take(&mut *TOK_ASYNC_HANDLES.lock().unwrap());
  for handle in handles {
    let _ = handle.await;
  }
  Ok(())
}