diff --git a/crates/model/src/comp/load.rs b/crates/model/src/comp/load.rs index f8801a586212f6e075479247cea5b23687022856..b682db0ee04d4ab5595ed382a52881833d4ea981 100644 --- a/crates/model/src/comp/load.rs +++ b/crates/model/src/comp/load.rs @@ -22,10 +22,13 @@ impl Comp { } pub fn from_fusion_str(text: &str) -> Result { - let root_val = parse_lua(text)?; - let root = root_val - .as_table() - .ok_or_else(|| ParseError { offset: 0, line: 1, message: "comp root is not a table".into() })?; + let LuaValue::Table(root) = parse_lua(text)? else { + return Err(ParseError { + offset: 0, + line: 1, + message: "comp root is not a table".into(), + }); + }; let current_time = root.get_f64("CurrentTime").unwrap_or(0.0); let global_range = root @@ -70,9 +73,11 @@ impl Comp { } } - let mut nodes = Vec::new(); - let mut node_by_name = HashMap::new(); - let mut splines = HashMap::new(); + let tools_len = root.get_table("Tools").map_or(0, |t| t.entries.len()); + let approx_nodes = tools_len / 2; + let mut nodes = Vec::with_capacity(approx_nodes); + let mut node_by_name = HashMap::with_capacity(approx_nodes); + let mut splines = HashMap::with_capacity(tools_len - approx_nodes); let mut poly_paths = HashMap::new(); let mut gradient_modifiers = HashMap::new(); let mut text_modifiers = HashMap::new(); @@ -117,35 +122,45 @@ impl Comp { // For MacroOperator/GroupOperator Flow display: wire external inputs from inner InstanceInput targets // so Flow shows `Transform1 -> Invert -> Merge2` cleanly while `engine` follows `macro_output`. - let node_inputs_snapshot: Vec<(String, HashMap)> = nodes - .iter() - .map(|n| (n.name.clone(), n.inputs.clone())) - .collect(); - let snap_map: HashMap> = node_inputs_snapshot.into_iter().collect(); - for n in &mut nodes { - if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") { - let mut flow_wires = HashMap::new(); + if nodes.iter().any(|n| matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator")) { + let mut name_to_idx: HashMap<&str, usize> = HashMap::with_capacity(nodes.len()); + for (idx, n) in nodes.iter().enumerate() { + name_to_idx.insert(n.name.as_str(), idx); + } + let mut group_wires: Vec<(usize, Vec<(String, InputBinding)>)> = Vec::new(); + for (idx, n) in nodes.iter().enumerate() { + if !matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") { + continue; + } + let mut flow_wires = Vec::new(); for (in_name, b) in &n.inputs { if let (Some(inner_op), Some(inner_port)) = (&b.source_op, &b.source_output) { - if let Some(inner_in) = snap_map.get(inner_op).and_then(|m| m.get(inner_port)) { - if let Some(ext_src) = &inner_in.source_op { - // Only connect if ext_src is a visible (non-internal) flow node - if node_by_name.get(ext_src).is_some_and(|&id| !snap_map.is_empty() && id != n.id) { - flow_wires.insert( - in_name.clone(), - InputBinding { - value: None, - source_op: Some(ext_src.clone()), - source_output: inner_in.source_output.clone(), - expression: None, - }, - ); + if let Some(&inner_idx) = name_to_idx.get(inner_op.as_str()) { + if let Some(inner_in) = nodes[inner_idx].inputs.get(inner_port) { + if let Some(ext_src) = &inner_in.source_op { + // Only connect if ext_src is a visible (non-internal) flow node + if node_by_name.get(ext_src).is_some_and(|&id| id != n.id) { + flow_wires.push(( + in_name.clone(), + InputBinding { + value: None, + source_op: Some(ext_src.clone()), + source_output: inner_in.source_output.clone(), + expression: None, + }, + )); + } } } } } } - n.inputs.extend(flow_wires); + if !flow_wires.is_empty() { + group_wires.push((idx, flow_wires)); + } + } + for (idx, wires) in group_wires { + nodes[idx].inputs.extend(wires); } } @@ -163,13 +178,20 @@ impl Comp { .map(|mid| (*nid, mid)) }) .collect(); - let orig_inputs: Vec> = - nodes.iter().map(|n| n.inputs.clone()).collect(); + let mut orig_inputs: HashMap> = + HashMap::with_capacity(parent_of.len()); + for &pid in parent_of.values() { + orig_inputs + .entry(pid) + .or_insert_with(|| nodes[pid.0].inputs.clone()); + } + let mut visited = HashSet::new(); + let mut blocked: HashSet = HashSet::new(); for &(nid, _) in &instanced_from { - let mut visited = HashSet::new(); + visited.clear(); visited.insert(nid); - let mut blocked: HashSet = HashSet::new(); + blocked.clear(); let mut cur = nid; for _depth in 0..8 { let Some(&pid) = parent_of.get(&cur) else { @@ -179,25 +201,26 @@ impl Comp { break; } let inst_inputs = &mut nodes[nid.0].inputs; - for (inp_name, parent_binding) in &orig_inputs[pid.0] { - if is_non_inheritable_instance_port(inp_name, parent_binding, &node_by_name) - { - continue; - } - if blocked.contains(inp_name) { - continue; - } - if parent_binding.value.is_none() - && parent_binding.source_op.is_none() - && parent_binding.expression.is_none() - { - // An empty `Param = Input {}` on an ancestor marks a de-instanced - // override to default and stops further inheritance up the chain. - blocked.insert(inp_name.clone()); - continue; - } - if !inst_inputs.contains_key(inp_name) { - inst_inputs.insert(inp_name.clone(), parent_binding.clone()); + if let Some(parent_map) = orig_inputs.get(&pid) { + for (inp_name, parent_binding) in parent_map { + if is_non_inheritable_instance_port(inp_name, parent_binding, &node_by_name) { + continue; + } + if blocked.contains(inp_name) { + continue; + } + if parent_binding.value.is_none() + && parent_binding.source_op.is_none() + && parent_binding.expression.is_none() + { + // An empty `Param = Input {}` on an ancestor marks a de-instanced + // override to default and stops further inheritance up the chain. + blocked.insert(inp_name.clone()); + continue; + } + if !inst_inputs.contains_key(inp_name) { + inst_inputs.insert(inp_name.clone(), parent_binding.clone()); + } } } cur = pid; @@ -217,19 +240,21 @@ impl Comp { "GreenSuppress", "BlueSuppress", ]; - let mut hue_spline_names: HashSet = HashSet::new(); - for n in &nodes { - if n.kind == "HueCurves" { - for &port in HUE_CURVE_PORTS { - if let Some(sp_name) = n.connected_node(port) { - hue_spline_names.insert(sp_name.to_owned()); + if !splines.is_empty() && nodes.iter().any(|n| n.kind == "HueCurves") { + let mut hue_spline_names: HashSet = HashSet::new(); + for n in &nodes { + if n.kind == "HueCurves" { + for &port in HUE_CURVE_PORTS { + if let Some(sp_name) = n.connected_node(port) { + hue_spline_names.insert(sp_name.to_owned()); + } } } } - } - for sp_name in hue_spline_names { - if let Some(sp) = splines.get_mut(&sp_name) { - sp.apply_hue_curves_cyclic_ends(); + for sp_name in hue_spline_names { + if let Some(sp) = splines.get_mut(&sp_name) { + sp.apply_hue_curves_cyclic_ends(); + } } } @@ -272,7 +297,7 @@ impl Comp { shakes, expression_modifiers, cross_macro_wires, - raw_root: Some(root.clone()), + raw_root: Some(root), revision: NEXT_COMP_REVISION.fetch_add(REVISION_STRIDE, Ordering::Relaxed), }) } @@ -284,9 +309,25 @@ impl Comp { /// unrelated macro stays unconnected. Returns the `(node, port)` wires whose `source_op` was /// cleared here so saving keeps the original text. fn clear_cross_macro_wires(nodes: &mut [Node], owner: &HashMap) -> HashSet<(String, String)> { - let mut by_name: HashMap<&str, Vec> = HashMap::new(); + if owner.is_empty() { + return HashSet::new(); + } + enum NameMatches { + One(NodeId), + Many(Vec), + } + let mut by_name: HashMap<&str, NameMatches> = HashMap::with_capacity(nodes.len()); for n in nodes.iter() { - by_name.entry(n.name.as_str()).or_default().push(n.id); + match by_name.get_mut(n.name.as_str()) { + None => { + by_name.insert(n.name.as_str(), NameMatches::One(n.id)); + } + Some(NameMatches::One(first)) => { + let first = *first; + by_name.insert(n.name.as_str(), NameMatches::Many(vec![first, n.id])); + } + Some(NameMatches::Many(v)) => v.push(n.id), + } } let encloses = |outer: NodeId, mut inner: NodeId| { loop { @@ -314,7 +355,11 @@ fn clear_cross_macro_wires(nodes: &mut [Node], owner: &HashMap) let Some(candidates) = b.source_op.as_deref().and_then(|s| by_name.get(s)) else { continue; }; - if !candidates.iter().any(|&t| in_scope(n_scope, t)) { + let any_in_scope = match candidates { + NameMatches::One(t) => in_scope(n_scope, *t), + NameMatches::Many(vec) => vec.iter().any(|&t| in_scope(n_scope, t)), + }; + if !any_in_scope { cleared.push((n.id, port.clone())); } } @@ -368,11 +413,34 @@ fn is_non_inheritable_instance_port( } pub(super) fn parse_input_binding(t: &LuaTable) -> InputBinding { - let source_op = t.get_str("SourceOp").map(str::to_owned); - let source_output = t.get_str("Source").map(str::to_owned); - let expression = t.get_str("Expression").map(str::to_owned); - - let value = t.get("Value").map(parse_param_value); + let mut source_op = None; + let mut source_output = None; + let mut expression = None; + let mut value = None; + for (k, v) in &t.entries { + let LuaKey::Str(s) = k else { continue }; + match s.as_str() { + "SourceOp" => { + if let Some(sv) = v.as_str() { + source_op = Some(sv.to_owned()); + } + } + "Source" => { + if let Some(sv) = v.as_str() { + source_output = Some(sv.to_owned()); + } + } + "Expression" => { + if let Some(sv) = v.as_str() { + expression = Some(sv.to_owned()); + } + } + "Value" => { + value = Some(parse_param_value(v)); + } + _ => {} + } + } InputBinding { value, source_op, @@ -407,9 +475,8 @@ pub(super) fn parse_param_value(v: &LuaValue) -> ParamValue { } } -fn try_parse_gradient_keyframes(table: &LuaTable) -> Option> { - let kfs = table.get_table("KeyFrames")?; - let mut grads = Vec::new(); +fn try_parse_gradient_keyframes(kfs: &LuaTable) -> Option> { + let mut grads = Vec::with_capacity(kfs.entries.len()); for (k, v) in &kfs.entries { let time = match k { LuaKey::Index(i) => *i as f64, @@ -433,9 +500,8 @@ fn try_parse_gradient_keyframes(table: &LuaTable) -> Option Some(grads) } -fn try_parse_text_keyframes(table: &LuaTable) -> Option> { - let kfs = table.get_table("KeyFrames")?; - let mut texts = Vec::new(); +fn try_parse_text_keyframes(kfs: &LuaTable) -> Option> { + let mut texts = Vec::with_capacity(kfs.entries.len()); for (k, v) in &kfs.entries { let time = match k { LuaKey::Index(i) => *i as f64, @@ -458,9 +524,8 @@ fn try_parse_text_keyframes(table: &LuaTable) -> Option> { Some(texts) } -fn try_parse_polyline_keyframes(table: &LuaTable) -> Option)>> { - let kfs = table.get_table("KeyFrames")?; - let mut shapes = Vec::new(); +fn try_parse_polyline_keyframes(kfs: &LuaTable) -> Option)>> { + let mut shapes = Vec::with_capacity(kfs.entries.len()); for (k, v) in &kfs.entries { let time = match k { LuaKey::Index(i) => *i as f64, @@ -505,25 +570,43 @@ fn parse_tools_table( for (key, val) in &tools.entries { let LuaKey::Str(name) = key else { continue }; let Some(tbl) = val.as_table() else { continue }; - let kind = tbl.tag.clone().unwrap_or_else(|| "Unknown".to_owned()); + let kind_ref = tbl.tag.as_deref().unwrap_or("Unknown"); - if kind == "BezierSpline" || kind == "LUTBezier" { - if let Some(grads) = try_parse_gradient_keyframes(tbl) { - gradient_modifiers.insert(name.clone(), grads); - } else if let Some(txts) = try_parse_text_keyframes(tbl) { - text_splines.insert(name.clone(), txts); - } else if let Some(polys) = try_parse_polyline_keyframes(tbl) { - polyline_splines.insert(name.clone(), (BezierSpline::from_lua(name.clone(), tbl), polys)); - } else { - splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl)); + if kind_ref == "BezierSpline" || kind_ref == "LUTBezier" { + if let Some(kfs) = tbl.get_table("KeyFrames") { + let first_val_tag = kfs.entries.iter().find_map(|(k, v)| { + if !matches!(k, LuaKey::Index(_) | LuaKey::Number(_)) { + return None; + } + let kt = v.as_table()?; + kt.get_table("Value") + .or_else(|| kt.get_index(1).and_then(LuaValue::as_table)) + .and_then(|t| t.tag.as_deref()) + }); + match first_val_tag { + Some("Gradient") if try_parse_gradient_keyframes(kfs).is_some_and(|g| { gradient_modifiers.insert(name.clone(), g); true }) => { + continue; + } + Some("Text" | "StyledText") if try_parse_text_keyframes(kfs).is_some_and(|t| { text_splines.insert(name.clone(), t); true }) => { + continue; + } + Some("Polyline") if try_parse_polyline_keyframes(kfs).is_some_and(|p| { + polyline_splines.insert(name.clone(), (BezierSpline::from_lua(name.clone(), tbl), p)); + true + }) => { + continue; + } + _ => {} + } } + splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl)); continue; } - if kind == "PolyPath" || kind == "Path" { + if kind_ref == "PolyPath" || kind_ref == "Path" { poly_paths.insert(name.clone(), PolyPath::from_lua(name.clone(), tbl)); continue; } - if kind == "TrackerModifier" { + if kind_ref == "TrackerModifier" { if let Some(in_tbl) = tbl.get_table("Inputs") { if let Some(src_op) = in_tbl .get_table("TrackedCenter0") @@ -557,7 +640,7 @@ fn parse_tools_table( } continue; } - if kind == "StyledTextCLS" || kind == "CharacterLevelStyling" { + if kind_ref == "StyledTextCLS" || kind_ref == "CharacterLevelStyling" { if let Some(in_tbl) = tbl.get_table("Inputs") { if let Some(txt_in) = in_tbl.get_table("Text").or_else(|| in_tbl.get_table("StyledText")) { if let Some(txt) = txt_in @@ -607,9 +690,10 @@ fn parse_tools_table( } continue; } - if kind == "Shake" { + if kind_ref == "Shake" { let mut inputs = HashMap::new(); if let Some(in_tbl) = tbl.get_table("Inputs") { + inputs.reserve(in_tbl.entries.len()); for (ik, iv) in &in_tbl.entries { let LuaKey::Str(in_name) = ik else { continue }; let Some(it) = iv.as_table() else { continue }; @@ -619,9 +703,10 @@ fn parse_tools_table( shakes.insert(name.clone(), ShakeModifier { inputs }); continue; } - if kind == "Expression" { + if kind_ref == "Expression" { let mut inputs = HashMap::new(); if let Some(in_tbl) = tbl.get_table("Inputs") { + inputs.reserve(in_tbl.entries.len()); for (ik, iv) in &in_tbl.entries { let LuaKey::Str(in_name) = ik else { continue }; let Some(it) = iv.as_table() else { continue }; @@ -653,23 +738,45 @@ fn parse_tools_table( expression_modifiers.insert(name.clone(), ExpressionModifier { inputs }); continue; } - if is_modifier_type(&kind) { + if is_modifier_type(kind_ref) { if tbl.get_table("KeyFrames").is_some() { splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl)); } continue; } - let pos = tbl - .get_table("ViewInfo") + let mut view_info_tbl: Option<&LuaTable> = None; + let mut bypassed = false; + let mut inputs_tbl: Option<&LuaTable> = None; + let mut user_controls_tbl: Option<&LuaTable> = None; + let mut clips_tbl: Option<&LuaTable> = None; + let mut inner_tools_tbl: Option<&LuaTable> = None; + let mut outputs_tbl: Option<&LuaTable> = None; + let mut source_op_str: Option<&str> = None; + for (tk, tv) in &tbl.entries { + let LuaKey::Str(s) = tk else { continue }; + match s.as_str() { + "ViewInfo" => view_info_tbl = tv.as_table(), + "PassThrough" => if let Some(b) = tv.as_bool() { bypassed = b; }, + "Inputs" => inputs_tbl = tv.as_table(), + "UserControls" => user_controls_tbl = tv.as_table(), + "Clips" => clips_tbl = tv.as_table(), + "Tools" => inner_tools_tbl = tv.as_table(), + "Outputs" => outputs_tbl = tv.as_table(), + "SourceOp" => source_op_str = tv.as_str(), + _ => {} + } + } + + let pos = view_info_tbl .and_then(|vi| vi.get_table("Pos")) .and_then(read_vec2) .map(|[x, y]| [x as f32, y as f32]) .unwrap_or([0.0, 0.0]); - let bypassed = tbl.get_bool("PassThrough").unwrap_or(false); let mut inputs = HashMap::new(); - if let Some(in_tbl) = tbl.get_table("Inputs") { + if let Some(in_tbl) = inputs_tbl { + inputs.reserve(in_tbl.entries.len()); for (ik, iv) in &in_tbl.entries { let LuaKey::Str(in_name) = ik else { continue }; let Some(it) = iv.as_table() else { continue }; @@ -679,7 +786,7 @@ fn parse_tools_table( } // Populate defaults declared in Fusion `UserControls` (needed for ShakeTransform, Custom, etc.) - if let Some(uc) = tbl.get_table("UserControls") { + if let Some(uc) = user_controls_tbl { for (uk, uv) in &uc.entries { let LuaKey::Str(uname) = uk else { continue }; let Some(ut) = uv.as_table() else { continue }; @@ -712,34 +819,18 @@ fn parse_tools_table( } let mut clips = Vec::new(); - if let Some(clips_tbl) = tbl.get_table("Clips") { + if let Some(clips_tbl) = clips_tbl { for (_, cv) in &clips_tbl.entries { if let Some(ct) = cv.as_table() { - if let Some(filename) = ct.get_str("Filename") { - clips.push(ClipSpec { - filename: filename.to_owned(), - alternate_filename: ct.get_str("AlternateFilename").map(str::to_owned), - start_frame: ct.get_f64("StartFrame").unwrap_or(-1.0) as i64, - length: ct.get_f64("Length").map(|v| v as i64), - trim_in: ct.get_f64("TrimIn").unwrap_or(0.0) as i64, - trim_out: ct.get_f64("TrimOut").unwrap_or(0.0) as i64, - global_start: ct.get_f64("GlobalStart").unwrap_or(0.0) as i64, - global_end: ct.get_f64("GlobalEnd").unwrap_or(0.0) as i64, - extend_first: ct.get_f64("ExtendFirst").unwrap_or(0.0) as i64, - extend_last: ct.get_f64("ExtendLast").unwrap_or(0.0) as i64, - // Fusion `Clip.Loop` is a loop count: 0 = infinite loop (Loop ON), - // 1 (or omitted) = play once (Loop OFF). - loop_clip: ct.get_f64("Loop").is_some_and(|v| v == 0.0), - reverse: ct.get_bool("Reverse").unwrap_or(false), - }); + if let Some(clip) = parse_clip_spec(ct) { + clips.push(clip); } } } } - if kind == "Saver" && clips.is_empty() { - if let Some(c) = tbl - .get_table("Inputs") + if kind_ref == "Saver" && clips.is_empty() { + if let Some(c) = inputs_tbl .and_then(|i| i.get_table("Clip")) .and_then(|c| c.get_table("Value")) { @@ -763,8 +854,8 @@ fn parse_tools_table( } // ColorCurves and HueCurves embed their LUTBezier splines inside a nested `Tools` table! - if kind == "ColorCurves" || kind == "HueCurves" { - if let Some(inner_tools) = tbl.get_table("Tools") { + if kind_ref == "ColorCurves" || kind_ref == "HueCurves" { + if let Some(inner_tools) = inner_tools_tbl { parse_tools_table( inner_tools, true, @@ -788,13 +879,13 @@ fn parse_tools_table( let mut macro_output = None; let mut macro_inner_start = None; - if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") { - let mut out_name: Option = None; - if let Some(outs) = tbl.get_table("Outputs") { + if matches!(kind_ref, "MacroOperator" | "GroupOperator") { + let mut out_name: Option<&str> = None; + if let Some(outs) = outputs_tbl { for (_, ov) in &outs.entries { if let Some(ot) = ov.as_table() { if let Some(src_op) = ot.get_str("SourceOp") { - out_name = Some(src_op.to_owned()); + out_name = Some(src_op); break; } } @@ -802,7 +893,7 @@ fn parse_tools_table( } let inner_start = nodes.len(); macro_inner_start = Some(inner_start); - if let Some(inner_tools) = tbl.get_table("Tools") { + if let Some(inner_tools) = inner_tools_tbl { parse_tools_table( inner_tools, true, @@ -827,7 +918,7 @@ fn parse_tools_table( .iter() .find(|n| n.name == oname) .map(|n| n.id) - .or_else(|| node_by_name.get(&oname).copied()); + .or_else(|| node_by_name.get(oname).copied()); } } @@ -841,13 +932,13 @@ fn parse_tools_table( if !is_internal || !node_by_name.contains_key(name) { node_by_name.insert(name.clone(), id); } - if let Some(master) = tbl.get_str("SourceOp") { + if let Some(master) = source_op_str { instanced_from.push((id, master.to_owned())); } nodes.push(Node { id, name: name.clone(), - kind, + kind: kind_ref.to_owned(), pos, bypassed, internal: is_internal, @@ -859,6 +950,56 @@ fn parse_tools_table( } } +fn parse_clip_spec(ct: &LuaTable) -> Option { + let mut filename: Option<&str> = None; + let mut alternate_filename: Option<&str> = None; + let mut start_frame: i64 = -1; + let mut length: Option = None; + let mut trim_in: i64 = 0; + let mut trim_out: i64 = 0; + let mut global_start: i64 = 0; + let mut global_end: i64 = 0; + let mut extend_first: i64 = 0; + let mut extend_last: i64 = 0; + let mut loop_clip = false; + let mut reverse = false; + + for (k, v) in &ct.entries { + let LuaKey::Str(s) = k else { continue }; + match s.as_str() { + "Filename" => filename = v.as_str(), + "AlternateFilename" => alternate_filename = v.as_str(), + "StartFrame" => if let Some(n) = v.as_f64() { start_frame = n as i64; }, + "Length" => if let Some(n) = v.as_f64() { length = Some(n as i64); }, + "TrimIn" => if let Some(n) = v.as_f64() { trim_in = n as i64; }, + "TrimOut" => if let Some(n) = v.as_f64() { trim_out = n as i64; }, + "GlobalStart" => if let Some(n) = v.as_f64() { global_start = n as i64; }, + "GlobalEnd" => if let Some(n) = v.as_f64() { global_end = n as i64; }, + "ExtendFirst" => if let Some(n) = v.as_f64() { extend_first = n as i64; }, + "ExtendLast" => if let Some(n) = v.as_f64() { extend_last = n as i64; }, + "Loop" => if let Some(n) = v.as_f64() { loop_clip = n == 0.0; }, + "Reverse" => if let Some(b) = v.as_bool() { reverse = b; }, + _ => {} + } + } + + let filename = filename?; + Some(ClipSpec { + filename: filename.to_owned(), + alternate_filename: alternate_filename.map(str::to_owned), + start_frame, + length, + trim_in, + trim_out, + global_start, + global_end, + extend_first, + extend_last, + loop_clip, + reverse, + }) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/model/src/comp/save.rs b/crates/model/src/comp/save.rs index 0cd5381d108335b184ce10e1e580abda6fdc1d91..57a526ba45bc9a32d8528a44b7792488e4422fae 100644 --- a/crates/model/src/comp/save.rs +++ b/crates/model/src/comp/save.rs @@ -1,13 +1,61 @@ use super::load::{parse_input_binding, parse_param_value}; use super::math::find_raw_tool_mut; use super::{BitDepth, Comp, InputBinding, Node, ParamValue, is_modifier_type}; -use crate::lua_value::{LuaKey, LuaTable, LuaValue}; -use crate::spline::{BezierSpline, read_vec2}; -use std::collections::{HashMap, HashSet, VecDeque}; +use crate::lua_value::{ + LuaKey, LuaTable, LuaValue, can_use_positional, has_call_args, write_entry_key, write_indent, + write_table, write_table_prefix, write_value, +}; +use crate::spline::{BezierSpline, Gradient, HandleMode, KeyFlags, read_vec2}; +use std::collections::{HashMap, HashSet}; use std::io::Write; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; +enum NodePool<'a> { + One(&'a Node), + Many(Vec<&'a Node>, usize), +} + +impl<'a> NodePool<'a> { + fn push(&mut self, node: &'a Node) { + match self { + NodePool::One(first) => { + *self = NodePool::Many(vec![*first, node], 0); + } + NodePool::Many(v, _) => v.push(node), + } + } + + fn is_non_empty(&self) -> bool { + match self { + NodePool::One(_) => true, + NodePool::Many(v, idx) => *idx < v.len(), + } + } + + fn peek_at(&self, offset: usize) -> Option<&'a Node> { + match self { + NodePool::One(n) => (offset == 0).then_some(*n), + NodePool::Many(v, idx) => v.get(*idx + offset).copied(), + } + } +} + +fn pop_pool<'a>(pool: &mut HashMap<&'a str, NodePool<'a>>, name: &str) -> Option<&'a Node> { + match pool.get_mut(name)? { + NodePool::One(n) => { + let n = *n; + pool.remove(name); + Some(n) + } + NodePool::Many(v, idx) => { + let n = v.get(*idx).copied()?; + *idx += 1; + Some(n) + } + } +} + impl Comp { /// Synchronizes current comp state (metadata, node positions/bypass/inputs, spline edits, /// added/removed flow nodes) back onto a cloned raw Fusion `Composition { ... }` AST, @@ -87,10 +135,17 @@ impl Comp { tools.set(LuaKey::Str(node.name.clone()), LuaValue::Table(new_tbl)); } - let mut pool: HashMap<(bool, String), VecDeque<&Node>> = HashMap::new(); + let mut top_pool: HashMap<&str, NodePool<'_>> = HashMap::with_capacity(self.nodes.len()); + let mut inner_pool: HashMap<&str, NodePool<'_>> = HashMap::new(); let mut instance_defaults: HashMap<(&str, &str), ParamValue> = HashMap::new(); for node in &self.nodes { - pool.entry((node.internal, node.name.clone())).or_default().push_back(node); + let pool = if node.internal { &mut inner_pool } else { &mut top_pool }; + let key = node.name.as_str(); + if let Some(entry) = pool.get_mut(key) { + entry.push(node); + } else { + pool.insert(key, NodePool::One(node)); + } if !is_group_kind(&node.kind) { continue; } @@ -100,30 +155,33 @@ impl Comp { } } } - self.sync_tools_level(tools, false, &mut pool, &instance_defaults); + self.sync_tools_level(tools, false, &mut top_pool, &mut inner_pool, &instance_defaults); - // Sync BezierSpline edits (only touch splines that actually differ from the raw AST) - let mut spline_names: Vec<&String> = self.splines.keys().collect(); - spline_names.sort(); - for spline_name in spline_names { - let spline = &self.splines[spline_name]; - if let Some(tbl) = find_raw_tool_mut(tools, spline_name) { - sync_spline_table(spline_name, spline, tbl); - continue; + // Sync BezierSpline edits (walk `Tools` once in top-level-then-nested order -> O(T), not O(S * T)) + if !self.splines.is_empty() { + let mut remaining: HashMap<&str, &BezierSpline> = + self.splines.iter().map(|(k, v)| (k.as_str(), v)).collect(); + sync_existing_splines_in_tools(tools, &mut remaining); + if !remaining.is_empty() { + let mut new_names: Vec<&str> = remaining.keys().copied().collect(); + new_names.sort_unstable(); + for spline_name in new_names { + let spline = remaining[spline_name]; + let mut sp_tbl = LuaTable { + tag: Some("BezierSpline".to_owned()), + entries: Vec::with_capacity(2), + }; + sp_tbl.set( + LuaKey::Str("SplineColor".to_owned()), + spline_color_lua(spline.color), + ); + sp_tbl.set( + LuaKey::Str("KeyFrames".to_owned()), + LuaValue::Table(build_keyframes_table(spline)), + ); + tools.set(LuaKey::Str(spline_name.to_owned()), LuaValue::Table(sp_tbl)); + } } - let mut sp_tbl = LuaTable { - tag: Some("BezierSpline".to_owned()), - entries: Vec::new(), - }; - sp_tbl.set( - LuaKey::Str("SplineColor".to_owned()), - spline_color_lua(spline.color), - ); - sp_tbl.set( - LuaKey::Str("KeyFrames".to_owned()), - LuaValue::Table(build_keyframes_table(spline)), - ); - tools.set(LuaKey::Str(spline_name.clone()), LuaValue::Table(sp_tbl)); } root @@ -135,27 +193,35 @@ impl Comp { &'a self, tools: &mut LuaTable, internal: bool, - pool: &mut HashMap<(bool, String), VecDeque<&'a Node>>, + top_pool: &mut HashMap<&'a str, NodePool<'a>>, + inner_pool: &mut HashMap<&'a str, NodePool<'a>>, instance_defaults: &HashMap<(&str, &str), ParamValue>, ) { - tools.entries.retain(|(k, v)| { - let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { return true }; - is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) - || pool.get(&(internal, name.clone())).is_some_and(|q| !q.is_empty()) - }); + { + let pool = if internal { &*inner_pool } else { &*top_pool }; + tools.entries.retain(|(k, v)| { + let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { return true }; + is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) + || pool.get(name.as_str()).is_some_and(NodePool::is_non_empty) + }); + } for (k, v) in &mut tools.entries { let (LuaKey::Str(name), Some(tool_tbl)) = (&*k, v.as_table_mut()) else { continue }; if is_modifier_type(tool_tbl.tag.as_deref().unwrap_or("Unknown")) { continue; } - let Some(node) = pool.get_mut(&(internal, name.clone())).and_then(VecDeque::pop_front) else { + let node = { + let pool = if internal { &mut *inner_pool } else { &mut *top_pool }; + pop_pool(pool, name.as_str()) + }; + let Some(node) = node else { continue; }; self.sync_node_tool(node, tool_tbl, instance_defaults); if is_group_kind(&node.kind) { if let Some(inner) = tool_tbl.get_table_mut("Tools") { - self.sync_tools_level(inner, true, pool, instance_defaults); + self.sync_tools_level(inner, true, top_pool, inner_pool, instance_defaults); } sync_group_wiring(node, tool_tbl); } @@ -205,8 +271,12 @@ impl Comp { if node.kind == "Loader" { let edited = |port: &str| { let now = node.static_number(port)?; - let before = tool_tbl.get_table("Inputs").and_then(|i| i.get_table(port)).map(parse_input_binding); - (before.and_then(|b| b.value?.as_f64()) != Some(now)).then_some(now) + let before = tool_tbl + .get_table("Inputs") + .and_then(|i| i.get_table(port)) + .and_then(|t| t.get("Value")) + .and_then(lua_value_as_number); + (before != Some(now)).then_some(now) }; let updates = [ ("GlobalStart", edited("GlobalIn").map(LuaValue::Number)), @@ -240,6 +310,9 @@ impl Comp { /// Serializes this composition back to a Blackmagic Fusion `.comp` string. pub fn to_fusion_string(&self) -> String { + if let Some(s) = self.try_to_fusion_string_streaming() { + return s; + } let mut s = self.sync_to_raw_ast().to_fusion_string(); if !s.ends_with('\n') { s.push('\n'); @@ -247,6 +320,631 @@ impl Comp { s } + fn try_to_fusion_string_streaming(&self) -> Option { + let root = self.raw_root.as_ref()?; + if has_call_args(root) { + return None; + } + let tools = root.get_table("Tools")?; + if (tools.tag.as_deref() != Some("ordered") && tools.entries.len() <= 4) + || has_call_args(tools) + || !tools.entries.iter().all(|(k, _)| matches!(k, LuaKey::Str(_))) + { + return None; + } + + let cap = tools + .entries + .len() + .saturating_mul(1024) + .saturating_add(4096); + let mut out = String::with_capacity(cap); + + let mut top_pool: HashMap<&str, NodePool<'_>> = HashMap::with_capacity(self.nodes.len()); + let mut inner_pool: HashMap<&str, NodePool<'_>> = HashMap::new(); + let mut instance_defaults: HashMap<(&str, &str), ParamValue> = HashMap::new(); + for node in &self.nodes { + let pool = if node.internal { &mut inner_pool } else { &mut top_pool }; + let key = node.name.as_str(); + if let Some(entry) = pool.get_mut(key) { + entry.push(node); + } else { + pool.insert(key, NodePool::One(node)); + } + if !is_group_kind(&node.kind) { + continue; + } + for (inner_op, inner_port, default) in instance_inputs(&node.raw) { + if let Some(d) = default { + instance_defaults.insert((inner_op, inner_port), d); + } + } + } + + let positional = can_use_positional(root.entries.iter()); + write_table_prefix(root.tag.as_deref(), &[], 0, &mut out); + out.push_str("{\n"); + + let mut seen_current_time = false; + let mut seen_global_range = false; + let mut seen_render_range = false; + let mut seen_audio_filename = false; + let mut seen_audio_offset = false; + let mut seen_prefs = false; + let mut seen_tools = false; + + for (k, v) in &root.entries { + if let LuaKey::Str(name) = k { + match name.as_str() { + "CurrentTime" => { + seen_current_time = true; + write_indent(&mut out, 1); + write_entry_key(k, positional, &mut out); + write_value(&LuaValue::Number(self.current_time), 1, &mut out); + out.push_str(",\n"); + continue; + } + "GlobalRange" => { + seen_global_range = true; + write_indent(&mut out, 1); + write_entry_key(k, positional, &mut out); + let gr = vec2_lua(self.global_range[0] as f64, self.global_range[1] as f64); + write_value(&gr, 1, &mut out); + out.push_str(",\n"); + continue; + } + "RenderRange" => { + seen_render_range = true; + write_indent(&mut out, 1); + write_entry_key(k, positional, &mut out); + let rr = vec2_lua(self.render_range[0] as f64, self.render_range[1] as f64); + write_value(&rr, 1, &mut out); + out.push_str(",\n"); + continue; + } + "AudioFilename" => { + seen_audio_filename = true; + write_indent(&mut out, 1); + write_entry_key(k, positional, &mut out); + if let Some(ref af) = self.audio_filename { + write_value(&LuaValue::String(af.clone()), 1, &mut out); + } else { + write_value(v, 1, &mut out); + } + out.push_str(",\n"); + continue; + } + "AudioOffset" => { + seen_audio_offset = true; + write_indent(&mut out, 1); + write_entry_key(k, positional, &mut out); + write_value(&LuaValue::Number(self.audio_offset), 1, &mut out); + out.push_str(",\n"); + continue; + } + "Prefs" => { + seen_prefs = true; + write_indent(&mut out, 1); + write_entry_key(k, positional, &mut out); + if self.prefs_needs_sync(v) { + let mut prefs_val = v.clone(); + let prefs_tbl = match prefs_val.as_table_mut() { + Some(t) => t, + None => { + prefs_val = LuaValue::Table(LuaTable::default()); + prefs_val.as_table_mut().unwrap() + } + }; + self.patch_prefs_table(prefs_tbl); + write_value(&prefs_val, 1, &mut out); + } else { + write_value(v, 1, &mut out); + } + out.push_str(",\n"); + continue; + } + "Tools" => { + seen_tools = true; + write_indent(&mut out, 1); + write_entry_key(k, positional, &mut out); + self.write_tools_streaming( + tools, + &mut top_pool, + &mut inner_pool, + &instance_defaults, + &mut out, + ); + out.push_str(",\n"); + continue; + } + _ => {} + } + } + write_indent(&mut out, 1); + write_entry_key(k, positional, &mut out); + write_value(v, 1, &mut out); + out.push_str(",\n"); + } + + if !seen_current_time { + write_root_kv("CurrentTime", &LuaValue::Number(self.current_time), &mut out); + } + if !seen_global_range { + let gr = vec2_lua(self.global_range[0] as f64, self.global_range[1] as f64); + write_root_kv("GlobalRange", &gr, &mut out); + } + if !seen_render_range { + let rr = vec2_lua(self.render_range[0] as f64, self.render_range[1] as f64); + write_root_kv("RenderRange", &rr, &mut out); + } + if !seen_audio_filename { + if let Some(ref af) = self.audio_filename { + write_root_kv("AudioFilename", &LuaValue::String(af.clone()), &mut out); + } + } + if !seen_audio_offset && self.audio_offset != 0.0 { + write_root_kv("AudioOffset", &LuaValue::Number(self.audio_offset), &mut out); + } + if !seen_prefs { + let mut prefs_tbl = LuaTable::default(); + self.patch_prefs_table(&mut prefs_tbl); + write_root_kv("Prefs", &LuaValue::Table(prefs_tbl), &mut out); + } + if !seen_tools { + unreachable!("checked root.get_table(\"Tools\")"); + } + + out.push_str("}\n"); + Some(out) + } + + fn prefs_needs_sync(&self, prefs_val: &LuaValue) -> bool { + let Some(ff) = prefs_val + .as_table() + .and_then(|p| p.get_table("Comp")) + .and_then(|c| c.get_table("FrameFormat")) + else { + return true; + }; + if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) { + return true; + } + if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) { + return true; + } + if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) { + return true; + } + let existing_depth = ff + .get_f64("DepthFull") + .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32)) + .unwrap_or(BitDepth::Int8); + existing_depth != self.depth_full + } + + fn patch_prefs_table(&self, prefs: &mut LuaTable) { + let comp_prefs = ensure_table_mut(prefs, "Comp", None); + let ff = ensure_table_mut(comp_prefs, "FrameFormat", None); + if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) { + ff.set(LuaKey::Str("Width".to_owned()), LuaValue::Number(self.width as f64)); + } + if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) { + ff.set(LuaKey::Str("Height".to_owned()), LuaValue::Number(self.height as f64)); + } + if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) { + ff.set(LuaKey::Str("Rate".to_owned()), LuaValue::Number(self.fps)); + } + let existing_depth = ff + .get_f64("DepthFull") + .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32)) + .unwrap_or(BitDepth::Int8); + if existing_depth != self.depth_full { + ff.set( + LuaKey::Str("DepthFull".to_owned()), + LuaValue::Number((self.depth_full as i32) as f64), + ); + } + } + + fn write_tools_streaming<'a>( + &'a self, + tools: &LuaTable, + top_pool: &mut HashMap<&'a str, NodePool<'a>>, + inner_pool: &mut HashMap<&'a str, NodePool<'a>>, + instance_defaults: &HashMap<(&str, &str), ParamValue>, + out: &mut String, + ) { + let mut remaining_splines: HashMap<&str, &BezierSpline> = + self.splines.iter().map(|(k, v)| (k.as_str(), v)).collect(); + + // Record top-level spline names first so nested `Tools` matches `sync_existing_splines_in_tools` + // priority order even if a duplicate modifier name appears at both levels. + let mut top_level_spline_names: HashSet<&str> = HashSet::new(); + if !remaining_splines.is_empty() { + for (k, v) in &tools.entries { + if let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) { + let tag = tbl.tag.as_deref().unwrap_or("Unknown"); + if is_modifier_type(tag) && remaining_splines.contains_key(name.as_str()) { + top_level_spline_names.insert(name.as_str()); + } + } + } + } + + let mut seen_in_tools: HashSet<&str> = HashSet::with_capacity(tools.entries.len()); + + write_table_prefix(tools.tag.as_deref(), &[], 1, out); + out.push_str("{\n"); + + for (k, v) in &tools.entries { + let LuaKey::Str(name) = k else { + write_indent(out, 2); + write_entry_key(k, true, out); + write_value(v, 2, out); + out.push_str(",\n"); + continue; + }; + let Some(tbl) = v.as_table() else { + seen_in_tools.insert(name.as_str()); + write_indent(out, 2); + write_entry_key(k, true, out); + write_value(v, 2, out); + out.push_str(",\n"); + continue; + }; + + let tag = tbl.tag.as_deref().unwrap_or("Unknown"); + if is_modifier_type(tag) { + seen_in_tools.insert(name.as_str()); + write_indent(out, 2); + write_entry_key(k, true, out); + if let Some(spline) = remaining_splines.remove(name.as_str()) { + if !spline_needs_sync(name, spline, tbl) { + write_table(tbl, 2, out); + } else { + let mut cloned = tbl.clone(); + sync_spline_table(name, spline, &mut cloned); + write_table(&cloned, 2, out); + } + } else { + write_table(tbl, 2, out); + } + out.push_str(",\n"); + continue; + } + + let Some(node) = pop_pool(top_pool, name.as_str()) else { + // Deleted flow node. + continue; + }; + seen_in_tools.insert(name.as_str()); + + write_indent(out, 2); + write_entry_key(k, true, out); + + if is_group_kind(&node.kind) { + if self.group_can_stream_verbatim( + node, + tbl, + inner_pool, + instance_defaults, + &mut remaining_splines, + &top_level_spline_names, + ) { + write_table(tbl, 2, out); + } else { + let mut cloned = tbl.clone(); + self.sync_node_tool(node, &mut cloned, instance_defaults); + if let Some(inner) = cloned.get_table_mut("Tools") { + self.sync_tools_level(inner, true, top_pool, inner_pool, instance_defaults); + } + sync_group_wiring(node, &mut cloned); + if !remaining_splines.is_empty() { + if let Some(inner) = cloned.get_table_mut("Tools") { + sync_existing_splines_in_tools_excluding( + inner, + &mut remaining_splines, + &top_level_spline_names, + ); + } + } + write_table(&cloned, 2, out); + } + } else if self.node_can_stream_verbatim( + node, + tbl, + instance_defaults, + &mut remaining_splines, + &top_level_spline_names, + ) { + write_table(tbl, 2, out); + } else { + let mut cloned = tbl.clone(); + self.sync_node_tool(node, &mut cloned, instance_defaults); + if !remaining_splines.is_empty() { + if let Some(inner) = cloned.get_table_mut("Tools") { + sync_existing_splines_in_tools_excluding( + inner, + &mut remaining_splines, + &top_level_spline_names, + ); + } + } + write_table(&cloned, 2, out); + } + out.push_str(",\n"); + } + + // Newly added top-level nodes not yet present in `tools` + for node in self.nodes.iter().filter(|n| !n.internal) { + if seen_in_tools.contains(node.name.as_str()) { + continue; + } + seen_in_tools.insert(node.name.as_str()); + let Some(node) = pop_pool(top_pool, node.name.as_str()) else { + continue; + }; + let mut new_tbl = if node.raw.tag.is_some() { + node.raw.clone() + } else { + LuaTable { tag: None, entries: Vec::new() } + }; + if new_tbl.tag.is_none() { + new_tbl.tag = Some(node.kind.clone()); + } + self.sync_node_tool(node, &mut new_tbl, instance_defaults); + if is_group_kind(&node.kind) { + if let Some(inner) = new_tbl.get_table_mut("Tools") { + self.sync_tools_level(inner, true, top_pool, inner_pool, instance_defaults); + } + sync_group_wiring(node, &mut new_tbl); + } + if !remaining_splines.is_empty() { + if let Some(inner) = new_tbl.get_table_mut("Tools") { + sync_existing_splines_in_tools_excluding( + inner, + &mut remaining_splines, + &top_level_spline_names, + ); + } + } + write_indent(out, 2); + write_entry_key(&LuaKey::Str(node.name.clone()), true, out); + write_table(&new_tbl, 2, out); + out.push_str(",\n"); + } + + // Newly added splines not yet present in `tools` + if !remaining_splines.is_empty() { + let mut new_names: Vec<&str> = remaining_splines.keys().copied().collect(); + new_names.sort_unstable(); + for spline_name in new_names { + let spline = remaining_splines[spline_name]; + let mut sp_tbl = LuaTable { + tag: Some("BezierSpline".to_owned()), + entries: Vec::with_capacity(2), + }; + sp_tbl.set( + LuaKey::Str("SplineColor".to_owned()), + spline_color_lua(spline.color), + ); + sp_tbl.set( + LuaKey::Str("KeyFrames".to_owned()), + LuaValue::Table(build_keyframes_table(spline)), + ); + write_indent(out, 2); + write_entry_key(&LuaKey::Str(spline_name.to_owned()), true, out); + write_table(&sp_tbl, 2, out); + out.push_str(",\n"); + } + } + + write_indent(out, 1); + out.push('}'); + } + + fn node_header_needs_sync(&self, node: &Node, tool_tbl: &LuaTable) -> bool { + // ViewInfo.Pos + if let Some(vi) = tool_tbl.get_table("ViewInfo") { + let pos_changed = vi + .get_table("Pos") + .and_then(read_vec2) + .is_none_or(|[x, y]| { + (x as f32 - node.pos[0]).abs() > 1e-4 || (y as f32 - node.pos[1]).abs() > 1e-4 + }); + if pos_changed { + return true; + } + } else if node.pos[0] != 0.0 || node.pos[1] != 0.0 { + return true; + } + + // PassThrough + if node.bypassed { + if tool_tbl.get_bool("PassThrough") != Some(true) { + return true; + } + } else if tool_tbl.get("PassThrough").is_some() { + return true; + } + + // Loader clip timing + if node.kind == "Loader" { + let clip_exists = tool_tbl.get_table("Clips").is_some_and(|c| { + c.entries + .iter() + .any(|(_, v)| v.as_table().is_some_and(|t| t.get_str("Filename").is_some())) + }); + if clip_exists { + let edited = |port: &str| { + let now = node.static_number(port)?; + let before = tool_tbl + .get_table("Inputs") + .and_then(|i| i.get_table(port)) + .and_then(|t| t.get("Value")) + .and_then(lua_value_as_number); + (before != Some(now)).then_some(now) + }; + if edited("GlobalIn").is_some() + || edited("GlobalOut").is_some() + || edited("Loop").is_some() + || edited("Reverse").is_some() + { + return true; + } + } + } + + false + } + + fn node_can_stream_verbatim<'a>( + &'a self, + node: &Node, + tool_tbl: &LuaTable, + instance_defaults: &HashMap<(&str, &str), ParamValue>, + remaining_splines: &mut HashMap<&'a str, &'a BezierSpline>, + top_level_spline_names: &HashSet<&str>, + ) -> bool { + if self.node_header_needs_sync(node, tool_tbl) { + return false; + } + let master_inputs = node + .raw + .get_str("SourceOp") + .and_then(|m| self.find_node(m)) + .map(|mid| &self.nodes[mid.0].inputs); + if node_inputs_need_sync( + node, + master_inputs, + instance_defaults, + &self.cross_macro_wires, + tool_tbl, + ) { + return false; + } + if let Some(inner) = tool_tbl.get_table("Tools") { + if !nested_splines_verbatim(inner, remaining_splines, top_level_spline_names) { + return false; + } + consume_nested_splines(inner, remaining_splines, top_level_spline_names); + } + true + } + + fn group_can_stream_verbatim<'a>( + &'a self, + node: &Node, + tool_tbl: &LuaTable, + inner_pool: &mut HashMap<&'a str, NodePool<'a>>, + instance_defaults: &HashMap<(&str, &str), ParamValue>, + remaining_splines: &mut HashMap<&'a str, &'a BezierSpline>, + top_level_spline_names: &HashSet<&str>, + ) -> bool { + if self.node_header_needs_sync(node, tool_tbl) { + return false; + } + if group_wiring_needs_sync(node, tool_tbl) { + return false; + } + let Some(inner_tools) = tool_tbl.get_table("Tools") else { + return true; + }; + let mut peek_offsets: HashMap<&str, usize> = HashMap::new(); + if !self.check_inner_tools_verbatim( + inner_tools, + inner_pool, + &mut peek_offsets, + instance_defaults, + remaining_splines, + top_level_spline_names, + ) { + return false; + } + // All checks passed: commit pops from `inner_pool` and removals from `remaining_splines`. + commit_inner_tools_verbatim( + inner_tools, + inner_pool, + remaining_splines, + top_level_spline_names, + ); + true + } + + fn check_inner_tools_verbatim<'a, 'b>( + &'a self, + inner_tools: &'b LuaTable, + inner_pool: &HashMap<&'a str, NodePool<'a>>, + peek_offsets: &mut HashMap<&'b str, usize>, + instance_defaults: &HashMap<(&str, &str), ParamValue>, + remaining_splines: &HashMap<&'a str, &'a BezierSpline>, + top_level_spline_names: &HashSet<&str>, + ) -> bool { + // Check modifiers at this level first (matching `sync_existing_splines_in_tools` top-down order). + for (k, v) in &inner_tools.entries { + let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue }; + let tag = tbl.tag.as_deref().unwrap_or("Unknown"); + if is_modifier_type(tag) { + if !top_level_spline_names.contains(name.as_str()) { + if let Some(&spline) = remaining_splines.get(name.as_str()) { + if spline_needs_sync(name, spline, tbl) { + return false; + } + } + } + continue; + } + // Flow node: check if it survived `retain` and matches `node` + let offset = peek_offsets.entry(name.as_str()).or_insert(0); + let Some(inner_node) = inner_pool.get(name.as_str()).and_then(|p| p.peek_at(*offset)) else { + // Deleted inner node! + return false; + }; + *offset += 1; + + if is_group_kind(&inner_node.kind) { + if self.node_header_needs_sync(inner_node, tbl) || group_wiring_needs_sync(inner_node, tbl) { + return false; + } + if let Some(sub_tools) = tbl.get_table("Tools") { + if !self.check_inner_tools_verbatim( + sub_tools, + inner_pool, + peek_offsets, + instance_defaults, + remaining_splines, + top_level_spline_names, + ) { + return false; + } + } + } else { + if self.node_header_needs_sync(inner_node, tbl) { + return false; + } + let master_inputs = inner_node + .raw + .get_str("SourceOp") + .and_then(|m| self.find_node(m)) + .map(|mid| &self.nodes[mid.0].inputs); + if node_inputs_need_sync( + inner_node, + master_inputs, + instance_defaults, + &self.cross_macro_wires, + tbl, + ) { + return false; + } + if let Some(sub_tools) = tbl.get_table("Tools") { + if !nested_splines_verbatim(sub_tools, remaining_splines, top_level_spline_names) { + return false; + } + } + } + } + true + } /// Atomically saves this composition to `path`. /// If `path` already exists, backs up the original bytes to /// `/fission-backups/___.comp.bak` and returns `Ok(Some(backup_path))`. @@ -325,6 +1023,239 @@ impl Comp { } } +fn write_root_kv(key: &str, val: &LuaValue, out: &mut String) { + write_indent(out, 1); + out.push_str(key); + out.push_str(" = "); + write_value(val, 1, out); + out.push_str(",\n"); +} + +fn commit_inner_tools_verbatim<'a>( + inner_tools: &LuaTable, + inner_pool: &mut HashMap<&'a str, NodePool<'a>>, + remaining_splines: &mut HashMap<&'a str, &'a BezierSpline>, + top_level_spline_names: &HashSet<&str>, +) { + for (k, v) in &inner_tools.entries { + let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue }; + let tag = tbl.tag.as_deref().unwrap_or("Unknown"); + if is_modifier_type(tag) { + if !top_level_spline_names.contains(name.as_str()) { + remaining_splines.remove(name.as_str()); + } + continue; + } + let Some(inner_node) = pop_pool(inner_pool, name.as_str()) else { continue }; + if let Some(sub_tools) = tbl.get_table("Tools") { + if is_group_kind(&inner_node.kind) { + commit_inner_tools_verbatim(sub_tools, inner_pool, remaining_splines, top_level_spline_names); + } else { + consume_nested_splines(sub_tools, remaining_splines, top_level_spline_names); + } + } + } +} + +fn nested_splines_verbatim( + tools: &LuaTable, + remaining_splines: &HashMap<&str, &BezierSpline>, + top_level_spline_names: &HashSet<&str>, +) -> bool { + if remaining_splines.is_empty() { + return true; + } + for (k, v) in &tools.entries { + let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue }; + if !top_level_spline_names.contains(name.as_str()) { + if let Some(&spline) = remaining_splines.get(name.as_str()) { + if spline_needs_sync(name, spline, tbl) { + return false; + } + } + } + if let Some(sub) = tbl.get_table("Tools") { + if !nested_splines_verbatim(sub, remaining_splines, top_level_spline_names) { + return false; + } + } + } + true +} + +fn consume_nested_splines( + tools: &LuaTable, + remaining_splines: &mut HashMap<&str, &BezierSpline>, + top_level_spline_names: &HashSet<&str>, +) { + if remaining_splines.is_empty() { + return; + } + for (k, v) in &tools.entries { + let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue }; + if !top_level_spline_names.contains(name.as_str()) { + remaining_splines.remove(name.as_str()); + } + if let Some(sub) = tbl.get_table("Tools") { + consume_nested_splines(sub, remaining_splines, top_level_spline_names); + } + } +} + +fn sync_existing_splines_in_tools_excluding( + tools: &mut LuaTable, + remaining: &mut HashMap<&str, &BezierSpline>, + excluded: &HashSet<&str>, +) { + if remaining.is_empty() { + return; + } + for (k, v) in &mut tools.entries { + let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table_mut()) else { continue }; + if excluded.contains(name.as_str()) { + continue; + } + if let Some(spline) = remaining.remove(name.as_str()) { + sync_spline_table(name, spline, tbl); + if remaining.is_empty() { + return; + } + } + } + for (_, v) in &mut tools.entries { + if let Some(inner) = v.as_table_mut().and_then(|t| t.get_table_mut("Tools")) { + sync_existing_splines_in_tools_excluding(inner, remaining, excluded); + if remaining.is_empty() { + return; + } + } + } +} + +fn spline_needs_sync(spline_name: &str, spline: &BezierSpline, tbl: &LuaTable) -> bool { + if spline_color_from_lua(tbl) != spline.color { + return true; + } + if keyframes_match_lua(spline, tbl) { + return false; + } + let existing = BezierSpline::from_lua(spline_name.to_owned(), tbl); + let unchanged_cyclic = tbl.tag.as_deref() == Some("LUTBezier") && { + let mut normalized = existing.clone(); + normalized.apply_hue_curves_cyclic_ends(); + normalized.keyframes == spline.keyframes + }; + existing.keyframes != spline.keyframes && !unchanged_cyclic +} + +fn group_wiring_needs_sync(node: &Node, group_tbl: &LuaTable) -> bool { + let Some(inputs) = group_tbl.get_table("Inputs") else { + return false; + }; + let Some(inner_tools) = group_tbl.get_table("Tools") else { + return false; + }; + for (k, v) in &inputs.entries { + let LuaKey::Str(port) = k else { continue }; + let Some(t) = v.as_table() else { continue }; + let Some(inner_op) = t.get_str("SourceOp") else { continue }; + let Some(inner_port) = t.get_str("Source") else { continue }; + let desired = node.inputs.get(port); + if desired.is_some_and(|b| b.source_op.as_deref() == Some(inner_op)) { + continue; + } + let Some(inner_tbl) = super::math::find_raw_tool(inner_tools, inner_op) else { + continue; + }; + let existing_it = inner_tbl + .get_table("Inputs") + .and_then(|i| i.get_table(inner_port)); + let cur_src_op = existing_it.and_then(|it| it.get_str("SourceOp")); + let cur_src_out = existing_it.and_then(|it| it.get_str("Source")); + match desired { + Some(b) => { + if existing_it.is_none() + || (cur_src_op, cur_src_out) != (b.source_op.as_deref(), b.source_output.as_deref()) + { + return true; + } + } + None if cur_src_op.is_some() => { + return true; + } + _ => {} + } + } + false +} + +fn node_inputs_need_sync( + node: &Node, + master_inputs: Option<&HashMap>, + instance_defaults: &HashMap<(&str, &str), ParamValue>, + cross_macro_wires: &HashSet<(String, String)>, + tool_tbl: &LuaTable, +) -> bool { + let in_tbl = tool_tbl.get_table("Inputs"); + if let Some(in_tbl) = in_tbl { + for (k, v) in &in_tbl.entries { + let LuaKey::Str(port) = k else { continue }; + if v.as_table().is_some() && !node.inputs.contains_key(port) { + return true; + } + } + } + + for (port, binding) in &node.inputs { + if !instance_defaults.is_empty() + && binding.source_op.is_none() + && binding.expression.is_none() + && binding.value.is_some() + && binding.value.as_ref() == instance_defaults.get(&(node.name.as_str(), port.as_str())) + && in_tbl + .and_then(|i| i.get_table(port)) + .is_none_or(|t| t.get("Value").is_none()) + { + continue; + } + + if let Some(it) = in_tbl.and_then(|i| i.get_table(port)) { + let clear_src = !cross_macro_wires.is_empty() + && binding.source_op.is_none() + && cross_macro_wires.contains(&(node.name.clone(), port.clone())); + if binding_matches_lua(it, binding, clear_src) { + continue; + } + // Check empty-stub master inheritance skip + let is_empty_stub = it.get("Value").is_none() + && (clear_src || it.get_str("SourceOp").is_none()) + && it.get_str("Expression").is_none(); + if is_empty_stub && master_inputs.is_some_and(|m| m.get(port) == Some(binding)) { + continue; + } + return true; + } else { + if binding.value.is_none() && binding.source_op.is_none() && binding.expression.is_none() { + continue; + } + if binding.source_op.is_none() + && binding.expression.is_none() + && binding.value.is_some() + && binding.value == user_control_default(&node.raw, port) + { + continue; + } + if let Some(master) = master_inputs { + if master.get(port) == Some(binding) { + continue; + } + } + return true; + } + } + false +} + pub(crate) fn vec2_lua(x: f64, y: f64) -> LuaValue { LuaValue::Table(LuaTable { tag: None, @@ -467,6 +1398,88 @@ fn sync_group_wiring(node: &Node, group_tbl: &mut LuaTable) { } } +fn lua_value_as_number(v: &LuaValue) -> Option { + match v { + LuaValue::Number(n) => Some(*n), + LuaValue::Bool(b) => Some(if *b { 1.0 } else { 0.0 }), + LuaValue::Table(t) if t.tag.as_deref() == Some("Number") => Some(t.get_f64("Value").unwrap_or(0.0)), + _ => None, + } +} + +fn param_matches_lua(v: &LuaValue, p: &ParamValue) -> bool { + match (v, p) { + (LuaValue::Number(n), ParamValue::Number(pn)) => n == pn, + (LuaValue::Bool(b), ParamValue::Number(pn)) => (if *b { 1.0 } else { 0.0 }) == *pn, + (LuaValue::String(s), ParamValue::Text(ps)) => s == ps, + (LuaValue::Table(t), _) => match t.tag.as_deref() { + Some("FuID") => { + matches!(p, ParamValue::FuId(pf) if t.get_index(1).and_then(LuaValue::as_str).unwrap_or("") == pf) + } + Some("Number") => { + matches!(p, ParamValue::Number(pn) if t.get_f64("Value").unwrap_or(0.0) == *pn) + } + Some("Gradient") => { + matches!(p, ParamValue::Gradient(pg) if Gradient::from_lua(t) == *pg) + } + _ => { + if let Some(pt) = read_vec2(t) { + matches!(p, ParamValue::Point(pp) if pt == *pp) + } else { + matches!(p, ParamValue::Raw(LuaValue::Table(rt)) if rt == t) + } + } + }, + (LuaValue::Nil, ParamValue::Raw(LuaValue::Nil)) => true, + _ => false, + } +} + +fn binding_matches_lua(it: &LuaTable, binding: &InputBinding, clear_source_op: bool) -> bool { + let mut source_op: Option<&str> = None; + let mut source_output: Option<&str> = None; + let mut expression: Option<&str> = None; + let mut value: Option<&LuaValue> = None; + for (k, v) in &it.entries { + let LuaKey::Str(s) = k else { continue }; + match s.as_str() { + "SourceOp" => { + if let Some(sv) = v.as_str() { + source_op = Some(sv); + } + } + "Source" => { + if let Some(sv) = v.as_str() { + source_output = Some(sv); + } + } + "Expression" => { + if let Some(sv) = v.as_str() { + expression = Some(sv); + } + } + "Value" => { + value = Some(v); + } + _ => {} + } + } + if clear_source_op { + source_op = None; + } + if source_op != binding.source_op.as_deref() + || source_output != binding.source_output.as_deref() + || expression != binding.expression.as_deref() + { + return false; + } + match (value, &binding.value) { + (None, None) => true, + (Some(lv), Some(pv)) => param_matches_lua(lv, pv), + _ => false, + } +} + fn sync_node_inputs( node: &Node, master_inputs: Option<&HashMap>, @@ -487,37 +1500,38 @@ fn sync_node_inputs( // Collect sorted port names for deterministic output when appending new inputs. let mut ports: Vec<&String> = node.inputs.keys().collect(); - ports.sort(); + if ports.len() > 1 { + ports.sort(); + } for port in ports { let binding = &node.inputs[port]; // Load fills unset inner-tool inputs from the enclosing group's `InstanceInput` default. - if binding.source_op.is_none() + if !instance_defaults.is_empty() + && binding.source_op.is_none() && binding.expression.is_none() && binding.value.is_some() && binding.value.as_ref() == instance_defaults.get(&(node.name.as_str(), port.as_str())) && tool_tbl .get_table("Inputs") .and_then(|i| i.get_table(port)) - .is_none_or(|t| parse_input_binding(t).value.is_none()) + .is_none_or(|t| t.get("Value").is_none()) { continue; } - let existing_binding = tool_tbl - .get_table("Inputs") - .and_then(|i| i.get_table(port)) - .map(parse_input_binding) - .map(|mut b| { - if binding.source_op.is_none() && cross_macro_wires.contains(&(node.name.clone(), port.clone())) { - b.source_op = None; - } - b - }); - if let Some(orig) = existing_binding { - if orig == *binding { + let existing_tbl = tool_tbl.get_table("Inputs").and_then(|i| i.get_table(port)); + if let Some(it) = existing_tbl { + let clear_src = !cross_macro_wires.is_empty() + && binding.source_op.is_none() + && cross_macro_wires.contains(&(node.name.clone(), port.clone())); + if binding_matches_lua(it, binding, clear_src) { continue; } + let mut orig = parse_input_binding(it); + if clear_src { + orig.source_op = None; + } // Don't materialize inherited master inputs into an empty stub `Input {}` on instanced tools. if orig.value.is_none() && orig.source_op.is_none() @@ -591,7 +1605,7 @@ fn sync_node_inputs( let mut it = LuaTable { tag: Some("Input".to_owned()), - entries: Vec::new(), + entries: Vec::with_capacity(4), }; if let Some(op) = &binding.source_op { it.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(op.clone())); @@ -670,11 +1684,110 @@ fn build_keyframes_table(spline: &BezierSpline) -> LuaTable { tbl } +/// Walks `tools` in top-level-before-nested order to sync all existing splines in one O(T) pass. +fn sync_existing_splines_in_tools(tools: &mut LuaTable, remaining: &mut HashMap<&str, &BezierSpline>) { + if remaining.is_empty() { + return; + } + for (k, v) in &mut tools.entries { + let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table_mut()) else { continue }; + if let Some(spline) = remaining.remove(name.as_str()) { + sync_spline_table(name, spline, tbl); + if remaining.is_empty() { + return; + } + } + } + for (_, v) in &mut tools.entries { + if let Some(inner) = v.as_table_mut().and_then(|t| t.get_table_mut("Tools")) { + sync_existing_splines_in_tools(inner, remaining); + if remaining.is_empty() { + return; + } + } + } +} + +fn spline_color_from_lua(table: &LuaTable) -> [u8; 3] { + table + .get_table("SplineColor") + .map(|c| { + [ + c.get_f64("Red").unwrap_or(200.0) as u8, + c.get_f64("Green").unwrap_or(140.0) as u8, + c.get_f64("Blue").unwrap_or(255.0) as u8, + ] + }) + .unwrap_or([210, 140, 255]) +} + +fn keyframes_match_lua(spline: &BezierSpline, table: &LuaTable) -> bool { + let kf_table = table.get_table("KeyFrames").or_else(|| { + table + .get_table("KeyColorSplines") + .and_then(|kc| kc.get_index(0)) + .and_then(LuaValue::as_table) + }); + let Some(kfs) = kf_table else { + return spline.keyframes.is_empty(); + }; + let mut idx = 0usize; + let mut prev_time = f64::NEG_INFINITY; + for (k, v) in &kfs.entries { + let time = match k { + LuaKey::Index(i) => *i as f64, + LuaKey::Number(n) => *n, + _ => continue, + }; + let Some(kt) = v.as_table() else { continue }; + // Fall back to full parse + sort if raw keyframes are not strictly ascending. + if !(time > prev_time) && idx > 0 { + return false; + } + prev_time = time; + let Some(target) = spline.keyframes.get(idx) else { + return false; + }; + let value = kt.get_index(1).and_then(LuaValue::as_f64).unwrap_or(0.0); + let lh = kt.get_table("LH").and_then(read_vec2); + let rh = kt.get_table("RH").and_then(read_vec2); + let mut flags = KeyFlags::default(); + if let Some(ft) = kt.get_table("Flags") { + flags.linear = ft.get_bool("Linear").unwrap_or(false); + flags.step_in = ft.get_bool("StepIn").unwrap_or(false); + flags.step_out = ft.get_bool("StepOut").unwrap_or(false); + flags.loop_after = ft.get_bool("Loop").unwrap_or(false); + flags.loop_rel = ft.get_bool("LoopRel").unwrap_or(false); + flags.ping_pong = ft.get_bool("PingPong").unwrap_or(false); + flags.locked_y = ft.get_bool("LockedY").unwrap_or(false); + } + let handle_mode = if flags.linear { + HandleMode::Vector + } else { + HandleMode::Free + }; + if target.time != time + || target.value != value + || target.lh != lh + || target.rh != rh + || target.flags != flags + || target.handle_mode != handle_mode + { + return false; + } + idx += 1; + } + idx == spline.keyframes.len() +} + fn sync_spline_table(spline_name: &str, spline: &BezierSpline, tbl: &mut LuaTable) { - let existing = BezierSpline::from_lua(spline_name.to_owned(), tbl); - if existing.color != spline.color { + if spline_color_from_lua(tbl) != spline.color { tbl.set(LuaKey::Str("SplineColor".to_owned()), spline_color_lua(spline.color)); } + if keyframes_match_lua(spline, tbl) { + return; + } + let existing = BezierSpline::from_lua(spline_name.to_owned(), tbl); let unchanged_cyclic = tbl.tag.as_deref() == Some("LUTBezier") && { let mut normalized = existing.clone(); normalized.apply_hue_curves_cyclic_ends(); diff --git a/crates/model/src/lua_value.rs b/crates/model/src/lua_value.rs index 27ddf7b44ec6ef9bc7aa48220aabc89d73f88e12..36e09ee7ed6dd011aa59e7cdf4ad501f9d48061b 100644 --- a/crates/model/src/lua_value.rs +++ b/crates/model/src/lua_value.rs @@ -97,7 +97,10 @@ impl LuaTable { /// Serializes this table using Blackmagic Fusion `.comp` Lua table syntax. pub fn to_fusion_string(&self) -> String { - let mut out = String::new(); + let cap = self + .get_table("Tools") + .map_or_else(|| self.entries.len().saturating_mul(64), |t| t.entries.len().saturating_mul(1024).saturating_add(4096)); + let mut out = String::with_capacity(cap); write_table(self, 0, &mut out); out } @@ -221,32 +224,53 @@ impl<'a> Parser<'a> { Some(b) } + #[inline(always)] fn skip_ws_and_comments(&mut self) -> Result<(), ParseError> { + let src = self.src; + let len = src.len(); + let mut p = self.pos; + while p < len && matches!(src[p], b' ' | b'\t' | b'\r' | b'\n') { + p += 1; + } + self.pos = p; + if p + 1 < len && src[p] == b'-' && src[p + 1] == b'-' { + self.skip_comments_and_ws_slow() + } else { + Ok(()) + } + } + + #[cold] + fn skip_comments_and_ws_slow(&mut self) -> Result<(), ParseError> { + let src = self.src; + let len = src.len(); + let mut p = self.pos; loop { - while let Some(b) = self.peek() { - if matches!(b, b' ' | b'\t' | b'\r' | b'\n') { - self.pos += 1; - } else { - break; - } + while p < len && matches!(src[p], b' ' | b'\t' | b'\r' | b'\n') { + p += 1; } - if self.peek() == Some(b'-') && self.peek_at(1) == Some(b'-') { - self.pos += 2; - if self.peek() == Some(b'[') { + if p + 1 < len && src[p] == b'-' && src[p + 1] == b'-' { + p += 2; + if p < len && src[p] == b'[' { + self.pos = p; if let Some(level) = self.try_open_long_bracket() { self.skip_long_bracket(level)?; + p = self.pos; continue; } + p = self.pos; } - while let Some(b) = self.bump() { - if b == b'\n' { - break; - } + while p < len && src[p] != b'\n' { + p += 1; + } + if p < len { + p += 1; } continue; } break; } + self.pos = p; Ok(()) } @@ -269,22 +293,29 @@ impl<'a> Parser<'a> { fn skip_long_bracket(&mut self, level: usize) -> Result { let start = self.pos; - while self.pos < self.src.len() { - if self.src[self.pos] == b']' { - let mut i = self.pos + 1; - let mut eq = 0; - while i < self.src.len() && self.src[i] == b'=' && eq < level { - i += 1; - eq += 1; - } - if eq == level && i < self.src.len() && self.src[i] == b']' { - let s = String::from_utf8_lossy(&self.src[start..self.pos]).into_owned(); - self.pos = i + 1; - return Ok(s); - } + let src = self.src; + let len = src.len(); + let mut p = start; + while let Some(rel) = src[p..].iter().position(|&b| b == b']') { + let close_start = p + rel; + let mut i = close_start + 1; + let mut eq = 0; + while i < len && src[i] == b'=' && eq < level { + i += 1; + eq += 1; } - self.pos += 1; + if eq == level && i < len && src[i] == b']' { + let slice = &src[start..close_start]; + let s = match std::str::from_utf8(slice) { + Ok(v) => v.to_owned(), + Err(_) => String::from_utf8_lossy(slice).into_owned(), + }; + self.pos = i + 1; + return Ok(s); + } + p = close_start + 1; } + self.pos = len; Err(self.err("unterminated long bracket string/comment")) } @@ -318,26 +349,31 @@ impl<'a> Parser<'a> { fn parse_ident_or_constructor(&mut self) -> Result { let start = self.pos; - while let Some(b) = self.peek() { - if is_ident_cont(b) || b == b'.' { - self.pos += 1; - } else { - break; - } + let src = self.src; + let len = src.len(); + let mut p = start; + while p < len && (is_ident_cont(src[p]) || src[p] == b'.') { + p += 1; } - let ident = std::str::from_utf8(&self.src[start..self.pos]) + self.pos = p; + self.finish_ident_or_constructor(start, p) + } + + fn finish_ident_or_constructor(&mut self, start: usize, end: usize) -> Result { + let ident_bytes = &self.src[start..end]; + match ident_bytes { + b"true" => return Ok(LuaValue::Bool(true)), + b"false" => return Ok(LuaValue::Bool(false)), + b"nil" => return Ok(LuaValue::Nil), + b"inf" | b"INF" => return Ok(LuaValue::Number(f64::INFINITY)), + b"nan" | b"NaN" | b"NAN" => return Ok(LuaValue::Number(f64::NAN)), + _ => {} + } + + let ident = std::str::from_utf8(ident_bytes) .map_err(|_| self.err("invalid UTF-8 identifier"))? .to_owned(); - match ident.as_str() { - "true" => return Ok(LuaValue::Bool(true)), - "false" => return Ok(LuaValue::Bool(false)), - "nil" => return Ok(LuaValue::Nil), - "inf" | "INF" => return Ok(LuaValue::Number(f64::INFINITY)), - "nan" | "NaN" | "NAN" => return Ok(LuaValue::Number(f64::NAN)), - _ => {} - } - self.skip_ws_and_comments()?; // Handle calls like `ordered() { ... }` or `FuID("...")` or `Clip(...)` @@ -369,7 +405,7 @@ impl<'a> Parser<'a> { return Ok(LuaValue::Table(table)); } // Standalone call like `Point(0.5, 0.5)` or `FuID("Foo")` - let mut table = LuaTable { tag: Some(ident), entries: Vec::new() }; + let mut table = LuaTable { tag: Some(ident), entries: Vec::with_capacity(args.len()) }; for (i, arg) in args.into_iter().enumerate() { table.entries.push((LuaKey::Index((i + 1) as i64), arg)); } @@ -397,61 +433,38 @@ impl<'a> Parser<'a> { if self.bump() != Some(b'{') { return Err(self.err("expected '{'")); } - let mut entries = Vec::new(); + let mut first_entry: Option<(LuaKey, LuaValue)> = None; + let mut entries: Option> = None; let mut next_index: i64 = 1; loop { self.skip_ws_and_comments()?; - match self.peek() { - None => { - // Gracefully close open tables on truncated/export-clipped `.comp` files. - break; - } - Some(b'}') => { + let Some(b) = self.peek() else { + // Gracefully close open tables on truncated/export-clipped `.comp` files. + break; + }; + match b { + b'}' => { self.pos += 1; break; } - Some(b',') | Some(b';') => { + b',' | b';' => { self.pos += 1; continue; } _ => {} } - // Decide between `[expr] = val`, `ident = val`, or positional `val` - if self.peek() == Some(b'[') && self.peek_at(1) != Some(b'[') && self.peek_at(1) != Some(b'=') { - self.pos += 1; // consume '[' - self.skip_ws_and_comments()?; - let key_val = self.parse_value()?; - self.skip_ws_and_comments()?; - if self.bump() != Some(b']') { - return Err(self.err("expected ']' after table key")); - } - self.skip_ws_and_comments()?; - if self.bump() != Some(b'=') { - return Err(self.err("expected '=' after [key]")); - } - let val = self.parse_value()?; - let key = match key_val { - LuaValue::String(s) => LuaKey::Str(s), - LuaValue::Number(n) => { - if n.fract() == 0.0 && n.abs() < (i64::MAX as f64) { - LuaKey::Index(n as i64) - } else { - LuaKey::Number(n) - } - } - other => LuaKey::Str(format!("{other:?}")), - }; - entries.push((key, val)); - } else if let Some((key, saved_pos)) = self.try_ident_equals() { - let _ = saved_pos; - let val = self.parse_value()?; - entries.push((LuaKey::Str(key), val)); + let entry = self.parse_table_entry(b, &mut next_index)?; + if let Some(ref mut vec) = entries { + vec.push(entry); + } else if let Some(prev) = first_entry.take() { + let mut vec = Vec::with_capacity(4); + vec.push(prev); + vec.push(entry); + entries = Some(vec); } else { - let val = self.parse_value()?; - entries.push((LuaKey::Index(next_index), val)); - next_index += 1; + first_entry = Some(entry); } self.skip_ws_and_comments()?; @@ -460,187 +473,313 @@ impl<'a> Parser<'a> { } } + let entries = match (entries, first_entry) { + (Some(vec), _) => vec, + (None, Some(e)) => vec![e], + (None, None) => Vec::new(), + }; Ok(LuaTable { tag, entries }) } - fn try_ident_equals(&mut self) -> Option<(String, usize)> { - let saved = self.pos; - let b = self.peek()?; - if !is_ident_start(b) { - return None; - } - let start = self.pos; - while let Some(c) = self.peek() { - if is_ident_cont(c) { - self.pos += 1; + #[inline(always)] + fn parse_table_entry(&mut self, b: u8, next_index: &mut i64) -> Result<(LuaKey, LuaValue), ParseError> { + if b == b'[' && self.peek_at(1) != Some(b'[') && self.peek_at(1) != Some(b'=') { + self.pos += 1; // consume '[' + self.skip_ws_and_comments()?; + let key_val = self.parse_value()?; + self.skip_ws_and_comments()?; + if self.bump() != Some(b']') { + return Err(self.err("expected ']' after table key")); + } + self.skip_ws_and_comments()?; + if self.bump() != Some(b'=') { + return Err(self.err("expected '=' after [key]")); + } + let val = self.parse_value()?; + let key = match key_val { + LuaValue::String(s) => LuaKey::Str(s), + LuaValue::Number(n) => { + if n.fract() == 0.0 && n.abs() < (i64::MAX as f64) { + LuaKey::Index(n as i64) + } else { + LuaKey::Number(n) + } + } + other => LuaKey::Str(format!("{other:?}")), + }; + Ok((key, val)) + } else if is_ident_start(b) { + let start = self.pos; + let src = self.src; + let len = src.len(); + let mut p = start + 1; + while p < len && is_ident_cont(src[p]) { + p += 1; + } + if p < len && src[p] == b'.' { + // Dotted constructor/ident like `Fuse.Colorize { ... }` + p += 1; + while p < len && (is_ident_cont(src[p]) || src[p] == b'.') { + p += 1; + } + self.pos = p; + let val = self.finish_ident_or_constructor(start, p)?; + let idx = *next_index; + *next_index += 1; + Ok((LuaKey::Index(idx), val)) } else { - break; + self.pos = p; + self.skip_ws_and_comments()?; + if self.peek() == Some(b'=') && self.peek_at(1) != Some(b'=') { + self.pos += 1; + let key = std::str::from_utf8(&self.src[start..p]) + .map_err(|_| self.err("invalid UTF-8 identifier"))? + .to_owned(); + let val = self.parse_value()?; + Ok((LuaKey::Str(key), val)) + } else { + let val = self.finish_ident_or_constructor(start, p)?; + let idx = *next_index; + *next_index += 1; + Ok((LuaKey::Index(idx), val)) + } } - } - let end = self.pos; - let _ = self.skip_ws_and_comments(); - if self.peek() == Some(b'=') && self.peek_at(1) != Some(b'=') { - self.pos += 1; - let key = std::str::from_utf8(&self.src[start..end]).ok()?.to_owned(); - Some((key, saved)) } else { - self.pos = saved; - None + let val = self.parse_value()?; + let idx = *next_index; + *next_index += 1; + Ok((LuaKey::Index(idx), val)) } } fn parse_quoted_string(&mut self) -> Result { let quote = self.bump().ok_or_else(|| self.err("expected quote"))?; - let mut out = Vec::new(); - while let Some(b) = self.bump() { + let src = self.src; + let len = src.len(); + let start = self.pos; + let mut p = start; + while p < len { + let b = src[p]; if b == quote { - return Ok(String::from_utf8_lossy(&out).into_owned()); + let slice = &src[start..p]; + self.pos = p + 1; + return Ok(match std::str::from_utf8(slice) { + Ok(s) => s.to_owned(), + Err(_) => String::from_utf8_lossy(slice).into_owned(), + }); } if b == b'\\' { - let Some(esc) = self.bump() else { - return Err(self.err("unterminated escape sequence")); - }; - match esc { - b'n' => out.push(b'\n'), - b'r' => out.push(b'\r'), - b't' => out.push(b'\t'), - b'\\' => out.push(b'\\'), - b'"' => out.push(b'"'), - b'\'' => out.push(b'\''), - b'a' => out.push(0x07), - b'b' => out.push(0x08), - b'f' => out.push(0x0C), - b'v' => out.push(0x0B), - b'\n' => out.push(b'\n'), - b'\r' => { - if self.peek() == Some(b'\n') { - self.pos += 1; - } - out.push(b'\n'); + break; + } + p += 1; + } + if p >= len { + self.pos = len; + return Err(self.err("unterminated string literal")); + } + + let mut out = Vec::with_capacity((p - start).saturating_add(16)); + if p > start { + out.extend_from_slice(&src[start..p]); + } + self.pos = p; + + while self.pos < len { + let chunk_start = self.pos; + let mut q = chunk_start; + let mut found_quote = false; + let mut found_esc = false; + while q < len { + let b = src[q]; + if b == quote { + found_quote = true; + break; + } + if b == b'\\' { + found_esc = true; + break; + } + q += 1; + } + if q > chunk_start { + out.extend_from_slice(&src[chunk_start..q]); + } + if found_quote { + self.pos = q + 1; + return Ok(match String::from_utf8(out) { + Ok(s) => s, + Err(e) => String::from_utf8_lossy(e.as_bytes()).into_owned(), + }); + } + if !found_esc { + self.pos = q; + return Err(self.err("unterminated string literal")); + } + self.pos = q + 1; // consume '\\' + let Some(esc) = self.bump() else { + return Err(self.err("unterminated escape sequence")); + }; + match esc { + b'n' => out.push(b'\n'), + b'r' => out.push(b'\r'), + b't' => out.push(b'\t'), + b'\\' => out.push(b'\\'), + b'"' => out.push(b'"'), + b'\'' => out.push(b'\''), + b'a' => out.push(0x07), + b'b' => out.push(0x08), + b'f' => out.push(0x0C), + b'v' => out.push(0x0B), + b'\n' => out.push(b'\n'), + b'\r' => { + if self.peek() == Some(b'\n') { + self.pos += 1; } - b'z' => { - while let Some(ws) = self.peek() { - if matches!(ws, b' ' | b'\t' | b'\r' | b'\n') { - self.pos += 1; - } else { - break; - } + out.push(b'\n'); + } + b'z' => { + while let Some(ws) = self.peek() { + if matches!(ws, b' ' | b'\t' | b'\r' | b'\n') { + self.pos += 1; + } else { + break; } } - b'x' => { - let h1 = self.bump().ok_or_else(|| self.err("short \\x escape"))?; - let h2 = self.bump().ok_or_else(|| self.err("short \\x escape"))?; - let s = [h1, h2]; - let byte = u8::from_str_radix(std::str::from_utf8(&s).unwrap_or("00"), 16) - .map_err(|_| self.err("invalid hex escape"))?; - out.push(byte); - } - b'0'..=b'9' => { - let mut val = (esc - b'0') as u32; - for _ in 0..2 { - if let Some(d @ b'0'..=b'9') = self.peek() { - self.pos += 1; - val = val * 10 + (d - b'0') as u32; - } else { - break; - } + } + b'x' => { + let h1 = self.bump().ok_or_else(|| self.err("short \\x escape"))?; + let h2 = self.bump().ok_or_else(|| self.err("short \\x escape"))?; + let n1 = hex_nibble(h1).ok_or_else(|| self.err("invalid hex escape"))?; + let n2 = hex_nibble(h2).ok_or_else(|| self.err("invalid hex escape"))?; + out.push((n1 << 4) | n2); + } + b'0'..=b'9' => { + let mut val = (esc - b'0') as u32; + for _ in 0..2 { + if let Some(d @ b'0'..=b'9') = self.peek() { + self.pos += 1; + val = val * 10 + (d - b'0') as u32; + } else { + break; } - out.push((val & 0xFF) as u8); } - other => out.push(other), + out.push((val & 0xFF) as u8); } - } else { - out.push(b); + other => out.push(other), } } Err(self.err("unterminated string literal")) } fn parse_number(&mut self) -> Result { + let src = self.src; + let len = src.len(); let start = self.pos; - if matches!(self.peek(), Some(b'-' | b'+')) { - self.pos += 1; - } - // Check for -inf / -nan / -1.#INF / -1.#IND (Windows MSVC Fusion files!) - if self.src[self.pos..].starts_with(b"inf") || self.src[self.pos..].starts_with(b"INF") { - self.pos += 3; - let neg = self.src[start] == b'-'; - return Ok(LuaValue::Number(if neg { f64::NEG_INFINITY } else { f64::INFINITY })); - } - if self.src[self.pos..].starts_with(b"nan") || self.src[self.pos..].starts_with(b"NaN") || self.src[self.pos..].starts_with(b"NAN") { - self.pos += 3; - return Ok(LuaValue::Number(f64::NAN)); + let mut p = start; + let mut neg = false; + if p < len { + if src[p] == b'-' { + neg = true; + p += 1; + } else if src[p] == b'+' { + p += 1; + } } - // Hex integer / float `0x...` - if self.peek() == Some(b'0') && matches!(self.peek_at(1), Some(b'x' | b'X')) { - self.pos += 2; - let hex_start = self.pos; - while let Some(b) = self.peek() { - if b.is_ascii_hexdigit() { - self.pos += 1; - } else { - break; + if p < len && src[p].is_ascii_digit() { + // Hex integer `0x...` + if src[p] == b'0' && p + 1 < len && (src[p + 1] == b'x' || src[p + 1] == b'X') { + p += 2; + let hex_start = p; + let mut val: u64 = 0; + while p < len && src[p].is_ascii_hexdigit() { + if p - hex_start < 16 { + val = (val << 4) | (hex_nibble(src[p]).unwrap_or(0) as u64); + } + p += 1; } + self.pos = p; + let digits = p - hex_start; + if digits == 0 || digits > 16 { + let s = std::str::from_utf8(&src[hex_start..p]).unwrap_or("0"); + let v = u64::from_str_radix(s, 16).map_err(|_| self.err("invalid hex number"))? as f64; + return Ok(LuaValue::Number(if neg { -v } else { v })); + } + let v = val as f64; + return Ok(LuaValue::Number(if neg { -v } else { v })); } - let s = std::str::from_utf8(&self.src[hex_start..self.pos]).unwrap_or("0"); - let v = u64::from_str_radix(s, 16).map_err(|_| self.err("invalid hex number"))? as f64; - let neg = self.src[start] == b'-'; - return Ok(LuaValue::Number(if neg { -v } else { v })); - } - while let Some(b) = self.peek() { - if b.is_ascii_digit() { - self.pos += 1; - } else { - break; + let int_start = p; + let mut int_val: u64 = 0; + while p < len && src[p].is_ascii_digit() { + if p - int_start < 15 { + int_val = int_val * 10 + (src[p] - b'0') as u64; + } + p += 1; + } + let next = if p < len { src[p] } else { 0 }; + if next != b'.' && next != b'e' && next != b'E' && (p - int_start) <= 15 { + self.pos = p; + let v = int_val as f64; + return Ok(LuaValue::Number(if neg { -v } else { v })); + } + } else { + // Check for -inf / -nan (Windows MSVC / LuaJIT Fusion files!) + if src[p..].starts_with(b"inf") || src[p..].starts_with(b"INF") { + self.pos = p + 3; + return Ok(LuaValue::Number(if neg { f64::NEG_INFINITY } else { f64::INFINITY })); + } + if src[p..].starts_with(b"nan") || src[p..].starts_with(b"NaN") || src[p..].starts_with(b"NAN") { + self.pos = p + 3; + return Ok(LuaValue::Number(f64::NAN)); } } - if self.peek() == Some(b'.') { - self.pos += 1; + + if p < len && src[p] == b'.' { + p += 1; // Handle Windows MSVC `1.#INF`, `1.#IND`, `1.#QNAN` - if self.peek() == Some(b'#') { - while let Some(b) = self.peek() { - if b.is_ascii_alphanumeric() || b == b'#' { - self.pos += 1; - } else { - break; - } + if p < len && src[p] == b'#' { + while p < len && (src[p].is_ascii_alphanumeric() || src[p] == b'#') { + p += 1; } - let raw = std::str::from_utf8(&self.src[start..self.pos]).unwrap_or(""); + self.pos = p; + let raw = std::str::from_utf8(&src[start..p]).unwrap_or(""); if raw.contains("INF") { return Ok(LuaValue::Number(if raw.starts_with('-') { f64::NEG_INFINITY } else { f64::INFINITY })); } return Ok(LuaValue::Number(f64::NAN)); } - while let Some(b) = self.peek() { - if b.is_ascii_digit() { - self.pos += 1; - } else { - break; - } + while p < len && src[p].is_ascii_digit() { + p += 1; } } - if matches!(self.peek(), Some(b'e' | b'E')) { - self.pos += 1; - if matches!(self.peek(), Some(b'+' | b'-')) { - self.pos += 1; + if p < len && (src[p] == b'e' || src[p] == b'E') { + p += 1; + if p < len && (src[p] == b'+' || src[p] == b'-') { + p += 1; } - while let Some(b) = self.peek() { - if b.is_ascii_digit() { - self.pos += 1; - } else { - break; - } + while p < len && src[p].is_ascii_digit() { + p += 1; } } - let s = std::str::from_utf8(&self.src[start..self.pos]) + self.pos = p; + let s = std::str::from_utf8(&src[start..p]) .map_err(|_| self.err("invalid UTF-8 in number"))?; let n: f64 = s.parse().map_err(|_| self.err(format!("invalid number '{s}'")))?; Ok(LuaValue::Number(n)) } } +#[inline] +fn hex_nibble(b: u8) -> Option { + match b { + b'0'..=b'9' => Some(b - b'0'), + b'a'..=b'f' => Some(b - b'a' + 10), + b'A'..=b'F' => Some(b - b'A' + 10), + _ => None, + } +} + fn is_ident_start(b: u8) -> bool { b.is_ascii_alphabetic() || b == b'_' } @@ -654,6 +793,9 @@ pub(crate) fn is_valid_lua_ident(s: &str) -> bool { if bytes.is_empty() || !is_ident_start(bytes[0]) || !bytes[1..].iter().all(|&b| is_ident_cont(b)) { return false; } + if bytes.len() > 8 || bytes.len() < 2 { + return true; + } !matches!( s, "and" @@ -681,12 +823,39 @@ pub(crate) fn is_valid_lua_ident(s: &str) -> bool { ) } -fn write_indent(out: &mut String, depth: usize) { - for _ in 0..depth { - out.push('\t'); +#[inline] +pub(crate) fn write_indent(out: &mut String, mut depth: usize) { + const TABS: &str = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"; + while depth > 0 { + let chunk = depth.min(TABS.len()); + out.push_str(&TABS[..chunk]); + depth -= chunk; } } +#[inline] +fn write_i64(mut v: i64, out: &mut String) { + if v == 0 { + out.push('0'); + return; + } + let neg = v < 0; + let mut u = v.unsigned_abs(); + let mut buf = [0u8; 24]; + let mut i = buf.len(); + while u > 0 { + i -= 1; + buf[i] = b'0' + (u % 10) as u8; + u /= 10; + } + if neg { + i -= 1; + buf[i] = b'-'; + } + let _ = &mut v; + out.push_str(std::str::from_utf8(&buf[i..]).unwrap()); +} + fn write_number(n: f64, out: &mut String) { if n.is_nan() { out.push_str("nan"); @@ -699,8 +868,7 @@ fn write_number(n: f64, out: &mut String) { } else if n == 0.0 { out.push('0'); } else if n.fract() == 0.0 && n.abs() < 9_007_199_254_740_992.0 { - use std::fmt::Write; - let _ = write!(out, "{}", n as i64); + write_i64(n as i64, out); } else { use std::fmt::Write; let _ = write!(out, "{n}"); @@ -708,25 +876,40 @@ fn write_number(n: f64, out: &mut String) { } fn write_string(s: &str, out: &mut String) { - use std::fmt::Write; out.push('"'); - for c in s.chars() { - match c { - '\\' => out.push_str("\\\\"), - '"' => out.push_str("\\\""), - '\n' => out.push_str("\\n"), - '\r' => out.push_str("\\r"), - '\t' => out.push_str("\\t"), - c if (c as u32) < 0x20 || (c as u32) == 0x7F => { - let _ = write!(out, "\\{:03}", c as u32); + let bytes = s.as_bytes(); + let mut last = 0; + for (i, &b) in bytes.iter().enumerate() { + let esc = match b { + b'\\' => "\\\\", + b'"' => "\\\"", + b'\n' => "\\n", + b'\r' => "\\r", + b'\t' => "\\t", + 0x00..=0x1F | 0x7F => { + if i > last { + out.push_str(&s[last..i]); + } + let seq = [b'\\', b'0' + (b / 100), b'0' + ((b / 10) % 10), b'0' + (b % 10)]; + out.push_str(std::str::from_utf8(&seq).unwrap()); + last = i + 1; + continue; } - c => out.push(c), + _ => continue, + }; + if i > last { + out.push_str(&s[last..i]); } + out.push_str(esc); + last = i + 1; + } + if last < bytes.len() { + out.push_str(&s[last..]); } out.push('"'); } -fn write_value(val: &LuaValue, depth: usize, out: &mut String) { +pub(crate) fn write_value(val: &LuaValue, depth: usize, out: &mut String) { match val { LuaValue::Nil => out.push_str("nil"), LuaValue::Bool(true) => out.push_str("true"), @@ -737,6 +920,13 @@ fn write_value(val: &LuaValue, depth: usize, out: &mut String) { } } +#[inline] +pub(crate) fn has_call_args(tbl: &LuaTable) -> bool { + tbl.entries + .iter() + .any(|(k, _)| matches!(k, LuaKey::Str(s) if s == "__arg0")) +} + fn split_call_args(tbl: &LuaTable) -> (Vec<&LuaValue>, Vec<&(LuaKey, LuaValue)>) { let mut call_args = Vec::new(); let mut next_arg = 0usize; @@ -763,11 +953,17 @@ fn split_call_args(tbl: &LuaTable) -> (Vec<&LuaValue>, Vec<&(LuaKey, LuaValue)>) (call_args, body) } -fn can_use_positional(body: &[&(LuaKey, LuaValue)]) -> bool { +pub(crate) fn can_use_positional<'a>(entries: impl Iterator + Clone) -> bool { let mut expected = 1i64; let mut index_count = 0usize; - for (k, _) in body { - match k { + let mut len = 0usize; + let mut first = None; + for entry in entries { + if len == 0 { + first = Some(entry); + } + len += 1; + match &entry.0 { LuaKey::Number(_) => return false, LuaKey::Index(i) => { if *i != expected { @@ -779,8 +975,8 @@ fn can_use_positional(body: &[&(LuaKey, LuaValue)]) -> bool { LuaKey::Str(_) => {} } } - if index_count == 1 && body.len() == 1 { - if let (LuaKey::Index(1), LuaValue::Table(sub)) = body[0] { + if index_count == 1 && len == 1 { + if let Some((LuaKey::Index(1), LuaValue::Table(sub))) = first { if sub.tag.is_none() && (sub.get("Flags").is_some() || sub.get("LH").is_some() || sub.get("RH").is_some()) { @@ -792,24 +988,20 @@ fn can_use_positional(body: &[&(LuaKey, LuaValue)]) -> bool { } fn can_inline_table(tbl: &LuaTable, max_depth: usize) -> bool { - if max_depth == 0 { + if max_depth == 0 || tbl.entries.len() > 4 || tbl.tag.as_deref() == Some("ordered") { return false; } - if tbl.tag.as_deref() == Some("ordered") { + if has_call_args(tbl) { return false; } - let (call_args, body) = split_call_args(tbl); - if !call_args.is_empty() || body.len() > 4 { - return false; - } - body.iter().all(|(_, v)| match v { + tbl.entries.iter().all(|(_, v)| match v { LuaValue::Nil | LuaValue::Bool(_) | LuaValue::Number(_) => true, - LuaValue::String(s) => !s.contains('\n') && !s.contains('\r') && s.len() <= 48, + LuaValue::String(s) => s.len() <= 48 && !s.contains('\n') && !s.contains('\r'), LuaValue::Table(sub) => max_depth > 1 && can_inline_table(sub, max_depth - 1), }) } -fn write_table_prefix(tag: Option<&str>, call_args: &[&LuaValue], depth: usize, out: &mut String) { +pub(crate) fn write_table_prefix(tag: Option<&str>, call_args: &[&LuaValue], depth: usize, out: &mut String) { if let Some(t) = tag { out.push_str(t); if t == "ordered" || !call_args.is_empty() { @@ -826,12 +1018,13 @@ fn write_table_prefix(tag: Option<&str>, call_args: &[&LuaValue], depth: usize, } } -fn write_entry_key(key: &LuaKey, positional: bool, out: &mut String) -> bool { +pub(crate) fn write_entry_key(key: &LuaKey, positional: bool, out: &mut String) -> bool { match key { LuaKey::Index(_) if positional => false, LuaKey::Index(i) => { - use std::fmt::Write; - let _ = write!(out, "[{i}] = "); + out.push('['); + write_i64(*i, out); + out.push_str("] = "); true } LuaKey::Number(n) => { @@ -854,36 +1047,40 @@ fn write_entry_key(key: &LuaKey, positional: bool, out: &mut String) -> bool { } } -fn write_table(tbl: &LuaTable, depth: usize, out: &mut String) { - let (call_args, body) = split_call_args(tbl); - write_table_prefix(tbl.tag.as_deref(), &call_args, depth, out); - - if body.is_empty() { +fn write_table_body<'a>( + tbl: &LuaTable, + entries: impl Iterator + Clone, + depth: usize, + out: &mut String, +) { + let mut peek = entries.clone(); + if peek.next().is_none() { out.push_str("{}"); return; } - let positional = can_use_positional(&body); + let positional = can_use_positional(entries.clone()); if depth > 0 && can_inline_table(tbl, 2) { - let mut inline = String::new(); - inline.push_str("{ "); - for (i, (k, v)) in body.iter().enumerate() { + let saved_len = out.len(); + out.push_str("{ "); + for (i, (k, v)) in entries.clone().enumerate() { if i > 0 { - inline.push_str(", "); + out.push_str(", "); } - write_entry_key(k, positional, &mut inline); - write_value(v, depth + 1, &mut inline); + write_entry_key(k, positional, out); + write_value(v, depth + 1, out); } - inline.push_str(" }"); - if !inline.contains('\n') && inline.len() <= 100 { - out.push_str(&inline); + out.push_str(" }"); + let written = &out[saved_len..]; + if written.len() <= 100 && !written.contains('\n') { return; } + out.truncate(saved_len); } out.push_str("{\n"); - for (k, v) in body { + for (k, v) in entries { write_indent(out, depth + 1); write_entry_key(k, positional, out); write_value(v, depth + 1, out); @@ -892,3 +1089,15 @@ fn write_table(tbl: &LuaTable, depth: usize, out: &mut String) { write_indent(out, depth); out.push('}'); } + +pub(crate) fn write_table(tbl: &LuaTable, depth: usize, out: &mut String) { + if !has_call_args(tbl) { + write_table_prefix(tbl.tag.as_deref(), &[], depth, out); + write_table_body(tbl, tbl.entries.iter(), depth, out); + return; + } + + let (call_args, body) = split_call_args(tbl); + write_table_prefix(tbl.tag.as_deref(), &call_args, depth, out); + write_table_body(tbl, body.into_iter(), depth, out); +}