1 # Copyright (C) 2003, 2004, 2006, 2007, 2010 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;
21 use Automake::RuleDef;
22 use Automake::ChannelDefs;
23 use Automake::Channels;
24 use Automake::Options;
25 use Automake::Condition qw (TRUE FALSE);
26 use Automake::DisjConditions;
28 use vars '@ISA', '@EXPORT', '@EXPORT_OK';
29 @ISA = qw/Automake::Item Exporter/;
30 @EXPORT = qw (reset register_suffix_rule suffix_rules_count
31 suffixes rules $suffix_rules $KNOWN_EXTENSIONS_PATTERN
32 depend %dependencies %actions register_action
34 reject_rule msg_rule msg_cond_rule err_rule err_cond_rule
35 rule rrule ruledef rruledef);
39 Automake::Rule - support for rules definitions
44 use Automake::RuleDef;
49 This package provides support for Makefile rule definitions.
51 An C<Automake::Rule> is a rule name associated to possibly
52 many conditional definitions. These definitions are instances
53 of C<Automake::RuleDef>.
55 Therefore obtaining the value of a rule under a given
56 condition involves two lookups. One to look up the rule,
57 and one to look up the conditional definition:
59 my $rule = rule $name;
62 my $def = $rule->def ($cond);
65 return $def->location;
71 when it is known that the rule and the definition
72 being looked up exist, the above can be simplified to
74 return rule ($name)->def ($cond)->location; # do not write this.
78 return rrule ($name)->rdef ($cond)->location;
82 return rruledef ($name, $cond)->location;
84 The I<r> variants of the C<rule>, C<def>, and C<ruledef> methods add
85 an extra test to ensure that the lookup succeeded, and will diagnose
86 failures as internal errors (with a message which is much more
87 informative than Perl's warning about calling a method on a
90 =head2 Global variables
96 my $_SUFFIX_RULE_PATTERN =
97 '^(\.[a-zA-Z0-9_(){}$+@\-]+)(\.[a-zA-Z0-9_(){}$+@\-]+)' . "\$";
99 # Suffixes found during a run.
100 use vars '@_suffixes';
102 # Same as $suffix_rules (declared below), but records only the
103 # default rules supplied by the languages Automake supports.
104 use vars '$_suffix_rules_default';
106 =item C<%dependencies>
108 Holds the dependencies of targets which dependencies are factored.
109 Typically, C<.PHONY> will appear in plenty of F<*.am> files, but must
110 be output once. Arguably all pure dependencies could be subject to
111 this factoring, but it is not unpleasant to have paragraphs in
112 Makefile: keeping related stuff altogether.
116 use vars '%dependencies';
120 Holds the factored actions. Tied to C<%dependencies>, i.e., filled
121 only when keys exists in C<%dependencies>.
127 =item <$suffix_rules>
129 This maps the source extension for all suffix rule seen to
130 a C<hash> whose keys are the possible output extensions.
132 Note that this is transitively closed by construction:
134 exists $suffix_rules{$ext1}{$ext2}
135 && exists $suffix_rules{$ext2}{$ext3}
137 exists $suffix_rules{$ext1}{$ext3}
139 So it's easy to check whether C<.foo> can be transformed to
140 C<.$(OBJEXT)> by checking whether
141 C<$suffix_rules{'.foo'}{'.$(OBJEXT)'}> exists. This will work even if
142 transforming C<.foo> to C<.$(OBJEXT)> involves a chain of several
145 The value of C<$suffix_rules{$ext1}{$ext2}> is a pair
146 C<[ $next_sfx, $dist ]> where C<$next_sfx> is target suffix
147 for the next rule to use to reach C<$ext2>, and C<$dist> the
148 distance to C<$ext2'>.
150 The content of this variable should be updated via the
151 C<register_suffix_rule> function.
155 use vars '$suffix_rules';
157 =item C<$KNOWN_EXTENSIONS_PATTERN>
159 Pattern that matches all know input extensions (i.e. extensions used
160 by the languages supported by Automake). Using this pattern (instead
161 of `\..*$') to match extensions allows Automake to support dot-less
164 New extensions should be registered with C<accept_extensions>.
168 use vars qw ($KNOWN_EXTENSIONS_PATTERN @_known_extensions_list);
169 $KNOWN_EXTENSIONS_PATTERN = "";
170 @_known_extensions_list = ();
174 =head2 Error reporting functions
176 In these functions, C<$rule> can be either a rule name, or
177 an instance of C<Automake::Rule>.
181 =item C<err_rule ($rule, $message, [%options])>
183 Uncategorized errors about rules.
189 msg_rule ('error', @_);
192 =item C<err_cond_rule ($cond, $rule, $message, [%options])>
194 Uncategorized errors about conditional rules.
198 sub err_cond_rule ($$$;%)
200 msg_cond_rule ('error', @_);
203 =item C<msg_cond_rule ($channel, $cond, $rule, $message, [%options])>
205 Messages about conditional rules.
209 sub msg_cond_rule ($$$$;%)
211 my ($channel, $cond, $rule, $msg, %opts) = @_;
212 my $r = ref ($rule) ? $rule : rrule ($rule);
213 msg $channel, $r->rdef ($cond)->location, $msg, %opts;
216 =item C<msg_rule ($channel, $targetname, $message, [%options])>
218 Messages about rules.
224 my ($channel, $rule, $msg, %opts) = @_;
225 my $r = ref ($rule) ? $rule : rrule ($rule);
226 # Don't know which condition is concerned. Pick any.
227 my $cond = $r->conditions->one_cond;
228 msg_cond_rule ($channel, $cond, $r, $msg, %opts);
232 =item C<$bool = reject_rule ($rule, $error_msg)>
234 Bail out with C<$error_msg> if a rule with name C<$rule> has been
237 Return true iff C<$rule> is defined.
243 my ($rule, $msg) = @_;
246 err_rule $rule, $msg;
254 =head2 Administrative functions
258 =item C<accept_extensions (@exts)>
260 Update C<$KNOWN_EXTENSIONS_PATTERN> to recognize the extensions
261 listed C<@exts>. Extensions should contain a dot if needed.
265 sub accept_extensions (@)
267 push @_known_extensions_list, @_;
268 $KNOWN_EXTENSIONS_PATTERN =
269 '(?:' . join ('|', map (quotemeta, @_known_extensions_list)) . ')';
274 Return the list of all L<Automake::Rule> instances. (I.e., all
275 rules defined so far.)
279 use vars '%_rule_dict';
282 return values %_rule_dict;
286 =item C<register_action($target, $action)>
288 Append the C<$action> to C<$actions{$target}> taking care of special
293 sub register_action ($$)
295 my ($target, $action) = @_;
296 if ($actions{$target})
298 $actions{$target} .= "\n$action" if $action;
302 $actions{$target} = $action;
307 =item C<Automake::Rule::reset>
309 The I<forget all> function. Clears all know rules and reset some
318 # The first time we initialize the variables,
319 # we save the value of $suffix_rules.
320 if (defined $_suffix_rules_default)
322 $suffix_rules = $_suffix_rules_default;
326 $_suffix_rules_default = $suffix_rules;
343 # Installing/uninstalling.
344 'install-data-am' => [],
345 'install-exec-am' => [],
346 'uninstall-am' => [],
349 'uninstall-man' => [],
352 'install-dvi-am' => [],
353 'install-html' => [],
354 'install-html-am' => [],
355 'install-info' => [],
356 'install-info-am' => [],
358 'install-pdf-am' => [],
360 'install-ps-am' => [],
362 'installcheck-am' => [],
366 'mostlyclean-am' => [],
367 'maintainer-clean-am' => [],
368 'distclean-am' => [],
371 'maintainer-clean' => [],
379 # Recursive install targets (so `make -n install' works for BSD Make).
385 =item C<register_suffix_rule ($where, $src, $dest)>
387 Register a suffix rules defined on C<$where> that transform
388 files ending in C<$src> into files ending in C<$dest>.
390 This upgrades the C<$suffix_rules> variables.
394 sub register_suffix_rule ($$$)
396 my ($where, $src, $dest) = @_;
398 verb "Sources ending in $src become $dest";
399 push @_suffixes, $src, $dest;
401 # When transforming sources to objects, Automake uses the
402 # %suffix_rules to move from each source extension to
403 # `.$(OBJEXT)', not to `.o' or `.obj'. However some people
404 # define suffix rules for `.o' or `.obj', so internally we will
405 # consider these extensions equivalent to `.$(OBJEXT)'. We
406 # CANNOT rewrite the target (i.e., automagically replace `.o'
407 # and `.obj' by `.$(OBJEXT)' in the output), or warn the user
408 # that (s)he'd better use `.$(OBJEXT)', because Automake itself
409 # output suffix rules for `.o' or `.obj'...
410 $dest = '.$(OBJEXT)' if ($dest eq '.o' || $dest eq '.obj');
412 # Reading the comments near the declaration of $suffix_rules might
413 # help to understand the update of $suffix_rules that follows...
415 # Register $dest as a possible destination from $src.
416 # We might have the create the \hash.
417 if (exists $suffix_rules->{$src})
419 $suffix_rules->{$src}{$dest} = [ $dest, 1 ];
423 $suffix_rules->{$src} = { $dest => [ $dest, 1 ] };
426 # If we know how to transform $dest in something else, then
427 # we know how to transform $src in that "something else".
428 if (exists $suffix_rules->{$dest})
430 for my $dest2 (keys %{$suffix_rules->{$dest}})
432 my $dist = $suffix_rules->{$dest}{$dest2}[1] + 1;
433 # Overwrite an existing $src->$dest2 path only if
434 # the path via $dest which is shorter.
435 if (! exists $suffix_rules->{$src}{$dest2}
436 || $suffix_rules->{$src}{$dest2}[1] > $dist)
438 $suffix_rules->{$src}{$dest2} = [ $dest, $dist ];
443 # Similarly, any extension that can be derived into $src
444 # can be derived into the same extensions as $src can.
445 my @dest2 = keys %{$suffix_rules->{$src}};
446 for my $src2 (keys %$suffix_rules)
448 if (exists $suffix_rules->{$src2}{$src})
450 for my $dest2 (@dest2)
452 my $dist = $suffix_rules->{$src}{$dest2} + 1;
453 # Overwrite an existing $src2->$dest2 path only if
454 # the path via $src is shorter.
455 if (! exists $suffix_rules->{$src2}{$dest2}
456 || $suffix_rules->{$src2}{$dest2}[1] > $dist)
458 $suffix_rules->{$src2}{$dest2} = [ $src, $dist ];
465 =item C<$count = suffix_rules_count>
467 Return the number of suffix rules added while processing the current
468 F<Makefile> (excluding predefined suffix rules).
472 sub suffix_rules_count ()
474 return (scalar keys %$suffix_rules) - (scalar keys %$_suffix_rules_default);
477 =item C<@list = suffixes>
479 Return the list of known suffixes.
488 =item C<rule ($rulename)>
490 Return the C<Automake::Rule> object for the rule
491 named C<$rulename> if defined. Return 0 otherwise.
498 # Strip $(EXEEXT) from $name, so we can diagnose
499 # a clash if `ctags$(EXEEXT):' is redefined after `ctags:'.
500 $name =~ s,\$\(EXEEXT\)$,,;
501 return $_rule_dict{$name} || 0;
504 =item C<ruledef ($rulename, $cond)>
506 Return the C<Automake::RuleDef> object for the rule named
507 C<$rulename> if defined in condition C<$cond>. Return false
508 if the condition or the rule does not exist.
514 my ($name, $cond) = @_;
515 my $rule = rule $name;
516 return $rule && $rule->def ($cond);
519 =item C<rrule ($rulename)
521 Return the C<Automake::Rule> object for the variable named
522 C<$rulename>. Abort with an internal error if the variable was not
525 The I<r> in front of C<var> stands for I<required>. One
526 should call C<rvar> to assert the rule's existence.
534 prog_error ("undefined rule $name\n" . &rules_dump)
539 =item C<rruledef ($varname, $cond)>
541 Return the C<Automake::RuleDef> object for the rule named
542 C<$rulename> if defined in condition C<$cond>. Abort with an internal
543 error if the condition or the rule does not exist.
549 my ($name, $cond) = @_;
550 return rrule ($name)->rdef ($cond);
553 # Create the variable if it does not exist.
554 # This is used only by other functions in this package.
560 return _new Automake::Rule $name;
565 my ($class, $name) = @_;
567 # Strip $(EXEEXT) from $name, so we can diagnose
568 # a clash if `ctags$(EXEEXT):' is redefined after `ctags:'.
569 (my $keyname = $name) =~ s,\$\(EXEEXT\)$,,;
571 my $self = Automake::Item::new ($class, $name);
572 $_rule_dict{$keyname} = $self;
577 =item C<@conds = define ($rulename, $source, $owner, $cond, $where)>
579 Define a new rule. C<$rulename> is the list of targets. C<$source>
580 is the filename the rule comes from. C<$owner> is the owner of the
581 rule (C<RULE_AUTOMAKE> or C<RULE_USER>). C<$cond> is the
582 C<Automake::Condition> under which the rule is defined. C<$where> is
583 the C<Automake::Location> where the rule is defined.
585 Returns a (possibly empty) list of C<Automake::Condition>s where the
586 rule's definition should be output.
592 my ($target, $source, $owner, $cond, $where) = @_;
594 prog_error "$where is not a reference"
596 prog_error "$cond is not a reference"
599 # Don't even think about defining a rule in condition FALSE.
600 return () if $cond == FALSE;
602 # For now `foo:' will override `foo$(EXEEXT):'. This is temporary,
603 # though, so we emit a warning.
604 (my $noexe = $target) =~ s,\$\(EXEEXT\)$,,;
605 my $noexerule = rule $noexe;
606 my $tdef = $noexerule ? $noexerule->def ($cond) : undef;
608 if ($noexe ne $target
610 && $noexerule->name ne $target)
612 # The no-exeext option enables this feature.
613 if (! option 'no-exeext')
615 msg ('obsolete', $tdef->location,
616 "deprecated feature: target `$noexe' overrides "
617 . "`$noexe\$(EXEEXT)'\n"
618 . "change your target to read `$noexe\$(EXEEXT)'",
620 msg ('obsolete', $where, "target `$target' was defined here");
622 # Don't `return ()' now, as this might hide target clashes
627 # A GNU make-style pattern rule has a single "%" in the target name.
628 msg ('portability', $where,
629 "`%'-style pattern rules are a GNU make extension")
630 if $target =~ /^[^%]*%[^%]*$/;
632 # Diagnose target redefinitions.
635 my $oldowner = $tdef->owner;
636 # Ok, it's the name target, but the name maybe different because
637 # `foo$(EXEEXT)' and `foo' have the same key in our table.
638 my $oldname = $tdef->name;
640 # Don't mention true conditions in diagnostics.
642 $cond == TRUE ? '' : " in condition `" . $cond->human . "'";
644 if ($owner == RULE_USER)
646 if ($oldowner == RULE_USER)
648 # Ignore `%'-style pattern rules. We'd need the
649 # dependencies to detect duplicates, and they are
650 # already diagnosed as unportable by -Wportability.
651 if ($target !~ /^[^%]*%[^%]*$/)
653 ## FIXME: Presently we can't diagnose duplicate user rules
654 ## because we don't distinguish rules with commands
655 ## from rules that only add dependencies. E.g.,
658 ## is legitimate. (This is phony.test.)
660 # msg ('syntax', $where,
661 # "redefinition of `$target'$condmsg ...", partial => 1);
662 # msg_cond_rule ('syntax', $cond, $target,
663 # "... `$target' previously defined here");
665 # Return so we don't redefine the rule in our tables,
666 # don't check for ambiguous condition, etc. The rule
667 # will be output anyway because &read_am_file ignore the
673 # Since we parse the user Makefile.am before reading
674 # the Automake fragments, this condition should never happen.
675 prog_error ("user target `$target'$condmsg seen after Automake's"
676 . " definition\nfrom " . $tdef->source);
679 else # $owner == RULE_AUTOMAKE
681 if ($oldowner == RULE_USER)
683 # -am targets listed in %dependencies support a -local
684 # variant. If the user tries to override TARGET or
685 # TARGET-am for which there exists a -local variant,
686 # just tell the user to use it.
690 if (exists $dependencies{"$noam-am"})
692 $hint = "consider using $noam-local instead of $target";
695 msg_cond_rule ('override', $cond, $target,
696 "user target `$target' defined here"
697 . "$condmsg ...", partial => 1);
698 msg ('override', $where,
699 "... overrides Automake target `$oldname' defined here",
701 msg_cond_rule ('override', $cond, $target, $hint)
704 # Don't overwrite the user definition of TARGET.
707 else # $oldowner == RULE_AUTOMAKE
709 # Automake should ignore redefinitions of its own
710 # rules if they came from the same file. This makes
711 # it easier to process a Makefile fragment several times.
712 # However it's an error if the target is defined in many
713 # files. E.g., the user might be using bin_PROGRAMS = ctags
714 # which clashes with our `ctags' rule.
715 # (It would be more accurate if we had a way to compare
716 # the *content* of both rules. Then $targets_source would
718 my $oldsource = $tdef->source;
719 return () if $source eq $oldsource && $target eq $oldname;
721 msg ('syntax', $where, "redefinition of `$target'$condmsg ...",
723 msg_cond_rule ('syntax', $cond, $target,
724 "... `$oldname' previously defined here");
729 prog_error ("unreachable place reached");
732 # Conditions for which the rule should be defined.
735 # Check ambiguous conditional definitions.
736 my $rule = _crule $target;
737 my ($message, $ambig_cond) = $rule->conditions->ambiguous_p ($target, $cond);
738 if ($message) # We have an ambiguity.
740 if ($owner == RULE_USER)
742 # For user rules, just diagnose the ambiguity.
743 msg 'syntax', $where, "$message ...", partial => 1;
744 msg_cond_rule ('syntax', $ambig_cond, $target,
745 "... `$target' previously defined here");
750 # FIXME: for Automake rules, we can't diagnose ambiguities yet.
751 # The point is that Automake doesn't propagate conditions
752 # everywhere. For instance &handle_PROGRAMS doesn't care if
753 # bin_PROGRAMS was defined conditionally or not.
754 # On the following input
761 # &handle_PROGRAMS will attempt to define a `foo:' rule
762 # in condition TRUE (which conflicts with COND1). Fixing
763 # this in &handle_PROGRAMS and siblings seems hard: you'd
764 # have to explain &file_contents what to do with a
765 # condition. So for now we do our best *here*. If `foo:'
766 # was already defined in condition COND1 and we want to define
767 # it in condition TRUE, then define it only in condition !COND1.
768 # (See cond14.test and cond15.test for some test cases.)
769 @conds = $rule->not_always_defined_in_cond ($cond)->conds;
771 # No conditions left to define the rule.
772 # Warn, because our workaround is meaningless in this case.
773 if (scalar @conds == 0)
775 msg 'syntax', $where, "$message ...", partial => 1;
776 msg_cond_rule ('syntax', $ambig_cond, $target,
777 "... `$target' previously defined here");
783 # Finally define this rule.
786 my $def = new Automake::RuleDef ($target, '', $where->clone,
788 $rule->set ($c, $def);
791 # We honor inference rules with multiple targets because many
792 # make support this and people use it. However this is disallowed
793 # by POSIX. We'll print a warning later.
794 my $target_count = 0;
795 my $inference_rule_count = 0;
797 for my $t (split (' ', $target))
800 # Check if the rule is a suffix rule: either it's a rule for
801 # two known extensions...
802 if ($t =~ /^($KNOWN_EXTENSIONS_PATTERN)($KNOWN_EXTENSIONS_PATTERN)$/
803 # ...or it's a rule with unknown extensions (i.e., the rule
804 # looks like `.foo.bar:' but `.foo' or `.bar' are not
805 # declared in SUFFIXES and are not known language
806 # extensions). Automake will complete SUFFIXES from
807 # @suffixes automatically (see handle_footer).
810 || ($t =~ /$_SUFFIX_RULE_PATTERN/o && accept_extensions($1)))
812 ++$inference_rule_count;
813 register_suffix_rule ($where, $1, $2);
817 # POSIX allows multiple targets before the colon, but disallows
818 # definitions of multiple inference rules. It's also
819 # disallowed to mix plain targets with inference rules.
820 msg ('portability', $where,
821 "inference rules can have only one target before the colon (POSIX)")
822 if $inference_rule_count > 0 && $target_count > 1;
827 =item C<depend ($target, @deps)>
829 Adds C<@deps> to the dependencies of target C<$target>. This should
830 be used only with factored targets (those appearing in
837 my ($category, @dependees) = @_;
838 push (@{$dependencies{$category}}, @dependees);
845 L<Automake::RuleDef>, L<Automake::Condition>,
846 L<Automake::DisjConditions>, L<Automake::Location>.
852 ### Setup "GNU" style for perl-mode and cperl-mode.
854 ## perl-indent-level: 2
855 ## perl-continued-statement-offset: 2
856 ## perl-continued-brace-offset: 0
857 ## perl-brace-offset: 0
858 ## perl-brace-imaginary-offset: 0
859 ## perl-label-offset: -2
860 ## cperl-indent-level: 2
861 ## cperl-brace-offset: 0
862 ## cperl-continued-brace-offset: 0
863 ## cperl-label-offset: -2
864 ## cperl-extra-newline-before-brace: t
865 ## cperl-merge-trailing-else: nil
866 ## cperl-continued-statement-offset: 2