1package Config::AutoConf;
2
3use warnings;
4use strict;
5
6use base 'Exporter';
7
8our @EXPORT = ('$LIBEXT', '$EXEEXT');
9
10use constant QUOTE => do { $^O eq "MSWin32" ? q["] : q['] };
11
12use Config;
13use Carp qw/croak/;
14
15use File::Temp qw/tempfile/;
16use File::Basename;
17use File::Spec;
18use Text::ParseWords qw//;
19
20use Capture::Tiny qw/capture/;
21
22# in core since 5.7.3
23eval "use Scalar::Util qw/looks_like_number/;";
24__PACKAGE__->can("looks_like_number") or eval <<'EOP';
25=begin private
26
27=head2 looks_like_number
28
29=end private
30
31=cut
32
33# from PP part of Params::Util
34sub looks_like_number {
35    local $_ = shift;
36
37    # checks from perlfaq4
38    return 0 if !defined($_);
39    if (ref($_)) {
40        return overload::Overloaded($_) ? defined(0 + $_) : 0;
41    }
42    return 1 if (/^[+-]?[0-9]+$/); # is a +/- integer
43    return 1 if (/^([+-]?)(?=[0-9]|\.[0-9])[0-9]*(\.[0-9]*)?([Ee]([+-]?[0-9]+))?$/); # a C float
44    return 1 if ($] >= 5.008 and /^(Inf(inity)?|NaN)$/i) or ($] >= 5.006001 and /^Inf$/i);
45
46    0;
47}
48EOP
49
50eval "use File::Slurper qw/read_binary/;";
51__PACKAGE__->can("read_binary") or eval <<'EOP';
52=begin private
53
54=head2 read_file
55
56=end private
57
58=cut
59
60sub read_binary {
61  my $fn = shift;
62  local $@ = "";
63  open( my $fh, "<", $fn ) or croak "Error opening $fn: $!";
64  my $fc = <$fh>;
65  close($fh) or croak "I/O error closing $fn: $!";
66  return $fc;
67}
68EOP
69
70# PA-RISC1.1-thread-multi
71my %special_dlext = (
72    darwin  => ".dylib",
73    MSWin32 => ".dll",
74    ($Config{archname} =~ m/PA-RISC/i ? ("hpux" => ".sl") : ()),
75);
76
77our ($LIBEXT, $EXEEXT);
78
79defined $LIBEXT
80  or $LIBEXT =
81    defined $Config{so}         ? "." . $Config{so}
82  : defined $special_dlext{$^O} ? $special_dlext{$^O}
83  :                               ".so";
84defined $EXEEXT
85  or $EXEEXT = ($^O eq "MSWin32") ? ".exe" : "";
86
87=encoding UTF-8
88
89=head1 NAME
90
91Config::AutoConf - A module to implement some of AutoConf macros in pure perl.
92
93=cut
94
95our $VERSION = '0.319';
96$VERSION = eval $VERSION;
97
98=head1 ABSTRACT
99
100With this module I pretend to simulate some of the tasks AutoConf
101macros do. To detect a command, to detect a library, etc.
102
103=head1 SYNOPSIS
104
105    use Config::AutoConf;
106
107    Config::AutoConf->check_prog("agrep");
108    my $grep = Config::AutoConf->check_progs("agrep", "egrep", "grep");
109
110    Config::AutoConf->check_header("ncurses.h");
111    my $curses = Config::AutoConf->check_headers("ncurses.h","curses.h");
112
113    Config::AutoConf->check_prog_awk;
114    Config::AutoConf->check_prog_egrep;
115
116    Config::AutoConf->check_cc();
117
118    Config::AutoConf->check_lib("ncurses", "tgoto");
119
120    Config::AutoConf->check_file("/etc/passwd"); # -f && -r
121
122=head1 DESCRIPTION
123
124Config::AutoConf is intended to provide the same opportunities to Perl
125developers as L<GNU Autoconf|http://www.gnu.org/software/autoconf/>
126does for Shell developers.
127
128As Perl is the second most deployed language (mind: every Unix comes
129with Perl, several mini-computers have Perl and even lot's of Windows
130machines run Perl software - which requires deployed Perl there, too),
131this gives wider support than Shell based probes.
132
133The API is leaned against GNU Autoconf, but we try to make the API
134(especially optional arguments) more Perl'ish than m4 abilities allow
135to the original.
136
137=head1 CONSTRUCTOR
138
139=cut
140
141my $glob_instance;
142
143=head2 new
144
145This function instantiates a new instance of Config::AutoConf, e.g. to
146configure child components. The constructor adds also values set via
147environment variable C<PERL5_AUTOCONF_OPTS>.
148
149=cut
150
151sub new
152{
153    my $class = shift;
154    ref $class and $class = ref $class;
155    my %args = @_;
156
157    my %flags = map {
158        my ($k, $v) = split("=", $_, 2);
159        defined $v or $v = 1;
160        ($k, $v)
161    } split(":", $ENV{PERL5_AC_OPTS}) if ($ENV{PERL5_AC_OPTS});
162
163    my %instance = (
164        msg_prefix     => 'configure: ',
165        lang           => "C",
166        lang_stack     => [],
167        lang_supported => {
168            "C" => $class->can("check_prog_cc"),
169        },
170        cache                  => {},
171        defines                => {},
172        extra_libs             => [],
173        extra_lib_dirs         => [],
174        extra_include_dirs     => [],
175        extra_preprocess_flags => [],
176        extra_compile_flags    => {
177            "C" => [],
178        },
179        extra_link_flags => [],
180        logfile          => "config.log",
181        c_ac_flags       => {%flags},
182        %args
183    );
184    bless(\%instance, $class);
185}
186
187=head1 METHODS
188
189=head2 check_file
190
191This function checks if a file exists in the system and is readable by
192the user. Returns a boolean. You can use '-f $file && -r $file' so you
193don't need to use a function call.
194
195=cut
196
197sub check_file
198{
199    my $self = shift->_get_instance();
200    my $file = shift;
201
202    my $cache_name = $self->_cache_name("file", $file);
203    $self->check_cached(
204        $cache_name,
205        "for $file",
206        sub {
207            -f $file && -r $file;
208        }
209    );
210}
211
212=head2 check_files
213
214This function checks if a set of files exist in the system and are
215readable by the user. Returns a boolean.
216
217=cut
218
219sub check_files
220{
221    my $self = shift->_get_instance();
222
223    for (@_)
224    {
225        return 0 unless $self->check_file($_);
226    }
227
228    1;
229}
230
231sub _quote_shell_arg { scalar Text::ParseWords::shellwords($_[0]) > 1 ? QUOTE . $_[0] . QUOTE : $_[0] }
232
233sub _sanitize_prog { shift; _quote_shell_arg shift }
234
235sub _append_prog_args
236{
237    shift;
238    join " ", map { _quote_shell_arg $_ } @_;
239}
240
241my @exe_exts = ($^O eq "MSWin32" ? qw(.exe .com .bat .cmd) : (""));
242
243=head2 check_prog( $prog, \@dirlist?, \%options? )
244
245This function checks for a program with the supplied name. In success
246returns the full path for the executable;
247
248An optional array reference containing a list of directories to be searched
249instead of $PATH is gracefully honored.
250
251If the very last parameter contains a hash reference, C<CODE> references
252to I<action_on_true> or I<action_on_false> are executed, respectively.
253
254=cut
255
256sub check_prog
257{
258    my $self = shift->_get_instance();
259    # sanitize ac_prog
260    my $ac_prog = _sanitize(shift @_);
261
262    my $options = {};
263    scalar @_ > 1 and ref $_[-1] eq "HASH" and $options = pop @_;
264
265    my @dirlist;
266    @_ and scalar @_ > 1 and @dirlist = @_;
267    @_ and scalar @_ == 1 and ref $_[0] eq "ARRAY" and @dirlist = @{$_[0]};
268    @dirlist or @dirlist = split(/$Config{path_sep}/, $ENV{PATH});
269
270    for my $p (@dirlist)
271    {
272        for my $e (@exe_exts)
273        {
274            my $cmd           = $self->_sanitize_prog(File::Spec->catfile($p, $ac_prog . $e));
275            my $is_executable = -x $cmd and -f $cmd;
276                  $is_executable
277              and $options->{action_on_true}
278              and ref $options->{action_on_true} eq "CODE"
279              and $options->{action_on_true}->();
280            $is_executable and return $cmd;
281        }
282    }
283
284    $options->{action_on_false}
285      and ref $options->{action_on_false} eq "CODE"
286      and $options->{action_on_false}->();
287
288    return;
289}
290
291=head2 check_progs(progs, [dirlist])
292
293This function takes a list of program names. Returns the full path for
294the first found on the system. Returns undef if none was found.
295
296An optional array reference containing a list of directories to be searched
297instead of $PATH is gracefully honored.
298
299If the very last parameter contains a hash reference, C<CODE> references
300to I<action_on_true> or I<action_on_false> are executed, respectively. The
301name of the I<$prog> to check and the found full path are passed as first
302and second argument to the I<action_on_true> callback.
303
304=cut
305
306sub check_progs
307{
308    my $self = shift->_get_instance();
309
310    my $options = {};
311    scalar @_ > 1 and ref $_[-1] eq "HASH" and $options = pop @_;
312
313    my @dirlist;
314    scalar @_ > 1 and ref $_[-1] eq "ARRAY" and @dirlist = @{pop @_};
315    @dirlist or @dirlist = split(/$Config{path_sep}/, $ENV{PATH});
316
317    my @progs = @_;
318    foreach my $prog (@progs)
319    {
320        defined $prog or next;
321
322        my $ans = $self->check_prog($prog, \@dirlist);
323              $ans
324          and $options->{action_on_true}
325          and ref $options->{action_on_true} eq "CODE"
326          and $options->{action_if_true}->($prog, $ans);
327
328        $ans and return $ans;
329    }
330
331    $options->{action_on_false}
332      and ref $options->{action_on_false} eq "CODE"
333      and $options->{action_on_false}->();
334
335    return;
336}
337
338=head2 check_prog_yacc
339
340From the L<GNU Autoconf|https://www.gnu.org/software/autoconf/autoconf.html> documentation,
341
342  If `bison' is found, set [...] `bison -y'.
343  Otherwise, if `byacc' is found, set [...] `byacc'.
344  Otherwise set [...] `yacc'.  The result of this test can be influenced
345  by setting the variable YACC or the cache variable ac_cv_prog_YACC.
346
347Returns the full path, if found.
348
349=cut
350
351sub check_prog_yacc
352{
353    my $self = shift->_get_instance();
354
355    # my ($self, $cache_name, $message, $check_sub) = @_;
356
357    my $cache_name = $self->_cache_name("prog", "YACC");
358    $self->check_cached(
359        $cache_name,
360        "for yacc",
361        sub {
362            defined $ENV{YACC} and return $ENV{YACC};
363            my $binary = $self->check_progs(qw/bison byacc yacc/);
364            defined $binary
365              and $binary =~ /bison(?:\.(?:exe|com|bat|cmd))?$/
366              and $binary = $self->_append_prog_args($binary, "-y");
367            return $binary;
368        }
369    );
370}
371
372=head2 check_prog_awk
373
374From the L<GNU Autoconf|https://www.gnu.org/software/autoconf/autoconf.html> documentation,
375
376  Check for `gawk', `mawk', `nawk', and `awk', in that order, and
377  set output [...] to the first one that is found.  It tries
378  `gawk' first because that is reported to be the best implementation.
379  The result can be overridden by setting the variable AWK or the
380  cache variable ac_cv_prog_AWK.
381
382Note that it returns the full path, if found.
383
384=cut
385
386sub check_prog_awk
387{
388    my $self       = shift->_get_instance();
389    my $cache_name = $self->_cache_name("prog", "AWK");
390    $self->check_cached($cache_name, "for awk", sub { $ENV{AWK} || $self->check_progs(qw/gawk mawk nawk awk/) });
391}
392
393=head2 check_prog_egrep
394
395From the L<GNU Autoconf|https://www.gnu.org/software/autoconf/autoconf.html> documentation,
396
397  Check for `grep -E' and `egrep', in that order, and [...] output
398  [...] the first one that is found.  The result can be overridden by
399  setting the EGREP variable and is cached in the ac_cv_path_EGREP
400  variable.
401
402Note that it returns the full path, if found.
403
404=cut
405
406sub check_prog_egrep
407{
408    my $self = shift->_get_instance();
409
410    my $cache_name = $self->_cache_name("prog", "EGREP");
411    $self->check_cached(
412        $cache_name,
413        "for egrep",
414        sub {
415            defined $ENV{EGREP} and return $ENV{EGREP};
416            my $grep;
417            $grep = $self->check_progs("egrep") and return $grep;
418
419            if ($grep = $self->check_prog("grep"))
420            {
421                # check_run - Capture::Tiny, Open3 ... ftw!
422                my $ans = `echo a | ($grep -E '(a|b)') 2>/dev/null`;
423                chomp $ans;
424                $ans eq "a" and return $self->_append_prog_args($grep, "-E");
425            }
426        }
427    );
428}
429
430=head2 check_prog_lex
431
432From the L<GNU Autoconf|https://www.gnu.org/software/autoconf/autoconf.html> documentation,
433
434  If flex is found, set output [...] to ‘flex’ and [...] to -lfl, if that
435  library is in a standard place. Otherwise set output [...] to ‘lex’ and
436  [...] to -ll, if found. If [...] packages [...] ship the generated
437  file.yy.c alongside the source file.l, this [...] allows users without a
438  lexer generator to still build the package even if the timestamp for
439  file.l is inadvertently changed.
440
441Note that it returns the full path, if found.
442
443The structure $self->{lex} is set with attributes
444
445  prog => $LEX
446  lib => $LEXLIB
447  root => $lex_root
448
449=cut
450
451sub check_prog_lex
452{
453    my $self       = shift->_get_instance;
454    my $cache_name = $self->_cache_name("prog", "LEX");
455    my $lex        = $self->check_cached($cache_name, "for lex", sub { $ENV{LEX} || $self->check_progs(qw/flex lex/) });
456    if ($lex)
457    {
458        defined $self->{lex}->{prog} or $self->{lex}->{prog} = $lex;
459        my $lex_root_var = $self->check_cached(
460            "ac_cv_prog_lex_root",
461            "for lex output file root",
462            sub {
463                my ($fh, $filename) = tempfile(
464                    "testXXXXXX",
465                    SUFFIX => '.l',
466                    UNLINK => 0
467                );
468                my $src = <<'EOLEX';
469%%
470a { ECHO; }
471b { REJECT; }
472c { yymore (); }
473d { yyless (1); }
474e { /* IRIX 6.5 flex 2.5.4 underquotes its yyless argument.  */
475    yyless ((input () != 0)); }
476f { unput (yytext[0]); }
477. { BEGIN INITIAL; }
478%%
479#ifdef YYTEXT_POINTER
480extern char *yytext;
481#endif
482int
483main (void)
484{
485  return ! yylex () + ! yywrap ();
486}
487EOLEX
488
489                print {$fh} $src;
490                close $fh;
491
492                my ($stdout, $stderr, $exit) =
493                  capture { system($lex, $filename); };
494                chomp $stdout;
495                unlink $filename;
496                -f "lex.yy.c" and return "lex.yy";
497                -f "lexyy.c"  and return "lexyy";
498                $self->msg_error("cannot find output from $lex; giving up");
499            }
500        );
501        defined $self->{lex}->{root} or $self->{lex}->{root} = $lex_root_var;
502
503        my $conftest = read_binary($lex_root_var . ".c");
504        unlink $lex_root_var . ".c";
505
506        $cache_name = $self->_cache_name("lib", "lex");
507        my $check_sub = sub {
508            my @save_libs = @{$self->{extra_libs}};
509            my $have_lib  = 0;
510            foreach my $libstest (undef, qw(-lfl -ll))
511            {
512                # XXX would local work on array refs? can we omit @save_libs?
513                $self->{extra_libs} = [@save_libs];
514                defined($libstest) and unshift(@{$self->{extra_libs}}, $libstest);
515                $self->link_if_else($conftest)
516                  and ($have_lib = defined($libstest) ? $libstest : "none required")
517                  and last;
518            }
519            $self->{extra_libs} = [@save_libs];
520
521            if ($have_lib)
522            {
523                $self->define_var(_have_lib_define_name("lex"), $have_lib, "defined when lex library is available");
524            }
525            else
526            {
527                $self->define_var(_have_lib_define_name("lex"), undef, "defined when lex library is available");
528            }
529            return $have_lib;
530        };
531
532        my $lex_lib = $self->check_cached($cache_name, "lex library", $check_sub);
533        defined $self->{lex}->{lib} or $self->{lex}->{lib} = $lex_lib;
534    }
535
536    $lex;
537}
538
539=head2 check_prog_sed
540
541From the L<GNU Autoconf|https://www.gnu.org/software/autoconf/autoconf.html> documentation,
542
543  Set output variable [...] to a Sed implementation that conforms to Posix
544  and does not have arbitrary length limits. Report an error if no
545  acceptable Sed is found. See Limitations of Usual Tools, for more
546  information about portability problems with Sed.
547
548  The result of this test can be overridden by setting the SED variable and
549  is cached in the ac_cv_path_SED variable.
550
551Note that it returns the full path, if found.
552
553=cut
554
555sub check_prog_sed
556{
557    my $self       = shift->_get_instance();
558    my $cache_name = $self->_cache_name("prog", "SED");
559    $self->check_cached($cache_name, "for sed", sub { $ENV{SED} || $self->check_progs(qw/gsed sed/) });
560}
561
562=head2 check_prog_pkg_config
563
564Checks for C<pkg-config> program. No additional tests are made for it ...
565
566=cut
567
568sub check_prog_pkg_config
569{
570    my $self       = shift->_get_instance();
571    my $cache_name = $self->_cache_name("prog", "PKG_CONFIG");
572    $self->check_cached($cache_name, "for pkg-config", sub { $self->check_prog("pkg-config") });
573}
574
575=head2 check_prog_cc
576
577Determine a C compiler to use. Currently the probe is delegated to L<ExtUtils::CBuilder>.
578
579=cut
580
581sub check_prog_cc
582{
583    my $self       = shift->_get_instance();
584    my $cache_name = $self->_cache_name("prog", "CC");
585
586    $self->check_cached(
587        $cache_name,
588        "for cc",
589        sub {
590            $self->{lang_supported}->{C} = undef;
591            eval "use ExtUtils::CBuilder;";
592            $@ and return;
593            my $cb = ExtUtils::CBuilder->new(quiet => 1);
594            $cb->have_compiler or return;
595            $self->{lang_supported}->{C} = "ExtUtils::CBuilder";
596            $cb->{config}->{cc};
597        }
598    );
599}
600
601=head2 check_cc
602
603(Deprecated) Old name of L</check_prog_cc>.
604
605=cut
606
607sub check_cc { shift->check_prog_cc(@_) }
608
609=head2 check_valid_compiler
610
611This function checks for a valid compiler for the currently active language.
612At the very moment only C<C> is understood (corresponding to your compiler
613default options, e.g. -std=gnu89).
614
615=cut
616
617sub check_valid_compiler
618{
619    my $self = shift->_get_instance;
620    my $lang = $self->{lang};
621    $lang eq "C" or $self->msg_error("Language $lang is not supported");
622    $self->check_prog_cc;
623}
624
625=head2 check_valid_compilers(;\@)
626
627Checks for valid compilers for each given language. When unspecified
628defaults to C<[ "C" ]>.
629
630=cut
631
632sub check_valid_compilers
633{
634    my $self = shift;
635    for my $lang (@{$_[0]})
636    {
637        $self->push_lang($lang);
638        my $supp = $self->check_valid_compiler;
639        $self->pop_lang($lang);
640        $supp or return 0;
641    }
642
643    1;
644}
645
646=head2 msg_checking
647
648Prints "Checking @_ ..."
649
650=cut
651
652sub msg_checking
653{
654    my $self = shift->_get_instance();
655    $self->{quiet}
656      or print "Checking " . join(" ", @_) . "... ";
657    $self->_add_log_entry("Checking " . join(" ", @_, "..."));
658    return;
659}
660
661=head2 msg_result
662
663Prints result \n
664
665=cut
666
667my @_num_to_msg = qw/no yes/;
668
669sub _neat
670{
671    defined $_[0] or return "";
672    looks_like_number($_[0]) and defined $_num_to_msg[$_[0]] and return $_num_to_msg[$_[0]];
673    $_[0];
674}
675
676sub msg_result
677{
678    my $self = shift->_get_instance();
679    $self->{quiet}
680      or print join(" ", map { _neat $_ } @_), "\n";
681    $self->_add_log_entry(join(" ", map { _neat $_ } @_), "\n");
682    return;
683}
684
685=head2 msg_notice
686
687Prints "configure: " @_ to stdout
688
689=cut
690
691sub msg_notice
692{
693    my $self = shift->_get_instance();
694    $self->{quiet}
695      or print $self->{msg_prefix} . join(" ", @_) . "\n";
696    $self->_add_log_entry($self->{msg_prefix} . join(" ", @_) . "\n");
697    return;
698}
699
700=head2 msg_warn
701
702Prints "configure: " @_ to stderr
703
704=cut
705
706sub msg_warn
707{
708    my $self = shift->_get_instance();
709    print STDERR $self->{msg_prefix} . join(" ", @_) . "\n";
710    $self->_add_log_entry("WARNING: " . $self->{msg_prefix} . join(" ", @_) . "\n");
711    return;
712}
713
714=head2 msg_error
715
716Prints "configure: " @_ to stderr and exits with exit code 0 (tells
717toolchain to stop here and report unsupported environment)
718
719=cut
720
721sub msg_error
722{
723    my $self = shift->_get_instance();
724    print STDERR $self->{msg_prefix} . join(" ", @_) . "\n";
725    $self->_add_log_entry("ERROR: " . $self->{msg_prefix} . join(" ", @_) . "\n");
726    exit(0);    # #toolchain agreement: prevents configure stage to finish
727}
728
729=head2 msg_failure
730
731Prints "configure: " @_ to stderr and exits with exit code 0 (tells
732toolchain to stop here and report unsupported environment). Additional
733details are provides in config.log (probably more information in a
734later stage).
735
736=cut
737
738sub msg_failure
739{
740    my $self = shift->_get_instance();
741    print STDERR $self->{msg_prefix} . join(" ", @_) . "\n";
742    $self->_add_log_entry("FAILURE: " . $self->{msg_prefix} . join(" ", @_) . "\n");
743    exit(0);    # #toolchain agreement: prevents configure stage to finish
744}
745
746=head2 define_var( $name, $value [, $comment ] )
747
748Defines a check variable for later use in further checks or code to compile.
749Returns the value assigned value
750
751=cut
752
753sub define_var
754{
755    my $self = shift->_get_instance();
756    my ($name, $value, $comment) = @_;
757
758    defined($name) or croak("Need a name to add a define");
759    $self->{defines}->{$name} = [$value, $comment];
760    $value;
761}
762
763=head2 write_config_h( [$target] )
764
765Writes the defined constants into given target:
766
767  Config::AutoConf->write_config_h( "config.h" );
768
769=cut
770
771sub write_config_h
772{
773    my $self = shift->_get_instance();
774    my $tgt;
775
776    defined($_[0])
777      ? (
778        ref($_[0])
779        ? $tgt = $_[0]
780        : open($tgt, ">", $_[0])
781      )
782      : open($tgt, ">", "config.h");
783
784    my $conf_h = <<'EOC';
785/**
786 * Generated from Config::AutoConf
787 *
788 * Do not edit this file, all modifications will be lost,
789 * modify Makefile.PL or Build.PL instead.
790 *
791 * Inspired by GNU AutoConf.
792 *
793 * (c) 2011 Alberto Simoes & Jens Rehsack
794 */
795#ifndef __CONFIG_H__
796
797EOC
798
799    while (my ($defname, $defcnt) = each(%{$self->{defines}}))
800    {
801        if ($defcnt->[0])
802        {
803            defined $defcnt->[1] and $conf_h .= "/* " . $defcnt->[1] . " */\n";
804            $conf_h .= join(" ", "#define", $defname, $defcnt->[0]) . "\n";
805        }
806        else
807        {
808            defined $defcnt->[1] and $conf_h .= "/* " . $defcnt->[1] . " */\n";
809            $conf_h .= "/* " . join(" ", "#undef", $defname) . " */\n\n";
810        }
811    }
812    $conf_h .= "#endif /* ?__CONFIG_H__ */\n";
813
814    print {$tgt} $conf_h;
815
816    return;
817}
818
819=head2 push_lang(lang [, implementor ])
820
821Puts the current used language on the stack and uses specified language
822for subsequent operations until ending pop_lang call.
823
824=cut
825
826sub push_lang
827{
828    my $self = shift->_get_instance();
829
830    push @{$self->{lang_stack}}, [$self->{lang}];
831
832    $self->_set_language(@_);
833}
834
835=head2 pop_lang([ lang ])
836
837Pops the currently used language from the stack and restores previously used
838language. If I<lang> specified, it's asserted that the current used language
839equals to specified language (helps finding control flow bugs).
840
841=cut
842
843sub pop_lang
844{
845    my $self = shift->_get_instance();
846
847    scalar(@{$self->{lang_stack}}) > 0 or croak("Language stack empty");
848    defined($_[0])
849      and $self->{lang} ne $_[0]
850      and croak("pop_lang( $_[0] ) doesn't match language in use (" . $self->{lang} . ")");
851
852    $self->_set_language(@{pop @{$self->{lang_stack}}});
853}
854
855=head2 lang_build_program( prologue, body )
856
857Builds program for current chosen language. If no prologue is given
858(I<undef>), the default headers are used. If body is missing, default
859body is used.
860
861Typical call of
862
863  Config::AutoConf->lang_build_program( "const char hw[] = \"Hello, World\\n\";",
864                                        "fputs (hw, stdout);" )
865
866will create
867
868  const char hw[] = "Hello, World\n";
869
870  /* Override any gcc2 internal prototype to avoid an error.  */
871  #ifdef __cplusplus
872  extern "C" {
873  #endif
874
875  int
876  main (int argc, char **argv)
877  {
878    (void)argc;
879    (void)argv;
880    fputs (hw, stdout);;
881    return 0;
882  }
883
884  #ifdef __cplusplus
885  }
886  #endif
887
888=cut
889
890sub lang_build_program
891{
892    my ($self, $prologue, $body) = @_;
893    ref $self or $self = $self->_get_instance();
894
895    defined($prologue) or $prologue = $self->_default_includes();
896    defined($body)     or $body     = "";
897    $body = $self->_build_main($body);
898
899    $self->_fill_defines() . "\n$prologue\n\n$body\n";
900}
901
902sub _lang_prologue_func
903{
904    my ($self, $prologue, $function) = @_;
905    ref $self or $self = $self->_get_instance();
906
907    defined($prologue) or $prologue = $self->_default_includes();
908    $prologue .= <<"_ACEOF";
909/* Override any GCC internal prototype to avoid an error.
910   Use char because int might match the return type of a GCC
911   builtin and then its argument prototype would still apply.  */
912#ifdef __cplusplus
913extern "C" {
914#endif
915char $function ();
916#ifdef __cplusplus
917}
918#endif
919_ACEOF
920
921    return $prologue;
922}
923
924sub _lang_body_func
925{
926    my ($self, $function) = @_;
927    ref $self or $self = $self->_get_instance();
928
929    my $func_call = "return $function ();";
930    return $func_call;
931}
932
933=head2 lang_call( [prologue], function )
934
935Builds program which simply calls given function.
936When given, prologue is prepended otherwise, the default
937includes are used.
938
939=cut
940
941sub lang_call
942{
943    my ($self, $prologue, $function) = @_;
944    ref $self or $self = $self->_get_instance();
945
946    return $self->lang_build_program($self->_lang_prologue_func($prologue, $function), $self->_lang_body_func($function),);
947}
948
949sub _lang_prologue_builtin
950{
951    my ($self, $prologue, $builtin) = @_;
952    ref $self or $self = $self->_get_instance();
953
954    defined($prologue) or $prologue = $self->_default_includes();
955    $prologue .= <<"_ACEOF";
956#if !defined(__has_builtin)
957#undef $builtin
958/* Declare this builtin with the same prototype as __builtin_$builtin.
959  This removes a warning about conflicting types for built-in builtin $builtin */
960__typeof__(__builtin_$builtin) $builtin;
961__typeof__(__builtin_$builtin) *f = $builtin;
962#endif
963_ACEOF
964}
965
966sub _lang_body_builtin
967{
968    my ($self, $builtin) = @_;
969    ref $self or $self = $self->_get_instance();
970
971    my $body = <<"_ACEOF";
972#if !defined(__has_builtin)
973return f != $builtin;
974#else
975return __has_builtin($builtin);
976#endif
977_ACEOF
978    return $body;
979}
980
981=head2 lang_builtin( [prologue], builtin )
982
983Builds program which simply proves whether a builtin is known to
984language compiler.
985
986=cut
987
988sub lang_builtin
989{
990    my ($self, $prologue, $builtin) = @_;
991    ref $self or $self = $self->_get_instance();
992
993    return $self->lang_build_program($self->_lang_prologue_func($prologue, $builtin), $self->_lang_body_builtin($builtin),);
994}
995
996=head2 lang_build_bool_test (prologue, test, [@decls])
997
998Builds a static test which will fail to compile when test
999evaluates to false. If C<@decls> is given, it's prepended
1000before the test code at the variable definition place.
1001
1002=cut
1003
1004sub lang_build_bool_test
1005{
1006    my ($self, $prologue, $test, @decls) = @_;
1007    ref $self or $self = $self->_get_instance();
1008
1009    defined($test) or $test = "1";
1010    my $test_code = <<ACEOF;
1011  static int test_array [($test) ? 1 : -1 ];
1012  test_array [0] = 0
1013ACEOF
1014    if (@decls)
1015    {
1016        $test_code = join("\n", @decls, $test_code);
1017    }
1018    $self->lang_build_program($prologue, $test_code);
1019}
1020
1021=head2 push_includes
1022
1023Adds given list of directories to preprocessor/compiler
1024invocation. This is not proved to allow adding directories
1025which might be created during the build.
1026
1027=cut
1028
1029sub push_includes
1030{
1031    my ($self, @includes) = @_;
1032    ref $self or $self = $self->_get_instance();
1033
1034    push(@{$self->{extra_include_dirs}}, @includes);
1035
1036    return;
1037}
1038
1039=head2 push_preprocess_flags
1040
1041Adds given flags to the parameter list for preprocessor invocation.
1042
1043=cut
1044
1045sub push_preprocess_flags
1046{
1047    my ($self, @cpp_flags) = @_;
1048    ref $self or $self = $self->_get_instance();
1049
1050    push(@{$self->{extra_preprocess_flags}}, @cpp_flags);
1051
1052    return;
1053}
1054
1055=head2 push_compiler_flags
1056
1057Adds given flags to the parameter list for compiler invocation.
1058
1059=cut
1060
1061sub push_compiler_flags
1062{
1063    my ($self, @compiler_flags) = @_;
1064    ref $self or $self = $self->_get_instance();
1065    my $lang = $self->{lang};
1066
1067    if (scalar(@compiler_flags) && (ref($compiler_flags[-1]) eq "HASH"))
1068    {
1069        my $lang_opt = pop(@compiler_flags);
1070        defined($lang_opt->{lang}) or croak("Missing lang attribute in language options");
1071        $lang = $lang_opt->{lang};
1072        defined($self->{lang_supported}->{$lang}) or croak("Unsupported language '$lang'");
1073    }
1074
1075    push(@{$self->{extra_compile_flags}->{$lang}}, @compiler_flags);
1076
1077    return;
1078}
1079
1080=head2 push_libraries
1081
1082Adds given list of libraries to the parameter list for linker invocation.
1083
1084=cut
1085
1086sub push_libraries
1087{
1088    my ($self, @libs) = @_;
1089    ref $self or $self = $self->_get_instance();
1090
1091    push(@{$self->{extra_libs}}, @libs);
1092
1093    return;
1094}
1095
1096=head2 push_library_paths
1097
1098Adds given list of library paths to the parameter list for linker invocation.
1099
1100=cut
1101
1102sub push_library_paths
1103{
1104    my ($self, @libdirs) = @_;
1105    ref $self or $self = $self->_get_instance();
1106
1107    push(@{$self->{extra_lib_dirs}}, @libdirs);
1108
1109    return;
1110}
1111
1112=head2 push_link_flags
1113
1114Adds given flags to the parameter list for linker invocation.
1115
1116=cut
1117
1118sub push_link_flags
1119{
1120    my ($self, @link_flags) = @_;
1121    ref $self or $self = $self->_get_instance();
1122
1123    push(@{$self->{extra_link_flags}}, @link_flags);
1124
1125    return;
1126}
1127
1128=head2 compile_if_else( $src, \%options? )
1129
1130This function tries to compile specified code and returns a boolean value
1131containing check success state.
1132
1133If the very last parameter contains a hash reference, C<CODE> references
1134to I<action_on_true> or I<action_on_false> are executed, respectively.
1135
1136=cut
1137
1138sub compile_if_else
1139{
1140    my ($self, $src) = @_;
1141    ref $self or $self = $self->_get_instance();
1142
1143    my $options = {};
1144    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
1145
1146    my $builder = $self->_get_builder();
1147
1148    my ($fh, $filename) = tempfile(
1149        "testXXXXXX",
1150        SUFFIX => '.c',
1151        UNLINK => 0
1152    );
1153
1154    print {$fh} $src;
1155    close $fh;
1156
1157    my ($obj_file, $outbuf, $errbuf, $exception);
1158    ($outbuf, $errbuf) = capture
1159    {
1160        eval {
1161            $obj_file = $builder->compile(
1162                source               => $filename,
1163                include_dirs         => $self->{extra_include_dirs},
1164                extra_compiler_flags => $self->_get_extra_compiler_flags()
1165            );
1166        };
1167
1168        $exception = $@;
1169    };
1170
1171    unlink $filename;
1172    $obj_file and !-f $obj_file and undef $obj_file;
1173    unlink $obj_file if $obj_file;
1174
1175    if ($exception || !$obj_file)
1176    {
1177        $self->_add_log_lines("compile stage failed" . ($exception ? " - " . $exception : ""));
1178        $errbuf
1179          and $self->_add_log_lines($errbuf);
1180        $self->_add_log_lines("failing program is:\n" . $src);
1181        $outbuf
1182          and $self->_add_log_lines("stdout was :\n" . $outbuf);
1183
1184        $options->{action_on_false}
1185          and ref $options->{action_on_false} eq "CODE"
1186          and $options->{action_on_false}->();
1187
1188        return 0;
1189    }
1190
1191    $options->{action_on_true}
1192      and ref $options->{action_on_true} eq "CODE"
1193      and $options->{action_on_true}->();
1194
1195    1;
1196}
1197
1198=head2 link_if_else( $src, \%options? )
1199
1200This function tries to compile and link specified code and returns a boolean
1201value containing check success state.
1202
1203If the very last parameter contains a hash reference, C<CODE> references
1204to I<action_on_true> or I<action_on_false> are executed, respectively.
1205
1206=cut
1207
1208sub link_if_else
1209{
1210    my ($self, $src) = @_;
1211    ref $self or $self = $self->_get_instance();
1212    my $options = {};
1213    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
1214
1215    my $builder = $self->_get_builder();
1216
1217    my ($fh, $filename) = tempfile(
1218        "testXXXXXX",
1219        SUFFIX => '.c',
1220        UNLINK => 0
1221    );
1222
1223    print {$fh} $src;
1224    close $fh;
1225
1226    my ($obj_file, $outbuf, $errbuf, $exception);
1227    ($outbuf, $errbuf) = capture
1228    {
1229        eval {
1230            $obj_file = $builder->compile(
1231                source               => $filename,
1232                include_dirs         => $self->{extra_include_dirs},
1233                extra_compiler_flags => $self->_get_extra_compiler_flags()
1234            );
1235        };
1236
1237        $exception = $@;
1238    };
1239
1240    $obj_file and !-f $obj_file and undef $obj_file;
1241
1242    if ($exception || !$obj_file)
1243    {
1244        $self->_add_log_lines("compile stage failed" . ($exception ? " - " . $exception : ""));
1245        $errbuf
1246          and $self->_add_log_lines($errbuf);
1247        $self->_add_log_lines("failing program is:\n" . $src);
1248        $outbuf
1249          and $self->_add_log_lines("stdout was :\n" . $outbuf);
1250
1251        unlink $filename;
1252        unlink $obj_file if $obj_file;
1253
1254        $options->{action_on_false}
1255          and ref $options->{action_on_false} eq "CODE"
1256          and $options->{action_on_false}->();
1257
1258        return 0;
1259    }
1260
1261    my $exe_file;
1262    ($outbuf, $errbuf) = capture
1263    {
1264        eval {
1265            $exe_file = $builder->link_executable(
1266                objects            => $obj_file,
1267                extra_linker_flags => $self->_get_extra_linker_flags()
1268            );
1269        };
1270
1271        $exception = $@;
1272    };
1273
1274    $exe_file and !-f $exe_file and undef $exe_file;
1275
1276    unlink $filename;
1277    unlink $obj_file if $obj_file;
1278    unlink $exe_file if $exe_file;
1279
1280    if ($exception || !$exe_file)
1281    {
1282        $self->_add_log_lines("link stage failed" . ($exception ? " - " . $exception : ""));
1283        $errbuf
1284          and $self->_add_log_lines($errbuf);
1285        $self->_add_log_lines("failing program is:\n" . $src);
1286        $outbuf
1287          and $self->_add_log_lines("stdout was :\n" . $outbuf);
1288
1289        $options->{action_on_false}
1290          and ref $options->{action_on_false} eq "CODE"
1291          and $options->{action_on_false}->();
1292
1293        return 0;
1294    }
1295
1296    $options->{action_on_true}
1297      and ref $options->{action_on_true} eq "CODE"
1298      and $options->{action_on_true}->();
1299
1300    1;
1301}
1302
1303=head2 check_cached( $cache-key, $check-title, \&check-call, \%options? )
1304
1305Retrieves the result of a previous L</check_cached> invocation from
1306C<cache-key>, or (when called for the first time) populates the cache
1307by invoking C<\&check_call>.
1308
1309If the very last parameter contains a hash reference, C<CODE> references
1310to I<action_on_true> or I<action_on_false> are executed on B<every> call
1311to check_cached (not just the first cache-populating invocation), respectively.
1312
1313=cut
1314
1315sub check_cached
1316{
1317    my ($self, $cache_name, $message, $check_sub) = @_;
1318    ref $self or $self = $self->_get_instance();
1319    my $options = {};
1320    scalar @_ > 4 and ref $_[-1] eq "HASH" and $options = pop @_;
1321
1322    $self->msg_checking($message);
1323
1324    defined $ENV{$cache_name}
1325      and not defined $self->{cache}->{$cache_name}
1326      and $self->{cache}->{$cache_name} = $ENV{$cache_name};
1327
1328    my @cached_result;
1329    defined($self->{cache}->{$cache_name}) and push @cached_result, "(cached)";
1330    defined($self->{cache}->{$cache_name}) or $self->{cache}->{$cache_name} = $check_sub->();
1331
1332    $self->msg_result(@cached_result, $self->{cache}->{$cache_name});
1333
1334    $options->{action_on_true}
1335      and ref $options->{action_on_true} eq "CODE"
1336      and $self->{cache}->{$cache_name}
1337      and $options->{action_on_true}->();
1338
1339    $options->{action_on_false}
1340      and ref $options->{action_on_false} eq "CODE"
1341      and !$self->{cache}->{$cache_name}
1342      and $options->{action_on_false}->();
1343
1344    $self->{cache}->{$cache_name};
1345}
1346
1347=head2 cache_val
1348
1349This function returns the value of a previously check_cached call.
1350
1351=cut
1352
1353sub cache_val
1354{
1355    my ($self, $cache_name) = @_;
1356    ref $self or $self = $self->_get_instance();
1357    defined $self->{cache}->{$cache_name} or return;
1358    $self->{cache}->{$cache_name};
1359}
1360
1361=head2 check_decl( $symbol, \%options? )
1362
1363This method actually tests whether symbol is defined as a macro or can be
1364used as an r-value, not whether it is really declared, because it is much
1365safer to avoid introducing extra declarations when they are not needed.
1366In order to facilitate use of C++ and overloaded function declarations, it
1367is possible to specify function argument types in parentheses for types
1368which can be zero-initialized:
1369
1370  Config::AutoConf->check_decl("basename(char *)")
1371
1372This method caches its result in the C<ac_cv_decl_E<lt>set langE<gt>>_symbol
1373variable.
1374
1375If the very last parameter contains a hash reference, C<CODE> references
1376to I<action_on_true> or I<action_on_false> are executed, respectively.
1377When a I<prologue> exists in the optional hash at end, it will be favored
1378over C<default includes> (represented by L</_default_includes>). If any of
1379I<action_on_cache_true>, I<action_on_cache_false> is defined, both callbacks
1380are passed to L</check_cached> as I<action_on_true> or I<action_on_false> to
1381C<check_cached>, respectively.
1382
1383=cut
1384
1385sub check_decl
1386{
1387    my ($self, $symbol) = @_;
1388    $self = $self->_get_instance();
1389    my $options = {};
1390    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
1391
1392    defined($symbol)   or return croak("No symbol to check for");
1393    ref($symbol) eq "" or return croak("No symbol to check for");
1394    (my $sym_plain = $symbol) =~ s/ *\(.*//;
1395    my $sym_call = $symbol;
1396    $sym_call =~ s/\(/((/;
1397    $sym_call =~ s/\)/) 0)/;
1398    $sym_call =~ s/,/) 0, (/g;
1399
1400    my $cache_name = $self->_cache_name("decl", $self->{lang}, $symbol);
1401    my $check_sub  = sub {
1402
1403        my $body = <<ACEOF;
1404#ifndef $sym_plain
1405  (void) $sym_call;
1406#endif
1407ACEOF
1408        my $conftest = $self->lang_build_program($options->{prologue}, $body);
1409
1410        my $have_decl = $self->compile_if_else(
1411            $conftest,
1412            {
1413                ($options->{action_on_true}  ? (action_on_true  => $options->{action_on_true})  : ()),
1414                ($options->{action_on_false} ? (action_on_false => $options->{action_on_false}) : ())
1415            }
1416        );
1417
1418        $have_decl;
1419    };
1420
1421    $self->check_cached(
1422        $cache_name,
1423        "whether $symbol is declared",
1424        $check_sub,
1425        {
1426            ($options->{action_on_cache_true}  ? (action_on_true  => $options->{action_on_cache_true})  : ()),
1427            ($options->{action_on_cache_false} ? (action_on_false => $options->{action_on_cache_false}) : ())
1428        }
1429    );
1430}
1431
1432=head2 check_decls( symbols, \%options? )
1433
1434For each of the symbols (with optional function argument types for C++
1435overloads), run L<check_decl>.
1436
1437Contrary to B<GNU Autoconf>, this method does not declare C<HAVE_DECL_symbol>
1438macros for the resulting C<confdefs.h>, because it differs as C<check_decl>
1439between compiling languages.
1440
1441If the very last parameter contains a hash reference, C<CODE> references
1442to I<action_on_true> or I<action_on_false> are executed, respectively.
1443When a I<prologue> exists in the optional hash at end, it will be favored
1444over C<default includes> (represented by L</_default_includes>). If any of
1445I<action_on_cache_true>, I<action_on_cache_false> is defined, both callbacks
1446are passed to L</check_cached> as I<action_on_true> or I<action_on_false> to
1447C<check_cached>, respectively.
1448Given callbacks for I<action_on_symbol_true> or I<action_on_symbol_false> are
1449called for each symbol checked using L</check_decl> receiving the symbol as
1450first argument.
1451
1452=cut
1453
1454sub check_decls
1455{
1456    my ($self, $symbols) = @_;
1457    $self = $self->_get_instance();
1458    my $options = {};
1459    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
1460
1461    my %pass_options;
1462    defined $options->{prologue}              and $pass_options{prologue}              = $options->{prologue};
1463    defined $options->{action_on_cache_true}  and $pass_options{action_on_cache_true}  = $options->{action_on_cache_true};
1464    defined $options->{action_on_cache_false} and $pass_options{action_on_cache_false} = $options->{action_on_cache_false};
1465
1466    my $have_syms = 1;
1467    foreach my $symbol (@$symbols)
1468    {
1469        $have_syms &= $self->check_decl(
1470            $symbol,
1471            {
1472                %pass_options,
1473                (
1474                    $options->{action_on_symbol_true} && "CODE" eq ref $options->{action_on_symbol_true}
1475                    ? (action_on_true => sub { $options->{action_on_symbol_true}->($symbol) })
1476                    : ()
1477                ),
1478                (
1479                    $options->{action_on_symbol_false} && "CODE" eq ref $options->{action_on_symbol_false}
1480                    ? (action_on_false => sub { $options->{action_on_symbol_false}->($symbol) })
1481                    : ()
1482                ),
1483            }
1484        );
1485    }
1486
1487          $have_syms
1488      and $options->{action_on_true}
1489      and ref $options->{action_on_true} eq "CODE"
1490      and $options->{action_on_true}->();
1491
1492    $options->{action_on_false}
1493      and ref $options->{action_on_false} eq "CODE"
1494      and !$have_syms
1495      and $options->{action_on_false}->();
1496
1497    $have_syms;
1498}
1499
1500sub _have_func_define_name
1501{
1502    my $func      = $_[0];
1503    my $have_name = "HAVE_" . uc($func);
1504    $have_name =~ tr/_A-Za-z0-9/_/c;
1505    $have_name;
1506}
1507
1508=head2 check_func( $function, \%options? )
1509
1510This method actually tests whether I<$funcion> can be linked into a program
1511trying to call I<$function>.  This method caches its result in the
1512ac_cv_func_FUNCTION variable.
1513
1514If the very last parameter contains a hash reference, C<CODE> references
1515to I<action_on_true> or I<action_on_false> are executed, respectively.
1516If any of I<action_on_cache_true>, I<action_on_cache_false> is defined,
1517both callbacks are passed to L</check_cached> as I<action_on_true> or
1518I<action_on_false> to C<check_cached>, respectively.
1519
1520Returns: True if the function was found, false otherwise
1521
1522=cut
1523
1524sub check_func
1525{
1526    my ($self, $function) = @_;
1527    $self = $self->_get_instance();
1528    my $options = {};
1529    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
1530
1531    # Build the name of the cache variable.
1532    my $cache_name = $self->_cache_name('func', $function);
1533    # Wrap the actual check in a closure so that we can use check_cached.
1534    my $check_sub = sub {
1535        my $have_func = $self->link_if_else(
1536            $self->lang_call(q{}, $function),
1537            {
1538                ($options->{action_on_true}  ? (action_on_true  => $options->{action_on_true})  : ()),
1539                ($options->{action_on_false} ? (action_on_false => $options->{action_on_false}) : ())
1540            }
1541        );
1542        $have_func;
1543    };
1544
1545    # Run the check and cache the results.
1546    return $self->check_cached(
1547        $cache_name,
1548        "for $function",
1549        $check_sub,
1550        {
1551            action_on_true => sub {
1552                $self->define_var(
1553                    _have_func_define_name($function),
1554                    $self->cache_val($cache_name),
1555                    "Defined when $function is available"
1556                );
1557                $options->{action_on_cache_true}
1558                  and ref $options->{action_on_cache_true} eq "CODE"
1559                  and $options->{action_on_cache_true}->();
1560            },
1561            action_on_false => sub {
1562                $self->define_var(_have_func_define_name($function), undef, "Defined when $function is available");
1563                $options->{action_on_cache_false}
1564                  and ref $options->{action_on_cache_false} eq "CODE"
1565                  and $options->{action_on_cache_false}->();
1566            },
1567        }
1568    );
1569}
1570
1571=head2 check_funcs( \@functions-list, $action-if-true?, $action-if-false? )
1572
1573The same as check_func, but takes a list of functions in I<\@functions-list>
1574to look for and checks for each in turn. Define HAVE_FUNCTION for each
1575function that was found.
1576
1577If the very last parameter contains a hash reference, C<CODE> references
1578to I<action_on_true> or I<action_on_false> are executed, respectively.
1579If any of I<action_on_cache_true>, I<action_on_cache_false> is defined,
1580both callbacks are passed to L</check_cached> as I<action_on_true> or
1581I<action_on_false> to C<check_cached>, respectively.  Given callbacks
1582for I<action_on_function_true> or I<action_on_function_false> are called for
1583each symbol checked using L</check_func> receiving the symbol as first
1584argument.
1585
1586=cut
1587
1588sub check_funcs
1589{
1590    my ($self, $functions_ref) = @_;
1591    $self = $self->_get_instance();
1592
1593    my $options = {};
1594    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
1595
1596    my %pass_options;
1597    defined $options->{action_on_cache_true}  and $pass_options{action_on_cache_true}  = $options->{action_on_cache_true};
1598    defined $options->{action_on_cache_false} and $pass_options{action_on_cache_false} = $options->{action_on_cache_false};
1599
1600    # Go through the list of functions and call check_func for each one. We
1601    # generate new closures for the found and not-found functions that pass in
1602    # the relevant function name.
1603    my $have_funcs = 1;
1604    for my $function (@{$functions_ref})
1605    {
1606        # Build the code reference to run when a function was found. This defines
1607        # a HAVE_FUNCTION symbol, plus runs the current $action-if-true if there is
1608        # one.
1609        $pass_options{action_on_true} = sub {
1610            # Run the user-provided hook, if there is one.
1611            defined $options->{action_on_function_true}
1612              and ref $options->{action_on_function_true} eq "CODE"
1613              and $options->{action_on_function_true}->($function);
1614        };
1615
1616        defined $options->{action_on_function_false}
1617          and ref $options->{action_on_function_false} eq "CODE"
1618          and $pass_options{action_on_false} = sub { $options->{action_on_function_false}->($function); };
1619
1620        $have_funcs &= check_func($self, $function, \%pass_options);
1621    }
1622
1623          $have_funcs
1624      and $options->{action_on_true}
1625      and ref $options->{action_on_true} eq "CODE"
1626      and $options->{action_on_true}->();
1627
1628    $options->{action_on_false}
1629      and ref $options->{action_on_false} eq "CODE"
1630      and !$have_funcs
1631      and $options->{action_on_false}->();
1632
1633    return $have_funcs;
1634}
1635
1636=head2 check_builtin( $builtin, \%options? )
1637
1638This method actually tests whether I<$builtin> is a supported built-in
1639known by the compiler. Either, by giving us the type of the built-in or
1640by taking the value from C<__has_builtin>.  This method caches its result
1641in the ac_cv_builtin_FUNCTION variable.
1642
1643If the very last parameter contains a hash reference, C<CODE> references
1644to I<action_on_true> or I<action_on_false> are executed, respectively.
1645If any of I<action_on_cache_true>, I<action_on_cache_false> is defined,
1646both callbacks are passed to L</check_cached> as I<action_on_true> or
1647I<action_on_false> to C<check_cached>, respectively.
1648
1649Returns: True if the function was found, false otherwise
1650
1651=cut
1652
1653sub _have_builtin_define_name
1654{
1655    my $builtin   = $_[0];
1656    my $have_name = "HAVE_BUILTIN_" . uc($builtin);
1657    $have_name =~ tr/_A-Za-z0-9/_/c;
1658    $have_name;
1659}
1660
1661sub check_builtin
1662{
1663    my ($self, $builtin) = @_;
1664    $self = $self->_get_instance();
1665    my $options = {};
1666    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
1667
1668    # Build the name of the cache variable.
1669    my $cache_name = $self->_cache_name('builtin', $builtin);
1670    # Wrap the actual check in a closure so that we can use check_cached.
1671    my $check_sub = sub {
1672        my $have_builtin = $self->link_if_else(
1673            $self->lang_builtin(q{}, $builtin),
1674            {
1675                ($options->{action_on_true}  ? (action_on_true  => $options->{action_on_true})  : ()),
1676                ($options->{action_on_false} ? (action_on_false => $options->{action_on_false}) : ())
1677            }
1678        );
1679        $have_builtin;
1680    };
1681
1682    # Run the check and cache the results.
1683    return $self->check_cached(
1684        $cache_name,
1685        "for builtin $builtin",
1686        $check_sub,
1687        {
1688            action_on_true => sub {
1689                $self->define_var(
1690                    _have_builtin_define_name($builtin),
1691                    $self->cache_val($cache_name),
1692                    "Defined when builtin $builtin is available"
1693                );
1694                $options->{action_on_cache_true}
1695                  and ref $options->{action_on_cache_true} eq "CODE"
1696                  and $options->{action_on_cache_true}->();
1697            },
1698            action_on_false => sub {
1699                $self->define_var(_have_builtin_define_name($builtin), undef, "Defined when builtin $builtin is available");
1700                $options->{action_on_cache_false}
1701                  and ref $options->{action_on_cache_false} eq "CODE"
1702                  and $options->{action_on_cache_false}->();
1703            },
1704        }
1705    );
1706}
1707
1708sub _have_type_define_name
1709{
1710    my $type      = $_[0];
1711    my $have_name = "HAVE_" . uc($type);
1712    $have_name =~ tr/*/P/;
1713    $have_name =~ tr/_A-Za-z0-9/_/c;
1714    $have_name;
1715}
1716
1717=head2 check_type( $symbol, \%options? )
1718
1719Check whether type is defined. It may be a compiler builtin type or defined
1720by the includes.  In C, type must be a type-name, so that the expression
1721C<sizeof (type)> is valid (but C<sizeof ((type))> is not).
1722
1723If I<type> type is defined, preprocessor macro HAVE_I<type> (in all
1724capitals, with "*" replaced by "P" and spaces and dots replaced by
1725underscores) is defined.
1726
1727This method caches its result in the C<ac_cv_type_>type variable.
1728
1729If the very last parameter contains a hash reference, C<CODE> references
1730to I<action_on_true> or I<action_on_false> are executed, respectively.
1731When a I<prologue> exists in the optional hash at end, it will be favored
1732over C<default includes> (represented by L</_default_includes>). If any of
1733I<action_on_cache_true>, I<action_on_cache_false> is defined, both callbacks
1734are passed to L</check_cached> as I<action_on_true> or I<action_on_false> to
1735C<check_cached>, respectively.
1736
1737=cut
1738
1739sub check_type
1740{
1741    my ($self, $type) = @_;
1742    $self = $self->_get_instance();
1743    my $options = {};
1744    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
1745
1746    defined($type)   or return croak("No type to check for");
1747    ref($type) eq "" or return croak("No type to check for");
1748
1749    my $cache_name = $self->_cache_type_name("type", $type);
1750    my $check_sub  = sub {
1751
1752        my $body = <<ACEOF;
1753  if( sizeof ($type) )
1754    return 0;
1755ACEOF
1756        my $conftest = $self->lang_build_program($options->{prologue}, $body);
1757
1758        my $have_type = $self->compile_if_else(
1759            $conftest,
1760            {
1761                ($options->{action_on_true}  ? (action_on_true  => $options->{action_on_true})  : ()),
1762                ($options->{action_on_false} ? (action_on_false => $options->{action_on_false}) : ())
1763            }
1764        );
1765        $have_type;
1766    };
1767
1768    $self->check_cached(
1769        $cache_name,
1770        "for $type",
1771        $check_sub,
1772        {
1773            action_on_true => sub {
1774                $self->define_var(_have_type_define_name($type), $self->cache_val($cache_name),
1775                    "defined when $type is available");
1776                $options->{action_on_cache_true}
1777                  and ref $options->{action_on_cache_true} eq "CODE"
1778                  and $options->{action_on_cache_true}->();
1779            },
1780            action_on_false => sub {
1781                $self->define_var(_have_type_define_name($type), undef, "defined when $type is available");
1782                $options->{action_on_cache_false}
1783                  and ref $options->{action_on_cache_false} eq "CODE"
1784                  and $options->{action_on_cache_false}->();
1785            },
1786        }
1787    );
1788}
1789
1790=head2 check_types( \@type-list, \%options? )
1791
1792For each type in I<@type-list>, call L<check_type> is called to check
1793for type and return the accumulated result (accumulation op is binary and).
1794
1795If the very last parameter contains a hash reference, C<CODE> references
1796to I<action_on_true> or I<action_on_false> are executed, respectively.
1797When a I<prologue> exists in the optional hash at end, it will be favored
1798over C<default includes> (represented by L</_default_includes>). If any of
1799I<action_on_cache_true>, I<action_on_cache_false> is defined, both callbacks
1800are passed to L</check_cached> as I<action_on_true> or I<action_on_false> to
1801C<check_cached>, respectively.
1802Given callbacks for I<action_on_type_true> or I<action_on_type_false> are
1803called for each symbol checked using L</check_type> receiving the symbol as
1804first argument.
1805
1806=cut
1807
1808sub check_types
1809{
1810    my ($self, $types) = @_;
1811    $self = $self->_get_instance();
1812    my $options = {};
1813    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
1814
1815    my %pass_options;
1816    defined $options->{prologue}              and $pass_options{prologue}              = $options->{prologue};
1817    defined $options->{action_on_cache_true}  and $pass_options{action_on_cache_true}  = $options->{action_on_cache_true};
1818    defined $options->{action_on_cache_false} and $pass_options{action_on_cache_false} = $options->{action_on_cache_false};
1819
1820    my $have_types = 1;
1821    foreach my $type (@$types)
1822    {
1823        $have_types &= $self->check_type(
1824            $type,
1825            {
1826                %pass_options,
1827                (
1828                    $options->{action_on_type_true} && "CODE" eq ref $options->{action_on_type_true}
1829                    ? (action_on_true => sub { $options->{action_on_type_true}->($type) })
1830                    : ()
1831                ),
1832                (
1833                    $options->{action_on_type_false} && "CODE" eq ref $options->{action_on_type_false}
1834                    ? (action_on_false => sub { $options->{action_on_type_false}->($type) })
1835                    : ()
1836                ),
1837            }
1838        );
1839    }
1840
1841          $have_types
1842      and $options->{action_on_true}
1843      and ref $options->{action_on_true} eq "CODE"
1844      and $options->{action_on_true}->();
1845
1846    $options->{action_on_false}
1847      and ref $options->{action_on_false} eq "CODE"
1848      and !$have_types
1849      and $options->{action_on_false}->();
1850
1851    $have_types;
1852}
1853
1854sub _compute_int_compile
1855{
1856    my ($self, $expr, $prologue, @decls) = @_;
1857    $self = $self->_get_instance();
1858
1859    my ($body, $conftest, $compile_result);
1860
1861    my ($low, $mid, $high) = (0, 0, 0);
1862    if ($self->compile_if_else($self->lang_build_bool_test($prologue, "((long int)($expr)) >= 0", @decls)))
1863    {
1864        $low = $mid = 0;
1865        while (1)
1866        {
1867            if ($self->compile_if_else($self->lang_build_bool_test($prologue, "((long int)($expr)) <= $mid", @decls)))
1868            {
1869                $high = $mid;
1870                last;
1871            }
1872            $low = $mid + 1;
1873            # avoid overflow
1874            if ($low <= $mid)
1875            {
1876                $low = 0;
1877                last;
1878            }
1879            $mid = $low * 2;
1880        }
1881    }
1882    elsif ($self->compile_if_else($self->lang_build_bool_test($prologue, "((long int)($expr)) < 0", @decls)))
1883    {
1884        $high = $mid = -1;
1885        while (1)
1886        {
1887            if ($self->compile_if_else($self->lang_build_bool_test($prologue, "((long int)($expr)) >= $mid", @decls)))
1888            {
1889                $low = $mid;
1890                last;
1891            }
1892            $high = $mid - 1;
1893            # avoid overflow
1894            if ($mid < $high)
1895            {
1896                $high = 0;
1897                last;
1898            }
1899            $mid = $high * 2;
1900        }
1901    }
1902
1903    # perform binary search between $low and $high
1904    while ($low <= $high)
1905    {
1906        $mid = int(($high - $low) / 2 + $low);
1907        if ($self->compile_if_else($self->lang_build_bool_test($prologue, "((long int)($expr)) < $mid", @decls)))
1908        {
1909            $high = $mid - 1;
1910        }
1911        elsif ($self->compile_if_else($self->lang_build_bool_test($prologue, "((long int)($expr)) > $mid", @decls)))
1912        {
1913            $low = $mid + 1;
1914        }
1915        else
1916        {
1917            return $mid;
1918        }
1919    }
1920
1921    return;
1922}
1923
1924=head2 compute_int( $expression, @decls?, \%options )
1925
1926Returns the value of the integer I<expression>. The value should fit in an
1927initializer in a C variable of type signed long.  It should be possible
1928to evaluate the expression at compile-time. If no includes are specified,
1929the default includes are used.
1930
1931If the very last parameter contains a hash reference, C<CODE> references
1932to I<action_on_true> or I<action_on_false> are executed, respectively.
1933When a I<prologue> exists in the optional hash at end, it will be favored
1934over C<default includes> (represented by L</_default_includes>). If any of
1935I<action_on_cache_true>, I<action_on_cache_false> is defined, both callbacks
1936are passed to L</check_cached> as I<action_on_true> or I<action_on_false> to
1937C<check_cached>, respectively.
1938
1939=cut
1940
1941sub _expr_value_define_name
1942{
1943    my $expr      = $_[0];
1944    my $have_name = "EXPR_" . uc($expr);
1945    $have_name =~ tr/*/P/;
1946    $have_name =~ tr/_A-Za-z0-9/_/c;
1947    $have_name;
1948}
1949
1950sub compute_int
1951{
1952    my $options = {};
1953    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
1954    my ($self, $expr, @decls) = @_;
1955    $self = $self->_get_instance();
1956
1957    my $cache_name = $self->_cache_type_name("compute_int", $self->{lang}, $expr);
1958    my $check_sub  = sub {
1959        my $val = $self->_compute_int_compile($expr, $options->{prologue}, @decls);
1960
1961        defined $val
1962          and $options->{action_on_true}
1963          and ref $options->{action_on_true} eq "CODE"
1964          and $options->{action_on_true}->();
1965
1966        $options->{action_on_false}
1967          and ref $options->{action_on_false} eq "CODE"
1968          and !defined $val
1969          and $options->{action_on_false}->();
1970
1971        $val;
1972    };
1973
1974    $self->check_cached(
1975        $cache_name,
1976        "for compute result of ($expr)",
1977        $check_sub,
1978        {
1979            action_on_true => sub {
1980                $self->define_var(
1981                    _expr_value_define_name($expr),
1982                    $self->cache_val($cache_name),
1983                    "defined when ($expr) could computed"
1984                );
1985                $options->{action_on_cache_true}
1986                  and ref $options->{action_on_cache_true} eq "CODE"
1987                  and $options->{action_on_cache_true}->();
1988            },
1989            action_on_false => sub {
1990                $self->define_var(_expr_value_define_name($expr), undef, "defined when ($expr) could computed");
1991                $options->{action_on_cache_false}
1992                  and ref $options->{action_on_cache_false} eq "CODE"
1993                  and $options->{action_on_cache_false}->();
1994            },
1995        }
1996    );
1997}
1998
1999=head2 check_sizeof_type( $type, \%options? )
2000
2001Checks for the size of the specified type by compiling and define
2002C<SIZEOF_type> using the determined size.
2003
2004In opposition to GNU AutoConf, this method can determine size of structure
2005members, e.g.
2006
2007  $ac->check_sizeof_type( "SV.sv_refcnt", { prologue => $include_perl } );
2008  # or
2009  $ac->check_sizeof_type( "struct utmpx.ut_id", { prologue => "#include <utmpx.h>" } );
2010
2011This method caches its result in the C<ac_cv_sizeof_E<lt>set langE<gt>>_type variable.
2012
2013If the very last parameter contains a hash reference, C<CODE> references
2014to I<action_on_true> or I<action_on_false> are executed, respectively.
2015When a I<prologue> exists in the optional hash at end, it will be favored
2016over C<default includes> (represented by L</_default_includes>). If any of
2017I<action_on_cache_true>, I<action_on_cache_false> is defined, both callbacks
2018are passed to L</check_cached> as I<action_on_true> or I<action_on_false> to
2019C<check_cached>, respectively.
2020
2021=cut
2022
2023sub _sizeof_type_define_name
2024{
2025    my $type      = $_[0];
2026    my $have_name = "SIZEOF_" . uc($type);
2027    $have_name =~ tr/*/P/;
2028    $have_name =~ tr/_A-Za-z0-9/_/c;
2029    $have_name;
2030}
2031
2032sub check_sizeof_type
2033{
2034    my $options = {};
2035    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
2036    my ($self, $type) = @_;
2037    $self = $self->_get_instance();
2038    defined($type)   or return croak("No type to check for");
2039    ref($type) eq "" or return croak("No type to check for");
2040
2041    my $cache_name = $self->_cache_type_name("sizeof", $self->{lang}, $type);
2042    my $check_sub  = sub {
2043        my @decls;
2044        if ($type =~ m/^([^.]+)\.([^.]+)$/)
2045        {
2046            my $struct = $1;
2047            $type = "_ac_test_aggr.$2";
2048            my $decl = "static $struct _ac_test_aggr;";
2049            push(@decls, $decl);
2050        }
2051
2052        my $typesize = $self->_compute_int_compile("sizeof($type)", $options->{prologue}, @decls);
2053
2054              $typesize
2055          and $options->{action_on_true}
2056          and ref $options->{action_on_true} eq "CODE"
2057          and $options->{action_on_true}->();
2058
2059        $options->{action_on_false}
2060          and ref $options->{action_on_false} eq "CODE"
2061          and !$typesize
2062          and $options->{action_on_false}->();
2063
2064        $typesize;
2065    };
2066
2067    $self->check_cached(
2068        $cache_name,
2069        "for size of $type",
2070        $check_sub,
2071        {
2072            action_on_true => sub {
2073                $self->define_var(
2074                    _sizeof_type_define_name($type),
2075                    $self->cache_val($cache_name),
2076                    "defined when sizeof($type) is available"
2077                );
2078                $options->{action_on_cache_true}
2079                  and ref $options->{action_on_cache_true} eq "CODE"
2080                  and $options->{action_on_cache_true}->();
2081            },
2082            action_on_false => sub {
2083                $self->define_var(_sizeof_type_define_name($type), undef, "defined when sizeof($type) is available");
2084                $options->{action_on_cache_false}
2085                  and ref $options->{action_on_cache_false} eq "CODE"
2086                  and $options->{action_on_cache_false}->();
2087            },
2088        }
2089    );
2090}
2091
2092=head2 check_sizeof_types( type, \%options? )
2093
2094For each type L<check_sizeof_type> is called to check for size of type.
2095
2096If I<action-if-found> is given, it is additionally executed when all of the
2097sizes of the types could determined. If I<action-if-not-found> is given, it
2098is executed when one size of the types could not determined.
2099
2100If the very last parameter contains a hash reference, C<CODE> references
2101to I<action_on_true> or I<action_on_false> are executed, respectively.
2102When a I<prologue> exists in the optional hash at end, it will be favored
2103over C<default includes> (represented by L</_default_includes>). If any of
2104I<action_on_cache_true>, I<action_on_cache_false> is defined, both callbacks
2105are passed to L</check_cached> as I<action_on_true> or I<action_on_false> to
2106C<check_cached>, respectively.
2107Given callbacks for I<action_on_size_true> or I<action_on_size_false> are
2108called for each symbol checked using L</check_sizeof_type> receiving the
2109symbol as first argument.
2110
2111=cut
2112
2113sub check_sizeof_types
2114{
2115    my $options = {};
2116    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
2117    my ($self, $types) = @_;
2118    $self = $self->_get_instance();
2119
2120    my %pass_options;
2121    defined $options->{prologue}              and $pass_options{prologue}              = $options->{prologue};
2122    defined $options->{action_on_cache_true}  and $pass_options{action_on_cache_true}  = $options->{action_on_cache_true};
2123    defined $options->{action_on_cache_false} and $pass_options{action_on_cache_false} = $options->{action_on_cache_false};
2124
2125    my $have_sizes = 1;
2126    foreach my $type (@$types)
2127    {
2128        $have_sizes &= !!(
2129            $self->check_sizeof_type(
2130                $type,
2131                {
2132                    %pass_options,
2133                    (
2134                        $options->{action_on_size_true} && "CODE" eq ref $options->{action_on_size_true}
2135                        ? (action_on_true => sub { $options->{action_on_size_true}->($type) })
2136                        : ()
2137                    ),
2138                    (
2139                        $options->{action_on_size_false} && "CODE" eq ref $options->{action_on_size_false}
2140                        ? (action_on_false => sub { $options->{action_on_size_false}->($type) })
2141                        : ()
2142                    ),
2143                }
2144            )
2145        );
2146    }
2147
2148          $have_sizes
2149      and $options->{action_on_true}
2150      and ref $options->{action_on_true} eq "CODE"
2151      and $options->{action_on_true}->();
2152
2153    $options->{action_on_false}
2154      and ref $options->{action_on_false} eq "CODE"
2155      and !$have_sizes
2156      and $options->{action_on_false}->();
2157
2158    $have_sizes;
2159}
2160
2161sub _alignof_type_define_name
2162{
2163    my $type      = $_[0];
2164    my $have_name = "ALIGNOF_" . uc($type);
2165    $have_name =~ tr/*/P/;
2166    $have_name =~ tr/_A-Za-z0-9/_/c;
2167    $have_name;
2168}
2169
2170=head2 check_alignof_type( type, \%options? )
2171
2172Define ALIGNOF_type to be the alignment in bytes of type. I<type> must
2173be valid as a structure member declaration or I<type> must be a structure
2174member itself.
2175
2176This method caches its result in the C<ac_cv_alignof_E<lt>set langE<gt>>_type
2177variable, with I<*> mapped to C<p> and other characters not suitable for a
2178variable name mapped to underscores.
2179
2180If the very last parameter contains a hash reference, C<CODE> references
2181to I<action_on_true> or I<action_on_false> are executed, respectively.
2182When a I<prologue> exists in the optional hash at end, it will be favored
2183over C<default includes> (represented by L</_default_includes>). If any of
2184I<action_on_cache_true>, I<action_on_cache_false> is defined, both callbacks
2185are passed to L</check_cached> as I<action_on_true> or I<action_on_false> to
2186C<check_cached>, respectively.
2187
2188=cut
2189
2190sub check_alignof_type
2191{
2192    my $options = {};
2193    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
2194    my ($self, $type) = @_;
2195    $self = $self->_get_instance();
2196    defined($type)   or return croak("No type to check for");
2197    ref($type) eq "" or return croak("No type to check for");
2198
2199    my $cache_name = $self->_cache_type_name("alignof", $self->{lang}, $type);
2200    my $check_sub  = sub {
2201        my @decls = (
2202            "#ifndef offsetof",
2203            "# ifdef __ICC",
2204            "#  define offsetof(type,memb) ((size_t)(((char *)(&((type*)0)->memb)) - ((char *)0)))",
2205            "# else",  "#  define offsetof(type,memb) ((size_t)&((type*)0)->memb)",
2206            "# endif", "#endif"
2207        );
2208
2209        my ($struct, $memb);
2210        if ($type =~ m/^([^.]+)\.([^.]+)$/)
2211        {
2212            $struct = $1;
2213            $memb   = $2;
2214        }
2215        else
2216        {
2217            push(@decls, "typedef struct { char x; $type y; } ac__type_alignof_;");
2218            $struct = "ac__type_alignof_";
2219            $memb   = "y";
2220        }
2221
2222        my $typealign = $self->_compute_int_compile("offsetof($struct, $memb)", $options->{prologue}, @decls);
2223
2224              $typealign
2225          and $options->{action_on_true}
2226          and ref $options->{action_on_true} eq "CODE"
2227          and $options->{action_on_true}->();
2228
2229        $options->{action_on_false}
2230          and ref $options->{action_on_false} eq "CODE"
2231          and !$typealign
2232          and $options->{action_on_false}->();
2233
2234        $typealign;
2235    };
2236
2237    $self->check_cached(
2238        $cache_name,
2239        "for align of $type",
2240        $check_sub,
2241        {
2242            action_on_true => sub {
2243                $self->define_var(
2244                    _alignof_type_define_name($type),
2245                    $self->cache_val($cache_name),
2246                    "defined when alignof($type) is available"
2247                );
2248                $options->{action_on_cache_true}
2249                  and ref $options->{action_on_cache_true} eq "CODE"
2250                  and $options->{action_on_cache_true}->();
2251            },
2252            action_on_false => sub {
2253                $self->define_var(_alignof_type_define_name($type), undef, "defined when alignof($type) is available");
2254                $options->{action_on_cache_false}
2255                  and ref $options->{action_on_cache_false} eq "CODE"
2256                  and $options->{action_on_cache_false}->();
2257            },
2258        }
2259    );
2260}
2261
2262=head2 check_alignof_types (type, [action-if-found], [action-if-not-found], [prologue = default includes])
2263
2264For each type L<check_alignof_type> is called to check for align of type.
2265
2266If I<action-if-found> is given, it is additionally executed when all of the
2267aligns of the types could determined. If I<action-if-not-found> is given, it
2268is executed when one align of the types could not determined.
2269
2270If the very last parameter contains a hash reference, C<CODE> references
2271to I<action_on_true> or I<action_on_false> are executed, respectively.
2272When a I<prologue> exists in the optional hash at end, it will be favored
2273over C<default includes> (represented by L</_default_includes>). If any of
2274I<action_on_cache_true>, I<action_on_cache_false> is defined, both callbacks
2275are passed to L</check_cached> as I<action_on_true> or I<action_on_false> to
2276C<check_cached>, respectively.
2277Given callbacks for I<action_on_align_true> or I<action_on_align_false> are
2278called for each symbol checked using L</check_alignof_type> receiving the
2279symbol as first argument.
2280
2281=cut
2282
2283sub check_alignof_types
2284{
2285    my $options = {};
2286    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
2287    my ($self, $types) = @_;
2288    $self = $self->_get_instance();
2289
2290    my %pass_options;
2291    defined $options->{prologue}              and $pass_options{prologue}              = $options->{prologue};
2292    defined $options->{action_on_cache_true}  and $pass_options{action_on_cache_true}  = $options->{action_on_cache_true};
2293    defined $options->{action_on_cache_false} and $pass_options{action_on_cache_false} = $options->{action_on_cache_false};
2294
2295    my $have_aligns = 1;
2296    foreach my $type (@$types)
2297    {
2298        $have_aligns &= !!(
2299            $self->check_alignof_type(
2300                $type,
2301                {
2302                    %pass_options,
2303                    (
2304                        $options->{action_on_align_true} && "CODE" eq ref $options->{action_on_align_true}
2305                        ? (action_on_true => sub { $options->{action_on_align_true}->($type) })
2306                        : ()
2307                    ),
2308                    (
2309                        $options->{action_on_align_false} && "CODE" eq ref $options->{action_on_align_false}
2310                        ? (action_on_false => sub { $options->{action_on_align_false}->($type) })
2311                        : ()
2312                    ),
2313                }
2314            )
2315        );
2316    }
2317
2318          $have_aligns
2319      and $options->{action_on_true}
2320      and ref $options->{action_on_true} eq "CODE"
2321      and $options->{action_on_true}->();
2322
2323    $options->{action_on_false}
2324      and ref $options->{action_on_false} eq "CODE"
2325      and !$have_aligns
2326      and $options->{action_on_false}->();
2327
2328    $have_aligns;
2329}
2330
2331sub _have_member_define_name
2332{
2333    my $member    = $_[0];
2334    my $have_name = "HAVE_" . uc($member);
2335    $have_name =~ tr/_A-Za-z0-9/_/c;
2336    $have_name;
2337}
2338
2339=head2 check_member( member, \%options? )
2340
2341Check whether I<member> is in form of I<aggregate>.I<member> and
2342I<member> is a member of the I<aggregate> aggregate.
2343
2344which are used prior to the aggregate under test.
2345
2346  Config::AutoConf->check_member(
2347    "struct STRUCT_SV.sv_refcnt",
2348    {
2349      action_on_false => sub { Config::AutoConf->msg_failure( "sv_refcnt member required for struct STRUCT_SV" ); },
2350      prologue => "#include <EXTERN.h>\n#include <perl.h>"
2351    }
2352  );
2353
2354This function will return a true value (1) if the member is found.
2355
2356If I<aggregate> aggregate has I<member> member, preprocessor
2357macro HAVE_I<aggregate>_I<MEMBER> (in all capitals, with spaces
2358and dots replaced by underscores) is defined.
2359
2360This macro caches its result in the C<ac_cv_>aggr_member variable.
2361
2362If the very last parameter contains a hash reference, C<CODE> references
2363to I<action_on_true> or I<action_on_false> are executed, respectively.
2364When a I<prologue> exists in the optional hash at end, it will be favored
2365over C<default includes> (represented by L</_default_includes>). If any of
2366I<action_on_cache_true>, I<action_on_cache_false> is defined, both callbacks
2367are passed to L</check_cached> as I<action_on_true> or I<action_on_false> to
2368C<check_cached>, respectively.
2369
2370=cut
2371
2372sub check_member
2373{
2374    my $options = {};
2375    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
2376    my ($self, $member) = @_;
2377    $self = $self->_get_instance();
2378    defined($member)   or return croak("No type to check for");
2379    ref($member) eq "" or return croak("No type to check for");
2380
2381    $member =~ m/^([^.]+)\.([^.]+)$/ or return croak("check_member(\"struct foo.member\", \%options)");
2382    my $type = $1;
2383    $member = $2;
2384
2385    my $cache_name = $self->_cache_type_name("$type.$member");
2386    my $check_sub  = sub {
2387
2388        my $body = <<ACEOF;
2389  static $type check_aggr;
2390  if( check_aggr.$member )
2391    return 0;
2392ACEOF
2393        my $conftest    = $self->lang_build_program($options->{prologue}, $body);
2394        my $have_member = $self->compile_if_else($conftest);
2395
2396        unless ($have_member)
2397        {
2398            $body = <<ACEOF;
2399  static $type check_aggr;
2400  if( sizeof check_aggr.$member )
2401    return 0;
2402ACEOF
2403            $conftest    = $self->lang_build_program($options->{prologue}, $body);
2404            $have_member = $self->compile_if_else($conftest);
2405        }
2406
2407              $have_member
2408          and $options->{action_on_true}
2409          and ref $options->{action_on_true} eq "CODE"
2410          and $options->{action_on_true}->();
2411
2412        $options->{action_on_false}
2413          and ref $options->{action_on_false} eq "CODE"
2414          and $options->{action_on_false}->()
2415          unless $have_member;
2416
2417        $have_member;
2418    };
2419
2420    $self->check_cached(
2421        $cache_name,
2422        "for $type.$member",
2423        $check_sub,
2424        {
2425            action_on_true => sub {
2426                $self->define_var(
2427                    _have_member_define_name("$type.$member"),
2428                    $self->cache_val($cache_name),
2429                    "defined when $type.$member is available"
2430                );
2431                $options->{action_on_cache_true}
2432                  and ref $options->{action_on_cache_true} eq "CODE"
2433                  and $options->{action_on_cache_true}->();
2434            },
2435            action_on_false => sub {
2436                $self->define_var(_have_member_define_name("$type.$member"), undef, "defined when $type.$member is available");
2437                $options->{action_on_cache_false}
2438                  and ref $options->{action_on_cache_false} eq "CODE"
2439                  and $options->{action_on_cache_false}->();
2440            },
2441        }
2442    );
2443}
2444
2445=head2 check_members( members, \%options? )
2446
2447For each member L<check_member> is called to check for member of aggregate.
2448
2449This function will return a true value (1) if at least one member is found.
2450
2451If the very last parameter contains a hash reference, C<CODE> references
2452to I<action_on_true> or I<action_on_false> are executed, respectively.
2453When a I<prologue> exists in the optional hash at end, it will be favored
2454over C<default includes> (represented by L</_default_includes>). If any of
2455I<action_on_cache_true>, I<action_on_cache_false> is defined, both callbacks
2456are passed to L</check_cached> as I<action_on_true> or I<action_on_false> to
2457C<check_cached>, respectively.
2458Given callbacks for I<action_on_member_true> or I<action_on_member_false> are
2459called for each symbol checked using L</check_member> receiving the symbol as
2460first argument.
2461
2462=cut
2463
2464sub check_members
2465{
2466    my $options = {};
2467    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
2468    my ($self, $members) = @_;
2469    $self = $self->_get_instance();
2470
2471    my %pass_options;
2472    defined $options->{prologue}              and $pass_options{prologue}              = $options->{prologue};
2473    defined $options->{action_on_cache_true}  and $pass_options{action_on_cache_true}  = $options->{action_on_cache_true};
2474    defined $options->{action_on_cache_false} and $pass_options{action_on_cache_false} = $options->{action_on_cache_false};
2475
2476    my $have_members = 0;
2477    foreach my $member (@$members)
2478    {
2479        $have_members |= (
2480            $self->check_member(
2481                $member,
2482                {
2483                    %pass_options,
2484                    (
2485                        $options->{action_on_member_true} && "CODE" eq ref $options->{action_on_member_true}
2486                        ? (action_on_true => sub { $options->{action_on_member_true}->($member) })
2487                        : ()
2488                    ),
2489                    (
2490                        $options->{action_on_member_false} && "CODE" eq ref $options->{action_on_member_false}
2491                        ? (action_on_false => sub { $options->{action_on_member_false}->($member) })
2492                        : ()
2493                    ),
2494                }
2495            )
2496        );
2497    }
2498
2499          $have_members
2500      and $options->{action_on_true}
2501      and ref $options->{action_on_true} eq "CODE"
2502      and $options->{action_on_true}->();
2503
2504    $options->{action_on_false}
2505      and ref $options->{action_on_false} eq "CODE"
2506      and !$have_members
2507      and $options->{action_on_false}->();
2508
2509    $have_members;
2510}
2511
2512sub _have_header_define_name
2513{
2514    my $header    = $_[0];
2515    my $have_name = "HAVE_" . uc($header);
2516    $have_name =~ tr/_A-Za-z0-9/_/c;
2517    return $have_name;
2518}
2519
2520sub _check_header
2521{
2522    my $options = {};
2523    scalar @_ > 4 and ref $_[-1] eq "HASH" and $options = pop @_;
2524    my ($self, $header, $prologue, $body) = @_;
2525
2526    $prologue .= <<"_ACEOF";
2527    #include <$header>
2528_ACEOF
2529    my $conftest = $self->lang_build_program($prologue, $body);
2530
2531    $self->compile_if_else($conftest, $options);
2532}
2533
2534=head2 check_header( $header, \%options? )
2535
2536This function is used to check if a specific header file is present in
2537the system: if we detect it and if we can compile anything with that
2538header included. Note that normally you want to check for a header
2539first, and then check for the corresponding library (not all at once).
2540
2541The standard usage for this module is:
2542
2543  Config::AutoConf->check_header("ncurses.h");
2544
2545This function will return a true value (1) on success, and a false value
2546if the header is not present or not available for common usage.
2547
2548If the very last parameter contains a hash reference, C<CODE> references
2549to I<action_on_true> or I<action_on_false> are executed, respectively.
2550When a I<prologue> exists in the optional hash at end, it will be prepended
2551to the tested header. If any of I<action_on_cache_true>,
2552I<action_on_cache_false> is defined, both callbacks are passed to
2553L</check_cached> as I<action_on_true> or I<action_on_false> to
2554C<check_cached>, respectively.
2555
2556=cut
2557
2558sub check_header
2559{
2560    my $options = {};
2561    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
2562    my ($self, $header) = @_;
2563    $self = $self->_get_instance();
2564    defined($header)   or return croak("No type to check for");
2565    ref($header) eq "" or return croak("No type to check for");
2566
2567    return 0 unless $header;
2568    my $cache_name = $self->_cache_name($header);
2569    my $check_sub  = sub {
2570        my $prologue = defined $options->{prologue} ? $options->{prologue} : "";
2571
2572        my $have_header = $self->_check_header(
2573            $header,
2574            $prologue,
2575            "",
2576            {
2577                ($options->{action_on_true}  ? (action_on_true  => $options->{action_on_true})  : ()),
2578                ($options->{action_on_false} ? (action_on_false => $options->{action_on_false}) : ())
2579            }
2580        );
2581
2582        $have_header;
2583    };
2584
2585    $self->check_cached(
2586        $cache_name,
2587        "for $header",
2588        $check_sub,
2589        {
2590            action_on_true => sub {
2591                $self->define_var(
2592                    _have_header_define_name($header),
2593                    $self->cache_val($cache_name),
2594                    "defined when $header is available"
2595                );
2596                $options->{action_on_cache_true}
2597                  and ref $options->{action_on_cache_true} eq "CODE"
2598                  and $options->{action_on_cache_true}->();
2599            },
2600            action_on_false => sub {
2601                $self->define_var(_have_header_define_name($header), undef, "defined when $header is available");
2602                $options->{action_on_cache_false}
2603                  and ref $options->{action_on_cache_false} eq "CODE"
2604                  and $options->{action_on_cache_false}->();
2605            },
2606        }
2607    );
2608}
2609
2610=head2 check_headers
2611
2612This function uses check_header to check if a set of include files exist
2613in the system and can be included and compiled by the available compiler.
2614Returns the name of the first header file found.
2615
2616Passes an optional \%options hash to each L</check_header> call.
2617
2618=cut
2619
2620sub check_headers
2621{
2622    my $options = {};
2623    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
2624    my $self = shift->_get_instance();
2625    $self->check_header($_, $options) and return $_ for (@_);
2626    return;
2627}
2628
2629=head2 check_all_headers
2630
2631This function checks each given header for usability and returns true
2632when each header can be used -- otherwise false.
2633
2634If the very last parameter contains a hash reference, C<CODE> references
2635to I<action_on_true> or I<action_on_false> are executed, respectively.
2636Each of existing key/value pairs using I<prologue>, I<action_on_cache_true>
2637or I<action_on_cache_false> as key are passed-through to each call of
2638L</check_header>.
2639Given callbacks for I<action_on_header_true> or I<action_on_header_false> are
2640called for each symbol checked using L</check_header> receiving the symbol as
2641first argument.
2642
2643=cut
2644
2645sub check_all_headers
2646{
2647    my $options = {};
2648    scalar @_ > 2 and ref $_[-1] eq "HASH" and $options = pop @_;
2649    my $self = shift->_get_instance();
2650    @_ or return;
2651
2652    my %pass_options;
2653    defined $options->{prologue}              and $pass_options{prologue}              = $options->{prologue};
2654    defined $options->{action_on_cache_true}  and $pass_options{action_on_cache_true}  = $options->{action_on_cache_true};
2655    defined $options->{action_on_cache_false} and $pass_options{action_on_cache_false} = $options->{action_on_cache_false};
2656
2657    my $all_headers = 1;
2658    foreach my $header (@_)
2659    {
2660        $all_headers &= $self->check_header(
2661            $header,
2662            {
2663                %pass_options,
2664                (
2665                    $options->{action_on_header_true} && "CODE" eq ref $options->{action_on_header_true}
2666                    ? (action_on_true => sub { $options->{action_on_header_true}->($header) })
2667                    : ()
2668                ),
2669                (
2670                    $options->{action_on_header_false} && "CODE" eq ref $options->{action_on_header_false}
2671                    ? (action_on_false => sub { $options->{action_on_header_false}->($header) })
2672                    : ()
2673                ),
2674            }
2675        );
2676    }
2677
2678          $all_headers
2679      and $options->{action_on_true}
2680      and ref $options->{action_on_true} eq "CODE"
2681      and $options->{action_on_true}->();
2682
2683    $options->{action_on_false}
2684      and ref $options->{action_on_false} eq "CODE"
2685      and !$all_headers
2686      and $options->{action_on_false}->();
2687
2688    $all_headers;
2689}
2690
2691=head2 check_stdc_headers
2692
2693Checks for standard C89 headers, namely stdlib.h, stdarg.h, string.h and float.h.
2694If those are found, additional all remaining C89 headers are checked: assert.h,
2695ctype.h, errno.h, limits.h, locale.h, math.h, setjmp.h, signal.h, stddef.h,
2696stdio.h and time.h.
2697
2698Returns a false value if it fails.
2699
2700Passes an optional \%options hash to each L</check_all_headers> call.
2701
2702=cut
2703
2704my @ansi_c_headers = qw(stdlib stdarg string float assert ctype errno limits locale math setjmp signal stddef stdio time);
2705
2706sub check_stdc_headers
2707{
2708    my $options = {};
2709    scalar @_ > 1 and ref $_[-1] eq "HASH" and $options = pop @_;
2710    my $self = shift->_get_instance();
2711
2712    # XXX for C++ the map should look like "c${_}" ...
2713    my @c_ansi_c_headers = map { "${_}.h" } @ansi_c_headers;
2714    my $rc               = $self->check_all_headers(@c_ansi_c_headers, $options);
2715    $rc and $self->define_var("STDC_HEADERS", 1, "Define to 1 if you have the ANSI C header files.");
2716    $rc;
2717}
2718
2719=head2 check_default_headers
2720
2721This function checks for some default headers, the std c89 headers and
2722sys/types.h, sys/stat.h, memory.h, strings.h, inttypes.h, stdint.h and unistd.h
2723
2724Passes an optional \%options hash to each L</check_all_headers> call.
2725
2726=cut
2727
2728sub check_default_headers
2729{
2730    my $options = {};
2731    scalar @_ > 1 and ref $_[-1] eq "HASH" and $options = pop @_;
2732    my $self = shift->_get_instance();
2733    $self->check_stdc_headers($options)
2734      and $self->check_all_headers(qw(sys/types.h sys/stat.h memory.h strings.h inttypes.h stdint.h unistd.h), $options);
2735}
2736
2737=head2 check_dirent_header
2738
2739Check for the following header files. For the first one that is found and
2740defines 'DIR', define the listed C preprocessor macro:
2741
2742  dirent.h      HAVE_DIRENT_H
2743  sys/ndir.h    HAVE_SYS_NDIR_H
2744  sys/dir.h     HAVE_SYS_DIR_H
2745  ndir.h        HAVE_NDIR_H
2746
2747The directory-library declarations in your source code should look
2748something like the following:
2749
2750  #include <sys/types.h>
2751  #ifdef HAVE_DIRENT_H
2752  # include <dirent.h>
2753  # define NAMLEN(dirent) strlen ((dirent)->d_name)
2754  #else
2755  # define dirent direct
2756  # define NAMLEN(dirent) ((dirent)->d_namlen)
2757  # ifdef HAVE_SYS_NDIR_H
2758  #  include <sys/ndir.h>
2759  # endif
2760  # ifdef HAVE_SYS_DIR_H
2761  #  include <sys/dir.h>
2762  # endif
2763  # ifdef HAVE_NDIR_H
2764  #  include <ndir.h>
2765  # endif
2766  #endif
2767
2768Using the above declarations, the program would declare variables to be of
2769type C<struct dirent>, not C<struct direct>, and would access the length
2770of a directory entry name by passing a pointer to a C<struct dirent> to
2771the C<NAMLEN> macro.
2772
2773For the found header, the macro HAVE_DIRENT_IN_${header} is defined.
2774
2775This method might be obsolescent, as all current systems with directory
2776libraries have C<< E<lt>dirent.hE<gt> >>. Programs supporting only newer OS
2777might not need to use this method.
2778
2779If the very last parameter contains a hash reference, C<CODE> references
2780to I<action_on_true> or I<action_on_false> are executed, respectively.
2781Each of existing key/value pairs using I<prologue>, I<action_on_header_true>
2782(as I<action_on_true> having the name of the tested header as first argument)
2783or I<action_on_header_false> (as I<action_on_false> having the name of the
2784tested header as first argument) as key are passed-through to each call of
2785L</_check_header>.
2786Given callbacks for I<action_on_cache_true> or I<action_on_cache_false> are
2787passed to the call of L</check_cached>.
2788
2789=cut
2790
2791sub _have_dirent_header_define_name
2792{
2793    my $header    = $_[0];
2794    my $have_name = "HAVE_DIRENT_IN_" . uc($header);
2795    $have_name =~ tr/_A-Za-z0-9/_/c;
2796    return $have_name;
2797}
2798
2799sub check_dirent_header
2800{
2801    my $options = {};
2802    scalar @_ > 1 and ref $_[-1] eq "HASH" and $options = pop @_;
2803    my $self = shift->_get_instance();
2804
2805    my %pass_options;
2806    defined $options->{prologue} and $pass_options{prologue} = $options->{prologue};
2807
2808    my $have_dirent;
2809    foreach my $header (qw(dirent.h sys/ndir.h sys/dir.h ndir.h))
2810    {
2811        if ($self->check_header($header))
2812        {
2813            my $cache_name = $self->_cache_name("dirent", $header);
2814            my $check_sub  = sub {
2815                my $have_dirent;
2816                $have_dirent = $self->_check_header(
2817                    $header,
2818                    "#include <sys/types.h>\n",
2819                    "if ((DIR *) 0) { return 0; }",
2820                    {
2821                        %pass_options,
2822                        (
2823                            $options->{action_on_header_true} && "CODE" eq ref $options->{action_on_header_true}
2824                            ? (action_on_true => sub { $options->{action_on_header_true}->($header) })
2825                            : ()
2826                        ),
2827                        (
2828                            $options->{action_on_header_false} && "CODE" eq ref $options->{action_on_header_false}
2829                            ? (action_on_false => sub { $options->{action_on_header_false}->($header) })
2830                            : ()
2831                        ),
2832                    }
2833                );
2834            };
2835
2836            $have_dirent = $self->check_cached(
2837                $cache_name,
2838                "for header defining DIR *",
2839                $check_sub,
2840                {
2841                    action_on_true => sub {
2842                        $self->define_var(
2843                            _have_dirent_header_define_name($header),
2844                            $self->cache_val($cache_name),
2845                            "defined when $header is available"
2846                        );
2847                        $options->{action_on_cache_true}
2848                          and ref $options->{action_on_cache_true} eq "CODE"
2849                          and $options->{action_on_cache_true}->();
2850                    },
2851                    action_on_false => sub {
2852                        $self->define_var(_have_dirent_header_define_name($header), undef, "defined when $header is available");
2853                        $options->{action_on_cache_false}
2854                          and ref $options->{action_on_cache_false} eq "CODE"
2855                          and $options->{action_on_cache_false}->();
2856                    },
2857                }
2858            );
2859
2860            $have_dirent and $have_dirent = $header and last;
2861        }
2862    }
2863
2864          $have_dirent
2865      and $options->{action_on_true}
2866      and ref $options->{action_on_true} eq "CODE"
2867      and $options->{action_on_true}->();
2868
2869    $options->{action_on_false}
2870      and ref $options->{action_on_false} eq "CODE"
2871      and !$have_dirent
2872      and $options->{action_on_false}->();
2873
2874    $have_dirent;
2875}
2876
2877=head2 _check_perlapi_program
2878
2879This method provides the program source which is suitable to do basic
2880compile/link tests to prove perl development environment.
2881
2882=cut
2883
2884sub _check_perlapi_program
2885{
2886    my $self = shift;
2887
2888    my $includes        = $self->_default_includes_with_perl();
2889    my $perl_check_body = <<'EOB';
2890  I32 rc;
2891  SV *foo = newSVpv("Perl rocks", 11);
2892  rc = SvCUR(foo);
2893EOB
2894    $self->lang_build_program($includes, $perl_check_body);
2895}
2896
2897=head2 _check_compile_perlapi
2898
2899This method can be used from other checks to prove whether we have a perl
2900development environment or not (perl.h, reasonable basic checks - types, etc.)
2901
2902=cut
2903
2904sub _check_compile_perlapi
2905{
2906    my $self = shift;
2907
2908    my $conftest = $self->_check_perlapi_program();
2909    $self->compile_if_else($conftest);
2910}
2911
2912=head2 check_compile_perlapi
2913
2914This method can be used from other checks to prove whether we have a perl
2915development environment or not (perl.h, reasonable basic checks - types, etc.)
2916
2917=cut
2918
2919sub check_compile_perlapi
2920{
2921    my $self       = shift->_get_instance;
2922    my $cache_name = $self->_cache_name(qw(compile perlapi));
2923
2924    $self->check_cached($cache_name, "whether perlapi is accessible", sub { $self->_check_compile_perlapi });
2925}
2926
2927=head2 check_compile_perlapi_or_die
2928
2929Dies when not being able to compile using the Perl API
2930
2931=cut
2932
2933sub check_compile_perlapi_or_die
2934{
2935    my $self = shift;
2936    $self->check_compile_perlapi(@_) or $self->msg_error("Cannot use Perl API - giving up");
2937}
2938
2939=head2 check_linkable_xs_so
2940
2941Checks whether a dynamic loadable object containing an XS module can be
2942linked or not. Due the nature of the beast, this test currently always
2943succeed.
2944
2945=cut
2946
2947sub check_linkable_xs_so { 1 }
2948
2949=head2 check_linkable_xs_so_or_die
2950
2951Dies when L</check_linkable_xs_so> fails.
2952
2953=cut
2954
2955sub check_linkable_xs_so_or_die
2956{
2957    my $self = shift;
2958    $self->check_linkable_xs_so(@_) or $self->msg_error("Cannot link XS dynamic loadable - giving up");
2959}
2960
2961=head2 check_loadable_xs_so
2962
2963Checks whether a dynamic loadable object containing an XS module can be
2964loaded or not. Due the nature of the beast, this test currently always
2965succeed.
2966
2967=cut
2968
2969sub check_loadable_xs_so { 1 }
2970
2971=head2 check_loadable_xs_so_or_die
2972
2973Dies when L</check_loadable_xs_so> fails.
2974
2975=cut
2976
2977sub check_loadable_xs_so_or_die
2978{
2979    my $self = shift;
2980    $self->check_loadable_xs_so(@_) or $self->msg_error("Cannot load XS dynamic loadable - giving up");
2981}
2982
2983=head2 _check_link_perlapi
2984
2985This method can be used from other checks to prove whether we have a perl
2986development environment including a suitable libperl or not (perl.h,
2987reasonable basic checks - types, etc.)
2988
2989Caller must ensure that the linker flags are set appropriate (C<-lperl>
2990or similar).
2991
2992=cut
2993
2994sub _check_link_perlapi
2995{
2996    my $self = shift;
2997
2998    my $conftest              = $self->_check_perlapi_program();
2999    my @save_libs             = @{$self->{extra_libs}};
3000    my @save_extra_link_flags = @{$self->{extra_link_flags}};
3001
3002    my $libperl = $Config{libperl};
3003    $libperl =~ s/^lib//;
3004    $libperl =~ s/\.[^\.]*$//;
3005
3006    push @{$self->{extra_link_flags}}, "-L" . File::Spec->catdir($Config{installarchlib}, "CORE");
3007    push @{$self->{extra_libs}},       "$libperl";
3008    if ($Config{perllibs})
3009    {
3010        foreach my $perllib (split(" ", $Config{perllibs}))
3011        {
3012            $perllib =~ m/^\-l(\w+)$/ and push @{$self->{extra_libs}}, "$1" and next;
3013            push @{$self->{extra_link_flags}}, $perllib;
3014        }
3015    }
3016
3017    my $have_libperl = $self->link_if_else($conftest);
3018
3019    $have_libperl or $self->{extra_libs}       = [@save_libs];
3020    $have_libperl or $self->{extra_link_flags} = [@save_extra_link_flags];
3021
3022    $have_libperl;
3023}
3024
3025=head2 check_link_perlapi
3026
3027This method can be used from other checks to prove whether we have a perl
3028development environment or not (perl.h, libperl.la, reasonable basic
3029checks - types, etc.)
3030
3031=cut
3032
3033sub check_link_perlapi
3034{
3035    my $self       = shift->_get_instance;
3036    my $cache_name = $self->_cache_name(qw(link perlapi));
3037
3038    $self->check_cached($cache_name, "whether perlapi is linkable", sub { $self->_check_link_perlapi });
3039}
3040
3041sub _have_lib_define_name
3042{
3043    my $lib       = $_[0];
3044    my $have_name = "HAVE_LIB" . uc($lib);
3045    $have_name =~ tr/_A-Za-z0-9/_/c;
3046    return $have_name;
3047}
3048
3049=head2 check_lib( lib, func, @other-libs?, \%options? )
3050
3051This function is used to check if a specific library includes some
3052function. Call it with the library name (without the lib portion), and
3053the name of the function you want to test:
3054
3055  Config::AutoConf->check_lib("z", "gzopen");
3056
3057It returns 1 if the function exist, 0 otherwise.
3058
3059In case of function found, the HAVE_LIBlibrary (all in capitals)
3060preprocessor macro is defined with 1 and $lib together with @other_libs
3061are added to the list of libraries to link with.
3062
3063If linking with library results in unresolved symbols that would be
3064resolved by linking with additional libraries, give those libraries
3065as the I<other-libs> argument: e.g., C<[qw(Xt X11)]>.
3066Otherwise, this routine may fail to detect that library is present,
3067because linking the test program can fail with unresolved symbols.
3068The other-libraries argument should be limited to cases where it is
3069desirable to test for one library in the presence of another that
3070is not already in LIBS.
3071
3072This method caches its result in the C<ac_cv_lib_>lib_func variable.
3073
3074If the very last parameter contains a hash reference, C<CODE> references
3075to I<action_on_true> or I<action_on_false> are executed, respectively.
3076If any of I<action_on_cache_true>, I<action_on_cache_false> is defined,
3077both callbacks are passed to L</check_cached> as I<action_on_true> or
3078I<action_on_false> to C<check_cached>, respectively.
3079
3080It's recommended to use L<search_libs> instead of check_lib these days.
3081
3082=cut
3083
3084sub check_lib
3085{
3086    my $options = {};
3087    scalar @_ > 1 and ref $_[-1] eq "HASH" and $options = pop @_;
3088    my $self = shift->_get_instance();
3089    my ($lib, $func, @other_libs) = @_;
3090
3091    return 0 unless $lib and $func;
3092
3093    scalar(@other_libs) == 1
3094      and ref($other_libs[0]) eq "ARRAY"
3095      and @other_libs = @{$other_libs[0]};
3096
3097    my $cache_name = $self->_cache_name("lib", $lib, $func);
3098    my $check_sub  = sub {
3099        my $conftest = $self->lang_call("", $func);
3100
3101        my @save_libs = @{$self->{extra_libs}};
3102        push(@{$self->{extra_libs}}, $lib, @other_libs);
3103        my $have_lib = $self->link_if_else(
3104            $conftest,
3105            {
3106                ($options->{action_on_true}  ? (action_on_true  => $options->{action_on_true})  : ()),
3107                ($options->{action_on_false} ? (action_on_false => $options->{action_on_false}) : ())
3108            }
3109        );
3110        $self->{extra_libs} = [@save_libs];
3111
3112        $have_lib;
3113    };
3114
3115    $self->check_cached(
3116        $cache_name,
3117        "for $func in -l$lib",
3118        $check_sub,
3119        {
3120            action_on_true => sub {
3121                $self->define_var(
3122                    _have_lib_define_name($lib),
3123                    $self->cache_val($cache_name),
3124                    "defined when library $lib is available"
3125                );
3126                push(@{$self->{extra_libs}}, $lib, @other_libs);
3127                $options->{action_on_cache_true}
3128                  and ref $options->{action_on_cache_true} eq "CODE"
3129                  and $options->{action_on_cache_true}->();
3130            },
3131            action_on_false => sub {
3132                $self->define_var(_have_lib_define_name($lib), undef, "defined when library $lib is available");
3133                $options->{action_on_cache_false}
3134                  and ref $options->{action_on_cache_false} eq "CODE"
3135                  and $options->{action_on_cache_false}->();
3136            },
3137        }
3138    );
3139}
3140
3141=head2 search_libs( function, search-libs, @other-libs?, @extra_link_flags?, \%options? )
3142
3143    Config::AutoConf->search_libs("gethostent", "nsl", [qw(socket net)], {
3144        action_on_true => sub { ... }
3145    });
3146    Config::AutoConf->search_libs("log4cplus_initialize", ["log4cplus"],
3147        [[qw(stdc++)], [qw(stdc++ unwind)]],
3148        [qw(-pthread -thread)]
3149    );
3150
3151Search for a library defining function if it's not already available.
3152This equates to calling
3153
3154    Config::AutoConf->link_if_else(
3155        Config::AutoConf->lang_call( "", "$function" ) );
3156
3157first with no libraries, then for each library listed in search-libs.
3158I<search-libs> must be specified as an array reference to avoid
3159confusion in argument order.
3160
3161Prepend -llibrary to LIBS for the first library found to contain function.
3162
3163If linking with library results in unresolved symbols that would be
3164resolved by linking with additional libraries, give those libraries as
3165the I<other-libraries> argument: e.g., C<[qw(Xt X11)]> or C<[qw(intl),
3166qw(intl iconv)]>. Otherwise, this method fails to detect that function
3167is present, because linking the test program always fails with unresolved
3168symbols.
3169
3170The result of this test is cached in the ac_cv_search_function variable
3171as "none required" if function is already available, as C<0> if no
3172library containing function was found, otherwise as the -llibrary option
3173that needs to be prepended to LIBS.
3174
3175If the very last parameter contains a hash reference, C<CODE> references
3176to I<action_on_true> or I<action_on_false> are executed, respectively.
3177If any of I<action_on_cache_true>, I<action_on_cache_false> is defined,
3178both callbacks are passed to L</check_cached> as I<action_on_true> or
3179I<action_on_false> to C<check_cached>, respectively.  Given callbacks
3180for I<action_on_lib_true> or I<action_on_lib_false> are called for
3181each library checked using L</link_if_else> receiving the library as
3182first argument and all C<@other_libs> subsequently.
3183
3184=cut
3185
3186sub search_libs
3187{
3188    my $options = {};
3189    scalar @_ > 1 and ref $_[-1] eq "HASH" and $options = pop @_;
3190    my $self = shift->_get_instance();
3191    my ($func, $libs, @other_libs, @other_link_flags) = @_;
3192
3193    (defined($libs) and "ARRAY" eq ref($libs) and scalar(@{$libs}) > 0)
3194      or return 0;    # XXX would prefer croak
3195    return 0 unless $func;
3196
3197    scalar(@other_libs) == 1
3198      and ref($other_libs[0]) eq "ARRAY"
3199      and @other_libs = @{$other_libs[0]};
3200
3201    scalar(@other_link_flags) == 1
3202      and ref($other_link_flags[0]) eq "ARRAY"
3203      and @other_link_flags = @{$other_link_flags[0]};
3204
3205    my $cache_name = $self->_cache_name("search", $func);
3206    my $check_sub  = sub {
3207        my $conftest = $self->lang_call("", $func);
3208
3209        my @save_libs  = @{$self->{extra_libs}};
3210        my @save_extra = @{$self->{extra_link_flags}};
3211        my $have_lib   = 0;
3212
3213        my $if_else_sub = sub {
3214            my ($libstest, @other) = @_;
3215            defined($libstest) and unshift(@{$self->{extra_libs}}, $libstest, @other);
3216            $self->link_if_else(
3217                $conftest,
3218                {
3219                    (
3220                        $options->{action_on_lib_true} && "CODE" eq ref $options->{action_on_lib_true}
3221                        ? (action_on_true => sub { $options->{action_on_lib_true}->($libstest, @other, @_) })
3222                        : ()
3223                    ),
3224                    (
3225                        $options->{action_on_lib_false} && "CODE" eq ref $options->{action_on_lib_false}
3226                        ? (action_on_false => sub { $options->{action_on_lib_false}->($libstest, @other, @_) })
3227                        : ()
3228                    ),
3229                }
3230            ) and ($have_lib = defined($libstest) ? $libstest : "none required");
3231        };
3232
3233      LIBTEST:
3234        foreach my $libstest (undef, @$libs)
3235        {
3236            foreach my $linkextra (undef, @other_link_flags)
3237            {
3238                # XXX would local work on array refs? can we omit @save_libs?
3239                $self->{extra_libs}       = [@save_libs];
3240                $self->{extra_link_flags} = [@save_extra];
3241                if (defined $libstest and scalar(@other_libs) > 1 and ref($other_libs[0]) eq "ARRAY")
3242                {
3243                    foreach my $ol (@other_libs)
3244                    {
3245                        $if_else_sub->($libstest, @{$ol}) and last LIBTEST;
3246                    }
3247                }
3248                else
3249                {
3250                    $if_else_sub->($libstest, @other_libs) and last LIBTEST;
3251                }
3252            }
3253        }
3254
3255        $self->{extra_libs} = [@save_libs];
3256
3257              $have_lib
3258          and $options->{action_on_true}
3259          and ref $options->{action_on_true} eq "CODE"
3260          and $options->{action_on_true}->();
3261
3262        $options->{action_on_false}
3263          and ref $options->{action_on_false} eq "CODE"
3264          and !$have_lib
3265          and $options->{action_on_false}->();
3266
3267        $have_lib;
3268    };
3269
3270    return $self->check_cached(
3271        $cache_name,
3272        "for library containing $func",
3273        $check_sub,
3274        {
3275            action_on_true => sub {
3276                $self->cache_val($cache_name) eq "none required"
3277                  or unshift(@{$self->{extra_libs}}, $self->cache_val($cache_name));
3278
3279                $options->{action_on_cache_true}
3280                  and ref $options->{action_on_cache_true} eq "CODE"
3281                  and $options->{action_on_cache_true}->();
3282            },
3283            ($options->{action_on_cache_false} ? (action_on_false => $options->{action_on_cache_false}) : ())
3284        }
3285    );
3286}
3287
3288sub _check_lm_funcs { qw(log2 pow log10 log exp sqrt) }
3289
3290=head2 check_lm( \%options? )
3291
3292This method is used to check if some common C<math.h> functions are
3293available, and if C<-lm> is needed. Returns the empty string if no
3294library is needed, or the "-lm" string if libm is needed.
3295
3296If the very last parameter contains a hash reference, C<CODE> references
3297to I<action_on_true> or I<action_on_false> are executed, respectively.
3298Each of existing key/value pairs using I<action_on_func_true> (as
3299I<action_on_true> having the name of the tested functions as first argument),
3300I<action_on_func_false> (as I<action_on_false> having the name of the tested
3301functions as first argument), I<action_on_func_lib_true> (as
3302I<action_on_lib_true> having the name of the tested functions as first
3303argument), I<action_on_func_lib_false> (as I<action_on_lib_false> having
3304the name of the tested functions as first argument) as key are passed-
3305through to each call of L</search_libs>.
3306Given callbacks for I<action_on_lib_true>, I<action_on_lib_false>,
3307I<action_on_cache_true> or I<action_on_cache_false> are passed to the
3308call of L</search_libs>.
3309
3310B<Note> that I<action_on_lib_true> and I<action_on_func_lib_true> or
3311I<action_on_lib_false> and I<action_on_func_lib_false> cannot be used
3312at the same time, respectively.
3313
3314=cut
3315
3316sub check_lm
3317{
3318    my $options = {};
3319    scalar @_ > 1 and ref $_[-1] eq "HASH" and $options = pop @_;
3320    my $self = shift->_get_instance();
3321
3322    defined $options->{action_on_lib_true}
3323      and defined $options->{action_on_func_lib_true}
3324      and croak("action_on_lib_true and action_on_func_lib_true cannot be used together");
3325    defined $options->{action_on_lib_false}
3326      and defined $options->{action_on_func_lib_false}
3327      and croak("action_on_lib_false and action_on_func_lib_false cannot be used together");
3328
3329    my %pass_options;
3330    defined $options->{action_on_cache_true}  and $pass_options{action_on_cache_true}  = $options->{action_on_cache_true};
3331    defined $options->{action_on_cache_false} and $pass_options{action_on_cache_false} = $options->{action_on_cache_false};
3332    defined $options->{action_on_lib_true}    and $pass_options{action_on_lib_true}    = $options->{action_on_lib_true};
3333    defined $options->{action_on_lib_false}   and $pass_options{action_on_lib_false}   = $options->{action_on_lib_false};
3334
3335    my $fail       = 0;
3336    my $required   = "";
3337    my @math_funcs = $self->_check_lm_funcs;
3338    for my $func (@math_funcs)
3339    {
3340        my $ans = $self->search_libs(
3341            $func,
3342            ['m'],
3343            {
3344                %pass_options,
3345                (
3346                    $options->{action_on_func_true} && "CODE" eq ref $options->{action_on_func_true}
3347                    ? (action_on_true => sub { $options->{action_on_func_true}->($func, @_) })
3348                    : ()
3349                ),
3350                (
3351                    $options->{action_on_func_false} && "CODE" eq ref $options->{action_on_func_false}
3352                    ? (action_on_false => sub { $options->{action_on_func_false}->($func, @_) })
3353                    : ()
3354                ),
3355                (
3356                    $options->{action_on_func_lib_true} && "CODE" eq ref $options->{action_on_func_lib_true}
3357                    ? (action_on_lib_true => sub { $options->{action_on_func_lib_true}->($func, @_) })
3358                    : ()
3359                ),
3360                (
3361                    $options->{action_on_func_lib_false} && "CODE" eq ref $options->{action_on_func_lib_false}
3362                    ? (action_on_lib_false => sub { $options->{action_on_func_lib_false}->($func, @_) })
3363                    : ()
3364                ),
3365            },
3366        );
3367
3368        $ans or $fail = 1;
3369        $ans ne "none required" and $required = $ans;
3370    }
3371
3372         !$fail
3373      and $options->{action_on_true}
3374      and ref $options->{action_on_true} eq "CODE"
3375      and $options->{action_on_true}->();
3376
3377          $fail
3378      and $options->{action_on_false}
3379      and ref $options->{action_on_false} eq "CODE"
3380      and $options->{action_on_false}->();
3381
3382    $required;
3383}
3384
3385=head2 pkg_config_package_flags($package, \%options?)
3386
3387  use Config::AutoConf
3388
3389  my $c = Config::AutoConf->new;
3390  $c->pkg_config_package_flags('log4cplus');
3391  WriteMakefile(
3392    ...
3393    INC  => $c->_get_extra_compiler_flags,
3394    LIBS => $c->_get_extra_linker_flags,
3395  );
3396
3397Search for C<pkg-config> flags for package as specified. The flags which are
3398extracted are C<--cflags> and C<--libs>. The extracted flags are appended
3399to the global C<extra_preprocess_flags>, C<extra_link_flags> or C<extra_libs>,
3400respectively. Distinguishing between C<extra_link_flags> and C<extra_libs>
3401is essential to avoid conflicts with L<search_libs function|/search_libs>
3402and family.  In case, no I<package configuration> matching given criteria
3403could be found, return a C<false> value (C<0>).
3404
3405The C<pkg-config> flags are taken from I<environment variables>
3406C<< ${package}_CFLAGS >> or C<< ${package}_LIBS >> when defined, respectively.
3407It will be a nice touch to document the particular environment variables
3408for your build procedure - as for above example it should be
3409
3410  $ env log4cplus_CFLAGS="-I/opt/coolapp/include" \
3411        log4cplus_LIBS="-L/opt/coolapp/lib -Wl,-R/opt/coolapp/lib -llog4cplus" \
3412    perl Makefile.PL
3413
3414Call C<pkg_config_package_flags> with the package you're looking for and
3415optional callback whether found or not.
3416
3417To support stage compiling properly (C<rpath> vs. library file location),
3418the internal representation is a moving target. Do not use the result
3419directly - the getters L<_get_extra_compiler_flags|/_get_extra_compiler_flags>
3420and L<_get_extra_linker_flags|/_get_extra_linker_flags> are strongly
3421encouraged. In case this is not possible, please open a ticket to get
3422informed on invasive changes.
3423
3424If the very last parameter contains a hash reference, C<CODE> references
3425to I<action_on_true> or I<action_on_false> are executed, respectively.
3426If any of I<action_on_cache_true>, I<action_on_cache_false> is defined,
3427both callbacks are passed to L</check_cached> as I<action_on_true> or
3428I<action_on_false> to L</check_cached>, respectively.
3429
3430=cut
3431
3432my $_pkg_config_prog;
3433
3434sub _pkg_config_flag
3435{
3436    defined $_pkg_config_prog or croak("pkg_config_prog required");
3437    my @pkg_config_args = @_;
3438    my ($stdout, $stderr, $exit) =
3439      capture { system($_pkg_config_prog, @pkg_config_args); };
3440    chomp $stdout;
3441    0 == $exit and return $stdout;
3442    return $exit;
3443}
3444
3445sub pkg_config_package_flags
3446{
3447    my $options = {};
3448    scalar @_ > 1 and ref $_[-1] eq "HASH" and $options = pop @_;
3449    my ($self, $package) = @_;
3450    $self = $self->_get_instance();
3451
3452    (my $pkgpfx = $package) =~ s/^(\w+).*?$/$1/;
3453    my $cache_name = $self->_cache_name("pkg", $pkgpfx);
3454
3455    defined $_pkg_config_prog or $_pkg_config_prog = $self->{cache}->{$self->_cache_name("prog", "PKG_CONFIG")};
3456    defined $_pkg_config_prog or $_pkg_config_prog = $self->check_prog_pkg_config;
3457    my $check_sub = sub {
3458        my (@pkg_cflags, @pkg_libs);
3459
3460        (my $ENV_CFLAGS = $package) =~ s/^(\w+).*?$/$1_CFLAGS/;
3461        (my $ENV_LIBS   = $package) =~ s/^(\w+).*?$/$1_LIBS/;
3462
3463        my $pkg_exists = 0 + (
3464                 defined $ENV{$ENV_CFLAGS}
3465              or defined $ENV{$ENV_LIBS}
3466              or _pkg_config_flag($package, "--exists") eq ""
3467        );
3468        looks_like_number($pkg_exists) and $pkg_exists == 0 and return 0;
3469
3470        my $CFLAGS =
3471          defined $ENV{$ENV_CFLAGS}
3472          ? $ENV{$ENV_CFLAGS}
3473          : _pkg_config_flag($package, "--cflags");
3474        $CFLAGS and not looks_like_number($CFLAGS) and @pkg_cflags = (
3475            map { $_ =~ s/^\s+//; $_ =~ s/\s+$//; Text::ParseWords::shellwords $_; }
3476              split(m/\n/, $CFLAGS)
3477        ) and push @{$self->{extra_preprocess_flags}}, @pkg_cflags;
3478
3479        # do not separate between libs and extra (for now) - they come with -l prepended
3480        my $LIBS =
3481          defined $ENV{$ENV_LIBS}
3482          ? $ENV{$ENV_LIBS}
3483          : _pkg_config_flag($package, "--libs");
3484        $LIBS and not looks_like_number($LIBS) and @pkg_libs = (
3485            map { $_ =~ s/^\s+//; $_ =~ s/\s+$//; Text::ParseWords::shellwords $_; }
3486              split(m/\n/, $LIBS)
3487        );
3488        @pkg_libs and push @{$self->{extra_link_flags}}, grep { $_ !~ m/^-l/ } @pkg_libs;
3489        @pkg_libs and push @{$self->{extra_libs}}, map { (my $l = $_) =~ s/^-l//; $l } grep { $_ =~ m/^-l/ } @pkg_libs;
3490
3491        my $pkg_config_flags = join(" ", @pkg_cflags, @pkg_libs);
3492
3493              $pkg_config_flags
3494          and $options->{action_on_true}
3495          and ref $options->{action_on_true} eq "CODE"
3496          and $options->{action_on_true}->();
3497
3498        $options->{action_on_false}
3499          and ref $options->{action_on_false} eq "CODE"
3500          and !$pkg_config_flags
3501          and $options->{action_on_false}->();
3502
3503        $pkg_config_flags;
3504    };
3505
3506    $self->check_cached(
3507        $cache_name,
3508        "for pkg-config package of $package",
3509        $check_sub,
3510        {
3511            ($options->{action_on_cache_true}  ? (action_on_true  => $options->{action_on_cache_true})  : ()),
3512            ($options->{action_on_cache_false} ? (action_on_false => $options->{action_on_cache_false}) : ())
3513        }
3514    );
3515}
3516
3517=head2 _check_mm_pureperl_build_wanted
3518
3519This method proves the C<_argv> attribute and (when set) the C<PERL_MM_OPT>
3520whether they contain I<PUREPERL_ONLY=(0|1)> or not. The attribute C<_force_xs>
3521is set as appropriate, which allows a compile test to bail out when C<Makefile.PL>
3522is called with I<PUREPERL_ONLY=0>.
3523
3524=cut
3525
3526sub _check_mm_pureperl_build_wanted
3527{
3528    my $self = shift->_get_instance;
3529
3530    defined $ENV{PERL_MM_OPT} and my @env_args = split " ", $ENV{PERL_MM_OPT};
3531
3532    foreach my $arg (@{$self->{_argv}}, @env_args)
3533    {
3534        $arg =~ m/^PUREPERL_ONLY=(.*)$/ and return int($1);
3535    }
3536
3537    0;
3538}
3539
3540=head2 _check_mb_pureperl_build_wanted
3541
3542This method proves the C<_argv> attribute and (when set) the C<PERL_MB_OPT>
3543whether they contain I<--pureperl-only> or not.
3544
3545=cut
3546
3547sub _check_mb_pureperl_build_wanted
3548{
3549    my $self = shift->_get_instance;
3550
3551    defined $ENV{PERL_MB_OPT} and my @env_args = split " ", $ENV{PERL_MB_OPT};
3552
3553    foreach my $arg (@{$self->{_argv}}, @env_args)
3554    {
3555        $arg eq "--pureperl-only" and return 1;
3556    }
3557
3558    0;
3559}
3560
3561=head2 _check_pureperl_required
3562
3563This method calls C<_check_mm_pureperl_build_wanted> when running under
3564L<ExtUtils::MakeMaker> (C<Makefile.PL>) or C<_check_mb_pureperl_build_wanted>
3565when running under a C<Build.PL> (L<Module::Build> compatible) environment.
3566
3567When neither is found (C<$0> contains neither C<Makefile.PL> nor C<Build.PL>),
3568simply 0 is returned.
3569
3570=cut
3571
3572sub _check_pureperl_required
3573{
3574    my $self = shift;
3575    $0 =~ m/Makefile\.PL$/i and return $self->_check_mm_pureperl_build_wanted(@_);
3576    $0 =~ m/Build\.PL$/i    and return $self->_check_mb_pureperl_build_wanted(@_);
3577
3578    0;
3579}
3580
3581=head2 check_pureperl_required
3582
3583This check method proves whether a pure perl build is wanted or not by
3584cached-checking C<< $self->_check_pureperl_required >>.
3585
3586=cut
3587
3588sub check_pureperl_required
3589{
3590    my $self       = shift->_get_instance;
3591    my $cache_name = $self->_cache_name(qw(pureperl required));
3592    $self->check_cached($cache_name, "whether pureperl is required", sub { $self->_check_pureperl_required });
3593}
3594
3595=head2 check_produce_xs_build
3596
3597This routine checks whether XS can be produced. Therefore it does
3598following checks in given order:
3599
3600=over 4
3601
3602=item *
3603
3604check pure perl environment variables (L</check_pureperl_required>) or
3605command line arguments and return false when pure perl is requested
3606
3607=item *
3608
3609check whether a compiler is available (L</check_valid_compilers>) and
3610return false if none found
3611
3612=item *
3613
3614check whether a test program accessing Perl API can be compiled and
3615die with error if not
3616
3617=back
3618
3619When all checks passed successfully, return a true value.
3620
3621If the very last parameter contains a hash reference, C<CODE> references
3622to I<action_on_true> or I<action_on_false> are executed, respectively.
3623
3624=cut
3625
3626sub check_produce_xs_build
3627{
3628    my $options = {};
3629    scalar @_ > 1 and ref $_[-1] eq "HASH" and $options = pop @_;
3630    my $self = shift->_get_instance;
3631    $self->check_pureperl_required() and return _on_return_callback_helper(0, $options, "action_on_false");
3632    eval { $self->check_valid_compilers($_[0] || [qw(C)]) }
3633      or return _on_return_callback_helper(0, $options, "action_on_false");
3634    # XXX necessary check for $Config{useshrlib}? (need to dicuss with e.g. TuX, 99% likely return 0)
3635    $self->check_compile_perlapi_or_die();
3636
3637    $options->{action_on_true}
3638      and ref $options->{action_on_true} eq "CODE"
3639      and $options->{action_on_true}->();
3640
3641    return 1;
3642}
3643
3644=head2 check_produce_loadable_xs_build
3645
3646This routine proves whether XS should be built and it's possible to create
3647a dynamic linked object which can be loaded using Perl's Dynaloader.
3648
3649The extension over L</check_produce_xs_build> can be avoided by adding the
3650C<notest_loadable_xs> to C<$ENV{PERL5_AC_OPTS}>.
3651
3652If the very last parameter contains a hash reference, C<CODE> references
3653to I<action_on_true> or I<action_on_false> are executed, respectively.
3654
3655=cut
3656
3657sub check_produce_loadable_xs_build
3658{
3659    my $self = shift->_get_instance;
3660    $self->check_produce_xs_build(@_)
3661      and !$self->{c_ac_flags}->{notest_loadable_xs}
3662      and $self->check_linkable_xs_so_or_die
3663      and $self->check_loadable_xs_so_or_die;
3664}
3665
3666#
3667#
3668# Auxiliary funcs
3669#
3670
3671=head2 _set_argv
3672
3673Intended to act as a helper for evaluating given command line arguments.
3674Stores given arguments in instances C<_argv> attribute.
3675
3676Call once at very begin of C<Makefile.PL> or C<Build.PL>:
3677
3678  Your::Pkg::Config::AutoConf->_set_args(@ARGV);
3679
3680=cut
3681
3682sub _set_argv
3683{
3684    my ($self, @argv) = @_;
3685    $self = $self->_get_instance;
3686    $self->{_argv} = \@argv;
3687    return;
3688}
3689
3690sub _sanitize
3691{
3692    # This is hard coded, and maybe a little stupid...
3693    my $x = shift;
3694    $x =~ s/ //g;
3695    $x =~ s/\///g;
3696    $x =~ s/\\//g;
3697    $x;
3698}
3699
3700sub _get_instance
3701{
3702    ref $_[0] and return $_[0];
3703    defined $glob_instance or $glob_instance = $_[0]->new();
3704    $glob_instance;
3705}
3706
3707sub _get_builder
3708{
3709    my $self = $_[0]->_get_instance();
3710
3711    ref $self->{lang_supported}->{$self->{lang}} eq "CODE" and $self->{lang_supported}->{$self->{lang}}->($self);
3712    defined($self->{lang_supported}->{$self->{lang}}) or croak("Unsupported compile language \"" . $self->{lang} . "\"");
3713
3714    $self->{lang_supported}->{$self->{lang}}->new();
3715}
3716
3717sub _set_language
3718{
3719    my $self = shift->_get_instance();
3720    my ($lang, $impl) = @_;
3721
3722    defined($lang) or croak("Missing language");
3723
3724          defined($impl)
3725      and defined($self->{lang_supported}->{$lang})
3726      and $impl ne $self->{lang_supported}->{$lang}
3727      and croak("Language implementor ($impl) doesn't match exisiting one (" . $self->{lang_supported}->{$lang} . ")");
3728
3729    defined($impl)
3730      and !defined($self->{lang_supported}->{$lang})
3731      and $self->{lang_supported}->{$lang} = $impl;
3732
3733    ref $self->{lang_supported}->{$lang} eq "CODE" and $self->{lang_supported}->{$lang}->($self);
3734    defined($self->{lang_supported}->{$lang}) or croak("Unsupported language \"$lang\"");
3735
3736    defined($self->{extra_compile_flags}->{$lang}) or $self->{extra_compile_flags}->{$lang} = [];
3737
3738    $self->{lang} = $lang;
3739
3740    return;
3741}
3742
3743sub _on_return_callback_helper
3744{
3745    my $callback = pop @_;
3746    my $options  = pop @_;
3747    $options->{$callback}
3748      and ref $options->{$callback} eq "CODE"
3749      and $options->{$callback}->();
3750    @_ and wantarray and return @_;
3751    1 == scalar @_ and return $_[0];
3752    return;
3753}
3754
3755sub _fill_defines
3756{
3757    my ($self, $src, $action_if_true, $action_if_false) = @_;
3758    ref $self or $self = $self->_get_instance();
3759
3760    my $conftest = "";
3761    while (my ($defname, $defcnt) = each(%{$self->{defines}}))
3762    {
3763        $defcnt->[0] or next;
3764        defined $defcnt->[1] and $conftest .= "/* " . $defcnt->[1] . " */\n";
3765        $conftest .= join(" ", "#define", $defname, $defcnt->[0]) . "\n";
3766    }
3767    $conftest .= "/* end of conftest.h */\n";
3768
3769    $conftest;
3770}
3771
3772#
3773# default includes taken from autoconf/headers.m4
3774#
3775
3776=head2 _default_includes
3777
3778returns a string containing default includes for program prologue taken
3779from C<autoconf/headers.m4>:
3780
3781  #include <stdio.h>
3782  #ifdef HAVE_SYS_TYPES_H
3783  # include <sys/types.h>
3784  #endif
3785  #ifdef HAVE_SYS_STAT_H
3786  # include <sys/stat.h>
3787  #endif
3788  #ifdef STDC_HEADERS
3789  # include <stdlib.h>
3790  # include <stddef.h>
3791  #else
3792  # ifdef HAVE_STDLIB_H
3793  #  include <stdlib.h>
3794  # endif
3795  #endif
3796  #ifdef HAVE_STRING_H
3797  # if !defined STDC_HEADERS && defined HAVE_MEMORY_H
3798  #  include <memory.h>
3799  # endif
3800  # include <string.h>
3801  #endif
3802  #ifdef HAVE_STRINGS_H
3803  # include <strings.h>
3804  #endif
3805  #ifdef HAVE_INTTYPES_H
3806  # include <inttypes.h>
3807  #endif
3808  #ifdef HAVE_STDINT_H
3809  # include <stdint.h>
3810  #endif
3811  #ifdef HAVE_UNISTD_H
3812  # include <unistd.h>
3813  #endif
3814
3815=cut
3816
3817my $_default_includes = <<"_ACEOF";
3818#include <stdio.h>
3819#ifdef HAVE_SYS_TYPES_H
3820# include <sys/types.h>
3821#endif
3822#ifdef HAVE_SYS_STAT_H
3823# include <sys/stat.h>
3824#endif
3825#ifdef STDC_HEADERS
3826# include <stdlib.h>
3827# include <stddef.h>
3828#else
3829# ifdef HAVE_STDLIB_H
3830#  include <stdlib.h>
3831# endif
3832#endif
3833#ifdef HAVE_STRING_H
3834# if !defined STDC_HEADERS && defined HAVE_MEMORY_H
3835#  include <memory.h>
3836# endif
3837# include <string.h>
3838#endif
3839#ifdef HAVE_STRINGS_H
3840# include <strings.h>
3841#endif
3842#ifdef HAVE_INTTYPES_H
3843# include <inttypes.h>
3844#endif
3845#ifdef HAVE_STDINT_H
3846# include <stdint.h>
3847#endif
3848#ifdef HAVE_UNISTD_H
3849# include <unistd.h>
3850#endif
3851_ACEOF
3852
3853sub _default_includes { $_default_includes }
3854
3855sub _default_main { $_[0]->_build_main("") }
3856
3857my $_main_tpl = <<"_ACEOF";
3858  int
3859  main ()
3860  {
3861    %s;
3862    return 0;
3863  }
3864_ACEOF
3865
3866sub _build_main
3867{
3868    my $self = shift->_get_instance();
3869    my $body = shift || "";
3870    sprintf($_main_tpl, $body);
3871}
3872
3873=head2 _default_includes_with_perl
3874
3875returns a string containing default includes for program prologue containing
3876I<_default_includes> plus
3877
3878  #include <EXTERN.h>
3879  #include <perl.h>
3880
3881=cut
3882
3883my $_include_perl = <<"_ACEOF";
3884#include <EXTERN.h>
3885#include <perl.h>
3886#include <XSUB.h> /* for perl context in threaded perls */
3887_ACEOF
3888
3889sub _default_includes_with_perl
3890{
3891    join("\n", $_[0]->_default_includes, $_include_perl);
3892}
3893
3894sub _cache_prefix { "ac" }
3895
3896sub _cache_name
3897{
3898    my ($self, @names) = @_;
3899    my $cache_name = join("_", $self->_cache_prefix(), "cv", @names);
3900    $cache_name =~ tr/_A-Za-z0-9/_/c;
3901    $cache_name;
3902}
3903
3904sub _get_log_fh
3905{
3906    my $self = $_[0]->_get_instance();
3907    unless (defined($self->{logfh}))
3908    {
3909        my $open_mode = defined $self->{logfile_mode} ? $self->{logfile_mode} : ">";
3910        open(my $fh, $open_mode, $self->{logfile}) or croak "Could not open file $self->{logfile}: $!";
3911        $self->{logfh} = [$fh];
3912    }
3913
3914    $self->{logfh};
3915}
3916
3917sub _add_log_entry
3918{
3919    my ($self, @logentries) = @_;
3920    ref($self) or $self = $self->_get_instance();
3921    $self->_get_log_fh();
3922    foreach my $logentry (@logentries)
3923    {
3924        foreach my $fh (@{$self->{logfh}})
3925        {
3926            print {$fh} "$logentry";
3927        }
3928    }
3929
3930    return;
3931}
3932
3933sub _add_log_lines
3934{
3935    my ($self, @logentries) = @_;
3936    ref($self) or $self = $self->_get_instance();
3937    $self->_get_log_fh();
3938    my $logmsg = join("\n", @logentries) . "\n";
3939    foreach my $fh (@{$self->{logfh}})
3940    {
3941        print {$fh} $logmsg;
3942    }
3943
3944    return;
3945}
3946
3947=head2 add_log_fh
3948
3949Push new file handles at end of log-handles to allow tee'ing log-output
3950
3951=cut
3952
3953sub add_log_fh
3954{
3955    my ($self, @newh) = @_;
3956    $self->_get_log_fh();
3957  SKIP_DUP:
3958    foreach my $fh (@newh)
3959    {
3960        foreach my $eh (@{$self->{logfh}})
3961        {
3962            $fh == $eh and next SKIP_DUP;
3963        }
3964        push @{$self->{logfh}}, $fh;
3965    }
3966    return;
3967}
3968
3969=head2 delete_log_fh
3970
3971Removes specified log file handles. This method allows you to shoot
3972yourself in the foot - it doesn't prove whether the primary nor the last handle
3973is removed. Use with caution.
3974
3975=cut
3976
3977sub delete_log_fh
3978{
3979    my ($self, @xh) = @_;
3980    $self->_get_log_fh();
3981  SKIP_DUP:
3982    foreach my $fh (@xh)
3983    {
3984        foreach my $ih (0 .. $#{$self->{logfh}})
3985        {
3986            $fh == $self->{logfh}->[$ih] or next;
3987            splice @{$self->{logfh}}, $ih, 1;
3988            last;
3989        }
3990    }
3991    return;
3992}
3993
3994sub _cache_type_name
3995{
3996    my ($self, @names) = @_;
3997    $self->_cache_name(map { $_ =~ tr/*/p/; $_ } @names);
3998}
3999
4000=head2 _get_extra_compiler_flags
4001
4002Returns the determined flags required to run the compile stage as string
4003
4004=cut
4005
4006sub _get_extra_compiler_flags
4007{
4008    my $self    = shift->_get_instance();
4009    my @ppflags = @{$self->{extra_preprocess_flags}};
4010    my @cflags  = @{$self->{extra_compile_flags}->{$self->{lang}}};
4011    join(" ", map { _quote_shell_arg $_ } (@ppflags, @cflags));
4012}
4013
4014=head2 _get_extra_linker_flags
4015
4016Returns the determined flags required to run the link stage as string
4017
4018=cut
4019
4020sub _get_extra_linker_flags
4021{
4022    my $self     = shift->_get_instance();
4023    my @libs     = @{$self->{extra_libs}};
4024    my @lib_dirs = @{$self->{extra_lib_dirs}};
4025    my @ldflags  = @{$self->{extra_link_flags}};
4026    join(" ", map { _quote_shell_arg $_ } (@ldflags, map("-L" . $self->_sanitize_prog($_), @lib_dirs), map("-l$_", @libs)));
4027}
4028
4029=head1 AUTHOR
4030
4031Alberto Simões, C<< <ambs@cpan.org> >>
4032
4033Jens Rehsack, C<< <rehsack@cpan.org> >>
4034
4035=head1 NEXT STEPS
4036
4037Although a lot of work needs to be done, these are the next steps I
4038intend to take.
4039
4040  - detect flex/lex
4041  - detect yacc/bison/byacc
4042  - detect ranlib (not sure about its importance)
4043
4044These are the ones I think not too much important, and will be
4045addressed later, or by request.
4046
4047  - detect an 'install' command
4048  - detect a 'ln -s' command -- there should be a module doing
4049    this kind of task.
4050
4051=head1 BUGS
4052
4053A lot. Portability is a pain. B<<Patches welcome!>>.
4054
4055Please report any bugs or feature requests to
4056C<bug-Config-AutoConf@rt.cpan.org>, or through the web interface at
4057L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Config-AutoConf>.  We will
4058be notified, and then you'll automatically be notified of progress
4059on your bug as we make changes.
4060
4061=head1 SUPPORT
4062
4063You can find documentation for this module with the perldoc command.
4064
4065    perldoc Config::AutoConf
4066
4067You can also look for information at:
4068
4069=over 4
4070
4071=item * AnnoCPAN: Annotated CPAN documentation
4072
4073L<http://annocpan.org/dist/Config-AutoConf>
4074
4075=item * CPAN Ratings
4076
4077L<http://cpanratings.perl.org/dist/Config-AutoConf>
4078
4079=item * MetaCPAN
4080
4081L<https://metacpan.org/release/Config-AutoConf>
4082
4083=item * Git Repository
4084
4085L<https://github.com/ambs/Config-AutoConf>
4086
4087=back
4088
4089=head1 ACKNOWLEDGEMENTS
4090
4091Michael Schwern for kind MacOS X help.
4092
4093Ken Williams for ExtUtils::CBuilder
4094
4095Peter Rabbitson for help on refactoring and making the API more Perl'ish
4096
4097=head1 COPYRIGHT & LICENSE
4098
4099Copyright 2004-2020 by the Authors
4100
4101This program is free software; you can redistribute it and/or modify it
4102under the same terms as Perl itself.
4103
4104=head1 SEE ALSO
4105
4106ExtUtils::CBuilder(3)
4107
4108=cut
4109
41101;    # End of Config::AutoConf
4111