1 # Copyright (C) 2003-2012 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
33 suffixes rules
$suffix_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 # Same as $suffix_rules (declared below), but records only the
105 # default rules supplied by the languages Automake supports.
106 use vars
'$_suffix_rules_default';
108 =item C<%dependencies>
110 Holds the dependencies of targets which dependencies are factored.
111 Typically, C<.PHONY> will appear in plenty of F<*.am> files, but must
112 be output once. Arguably all pure dependencies could be subject to
113 this factoring, but it is not unpleasant to have paragraphs in
114 Makefile: keeping related stuff altogether.
118 use vars
'%dependencies';
122 Holds the factored actions. Tied to C<%dependencies>, i.e., filled
123 only when keys exists in C<%dependencies>.
129 =item <$suffix_rules>
131 This maps the source extension for all suffix rules seen to
132 a C<hash> whose keys are the possible output extensions.
134 Note that this is transitively closed by construction:
136 exists $suffix_rules{$ext1}{$ext2}
137 && exists $suffix_rules{$ext2}{$ext3}
139 exists $suffix_rules{$ext1}{$ext3}
141 So it's easy to check whether C<.foo> can be transformed to
142 C<.$(OBJEXT)> by checking whether
143 C<$suffix_rules{'.foo'}{'.$(OBJEXT)'}> exists. This will work even if
144 transforming C<.foo> to C<.$(OBJEXT)> involves a chain of several
147 The value of C<$suffix_rules{$ext1}{$ext2}> is a pair
148 C<[ $next_sfx, $dist ]> where C<$next_sfx> is target suffix
149 for the next rule to use to reach C<$ext2>, and C<$dist> the
150 distance to C<$ext2'>.
152 The content of this variable should be updated via the
153 C<register_suffix_rule> function.
157 use vars
'$suffix_rules';
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 # The first time we initialize the variables,
321 # we save the value of $suffix_rules.
322 if (defined $_suffix_rules_default)
324 $suffix_rules = $_suffix_rules_default;
328 $_suffix_rules_default = $suffix_rules;
345 # Installing/uninstalling.
346 'install-data-am' => [],
347 'install-exec-am' => [],
348 'uninstall-am' => [],
351 'uninstall-man' => [],
354 'install-dvi-am' => [],
355 'install-html' => [],
356 'install-html-am' => [],
357 'install-info' => [],
358 'install-info-am' => [],
360 'install-pdf-am' => [],
362 'install-ps-am' => [],
364 'installcheck-am' => [],
368 'mostlyclean-am' => [],
369 'maintainer-clean-am' => [],
370 'distclean-am' => [],
373 'maintainer-clean' => [],
381 # Recursive install targets (so "make -n install" works for BSD Make).
387 =item C<register_suffix_rule ($where, $src, $dest)>
389 Register a suffix rule defined on C<$where> that transforms
390 files ending in C<$src> into files ending in C<$dest>.
392 This upgrades the C<$suffix_rules> variables.
396 sub register_suffix_rule
($$$)
398 my ($where, $src, $dest) = @_;
400 verb
"Sources ending in $src become $dest";
401 push @_suffixes, $src, $dest;
403 # When transforming sources to objects, Automake uses the
404 # %suffix_rules to move from each source extension to
405 # '.$(OBJEXT)', not to '.o' or '.obj'. However some people
406 # define suffix rules for '.o' or '.obj', so internally we will
407 # consider these extensions equivalent to '.$(OBJEXT)'. We
408 # CANNOT rewrite the target (i.e., automagically replace '.o'
409 # and '.obj' by '.$(OBJEXT)' in the output), or warn the user
410 # that (s)he'd better use '.$(OBJEXT)', because Automake itself
411 # output suffix rules for '.o' or '.obj' ...
412 $dest = '.$(OBJEXT)' if ($dest eq '.o' || $dest eq '.obj');
414 # Reading the comments near the declaration of $suffix_rules might
415 # help to understand the update of $suffix_rules that follows ...
417 # Register $dest as a possible destination from $src.
418 # We might have the create the \hash.
419 if (exists $suffix_rules->{$src})
421 $suffix_rules->{$src}{$dest} = [ $dest, 1 ];
425 $suffix_rules->{$src} = { $dest => [ $dest, 1 ] };
428 # If we know how to transform $dest in something else, then
429 # we know how to transform $src in that "something else".
430 if (exists $suffix_rules->{$dest})
432 for my $dest2 (keys %{$suffix_rules->{$dest}})
434 my $dist = $suffix_rules->{$dest}{$dest2}[1] + 1;
435 # Overwrite an existing $src->$dest2 path only if
436 # the path via $dest which is shorter.
437 if (! exists $suffix_rules->{$src}{$dest2}
438 || $suffix_rules->{$src}{$dest2}[1] > $dist)
440 $suffix_rules->{$src}{$dest2} = [ $dest, $dist ];
445 # Similarly, any extension that can be derived into $src
446 # can be derived into the same extensions as $src can.
447 my @dest2 = keys %{$suffix_rules->{$src}};
448 for my $src2 (keys %$suffix_rules)
450 if (exists $suffix_rules->{$src2}{$src})
452 for my $dest2 (@dest2)
454 my $dist = $suffix_rules->{$src}{$dest2} + 1;
455 # Overwrite an existing $src2->$dest2 path only if
456 # the path via $src is shorter.
457 if (! exists $suffix_rules->{$src2}{$dest2}
458 || $suffix_rules->{$src2}{$dest2}[1] > $dist)
460 $suffix_rules->{$src2}{$dest2} = [ $src, $dist ];
467 =item C<$count = suffix_rules_count>
469 Return the number of suffix rules added while processing the current
470 F<Makefile> (excluding predefined suffix rules).
474 sub suffix_rules_count
()
476 return (scalar keys %$suffix_rules) - (scalar keys %$_suffix_rules_default);
479 =item C<@list = suffixes>
481 Return the list of known suffixes.
490 =item C<rule ($rulename)>
492 Return the C<Automake::Rule> object for the rule
493 named C<$rulename> if defined. Return 0 otherwise.
500 # Strip $(EXEEXT) from $name, so we can diagnose
501 # a clash if 'ctags$(EXEEXT):' is redefined after 'ctags:'.
502 $name =~ s
,\
$\
(EXEEXT\
)$,,;
503 return $_rule_dict{$name} || 0;
506 =item C<ruledef ($rulename, $cond)>
508 Return the C<Automake::RuleDef> object for the rule named
509 C<$rulename> if defined in condition C<$cond>. Return false
510 if the condition or the rule does not exist.
516 my ($name, $cond) = @_;
517 my $rule = rule
$name;
518 return $rule && $rule->def ($cond);
521 =item C<rrule ($rulename)
523 Return the C<Automake::Rule> object for the variable named
524 C<$rulename>. Abort with an internal error if the variable was not
527 The I<r> in front of C<var> stands for I<required>. One
528 should call C<rvar> to assert the rule's existence.
536 prog_error
("undefined rule $name\n" . &rules_dump
)
541 =item C<rruledef ($varname, $cond)>
543 Return the C<Automake::RuleDef> object for the rule named
544 C<$rulename> if defined in condition C<$cond>. Abort with an internal
545 error if the condition or the rule does not exist.
551 my ($name, $cond) = @_;
552 return rrule
($name)->rdef ($cond);
555 # Create the variable if it does not exist.
556 # This is used only by other functions in this package.
562 return _new Automake
::Rule
$name;
567 my ($class, $name) = @_;
569 # Strip $(EXEEXT) from $name, so we can diagnose
570 # a clash if 'ctags$(EXEEXT):' is redefined after 'ctags:'.
571 (my $keyname = $name) =~ s
,\
$\
(EXEEXT\
)$,,;
573 my $self = Automake
::Item
::new
($class, $name);
574 $_rule_dict{$keyname} = $self;
578 sub _rule_defn_with_exeext_awareness
($$$)
580 my ($target, $cond, $where) = @_;
582 # For now 'foo:' will override 'foo$(EXEEXT):'. This is temporary,
583 # though, so we emit a warning.
584 (my $noexe = $target) =~ s/\$\(EXEEXT\)$//;
585 my $noexerule = rule
$noexe;
586 my $tdef = $noexerule ?
$noexerule->def ($cond) : undef;
588 if ($noexe ne $target
590 && $noexerule->name ne $target)
592 # The no-exeext option enables this feature.
593 if (! option
'no-exeext')
595 msg
('obsolete', $tdef->location,
596 "deprecated feature: target '$noexe' overrides "
597 . "'$noexe\$(EXEEXT)'\n"
598 . "change your target to read '$noexe\$(EXEEXT)'",
600 msg
('obsolete', $where, "target '$target' was defined here");
606 sub _maybe_warn_about_duplicated_target
($$$$$$)
608 my ($target, $tdef, $source, $owner, $cond, $where) = @_;
610 my $oldowner = $tdef->owner;
611 # Ok, it's the name target, but the name maybe different because
612 # 'foo$(EXEEXT)' and 'foo' have the same key in our table.
613 my $oldname = $tdef->name;
615 # Don't mention true conditions in diagnostics.
617 $cond == TRUE ?
'' : (" in condition '" . $cond->human . "'");
619 if ($owner == RULE_USER
)
621 if ($oldowner == RULE_USER
)
623 # Ignore '%'-style pattern rules. We'd need the
624 # dependencies to detect duplicates, and they are
625 # already diagnosed as unportable by -Wportability.
626 if ($target !~ /^[^%]*%[^%]*$/)
628 ## FIXME: Presently we can't diagnose duplicate user rules
629 ## because we don't distinguish rules with commands
630 ## from rules that only add dependencies. E.g.,
633 ## is legitimate. (This is phony.test.)
635 # msg ('syntax', $where,
636 # "redefinition of '$target'$condmsg ...", partial => 1);
637 # msg_cond_rule ('syntax', $cond, $target,
638 # "... '$target' previously defined here");
643 # Since we parse the user Makefile.am before reading
644 # the Automake fragments, this condition should never happen.
645 prog_error
("user target '$target'$condmsg seen after Automake's"
646 . " definition\nfrom " . $tdef->source);
649 else # $owner == RULE_AUTOMAKE
651 if ($oldowner == RULE_USER
)
653 # -am targets listed in %dependencies support a -local
654 # variant. If the user tries to override TARGET or
655 # TARGET-am for which there exists a -local variant,
656 # just tell the user to use it.
660 if (exists $dependencies{"$noam-am"})
662 $hint = "consider using $noam-local instead of $target";
665 msg_cond_rule
('override', $cond, $target,
666 "user target '$target' defined here"
667 . "$condmsg ...", partial
=> 1);
668 msg
('override', $where,
669 "... overrides Automake target '$oldname' defined here",
671 msg_cond_rule
('override', $cond, $target, $hint)
674 else # $oldowner == RULE_AUTOMAKE
676 # Automake should ignore redefinitions of its own
677 # rules if they came from the same file. This makes
678 # it easier to process a Makefile fragment several times.
679 # However it's an error if the target is defined in many
680 # files. E.g., the user might be using bin_PROGRAMS = ctags
681 # which clashes with our 'ctags' rule.
682 # (It would be more accurate if we had a way to compare
683 # the *content* of both rules. Then $targets_source would
685 my $oldsource = $tdef->source;
686 if (not ($source eq $oldsource && $target eq $oldname))
689 $where, "redefinition of '$target'$condmsg ...",
691 msg_cond_rule
('syntax', $cond, $target,
692 "... '$oldname' previously defined here");
698 # Return the list of conditionals in which the rule was defined. In case
699 # an ambiguous conditional definition is detected, return the empty list.
700 sub _conditionals_for_rule
($$$$)
702 my ($rule, $owner, $cond, $where) = @_;
703 my $target = $rule->name;
705 my ($message, $ambig_cond) = $rule->conditions->ambiguous_p ($target, $cond);
707 return $cond if !$message; # No ambiguity.
709 if ($owner == RULE_USER
)
711 # For user rules, just diagnose the ambiguity.
712 msg
'syntax', $where, "$message ...", partial
=> 1;
713 msg_cond_rule
('syntax', $ambig_cond, $target,
714 "... '$target' previously defined here");
718 # FIXME: for Automake rules, we can't diagnose ambiguities yet.
719 # The point is that Automake doesn't propagate conditions
720 # everywhere. For instance &handle_PROGRAMS doesn't care if
721 # bin_PROGRAMS was defined conditionally or not.
722 # On the following input
729 # &handle_PROGRAMS will attempt to define a 'foo:' rule
730 # in condition TRUE (which conflicts with COND1). Fixing
731 # this in &handle_PROGRAMS and siblings seems hard: you'd
732 # have to explain &file_contents what to do with a
733 # condition. So for now we do our best *here*. If 'foo:'
734 # was already defined in condition COND1 and we want to define
735 # it in condition TRUE, then define it only in condition !COND1.
736 # (See cond14.test and cond15.test for some test cases.)
737 @conds = $rule->not_always_defined_in_cond ($cond)->conds;
739 # No conditions left to define the rule.
740 # Warn, because our workaround is meaningless in this case.
741 if (scalar @conds == 0)
743 msg
'syntax', $where, "$message ...", partial
=> 1;
744 msg_cond_rule
('syntax', $ambig_cond, $target,
745 "... '$target' previously defined here");
751 =item C<@conds = define ($rulename, $source, $owner, $cond, $where)>
753 Define a new rule. C<$rulename> is the list of targets. C<$source>
754 is the filename the rule comes from. C<$owner> is the owner of the
755 rule (C<RULE_AUTOMAKE> or C<RULE_USER>). C<$cond> is the
756 C<Automake::Condition> under which the rule is defined. C<$where> is
757 the C<Automake::Location> where the rule is defined.
759 Returns a (possibly empty) list of C<Automake::Condition>s where the
760 rule's definition should be output.
766 my ($target, $source, $owner, $cond, $where) = @_;
768 prog_error
"$where is not a reference"
770 prog_error
"$cond is not a reference"
773 # Don't even think about defining a rule in condition FALSE.
774 return () if $cond == FALSE
;
776 my $tdef = _rule_defn_with_exeext_awareness
($target, $cond, $where);
778 # A GNU make-style pattern rule has a single "%" in the target name.
779 msg
('portability', $where,
780 "'%'-style pattern rules are a GNU make extension")
781 if $target =~ /^[^%]*%[^%]*$/;
783 # See whether this is a duplicated target declaration.
786 # Diagnose invalid target redefinitions, if any. Note that some
787 # target redefinitions are valid (e.g., for multiple-targets
789 _maybe_warn_about_duplicated_target
($target, $tdef, $source,
790 $owner, $cond, $where);
791 # Return so we don't redefine the rule in our tables, don't check
792 # for ambiguous condition, etc. The rule will be output anyway
793 # because '&read_am_file' ignores the return code.
797 my $rule = _crule
$target;
799 # Conditions for which the rule should be defined. Due to some
800 # complications in the automake internals, this aspect is not as
801 # obvious as it might be, and in come cases this list must contain
802 # other entries in addition to '$cond'. See the comments in
803 # '_conditionals_for_rule' for a rationale.
804 my @conds = _conditionals_for_rule
($rule, $owner, $cond, $where);
806 # Stop if we had ambiguous conditional definitions.
807 return unless @conds;
809 # Finally define this rule.
812 my $def = new Automake
::RuleDef
($target, '', $where->clone,
814 $rule->set ($c, $def);
817 # We honor inference rules with multiple targets because many
818 # makes support this and people use it. However this is disallowed
819 # by POSIX. We'll print a warning later.
820 my $target_count = 0;
821 my $inference_rule_count = 0;
823 for my $t (split (' ', $target))
826 # Check if the rule is a suffix rule: either it's a rule for
827 # two known extensions...
828 if ($t =~ /^($KNOWN_EXTENSIONS_PATTERN)($KNOWN_EXTENSIONS_PATTERN)$/
829 # ...or it's a rule with unknown extensions (i.e., the rule
830 # looks like '.foo.bar:' but '.foo' or '.bar' are not
831 # declared in SUFFIXES and are not known language
832 # extensions). Automake will complete SUFFIXES from
833 # @suffixes automatically (see handle_footer).
834 || ($t =~ /$_SUFFIX_RULE_PATTERN/o && accept_extensions
($1)))
836 ++$inference_rule_count;
837 register_suffix_rule
($where, $1, $2);
841 # POSIX allows multiple targets before the colon, but disallows
842 # definitions of multiple inference rules. It's also
843 # disallowed to mix plain targets with inference rules.
844 msg
('portability', $where,
845 "inference rules can have only one target before the colon (POSIX)")
846 if $inference_rule_count > 0 && $target_count > 1;
851 =item C<depend ($target, @deps)>
853 Adds C<@deps> to the dependencies of target C<$target>. This should
854 be used only with factored targets (those appearing in
861 my ($category, @dependees) = @_;
862 push (@
{$dependencies{$category}}, @dependees);
869 L<Automake::RuleDef>, L<Automake::Condition>,
870 L<Automake::DisjConditions>, L<Automake::Location>.
876 ### Setup "GNU" style for perl-mode and cperl-mode.
878 ## perl-indent-level: 2
879 ## perl-continued-statement-offset: 2
880 ## perl-continued-brace-offset: 0
881 ## perl-brace-offset: 0
882 ## perl-brace-imaginary-offset: 0
883 ## perl-label-offset: -2
884 ## cperl-indent-level: 2
885 ## cperl-brace-offset: 0
886 ## cperl-continued-brace-offset: 0
887 ## cperl-label-offset: -2
888 ## cperl-extra-newline-before-brace: t
889 ## cperl-merge-trailing-else: nil
890 ## cperl-continued-statement-offset: 2