1 # Copyright (C) 2003-2013 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 <http://www.gnu.org/licenses/>.
16 package Automake::Rule;
23 use Automake::RuleDef;
24 use Automake::ChannelDefs;
25 use Automake::Channels;
26 use Automake::Options;
27 use Automake::Condition qw (TRUE FALSE);
28 use Automake::DisjConditions;
30 use vars '@ISA', '@EXPORT', '@EXPORT_OK';
31 @ISA = qw/Automake::Item Exporter/;
32 @EXPORT = qw (reset register_suffix_rule suffix_rules_count suffix_rule
33 suffixes rules $KNOWN_EXTENSIONS_PATTERN
34 depend %dependencies %actions register_action
36 reject_rule msg_rule msg_cond_rule err_rule err_cond_rule
37 rule rrule ruledef rruledef);
41 Automake::Rule - support for rules definitions
46 use Automake::RuleDef;
51 This package provides support for Makefile rule definitions.
53 An C<Automake::Rule> is a rule name associated to possibly
54 many conditional definitions. These definitions are instances
55 of C<Automake::RuleDef>.
57 Therefore obtaining the value of a rule under a given
58 condition involves two lookups. One to look up the rule,
59 and one to look up the conditional definition:
61 my $rule = rule $name;
64 my $def = $rule->def ($cond);
67 return $def->location;
73 when it is known that the rule and the definition
74 being looked up exist, the above can be simplified to
76 return rule ($name)->def ($cond)->location; # do not write this.
80 return rrule ($name)->rdef ($cond)->location;
84 return rruledef ($name, $cond)->location;
86 The I<r> variants of the C<rule>, C<def>, and C<ruledef> methods add
87 an extra test to ensure that the lookup succeeded, and will diagnose
88 failures as internal errors (with a message which is much more
89 informative than Perl's warning about calling a method on a
92 =head2 Global variables
98 my $_SUFFIX_RULE_PATTERN =
99 '^(\.[a-zA-Z0-9_(){}$+@\-]+)(\.[a-zA-Z0-9_(){}$+@\-]+)' . "\$";
101 # Suffixes found during a run.
102 use vars '@_suffixes';
104 =item C<%dependencies>
106 Holds the dependencies of targets which dependencies are factored.
107 Typically, C<.PHONY> will appear in plenty of F<*.am> files, but must
108 be output once. Arguably all pure dependencies could be subject to
109 this factoring, but it is not unpleasant to have paragraphs in
110 Makefile: keeping related stuff altogether.
114 use vars '%dependencies';
118 Holds the factored actions. Tied to C<%dependencies>, i.e., filled
119 only when keys exists in C<%dependencies>.
125 =item <$suffix_rules>
127 This maps the source extension for all suffix rules seen to
128 a C<hash> whose keys are the possible output extensions.
130 Note that this is transitively closed by construction:
132 exists $suffix_rules{$ext1}{$ext2}
133 && exists $suffix_rules{$ext2}{$ext3}
135 exists $suffix_rules{$ext1}{$ext3}
137 So it's easy to check whether C<.foo> can be transformed to
138 C<.$(OBJEXT)> by checking whether
139 C<$suffix_rules{'.foo'}{'.$(OBJEXT)'}> exists. This will work even if
140 transforming C<.foo> to C<.$(OBJEXT)> involves a chain of several
143 The value of C<$suffix_rules{$ext1}{$ext2}> is a pair
144 C<[ $next_sfx, $dist ]> where C<$next_sfx> is target suffix
145 for the next rule to use to reach C<$ext2>, and C<$dist> the
146 distance to C<$ext2'>.
148 The content of this variable should be updated via the
149 C<register_suffix_rule> function.
155 # Same as $suffix_rules, but records only the default rules
156 # supplied by the languages Automake supports.
157 my %suffix_rules_builtin;
159 =item C<$KNOWN_EXTENSIONS_PATTERN>
161 Pattern that matches all know input extensions (i.e. extensions used
162 by the languages supported by Automake). Using this pattern (instead
163 of '\..*$') to match extensions allows Automake to support dot-less
166 New extensions should be registered with C<accept_extensions>.
170 use vars qw ($KNOWN_EXTENSIONS_PATTERN @_known_extensions_list);
171 $KNOWN_EXTENSIONS_PATTERN = "";
172 @_known_extensions_list = ();
176 =head2 Error reporting functions
178 In these functions, C<$rule> can be either a rule name, or
179 an instance of C<Automake::Rule>.
183 =item C<err_rule ($rule, $message, [%options])>
185 Uncategorized errors about rules.
191 msg_rule ('error', @_);
194 =item C<err_cond_rule ($cond, $rule, $message, [%options])>
196 Uncategorized errors about conditional rules.
200 sub err_cond_rule ($$$;%)
202 msg_cond_rule ('error', @_);
205 =item C<msg_cond_rule ($channel, $cond, $rule, $message, [%options])>
207 Messages about conditional rules.
211 sub msg_cond_rule ($$$$;%)
213 my ($channel, $cond, $rule, $msg, %opts) = @_;
214 my $r = ref ($rule) ? $rule : rrule ($rule);
215 msg $channel, $r->rdef ($cond)->location, $msg, %opts;
218 =item C<msg_rule ($channel, $targetname, $message, [%options])>
220 Messages about rules.
226 my ($channel, $rule, $msg, %opts) = @_;
227 my $r = ref ($rule) ? $rule : rrule ($rule);
228 # Don't know which condition is concerned. Pick any.
229 my $cond = $r->conditions->one_cond;
230 msg_cond_rule ($channel, $cond, $r, $msg, %opts);
234 =item C<$bool = reject_rule ($rule, $error_msg)>
236 Bail out with C<$error_msg> if a rule with name C<$rule> has been
239 Return true iff C<$rule> is defined.
245 my ($rule, $msg) = @_;
248 err_rule $rule, $msg;
256 =head2 Administrative functions
260 =item C<accept_extensions (@exts)>
262 Update C<$KNOWN_EXTENSIONS_PATTERN> to recognize the extensions
263 listed in C<@exts>. Extensions should contain a dot if needed.
267 sub accept_extensions (@)
269 push @_known_extensions_list, @_;
270 $KNOWN_EXTENSIONS_PATTERN =
271 '(?:' . join ('|', map (quotemeta, @_known_extensions_list)) . ')';
276 Return the list of all L<Automake::Rule> instances. (I.e., all
277 rules defined so far.)
281 use vars '%_rule_dict';
284 return values %_rule_dict;
288 =item C<register_action($target, $action)>
290 Append the C<$action> to C<$actions{$target}> taking care of special
295 sub register_action ($$)
297 my ($target, $action) = @_;
298 if ($actions{$target})
300 $actions{$target} .= "\n$action" if $action;
304 $actions{$target} = $action;
309 =item C<Automake::Rule::reset>
311 The I<forget all> function. Clears all known rules and resets some
320 %suffix_rules = %suffix_rules_builtin;
336 # Installing/uninstalling.
337 'install-data-am' => [],
338 'install-exec-am' => [],
339 'uninstall-am' => [],
342 'uninstall-man' => [],
345 'install-dvi-am' => [],
346 'install-html' => [],
347 'install-html-am' => [],
348 'install-info' => [],
349 'install-info-am' => [],
351 'install-pdf-am' => [],
353 'install-ps-am' => [],
355 'installcheck-am' => [],
359 'mostlyclean-am' => [],
360 'maintainer-clean-am' => [],
361 'distclean-am' => [],
364 'maintainer-clean' => [],
372 # Recursive install targets (so "make -n install" works for BSD Make).
378 =item C<suffix_rule ($ext, $obj)>
386 my ($source_ext, $obj) = @_;
387 return undef unless (exists $suffix_rules{$source_ext} and
388 exists $suffix_rules{$source_ext}{$obj});
389 return $suffix_rules{$source_ext}{$obj}[0];
392 =item C<register_suffix_rule ($where, $src, $dest)>
394 Register a suffix rule defined on C<$where> that transforms
395 files ending in C<$src> into files ending in C<$dest>.
397 This upgrades the C<$suffix_rules> variables.
401 sub register_suffix_rule ($$$)
403 my ($where, $src, $dest) = @_;
404 my $suffix_rules = $where->{'position'} ? \%suffix_rules
405 : \%suffix_rules_builtin;
407 verb "Sources ending in $src become $dest";
408 push @_suffixes, $src, $dest;
410 # When transforming sources to objects, Automake uses the
411 # %suffix_rules to move from each source extension to
412 # '.$(OBJEXT)', not to '.o' or '.obj'. However some people
413 # define suffix rules for '.o' or '.obj', so internally we will
414 # consider these extensions equivalent to '.$(OBJEXT)'. We
415 # CANNOT rewrite the target (i.e., automagically replace '.o'
416 # and '.obj' by '.$(OBJEXT)' in the output), or warn the user
417 # that (s)he'd better use '.$(OBJEXT)', because Automake itself
418 # output suffix rules for '.o' or '.obj' ...
419 $dest = '.$(OBJEXT)' if ($dest eq '.o' || $dest eq '.obj');
421 # Reading the comments near the declaration of $suffix_rules might
422 # help to understand the update of $suffix_rules that follows ...
424 # Register $dest as a possible destination from $src.
425 # We might have the create the \hash.
426 if (exists $suffix_rules->{$src})
428 $suffix_rules->{$src}{$dest} = [ $dest, 1 ];
432 $suffix_rules->{$src} = { $dest => [ $dest, 1 ] };
435 # If we know how to transform $dest in something else, then
436 # we know how to transform $src in that "something else".
437 if (exists $suffix_rules->{$dest})
439 for my $dest2 (keys %{$suffix_rules->{$dest}})
441 my $dist = $suffix_rules->{$dest}{$dest2}[1] + 1;
442 # Overwrite an existing $src->$dest2 path only if
443 # the path via $dest which is shorter.
444 if (! exists $suffix_rules->{$src}{$dest2}
445 || $suffix_rules->{$src}{$dest2}[1] > $dist)
447 $suffix_rules->{$src}{$dest2} = [ $dest, $dist ];
452 # Similarly, any extension that can be derived into $src
453 # can be derived into the same extensions as $src can.
454 my @dest2 = keys %{$suffix_rules->{$src}};
455 for my $src2 (keys %$suffix_rules)
457 if (exists $suffix_rules->{$src2}{$src})
459 for my $dest2 (@dest2)
461 my $dist = $suffix_rules->{$src}{$dest2} + 1;
462 # Overwrite an existing $src2->$dest2 path only if
463 # the path via $src is shorter.
464 if (! exists $suffix_rules->{$src2}{$dest2}
465 || $suffix_rules->{$src2}{$dest2}[1] > $dist)
467 $suffix_rules->{$src2}{$dest2} = [ $src, $dist ];
474 =item C<$count = suffix_rules_count>
476 Return the number of suffix rules added while processing the current
477 F<Makefile> (excluding predefined suffix rules).
481 sub suffix_rules_count ()
483 return (scalar keys %suffix_rules) - (scalar keys %suffix_rules_builtin);
486 =item C<@list = suffixes>
488 Return the list of known suffixes.
497 =item C<rule ($rulename)>
499 Return the C<Automake::Rule> object for the rule
500 named C<$rulename> if defined. Return 0 otherwise.
507 # Strip $(EXEEXT) from $name, so we can diagnose
508 # a clash if 'ctags$(EXEEXT):' is redefined after 'ctags:'.
509 $name =~ s,\$\(EXEEXT\)$,,;
510 return $_rule_dict{$name} || 0;
513 =item C<ruledef ($rulename, $cond)>
515 Return the C<Automake::RuleDef> object for the rule named
516 C<$rulename> if defined in condition C<$cond>. Return false
517 if the condition or the rule does not exist.
523 my ($name, $cond) = @_;
524 my $rule = rule $name;
525 return $rule && $rule->def ($cond);
528 =item C<rrule ($rulename)
530 Return the C<Automake::Rule> object for the variable named
531 C<$rulename>. Abort with an internal error if the variable was not
534 The I<r> in front of C<var> stands for I<required>. One
535 should call C<rvar> to assert the rule's existence.
543 prog_error ("undefined rule $name\n" . &rules_dump)
548 =item C<rruledef ($varname, $cond)>
550 Return the C<Automake::RuleDef> object for the rule named
551 C<$rulename> if defined in condition C<$cond>. Abort with an internal
552 error if the condition or the rule does not exist.
558 my ($name, $cond) = @_;
559 return rrule ($name)->rdef ($cond);
562 # Create the variable if it does not exist.
563 # This is used only by other functions in this package.
569 return _new Automake::Rule $name;
574 my ($class, $name) = @_;
576 # Strip $(EXEEXT) from $name, so we can diagnose
577 # a clash if 'ctags$(EXEEXT):' is redefined after 'ctags:'.
578 (my $keyname = $name) =~ s,\$\(EXEEXT\)$,,;
580 my $self = Automake::Item::new ($class, $name);
581 $_rule_dict{$keyname} = $self;
585 sub _rule_defn_with_exeext_awareness ($$$)
587 my ($target, $cond, $where) = @_;
589 # For now 'foo:' will override 'foo$(EXEEXT):'. This is temporary,
590 # though, so we emit a warning.
591 (my $noexe = $target) =~ s/\$\(EXEEXT\)$//;
592 my $noexerule = rule $noexe;
593 my $tdef = $noexerule ? $noexerule->def ($cond) : undef;
595 if ($noexe ne $target
597 && $noexerule->name ne $target)
599 # The no-exeext option enables this feature.
600 if (! option 'no-exeext')
602 msg ('obsolete', $tdef->location,
603 "deprecated feature: target '$noexe' overrides "
604 . "'$noexe\$(EXEEXT)'\n"
605 . "change your target to read '$noexe\$(EXEEXT)'",
607 msg ('obsolete', $where, "target '$target' was defined here");
613 sub _maybe_warn_about_duplicated_target ($$$$$$)
615 my ($target, $tdef, $source, $owner, $cond, $where) = @_;
617 my $oldowner = $tdef->owner;
618 # Ok, it's the name target, but the name maybe different because
619 # 'foo$(EXEEXT)' and 'foo' have the same key in our table.
620 my $oldname = $tdef->name;
622 # Don't mention true conditions in diagnostics.
624 $cond == TRUE ? '' : (" in condition '" . $cond->human . "'");
626 if ($owner == RULE_USER)
628 if ($oldowner == RULE_USER)
630 # Ignore '%'-style pattern rules. We'd need the
631 # dependencies to detect duplicates, and they are
632 # already diagnosed as unportable by -Wportability.
633 if ($target !~ /^[^%]*%[^%]*$/)
635 ## FIXME: Presently we can't diagnose duplicate user rules
636 ## because we don't distinguish rules with commands
637 ## from rules that only add dependencies. E.g.,
640 ## is legitimate. (This is phony.test.)
642 # msg ('syntax', $where,
643 # "redefinition of '$target'$condmsg ...", partial => 1);
644 # msg_cond_rule ('syntax', $cond, $target,
645 # "... '$target' previously defined here");
650 # Since we parse the user Makefile.am before reading
651 # the Automake fragments, this condition should never happen.
652 prog_error ("user target '$target'$condmsg seen after Automake's"
653 . " definition\nfrom " . $tdef->source);
656 else # $owner == RULE_AUTOMAKE
658 if ($oldowner == RULE_USER)
660 # -am targets listed in %dependencies support a -local
661 # variant. If the user tries to override TARGET or
662 # TARGET-am for which there exists a -local variant,
663 # just tell the user to use it.
667 if (exists $dependencies{"$noam-am"})
669 $hint = "consider using $noam-local instead of $target";
672 msg_cond_rule ('override', $cond, $target,
673 "user target '$target' defined here"
674 . "$condmsg ...", partial => 1);
675 msg ('override', $where,
676 "... overrides Automake target '$oldname' defined here",
678 msg_cond_rule ('override', $cond, $target, $hint)
681 else # $oldowner == RULE_AUTOMAKE
683 # Automake should ignore redefinitions of its own
684 # rules if they came from the same file. This makes
685 # it easier to process a Makefile fragment several times.
686 # However it's an error if the target is defined in many
687 # files. E.g., the user might be using bin_PROGRAMS = ctags
688 # which clashes with our 'ctags' rule.
689 # (It would be more accurate if we had a way to compare
690 # the *content* of both rules. Then $targets_source would
692 my $oldsource = $tdef->source;
693 if (not ($source eq $oldsource && $target eq $oldname))
696 $where, "redefinition of '$target'$condmsg ...",
698 msg_cond_rule ('syntax', $cond, $target,
699 "... '$oldname' previously defined here");
705 # Return the list of conditionals in which the rule was defined. In case
706 # an ambiguous conditional definition is detected, return the empty list.
707 sub _conditionals_for_rule ($$$$)
709 my ($rule, $owner, $cond, $where) = @_;
710 my $target = $rule->name;
712 my ($message, $ambig_cond) = $rule->conditions->ambiguous_p ($target, $cond);
714 return $cond if !$message; # No ambiguity.
716 if ($owner == RULE_USER)
718 # For user rules, just diagnose the ambiguity.
719 msg 'syntax', $where, "$message ...", partial => 1;
720 msg_cond_rule ('syntax', $ambig_cond, $target,
721 "... '$target' previously defined here");
725 # FIXME: for Automake rules, we can't diagnose ambiguities yet.
726 # The point is that Automake doesn't propagate conditions
727 # everywhere. For instance &handle_PROGRAMS doesn't care if
728 # bin_PROGRAMS was defined conditionally or not.
729 # On the following input
736 # &handle_PROGRAMS will attempt to define a 'foo:' rule
737 # in condition TRUE (which conflicts with COND1). Fixing
738 # this in &handle_PROGRAMS and siblings seems hard: you'd
739 # have to explain &file_contents what to do with a
740 # condition. So for now we do our best *here*. If 'foo:'
741 # was already defined in condition COND1 and we want to define
742 # it in condition TRUE, then define it only in condition !COND1.
743 # (See cond14.test and cond15.test for some test cases.)
744 @conds = $rule->not_always_defined_in_cond ($cond)->conds;
746 # No conditions left to define the rule.
747 # Warn, because our workaround is meaningless in this case.
748 if (scalar @conds == 0)
750 msg 'syntax', $where, "$message ...", partial => 1;
751 msg_cond_rule ('syntax', $ambig_cond, $target,
752 "... '$target' previously defined here");
758 =item C<@conds = define ($rulename, $source, $owner, $cond, $where)>
760 Define a new rule. C<$rulename> is the list of targets. C<$source>
761 is the filename the rule comes from. C<$owner> is the owner of the
762 rule (C<RULE_AUTOMAKE> or C<RULE_USER>). C<$cond> is the
763 C<Automake::Condition> under which the rule is defined. C<$where> is
764 the C<Automake::Location> where the rule is defined.
766 Returns a (possibly empty) list of C<Automake::Condition>s where the
767 rule's definition should be output.
773 my ($target, $source, $owner, $cond, $where) = @_;
775 prog_error "$where is not a reference"
777 prog_error "$cond is not a reference"
780 # Don't even think about defining a rule in condition FALSE.
781 return () if $cond == FALSE;
783 my $tdef = _rule_defn_with_exeext_awareness ($target, $cond, $where);
785 # A GNU make-style pattern rule has a single "%" in the target name.
786 msg ('portability', $where,
787 "'%'-style pattern rules are a GNU make extension")
788 if $target =~ /^[^%]*%[^%]*$/;
790 # See whether this is a duplicated target declaration.
793 # Diagnose invalid target redefinitions, if any. Note that some
794 # target redefinitions are valid (e.g., for multiple-targets
796 _maybe_warn_about_duplicated_target ($target, $tdef, $source,
797 $owner, $cond, $where);
798 # Return so we don't redefine the rule in our tables, don't check
799 # for ambiguous condition, etc. The rule will be output anyway
800 # because '&read_am_file' ignores the return code.
804 my $rule = _crule $target;
806 # Conditions for which the rule should be defined. Due to some
807 # complications in the automake internals, this aspect is not as
808 # obvious as it might be, and in come cases this list must contain
809 # other entries in addition to '$cond'. See the comments in
810 # '_conditionals_for_rule' for a rationale.
811 my @conds = _conditionals_for_rule ($rule, $owner, $cond, $where);
813 # Stop if we had ambiguous conditional definitions.
814 return unless @conds;
816 # Finally define this rule.
819 my $def = new Automake::RuleDef ($target, '', $where->clone,
821 $rule->set ($c, $def);
824 # We honor inference rules with multiple targets because many
825 # makes support this and people use it. However this is disallowed
826 # by POSIX. We'll print a warning later.
827 my $target_count = 0;
828 my $inference_rule_count = 0;
830 for my $t (split (' ', $target))
833 # Check if the rule is a suffix rule: either it's a rule for
834 # two known extensions...
835 if ($t =~ /^($KNOWN_EXTENSIONS_PATTERN)($KNOWN_EXTENSIONS_PATTERN)$/
836 # ...or it's a rule with unknown extensions (i.e., the rule
837 # looks like '.foo.bar:' but '.foo' or '.bar' are not
838 # declared in SUFFIXES and are not known language
839 # extensions). Automake will complete SUFFIXES from
840 # @suffixes automatically (see handle_footer).
841 || ($t =~ /$_SUFFIX_RULE_PATTERN/o && accept_extensions($1)))
843 ++$inference_rule_count;
844 register_suffix_rule ($where, $1, $2);
848 # POSIX allows multiple targets before the colon, but disallows
849 # definitions of multiple inference rules. It's also
850 # disallowed to mix plain targets with inference rules.
851 msg ('portability', $where,
852 "inference rules can have only one target before the colon (POSIX)")
853 if $inference_rule_count > 0 && $target_count > 1;
858 =item C<depend ($target, @deps)>
860 Adds C<@deps> to the dependencies of target C<$target>. This should
861 be used only with factored targets (those appearing in
868 my ($category, @dependees) = @_;
869 push (@{$dependencies{$category}}, @dependees);
876 L<Automake::RuleDef>, L<Automake::Condition>,
877 L<Automake::DisjConditions>, L<Automake::Location>.
883 ### Setup "GNU" style for perl-mode and cperl-mode.
885 ## perl-indent-level: 2
886 ## perl-continued-statement-offset: 2
887 ## perl-continued-brace-offset: 0
888 ## perl-brace-offset: 0
889 ## perl-brace-imaginary-offset: 0
890 ## perl-label-offset: -2
891 ## cperl-indent-level: 2
892 ## cperl-brace-offset: 0
893 ## cperl-continued-brace-offset: 0
894 ## cperl-label-offset: -2
895 ## cperl-extra-newline-before-brace: t
896 ## cperl-merge-trailing-else: nil
897 ## cperl-continued-statement-offset: 2