Another bootstrap kludge.
[coreutils/ericb.git] / src / seq.c
blobd7d2521b1454fafee12270cdfac3b6754ede349e
1 /* seq - print sequence of numbers to standard output.
2 Copyright (C) 1994-2007 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by Ulrich Drepper. */
19 #include <config.h>
20 #include <getopt.h>
21 #include <stdio.h>
22 #include <sys/types.h>
24 #include "system.h"
25 #include "c-strtod.h"
26 #include "error.h"
27 #include "quote.h"
28 #include "xstrtod.h"
30 /* Roll our own isfinite rather than using <math.h>, so that we don't
31 have to worry about linking -lm just for isfinite. */
32 #ifndef isfinite
33 # define isfinite(x) ((x) * 0 == 0)
34 #endif
36 /* The official name of this program (e.g., no `g' prefix). */
37 #define PROGRAM_NAME "seq"
39 #define AUTHORS "Ulrich Drepper"
41 /* If true print all number with equal width. */
42 static bool equal_width;
44 /* The name that this program was run with. */
45 char *program_name;
47 /* The string used to separate two numbers. */
48 static char const *separator;
50 /* The string output after all numbers have been output.
51 Usually "\n" or "\0". */
52 /* FIXME: make this an option. */
53 static char const terminator[] = "\n";
55 static struct option const long_options[] =
57 { "equal-width", no_argument, NULL, 'w'},
58 { "format", required_argument, NULL, 'f'},
59 { "separator", required_argument, NULL, 's'},
60 {GETOPT_HELP_OPTION_DECL},
61 {GETOPT_VERSION_OPTION_DECL},
62 { NULL, 0, NULL, 0}
65 void
66 usage (int status)
68 if (status != EXIT_SUCCESS)
69 fprintf (stderr, _("Try `%s --help' for more information.\n"),
70 program_name);
71 else
73 printf (_("\
74 Usage: %s [OPTION]... LAST\n\
75 or: %s [OPTION]... FIRST LAST\n\
76 or: %s [OPTION]... FIRST INCREMENT LAST\n\
77 "), program_name, program_name, program_name);
78 fputs (_("\
79 Print numbers from FIRST to LAST, in steps of INCREMENT.\n\
80 \n\
81 -f, --format=FORMAT use printf style floating-point FORMAT\n\
82 -s, --separator=STRING use STRING to separate numbers (default: \\n)\n\
83 -w, --equal-width equalize width by padding with leading zeroes\n\
84 "), stdout);
85 fputs (HELP_OPTION_DESCRIPTION, stdout);
86 fputs (VERSION_OPTION_DESCRIPTION, stdout);
87 fputs (_("\
88 \n\
89 If FIRST or INCREMENT is omitted, it defaults to 1. That is, an\n\
90 omitted INCREMENT defaults to 1 even when LAST is smaller than FIRST.\n\
91 FIRST, INCREMENT, and LAST are interpreted as floating point values.\n\
92 INCREMENT is usually positive if FIRST is smaller than LAST, and\n\
93 INCREMENT is usually negative if FIRST is greater than LAST.\n\
94 "), stdout);
95 fputs (_("\
96 FORMAT must be suitable for printing one argument of type `double';\n\
97 it defaults to %.PRECf if FIRST, INCREMENT, and LAST are all fixed point\n\
98 decimal numbers with maximum precision PREC, and to %g otherwise.\n\
99 "), stdout);
100 emit_bug_reporting_address ();
102 exit (status);
105 /* A command-line operand. */
106 struct operand
108 /* Its value, converted to 'long double'. */
109 long double value;
111 /* Its print width, if it were printed out in a form similar to its
112 input form. An input like "-.1" is treated like "-0.1", and an
113 input like "1." is treated like "1", but otherwise widths are
114 left alone. */
115 size_t width;
117 /* Number of digits after the decimal point, or INT_MAX if the
118 number can't easily be expressed as a fixed-point number. */
119 int precision;
121 typedef struct operand operand;
123 /* Description of what a number-generating format will generate. */
124 struct layout
126 /* Number of bytes before and after the number. */
127 size_t prefix_len;
128 size_t suffix_len;
131 /* Read a long double value from the command line.
132 Return if the string is correct else signal error. */
134 static operand
135 scan_arg (const char *arg)
137 operand ret;
139 if (! xstrtold (arg, NULL, &ret.value, c_strtold))
141 error (0, 0, _("invalid floating point argument: %s"), arg);
142 usage (EXIT_FAILURE);
145 /* We don't output spaces or '+' so don't include in width */
146 while (isspace (*arg) || *arg == '+')
147 arg++;
149 ret.width = strlen (arg);
150 ret.precision = INT_MAX;
152 if (! arg[strcspn (arg, "xX")] && isfinite (ret.value))
154 char const *decimal_point = strchr (arg, '.');
155 if (! decimal_point)
156 ret.precision = 0;
157 else
159 size_t fraction_len = strcspn (decimal_point + 1, "eE");
160 if (fraction_len <= INT_MAX)
161 ret.precision = fraction_len;
162 ret.width += (fraction_len == 0 /* #. -> # */
163 ? -1
164 : (decimal_point == arg /* .# -> 0.# */
165 || ! ISDIGIT (decimal_point[-1]))); /* -.# -> 0.# */
167 char const *e = strchr (arg, 'e');
168 if (! e)
169 e = strchr (arg, 'E');
170 if (e)
172 long exponent = strtol (e + 1, NULL, 10);
173 ret.precision += exponent < 0 ? -exponent : 0;
177 return ret;
180 /* If FORMAT is a valid printf format for a double argument, return
181 its long double equivalent, possibly allocated from dynamic
182 storage, and store into *LAYOUT a description of the output layout;
183 otherwise, return NULL. */
185 static char const *
186 long_double_format (char const *fmt, struct layout *layout)
188 size_t i;
189 size_t prefix_len = 0;
190 size_t suffix_len = 0;
191 size_t length_modifier_offset;
192 bool has_L;
194 for (i = 0; ! (fmt[i] == '%' && fmt[i + 1] != '%'); i += (fmt[i] == '%') + 1)
195 if (fmt[i])
196 prefix_len++;
197 else
198 return NULL;
200 i++;
201 i += strspn (fmt + i, "-+#0 '");
202 i += strspn (fmt + i, "0123456789");
203 if (fmt[i] == '.')
205 i++;
206 i += strspn (fmt + i, "0123456789");
209 length_modifier_offset = i;
210 has_L = (fmt[i] == 'L');
211 i += has_L;
212 if (! strchr ("efgaEFGA", fmt[i]))
213 return NULL;
215 for (i++; ! (fmt[i] == '%' && fmt[i + 1] != '%'); i += (fmt[i] == '%') + 1)
216 if (fmt[i])
217 suffix_len++;
218 else
220 size_t format_size = i + 1;
221 char *ldfmt = xmalloc (format_size + 1);
222 memcpy (ldfmt, fmt, length_modifier_offset);
223 ldfmt[length_modifier_offset] = 'L';
224 strcpy (ldfmt + length_modifier_offset + 1,
225 fmt + length_modifier_offset + has_L);
226 layout->prefix_len = prefix_len;
227 layout->suffix_len = suffix_len;
228 return ldfmt;
231 return NULL;
234 /* Actually print the sequence of numbers in the specified range, with the
235 given or default stepping and format. */
237 static void
238 print_numbers (char const *fmt, struct layout layout,
239 long double first, long double step, long double last)
241 long double i;
242 long double x0 IF_LINT (= 0);
244 for (i = 0; /* empty */; i++)
246 long double x = first + i * step;
248 if (step < 0 ? x < last : last < x)
250 /* If we go one past the end, but that number prints as a
251 value equal to "last", and prints differently from the
252 previous number, then print "last". This avoids problems
253 with rounding. For example, with the x86 it causes "seq
254 0 0.000001 0.000003" to print 0.000003 instead of
255 stopping at 0.000002. */
257 if (i)
259 long double x_val;
260 char *x_str;
261 int x_strlen = asprintf (&x_str, fmt, x);
262 if (x_strlen < 0)
263 xalloc_die ();
264 x_str[x_strlen - layout.suffix_len] = '\0';
266 if (xstrtold (x_str + layout.prefix_len, NULL, &x_val, c_strtold)
267 && x_val == last)
269 char *x0_str = NULL;
270 if (asprintf (&x0_str, fmt, x0) < 0)
271 xalloc_die ();
272 if (!STREQ (x0_str, x_str))
274 fputs (separator, stdout);
275 fputs (x_str, stdout);
277 free (x0_str);
280 free (x_str);
283 break;
286 if (i)
287 fputs (separator, stdout);
288 printf (fmt, x);
289 x0 = x;
292 if (i)
293 fputs (terminator, stdout);
296 /* Return the default format given FIRST, STEP, and LAST. */
297 static char const *
298 get_default_format (operand first, operand step, operand last)
300 static char format_buf[sizeof "%0.Lf" + 2 * INT_STRLEN_BOUND (int)];
302 int prec = MAX (first.precision, step.precision);
304 if (prec != INT_MAX && last.precision != INT_MAX)
306 if (equal_width)
308 /* increase first_width by any increased precision in step */
309 size_t first_width = first.width + (prec - first.precision);
310 /* adjust last_width to use precision from first/step */
311 size_t last_width = last.width + (prec - last.precision);
312 if (last.precision && prec == 0)
313 last_width--; /* don't include space for '.' */
314 size_t width = MAX (first_width, last_width);
315 if (width <= INT_MAX)
317 int w = width;
318 sprintf (format_buf, "%%0%d.%dLf", w, prec);
319 return format_buf;
322 else
324 sprintf (format_buf, "%%.%dLf", prec);
325 return format_buf;
329 return "%Lg";
333 main (int argc, char **argv)
335 int optc;
336 operand first = { 1, 1, 0 };
337 operand step = { 1, 1, 0 };
338 operand last;
339 struct layout layout = { 0, 0 };
341 /* The printf(3) format used for output. */
342 char const *format_str = NULL;
344 initialize_main (&argc, &argv);
345 program_name = argv[0];
346 setlocale (LC_ALL, "");
347 bindtextdomain (PACKAGE, LOCALEDIR);
348 textdomain (PACKAGE);
350 atexit (close_stdout);
352 equal_width = false;
353 separator = "\n";
355 /* We have to handle negative numbers in the command line but this
356 conflicts with the command line arguments. So explicitly check first
357 whether the next argument looks like a negative number. */
358 while (optind < argc)
360 if (argv[optind][0] == '-'
361 && ((optc = argv[optind][1]) == '.' || ISDIGIT (optc)))
363 /* means negative number */
364 break;
367 optc = getopt_long (argc, argv, "+f:s:w", long_options, NULL);
368 if (optc == -1)
369 break;
371 switch (optc)
373 case 'f':
374 format_str = optarg;
375 break;
377 case 's':
378 separator = optarg;
379 break;
381 case 'w':
382 equal_width = true;
383 break;
385 case_GETOPT_HELP_CHAR;
387 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
389 default:
390 usage (EXIT_FAILURE);
394 if (argc - optind < 1)
396 error (0, 0, _("missing operand"));
397 usage (EXIT_FAILURE);
400 if (3 < argc - optind)
402 error (0, 0, _("extra operand %s"), quote (argv[optind + 3]));
403 usage (EXIT_FAILURE);
406 if (format_str)
408 char const *f = long_double_format (format_str, &layout);
409 if (! f)
411 error (0, 0, _("invalid format string: %s"), quote (format_str));
412 usage (EXIT_FAILURE);
414 format_str = f;
417 last = scan_arg (argv[optind++]);
419 if (optind < argc)
421 first = last;
422 last = scan_arg (argv[optind++]);
424 if (optind < argc)
426 step = last;
427 last = scan_arg (argv[optind++]);
431 if (format_str != NULL && equal_width)
433 error (0, 0, _("\
434 format string may not be specified when printing equal width strings"));
435 usage (EXIT_FAILURE);
438 if (format_str == NULL)
439 format_str = get_default_format (first, step, last);
441 print_numbers (format_str, layout, first.value, step.value, last.value);
443 exit (EXIT_SUCCESS);