Skip to content

Commit

Permalink
Merge pull request #17 from Berrysoft/dev/log-default
Browse files Browse the repository at this point in the history
Simplify unwrap-or-else-log with trylog.
  • Loading branch information
Berrysoft committed Sep 27, 2022
2 parents 46787fc + ad24097 commit 7f37838
Show file tree
Hide file tree
Showing 10 changed files with 85 additions and 114 deletions.
1 change: 1 addition & 0 deletions bins/ayaka-gui/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ serde = { version = "1.0", features = ["derive"] }
tauri = { version = "1.0", features = ["cli", "protocol-all", "window-all"] }
tauri-plugin-localhost = "0.1"
portpicker = "0.1"
trylog = "0.1"

[features]
default = [ "custom-protocol" ]
Expand Down
46 changes: 13 additions & 33 deletions bins/ayaka-gui/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

use ayaka_runtime::{
anyhow::{self, anyhow, Result},
log::{debug, error, info, warn},
log::{debug, info},
*,
};
use flexi_logger::{FileSpec, LogSpecification, Logger};
Expand All @@ -15,6 +15,7 @@ use std::{
fmt::Display,
};
use tauri::{async_runtime::Mutex, command, AppHandle, Manager, State};
use trylog::TryLog;

type CommandResult<T> = std::result::Result<T, CommandError>;

Expand Down Expand Up @@ -126,27 +127,18 @@ async fn open_game(handle: AppHandle, storage: State<'_, Storage>) -> CommandRes
window.set_title(&ctx.game.config.title)?;
let settings = {
OpenGameStatus::LoadSettings.emit(&handle)?;
load_settings(&storage.ident).unwrap_or_else(|e| {
warn!("Load settings failed: {}", e);
Settings::new()
})
load_settings(&storage.ident).unwrap_or_default_log("Load settings failed")
};
*storage.settings.lock().await = Some(settings);

OpenGameStatus::LoadGlobalRecords.emit(&handle)?;
let global_record =
load_global_record(&storage.ident, &ctx.game.config.title).unwrap_or_else(|e| {
warn!("Load global records failed: {}", e);
Default::default()
});
let global_record = load_global_record(&storage.ident, &ctx.game.config.title)
.unwrap_or_default_log("Load global records failed");
*storage.global_record.lock().await = Some(global_record);

OpenGameStatus::LoadRecords.emit(&handle)?;
*storage.records.lock().await = load_records(&storage.ident, &ctx.game.config.title)
.unwrap_or_else(|e| {
warn!("Load records failed: {}", e);
Default::default()
});
.unwrap_or_default_log("Load records failed");
*storage.context.lock().await = Some(ctx);

OpenGameStatus::Loaded.emit(&handle)?;
Expand Down Expand Up @@ -288,9 +280,7 @@ async fn next_run(storage: State<'_, Storage>) -> CommandResult<bool> {
if let Some(raw_ctx) = context.next_run() {
debug!("Next action: {:?}", raw_ctx);
let is_empty = {
let action = context
.get_action(&context.game.config.base_lang, &raw_ctx)
.unwrap_or_default();
let action = context.get_action(&context.game.config.base_lang, &raw_ctx)?;
if let Action::Empty = action {
true
} else if let Action::Custom(vars) = action {
Expand Down Expand Up @@ -336,10 +326,7 @@ async fn current_visited(storage: State<'_, Storage>) -> CommandResult<bool> {
let raw_ctx = storage.current.lock().await;
let visited = if let Some(raw_ctx) = raw_ctx.as_ref() {
let record = storage.global_record.lock().await;
record
.as_ref()
.map(|record| record.visited(raw_ctx))
.unwrap_or_default()
record.as_ref().unwrap().visited(raw_ctx)
} else {
false
};
Expand All @@ -359,18 +346,11 @@ fn get_actions(
) -> (Action, Option<Action>) {
let action = context
.get_action(&settings.lang, raw_ctx)
.unwrap_or_else(|e| {
error!("Cannot get action: {}", e);
Action::default()
});
let base_action = settings.sub_lang.as_ref().and_then(|sub_lang| {
match context.get_action(sub_lang, raw_ctx) {
Ok(action) => Some(action),
Err(e) => {
error!("Cannot get sub action: {}", e);
None
}
}
.unwrap_or_default_log("Cannot get action");
let base_action = settings.sub_lang.as_ref().map(|sub_lang| {
context
.get_action(sub_lang, raw_ctx)
.unwrap_or_default_log("Cannot get sub action")
});
(action, base_action)
}
Expand Down
1 change: 1 addition & 0 deletions plugins/random/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ crate-type = ["cdylib"]
[dependencies]
ayaka-bindings = { path = "../../utils/ayaka-bindings" }
rand = "0.8"
trylog = "0.1"
22 changes: 11 additions & 11 deletions plugins/random/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use ayaka_bindings::*;
use rand::{rngs::StdRng, Rng, SeedableRng};
use std::sync::{LazyLock, Mutex};
use trylog::TryLog;

#[export]
fn plugin_type() -> PluginType {
Expand All @@ -13,15 +14,14 @@ static RNG: LazyLock<Mutex<StdRng>> = LazyLock::new(|| Mutex::new(StdRng::from_e

#[export]
fn rnd(args: Vec<RawValue>) -> RawValue {
if let Ok(mut rng) = RNG.lock() {
let res = match args.len() {
0 => rng.gen(),
1 => rng.gen_range(0..args[0].get_num()),
_ => rng.gen_range(args[0].get_num()..args[1].get_num()),
};
RawValue::Num(res)
} else {
log::error!("Cannot get random engine.");
RawValue::Unit
}
RNG.lock()
.map(|mut rng| {
let res = match args.len() {
0 => rng.gen(),
1 => rng.gen_range(0..args[0].get_num()),
_ => rng.gen_range(args[0].get_num()..args[1].get_num()),
};
RawValue::Num(res)
})
.unwrap_or_default_log("Cannot get random engine")
}
1 change: 1 addition & 0 deletions utils/ayaka-runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ futures-util = "0.3"
tryiterator = { git = "https://github.com/Pernosco/tryiterator.git" }
dirs = "4.0"
scopeguard = "1.1"
trylog = "0.1"

[dev-dependencies]
tokio = { version = "1", features = ["parking_lot", "rt"] }
57 changes: 28 additions & 29 deletions utils/ayaka-runtime/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use std::{
path::{Path, PathBuf},
};
use stream_future::stream;
use trylog::TryLog;

/// The game running context.
pub struct Context {
Expand Down Expand Up @@ -94,13 +95,14 @@ impl Context {
for rl in std::fs::read_dir(res_path)? {
let p = rl?.path();
if p.is_file() && p.extension().unwrap_or_default() == "yaml" {
let loc = p
if let Some(loc) = p
.file_stem()
.and_then(|s| s.to_string_lossy().parse::<Locale>().ok())
.unwrap_or_default();
let r = std::fs::read(p)?;
let r = serde_yaml::from_slice(&r)?;
res.insert(loc, r);
{
let r = std::fs::read(p)?;
let r = serde_yaml::from_slice(&r)?;
res.insert(loc, r);
}
}
}
}
Expand All @@ -111,25 +113,26 @@ impl Context {
for pl in std::fs::read_dir(paras_path)? {
let p = pl?.path();
if p.is_dir() {
let loc = p
if let Some(loc) = p
.file_name()
.and_then(|s| s.to_string_lossy().parse::<Locale>().ok())
.unwrap_or_default();
let mut paras_map = HashMap::new();
for p in std::fs::read_dir(p)? {
let p = p?.path();
if p.is_file() && p.extension().unwrap_or_default() == "yaml" {
let key = p
.file_stem()
.unwrap_or_default()
.to_string_lossy()
.into_owned();
let para = std::fs::read(p)?;
let para = serde_yaml::from_slice(&para)?;
paras_map.insert(key, para);
{
let mut paras_map = HashMap::new();
for p in std::fs::read_dir(p)? {
let p = p?.path();
if p.is_file() && p.extension().unwrap_or_default() == "yaml" {
let key = p
.file_stem()
.unwrap_or_default()
.to_string_lossy()
.into_owned();
let para = std::fs::read(p)?;
let para = serde_yaml::from_slice(&para)?;
paras_map.insert(key, para);
}
}
paras.insert(loc, paras_map);
}
paras.insert(loc, paras_map);
}
}
Ok(Self {
Expand Down Expand Up @@ -428,16 +431,12 @@ impl Context {
}
};

// TODO: reduce clone
let ctx = if let Some(t) = cur_text_base.cloned() {
self.process_line(t).unwrap_or_else(|e| {
error!("Parse line error: {}", e);
});
let ctx = cur_text_base.cloned().map(|t| {
self.process_line(t)
.unwrap_or_default_log("Parse line error");
self.push_history();
Some(self.ctx.clone())
} else {
None
};
self.ctx.clone()
});
self.ctx.cur_act += 1;
ctx
}
Expand Down
53 changes: 27 additions & 26 deletions utils/ayaka-runtime/src/script.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
use crate::plugin::Runtime;
use ayaka_bindings_types::VarMap;
use ayaka_script::*;
use log::{error, warn};
use log::warn;
use trylog::TryLog;

/// The variable table in scripts.
pub struct VarTable<'a> {
Expand Down Expand Up @@ -208,32 +209,31 @@ fn call(ctx: &mut VarTable, ns: &str, name: &str, args: &[Expr]) -> RawValue {
}
} else {
let args = args.iter().map(|e| e.call(ctx)).collect::<Vec<_>>();
if let Some(runtime) = ctx.runtime.modules.get(ns) {
match runtime.dispatch_method(name, &args) {
Ok(res) => res,
Err(e) => {
error!("Calling `{}.{}` error: {}", ns, name, e);
RawValue::Unit
}
}
} else {
error!("Cannot find namespace `{}`.", ns);
RawValue::Unit
}
ctx.runtime
.modules
.get(ns)
.map(|runtime| {
runtime
.dispatch_method(name, &args)
.unwrap_or_default_log_with(|| format!("Calling `{}.{}` error", ns, name))
})
.unwrap_or_default_log_with(|| format!("Cannot find namespace `{}`", ns))
}
}

impl Callable for Ref {
fn call(&self, ctx: &mut VarTable) -> RawValue {
match self {
Self::Var(n) => ctx.vars.get(n).cloned().unwrap_or_else(|| {
warn!("Cannot find variable `{}`.", n);
Default::default()
}),
Self::Ctx(n) => ctx.locals.get(n).cloned().unwrap_or_else(|| {
warn!("Cannot find context variable `{}`.", n);
Default::default()
}),
Self::Var(n) => ctx
.vars
.get(n)
.cloned()
.unwrap_or_default_log("Cannot find variable"),
Self::Ctx(n) => ctx
.locals
.get(n)
.cloned()
.unwrap_or_default_log("Cannot find context variable"),
}
}
}
Expand All @@ -249,12 +249,13 @@ impl Callable for Text {
Command::Character(_, _) => RawValue::Unit,
Command::Res(_) | Command::Other(_, _) => {
warn!("Unsupported command in text.");
Default::default()
RawValue::Unit
}
Command::Ctx(n) => ctx.locals.get(n).cloned().unwrap_or_else(|| {
warn!("Cannot find variable `{}`.", n);
Default::default()
}),
Command::Ctx(n) => ctx
.locals
.get(n)
.cloned()
.unwrap_or_default_log("Cannot find variable"),
};
str.push_str(&value.get_str());
}
Expand Down
10 changes: 0 additions & 10 deletions utils/ayaka-runtime/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,6 @@ pub struct Settings {
pub sub_lang: Option<Locale>,
}

impl Settings {
/// Creates [`Settings`] object with current locale.
pub fn new() -> Self {
Self {
lang: Locale::default(),
sub_lang: None,
}
}
}

/// The global record.
#[derive(Debug, Default, Clone, Deserialize, Serialize)]
pub struct GlobalRecord {
Expand Down
1 change: 1 addition & 0 deletions utils/ayaka-script/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ serde_with = "2.0"
lalrpop-util = { version = "0.19", features = ["lexer"] }
regex = "1"
log = "0.4"
trylog = "0.1"

[dev-dependencies]
serde_yaml = "0.9"
Expand Down
7 changes: 2 additions & 5 deletions utils/ayaka-script/src/exec/grammer.lalrpop
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::*;
use log::warn;
use std::str::FromStr;
use trylog::TryLog;

grammar;

Expand Down Expand Up @@ -117,9 +117,6 @@ Bool: bool = {
"false" => false,
}

Num: i64 = <s:r"[0-9]+"> => i64::from_str(s).unwrap_or_else(|e| {
warn!("{}", e);
0
});
Num: i64 = <s:r"[0-9]+"> => i64::from_str(s).unwrap_or_default_log("Parse num error");

Str: String = <s:r##""[^"\\]*(\\.[^"\\]*)*""##> => s[1..s.len() - 1].into();

0 comments on commit 7f37838

Please sign in to comment.