1 # Copyright (C) 2003-2024 Free Software Foundation, Inc.
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2, or (at your option)
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program. If not, see <https://www.gnu.org/licenses/>.
16 package Automake
::Rule
;
20 use warnings FATAL
=> 'all';
26 use Automake
::RuleDef
;
27 use Automake
::ChannelDefs
;
28 use Automake
::Channels
;
29 use Automake
::Options
;
30 use Automake
::Condition qw
(TRUE FALSE
);
31 use Automake
::DisjConditions
;
33 our @ISA = qw
(Automake
::Item Exporter
);
34 our @EXPORT = qw
(reset register_suffix_rule next_in_suffix_chain
35 suffixes rules
$KNOWN_EXTENSIONS_PATTERN
36 depend
%dependencies %actions register_action
38 reject_rule msg_rule msg_cond_rule err_rule err_cond_rule
39 rule rrule ruledef rruledef
);
43 Automake::Rule - support for rules definitions
48 use Automake::RuleDef;
53 This package provides support for Makefile rule definitions.
55 An C<Automake::Rule> is a rule name associated to possibly
56 many conditional definitions. These definitions are instances
57 of C<Automake::RuleDef>.
59 Therefore obtaining the value of a rule under a given
60 condition involves two lookups. One to look up the rule,
61 and one to look up the conditional definition:
63 my $rule = rule $name;
66 my $def = $rule->def ($cond);
69 return $def->location;
75 when it is known that the rule and the definition
76 being looked up exist, the above can be simplified to
78 return rule ($name)->def ($cond)->location; # do not write this.
82 return rrule ($name)->rdef ($cond)->location;
86 return rruledef ($name, $cond)->location;
88 The I<r> variants of the C<rule>, C<def>, and C<ruledef> methods add
89 an extra test to ensure that the lookup succeeded, and will diagnose
90 failures as internal errors (with a message which is much more
91 informative than Perl's warning about calling a method on a
94 =head2 Global variables
100 my $_SUFFIX_RULE_PATTERN =
101 '^(\.[a-zA-Z0-9_(){}$+@\-]+)(\.[a-zA-Z0-9_(){}$+@\-]+)' . "\$";
104 my @_known_extensions_list = ();
107 # See comments in the implementation of the 'next_in_suffix_chain()'
108 # variable for details.
111 # Same as $suffix_rules, but records only the default rules
112 # supplied by the languages Automake supports.
113 my %_suffix_rules_builtin;
115 =item C<%dependencies>
117 Holds the dependencies of targets which dependencies are factored.
118 Typically, C<.PHONY> will appear in plenty of F<*.am> files, but must
119 be output once. Arguably all pure dependencies could be subject to
120 this factoring, but it is not unpleasant to have paragraphs in
121 Makefile: keeping related stuff altogether.
129 Holds the factored actions. Tied to C<%dependencies>, i.e., filled
130 only when keys exists in C<%dependencies>.
136 =item C<$KNOWN_EXTENSIONS_PATTERN>
138 Pattern that matches all know input extensions (i.e. extensions used
139 by the languages supported by Automake). Using this pattern (instead
140 of '\..*$') to match extensions allows Automake to support dot-less
143 New extensions should be registered with C<accept_extensions>.
147 our $KNOWN_EXTENSIONS_PATTERN = "";
151 =head2 Error reporting functions
153 In these functions, C<$rule> can be either a rule name, or
154 an instance of C<Automake::Rule>.
158 =item C<err_rule ($rule, $message, [%options])>
160 Uncategorized errors about rules.
166 msg_rule
('error', @_);
169 =item C<err_cond_rule ($cond, $rule, $message, [%options])>
171 Uncategorized errors about conditional rules.
175 sub err_cond_rule
($$$;%)
177 msg_cond_rule
('error', @_);
180 =item C<msg_cond_rule ($channel, $cond, $rule, $message, [%options])>
182 Messages about conditional rules.
186 sub msg_cond_rule
($$$$;%)
188 my ($channel, $cond, $rule, $msg, %opts) = @_;
189 my $r = ref ($rule) ?
$rule : rrule
($rule);
190 msg
$channel, $r->rdef ($cond)->location, $msg, %opts;
193 =item C<msg_rule ($channel, $targetname, $message, [%options])>
195 Messages about rules.
201 my ($channel, $rule, $msg, %opts) = @_;
202 my $r = ref ($rule) ?
$rule : rrule
($rule);
203 # Don't know which condition is concerned. Pick any.
204 my $cond = $r->conditions->one_cond;
205 msg_cond_rule
($channel, $cond, $r, $msg, %opts);
209 =item C<$bool = reject_rule ($rule, $error_msg)>
211 Bail out with C<$error_msg> if a rule with name C<$rule> has been
214 Return true iff C<$rule> is defined.
220 my ($rule, $msg) = @_;
223 err_rule
$rule, $msg;
231 =head2 Administrative functions
235 =item C<accept_extensions (@exts)>
237 Update C<$KNOWN_EXTENSIONS_PATTERN> to recognize the extensions
238 listed in C<@exts>. Extensions should contain a dot if needed.
242 sub accept_extensions
(@
)
244 push @_known_extensions_list, @_;
245 $KNOWN_EXTENSIONS_PATTERN =
246 '(?:' . join ('|', map (quotemeta, @_known_extensions_list)) . ')';
251 Return the list of all L<Automake::Rule> instances. (I.e., all
252 rules defined so far.)
258 return values %_rule_dict;
262 =item C<register_action($target, $action)>
264 Append the C<$action> to C<$actions{$target}> taking care of special
269 sub register_action
($$)
271 my ($target, $action) = @_;
272 if ($actions{$target})
274 $actions{$target} .= "\n$action" if $action;
278 $actions{$target} = $action;
283 =item C<Automake::Rule::reset>
285 The I<forget all> function. Clears all known rules and resets some
294 %_suffix_rules = %_suffix_rules_builtin;
310 # Installing/uninstalling.
311 'install-data-am' => [],
312 'install-exec-am' => [],
313 'uninstall-am' => [],
316 'uninstall-man' => [],
319 'install-dvi-am' => [],
320 'install-html' => [],
321 'install-html-am' => [],
322 'install-info' => [],
323 'install-info-am' => [],
325 'install-pdf-am' => [],
327 'install-ps-am' => [],
329 'installcheck-am' => [],
333 'mostlyclean-am' => [],
334 'maintainer-clean-am' => [],
335 'distclean-am' => [],
338 'maintainer-clean' => [],
346 # Recursive install targets (so "make -n install" works for BSD Make).
352 =item C<next_in_suffix_chain ($ext1, $ext2)>
354 Return the target suffix for the next rule to use to reach C<$ext2>
355 from C<$ext1>, or C<undef> if no such rule exists.
359 sub next_in_suffix_chain
($$)
361 my ($ext1, $ext2) = @_;
362 return undef unless (exists $_suffix_rules{$ext1} and
363 exists $_suffix_rules{$ext1}{$ext2});
364 return $_suffix_rules{$ext1}{$ext2}[0];
367 =item C<register_suffix_rule ($where, $src, $dest)>
369 Register a suffix rule defined on C<$where> that transforms
370 files ending in C<$src> into files ending in C<$dest>.
374 sub register_suffix_rule
($$$)
376 my ($where, $src, $dest) = @_;
377 my $suffix_rules = $where->{'position'} ? \
%_suffix_rules
378 : \
%_suffix_rules_builtin;
380 verb
"Sources ending in $src become $dest";
381 push @_suffixes, $src, $dest;
383 # When transforming sources to objects, Automake uses the
384 # %suffix_rules to move from each source extension to
385 # '.$(OBJEXT)', not to '.o' or '.obj'. However some people
386 # define suffix rules for '.o' or '.obj', so internally we will
387 # consider these extensions equivalent to '.$(OBJEXT)'. We
388 # CANNOT rewrite the target (i.e., automagically replace '.o'
389 # and '.obj' by '.$(OBJEXT)' in the output), or warn the user
390 # that (s)he'd better use '.$(OBJEXT)', because Automake itself
391 # output suffix rules for '.o' or '.obj' ...
392 $dest = '.$(OBJEXT)' if ($dest eq '.o' || $dest eq '.obj');
394 # ----------------------------------------------------------------------
395 # The $suffix_rules variable maps the source extension for all suffix
396 # rules seen to a hash whose keys are the possible output extensions.
398 # Note that this is transitively closed by construction:
401 # exists $suffix_rules{$ext1}{$ext2}
402 # && exists $suffix_rules{$ext2}{$ext3}
406 # exists $suffix_rules{$ext1}{$ext3}
408 # So it's easy to check whether '.foo' can be transformed to
409 # '.$(OBJEXT)' by checking whether $suffix_rules{'.foo'}{'.$(OBJEXT)'}
410 # exists. This will work even if transforming '.foo' to '.$(OBJEXT)'
411 # involves a chain of several suffix rules.
413 # The value of $suffix_rules{$ext1}{$ext2} is a pair [$next_sfx, $dist]
414 # where $next_sfx is target suffix for the next rule to use to reach
415 # $ext2, and $dist the distance to $ext2.
416 # ----------------------------------------------------------------------
418 # Register $dest as a possible destination from $src.
419 # We might have the create the \hash.
420 if (exists $suffix_rules->{$src})
422 $suffix_rules->{$src}{$dest} = [ $dest, 1 ];
426 $suffix_rules->{$src} = { $dest => [ $dest, 1 ] };
429 # If we know how to transform $dest in something else, then
430 # we know how to transform $src in that "something else".
431 if (exists $suffix_rules->{$dest})
433 for my $dest2 (keys %{$suffix_rules->{$dest}})
435 my $dist = $suffix_rules->{$dest}{$dest2}[1] + 1;
436 # Overwrite an existing $src->$dest2 path only if
437 # the path via $dest which is shorter.
438 if (! exists $suffix_rules->{$src}{$dest2}
439 || $suffix_rules->{$src}{$dest2}[1] > $dist)
441 $suffix_rules->{$src}{$dest2} = [ $dest, $dist ];
446 # Similarly, any extension that can be derived into $src
447 # can be derived into the same extensions as $src can.
448 my @dest2 = keys %{$suffix_rules->{$src}};
449 for my $src2 (keys %$suffix_rules)
451 if (exists $suffix_rules->{$src2}{$src})
453 for my $dest2 (@dest2)
455 my $dist = $suffix_rules->{$src}{$dest2} + 1;
456 # Overwrite an existing $src2->$dest2 path only if
457 # the path via $src is shorter.
458 if (! exists $suffix_rules->{$src2}{$dest2}
459 || $suffix_rules->{$src2}{$dest2}[1] > $dist)
461 $suffix_rules->{$src2}{$dest2} = [ $src, $dist ];
468 =item C<@list = suffixes>
470 Return the list of known suffixes.
479 =item C<rule ($rulename)>
481 Return the C<Automake::Rule> object for the rule
482 named C<$rulename> if defined. Return 0 otherwise.
489 # Strip $(EXEEXT) from $name, so we can diagnose
490 # a clash if 'ctags$(EXEEXT):' is redefined after 'ctags:'.
491 $name =~ s
,\
$\
(EXEEXT\
)$,,;
492 return $_rule_dict{$name} || 0;
495 =item C<ruledef ($rulename, $cond)>
497 Return the C<Automake::RuleDef> object for the rule named
498 C<$rulename> if defined in condition C<$cond>. Return false
499 if the condition or the rule does not exist.
505 my ($name, $cond) = @_;
506 my $rule = rule
$name;
507 return $rule && $rule->def ($cond);
510 =item C<rrule ($rulename)
512 Return the C<Automake::Rule> object for the variable named
513 C<$rulename>. Abort with an internal error if the variable was not
516 The I<r> in front of C<var> stands for I<required>. One
517 should call C<rvar> to assert the rule's existence.
525 prog_error
("undefined rule $name\n" . &rules_dump
)
530 =item C<rruledef ($varname, $cond)>
532 Return the C<Automake::RuleDef> object for the rule named
533 C<$rulename> if defined in condition C<$cond>. Abort with an internal
534 error if the condition or the rule does not exist.
540 my ($name, $cond) = @_;
541 return rrule
($name)->rdef ($cond);
544 # Create the variable if it does not exist.
545 # This is used only by other functions in this package.
551 return _new Automake
::Rule
$name;
556 my ($class, $name) = @_;
558 # Strip $(EXEEXT) from $name, so we can diagnose
559 # a clash if 'ctags$(EXEEXT):' is redefined after 'ctags:'.
560 (my $keyname = $name) =~ s
,\
$\
(EXEEXT\
)$,,;
562 my $self = Automake
::Item
::new
($class, $name);
563 $_rule_dict{$keyname} = $self;
567 sub _rule_defn_with_exeext_awareness
($$$)
569 my ($target, $cond, $where) = @_;
571 # For now 'foo:' will override 'foo$(EXEEXT):'. This is temporary,
572 # though, so we emit a warning.
573 (my $noexe = $target) =~ s/\$\(EXEEXT\)$//;
574 my $noexerule = rule
$noexe;
575 my $tdef = $noexerule ?
$noexerule->def ($cond) : undef;
577 if ($noexe ne $target
579 && $noexerule->name ne $target)
581 # The no-exeext option enables this feature.
582 if (! option
'no-exeext')
584 msg
('obsolete', $tdef->location,
585 "deprecated feature: target '$noexe' overrides "
586 . "'$noexe\$(EXEEXT)'\n"
587 . "change your target to read '$noexe\$(EXEEXT)'",
589 msg
('obsolete', $where, "target '$target' was defined here");
595 sub _maybe_warn_about_duplicated_target
($$$$$$)
597 my ($target, $tdef, $source, $owner, $cond, $where) = @_;
599 my $oldowner = $tdef->owner;
600 # Ok, it's the name target, but the name maybe different because
601 # 'foo$(EXEEXT)' and 'foo' have the same key in our table.
602 my $oldname = $tdef->name;
604 # Don't mention true conditions in diagnostics.
606 $cond == TRUE ?
'' : (" in condition '" . $cond->human . "'");
608 if ($owner == RULE_USER
)
610 if ($oldowner == RULE_USER
)
612 # Ignore '%'-style pattern rules. We'd need the
613 # dependencies to detect duplicates, and they are
614 # already diagnosed as unportable by -Wportability.
615 if ($target !~ /^[^%]*%[^%]*$/)
617 ## FIXME: Presently we can't diagnose duplicate user rules
618 ## because we don't distinguish rules with commands
619 ## from rules that only add dependencies. E.g.,
622 ## is legitimate. This is checked in the 'phony.sh' test.
624 # msg ('syntax', $where,
625 # "redefinition of '$target'$condmsg ...", partial => 1);
626 # msg_cond_rule ('syntax', $cond, $target,
627 # "... '$target' previously defined here");
632 # Since we parse the user Makefile.am before reading
633 # the Automake fragments, this condition should never happen.
634 prog_error
("user target '$target'$condmsg seen after Automake's"
635 . " definition\nfrom " . $tdef->source);
638 else # $owner == RULE_AUTOMAKE
640 if ($oldowner == RULE_USER
)
642 # -am targets listed in %dependencies support a -local
643 # variant. If the user tries to override TARGET or
644 # TARGET-am for which there exists a -local variant,
645 # just tell the user to use it.
649 if (exists $dependencies{"$noam-am"})
651 $hint = "consider using $noam-local instead of $target";
654 msg_cond_rule
('override', $cond, $target,
655 "user target '$target' defined here"
656 . "$condmsg ...", partial
=> 1);
657 msg
('override', $where,
658 "... overrides Automake target '$oldname' defined here",
660 msg_cond_rule
('override', $cond, $target, $hint)
663 else # $oldowner == RULE_AUTOMAKE
665 # Automake should ignore redefinitions of its own
666 # rules if they came from the same file. This makes
667 # it easier to process a Makefile fragment several times.
668 # However it's an error if the target is defined in many
669 # files. E.g., the user might be using bin_PROGRAMS = ctags
670 # which clashes with our 'ctags' rule.
671 # (It would be more accurate if we had a way to compare
672 # the *content* of both rules. Then $targets_source would
674 my $oldsource = $tdef->source;
675 if (not ($source eq $oldsource && $target eq $oldname))
678 $where, "redefinition of '$target'$condmsg ...",
680 msg_cond_rule
('syntax', $cond, $target,
681 "... '$oldname' previously defined here");
687 # Return the list of conditionals in which the rule was defined. In case
688 # an ambiguous conditional definition is detected, return the empty list.
689 sub _conditionals_for_rule
($$$$)
691 my ($rule, $owner, $cond, $where) = @_;
692 my $target = $rule->name;
694 my ($message, $ambig_cond) = $rule->conditions->ambiguous_p ($target, $cond);
696 return $cond if !$message; # No ambiguity.
698 # Don't coalesce the several pattern rules from footer.am into a single one.
699 return $cond if $target eq "%:" && $where->get =~ /\/am\
/footer\.am$/;
701 if ($owner == RULE_USER
)
703 # For user rules, just diagnose the ambiguity.
704 msg
'syntax', $where, "$message ...", partial
=> 1;
705 msg_cond_rule
('syntax', $ambig_cond, $target,
706 "... '$target' previously defined here");
710 # FIXME: for Automake rules, we can't diagnose ambiguities yet.
711 # The point is that Automake doesn't propagate conditions
712 # everywhere. For instance &handle_PROGRAMS doesn't care if
713 # bin_PROGRAMS was defined conditionally or not.
714 # On the following input
721 # &handle_PROGRAMS will attempt to define a 'foo:' rule
722 # in condition TRUE (which conflicts with COND1). Fixing
723 # this in &handle_PROGRAMS and siblings seems hard: you'd
724 # have to explain &file_contents what to do with a
725 # condition. So for now we do our best *here*. If 'foo:'
726 # was already defined in condition COND1 and we want to define
727 # it in condition TRUE, then define it only in condition !COND1.
728 # (See cond14.sh and cond15.sh for some test cases.)
729 @conds = $rule->not_always_defined_in_cond ($cond)->conds;
731 # No conditions left to define the rule.
732 # Warn, because our workaround is meaningless in this case.
733 if (scalar @conds == 0)
735 msg
'syntax', $where, "$message ...", partial
=> 1;
736 msg_cond_rule
('syntax', $ambig_cond, $target,
737 "... '$target' previously defined here");
743 =item C<@conds = define ($rulename, $source, $owner, $cond, $where)>
745 Define a new rule. C<$rulename> is the list of targets. C<$source>
746 is the filename the rule comes from. C<$owner> is the owner of the
747 rule (C<RULE_AUTOMAKE> or C<RULE_USER>). C<$cond> is the
748 C<Automake::Condition> under which the rule is defined. C<$where> is
749 the C<Automake::Location> where the rule is defined.
751 Returns a (possibly empty) list of C<Automake::Condition>s where the
752 rule's definition should be output.
758 my ($target, $source, $owner, $cond, $where) = @_;
760 prog_error
"$where is not a reference"
762 prog_error
"$cond is not a reference"
765 # Don't even think about defining a rule in condition FALSE.
766 return () if $cond == FALSE
;
768 my $tdef = _rule_defn_with_exeext_awareness
($target, $cond, $where);
770 # The pattern rules in footer.am look like duplicates, but really aren't.
771 if ($source !~ /\/am\
/footer\.am$/)
773 # A GNU make-style pattern rule has a single "%" in the target name.
774 msg
('portability', $where,
775 "'%'-style pattern rules are a GNU make extension")
776 if $target =~ /^[^%]*%[^%]*$/;
778 # See whether this is a duplicated target declaration.
781 # Diagnose invalid target redefinitions, if any. Note that some
782 # target redefinitions are valid (e.g., for multiple-targets
784 _maybe_warn_about_duplicated_target
($target, $tdef, $source,
785 $owner, $cond, $where);
786 # Return so we don't redefine the rule in our tables, don't check
787 # for ambiguous condition, etc. The rule will be output anyway
788 # because '&read_am_file' ignores the return code.
793 my $rule = _crule
$target;
795 # Conditions for which the rule should be defined. Due to some
796 # complications in the automake internals, this aspect is not as
797 # obvious as it might be, and in come cases this list must contain
798 # other entries in addition to '$cond'. See the comments in
799 # '_conditionals_for_rule' for a rationale.
800 my @conds = _conditionals_for_rule
($rule, $owner, $cond, $where);
802 # Stop if we had ambiguous conditional definitions.
803 return unless @conds;
805 # Finally define this rule.
808 my $def = new Automake
::RuleDef
($target, '', $where->clone,
810 $rule->set ($c, $def);
813 # We honor inference rules with multiple targets because many
814 # makes support this and people use it. However this is disallowed
815 # by POSIX. We'll print a warning later.
816 my $target_count = 0;
817 my $inference_rule_count = 0;
819 for my $t (split (' ', $target))
822 # Check if the rule is a suffix rule: either it's a rule for
823 # two known extensions...
824 if ($t =~ /^($KNOWN_EXTENSIONS_PATTERN)($KNOWN_EXTENSIONS_PATTERN)$/
825 # ...or it's a rule with unknown extensions (i.e., the rule
826 # looks like '.foo.bar:' but '.foo' or '.bar' are not
827 # declared in SUFFIXES and are not known language
828 # extensions). Automake will complete SUFFIXES from
829 # @suffixes automatically (see handle_footer).
830 || ($t =~ /$_SUFFIX_RULE_PATTERN/o && accept_extensions
($1)))
832 ++$inference_rule_count;
833 register_suffix_rule
($where, $1, $2);
837 # POSIX allows multiple targets before the colon, but disallows
838 # definitions of multiple inference rules. It's also
839 # disallowed to mix plain targets with inference rules.
840 msg
('portability', $where,
841 "inference rules can have only one target before the colon (POSIX)")
842 if $inference_rule_count > 0 && $target_count > 1;
847 =item C<depend ($target, @deps)>
849 Adds C<@deps> to the dependencies of target C<$target>. This should
850 be used only with factored targets (those appearing in
857 my ($category, @dependees) = @_;
858 push (@
{$dependencies{$category}}, @dependees);
865 L<Automake::RuleDef>, L<Automake::Condition>,
866 L<Automake::DisjConditions>, L<Automake::Location>.