]> git.vpit.fr Git - perl/modules/LaTeX-TikZ.git/blobdiff - lib/LaTeX/TikZ/Functor/Rule.pm
Insert rules after all their subrules and before all their superrules
[perl/modules/LaTeX-TikZ.git] / lib / LaTeX / TikZ / Functor / Rule.pm
index bccbb48d739707e5a5f416d4356c98533596416d..d4e070011a3b5e7413d81c6b3e67bd3d0ff792dd 100644 (file)
@@ -123,8 +123,9 @@ around 'BUILDARGS' => sub {
 =head2 C<< insert into => \@list, overwrite => $overwrite, replace => $replace >>
 
 Inserts the current rule into the list of rules C<@list>.
+The list is expected to be ordered, in that each rule must come after all the rules that have a target that inherits or consumes the original rule's own target.
 
-If C<$replace> is false, then the rule will be appended to the C<@list> ; except if there already is an existent entry for the same target, in which case it will be overwritten if C<$overwrite> is true, or an exception will be thrown if it is false.
+If C<$replace> is false, then the rule will be inserted into C<@list> after all the rules applying to the target's subclasses/subroles and before all its superclasses/superroles ; except if there is already an existent entry for the same target, in which case it will be overwritten if C<$overwrite> is true, or an exception will be thrown if it is false.
 
 If C<$replace> is true, then the rule will replace the first rule in the list that is a subclass or that consumes the role denoted by the target.
 All the subsequent rules in the list that inherit or consume the target will be removed.
@@ -167,15 +168,37 @@ sub insert {
  } else { # Replace only an existent rule
   my $target  = $rule->target;
 
+  my $last_descendant = undef;
+  my $first_ancestor  = undef;
+
   for my $i (0 .. $#$list) {
-   my $old_target = $list->[$i]->target;
+   my $old_rule   = $list->[$i];
+   my $old_target = $old_rule->target;
    if ($old_target eq $target) {
     Carp::confess("Default rule already defined for target $target")
                                                               unless $overwrite;
     splice @$list, $i, 1, $rule;
     return 1;
+   } elsif ($rule->handles($old_target)) {
+    $last_descendant = $i;
+   } elsif ($old_rule->handles($target)) {
+    $first_ancestor  = $i;
    }
   }
+
+  my $pos;
+  if (defined $first_ancestor) {
+   Carp::confess("Unsorted rule list")
+            if defined $last_descendant and $first_ancestor <= $last_descendant;
+   $pos = $first_ancestor;
+  } elsif (defined $last_descendant) {
+   $pos = $last_descendant + 1;
+  }
+
+  if (defined $pos) {
+   splice @$list, $pos, 1, $rule;
+   return 0;
+  }
  }
 
  push @$list, $rule;