diff --git a/README.md b/README.md index 069b202..8dcc592 100644 --- a/README.md +++ b/README.md @@ -185,7 +185,9 @@ Rules: the shapes, `--graphics drop` removes them. - A class with only placed connectors and no connections (an interface) is left as it is. - A component inherited from a base class sits where the base class has it. When the base class - is laid out in the same run, that is its new place. + is laid out in the same run, that is its new place. The new components go beside the inherited + ones (not beside inherited connectors), on the side where the lines to them are shortest; no + component or line is placed on an inherited component. - A file that is not UTF-8 is refused. - A second run on the result changes nothing. @@ -286,7 +288,7 @@ to crates.io (`publish = false`). its rotation and flip; the size of an existing extent is kept. Circuits with many parallel branches (ladders) come out worse than hand-made layouts: there are no junction points. - Modifiers and redeclarations are not applied in the class lookup. -- Connections to inherited components do not influence the placement. +- Connections to inherited components only choose the side the new components go to. - With `--keep`, existing lines are not obstacles for the new ones. - `replaceable ... constrainedby ... annotation(...)`: the `Placement` goes into the annotation of the constraining clause. diff --git a/src/api.rs b/src/api.rs index 7c75ded..3613db9 100644 --- a/src/api.rs +++ b/src/api.rs @@ -117,7 +117,7 @@ pub(crate) fn layout_diagrams( } res.classes.push(ClassReport { name: name.clone(), - components: d.nodes.len(), + components: d.nodes.iter().filter(|n| !n.inherited).count(), connections: d.links.len(), placed, routed, diff --git a/src/layout/extract.rs b/src/layout/extract.rs index a46c5c4..c4445d8 100644 --- a/src/layout/extract.rs +++ b/src/layout/extract.rs @@ -23,7 +23,7 @@ use crate::source::absyn::{ }; use crate::source::lookup::{ClassId, DEFAULT_ICON_SYSTEM, LayoutPlaces, Library, file_path, read_text}; use crate::source::resolve::{ - ClassKind, MAX_LOOKUP_DEPTH, class_color, direction_code, find_component, icon_places, icon_system, + ClassKind, MAX_LOOKUP_DEPTH, base_classes, class_color, direction_code, find_component, icon_places, icon_system, is_builtin_path, kind_and_causality, lookup_path, port_info, read_placement, restriction_kind, transformation_centre, }; @@ -238,9 +238,22 @@ impl Extraction<'_> { } } + /// Every component inherited from a base class that has a place, as a fixed node: the parts of + /// the class are placed clear of them and the lines routed around them. + fn inherited_obstacles(&mut self) { + let mut names = Vec::new(); + inherited_names(self.lib, self.class, 0, &mut names); + for name in names { + if !self.d.index.contains_key(&name) { + self.inherited_node(&name, true); + } + } + } + /// The node of a component inherited from a base class. It is where the base class has it: at - /// the place this run gives it there, or else at its placement. - fn inherited_node(&mut self, name: &str) -> Option { + /// the place this run gives it there, or else at its placement. With `drawn`, none for a + /// component whose class has no diagram box (a type, a function, a package). + fn inherited_node(&mut self, name: &str, drawn: bool) -> Option { let d = find_component(self.lib, self.class, name, 0)?; if d.owner == self.class { return None; @@ -267,6 +280,9 @@ impl Extraction<'_> { let tref = lookup_path(self.lib, d.owner, tp, false, 0); let direction = d.attributes().map_or(ACAUSAL, direction_code); let (kind, direction) = kind_and_causality(self.lib, tref, direction); + if drawn && kind.is_some_and(ClassKind::is_not_drawn) { + return None; + } let mut n = self.make_node(name, &path_parts(tp).join("."), tref, kind, direction, &t); n.set_transformation(&t); n.fixed = true; @@ -285,7 +301,7 @@ impl Extraction<'_> { } let ni = match self.d.index.get(&first) { Some(i) => *i, - None => self.inherited_node(&first)?, + None => self.inherited_node(&first, false)?, }; let n = &self.d.nodes[ni]; if n.is_connector || second.is_empty() { @@ -504,7 +520,42 @@ pub fn is_interface(d: &Diagram) -> bool { d.links.is_empty() && d.nodes .iter() - .all(|n| n.is_connector && n.has_transformation && !n.inherited) + .filter(|n| !n.inherited) + .all(|n| n.is_connector && n.has_transformation) +} + +/// The names of the components that class `c` inherits, from its base classes and theirs, in +/// order and without repeats; components of a built-in type are left out. +fn inherited_names(lib: &mut Library, c: ClassId, depth: usize, out: &mut Vec) { + if depth > MAX_LOOKUP_DEPTH { + return; + } + for b in base_classes(lib, c, depth) { + let elements = lib.elements_of(b); + for e in elements.iter() { + let Absyn::ELEMENT { specification, .. } = &**e else { + continue; + }; + let Absyn::COMPONENTS { + typeSpec: type_spec, + components, + .. + } = &**specification + else { + continue; + }; + if is_builtin_path(&path_parts(type_path(type_spec))) { + continue; + } + for item in components { + let name = item.component.name.as_str(); + if !out.iter().any(|o| o == name) { + out.push(name.to_owned()); + } + } + } + inherited_names(lib, b, depth + 1, out); + } } /// The diagram of class `c`, or none when it has nothing to lay out: no components, or only @@ -546,8 +597,9 @@ pub fn extract_diagram( } } x.drop_tentative(); + x.inherited_obstacles(); let mut d = x.d; - if d.nodes.is_empty() || is_interface(&d) { + if (d.nodes.iter().all(|n| n.inherited) && d.links.is_empty()) || is_interface(&d) { return None; } d.end_tok = class_end_token(src, &class); diff --git a/src/layout/placement.rs b/src/layout/placement.rs index 8e50496..4fdde2f 100644 --- a/src/layout/placement.rs +++ b/src/layout/placement.rs @@ -187,6 +187,74 @@ fn layout_free(d: &mut Diagram, opts: &Options) { } } +/// Move the free nodes as one block beside the inherited components (not the connectors): right +/// of, below, left of or above them, on the side where the lines between the two are shortest +/// (right when there are none). The components of the base class keep their places and the new +/// ones their layout; inherited connectors on the border keep the block between them. +fn beside_inherited(d: &mut Diagram, opts: &Options) { + let parts: Vec = (0..d.nodes.len()) + .filter(|&i| d.nodes[i].inherited && !d.nodes[i].is_connector) + .collect(); + let free: Vec = (0..d.nodes.len()).filter(|&i| !d.nodes[i].fixed).collect(); + if parts.is_empty() || free.is_empty() { + return; + } + let f = box_of(d, &parts); + let b = box_of(d, &free); + // The ends of the lines between a free node and a fixed one: (free, fixed). + let pairs: Vec<(Point, Point)> = d + .links + .iter() + .filter_map(|l| { + let (a, b) = (d.nodes[l.a].port_position(l.pa), d.nodes[l.b].port_position(l.pb)); + match (d.nodes[l.a].fixed, d.nodes[l.b].fixed) { + (false, true) => Some((a, b)), + (true, false) => Some((b, a)), + _ => None, + } + }) + .collect(); + // The shift along a side that lines the block up with the fixed nodes it connects to; without + // lines, the tops (right and left) or the left edges (below and above) line up. + let along = |vertical: bool| -> f64 { + if pairs.is_empty() { + return if vertical { f.3 - b.3 } else { f.0 - b.0 }; + } + let sum: f64 = pairs + .iter() + .map(|&(p, q)| if vertical { q.1 - p.1 } else { q.0 - p.0 }) + .sum(); + sum / pairs.len() as f64 + }; + let sides = [ + (f.2 + opts.dx - b.0, along(true)), + (along(false), f.1 - opts.dy - b.3), + (f.0 - opts.dx - b.2, along(true)), + (along(false), f.3 + opts.dy - b.1), + ]; + let length = |s: (f64, f64)| -> f64 { + pairs + .iter() + .map(|&(p, q)| (p.0 + s.0 - q.0).abs() + (p.1 + s.1 - q.1).abs()) + .sum() + }; + let mut best = sides[0]; + for &s in &sides[1..] { + if length(s) < length(best) - 1.0e-9 { + best = s; + } + } + shift_nodes( + d, + &free, + (best.0 / 10.0).round_ties_even() * 10.0, + (best.1 / 10.0).round_ties_even() * 10.0, + ); + for &i in &free { + d.nodes[i].set_free(); + } +} + /// Move the free nodes that overlap a fixed node to the nearest free position. fn clear_fixed(d: &mut Diagram, opts: &Options) { let gap = opts.dx.min(opts.dy) / 2.0; @@ -402,6 +470,7 @@ pub fn place_diagram(d: &mut Diagram, opts: &Options) { } } if fixed > 0 { + beside_inherited(d, opts); clear_fixed(d, opts); } } diff --git a/src/source/tokens.rs b/src/source/tokens.rs index 0cc6974..fa2beb4 100644 --- a/src/source/tokens.rs +++ b/src/source/tokens.rs @@ -234,10 +234,10 @@ impl Source { /// The token that closes the bracket opened by token `i`. pub fn match_close(&self, i: usize) -> Option { let mut depth: i32 = 0; - for j in i..self.kinds.len() { - if is_open(&self.kinds[j]) { + for (j, k) in self.kinds.iter().enumerate().skip(i) { + if is_open(k) { depth += 1; - } else if is_close(&self.kinds[j]) { + } else if is_close(k) { depth -= 1; if depth == 0 { return Some(j); @@ -252,8 +252,7 @@ impl Source { let mut segs: Vec = Vec::new(); let mut depth: i32 = 0; let mut seg = Segment::ending_at(s); - for j in s..self.kinds.len() { - let k = &self.kinds[j]; + for (j, k) in self.kinds.iter().enumerate().skip(s) { if is_open(k) { depth += 1; } else if is_close(k) { @@ -282,8 +281,7 @@ impl Source { pub fn equation_end(&self, s: usize) -> (Option, Option) { let mut depth: i32 = 0; let mut ann: Option = None; - for j in s..self.kinds.len() { - let k = &self.kinds[j]; + for (j, k) in self.kinds.iter().enumerate().skip(s) { if is_open(k) { depth += 1; } else if is_close(k) { diff --git a/src/tests.rs b/src/tests.rs index 52c5279..3609fe4 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -101,6 +101,15 @@ const CASES: &[Case] = &[ expected: "Features-keep.mo", set: |o| o.keep = true, }, + Case { + model: "Inheritance.mo", + expected: "Inheritance.mo", + set: |o| { + o.classes = ["Extended", "Separate", "Deeper", "Circuit"] + .map(|c| format!("Inheritance.{c}")) + .to_vec(); + }, + }, Case { model: "Tickets.mo", expected: "Tickets.mo", @@ -116,9 +125,6 @@ const CASES: &[Case] = &[ }, ]; -/// Components that keep a place given elsewhere, so the class does not place them: (class, how many). -const NOT_PLACED: &[(&str, usize)] = &[("Features.Derived", 1)]; - /// The text of a file with LF line endings. fn read_lf(path: &Path) -> Option { std::fs::read_to_string(path).ok().map(|t| t.replace("\r\n", "\n")) @@ -197,8 +203,7 @@ fn check_report(result: &LayoutResult, opts: &Options) -> Result<(), String> { return Err(format!("warnings: {:?}", result.warnings)); } for c in &result.classes { - let given = NOT_PLACED.iter().find(|(n, _)| *n == c.name).map_or(0, |(_, k)| *k); - if (!opts.keep && c.placed + given != c.components) || c.routed != c.connections { + if (!opts.keep && c.placed != c.components) || c.routed != c.connections { return Err(format!( "{}: {} of {} placed, {} of {} routed", c.name, c.placed, c.components, c.routed, c.connections diff --git a/test/README.md b/test/README.md index 95b57c9..f9c5024 100644 --- a/test/README.md +++ b/test/README.md @@ -6,6 +6,6 @@ parts in `library/` and compares each result with its file in `expected/`. | File | Origin | |---|---| | `library/Parts.mo` | Written for these tests. Names, connector placements and the `RealInput`/`RealOutput` icon follow the Modelica Standard Library 4.1.0 (3-Clause BSD License, Modelica Association; see [LICENSE.md](../LICENSE.md)). No MSL classes are copied. | -| `models/Chain.mo`, `Control.mo`, `DriveTrain.mo`, `Features.mo`, `GainChain.mo`, `RCLadder.mo`, `ResistorMesh.mo` | Written for these tests. | +| `models/Chain.mo`, `Control.mo`, `DriveTrain.mo`, `Features.mo`, `GainChain.mo`, `Inheritance.mo`, `RCLadder.mo`, `ResistorMesh.mo` | Written for these tests. | | `models/Tickets.mo` | Written for these tests, after the OpenModelica issues on auto layout: `System` is the example of [#16959](https://github.com/OpenModelica/OpenModelica/issues/16959); `Partial` and `Bad` are the missing, partial and bad annotations of [#7232](https://github.com/OpenModelica/OpenModelica/issues/7232). The media and fluid parts are stand-ins, not the MSL's. | | `expected/*.mo` | Written by mocoal (`MOCOAL_BLESS=1 cargo test -p mocoal layouts`). | diff --git a/test/expected/Features.mo b/test/expected/Features.mo index 076d716..e5e3e5a 100644 --- a/test/expected/Features.mo +++ b/test/expected/Features.mo @@ -31,11 +31,12 @@ package Features "The rules of the layout: own connectors, inheritance, unconnec model Derived "The inherited components sit where Base has them" extends Base; - Parts.Integrator integrator annotation(Placement(transformation(origin={-30,0}, extent={{-10,-10},{10,10}}))); - Parts.Gain amplifier annotation(Placement(transformation(origin={-10,30}, extent={{-10,-10},{10,10}}))); + Parts.Integrator integrator annotation(Placement(transformation(origin={70,0}, extent={{-10,-10},{10,10}}))); + Parts.Gain amplifier annotation(Placement(transformation(origin={120,0}, extent={{-10,-10},{10,10}}))); equation - connect(gain.y, integrator.u) annotation(Line(points={{31,0},{40,0},{40,-15},{-50,-15},{-50,0},{-42,0}}, color={0,0,127})); - connect(integrator.y, amplifier.u) annotation(Line(points={{-19,0},{-10,0},{-10,15},{-30,15},{-30,30},{-22,30}}, color={0,0,127})); + connect(gain.y, integrator.u) annotation(Line(points={{31,0},{58,0}}, color={0,0,127})); + connect(integrator.y, amplifier.u) annotation(Line(points={{81,0},{108,0}}, color={0,0,127})); + annotation(Diagram(coordinateSystem(extent={{-100,-100},{160,100}}))); end Derived; model Unconnected "Connected parts in a row, unconnected ones in a grid" diff --git a/test/expected/Inheritance.mo b/test/expected/Inheritance.mo new file mode 100644 index 0000000..5b1a507 --- /dev/null +++ b/test/expected/Inheritance.mo @@ -0,0 +1,46 @@ +package Inheritance "Components inherited from a base class keep their places; the new ones go beside them" + model Placed "Placed by hand; not laid out in the run" + Parts.Constant source annotation(Placement(transformation(origin = {-60, 0}, extent = {{-10, -10}, {10, 10}}))); + Parts.Gain gain annotation(Placement(transformation(origin = {-20, 0}, extent = {{-10, -10}, {10, 10}}))); + equation + connect(source.y, gain.u) annotation(Line(points = {{-49, 0}, {-32, 0}}, color = {0, 0, 127})); + end Placed; + + model Extended "New parts connected to the inherited gain: in a row after it" + extends Placed; + Parts.Integrator integrator annotation(Placement(transformation(origin={30,0}, extent={{-10,-10},{10,10}}))); + Parts.Gain sensor annotation(Placement(transformation(origin={80,0}, extent={{-10,-10},{10,10}}))); + equation + connect(gain.y, integrator.u) annotation(Line(points={{-9,0},{18,0}}, color={0,0,127})); + connect(integrator.y, sensor.u) annotation(Line(points={{41,0},{68,0}}, color={0,0,127})); + annotation(Diagram(coordinateSystem(extent={{-100,-100},{120,100}}))); + end Extended; + + model Separate "New parts not connected to the inherited ones: beside them, not on them" + extends Placed; + Parts.Sine sine annotation(Placement(transformation(origin={30,0}, extent={{-10,-10},{10,10}}))); + Parts.Gain amplifier annotation(Placement(transformation(origin={80,0}, extent={{-10,-10},{10,10}}))); + equation + connect(sine.y, amplifier.u) annotation(Line(points={{41,0},{68,0}}, color={0,0,127})); + annotation(Diagram(coordinateSystem(extent={{-100,-100},{120,100}}))); + end Separate; + + model Deeper "Inherited through Extended, which is laid out in the same run" + extends Extended; + Parts.Gain extra annotation(Placement(transformation(origin={130,0}, extent={{-10,-10},{10,10}}))); + equation + connect(sensor.y, extra.u) annotation(Line(points={{91,0},{118,0}}, color={0,0,127})); + annotation(Diagram(coordinateSystem(extent={{-100,-100},{160,100}}))); + end Deeper; + + model Circuit "Inherited connectors on the border: the new parts go between them" + extends Parts.TwoPin; + Parts.Resistor r1 annotation(Placement(transformation(origin={-30,0}, extent={{-10,-10},{10,10}}))); + Parts.Resistor r2 annotation(Placement(transformation(origin={20,0}, extent={{-10,-10},{10,10}}))); + equation + connect(p, r1.p) annotation(Line(points={{-100,0},{-40,0}}, color={0,0,255})); + connect(r1.n, r2.p) annotation(Line(points={{-20,0},{10,0}}, color={0,0,255})); + connect(r2.n, n) annotation(Line(points={{30,0},{100,0}}, color={0,0,255})); + annotation(Diagram(coordinateSystem(extent={{-140,-100},{140,100}}))); + end Circuit; +end Inheritance; diff --git a/test/models/Inheritance.mo b/test/models/Inheritance.mo new file mode 100644 index 0000000..01c1009 --- /dev/null +++ b/test/models/Inheritance.mo @@ -0,0 +1,42 @@ +package Inheritance "Components inherited from a base class keep their places; the new ones go beside them" + model Placed "Placed by hand; not laid out in the run" + Parts.Constant source annotation(Placement(transformation(origin = {-60, 0}, extent = {{-10, -10}, {10, 10}}))); + Parts.Gain gain annotation(Placement(transformation(origin = {-20, 0}, extent = {{-10, -10}, {10, 10}}))); + equation + connect(source.y, gain.u) annotation(Line(points = {{-49, 0}, {-32, 0}}, color = {0, 0, 127})); + end Placed; + + model Extended "New parts connected to the inherited gain: in a row after it" + extends Placed; + Parts.Integrator integrator; + Parts.Gain sensor; + equation + connect(gain.y, integrator.u); + connect(integrator.y, sensor.u); + end Extended; + + model Separate "New parts not connected to the inherited ones: beside them, not on them" + extends Placed; + Parts.Sine sine; + Parts.Gain amplifier; + equation + connect(sine.y, amplifier.u); + end Separate; + + model Deeper "Inherited through Extended, which is laid out in the same run" + extends Extended; + Parts.Gain extra; + equation + connect(sensor.y, extra.u); + end Deeper; + + model Circuit "Inherited connectors on the border: the new parts go between them" + extends Parts.TwoPin; + Parts.Resistor r1; + Parts.Resistor r2; + equation + connect(p, r1.p); + connect(r1.n, r2.p); + connect(r2.n, n); + end Circuit; +end Inheritance;