1# -*-perl-*- hey - emacs - this is a perl file
2
3# src/tools/msvc/pgflex.pl
4
5# silence flex bleatings about file path style
6$ENV{CYGWIN} = 'nodosfilewarning';
7
8use strict;
9use File::Basename;
10
11# assume we are in the postgres source root
12
13do './src/tools/msvc/buildenv.pl' if -e 'src/tools/msvc/buildenv.pl';
14
15my ($flexver) = `flex -V`;    # grab first line
16$flexver = (split(/\s+/, $flexver))[1];
17$flexver =~ s/[^0-9.]//g;
18my @verparts = split(/\./, $flexver);
19unless ($verparts[0] == 2
20	&& ($verparts[1] > 5 || ($verparts[1] == 5 && $verparts[2] >= 31)))
21{
22	print "WARNING! Flex install not found, or unsupported Flex version.\n";
23	print "echo Attempting to build without.\n";
24	exit 0;
25}
26
27my $input = shift;
28if ($input !~ /\.l$/)
29{
30	print "Input must be a .l file\n";
31	exit 1;
32}
33elsif (!-e $input)
34{
35	print "Input file $input not found\n";
36	exit 1;
37}
38
39(my $output = $input) =~ s/\.l$/.c/;
40
41# get flex flags from make file
42my $makefile = dirname($input) . "/Makefile";
43my ($mf, $make);
44open($mf, $makefile);
45local $/ = undef;
46$make = <$mf>;
47close($mf);
48my $basetarg = basename($output);
49my $flexflags = ($make =~ /^$basetarg:\s*FLEXFLAGS\s*=\s*(\S.*)/m ? $1 : '');
50
51system("flex $flexflags -o$output $input");
52if ($? == 0)
53{
54
55	# For non-reentrant scanners we need to fix up the yywrap macro definition
56	# to keep the MS compiler happy.
57	# For reentrant scanners (like the core scanner) we do not
58	# need to (and must not) change the yywrap definition.
59	my $lfile;
60	open($lfile, $input) || die "opening $input for reading: $!";
61	my $lcode = <$lfile>;
62	close($lfile);
63	if ($lcode !~ /\%option\sreentrant/)
64	{
65		my $cfile;
66		open($cfile, $output) || die "opening $output for reading: $!";
67		my $ccode = <$cfile>;
68		close($cfile);
69		$ccode =~ s/yywrap\(n\)/yywrap()/;
70		open($cfile, ">$output") || die "opening $output for reading: $!";
71		print $cfile $ccode;
72		close($cfile);
73	}
74	if ($flexflags =~ /\s-b\s/)
75	{
76		my $lexback = "lex.backup";
77		open($lfile, $lexback) || die "opening $lexback for reading: $!";
78		my $lexbacklines = <$lfile>;
79		close($lfile);
80		my $linecount = $lexbacklines =~ tr /\n/\n/;
81		if ($linecount != 1)
82		{
83			print "Scanner requires backup, see lex.backup.\n";
84			exit 1;
85		}
86		unlink $lexback;
87	}
88
89	exit 0;
90
91}
92else
93{
94	exit $? >> 8;
95}
96