Skip to main content

virtuoso_cli/client/
maestro_ops.rs

1use crate::client::bridge::escape_skill_string;
2use crate::version::VirtuosoVersion;
3
4pub struct MaestroOps;
5
6impl MaestroOps {
7    /// Returns session handle like `"fnxSession4"`.
8    pub fn open_session(&self, lib: &str, cell: &str, view: &str) -> String {
9        let lib = escape_skill_string(lib);
10        let cell = escape_skill_string(cell);
11        let view = escape_skill_string(view);
12        format!(r#"maeOpenSetup("{lib}" "{cell}" "{view}")"#)
13    }
14
15    /// Force-closes the session, cancels any in-flight simulation.
16    pub fn close_session(&self, session: &str) -> String {
17        let session = escape_skill_string(session);
18        format!(r#"maeCloseSession("{session}" ?forceClose t)"#)
19    }
20
21    pub fn list_sessions(&self) -> String {
22        skill_strings_to_json("maeGetSessions()")
23    }
24
25    pub fn set_var(&self, name: &str, value: &str) -> String {
26        let name = escape_skill_string(name);
27        let value = escape_skill_string(value);
28        format!(r#"maeSetVar("{name}" "{value}")"#)
29    }
30
31    pub fn get_var(&self, name: &str) -> String {
32        let name = escape_skill_string(name);
33        format!(r#"maeGetVar("{name}")"#)
34    }
35
36    pub fn list_vars(&self) -> String {
37        r#"let((vars out sep) vars = asiGetDesignVarList(asiGetCurrentSession()) out = "[" sep = "" foreach(v vars out = strcat(out sep sprintf(nil "{\"name\":\"%s\",\"value\":\"%s\"}" car(v) cadr(v))) sep = ",") strcat(out "]"))"#.into()
38    }
39
40    /// Get enabled analyses. Always returns a JSON string array; empty → `[]` (not an error).
41    pub fn get_analyses(&self, session: &str) -> String {
42        let session = escape_skill_string(session);
43        skill_strings_to_json(&format!(
44            r#"let((setup) setup = car(maeGetSetup(?session "{session}")) maeGetEnabledAnalysis(setup))"#
45        ))
46    }
47
48    /// Enable an analysis type — version-aware.
49    ///
50    /// IC23: `maeSetAnalysis(setupName analysisType)`.
51    /// IC25: `maeSetAnalysis(analysisType ?session s ?enable t ?options \`(...))`.
52    ///
53    /// `options_skill_alist` is validated and converted at the command layer before this is called.
54    pub fn set_analysis(
55        &self,
56        session: &str,
57        analysis_type: &str,
58        options_skill_alist: Option<&str>,
59        version: VirtuosoVersion,
60    ) -> String {
61        let session = escape_skill_string(session);
62        let analysis_type = escape_skill_string(analysis_type);
63        if version.is_ic25() {
64            let options_part = match options_skill_alist {
65                Some(alist) => format!(" ?options `{alist}"),
66                None => String::new(),
67            };
68            format!(
69                r#"maeSetAnalysis("{analysis_type}" ?session "{session}" ?enable t{options_part})"#
70            )
71        } else {
72            // IC23: positional — setup name first; options not supported in this path
73            format!(
74                r#"let((setup) setup = car(maeGetSetup(?session "{session}")) maeSetAnalysis(setup "{analysis_type}"))"#
75            )
76        }
77    }
78
79    /// Run simulation asynchronously. Returns immediately.
80    pub fn run_simulation(&self, session: &str) -> String {
81        let session = escape_skill_string(session);
82        format!(r#"maeRunSimulation(?session "{session}")"#)
83    }
84
85    /// IC23.1: `maeGetTestOutputs` returns list-of-lists; elements accessed via car/cadr/caddr.
86    pub fn get_outputs(&self, test_name: &str) -> String {
87        let test_name = escape_skill_string(test_name);
88        format!(r#"let((outs out sep) outs = maeGetTestOutputs("{test_name}") out = "[" sep = "" foreach(o outs out = strcat(out sep sprintf(nil "{{\"name\":\"%s\",\"test\":\"%s\",\"expr\":\"%s\"}}" car(o) cadr(o) if(caddr(o) then caddr(o) else ""))) sep = ",") strcat(out "]"))"#)
89    }
90
91    pub fn add_output(&self, output_name: &str, test_name: &str, expr: &str) -> String {
92        let output_name = escape_skill_string(output_name);
93        let test_name = escape_skill_string(test_name);
94        let expr = escape_skill_string(expr);
95        format!(r#"maeAddOutput("{output_name}" "{test_name}" ?expr "{expr}")"#)
96    }
97
98    pub fn set_design(&self, session: &str, lib: &str, cell: &str, view: &str) -> String {
99        let session = escape_skill_string(session);
100        let lib = escape_skill_string(lib);
101        let cell = escape_skill_string(cell);
102        let view = escape_skill_string(view);
103        format!(
104            r#"maeSetDesign(?session "{session}" ?libName "{lib}" ?cellName "{cell}" ?viewName "{view}")"#
105        )
106    }
107
108    pub fn save_setup(&self, session: &str) -> String {
109        let session = escape_skill_string(session);
110        format!(r#"maeSaveSetup(?session "{session}")"#)
111    }
112
113    pub fn get_sim_messages(&self, session: &str) -> String {
114        let session = escape_skill_string(session);
115        format!(r#"maeGetSimulationMessages(?session "{session}")"#)
116    }
117
118    /// Get focused ADE window name, all window names, and active sessions.
119    /// Returns a SKILL list: (focused_window_name (all_names...) (sessions...))
120    pub fn focused_window_skill(&self) -> String {
121        r#"let((cw) cw=hiGetCurrentWindow() list(if(cw hiGetWindowName(cw) nil) mapcar(lambda((w) hiGetWindowName(w)) hiGetWindowList()) maeGetSessions()))"#.into()
122    }
123
124    /// Get simulation run directory for a maestro session via asiGetAnalogRunDir.
125    pub fn run_dir_skill(&self, session: &str) -> String {
126        let session = escape_skill_string(session);
127        format!(
128            r#"let((sess) sess=asiGetSession("{session}") if(sess asiGetAnalogRunDir(sess) nil))"#
129        )
130    }
131
132    /// Export results to CSV.
133    pub fn export_results(&self, session: &str, file_path: &str) -> String {
134        let session = escape_skill_string(session);
135        let file_path = escape_skill_string(file_path);
136        format!(
137            r#"maeExportOutputView(?session "{session}" ?fileName "{file_path}" ?view "Detail")"#
138        )
139    }
140
141    // =========================================================================
142    // Result Reading Functions (IC23/IC25 compatible)
143    // =========================================================================
144
145    pub fn open_results(&self, history: &str) -> String {
146        let history = escape_skill_string(history);
147        format!(r#"maeOpenResults(?history "{history}")"#)
148    }
149
150    pub fn close_results(&self) -> String {
151        r#"maeCloseResults()"#.into()
152    }
153
154    /// List all test names that have results in the current history.
155    pub fn get_result_tests(&self) -> String {
156        skill_strings_to_json("maeGetResultTests()")
157    }
158
159    pub fn get_result_outputs(&self, test_name: &str) -> String {
160        let test_name = escape_skill_string(test_name);
161        skill_strings_to_json(&format!(
162            r#"maeGetResultOutputs(?testName "{test_name}")"#
163        ))
164    }
165
166    pub fn get_output_value(&self, name: &str, test_name: &str, corner: Option<&str>) -> String {
167        let name = escape_skill_string(name);
168        let test_name = escape_skill_string(test_name);
169        match corner {
170            Some(c) => {
171                let c = escape_skill_string(c);
172                format!(r#"maeGetOutputValue("{name}" "{test_name}" ?cornerName "{c}")"#)
173            }
174            None => format!(r#"maeGetOutputValue("{name}" "{test_name}")"#),
175        }
176    }
177
178    pub fn get_spec_status(&self, name: &str, test_name: &str) -> String {
179        let name = escape_skill_string(name);
180        let test_name = escape_skill_string(test_name);
181        format!(r#"maeGetSpecStatus("{name}" "{test_name}")"#)
182    }
183
184    /// List available history runs for a Maestro session.
185    /// Uses maeGetAllExplorerHistoryNames(sessionName) — IC23.1 documented API.
186    /// Pass the Maestro session name from maeGetSessions(), not the Ocean session.
187    pub fn get_history_list(&self, session: &str) -> String {
188        let session = escape_skill_string(session);
189        skill_strings_to_json(&format!(r#"maeGetAllExplorerHistoryNames("{session}")"#))
190    }
191
192    pub fn get_current_session(&self) -> String {
193        r#"let((sess) sess = asiGetCurrentSession() if(sess then sess~>name else nil))"#.into()
194    }
195}
196
197/// Wrap a SKILL expression that returns a list-of-strings into a JSON array string.
198///
199/// If `list_expr` returns nil (empty), the output is `"[]"`.
200/// This ensures list-returning ops never produce SKILL nil — callers use r.ok() not r.skill_ok().
201fn skill_strings_to_json(list_expr: &str) -> String {
202    format!(r#"let((xs out sep) xs = {list_expr} out = "[" sep = "" foreach(x xs out = strcat(out sep sprintf(nil "\"%s\"" x)) sep = ",") strcat(out "]"))"#)
203}
204
205/// Convert a JSON object string to a SKILL association list.
206///
207/// Input:  `{"start":"1","stop":"10G","dec":"20"}`
208/// Output: `(("start" "1") ("stop" "10G") ("dec" "20"))`
209///
210/// Returns `Err` if the input is not valid JSON or not a JSON object.
211pub(crate) fn json_to_skill_alist(json_str: &str) -> Result<String, String> {
212    let parsed: serde_json::Value = serde_json::from_str(json_str)
213        .map_err(|e| format!("invalid JSON: {e}"))?;
214    let obj = parsed
215        .as_object()
216        .ok_or_else(|| "expected a JSON object".to_string())?;
217    let pairs: Vec<String> = obj
218        .iter()
219        .map(|(k, v)| {
220            let binding = v.to_string();
221            let val = v.as_str().unwrap_or(&binding);
222            format!("(\"{k}\" \"{val}\")")
223        })
224        .collect();
225    Ok(format!("({})", pairs.join(" ")))
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    fn ops() -> MaestroOps {
233        MaestroOps
234    }
235
236    #[test]
237    fn open_session_quoting() {
238        let s = ops().open_session("myLib", "myCell", "adexl");
239        assert_eq!(s, r#"maeOpenSetup("myLib" "myCell" "adexl")"#);
240    }
241
242    #[test]
243    fn open_session_escapes_quotes() {
244        let s = ops().open_session(r#"lib"x"#, "cell", "adexl");
245        assert!(s.contains(r#"lib\"x"#), "{s}");
246    }
247
248    #[test]
249    fn set_var_format() {
250        let s = ops().set_var("Vdd", "1.8");
251        assert_eq!(s, r#"maeSetVar("Vdd" "1.8")"#);
252    }
253
254    #[test]
255    fn run_simulation_includes_session() {
256        let s = ops().run_simulation("sess1");
257        assert!(s.contains("maeRunSimulation"), "{s}");
258        assert!(s.contains("\"sess1\""), "{s}");
259    }
260
261    #[test]
262    fn list_sessions_uses_helper() {
263        let s = ops().list_sessions();
264        assert!(s.contains("maeGetSessions()"), "{s}");
265        assert!(s.contains("foreach"), "{s}");
266        assert!(s.contains(r#"strcat(out "]")"#), "{s}");
267    }
268
269    #[test]
270    fn get_analyses_resolves_setup() {
271        let s = ops().get_analyses("sess1");
272        assert!(s.contains("maeGetSetup"), "must resolve setup: {s}");
273        assert!(s.contains("maeGetEnabledAnalysis"), "{s}");
274        assert!(s.contains("foreach"), "must produce JSON array: {s}");
275    }
276
277    #[test]
278    fn get_result_tests_uses_helper() {
279        let s = ops().get_result_tests();
280        assert!(s.contains("maeGetResultTests()"), "{s}");
281        assert!(s.contains("foreach"), "{s}");
282    }
283
284    #[test]
285    fn get_history_list_uses_helper() {
286        let s = ops().get_history_list("fnxSession0");
287        assert!(s.contains("maeGetAllExplorerHistoryNames"), "{s}");
288        assert!(s.contains("fnxSession0"), "{s}");
289        assert!(s.contains("foreach"), "{s}");
290    }
291
292    #[test]
293    fn set_analysis_ic23_positional() {
294        let s = ops().set_analysis("sess1", "ac", None, VirtuosoVersion::IC23);
295        assert!(s.contains("maeGetSetup"), "IC23 must resolve setup: {s}");
296        assert!(s.contains("maeSetAnalysis"), "{s}");
297        assert!(s.contains("\"ac\""), "{s}");
298    }
299
300    #[test]
301    fn set_analysis_ic23_no_options() {
302        let s = ops().set_analysis("sess1", "ac", None, VirtuosoVersion::IC23);
303        assert!(!s.contains("?options"), "IC23 path must not inject options: {s}");
304    }
305
306    #[test]
307    fn add_output_includes_expr() {
308        let s = ops().add_output("gain", "AC", "getData(\"vout\")");
309        assert!(s.contains("maeAddOutput"), "{s}");
310        assert!(s.contains("\"gain\""), "{s}");
311        assert!(s.contains("\"AC\""), "{s}");
312    }
313
314    #[test]
315    fn json_to_skill_alist_valid_input() {
316        let input = r#"{"start":"1","stop":"10G"}"#;
317        let out = json_to_skill_alist(input).unwrap();
318        assert!(out.contains("(\"start\" \"1\")"), "{out}");
319        assert!(out.contains("(\"stop\" \"10G\")"), "{out}");
320    }
321
322    #[test]
323    fn json_to_skill_alist_invalid_json_returns_err() {
324        assert!(json_to_skill_alist("not json").is_err());
325    }
326
327    #[test]
328    fn json_to_skill_alist_non_object_returns_err() {
329        assert!(json_to_skill_alist("[1,2,3]").is_err());
330    }
331}