Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,14 @@ macOS arm64: `mocoal` 1.6 MB, `libmocoal.dylib` 1.5 MB, no other files needed at

```
usage: mocoal [options] file.mo|directory ...
mocoal [options] --stdin file.mo

Give the components of Modelica models a placement and the connections a line.
One file without -o, -i or -n: the result is printed.

-o, --output FILE write the result to FILE (one input file)
--stdin FILE read the text of FILE from the standard input (FILE need not
exist; its place finds the libraries next to it)
-i, --in-place change the input files
-n, --dry-run report only, write nothing
-c, --class NAME lay out only this class or package (may be repeated)
Expand Down
6 changes: 3 additions & 3 deletions src/capi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
//! Mirrors `juliac/libmocoal.jl` of ModelicaComponentAutolayout.jl.

use std::ffi::{CStr, CString, c_char};
use std::panic::catch_unwind;
use std::sync::Mutex;

use crate::cli::layout_text;
use crate::stack::on_large_stack;

/// The message of the last `mocoal_layout`.
static MESSAGE: Mutex<Option<CString>> = Mutex::new(None);
Expand Down Expand Up @@ -66,8 +66,8 @@ pub unsafe extern "C" fn mocoal_layout(
let args = unsafe { (c_text(text), c_text(file_name), c_text(options)) };
let result = match args {
(Ok(text), Ok(file_name), Ok(options)) => {
// No panic may cross the interface.
catch_unwind(|| layout(text, file_name, options)).unwrap_or_else(|_| Err(INTERNAL_ERROR.to_owned()))
// No panic may cross the interface; deep nesting needs more stack than the caller's thread may have.
on_large_stack(|| layout(text, file_name, options)).unwrap_or_else(|_| Err(INTERNAL_ERROR.to_owned()))
}
(Err(e), _, _) | (_, Err(e), _) | (_, _, Err(e)) => Err(e),
};
Expand Down
13 changes: 13 additions & 0 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@ use crate::options::Options;
use crate::source::lookup::{is_dir, is_file, join_path};

pub const USAGE_TEXT: &str = "usage: mocoal [options] file.mo|directory ...
mocoal [options] --stdin file.mo

Give the components of Modelica models a placement and the connections a line.
One file without -o, -i or -n: the result is printed.

-o, --output FILE write the result to FILE (one input file)
--stdin FILE read the text of FILE from the standard input (FILE need not
exist; its place finds the libraries next to it)
-i, --in-place change the input files
-n, --dry-run report only, write nothing
-c, --class NAME lay out only this class or package (may be repeated)
Expand All @@ -43,6 +46,8 @@ pub struct CommandLine {
pub opts: Options,
pub inputs: Vec<String>,
pub output: String,
/// With `--stdin`: the name of the file whose text is read from the standard input.
pub stdin: String,
pub in_place: bool,
pub dry_run: bool,
pub quiet: bool,
Expand All @@ -57,6 +62,7 @@ impl CommandLine {
let o = &mut self.opts;
match name {
"-o" | "--output" => self.output = value.to_owned(),
"--stdin" => self.stdin = value.to_owned(),
"-c" | "--class" => o.classes.push(value.to_owned()),
"-L" | "--library" => o.libraries.push(value.to_owned()),
"--layout" => o.layout = value.to_owned(),
Expand Down Expand Up @@ -104,6 +110,7 @@ fn takes_value(name: &str) -> bool {
matches!(
name,
"-o" | "--output"
| "--stdin"
| "-c"
| "--class"
| "-L"
Expand Down Expand Up @@ -197,6 +204,7 @@ pub fn layout_text(text: &str, file_name: &str, options: &str) -> Result<(String
let cl = parse_arguments(&split_arguments(options))?;
if !cl.inputs.is_empty()
|| !cl.output.is_empty()
|| !cl.stdin.is_empty()
|| cl.in_place
|| !cl.svg_dir.is_empty()
|| cl.dry_run
Expand Down Expand Up @@ -263,6 +271,11 @@ mod tests {
);
assert_eq!(cl.opts.classes, ["A", "B.C"]);
assert_eq!(cl.inputs, ["x.mo", "-y.mo"]);
assert_eq!(
parse_arguments(&words("--stdin \"/a b/M.mo\"")).unwrap().stdin,
"/a b/M.mo"
);
assert!(layout_text("model M end M;", "M.mo", "--stdin M.mo").is_err());
assert_eq!(
parse_arguments(&words("--scale")).unwrap_err(),
"--scale: a value is missing"
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ pub mod api;
pub mod capi;
pub mod options;
pub mod program;
pub mod stack;

mod cli;
mod layout;
Expand Down
9 changes: 8 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,12 @@ fn main() -> ExitCode {
.skip(1)
.map(|a| a.to_string_lossy().into_owned())
.collect();
ExitCode::from(mocoal::program::run(&args))
// Deep nesting in a model needs more stack than the main thread has.
match mocoal::stack::on_large_stack(|| mocoal::program::run(&args)) {
Ok(status) => ExitCode::from(status),
Err(_) => {
eprintln!("mocoal: internal error");
ExitCode::from(1)
}
}
}
51 changes: 45 additions & 6 deletions src/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
//! that is wrong.
//! Mirrors `src/main.jl` of ModelicaComponentAutolayout.jl.

use std::io::Write;
use std::io::{Read, Write};
use std::panic::{AssertUnwindSafe, catch_unwind};

use crate::api::{VERSION, layout_file_in, write_text};
use crate::api::{VERSION, layout_file_in, layout_string_in, write_text};
use crate::cli::{CommandLine, USAGE_TEXT, modelica_files, parse_arguments, svg_file_name};
use crate::source::lookup::{Library, file_path, is_dir, is_file, join_path};

Expand All @@ -24,9 +24,21 @@ fn say(s: &str) {
/// was.
type Pending = Vec<(String, String)>;

/// Lay out one file as the command line asks: (done, changed).
fn run_file(cl: &CommandLine, lib: &mut Library, file: &str, several: bool, pending: &mut Pending) -> (bool, bool) {
let res = match catch_unwind(AssertUnwindSafe(|| layout_file_in(file, &cl.opts, lib))) {
/// Lay out one file as the command line asks: (done, changed). `text` is the text of `file` when
/// it is not read from the file (`--stdin`).
fn run_file(
cl: &CommandLine,
lib: &mut Library,
file: &str,
text: Option<&str>,
several: bool,
pending: &mut Pending,
) -> (bool, bool) {
let lay = |lib: &mut Library| match text {
Some(text) => layout_string_in(text, file, &cl.opts, lib),
None => layout_file_in(file, &cl.opts, lib),
};
let res = match catch_unwind(AssertUnwindSafe(|| lay(lib))) {
Ok(Ok(res)) => res,
Ok(Err(msg)) => {
say(&format!("mocoal: {msg}"));
Expand Down Expand Up @@ -104,6 +116,9 @@ pub fn run(args: &[String]) -> u8 {
println!("mocoal {VERSION}");
return 0;
}
if !cl.stdin.is_empty() {
return run_stdin(&cl);
}
if cl.inputs.is_empty() {
eprint!("{USAGE_TEXT}");
return 2;
Expand Down Expand Up @@ -141,7 +156,7 @@ pub fn run(args: &[String]) -> u8 {
let mut changed = 0;
let mut pending = Pending::new();
for file in &files {
let (ok, ch) = run_file(&cl, &mut lib, file, several, &mut pending);
let (ok, ch) = run_file(&cl, &mut lib, file, None, several, &mut pending);
failed += usize::from(!ok);
changed += usize::from(ch);
}
Expand All @@ -158,3 +173,27 @@ pub fn run(args: &[String]) -> u8 {
}
u8::from(failed > 0)
}

/// `--stdin FILE`: lay out the text on the standard input as the text of `FILE`.
fn run_stdin(cl: &CommandLine) -> u8 {
if !cl.inputs.is_empty() || cl.in_place {
say("mocoal: --stdin takes no input files and no -i");
return 2;
}
if !cl.svg_dir.is_empty() && std::fs::create_dir_all(&cl.svg_dir).is_err() {
say(&format!("mocoal: cannot create {}", cl.svg_dir));
return 2;
}
let mut bytes = Vec::new();
if std::io::stdin().read_to_end(&mut bytes).is_err() {
say("mocoal: cannot read the standard input");
return 2;
}
let Ok(text) = String::from_utf8(bytes) else {
say(&format!("mocoal: {}: not UTF-8", cl.stdin));
return 1;
};
let mut lib = Library::new(&cl.opts.libraries);
let (ok, _) = run_file(cl, &mut lib, &cl.stdin, Some(&text), false, &mut Pending::new());
u8::from(!ok)
}
102 changes: 102 additions & 0 deletions src/stack.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// This file is part of mocoal-rs.
// Copyright (c) 2026 Open Source Modelica Consortium (OSMC)
//
// This program is provided under the terms of the GNU AGPL version 3 license or the OSMC Public
// License (OSMC-PL) version 1.8, according to the recipient's choice. See LICENSE.md.

//! A thread with a large stack for the layout. The parser descends recursively: each level of
//! nesting in a model (parentheses, packages) takes about 3 KB of stack in a release build, so an
//! 8 MB main thread overflows at about 2500 levels, which omc still loads (it stops at 10000). A
//! stack overflow aborts the process; no `catch_unwind` stops it.

use std::any::Any;
use std::io;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Mutex;
use std::thread;

/// 256 MB: about 80000 levels. Only the part that is used takes memory.
pub const STACK_SIZE: usize = 256 << 20;

/// `f()` on a thread with a stack of `STACK_SIZE`. `Err` when `f` panics. Without such a thread
/// (a limit on memory), `f()` runs on the current thread.
pub fn on_large_stack<T: Send>(f: impl FnOnce() -> T + Send) -> Result<T, Box<dyn Any + Send>> {
// The thread takes `f` from here; when there is no thread, `f` is still here.
let slot = Mutex::new(Some(f));
let take = || slot.lock().unwrap_or_else(|e| e.into_inner()).take();
let spawned = thread::scope(|s| {
if no_thread() {
return Err(io::Error::other("no thread (test)"));
}
thread::Builder::new()
.stack_size(STACK_SIZE)
.spawn_scoped(s, || take().map(|f| f()))
.map(|handle| handle.join())
});
match spawned {
Ok(Ok(Some(value))) => Ok(value),
Ok(Ok(None)) => unreachable!("the thread runs f"),
Ok(Err(panic)) => Err(panic),
Err(_) => match take() {
Some(f) => catch_unwind(AssertUnwindSafe(f)),
None => unreachable!("no thread took f"),
},
}
}

/// True when a test asks for no thread, as under a limit on memory.
#[cfg(not(test))]
fn no_thread() -> bool {
false
}

#[cfg(test)]
fn no_thread() -> bool {
tests::NO_THREAD.get()
}

#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;

thread_local! {
/// Set by a test: `on_large_stack` gets no thread.
pub static NO_THREAD: Cell<bool> = const { Cell::new(false) };
}
use crate::api::layout_string;
use crate::options::Options;

/// A model whose equation has `n` nested parentheses.
fn deep(n: usize) -> String {
format!(
"model Deep\n Real x = {}1{};\nend Deep;\n",
"(".repeat(n),
")".repeat(n)
)
}

#[test]
fn deep_nesting_on_the_large_stack() {
// 4000 levels overflow the 8 MB main thread of a release build and the 2 MB test thread.
let text = deep(4000);
let result = on_large_stack(|| layout_string(&text, "Deep.mo", &Options::default()));
assert!(matches!(result, Ok(Ok(_))));
}

#[test]
fn without_the_thread_on_the_current_one() {
NO_THREAD.set(true);
let value = on_large_stack(|| 7).ok();
let panic = on_large_stack(|| -> u8 { panic!("test") }).is_err();
NO_THREAD.set(false);
assert_eq!(value, Some(7));
assert!(panic);
}

#[test]
fn a_panic_is_an_error() {
assert!(on_large_stack(|| -> u8 { panic!("test") }).is_err());
assert_eq!(on_large_stack(|| 7).ok(), Some(7));
}
}
Loading