home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / MPW / gawk 2.11.1r3 / Sources / main.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-06-02  |  14.2 KB  |  678 lines  |  [TEXT/MPS ]

  1. /*
  2.  * main.c -- Expression tree constructors and main program for gawk. 
  3.  */
  4.  
  5. /* 
  6.  * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc.
  7.  * 
  8.  * This file is part of GAWK, the GNU implementation of the
  9.  * AWK Progamming Language.
  10.  * 
  11.  * GAWK is free software; you can redistribute it and/or modify
  12.  * it under the terms of the GNU General Public License as published by
  13.  * the Free Software Foundation; either version 1, or (at your option)
  14.  * any later version.
  15.  * 
  16.  * GAWK is distributed in the hope that it will be useful,
  17.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  19.  * GNU General Public License for more details.
  20.  * 
  21.  * You should have received a copy of the GNU General Public License
  22.  * along with GAWK; see the file COPYING.  If not, write to
  23.  * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  24.  */
  25.  
  26. /* 02Jun91    Matthias Neeracher    <neeri@iis.ethz.ch>    MPW port */
  27.  
  28. #include "awk.h"
  29. #include "patchlevel.h"
  30. #include <signal.h>
  31. #ifdef macintosh
  32. #include <ioctl.h>
  33. #define fileno(p)    (p)->_file
  34.  
  35. int mpw_regex = 0;
  36. #endif
  37.  
  38. extern int yyparse();
  39. extern void do_input();
  40. extern int close_io();
  41. extern void init_fields();
  42. extern int getopt();
  43. extern int re_set_syntax();
  44. extern NODE *node();
  45.  
  46. static void usage();
  47. static void set_fs();
  48. static void init_vars();
  49. static void init_args();
  50. static NODE *spc_var();
  51. static void pre_assign();
  52. static void copyleft();
  53.  
  54. /* These nodes store all the special variables AWK uses */
  55. NODE *FS_node, *NF_node, *RS_node, *NR_node;
  56. NODE *FILENAME_node, *OFS_node, *ORS_node, *OFMT_node;
  57. NODE *FNR_node, *RLENGTH_node, *RSTART_node, *SUBSEP_node;
  58. NODE *ENVIRON_node, *IGNORECASE_node;
  59. NODE *ARGC_node, *ARGV_node;
  60.  
  61. /*
  62.  * The parse tree and field nodes are stored here.  Parse_end is a dummy item
  63.  * used to free up unneeded fields without freeing the program being run 
  64.  */
  65. int errcount = 0;    /* error counter, used by yyerror() */
  66.  
  67. /* The global null string */
  68. NODE *Nnull_string;
  69.  
  70. /* The name the program was invoked under, for error messages */
  71. char *myname;
  72.  
  73. /* A block of AWK code to be run before running the program */
  74. NODE *begin_block = 0;
  75.  
  76. /* A block of AWK code to be run after the last input file */
  77. NODE *end_block = 0;
  78.  
  79. int exiting = 0;        /* Was an "exit" statement executed? */
  80. int exit_val = 0;        /* optional exit value */
  81.  
  82. #ifdef DEBUG
  83. /* non-zero means in debugging is enabled.  Probably not very useful */
  84. int debugging = 0;
  85. extern int yydebug;
  86. #endif
  87.  
  88. int tempsource = 0;        /* source is in a temp file */
  89. char **sourcefile = NULL;    /* source file name(s) */
  90. int numfiles = -1;        /* how many source files */
  91.  
  92. int strict = 0;            /* turn off gnu extensions */
  93.  
  94. int output_is_tty = 0;        /* control flushing of output */
  95.  
  96. NODE *expression_value;
  97.  
  98. /*
  99.  * for strict to work, legal options must be first
  100.  *
  101.  * Unfortunately, -a, -e, and -m are orthogonal to -c.
  102.  */
  103. #define EXTENSIONS    8    /* where to clear */
  104. #ifndef macintosh
  105. #ifdef DEBUG
  106. char awk_opts[] = "F:f:v:caeCVdD";
  107. #else
  108. char awk_opts[] = "F:f:v:caeCV";
  109. #endif
  110. #else
  111. #ifdef DEBUG
  112. char awk_opts[] = "F:f:v:caemCVdD";
  113. #else
  114. char awk_opts[] = "F:f:v:caemCV";
  115. #endif
  116. #endif
  117.  
  118. #ifdef macintosh
  119. char ** sortargs(int argc, char ** args)
  120. {
  121.     char **     sorted;
  122.     char **    options;
  123.     char **    argv;
  124.     
  125.     sorted     = (char **) malloc((argc+1) * sizeof(char *));
  126.     options    = sorted+1;
  127.     *sorted    = *args++;
  128.     
  129.     /* Copy options */
  130.     for (argv=args; *argv; argv++)
  131.         if ((*argv)[0] == '-')
  132.             switch ((*argv)[1]) {
  133.             case 'F':
  134.             case 'f':
  135.             case 'v':
  136.                 *options++ = *argv++;
  137.                 *options++ = *argv;
  138.                 break;
  139.             default:
  140.                 *options++ = *argv;
  141.             }
  142.     
  143.     /* Copy files */
  144.     for (argv=args; *argv; argv++)
  145.         if ((*argv)[0] == '-')
  146.             switch ((*argv)[1]) {
  147.             case 'F':
  148.             case 'f':
  149.             case 'v':
  150.                 argv++;
  151.                 break;
  152.             default:
  153.                 break;
  154.             }
  155.         else
  156.             *options++ = *argv;
  157.     
  158.     return sorted;
  159. }
  160. #endif
  161.     
  162. int
  163. main(argc, argv, envp)
  164. int argc;
  165. char **argv;
  166. char **envp;
  167. {
  168. #ifdef DEBUG
  169.     /* Print out the parse tree.   For debugging */
  170.     register int dotree = 0;
  171. #endif
  172.     extern char *version_string;
  173.     FILE *fp;
  174.     int c;
  175.     extern int opterr, optind;
  176.     extern char *optarg;
  177.      extern char *strrchr();
  178.      extern char *tmpnam();
  179.     extern SIGTYPE catchsig();
  180.     int i;
  181.     int nostalgia;
  182. #ifdef somtime_in_the_future
  183.     int regex_mode = RE_SYNTAX_POSIX_EGREP;
  184. #else
  185.     int regex_mode = RE_SYNTAX_AWK;
  186. #endif
  187.  
  188. #ifdef macintosh
  189.     argv = sortargs(argc, argv);
  190.     InitCursorCtl(NULL);
  191. #endif
  192.  
  193.     (void) signal(SIGFPE, catchsig);
  194.     (void) signal(SIGSEGV, catchsig);
  195.  
  196.     if (strncmp(version_string, "@(#)", 4) == 0)
  197.         version_string += 4;
  198.  
  199.     myname = strrchr(argv[0], '/');
  200.     if (myname == NULL)
  201.         myname = argv[0];
  202.     else
  203.         myname++;
  204.     if (argc < 2)
  205.         usage();
  206.  
  207.     /* initialize the null string */
  208.     Nnull_string = make_string("", 0);
  209.     Nnull_string->numbr = 0.0;
  210.     Nnull_string->type = Node_val;
  211.     Nnull_string->flags = (PERM|STR|NUM|NUMERIC);
  212.  
  213.     /* Set up the special variables */
  214.  
  215.     /*
  216.      * Note that this must be done BEFORE arg parsing else -F
  217.      * breaks horribly 
  218.      */
  219. #ifndef macintosh
  220.     init_vars();
  221. #else
  222.     init_vars(envp);
  223. #endif
  224.  
  225.     /* worst case */
  226.     emalloc(sourcefile, char **, argc * sizeof(char *), "main");
  227.  
  228.  
  229. #ifdef STRICT    /* strict new awk compatibility */
  230.     strict = 1;
  231.     awk_opts[EXTENSIONS] = '\0';
  232. #endif
  233.  
  234. #ifndef STRICT
  235.     /* undocumented feature, inspired by nostalgia, and a T-shirt */
  236.     nostalgia = 0;
  237.     for (i = 1; i < argc && argv[i][0] == '-'; i++) {
  238.         if (argv[i][1] == '-')        /* -- */
  239.             break;
  240.         else if (argv[i][1] == 'c') {    /* compatibility mode */
  241.             nostalgia = 0;
  242.             break;
  243.         } else if (STREQ(&argv[i][1], "nostalgia"))
  244.             nostalgia = 1;
  245.             /* keep looping, in case -c after -nostalgia */
  246.     }
  247.     if (nostalgia) {
  248.         fprintf (stderr, "awk: bailing out near line 1\n");
  249.         abort();
  250.     }
  251. #endif
  252.         
  253.     while ((c = getopt (argc, argv, awk_opts)) != EOF) {
  254.         switch (c) {
  255. #ifdef DEBUG
  256.         case 'd':
  257.             debugging++;
  258.             dotree++;
  259.             break;
  260.  
  261.         case 'D':
  262.             debugging++;
  263.             yydebug = 2;
  264.             break;
  265. #endif
  266.  
  267. #ifndef STRICT
  268.         case 'c':
  269.             strict = 1;
  270.             break;
  271. #endif
  272.  
  273.         case 'F':
  274.             set_fs(optarg);
  275.             break;
  276.  
  277.         case 'f':
  278.             /*
  279.              * a la MKS awk, allow multiple -f options.
  280.              * this makes function libraries real easy.
  281.              * most of the magic is in the scanner.
  282.              */
  283.             sourcefile[++numfiles] = optarg;
  284.             break;
  285.  
  286.         case 'v':
  287.             pre_assign(optarg);
  288.             break;
  289.  
  290.         case 'V':
  291.             fprintf(stderr, "%s, patchlevel %d\n",
  292.                     version_string, PATCHLEVEL);
  293.             break;
  294.  
  295.         case 'C':
  296.             copyleft();
  297.             break;
  298.  
  299.         case 'a':    /* use old fashioned awk regexps */
  300.             regex_mode = RE_SYNTAX_AWK;
  301.             break;
  302.  
  303.         case 'e':    /* use egrep style regexps, per Posix */
  304.             regex_mode = RE_SYNTAX_POSIX_EGREP;
  305.             break;
  306.  
  307. #ifdef macintosh
  308.         case 'm':
  309.             regex_mode = RE_SYNTAX_MPW;
  310.             mpw_regex  = 1;
  311.             break;
  312. #endif
  313.  
  314.         case '?':
  315.         default:
  316.             /* getopt will print a message for us */
  317.             /* S5R4 awk ignores bad options and keeps going */
  318.             break;
  319.         }
  320.     }
  321.  
  322.     /* Tell the regex routines how they should work. . . */
  323.     (void) re_set_syntax(regex_mode);
  324.  
  325. #ifdef DEBUG
  326.     setbuf(stdout, (char *) NULL);    /* make debugging easier */
  327. #endif
  328.     if (isatty(fileno(stdout)))
  329.         output_is_tty = 1;
  330.     /* No -f option, use next arg */
  331.     /* write to temp file and save sourcefile name */
  332.     if (numfiles == -1) {
  333.         int i;
  334.  
  335.         if (optind > argc - 1)    /* no args left */
  336.             usage();
  337.         numfiles++;
  338.         i = strlen (argv[optind]);
  339.         if (i == 0) {    /* sanity check */
  340.             fprintf(stderr, "%s: empty program text\n", myname);
  341.             usage();
  342.             /* NOTREACHED */
  343.         }
  344.         sourcefile[0] = tmpnam((char *) NULL);
  345.         if ((fp = fopen (sourcefile[0], "w")) == NULL)
  346.             fatal("could not save source prog in temp file (%s)",
  347.             strerror(errno));
  348.         if (fwrite (argv[optind], 1, i, fp) == 0)
  349.             fatal(
  350.             "could not write source program to temp file (%s)",
  351.             strerror(errno));
  352.         if (argv[optind][i-1] != '\n')
  353.             putc ('\n', fp);
  354.         (void) fclose (fp);
  355.         tempsource++;
  356.         optind++;
  357.     }
  358.     init_args(optind, argc, myname, argv);
  359.  
  360.     /* Read in the program */
  361.     if (yyparse() || errcount)
  362.         exit(1);
  363.  
  364. #ifdef DEBUG
  365.     if (dotree)
  366.         print_parse_tree(expression_value);
  367. #endif
  368.     /* Set up the field variables */
  369.     init_fields();
  370.  
  371.     if (begin_block)
  372.         (void) interpret(begin_block);
  373.     if (!exiting && (expression_value || end_block))
  374.         do_input();
  375.     if (end_block)
  376.         (void) interpret(end_block);
  377.     if (close_io() != 0 && exit_val == 0)
  378.         exit_val = 1;
  379.     exit(exit_val);
  380.     /* NOTREACHED */
  381.     return exit_val;
  382. }
  383.  
  384. static void
  385. usage()
  386. {
  387.     char *opt1 = " -f progfile [--]";
  388.     char *opt2 = " [--] 'program'";
  389. #ifdef STRICT
  390.     char *regops = " [-ae] [-F fs] [-v var=val]"
  391. #else
  392.     char *regops = " [-aecCV] [-F fs] [-v var=val]";
  393. #endif
  394.  
  395.     fprintf(stderr, "usage: %s%s%s file ...\n       %s%s%s file ...\n",
  396.         myname, regops, opt1, myname, regops, opt2);
  397.     exit(11);
  398. }
  399.  
  400. /* Generate compiled regular expressions */
  401. struct re_pattern_buffer *
  402. make_regexp(s, ignorecase)
  403. NODE *s;
  404. int ignorecase;
  405. {
  406.     struct re_pattern_buffer *rp;
  407.     char *err;
  408.  
  409.     emalloc(rp, struct re_pattern_buffer *, sizeof(*rp), "make_regexp");
  410.     memset((char *) rp, 0, sizeof(*rp));
  411.     emalloc(rp->buffer, char *, 16, "make_regexp");
  412.     rp->allocated = 16;
  413.     emalloc(rp->fastmap, char *, 256, "make_regexp");
  414.  
  415.     if (! strict && ignorecase)
  416.         rp->translate = casetable;
  417.     else
  418.         rp->translate = NULL;
  419.     if ((err = re_compile_pattern(s->stptr, s->stlen, rp)) != NULL)
  420.         fatal("%s: /%s/", err, s->stptr);
  421.     free_temp(s);
  422.     return rp;
  423. }
  424.  
  425. struct re_pattern_buffer *
  426. mk_re_parse(s, ignorecase)
  427. char *s;
  428. int ignorecase;
  429. {
  430.     char *src;
  431.     register char *dest;
  432.     register int c;
  433.     int in_brack = 0;
  434.  
  435. #ifdef macintosh
  436.     if (mpw_regex)
  437.         for (dest = src = s; *src != '\0';) {
  438.             if (*src == '∂') {
  439.                 c = *++src;
  440.                 switch (c) {
  441.                 case 'f':
  442.                 case 'n':
  443.                 case 't':
  444.                     c = parse_escape(&src);
  445.                     if (c < 0)
  446.                         cant_happen();
  447.                     *dest++ = (char)c;
  448.                     break;
  449.                 default:
  450.                     *dest++ = (char)c;
  451.                     src++;
  452.                     break;
  453.                 }
  454.             } else if (*src == '/' && ! in_brack)
  455.                 break;
  456.             else {
  457.                 if (*src == '[')
  458.                     in_brack = 1;
  459.                 else if (*src == ']')
  460.                     in_brack = 0;
  461.     
  462.                 *dest++ = *src++;
  463.             }
  464.         }
  465.     else
  466. #endif
  467.     for (dest = src = s; *src != '\0';) {
  468.         if (*src == '\\') {
  469.             c = *++src;
  470.             switch (c) {
  471.             case '/':
  472.             case 'a':
  473.             case 'b':
  474.             case 'f':
  475.             case 'n':
  476.             case 'r':
  477.             case 't':
  478.             case 'v':
  479.             case 'x':
  480.             case '0':
  481.             case '1':
  482.             case '2':
  483.             case '3':
  484.             case '4':
  485.             case '5':
  486.             case '6':
  487.             case '7':
  488.                 c = parse_escape(&src);
  489.                 if (c < 0)
  490.                     cant_happen();
  491.                 *dest++ = (char)c;
  492.                 break;
  493.             default:
  494.                 *dest++ = '\\';
  495.                 *dest++ = (char)c;
  496.                 src++;
  497.                 break;
  498.             }
  499.         } else if (*src == '/' && ! in_brack)
  500.             break;
  501.         else {
  502.             if (*src == '[')
  503.                 in_brack = 1;
  504.             else if (*src == ']')
  505.                 in_brack = 0;
  506.  
  507.             *dest++ = *src++;
  508.         }
  509.     }
  510.     return make_regexp(tmp_string(s, dest-s), ignorecase);
  511. }
  512.  
  513. static void
  514. copyleft ()
  515. {
  516.     extern char *version_string;
  517.     static char blurb[] =
  518. "Copyright (C) 1989, Free Software Foundation.\n\
  519. GNU Awk comes with ABSOLUTELY NO WARRANTY.  This is free software, and\n\
  520. you are welcome to distribute it under the terms of the GNU General\n\
  521. Public License, which covers both the warranty information and the\n\
  522. terms for redistribution.\n\n\
  523. You should have received a copy of the GNU General Public License along\n\
  524. with this program; if not, write to the Free Software Foundation, Inc.,\n\
  525. 675 Mass Ave, Cambridge, MA 02139, USA.\n";
  526.  
  527.     fprintf (stderr, "%s, patchlevel %d\n", version_string, PATCHLEVEL);
  528.     fputs(blurb, stderr);
  529.     fflush(stderr);
  530. }
  531.  
  532. static void
  533. set_fs(str)
  534. char *str;
  535. {
  536.     register NODE **tmp;
  537.  
  538.     tmp = get_lhs(FS_node, 0);
  539.     /*
  540.      * Only if in full compatibility mode check for the stupid special
  541.      * case so -F\t works as documented in awk even though the shell
  542.      * hands us -Ft.  Bleah!
  543.      */
  544.     if (strict && str[0] == 't' && str[1] == '\0')
  545.         str[0] = '\t';
  546.     *tmp = make_string(str, 1);
  547.     do_deref();
  548. }
  549.  
  550. static void
  551. init_args(argc0, argc, argv0, argv)
  552. int argc0, argc;
  553. char *argv0;
  554. char **argv;
  555. {
  556.     int i, j;
  557.     NODE **aptr;
  558.  
  559.     ARGV_node = spc_var("ARGV", Nnull_string);
  560.     aptr = assoc_lookup(ARGV_node, tmp_number(0.0));
  561.     *aptr = make_string(argv0, strlen(argv0));
  562.     for (i = argc0, j = 1; i < argc; i++) {
  563.         aptr = assoc_lookup(ARGV_node, tmp_number((AWKNUM) j));
  564.         *aptr = make_string(argv[i], strlen(argv[i]));
  565.         j++;
  566.     }
  567.     ARGC_node = spc_var("ARGC", make_number((AWKNUM) j));
  568. }
  569.  
  570. /*
  571.  * Set all the special variables to their initial values.
  572.  */
  573. static void
  574. #ifndef macintosh
  575. init_vars()
  576. {
  577.     extern char **environ;
  578. #else
  579. init_vars(environ)
  580. char ** environ;
  581. {
  582. #endif
  583.     char *var, *val;
  584.     NODE **aptr;
  585.     int i;
  586.  
  587.     FS_node = spc_var("FS", make_string(" ", 1));
  588.     NF_node = spc_var("NF", make_number(-1.0));
  589.     RS_node = spc_var("RS", make_string("\n", 1));
  590.     NR_node = spc_var("NR", make_number(0.0));
  591.     FNR_node = spc_var("FNR", make_number(0.0));
  592.     FILENAME_node = spc_var("FILENAME", make_string("-", 1));
  593.     OFS_node = spc_var("OFS", make_string(" ", 1));
  594.     ORS_node = spc_var("ORS", make_string("\n", 1));
  595.     OFMT_node = spc_var("OFMT", make_string("%.6g", 4));
  596.     RLENGTH_node = spc_var("RLENGTH", make_number(0.0));
  597.     RSTART_node = spc_var("RSTART", make_number(0.0));
  598.     SUBSEP_node = spc_var("SUBSEP", make_string("\034", 1));
  599.     IGNORECASE_node = spc_var("IGNORECASE", make_number(0.0));
  600.  
  601.     ENVIRON_node = spc_var("ENVIRON", Nnull_string);
  602.     for (i = 0; environ[i]; i++) {
  603.         static char nullstr[] = "";
  604.  
  605.         var = environ[i];
  606. #ifndef macintosh
  607.         val = strchr(var, '=');
  608.         if (val)
  609.             *val++ = '\0';
  610.         else
  611.             val = nullstr;
  612. #else
  613.         val = var + strlen(var)+1;
  614. #endif
  615.         aptr = assoc_lookup(ENVIRON_node, tmp_string(var, strlen (var)));
  616.         *aptr = make_string(val, strlen (val));
  617.  
  618. #ifndef macintosh
  619.         /* restore '=' so that system() gets a valid environment */
  620.         if (val != nullstr)
  621.             *--val = '=';
  622. #endif
  623.     }
  624. }
  625.  
  626. /* Create a special variable */
  627. static NODE *
  628. spc_var(name, value)
  629. char *name;
  630. NODE *value;
  631. {
  632.     register NODE *r;
  633.  
  634.     if ((r = lookup(variables, name)) == NULL)
  635.         r = install(variables, name, node(value, Node_var, (NODE *) NULL));
  636.     return r;
  637. }
  638.  
  639. static void
  640. pre_assign(v)
  641. char *v;
  642. {
  643.     char *cp;
  644.  
  645.     cp = strchr(v, '=');
  646.     if (cp != NULL) {
  647.         *cp++ = '\0';
  648.         variable(v)->var_value = make_string(cp, strlen(cp));
  649.     } else {
  650.         fprintf (stderr,
  651.             "%s: '%s' argument to -v not in 'var=value' form\n",
  652.                 myname, v);
  653.         usage();
  654.     }
  655. }
  656.  
  657. #ifdef macintosh
  658. void catchsig(sig)
  659. int sig;
  660. #else
  661. int catchsig(sig, code)
  662. int sig, code;
  663. #endif
  664. {
  665. #ifdef lint
  666.     code = 0; sig = code; code = sig;
  667. #endif
  668.     if (sig == SIGFPE) {
  669.         fatal("floating point exception");
  670.     } else if (sig == SIGSEGV) {
  671.         msg("fatal error: segmentation fault");
  672.         /* fatal won't abort() if not compiled for debugging */
  673.         abort();
  674.     } else
  675.         cant_happen();
  676.     /* NOTREACHED */
  677. }
  678.